@infernetprotocol/cli 0.1.67 → 0.1.69

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,145 @@
1
+ /**
2
+ * `infernet credits` / `infernet redeem` / `infernet invites` — consumer
3
+ * compute credits and scarce invites for a signed-in account (`infernet login`).
4
+ *
5
+ * Credits are what you hold as a CUSTOMER of the network. They are separate
6
+ * from node earnings (`infernet payout`) and can never be withdrawn.
7
+ */
8
+ import { resolveCreditsOptions, createCreditsClient } from '../lib/credits-client.js';
9
+
10
+ export const CREDITS_HELP = `infernet credits — consumer compute credits
11
+
12
+ Usage:
13
+ infernet credits Balance and recent grants
14
+ infernet credits redeem <code> Redeem a credit code (also: infernet redeem <code>)
15
+ infernet invites Your invites, quota and affiliate link
16
+ infernet invites create [--note <text>] Create an invite (the code is shown once)
17
+ infernet invites revoke <invite-id> Withdraw an unused invite
18
+ infernet invites accept <code> Join on an invite (new accounts only)
19
+
20
+ Admin (INFERNET_ADMIN_TOKEN or an admin login):
21
+ infernet credits admin list
22
+ infernet credits admin mint --credits <n> [--label <text>] [--max <n>] [--expires <iso>] [--monthly]
23
+ infernet credits admin revoke <code-id>
24
+
25
+ Options: --json, --url <base>, --token <bearer>
26
+ Credits are not node earnings and cannot be withdrawn (see \`infernet payout\`).
27
+ `;
28
+
29
+ async function client(args) {
30
+ return createCreditsClient(await resolveCreditsOptions({ url: args.get('url'), token: args.get('token') }));
31
+ }
32
+
33
+ function out(args, data, text) {
34
+ process.stdout.write(args.has('json') ? `${JSON.stringify(data, null, 2)}\n` : `${text}\n`);
35
+ }
36
+
37
+ export async function redeemCode(args, code) {
38
+ if (!code) {
39
+ process.stderr.write('Usage: infernet redeem <code>\n');
40
+ return 1;
41
+ }
42
+ const c = await client(args);
43
+ try {
44
+ const r = await c.redeem(code);
45
+ out(args, r, `Redeemed: +${r.credits} credits${r.monthly ? ' every month' : ''}. Balance: ${r.balance}`);
46
+ return 0;
47
+ } catch (err) {
48
+ process.stderr.write(`${err.message}\n`);
49
+ return 1;
50
+ }
51
+ }
52
+
53
+ export async function credits(args) {
54
+ const [sub, ...rest] = args.positional;
55
+ if (args.has('help') || args.has('h') || sub === 'help') {
56
+ process.stdout.write(CREDITS_HELP);
57
+ return 0;
58
+ }
59
+ if (sub === 'redeem') return redeemCode(args, rest[0]);
60
+ const c = await client(args);
61
+ if (sub === 'admin') {
62
+ const [action, arg] = rest;
63
+ if (action === 'list') {
64
+ const rows = await c.listCodes();
65
+ out(args, rows, rows.length
66
+ ? rows.map((r) => `${r.id} ${r.grant.amount} ${r.grant.unit}${r.grant.every ? '/month' : ''} ${r.redemptions}/${r.maxRedemptions}${r.revokedAt ? ' revoked' : ''} ${r.label}`).join('\n')
67
+ : 'No codes.');
68
+ return 0;
69
+ }
70
+ if (action === 'mint') {
71
+ const body = {
72
+ credits: Number(args.get('credits') ?? args.get('amount')),
73
+ label: args.get('label'),
74
+ max_redemptions: args.get('max') ? Number(args.get('max')) : undefined,
75
+ expires_at: args.get('expires'),
76
+ monthly: args.has('monthly')
77
+ };
78
+ const r = await c.mintCode(body);
79
+ out(args, r, `Code: ${r.code}\n(shown once; only its hash is stored) id ${r.id} ${r.grant.amount} credits${r.grant.every ? '/month' : ''} max ${r.maxRedemptions}`);
80
+ return 0;
81
+ }
82
+ if (action === 'revoke' && arg) {
83
+ out(args, await c.revokeCode(arg), `Revoked ${arg}.`);
84
+ return 0;
85
+ }
86
+ process.stderr.write(CREDITS_HELP);
87
+ return 1;
88
+ }
89
+ if (sub && sub !== 'balance') {
90
+ process.stderr.write(CREDITS_HELP);
91
+ return 1;
92
+ }
93
+ const s = await c.balance();
94
+ const lines = [`Credits: ${s.balance}`];
95
+ for (const h of (s.history ?? []).slice(0, 10)) lines.push(` ${h.kind === 'spend' ? '-' : '+'}${h.amount} ${h.source} ${String(h.at).slice(0, 10)}`);
96
+ out(args, s, lines.join('\n'));
97
+ return 0;
98
+ }
99
+
100
+ export async function invites(args) {
101
+ const [sub, arg] = args.positional;
102
+ if (args.has('help') || args.has('h') || sub === 'help') {
103
+ process.stdout.write(CREDITS_HELP);
104
+ return 0;
105
+ }
106
+ const c = await client(args);
107
+ try {
108
+ if (sub === 'create') {
109
+ const r = await c.createInvite(args.get('note') ?? '');
110
+ out(args, r, `Invite: ${r.url}\n(code ${r.code}, shown once; expires ${String(r.expiresAt ?? '').slice(0, 10)})`);
111
+ return 0;
112
+ }
113
+ if (sub === 'revoke' && arg) {
114
+ out(args, await c.revokeInvite(arg), `Withdrawn ${arg}.`);
115
+ return 0;
116
+ }
117
+ if (sub === 'accept' && arg) {
118
+ const r = await c.acceptInvite(arg);
119
+ out(args, r, `Joined on the invite. Bonus: ${r.bonus}.`);
120
+ return 0;
121
+ }
122
+ if (sub && sub !== 'list') {
123
+ process.stderr.write(CREDITS_HELP);
124
+ return 1;
125
+ }
126
+ const o = await c.invites();
127
+ const lines = [
128
+ `Invites: ${o.quota.left} of ${o.quota.total} left${o.canInvite ? '' : ` (unlock ${String(o.unlocksAt ?? '').slice(0, 10)})`}`,
129
+ `Bonus: ${o.bonusCredits} credits each when an invited account confirms`,
130
+ `Link: ${o.refUrl}`
131
+ ];
132
+ for (const i of o.invites ?? []) lines.push(` ${i.id} ${i.status}${i.bonus ? ` (${i.bonus})` : ''} ${i.note ?? ''}`);
133
+ out(args, o, lines.join('\n'));
134
+ return 0;
135
+ } catch (err) {
136
+ process.stderr.write(`${err.message}\n`);
137
+ return 1;
138
+ }
139
+ }
140
+
141
+ export async function redeem(args) {
142
+ return redeemCode(args, args.positional[0]);
143
+ }
144
+
145
+ export default credits;
package/commands/help.js CHANGED
@@ -40,11 +40,15 @@ Diagnostics:
40
40
  Payments:
