toolpal 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/dist/cli.js ADDED
@@ -0,0 +1,817 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises";
3
+ import { basename, resolve } from "node:path";
4
+ import { analyzeBundle } from "@toolpal/analyzer";
5
+ import { BuildError, buildTool, bundle, packTool, readProjectPackage } from "@toolpal/builder";
6
+ import { describePermissions, fileFields, keyIdOf, ManifestError, mergePermissions, normalizePermissions, parseToolRef, permissionsFromReport, publicKeyFromX, splitToolName, } from "@toolpal/manifest";
7
+ import { accountMcpTools, DEFAULT_REGISTRY, explicitMcpTools, INSTALL_TOOL, normalizeRegistryUrl, PUBLISH_TOOL, RegistryClient, SEARCH_TOOL, serveAccountMcp, serveMcpStdio, Toolpal, ToolpalError, toolpalHome, UPDATE_TOOL, UserConfigStore, } from "@toolpal/runtime";
8
+ import { NODE_ADVISORIES, nodeAdvisoriesFor, resolveNodeRuntime, SandboxError, Supervisor, } from "@toolpal/sandbox";
9
+ import { Argument, Command, Option } from "commander";
10
+ import { sourceAuthoring } from "./authoring.js";
11
+ import { bold, dim, err, formatBytes, green, out, printFlags, printPermissions, printReport, red, yellow, } from "./format.js";
12
+ import { scaffoldTool } from "./init.js";
13
+ import { browserLogin } from "./login.js";
14
+ import { verifyBuild } from "./verify-build.js";
15
+ const VERSION = "0.1.0";
16
+ function globals(cmd) {
17
+ return cmd.optsWithGlobals();
18
+ }
19
+ function projectDir(cmd) {
20
+ return resolve(globals(cmd).cwd ?? process.cwd());
21
+ }
22
+ function logToStderr(entry) {
23
+ if (entry.level === "debug" && !process.env.TOOLPAL_DEBUG)
24
+ return;
25
+ const prefix = entry.source === "tool" ? dim(`[${entry.tool}]`) : dim("[toolpal]");
26
+ const level = entry.level === "warn"
27
+ ? yellow("warn")
28
+ : entry.level === "error"
29
+ ? red("error")
30
+ : dim(entry.level);
31
+ err(`${prefix} ${level} ${entry.message}${entry.data !== undefined ? ` ${dim(JSON.stringify(entry.data))}` : ""}`);
32
+ }
33
+ function toolpalFor(cmd, extra = {}) {
34
+ const g = globals(cmd);
35
+ return new Toolpal({
36
+ projectDir: projectDir(cmd),
37
+ registry: g.registry,
38
+ onLog: logToStderr,
39
+ ...extra,
40
+ });
41
+ }
42
+ async function registryUrl(cmd) {
43
+ const g = globals(cmd);
44
+ const user = await new UserConfigStore(toolpalHome()).read();
45
+ let fromProject;
46
+ try {
47
+ fromProject = JSON.parse(await readFile(resolve(projectDir(cmd), "toolpal.json"), "utf8")).registry;
48
+ }
49
+ catch {
50
+ // no toolpal.json
51
+ }
52
+ return normalizeRegistryUrl(g.registry ??
53
+ fromProject ??
54
+ process.env.TOOLPAL_REGISTRY ??
55
+ user.defaultRegistry ??
56
+ DEFAULT_REGISTRY);
57
+ }
58
+ async function client(cmd) {
59
+ const url = await registryUrl(cmd);
60
+ const user = await new UserConfigStore(toolpalHome()).read();
61
+ return new RegistryClient(url, process.env.TOOLPAL_TOKEN ?? user.registries[url]?.token);
62
+ }
63
+ /**
64
+ * `@scope/name` as given; a bare name gets the signed-in user's scope (their username).
65
+ * The registry is asked each time: the login saved by `toolpal login` can be stale, or
66
+ * belong to a different account than TOOLPAL_TOKEN.
67
+ */
68
+ async function scopedToolName(cmd, name) {
69
+ if (name.startsWith("@"))
70
+ return name;
71
+ try {
72
+ const { login } = await (await client(cmd)).me();
73
+ return `@${login}/${name}`;
74
+ }
75
+ catch (e) {
76
+ if (!(e instanceof ToolpalError))
77
+ throw e;
78
+ throw new ToolpalError(e.code, `${e.message}
79
+ could not look up your username: run \`toolpal login\`, or pass --name @your-username/${name}`);
80
+ }
81
+ }
82
+ /** Trust-on-first-use: pin the registry's signing keys unless keys are already pinned. */
83
+ async function pinRegistryKeys(url, replace) {
84
+ const keys = await new RegistryClient(url).keys();
85
+ for (const k of keys) {
86
+ if (keyIdOf(publicKeyFromX(k.x)) !== k.keyId)
87
+ throw new Error(`registry key ${k.keyId} does not match its key id`);
88
+ }
89
+ const store = new UserConfigStore(toolpalHome());
90
+ const current = (await store.read()).registries[url]?.keys ?? [];
91
+ const same = current.length === keys.length &&
92
+ current.every((c) => keys.some((k) => k.keyId === c.keyId && k.x === c.x));
93
+ if (current.length > 0 && !same && !replace) {
94
+ err(yellow(`warning: ${url} now presents different signing keys than the ones you pinned.`));
95
+ err(yellow(" Not changing trust. Run `toolpal trust --replace` only if the registry announced a key rotation."));
96
+ return;
97
+ }
98
+ await store.update((cfg) => {
99
+ cfg.registries[url] = { ...(cfg.registries[url] ?? { keys: [] }), keys };
100
+ });
101
+ for (const k of keys)
102
+ out(`${same ? "trusted" : green("pinned")} signing key ${bold(k.keyId)} for ${url}`);
103
+ }
104
+ async function run(action) {
105
+ try {
106
+ await action();
107
+ }
108
+ catch (e) {
109
+ if (e instanceof ToolpalError || e instanceof SandboxError) {
110
+ err(`${red("error")} ${e.code}: ${e.message}`);
111
+ const findings = e.details?.findings;
112
+ for (const f of findings ?? [])
113
+ err(dim(` L${f.line}:${f.col} ${f.detail} ${f.snippet ?? ""}`));
114
+ }
115
+ else if (e instanceof BuildError || e instanceof ManifestError) {
116
+ err(`${red("error")} ${e.message}`);
117
+ }
118
+ else {
119
+ err(`${red("error")} ${e?.stack ?? e}`);
120
+ }
121
+ process.exitCode = 1;
122
+ }
123
+ }
124
+ const program = new Command()
125
+ .name("toolpal")
126
+ .description("Local-first package manager and sandboxed runtime for AI agent tools")
127
+ .version(VERSION)
128
+ .option("-C, --cwd <dir>", "project directory (default: current directory)")
129
+ .option("--registry <url>", "registry URL");
130
+ // ---------------------------------------------------------------------------
131
+ // Authoring
132
+ // ---------------------------------------------------------------------------
133
+ program
134
+ .command("init")
135
+ .description("scaffold a new tool project")
136
+ .argument("[dir]", "directory to create", ".")
137
+ .option("--name <name>", "tool name (default: the directory's name); a bare name goes in your own scope, @your-username")
138
+ .action((dir, opts, cmd) => run(async () => {
139
+ const target = resolve(projectDir(cmd), dir);
140
+ const name = await scopedToolName(cmd, opts.name ?? basename(target));
141
+ const files = await scaffoldTool(target, name);
142
+ out(`created ${name} in ${target}`);
143
+ for (const f of files)
144
+ out(dim(` ${f}`));
145
+ out(`\nnext: ${bold("npm install")} && ${bold("toolpal build")}`);
146
+ }));
147
+ program
148
+ .command("build")
149
+ .description("bundle the tool, derive its permissions and write dist/manifest.json")
150
+ .argument("[dir]", "tool project directory", ".")
151
+ .option("-v, --verbose", "list every analyzer finding")
152
+ .option("-e, --env <KEY=VALUE...>", "env var passed when capturing outputs for declared examples (only declared vars are passed)")
153
+ .option("--no-examples", "skip running declared examples during build")
154
+ .action((dir, opts, cmd) => run(async () => {
155
+ const exampleEnv = Object.fromEntries((opts.env ?? []).map((pair) => {
156
+ const eq = pair.indexOf("=");
157
+ return eq === -1 ? [pair, process.env[pair]] : [pair.slice(0, eq), pair.slice(eq + 1)];
158
+ }));
159
+ const result = await buildTool({
160
+ projectDir: resolve(projectDir(cmd), dir),
161
+ exampleEnv,
162
+ runExamples: opts.examples,
163
+ });
164
+ const m = result.manifest;
165
+ // A build has no version: `toolpal publish` gives it the tool's next one.
166
+ out(`${green("built")} ${bold(m.name)} ${dim(`(${formatBytes(result.bundle.length)}, ${result.entryIntegrity.slice(0, 22)}…)`)}`);
167
+ out(bold("Permissions"));
168
+ printPermissions(m.permissions);
169
+ printFlags(result.flags);
170
+ if (m.examples?.length) {
171
+ const captured = m.examples.filter((e) => e.output !== undefined).length;
172
+ out(bold("Examples"));
173
+ out(` ${captured}/${m.examples.length} captured from sandbox run${captured < m.examples.length ? dim(" (inputs only for skipped examples)") : ""}`);
174
+ }
175
+ printReport(result.report, opts.verbose);
176
+ }));
177
+ program
178
+ .command("analyze")
179
+ .description("statically analyze a tool project or a bundle file")
180
+ .argument("[path]", "tool project directory or .mjs bundle", ".")
181
+ .action((path, _opts, cmd) => run(async () => {
182
+ const target = resolve(projectDir(cmd), path);
183
+ let code;
184
+ if (target.endsWith(".mjs") || target.endsWith(".js")) {
185
+ code = await readFile(target, "utf8");
186
+ }
187
+ else {
188
+ const pkg = await readProjectPackage(target);
189
+ code = (await bundle(target, pkg.toolpal.entry)).toString("utf8");
190
+ const report = analyzeBundle(code);
191
+ out(bold("Permissions this code needs"));
192
+ printPermissions(mergePermissions(permissionsFromReport(report), pkg.toolpal.permissions));
193
+ printReport(report, true);
194
+ return;
195
+ }
196
+ printReport(analyzeBundle(code), true);
197
+ }));
198
+ program
199
+ .command("publish")
200
+ .description("build, pack and upload the tool to the registry, as its next version (1.0, 2.0, 3.0, …)")
201
+ .argument("[dir]", "tool project directory", ".")
202
+ .option("--dry-run", "validate everything (including on the registry) without publishing")
203
+ .option("--no-build", "publish the existing dist/ as-is")
204
+ .option("--private", "the tool is private: only you can see, install or run it (refused if it is already public)")
205
+ .option("--public", "the tool is public, the default for a new one (refused if it is private)")
206
+ .action((dir, opts, cmd) => run(async () => {
207
+ if (opts.private && opts.public)
208
+ throw new Error("choose one of --private and --public");
209
+ const visibility = opts.private ? "private" : opts.public ? "public" : undefined;
210
+ const target = resolve(projectDir(cmd), dir);
211
+ const api = await client(cmd);
212
+ // Who we are comes from the registry, before any work: the saved login can be stale.
213
+ const me = await api.me();
214
+ const { name } = await readProjectPackage(target);
215
+ const { scope, name: base } = splitToolName(name);
216
+ if (!me.scopes.includes(scope)) {
217
+ throw new ToolpalError("UNAUTHORIZED", `${name} is in @${scope}, but you are signed in as ${me.login}. Set "name" in package.json to @${me.login}/${base}, or sign in as the owner of @${scope}.`);
218
+ }
219
+ if (opts.build)
220
+ await buildTool({ projectDir: target });
221
+ // Nobody chooses a version: the registry numbers each publish 1.0, 2.0, 3.0, …
222
+ let pack = await packTool(target, { version: await api.nextVersion(name) });
223
+ const m = pack.manifest;
224
+ if (m.name !== name) {
225
+ throw new BuildError(`dist/ was built as ${m.name}, but package.json says ${name}; run \`toolpal build\``);
226
+ }
227
+ out(`${bold(`${name}@${m.version}`)} ${dim(`${formatBytes(pack.tarball.length)} packed, ${pack.files.length} files`)}`);
228
+ for (const f of pack.files)
229
+ out(dim(` ${formatBytes(f.size).padStart(9)} ${f.path}`));
230
+ out(bold("Permissions"));
231
+ printPermissions(m.permissions);
232
+ let res;
233
+ for (let attempt = 1;; attempt++) {
234
+ try {
235
+ res = await api.publish(name, pack.manifest.version, pack.tarball, pack.integrity, {
236
+ dryRun: opts.dryRun,
237
+ visibility,
238
+ });
239
+ break;
240
+ }
241
+ catch (e) {
242
+ const code = e instanceof ToolpalError ? e.details.registryCode : undefined;
243
+ if (attempt >= 3 || (code !== "VERSION_NOT_NEXT" && code !== "VERSION_EXISTS"))
244
+ throw e;
245
+ // Another publish of this tool took the number first, so this one is the next.
246
+ const taken = pack.manifest.version;
247
+ pack = await packTool(target, { version: await api.nextVersion(name) });
248
+ out(dim(` ${taken} went to another publish; this one is ${pack.manifest.version}`));
249
+ }
250
+ }
251
+ printFlags(res.flags);
252
+ if (opts.dryRun) {
253
+ out(green(`dry run OK on ${api.baseUrl}: nothing was published`));
254
+ }
255
+ else {
256
+ const shown = res.visibility === "private"
257
+ ? ` ${yellow("(private: only you can see or install it)")}`
258
+ : res.visibility === "public"
259
+ ? ` ${dim("(public)")}`
260
+ : "";
261
+ out(`${green("published")} ${res.id}${shown} → ${res.url}`);
262
+ }
263
+ // A registry from before private tools ignores the request and publishes for everyone.
264
+ if (visibility === "private" && res.visibility !== "private") {
265
+ throw new ToolpalError("REGISTRY_ERROR", opts.dryRun
266
+ ? `${api.baseUrl} does not support private tools; publishing there would make ${m.name} public`
267
+ : `${api.baseUrl} does not support private tools, so ${res.id} is PUBLIC. Yank it with \`toolpal yank ${res.id}\` if it must not be installed.`);
268
+ }
269
+ }));
270
+ // ---------------------------------------------------------------------------
271
+ // Consuming
272
+ // ---------------------------------------------------------------------------
273
+ program
274
+ .command("run")
275
+ .description("run a tool added to this project and print its JSON output")
276
+ .argument("<tool>", "@scope/name[@range] of an added tool, or a path to a built tool")
277
+ .option("-i, --input <json>", "input object as JSON", "{}")
278
+ .option("-e, --env <KEY=VALUE...>", "env var for the tool (only declared vars are passed)")
279
+ .option("-t, --timeout <ms>", "timeout in milliseconds")
280
+ .option("-o, --out <dir>", "where files the tool produces are put (default: a new folder under the OS temp directory)")
281
+ .action((tool, opts, cmd) => run(async () => {
282
+ const env = Object.fromEntries((opts.env ?? []).map((pair) => {
283
+ const eq = pair.indexOf("=");
284
+ return eq === -1 ? [pair, process.env[pair]] : [pair.slice(0, eq), pair.slice(eq + 1)];
285
+ }));
286
+ const tp = toolpalFor(cmd);
287
+ try {
288
+ const output = await tp.execute({
289
+ tool,
290
+ input: JSON.parse(opts.input),
291
+ env,
292
+ ...(opts.out ? { outputDir: resolve(opts.out) } : {}),
293
+ ...(opts.timeout ? { timeoutMs: Number(opts.timeout) } : {}),
294
+ });
295
+ out(JSON.stringify(output, null, 2));
296
+ }
297
+ finally {
298
+ await tp.close();
299
+ }
300
+ }));
301
+ /** What `toolpal add` prints for each tool it added. */
302
+ function printAdded(info) {
303
+ out(`${green("+")} ${bold(`${info.name}@${info.version}`)} ${dim(info.description)}`);
304
+ out(` ${dim("publisher")} ${info.publisher ?? "?"}${info.verified ? green(" ✓ verified") : ""} ${dim("added by")} ${info.stars ?? 0} ${dim("downloads")} ${info.downloads ?? 0}`);
305
+ if (info.deprecated)
306
+ out(` ${yellow("deprecated")} ${info.deprecated}`);
307
+ printPermissions(info.permissions);
308
+ if (info.hosts?.length)
309
+ out(dim(` contacts: ${info.hosts.join(", ")}`));
310
+ printFlags(info.flags);
311
+ }
312
+ /** The account holds whole tools: `toolpal mcp` installs the newest version of each. */
313
+ function accountToolName(ref) {
314
+ const parsed = parseToolRef(ref);
315
+ if (parsed.kind !== "registry") {
316
+ throw new ToolpalError("INVALID_REF", `expected @scope/name, got ${ref}`);
317
+ }
318
+ if (parsed.range !== undefined && parsed.range !== "latest") {
319
+ throw new ToolpalError("INVALID_REF", `${ref}: your account gets a tool's newest version, so leave out @${parsed.range}`);
320
+ }
321
+ return parsed.name;
322
+ }
323
+ async function signedInClient(account) {
324
+ const api = await account.client();
325
+ if (!api.signedIn) {
326
+ throw new ToolpalError("UNAUTHORIZED", `not signed in to ${api.baseUrl}; run \`toolpal login\` first`);
327
+ }
328
+ return api;
329
+ }
330
+ /**
331
+ * `toolpal add --account`: adds the tools to the signed-in user's account, which is
332
+ * what `toolpal mcp` serves, and installs them there now to show what they may do.
333
+ */
334
+ async function addToAccount(cmd, refs) {
335
+ const names = refs.map(accountToolName);
336
+ const account = await Toolpal.forAccount({ registry: globals(cmd).registry, onLog: () => { } });
337
+ try {
338
+ const api = await signedInClient(account);
339
+ for (const name of names)
340
+ await api.star(name, true);
341
+ const sync = await account.syncAccount();
342
+ for (const name of names) {
343
+ if (sync.tools.includes(name)) {
344
+ printAdded(await account.describe(name));
345
+ continue;
346
+ }
347
+ const why = sync.unavailable[name] ?? "the registry could not be reached to install it";
348
+ err(`${red("error")} ${name} is on your account, but cannot run yet: ${why}`);
349
+ process.exitCode = 1;
350
+ }
351
+ out(dim("\nPermissions are granted as declared. A `toolpal mcp` server that is already running serves them after a restart."));
352
+ }
353
+ finally {
354
+ await account.close();
355
+ }
356
+ }
357
+ program
358
+ .command("add")
359
+ .description("add tools to this project, pinning their exact version, and show what they may do")
360
+ .argument("<tools...>", "@scope/name[@range]")
361
+ .option("--account", "add them to your Toolpal account instead, so `toolpal mcp` serves them wherever you sign in")
362
+ .action((tools, opts, cmd) => run(async () => {
363
+ if (opts.account)
364
+ return addToAccount(cmd, tools);
365
+ const tp = toolpalFor(cmd, { onLog: () => { } });
366
+ try {
367
+ for (const ref of tools)
368
+ printAdded(await tp.describe(ref, { fetch: true }));
369
+ out(dim("\nPermissions are granted as declared. Review them with `toolpal info` before relying on a tool."));
370
+ }
371
+ finally {
372
+ await tp.close();
373
+ }
374
+ }));
375
+ program
376
+ .command("install")
377
+ .description("install everything in toolpal.json")
378
+ .option("--frozen-lockfile", "fail instead of changing toolpal.lock")
379
+ .action((opts, cmd) => run(async () => {
380
+ const tp = toolpalFor(cmd);
381
+ try {
382
+ const infos = await tp.installAll({ frozen: opts.frozenLockfile });
383
+ for (const i of infos)
384
+ out(`${green("✓")} ${i.name}@${i.version} ${dim(describePermissions(i.permissions).join("; "))}`);
385
+ if (infos.length === 0)
386
+ out(dim("nothing to install (toolpal.json lists no tools)"));
387
+ }
388
+ finally {
389
+ await tp.close();
390
+ }
391
+ }));
392
+ program
393
+ .command("update")
394
+ .description("move tools to their newest version and record it in toolpal.json")
395
+ .argument("[tool]", "only this tool")
396
+ .option("--account", "update the tools `toolpal mcp` serves instead of this project's: a tool you added stays on its installed version until this moves it")
397
+ .action((tool, opts, cmd) => run(async () => {
398
+ const tp = opts.account
399
+ ? await Toolpal.forAccount({ registry: globals(cmd).registry, onLog: logToStderr })
400
+ : toolpalFor(cmd);
401
+ try {
402
+ const results = opts.account
403
+ ? await tp.updateAccount(tool === undefined ? undefined : parseRegistryName(tool))
404
+ : await tp.update(tool);
405
+ if (results.length === 0)
406
+ out("everything is up to date");
407
+ for (const r of results) {
408
+ out(`${bold(r.name)} ${r.from ?? "(none)"} → ${green(r.to)}`);
409
+ if (r.addedPermissions.length > 0)
410
+ out(yellow(` new permissions: ${r.addedPermissions.join(", ")}`));
411
+ }
412
+ if (opts.account && results.length > 0)
413
+ out(dim("A `toolpal mcp` server that is already running serves them after a restart."));
414
+ }
415
+ finally {
416
+ await tp.close();
417
+ }
418
+ }));
419
+ program
420
+ .command("remove")
421
+ .description("remove a tool from toolpal.json and toolpal.lock")
422
+ .argument("<tool>", "@scope/name")
423
+ .option("--account", "remove it from your Toolpal account instead, so `toolpal mcp` stops serving it")
424
+ .action((tool, opts, cmd) => run(async () => {
425
+ const name = parseRegistryName(tool);
426
+ if (!opts.account) {
427
+ await toolpalFor(cmd).remove(name);
428
+ out(`removed ${tool}`);
429
+ return;
430
+ }
431
+ const account = await Toolpal.forAccount({
432
+ registry: globals(cmd).registry,
433
+ onLog: () => { },
434
+ });
435
+ try {
436
+ await (await signedInClient(account)).star(name, false);
437
+ const sync = await account.syncAccount();
438
+ // The tools a user published are always theirs to serve.
439
+ out(sync.tools.includes(name)
440
+ ? `${name} is one of your own tools, so \`toolpal mcp\` keeps serving it`
441
+ : `removed ${name} from your account`);
442
+ }
443
+ finally {
444
+ await account.close();
445
+ }
446
+ }));
447
+ program
448
+ .command("info")
449
+ .description("show a tool's description, permissions, analysis flags and trust signals")
450
+ .argument("<tool>", "@scope/name[@range] or a path")
451
+ .option("--json", "machine-readable output")
452
+ .action((tool, opts, cmd) => run(async () => {
453
+ const tp = toolpalFor(cmd, { lock: false, onLog: () => { } });
454
+ try {
455
+ const info = await tp.describe(tool, { fetch: true });
456
+ if (opts.json)
457
+ return out(JSON.stringify(info, null, 2));
458
+ // A build from a path has no version; one is assigned when it is published.
459
+ out(info.source === "path"
460
+ ? `${bold(info.name)} ${dim("local build, not published")}`
461
+ : `${bold(`${info.name}@${info.version}`)} ${dim(info.source)}`);
462
+ out(` ${info.description}`);
463
+ if (info.source === "registry") {
464
+ out(` ${dim("publisher")} ${info.publisher ?? "?"}${info.verified ? green(" ✓ verified") : ""} ${dim("added by")} ${info.stars ?? "?"} ${dim("downloads")} ${info.downloads ?? "?"}`);
465
+ if (info.integrity)
466
+ out(dim(` integrity ${info.integrity}`));
467
+ if (info.visibility === "private")
468
+ out(` ${yellow("private")} only you can see or install it`);
469
+ if (info.deprecated)
470
+ out(` ${yellow("deprecated")} ${info.deprecated}`);
471
+ }
472
+ out(bold("Permissions (granted as declared)"));
473
+ printPermissions(info.permissions);
474
+ if (info.hosts?.length)
475
+ out(dim(` hosts seen in code: ${info.hosts.join(", ")}`));
476
+ printFlags(info.flags);
477
+ const takes = fileFields(info.inputSchema);
478
+ const returns = fileFields(info.outputSchema);
479
+ if (takes.length + returns.length > 0) {
480
+ const named = (fields) => fields.map((f) => (f.many ? `${f.name}[]` : f.name)).join(", ");
481
+ out(bold("Files"));
482
+ if (takes.length > 0)
483
+ out(` reads a copy of the files you name in: ${named(takes)}`);
484
+ if (returns.length > 0)
485
+ out(` writes new files, returned in: ${named(returns)}`);
486
+ }
487
+ out(bold("Input schema"));
488
+ out(dim(JSON.stringify(info.inputSchema, null, 2).replace(/^/gm, " ")));
489
+ out(bold("Output schema"));
490
+ out(dim(JSON.stringify(info.outputSchema, null, 2).replace(/^/gm, " ")));
491
+ if (info.examples?.length) {
492
+ out(bold("Examples"));
493
+ for (const ex of info.examples) {
494
+ if (ex.title)
495
+ out(` ${bold(ex.title)}`);
496
+ if (ex.prompt)
497
+ out(` ${dim(ex.prompt)}`);
498
+ out(dim(` input: ${JSON.stringify(ex.input)}`));
499
+ if (ex.output !== undefined)
500
+ out(dim(` output: ${JSON.stringify(ex.output)}`));
501
+ }
502
+ }
503
+ }
504
+ finally {
505
+ await tp.close();
506
+ }
507
+ }));
508
+ program
509
+ .command("list")
510
+ .description("list tools pinned in toolpal.lock")
511
+ .action((_opts, cmd) => run(async () => {
512
+ const tools = await toolpalFor(cmd).list();
513
+ if (tools.length === 0)
514
+ out(dim("no tools pinned"));
515
+ for (const t of tools)
516
+ out(`${bold(t.name)}@${t.version} ${dim(describePermissions(t.permissions).join("; "))}`);
517
+ }));
518
+ program
519
+ .command("verify")
520
+ .description("re-hash every stored file of the pinned tools")
521
+ .action((_opts, cmd) => run(async () => {
522
+ const results = await toolpalFor(cmd).verifyStore();
523
+ for (const r of results) {
524
+ if (r.problems.length === 0)
525
+ out(`${green("✓")} ${r.name}`);
526
+ else {
527
+ out(`${red("✗")} ${r.name}`);
528
+ for (const p of r.problems)
529
+ out(red(` ${p}`));
530
+ process.exitCode = 1;
531
+ }
532
+ }
533
+ }));
534
+ program
535
+ .command("verify-build")
536
+ .description("rebuild a tool from its published sources and compare with the bundle that runs")
537
+ .argument("<tool>", "@scope/name[@version]")
538
+ .action((tool, _opts, cmd) => run(async () => {
539
+ const tp = toolpalFor(cmd, { lock: false });
540
+ try {
541
+ const r = await verifyBuild(tp, tool);
542
+ for (const n of r.notes)
543
+ out(yellow(`note: ${n}`));
544
+ out(`expected ${r.expected}`);
545
+ if (r.actual)
546
+ out(`rebuilt ${r.actual}`);
547
+ out(r.ok
548
+ ? green(`✓ ${r.tool} reproduces byte-for-byte`)
549
+ : red(`✗ ${r.tool} could not be reproduced`));
550
+ if (!r.ok)
551
+ process.exitCode = 1;
552
+ }
553
+ finally {
554
+ await tp.close();
555
+ }
556
+ }));
557
+ program
558
+ .command("search")
559
+ .description("search the registry")
560
+ .argument("<query>")
561
+ .action((query, _opts, cmd) => run(async () => {
562
+ const hits = await (await client(cmd)).search(query);
563
+ if (hits.length === 0)
564
+ out(dim("no results"));
565
+ for (const h of hits) {
566
+ const perms = describePermissions(normalizePermissions(h.permissions)).join("; ");
567
+ out(`${bold(h.name)}@${h.latest}${h.verified ? green(" ✓") : ""}${h.visibility === "private" ? yellow(" private") : ""} ${dim(`added by ${h.stars} ↓ ${h.downloads}`)}`);
568
+ out(` ${h.description}`);
569
+ out(dim(` ${perms}${h.flags.length ? ` [${h.flags.join(", ")}]` : ""}`));
570
+ }
571
+ }));
572
+ program
573
+ .command("yank")
574
+ .description("mark a published version as yanked (it stays downloadable for existing lockfiles)")
575
+ .argument("<tool@version>")
576
+ .option("--reason <text>", "why", "")
577
+ .action((spec, opts, cmd) => run(async () => {
578
+ const ref = parseToolRef(spec);
579
+ if (ref.kind !== "registry" || !ref.range)
580
+ throw new Error("usage: toolpal yank @scope/name@1.2.3");
581
+ await (await client(cmd)).yank(ref.name, ref.range, opts.reason);
582
+ out(`yanked ${spec}`);
583
+ }));
584
+ program
585
+ .command("deprecate")
586
+ .description("deprecate a tool you maintain (installs show the message)")
587
+ .argument("<tool>", "@scope/name")
588
+ .argument("[message]", 'e.g. "use @acme/new-tool instead"')
589
+ .option("--undo", "remove the deprecation")
590
+ .action((tool, message, opts, cmd) => run(async () => {
591
+ if (!opts.undo && !message)
592
+ throw new Error("give a message, or --undo");
593
+ await (await client(cmd)).deprecate(parseRegistryName(tool), opts.undo ? null : message);
594
+ out(opts.undo ? `${tool} is no longer deprecated` : `deprecated ${tool}`);
595
+ }));
596
+ program
597
+ .command("visibility")
598
+ .description("make a tool you own private (only you can see, install or run it) or public")
599
+ .argument("<tool>", "@scope/name")
600
+ .addArgument(new Argument("<visibility>", "who can see it").choices(["public", "private"]))
601
+ .action((tool, visibility, _opts, cmd) => run(async () => {
602
+ const name = parseRegistryName(tool);
603
+ await (await client(cmd)).setVisibility(name, visibility);
604
+ out(`${name} is now ${bold(visibility)}`);
605
+ if (visibility === "private") {
606
+ out(dim(" Only you can see, install or run it. Copies other people already installed keep running,\n but they cannot download it again."));
607
+ }
608
+ }));
609
+ program
610
+ .command("report")
611
+ .description("report a tool (or one version) to the registry moderators")
612
+ .argument("<tool[@version]>")
613
+ .addOption(new Option("--reason <reason>", "why")
614
+ .choices(["malware", "spam", "impersonation", "other"])
615
+ .makeOptionMandatory())
616
+ .option("--details <text>", "what you found", "")
617
+ .action((spec, opts, cmd) => run(async () => {
618
+ const ref = parseToolRef(spec);
619
+ if (ref.kind !== "registry")
620
+ throw new Error(`expected @scope/name[@version], got ${spec}`);
621
+ const r = await (await client(cmd)).report(ref.name, {
622
+ version: ref.range,
623
+ reason: opts.reason,
624
+ details: opts.details,
625
+ });
626
+ out(`report #${r.id} sent to the moderators. Thank you.`);
627
+ }));
628
+ program
629
+ .command("audit")
630
+ .description("check pinned tools for yanked, quarantined, removed or deprecated versions")
631
+ .action((_opts, cmd) => run(async () => {
632
+ const tp = toolpalFor(cmd);
633
+ try {
634
+ const advisories = await tp.audit();
635
+ let bad = 0;
636
+ for (const a of advisories) {
637
+ const id = `${a.name}@${a.version}`;
638
+ const why = a.reason ? dim(` ${a.reason}`) : "";
639
+ if (a.status === "quarantined" || a.status === "removed") {
640
+ bad++;
641
+ out(`${red(a.status.padEnd(11))} ${bold(id)}${why}`);
642
+ }
643
+ else if (a.status === "yanked") {
644
+ out(`${yellow("yanked".padEnd(11))} ${bold(id)}${why}`);
645
+ }
646
+ else if (a.status === "unknown") {
647
+ out(`${yellow("unknown".padEnd(11))} ${bold(id)}${dim(" not on this registry, or private and not yours")}`);
648
+ }
649
+ else {
650
+ out(`${green("ok".padEnd(11))} ${id}`);
651
+ }
652
+ if (a.deprecated)
653
+ out(dim(` deprecated: ${a.deprecated}`));
654
+ }
655
+ if (advisories.length === 0)
656
+ out(dim("no registry tools pinned"));
657
+ if (bad > 0) {
658
+ err(red(`${bad} pinned tool(s) were withheld by the registry; run \`toolpal update\``));
659
+ process.exitCode = 1;
660
+ }
661
+ }
662
+ finally {
663
+ await tp.close();
664
+ }
665
+ }));
666
+ program
667
+ .command("mcp")
668
+ .description("serve the tools you created or added to your account over MCP (stdio), with search, install, update and publish; or only the tools given")
669
+ .argument("[tools...]", "serve exactly these instead: registry tools, or paths to built tools")
670
+ .action((tools, _opts, cmd) => run(async () => {
671
+ // stdout carries the MCP protocol, so all logging goes to stderr.
672
+ const serving = (n, rest) => logToStderr({
673
+ source: "toolpal",
674
+ level: "info",
675
+ message: `serving ${n} tool${n === 1 ? "" : "s"} over MCP${rest}`,
676
+ });
677
+ if (tools.length > 0) {
678
+ // Named tools are for trying things out; they are never pinned where the server starts.
679
+ const served = await explicitMcpTools(toolpalFor(cmd, { lock: false }), tools);
680
+ serving(served.length, "");
681
+ serveMcpStdio(served);
682
+ return;
683
+ }
684
+ // The account's tools: neither a project nor the current directory is consulted.
685
+ const account = await Toolpal.forAccount({
686
+ registry: globals(cmd).registry,
687
+ onLog: logToStderr,
688
+ });
689
+ const { tools: served, sync } = await accountMcpTools(account);
690
+ const extras = `, plus ${SEARCH_TOOL}, ${INSTALL_TOOL}, ${UPDATE_TOOL} and ${PUBLISH_TOOL}`;
691
+ serving(served.length, sync.status === "signed-out"
692
+ ? `${extras}; run \`toolpal login\` to serve the tools you created or added and to add more`
693
+ : ` that you created or added on ${(await account.client()).baseUrl}${extras}`);
694
+ serveAccountMcp(account, served, sourceAuthoring(account));
695
+ }));
696
+ // ---------------------------------------------------------------------------
697
+ // Account & trust
698
+ // ---------------------------------------------------------------------------
699
+ program
700
+ .command("login")
701
+ .description("sign in through your browser and pin the registry's signing key")
702
+ .option("--token <token>", "store an existing Toolpal API token instead (e.g. in CI)")
703
+ .addOption(new Option("--dev <login>", "local development registries only (TOOLPAL_DEV_AUTH=1)").hideHelp())
704
+ .action((opts, cmd) => run(async () => {
705
+ const url = await registryUrl(cmd);
706
+ let token = opts.token;
707
+ let login = "";
708
+ if (opts.dev) {
709
+ const res = await fetch(`${url}/v1/auth/dev`, {
710
+ method: "POST",
711
+ headers: { "content-type": "application/json" },
712
+ body: JSON.stringify({ login: opts.dev }),
713
+ });
714
+ if (!res.ok)
715
+ throw new Error(`dev login failed (${res.status}); is the registry running with TOOLPAL_DEV_AUTH=1?`);
716
+ ({ token, login } = (await res.json()));
717
+ }
718
+ else if (!token) {
719
+ const session = await browserLogin(new RegistryClient(url), (m) => out(m));
720
+ token = session.token;
721
+ login = session.login;
722
+ }
723
+ else {
724
+ login = (await new RegistryClient(url, token).me()).login;
725
+ }
726
+ await new UserConfigStore(toolpalHome()).update((cfg) => {
727
+ cfg.registries[url] = { ...(cfg.registries[url] ?? { keys: [] }), token, login };
728
+ cfg.defaultRegistry ??= url;
729
+ });
730
+ out(`${green("logged in")} to ${url} as ${bold(login)}`);
731
+ await pinRegistryKeys(url, false);
732
+ }));
733
+ program
734
+ .command("logout")
735
+ .description("forget the stored token for the registry")
736
+ .action((_opts, cmd) => run(async () => {
737
+ const url = await registryUrl(cmd);
738
+ await new UserConfigStore(toolpalHome()).update((cfg) => {
739
+ const entry = cfg.registries[url];
740
+ if (entry)
741
+ cfg.registries[url] = { keys: entry.keys };
742
+ });
743
+ out(`logged out of ${url}`);
744
+ }));
745
+ program.command("whoami").action((_opts, cmd) => run(async () => {
746
+ const me = await (await client(cmd)).me();
747
+ out(`${me.login} ${dim(`scopes: ${me.scopes.map((s) => `@${s}`).join(", ")}`)}`);
748
+ }));
749
+ program
750
+ .command("trust")
751
+ .description("pin the registry's signing keys (trust on first use)")
752
+ .option("--replace", "replace previously pinned keys (only after an announced rotation)")
753
+ .action((opts, cmd) => run(async () => pinRegistryKeys(await registryUrl(cmd), opts.replace === true)));
754
+ const token = program.command("token").description("manage API tokens");
755
+ token
756
+ .command("create")
757
+ .requiredOption("--name <label>", "label, e.g. ci")
758
+ .action((opts, cmd) => run(async () => {
759
+ const created = await (await client(cmd)).createToken(opts.name);
760
+ out(created.token);
761
+ err(dim(`token ${created.id} created; it is shown only once. Use it as TOOLPAL_TOKEN.`));
762
+ }));
763
+ token.command("list").action((_opts, cmd) => run(async () => {
764
+ for (const t of await (await client(cmd)).listTokens()) {
765
+ out(`${t.id} ${t.name} ${dim(t.createdAt)}`);
766
+ }
767
+ }));
768
+ token
769
+ .command("revoke")
770
+ .argument("<id>")
771
+ .action((id, _opts, cmd) => run(async () => {
772
+ await (await client(cmd)).revokeToken(id);
773
+ out(`revoked ${id}`);
774
+ }));
775
+ program
776
+ .command("doctor")
777
+ .description("check Node, sandbox isolation, the store and the registry")
778
+ .addOption(new Option("--node <path>", "check a specific node binary"))
779
+ .action((opts, cmd) => run(async () => {
780
+ const runtime = await resolveNodeRuntime(opts.node);
781
+ out(`${bold("node")} ${runtime.version} (${runtime.path})`);
782
+ out(`${bold("network")} tools without "net" are blocked ${runtime.netMode === "native" ? green("natively (--permission)") : yellow("by a best-effort JS guard (Node < 25)")}`);
783
+ const warnings = nodeAdvisoriesFor(runtime.version);
784
+ if (warnings.length === 0)
785
+ out(`${bold("advisories")} ${green(`none of the ${NODE_ADVISORIES.length} known permission-model CVEs apply`)}`);
786
+ for (const w of warnings)
787
+ out(`${bold("advisory")} ${yellow(w)}`);
788
+ const supervisor = new Supervisor({ nodePath: opts.node });
789
+ try {
790
+ await supervisor.runtime();
791
+ out(`${bold("sandbox")} ${green("ok")}`);
792
+ }
793
+ finally {
794
+ await supervisor.close();
795
+ }
796
+ out(`${bold("home")} ${toolpalHome()}`);
797
+ const url = await registryUrl(cmd);
798
+ try {
799
+ const keys = await new RegistryClient(url).keys();
800
+ const pinned = (await new UserConfigStore(toolpalHome()).read()).registries[url]?.keys ?? [];
801
+ const trusted = keys.every((k) => pinned.some((p) => p.keyId === k.keyId));
802
+ out(`${bold("registry")} ${url} ${green("reachable")}; signing key ${trusted ? green("pinned") : yellow("not pinned (run `toolpal trust`)")}`);
803
+ }
804
+ catch (e) {
805
+ out(`${bold("registry")} ${url} ${yellow(`unreachable: ${e.message}`)}`);
806
+ }
807
+ const problems = (await toolpalFor(cmd).verifyStore()).filter((r) => r.problems.length > 0);
808
+ out(`${bold("store")} ${problems.length === 0 ? green("pinned tools verify") : red(`${problems.length} tool(s) modified on disk; run \`toolpal verify\``)}`);
809
+ }));
810
+ function parseRegistryName(ref) {
811
+ const parsed = parseToolRef(ref);
812
+ if (parsed.kind !== "registry")
813
+ throw new Error(`expected @scope/name, got ${ref}`);
814
+ return parsed.name;
815
+ }
816
+ await program.parseAsync(process.argv);
817
+ //# sourceMappingURL=cli.js.map