@rubicon-caliga/cli 0.1.0 → 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.
- package/dist/circle.d.ts +48 -0
- package/dist/circle.d.ts.map +1 -0
- package/dist/circle.js +198 -0
- package/dist/circle.js.map +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +9 -1
- package/dist/errors.js.map +1 -1
- package/dist/format.d.ts +5 -0
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js +81 -6
- package/dist/format.js.map +1 -1
- package/dist/index.js +236 -39
- package/dist/index.js.map +1 -1
- package/dist/payments.d.ts +1 -0
- package/dist/payments.d.ts.map +1 -1
- package/dist/payments.js +3 -1
- package/dist/payments.js.map +1 -1
- package/dist/quickstart.d.ts +30 -0
- package/dist/quickstart.d.ts.map +1 -0
- package/dist/quickstart.js +270 -0
- package/dist/quickstart.js.map +1 -0
- package/dist/quickstart.test.d.ts +2 -0
- package/dist/quickstart.test.d.ts.map +1 -0
- package/dist/quickstart.test.js +229 -0
- package/dist/quickstart.test.js.map +1 -0
- package/package.json +12 -10
- package/src/circle.ts +232 -0
- package/src/errors.ts +16 -1
- package/src/format.ts +87 -6
- package/src/index.ts +248 -37
- package/src/payments.ts +4 -1
- package/src/quickstart.test.ts +264 -0
- package/src/quickstart.ts +330 -0
- package/LICENSE +0 -21
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { mkdtempSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { test } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import type { ReadReceipt, RubiconClient } from "@rubicon-caliga/agent-sdk";
|
|
7
|
+
import type { ArticleSummary } from "@rubicon-caliga/core";
|
|
8
|
+
import { parseArgs } from "./args.js";
|
|
9
|
+
import { CliError } from "./errors.js";
|
|
10
|
+
import { finalReceiptJson, runDoctor, runQuickstartRead, type CommandRuntime } from "./quickstart.js";
|
|
11
|
+
|
|
12
|
+
test("doctor reports missing gateway config and Circle CLI missing", async () => {
|
|
13
|
+
const runtime = runtimeFor();
|
|
14
|
+
const result = await runDoctor(runtime, {
|
|
15
|
+
cliVersion: "0.1.1",
|
|
16
|
+
fetch: okFetch,
|
|
17
|
+
circleRunner: async () => {
|
|
18
|
+
throw new Error("spawn circle ENOENT");
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const checks = result.checks as Array<{ name: string; status: string; guidance?: string }>;
|
|
23
|
+
assert.equal(checks.find((check) => check.name === "gatewayConfig")?.status, "warning");
|
|
24
|
+
assert.match(checks.find((check) => check.name === "gatewayConfig")?.guidance ?? "", /hosted default/);
|
|
25
|
+
assert.equal(checks.find((check) => check.name === "circleCli")?.status, "error");
|
|
26
|
+
assert.match(checks.find((check) => check.name === "circleCli")?.guidance ?? "", /Install Circle CLI/);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("doctor explains Circle CLI not logged in and sandbox network failures", async () => {
|
|
30
|
+
const notLoggedIn = await runDoctor(runtimeFor(), {
|
|
31
|
+
fetch: okFetch,
|
|
32
|
+
circleRunner: async (_command, args) => {
|
|
33
|
+
if (args[0] === "--version") return "circle 1.0.0";
|
|
34
|
+
throw new Error("unauthorized: please login");
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
const notLoggedChecks = notLoggedIn.checks as Array<{ name: string; guidance?: string }>;
|
|
38
|
+
assert.match(notLoggedChecks.find((check) => check.name === "circleAuth")?.guidance ?? "", /login/);
|
|
39
|
+
|
|
40
|
+
const networkFailure = await runDoctor(runtimeFor(), {
|
|
41
|
+
fetch: (async () => {
|
|
42
|
+
throw new Error("fetch failed");
|
|
43
|
+
}) as unknown as typeof fetch,
|
|
44
|
+
circleRunner: async () => "circle 1.0.0",
|
|
45
|
+
});
|
|
46
|
+
const networkChecks = networkFailure.checks as Array<{ name: string; guidance?: string }>;
|
|
47
|
+
assert.match(networkChecks.find((check) => check.name === "gatewayReachability")?.guidance ?? "", /network-capable/);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("quickstart refuses paid reads without explicit budget", async () => {
|
|
51
|
+
await assert.rejects(
|
|
52
|
+
() => runQuickstartRead(runtimeFor({ argv: ["quickstart-read", "--first", "--goal", "answer"] })),
|
|
53
|
+
(error) => error instanceof CliError && error.code === "MISSING_BUDGET",
|
|
54
|
+
);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("quickstart detects expired OTP request IDs", async () => {
|
|
58
|
+
await assert.rejects(
|
|
59
|
+
() =>
|
|
60
|
+
runQuickstartRead(runtimeFor(), {
|
|
61
|
+
circleRunner: async (_command, args) => {
|
|
62
|
+
if (args[0] === "auth") throw new Error("OTP request id expired");
|
|
63
|
+
return circleOutput(args, "1000000");
|
|
64
|
+
},
|
|
65
|
+
}),
|
|
66
|
+
(error) => error instanceof CliError && error.code === "OTP_EXPIRED" && /fresh Circle auth OTP/.test(error.message),
|
|
67
|
+
);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("quickstart stops when dry-run estimate exceeds budget", async () => {
|
|
71
|
+
await assert.rejects(
|
|
72
|
+
() => runQuickstartRead(runtimeFor({ article: article({ pricePerWordAtomic: "1000000" }) })),
|
|
73
|
+
(error) => error instanceof CliError && error.code === "DRY_RUN_OVER_BUDGET",
|
|
74
|
+
);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("quickstart uses existing Arc Testnet balance without faucet", async () => {
|
|
78
|
+
const calls: string[][] = [];
|
|
79
|
+
const result = await runQuickstartRead(runtimeFor(), {
|
|
80
|
+
circleRunner: async (_command, args) => {
|
|
81
|
+
calls.push(args);
|
|
82
|
+
return circleOutput(args, "1000000");
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
assert.equal((result.receipt as Record<string, unknown>).amountPaidAtomic, "2");
|
|
87
|
+
assert.equal(calls.some((args) => args[0] === "gateway" && args[1] === "faucet"), false);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("quickstart faucet-funds only the testnet path when needed", async () => {
|
|
91
|
+
const calls: string[][] = [];
|
|
92
|
+
let funded = false;
|
|
93
|
+
const result = await runQuickstartRead(runtimeFor(), {
|
|
94
|
+
circleRunner: async (_command, args) => {
|
|
95
|
+
calls.push(args);
|
|
96
|
+
if (args[0] === "gateway" && args[1] === "faucet") {
|
|
97
|
+
funded = true;
|
|
98
|
+
return JSON.stringify({ ok: true });
|
|
99
|
+
}
|
|
100
|
+
return circleOutput(args, funded ? "1000000" : "0");
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
assert.equal(calls.some((args) => args[0] === "gateway" && args[1] === "faucet"), true);
|
|
105
|
+
assert.equal((result.wallet as Record<string, unknown>).balanceAtomic, "1000000");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("quickstart refuses to suggest mainnet funding", async () => {
|
|
109
|
+
await assert.rejects(
|
|
110
|
+
() =>
|
|
111
|
+
runQuickstartRead(runtimeFor({ article: article({ environment: "mainnet", network: "eip155:1", circleChain: "ETH" }) }), {
|
|
112
|
+
circleRunner: async (_command, args) => circleOutput(args, "0"),
|
|
113
|
+
}),
|
|
114
|
+
(error) => error instanceof CliError && error.code === "INSUFFICIENT_FUNDS" && /Refusing to suggest mainnet funding/.test(error.message),
|
|
115
|
+
);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("final receipt schema includes buyer/Circle wallet mismatch explanation", () => {
|
|
119
|
+
const shaped = finalReceiptJson({
|
|
120
|
+
article: article(),
|
|
121
|
+
receipt: receipt(),
|
|
122
|
+
receiptId: "receipt_1",
|
|
123
|
+
goal: "answer",
|
|
124
|
+
approvedBudgetUsdc: "0.01",
|
|
125
|
+
circleWalletAddress: "0x1111111111111111111111111111111111111111",
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
assert.deepEqual(Object.keys(shaped), [
|
|
129
|
+
"articleId",
|
|
130
|
+
"title",
|
|
131
|
+
"author",
|
|
132
|
+
"sessionId",
|
|
133
|
+
"receiptId",
|
|
134
|
+
"goal",
|
|
135
|
+
"approvedBudgetUsdc",
|
|
136
|
+
"amountPaidAtomic",
|
|
137
|
+
"amountPaidUsdc",
|
|
138
|
+
"wordsRead",
|
|
139
|
+
"completed",
|
|
140
|
+
"stopReason",
|
|
141
|
+
"paymentIds",
|
|
142
|
+
"settlementIds",
|
|
143
|
+
"transactionHashes",
|
|
144
|
+
"buyerWalletAddress",
|
|
145
|
+
"circleWalletAddress",
|
|
146
|
+
"walletAddressMismatchExplanation",
|
|
147
|
+
]);
|
|
148
|
+
assert.match(String(shaped.walletAddressMismatchExplanation), /Gateway backing EOA/);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
function runtimeFor(input: { argv?: string[]; article?: ArticleSummary } = {}): CommandRuntime {
|
|
152
|
+
process.env.HOME = mkdtempSync(join(tmpdir(), "rubicon-cli-test-"));
|
|
153
|
+
const articleFixture = input.article ?? article();
|
|
154
|
+
const client = {
|
|
155
|
+
async getRepository() {
|
|
156
|
+
return { repository: "articles" as const, articles: [articleFixture] };
|
|
157
|
+
},
|
|
158
|
+
async getNavigation() {
|
|
159
|
+
return {
|
|
160
|
+
article: articleFixture,
|
|
161
|
+
navigation: {
|
|
162
|
+
articleId: articleFixture.articleId,
|
|
163
|
+
sections: articleFixture.sections,
|
|
164
|
+
sellerAgent: {
|
|
165
|
+
recommendedSectionId: "intro",
|
|
166
|
+
alternativeSectionIds: [],
|
|
167
|
+
rationale: "Start here.",
|
|
168
|
+
safeHints: [],
|
|
169
|
+
withheld: [],
|
|
170
|
+
},
|
|
171
|
+
stopConditions: [],
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
},
|
|
175
|
+
async run() {
|
|
176
|
+
return receipt();
|
|
177
|
+
},
|
|
178
|
+
} as unknown as RubiconClient;
|
|
179
|
+
return {
|
|
180
|
+
parsed: parseArgs(input.argv ?? ["quickstart-read", "--first", "--goal", "answer", "--max-usdc", "0.01"]),
|
|
181
|
+
config: {},
|
|
182
|
+
gatewayUrl: "https://rubicon.test",
|
|
183
|
+
paymentMode: "circle-cli",
|
|
184
|
+
circleChain: "ARC-TESTNET",
|
|
185
|
+
client,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function article(input: {
|
|
190
|
+
pricePerWordAtomic?: `${bigint}`;
|
|
191
|
+
network?: string;
|
|
192
|
+
circleChain?: string;
|
|
193
|
+
environment?: "testnet" | "mainnet" | "unknown";
|
|
194
|
+
} = {}): ArticleSummary {
|
|
195
|
+
return {
|
|
196
|
+
articleId: "article_1",
|
|
197
|
+
creatorId: "creator_1",
|
|
198
|
+
creatorUsername: "creator",
|
|
199
|
+
title: "Rubicon Field Notes",
|
|
200
|
+
author: "Ada",
|
|
201
|
+
state: "live",
|
|
202
|
+
totalWords: 2,
|
|
203
|
+
pricePerWordAtomic: input.pricePerWordAtomic ?? "1",
|
|
204
|
+
maxArticlePriceAtomic: `${BigInt(input.pricePerWordAtomic ?? "1") * 2n}` as `${bigint}`,
|
|
205
|
+
paymentTerms: {
|
|
206
|
+
asset: "USDC",
|
|
207
|
+
network: input.network ?? "eip155:5042002",
|
|
208
|
+
circleChain: input.circleChain ?? "ARC-TESTNET",
|
|
209
|
+
environment: input.environment ?? "testnet",
|
|
210
|
+
fundingMethod: "Circle testnet faucet.",
|
|
211
|
+
payTo: "0x3333333333333333333333333333333333333333",
|
|
212
|
+
pricePerWordAtomic: input.pricePerWordAtomic ?? "1",
|
|
213
|
+
meteringUnit: "word",
|
|
214
|
+
},
|
|
215
|
+
sections: [{ sectionId: "intro", heading: "Intro", level: 1, wordStart: 0, wordCount: 2 }],
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function receipt(): ReadReceipt {
|
|
220
|
+
return {
|
|
221
|
+
sessionId: "session_1",
|
|
222
|
+
articleId: "article_1",
|
|
223
|
+
conversationId: "conversation_1",
|
|
224
|
+
wordsRead: 2,
|
|
225
|
+
amountPaidAtomic: "2",
|
|
226
|
+
payments: [
|
|
227
|
+
{
|
|
228
|
+
paymentId: "payment_1",
|
|
229
|
+
sessionId: "session_1",
|
|
230
|
+
articleId: "article_1",
|
|
231
|
+
sequence: 0,
|
|
232
|
+
meteringUnit: "word",
|
|
233
|
+
amountAtomic: "2",
|
|
234
|
+
currency: "USDC",
|
|
235
|
+
settlementIds: ["settlement_1"],
|
|
236
|
+
transactionHashes: ["0xtx"],
|
|
237
|
+
buyerWalletAddress: "0x2222222222222222222222222222222222222222",
|
|
238
|
+
settledAt: "2026-06-19T12:00:00.000Z",
|
|
239
|
+
},
|
|
240
|
+
],
|
|
241
|
+
transactionHashes: ["0xtx"],
|
|
242
|
+
settlementIds: ["settlement_1"],
|
|
243
|
+
buyerWalletAddress: "0x2222222222222222222222222222222222222222",
|
|
244
|
+
sellerPayTo: "0x3333333333333333333333333333333333333333",
|
|
245
|
+
network: "eip155:5042002",
|
|
246
|
+
text: "hello world",
|
|
247
|
+
completed: true,
|
|
248
|
+
stopReason: "article_completed",
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function circleOutput(args: string[], balanceAtomic: `${bigint}`): string {
|
|
253
|
+
if (args[0] === "--version") return "circle 1.0.0";
|
|
254
|
+
if (args[0] === "auth") return JSON.stringify({ loggedIn: true });
|
|
255
|
+
if (args[0] === "wallet") {
|
|
256
|
+
return JSON.stringify({ data: { wallets: [{ address: "0x1111111111111111111111111111111111111111" }] } });
|
|
257
|
+
}
|
|
258
|
+
if (args[0] === "gateway" && args[1] === "balance") {
|
|
259
|
+
return JSON.stringify({ data: { balanceAtomic, backingEOA: "0x2222222222222222222222222222222222222222" } });
|
|
260
|
+
}
|
|
261
|
+
return JSON.stringify({ ok: true });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const okFetch = (async () => new Response("ok", { status: 200 })) as unknown as typeof fetch;
|
|
@@ -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.
|