41
41
  payout Earnings, withdrawals and payout address
42
42
  payments Show recent payment transactions
43
+ credits Your consumer compute credits (not earnings); redeem a code
44
+ redeem Redeem a credit code: infernet redeem CR-XXXX-XXXX-XXXX-XXXX
45
+ invites Scarce invites (both sides get credits) and your affiliate link
43
46
 
44
47
  Managed endpoints:
45
48
  reservation Book a pinned operator + exact model by the hour; keys, limits,
46
49
  per-minute availability report, post-paid invoice data
47
- mcp MCP server (stdio) exposing the reservation tools
50
+ order Order a dedicated model endpoint yourself: pay by x402 or CoinPay
51
+ mcp MCP server (stdio): order, reservation, credit and invite tools
48
52
 
49
53
  Other:
50
54
  help Show this help
package/commands/mcp.js CHANGED
@@ -12,11 +12,22 @@
12
12
  */
13
13
  import { createInterface } from 'node:readline';
14
14
  import { resolveClientOptions, createReservationsClient } from '../lib/reservations-client.js';
15
+ import { createOrdersClient, x402KeyFrom, DEFAULT_MAX_USD } from '../lib/orders-client.js';
16
+ import { resolveCreditsOptions, createCreditsClient } from '../lib/credits-client.js';
15
17
  import { CURRENT_VERSION } from '../lib/version.js';
