smartypants-network 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Howcan (Smarty Pants)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,62 @@
1
- # Temporary Holding Version
1
+ # smartypants: command-line tool for agents
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use [Smarty Pants](https://smartypants.network/docs/agents) from a terminal, a script or an AI agent:
4
+ exact open models priced per token, and sealed Linux workspaces and fleets on idle Macs.
5
+ Node 18 or newer. No dependencies.
6
+
7
+ ```sh
8
+ npm install -g smartypants-network # or: npx smartypants-network help
9
+ ```
10
+
11
+ ```sh
12
+ export SMARTYPANTS_API_KEY=sp_live_... # from https://smartypants.network/api
13
+ smartypants doctor # is the key OK, what can it use
14
+ smartypants models # exact model ids, prices, ready or not
15
+ smartypants ask "Name three planets." # one prompt in, the answer out
16
+ git diff | smartypants ask --system "Review this diff in 5 bullets"
17
+ ```
18
+
19
+ ## Workspaces and fleets
20
+
21
+ Our own account first, for now. Other keys get `CPU_PILOT_ACCOUNT_REQUIRED` until they open.
22
+
23
+ ```sh
24
+ smartypants run python -c 'print(6 * 7)' # one program, then the VM is wiped
25
+
26
+ ID=$(smartypants ws new --minutes 15 --budget 0.50) # one VM, many commands; prints its id
27
+ smartypants ws put $ID script.py # files up to 8 KiB
28
+ smartypants ws exec $ID python script.py # output streams; exit code is the program's
29
+ smartypants ws get $ID out.txt ./out.txt
30
+ smartypants ws end $ID # VM, files and its model key are destroyed
31
+
32
+ F=$(smartypants fleet new --size 4 --minutes 10) # several workspaces at once
33
+ smartypants fleet exec $F sh -c 'nproc; uname -m' # same program on every ready one
34
+ smartypants fleet end $F
35
+ ```
36
+
37
+ `--budget USD` gives each workspace its own model key that can spend at most that much and stops
38
+ working when the workspace ends. It is printed once, on stderr.
39
+ `--internet pypi.org,files.pythonhosted.org` (or `listed`) asks for the approved-sites-only internet,
40
+ once it is switched on.
41
+
42
+ Every command takes `--json` for machine-readable output, plus `--api-key` and `--base-url`.
43
+ Exit codes: 0 ok, 1 the site refused or failed, 2 bad usage, otherwise the program's own exit code.
44
+ `smartypants help` lists every command.
45
+
46
+ ## As a library
47
+
48
+ The package also carries the one-file JavaScript kit:
49
+
50
+ ```js
51
+ import { SmartyPants } from "smartypants-network";
52
+ const sp = new SmartyPants();
53
+ console.log(await sp.ask("Say hello in five words."));
54
+ ```
55
+
56
+ ## For people working on this repo
57
+
58
+ - The kit itself lives in `apps/gateway/agent-kit/smartypants.mjs`; `npm run sync` (and `prepack`)
59
+ copies it here. The copy is not committed.
60
+ - Tests: `node --test packages/cli/test/cli.test.mjs` (offline, against a fake site).
61
+ - MIT licence. Published as `smartypants-network` (plain `smartypants` is taken on npm and PyPI) by
62
+ the "Publish agent packages" workflow; bump `version` first.
@@ -0,0 +1,369 @@
1
+ #!/usr/bin/env node
2
+ // Smarty Pants command-line tool: models, CPU jobs, workspaces and fleets from a terminal or an agent.
3
+ // Built on the one-file JavaScript kit (apps/gateway/agent-kit/smartypants.mjs). Node 18+, no packages.
4
+ // Docs: https://smartypants.network/docs/agents
5
+ import { readFileSync, writeFileSync, existsSync, realpathSync } from "node:fs";
6
+ import { dirname, join, basename } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ export const VERSION = "0.1.0";
10
+ const here = dirname(fileURLToPath(import.meta.url));
11
+
12
+ /** The kit sits next to this file when both are downloaded from /kits/, inside the package (copied at
13
+ * pack time), or in the repo under apps/gateway/agent-kit. */
14
+ async function loadKit() {
15
+ const self = fileURLToPath(import.meta.url);
16
+ for (const candidate of [join(here, "smartypants.mjs"), join(here, "..", "smartypants.mjs"), join(here, "..", "..", "..", "apps", "gateway", "agent-kit", "smartypants.mjs")]) {
17
+ if (candidate !== self && existsSync(candidate)) return import(new URL(`file://${candidate}`).href);
18
+ }
19
+ throw new Error("smartypants.mjs kit not found next to the CLI");
20
+ }
21
+
22
+ export const HELP = `smartypants ${VERSION}: use Smarty Pants from a terminal or an agent.
23
+
24
+ Set SMARTYPANTS_API_KEY first (create one at https://smartypants.network/api).
25
+
26
+ Models
27
+ smartypants models [--kind text|image|audio|embedding] Models with exact ids, prices, ready or not
28
+ smartypants ask [PROMPT | -] [--model ID] [--system TEXT] [--max-tokens N] [--think]
29
+ One prompt in, the answer out (stdin if no prompt)
30
+ Account
31
+ smartypants balance Balance in US dollars
32
+ smartypants credit USD A payment link for your person to pay (charges nothing itself)
33
+ smartypants mcp tools [--public] MCP tools this key can use
34
+ smartypants mcp call TOOL [JSON] [--public] Call one MCP tool
35
+ smartypants doctor Check the key, the site and what this key can use
36
+
37
+ Computers (our own account first, for now)
38
+ smartypants run LANG (FILE | -c CODE | -) [--timeout S] [--wait S]
39
+ One program in a sealed VM, then it is wiped
40
+ smartypants ws new [--minutes N] [--budget USD] [--internet listed|HOST,HOST] [--wait S | --no-wait]
41
+ Open a workspace; prints its id
42
+ smartypants ws status ID
43
+ smartypants ws exec ID LANG (FILE | -c CODE | -) [--timeout S] Output streams; exit code is the program's
44
+ smartypants ws put ID LOCAL [REMOTE] Copy a file in (8 KiB max)
45
+ smartypants ws get ID REMOTE [LOCAL] Copy a file out (stdout if no LOCAL)
46
+ smartypants ws usage ID What the workspace's own model key spent
47
+ smartypants ws end ID End it; its VM and files are destroyed
48
+ smartypants fleet new --size N [--minutes N] [--budget USD] [--wait S | --no-wait]
49
+ smartypants fleet status ID
50
+ smartypants fleet exec ID LANG (FILE | -c CODE | -) [--timeout S] Same program on every ready workspace
51
+ smartypants fleet end ID
52
+
53
+ LANG is python, node or sh.
54
+ Every command takes --json (raw JSON out), --api-key KEY and --base-url URL.
55
+ Exit codes: 0 ok, 1 error from the site, 2 bad usage, otherwise the program's own exit code.
56
+ `;
57
+
58
+ export class UsageError extends Error {}
59
+
60
+ const BOOLEAN_FLAGS = new Set(["json", "think", "public", "no-wait", "help", "version"]);
61
+ const SHORT = { c: "code", h: "help", v: "version" };
62
+
63
+ /** Split argv into positional words and --flags. Flags may come anywhere. */
64
+ export function parseArgs(argv) {
65
+ const positional = [], flags = {};
66
+ for (let i = 0; i < argv.length; i++) {
67
+ const word = argv[i];
68
+ if (word === "--") { positional.push(...argv.slice(i + 1)); break; }
69
+ let name = null, value;
70
+ if (word.startsWith("--") && word.length > 2) {
71
+ const eq = word.indexOf("=");
72
+ name = eq > 0 ? word.slice(2, eq) : word.slice(2);
73
+ if (eq > 0) value = word.slice(eq + 1);
74
+ } else if (/^-[a-z]$/.test(word) && SHORT[word[1]]) name = SHORT[word[1]];
75
+ if (name === null) { positional.push(word); continue; }
76
+ if (BOOLEAN_FLAGS.has(name)) { flags[name] = value === undefined ? true : value !== "false"; continue; }
77
+ if (value === undefined) {
78
+ if (i + 1 >= argv.length) throw new UsageError(`--${name} needs a value`);
79
+ value = argv[++i];
80
+ }
81
+ flags[name] = value;
82
+ }
83
+ return { positional, flags };
84
+ }
85
+
86
+ const LANGS = new Set(["python", "node", "sh"]);
87
+
88
+ function number(flags, name, fallback, { min = -Infinity, max = Infinity } = {}) {
89
+ if (flags[name] === undefined) return fallback;
90
+ const n = Number(flags[name]);
91
+ if (!Number.isFinite(n) || n < min || n > max) throw new UsageError(`--${name} must be a number from ${min} to ${max}`);
92
+ return n;
93
+ }
94
+
95
+ /** Source code from -c CODE, a file, or stdin ("-"). */
96
+ function source(io, words, flags) {
97
+ if (flags.code !== undefined) return String(flags.code);
98
+ const file = words[0];
99
+ if (file === undefined) throw new UsageError("give a FILE, -c CODE, or - for stdin");
100
+ return file === "-" ? io.stdin() : io.readFile(file, "utf8");
101
+ }
102
+
103
+ function language(word) {
104
+ if (!LANGS.has(word)) throw new UsageError(`LANG must be python, node or sh (got ${word ?? "nothing"})`);
105
+ return word;
106
+ }
107
+
108
+ function need(words, i, what) {
109
+ if (words[i] === undefined) throw new UsageError(`missing ${what}`);
110
+ return words[i];
111
+ }
112
+
113
+ function sessionBody(flags) {
114
+ const body = { seconds: Math.round(number(flags, "minutes", 10, { min: 0.5, max: 30 }) * 60) };
115
+ if (flags.budget !== undefined) body.inference = { budgetMicros: Math.round(number(flags, "budget", 0, { min: 0, max: 1000 }) * 1e6) };
116
+ if (flags.internet !== undefined) body.internet = flags.internet === "listed" ? "listed" : { hosts: String(flags.internet).split(",").map((h) => h.trim()).filter(Boolean) };
117
+ return body;
118
+ }
119
+
120
+ const usd = (micros) => (typeof micros === "number" ? `$${(micros / 1e6).toFixed(6)}` : "unknown");
121
+ const sessionPath = (id) => `/v1/cpu/sessions/${encodeURIComponent(id)}`;
122
+ const fleetPath = (id) => `/v1/cpu/fleets/${encodeURIComponent(id)}`;
123
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
124
+
125
+ /** Wait while a workspace is queued. Returns the last view. */
126
+ async function waitReady(sp, id, { waitSeconds, pollMs }) {
127
+ const deadline = Date.now() + waitSeconds * 1000;
128
+ let view = await sp.request("GET", sessionPath(id));
129
+ while (view.status === "queued" && Date.now() < deadline) { await sleep(pollMs); view = await sp.request("GET", sessionPath(id)); }
130
+ return view;
131
+ }
132
+
133
+ /** Run a program in an existing workspace, streaming output through onOutput. */
134
+ async function execIn(kit, sp, id, lang, code, timeoutSeconds, onOutput, pollMs) {
135
+ const ws = new kit.Workspace(sp, id, pollMs);
136
+ return ws.run(lang, code, { timeoutSeconds, onOutput });
137
+ }
138
+
139
+ /** Run one parsed command. io carries stdout/stderr writers, file access and the kit's client. */
140
+ export async function main(argv, io) {
141
+ const { positional, flags } = parseArgs(argv);
142
+ const out = (text) => io.stdout(text.endsWith("\n") ? text : `${text}\n`);
143
+ const json = (value) => out(JSON.stringify(value, null, 2));
144
+ const show = (value, human) => (flags.json ? json(value) : out(human(value)));
145
+ const [command, ...rest] = positional;
146
+ if (flags.version) { out(VERSION); return 0; }
147
+ if (!command || flags.help || command === "help") { io.stdout(HELP); return 0; }
148
+
149
+ const kit = io.kit ?? (await loadKit());
150
+ const sp = new kit.SmartyPants({ apiKey: flags["api-key"] ?? io.env.SMARTYPANTS_API_KEY ?? io.env.SMARTY_PANTS_API_KEY,
151
+ baseUrl: flags["base-url"] ?? io.env.SMARTYPANTS_BASE_URL ?? io.env.SMARTY_PANTS_BASE_URL ?? kit.DEFAULT_BASE_URL,
152
+ model: flags.model ?? null, fetch: io.fetch });
153
+ const pollMs = io.pollMs ?? 1000;
154
+
155
+ switch (command) {
156
+ case "models": {
157
+ let models = (await sp.request("GET", "/v1/models", undefined, { auth: false })).data;
158
+ if (flags.kind) models = models.filter((m) => (m.kind ?? "text") === flags.kind);
159
+ return show(models, (list) => list.map((m) => {
160
+ const perM = (v) => (v === undefined || v === null || v === "" ? "?" : `$${+(Number(v) * 1e6).toFixed(4)}`);
161
+ const price = m.pricing && (m.pricing.prompt !== undefined || m.pricing.completion !== undefined) ? ` ${perM(m.pricing.prompt)} in / ${perM(m.pricing.completion)} out per M tokens` : "";
162
+ return `${m.is_ready ? "ready " : "waiting"} ${(m.kind ?? "text").padEnd(9)} ${m.id}${price}`;
163
+ }).join("\n") || "No models match."), 0;
164
+ }
165
+ case "ask": {
166
+ let prompt = rest.join(" ");
167
+ if (!prompt || prompt === "-") prompt = io.stdin();
168
+ if (!prompt.trim()) throw new UsageError("give a prompt, or pipe one in");
169
+ const options = { thinking: Boolean(flags.think) };
170
+ if (flags.system !== undefined) options.system = flags.system;
171
+ if (flags["max-tokens"] !== undefined) options.max_tokens = number(flags, "max-tokens", 512, { min: 1, max: 1_000_000 });
172
+ if (flags.json) {
173
+ const messages = [...(options.system ? [{ role: "system", content: options.system }] : []), { role: "user", content: prompt }];
174
+ json(await sp.chat(messages, { reasoning: { enabled: options.thinking }, ...(options.max_tokens ? { max_tokens: options.max_tokens } : {}) }));
175
+ } else out(await sp.ask(prompt, options));
176
+ return 0;
177
+ }
178
+ case "balance":
179
+ return show(await sp.balance(), (b) => `Available $${b.available_usd} (free credit $${b.free_credit_usd ?? 0}); spent this month $${b.spent_this_month_usd ?? 0}`), 0;
180
+ case "credit": {
181
+ const amount = Number(need(rest, 0, "USD amount"));
182
+ if (!Number.isFinite(amount) || amount <= 0) throw new UsageError("USD must be a positive number");
183
+ return show(await sp.addCredit(amount), (r) => `Give this link to the person you work for; only they pay it:\n${r.url ?? r.checkout_url ?? JSON.stringify(r)}`), 0;
184
+ }
185
+ case "mcp": {
186
+ const path = flags.public ? "/mcp" : "/mcp/account";
187
+ const sub = need(rest, 0, "tools or call");
188
+ if (sub === "tools") return show(await sp.mcpTools({ path }), (names) => names.join("\n")), 0;
189
+ if (sub === "call") {
190
+ const tool = need(rest, 1, "TOOL");
191
+ let args = {};
192
+ if (rest[2] !== undefined) { try { args = JSON.parse(rest[2]); } catch { throw new UsageError("JSON arguments did not parse"); } }
193
+ json(await sp.mcp(tool, args, { path }));
194
+ return 0;
195
+ }
196
+ throw new UsageError(`unknown mcp command ${sub}`);
197
+ }
198
+ case "doctor": return doctor(sp, io, flags, out, json);
199
+ case "run": {
200
+ const lang = language(rest[0]);
201
+ const code = source(io, rest.slice(1), flags);
202
+ let result;
203
+ try {
204
+ result = await sp.runCode(lang, code, { timeoutSeconds: number(flags, "timeout", 20, { min: 3, max: 30 }),
205
+ waitSeconds: number(flags, "wait", 120, { min: 1, max: 3600 }), pollMs: io.pollMs ?? 5000 });
206
+ } catch (error) {
207
+ // Still waiting for a Mac: cancel it so it doesn't run (and charge) later, after we gave up.
208
+ const id = errorCode(error) === "WAIT_TIMEOUT" && /CPU job (\S+)/.exec(error.message)?.[1];
209
+ if (id) {
210
+ await sp.request("DELETE", `/v1/cpu/jobs/${encodeURIComponent(id)}`).catch(() => null);
211
+ error.message += " (cancelled it; try again later or pass --wait with more seconds)";
212
+ }
213
+ throw error;
214
+ }
215
+ if (flags.json) json(result);
216
+ else {
217
+ if (result.stdout) io.stdout(result.stdout);
218
+ if (result.stderr) io.stderr(result.stderr);
219
+ io.stderr(`[${result.status}, exit ${result.exitCode ?? "none"}, cost ${usd(result.chargeMicros)}]\n`);
220
+ }
221
+ return result.exitCode ?? (result.status === "succeeded" ? 0 : 1);
222
+ }
223
+ case "ws": case "workspace": return workspace(kit, sp, io, rest, flags, { out, json, show, pollMs });
224
+ case "fleet": return fleet(kit, sp, io, rest, flags, { out, json, show, pollMs });
225
+ default: throw new UsageError(`unknown command ${command} (try smartypants help)`);
226
+ }
227
+ }
228
+
229
+ async function workspace(kit, sp, io, words, flags, { out, json, show, pollMs }) {
230
+ const sub = need(words, 0, "a workspace command (new, status, exec, put, get, usage, end)");
231
+ if (sub === "new") {
232
+ let view = await sp.request("POST", "/v1/cpu/sessions", sessionBody(flags));
233
+ const inference = view.inference;
234
+ if (!flags["no-wait"]) view = { ...(await waitReady(sp, view.id, { waitSeconds: number(flags, "wait", 300, { min: 0 }), pollMs })), inference };
235
+ if (flags.json) json(view);
236
+ else {
237
+ out(view.id);
238
+ io.stderr(`[${view.status}${view.reason ? `: ${view.reason}` : ""}; ends after ${Math.round(view.seconds / 60)} min or 10 min idle. End it with: smartypants ws end ${view.id}]\n`);
239
+ if (inference?.apiKey) io.stderr(`[its own model key, shown once: SMARTYPANTS_API_KEY=${inference.apiKey} SMARTYPANTS_BASE_URL=${inference.baseUrl.replace(/\/v1$/, "")}]\n`);
240
+ }
241
+ return view.status === "ready" || view.status === "queued" ? 0 : 1;
242
+ }
243
+ const id = need(words, 1, "workspace ID");
244
+ switch (sub) {
245
+ case "status": return show(await sp.request("GET", sessionPath(id)), (v) => `${v.id} ${v.status}${v.reason ? ` (${v.reason})` : ""}, ${v.requests} commands so far`), 0;
246
+ case "end": return show(await sp.request("DELETE", sessionPath(id)), (v) => `${v.id} ${v.status}`), 0;
247
+ case "usage": return show(await sp.request("GET", `${sessionPath(id)}/inference`), (u) => JSON.stringify(u, null, 2)), 0;
248
+ case "exec": {
249
+ const lang = language(words[2]);
250
+ const code = source(io, words.slice(3), flags);
251
+ const timeoutSeconds = number(flags, "timeout", 60, { min: 1, max: 600 });
252
+ const r = await execIn(kit, sp, id, lang, code, timeoutSeconds, flags.json ? undefined : (stream, text) => (stream === "stderr" ? io.stderr : io.stdout)(text), pollMs);
253
+ if (flags.json) json(r);
254
+ else if (r.timedOut) io.stderr(`[timed out after ${timeoutSeconds} s]\n`);
255
+ return r.exitCode ?? 1;
256
+ }
257
+ case "put": {
258
+ const local = need(words, 2, "LOCAL file");
259
+ await new kit.Workspace(sp, id, pollMs).putFile(words[3] ?? basename(local), io.readFile(local));
260
+ if (flags.json) json({ ok: true }); else io.stderr(`[copied ${local} to ${words[3] ?? basename(local)}]\n`);
261
+ return 0;
262
+ }
263
+ case "get": {
264
+ const remote = need(words, 2, "REMOTE path");
265
+ const bytes = await new kit.Workspace(sp, id, pollMs).getFile(remote);
266
+ if (words[3]) io.writeFile(words[3], bytes);
267
+ else io.stdoutBytes(bytes);
268
+ return 0;
269
+ }
270
+ default: throw new UsageError(`unknown workspace command ${sub}`);
271
+ }
272
+ }
273
+
274
+ async function fleet(kit, sp, io, words, flags, { out, json, show, pollMs }) {
275
+ const sub = need(words, 0, "a fleet command (new, status, exec, end)");
276
+ const summary = (f) => `${f.fleetId}: ${f.sessions.length} workspaces\n${f.sessions.map((s) => ` ${s.id} ${s.status}${s.reason ? ` (${s.reason})` : ""}`).join("\n")}`;
277
+ if (sub === "new") {
278
+ const size = number(flags, "size", NaN, { min: 1, max: 100 });
279
+ if (!Number.isInteger(size)) throw new UsageError("--size N is required (a whole number)");
280
+ let view = await sp.request("POST", "/v1/cpu/fleets", { ...sessionBody(flags), size });
281
+ const keys = Object.fromEntries(view.sessions.map((s) => [s.id, s.inference]));
282
+ if (!flags["no-wait"]) {
283
+ const deadline = Date.now() + number(flags, "wait", 300, { min: 0 }) * 1000;
284
+ while (view.sessions.some((s) => s.status === "queued") && Date.now() < deadline) { await sleep(pollMs); view = await sp.request("GET", fleetPath(view.fleetId)); }
285
+ view = { ...view, sessions: view.sessions.map((s) => ({ ...s, inference: keys[s.id] ?? null })) };
286
+ }
287
+ if (flags.json) json(view);
288
+ else { out(view.fleetId); io.stderr(`${summary(view)}\n[end it with: smartypants fleet end ${view.fleetId}]\n`); }
289
+ return 0;
290
+ }
291
+ const id = need(words, 1, "fleet ID");
292
+ switch (sub) {
293
+ case "status": return show(await sp.request("GET", fleetPath(id)), summary), 0;
294
+ case "end": return show(await sp.request("DELETE", fleetPath(id)), summary), 0;
295
+ case "exec": {
296
+ const lang = language(words[2]);
297
+ const code = source(io, words.slice(3), flags);
298
+ const timeoutSeconds = number(flags, "timeout", 60, { min: 1, max: 600 });
299
+ const view = await sp.request("GET", fleetPath(id));
300
+ const ready = view.sessions.filter((s) => s.status === "ready");
301
+ if (!ready.length) throw new Error(`no workspace in fleet ${id} is ready (${view.sessions.map((s) => s.status).join(", ") || "none"})`);
302
+ const results = await Promise.all(ready.map(async (s) => {
303
+ try { return { id: s.id, ...(await execIn(kit, sp, s.id, lang, code, timeoutSeconds, undefined, pollMs)) }; }
304
+ catch (error) { return { id: s.id, exitCode: null, error: error.message, stdout: "", stderr: "" }; }
305
+ }));
306
+ if (flags.json) json(results);
307
+ else for (const r of results) {
308
+ out(`== ${r.id} exit ${r.exitCode ?? "none"}${r.error ? ` (${r.error})` : ""}${r.timedOut ? " (timed out)" : ""}`);
309
+ if (r.stdout) io.stdout(r.stdout.endsWith("\n") ? r.stdout : `${r.stdout}\n`);
310
+ if (r.stderr) io.stderr(r.stderr.endsWith("\n") ? r.stderr : `${r.stderr}\n`);
311
+ }
312
+ return results.reduce((worst, r) => Math.max(worst, r.exitCode ?? 1), 0);
313
+ }
314
+ default: throw new UsageError(`unknown fleet command ${sub}`);
315
+ }
316
+ }
317
+
318
+ async function doctor(sp, io, flags, out, json) {
319
+ const checks = [];
320
+ const check = async (name, fn) => {
321
+ try { checks.push({ name, ok: true, detail: await fn() }); }
322
+ catch (error) { checks.push({ name, ok: false, detail: error.code ? `${error.code}: ${error.message}` : error.message }); }
323
+ };
324
+ await check("site reachable, models listed", async () => {
325
+ const models = (await sp.request("GET", "/v1/models", undefined, { auth: false })).data;
326
+ return `${models.length} models, ${models.filter((m) => m.is_ready).length} ready`;
327
+ });
328
+ await check("API key set", async () => { if (!sp.apiKey) throw new Error("set SMARTYPANTS_API_KEY"); return `${sp.apiKey.slice(0, 8)}...`; });
329
+ await check("key works (balance)", async () => `$${(await sp.balance()).available_usd} available`);
330
+ await check("MCP tools for this key", async () => (await sp.mcpTools()).join(", "));
331
+ if (flags.json) json(checks);
332
+ else for (const c of checks) out(`${c.ok ? "ok " : "FAIL"} ${c.name}: ${c.detail}`);
333
+ return checks.every((c) => c.ok) ? 0 : 1;
334
+ }
335
+
336
+ /** The site answers some refusals as {"error":"CODE"}; the kit keeps that in error.body. */
337
+ export function errorCode(error) {
338
+ return error?.code ?? (typeof error?.body?.error === "string" ? error.body.error : null);
339
+ }
340
+
341
+ /** Real process wiring. Tests call main() with their own io. */
342
+ export function processIO() {
343
+ return {
344
+ env: process.env,
345
+ fetch: globalThis.fetch,
346
+ stdout: (t) => process.stdout.write(t),
347
+ stdoutBytes: (b) => process.stdout.write(b),
348
+ stderr: (t) => process.stderr.write(t),
349
+ stdin: () => (process.stdin.isTTY ? "" : readFileSync(0, "utf8")),
350
+ readFile: (path, encoding) => readFileSync(path, encoding),
351
+ writeFile: (path, data) => writeFileSync(path, data),
352
+ };
353
+ }
354
+
355
+ const invokedDirectly = (() => {
356
+ try { return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); }
357
+ catch { return false; }
358
+ })();
359
+
360
+ if (invokedDirectly) {
361
+ const io = processIO();
362
+ main(process.argv.slice(2), io).then((code) => { process.exitCode = code; }, (error) => {
363
+ if (error instanceof UsageError) { io.stderr(`smartypants: ${error.message}\n(see smartypants help)\n`); process.exitCode = 2; return; }
364
+ const code = errorCode(error);
365
+ io.stderr(`smartypants: ${error.message}${code && !error.message.includes(code) ? ` [${code}]` : ""}\n`);
366
+ if (code === "CPU_PILOT_ACCOUNT_REQUIRED") io.stderr("Workspaces and CPU jobs are open to our own account first, for now.\n");
367
+ process.exitCode = 1;
368
+ });
369
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "smartypants-network",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Smarty Pants for agents: exact open models priced per token, plus sealed Linux workspaces and fleets on idle Macs. Command-line tool and one-file JavaScript kit, no dependencies.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://smartypants.network/docs/agents",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Howcanio/smarty-pants.git",
11
+ "directory": "packages/cli"
12
+ },
13
+ "keywords": [
14
+ "llm",
15
+ "openai-compatible",
16
+ "mcp",
17
+ "agents",
18
+ "sandbox",
19
+ "cli",
20
+ "apple-silicon"
21
+ ],
22
+ "bin": {
23
+ "smartypants": "bin/smartypants.mjs"
24
+ },
25
+ "exports": {
26
+ ".": "./smartypants.mjs",
27
+ "./cli": "./bin/smartypants.mjs"
28
+ },
29
+ "files": [
30
+ "bin/",
31
+ "smartypants.mjs",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "engines": {
36
+ "node": ">=18"
37
+ },
38
+ "scripts": {
39
+ "sync": "node scripts/sync-kits.mjs",
40
+ "prepack": "node scripts/sync-kits.mjs",
41
+ "test": "node --test test/cli.test.mjs"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ }
46
+ }
@@ -0,0 +1,253 @@
1
+ // Smarty Pants starter kit for JavaScript (Node 18+, Deno, Bun or a browser). No packages needed.
2
+ // Docs: https://smartypants.network/docs/agents
3
+ //
4
+ // import { SmartyPants } from "./smartypants.mjs";
5
+ // const sp = new SmartyPants(); // reads SMARTYPANTS_API_KEY
6
+ // console.log(await sp.ask("Say hello in five words."));
7
+ // console.log(await sp.balance());
8
+ // console.log(await sp.runCode("python", "print(6 * 7)")); // CPU jobs: our own account first, for now
9
+ // const ws = await sp.workspace({ minutes: 10 }); // one VM, many commands
10
+ // try { await ws.putFile("data.txt", "hello"); console.log((await ws.run("sh", "cat data.txt | wc -c")).stdout); }
11
+ // finally { await ws.close(); }
12
+ //
13
+ // Run this file directly for a quick check: SMARTYPANTS_API_KEY=sp_live_... node smartypants.mjs
14
+
15
+ export const DEFAULT_BASE_URL = "https://smartypants.network";
16
+ // No fixed model: the first call picks a ready text model from the live /v1/models list.
17
+ // Pass { model: "smartypants/..." } to choose one yourself.
18
+ export const DEFAULT_MODEL = null;
19
+
20
+ /** The text model to use when none is given: a ready one first, then a released (active) one. */
21
+ export function pickTextModel(models) {
22
+ const text = (models ?? []).filter((m) => (m.kind ?? "text") === "text");
23
+ return (text.find((m) => m.is_ready) ?? text.find((m) => m.status === "active") ?? text[0])?.id ?? null;
24
+ }
25
+
26
+ export class SmartyPantsError extends Error {
27
+ constructor(message, { status = null, code = null, body = null } = {}) {
28
+ super(message);
29
+ this.name = "SmartyPantsError";
30
+ this.status = status;
31
+ this.code = code;
32
+ this.body = body;
33
+ }
34
+ }
35
+
36
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
37
+ const env = (name) => (typeof process !== "undefined" && process.env ? process.env[name] : undefined);
38
+
39
+ export class SmartyPants {
40
+ constructor({ apiKey = env("SMARTYPANTS_API_KEY") || env("SMARTY_PANTS_API_KEY"), baseUrl = env("SMARTYPANTS_BASE_URL") || env("SMARTY_PANTS_BASE_URL") || DEFAULT_BASE_URL, model = DEFAULT_MODEL, fetch: fetchImpl = globalThis.fetch, timeoutMs = 120_000 } = {}) {
41
+ this.apiKey = apiKey;
42
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
43
+ this.model = model;
44
+ this.fetch = fetchImpl;
45
+ this.timeoutMs = timeoutMs;
46
+ this.rpcId = 0;
47
+ }
48
+
49
+ async request(method, path, body, { auth = true, headers = {} } = {}) {
50
+ if (auth && !this.apiKey) throw new SmartyPantsError("No API key. Set SMARTYPANTS_API_KEY (create one at https://smartypants.network/api).");
51
+ const response = await this.fetch(`${this.baseUrl}${path}`, {
52
+ method,
53
+ headers: { accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }), ...(auth ? { authorization: `Bearer ${this.apiKey}` } : {}), ...headers },
54
+ body: body === undefined ? undefined : JSON.stringify(body),
55
+ signal: AbortSignal.timeout(this.timeoutMs),
56
+ });
57
+ const text = await response.text();
58
+ let data = null;
59
+ try { data = text ? JSON.parse(text) : null; } catch { data = text; }
60
+ if (!response.ok) {
61
+ const error = data && typeof data === "object" ? data.error ?? data : null;
62
+ const message = (error && (error.message || error.error_description)) || `HTTP ${response.status}`;
63
+ throw new SmartyPantsError(`${method} ${path} failed (${response.status}): ${message}`, { status: response.status, code: error?.code ?? error?.type ?? null, body: data });
64
+ }
65
+ return data;
66
+ }
67
+
68
+ /** Every model with exact id, price per token and is_ready. */
69
+ async models() {
70
+ return (await this.request("GET", "/v1/models")).data;
71
+ }
72
+
73
+ /** OpenAI-format chat completion. Pass any extra OpenAI fields in `options`. */
74
+ async chat(messages, options = {}) {
75
+ return this.request("POST", "/v1/chat/completions", { model: await this.textModel(), max_tokens: 512, ...options, messages });
76
+ }
77
+
78
+ /** The model chat() uses: the one you passed, or a ready text model from the live list (looked up once). */
79
+ async textModel() {
80
+ if (!this.model) {
81
+ this.model = pickTextModel(await this.models());
82
+ if (!this.model) throw new SmartyPantsError("No text model is offered right now. See https://smartypants.network/v1/models.");
83
+ }
84
+ return this.model;
85
+ }
86
+
87
+ /** One prompt in, the answer text out. Thinking is off unless you pass { thinking: true }. */
88
+ async ask(prompt, options = {}) {
89
+ const { system, thinking = false, ...rest } = options;
90
+ const reply = await this.chat([...(system ? [{ role: "system", content: system }] : []), { role: "user", content: prompt }], { reasoning: { enabled: thinking }, ...rest });
91
+ return reply.choices?.[0]?.message?.content ?? "";
92
+ }
93
+
94
+ /** Call a tool on the MCP server. Signed-in tools live at /mcp/account; the no-sign-in ones at /mcp. */
95
+ async mcp(tool, args = {}, { path = "/mcp/account" } = {}) {
96
+ const rpc = await this.request("POST", path, { jsonrpc: "2.0", id: ++this.rpcId, method: "tools/call", params: { name: tool, arguments: args } },
97
+ { auth: path !== "/mcp", headers: { accept: "application/json, text/event-stream" } });
98
+ if (rpc.error) throw new SmartyPantsError(`MCP ${tool}: ${rpc.error.message}`, { code: rpc.error.code, body: rpc });
99
+ if (rpc.result?.isError) throw new SmartyPantsError(`MCP ${tool}: ${rpc.result.content?.[0]?.text ?? "tool error"}`, { body: rpc });
100
+ return rpc.result?.structuredContent ?? JSON.parse(rpc.result?.content?.[0]?.text ?? "null");
101
+ }
102
+
103
+ /** Names of the MCP tools this key can use. */
104
+ async mcpTools({ path = "/mcp/account" } = {}) {
105
+ const rpc = await this.request("POST", path, { jsonrpc: "2.0", id: ++this.rpcId, method: "tools/list" },
106
+ { auth: path !== "/mcp", headers: { accept: "application/json, text/event-stream" } });
107
+ return (rpc.result?.tools ?? []).map((t) => t.name);
108
+ }
109
+
110
+ /** Balance in US dollars: available_usd, free_credit_usd, spent_this_month_usd. */
111
+ async balance() {
112
+ return this.mcp("get_balance");
113
+ }
114
+
115
+ /**
116
+ * A Stripe payment page for adding credit. This charges nothing: give the link to the person you
117
+ * work for, and only they pay it. Never handle card details. The balance updates about a minute after they pay.
118
+ */
119
+ async addCredit(amountUsd) {
120
+ return this.mcp("add_credit", { amount_usd: amountUsd });
121
+ }
122
+
123
+ /**
124
+ * Run a short program in a sealed Linux VM on a Mac (no network, wiped after).
125
+ * Open to our own account first; other accounts get 403 CPU_PILOT_ACCOUNT_REQUIRED until it opens.
126
+ * language: "python", "node" or "sh"; timeoutSeconds 3 to 30.
127
+ * Returns { id, status, exitCode, timedOut, stdout, stderr, stdoutTruncated, stderrTruncated, chargeMicros }.
128
+ */
129
+ async runCode(language, source, { timeoutSeconds = 20, pollMs = 5000, waitSeconds = 120 } = {}) {
130
+ const idempotencyKey = `kit-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
131
+ const job = await this.request("POST", "/v1/cpu/jobs", { runtime: "code-v1", language, source, timeoutMs: Math.round(timeoutSeconds * 1000), idempotencyKey });
132
+ const id = job.id;
133
+ const done = new Set(["succeeded", "failed", "timed_out", "cancelled", "expired"]);
134
+ const deadline = Date.now() + waitSeconds * 1000;
135
+ let status = job.status;
136
+ while (!done.has(status)) {
137
+ if (Date.now() > deadline) throw new SmartyPantsError(`CPU job ${id} still ${status} after ${waitSeconds} s`, { code: "WAIT_TIMEOUT" });
138
+ await sleep(pollMs);
139
+ status = (await this.request("GET", `/v1/cpu/jobs/${encodeURIComponent(id)}`)).status;
140
+ }
141
+ const enc = encodeURIComponent(id);
142
+ const finished = status === "succeeded" || status === "failed" || status === "timed_out";
143
+ const out = finished ? (await this.request("GET", `/v1/cpu/jobs/${enc}/result`).catch(() => null))?.result ?? {} : {};
144
+ const usage = await this.request("GET", `/v1/cpu/jobs/${enc}/usage`).catch(() => null);
145
+ const charges = (Array.isArray(usage) ? usage : usage ? [usage] : []).map((u) => u?.chargeMicros).filter((n) => typeof n === "number");
146
+ return { id, status, exitCode: out.exitCode ?? null, timedOut: out.timedOut ?? status === "timed_out", stdout: out.stdout ?? "", stderr: out.stderr ?? "",
147
+ stdoutTruncated: out.stdoutTruncated ?? false, stderrTruncated: out.stderrTruncated ?? false, chargeMicros: charges.length ? charges.reduce((a, b) => a + b, 0) : null };
148
+ }
149
+
150
+ /**
151
+ * Open a workspace: one sealed VM that keeps its files across many commands until it ends
152
+ * (at most 2 hours, 10 minutes idle, or when the Mac's owner comes back). Always close() it.
153
+ * Our own account first, for now.
154
+ * inferenceBudgetUsd gives the workspace its own Smarty Pants key (ws.inference.apiKey and
155
+ * ws.inference.baseUrl) that can spend at most that much and stops working when it ends.
156
+ */
157
+ async workspace({ minutes = 10, waitSeconds = 120, pollMs = 1000, inferenceBudgetUsd } = {}) {
158
+ const body = { seconds: Math.round(minutes * 60) };
159
+ if (inferenceBudgetUsd !== undefined) body.inference = { budgetMicros: Math.round(inferenceBudgetUsd * 1e6) };
160
+ let session = await this.request("POST", "/v1/cpu/sessions", body);
161
+ const ws = new Workspace(this, session.id, pollMs);
162
+ ws.inference = session.inference ?? null;
163
+ const deadline = Date.now() + waitSeconds * 1000;
164
+ while (session.status === "queued") {
165
+ if (Date.now() > deadline) { await ws.close(); throw new SmartyPantsError(`workspace ${session.id} still waiting for a Mac after ${waitSeconds} s`, { code: "WAIT_TIMEOUT" }); }
166
+ await sleep(pollMs);
167
+ session = await ws.status();
168
+ }
169
+ if (session.status !== "ready") throw new SmartyPantsError(`workspace ${session.id} ended: ${session.reason}`, { code: session.reason });
170
+ return ws;
171
+ }
172
+ }
173
+
174
+ const PIECE = 256 * 1024;
175
+ const AHEAD = 4;
176
+
177
+ /** One VM session. run(), putFile() and getFile() go to the guest one at a time. */
178
+ export class Workspace {
179
+ constructor(sp, id, pollMs) { this.sp = sp; this.id = id; this.pollMs = pollMs; this.path = `/v1/cpu/sessions/${encodeURIComponent(id)}`; }
180
+ status() { return this.sp.request("GET", this.path); }
181
+ /** End the workspace. Its VM, files and disk are destroyed. */
182
+ close() { return this.sp.request("DELETE", this.path).catch(() => null); }
183
+ async wait(requestId, waitSeconds, onOutput) {
184
+ const offsets = { stdout: 0, stderr: 0 };
185
+ const deadline = Date.now() + waitSeconds * 1000;
186
+ for (;;) {
187
+ const r = await this.sp.request("GET", `${this.path}/requests/${requestId}?stdoutOffset=${offsets.stdout}&stderrOffset=${offsets.stderr}`);
188
+ for (const stream of ["stdout", "stderr"]) {
189
+ if (!r[stream]) continue;
190
+ if (onOutput && r[stream].text) onOutput(stream, r[stream].text);
191
+ offsets[stream] = r[stream].nextOffset;
192
+ }
193
+ if (r.done) {
194
+ if (r.error) throw new SmartyPantsError(`workspace request ${requestId} failed: ${r.error}`, { code: r.error });
195
+ return r;
196
+ }
197
+ if (Date.now() > deadline) throw new SmartyPantsError(`workspace request ${requestId} still running after ${waitSeconds} s`, { code: "WAIT_TIMEOUT" });
198
+ await sleep(this.pollMs);
199
+ }
200
+ }
201
+ /** Run a program ("python", "node" or "sh"). onOutput(stream, text) gets output as it arrives. */
202
+ async run(language, source, { timeoutSeconds = 60, onOutput } = {}) {
203
+ const { requestId } = await this.sp.request("POST", `${this.path}/exec`, { language, source, timeoutSeconds: Math.round(timeoutSeconds) });
204
+ const out = { stdout: "", stderr: "" };
205
+ const r = await this.wait(requestId, timeoutSeconds + 30, (stream, text) => { out[stream] += text; onOutput?.(stream, text); });
206
+ return { exitCode: r.exitCode ?? null, timedOut: r.timedOut ?? null, ...out };
207
+ }
208
+ /** Write a file (string or bytes, up to 64 MiB) at a relative path in the workspace. */
209
+ async putFile(path, content) {
210
+ const data = Buffer.from(content);
211
+ if (data.length <= 8 * 1024) {
212
+ const { requestId } = await this.sp.request("POST", `${this.path}/files`, { path, contentBase64: data.toString("base64") });
213
+ await this.wait(requestId, 60);
214
+ return;
215
+ }
216
+ // Larger files move in 256 KiB pieces, a few at a time; the site keeps them in order.
217
+ const waiting = [];
218
+ for (let offset = 0; offset < data.length; offset += PIECE) {
219
+ const contentBase64 = data.subarray(offset, offset + PIECE).toString("base64");
220
+ waiting.push((await this.sp.request("POST", `${this.path}/files`, { path, offset, contentBase64 })).requestId);
221
+ if (waiting.length >= AHEAD) await this.wait(waiting.shift(), 120);
222
+ }
223
+ for (const id of waiting) await this.wait(id, 120);
224
+ }
225
+ /** Read a file (up to 64 MiB) from the workspace, as a Buffer. */
226
+ async getFile(path) {
227
+ const q = encodeURIComponent(path);
228
+ const { requestId } = await this.sp.request("GET", `${this.path}/files?path=${q}`);
229
+ try {
230
+ return Buffer.from((await this.wait(requestId, 60)).contentBase64 ?? "", "base64");
231
+ } catch (error) {
232
+ if (error.code !== "TOO_LARGE") throw error;
233
+ }
234
+ const piece = async offset => (await this.sp.request("GET", `${this.path}/files?path=${q}&offset=${offset}`)).requestId;
235
+ const first = await this.wait(await piece(0), 120);
236
+ const parts = [Buffer.from(first.contentBase64 ?? "", "base64")];
237
+ const offsets = [];
238
+ for (let offset = PIECE; offset < first.size; offset += PIECE) offsets.push(offset);
239
+ const waiting = [];
240
+ while (offsets.length || waiting.length) {
241
+ while (offsets.length && waiting.length < AHEAD) waiting.push(await piece(offsets.shift()));
242
+ parts.push(Buffer.from((await this.wait(waiting.shift(), 120)).contentBase64 ?? "", "base64"));
243
+ }
244
+ return Buffer.concat(parts);
245
+ }
246
+ }
247
+
248
+ // Quick check when run directly: node smartypants.mjs
249
+ if (typeof process !== "undefined" && process.argv?.[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
250
+ const sp = new SmartyPants();
251
+ console.log("Balance:", await sp.balance());
252
+ console.log("Answer:", await sp.ask("Name three planets, comma separated.", { max_tokens: 40 }));
253
+ }