@conto_finance/create-conto-agent 0.4.4 → 0.4.6
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/CHANGELOG.md +19 -0
- package/README.md +62 -0
- package/dist/chunk-MASQPQTP.js +2568 -0
- package/dist/{chunk-CR3H37ZX.js → chunk-XWUWB3FT.js} +1 -1
- package/dist/cli.js +1645 -40
- package/dist/{config-YV6X7VKJ.js → config-N7W4ZJJY.js} +1 -1
- package/dist/index.js +10 -3
- package/package.json +1 -1
- package/dist/chunk-ETJJHYIL.js +0 -1359
|
@@ -0,0 +1,2568 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isJsonMode,
|
|
3
|
+
printBanner,
|
|
4
|
+
printError,
|
|
5
|
+
printInfo,
|
|
6
|
+
printJson,
|
|
7
|
+
printSuccess,
|
|
8
|
+
printWarning
|
|
9
|
+
} from "./chunk-K4LBO234.js";
|
|
10
|
+
import {
|
|
11
|
+
ensureContoDirGitignored,
|
|
12
|
+
ensureEnvLocalGitignored,
|
|
13
|
+
loadProjectEnv,
|
|
14
|
+
saveGlobalConfig,
|
|
15
|
+
writeContoConfig,
|
|
16
|
+
writeEnvLocal,
|
|
17
|
+
writeSandboxSetupEnv
|
|
18
|
+
} from "./chunk-XWUWB3FT.js";
|
|
19
|
+
|
|
20
|
+
// package.json
|
|
21
|
+
var package_default = {
|
|
22
|
+
name: "@conto_finance/create-conto-agent",
|
|
23
|
+
version: "0.4.6",
|
|
24
|
+
description: "Set up an AI agent with Conto spending controls",
|
|
25
|
+
bin: {
|
|
26
|
+
"create-conto-agent": "bin/create-conto-agent.js",
|
|
27
|
+
conto: "bin/conto.js"
|
|
28
|
+
},
|
|
29
|
+
main: "./dist/index.js",
|
|
30
|
+
type: "module",
|
|
31
|
+
files: [
|
|
32
|
+
"dist",
|
|
33
|
+
"bin",
|
|
34
|
+
"README.md",
|
|
35
|
+
"CHANGELOG.md"
|
|
36
|
+
],
|
|
37
|
+
publishConfig: {
|
|
38
|
+
access: "public"
|
|
39
|
+
},
|
|
40
|
+
scripts: {
|
|
41
|
+
build: "tsup src/index.ts src/cli.ts src/lib/rule-values.ts --format esm --dts --clean",
|
|
42
|
+
dev: "tsup src/index.ts src/cli.ts src/lib/rule-values.ts --format esm --dts --watch",
|
|
43
|
+
lint: "tsc --noEmit",
|
|
44
|
+
test: "npm run lint && npm run test:contract",
|
|
45
|
+
"test:contract": "npm run build && node --test test/*.test.mjs",
|
|
46
|
+
"verify:release": "node scripts/verify-release.mjs",
|
|
47
|
+
prepublishOnly: "npm run verify:release && npm test"
|
|
48
|
+
},
|
|
49
|
+
engines: {
|
|
50
|
+
node: ">=20.19.0"
|
|
51
|
+
},
|
|
52
|
+
keywords: [
|
|
53
|
+
"conto",
|
|
54
|
+
"ai",
|
|
55
|
+
"agent",
|
|
56
|
+
"payments",
|
|
57
|
+
"cli",
|
|
58
|
+
"quickstart",
|
|
59
|
+
"tempo",
|
|
60
|
+
"blockchain"
|
|
61
|
+
],
|
|
62
|
+
author: "Conto",
|
|
63
|
+
license: "MIT",
|
|
64
|
+
repository: {
|
|
65
|
+
type: "git",
|
|
66
|
+
url: "https://github.com/conto-finance/conto.git",
|
|
67
|
+
directory: "packages/cli"
|
|
68
|
+
},
|
|
69
|
+
homepage: "https://conto.finance/docs/cli/quickstart",
|
|
70
|
+
bugs: {
|
|
71
|
+
email: "support@conto.finance"
|
|
72
|
+
},
|
|
73
|
+
dependencies: {
|
|
74
|
+
"@clack/prompts": "^0.9.1",
|
|
75
|
+
chalk: "^5.4.1",
|
|
76
|
+
"cli-table3": "^0.6.5",
|
|
77
|
+
commander: "^13.1.0",
|
|
78
|
+
open: "^10.1.0"
|
|
79
|
+
},
|
|
80
|
+
overrides: {
|
|
81
|
+
esbuild: "0.28.1"
|
|
82
|
+
},
|
|
83
|
+
devDependencies: {
|
|
84
|
+
"@types/node": "22.19.18",
|
|
85
|
+
tsup: "^8.5.1",
|
|
86
|
+
typescript: "^5.9.3"
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
// src/lib/package-version.ts
|
|
91
|
+
var CLI_PACKAGE_VERSION = package_default.version || "0.0.0";
|
|
92
|
+
|
|
93
|
+
// src/commands/init.ts
|
|
94
|
+
import * as p from "@clack/prompts";
|
|
95
|
+
import chalk from "chalk";
|
|
96
|
+
import fs2 from "fs";
|
|
97
|
+
import path2 from "path";
|
|
98
|
+
import { spawnSync } from "child_process";
|
|
99
|
+
|
|
100
|
+
// src/lib/chains.ts
|
|
101
|
+
var FALLBACK_CHAINS = {
|
|
102
|
+
"4217": {
|
|
103
|
+
name: "Tempo",
|
|
104
|
+
shortName: "Tempo",
|
|
105
|
+
chainId: "4217",
|
|
106
|
+
rpcUrl: "https://rpc.tempo.xyz",
|
|
107
|
+
explorerUrl: "https://explore.tempo.xyz",
|
|
108
|
+
explorerName: "Tempo Explorer",
|
|
109
|
+
currency: "USDC.e",
|
|
110
|
+
chainType: "EVM",
|
|
111
|
+
testnet: false,
|
|
112
|
+
isDefault: false,
|
|
113
|
+
faucetAvailable: false,
|
|
114
|
+
stablecoins: [
|
|
115
|
+
{
|
|
116
|
+
symbol: "USDC.e",
|
|
117
|
+
name: "Bridged USDC",
|
|
118
|
+
address: "0x20c000000000000000000000b9537d11c60e8b50",
|
|
119
|
+
decimals: 6
|
|
120
|
+
}
|
|
121
|
+
]
|
|
122
|
+
},
|
|
123
|
+
"42431": {
|
|
124
|
+
name: "Tempo Testnet",
|
|
125
|
+
shortName: "Tempo Testnet",
|
|
126
|
+
chainId: "42431",
|
|
127
|
+
rpcUrl: "https://rpc.moderato.tempo.xyz",
|
|
128
|
+
explorerUrl: "https://explore.moderato.tempo.xyz",
|
|
129
|
+
explorerName: "Tempo Explorer",
|
|
130
|
+
currency: "pathUSD",
|
|
131
|
+
chainType: "EVM",
|
|
132
|
+
testnet: true,
|
|
133
|
+
isDefault: true,
|
|
134
|
+
faucetAvailable: true,
|
|
135
|
+
stablecoins: [
|
|
136
|
+
{
|
|
137
|
+
symbol: "pathUSD",
|
|
138
|
+
name: "Path USD",
|
|
139
|
+
address: "0x20c0000000000000000000000000000000000000",
|
|
140
|
+
decimals: 6
|
|
141
|
+
}
|
|
142
|
+
]
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
var DEFAULT_EVALUATION_CHAIN_ID = "42431";
|
|
146
|
+
var DEFAULT_FALLBACK_CHAIN_ID = DEFAULT_EVALUATION_CHAIN_ID;
|
|
147
|
+
var cachedChains = null;
|
|
148
|
+
var cachedDefaultChainId = null;
|
|
149
|
+
function getEvaluationDefaultChainId(chains, serverDefaultChainId) {
|
|
150
|
+
if (chains[DEFAULT_EVALUATION_CHAIN_ID]?.testnet) return DEFAULT_EVALUATION_CHAIN_ID;
|
|
151
|
+
if (serverDefaultChainId && chains[serverDefaultChainId]?.testnet) return serverDefaultChainId;
|
|
152
|
+
const firstTestnet = Object.values(chains).find((chain) => chain.testnet);
|
|
153
|
+
if (firstTestnet) return firstTestnet.chainId;
|
|
154
|
+
return serverDefaultChainId && chains[serverDefaultChainId] ? serverDefaultChainId : Object.keys(chains)[0];
|
|
155
|
+
}
|
|
156
|
+
async function fetchChains(baseUrl) {
|
|
157
|
+
if (cachedChains) {
|
|
158
|
+
return { chains: cachedChains, defaultChainId: cachedDefaultChainId };
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
const res = await fetch(`${baseUrl.replace(/\/$/, "")}/api/chains`, {
|
|
162
|
+
signal: AbortSignal.timeout(5e3)
|
|
163
|
+
});
|
|
164
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
165
|
+
const data = await res.json();
|
|
166
|
+
const chains = {};
|
|
167
|
+
for (const c of data.chains) {
|
|
168
|
+
chains[c.id] = {
|
|
169
|
+
name: c.name,
|
|
170
|
+
shortName: c.shortName,
|
|
171
|
+
chainId: c.id,
|
|
172
|
+
rpcUrl: c.rpcUrl,
|
|
173
|
+
explorerUrl: c.explorerUrl,
|
|
174
|
+
explorerName: c.explorerName,
|
|
175
|
+
currency: c.currency,
|
|
176
|
+
chainType: c.type,
|
|
177
|
+
testnet: c.isTestnet,
|
|
178
|
+
isDefault: c.isDefault,
|
|
179
|
+
faucetAvailable: c.faucetAvailable,
|
|
180
|
+
iconUrl: c.iconUrl,
|
|
181
|
+
stablecoins: c.stablecoins
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
cachedChains = chains;
|
|
185
|
+
cachedDefaultChainId = getEvaluationDefaultChainId(chains, data.defaultChainId);
|
|
186
|
+
return { chains, defaultChainId: cachedDefaultChainId };
|
|
187
|
+
} catch {
|
|
188
|
+
cachedChains = FALLBACK_CHAINS;
|
|
189
|
+
cachedDefaultChainId = DEFAULT_FALLBACK_CHAIN_ID;
|
|
190
|
+
return { chains: FALLBACK_CHAINS, defaultChainId: DEFAULT_FALLBACK_CHAIN_ID };
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function getChain(chainId) {
|
|
194
|
+
return cachedChains?.[chainId] || FALLBACK_CHAINS[chainId];
|
|
195
|
+
}
|
|
196
|
+
function getChainChoices(chains) {
|
|
197
|
+
const entries = Object.entries(chains);
|
|
198
|
+
entries.sort(([, a], [, b]) => {
|
|
199
|
+
if (a.chainId === DEFAULT_EVALUATION_CHAIN_ID) return -1;
|
|
200
|
+
if (b.chainId === DEFAULT_EVALUATION_CHAIN_ID) return 1;
|
|
201
|
+
if (a.testnet && !b.testnet) return -1;
|
|
202
|
+
if (!a.testnet && b.testnet) return 1;
|
|
203
|
+
return a.name.localeCompare(b.name);
|
|
204
|
+
});
|
|
205
|
+
return entries.map(([id, chain]) => ({
|
|
206
|
+
value: id,
|
|
207
|
+
label: chain.chainId === DEFAULT_EVALUATION_CHAIN_ID ? `${chain.name} (recommended for evaluation)` : chain.name,
|
|
208
|
+
hint: chainHint(chain)
|
|
209
|
+
}));
|
|
210
|
+
}
|
|
211
|
+
function chainHint(chain) {
|
|
212
|
+
if (chain.testnet) return `Testnet \u2014 free ${chain.currency}, no real funds`;
|
|
213
|
+
if (chain.chainId === "4217") return "Mainnet \u2014 real USDC.e and real settlement";
|
|
214
|
+
return `${chain.chainType} \u2014 ${chain.currency}`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// src/lib/auth.ts
|
|
218
|
+
import http from "http";
|
|
219
|
+
import { randomBytes } from "crypto";
|
|
220
|
+
import open from "open";
|
|
221
|
+
var CALLBACK_BODY_LIMIT_BYTES = 16 * 1024;
|
|
222
|
+
async function readRequestBody(req) {
|
|
223
|
+
return new Promise((resolve, reject) => {
|
|
224
|
+
let totalBytes = 0;
|
|
225
|
+
let body = "";
|
|
226
|
+
req.setEncoding("utf8");
|
|
227
|
+
req.on("data", (chunk) => {
|
|
228
|
+
totalBytes += Buffer.byteLength(chunk);
|
|
229
|
+
if (totalBytes > CALLBACK_BODY_LIMIT_BYTES) {
|
|
230
|
+
reject(new Error("Callback payload too large"));
|
|
231
|
+
req.destroy();
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
body += chunk;
|
|
235
|
+
});
|
|
236
|
+
req.on("end", () => resolve(body));
|
|
237
|
+
req.on("error", reject);
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
async function parseCallbackPayload(req) {
|
|
241
|
+
const url = new URL(req.url || "/", "http://127.0.0.1");
|
|
242
|
+
let params = url.searchParams;
|
|
243
|
+
const isPost = req.method === "POST";
|
|
244
|
+
if (isPost) {
|
|
245
|
+
const rawBody = await readRequestBody(req);
|
|
246
|
+
params = new URLSearchParams(rawBody);
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
// The org API key is a secret. Accept it only from the POST body so it
|
|
250
|
+
// never transits a GET query string (query strings leak into browser
|
|
251
|
+
// history, proxy logs, and Referer headers). Ignore any ?token= on GET.
|
|
252
|
+
orgApiKey: isPost ? params.get("token") : null,
|
|
253
|
+
organizationName: params.get("org") || "",
|
|
254
|
+
expiresAt: params.get("expiresAt") || "",
|
|
255
|
+
error: params.get("error"),
|
|
256
|
+
returnedState: params.get("state")
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
async function browserAuth(baseUrl) {
|
|
260
|
+
return new Promise((resolve, reject) => {
|
|
261
|
+
const state = randomBytes(16).toString("hex");
|
|
262
|
+
const timeout = setTimeout(
|
|
263
|
+
() => {
|
|
264
|
+
server.close();
|
|
265
|
+
reject(new Error("Authentication timed out. Please try again."));
|
|
266
|
+
},
|
|
267
|
+
5 * 60 * 1e3
|
|
268
|
+
);
|
|
269
|
+
const server = http.createServer((req, res) => {
|
|
270
|
+
void (async () => {
|
|
271
|
+
const url = new URL(req.url || "/", "http://127.0.0.1");
|
|
272
|
+
if (url.pathname !== "/callback") {
|
|
273
|
+
res.writeHead(404);
|
|
274
|
+
res.end();
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (req.method !== "GET" && req.method !== "POST") {
|
|
278
|
+
res.writeHead(405, { "Content-Type": "text/html" });
|
|
279
|
+
res.end(getErrorHtml("Unsupported callback method"));
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const { orgApiKey, organizationName, expiresAt, error, returnedState } = await parseCallbackPayload(req);
|
|
283
|
+
if (returnedState !== state) {
|
|
284
|
+
res.writeHead(400, { "Content-Type": "text/html" });
|
|
285
|
+
res.end(getErrorHtml("Invalid authentication state"));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (error) {
|
|
289
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
290
|
+
res.end(getErrorHtml(error));
|
|
291
|
+
clearTimeout(timeout);
|
|
292
|
+
server.close();
|
|
293
|
+
reject(new Error(`Authentication failed: ${error}`));
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (!orgApiKey) {
|
|
297
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
298
|
+
res.end(getErrorHtml("No token received"));
|
|
299
|
+
clearTimeout(timeout);
|
|
300
|
+
server.close();
|
|
301
|
+
reject(new Error("No authentication token received"));
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
305
|
+
res.end(getSuccessHtml());
|
|
306
|
+
clearTimeout(timeout);
|
|
307
|
+
server.close();
|
|
308
|
+
resolve({ orgApiKey, organizationName, expiresAt });
|
|
309
|
+
})().catch((error) => {
|
|
310
|
+
res.writeHead(500, { "Content-Type": "text/html" });
|
|
311
|
+
res.end(getErrorHtml("Authentication callback failed"));
|
|
312
|
+
clearTimeout(timeout);
|
|
313
|
+
server.close();
|
|
314
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
server.listen(0, "127.0.0.1", () => {
|
|
318
|
+
const address = server.address();
|
|
319
|
+
if (!address || typeof address === "string") {
|
|
320
|
+
clearTimeout(timeout);
|
|
321
|
+
reject(new Error("Failed to start local auth server"));
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const callbackUrl = `http://127.0.0.1:${address.port}/callback`;
|
|
325
|
+
const authUrl = `${baseUrl}/cli-auth?callback=${encodeURIComponent(callbackUrl)}&state=${encodeURIComponent(state)}`;
|
|
326
|
+
open(authUrl).catch(() => {
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
function getSuccessHtml() {
|
|
332
|
+
return `<!DOCTYPE html>
|
|
333
|
+
<html>
|
|
334
|
+
<head><title>Conto CLI - Authenticated</title></head>
|
|
335
|
+
<body style="font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa;">
|
|
336
|
+
<script>
|
|
337
|
+
if (window.location.search || window.location.hash) {
|
|
338
|
+
window.history.replaceState(null, '', window.location.pathname);
|
|
339
|
+
}
|
|
340
|
+
</script>
|
|
341
|
+
<div style="text-align: center;">
|
|
342
|
+
<h1 style="color: #22c55e;">Authenticated</h1>
|
|
343
|
+
<p>You can close this window and return to the terminal.</p>
|
|
344
|
+
</div>
|
|
345
|
+
</body>
|
|
346
|
+
</html>`;
|
|
347
|
+
}
|
|
348
|
+
function escapeHtml(str) {
|
|
349
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
350
|
+
}
|
|
351
|
+
function getErrorHtml(error) {
|
|
352
|
+
return `<!DOCTYPE html>
|
|
353
|
+
<html>
|
|
354
|
+
<head><title>Conto CLI - Error</title></head>
|
|
355
|
+
<body style="font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa;">
|
|
356
|
+
<div style="text-align: center;">
|
|
357
|
+
<h1 style="color: #ef4444;">Authentication Failed</h1>
|
|
358
|
+
<p>${escapeHtml(error)}</p>
|
|
359
|
+
<p>Please return to the terminal and try again.</p>
|
|
360
|
+
</div>
|
|
361
|
+
</body>
|
|
362
|
+
</html>`;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// src/lib/http-json.ts
|
|
366
|
+
var HttpTransportError = class extends Error {
|
|
367
|
+
constructor(failure, code, message) {
|
|
368
|
+
super(message);
|
|
369
|
+
this.failure = failure;
|
|
370
|
+
this.code = code;
|
|
371
|
+
this.name = "HttpTransportError";
|
|
372
|
+
}
|
|
373
|
+
failure;
|
|
374
|
+
code;
|
|
375
|
+
};
|
|
376
|
+
var NOT_SENT_CODES = /* @__PURE__ */ new Set([
|
|
377
|
+
"ECONNREFUSED",
|
|
378
|
+
"ENOTFOUND",
|
|
379
|
+
"EAI_AGAIN",
|
|
380
|
+
"EHOSTUNREACH",
|
|
381
|
+
"ENETUNREACH",
|
|
382
|
+
"ERR_INVALID_URL",
|
|
383
|
+
"CERT_HAS_EXPIRED",
|
|
384
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
385
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
386
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
387
|
+
"ERR_TLS_CERT_ALTNAME_INVALID"
|
|
388
|
+
]);
|
|
389
|
+
var SECRET_PATTERNS = [
|
|
390
|
+
[/conto_claim_[A-Za-z0-9]+/g, "conto_claim_[redacted]"],
|
|
391
|
+
[/conto_agent_[A-Za-z0-9]+/g, "conto_agent_[redacted]"],
|
|
392
|
+
[/conto_setup_[A-Za-z0-9]+/g, "conto_setup_[redacted]"],
|
|
393
|
+
[/conto_[A-Fa-f0-9]{16,}/g, "conto_[redacted]"],
|
|
394
|
+
[/(Bearer\s+)\S+/gi, "$1[redacted]"]
|
|
395
|
+
];
|
|
396
|
+
function redactSecrets(text2) {
|
|
397
|
+
let result = text2;
|
|
398
|
+
for (const [pattern, replacement] of SECRET_PATTERNS) {
|
|
399
|
+
result = result.replace(pattern, replacement);
|
|
400
|
+
}
|
|
401
|
+
return result;
|
|
402
|
+
}
|
|
403
|
+
function isLoopbackHost(hostname) {
|
|
404
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
405
|
+
}
|
|
406
|
+
function parseSecureBaseUrl(baseUrl) {
|
|
407
|
+
let parsed;
|
|
408
|
+
try {
|
|
409
|
+
parsed = new URL(baseUrl);
|
|
410
|
+
} catch {
|
|
411
|
+
throw new Error(`Invalid base URL: ${baseUrl}`);
|
|
412
|
+
}
|
|
413
|
+
if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopbackHost(parsed.hostname))) {
|
|
414
|
+
throw new Error("Base URL must use https (except for localhost)");
|
|
415
|
+
}
|
|
416
|
+
if (parsed.username || parsed.password) {
|
|
417
|
+
throw new Error("Base URL must not contain credentials");
|
|
418
|
+
}
|
|
419
|
+
return parsed;
|
|
420
|
+
}
|
|
421
|
+
function normalizeBaseUrl(baseUrl) {
|
|
422
|
+
const parsed = new URL(baseUrl);
|
|
423
|
+
const pathname = parsed.pathname.replace(/\/+$/, "");
|
|
424
|
+
return `${parsed.origin}${pathname}`;
|
|
425
|
+
}
|
|
426
|
+
function apiUrl(baseUrl, apiPath) {
|
|
427
|
+
return new URL(`${normalizeBaseUrl(baseUrl)}${apiPath}`);
|
|
428
|
+
}
|
|
429
|
+
function errorCode(error) {
|
|
430
|
+
const cause = error?.cause;
|
|
431
|
+
return typeof cause?.code === "string" ? cause.code : void 0;
|
|
432
|
+
}
|
|
433
|
+
function classifyFetchError(error, callerSignal) {
|
|
434
|
+
const name = error?.name;
|
|
435
|
+
if (callerSignal?.aborted) {
|
|
436
|
+
return new HttpTransportError("aborted", "ABORTED", "The request was cancelled.");
|
|
437
|
+
}
|
|
438
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
439
|
+
return new HttpTransportError(
|
|
440
|
+
"unknown",
|
|
441
|
+
"TIMEOUT",
|
|
442
|
+
"The server did not respond in time. The request may still have been processed."
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
const code = errorCode(error);
|
|
446
|
+
if (code && NOT_SENT_CODES.has(code)) {
|
|
447
|
+
return new HttpTransportError("not_sent", code, `Could not connect to the server (${code}).`);
|
|
448
|
+
}
|
|
449
|
+
return new HttpTransportError(
|
|
450
|
+
"unknown",
|
|
451
|
+
code || "NETWORK_ERROR",
|
|
452
|
+
`The connection failed${code ? ` (${code})` : ""} before a response arrived. The request may still have been processed.`
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
async function requestJson(input) {
|
|
456
|
+
const headers = {
|
|
457
|
+
Accept: "application/json",
|
|
458
|
+
"User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`,
|
|
459
|
+
...input.headers
|
|
460
|
+
};
|
|
461
|
+
if (input.body !== void 0) headers["Content-Type"] = "application/json";
|
|
462
|
+
if (input.bearer) headers.Authorization = `Bearer ${input.bearer}`;
|
|
463
|
+
const timeoutSignal = AbortSignal.timeout(input.timeoutMs);
|
|
464
|
+
const signal = input.signal ? AbortSignal.any([input.signal, timeoutSignal]) : timeoutSignal;
|
|
465
|
+
let response;
|
|
466
|
+
try {
|
|
467
|
+
response = await fetch(input.url, {
|
|
468
|
+
method: input.method,
|
|
469
|
+
headers,
|
|
470
|
+
body: input.body === void 0 ? void 0 : JSON.stringify(input.body),
|
|
471
|
+
redirect: "manual",
|
|
472
|
+
signal
|
|
473
|
+
});
|
|
474
|
+
} catch (error) {
|
|
475
|
+
throw classifyFetchError(error, input.signal);
|
|
476
|
+
}
|
|
477
|
+
if (response.status >= 300 && response.status < 400) {
|
|
478
|
+
await response.body?.cancel().catch(() => void 0);
|
|
479
|
+
throw new HttpTransportError(
|
|
480
|
+
"not_sent",
|
|
481
|
+
"REDIRECT_REFUSED",
|
|
482
|
+
`The server answered with a redirect (HTTP ${response.status}). Credentials are never sent to a redirect target. Check the base URL.`
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
const contentType = response.headers.get("content-type") || "";
|
|
486
|
+
if (!contentType.includes("application/json")) {
|
|
487
|
+
await response.body?.cancel().catch(() => void 0);
|
|
488
|
+
return { status: response.status, headers: response.headers, data: void 0, isJson: false };
|
|
489
|
+
}
|
|
490
|
+
try {
|
|
491
|
+
const data = await response.json();
|
|
492
|
+
return { status: response.status, headers: response.headers, data, isJson: true };
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (input.signal?.aborted) throw classifyFetchError(error, input.signal);
|
|
495
|
+
return { status: response.status, headers: response.headers, data: void 0, isJson: false };
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
function retryAfterSeconds(headers, body) {
|
|
499
|
+
const header = headers.get("retry-after");
|
|
500
|
+
if (header) {
|
|
501
|
+
const seconds = Number(header);
|
|
502
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
503
|
+
const date = Date.parse(header);
|
|
504
|
+
if (Number.isFinite(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
|
|
505
|
+
}
|
|
506
|
+
const hint = body?.retryAfterSeconds;
|
|
507
|
+
if (typeof hint === "number" && Number.isFinite(hint) && hint >= 0) return Math.ceil(hint);
|
|
508
|
+
return void 0;
|
|
509
|
+
}
|
|
510
|
+
function responseErrorMessage(response, fallback) {
|
|
511
|
+
const body = response.data;
|
|
512
|
+
const text2 = typeof body?.error === "string" ? body.error : typeof body?.message === "string" ? body.message : fallback;
|
|
513
|
+
return redactSecrets(text2);
|
|
514
|
+
}
|
|
515
|
+
function responseErrorCode(response, fallback) {
|
|
516
|
+
const code = response.data?.code;
|
|
517
|
+
return typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code) ? code : fallback;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// src/lib/project-state.ts
|
|
521
|
+
import fs from "fs";
|
|
522
|
+
import path from "path";
|
|
523
|
+
import { createHash, randomBytes as randomBytes2 } from "crypto";
|
|
524
|
+
var PROJECT_STATE_DIR = ".conto";
|
|
525
|
+
var PRIVATE_DIR_MODE = 448;
|
|
526
|
+
var PRIVATE_FILE_MODE = 384;
|
|
527
|
+
function projectStateFile(fileName) {
|
|
528
|
+
return path.join(PROJECT_STATE_DIR, fileName);
|
|
529
|
+
}
|
|
530
|
+
function ensurePrivateStateDir(cwd) {
|
|
531
|
+
const dir = path.join(cwd, PROJECT_STATE_DIR);
|
|
532
|
+
if (!fs.existsSync(dir)) {
|
|
533
|
+
fs.mkdirSync(dir, { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
534
|
+
}
|
|
535
|
+
fs.chmodSync(dir, PRIVATE_DIR_MODE);
|
|
536
|
+
ensureContoDirGitignored(cwd);
|
|
537
|
+
return dir;
|
|
538
|
+
}
|
|
539
|
+
function readProjectStateFile(cwd, fileName) {
|
|
540
|
+
const filePath = path.join(cwd, PROJECT_STATE_DIR, fileName);
|
|
541
|
+
let raw;
|
|
542
|
+
try {
|
|
543
|
+
raw = fs.readFileSync(filePath, "utf8");
|
|
544
|
+
} catch (error) {
|
|
545
|
+
if (error.code === "ENOENT") return { found: false };
|
|
546
|
+
return { found: true, corrupt: true };
|
|
547
|
+
}
|
|
548
|
+
try {
|
|
549
|
+
return { found: true, corrupt: false, value: JSON.parse(raw) };
|
|
550
|
+
} catch {
|
|
551
|
+
return { found: true, corrupt: true };
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function writeProjectStateFile(cwd, fileName, value, options = {}) {
|
|
555
|
+
const dir = ensurePrivateStateDir(cwd);
|
|
556
|
+
const filePath = path.join(dir, fileName);
|
|
557
|
+
const content = JSON.stringify(value, null, 2) + "\n";
|
|
558
|
+
if (options.exclusive) {
|
|
559
|
+
fs.writeFileSync(filePath, content, { mode: PRIVATE_FILE_MODE, flag: "wx" });
|
|
560
|
+
} else {
|
|
561
|
+
const tempPath = `${filePath}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
|
|
562
|
+
try {
|
|
563
|
+
fs.writeFileSync(tempPath, content, { mode: PRIVATE_FILE_MODE, flag: "wx" });
|
|
564
|
+
fs.renameSync(tempPath, filePath);
|
|
565
|
+
} catch (error) {
|
|
566
|
+
fs.rmSync(tempPath, { force: true });
|
|
567
|
+
throw error;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
fs.chmodSync(filePath, PRIVATE_FILE_MODE);
|
|
571
|
+
return projectStateFile(fileName);
|
|
572
|
+
}
|
|
573
|
+
function removeProjectStateFile(cwd, fileName) {
|
|
574
|
+
const dir = path.join(cwd, PROJECT_STATE_DIR);
|
|
575
|
+
fs.rmSync(path.join(dir, fileName), { force: true });
|
|
576
|
+
try {
|
|
577
|
+
fs.rmdirSync(dir);
|
|
578
|
+
} catch {
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
function fingerprintSecret(secret) {
|
|
582
|
+
return `sha256:${createHash("sha256").update(secret).digest("hex").slice(0, 16)}`;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// src/lib/init-checkpoint.ts
|
|
586
|
+
import { createHash as createHash2, randomBytes as randomBytes3 } from "crypto";
|
|
587
|
+
var INIT_CHECKPOINT_NAME = "init-checkpoint.json";
|
|
588
|
+
var INIT_CHECKPOINT_FILE = projectStateFile(INIT_CHECKPOINT_NAME);
|
|
589
|
+
var STEP_ORDER = ["wallet", "faucet", "agent", "walletLink", "policy", "sdkKey"];
|
|
590
|
+
var STEP_LABELS = {
|
|
591
|
+
wallet: "wallet",
|
|
592
|
+
faucet: "testnet faucet request",
|
|
593
|
+
agent: "agent",
|
|
594
|
+
walletLink: "wallet link and spend limits",
|
|
595
|
+
policy: "default spending policy",
|
|
596
|
+
sdkKey: "agent SDK key"
|
|
597
|
+
};
|
|
598
|
+
function canonicalJson(value) {
|
|
599
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
600
|
+
if (value && typeof value === "object") {
|
|
601
|
+
const entries = Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
602
|
+
return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
|
|
603
|
+
}
|
|
604
|
+
return JSON.stringify(value);
|
|
605
|
+
}
|
|
606
|
+
function configurationHash(request) {
|
|
607
|
+
return `sha256:${createHash2("sha256").update(canonicalJson(request)).digest("hex")}`;
|
|
608
|
+
}
|
|
609
|
+
function newOperationId() {
|
|
610
|
+
return randomBytes3(8).toString("hex");
|
|
611
|
+
}
|
|
612
|
+
function createCheckpoint(input) {
|
|
613
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
614
|
+
const steps = Object.fromEntries(
|
|
615
|
+
STEP_ORDER.map((step) => [step, { status: "pending" }])
|
|
616
|
+
);
|
|
617
|
+
return {
|
|
618
|
+
version: 1,
|
|
619
|
+
kind: "conto-init",
|
|
620
|
+
operationId: input.operationId,
|
|
621
|
+
createdAt: now,
|
|
622
|
+
updatedAt: now,
|
|
623
|
+
status: "in_progress",
|
|
624
|
+
binding: {
|
|
625
|
+
baseUrl: input.baseUrl,
|
|
626
|
+
configurationHash: configurationHash(input.request),
|
|
627
|
+
organization: {
|
|
628
|
+
credentialFingerprint: input.credentialFingerprint,
|
|
629
|
+
...input.organizationName ? { name: input.organizationName } : {}
|
|
630
|
+
}
|
|
631
|
+
},
|
|
632
|
+
request: input.request,
|
|
633
|
+
steps
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
function validCheckpoint(value) {
|
|
637
|
+
const checkpoint = value;
|
|
638
|
+
if (!checkpoint || typeof checkpoint !== "object") return { ok: false, reason: "not an object" };
|
|
639
|
+
if (checkpoint.version !== 1 || checkpoint.kind !== "conto-init") {
|
|
640
|
+
return { ok: false, reason: "unsupported checkpoint version" };
|
|
641
|
+
}
|
|
642
|
+
if (!checkpoint.binding || typeof checkpoint.binding.baseUrl !== "string") {
|
|
643
|
+
return { ok: false, reason: "missing binding" };
|
|
644
|
+
}
|
|
645
|
+
if (!checkpoint.request || checkpoint.request.mode !== "organization") {
|
|
646
|
+
return { ok: false, reason: "missing requested configuration" };
|
|
647
|
+
}
|
|
648
|
+
if (!checkpoint.steps || STEP_ORDER.some((step) => !checkpoint.steps?.[step]?.status)) {
|
|
649
|
+
return { ok: false, reason: "missing step records" };
|
|
650
|
+
}
|
|
651
|
+
if (checkpoint.binding.configurationHash !== configurationHash(checkpoint.request)) {
|
|
652
|
+
return { ok: false, reason: "the requested configuration does not match its hash" };
|
|
653
|
+
}
|
|
654
|
+
return { ok: true };
|
|
655
|
+
}
|
|
656
|
+
function loadCheckpoint(cwd) {
|
|
657
|
+
const read = readProjectStateFile(cwd, INIT_CHECKPOINT_NAME);
|
|
658
|
+
if (!read.found) return { kind: "none" };
|
|
659
|
+
if (read.corrupt) return { kind: "corrupt", reason: "the file is not valid JSON" };
|
|
660
|
+
const valid = validCheckpoint(read.value);
|
|
661
|
+
if (!valid.ok) {
|
|
662
|
+
return {
|
|
663
|
+
kind: "corrupt",
|
|
664
|
+
reason: valid.reason,
|
|
665
|
+
partial: read.value ?? void 0
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
return { kind: "found", checkpoint: read.value };
|
|
669
|
+
}
|
|
670
|
+
function saveCheckpoint(cwd, checkpoint, options = {}) {
|
|
671
|
+
checkpoint.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
672
|
+
writeProjectStateFile(cwd, INIT_CHECKPOINT_NAME, checkpoint, options);
|
|
673
|
+
}
|
|
674
|
+
function removeCheckpoint(cwd) {
|
|
675
|
+
removeProjectStateFile(cwd, INIT_CHECKPOINT_NAME);
|
|
676
|
+
}
|
|
677
|
+
function recordedResources(checkpoint) {
|
|
678
|
+
const steps = checkpoint?.steps || {};
|
|
679
|
+
return {
|
|
680
|
+
walletId: steps.wallet?.id ?? null,
|
|
681
|
+
walletAddress: steps.wallet?.address ?? null,
|
|
682
|
+
agentId: steps.agent?.id ?? null,
|
|
683
|
+
walletLinkId: steps.walletLink?.id ?? null,
|
|
684
|
+
policyId: steps.policy?.id ?? null,
|
|
685
|
+
sdkKeyId: steps.sdkKey?.id ?? null
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
function hasServerSideEffects(checkpoint) {
|
|
689
|
+
return STEP_ORDER.some((step) => {
|
|
690
|
+
if (step === "faucet") return false;
|
|
691
|
+
const status = checkpoint.steps[step].status;
|
|
692
|
+
return status === "done" || status === "unknown" || status === "in_progress" || status === "action_required";
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// src/lib/init-provisioning.ts
|
|
697
|
+
var RECONCILE_WAIT_SECONDS = 300;
|
|
698
|
+
var iso = (ms = Date.now()) => new Date(ms).toISOString();
|
|
699
|
+
async function provisionOrganization(input) {
|
|
700
|
+
const { checkpoint, client, ui, chain } = input;
|
|
701
|
+
const steps = checkpoint.steps;
|
|
702
|
+
const request = checkpoint.request;
|
|
703
|
+
const now = input.now ?? Date.now;
|
|
704
|
+
const resources = {};
|
|
705
|
+
const persist = () => input.persist();
|
|
706
|
+
const bindOrganization = () => {
|
|
707
|
+
checkpoint.binding.organization.credentialFingerprint = input.organization.credentialFingerprint;
|
|
708
|
+
if (input.organization.name) checkpoint.binding.organization.name = input.organization.name;
|
|
709
|
+
};
|
|
710
|
+
const stopped = (stop) => {
|
|
711
|
+
if (stop.status !== "refused") {
|
|
712
|
+
checkpoint.failedStep = stop.step;
|
|
713
|
+
checkpoint.status = stop.status === "reconciliation_required" || stop.status === "owner_action_required" ? stop.status : "partial";
|
|
714
|
+
persist();
|
|
715
|
+
}
|
|
716
|
+
return { kind: "stopped", stop, resources };
|
|
717
|
+
};
|
|
718
|
+
const refuse2 = (step, code, message) => stopped({ status: "refused", step, code, message });
|
|
719
|
+
const credentialRejected = (step, failure) => failure.httpStatus === 401 || failure.httpStatus === 403 ? stopped({
|
|
720
|
+
status: "refused",
|
|
721
|
+
step,
|
|
722
|
+
code: "CREDENTIAL_REJECTED",
|
|
723
|
+
message: `The organization credential was rejected (${failure.message}). Resume with a valid organization API key for this organization.`,
|
|
724
|
+
httpStatus: failure.httpStatus
|
|
725
|
+
}) : null;
|
|
726
|
+
const verifyFailed = (step, failure) => credentialRejected(step, failure) ?? stopped({
|
|
727
|
+
status: "partial",
|
|
728
|
+
step,
|
|
729
|
+
code: "VERIFY_FAILED",
|
|
730
|
+
message: `Could not verify the ${STEP_LABELS[step]} from the earlier run: ${failure.message}`,
|
|
731
|
+
httpStatus: failure.httpStatus
|
|
732
|
+
});
|
|
733
|
+
const statusBeforeRun = Object.fromEntries(
|
|
734
|
+
Object.entries(steps).map(([step, record]) => [step, record.status])
|
|
735
|
+
);
|
|
736
|
+
const begin = (step) => {
|
|
737
|
+
const previous = steps[step];
|
|
738
|
+
steps[step] = {
|
|
739
|
+
status: "in_progress",
|
|
740
|
+
attemptedAt: iso(now()),
|
|
741
|
+
...previous.approvalRequestId ? { approvalRequestId: previous.approvalRequestId } : {}
|
|
742
|
+
};
|
|
743
|
+
checkpoint.status = "in_progress";
|
|
744
|
+
persist();
|
|
745
|
+
};
|
|
746
|
+
const complete = (step, fields = {}) => {
|
|
747
|
+
steps[step] = {
|
|
748
|
+
...fields,
|
|
749
|
+
status: "done",
|
|
750
|
+
attemptedAt: steps[step].attemptedAt,
|
|
751
|
+
completedAt: iso(now())
|
|
752
|
+
};
|
|
753
|
+
persist();
|
|
754
|
+
};
|
|
755
|
+
const createFailed = (step, result) => {
|
|
756
|
+
const attemptedAt = steps[step].attemptedAt ?? iso(now());
|
|
757
|
+
if (result.outcome === "approval_required") {
|
|
758
|
+
steps[step] = {
|
|
759
|
+
status: "action_required",
|
|
760
|
+
attemptedAt,
|
|
761
|
+
approvalRequestId: result.approvalRequestId,
|
|
762
|
+
error: result.failure
|
|
763
|
+
};
|
|
764
|
+
return stopped({
|
|
765
|
+
status: "owner_action_required",
|
|
766
|
+
step,
|
|
767
|
+
code: result.failure.code,
|
|
768
|
+
message: result.failure.message,
|
|
769
|
+
httpStatus: result.failure.httpStatus,
|
|
770
|
+
ownerAction: {
|
|
771
|
+
action: "An organization owner or admin must approve this governance request in Conto. Then resume setup, which retries with the approval.",
|
|
772
|
+
dashboardUrl: `${input.baseUrl}/alerts`,
|
|
773
|
+
approvalRequestId: result.approvalRequestId
|
|
774
|
+
}
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
if (result.outcome === "unknown") {
|
|
778
|
+
steps[step] = {
|
|
779
|
+
status: "unknown",
|
|
780
|
+
attemptedAt,
|
|
781
|
+
inFlightPossible: result.inFlightPossible,
|
|
782
|
+
error: result.failure
|
|
783
|
+
};
|
|
784
|
+
return stopped({
|
|
785
|
+
status: "reconciliation_required",
|
|
786
|
+
step,
|
|
787
|
+
code: result.failure.code,
|
|
788
|
+
message: result.failure.message,
|
|
789
|
+
httpStatus: result.failure.httpStatus,
|
|
790
|
+
reconciliation: {
|
|
791
|
+
reason: `The server may have created the ${STEP_LABELS[step]}. Setup stopped instead of sending it again.`,
|
|
792
|
+
action: reconcileAction(step),
|
|
793
|
+
...result.inFlightPossible && step !== "wallet" && step !== "walletLink" ? { notBefore: iso(Date.parse(attemptedAt) + RECONCILE_WAIT_SECONDS * 1e3) } : {}
|
|
794
|
+
}
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
steps[step] = { status: "failed", attemptedAt, error: result.failure };
|
|
798
|
+
const earlierOutcomeUnknown = ["unknown", "in_progress", "action_required"].includes(
|
|
799
|
+
statusBeforeRun[step]
|
|
800
|
+
);
|
|
801
|
+
return stopped({
|
|
802
|
+
status: hasServerSideEffects(checkpoint) || earlierOutcomeUnknown ? "partial" : "failed",
|
|
803
|
+
step,
|
|
804
|
+
code: result.failure.code,
|
|
805
|
+
message: result.failure.message,
|
|
806
|
+
httpStatus: result.failure.httpStatus,
|
|
807
|
+
retryAfterSeconds: result.retryAfterSeconds
|
|
808
|
+
});
|
|
809
|
+
};
|
|
810
|
+
const waitRequired = (step) => {
|
|
811
|
+
const record = steps[step];
|
|
812
|
+
const inFlight = record.status === "in_progress" || record.inFlightPossible === true;
|
|
813
|
+
if (!inFlight || !record.attemptedAt) return null;
|
|
814
|
+
const notBefore = Date.parse(record.attemptedAt) + RECONCILE_WAIT_SECONDS * 1e3;
|
|
815
|
+
if (now() >= notBefore) return null;
|
|
816
|
+
return {
|
|
817
|
+
status: "reconciliation_required",
|
|
818
|
+
step,
|
|
819
|
+
code: "RECONCILE_WAIT",
|
|
820
|
+
message: `The earlier ${STEP_LABELS[step]} request may still be running on the server, and the ${STEP_LABELS[step]} was not found yet.`,
|
|
821
|
+
reconciliation: {
|
|
822
|
+
reason: "A request with an unknown outcome can still complete for a few minutes.",
|
|
823
|
+
action: `Resume after ${iso(notBefore)}. The resume looks the ${STEP_LABELS[step]} up again before creating one.`,
|
|
824
|
+
notBefore: iso(notBefore)
|
|
825
|
+
}
|
|
826
|
+
};
|
|
827
|
+
};
|
|
828
|
+
const lookupFailed = (step, failure) => credentialRejected(step, failure) ?? stopped({
|
|
829
|
+
status: "reconciliation_required",
|
|
830
|
+
step,
|
|
831
|
+
code: "LOOKUP_FAILED",
|
|
832
|
+
message: `Could not check whether the ${STEP_LABELS[step]} exists: ${failure.message}`,
|
|
833
|
+
httpStatus: failure.httpStatus,
|
|
834
|
+
reconciliation: {
|
|
835
|
+
reason: "Setup could not confirm what already exists, so it created nothing.",
|
|
836
|
+
action: reconcileAction(step)
|
|
837
|
+
}
|
|
838
|
+
});
|
|
839
|
+
const duplicates = (step, ids) => stopped({
|
|
840
|
+
status: "reconciliation_required",
|
|
841
|
+
step,
|
|
842
|
+
code: "DUPLICATE_RESOURCES",
|
|
843
|
+
message: `Found ${ids.length} ${STEP_LABELS[step]} records from this setup. Setup will not pick one on its own.`,
|
|
844
|
+
reconciliation: {
|
|
845
|
+
reason: "An earlier request with an unknown outcome was completed more than once.",
|
|
846
|
+
action: `Keep one and remove the others in Conto, then resume.`,
|
|
847
|
+
resourceIds: ids
|
|
848
|
+
}
|
|
849
|
+
});
|
|
850
|
+
if (steps.wallet.status === "done" && input.resuming) {
|
|
851
|
+
ui.start("Checking the wallet from the earlier run...");
|
|
852
|
+
const read = await client.getWallet(steps.wallet.id);
|
|
853
|
+
if (!read.ok) {
|
|
854
|
+
ui.stop("Wallet check failed");
|
|
855
|
+
if (read.notFound) {
|
|
856
|
+
return refuse2(
|
|
857
|
+
"wallet",
|
|
858
|
+
"ORGANIZATION_MISMATCH",
|
|
859
|
+
`Wallet ${steps.wallet.id} from this setup is not visible with this credential. The credential belongs to another organization, or the wallet was removed.`
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
return verifyFailed("wallet", read.failure);
|
|
863
|
+
}
|
|
864
|
+
if (typeof read.value.chainId === "string" && read.value.chainId !== request.chainId) {
|
|
865
|
+
ui.stop("Wallet check failed");
|
|
866
|
+
return refuse2(
|
|
867
|
+
"wallet",
|
|
868
|
+
"RESOURCE_CHANGED",
|
|
869
|
+
`Wallet ${read.value.id} is on network ${read.value.chainId}, but this setup requested ${request.chainId}.`
|
|
870
|
+
);
|
|
871
|
+
}
|
|
872
|
+
ui.stop("Wallet verified");
|
|
873
|
+
resources.wallet = read.value;
|
|
874
|
+
bindOrganization();
|
|
875
|
+
} else if (steps.wallet.status !== "done") {
|
|
876
|
+
ui.start(`Creating wallet on ${chain.name}...`);
|
|
877
|
+
begin("wallet");
|
|
878
|
+
const result = await client.createWallet({
|
|
879
|
+
name: request.walletName,
|
|
880
|
+
chainType: request.chainType,
|
|
881
|
+
chainId: request.chainId
|
|
882
|
+
});
|
|
883
|
+
if (!result.ok) {
|
|
884
|
+
ui.stop("Wallet creation failed");
|
|
885
|
+
return createFailed("wallet", result);
|
|
886
|
+
}
|
|
887
|
+
const wallet2 = result.value;
|
|
888
|
+
checkpoint.binding.organization.anchor = { resource: "wallet", id: wallet2.id };
|
|
889
|
+
bindOrganization();
|
|
890
|
+
complete("wallet", { id: wallet2.id, address: wallet2.address, custodyMode: wallet2.custodyMode });
|
|
891
|
+
ui.stop(
|
|
892
|
+
result.httpStatus === 200 ? `Using the existing wallet named "${request.walletName}" on ${chain.name}` : `Wallet created on ${chain.name}`
|
|
893
|
+
);
|
|
894
|
+
ui.success(`Wallet: ${wallet2.address} (${wallet2.custodyMode ?? "MANAGED"} custody)`);
|
|
895
|
+
resources.wallet = wallet2;
|
|
896
|
+
}
|
|
897
|
+
const wallet = resources.wallet;
|
|
898
|
+
if (steps.faucet.status === "pending") {
|
|
899
|
+
if (chain.faucetAvailable) {
|
|
900
|
+
ui.start("Requesting testnet funds from faucet...");
|
|
901
|
+
begin("faucet");
|
|
902
|
+
const faucet = await client.requestFaucet(wallet.id);
|
|
903
|
+
if (faucet.ok) {
|
|
904
|
+
complete("faucet");
|
|
905
|
+
ui.stop("Faucet request sent");
|
|
906
|
+
ui.success(
|
|
907
|
+
typeof faucet.updatedBalance === "number" ? `Wallet balance: ${faucet.updatedBalance} ${chain.currency} (testnet)` : faucet.message || `Testnet ${chain.currency} requested`
|
|
908
|
+
);
|
|
909
|
+
} else {
|
|
910
|
+
steps.faucet = {
|
|
911
|
+
status: "failed",
|
|
912
|
+
attemptedAt: steps.faucet.attemptedAt,
|
|
913
|
+
error: { code: "FAUCET_UNAVAILABLE", message: faucet.message }
|
|
914
|
+
};
|
|
915
|
+
persist();
|
|
916
|
+
ui.stop("Faucet request failed (you can fund manually)");
|
|
917
|
+
ui.info(faucet.message);
|
|
918
|
+
}
|
|
919
|
+
} else {
|
|
920
|
+
steps.faucet = { status: "skipped" };
|
|
921
|
+
persist();
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
if (steps.agent.status === "done") {
|
|
925
|
+
if (input.resuming) {
|
|
926
|
+
ui.start("Checking the agent from the earlier run...");
|
|
927
|
+
const read = await client.getAgent(steps.agent.id);
|
|
928
|
+
if (!read.ok) {
|
|
929
|
+
ui.stop("Agent check failed");
|
|
930
|
+
return read.notFound ? refuse2(
|
|
931
|
+
"agent",
|
|
932
|
+
"RESOURCE_MISSING",
|
|
933
|
+
`Agent ${steps.agent.id} from this setup no longer exists.`
|
|
934
|
+
) : verifyFailed("agent", read.failure);
|
|
935
|
+
}
|
|
936
|
+
ui.stop("Agent verified");
|
|
937
|
+
resources.agent = read.value;
|
|
938
|
+
}
|
|
939
|
+
} else {
|
|
940
|
+
if (steps.agent.status === "in_progress" || steps.agent.status === "unknown") {
|
|
941
|
+
ui.start("Looking up the agent from the earlier run...");
|
|
942
|
+
const found = await client.findAgentsByExternalId(request.agentExternalId);
|
|
943
|
+
ui.stop("Agent lookup finished");
|
|
944
|
+
if (!found.ok) return lookupFailed("agent", found.failure);
|
|
945
|
+
if (found.value.length > 1)
|
|
946
|
+
return duplicates(
|
|
947
|
+
"agent",
|
|
948
|
+
found.value.map((agent2) => agent2.id)
|
|
949
|
+
);
|
|
950
|
+
if (found.value.length === 1) {
|
|
951
|
+
resources.agent = found.value[0];
|
|
952
|
+
complete("agent", { id: found.value[0].id });
|
|
953
|
+
ui.success(`Agent "${found.value[0].name}" found from the earlier run`);
|
|
954
|
+
} else {
|
|
955
|
+
const wait = waitRequired("agent");
|
|
956
|
+
if (wait) return stopped(wait);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
if (!resources.agent) {
|
|
960
|
+
ui.start(`Registering agent "${request.agentName}"...`);
|
|
961
|
+
begin("agent");
|
|
962
|
+
const result = await client.createAgent({
|
|
963
|
+
name: request.agentName,
|
|
964
|
+
agentType: request.agentType,
|
|
965
|
+
description: "Created via CLI quickstart",
|
|
966
|
+
environment: request.agentEnvironment,
|
|
967
|
+
externalId: request.agentExternalId
|
|
968
|
+
});
|
|
969
|
+
if (!result.ok) {
|
|
970
|
+
ui.stop("Agent creation failed");
|
|
971
|
+
return createFailed("agent", result);
|
|
972
|
+
}
|
|
973
|
+
complete("agent", { id: result.value.id });
|
|
974
|
+
ui.stop("Agent registered");
|
|
975
|
+
ui.success(
|
|
976
|
+
`Agent "${result.value.name}" created (${result.value.environment ?? request.agentEnvironment})`
|
|
977
|
+
);
|
|
978
|
+
resources.agent = result.value;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
const agent = resources.agent;
|
|
982
|
+
if (steps.walletLink.status === "done") {
|
|
983
|
+
if (input.resuming) {
|
|
984
|
+
const links = await client.listWalletLinks(agent.id);
|
|
985
|
+
if (!links.ok) return verifyFailed("walletLink", links.failure);
|
|
986
|
+
const link = links.value.find((entry) => entry.walletId === wallet.id);
|
|
987
|
+
if (!link) {
|
|
988
|
+
return refuse2(
|
|
989
|
+
"walletLink",
|
|
990
|
+
"RESOURCE_MISSING",
|
|
991
|
+
`The link between agent ${agent.id} and wallet ${wallet.id} no longer exists.`
|
|
992
|
+
);
|
|
993
|
+
}
|
|
994
|
+
if (link.isActive === false) {
|
|
995
|
+
return refuse2(
|
|
996
|
+
"walletLink",
|
|
997
|
+
"RESOURCE_CHANGED",
|
|
998
|
+
`The link between agent ${agent.id} and wallet ${wallet.id} was deactivated after setup created it.`
|
|
999
|
+
);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
} else {
|
|
1003
|
+
let adopted = false;
|
|
1004
|
+
if (input.resuming || steps.walletLink.status !== "pending") {
|
|
1005
|
+
const links = await client.listWalletLinks(agent.id);
|
|
1006
|
+
if (!links.ok) return lookupFailed("walletLink", links.failure);
|
|
1007
|
+
const link = links.value.find((entry) => entry.walletId === wallet.id);
|
|
1008
|
+
if (link && link.isActive === false) {
|
|
1009
|
+
return stopped({
|
|
1010
|
+
status: "owner_action_required",
|
|
1011
|
+
step: "walletLink",
|
|
1012
|
+
code: "LINK_INACTIVE",
|
|
1013
|
+
message: `The link between agent ${agent.id} and wallet ${wallet.id} exists but is inactive.`,
|
|
1014
|
+
ownerAction: {
|
|
1015
|
+
action: "Reactivate the wallet link in Conto or remove it, then resume.",
|
|
1016
|
+
dashboardUrl: `${input.baseUrl}/agents/${agent.id}`
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
if (link) {
|
|
1021
|
+
complete("walletLink", { id: link.id });
|
|
1022
|
+
ui.success(
|
|
1023
|
+
typeof link.spendLimitDaily === "number" ? `Wallet link found ($${link.spendLimitDaily}/day limit kept as is)` : "Wallet link found (limits kept as is)"
|
|
1024
|
+
);
|
|
1025
|
+
adopted = true;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
if (!adopted) {
|
|
1029
|
+
ui.start("Linking wallet to agent...");
|
|
1030
|
+
begin("walletLink");
|
|
1031
|
+
const result = await client.linkWallet(agent.id, {
|
|
1032
|
+
walletId: wallet.id,
|
|
1033
|
+
delegationType: "FULL",
|
|
1034
|
+
spendLimitDaily: request.dailyLimit,
|
|
1035
|
+
spendLimitPerTx: request.perTransactionLimit
|
|
1036
|
+
});
|
|
1037
|
+
if (!result.ok) {
|
|
1038
|
+
ui.stop("Wallet linking failed");
|
|
1039
|
+
return createFailed("walletLink", result);
|
|
1040
|
+
}
|
|
1041
|
+
complete("walletLink", { id: result.value.id });
|
|
1042
|
+
ui.stop("Wallet linked");
|
|
1043
|
+
ui.success(`Wallet linked ($${request.dailyLimit}/day limit)`);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
if (steps.policy.status === "done") {
|
|
1047
|
+
if (input.resuming) {
|
|
1048
|
+
const assigned = await client.listAssignedPolicies(agent.id);
|
|
1049
|
+
if (!assigned.ok) return verifyFailed("policy", assigned.failure);
|
|
1050
|
+
if (!assigned.value.some((policy) => policy.policyId === steps.policy.id)) {
|
|
1051
|
+
return refuse2(
|
|
1052
|
+
"policy",
|
|
1053
|
+
"RESOURCE_MISSING",
|
|
1054
|
+
`Policy ${steps.policy.id} from this setup is no longer assigned to agent ${agent.id}.`
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
} else {
|
|
1059
|
+
let adopted = false;
|
|
1060
|
+
if (steps.policy.status === "in_progress" || steps.policy.status === "unknown") {
|
|
1061
|
+
const assigned = await client.listAssignedPolicies(agent.id);
|
|
1062
|
+
if (!assigned.ok) return lookupFailed("policy", assigned.failure);
|
|
1063
|
+
const matches = assigned.value.filter((policy) => policy.name === request.policyName);
|
|
1064
|
+
if (matches.length > 1)
|
|
1065
|
+
return duplicates(
|
|
1066
|
+
"policy",
|
|
1067
|
+
matches.map((policy) => policy.policyId)
|
|
1068
|
+
);
|
|
1069
|
+
if (matches.length === 1) {
|
|
1070
|
+
complete("policy", { id: matches[0].policyId });
|
|
1071
|
+
ui.success("Default spending policy found from the earlier run");
|
|
1072
|
+
adopted = true;
|
|
1073
|
+
} else {
|
|
1074
|
+
const wait = waitRequired("policy");
|
|
1075
|
+
if (wait) return stopped(wait);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
if (!adopted) {
|
|
1079
|
+
const approvalRequestId = steps.policy.status === "action_required" ? steps.policy.approvalRequestId : void 0;
|
|
1080
|
+
ui.start("Creating default spending policy...");
|
|
1081
|
+
begin("policy");
|
|
1082
|
+
const result = await client.createPolicy(
|
|
1083
|
+
{
|
|
1084
|
+
name: request.policyName,
|
|
1085
|
+
policyType: "SPEND_LIMIT",
|
|
1086
|
+
priority: 50,
|
|
1087
|
+
isActive: true,
|
|
1088
|
+
rules: [
|
|
1089
|
+
{
|
|
1090
|
+
ruleType: "DAILY_LIMIT",
|
|
1091
|
+
// Canonical operator accepted by the strict enum at POST /api/policies.
|
|
1092
|
+
operator: "LTE",
|
|
1093
|
+
value: String(request.dailyLimit),
|
|
1094
|
+
action: "ALLOW"
|
|
1095
|
+
}
|
|
1096
|
+
],
|
|
1097
|
+
agentIds: [agent.id]
|
|
1098
|
+
},
|
|
1099
|
+
approvalRequestId
|
|
1100
|
+
);
|
|
1101
|
+
if (!result.ok) {
|
|
1102
|
+
ui.stop("Policy creation failed");
|
|
1103
|
+
return createFailed("policy", result);
|
|
1104
|
+
}
|
|
1105
|
+
complete("policy", { id: result.value.id });
|
|
1106
|
+
ui.stop("Policy created");
|
|
1107
|
+
ui.success("Default spending policy applied");
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
const rotationAction = (keys) => ({
|
|
1111
|
+
status: "owner_action_required",
|
|
1112
|
+
step: "sdkKey",
|
|
1113
|
+
code: "SDK_KEY_SECRET_UNAVAILABLE",
|
|
1114
|
+
message: "An SDK key was issued for this agent, but its secret was not saved. A key secret is shown only once and cannot be recovered.",
|
|
1115
|
+
ownerAction: {
|
|
1116
|
+
action: "Revoke the key listed here (agent page, SDK Integration tab, or the API call below with an organization key). Then resume setup to issue a new key.",
|
|
1117
|
+
dashboardUrl: `${input.baseUrl}/agents/${agent.id}`,
|
|
1118
|
+
api: {
|
|
1119
|
+
method: "DELETE",
|
|
1120
|
+
path: `/api/agents/${agent.id}/sdk-keys?keyId=${keys[0]?.id ?? "<keyId>"}`,
|
|
1121
|
+
requiredScope: "agents:write"
|
|
1122
|
+
},
|
|
1123
|
+
keys
|
|
1124
|
+
}
|
|
1125
|
+
});
|
|
1126
|
+
const adoptStoredKey = async () => {
|
|
1127
|
+
const stored = input.storedSdkKey(agent.id);
|
|
1128
|
+
if (!stored) return "none";
|
|
1129
|
+
const check = await client.checkSdkKey(stored);
|
|
1130
|
+
if (check.ok && check.value.agentId === agent.id) {
|
|
1131
|
+
resources.sdkKey = { key: stored };
|
|
1132
|
+
return "adopted";
|
|
1133
|
+
}
|
|
1134
|
+
if (!check.ok && !check.notFound && !(check.failure.httpStatus && check.failure.httpStatus < 500)) {
|
|
1135
|
+
return {
|
|
1136
|
+
status: "partial",
|
|
1137
|
+
step: "sdkKey",
|
|
1138
|
+
code: "VERIFY_FAILED",
|
|
1139
|
+
message: `Could not verify the stored SDK key: ${check.failure.message}`,
|
|
1140
|
+
httpStatus: check.failure.httpStatus
|
|
1141
|
+
};
|
|
1142
|
+
}
|
|
1143
|
+
return "none";
|
|
1144
|
+
};
|
|
1145
|
+
if (steps.sdkKey.status === "done" && input.resuming) {
|
|
1146
|
+
const stored = await adoptStoredKey();
|
|
1147
|
+
if (typeof stored === "object") return stopped(stored);
|
|
1148
|
+
if (stored === "none") {
|
|
1149
|
+
steps.sdkKey = { ...steps.sdkKey, status: "action_required" };
|
|
1150
|
+
return stopped(rotationAction(steps.sdkKey.id ? [{ id: steps.sdkKey.id }] : []));
|
|
1151
|
+
}
|
|
1152
|
+
} else if (steps.sdkKey.status !== "done") {
|
|
1153
|
+
let adopted = false;
|
|
1154
|
+
if (["in_progress", "unknown", "action_required"].includes(steps.sdkKey.status)) {
|
|
1155
|
+
const stored = await adoptStoredKey();
|
|
1156
|
+
if (typeof stored === "object") return stopped(stored);
|
|
1157
|
+
if (stored === "adopted") {
|
|
1158
|
+
complete("sdkKey", { id: steps.sdkKey.id, secretStoredIn: ".env.local" });
|
|
1159
|
+
ui.success("SDK key from the earlier run verified");
|
|
1160
|
+
adopted = true;
|
|
1161
|
+
} else {
|
|
1162
|
+
const keys = await client.listSdkKeys(agent.id);
|
|
1163
|
+
if (!keys.ok) return lookupFailed("sdkKey", keys.failure);
|
|
1164
|
+
const orphaned = keys.value.filter(
|
|
1165
|
+
(key) => key.name === request.sdkKeyName && key.isActive !== false && !key.revokedAt
|
|
1166
|
+
);
|
|
1167
|
+
if (orphaned.length > 0) {
|
|
1168
|
+
steps.sdkKey = { ...steps.sdkKey, status: "action_required" };
|
|
1169
|
+
return stopped(
|
|
1170
|
+
rotationAction(orphaned.map((key) => ({ id: key.id, keyPrefix: key.keyPrefix })))
|
|
1171
|
+
);
|
|
1172
|
+
}
|
|
1173
|
+
if (steps.sdkKey.status !== "action_required") {
|
|
1174
|
+
const wait = waitRequired("sdkKey");
|
|
1175
|
+
if (wait) return stopped(wait);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
if (!adopted) {
|
|
1180
|
+
ui.start("Generating SDK key...");
|
|
1181
|
+
begin("sdkKey");
|
|
1182
|
+
const result = await client.createSdkKey(agent.id, {
|
|
1183
|
+
name: request.sdkKeyName,
|
|
1184
|
+
keyType: request.sdkKeyType
|
|
1185
|
+
});
|
|
1186
|
+
if (!result.ok) {
|
|
1187
|
+
ui.stop("SDK key generation failed");
|
|
1188
|
+
return createFailed("sdkKey", result);
|
|
1189
|
+
}
|
|
1190
|
+
let storedIn;
|
|
1191
|
+
try {
|
|
1192
|
+
storedIn = input.storeSdkKey(result.value.key, wallet, agent);
|
|
1193
|
+
} catch {
|
|
1194
|
+
ui.stop("SDK key could not be saved");
|
|
1195
|
+
steps.sdkKey = {
|
|
1196
|
+
status: "action_required",
|
|
1197
|
+
id: result.value.id,
|
|
1198
|
+
attemptedAt: steps.sdkKey.attemptedAt
|
|
1199
|
+
};
|
|
1200
|
+
return stopped(rotationAction([{ id: result.value.id }]));
|
|
1201
|
+
}
|
|
1202
|
+
complete("sdkKey", { id: result.value.id, secretStoredIn: storedIn });
|
|
1203
|
+
ui.stop("SDK key generated");
|
|
1204
|
+
if (result.value.scopes && !result.value.scopes.includes("payments:execute")) {
|
|
1205
|
+
ui.warning(
|
|
1206
|
+
'SDK key is missing payments:execute, so "conto pay" will not be able to execute'
|
|
1207
|
+
);
|
|
1208
|
+
} else {
|
|
1209
|
+
ui.success("SDK key created (standard preset, includes payments:execute)");
|
|
1210
|
+
}
|
|
1211
|
+
resources.sdkKey = { key: result.value.key, scopes: result.value.scopes };
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
if (!resources.sdkKey) {
|
|
1215
|
+
return stopped(rotationAction(steps.sdkKey.id ? [{ id: steps.sdkKey.id }] : []));
|
|
1216
|
+
}
|
|
1217
|
+
return { kind: "complete", resources: { wallet, agent, sdkKey: resources.sdkKey } };
|
|
1218
|
+
}
|
|
1219
|
+
function reconcileAction(step) {
|
|
1220
|
+
switch (step) {
|
|
1221
|
+
case "wallet":
|
|
1222
|
+
return "Resume setup. It sends the same wallet request again, and the server returns the existing wallet if the first request created it.";
|
|
1223
|
+
case "walletLink":
|
|
1224
|
+
return "Resume setup. It checks the agent for the wallet link before linking again.";
|
|
1225
|
+
case "agent":
|
|
1226
|
+
return "Resume setup. It looks the agent up by its setup marker before creating one.";
|
|
1227
|
+
case "policy":
|
|
1228
|
+
return "Resume setup. It checks the agent's assigned policies before creating one.";
|
|
1229
|
+
case "sdkKey":
|
|
1230
|
+
return "Resume setup. It checks the agent for an issued key before creating one. A key whose secret was lost must be revoked by an owner.";
|
|
1231
|
+
default:
|
|
1232
|
+
return "Resume setup.";
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// src/lib/setup-resources-client.ts
|
|
1237
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
1238
|
+
function isRecord(value) {
|
|
1239
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
1240
|
+
}
|
|
1241
|
+
function failureFromResponse(response, fallback) {
|
|
1242
|
+
return {
|
|
1243
|
+
code: responseErrorCode(response, response.status >= 500 ? "SERVER_ERROR" : "API_ERROR"),
|
|
1244
|
+
message: responseErrorMessage(response, `${fallback} (HTTP ${response.status})`),
|
|
1245
|
+
httpStatus: response.status
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
function failureFromTransport(error) {
|
|
1249
|
+
if (error instanceof HttpTransportError) return { code: error.code, message: error.message };
|
|
1250
|
+
return {
|
|
1251
|
+
code: "NETWORK_ERROR",
|
|
1252
|
+
message: redactSecrets(error instanceof Error ? error.message : String(error))
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
function classifyCreate(response, label, parse) {
|
|
1256
|
+
if (response.status >= 200 && response.status < 300) {
|
|
1257
|
+
const body = response.data;
|
|
1258
|
+
if (response.status === 202 && body?.requiresGovernanceApproval === true) {
|
|
1259
|
+
const approvalRequest = body.approvalRequest;
|
|
1260
|
+
return {
|
|
1261
|
+
ok: false,
|
|
1262
|
+
outcome: "approval_required",
|
|
1263
|
+
approvalRequestId: typeof approvalRequest?.id === "string" ? approvalRequest.id : void 0,
|
|
1264
|
+
failure: {
|
|
1265
|
+
code: "GOVERNANCE_APPROVAL_REQUIRED",
|
|
1266
|
+
message: redactSecrets(
|
|
1267
|
+
typeof body.message === "string" ? body.message : "This change needs governance approval before it applies."
|
|
1268
|
+
),
|
|
1269
|
+
httpStatus: 202
|
|
1270
|
+
}
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
const value = response.isJson ? parse(response.data) : void 0;
|
|
1274
|
+
if (value === void 0) {
|
|
1275
|
+
return {
|
|
1276
|
+
ok: false,
|
|
1277
|
+
outcome: "unknown",
|
|
1278
|
+
inFlightPossible: false,
|
|
1279
|
+
failure: {
|
|
1280
|
+
code: "UNREADABLE_RESPONSE",
|
|
1281
|
+
message: `The server accepted the ${label} request but its response could not be read.`,
|
|
1282
|
+
httpStatus: response.status
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
return { ok: true, httpStatus: response.status, value };
|
|
1287
|
+
}
|
|
1288
|
+
if (response.status >= 500) {
|
|
1289
|
+
const code = responseErrorCode(response, "");
|
|
1290
|
+
if (response.isJson && (code === "SERVICE_UNAVAILABLE" || code === "RATE_LIMITED")) {
|
|
1291
|
+
return {
|
|
1292
|
+
ok: false,
|
|
1293
|
+
outcome: "not_created",
|
|
1294
|
+
failure: failureFromResponse(response, `The ${label} request was refused`)
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
return {
|
|
1298
|
+
ok: false,
|
|
1299
|
+
outcome: "unknown",
|
|
1300
|
+
// A JSON error came from the route after it finished. A gateway error
|
|
1301
|
+
// (non-JSON) can mean the route is still running.
|
|
1302
|
+
inFlightPossible: !response.isJson,
|
|
1303
|
+
failure: failureFromResponse(response, `The ${label} request failed on the server`)
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
return {
|
|
1307
|
+
ok: false,
|
|
1308
|
+
outcome: "not_created",
|
|
1309
|
+
failure: failureFromResponse(response, `The ${label} request was refused`),
|
|
1310
|
+
...response.status === 429 ? { retryAfterSeconds: retryAfterSeconds(response.headers, response.data) } : {}
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
function classifyTransport(error) {
|
|
1314
|
+
const failure = failureFromTransport(error);
|
|
1315
|
+
if (error instanceof HttpTransportError && error.failure === "not_sent") {
|
|
1316
|
+
return { ok: false, outcome: "not_created", failure };
|
|
1317
|
+
}
|
|
1318
|
+
return { ok: false, outcome: "unknown", inFlightPossible: true, failure };
|
|
1319
|
+
}
|
|
1320
|
+
function parseWallet(data) {
|
|
1321
|
+
if (!isRecord(data) || typeof data.id !== "string" || typeof data.address !== "string") {
|
|
1322
|
+
return void 0;
|
|
1323
|
+
}
|
|
1324
|
+
return data;
|
|
1325
|
+
}
|
|
1326
|
+
function parseAgent(data) {
|
|
1327
|
+
if (!isRecord(data) || typeof data.id !== "string" || typeof data.name !== "string") {
|
|
1328
|
+
return void 0;
|
|
1329
|
+
}
|
|
1330
|
+
return data;
|
|
1331
|
+
}
|
|
1332
|
+
var SetupResourcesClient = class {
|
|
1333
|
+
constructor(baseUrl, orgApiKey) {
|
|
1334
|
+
this.baseUrl = baseUrl;
|
|
1335
|
+
this.orgApiKey = orgApiKey;
|
|
1336
|
+
}
|
|
1337
|
+
baseUrl;
|
|
1338
|
+
orgApiKey;
|
|
1339
|
+
async send(method, path3, body, headers, bearer = this.orgApiKey) {
|
|
1340
|
+
return requestJson({
|
|
1341
|
+
url: apiUrl(this.baseUrl, path3),
|
|
1342
|
+
method,
|
|
1343
|
+
bearer,
|
|
1344
|
+
body,
|
|
1345
|
+
headers,
|
|
1346
|
+
timeoutMs: REQUEST_TIMEOUT_MS
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
async create(path3, body, label, parse, headers) {
|
|
1350
|
+
let response;
|
|
1351
|
+
try {
|
|
1352
|
+
response = await this.send("POST", path3, body, headers);
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
return classifyTransport(error);
|
|
1355
|
+
}
|
|
1356
|
+
return classifyCreate(response, label, parse);
|
|
1357
|
+
}
|
|
1358
|
+
async read(path3, label, parse, bearer) {
|
|
1359
|
+
let response;
|
|
1360
|
+
try {
|
|
1361
|
+
response = await this.send("GET", path3, void 0, void 0, bearer);
|
|
1362
|
+
} catch (error) {
|
|
1363
|
+
return { ok: false, notFound: false, failure: failureFromTransport(error) };
|
|
1364
|
+
}
|
|
1365
|
+
if (response.status === 200) {
|
|
1366
|
+
const value = response.isJson ? parse(response.data) : void 0;
|
|
1367
|
+
if (value !== void 0) return { ok: true, value };
|
|
1368
|
+
return {
|
|
1369
|
+
ok: false,
|
|
1370
|
+
notFound: false,
|
|
1371
|
+
failure: {
|
|
1372
|
+
code: "UNREADABLE_RESPONSE",
|
|
1373
|
+
message: `The ${label} response could not be read.`,
|
|
1374
|
+
httpStatus: 200
|
|
1375
|
+
}
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
return {
|
|
1379
|
+
ok: false,
|
|
1380
|
+
notFound: response.status === 404,
|
|
1381
|
+
failure: failureFromResponse(response, `Could not read the ${label}`)
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
// ── Creates ──
|
|
1385
|
+
createWallet(params) {
|
|
1386
|
+
return this.create(
|
|
1387
|
+
"/api/wallets",
|
|
1388
|
+
{
|
|
1389
|
+
name: params.name,
|
|
1390
|
+
chainType: params.chainType,
|
|
1391
|
+
chainId: params.chainId,
|
|
1392
|
+
custodyMode: "MANAGED"
|
|
1393
|
+
},
|
|
1394
|
+
"wallet",
|
|
1395
|
+
parseWallet
|
|
1396
|
+
);
|
|
1397
|
+
}
|
|
1398
|
+
createAgent(params) {
|
|
1399
|
+
return this.create("/api/agents", params, "agent", parseAgent);
|
|
1400
|
+
}
|
|
1401
|
+
linkWallet(agentId, params) {
|
|
1402
|
+
return this.create(
|
|
1403
|
+
`/api/agents/${encodeURIComponent(agentId)}/wallets`,
|
|
1404
|
+
params,
|
|
1405
|
+
"wallet link",
|
|
1406
|
+
(data) => isRecord(data) ? { id: typeof data.id === "string" ? data.id : void 0 } : void 0
|
|
1407
|
+
);
|
|
1408
|
+
}
|
|
1409
|
+
createPolicy(params, approvalRequestId) {
|
|
1410
|
+
return this.create(
|
|
1411
|
+
"/api/policies",
|
|
1412
|
+
params,
|
|
1413
|
+
"policy",
|
|
1414
|
+
(data) => isRecord(data) && typeof data.id === "string" ? { id: data.id } : void 0,
|
|
1415
|
+
approvalRequestId ? { "x-governance-approval-id": approvalRequestId } : void 0
|
|
1416
|
+
);
|
|
1417
|
+
}
|
|
1418
|
+
createSdkKey(agentId, params) {
|
|
1419
|
+
return this.create(
|
|
1420
|
+
`/api/agents/${encodeURIComponent(agentId)}/sdk-keys`,
|
|
1421
|
+
params,
|
|
1422
|
+
"SDK key",
|
|
1423
|
+
(data) => isRecord(data) && typeof data.id === "string" && typeof data.key === "string" && data.key.startsWith("conto_agent_") ? {
|
|
1424
|
+
id: data.id,
|
|
1425
|
+
key: data.key,
|
|
1426
|
+
scopes: Array.isArray(data.scopes) ? data.scopes.filter((scope) => typeof scope === "string") : void 0
|
|
1427
|
+
} : void 0
|
|
1428
|
+
);
|
|
1429
|
+
}
|
|
1430
|
+
/** Best effort testnet funding. Never retried. */
|
|
1431
|
+
async requestFaucet(walletId) {
|
|
1432
|
+
let response;
|
|
1433
|
+
try {
|
|
1434
|
+
response = await this.send("POST", `/api/wallets/${encodeURIComponent(walletId)}/faucet`);
|
|
1435
|
+
} catch (error) {
|
|
1436
|
+
return { ok: false, message: failureFromTransport(error).message };
|
|
1437
|
+
}
|
|
1438
|
+
if (response.status >= 200 && response.status < 300) {
|
|
1439
|
+
const body = response.data || {};
|
|
1440
|
+
return {
|
|
1441
|
+
ok: true,
|
|
1442
|
+
message: typeof body.message === "string" ? redactSecrets(body.message) : void 0,
|
|
1443
|
+
updatedBalance: typeof body.updatedBalance === "number" ? body.updatedBalance : void 0
|
|
1444
|
+
};
|
|
1445
|
+
}
|
|
1446
|
+
return { ok: false, message: failureFromResponse(response, "Faucet unavailable").message };
|
|
1447
|
+
}
|
|
1448
|
+
// ── Reads used to verify and reconcile ──
|
|
1449
|
+
getWallet(walletId) {
|
|
1450
|
+
return this.read(`/api/wallets/${encodeURIComponent(walletId)}`, "wallet", parseWallet);
|
|
1451
|
+
}
|
|
1452
|
+
getAgent(agentId) {
|
|
1453
|
+
return this.read(`/api/agents/${encodeURIComponent(agentId)}`, "agent", parseAgent);
|
|
1454
|
+
}
|
|
1455
|
+
findAgentsByExternalId(externalId) {
|
|
1456
|
+
const query = new URLSearchParams({ search: externalId, limit: "100" });
|
|
1457
|
+
return this.read(`/api/agents?${query.toString()}`, "agent list", (data) => {
|
|
1458
|
+
if (!isRecord(data) || !Array.isArray(data.agents)) return void 0;
|
|
1459
|
+
return data.agents.map(parseAgent).filter(
|
|
1460
|
+
(agent) => Boolean(agent) && agent?.externalId === externalId
|
|
1461
|
+
);
|
|
1462
|
+
});
|
|
1463
|
+
}
|
|
1464
|
+
listWalletLinks(agentId) {
|
|
1465
|
+
return this.read(
|
|
1466
|
+
`/api/agents/${encodeURIComponent(agentId)}/wallets`,
|
|
1467
|
+
"wallet links",
|
|
1468
|
+
(data) => {
|
|
1469
|
+
if (!isRecord(data) || !Array.isArray(data.wallets)) return void 0;
|
|
1470
|
+
return data.wallets.filter(isRecord).flatMap(
|
|
1471
|
+
(link) => typeof link.walletId === "string" ? [
|
|
1472
|
+
{
|
|
1473
|
+
id: typeof link.id === "string" ? link.id : void 0,
|
|
1474
|
+
walletId: link.walletId,
|
|
1475
|
+
isActive: typeof link.isActive === "boolean" ? link.isActive : void 0,
|
|
1476
|
+
spendLimitDaily: typeof link.spendLimitDaily === "number" ? link.spendLimitDaily : null,
|
|
1477
|
+
spendLimitPerTx: typeof link.spendLimitPerTx === "number" ? link.spendLimitPerTx : null
|
|
1478
|
+
}
|
|
1479
|
+
] : []
|
|
1480
|
+
);
|
|
1481
|
+
}
|
|
1482
|
+
);
|
|
1483
|
+
}
|
|
1484
|
+
listAssignedPolicies(agentId) {
|
|
1485
|
+
return this.read(
|
|
1486
|
+
`/api/agents/${encodeURIComponent(agentId)}/policies`,
|
|
1487
|
+
"assigned policies",
|
|
1488
|
+
(data) => {
|
|
1489
|
+
if (!isRecord(data) || !Array.isArray(data.policies)) return void 0;
|
|
1490
|
+
return data.policies.filter(isRecord).flatMap((assignment) => {
|
|
1491
|
+
const policy = isRecord(assignment.policy) ? assignment.policy : void 0;
|
|
1492
|
+
const policyId = typeof assignment.policyId === "string" ? assignment.policyId : policy?.id;
|
|
1493
|
+
return typeof policyId === "string" && typeof policy?.name === "string" ? [{ policyId, name: policy.name }] : [];
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
);
|
|
1497
|
+
}
|
|
1498
|
+
listSdkKeys(agentId) {
|
|
1499
|
+
return this.read(
|
|
1500
|
+
`/api/agents/${encodeURIComponent(agentId)}/sdk-keys`,
|
|
1501
|
+
"SDK key list",
|
|
1502
|
+
(data) => {
|
|
1503
|
+
if (!Array.isArray(data)) return void 0;
|
|
1504
|
+
return data.filter(isRecord).flatMap(
|
|
1505
|
+
(key) => typeof key.id === "string" && typeof key.name === "string" ? [
|
|
1506
|
+
{
|
|
1507
|
+
id: key.id,
|
|
1508
|
+
name: key.name,
|
|
1509
|
+
keyPrefix: typeof key.keyPrefix === "string" ? key.keyPrefix : void 0,
|
|
1510
|
+
isActive: typeof key.isActive === "boolean" ? key.isActive : void 0,
|
|
1511
|
+
revokedAt: typeof key.revokedAt === "string" ? key.revokedAt : null
|
|
1512
|
+
}
|
|
1513
|
+
] : []
|
|
1514
|
+
);
|
|
1515
|
+
}
|
|
1516
|
+
);
|
|
1517
|
+
}
|
|
1518
|
+
/** Check a stored SDK key by reading its own setup. Returns the agent it belongs to. */
|
|
1519
|
+
checkSdkKey(sdkKey) {
|
|
1520
|
+
return this.read(
|
|
1521
|
+
"/api/sdk/setup",
|
|
1522
|
+
"agent setup",
|
|
1523
|
+
(data) => isRecord(data) && isRecord(data.agent) && typeof data.agent.id === "string" ? { agentId: data.agent.id } : void 0,
|
|
1524
|
+
sdkKey
|
|
1525
|
+
);
|
|
1526
|
+
}
|
|
1527
|
+
};
|
|
1528
|
+
|
|
1529
|
+
// src/commands/init.ts
|
|
1530
|
+
var INIT_EXIT_CODES = {
|
|
1531
|
+
complete: 0,
|
|
1532
|
+
failed: 1,
|
|
1533
|
+
refused: 2,
|
|
1534
|
+
partial: 3,
|
|
1535
|
+
actionRequired: 4
|
|
1536
|
+
};
|
|
1537
|
+
var DEFAULT_BASE_URL = "https://conto.finance";
|
|
1538
|
+
var HEADLESS_DEFAULT_NAME = "conto-agent";
|
|
1539
|
+
var HEADLESS_DEFAULT_TYPE = "CUSTOM";
|
|
1540
|
+
var HEADLESS_DEFAULT_LIMIT = 500;
|
|
1541
|
+
var SDK_KEY_NAME = "CLI Quickstart Key";
|
|
1542
|
+
function failInit(message, details = {}, exitCode = INIT_EXIT_CODES.failed) {
|
|
1543
|
+
if (isJsonMode()) {
|
|
1544
|
+
printJson({ ok: false, error: message, ...details });
|
|
1545
|
+
} else {
|
|
1546
|
+
printError(message);
|
|
1547
|
+
}
|
|
1548
|
+
process.exit(exitCode);
|
|
1549
|
+
}
|
|
1550
|
+
function initSpinner() {
|
|
1551
|
+
if (!isJsonMode()) return p.spinner();
|
|
1552
|
+
return {
|
|
1553
|
+
start() {
|
|
1554
|
+
},
|
|
1555
|
+
stop() {
|
|
1556
|
+
},
|
|
1557
|
+
message() {
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1560
|
+
}
|
|
1561
|
+
async function runInit(options = {}) {
|
|
1562
|
+
if (options.sandbox) {
|
|
1563
|
+
if (options.resume || options.restart) {
|
|
1564
|
+
failInit(
|
|
1565
|
+
"--resume and --restart apply to organization setup. A sandbox is created in one step.",
|
|
1566
|
+
{ status: "refused", code: "INVALID_OPTIONS" },
|
|
1567
|
+
INIT_EXIT_CODES.refused
|
|
1568
|
+
);
|
|
1569
|
+
}
|
|
1570
|
+
await runSandboxInit(options);
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
await runOrganizationInit(options);
|
|
1574
|
+
}
|
|
1575
|
+
function resumeCommand(baseUrl, options) {
|
|
1576
|
+
return [
|
|
1577
|
+
"npx @conto_finance/create-conto-agent --resume",
|
|
1578
|
+
...baseUrl !== DEFAULT_BASE_URL ? [`--base-url ${baseUrl}`] : [],
|
|
1579
|
+
...options.install === false ? ["--no-install"] : [],
|
|
1580
|
+
...isJsonMode() ? ["--json"] : []
|
|
1581
|
+
].join(" ");
|
|
1582
|
+
}
|
|
1583
|
+
var RESUME_CREDENTIAL_HINT = "Resume with the same organization: pass --api-key or set CONTO_ORG_API_KEY, or run it in a terminal to sign in with the browser.";
|
|
1584
|
+
function refuse(message, details) {
|
|
1585
|
+
failInit(message, { status: "refused", ...details }, INIT_EXIT_CODES.refused);
|
|
1586
|
+
}
|
|
1587
|
+
function writeOrganizationEnvLocal(cwd, input) {
|
|
1588
|
+
ensureEnvLocalGitignored(cwd);
|
|
1589
|
+
writeEnvLocal(cwd, [
|
|
1590
|
+
"# Conto Agent Configuration",
|
|
1591
|
+
"# Generated by: npx @conto_finance/create-conto-agent",
|
|
1592
|
+
"",
|
|
1593
|
+
"# SDK Authentication",
|
|
1594
|
+
["CONTO_API_KEY", input.sdkKey],
|
|
1595
|
+
["CONTO_BASE_URL", input.baseUrl],
|
|
1596
|
+
"",
|
|
1597
|
+
"# Agent Identity",
|
|
1598
|
+
["CONTO_AGENT_ID", input.agent.id],
|
|
1599
|
+
["CONTO_AGENT_NAME", input.agent.name],
|
|
1600
|
+
"",
|
|
1601
|
+
`# Network: ${input.chain.name}${input.chain.testnet ? " (testnet)" : ""}`,
|
|
1602
|
+
["CONTO_CHAIN_ID", input.chain.chainId],
|
|
1603
|
+
["CONTO_CHAIN_NAME", input.chain.name],
|
|
1604
|
+
["CONTO_RPC_URL", input.chain.rpcUrl],
|
|
1605
|
+
["CONTO_EXPLORER_URL", input.chain.explorerUrl],
|
|
1606
|
+
["CONTO_CURRENCY", input.chain.currency],
|
|
1607
|
+
"",
|
|
1608
|
+
"# Wallet",
|
|
1609
|
+
["CONTO_WALLET_ID", input.wallet.id],
|
|
1610
|
+
["CONTO_WALLET_ADDRESS", input.wallet.address]
|
|
1611
|
+
]);
|
|
1612
|
+
return ".env.local";
|
|
1613
|
+
}
|
|
1614
|
+
function storedSdkKeyFor(cwd, baseUrl, agentId) {
|
|
1615
|
+
const env = loadProjectEnv(cwd);
|
|
1616
|
+
if (env.CONTO_AGENT_ID !== agentId || !env.CONTO_API_KEY?.startsWith("conto_agent_")) {
|
|
1617
|
+
return void 0;
|
|
1618
|
+
}
|
|
1619
|
+
try {
|
|
1620
|
+
return normalizeBaseUrl(env.CONTO_BASE_URL || DEFAULT_BASE_URL) === baseUrl ? env.CONTO_API_KEY : void 0;
|
|
1621
|
+
} catch {
|
|
1622
|
+
return void 0;
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
function organizationBindingProblem(checkpoint, credential) {
|
|
1626
|
+
const organization = checkpoint.binding.organization;
|
|
1627
|
+
if (organization.anchor) return null;
|
|
1628
|
+
if (!hasServerSideEffects(checkpoint)) return null;
|
|
1629
|
+
if (organization.credentialFingerprint === credential.fingerprint) return null;
|
|
1630
|
+
if (credential.organizationName && organization.name && credential.organizationName === organization.name) {
|
|
1631
|
+
return null;
|
|
1632
|
+
}
|
|
1633
|
+
return "Nothing created by this setup can prove which organization it belongs to yet, and this credential differs from the one used before. Resume with the original organization API key, or check the dashboard and run with --restart.";
|
|
1634
|
+
}
|
|
1635
|
+
async function runOrganizationInit(options) {
|
|
1636
|
+
const cwd = process.cwd();
|
|
1637
|
+
const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
1638
|
+
const providedOrgApiKey = options.apiKey || process.env.CONTO_ORG_API_KEY;
|
|
1639
|
+
if (options.resume && options.restart) {
|
|
1640
|
+
refuse("Use --resume or --restart, not both.", { code: "INVALID_OPTIONS" });
|
|
1641
|
+
}
|
|
1642
|
+
const existing = loadCheckpoint(cwd);
|
|
1643
|
+
let resumeFrom;
|
|
1644
|
+
let discarded;
|
|
1645
|
+
if (options.resume) {
|
|
1646
|
+
if (existing.kind === "none") {
|
|
1647
|
+
refuse("There is no unfinished setup to resume in this directory.", {
|
|
1648
|
+
code: "NOTHING_TO_RESUME"
|
|
1649
|
+
});
|
|
1650
|
+
}
|
|
1651
|
+
if (existing.kind === "corrupt") {
|
|
1652
|
+
refuse(
|
|
1653
|
+
`${INIT_CHECKPOINT_FILE} cannot be used (${existing.reason}). Check the resources it lists in the dashboard, then run again with --restart.`,
|
|
1654
|
+
{
|
|
1655
|
+
code: "CHECKPOINT_UNREADABLE",
|
|
1656
|
+
checkpoint: INIT_CHECKPOINT_FILE,
|
|
1657
|
+
resources: recordedResources(existing.partial)
|
|
1658
|
+
}
|
|
1659
|
+
);
|
|
1660
|
+
}
|
|
1661
|
+
resumeFrom = existing.checkpoint;
|
|
1662
|
+
} else if (existing.kind !== "none") {
|
|
1663
|
+
const partial = existing.kind === "found" ? existing.checkpoint : existing.partial;
|
|
1664
|
+
if (!options.restart) {
|
|
1665
|
+
const baseUrlHint = existing.kind === "found" ? existing.checkpoint.binding.baseUrl : DEFAULT_BASE_URL;
|
|
1666
|
+
refuse(
|
|
1667
|
+
`An unfinished setup is recorded in ${INIT_CHECKPOINT_FILE}. Resume it with --resume, or discard the record with --restart. Discarding keeps any resources it already created.`,
|
|
1668
|
+
{
|
|
1669
|
+
code: "UNFINISHED_SETUP",
|
|
1670
|
+
checkpoint: INIT_CHECKPOINT_FILE,
|
|
1671
|
+
failedStep: existing.kind === "found" ? existing.checkpoint.failedStep ?? null : null,
|
|
1672
|
+
resources: recordedResources(partial),
|
|
1673
|
+
resume: { command: resumeCommand(baseUrlHint, options) }
|
|
1674
|
+
}
|
|
1675
|
+
);
|
|
1676
|
+
}
|
|
1677
|
+
discarded = { operationId: partial?.operationId, resources: recordedResources(partial) };
|
|
1678
|
+
}
|
|
1679
|
+
if (!interactive && !providedOrgApiKey) {
|
|
1680
|
+
failInit(
|
|
1681
|
+
[
|
|
1682
|
+
resumeFrom ? "Resuming setup without an interactive terminal needs an organization API key." : "create-conto-agent needs an interactive terminal for the setup wizard.",
|
|
1683
|
+
"Headless options: --sandbox, or --api-key <org-api-key>.",
|
|
1684
|
+
"Add --json for machine-readable output."
|
|
1685
|
+
].join(" "),
|
|
1686
|
+
{ headlessOptions: ["--sandbox", "--api-key <org-api-key>"] }
|
|
1687
|
+
);
|
|
1688
|
+
}
|
|
1689
|
+
printBanner();
|
|
1690
|
+
const requestedBaseUrl = options.baseUrl || process.env.CONTO_BASE_URL || DEFAULT_BASE_URL;
|
|
1691
|
+
let baseUrl;
|
|
1692
|
+
try {
|
|
1693
|
+
parseSecureBaseUrl(requestedBaseUrl);
|
|
1694
|
+
baseUrl = normalizeBaseUrl(requestedBaseUrl);
|
|
1695
|
+
} catch (err) {
|
|
1696
|
+
failInit(err instanceof Error ? err.message : "Invalid base URL");
|
|
1697
|
+
}
|
|
1698
|
+
if (resumeFrom && resumeFrom.binding.baseUrl !== baseUrl) {
|
|
1699
|
+
refuse(
|
|
1700
|
+
`This setup was started against ${resumeFrom.binding.baseUrl}, not ${baseUrl}. Resume it with --base-url ${resumeFrom.binding.baseUrl}.`,
|
|
1701
|
+
{ code: "BASE_URL_MISMATCH", expectedBaseUrl: resumeFrom.binding.baseUrl }
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
const resumed = resumeFrom?.request;
|
|
1705
|
+
if (resumed) {
|
|
1706
|
+
const mismatched = [
|
|
1707
|
+
options.name !== void 0 && options.name !== resumed.agentName ? "--name" : null,
|
|
1708
|
+
options.type !== void 0 && options.type !== resumed.agentType ? "--type" : null,
|
|
1709
|
+
options.limit !== void 0 && options.limit !== resumed.dailyLimit ? "--limit" : null,
|
|
1710
|
+
options.chain !== void 0 && options.chain !== resumed.chainId ? "--chain" : null
|
|
1711
|
+
].filter((flag) => flag !== null);
|
|
1712
|
+
if (mismatched.length > 0) {
|
|
1713
|
+
refuse(
|
|
1714
|
+
`${mismatched.join(", ")} ${mismatched.length === 1 ? "differs" : "differ"} from the unfinished setup. Resume without them, or run with --restart to start a different setup.`,
|
|
1715
|
+
{
|
|
1716
|
+
code: "CONFIGURATION_MISMATCH",
|
|
1717
|
+
mismatched,
|
|
1718
|
+
requested: {
|
|
1719
|
+
name: resumed.agentName,
|
|
1720
|
+
type: resumed.agentType,
|
|
1721
|
+
limit: resumed.dailyLimit,
|
|
1722
|
+
chain: resumed.chainId
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
);
|
|
1726
|
+
}
|
|
1727
|
+
printInfo(
|
|
1728
|
+
`Resuming the setup started ${resumeFrom?.createdAt} for agent "${resumed.agentName}".`
|
|
1729
|
+
);
|
|
1730
|
+
}
|
|
1731
|
+
const agentName = options.name || resumed?.agentName || (interactive ? await p.text({
|
|
1732
|
+
message: "Agent name",
|
|
1733
|
+
placeholder: "my-procurement-bot",
|
|
1734
|
+
validate: (v) => v.length < 2 ? "Name must be at least 2 characters" : void 0
|
|
1735
|
+
}) : HEADLESS_DEFAULT_NAME);
|
|
1736
|
+
if (p.isCancel(agentName)) {
|
|
1737
|
+
p.cancel("Setup cancelled.");
|
|
1738
|
+
process.exit(0);
|
|
1739
|
+
}
|
|
1740
|
+
const agentType = options.type || resumed?.agentType || (interactive ? await p.select({
|
|
1741
|
+
message: "Agent type",
|
|
1742
|
+
options: [
|
|
1743
|
+
{ value: "ANTHROPIC_CLAUDE", label: "Claude" },
|
|
1744
|
+
{ value: "OPENAI_ASSISTANT", label: "OpenAI" },
|
|
1745
|
+
{ value: "AUTOGPT", label: "AutoGPT" },
|
|
1746
|
+
{ value: "CUSTOM", label: "Custom" }
|
|
1747
|
+
]
|
|
1748
|
+
}) : HEADLESS_DEFAULT_TYPE);
|
|
1749
|
+
if (p.isCancel(agentType)) {
|
|
1750
|
+
p.cancel("Setup cancelled.");
|
|
1751
|
+
process.exit(0);
|
|
1752
|
+
}
|
|
1753
|
+
const dailyLimit = options.limit || resumed?.dailyLimit || (interactive ? await p.text({
|
|
1754
|
+
message: "Daily spending limit (USD)",
|
|
1755
|
+
placeholder: "500",
|
|
1756
|
+
initialValue: "500",
|
|
1757
|
+
validate: (v) => {
|
|
1758
|
+
const n = Number(v);
|
|
1759
|
+
if (isNaN(n) || n <= 0) return "Enter a positive number";
|
|
1760
|
+
return void 0;
|
|
1761
|
+
}
|
|
1762
|
+
}) : HEADLESS_DEFAULT_LIMIT);
|
|
1763
|
+
if (p.isCancel(dailyLimit)) {
|
|
1764
|
+
p.cancel("Setup cancelled.");
|
|
1765
|
+
process.exit(0);
|
|
1766
|
+
}
|
|
1767
|
+
const s0 = initSpinner();
|
|
1768
|
+
s0.start("Fetching supported networks...");
|
|
1769
|
+
const { chains: availableChains, defaultChainId } = await fetchChains(baseUrl);
|
|
1770
|
+
s0.stop(`Found ${Object.keys(availableChains).length} networks`);
|
|
1771
|
+
const chainChoices = getChainChoices(availableChains);
|
|
1772
|
+
const selectedChain = options.chain || resumed?.chainId || process.env.CONTO_CHAIN_ID || (interactive ? await p.select({
|
|
1773
|
+
message: "Network",
|
|
1774
|
+
options: chainChoices,
|
|
1775
|
+
initialValue: defaultChainId
|
|
1776
|
+
}) : defaultChainId);
|
|
1777
|
+
if (p.isCancel(selectedChain)) {
|
|
1778
|
+
p.cancel("Setup cancelled.");
|
|
1779
|
+
process.exit(0);
|
|
1780
|
+
}
|
|
1781
|
+
const selectedChainId = String(selectedChain);
|
|
1782
|
+
const chain = availableChains[selectedChainId];
|
|
1783
|
+
if (!chain) {
|
|
1784
|
+
failInit(`Unknown chain "${selectedChainId}". Choose a chain ID returned by /api/chains.`, {
|
|
1785
|
+
availableChainIds: Object.keys(availableChains)
|
|
1786
|
+
});
|
|
1787
|
+
}
|
|
1788
|
+
if (!chain.testnet && !options.confirmMainnet && !resumed?.mainnetConfirmed) {
|
|
1789
|
+
if (!interactive) {
|
|
1790
|
+
failInit(
|
|
1791
|
+
`Chain ${chain.chainId} (${chain.name}) is a mainnet and can move real funds. Re-run with --confirm-mainnet after reviewing the network and limits.`,
|
|
1792
|
+
{ chainId: chain.chainId, requiresConfirmation: "--confirm-mainnet" }
|
|
1793
|
+
);
|
|
1794
|
+
}
|
|
1795
|
+
const confirmed = await p.confirm({
|
|
1796
|
+
message: `${chain.name} is a real-money network. Continue with mainnet provisioning?`,
|
|
1797
|
+
initialValue: false
|
|
1798
|
+
});
|
|
1799
|
+
if (p.isCancel(confirmed) || !confirmed) {
|
|
1800
|
+
p.cancel("Setup cancelled before any mainnet resources were created.");
|
|
1801
|
+
process.exit(0);
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
const limit = typeof dailyLimit === "string" ? Number(dailyLimit) : dailyLimit;
|
|
1805
|
+
const s = initSpinner();
|
|
1806
|
+
let orgApiKey;
|
|
1807
|
+
let orgApiKeyExpiresAt;
|
|
1808
|
+
let organizationName;
|
|
1809
|
+
if (providedOrgApiKey) {
|
|
1810
|
+
orgApiKey = providedOrgApiKey;
|
|
1811
|
+
printSuccess("Using provided organization API key");
|
|
1812
|
+
} else {
|
|
1813
|
+
s.start("Opening browser to authenticate...");
|
|
1814
|
+
try {
|
|
1815
|
+
const authResult = await browserAuth(baseUrl);
|
|
1816
|
+
orgApiKey = authResult.orgApiKey;
|
|
1817
|
+
orgApiKeyExpiresAt = authResult.expiresAt || void 0;
|
|
1818
|
+
organizationName = authResult.organizationName || void 0;
|
|
1819
|
+
s.stop("Authenticated");
|
|
1820
|
+
printSuccess("Account connected");
|
|
1821
|
+
} catch (err) {
|
|
1822
|
+
s.stop("Authentication failed");
|
|
1823
|
+
failInit(err instanceof Error ? err.message : "Authentication failed");
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
const credentialFingerprint = fingerprintSecret(orgApiKey);
|
|
1827
|
+
let checkpoint;
|
|
1828
|
+
if (resumeFrom) {
|
|
1829
|
+
const problem = organizationBindingProblem(resumeFrom, {
|
|
1830
|
+
fingerprint: credentialFingerprint,
|
|
1831
|
+
organizationName
|
|
1832
|
+
});
|
|
1833
|
+
if (problem) {
|
|
1834
|
+
refuse(problem, {
|
|
1835
|
+
code: "ORGANIZATION_UNVERIFIED",
|
|
1836
|
+
checkpoint: INIT_CHECKPOINT_FILE,
|
|
1837
|
+
resources: recordedResources(resumeFrom)
|
|
1838
|
+
});
|
|
1839
|
+
}
|
|
1840
|
+
checkpoint = resumeFrom;
|
|
1841
|
+
} else {
|
|
1842
|
+
const operationId = newOperationId();
|
|
1843
|
+
const request = {
|
|
1844
|
+
mode: "organization",
|
|
1845
|
+
agentName: String(agentName),
|
|
1846
|
+
agentType: String(agentType),
|
|
1847
|
+
dailyLimit: limit,
|
|
1848
|
+
perTransactionLimit: Math.min(limit, 1e3),
|
|
1849
|
+
chainId: chain.chainId,
|
|
1850
|
+
chainType: chain.chainType,
|
|
1851
|
+
testnet: chain.testnet,
|
|
1852
|
+
mainnetConfirmed: !chain.testnet,
|
|
1853
|
+
// Conto only lets PROD agents pay from mainnet wallets, so a confirmed
|
|
1854
|
+
// mainnet setup creates a PROD agent. Testnet setups stay DEV.
|
|
1855
|
+
agentEnvironment: chain.testnet ? "DEV" : "PROD",
|
|
1856
|
+
walletName: `${agentName} Wallet`,
|
|
1857
|
+
policyName: `${agentName} - Daily Limit`,
|
|
1858
|
+
sdkKeyName: SDK_KEY_NAME,
|
|
1859
|
+
sdkKeyType: "standard",
|
|
1860
|
+
agentExternalId: `conto-cli-init:${operationId}`
|
|
1861
|
+
};
|
|
1862
|
+
if (discarded) {
|
|
1863
|
+
removeCheckpoint(cwd);
|
|
1864
|
+
printWarning(
|
|
1865
|
+
`Discarded the unfinished setup record. Resources it created stay in your organization: ${Object.entries(discarded.resources).filter(([, value]) => value).map(([key, value]) => `${key} ${value}`).join(", ") || "none recorded"}.`
|
|
1866
|
+
);
|
|
1867
|
+
}
|
|
1868
|
+
checkpoint = createCheckpoint({
|
|
1869
|
+
request,
|
|
1870
|
+
operationId,
|
|
1871
|
+
baseUrl,
|
|
1872
|
+
credentialFingerprint,
|
|
1873
|
+
organizationName
|
|
1874
|
+
});
|
|
1875
|
+
try {
|
|
1876
|
+
saveCheckpoint(cwd, checkpoint, { exclusive: true });
|
|
1877
|
+
} catch (err) {
|
|
1878
|
+
if (err.code === "EEXIST") {
|
|
1879
|
+
refuse(`Another setup started in this directory (${INIT_CHECKPOINT_FILE}).`, {
|
|
1880
|
+
code: "UNFINISHED_SETUP",
|
|
1881
|
+
checkpoint: INIT_CHECKPOINT_FILE
|
|
1882
|
+
});
|
|
1883
|
+
}
|
|
1884
|
+
throw err;
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
const ui = {
|
|
1888
|
+
start: (message) => s.start(message),
|
|
1889
|
+
stop: (message) => s.stop(message),
|
|
1890
|
+
success: (message) => printSuccess(message),
|
|
1891
|
+
info: (message) => printInfo(message),
|
|
1892
|
+
warning: (message) => printWarning(message)
|
|
1893
|
+
};
|
|
1894
|
+
const provisioned = await provisionOrganization({
|
|
1895
|
+
baseUrl,
|
|
1896
|
+
checkpoint,
|
|
1897
|
+
organization: { credentialFingerprint, name: organizationName },
|
|
1898
|
+
client: new SetupResourcesClient(baseUrl, orgApiKey),
|
|
1899
|
+
chain,
|
|
1900
|
+
resuming: Boolean(resumeFrom),
|
|
1901
|
+
ui,
|
|
1902
|
+
persist: () => saveCheckpoint(cwd, checkpoint),
|
|
1903
|
+
storeSdkKey: (sdkKey2, wallet2, agent2) => writeOrganizationEnvLocal(cwd, { sdkKey: sdkKey2, baseUrl, agent: agent2, wallet: wallet2, chain }),
|
|
1904
|
+
storedSdkKey: (agentId) => storedSdkKeyFor(cwd, baseUrl, agentId)
|
|
1905
|
+
});
|
|
1906
|
+
if (provisioned.kind === "stopped") {
|
|
1907
|
+
reportStoppedSetup({
|
|
1908
|
+
cwd,
|
|
1909
|
+
stop: provisioned.stop,
|
|
1910
|
+
checkpoint,
|
|
1911
|
+
baseUrl,
|
|
1912
|
+
options,
|
|
1913
|
+
discarded
|
|
1914
|
+
});
|
|
1915
|
+
}
|
|
1916
|
+
const { wallet, agent, sdkKey } = provisioned.resources;
|
|
1917
|
+
writeOrganizationEnvLocal(cwd, { sdkKey: sdkKey.key, baseUrl, agent, wallet, chain });
|
|
1918
|
+
writeContoConfig(cwd, {
|
|
1919
|
+
agent: {
|
|
1920
|
+
id: agent.id,
|
|
1921
|
+
name: agent.name,
|
|
1922
|
+
type: agentType
|
|
1923
|
+
},
|
|
1924
|
+
network: {
|
|
1925
|
+
chain: selectedChainId,
|
|
1926
|
+
chainId: chain.chainId,
|
|
1927
|
+
rpcUrl: chain.rpcUrl,
|
|
1928
|
+
explorerUrl: chain.explorerUrl,
|
|
1929
|
+
currency: chain.currency,
|
|
1930
|
+
testnet: chain.testnet
|
|
1931
|
+
},
|
|
1932
|
+
wallet: {
|
|
1933
|
+
id: wallet.id,
|
|
1934
|
+
address: wallet.address,
|
|
1935
|
+
custodyMode: wallet.custodyMode
|
|
1936
|
+
},
|
|
1937
|
+
server: {
|
|
1938
|
+
baseUrl
|
|
1939
|
+
}
|
|
1940
|
+
});
|
|
1941
|
+
writeExampleFile(cwd);
|
|
1942
|
+
saveGlobalConfig({
|
|
1943
|
+
agent: { id: agent.id, name: agent.name, type: agentType },
|
|
1944
|
+
network: {
|
|
1945
|
+
chain: selectedChainId,
|
|
1946
|
+
chainId: chain.chainId,
|
|
1947
|
+
rpcUrl: chain.rpcUrl,
|
|
1948
|
+
explorerUrl: chain.explorerUrl,
|
|
1949
|
+
currency: chain.currency,
|
|
1950
|
+
testnet: chain.testnet
|
|
1951
|
+
},
|
|
1952
|
+
wallet: {
|
|
1953
|
+
id: wallet.id,
|
|
1954
|
+
address: wallet.address,
|
|
1955
|
+
custodyMode: wallet.custodyMode ?? "MANAGED"
|
|
1956
|
+
},
|
|
1957
|
+
server: { baseUrl, apiKey: sdkKey.key, orgApiKey, orgApiKeyExpiresAt }
|
|
1958
|
+
});
|
|
1959
|
+
removeCheckpoint(cwd);
|
|
1960
|
+
let cliResolves = false;
|
|
1961
|
+
if (hasLocalCliBin(cwd)) {
|
|
1962
|
+
cliResolves = true;
|
|
1963
|
+
} else if (options.install !== false) {
|
|
1964
|
+
s.start("Installing conto CLI into this project...");
|
|
1965
|
+
const outcome = installCliLocally(cwd, agent.name);
|
|
1966
|
+
if (outcome === "installed") {
|
|
1967
|
+
s.stop("CLI installed (devDependency)");
|
|
1968
|
+
cliResolves = true;
|
|
1969
|
+
} else if (outcome === "unsupported-pm") {
|
|
1970
|
+
s.stop("Skipped CLI install (non-npm lockfile found)");
|
|
1971
|
+
printInfo(
|
|
1972
|
+
"Install it with your package manager: add @conto_finance/create-conto-agent as a dev dependency."
|
|
1973
|
+
);
|
|
1974
|
+
} else {
|
|
1975
|
+
s.stop("CLI install failed (continuing)");
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
|
|
1979
|
+
const nextSteps = [
|
|
1980
|
+
`${cli} doctor`,
|
|
1981
|
+
"node example.mjs",
|
|
1982
|
+
`${cli} pay <address> <amount>`,
|
|
1983
|
+
`${cli} mcp`
|
|
1984
|
+
];
|
|
1985
|
+
if (isJsonMode()) {
|
|
1986
|
+
printJson({
|
|
1987
|
+
ok: true,
|
|
1988
|
+
mode: "organization",
|
|
1989
|
+
baseUrl,
|
|
1990
|
+
agent,
|
|
1991
|
+
wallet,
|
|
1992
|
+
network: {
|
|
1993
|
+
chainId: chain.chainId,
|
|
1994
|
+
name: chain.name,
|
|
1995
|
+
currency: chain.currency,
|
|
1996
|
+
testnet: chain.testnet
|
|
1997
|
+
},
|
|
1998
|
+
credentials: {
|
|
1999
|
+
storedIn: ".env.local",
|
|
2000
|
+
sdkKeyEnv: "CONTO_API_KEY"
|
|
2001
|
+
},
|
|
2002
|
+
files: [".env.local", ".gitignore", "conto.config.json", "example.mjs"],
|
|
2003
|
+
...resumeFrom ? { resumed: true } : {},
|
|
2004
|
+
...discarded ? { discardedSetup: discarded } : {},
|
|
2005
|
+
nextSteps
|
|
2006
|
+
});
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
console.log("");
|
|
2010
|
+
console.log(chalk.green.bold(" Your agent is ready!") + " Files written:\n");
|
|
2011
|
+
console.log(` ${chalk.bold(".env.local")} - SDK key + config`);
|
|
2012
|
+
console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
|
|
2013
|
+
console.log(` ${chalk.bold("example.mjs")} - Runnable payment example`);
|
|
2014
|
+
console.log("");
|
|
2015
|
+
console.log(
|
|
2016
|
+
` ${chalk.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyMode ?? "MANAGED"} custody)`
|
|
2017
|
+
);
|
|
2018
|
+
console.log(` ${chalk.dim("Currency:")} ${chain.currency}`);
|
|
2019
|
+
console.log(` ${chalk.dim("Explorer:")} ${chain.explorerUrl}`);
|
|
2020
|
+
console.log("");
|
|
2021
|
+
console.log(chalk.bold(" Next steps:"));
|
|
2022
|
+
let step = 1;
|
|
2023
|
+
console.log(` ${step++}. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
|
|
2024
|
+
if (!chain.faucetAvailable) {
|
|
2025
|
+
console.log(
|
|
2026
|
+
` ${step++}. Fund your wallet with ${chain.currency} ${chalk.dim("\u2192")} ${wallet.address}`
|
|
2027
|
+
);
|
|
2028
|
+
}
|
|
2029
|
+
console.log(` ${step++}. Run the example: ${chalk.cyan("node example.mjs")}`);
|
|
2030
|
+
console.log(` ${step++}. Make a payment: ${chalk.cyan(`${cli} pay <address> <amount>`)}`);
|
|
2031
|
+
console.log(` ${step++}. Connect Claude: ${chalk.cyan(`${cli} mcp`)}`);
|
|
2032
|
+
if (!cliResolves) {
|
|
2033
|
+
printInfo(
|
|
2034
|
+
'Tip: "npx conto <command>" works after: npm install --save-dev @conto_finance/create-conto-agent'
|
|
2035
|
+
);
|
|
2036
|
+
}
|
|
2037
|
+
console.log("");
|
|
2038
|
+
}
|
|
2039
|
+
function reportStoppedSetup(input) {
|
|
2040
|
+
const { stop, checkpoint } = input;
|
|
2041
|
+
const label = STEP_LABELS[stop.step];
|
|
2042
|
+
const failure = {
|
|
2043
|
+
code: stop.code,
|
|
2044
|
+
message: stop.message,
|
|
2045
|
+
...stop.httpStatus !== void 0 ? { httpStatus: stop.httpStatus } : {}
|
|
2046
|
+
};
|
|
2047
|
+
if (stop.status === "failed") {
|
|
2048
|
+
removeCheckpoint(input.cwd);
|
|
2049
|
+
failInit(`Setup failed at the ${label} step: ${stop.message}`, {
|
|
2050
|
+
status: "failed",
|
|
2051
|
+
code: stop.code,
|
|
2052
|
+
failedStep: stop.step,
|
|
2053
|
+
failure,
|
|
2054
|
+
...stop.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop.retryAfterSeconds } : {}
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
2057
|
+
const exitCode = stop.status === "refused" ? INIT_EXIT_CODES.refused : stop.status === "partial" ? INIT_EXIT_CODES.partial : INIT_EXIT_CODES.actionRequired;
|
|
2058
|
+
const completedSteps = STEP_ORDER.filter((step) => checkpoint.steps[step].status === "done");
|
|
2059
|
+
const pendingSteps = STEP_ORDER.filter(
|
|
2060
|
+
(step) => step !== "faucet" && !["done", "skipped"].includes(checkpoint.steps[step].status)
|
|
2061
|
+
);
|
|
2062
|
+
const credentialsWritten = checkpoint.steps.sdkKey.status === "done";
|
|
2063
|
+
const command = resumeCommand(input.baseUrl, input.options);
|
|
2064
|
+
const resumable = stop.status !== "refused";
|
|
2065
|
+
if (isJsonMode()) {
|
|
2066
|
+
printJson({
|
|
2067
|
+
ok: false,
|
|
2068
|
+
mode: "organization",
|
|
2069
|
+
status: stop.status,
|
|
2070
|
+
code: stop.code,
|
|
2071
|
+
error: stop.message,
|
|
2072
|
+
failedStep: stop.step,
|
|
2073
|
+
failure,
|
|
2074
|
+
completedSteps,
|
|
2075
|
+
pendingSteps,
|
|
2076
|
+
resources: recordedResources(checkpoint),
|
|
2077
|
+
credentialsWritten,
|
|
2078
|
+
checkpoint: INIT_CHECKPOINT_FILE,
|
|
2079
|
+
resume: resumable ? {
|
|
2080
|
+
command,
|
|
2081
|
+
credential: RESUME_CREDENTIAL_HINT,
|
|
2082
|
+
...stop.reconciliation?.notBefore ? { notBefore: stop.reconciliation.notBefore } : {}
|
|
2083
|
+
} : null,
|
|
2084
|
+
...stop.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop.retryAfterSeconds } : {},
|
|
2085
|
+
...stop.reconciliation ? { reconciliation: stop.reconciliation } : {},
|
|
2086
|
+
...stop.ownerAction ? { ownerAction: stop.ownerAction } : {},
|
|
2087
|
+
...input.discarded ? { discardedSetup: input.discarded } : {}
|
|
2088
|
+
});
|
|
2089
|
+
process.exit(exitCode);
|
|
2090
|
+
}
|
|
2091
|
+
console.log("");
|
|
2092
|
+
printError(
|
|
2093
|
+
stop.status === "refused" ? `Resume refused at the ${label} step.` : `Setup stopped at the ${label} step. It is not complete.`
|
|
2094
|
+
);
|
|
2095
|
+
printInfo(`${stop.message}${stop.httpStatus ? ` (HTTP ${stop.httpStatus})` : ""}`);
|
|
2096
|
+
const resources = recordedResources(checkpoint);
|
|
2097
|
+
if (completedSteps.length > 0) {
|
|
2098
|
+
console.log("");
|
|
2099
|
+
console.log(chalk.bold(" Created and kept:"));
|
|
2100
|
+
if (resources.walletId) {
|
|
2101
|
+
console.log(` Wallet ${resources.walletAddress ?? ""} (${resources.walletId})`);
|
|
2102
|
+
}
|
|
2103
|
+
if (resources.agentId)
|
|
2104
|
+
console.log(` Agent ${checkpoint.request.agentName} (${resources.agentId})`);
|
|
2105
|
+
if (checkpoint.steps.walletLink.status === "done") {
|
|
2106
|
+
console.log(` Wallet link $${checkpoint.request.dailyLimit}/day limit`);
|
|
2107
|
+
}
|
|
2108
|
+
if (resources.policyId)
|
|
2109
|
+
console.log(` Policy ${checkpoint.request.policyName} (${resources.policyId})`);
|
|
2110
|
+
}
|
|
2111
|
+
if (pendingSteps.length > 0) {
|
|
2112
|
+
printInfo(`Not finished: ${pendingSteps.map((step) => STEP_LABELS[step]).join(", ")}.`);
|
|
2113
|
+
}
|
|
2114
|
+
if (!credentialsWritten) {
|
|
2115
|
+
printInfo("No agent credentials were written. The agent cannot pay until setup finishes.");
|
|
2116
|
+
}
|
|
2117
|
+
if (stop.reconciliation) {
|
|
2118
|
+
printWarning(stop.reconciliation.reason);
|
|
2119
|
+
printInfo(stop.reconciliation.action);
|
|
2120
|
+
if (stop.reconciliation.resourceIds?.length) {
|
|
2121
|
+
printInfo(`Records: ${stop.reconciliation.resourceIds.join(", ")}`);
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
if (stop.ownerAction) {
|
|
2125
|
+
printWarning(stop.ownerAction.action);
|
|
2126
|
+
if (stop.ownerAction.dashboardUrl) printInfo(`Open: ${stop.ownerAction.dashboardUrl}`);
|
|
2127
|
+
if (stop.ownerAction.api) {
|
|
2128
|
+
printInfo(
|
|
2129
|
+
`API: ${stop.ownerAction.api.method} ${stop.ownerAction.api.path} (organization key with ${stop.ownerAction.api.requiredScope})`
|
|
2130
|
+
);
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
console.log("");
|
|
2134
|
+
if (resumable) {
|
|
2135
|
+
printInfo(`Resume: ${command}`);
|
|
2136
|
+
printInfo(RESUME_CREDENTIAL_HINT);
|
|
2137
|
+
} else {
|
|
2138
|
+
printInfo(`The unfinished setup is kept in ${INIT_CHECKPOINT_FILE}. Nothing was changed.`);
|
|
2139
|
+
}
|
|
2140
|
+
console.log("");
|
|
2141
|
+
process.exit(exitCode);
|
|
2142
|
+
}
|
|
2143
|
+
async function runSandboxInit(options) {
|
|
2144
|
+
printBanner();
|
|
2145
|
+
const baseUrl = options.baseUrl || "https://conto.finance";
|
|
2146
|
+
const failure = (message) => {
|
|
2147
|
+
if (isJsonMode()) {
|
|
2148
|
+
printJson({ ok: false, mode: "sandbox", error: message });
|
|
2149
|
+
} else {
|
|
2150
|
+
printError(message);
|
|
2151
|
+
}
|
|
2152
|
+
process.exit(1);
|
|
2153
|
+
};
|
|
2154
|
+
printInfo(`Creating an anonymous sandbox on ${baseUrl}...`);
|
|
2155
|
+
let response;
|
|
2156
|
+
try {
|
|
2157
|
+
response = await fetch(`${baseUrl}/api/agents/sandbox`, {
|
|
2158
|
+
method: "POST",
|
|
2159
|
+
headers: { "Content-Type": "application/json" },
|
|
2160
|
+
body: JSON.stringify({
|
|
2161
|
+
name: options.name || "Sandbox Agent",
|
|
2162
|
+
agentType: options.type || "CUSTOM",
|
|
2163
|
+
description: "Created via create-conto-agent --sandbox"
|
|
2164
|
+
})
|
|
2165
|
+
});
|
|
2166
|
+
} catch (err) {
|
|
2167
|
+
return failure(
|
|
2168
|
+
`Could not reach ${baseUrl}: ${err instanceof Error ? err.message : "network error"}`
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
const body = await response.json().catch(() => ({}));
|
|
2172
|
+
if (response.status === 429) {
|
|
2173
|
+
const retryAfter = response.headers.get("retry-after");
|
|
2174
|
+
return failure(
|
|
2175
|
+
`Sandbox signup is rate limited for this IP.${retryAfter ? ` Retry after ${retryAfter}s.` : ""}`
|
|
2176
|
+
);
|
|
2177
|
+
}
|
|
2178
|
+
if (!response.ok) {
|
|
2179
|
+
return failure(
|
|
2180
|
+
typeof body.error === "string" ? body.error : `Sandbox signup failed (${response.status})`
|
|
2181
|
+
);
|
|
2182
|
+
}
|
|
2183
|
+
const sandbox = body;
|
|
2184
|
+
printSuccess(`Sandbox created (expires ${sandbox.expiresAt})`);
|
|
2185
|
+
let chain;
|
|
2186
|
+
try {
|
|
2187
|
+
const { chains } = await fetchChains(baseUrl);
|
|
2188
|
+
chain = chains[sandbox.wallet.chainId];
|
|
2189
|
+
} catch {
|
|
2190
|
+
chain = void 0;
|
|
2191
|
+
}
|
|
2192
|
+
const cwd = process.cwd();
|
|
2193
|
+
ensureEnvLocalGitignored(cwd);
|
|
2194
|
+
writeEnvLocal(cwd, [
|
|
2195
|
+
"# Conto Agent Configuration (anonymous test-mode sandbox)",
|
|
2196
|
+
"# Generated by: npx @conto_finance/create-conto-agent --sandbox",
|
|
2197
|
+
"",
|
|
2198
|
+
"# SDK Authentication",
|
|
2199
|
+
["CONTO_API_KEY", sandbox.credentials.sdkKey],
|
|
2200
|
+
["CONTO_BASE_URL", baseUrl],
|
|
2201
|
+
"",
|
|
2202
|
+
"# Agent Identity",
|
|
2203
|
+
["CONTO_AGENT_ID", sandbox.agent.id],
|
|
2204
|
+
["CONTO_AGENT_NAME", sandbox.agent.name],
|
|
2205
|
+
"",
|
|
2206
|
+
`# Network: ${chain?.name || sandbox.wallet.chainId} (testnet)`,
|
|
2207
|
+
["CONTO_CHAIN_ID", sandbox.wallet.chainId],
|
|
2208
|
+
...chain ? [
|
|
2209
|
+
["CONTO_CHAIN_NAME", chain.name],
|
|
2210
|
+
["CONTO_RPC_URL", chain.rpcUrl],
|
|
2211
|
+
["CONTO_EXPLORER_URL", chain.explorerUrl],
|
|
2212
|
+
["CONTO_CURRENCY", chain.currency]
|
|
2213
|
+
] : [["CONTO_CURRENCY", sandbox.wallet.currency]],
|
|
2214
|
+
"",
|
|
2215
|
+
"# Wallet",
|
|
2216
|
+
["CONTO_WALLET_ID", sandbox.wallet.id],
|
|
2217
|
+
["CONTO_WALLET_ADDRESS", sandbox.wallet.address],
|
|
2218
|
+
"",
|
|
2219
|
+
"# Sandbox (shown once, keep private)",
|
|
2220
|
+
["CONTO_SANDBOX_API_KEY", sandbox.credentials.apiKey],
|
|
2221
|
+
["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt]
|
|
2222
|
+
]);
|
|
2223
|
+
const setupKeyFile = sandbox.credentials.setupKey ? (ensureContoDirGitignored(cwd), writeSandboxSetupEnv(cwd, [
|
|
2224
|
+
"# Conto sandbox setup key: configures this sandbox's policies and spend limits.",
|
|
2225
|
+
"# Use it from setup scripts only. Never load it in the payment agent runtime.",
|
|
2226
|
+
"# Claiming the sandbox revokes it.",
|
|
2227
|
+
"",
|
|
2228
|
+
["CONTO_SANDBOX_SETUP_KEY", sandbox.credentials.setupKey],
|
|
2229
|
+
["CONTO_BASE_URL", baseUrl],
|
|
2230
|
+
["CONTO_AGENT_ID", sandbox.agent.id],
|
|
2231
|
+
["CONTO_WALLET_ID", sandbox.wallet.id],
|
|
2232
|
+
["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt]
|
|
2233
|
+
])) : null;
|
|
2234
|
+
writeContoConfig(cwd, {
|
|
2235
|
+
agent: {
|
|
2236
|
+
id: sandbox.agent.id,
|
|
2237
|
+
name: sandbox.agent.name,
|
|
2238
|
+
type: options.type || "CUSTOM"
|
|
2239
|
+
},
|
|
2240
|
+
network: {
|
|
2241
|
+
chain: sandbox.wallet.chainId,
|
|
2242
|
+
chainId: sandbox.wallet.chainId,
|
|
2243
|
+
rpcUrl: chain?.rpcUrl || "",
|
|
2244
|
+
explorerUrl: chain?.explorerUrl || "",
|
|
2245
|
+
currency: chain?.currency || sandbox.wallet.currency,
|
|
2246
|
+
testnet: true
|
|
2247
|
+
},
|
|
2248
|
+
wallet: {
|
|
2249
|
+
id: sandbox.wallet.id,
|
|
2250
|
+
address: sandbox.wallet.address,
|
|
2251
|
+
custodyMode: sandbox.wallet.custodyMode
|
|
2252
|
+
},
|
|
2253
|
+
server: {
|
|
2254
|
+
baseUrl
|
|
2255
|
+
},
|
|
2256
|
+
sandbox: {
|
|
2257
|
+
mode: "test",
|
|
2258
|
+
expiresAt: sandbox.expiresAt
|
|
2259
|
+
}
|
|
2260
|
+
});
|
|
2261
|
+
writeExampleFile(cwd);
|
|
2262
|
+
saveGlobalConfig({
|
|
2263
|
+
agent: {
|
|
2264
|
+
id: sandbox.agent.id,
|
|
2265
|
+
name: sandbox.agent.name,
|
|
2266
|
+
type: options.type || "CUSTOM"
|
|
2267
|
+
},
|
|
2268
|
+
network: {
|
|
2269
|
+
chain: sandbox.wallet.chainId,
|
|
2270
|
+
chainId: sandbox.wallet.chainId,
|
|
2271
|
+
rpcUrl: chain?.rpcUrl || "",
|
|
2272
|
+
explorerUrl: chain?.explorerUrl || "",
|
|
2273
|
+
currency: chain?.currency || sandbox.wallet.currency,
|
|
2274
|
+
testnet: true
|
|
2275
|
+
},
|
|
2276
|
+
wallet: {
|
|
2277
|
+
id: sandbox.wallet.id,
|
|
2278
|
+
address: sandbox.wallet.address,
|
|
2279
|
+
custodyMode: sandbox.wallet.custodyMode
|
|
2280
|
+
},
|
|
2281
|
+
server: {
|
|
2282
|
+
baseUrl,
|
|
2283
|
+
apiKey: sandbox.credentials.sdkKey,
|
|
2284
|
+
orgApiKey: sandbox.credentials.apiKey
|
|
2285
|
+
},
|
|
2286
|
+
sandbox: {
|
|
2287
|
+
mode: "test",
|
|
2288
|
+
expiresAt: sandbox.expiresAt
|
|
2289
|
+
}
|
|
2290
|
+
});
|
|
2291
|
+
let cliResolves = hasLocalCliBin(cwd);
|
|
2292
|
+
if (!cliResolves && options.install !== false) {
|
|
2293
|
+
cliResolves = installCliLocally(cwd, sandbox.agent.name) === "installed";
|
|
2294
|
+
}
|
|
2295
|
+
const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
|
|
2296
|
+
if (isJsonMode()) {
|
|
2297
|
+
printJson({
|
|
2298
|
+
ok: true,
|
|
2299
|
+
mode: "sandbox",
|
|
2300
|
+
baseUrl,
|
|
2301
|
+
expiresAt: sandbox.expiresAt,
|
|
2302
|
+
organization: sandbox.organization,
|
|
2303
|
+
agent: sandbox.agent,
|
|
2304
|
+
wallet: sandbox.wallet,
|
|
2305
|
+
credentials: {
|
|
2306
|
+
storedIn: ".env.local",
|
|
2307
|
+
sdkKeyEnv: "CONTO_API_KEY",
|
|
2308
|
+
sandboxApiKeyEnv: "CONTO_SANDBOX_API_KEY",
|
|
2309
|
+
...setupKeyFile ? { setupKeyStoredIn: setupKeyFile, setupKeyEnv: "CONTO_SANDBOX_SETUP_KEY" } : {}
|
|
2310
|
+
},
|
|
2311
|
+
files: [
|
|
2312
|
+
".env.local",
|
|
2313
|
+
".gitignore",
|
|
2314
|
+
"conto.config.json",
|
|
2315
|
+
"example.mjs",
|
|
2316
|
+
...setupKeyFile ? [setupKeyFile] : []
|
|
2317
|
+
],
|
|
2318
|
+
claim: {
|
|
2319
|
+
command: `${cli} sandbox claim --json`,
|
|
2320
|
+
credentialEnv: "CONTO_SANDBOX_API_KEY",
|
|
2321
|
+
...sandbox.claim ? { method: sandbox.claim.method, endpoint: sandbox.claim.endpoint } : {}
|
|
2322
|
+
},
|
|
2323
|
+
nextSteps: [
|
|
2324
|
+
"node example.mjs",
|
|
2325
|
+
"node example.mjs --resume REQUEST_ID",
|
|
2326
|
+
`${cli} doctor`,
|
|
2327
|
+
`${cli} pay 0x742d35Cc6634C0532925a3b844Bc454e4438f44e 1 --purpose test`,
|
|
2328
|
+
`${cli} sandbox claim --json`
|
|
2329
|
+
]
|
|
2330
|
+
});
|
|
2331
|
+
return;
|
|
2332
|
+
}
|
|
2333
|
+
console.log("");
|
|
2334
|
+
console.log(chalk.green.bold(" Sandbox agent ready!") + " Files written:\n");
|
|
2335
|
+
console.log(` ${chalk.bold(".env.local")} - SDK key + config (shown once)`);
|
|
2336
|
+
console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
|
|
2337
|
+
console.log(` ${chalk.bold("example.mjs")} - Runnable payment example`);
|
|
2338
|
+
if (setupKeyFile) {
|
|
2339
|
+
console.log(
|
|
2340
|
+
` ${chalk.bold(setupKeyFile)} - Setup key for policies and limits (keep out of the agent runtime)`
|
|
2341
|
+
);
|
|
2342
|
+
}
|
|
2343
|
+
console.log("");
|
|
2344
|
+
console.log(
|
|
2345
|
+
` ${chalk.dim("Wallet:")} ${sandbox.wallet.address} (${chain?.name || sandbox.wallet.chainId}, test mode)`
|
|
2346
|
+
);
|
|
2347
|
+
console.log(
|
|
2348
|
+
` ${chalk.dim("Balance:")} ${sandbox.wallet.balance} ${sandbox.wallet.currency} (test balance)`
|
|
2349
|
+
);
|
|
2350
|
+
console.log(
|
|
2351
|
+
` ${chalk.dim("Limits:")} $${sandbox.wallet.limits.perTransaction}/tx, $${sandbox.wallet.limits.daily}/day${setupKeyFile ? " (editable with the setup key)" : ""}`
|
|
2352
|
+
);
|
|
2353
|
+
console.log(` ${chalk.dim("Expires:")} ${sandbox.expiresAt}`);
|
|
2354
|
+
console.log("");
|
|
2355
|
+
console.log(chalk.bold(" Next steps:"));
|
|
2356
|
+
console.log(` 1. Run the example: ${chalk.cyan("node example.mjs")}`);
|
|
2357
|
+
console.log(` 2. Continue it: ${chalk.cyan("node example.mjs --resume REQUEST_ID")}`);
|
|
2358
|
+
console.log(" Replace REQUEST_ID with the ID printed by the example.");
|
|
2359
|
+
console.log(` 3. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
|
|
2360
|
+
console.log("");
|
|
2361
|
+
printInfo(
|
|
2362
|
+
"Sandbox test payments exercise policy checks, receipts, and spend tracking without an onchain transfer."
|
|
2363
|
+
);
|
|
2364
|
+
printInfo(`To hand this sandbox to its owner before it expires, run: ${cli} sandbox claim`);
|
|
2365
|
+
console.log("");
|
|
2366
|
+
}
|
|
2367
|
+
function hasLocalCliBin(cwd) {
|
|
2368
|
+
return fs2.existsSync(path2.join(cwd, "node_modules", ".bin", "conto"));
|
|
2369
|
+
}
|
|
2370
|
+
function installCliLocally(cwd, agentName) {
|
|
2371
|
+
const foreignLockfiles = ["yarn.lock", "pnpm-lock.yaml", "bun.lockb", "bun.lock"];
|
|
2372
|
+
if (foreignLockfiles.some((f) => fs2.existsSync(path2.join(cwd, f)))) {
|
|
2373
|
+
return "unsupported-pm";
|
|
2374
|
+
}
|
|
2375
|
+
const pkgJsonPath = path2.join(cwd, "package.json");
|
|
2376
|
+
const createdPkgJson = !fs2.existsSync(pkgJsonPath);
|
|
2377
|
+
if (createdPkgJson) {
|
|
2378
|
+
const slug = agentName.toLowerCase().replace(/[^a-z0-9-_]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "conto-agent";
|
|
2379
|
+
fs2.writeFileSync(
|
|
2380
|
+
pkgJsonPath,
|
|
2381
|
+
JSON.stringify({ name: slug, version: "0.1.0", private: true, type: "module" }, null, 2) + "\n"
|
|
2382
|
+
);
|
|
2383
|
+
}
|
|
2384
|
+
const result = spawnSync(
|
|
2385
|
+
process.platform === "win32" ? "npm.cmd" : "npm",
|
|
2386
|
+
[
|
|
2387
|
+
"install",
|
|
2388
|
+
"--save-dev",
|
|
2389
|
+
"--no-fund",
|
|
2390
|
+
"--no-audit",
|
|
2391
|
+
`@conto_finance/create-conto-agent@^${CLI_PACKAGE_VERSION}`
|
|
2392
|
+
],
|
|
2393
|
+
{
|
|
2394
|
+
cwd,
|
|
2395
|
+
stdio: "ignore",
|
|
2396
|
+
timeout: 18e4,
|
|
2397
|
+
shell: process.platform === "win32"
|
|
2398
|
+
}
|
|
2399
|
+
);
|
|
2400
|
+
if (result.status === 0) {
|
|
2401
|
+
return "installed";
|
|
2402
|
+
}
|
|
2403
|
+
if (createdPkgJson) {
|
|
2404
|
+
try {
|
|
2405
|
+
fs2.unlinkSync(pkgJsonPath);
|
|
2406
|
+
} catch {
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
return "failed";
|
|
2410
|
+
}
|
|
2411
|
+
function writeExampleFile(dir) {
|
|
2412
|
+
const content = `// Conto quickstart example, generated by create-conto-agent.
|
|
2413
|
+
//
|
|
2414
|
+
// Usage:
|
|
2415
|
+
// node example.mjs Check setup and request a test payment (no funds move)
|
|
2416
|
+
// node example.mjs --execute Start a new payment and execute it if approved
|
|
2417
|
+
// node example.mjs --resume REQUEST_ID Check and continue the same request
|
|
2418
|
+
// node example.mjs --status REQUEST_ID Read status without executing
|
|
2419
|
+
//
|
|
2420
|
+
// Reads CONTO_API_KEY and CONTO_BASE_URL from .env.local in this directory.
|
|
2421
|
+
// Docs: https://conto.finance/docs
|
|
2422
|
+
|
|
2423
|
+
import { readFileSync } from 'fs';
|
|
2424
|
+
import { randomUUID } from 'node:crypto';
|
|
2425
|
+
let lastRequestId;
|
|
2426
|
+
try {
|
|
2427
|
+
for (const line of readFileSync('.env.local', 'utf-8').split('\\n')) {
|
|
2428
|
+
const match = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
|
|
2429
|
+
if (match && !process.env[match[1]]) process.env[match[1]] = match[2];
|
|
2430
|
+
}
|
|
2431
|
+
} catch {}
|
|
2432
|
+
|
|
2433
|
+
const BASE_URL = process.env.CONTO_BASE_URL || 'https://conto.finance';
|
|
2434
|
+
const API_KEY = process.env.CONTO_API_KEY;
|
|
2435
|
+
const IS_SANDBOX = Boolean(process.env.CONTO_SANDBOX_EXPIRES_AT);
|
|
2436
|
+
const EXECUTE = process.argv.includes('--execute');
|
|
2437
|
+
|
|
2438
|
+
if (!API_KEY) {
|
|
2439
|
+
console.error('Missing CONTO_API_KEY in .env.local. Run: npx @conto_finance/create-conto-agent');
|
|
2440
|
+
process.exit(1);
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
async function api(method, path, body) {
|
|
2444
|
+
const res = await fetch(\`\${BASE_URL}\${path}\`, {
|
|
2445
|
+
method,
|
|
2446
|
+
headers: { Authorization: \`Bearer \${API_KEY}\`, 'Content-Type': 'application/json' },
|
|
2447
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
2448
|
+
});
|
|
2449
|
+
const data = await res.json();
|
|
2450
|
+
if (data.requestId) lastRequestId = data.requestId;
|
|
2451
|
+
if (!res.ok && data.actionUrl) console.error('Complete action:', data.actionUrl);
|
|
2452
|
+
if (!res.ok) throw new Error(data.error || \`\${method} \${path} failed (\${res.status})\`);
|
|
2453
|
+
return data;
|
|
2454
|
+
}
|
|
2455
|
+
|
|
2456
|
+
async function main() {
|
|
2457
|
+
const resumeIndex = process.argv.indexOf('--resume');
|
|
2458
|
+
const statusIndex = process.argv.indexOf('--status');
|
|
2459
|
+
if (resumeIndex >= 0 || statusIndex >= 0) {
|
|
2460
|
+
const requestId = process.argv[(resumeIndex >= 0 ? resumeIndex : statusIndex) + 1];
|
|
2461
|
+
if (!requestId || !/^[a-zA-Z0-9_-]+$/.test(requestId)) {
|
|
2462
|
+
throw new Error('Supply the saved request ID after --resume or --status.');
|
|
2463
|
+
}
|
|
2464
|
+
lastRequestId = requestId;
|
|
2465
|
+
const current = await api('GET', '/api/sdk/payments/' + requestId);
|
|
2466
|
+
console.log(JSON.stringify(current, null, 2));
|
|
2467
|
+
// Approval may already have executed it. Never create another request here.
|
|
2468
|
+
if (resumeIndex >= 0 && current.status === 'approved') {
|
|
2469
|
+
console.log(JSON.stringify(await api('POST', '/api/sdk/payments/' + requestId + '/execute'), null, 2));
|
|
2470
|
+
}
|
|
2471
|
+
return;
|
|
2472
|
+
}
|
|
2473
|
+
// 1. Setup snapshot: agent, key scopes, wallets. Same data as "conto doctor".
|
|
2474
|
+
const setup = await api('GET', '/api/sdk/setup');
|
|
2475
|
+
console.log(\`Agent: \${setup.agent.name} (\${setup.agent.status})\`);
|
|
2476
|
+
console.log(\`Scopes: \${(setup.scopes || []).join(', ')}\\n\`);
|
|
2477
|
+
for (const w of setup.wallets || []) {
|
|
2478
|
+
console.log(\`Wallet: \${w.address}\`);
|
|
2479
|
+
console.log(\` Chain: \${w.chainName} (\${w.chainId})\${w.isTestnet ? ' testnet' : ''}\`);
|
|
2480
|
+
const executionLabel =
|
|
2481
|
+
IS_SANDBOX
|
|
2482
|
+
? 'sandbox test mode'
|
|
2483
|
+
: w.custodyMode === 'MANAGED'
|
|
2484
|
+
? 'managed execution'
|
|
2485
|
+
: 'external execution';
|
|
2486
|
+
console.log(\` Custody: \${w.custodyMode}\${executionLabel ? \` (\${executionLabel})\` : ''}\`);
|
|
2487
|
+
console.log(\` Balance: \${w.balance} \${w.currency}\`);
|
|
2488
|
+
console.log(\` Daily: \${w.spent?.today ?? 0} / \${w.limits?.daily ?? 'unlimited'}\\n\`);
|
|
2489
|
+
}
|
|
2490
|
+
|
|
2491
|
+
const wallet = (setup.wallets || []).find((w) => String(w.chainId) === '42431');
|
|
2492
|
+
if (!wallet) throw new Error('This example requires a Tempo Testnet wallet (42431).');
|
|
2493
|
+
|
|
2494
|
+
// 2. Request a payment. The policy engine evaluates it and returns
|
|
2495
|
+
// APPROVED, DENIED, or REQUIRES_APPROVAL. No funds move on request.
|
|
2496
|
+
console.log('Requesting a $0.01 test payment...');
|
|
2497
|
+
const request = await api('POST', '/api/sdk/payments/request', {
|
|
2498
|
+
amount: 0.01,
|
|
2499
|
+
walletId: wallet.id,
|
|
2500
|
+
idempotencyKey: randomUUID(),
|
|
2501
|
+
recipientAddress: '0x0000000000000000000000000000000000000001',
|
|
2502
|
+
purpose: 'Test payment from CLI quickstart',
|
|
2503
|
+
category: 'TESTING',
|
|
2504
|
+
});
|
|
2505
|
+
lastRequestId = request.requestId;
|
|
2506
|
+
console.log('Request ID:', lastRequestId);
|
|
2507
|
+
console.log(\`Policy decision: \${request.status}\`);
|
|
2508
|
+
if (request.reasons?.length) console.log(\`Reasons: \${request.reasons.join(', ')}\`);
|
|
2509
|
+
|
|
2510
|
+
if (request.status === 'DENIED') {
|
|
2511
|
+
for (const v of request.violations || []) console.log(\` - \${v.message}\`);
|
|
2512
|
+
return;
|
|
2513
|
+
}
|
|
2514
|
+
if (request.status === 'REQUIRES_APPROVAL') {
|
|
2515
|
+
console.log('Ask the owner to review it in Conto. Then run: node example.mjs --resume ' + lastRequestId);
|
|
2516
|
+
return;
|
|
2517
|
+
}
|
|
2518
|
+
if (request.status !== 'APPROVED') {
|
|
2519
|
+
console.log(\`Stopped at status \${request.status}. Check the dashboard for next steps.\`);
|
|
2520
|
+
return;
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
// 3. Execute the approved request. The standard SDK key created by the
|
|
2524
|
+
// quickstart includes the payments:execute scope.
|
|
2525
|
+
if (!EXECUTE) {
|
|
2526
|
+
console.log(\`\\nApproved (request \${request.requestId}). No funds moved.\`);
|
|
2527
|
+
console.log('Continue this same request: node example.mjs --resume ' + lastRequestId);
|
|
2528
|
+
console.log('Each run without --resume creates a new payment intent.');
|
|
2529
|
+
return;
|
|
2530
|
+
}
|
|
2531
|
+
const result = await api('POST', \`/api/sdk/payments/\${request.requestId}/execute\`);
|
|
2532
|
+
console.log(IS_SANDBOX ? '\\nPayment recorded in sandbox test mode.' : '\\nPayment sent.');
|
|
2533
|
+
console.log('Status:', result.status);
|
|
2534
|
+
console.log('Settlement mode:', result.receipt?.settlementMode);
|
|
2535
|
+
if (result.receipt?.txHash) console.log('TX hash:', result.receipt.txHash);
|
|
2536
|
+
if (result.receipt?.explorerUrl) console.log('Explorer:', result.receipt.explorerUrl);
|
|
2537
|
+
console.log('Check settlement with GET /api/sdk/payments/' + lastRequestId);
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2540
|
+
main().catch((err) => {
|
|
2541
|
+
console.error(err instanceof Error ? err.message : err);
|
|
2542
|
+
if (lastRequestId) console.error('Do not repeat execution. Check GET /api/sdk/payments/' + lastRequestId);
|
|
2543
|
+
process.exit(1);
|
|
2544
|
+
});
|
|
2545
|
+
`;
|
|
2546
|
+
fs2.writeFileSync(path2.join(dir, "example.mjs"), content);
|
|
2547
|
+
}
|
|
2548
|
+
|
|
2549
|
+
export {
|
|
2550
|
+
CLI_PACKAGE_VERSION,
|
|
2551
|
+
fetchChains,
|
|
2552
|
+
getChain,
|
|
2553
|
+
browserAuth,
|
|
2554
|
+
HttpTransportError,
|
|
2555
|
+
redactSecrets,
|
|
2556
|
+
parseSecureBaseUrl,
|
|
2557
|
+
normalizeBaseUrl,
|
|
2558
|
+
apiUrl,
|
|
2559
|
+
requestJson,
|
|
2560
|
+
retryAfterSeconds,
|
|
2561
|
+
responseErrorMessage,
|
|
2562
|
+
responseErrorCode,
|
|
2563
|
+
projectStateFile,
|
|
2564
|
+
readProjectStateFile,
|
|
2565
|
+
writeProjectStateFile,
|
|
2566
|
+
fingerprintSecret,
|
|
2567
|
+
runInit
|
|
2568
|
+
};
|