crowdcode-mcp 0.12.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -0
- package/dist/chunk-CSAFC6V4.js +780 -0
- package/dist/chunk-CSAFC6V4.js.map +1 -0
- package/dist/chunk-L32J3R5J.js +1352 -0
- package/dist/chunk-L32J3R5J.js.map +1 -0
- package/dist/chunk-YPIV4BZP.js +408 -0
- package/dist/chunk-YPIV4BZP.js.map +1 -0
- package/dist/cli.js +47 -3
- package/dist/cli.js.map +1 -1
- package/dist/dashboard-5NIPV4UE.js +16 -0
- package/dist/dashboard-5NIPV4UE.js.map +1 -0
- package/dist/{server-AMGZRDBF.js → server-M5SB5SNQ.js} +52 -6
- package/dist/server-M5SB5SNQ.js.map +1 -0
- package/dist/skills/crowdcode/SKILL.md +23 -1
- package/dist/tools-ZNWEQA7W.js +40 -0
- package/dist/tools-ZNWEQA7W.js.map +1 -0
- package/package.json +1 -1
- package/dist/server-AMGZRDBF.js.map +0 -1
|
@@ -0,0 +1,780 @@
|
|
|
1
|
+
// src/agents/errors.ts
|
|
2
|
+
var ToolError = class extends Error {
|
|
3
|
+
name = "ToolError";
|
|
4
|
+
};
|
|
5
|
+
var UncertainError = class extends ToolError {
|
|
6
|
+
name = "UncertainError";
|
|
7
|
+
};
|
|
8
|
+
var WalletMissing = class extends Error {
|
|
9
|
+
name = "WalletMissing";
|
|
10
|
+
};
|
|
11
|
+
var NotSignedIn = class extends Error {
|
|
12
|
+
name = "NotSignedIn";
|
|
13
|
+
};
|
|
14
|
+
var LOGIN_COMMAND = "npx crowdcode-mcp login";
|
|
15
|
+
var WALLET_INIT_COMMAND = "npx crowdcode-mcp wallet init";
|
|
16
|
+
|
|
17
|
+
// src/agents/signer.ts
|
|
18
|
+
import { createHash, randomBytes } from "crypto";
|
|
19
|
+
import { getAddress } from "viem/utils";
|
|
20
|
+
var BASE_CHAIN_ID = 8453;
|
|
21
|
+
var BASE_CAIP2 = `eip155:${BASE_CHAIN_ID}`;
|
|
22
|
+
var BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
|
|
23
|
+
var USDC_DECIMALS = 6;
|
|
24
|
+
var TRANSFER_WITH_AUTHORIZATION = [
|
|
25
|
+
{ name: "from", type: "address" },
|
|
26
|
+
{ name: "to", type: "address" },
|
|
27
|
+
{ name: "value", type: "uint256" },
|
|
28
|
+
{ name: "validAfter", type: "uint256" },
|
|
29
|
+
{ name: "validBefore", type: "uint256" },
|
|
30
|
+
{ name: "nonce", type: "bytes32" }
|
|
31
|
+
];
|
|
32
|
+
function requestMessage(method, path, bodySha256, timestamp, nonce) {
|
|
33
|
+
return ["CrowdCode API request", `${method.toUpperCase()} ${path}`, bodySha256, timestamp, nonce].join("\n");
|
|
34
|
+
}
|
|
35
|
+
function sha256Hex(body) {
|
|
36
|
+
return body.length ? createHash("sha256").update(body).digest("hex") : "";
|
|
37
|
+
}
|
|
38
|
+
var Signer = class {
|
|
39
|
+
constructor(account) {
|
|
40
|
+
this.account = account;
|
|
41
|
+
}
|
|
42
|
+
account;
|
|
43
|
+
/** Checksummed. */
|
|
44
|
+
get address() {
|
|
45
|
+
return getAddress(this.account.address);
|
|
46
|
+
}
|
|
47
|
+
get caip10() {
|
|
48
|
+
return `${BASE_CAIP2}:${this.address}`;
|
|
49
|
+
}
|
|
50
|
+
/** EIP-191 personal_sign over the UTF-8 text, 0x-hex. */
|
|
51
|
+
signMessage(text) {
|
|
52
|
+
return this.account.signMessage({ message: text });
|
|
53
|
+
}
|
|
54
|
+
/** Headers for the CrowdCode signed owner API (Wallet API v1). */
|
|
55
|
+
async signRequest(method, path, body, fixed = {}) {
|
|
56
|
+
const timestamp = String(Math.floor(fixed.now ?? Date.now() / 1e3));
|
|
57
|
+
const nonce = fixed.nonce ?? randomBytes(16).toString("hex");
|
|
58
|
+
const message = requestMessage(method, path, sha256Hex(body), timestamp, nonce);
|
|
59
|
+
return {
|
|
60
|
+
"X-CrowdCode-Address": this.caip10,
|
|
61
|
+
"X-CrowdCode-Timestamp": timestamp,
|
|
62
|
+
"X-CrowdCode-Nonce": nonce,
|
|
63
|
+
"X-CrowdCode-Signature": await this.signMessage(message)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Sign an EIP-3009 `transferWithAuthorization`. It can only move exactly
|
|
68
|
+
* `value` to `to`, once, before `validBefore`. String fields, as x402 and the
|
|
69
|
+
* deposits endpoint expect.
|
|
70
|
+
*/
|
|
71
|
+
async authorizeTransfer(options) {
|
|
72
|
+
if (options.value <= 0n) throw new ToolError("value must be positive");
|
|
73
|
+
const now = Math.floor(options.now ?? Date.now() / 1e3);
|
|
74
|
+
const nonce = options.nonce ?? "0x" + randomBytes(32).toString("hex");
|
|
75
|
+
const validBefore = BigInt(now + Math.max(30, Math.trunc(options.validSeconds)));
|
|
76
|
+
const authorization = {
|
|
77
|
+
from: this.address,
|
|
78
|
+
to: getAddress(options.to),
|
|
79
|
+
value: options.value.toString(),
|
|
80
|
+
validAfter: "0",
|
|
81
|
+
validBefore: validBefore.toString(),
|
|
82
|
+
nonce
|
|
83
|
+
};
|
|
84
|
+
const signature = await this.account.signTypedData({
|
|
85
|
+
domain: {
|
|
86
|
+
name: options.tokenName ?? "USD Coin",
|
|
87
|
+
version: options.tokenVersion ?? "2",
|
|
88
|
+
chainId: options.chainId ?? BASE_CHAIN_ID,
|
|
89
|
+
verifyingContract: getAddress(options.asset ?? BASE_USDC)
|
|
90
|
+
},
|
|
91
|
+
types: { TransferWithAuthorization: TRANSFER_WITH_AUTHORIZATION },
|
|
92
|
+
primaryType: "TransferWithAuthorization",
|
|
93
|
+
message: {
|
|
94
|
+
from: authorization.from,
|
|
95
|
+
to: authorization.to,
|
|
96
|
+
value: options.value,
|
|
97
|
+
validAfter: 0n,
|
|
98
|
+
validBefore,
|
|
99
|
+
nonce
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
return { authorization, signature };
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
function usdToUnits(amount) {
|
|
106
|
+
if (typeof amount === "number" && !Number.isFinite(amount)) {
|
|
107
|
+
throw new ToolError("amount must be greater than zero");
|
|
108
|
+
}
|
|
109
|
+
const text = String(amount).trim();
|
|
110
|
+
const match = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text);
|
|
111
|
+
if (!match || !match[2] && !match[3]) throw new ToolError(`not an amount: ${JSON.stringify(amount)}`);
|
|
112
|
+
const [, sign, whole = "", fraction = "", expText = "0"] = match;
|
|
113
|
+
const digits = BigInt((whole + fraction).replace(/^0+(?=\d)/, "") || "0");
|
|
114
|
+
if (sign === "-" || digits === 0n) throw new ToolError("amount must be greater than zero");
|
|
115
|
+
const shift = Number(expText) - fraction.length + USDC_DECIMALS;
|
|
116
|
+
const units = shift >= 0 ? digits * 10n ** BigInt(shift) : digits / 10n ** BigInt(-shift);
|
|
117
|
+
if (units <= 0n) throw new ToolError("amount is below one USDC base unit");
|
|
118
|
+
return units;
|
|
119
|
+
}
|
|
120
|
+
function unitsToUsd(units) {
|
|
121
|
+
return Number(BigInt(units)) / 10 ** USDC_DECIMALS;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// src/agents/pyjson.ts
|
|
125
|
+
var PyFloat = class {
|
|
126
|
+
constructor(value) {
|
|
127
|
+
this.value = value;
|
|
128
|
+
}
|
|
129
|
+
value;
|
|
130
|
+
toJSON() {
|
|
131
|
+
return this.value;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
function pyFloat(value) {
|
|
135
|
+
return new PyFloat(value);
|
|
136
|
+
}
|
|
137
|
+
var SHORT_ESCAPES = {
|
|
138
|
+
8: "\\b",
|
|
139
|
+
9: "\\t",
|
|
140
|
+
10: "\\n",
|
|
141
|
+
12: "\\f",
|
|
142
|
+
13: "\\r"
|
|
143
|
+
};
|
|
144
|
+
function encodeString(value) {
|
|
145
|
+
let out = '"';
|
|
146
|
+
for (let i = 0; i < value.length; i++) {
|
|
147
|
+
const code = value.charCodeAt(i);
|
|
148
|
+
const short = SHORT_ESCAPES[code];
|
|
149
|
+
if (code === 34) out += '\\"';
|
|
150
|
+
else if (code === 92) out += "\\\\";
|
|
151
|
+
else if (short !== void 0) out += short;
|
|
152
|
+
else if (code < 32 || code > 126) out += "\\u" + code.toString(16).padStart(4, "0");
|
|
153
|
+
else out += value[i];
|
|
154
|
+
}
|
|
155
|
+
return out + '"';
|
|
156
|
+
}
|
|
157
|
+
function pyFloatRepr(x) {
|
|
158
|
+
if (Number.isNaN(x)) return "NaN";
|
|
159
|
+
if (x === Infinity) return "Infinity";
|
|
160
|
+
if (x === -Infinity) return "-Infinity";
|
|
161
|
+
if (x === 0) return Object.is(x, -0) ? "-0.0" : "0.0";
|
|
162
|
+
const sign = x < 0 ? "-" : "";
|
|
163
|
+
const [mantissa, expText] = Math.abs(x).toExponential().split("e");
|
|
164
|
+
const digits = mantissa.replace(".", "");
|
|
165
|
+
const exp = Number(expText);
|
|
166
|
+
if (exp >= -4 && exp < 16) {
|
|
167
|
+
if (exp < 0) return `${sign}0.${"0".repeat(-exp - 1)}${digits}`;
|
|
168
|
+
const whole = digits.slice(0, exp + 1).padEnd(exp + 1, "0");
|
|
169
|
+
return `${sign}${whole}.${digits.slice(exp + 1) || "0"}`;
|
|
170
|
+
}
|
|
171
|
+
const lead = digits.length > 1 ? `${digits[0]}.${digits.slice(1)}` : digits;
|
|
172
|
+
return `${sign}${lead}e${exp < 0 ? "-" : "+"}${String(Math.abs(exp)).padStart(2, "0")}`;
|
|
173
|
+
}
|
|
174
|
+
function encodeNumber(value) {
|
|
175
|
+
if (Number.isInteger(value)) {
|
|
176
|
+
return Number.isSafeInteger(value) ? String(value) : BigInt(value).toString();
|
|
177
|
+
}
|
|
178
|
+
return pyFloatRepr(value);
|
|
179
|
+
}
|
|
180
|
+
function pyDumps(value, options = {}) {
|
|
181
|
+
const item = options.compact ? "," : ", ";
|
|
182
|
+
const key = options.compact ? ":" : ": ";
|
|
183
|
+
const encode = (v) => {
|
|
184
|
+
if (v === null || v === void 0) return "null";
|
|
185
|
+
if (v instanceof PyFloat) return pyFloatRepr(v.value);
|
|
186
|
+
if (typeof v === "boolean") return v ? "true" : "false";
|
|
187
|
+
if (typeof v === "number") return encodeNumber(v);
|
|
188
|
+
if (typeof v === "bigint") return v.toString();
|
|
189
|
+
if (typeof v === "string") return encodeString(v);
|
|
190
|
+
if (Array.isArray(v)) return `[${v.map(encode).join(item)}]`;
|
|
191
|
+
if (typeof v === "object") {
|
|
192
|
+
let entries = Object.entries(v).filter(([, x]) => x !== void 0);
|
|
193
|
+
if (options.sortKeys) entries = entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
194
|
+
return `{${entries.map(([k, x]) => encodeString(k) + key + encode(x)).join(item)}}`;
|
|
195
|
+
}
|
|
196
|
+
return encodeString(String(v));
|
|
197
|
+
};
|
|
198
|
+
return encode(value);
|
|
199
|
+
}
|
|
200
|
+
function jsonBody(payload) {
|
|
201
|
+
return payload === void 0 || payload === null ? new Uint8Array() : new TextEncoder().encode(pyDumps(payload, { compact: true }));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// src/agents/client.ts
|
|
205
|
+
var USER_AGENT = "crowdcode-mcp (agents)";
|
|
206
|
+
var TIMEOUT_MS = 3e4;
|
|
207
|
+
var PAY_TIMEOUT_MS = 12e4;
|
|
208
|
+
var STREAM_TIMEOUT_MS = 3e5;
|
|
209
|
+
var ApiError = class extends Error {
|
|
210
|
+
constructor(status, error, detail = void 0) {
|
|
211
|
+
super(`${status} ${error}`);
|
|
212
|
+
this.status = status;
|
|
213
|
+
this.error = error;
|
|
214
|
+
this.detail = detail;
|
|
215
|
+
}
|
|
216
|
+
status;
|
|
217
|
+
error;
|
|
218
|
+
detail;
|
|
219
|
+
name = "ApiError";
|
|
220
|
+
};
|
|
221
|
+
async function http(url, init, timeoutMs = TIMEOUT_MS) {
|
|
222
|
+
const headers = new Headers(init.headers);
|
|
223
|
+
headers.set("user-agent", USER_AGENT);
|
|
224
|
+
return fetch(url, { ...init, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
|
|
225
|
+
}
|
|
226
|
+
async function decodeError(response) {
|
|
227
|
+
const text = await response.text().catch(() => "");
|
|
228
|
+
let body;
|
|
229
|
+
try {
|
|
230
|
+
body = JSON.parse(text);
|
|
231
|
+
} catch {
|
|
232
|
+
body = { error: text.trim().slice(0, 300) || response.statusText || String(response.status) };
|
|
233
|
+
}
|
|
234
|
+
const error = body && typeof body === "object" && !Array.isArray(body) ? body.error : void 0;
|
|
235
|
+
return new ApiError(response.status, String(error || response.statusText || response.status), body);
|
|
236
|
+
}
|
|
237
|
+
async function readJson(response) {
|
|
238
|
+
if (response.status >= 300) {
|
|
239
|
+
if (response.status < 400) {
|
|
240
|
+
await response.body?.cancel().catch(() => void 0);
|
|
241
|
+
throw new ApiError(response.status, "unexpected redirect", response.headers.get("location"));
|
|
242
|
+
}
|
|
243
|
+
throw await decodeError(response);
|
|
244
|
+
}
|
|
245
|
+
const text = await response.text();
|
|
246
|
+
return text ? JSON.parse(text) : {};
|
|
247
|
+
}
|
|
248
|
+
async function streamOf(response) {
|
|
249
|
+
if (response.status >= 300) {
|
|
250
|
+
if (response.status < 400) throw new ApiError(response.status, "unexpected redirect");
|
|
251
|
+
throw await decodeError(response);
|
|
252
|
+
}
|
|
253
|
+
const body = response.body;
|
|
254
|
+
if (!body) return (async function* () {
|
|
255
|
+
})();
|
|
256
|
+
return body;
|
|
257
|
+
}
|
|
258
|
+
function signedPath(url) {
|
|
259
|
+
const parts = new URL(url);
|
|
260
|
+
return parts.pathname + (parts.search && parts.search !== "?" ? parts.search : "");
|
|
261
|
+
}
|
|
262
|
+
var PublicClient = class {
|
|
263
|
+
constructor(baseUrl, wallet = null) {
|
|
264
|
+
this.baseUrl = baseUrl;
|
|
265
|
+
this.wallet = wallet;
|
|
266
|
+
}
|
|
267
|
+
baseUrl;
|
|
268
|
+
wallet;
|
|
269
|
+
get apiRoot() {
|
|
270
|
+
return this.baseUrl.replace(/\/+$/, "") + "/api/app/v1";
|
|
271
|
+
}
|
|
272
|
+
needWallet() {
|
|
273
|
+
if (!this.wallet) throw new WalletMissing(`No CrowdCode wallet yet. Run \`npx crowdcode-mcp wallet init\` to create one.`);
|
|
274
|
+
return this.wallet;
|
|
275
|
+
}
|
|
276
|
+
async demand() {
|
|
277
|
+
return readJson(await http(this.baseUrl.replace(/\/+$/, "") + "/api/service-proposals", { method: "GET" }));
|
|
278
|
+
}
|
|
279
|
+
/** POST without payment and return the x402 offer we would pay (Base USDC `exact`). */
|
|
280
|
+
async quote(url, payload) {
|
|
281
|
+
const response = await http(url, {
|
|
282
|
+
method: "POST",
|
|
283
|
+
body: jsonBody(payload),
|
|
284
|
+
headers: { "content-type": "application/json" }
|
|
285
|
+
});
|
|
286
|
+
if (response.status !== 402) {
|
|
287
|
+
if (response.status >= 400) throw await decodeError(response);
|
|
288
|
+
const text = (await response.text().catch(() => "")).slice(0, 300);
|
|
289
|
+
throw new ApiError(response.status, "expected a 402 payment challenge", text);
|
|
290
|
+
}
|
|
291
|
+
const required = await paymentRequired(response);
|
|
292
|
+
return { required, offer: pickBaseExact(required) };
|
|
293
|
+
}
|
|
294
|
+
/** Sign the quoted offer and POST again with `PAYMENT-SIGNATURE`. */
|
|
295
|
+
async pay(url, payload, quote) {
|
|
296
|
+
const wallet = this.needWallet();
|
|
297
|
+
const { required, offer } = quote;
|
|
298
|
+
const extra = offer.extra ?? {};
|
|
299
|
+
const { authorization, signature } = await wallet.authorizeTransfer({
|
|
300
|
+
to: String(offer.payTo),
|
|
301
|
+
value: BigInt(String(offer.amount)),
|
|
302
|
+
validSeconds: Math.min(Math.trunc(Number(offer.maxTimeoutSeconds || 300)), 1500),
|
|
303
|
+
asset: String(offer.asset),
|
|
304
|
+
chainId: Number(String(offer.network).split(":")[1]),
|
|
305
|
+
tokenName: extra.name ?? "USD Coin",
|
|
306
|
+
tokenVersion: extra.version ?? "2"
|
|
307
|
+
});
|
|
308
|
+
const payment = {
|
|
309
|
+
x402Version: required.x402Version ?? 2,
|
|
310
|
+
resource: required.resource ?? null,
|
|
311
|
+
accepted: offer,
|
|
312
|
+
payload: { authorization, signature }
|
|
313
|
+
};
|
|
314
|
+
if (required.extensions) payment.extensions = required.extensions;
|
|
315
|
+
const header = Buffer.from(pyDumps(payment, { compact: true })).toString("base64");
|
|
316
|
+
const response = await http(
|
|
317
|
+
url,
|
|
318
|
+
{
|
|
319
|
+
method: "POST",
|
|
320
|
+
body: jsonBody(payload),
|
|
321
|
+
headers: { "content-type": "application/json", "PAYMENT-SIGNATURE": header }
|
|
322
|
+
},
|
|
323
|
+
PAY_TIMEOUT_MS
|
|
324
|
+
);
|
|
325
|
+
let settlement = null;
|
|
326
|
+
const raw = response.headers.get("payment-response") ?? response.headers.get("x-payment-response");
|
|
327
|
+
if (raw) {
|
|
328
|
+
try {
|
|
329
|
+
settlement = JSON.parse(Buffer.from(raw, "base64").toString("utf8"));
|
|
330
|
+
} catch {
|
|
331
|
+
settlement = null;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const text = await response.text().catch(() => "");
|
|
335
|
+
let body;
|
|
336
|
+
try {
|
|
337
|
+
body = JSON.parse(text);
|
|
338
|
+
} catch {
|
|
339
|
+
body = { error: text.slice(0, 300) };
|
|
340
|
+
}
|
|
341
|
+
if (response.status === 402) {
|
|
342
|
+
try {
|
|
343
|
+
const challenge = await paymentRequired(response, body);
|
|
344
|
+
body = { error: challenge.error || "payment refused", ...body ?? {} };
|
|
345
|
+
} catch {
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return { status: response.status, body, settlement };
|
|
349
|
+
}
|
|
350
|
+
/** USDC on Base held by `address`, in dollars: one read-only `eth_call`. */
|
|
351
|
+
async usdcBalance(rpcUrl, address) {
|
|
352
|
+
const data = "0x70a08231" + address.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
353
|
+
const call = { jsonrpc: "2.0", id: 1, method: "eth_call", params: [{ to: BASE_USDC, data }, "latest"] };
|
|
354
|
+
const response = await http(rpcUrl, {
|
|
355
|
+
method: "POST",
|
|
356
|
+
body: JSON.stringify(call),
|
|
357
|
+
headers: { "content-type": "application/json" }
|
|
358
|
+
});
|
|
359
|
+
const body = await readJson(response);
|
|
360
|
+
const result = body?.result;
|
|
361
|
+
if (typeof result !== "string") throw new ApiError(502, "base rpc returned no result", body);
|
|
362
|
+
return unitsToUsd(BigInt(result === "0x" ? "0x0" : result));
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
var WalletClient = class extends PublicClient {
|
|
366
|
+
async signed(method, path, payload, extraHeaders = {}) {
|
|
367
|
+
const wallet = this.needWallet();
|
|
368
|
+
const url = this.apiRoot + path;
|
|
369
|
+
const body = jsonBody(payload);
|
|
370
|
+
const headers = {
|
|
371
|
+
...extraHeaders,
|
|
372
|
+
...await wallet.signRequest(method, signedPath(url), body)
|
|
373
|
+
};
|
|
374
|
+
if (body.length) headers["content-type"] = "application/json";
|
|
375
|
+
const response = await http(url, { method: method.toUpperCase(), headers, body: body.length ? body : void 0 });
|
|
376
|
+
return readJson(response);
|
|
377
|
+
}
|
|
378
|
+
async signedStream(path) {
|
|
379
|
+
const wallet = this.needWallet();
|
|
380
|
+
const url = this.apiRoot + path;
|
|
381
|
+
const headers = await wallet.signRequest("GET", signedPath(url), new Uint8Array());
|
|
382
|
+
return streamOf(await http(url, { method: "GET", headers }, STREAM_TIMEOUT_MS));
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
async function paymentRequired(response, parsedBody) {
|
|
386
|
+
const raw = response.headers.get("payment-required");
|
|
387
|
+
if (raw) {
|
|
388
|
+
try {
|
|
389
|
+
return JSON.parse(Buffer.from(raw, "base64").toString("utf8"));
|
|
390
|
+
} catch {
|
|
391
|
+
throw new ApiError(402, "unreadable PAYMENT-REQUIRED header");
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
let body = parsedBody;
|
|
395
|
+
if (body === void 0) {
|
|
396
|
+
try {
|
|
397
|
+
body = JSON.parse(await response.text());
|
|
398
|
+
} catch {
|
|
399
|
+
throw new ApiError(402, "402 without a payment challenge");
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (!body || typeof body !== "object" || !("accepts" in body)) {
|
|
403
|
+
throw new ApiError(402, "402 without a payment challenge", body);
|
|
404
|
+
}
|
|
405
|
+
return body;
|
|
406
|
+
}
|
|
407
|
+
function pickBaseExact(required) {
|
|
408
|
+
for (const offer of required.accepts ?? []) {
|
|
409
|
+
if (offer?.scheme === "exact" && offer.network === BASE_CAIP2 && String(offer.asset ?? "").toLowerCase() === BASE_USDC.toLowerCase()) {
|
|
410
|
+
if (!("amount" in offer) && "maxAmountRequired" in offer) return { ...offer, amount: offer.maxAmountRequired };
|
|
411
|
+
return offer;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
throw new ApiError(402, "no x402 exact USDC-on-Base offer in the challenge", required.accepts);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// src/agents/home.ts
|
|
418
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
419
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from "fs/promises";
|
|
420
|
+
import { homedir } from "os";
|
|
421
|
+
import { join } from "path";
|
|
422
|
+
function crowdcodeHome(env = process.env) {
|
|
423
|
+
return env.CROWDCODE_HOME?.trim() || join(homedir(), ".crowdcode");
|
|
424
|
+
}
|
|
425
|
+
var CREDENTIALS_FILE = "credentials.json";
|
|
426
|
+
var CONFIG_FILE = "config.json";
|
|
427
|
+
var STATE_FILE = "state.json";
|
|
428
|
+
async function readJsonFile(path) {
|
|
429
|
+
let raw;
|
|
430
|
+
try {
|
|
431
|
+
raw = await readFile(path, "utf8");
|
|
432
|
+
} catch (err) {
|
|
433
|
+
if (err.code === "ENOENT") return void 0;
|
|
434
|
+
throw err;
|
|
435
|
+
}
|
|
436
|
+
try {
|
|
437
|
+
return JSON.parse(raw);
|
|
438
|
+
} catch {
|
|
439
|
+
return void 0;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
async function writePrivateJson(home, name, value) {
|
|
443
|
+
await mkdir(home, { recursive: true, mode: 448 });
|
|
444
|
+
await chmod(home, 448);
|
|
445
|
+
const path = join(home, name);
|
|
446
|
+
const temporary = join(home, `.${name}.${randomBytes2(6).toString("hex")}.tmp`);
|
|
447
|
+
try {
|
|
448
|
+
await writeFile(temporary, JSON.stringify(value, null, 2) + "\n", { mode: 384, flag: "wx" });
|
|
449
|
+
await chmod(temporary, 384);
|
|
450
|
+
await rename(temporary, path);
|
|
451
|
+
} catch (err) {
|
|
452
|
+
await rm(temporary, { force: true });
|
|
453
|
+
throw err;
|
|
454
|
+
}
|
|
455
|
+
return path;
|
|
456
|
+
}
|
|
457
|
+
async function removeFile(home, name) {
|
|
458
|
+
try {
|
|
459
|
+
await rm(join(home, name));
|
|
460
|
+
return true;
|
|
461
|
+
} catch (err) {
|
|
462
|
+
if (err.code === "ENOENT") return false;
|
|
463
|
+
throw err;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
async function recentTasks(home) {
|
|
467
|
+
const state = await readJsonFile(join(home, STATE_FILE));
|
|
468
|
+
return Array.isArray(state?.tasks) ? state.tasks : [];
|
|
469
|
+
}
|
|
470
|
+
async function rememberTask(home, record) {
|
|
471
|
+
const state = await readJsonFile(join(home, STATE_FILE)) ?? {};
|
|
472
|
+
const tasks = (Array.isArray(state.tasks) ? state.tasks : []).filter(
|
|
473
|
+
(t) => t?.task_id !== record.task_id
|
|
474
|
+
);
|
|
475
|
+
tasks.push(record);
|
|
476
|
+
await writePrivateJson(home, STATE_FILE, { ...state, tasks: tasks.slice(-50) });
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// src/agents/account.ts
|
|
480
|
+
import { spawn } from "child_process";
|
|
481
|
+
import { createHash as createHash2, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
482
|
+
import { createServer } from "http";
|
|
483
|
+
import { join as join2 } from "path";
|
|
484
|
+
var CLIENT_ID = "crowdcode-mcp";
|
|
485
|
+
var SCOPE = "read tasks transfers withdraw_to_main services files";
|
|
486
|
+
var LOGIN_TIMEOUT_MS = 5 * 6e4;
|
|
487
|
+
var EXPIRY_SKEW_SECONDS = 30;
|
|
488
|
+
var MODES = ["auto", "account", "wallet"];
|
|
489
|
+
function origin(url) {
|
|
490
|
+
return url.replace(/\/+$/, "");
|
|
491
|
+
}
|
|
492
|
+
function base64url(bytes) {
|
|
493
|
+
return Buffer.from(bytes).toString("base64url");
|
|
494
|
+
}
|
|
495
|
+
function pkcePair() {
|
|
496
|
+
const verifier = base64url(randomBytes3(48));
|
|
497
|
+
return { verifier, challenge: pkceChallenge(verifier) };
|
|
498
|
+
}
|
|
499
|
+
function pkceChallenge(verifier) {
|
|
500
|
+
return base64url(createHash2("sha256").update(verifier).digest());
|
|
501
|
+
}
|
|
502
|
+
function randomState() {
|
|
503
|
+
return base64url(randomBytes3(24));
|
|
504
|
+
}
|
|
505
|
+
function sameSecret(a, b) {
|
|
506
|
+
const x = Buffer.from(a);
|
|
507
|
+
const y = Buffer.from(b);
|
|
508
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
509
|
+
}
|
|
510
|
+
async function readCredentials(home, baseUrl) {
|
|
511
|
+
const data = await readJsonFile(join2(home, CREDENTIALS_FILE));
|
|
512
|
+
if (!data || typeof data.access_token !== "string" || !data.access_token || typeof data.base_url !== "string") {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
if (baseUrl !== void 0 && origin(data.base_url) !== origin(baseUrl)) return null;
|
|
516
|
+
return {
|
|
517
|
+
access_token: data.access_token,
|
|
518
|
+
refresh_token: typeof data.refresh_token === "string" ? data.refresh_token : null,
|
|
519
|
+
expires_at: typeof data.expires_at === "number" ? data.expires_at : null,
|
|
520
|
+
scope: typeof data.scope === "string" ? data.scope : null,
|
|
521
|
+
base_url: origin(data.base_url)
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
async function saveCredentials(home, credentials) {
|
|
525
|
+
return writePrivateJson(home, CREDENTIALS_FILE, credentials);
|
|
526
|
+
}
|
|
527
|
+
async function deleteCredentials(home) {
|
|
528
|
+
return removeFile(home, CREDENTIALS_FILE);
|
|
529
|
+
}
|
|
530
|
+
function fromTokenResponse(body, baseUrl, previous) {
|
|
531
|
+
if (!body || typeof body.access_token !== "string" || !body.access_token) {
|
|
532
|
+
throw new ApiError(502, "the token endpoint returned no access_token", body);
|
|
533
|
+
}
|
|
534
|
+
const expiresIn = Number(body.expires_in);
|
|
535
|
+
return {
|
|
536
|
+
access_token: body.access_token,
|
|
537
|
+
refresh_token: typeof body.refresh_token === "string" ? body.refresh_token : previous?.refresh_token ?? null,
|
|
538
|
+
expires_at: Number.isFinite(expiresIn) && expiresIn > 0 ? Math.floor(Date.now() / 1e3) + expiresIn : null,
|
|
539
|
+
scope: typeof body.scope === "string" ? body.scope : previous?.scope ?? null,
|
|
540
|
+
base_url: origin(baseUrl)
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
async function tokenRequest(baseUrl, form) {
|
|
544
|
+
return http(origin(baseUrl) + "/api/app/oauth/token", {
|
|
545
|
+
method: "POST",
|
|
546
|
+
body: new URLSearchParams(form).toString(),
|
|
547
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
async function refreshCredentials(home, credentials) {
|
|
551
|
+
if (!credentials.refresh_token) {
|
|
552
|
+
await deleteCredentials(home);
|
|
553
|
+
throw new NotSignedIn(`The CrowdCode sign-in expired. Sign in again: ${LOGIN_COMMAND}`);
|
|
554
|
+
}
|
|
555
|
+
const response = await tokenRequest(credentials.base_url, {
|
|
556
|
+
grant_type: "refresh_token",
|
|
557
|
+
refresh_token: credentials.refresh_token,
|
|
558
|
+
client_id: CLIENT_ID
|
|
559
|
+
});
|
|
560
|
+
if (response.status >= 400 && response.status < 500) {
|
|
561
|
+
await response.body?.cancel().catch(() => void 0);
|
|
562
|
+
await deleteCredentials(home);
|
|
563
|
+
throw new NotSignedIn(`The CrowdCode sign-in was revoked or expired. Sign in again: ${LOGIN_COMMAND}`);
|
|
564
|
+
}
|
|
565
|
+
const next = fromTokenResponse(await readJson(response), credentials.base_url, credentials);
|
|
566
|
+
await saveCredentials(home, next);
|
|
567
|
+
return next;
|
|
568
|
+
}
|
|
569
|
+
var openInBrowser = (url) => {
|
|
570
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
|
|
571
|
+
try {
|
|
572
|
+
const child = spawn(command, args, {
|
|
573
|
+
stdio: "ignore",
|
|
574
|
+
detached: true,
|
|
575
|
+
windowsVerbatimArguments: process.platform === "win32"
|
|
576
|
+
});
|
|
577
|
+
child.on("error", () => void 0);
|
|
578
|
+
child.unref();
|
|
579
|
+
} catch {
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>CrowdCode</title>
|
|
583
|
+
<body style="font-family:system-ui;margin:3em">
|
|
584
|
+
<h1>Signed in to CrowdCode</h1><p>crowdcode-mcp is connected. You can close this tab.</p></body>`;
|
|
585
|
+
var FAILED_PAGE = (why) => `<!doctype html><meta charset="utf-8"><title>CrowdCode</title>
|
|
586
|
+
<body style="font-family:system-ui;margin:3em"><h1>Not signed in</h1><p>${why.replace(/[<>&"]/g, "")}</p></body>`;
|
|
587
|
+
async function login(options) {
|
|
588
|
+
const baseUrl = origin(options.baseUrl);
|
|
589
|
+
const log = options.log ?? ((line) => process.stderr.write(line + "\n"));
|
|
590
|
+
const { verifier, challenge } = pkcePair();
|
|
591
|
+
const state = randomState();
|
|
592
|
+
let settle;
|
|
593
|
+
const codePromise = new Promise((resolve, reject) => {
|
|
594
|
+
settle = { resolve, reject };
|
|
595
|
+
});
|
|
596
|
+
const server = createServer((req, res) => {
|
|
597
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
598
|
+
if (url.pathname !== "/callback") {
|
|
599
|
+
res.writeHead(404, { "content-type": "text/plain" }).end("not found");
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
const error = url.searchParams.get("error");
|
|
603
|
+
const code = url.searchParams.get("code");
|
|
604
|
+
const returned = url.searchParams.get("state") ?? "";
|
|
605
|
+
let failure = null;
|
|
606
|
+
if (!sameSecret(returned, state)) failure = "The sign-in answer did not match this login (state mismatch).";
|
|
607
|
+
else if (error) failure = `CrowdCode did not sign you in: ${error}${url.searchParams.get("error_description") ? ` (${url.searchParams.get("error_description")})` : ""}.`;
|
|
608
|
+
else if (!code) failure = "The sign-in answer carried no authorization code.";
|
|
609
|
+
if (failure) {
|
|
610
|
+
res.writeHead(400, { "content-type": "text/html; charset=utf-8" }).end(FAILED_PAGE(failure));
|
|
611
|
+
settle.reject(new ToolError(failure));
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(DONE_PAGE);
|
|
615
|
+
settle.resolve(code);
|
|
616
|
+
});
|
|
617
|
+
await new Promise((resolve, reject) => {
|
|
618
|
+
server.once("error", reject);
|
|
619
|
+
server.listen(0, "127.0.0.1", () => resolve());
|
|
620
|
+
});
|
|
621
|
+
const port = server.address().port;
|
|
622
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
623
|
+
const query = new URLSearchParams({
|
|
624
|
+
response_type: "code",
|
|
625
|
+
client_id: CLIENT_ID,
|
|
626
|
+
redirect_uri: redirectUri,
|
|
627
|
+
scope: SCOPE,
|
|
628
|
+
state,
|
|
629
|
+
code_challenge: challenge,
|
|
630
|
+
code_challenge_method: "S256"
|
|
631
|
+
});
|
|
632
|
+
const authorizeUrl = `${baseUrl}/connect?${query.toString()}`;
|
|
633
|
+
const timer = setTimeout(
|
|
634
|
+
() => settle.reject(new ToolError("Timed out waiting for the CrowdCode sign-in (5 minutes). Run login again.")),
|
|
635
|
+
options.timeoutMs ?? LOGIN_TIMEOUT_MS
|
|
636
|
+
);
|
|
637
|
+
try {
|
|
638
|
+
log("Sign in to CrowdCode in your browser. If it does not open, visit:");
|
|
639
|
+
log("");
|
|
640
|
+
log(` ${authorizeUrl}`);
|
|
641
|
+
log("");
|
|
642
|
+
void Promise.resolve().then(() => (options.openBrowser ?? openInBrowser)(authorizeUrl)).catch(() => void 0);
|
|
643
|
+
const code = await codePromise;
|
|
644
|
+
const response = await tokenRequest(baseUrl, {
|
|
645
|
+
grant_type: "authorization_code",
|
|
646
|
+
code,
|
|
647
|
+
code_verifier: verifier,
|
|
648
|
+
redirect_uri: redirectUri,
|
|
649
|
+
client_id: CLIENT_ID
|
|
650
|
+
});
|
|
651
|
+
if (response.status >= 400) throw await decodeError(response);
|
|
652
|
+
const credentials = fromTokenResponse(await readJson(response), baseUrl);
|
|
653
|
+
await saveCredentials(options.home, credentials);
|
|
654
|
+
return credentials;
|
|
655
|
+
} finally {
|
|
656
|
+
clearTimeout(timer);
|
|
657
|
+
server.closeAllConnections?.();
|
|
658
|
+
server.close();
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
async function logout(home) {
|
|
662
|
+
const credentials = await readCredentials(home);
|
|
663
|
+
if (!credentials) {
|
|
664
|
+
await deleteCredentials(home);
|
|
665
|
+
return { signedIn: false, revoked: false };
|
|
666
|
+
}
|
|
667
|
+
let revoked = false;
|
|
668
|
+
try {
|
|
669
|
+
const response = await http(credentials.base_url + "/api/app/v1/connection/revoke", {
|
|
670
|
+
method: "POST",
|
|
671
|
+
body: jsonBody({}),
|
|
672
|
+
headers: { authorization: `Bearer ${credentials.access_token}`, "content-type": "application/json" }
|
|
673
|
+
});
|
|
674
|
+
revoked = response.ok;
|
|
675
|
+
await response.body?.cancel().catch(() => void 0);
|
|
676
|
+
} catch {
|
|
677
|
+
revoked = false;
|
|
678
|
+
} finally {
|
|
679
|
+
await deleteCredentials(home);
|
|
680
|
+
}
|
|
681
|
+
return { signedIn: true, revoked };
|
|
682
|
+
}
|
|
683
|
+
async function modeSetting(env, home) {
|
|
684
|
+
const fromEnv = env.CROWDCODE_MODE?.trim().toLowerCase();
|
|
685
|
+
if (fromEnv) return { setting: checkMode(fromEnv), from: "CROWDCODE_MODE" };
|
|
686
|
+
const config = await readJsonFile(join2(home, CONFIG_FILE));
|
|
687
|
+
if (typeof config?.mode === "string" && config.mode) {
|
|
688
|
+
return { setting: checkMode(config.mode.toLowerCase()), from: "config" };
|
|
689
|
+
}
|
|
690
|
+
return { setting: "auto", from: "default" };
|
|
691
|
+
}
|
|
692
|
+
function checkMode(value) {
|
|
693
|
+
if (!MODES.includes(value)) {
|
|
694
|
+
throw new ToolError(`the mode setting must be one of ${MODES.join(", ")}`);
|
|
695
|
+
}
|
|
696
|
+
return value;
|
|
697
|
+
}
|
|
698
|
+
async function saveModeSetting(home, mode) {
|
|
699
|
+
const checked = checkMode(mode.trim().toLowerCase());
|
|
700
|
+
const config = await readJsonFile(join2(home, CONFIG_FILE)) ?? {};
|
|
701
|
+
await writePrivateJson(home, CONFIG_FILE, { ...config, mode: checked });
|
|
702
|
+
return checked;
|
|
703
|
+
}
|
|
704
|
+
var AccountClient = class {
|
|
705
|
+
constructor(baseUrl, home) {
|
|
706
|
+
this.baseUrl = baseUrl;
|
|
707
|
+
this.home = home;
|
|
708
|
+
}
|
|
709
|
+
baseUrl;
|
|
710
|
+
home;
|
|
711
|
+
wallet = null;
|
|
712
|
+
get apiRoot() {
|
|
713
|
+
return origin(this.baseUrl) + "/api/app/v1";
|
|
714
|
+
}
|
|
715
|
+
async credentials() {
|
|
716
|
+
const credentials = await readCredentials(this.home, this.baseUrl);
|
|
717
|
+
if (!credentials) {
|
|
718
|
+
throw new NotSignedIn(`Not signed in to a CrowdCode account at ${origin(this.baseUrl)}.`);
|
|
719
|
+
}
|
|
720
|
+
if (credentials.expires_at !== null && Date.now() / 1e3 >= credentials.expires_at - EXPIRY_SKEW_SECONDS) {
|
|
721
|
+
return refreshCredentials(this.home, credentials);
|
|
722
|
+
}
|
|
723
|
+
return credentials;
|
|
724
|
+
}
|
|
725
|
+
async call(method, path, payload, extraHeaders, timeoutMs) {
|
|
726
|
+
const body = jsonBody(payload);
|
|
727
|
+
const send = (token) => {
|
|
728
|
+
const headers = { ...extraHeaders, authorization: `Bearer ${token}` };
|
|
729
|
+
if (body.length) headers["content-type"] = "application/json";
|
|
730
|
+
return http(
|
|
731
|
+
this.apiRoot + path,
|
|
732
|
+
{ method: method.toUpperCase(), headers, body: body.length ? body : void 0 },
|
|
733
|
+
timeoutMs
|
|
734
|
+
);
|
|
735
|
+
};
|
|
736
|
+
let credentials = await this.credentials();
|
|
737
|
+
let response = await send(credentials.access_token);
|
|
738
|
+
if (response.status === 401) {
|
|
739
|
+
const error = await decodeError(response);
|
|
740
|
+
if (error.error !== "invalid_token") throw error;
|
|
741
|
+
credentials = await refreshCredentials(this.home, credentials);
|
|
742
|
+
response = await send(credentials.access_token);
|
|
743
|
+
}
|
|
744
|
+
return response;
|
|
745
|
+
}
|
|
746
|
+
async signed(method, path, payload, extraHeaders = {}) {
|
|
747
|
+
return readJson(await this.call(method, path, payload, extraHeaders));
|
|
748
|
+
}
|
|
749
|
+
async signedStream(path) {
|
|
750
|
+
return streamOf(await this.call("GET", path, void 0, {}, STREAM_TIMEOUT_MS));
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
|
|
754
|
+
export {
|
|
755
|
+
ToolError,
|
|
756
|
+
UncertainError,
|
|
757
|
+
WalletMissing,
|
|
758
|
+
NotSignedIn,
|
|
759
|
+
LOGIN_COMMAND,
|
|
760
|
+
WALLET_INIT_COMMAND,
|
|
761
|
+
Signer,
|
|
762
|
+
usdToUnits,
|
|
763
|
+
unitsToUsd,
|
|
764
|
+
pyFloat,
|
|
765
|
+
pyDumps,
|
|
766
|
+
ApiError,
|
|
767
|
+
PublicClient,
|
|
768
|
+
WalletClient,
|
|
769
|
+
crowdcodeHome,
|
|
770
|
+
CREDENTIALS_FILE,
|
|
771
|
+
recentTasks,
|
|
772
|
+
rememberTask,
|
|
773
|
+
readCredentials,
|
|
774
|
+
login,
|
|
775
|
+
logout,
|
|
776
|
+
modeSetting,
|
|
777
|
+
saveModeSetting,
|
|
778
|
+
AccountClient
|
|
779
|
+
};
|
|
780
|
+
//# sourceMappingURL=chunk-CSAFC6V4.js.map
|