16
18
 
17
19
  const PROTOCOL_VERSION = '2025-06-18';
18
20
 
19
21
  const id = { type: 'string', description: 'reservation id (uuid)' };
22
+ const ORDER_PROPS = {
23
+ gpu_class: { type: 'string', enum: ['l40s', 'a100', 'h100', 'h100x2'] },
24
+ models: { type: 'array', items: { type: 'string' }, description: 'exact model ids, from order_capacity' },
25
+ hours: { type: 'integer', minimum: 1, maximum: 168 },
26
+ start_at: { type: 'string', description: 'whole UTC hour, ISO; default the next hour' },
27
+ email: { type: 'string' },
28
+ name: { type: 'string' }
29
+ };
30
+ const orderInput = (a) => Object.fromEntries(['gpu_class', 'models', 'hours', 'start_at', 'email', 'name'].filter((k) => a[k] !== undefined).map((k) => [k, a[k]]));
20
31
 
21
32
  export const TOOLS = [
22
33
  {
@@ -83,6 +94,47 @@ export const TOOLS = [
83
94
  description: 'Post-paid invoice data: hour statuses and amount due for compliant hours only. Executes no payment.',
84
95
  inputSchema: { type: 'object', required: ['id'], properties: { id } },
85
96
  run: (c, a) => c.invoice(a.id)
97
+ },
98
+ // Self-serve orders: anyone can book, no admin token. x402 pays from X402_PRIVATE_KEY.
99
+ { name: 'order_capacity', description: 'What can be ordered right now: per GPU class the list price, how many online nodes are free and which models they serve.', inputSchema: { type: 'object', properties: {} }, run: (c) => c.orders.capacity() },
100
+ {
101
+ name: 'order_quote',
102
+ description: 'Price an order without paying: matches an online node and returns the quote plus the x402 offer.',
103
+ inputSchema: { type: 'object', required: ['gpu_class', 'models'], properties: ORDER_PROPS },
104
+ run: (c, a) => c.orders.quote(orderInput(a))
105
+ },
106
+ {
107
+ name: 'order_create',
108
+ description: 'Order a dedicated model endpoint (prepaid). pay="x402" pays now in USDC from the X402_PRIVATE_KEY wallet (refuses above max_usd) and returns the reservation, buyer token and an API key. pay="checkout" returns a CoinPay checkout URL for a person to pay (any coin or PayPal) and the buyer token; poll order_status.',
109
+ inputSchema: {
110
+ type: 'object', required: ['gpu_class', 'models', 'pay'],
111
+ properties: { ...ORDER_PROPS, pay: { type: 'string', enum: ['x402', 'checkout'] }, max_usd: { type: 'number', description: `x402 spend ceiling, default ${DEFAULT_MAX_USD}` } }
112
+ },
113
+ run: (c, a) => (a.pay === 'checkout'
114
+ ? c.orders.checkout(orderInput(a))
115
+ : c.orders.payX402(orderInput(a), { key: x402KeyFrom(), maxUsd: a.max_usd ?? DEFAULT_MAX_USD }))
116
+ },
117
+ {
118
+ name: 'order_status',
119
+ description: 'An order and, once paid, its reservation. Needs the buyer token the order returned.',
120
+ inputSchema: { type: 'object', required: ['id', 'buyer_token'], properties: { id: { type: 'string' }, buyer_token: { type: 'string' } } },
121
+ run: (c, a) => c.orders.status(a.id, a.buyer_token)
122
+ },
123
+ // Consumer compute credits + invites for the `infernet login` account.
124
+ // Credits are never node earnings and cannot be withdrawn.
125
+ { name: 'credits_balance', description: 'Your consumer compute-credit balance and recent grants (signed-in account).', inputSchema: { type: 'object', properties: {} }, run: (c) => c.credits.balance() },
126
+ {
127
+ name: 'credits_redeem',
128
+ description: 'Redeem a credit code (CR-XXXX-XXXX-XXXX-XXXX) for consumer compute credits.',
129
+ inputSchema: { type: 'object', required: ['code'], properties: { code: { type: 'string' } } },
130
+ run: (c, a) => c.credits.redeem(a.code)
131
+ },
132
+ { name: 'invites_list', description: 'Your invites, quota, bonus and affiliate link.', inputSchema: { type: 'object', properties: {} }, run: (c) => c.credits.invites() },
133
+ {
134
+ name: 'invite_create',
135
+ description: 'Create a single-use invite link (shown once). Both people get credits when a new account joins on it and confirms its email.',
136
+ inputSchema: { type: 'object', properties: { note: { type: 'string' } } },
137
+ run: (c, a) => c.credits.createInvite(a.note)
86
138
  }
87
139
  ];
88
140
 
@@ -119,10 +171,12 @@ export async function handleMessage(msg, client) {
119
171
 
120
172
  export default async function mcp(args) {
121
173
  if (args.has('help') || args.has('h')) {
122
- process.stdout.write('infernet mcp — MCP server (stdio) for managed-endpoint reservations\n\n claude mcp add infernet -- infernet mcp\n');
174
+ process.stdout.write('infernet mcp — MCP server (stdio): self-serve orders, managed-endpoint reservations, credits and invites\n\n claude mcp add infernet -- infernet mcp\n');
123
175
  return 0;
124
176
  }
125
177
  const client = createReservationsClient(await resolveClientOptions({ url: args.get('url'), token: args.get('token'), buyerToken: args.get('buyer-token') }));
178
+ client.orders = createOrdersClient({ baseUrl: (await resolveClientOptions({ url: args.get('url') })).baseUrl });
179
+ client.credits = createCreditsClient(await resolveCreditsOptions({ url: args.get('url'), token: args.get('token') }));
126
180
  const rl = createInterface({ input: process.stdin });
127
181
  for await (const line of rl) {
128
182
  if (!line.trim()) continue;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * `infernet order` — book a managed endpoint yourself, no admin
3
+ * (docs/prd/16-managed-endpoints.md, "Self-serve orders"). Talks to /api/v1/orders/*.
4
+ */
5
+ import { resolveClientOptions } from '../lib/reservations-client.js';
6
+ import { createOrdersClient, orderBodyFromFlags, x402KeyFrom, DEFAULT_MAX_USD } from '../lib/orders-client.js';
7
+
8
+ const HELP = `infernet order — order a dedicated model endpoint by the hour
9
+
10
+ We pin the models on one online node with the GPU class you pick, for the
11
+ hours you book, and you get an OpenAI-compatible API key. Prepaid at the list
12
+ price; non-compliant hours are credited or refunded.
13
+
14
+ Usage:
15
+ infernet order capacity what is on sale now: classes, prices, free nodes, models
16
+ infernet order quote --gpu l40s --models m1[,m2] [--hours 1] [--start 2026-10-28T15:00:00Z]
17
+ infernet order create --gpu l40s --models m1[,m2] [--hours 1] [--start ISO] [--email you@x]
18
+ --checkout pay at CoinPay (any coin or PayPal): prints the checkout URL
19
+ --x402 pay now in USDC from X402_PRIVATE_KEY (or --key-file F)
20
+ [--max-usd ${DEFAULT_MAX_USD}] refuse to sign more than this
21
+ infernet order status <id> --buyer-token ifr_buy_… (or INFERNET_BUYER_TOKEN)
22
+
23
+ After booking, manage it with \`infernet reservation\` and the same buyer token:
24
+ INFERNET_BUYER_TOKEN=ifr_buy_… infernet reservation key-issue <reservation id>
25
+ `;
26
+
27
+ function out(obj) {
28
+ process.stdout.write(`${JSON.stringify(obj, null, 2)}\n`);
29
+ }
30
+
31
+ function line(o) {
32
+ return `${o.id} ${o.status.padEnd(16)} ${o.gpu_class} ${o.models.join(',')} ${o.start_at} +${o.hours}h $${Number(o.total_usd).toFixed(2)} ${o.operator_name}`;
33
+ }
34
+
35
+ export default async function order(args) {
36
+ const [sub, a1] = args.positional;
37
+ if (!sub || args.has('help') || args.has('h') || sub === 'help') {
38
+ process.stdout.write(HELP);
39
+ return sub || args.has('help') ? 0 : 1;
40
+ }
41
+ const { baseUrl } = await resolveClientOptions({ url: args.get('url') });
42
+ const client = createOrdersClient({ baseUrl });
43
+ const json = args.has('json');
44
+ const body = () => orderBodyFromFlags((k) => args.get(k));
45
+
46
+ switch (sub) {
47
+ case 'capacity': {
48
+ const c = await client.capacity();
49
+ if (json) return out(c), 0;
50
+ process.stdout.write(`${c.terms}\nearliest start ${c.earliest_start}, up to ${c.max_hours}h; pay: x402=${c.pay.x402} checkout=${c.pay.checkout}\n\n`);
51
+ for (const k of c.classes) {
52
+ process.stdout.write(`${k.gpu_class.padEnd(7)} ${k.label.padEnd(13)} $${k.price_per_hour.toFixed(2)}/hr + $${k.setup_fee.toFixed(2)} setup ${String(k.nodes_available).padStart(2)} free ${k.models.join(', ') || '—'}\n`);
53
+ }
54
+ return 0;
55
+ }
56
+ case 'quote': {
57
+ const q = await client.quote(body());
58
+ if (json) return out(q), 0;
59
+ const s = q.quote;
60
+ process.stdout.write(`${s.label} x ${s.hours}h from ${s.start_at}: $${s.total_usd.toFixed(2)} ($${s.price_per_hour}/h + $${s.setup_fee} setup) on ${s.operator_name}\n`);
61
+ process.stdout.write(`x402: ${q.accepts.map((a) => a.network).join(', ')} | or: infernet order create ... --checkout\n`);
62
+ return 0;
63
+ }
64
+ case 'create': {
65
+ if (args.has('x402') === args.has('checkout')) throw new Error('pick one: --checkout (CoinPay page) or --x402 (pay now in USDC)');
66
+ if (args.has('checkout')) {
67
+ const r = await client.checkout(body());
68
+ if (json) return out(r), 0;
69
+ process.stdout.write(`order ${line(r.order)}\n`);
70
+ process.stdout.write(`pay here: ${r.checkout_url}\n`);
71
+ process.stdout.write(`buyer token (shown once, keep it):\n ${r.buyer_token}\n`);
72
+ process.stdout.write(`then: infernet order status ${r.order.id} --buyer-token ${r.buyer_token}\n`);
73
+ return 0;
74
+ }
75
+ const key = x402KeyFrom({ keyFile: args.get('key-file') });
76
+ const r = await client.payX402(body(), { key, maxUsd: args.get('max-usd') ?? DEFAULT_MAX_USD });
77
+ if (json) return out(r), 0;
78
+ process.stdout.write(`paid $${r.paid_usd} from ${r.payer} on ${r.network}${r.tx_hash ? ` (tx ${r.tx_hash})` : ''}\n`);
79
+ process.stdout.write(`order ${line(r.order)}\nreservation ${r.reservation?.id}\n`);
80
+ process.stdout.write(`buyer token (shown once):\n ${r.buyer_token}\napi key (shown once):\n ${r.api_key}\n`);
81
+ process.stdout.write(`use: ${r.use.base_url}/chat/completions with Authorization: Bearer <api key>\n`);
82
+ return 0;
83
+ }
84
+ case 'status': {
85
+ if (!a1) throw new Error('usage: infernet order status <id> --buyer-token ifr_buy_…');
86
+ const token = args.get('buyer-token') || process.env.INFERNET_BUYER_TOKEN;
87
+ if (!token) throw new Error('--buyer-token (or INFERNET_BUYER_TOKEN) is required');
88
+ const o = await client.status(a1, token);
89
+ if (json) return out(o), 0;
90
+ process.stdout.write(`${line(o)}\n`);
91
+ if (o.reservation_id) process.stdout.write(`reservation ${o.reservation_id}: INFERNET_BUYER_TOKEN=… infernet reservation key-issue ${o.reservation_id}\n`);
92
+ return 0;
93
+ }
94
+ default:
95
+ process.stderr.write(`unknown subcommand: ${sub}\n\n${HELP}`);
96
+ return 1;
97
+ }
98
+ }
package/index.js CHANGED
@@ -49,7 +49,9 @@ import inference from './commands/inference.js';
49
49
  import rpc from './commands/rpc.js';
50
50
  import uncensored from './commands/uncensored.js';
51
51
  import reservation from './commands/reservation.js';
52
+ import order from './commands/order.js';
52
53
  import mcp from './commands/mcp.js';
54
+ import credits, { invites, redeem } from './commands/credits.js';
53
55
 
54
56
  function parseArgs(argv) {
55
57
  const positional = [];
@@ -111,11 +113,11 @@ const COMMANDS = {
111
113
  // aliases
112
114
  uninstall: remove,
113
115
  start, status, stop, restart, stats, logs,
114
- payout, payments, gpu, firewall, chat, setup, model, train, publish, inference, rpc, uncensored, reservation, reservations: reservation, mcp, tui, doctor, service, pubkey, debug, deploy, console: consoleCmd, help
116
+ payout, payments, gpu, firewall, chat, setup, model, train, publish, inference, rpc, uncensored, reservation, reservations: reservation, order, orders: order, mcp, credits, invites, redeem, tui, doctor, service, pubkey, debug, deploy, console: consoleCmd, help
115
117
  };
116
118
 
117
119
  // Commands that can run without a loaded config.
118
- const NO_CONFIG = new Set(['init', 'login', 'help', 'stats', 'logs', 'stop', 'restart', 'gpu', 'firewall', 'chat', 'setup', 'model', 'train', 'publish', 'inference', 'rpc', 'uncensored', 'reservation', 'reservations', 'mcp', 'tui', 'doctor', 'service', 'pubkey', 'debug', 'deploy', 'console', 'upgrade', 'update', 'remove', 'uninstall']);
120
+ const NO_CONFIG = new Set(['init', 'login', 'help', 'stats', 'logs', 'stop', 'restart', 'gpu', 'firewall', 'chat', 'setup', 'model', 'train', 'publish', 'inference', 'rpc', 'uncensored', 'reservation', 'reservations', 'order', 'orders', 'mcp', 'credits', 'invites', 'redeem', 'tui', 'doctor', 'service', 'pubkey', 'debug', 'deploy', 'console', 'upgrade', 'update', 'remove', 'uninstall']);
119
121
  // Commands that need a config but not a control-plane client (none today
120
122
  // — kept as a future escape hatch).
121
123
  const NO_CLIENT = new Set();
@@ -0,0 +1,64 @@
1
+ /**
2
+ * HTTP client for consumer compute credits and invites — shared by
3
+ * `infernet credits`, `infernet redeem`, `infernet invites` and `infernet mcp`.
4
+ *
5
+ * Base URL: --url, INFERNET_URL, config.controlPlane.url, else infernetprotocol.com
6
+ * User auth: the `infernet login` bearer (config.auth.bearerToken) or --token
7
+ * Admin (mint/list/revoke codes): INFERNET_ADMIN_TOKEN, else the login bearer
8
+ * of an admin account.
9
+ *
10
+ * Credits are a CONSUMER balance: never node earnings, never withdrawable.
11
+ */
12
+ import { loadConfig } from './config.js';
13
+
14
+ const DEFAULT_URL = 'https://infernetprotocol.com';
15
+
16
+ export async function resolveCreditsOptions(opts = {}) {
17
+ const config = await loadConfig().catch(() => null);
18
+ const bearer = config?.auth?.bearerToken || null;
19
+ return {
20
+ baseUrl: String(opts.url || process.env.INFERNET_URL || config?.controlPlane?.url || DEFAULT_URL).replace(/\/+$/, ''),
21
+ userToken: opts.token || bearer,
22
+ adminToken: opts.token || process.env.INFERNET_ADMIN_TOKEN || bearer
23
+ };
24
+ }
25
+
26
+ export function createCreditsClient({ baseUrl, userToken, adminToken, fetchImpl = fetch }) {
27
+ async function call(method, path, { body, admin = false } = {}) {
28
+ const token = admin ? adminToken : userToken;
29
+ if (!token) {
30
+ throw new Error(admin
31
+ ? 'admin authorization required: set INFERNET_ADMIN_TOKEN or run `infernet login` as an admin'
32
+ : 'not signed in: run `infernet login` first');
33
+ }
34
+ const headers = { accept: 'application/json', authorization: `Bearer ${token}` };
35
+ if (body !== undefined) headers['content-type'] = 'application/json';
36
+ const res = await fetchImpl(`${baseUrl}${path}`, {
37
+ method,
38
+ headers,
39
+ body: body === undefined ? undefined : JSON.stringify(body)
40
+ });
41
+ const text = await res.text();
42
+ let json = null;
43
+ try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON */ }
44
+ if (!res.ok) {
45
+ const err = new Error(json?.error ?? `${method} ${path} -> HTTP ${res.status} ${text.slice(0, 200)}`);
46
+ err.status = res.status;
47
+ err.reason = json?.reason;
48
+ throw err;
49
+ }
50
+ return json?.data ?? json;
51
+ }
52
+ const enc = encodeURIComponent;
53
+ return {
54
+ balance: () => call('GET', '/api/v1/credits'),
55
+ redeem: (code) => call('POST', '/api/v1/credits/redeem', { body: { code } }),
56
+ invites: () => call('GET', '/api/v1/invites'),
57
+ createInvite: (note) => call('POST', '/api/v1/invites', { body: { note: note ?? '' } }),
58
+ revokeInvite: (id) => call('DELETE', `/api/v1/invites/${enc(id)}`),
59
+ acceptInvite: (code) => call('POST', '/api/v1/invites/accept', { body: { code } }),
60
+ listCodes: () => call('GET', '/api/v1/admin/credit-codes', { admin: true }),
61
+ mintCode: (input) => call('POST', '/api/v1/admin/credit-codes', { body: input, admin: true }),
62
+ revokeCode: (id) => call('DELETE', `/api/v1/admin/credit-codes/${enc(id)}`, { admin: true })
63
+ };
64
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * HTTP client for self-serve orders (/api/v1/orders/*) — shared by
3
+ * `infernet order` and the `infernet mcp` order tools.
4
+ *
5
+ * Paying:
6
+ * checkout POST with pay: "checkout" -> a CoinPay checkout URL (any coin, PayPal)
7
+ * x402 the 402 offer is signed with X402_PRIVATE_KEY (or --key-file) by
8
+ * @profullstack/x402-client and the reservation comes back in the
9
+ * same call. --max-usd caps what it will sign (default 50).
10
+ */
11
+ import { readFileSync } from 'node:fs';
12
+ import { createClient as createX402Client } from '@profullstack/x402-client';
13
+
14
+ export const DEFAULT_MAX_USD = 50;
15
+
16
+ export function x402KeyFrom({ key, keyFile } = {}) {
17
+ if (key) return String(key).trim();
18
+ if (keyFile) return readFileSync(keyFile, 'utf8').trim();
19
+ return process.env.X402_PRIVATE_KEY ? process.env.X402_PRIVATE_KEY.trim() : null;
20
+ }
21
+
22
+ export function createOrdersClient({ baseUrl, fetchImpl = fetch, x402 = createX402Client }) {
23
+ async function call(method, path, { body, headers = {} } = {}) {
24
+ const res = await fetchImpl(`${baseUrl}${path}`, {
25
+ method,
26
+ headers: { accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...headers },
27
+ body: body === undefined ? undefined : JSON.stringify(body)
28
+ });
29
+ const text = await res.text();
30
+ let json = null;
31
+ try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON */ }
32
+ if (!res.ok) {
33
+ const detail = json?.details ? `: ${json.details.join('; ')}` : json?.hint ? ` (${json.hint})` : '';
34
+ const err = new Error(`${method} ${path} -> HTTP ${res.status} ${json?.error ?? text.slice(0, 200)}${detail}`);
35
+ err.status = res.status;
36
+ err.body = json;
37
+ throw err;
38
+ }
39
+ return json?.data ?? json;
40
+ }
41
+
42
+ return {
43
+ capacity: () => call('GET', '/api/v1/orders/capacity'),
44
+ status: (id, buyerToken) => call('GET', `/api/v1/orders/${encodeURIComponent(id)}`, { headers: { 'x-buyer-token': buyerToken } }),
45
+ /** Quote without paying: the 402 body (offer + quote). */
46
+ async quote(input) {
47
+ const res = await fetchImpl(`${baseUrl}/api/v1/orders`, {
48
+ method: 'POST',
49
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
50
+ body: JSON.stringify(input)
51
+ });
52
+ const json = await res.json().catch(() => null);
53
+ if (res.status === 402) return json;
54
+ throw Object.assign(new Error(`quote -> HTTP ${res.status} ${json?.error ?? ''}${json?.details ? `: ${json.details.join('; ')}` : ''}`), { status: res.status, body: json });
55
+ },
56
+ checkout: (input) => call('POST', '/api/v1/orders', { body: { ...input, pay: 'checkout' } }),
57
+ /** Pay the order's x402 offer and get the reservation back. */
58
+ async payX402(input, { key, maxUsd = DEFAULT_MAX_USD } = {}) {
59
+ if (!key) throw new Error('x402 needs a wallet key: set X402_PRIVATE_KEY or pass --key-file (or pay with --checkout)');
60
+ const client = x402({ key, maxUsd: Number(maxUsd), fetch: fetchImpl });
61
+ const result = await client.pay(`${baseUrl}/api/v1/orders`, {
62
+ init: { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(input) }
63
+ });
64
+ const body = result.body;
65
+ if (result.status >= 400) throw Object.assign(new Error(`order -> HTTP ${result.status} ${body?.error ?? ''}`), { status: result.status, body });
66
+ return { ...(body?.data ?? body), paid_usd: result.amountUsd, payer: result.payer, network: result.network };
67
+ }
68
+ };
69
+ }
70
+
71
+ /** CLI flags -> order body. Kept here so the MCP tool and CLI agree. */
72
+ export function orderBodyFromFlags(get) {
73
+ const body = {
74
+ gpu_class: get('gpu'),
75
+ models: get('models') ? String(get('models')).split(',').map((s) => s.trim()).filter(Boolean) : undefined,
76
+ hours: get('hours') === undefined ? undefined : Number(get('hours')),
77
+ start_at: get('start'),
78
+ name: get('name'),
79
+ email: get('email'),
80
+ provider_id: get('provider-id')
81
+ };
82
+ for (const k of Object.keys(body)) if (body[k] === undefined) delete body[k];
83
+ return body;
84
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infernetprotocol/cli",
3
- "version": "0.1.67",
3
+ "version": "0.1.69",
4
4
  "description": "GPU-node CLI / daemon for the Infernet Protocol — register a GPU server with a Supabase control plane and start earning.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,18 +25,19 @@
25
25
  "@noble/ciphers": "^2.4.0",
26
26
  "@noble/curves": "^2.4.0",
27
27
  "@noble/hashes": "^2.4.0",
28
+ "@profullstack/x402-client": "^0.3.0",
28
29
  "blessed": "^0.1.81",
29
30
  "dotenv": "^18.0.9",
30
31
  "ora": "^9.4.1",
31
32
  "react": "^17.0.2",
32
33
  "react-blessed": "^0.7.2",
33
- "@infernetprotocol/config": "0.1.67",
34
- "@infernetprotocol/deploy-providers": "0.1.67",
35
- "@infernetprotocol/auth": "0.1.67",
36
- "@infernetprotocol/gpu": "0.1.67",
37
- "@infernetprotocol/engine": "0.1.67",
38
- "@infernetprotocol/rpc-adapter": "0.1.67",
39
- "@infernetprotocol/liquid-agent": "0.1.67"
34
+ "@infernetprotocol/auth": "0.1.69",
35
+ "@infernetprotocol/deploy-providers": "0.1.69",
36
+ "@infernetprotocol/config": "0.1.69",
37
+ "@infernetprotocol/engine": "0.1.69",
38
+ "@infernetprotocol/gpu": "0.1.69",
39
+ "@infernetprotocol/liquid-agent": "0.1.69",
40
+ "@infernetprotocol/rpc-adapter": "0.1.69"
40
41
  },
41
42
  "repository": {
42
43
  "type": "git",