@zaisma/cli 0.44.0 → 0.46.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/zaisma.mjs CHANGED
@@ -5,9 +5,10 @@
5
5
  import { createHash } from "node:crypto";
6
6
  import { createReadStream, createWriteStream, readFileSync } from "node:fs";
7
7
  import { mkdir, mkdtemp, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
8
- import { tmpdir } from "node:os";
8
+ import { homedir, tmpdir } from "node:os";
9
9
  import { dirname, extname, join, posix, relative, resolve, sep } from "node:path";
10
10
  import { pipeline } from "node:stream/promises";
11
+ import { fileURLToPath } from "node:url";
11
12
  import { createBrotliDecompress, createGunzip } from "node:zlib";
12
13
  import { CHECKED_TEXT_EXTENSIONS, GAME_FILE_EXTENSIONS, PRECOMPRESSED_EXTENSIONS, checkGameFiles, extensionOf, findOutsideReferences } from "./check.mjs";
13
14
  import { assetHeadSizes } from "./performance.mjs";
@@ -109,6 +110,8 @@ const COMMAND_ERROR_CODES = {
109
110
  game_server_not_run: "play-locally: npx couldn't run @zaisma/game-server, which runs the game on this computer.",
110
111
  server_unreachable: "Zaisma couldn't be reached: no connection, or a wrong ZAISMA_API.",
111
112
  unexpected_answer: "Zaisma answered without JSON, like a page from a network in between.",
113
+ skill_not_ours: "skill: a zaisma skill this command didn't install is already in that folder, so nothing was written; field names the folder.",
114
+ install_not_confirmed: "skill: nothing was installed, since nobody answered the question: give --yes to install without it.",
112
115
  };
113
116
 
114
117
  const BY_ME = { hasValue: false, about: "Mark it as written by you; otherwise it says your AI wrote it" };
@@ -320,6 +323,15 @@ const COMMANDS = {
320
323
  arguments: [{ name: "slug" }],
321
324
  flags: { folder: { hasValue: true, placeholder: "<folder>", about: "Where to save it: a new or empty folder; ./<slug>-export if left out" } },
322
325
  },
326
+ skill: {
327
+ about: "Install the Zaisma skill into the AI tools on this computer, or update the copies it installed. Copies it installed update themselves whenever any command runs",
328
+ arguments: [],
329
+ flags: {
330
+ folder: { hasValue: true, placeholder: "<folder>", about: "Install into this skills folder only, as <folder>/zaisma" },
331
+ project: { hasValue: false, about: "Install into this project's folders (.claude/skills and the rest, here) instead of your home folder's" },
332
+ yes: { hasValue: false, about: "Install without asking first" },
333
+ },
334
+ },
323
335
  help: { about: "This help; with --json, every command, flag, exit code and error code", arguments: [], flags: {} },
324
336
  };
325
337
  /** Commands with a second word, like zaisma forum post. */
