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.
@@ -0,0 +1,1352 @@
1
+ import {
2
+ getConfig
3
+ } from "./chunk-CF6JGOQF.js";
4
+ import {
5
+ loadWallet
6
+ } from "./chunk-2Y65AAP3.js";
7
+ import {
8
+ AccountClient,
9
+ ApiError,
10
+ LOGIN_COMMAND,
11
+ NotSignedIn,
12
+ PublicClient,
13
+ Signer,
14
+ ToolError,
15
+ UncertainError,
16
+ WALLET_INIT_COMMAND,
17
+ WalletClient,
18
+ WalletMissing,
19
+ crowdcodeHome,
20
+ modeSetting,
21
+ pyDumps,
22
+ pyFloat,
23
+ readCredentials,
24
+ recentTasks,
25
+ rememberTask,
26
+ unitsToUsd,
27
+ usdToUnits
28
+ } from "./chunk-CSAFC6V4.js";
29
+
30
+ // src/agents/tools.ts
31
+ import { createHash } from "crypto";
32
+ import { mkdir, realpath } from "fs/promises";
33
+
34
+ // src/agents/contract.ts
35
+ import { z } from "zod";
36
+
37
+ // ../../spec/agent-tools.json
38
+ var agent_tools_default = {
39
+ version: 1,
40
+ description: "The CrowdCode agent tools every client exposes (Hermes plugin, crowdcode-mcp for Codex and Claude Code): names, arguments and the fields each result carries. design-docs/AGENT_CLIENTS.md in sr33j/crowdcode.",
41
+ tools: [
42
+ {
43
+ name: "crowdcode_wallet",
44
+ description: "Show how this Hermes install reaches CrowdCode. In wallet mode: its Base address, USDC balance (one read-only Base RPC call), today's spending against the daily cap, and how to fund it. In account mode (signed in with /crowdcode login): the account's main wallet, what the sign-in allows and its daily cap. With init=true, create the wallet first if there is none (the key is stored in Hermes's credential store and never shown).",
45
+ input_schema: {
46
+ type: "object",
47
+ properties: {
48
+ init: {
49
+ type: "boolean",
50
+ description: "Create the wallet if it does not exist yet."
51
+ }
52
+ },
53
+ required: []
54
+ },
55
+ result_fields: [
56
+ "address",
57
+ "owner",
58
+ "usdc_base",
59
+ "fund"
60
+ ]
61
+ },
62
+ {
63
+ name: "crowdcode_agents",
64
+ description: "List the CrowdCode cloud agents this wallet (or the signed-in account) owns with their USDC balances on Base, Solana and Tempo, or show one agent in detail. Read-only.",
65
+ input_schema: {
66
+ type: "object",
67
+ properties: {
68
+ agent_id: {
69
+ type: "string",
70
+ description: "CrowdCode agent id (from crowdcode_agents or crowdcode_create_agent)."
71
+ }
72
+ },
73
+ required: []
74
+ },
75
+ result_fields: [],
76
+ result_shapes: {
77
+ "without agent_id": [
78
+ "agents"
79
+ ],
80
+ "with agent_id": [
81
+ "agent"
82
+ ]
83
+ }
84
+ },
85
+ {
86
+ name: "crowdcode_create_agent",
87
+ description: "Create a CrowdCode cloud agent owned by this wallet. Pays CrowdCode's creation price (about $0.35 USDC on Base) with an x402 payment signed by the wallet. The agent gets its own wallets on Base, Solana and Tempo, can run tasks, call paid x402/MPP services and deploy paid services of its own.",
88
+ input_schema: {
89
+ type: "object",
90
+ properties: {
91
+ name: {
92
+ type: "string",
93
+ description: "3-40 characters."
94
+ },
95
+ model: {
96
+ type: "string",
97
+ description: "Optional CrowdCode model catalog id."
98
+ },
99
+ instructions: {
100
+ type: "string",
101
+ description: "Optional standing instructions, at most 4000 characters."
102
+ },
103
+ max_price_usd: {
104
+ type: "number",
105
+ description: "Refuse to pay more than this. Default 0.50."
106
+ }
107
+ },
108
+ required: [
109
+ "name"
110
+ ]
111
+ },
112
+ result_fields: [
113
+ "agent_id",
114
+ "status",
115
+ "paid_usd",
116
+ "addresses"
117
+ ]
118
+ },
119
+ {
120
+ name: "crowdcode_fund_agent",
121
+ description: "Send USDC on Base from this wallet to one of its agents. Gasless: the wallet signs an EIP-3009 authorization for exactly this amount to the agent's own address and CrowdCode's relayer submits it. Minimum $0.50. In account mode nothing moves from Hermes: it returns the crowdcode.app link where the owner approves the deposit from their main wallet; give the user that link.",
122
+ input_schema: {
123
+ type: "object",
124
+ properties: {
125
+ agent_id: {
126
+ type: "string",
127
+ description: "CrowdCode agent id (from crowdcode_agents or crowdcode_create_agent)."
128
+ },
129
+ amount_usd: {
130
+ type: "number",
131
+ description: "USDC to send, e.g. 1.00."
132
+ }
133
+ },
134
+ required: [
135
+ "agent_id",
136
+ "amount_usd"
137
+ ]
138
+ },
139
+ result_fields: [
140
+ "agent_id",
141
+ "amount_usd"
142
+ ],
143
+ result_shapes: {
144
+ "wallet mode": [
145
+ "tx_hash"
146
+ ],
147
+ "account mode": [
148
+ "moved",
149
+ "approve_url"
150
+ ]
151
+ }
152
+ },
153
+ {
154
+ name: "crowdcode_run_task",
155
+ description: "Give a CrowdCode agent a task. It runs in the cloud and spends from the agent's own wallet, never more than budget_usd: it can research, write code, buy x402/MPP services and deploy paid services (deploy_service). Waits for the result by default and returns the answer, the amount spent, every purchase with its transaction, and any files it produced.",
156
+ input_schema: {
157
+ type: "object",
158
+ properties: {
159
+ agent_id: {
160
+ type: "string",
161
+ description: "CrowdCode agent id (from crowdcode_agents or crowdcode_create_agent)."
162
+ },
163
+ prompt: {
164
+ type: "string",
165
+ description: "The task, at most 20000 characters."
166
+ },
167
+ budget_usd: {
168
+ type: "number",
169
+ description: "Required spending cap for this task in USD."
170
+ },
171
+ model: {
172
+ type: "string",
173
+ description: "Optional model id for this task."
174
+ },
175
+ wait: {
176
+ type: "boolean",
177
+ description: "Wait for completion (default true)."
178
+ },
179
+ timeout_seconds: {
180
+ type: "number",
181
+ description: "How long to wait before returning (default 600)."
182
+ }
183
+ },
184
+ required: [
185
+ "agent_id",
186
+ "prompt",
187
+ "budget_usd"
188
+ ]
189
+ },
190
+ result_fields: [
191
+ "task_id",
192
+ "agent_id",
193
+ "status",
194
+ "answer",
195
+ "spent_usd",
196
+ "purchases",
197
+ "files"
198
+ ]
199
+ },
200
+ {
201
+ name: "crowdcode_task_status",
202
+ description: "Check a CrowdCode task: status, answer, spend, purchases and the files it produced (ids; download them with crowdcode_download). With cancel=true, cancel it first.",
203
+ input_schema: {
204
+ type: "object",
205
+ properties: {
206
+ agent_id: {
207
+ type: "string",
208
+ description: "CrowdCode agent id (from crowdcode_agents or crowdcode_create_agent)."
209
+ },
210
+ task_id: {
211
+ type: "string"
212
+ },
213
+ cancel: {
214
+ type: "boolean",
215
+ description: "Cancel the task."
216
+ }
217
+ },
218
+ required: [
219
+ "agent_id",
220
+ "task_id"
221
+ ]
222
+ },
223
+ result_fields: [
224
+ "task_id",
225
+ "agent_id",
226
+ "status",
227
+ "answer",
228
+ "spent_usd",
229
+ "purchases",
230
+ "files"
231
+ ]
232
+ },
233
+ {
234
+ name: "crowdcode_services",
235
+ description: "List the paid services an agent has deployed, with price, calls and USDC earned, or stop/start one.",
236
+ input_schema: {
237
+ type: "object",
238
+ properties: {
239
+ agent_id: {
240
+ type: "string",
241
+ description: "CrowdCode agent id (from crowdcode_agents or crowdcode_create_agent)."
242
+ },
243
+ action: {
244
+ type: "string",
245
+ enum: [
246
+ "list",
247
+ "stop",
248
+ "start"
249
+ ],
250
+ description: "Default list."
251
+ },
252
+ service_id: {
253
+ type: "string",
254
+ description: "Required for stop/start."
255
+ }
256
+ },
257
+ required: [
258
+ "agent_id"
259
+ ]
260
+ },
261
+ result_fields: [
262
+ "agent_id",
263
+ "services",
264
+ "total_earned_usd"
265
+ ]
266
+ },
267
+ {
268
+ name: "crowdcode_withdraw",
269
+ description: "Withdraw USDC from an agent. It can only go to this wallet (the agent's owner), never anywhere else. Minimum $0.50. In account mode nothing moves from Hermes: it returns the crowdcode.app link where the owner approves the deposit from their main wallet; give the user that link.",
270
+ input_schema: {
271
+ type: "object",
272
+ properties: {
273
+ agent_id: {
274
+ type: "string",
275
+ description: "CrowdCode agent id (from crowdcode_agents or crowdcode_create_agent)."
276
+ },
277
+ amount_usd: {
278
+ type: "number"
279
+ },
280
+ network: {
281
+ type: "string",
282
+ enum: [
283
+ "base",
284
+ "tempo"
285
+ ],
286
+ description: "Default base."
287
+ }
288
+ },
289
+ required: [
290
+ "agent_id",
291
+ "amount_usd"
292
+ ]
293
+ },
294
+ result_fields: [
295
+ "agent_id",
296
+ "amount_usd",
297
+ "network",
298
+ "tx_hash"
299
+ ]
300
+ },
301
+ {
302
+ name: "crowdcode_transfer",
303
+ description: "Move USDC between two agents this wallet owns, on one network. Minimum $0.50.",
304
+ input_schema: {
305
+ type: "object",
306
+ properties: {
307
+ from_agent_id: {
308
+ type: "string",
309
+ description: "CrowdCode agent id (from crowdcode_agents or crowdcode_create_agent)."
310
+ },
311
+ to_agent_id: {
312
+ type: "string",
313
+ description: "CrowdCode agent id (from crowdcode_agents or crowdcode_create_agent)."
314
+ },
315
+ amount_usd: {
316
+ type: "number"
317
+ },
318
+ network: {
319
+ type: "string",
320
+ enum: [
321
+ "base",
322
+ "solana",
323
+ "tempo"
324
+ ],
325
+ description: "Chain the USDC is on. Default base."
326
+ }
327
+ },
328
+ required: [
329
+ "from_agent_id",
330
+ "to_agent_id",
331
+ "amount_usd"
332
+ ]
333
+ },
334
+ result_fields: [
335
+ "from_agent_id",
336
+ "to_agent_id",
337
+ "amount_usd",
338
+ "network"
339
+ ]
340
+ },
341
+ {
342
+ name: "crowdcode_demand",
343
+ description: "What other AI agents have asked CrowdCode for and would pay for: public service proposals with the number of agents asking and the price they named. Good ideas for a paid service an agent could build. Read-only.",
344
+ input_schema: {
345
+ type: "object",
346
+ properties: {
347
+ query: {
348
+ type: "string",
349
+ description: "Optional keyword filter."
350
+ },
351
+ limit: {
352
+ type: "integer",
353
+ description: "How many to return (default 10, max 50)."
354
+ }
355
+ },
356
+ required: []
357
+ },
358
+ result_fields: [
359
+ "count",
360
+ "proposals"
361
+ ]
362
+ },
363
+ {
364
+ name: "crowdcode_files",
365
+ description: "List the files an agent has produced across its tasks (newest first): id, name, size, type, task. Read-only; nothing is downloaded.",
366
+ input_schema: {
367
+ type: "object",
368
+ properties: {
369
+ agent_id: {
370
+ type: "string",
371
+ description: "The agent's id or its name."
372
+ },
373
+ task_id: {
374
+ type: "string",
375
+ description: "Only files from this task."
376
+ }
377
+ },
378
+ required: [
379
+ "agent_id"
380
+ ]
381
+ },
382
+ result_fields: [
383
+ "agent_id",
384
+ "count",
385
+ "total_bytes",
386
+ "files"
387
+ ]
388
+ },
389
+ {
390
+ name: "crowdcode_download",
391
+ description: "Download an agent's files to this machine, only when the user asks for them. Saves into ./crowdcode-files/<agent name>/ under the session's working directory unless dest is given, keeps the file names (made safe), never overwrites (adds -1, -2\u2026), and returns the local paths and sizes.",
392
+ input_schema: {
393
+ type: "object",
394
+ properties: {
395
+ agent_id: {
396
+ type: "string",
397
+ description: "The agent's id or its name."
398
+ },
399
+ file_ids: {
400
+ type: "array",
401
+ items: {
402
+ type: "string"
403
+ },
404
+ description: 'File ids from crowdcode_files, or ["all"] for every file.'
405
+ },
406
+ task_id: {
407
+ type: "string",
408
+ description: `With "all": only that task's files.`
409
+ },
410
+ dest: {
411
+ type: "string",
412
+ description: "Folder to save into, inside the session's working directory (created if missing). A folder outside it asks the user first."
413
+ }
414
+ },
415
+ required: [
416
+ "agent_id",
417
+ "file_ids"
418
+ ]
419
+ },
420
+ result_fields: [
421
+ "agent_id",
422
+ "directory",
423
+ "downloaded",
424
+ "failed",
425
+ "total_bytes"
426
+ ]
427
+ },
428
+ {
429
+ name: "crowdcode_claim",
430
+ description: "Move agents this wallet owns into the user's CrowdCode account (claim). Signs a claim request with the wallet and returns a one-time link (valid 15 minutes) that the user opens while signed in to crowdcode.app to approve. Nothing moves until they approve; after that the agents belong to the account and withdraw only to its main wallet. Moves no money.",
431
+ input_schema: {
432
+ type: "object",
433
+ properties: {
434
+ agents: {
435
+ type: "array",
436
+ items: {
437
+ type: "string"
438
+ },
439
+ description: "Agent names or ids; omit for every agent this wallet owns."
440
+ }
441
+ },
442
+ required: []
443
+ },
444
+ result_fields: [
445
+ "approve_url",
446
+ "agents"
447
+ ]
448
+ }
449
+ ]
450
+ };
451
+
452
+ // src/agents/contract.ts
453
+ var CONTRACT = agent_tools_default;
454
+ var AGENT_TOOL_NAMES = [
455
+ "crowdcode_wallet",
456
+ "crowdcode_agents",
457
+ "crowdcode_create_agent",
458
+ "crowdcode_fund_agent",
459
+ "crowdcode_run_task",
460
+ "crowdcode_task_status",
461
+ "crowdcode_services",
462
+ "crowdcode_withdraw",
463
+ "crowdcode_transfer",
464
+ "crowdcode_demand",
465
+ "crowdcode_files",
466
+ "crowdcode_download",
467
+ "crowdcode_claim"
468
+ ];
469
+ var HOST_DESCRIPTIONS = {
470
+ crowdcode_wallet: {
471
+ tool: "Show how this machine reaches CrowdCode. In wallet mode: its Base address (the local AgentCash wallet, ~/.agentcash/wallet.json, the same key that signs CrowdCode reviews), USDC balance (one read-only Base RPC call) and how to fund it. In account mode (signed in with `npx crowdcode-mcp login`): the account's main wallet and what the sign-in allows. With init=true, create the wallet first if there is none (the key stays in that file and is never shown)."
472
+ },
473
+ crowdcode_fund_agent: {
474
+ tool: "Send USDC on Base from this wallet to one of its agents. Gasless: the wallet signs an EIP-3009 authorization for exactly this amount to the agent's own address and CrowdCode's relayer submits it. Minimum $0.50. In account mode nothing moves from here: it returns the crowdcode.app link where the owner approves the deposit from their main wallet; give the user that link."
475
+ },
476
+ crowdcode_withdraw: {
477
+ tool: "Withdraw USDC from an agent. It can only go to the agent's owner, never anywhere else: this wallet, or in account mode the account's main wallet. Minimum $0.50."
478
+ },
479
+ crowdcode_download: {
480
+ args: {
481
+ dest: "Folder to save into, relative to the session's working directory or absolute (created if missing). Default ./crowdcode-files/<agent name>/."
482
+ }
483
+ }
484
+ };
485
+ function toolContract(name) {
486
+ const tool = CONTRACT.tools.find((t) => t.name === name);
487
+ if (!tool) throw new Error(`spec/agent-tools.json has no tool ${name}`);
488
+ return tool;
489
+ }
490
+ function hostDescription(name) {
491
+ return HOST_DESCRIPTIONS[name]?.tool ?? toolContract(name).description;
492
+ }
493
+ function zodFor(property) {
494
+ switch (property.type) {
495
+ case "string":
496
+ return property.enum && property.enum.length > 0 ? z.enum(property.enum) : z.string();
497
+ case "number":
498
+ return z.number();
499
+ case "integer":
500
+ return z.number().int();
501
+ case "boolean":
502
+ return z.boolean();
503
+ case "array":
504
+ return z.array(z.string());
505
+ default:
506
+ throw new Error(`unsupported argument type ${property.type}`);
507
+ }
508
+ }
509
+ function zodShape(name) {
510
+ const tool = toolContract(name);
511
+ const required = new Set(tool.input_schema.required ?? []);
512
+ const overrides = HOST_DESCRIPTIONS[name]?.args ?? {};
513
+ const shape = {};
514
+ for (const [key, property] of Object.entries(tool.input_schema.properties)) {
515
+ let schema = zodFor(property);
516
+ const description = overrides[key] ?? property.description;
517
+ if (description) schema = schema.describe(description);
518
+ shape[key] = required.has(key) ? schema : schema.optional();
519
+ }
520
+ return shape;
521
+ }
522
+
523
+ // src/agents/files.ts
524
+ import { open, rm } from "fs/promises";
525
+ import { homedir } from "os";
526
+ import { basename, isAbsolute, join, resolve } from "path";
527
+ var DEFAULT_DIR = "crowdcode-files";
528
+ var PAGE = 200;
529
+ var MAX_LIST = 2e3;
530
+ var DEFAULT_MAX_DOWNLOAD_MB = 500;
531
+ var BAD = /[<>:"|?*\x00-\x1f\x7f]/g;
532
+ var RESERVED = /* @__PURE__ */ new Set([
533
+ "con",
534
+ "prn",
535
+ "aux",
536
+ "nul",
537
+ ...Array.from({ length: 9 }, (_, i) => `com${i + 1}`),
538
+ ...Array.from({ length: 9 }, (_, i) => `lpt${i + 1}`)
539
+ ]);
540
+ var PY_SPACE = "\\t\\n\\x0b\\x0c\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
541
+ var PY_STRIP = new RegExp(`^[${PY_SPACE}]+|[${PY_SPACE}]+$`, "g");
542
+ function rpartition(text) {
543
+ const at = text.lastIndexOf(".");
544
+ return at < 0 ? ["", "", text] : [text.slice(0, at), ".", text.slice(at + 1)];
545
+ }
546
+ function truncateUtf8(text, max) {
547
+ const bytes = Buffer.from(text, "utf8");
548
+ if (bytes.length <= max) return text;
549
+ let cut = max;
550
+ while (cut > 0 && (bytes[cut] & 192) === 128) cut--;
551
+ return bytes.subarray(0, cut).toString("utf8");
552
+ }
553
+ function safeName(name, fallback = "file") {
554
+ let text = String(name ?? "").normalize("NFC");
555
+ text = text.replace(/\\/g, "/").split("/").pop() ?? "";
556
+ text = text.replace(BAD, "_").replace(PY_STRIP, "").replace(/^\.+|\.+$/g, "");
557
+ if (!text || text === "." || text === "..") text = fallback;
558
+ const [stem, dot, ext] = rpartition(text);
559
+ if (RESERVED.has((dot ? stem : text).toLowerCase())) text = "_" + text;
560
+ if (Buffer.byteLength(text, "utf8") > 200) {
561
+ const keep = dot && [...ext].length <= 16 ? "." + ext : "";
562
+ text = truncateUtf8(text, 200 - Buffer.byteLength(keep, "utf8")) + keep;
563
+ }
564
+ return text;
565
+ }
566
+ async function uniquePath(directory, name) {
567
+ let [stem, dot, ext] = rpartition(name);
568
+ if (!dot || !stem) {
569
+ stem = name;
570
+ ext = "";
571
+ } else {
572
+ ext = "." + ext;
573
+ }
574
+ for (let n = 0; n < 1e4; n++) {
575
+ const candidate = join(directory, n === 0 ? name : `${stem}-${n}${ext}`);
576
+ try {
577
+ return { path: candidate, handle: await open(candidate, "wx", 420) };
578
+ } catch (err) {
579
+ if (err.code === "EEXIST") continue;
580
+ throw err;
581
+ }
582
+ }
583
+ throw new ToolError(`too many files named ${name} in ${directory}`);
584
+ }
585
+ function planDest(dest, agentName, base) {
586
+ const root = resolve(base);
587
+ if (!dest) return join(root, DEFAULT_DIR, safeName(agentName, "agent"));
588
+ let target = dest;
589
+ if (target === "~" || target.startsWith("~/") || target.startsWith("~\\")) target = join(homedir(), target.slice(1));
590
+ return isAbsolute(target) ? resolve(target) : resolve(root, target);
591
+ }
592
+ async function listFiles(api, agentId, taskId = "") {
593
+ const files = [];
594
+ let before = "";
595
+ while (files.length < MAX_LIST) {
596
+ const query = [`limit=${PAGE}`];
597
+ if (taskId) query.push(`task_id=${encodeURIComponent(taskId)}`);
598
+ if (before) query.push(`before=${encodeURIComponent(before)}`);
599
+ let page = await api.signed("GET", `/agents/${agentId}/files?${query.join("&")}`);
600
+ if (page && !Array.isArray(page) && typeof page === "object") page = page.files ?? [];
601
+ const rows = Array.isArray(page) ? page : [];
602
+ files.push(...rows);
603
+ const last = rows[rows.length - 1];
604
+ if (rows.length < PAGE || !last?.created_at) break;
605
+ before = String(last.created_at);
606
+ }
607
+ return files;
608
+ }
609
+ function tooLarge(name, maxBytes) {
610
+ return new ToolError(`${name} is larger than the ${Math.floor(maxBytes / 1e6)} MB download limit`);
611
+ }
612
+ async function downloadFile(api, agentId, file, directory, maxBytes) {
613
+ const name = safeName(file.name || file.path, `file-${file.id ?? "unknown"}`);
614
+ if (Number(file.size_bytes) > maxBytes) throw tooLarge(name, maxBytes);
615
+ const { path, handle } = await uniquePath(directory, name);
616
+ let written = 0;
617
+ try {
618
+ try {
619
+ const stream = await api.signedStream(`/agents/${agentId}/files/${file.id}`);
620
+ for await (const chunk of stream) {
621
+ written += chunk.length;
622
+ if (written > maxBytes) throw tooLarge(name, maxBytes);
623
+ await handle.write(chunk);
624
+ }
625
+ } finally {
626
+ await handle.close();
627
+ }
628
+ } catch (err) {
629
+ await rm(path, { force: true });
630
+ throw err;
631
+ }
632
+ return { id: file.id ?? null, name: basename(path), path, size_bytes: written };
633
+ }
634
+
635
+ // src/agents/tools.ts
636
+ var DEFAULT_BASE_URL = "https://crowdcode.app";
637
+ var DEFAULT_RPC = "https://mainnet.base.org";
638
+ var NETWORKS = ["base", "solana", "tempo"];
639
+ var WITHDRAW_NETWORKS = ["base", "tempo"];
640
+ var MIN_MOVE_USD = 0.5;
641
+ var DEFAULT_CREATE_MAX_USD = 0.5;
642
+ var TERMINAL = ["completed", "failed", "cancelled"];
643
+ var ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
644
+ var FUND_HINT = "Send USDC on Base to this address from any exchange or wallet (Coinbase, a Base wallet, etc.). No ETH is needed: agent creation is paid with a signed x402 authorization and deposits are gasless.";
645
+ var UNSURE = "CrowdCode may have received this; the outcome is unknown. Do NOT retry: check balances with crowdcode_agents (and crowdcode_wallet) first.";
646
+ var WALLET_HINT = `Run \`${WALLET_INIT_COMMAND}\` (or crowdcode_wallet with init=true), or \`${LOGIN_COMMAND}\` to use your CrowdCode account.`;
647
+ var ok = (data) => ({ ok: true, ...data });
648
+ var fail = (error, data = {}) => ({ ok: false, error, ...data });
649
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
650
+ var nowSeconds = () => Date.now() / 1e3;
651
+ function truthy(value) {
652
+ return !(value === void 0 || value === null || value === false || value === 0 || value === "" || Array.isArray(value) && value.length === 0);
653
+ }
654
+ function amount(args, key, fallback = 0) {
655
+ const raw = args[key];
656
+ if (!truthy(raw)) return fallback;
657
+ const value = typeof raw === "number" ? raw : Number(String(raw).trim());
658
+ if (Number.isNaN(value) || typeof raw === "boolean" || typeof raw === "string" && !String(raw).trim()) {
659
+ throw new ToolError(`${key} must be a number`);
660
+ }
661
+ return value;
662
+ }
663
+ function checkId(args, key) {
664
+ const value = truthy(args[key]) ? String(args[key]).trim() : "";
665
+ if (!value) throw new ToolError(`${key} is required`);
666
+ if (!ID_RE.test(value)) throw new ToolError(`${key} is not a valid CrowdCode id`);
667
+ return value;
668
+ }
669
+ function words(value) {
670
+ if (typeof value === "string") return value.replace(/,/g, " ").split(/\s+/).filter(Boolean);
671
+ if (Array.isArray(value)) return value.map((v) => String(v));
672
+ return [];
673
+ }
674
+ function money(value) {
675
+ return `$${value.toFixed(2)}`;
676
+ }
677
+ function fileSummary(f) {
678
+ const out = {};
679
+ for (const key of ["id", "name", "path", "size_bytes", "content_type", "task_id", "created_at"]) {
680
+ if (key in f) out[key] = f[key] ?? null;
681
+ }
682
+ return out;
683
+ }
684
+ function definitelyFailed(err) {
685
+ if (err instanceof ApiError) return err.status >= 400 && err.status < 500;
686
+ if (err instanceof ToolError || err instanceof WalletMissing || err instanceof NotSignedIn) return true;
687
+ const code = err?.cause?.code;
688
+ return ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "ERR_INVALID_URL"].includes(code ?? "");
689
+ }
690
+ function hintFor(err) {
691
+ if (err.status === 401 && err.error === "invalid_token") {
692
+ return `The CrowdCode sign-in was revoked or expired. Sign in again: ${LOGIN_COMMAND}`;
693
+ }
694
+ if (err.status === 403 && err.error === "insufficient_scope") {
695
+ return `Your CrowdCode sign-in does not allow this. Sign in again to grant it (${LOGIN_COMMAND}).`;
696
+ }
697
+ if (err.status === 403 && err.error === "daily_cap") {
698
+ return "The daily cap you set when connecting crowdcode-mcp is used up for today (UTC).";
699
+ }
700
+ if (err.status === 401) {
701
+ return { expired: "The request signature expired: check this machine's clock.", replayed: "The request nonce was reused; retry once." }[err.error] ?? "CrowdCode rejected the wallet signature.";
702
+ }
703
+ if (err.status === 403) return "This wallet does not own that agent. Use crowdcode_agents to list the agents you own.";
704
+ if (err.status === 402) return "Not enough USDC. Check balances with crowdcode_agents / crowdcode_wallet and fund first.";
705
+ if (err.status === 409 && err.error === "task_active") {
706
+ return "That agent is already running a task (one at a time). Check it with crowdcode_task_status or cancel it.";
707
+ }
708
+ if (err.status === 404) return "Not found: check the agent or task id.";
709
+ return "";
710
+ }
711
+ function describeError(err) {
712
+ if (!(err instanceof Error)) return String(err);
713
+ const cause = err.cause;
714
+ const extra = cause?.code ?? (cause?.message && cause.message !== err.message ? cause.message : "");
715
+ return `${err.name}: ${err.message}${extra ? ` (${extra})` : ""}`;
716
+ }
717
+ function failureFor(err) {
718
+ if (err instanceof WalletMissing) return fail(err.message, { hint: WALLET_HINT });
719
+ if (err instanceof NotSignedIn) return fail(err.message, { hint: `Sign in with: ${LOGIN_COMMAND} (in a terminal)` });
720
+ if (err instanceof ApiError) {
721
+ return fail(`CrowdCode API: ${err.error}`, { status: err.status, hint: hintFor(err), detail: err.detail ?? null });
722
+ }
723
+ if (err instanceof ToolError) return fail(err.message);
724
+ return fail(describeError(err));
725
+ }
726
+ var AgentTools = class {
727
+ options;
728
+ constructor(options = {}) {
729
+ this.options = options;
730
+ }
731
+ // settings ------------------------------------------------------------------
732
+ get env() {
733
+ return this.options.env ?? process.env;
734
+ }
735
+ get home() {
736
+ return crowdcodeHome(this.env);
737
+ }
738
+ cwd() {
739
+ const cwd = this.options.cwd;
740
+ return typeof cwd === "function" ? cwd() : cwd ?? process.cwd();
741
+ }
742
+ baseUrl() {
743
+ const url = (this.env.CROWDCODE_APP_URL?.trim() || DEFAULT_BASE_URL).replace(/\/+$/, "");
744
+ let parts;
745
+ try {
746
+ parts = new URL(url);
747
+ } catch {
748
+ throw new ToolError("CROWDCODE_APP_URL must be an https:// URL");
749
+ }
750
+ const local = ["localhost", "127.0.0.1", "[::1]", "::1"].includes(parts.hostname);
751
+ if (parts.protocol !== "https:" && !(local && parts.protocol === "http:")) {
752
+ throw new ToolError("CROWDCODE_APP_URL must be an https:// URL (plain http is allowed only for localhost)");
753
+ }
754
+ return url;
755
+ }
756
+ rpcUrl() {
757
+ return this.env.CROWDCODE_BASE_RPC_URL?.trim() || DEFAULT_RPC;
758
+ }
759
+ maxDownloadBytes() {
760
+ const mb = Number(this.env.CROWDCODE_MAX_DOWNLOAD_MB || DEFAULT_MAX_DOWNLOAD_MB);
761
+ return Math.floor((Number.isFinite(mb) && mb > 0 ? mb : DEFAULT_MAX_DOWNLOAD_MB) * 1e6);
762
+ }
763
+ // credentials -----------------------------------------------------------------
764
+ /** The local wallet; with `create`, make one first if there is none (unless creation is turned off). */
765
+ async loadSigner(create = false) {
766
+ const config = getConfig(this.env);
767
+ const wallet = await loadWallet({
768
+ env: this.env,
769
+ walletDir: config.walletDir,
770
+ autoCreate: create && config.walletAutoCreate
771
+ });
772
+ if (!wallet.account) {
773
+ if (wallet.error) throw new WalletMissing(wallet.error);
774
+ if (create && !config.walletAutoCreate) {
775
+ throw new WalletMissing(
776
+ "No CrowdCode wallet yet, and creating one is turned off here (CROWDCODE_DISABLE_WALLET_CREATE)."
777
+ );
778
+ }
779
+ throw new WalletMissing(`No CrowdCode wallet yet. Run \`${WALLET_INIT_COMMAND}\` to create one.`);
780
+ }
781
+ return { signer: new Signer(wallet.account), created: wallet.created === true };
782
+ }
783
+ async walletExists() {
784
+ try {
785
+ await this.loadSigner(false);
786
+ return true;
787
+ } catch {
788
+ return false;
789
+ }
790
+ }
791
+ /** `account` (the crowdcode-mcp sign-in) or `wallet` (the local key). `auto` = the account when signed in. */
792
+ async mode() {
793
+ const { setting } = await modeSetting(this.env, this.home);
794
+ if (setting !== "auto") return setting;
795
+ return await readCredentials(this.home, this.baseUrl()) ? "account" : "wallet";
796
+ }
797
+ account() {
798
+ return new AccountClient(this.baseUrl(), this.home);
799
+ }
800
+ publicApi() {
801
+ return new PublicClient(this.baseUrl());
802
+ }
803
+ async walletApi() {
804
+ return new WalletClient(this.baseUrl(), (await this.loadSigner()).signer);
805
+ }
806
+ /** The owner API client for the current mode. */
807
+ async api() {
808
+ if (await this.mode() === "account") return this.account();
809
+ try {
810
+ return await this.walletApi();
811
+ } catch (err) {
812
+ if (err instanceof WalletMissing) {
813
+ throw new WalletMissing(`${err.message} Or sign in to your CrowdCode account instead: ${LOGIN_COMMAND}.`);
814
+ }
815
+ throw err;
816
+ }
817
+ }
818
+ async recentTasks() {
819
+ return recentTasks(this.home);
820
+ }
821
+ // plumbing --------------------------------------------------------------------
822
+ /** Run a request that may move money; an unclear outcome says so instead of inviting a retry. */
823
+ async moneyCall(call) {
824
+ try {
825
+ return await call();
826
+ } catch (err) {
827
+ if (definitelyFailed(err)) throw err;
828
+ throw new UncertainError(`${describeError(err)}. ${UNSURE}`);
829
+ }
830
+ }
831
+ guarded(fn) {
832
+ return async (args) => {
833
+ try {
834
+ return await fn(args ?? {});
835
+ } catch (err) {
836
+ return failureFor(err);
837
+ }
838
+ };
839
+ }
840
+ handlers() {
841
+ const table = {
842
+ crowdcode_wallet: (a) => this.wallet(a),
843
+ crowdcode_agents: (a) => this.agents(a),
844
+ crowdcode_create_agent: (a) => this.createAgent(a),
845
+ crowdcode_fund_agent: (a) => this.fundAgent(a),
846
+ crowdcode_run_task: (a) => this.runTask(a),
847
+ crowdcode_task_status: (a) => this.taskStatus(a),
848
+ crowdcode_services: (a) => this.services(a),
849
+ crowdcode_withdraw: (a) => this.withdraw(a),
850
+ crowdcode_transfer: (a) => this.transfer(a),
851
+ crowdcode_demand: (a) => this.demand(a),
852
+ crowdcode_files: (a) => this.files(a),
853
+ crowdcode_download: (a) => this.download(a),
854
+ crowdcode_claim: (a) => this.claim(a)
855
+ };
856
+ return Object.fromEntries(AGENT_TOOL_NAMES.map((name) => [name, this.guarded(table[name])]));
857
+ }
858
+ // tools -------------------------------------------------------------------------
859
+ async wallet(args) {
860
+ let created = false;
861
+ if (truthy(args.init)) created = (await this.loadSigner(true)).created;
862
+ if (!truthy(args.init) && await this.mode() === "account") {
863
+ const me = await this.account().signed("GET", "/me");
864
+ const main = typeof me.address === "string" ? me.address : null;
865
+ const plain = main ? main.split(":").pop() ?? null : null;
866
+ let balance = "unavailable (no main wallet yet)";
867
+ if (plain && /^0x[0-9a-fA-F]{40}$/.test(plain)) balance = await this.balance(plain);
868
+ return ok({
869
+ mode: "account",
870
+ address: plain,
871
+ owner: main,
872
+ usdc_base: balance,
873
+ main_wallet: main,
874
+ agents: (me.agents ?? []).length,
875
+ connection: me.connection ?? {},
876
+ wallet_key: await this.walletExists(),
877
+ fund: `Fund agents from your main wallet at ${this.baseUrl()}/wallet; only you can sign for it.`
878
+ });
879
+ }
880
+ const { signer } = await this.loadSigner(false);
881
+ return ok({
882
+ mode: "wallet",
883
+ created,
884
+ address: signer.address,
885
+ owner: signer.caip10,
886
+ usdc_base: await this.balance(signer.address),
887
+ fund: FUND_HINT
888
+ });
889
+ }
890
+ async balance(address) {
891
+ try {
892
+ const usd = await this.publicApi().usdcBalance(this.rpcUrl(), address);
893
+ return Math.round(usd * 1e6) / 1e6;
894
+ } catch (err) {
895
+ return `unavailable (${err instanceof Error ? err.name : typeof err})`;
896
+ }
897
+ }
898
+ async agents(args) {
899
+ const api = await this.api();
900
+ if (truthy(args.agent_id)) return ok({ agent: await api.signed("GET", `/agents/${checkId(args, "agent_id")}`) });
901
+ const me = await api.signed("GET", "/me");
902
+ const listed = [];
903
+ for (const item of (me.agents ?? []).slice(0, 12)) {
904
+ try {
905
+ const detail = await api.signed("GET", `/agents/${item.id}`);
906
+ listed.push({
907
+ id: item.id,
908
+ name: detail.name ?? item.name,
909
+ status: detail.status ?? item.status,
910
+ balances_usd: detail.balances_usd ?? null,
911
+ addresses: detail.addresses ?? null
912
+ });
913
+ } catch (err) {
914
+ if (!(err instanceof ApiError)) throw err;
915
+ listed.push(item);
916
+ }
917
+ }
918
+ return ok({ owner: me.address ?? null, agents: listed });
919
+ }
920
+ async createAgent(args) {
921
+ const name = truthy(args.name) ? String(args.name).trim() : "";
922
+ const length = [...name].length;
923
+ if (length < 3 || length > 40) throw new ToolError("name must be 3-40 characters");
924
+ const body = { name };
925
+ if (truthy(args.model)) body.model = String(args.model);
926
+ if (truthy(args.instructions)) {
927
+ if ([...String(args.instructions)].length > 4e3) {
928
+ throw new ToolError("instructions must be at most 4000 characters");
929
+ }
930
+ body.instructions = String(args.instructions);
931
+ }
932
+ const maxPrice = amount(args, "max_price_usd", DEFAULT_CREATE_MAX_USD);
933
+ if (await this.mode() === "account") {
934
+ return fail(
935
+ "In account mode, create agents at crowdcode.app (your main wallet pays for them); only the wallet mode pays for creation from here.",
936
+ { create_at: `${this.baseUrl()}/agents` }
937
+ );
938
+ }
939
+ const api = await this.api();
940
+ const url = this.baseUrl() + "/s/crowdcode/agents";
941
+ const quote = await api.quote(url, body);
942
+ const price = unitsToUsd(BigInt(String(quote.offer.amount)));
943
+ if (price > maxPrice + 1e-9) {
944
+ return fail(
945
+ `Creating an agent costs ${money(price)}, above max_price_usd ${money(maxPrice)}; nothing was paid.`,
946
+ { price_usd: price }
947
+ );
948
+ }
949
+ const paid = await this.moneyCall(() => api.pay(url, body, quote));
950
+ const tx = paid.settlement?.transaction ?? null;
951
+ let created = paid.body;
952
+ if (paid.status >= 400) {
953
+ const settled = Boolean(paid.settlement?.success);
954
+ if (paid.status >= 500 && !settled) {
955
+ return fail(`Agent creation answered ${paid.status}. ${UNSURE}`, { detail: created });
956
+ }
957
+ const why = created && typeof created === "object" ? created.error : created;
958
+ return fail(`Agent creation failed (${paid.status}): ${why}`, {
959
+ status: paid.status,
960
+ paid: settled,
961
+ detail: created
962
+ });
963
+ }
964
+ const agentId = String(created.agent_id ?? "");
965
+ let statusNow = String(created.status ?? "pending");
966
+ const deadline = Date.now() + (this.options.createWaitMs ?? 9e4);
967
+ while (agentId && statusNow === "pending" && Date.now() < deadline) {
968
+ await sleep(this.options.createPollMs ?? 3e3);
969
+ let detail;
970
+ try {
971
+ detail = await api.signed("GET", `/agents/${agentId}`);
972
+ } catch (err) {
973
+ if (err instanceof ApiError && (err.status === 403 || err.status === 404)) continue;
974
+ throw err;
975
+ }
976
+ statusNow = String(detail.status ?? statusNow);
977
+ const picked = Object.fromEntries(
978
+ Object.entries(detail).filter(([k]) => ["addresses", "owner", "status", "name"].includes(k))
979
+ );
980
+ created = { ...created, ...picked };
981
+ }
982
+ if (statusNow === "failed") {
983
+ return fail(
984
+ "CrowdCode could not settle the creation payment, so the agent was removed. You were not charged.",
985
+ { agent_id: agentId }
986
+ );
987
+ }
988
+ created.status = statusNow;
989
+ return ok({
990
+ paid_usd: price,
991
+ payment_tx: tx,
992
+ ...created,
993
+ next: statusNow === "pending" ? "Payment is still settling; check with crowdcode_agents in a minute." : "Fund it with crowdcode_fund_agent, then give it work with crowdcode_run_task."
994
+ });
995
+ }
996
+ async fundAgent(args) {
997
+ const agentId = checkId(args, "agent_id");
998
+ const value = amount(args, "amount_usd");
999
+ const units = usdToUnits(value);
1000
+ if (value < MIN_MOVE_USD - 1e-9) {
1001
+ throw new ToolError(
1002
+ `the minimum relayed deposit is ${money(MIN_MOVE_USD)}; smaller amounts can be sent as a plain USDC transfer to the agent's Base address`
1003
+ );
1004
+ }
1005
+ const api = await this.api();
1006
+ if (api instanceof AccountClient) {
1007
+ try {
1008
+ await api.signed("POST", `/agents/${agentId}/deposits`, { amount_usd: pyFloat(value) });
1009
+ } catch (err) {
1010
+ const detail = err instanceof ApiError && err.detail && typeof err.detail === "object" ? err.detail : {};
1011
+ if (err instanceof ApiError && err.error === "browser_approval_required" && detail.approve_url) {
1012
+ return ok({
1013
+ agent_id: agentId,
1014
+ amount_usd: value,
1015
+ moved: false,
1016
+ approve_url: detail.approve_url,
1017
+ next: `Open ${detail.approve_url} and approve ${money(value)} from your main wallet. Nothing moves until you do.`
1018
+ });
1019
+ }
1020
+ throw err;
1021
+ }
1022
+ return fail("CrowdCode did not return an approval link; nothing was sent.");
1023
+ }
1024
+ const agent = await api.signed("GET", `/agents/${agentId}`);
1025
+ const to = agent?.addresses?.base;
1026
+ if (!to) return fail("CrowdCode did not return a Base address for this agent; nothing was sent.");
1027
+ const { authorization, signature } = await api.wallet.authorizeTransfer({ to, value: units, validSeconds: 300 });
1028
+ const result = await this.moneyCall(
1029
+ () => api.signed("POST", `/agents/${agentId}/deposits`, { authorization, signature })
1030
+ );
1031
+ const txHash = result?.tx_hash ?? null;
1032
+ return ok({
1033
+ agent_id: agentId,
1034
+ amount_usd: value,
1035
+ to,
1036
+ tx_hash: txHash,
1037
+ explorer: txHash ? `https://basescan.org/tx/${txHash}` : null
1038
+ });
1039
+ }
1040
+ async runTask(args) {
1041
+ const agentId = checkId(args, "agent_id");
1042
+ const prompt = truthy(args.prompt) ? String(args.prompt).trim() : "";
1043
+ if (!prompt) throw new ToolError("prompt is required");
1044
+ if ([...prompt].length > 2e4) throw new ToolError("prompt must be at most 20000 characters");
1045
+ const budget = amount(args, "budget_usd");
1046
+ if (!(budget > 0)) throw new ToolError("budget_usd is required and must be greater than zero");
1047
+ const body = { prompt, budget_usd: pyFloat(budget) };
1048
+ if (truthy(args.model)) body.model = String(args.model);
1049
+ const api = await this.api();
1050
+ const key = createHash("sha256").update(pyDumps([agentId, body, Math.floor(nowSeconds() / 600)], { sortKeys: true })).digest("hex");
1051
+ const started = await this.moneyCall(
1052
+ () => api.signed("POST", `/agents/${agentId}/tasks`, body, { "Idempotency-Key": key })
1053
+ );
1054
+ const taskId = String(started?.task_id ?? "");
1055
+ const record = {
1056
+ agent_id: agentId,
1057
+ task_id: taskId,
1058
+ prompt: [...prompt].slice(0, 120).join(""),
1059
+ budget_usd: budget,
1060
+ status: "queued",
1061
+ at: nowSeconds()
1062
+ };
1063
+ await this.remember(record);
1064
+ if (args.wait === false) {
1065
+ return ok({
1066
+ task_id: taskId,
1067
+ agent_id: agentId,
1068
+ status: "queued",
1069
+ answer: null,
1070
+ spent_usd: null,
1071
+ budget_usd: budget,
1072
+ purchases: [],
1073
+ files: [],
1074
+ next: "Check it with crowdcode_task_status."
1075
+ });
1076
+ }
1077
+ const timeout = amount(args, "timeout_seconds", 600);
1078
+ return this.poll(api, record, Date.now() + Math.max(10, Math.min(timeout, 1800)) * 1e3);
1079
+ }
1080
+ async remember(record) {
1081
+ try {
1082
+ await rememberTask(this.home, record);
1083
+ } catch {
1084
+ }
1085
+ }
1086
+ async poll(api, record, deadline) {
1087
+ let delay = this.options.taskPollMs ?? 2e3;
1088
+ let task;
1089
+ for (; ; ) {
1090
+ task = await api.signed("GET", `/agents/${record.agent_id}/tasks/${record.task_id}`);
1091
+ if (TERMINAL.includes(task.status) || Date.now() >= deadline) break;
1092
+ await sleep(Math.min(delay, Math.max(0, deadline - Date.now())));
1093
+ delay = Math.min(delay * 1.5, 1e4);
1094
+ }
1095
+ return this.report(record, task);
1096
+ }
1097
+ async report(record, task) {
1098
+ const status = String(task.status ?? "unknown");
1099
+ record.status = status;
1100
+ if (task.spent_usd !== void 0 && task.spent_usd !== null) record.spent_usd = task.spent_usd;
1101
+ await this.remember(record);
1102
+ const out = {
1103
+ task_id: record.task_id,
1104
+ agent_id: record.agent_id,
1105
+ status,
1106
+ answer: task.answer ?? null,
1107
+ spent_usd: task.spent_usd ?? null,
1108
+ budget_usd: record.budget_usd ?? null,
1109
+ purchases: task.purchases || [],
1110
+ files: (task.artifacts || []).map(fileSummary)
1111
+ };
1112
+ if (task.waiting_for) out.waiting_for = task.waiting_for;
1113
+ if (out.files.length) {
1114
+ out.files_note = 'Nothing was downloaded. Save them with crowdcode_download (file ids or "all").';
1115
+ }
1116
+ if (!TERMINAL.includes(status)) out.next = "Still running; check again with crowdcode_task_status.";
1117
+ return ok(out);
1118
+ }
1119
+ async taskStatus(args) {
1120
+ const agentId = checkId(args, "agent_id");
1121
+ const taskId = checkId(args, "task_id");
1122
+ const api = await this.api();
1123
+ if (truthy(args.cancel)) await api.signed("POST", `/agents/${agentId}/tasks/${taskId}/cancel`);
1124
+ const task = await api.signed("GET", `/agents/${agentId}/tasks/${taskId}`);
1125
+ const known = (await recentTasks(this.home).catch(() => [])).find((t) => t?.task_id === taskId);
1126
+ return this.report(known ?? { agent_id: agentId, task_id: taskId, at: nowSeconds() }, task);
1127
+ }
1128
+ async services(args) {
1129
+ const agentId = checkId(args, "agent_id");
1130
+ const action = truthy(args.action) ? String(args.action) : "list";
1131
+ const api = await this.api();
1132
+ if (action === "stop" || action === "start") {
1133
+ const serviceId = checkId(args, "service_id");
1134
+ await api.signed("POST", `/agents/${agentId}/services/${serviceId}/${action}`);
1135
+ } else if (action !== "list") {
1136
+ throw new ToolError("action must be list, stop or start");
1137
+ }
1138
+ let services = await api.signed("GET", `/agents/${agentId}/services`);
1139
+ if (services && !Array.isArray(services)) services = services.services ?? [];
1140
+ const rows = Array.isArray(services) ? services : [];
1141
+ const earned = rows.reduce((sum, s) => sum + (Number(s.earned_usd) || 0), 0);
1142
+ return ok({ agent_id: agentId, services: rows, total_earned_usd: Math.round(earned * 1e6) / 1e6 });
1143
+ }
1144
+ moveAmount(args) {
1145
+ const value = amount(args, "amount_usd");
1146
+ usdToUnits(value);
1147
+ if (value < MIN_MOVE_USD - 1e-9) {
1148
+ throw new ToolError(`the minimum withdrawal or transfer is ${money(MIN_MOVE_USD)}`);
1149
+ }
1150
+ return value;
1151
+ }
1152
+ async withdraw(args) {
1153
+ const agentId = checkId(args, "agent_id");
1154
+ const network = truthy(args.network) ? String(args.network) : "base";
1155
+ if (!WITHDRAW_NETWORKS.includes(network)) {
1156
+ throw new ToolError("withdrawals go to your wallet's EVM address: network must be base or tempo");
1157
+ }
1158
+ const value = this.moveAmount(args);
1159
+ const api = await this.api();
1160
+ const result = await this.moneyCall(
1161
+ () => api.signed("POST", `/agents/${agentId}/withdraw`, { amount_usd: pyFloat(value), network })
1162
+ );
1163
+ return ok({
1164
+ agent_id: agentId,
1165
+ amount_usd: value,
1166
+ network,
1167
+ to: result?.to || (api.wallet ? api.wallet.address : null),
1168
+ tx_hash: result?.tx_hash ?? null
1169
+ });
1170
+ }
1171
+ async transfer(args) {
1172
+ const source = checkId(args, "from_agent_id");
1173
+ const target = checkId(args, "to_agent_id");
1174
+ const network = truthy(args.network) ? String(args.network) : "base";
1175
+ if (!NETWORKS.includes(network)) {
1176
+ throw new ToolError(`network must be one of ${NETWORKS.join(", ")}`);
1177
+ }
1178
+ const value = this.moveAmount(args);
1179
+ const api = await this.api();
1180
+ const result = await this.moneyCall(
1181
+ () => api.signed("POST", `/agents/${source}/transfer`, {
1182
+ to_agent_id: target,
1183
+ amount_usd: pyFloat(value),
1184
+ network
1185
+ })
1186
+ );
1187
+ return ok({ from_agent_id: source, to_agent_id: target, amount_usd: value, network, ...result ?? {} });
1188
+ }
1189
+ async demand(args) {
1190
+ const data = await this.publicApi().demand();
1191
+ const proposals = data && !Array.isArray(data) && Array.isArray(data.proposals) ? data.proposals : [];
1192
+ const query = truthy(args.query) ? String(args.query).toLowerCase().trim() : "";
1193
+ const rows = [];
1194
+ for (const p of proposals) {
1195
+ const text = ["title", "problem", "input", "output"].map((k) => String(p[k] ?? "")).join(" ").toLowerCase();
1196
+ if (query && !text.includes(query)) continue;
1197
+ const demand = p.demand ?? {};
1198
+ rows.push({
1199
+ title: p.title ?? null,
1200
+ problem: p.problem ?? null,
1201
+ input: p.input ?? null,
1202
+ output: p.output ?? null,
1203
+ median_price_usd: p.price?.median ?? null,
1204
+ agents_asking: demand.requesters ?? null,
1205
+ would_pay: p.would_pay ?? null,
1206
+ last_requested_at: demand.last_requested_at ?? null
1207
+ });
1208
+ }
1209
+ const rank = (r) => [Number(r.agents_asking) || 0, Number(r.median_price_usd) || 0];
1210
+ rows.sort((a, b) => {
1211
+ const [a1, a2] = rank(a);
1212
+ const [b1, b2] = rank(b);
1213
+ return b1 - a1 || b2 - a2;
1214
+ });
1215
+ const limit = Math.max(1, Math.min(Math.trunc(amount(args, "limit", 10)), 50));
1216
+ return ok({
1217
+ count: rows.length,
1218
+ proposals: rows.slice(0, limit),
1219
+ tip: "Each one is a service other agents asked for. To have an agent build one, ask a CrowdCode agent to with crowdcode_run_task."
1220
+ });
1221
+ }
1222
+ async files(args) {
1223
+ const agentId = await this.resolveAgent(checkId(args, "agent_id"));
1224
+ const taskId = truthy(args.task_id) ? checkId(args, "task_id") : "";
1225
+ const listed = await listFiles(await this.api(), agentId, taskId);
1226
+ const total = listed.reduce((sum, f) => sum + (Math.trunc(Number(f.size_bytes)) || 0), 0);
1227
+ return ok({
1228
+ agent_id: agentId,
1229
+ count: listed.length,
1230
+ total_bytes: total,
1231
+ files: listed.map(fileSummary),
1232
+ next: listed.length ? "Save some or all of them with crowdcode_download." : null
1233
+ });
1234
+ }
1235
+ async download(args) {
1236
+ const agentId = await this.resolveAgent(checkId(args, "agent_id"));
1237
+ const taskId = truthy(args.task_id) ? checkId(args, "task_id") : "";
1238
+ const wanted = words(args.file_ids);
1239
+ if (!wanted.length) throw new ToolError('file_ids is required: a list of file ids, or "all"');
1240
+ const api = await this.api();
1241
+ const listed = await listFiles(api, agentId, taskId);
1242
+ let chosen;
1243
+ if (wanted.length === 1 && wanted[0].toLowerCase() === "all") {
1244
+ chosen = listed;
1245
+ } else {
1246
+ const byId = new Map(listed.map((f) => [String(f.id), f]));
1247
+ for (const w of wanted) {
1248
+ if (!ID_RE.test(w)) throw new ToolError(`${JSON.stringify(w)} is not a valid file id`);
1249
+ }
1250
+ const missing = wanted.filter((w) => !byId.has(w));
1251
+ if (missing.length) {
1252
+ return fail(`No such file for this agent: ${missing.join(", ")}. List them with crowdcode_files.`);
1253
+ }
1254
+ chosen = wanted.map((w) => byId.get(w));
1255
+ }
1256
+ if (!chosen.length) {
1257
+ return ok({
1258
+ agent_id: agentId,
1259
+ directory: null,
1260
+ downloaded: [],
1261
+ failed: [],
1262
+ total_bytes: 0,
1263
+ note: "This agent has no files yet."
1264
+ });
1265
+ }
1266
+ const name = (await api.signed("GET", `/agents/${agentId}`))?.name || agentId;
1267
+ const target = planDest(truthy(args.dest) ? String(args.dest) : "", String(name), this.cwd());
1268
+ await mkdir(target, { recursive: true });
1269
+ const directory = await realpath(target);
1270
+ const maxBytes = this.maxDownloadBytes();
1271
+ const saved = [];
1272
+ const failed = [];
1273
+ for (const f of chosen) {
1274
+ try {
1275
+ saved.push(await downloadFile(api, agentId, f, directory, maxBytes));
1276
+ } catch (err) {
1277
+ const message = err instanceof ApiError || err instanceof ToolError ? err.message : describeError(err);
1278
+ failed.push({ id: f.id ?? null, name: f.name ?? null, error: message });
1279
+ }
1280
+ }
1281
+ return ok({
1282
+ agent_id: agentId,
1283
+ directory,
1284
+ downloaded: saved,
1285
+ failed,
1286
+ total_bytes: saved.reduce((sum, s) => sum + s.size_bytes, 0)
1287
+ });
1288
+ }
1289
+ /** Ask to move this wallet's agents into a CrowdCode account; the account's owner approves in the browser. */
1290
+ async claim(args) {
1291
+ const api = await this.walletApi();
1292
+ const refs = words(args.agents);
1293
+ const body = {};
1294
+ if (refs.length) {
1295
+ const mine = (await api.signed("GET", "/me")).agents ?? [];
1296
+ body.agent_ids = refs.map((r) => matchAgent(mine, r));
1297
+ }
1298
+ const made = await api.signed("POST", "/claims", body);
1299
+ return ok({
1300
+ approve_url: made.approve_url ?? null,
1301
+ expires_at: made.expires_at ?? null,
1302
+ agents: made.agents || [],
1303
+ next: `Open the link while signed in to your CrowdCode account and approve. It works once and expires in 15 minutes. Withdrawals from these agents will then go only to that account's main wallet. Afterwards run \`${LOGIN_COMMAND}\` so this machine keeps controlling them through the account.`
1304
+ });
1305
+ }
1306
+ /** An agent id from an id, an id prefix or a name, among the agents of the current credential. */
1307
+ async resolveAgent(ref) {
1308
+ const wanted = (ref ?? "").trim();
1309
+ if (!wanted) throw new ToolError("name an agent (its name or id)");
1310
+ const me = await (await this.api()).signed("GET", "/me");
1311
+ return matchAgent(me.agents ?? [], wanted);
1312
+ }
1313
+ };
1314
+ function matchAgent(agents, ref) {
1315
+ const tests = [
1316
+ (a) => a.id === ref,
1317
+ (a) => String(a.name ?? "").toLowerCase() === ref.toLowerCase(),
1318
+ (a) => String(a.id ?? "").startsWith(ref)
1319
+ ];
1320
+ for (const test of tests) {
1321
+ const found = agents.filter(test);
1322
+ if (found.length === 1) return String(found[0].id);
1323
+ if (found.length > 1) throw new ToolError(`'${ref}' matches more than one agent; use its id`);
1324
+ }
1325
+ throw new ToolError(`no agent of yours is called '${ref}'`);
1326
+ }
1327
+ function createAgentTools(options = {}) {
1328
+ return new AgentTools(options);
1329
+ }
1330
+
1331
+ export {
1332
+ AGENT_TOOL_NAMES,
1333
+ hostDescription,
1334
+ zodShape,
1335
+ DEFAULT_BASE_URL,
1336
+ DEFAULT_RPC,
1337
+ NETWORKS,
1338
+ WITHDRAW_NETWORKS,
1339
+ MIN_MOVE_USD,
1340
+ DEFAULT_CREATE_MAX_USD,
1341
+ TERMINAL,
1342
+ ID_RE,
1343
+ FUND_HINT,
1344
+ UNSURE,
1345
+ checkId,
1346
+ hintFor,
1347
+ failureFor,
1348
+ AgentTools,
1349
+ matchAgent,
1350
+ createAgentTools
1351
+ };
1352
+ //# sourceMappingURL=chunk-L32J3R5J.js.map