@@ -352,7 +364,9 @@ function refuse(code, { message, field = null, fix, retryAfterSec = null }, exit
352
364
  let isJson = false;
353
365
  /** A line for people. With --json, stdout holds only the JSON, so progress goes to stderr. */
354
366
  const say = (line) => (isJson ? console.error(line) : console.log(line));
355
- const printJson = (answer) => console.log(JSON.stringify(answer));
367
+ /** The installed skill copies this run updated (skill_updates), added to a --json answer that's an object. */
368
+ let skillUpdates = [];
369
+ const printJson = (answer) => console.log(JSON.stringify(skillUpdates.length && answer && typeof answer === "object" && !Array.isArray(answer) ? { ...answer, skill_updates: skillUpdates } : answer));
356
370
  /** --json: the API's answer as-is, compact (docs/NAMING.md, Outputs). */
357
371
  const printAnswer = (answer) => {
358
372
  printJson(answer);
@@ -2171,6 +2185,8 @@ async function run({ command, values, flags, globalFlags, rest }) {
2171
2185
  else console.log(about ? `${usage(about)}\n${COMMANDS[about].about}.\n\n${helpText()}` : helpText());
2172
2186
  return EXIT_CODES.done;
2173
2187
  }
2188
+ if (command === "skill") return installSkill(flags);
2189
+ await updateSkillCopies();
2174
2190
  if (command === "games") {
2175
2191
  const answer = await api("GET", "/games");
2176
2192
  if (isJson) return printAnswer(answer);
@@ -2254,6 +2270,103 @@ async function run({ command, values, flags, globalFlags, rest }) {
2254
2270
  return EXIT_CODES.done;
2255
2271
  }
2256
2272
 
2273
+ /**
2274
+ * The Zaisma skill (docs/DEVELOPER-API.md, "Teaching your AI"): the files in ./skill, which scripts/build-skill.mjs copies
2275
+ * from skills/zaisma, installed into the skills folder of every AI tool found. A copy this command writes says so in its
2276
+ * SKILL.md (metadata.installed_by) with the command's version, so later runs update it and never touch one it didn't write.
2277
+ */
2278
+ const SKILL_TOOLS = [
2279
+ { tool: "claude_code", toolName: "Claude Code", toolFolder: ".claude" },
2280
+ { tool: "codex", toolName: "Codex", toolFolder: ".codex" },
2281
+ { tool: "cursor", toolName: "Cursor", toolFolder: ".cursor" },
2282
+ { tool: "gemini_cli", toolName: "Gemini CLI", toolFolder: ".gemini" },
2283
+ // The shared folder several tools read: always written.
2284
+ { tool: "agents", toolName: "the shared .agents folder", toolFolder: ".agents", isAlwaysWritten: true },
2285
+ ];
2286
+ const SKILL_MARKER = "@zaisma/cli";
2287
+
2288
+ /** A skills folder's zaisma copy as it stands: missing, someone else's, or ours at a version. */
2289
+ async function skillCopyAt(folder) {
2290
+ let text;
2291
+ try {
2292
+ text = await readFile(join(folder, "SKILL.md"), "utf8");
2293
+ } catch {
2294
+ return { isThere: false, isOurs: false, version: null };
2295
+ }
2296
+ const frontmatter = text.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? "";
2297
+ return { isThere: true, isOurs: frontmatter.includes(`installed_by: "${SKILL_MARKER}"`), version: frontmatter.match(/^\s+version: "([0-9.]+)"$/m)?.[1] ?? null };
2298
+ }
2299
+
2300
+ /** True when installedVersion is older than newerVersion, both x.y.z. */
2301
+ const isOlderVersion = (installedVersion, newerVersion) => {
2302
+ const [first, second] = [installedVersion, newerVersion].map((version) => version.split(".").map(Number));
2303
+ for (let index = 0; index < 3; index++) if ((first[index] ?? 0) !== (second[index] ?? 0)) return (first[index] ?? 0) < (second[index] ?? 0);
2304
+ return false;
2305
+ };
2306
+
2307
+ /** Writes the skill into folder whole, replacing what's there, with this command's marker and version in SKILL.md. */
2308
+ async function writeSkillCopy(folder) {
2309
+ const source = fileURLToPath(new URL("./skill/", import.meta.url));
2310
+ await rm(folder, { recursive: true, force: true });
2311
+ for (const file of (await walk(source)).files) {
2312
+ const relativePath = relative(source, file);
2313
+ let text = await readFile(file, "utf8");
2314
+ if (relativePath === "SKILL.md") text = text.replace(/^---\n([\s\S]*?)\n---/, (whole, fields) => `---\n${fields}\nmetadata:\n version: "${CLI_VERSION}"\n installed_by: "${SKILL_MARKER}"\n---`);
2315
+ await mkdir(dirname(join(folder, relativePath)), { recursive: true });
2316
+ await writeFile(join(folder, relativePath), text);
2317
+ }
2318
+ }
2319
+
2320
+ /** Every place a copy could be: each tool's skills folder in the home folder and in this one. */
2321
+ const skillCopyPlaces = (base) => SKILL_TOOLS.map((each) => ({ ...each, folder: join(base, each.toolFolder, "skills", "zaisma") }));
2322
+
2323
+ /** Before any other command: copies this command installed at an older version are rewritten, quietly if anything fails. */
2324
+ async function updateSkillCopies() {
2325
+ const places = [...skillCopyPlaces(homedir()), ...(resolve(process.cwd()) === resolve(homedir()) ? [] : skillCopyPlaces(process.cwd()))];
2326
+ for (const place of places) {
2327
+ try {
2328
+ const copy = await skillCopyAt(place.folder);
2329
+ if (!copy.isOurs || !copy.version || !isOlderVersion(copy.version, CLI_VERSION)) continue;
2330
+ await writeSkillCopy(place.folder);
2331
+ skillUpdates.push({ tool: place.tool, folder: place.folder, from_version: copy.version, to_version: CLI_VERSION });
2332
+ } catch {
2333
+ // An update that can't be written never stops the command; the next run tries again.
2334
+ }
2335
+ }
2336
+ if (skillUpdates.length && !isJson) console.error(`Updated the Zaisma skill in ${skillUpdates.length} ${skillUpdates.length === 1 ? "AI tool" : "AI tools"} to ${CLI_VERSION}.`);
2337
+ }
2338
+
2339
+ /** zaisma skill: install the skill into each AI tool found, after one question (or --yes). */
2340
+ async function installSkill(flags) {
2341
+ if (flags.folder !== undefined && flags.project) refuse("conflicting_flags", { message: "--folder and --project don't go together.", field: "project", fix: "Give --folder to install into one skills folder, or --project to install into this project's tool folders." });
2342
+ const base = flags.project ? process.cwd() : homedir();
2343
+ const places = flags.folder !== undefined ? [{ tool: "folder", toolName: "the folder you gave", folder: join(resolve(flags.folder), "zaisma"), isFound: true }] : await Promise.all(skillCopyPlaces(base).map(async (place) => ({ ...place, isFound: place.isAlwaysWritten || (await stat(join(base, place.toolFolder)).then((found) => found.isDirectory(), () => false)) })));
2344
+ const chosen = places.filter((place) => place.isFound);
2345
+ for (const place of chosen) {
2346
+ const copy = await skillCopyAt(place.folder);
2347
+ if (copy.isThere && !copy.isOurs) refuse("skill_not_ours", { message: `${place.folder} already holds a zaisma skill this command didn't install, so nothing was written.`, field: place.folder, fix: "Move or remove that folder if it's an old copy of the Zaisma skill, or install elsewhere with --folder." }, EXIT_CODES.failed);
2348
+ }
2349
+ if (!flags.yes) {
2350
+ if (isJson || !process.stdin.isTTY) refuse("install_not_confirmed", { message: "Nothing was installed: there's nobody to answer the question here.", fix: "Run zaisma skill --yes to install without the question." });
2351
+ console.log("The Zaisma skill goes into:");
2352
+ for (const place of chosen) console.log(` ${place.toolName.padEnd(26)} ${place.folder}`);
2353
+ const { createInterface } = await import("node:readline/promises");
2354
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
2355
+ const answer = await reader.question("Install it? [y/N] ");
2356
+ reader.close();
2357
+ if (!/^y(es)?$/i.test(answer.trim())) {
2358
+ console.log("Nothing installed.");
2359
+ return EXIT_CODES.done;
2360
+ }
2361
+ }
2362
+ for (const place of chosen) await writeSkillCopy(place.folder);
2363
+ const skippedTools = places.filter((place) => !place.isFound).map((place) => place.tool);
2364
+ if (isJson) return printAnswer({ installed_copies: chosen.map((place) => ({ tool: place.tool, folder: place.folder })), skipped_tools: skippedTools });
2365
+ for (const place of chosen) console.log(`Installed the Zaisma skill for ${place.toolName}: ${place.folder}`);
2366
+ console.log("It updates itself whenever a zaisma command runs. In Claude Code you can also add the plugin: /plugin marketplace add zaisma/zaisma, then /plugin install zaisma@zaisma.");
2367
+ return EXIT_CODES.done;
2368
+ }
2369
+
2257
2370
  /**
2258
2371
  * play-locally: the game server package's command, run through npx so this command stays free of dependencies
2259
2372
  * (ZAISMA_GAME_SERVER_BIN, a path to its bin/node.js, is for tests and the repository). Its output and exit code