@hypersocial/decks-cli 0.9.15 → 0.9.16

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/README.md CHANGED
@@ -32,6 +32,31 @@ decks login
32
32
  decks activity
33
33
  ```
34
34
 
35
+ ## Updating
36
+
37
+ ```bash
38
+ npm i -g hyperdecks@latest # or run every command as: npx hyperdecks@latest <command>
39
+ hyperdecks whoami # cli: <yours> (latest X, minimum Y)
40
+ ```
41
+
42
+ - **Daily notice.** Once a day the CLI asks the server which version is current
43
+ (`/api/cli/version`, cached in `~/.hyperdecks/update-check.json`). When a newer
44
+ one is out it prints one line on stderr with the upgrade command. Offline or
45
+ slow, it says nothing and never holds a command up.
46
+ `HYPERDECKS_NO_UPDATE_CHECK=1`, or `CI=true`, turns the line off.
47
+ - **Minimum.** Below the server's minimum version, `narrate`, `check`,
48
+ `release`, `deck new`, `preview create` and `init` refuse with the upgrade
49
+ command and exit 1, because an old CLI ships retired templates or since-fixed
50
+ bugs. Everything else (`whoami`, `deck list`, share links, stats) still runs.
51
+ `HYPERDECKS_ALLOW_OLD=1` runs them anyway in an emergency, with a warning.
52
+ - **Skill copies.** After an update, the next command refreshes the hyperdecks
53
+ skill copies `skills install` / `init` put in your agents' folders (Claude
54
+ Code, Codex, Cursor, ...) from the copy bundled with the CLI, and says so in
55
+ one line. A copy you edited by hand is left alone with a warning
56
+ (`hyperdecks skills install` replaces it). A copy installed before 0.9.16 is
57
+ saved to `~/.hyperdecks/skill-backups/` before it is refreshed.
58
+ - The CLI never installs itself: it only prints the command.
59
+
35
60
  ## Auth
36
61
 
37
62
  `decks login` opens the production broker at `https://hyperdecks.ai` and
package/bin/decks.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { runCli } from "../src/commands.mjs";
2
+ import { main } from "../src/commands.mjs";
3
3
 
4
- process.exitCode = await runCli(process.argv.slice(2));
4
+ process.exitCode = await main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hypersocial/decks-cli",
3
- "version": "0.9.15",
3
+ "version": "0.9.16",
4
4
  "description": "Command-line client for Hypersocial Decks live analytics and share management.",
5
5
  "type": "module",
6
6
  "main": "./src/commands.mjs",
@@ -1,10 +1,14 @@
1
1
  ---
2
2
  name: hyperdecks
3
3
  description: Use when asked to make, narrate, check or ship a deck ("make me a narrated deck", "turn this into a deck and send it"), or when working with Hypersocial Decks, Hyperdecks CLI, production deck analytics, recipient share links, deck activity, MCP deck tools, or real-world/customer-facing deck checks. Prefer production for real activity and analytics; use development only for local implementation/testing when explicitly requested.
4
+ metadata:
5
+ version: "0.9.16"
4
6
  ---
5
7
 
6
8
  # Hyperdecks
7
9
 
10
+ Run `hyperdecks --version`; if it's behind `npx hyperdecks@latest --version`, update before making a deck (`npm i -g hyperdecks@latest`, or run every command as `npx hyperdecks@latest`).
11
+
8
12
  ## Overview
9
13
 
10
14
  Hyperdecks is the CLI and MCP surface for Hypersocial Decks live analytics,
package/src/commands.mjs CHANGED
@@ -1,16 +1,21 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { basename, join, resolve } from "node:path";
3
3
  import {
4
+ agentTable,
4
5
  backupLinkUrl,
6
+ CLIENT_HEADERS,
5
7
  installHyperdecksSkill,
6
8
  login,
7
9
  logout,
8
10
  openBrowser,
9
11
  linkBase,
10
12
  parse,
13
+ PACKAGED_SKILLS_DIR,
11
14
  target,
12
15
  VERSION,
13
16
  } from "./runtime.mjs";
17
+ import { fetchVersionInfo, updatePreflight } from "./update.mjs";
18
+ import { refreshSkillCopies } from "./skillFreshness.mjs";
14
19
  import * as ops from "./ops.mjs";
15
20
  import { exportVideo } from "./export-video.mjs";
16
21
  import { presenterLine } from "./presenter.mjs";
@@ -21,21 +26,40 @@ export const playbackLabel = (p) => p.narrationFinished ? "narration finished"
21
26
 
22
27
  const fmtMs = (ms) => (ms >= 60000 ? `${(ms / 60000).toFixed(1)}m` : `${Math.round(ms / 1000)}s`);
23
28
 
29
+ // This CLI's version against the server's latest and minimum (null: unreachable).
30
+ async function cliVersions(opts) {
31
+ const info = await fetchVersionInfo(target(opts).brokerBase, { timeoutMs: 5000, headers: CLIENT_HEADERS });
32
+ return { version: VERSION, latest: info?.latest ?? null, minimum: info?.minimum ?? null };
33
+ }
34
+
24
35
  async function whoamiCmd(opts) {
25
36
  const t = target(opts);
26
- const who = await ops.whoami(opts);
37
+ // Signed out, it still prints the versions (agents run whoami first), then
38
+ // fails as before: exit 1 with the login hint.
39
+ let signedOut = null;
40
+ const signedIn = ops.whoami(opts).catch((e) => {
41
+ if (!/^not authenticated/.test(String(e?.message))) throw e;
42
+ signedOut = e;
43
+ return null;
44
+ });
45
+ const [who, cli] = await Promise.all([signedIn, cliVersions(opts)]);
27
46
  if (opts.json) {
28
- console.log(JSON.stringify({ ...(who || {}), deployment: t.name, convexUrl: t.convexUrl }, null, 2));
47
+ console.log(JSON.stringify({ ...(who || {}), deployment: t.name, convexUrl: t.convexUrl, cli }, null, 2));
48
+ if (signedOut) throw signedOut;
29
49
  return;
30
50
  }
51
+ const cliLine = `cli: ${cli.version}${cli.latest ? ` (latest ${cli.latest}, minimum ${cli.minimum})` : " (could not reach the server for the latest)"}`;
31
52
  if (!who) {
32
53
  console.log(`not authenticated (${t.name})`);
54
+ console.log(cliLine);
55
+ if (signedOut) throw signedOut;
33
56
  return;
34
57
  }
35
58
  console.log(`email: ${who.email}`);
36
59
  console.log(`subject: ${who.subject}`);
37
60
  console.log(`isAdmin: ${who.isAdmin}`);
38
61
  console.log(`deployment: ${t.name} (${t.convexUrl})`);
62
+ console.log(cliLine);
39
63
  }
40
64
 
41
65
  async function deckList(opts) {
@@ -1254,3 +1278,46 @@ export async function runCli(argv = process.argv.slice(2)) {
1254
1278
  return 1;
1255
1279
  }
1256
1280
  }
1281
+
1282
+ // The installed CLI's entry point (bin/): runCli plus the version checks. Kept
1283
+ // out of runCli so tests and the repo's own cli/decks.mjs dispatch without
1284
+ // touching the network or ~/.hyperdecks.
1285
+ // 1. refresh this machine's stale hyperdecks skill copies (local, no network);
1286
+ // 2. below the server's minimum, refuse the commands that make or ship a deck;
1287
+ // 3. after the command, print the once-a-day "newer version is out" line.
1288
+ // Only an installed copy (global or an npx cache, both under node_modules) does
1289
+ // this: run from a source checkout it would push a work-in-progress skill into
1290
+ // the developer's agents, and the repo's tests spawn the bin.
1291
+ export const isInstalledCopy = (dir = PACKAGED_SKILLS_DIR) => /[\\/]node_modules[\\/]/.test(dir);
1292
+
1293
+ export async function main(argv = process.argv.slice(2), { env = process.env, home, fetchImpl = fetch, stateFile, now, log, installed = isInstalledCopy() } = {}) {
1294
+ if (!installed) return runCli(argv);
1295
+ let parsed;
1296
+ try {
1297
+ parsed = parse(argv);
1298
+ } catch {
1299
+ return runCli(argv);
1300
+ }
1301
+ const { pos, opts } = parsed;
1302
+ if (opts.version || opts.help || pos.length === 0) return runCli(argv);
1303
+
1304
+ try {
1305
+ refreshSkillCopies({ version: VERSION, bundledDir: join(PACKAGED_SKILLS_DIR, "hyperdecks"), skillsDirs: agentTable({ home, env }).map((a) => a.skills), ...(home ? { home } : {}), ...(now ? { now } : {}), ...(log ? { log } : {}) });
1306
+ } catch (e) {
1307
+ // Never let housekeeping stop a command, but say what went wrong.
1308
+ (log ?? ((line) => console.error(line)))(`⚠ hyperdecks skill freshness check failed: ${e?.message ?? e}`);
1309
+ }
1310
+
1311
+ let base = null;
1312
+ try {
1313
+ const t = target(opts);
1314
+ if (t.name === "prod") base = t.brokerBase;
1315
+ } catch {
1316
+ // A bad --dev setup is reported by the command itself.
1317
+ }
1318
+ const pre = await updatePreflight(pos, { version: VERSION, base, env, fetchImpl, headers: CLIENT_HEADERS, ...(stateFile ? { stateFile } : {}), ...(now ? { now } : {}), ...(log ? { warn: log } : {}) });
1319
+ if (pre.refuse) return 1;
1320
+ const code = await runCli(argv);
1321
+ await pre.after();
1322
+ return code;
1323
+ }
package/src/init.mjs CHANGED
@@ -9,15 +9,16 @@
9
9
  // In chat (no folder, no git) the hosted MCP's get_started tool walks the same
10
10
  // steps on a hosted draft (lib/getStarted.ts); the deck fill is shared (firstDeck.mjs).
11
11
  import { execFileSync } from "node:child_process";
12
- import { createHash, randomBytes } from "node:crypto";
13
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
12
+ import { randomBytes } from "node:crypto";
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
14
14
  import { homedir } from "node:os";
15
- import { dirname, join, relative, resolve } from "node:path";
15
+ import { dirname, join, resolve } from "node:path";
16
16
  import { createInterface } from "node:readline/promises";
17
17
  import { fileURLToPath } from "node:url";
18
18
  import * as ops from "./ops.mjs";
19
19
  import { ANSWER_MAX, DASH_AVATAR, FIRST_DECK_LAYOUTS, cleanAnswer, fillFirstDeck, firstDeckCopy, firstDeckSlug } from "./firstDeck.mjs";
20
20
  import { agentTable, api, chooseAgents, client, CRED_DIR, installHyperdecksSkill, linkBase, login as runLogin, openBrowser, target } from "./runtime.mjs";
21
+ import { skillHash } from "./skillFreshness.mjs";
21
22
  import { READING_PASSAGE, voiceClone as runVoiceClone } from "./voice.mjs";
22
23
  import { assembleLayoutDeck, deckNew as runDeckNew } from "./scaffold.mjs";
23
24
  import { narrate as runNarrate } from "./narrate.mjs";
@@ -100,20 +101,8 @@ function gitConfig(dir, key) {
100
101
 
101
102
  // ---- skill ----------------------------------------------------------------
102
103
 
103
- function filesUnder(dir, base = dir) {
104
- return readdirSync(dir).flatMap((name) => {
105
- const p = join(dir, name);
106
- return statSync(p).isDirectory() ? filesUnder(p, base) : [relative(base, p)];
107
- }).sort();
108
- }
109
-
110
- // A hash of every file in a skill folder; null when it is not there.
111
- export function skillHash(dir) {
112
- if (!existsSync(join(dir, "SKILL.md"))) return null;
113
- const h = createHash("sha256");
114
- for (const f of filesUnder(dir)) h.update(f).update("\0").update(readFileSync(join(dir, f))).update("\0");
115
- return h.digest("hex");
116
- }
104
+ // skillHash: a hash of every file in a skill folder (skillFreshness.mjs).
105
+ export { skillHash };
117
106
 
118
107
  // ---- prompts --------------------------------------------------------------
119
108
 
package/src/runtime.mjs CHANGED
@@ -7,8 +7,13 @@ import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { ConvexHttpClient } from "convex/browser";
9
9
  import { makeFunctionReference } from "convex/server";
10
+ import { recordSkillInstall } from "./skillFreshness.mjs";
10
11
 
11
- export const VERSION = "0.9.15";
12
+ export const VERSION = "0.9.16";
13
+
14
+ // Sent on the CLI's calls to our routes and to Convex, so the server can see
15
+ // which CLI versions are still out there (not used to refuse anything).
16
+ export const CLIENT_HEADERS = { "x-hyperdecks-client": `cli/${VERSION}` };
12
17
  const UPLOAD_TIMEOUT_MS = 125_000;
13
18
 
14
19
  // The app's home. HYPERDECKS_HOST points the prod target's broker and share
@@ -220,7 +225,7 @@ function addRecipient(opts, k, v) {
220
225
  export const CRED_DIR = join(homedir(), ".config", "hypersocial-decks");
221
226
  export const CRED_FILE = join(CRED_DIR, "credentials.json");
222
227
  const SRC_DIR = dirname(fileURLToPath(import.meta.url));
223
- const PACKAGED_SKILLS_DIR = join(SRC_DIR, "..", "skills");
228
+ export const PACKAGED_SKILLS_DIR = join(SRC_DIR, "..", "skills");
224
229
 
225
230
  export function parse(args) {
226
231
  const opts = {};
@@ -367,7 +372,7 @@ async function mintJwt(brokerBase, refreshToken) {
367
372
  try {
368
373
  res = await fetch(`${brokerBase}/api/cli/token`, {
369
374
  method: "POST",
370
- headers: { authorization: `Bearer ${refreshToken}` },
375
+ headers: { ...CLIENT_HEADERS, authorization: `Bearer ${refreshToken}` },
371
376
  signal: AbortSignal.timeout(15000),
372
377
  });
373
378
  } catch (e) {
@@ -395,12 +400,18 @@ async function jwtFor(brokerBase, refreshToken) {
395
400
  return token;
396
401
  }
397
402
 
403
+ function withClientHeaders(input, init = {}) {
404
+ const headers = new Headers(init.headers);
405
+ for (const [k, v] of Object.entries(CLIENT_HEADERS)) headers.set(k, v);
406
+ return fetch(input, { ...init, headers });
407
+ }
408
+
398
409
  export async function client(opts = {}) {
399
410
  // Allow a pre-authenticated client to be injected (e.g. the remote MCP OAuth
400
411
  // route, which already holds a Convex client authed as the requesting user).
401
412
  if (opts.client) return opts.client;
402
413
  const t = target(opts);
403
- const c = new ConvexHttpClient(t.convexUrl);
414
+ const c = new ConvexHttpClient(t.convexUrl, { fetch: withClientHeaders });
404
415
  const admin = opts.admin || process.env.HSDECKS_ADMIN === "1";
405
416
  if (admin) {
406
417
  if (t.name === "prod") throw new Error("legacy --admin is dev-only; run `decks login` for prod");
@@ -513,6 +524,16 @@ export function installHyperdecksSkill(opts = {}, extraArgs = [], { spawn = spaw
513
524
  const tail = quiet ? `${result.stdout || ""}\n${result.stderr || ""}`.trim().split("\n").filter((l) => l.trim() && !/^npm warn/i.test(l)).slice(-3).join(" ") : "";
514
525
  throw new Error(`skills add failed with exit code ${result.status}${tail ? `: ${tail}` : ""}`);
515
526
  }
527
+ // Remember what was written (and its hash) so later runs can refresh these
528
+ // copies when the CLI updates, and leave hand-edited ones alone.
529
+ const table = agentTable({ home, env });
530
+ const written = agents[0] === "*" ? table : table.filter((a) => agents.includes(a.id));
531
+ try {
532
+ recordSkillInstall(written.map((a) => a.skills), home ? { home } : {});
533
+ } catch (e) {
534
+ // The install worked; only automatic refreshes of it are lost.
535
+ if (!quiet) log(`⚠ installed, but could not record it for automatic updates (${e.message})`);
536
+ }
516
537
  return { installed: true, agents, source };
517
538
  }
518
539
 
@@ -0,0 +1,265 @@
1
+ // Keeps the hyperdecks skill copies an agent reads in step with this CLI.
2
+ //
3
+ // `skills install` / `init` copy the packaged skill into each agent's folder
4
+ // (agentTable). An agent then reads that copy for good, even after the CLI is
5
+ // updated, and an old copy steers it to retired layouts. So on every run (local
6
+ // only, no network) the CLI looks at those copies and refreshes any whose
7
+ // stamped version (SKILL.md frontmatter `metadata.version`) is older than its
8
+ // own, from the copy bundled in this package.
9
+ //
10
+ // It never overwrites a hand-edited copy: ~/.hyperdecks/skills.json records the
11
+ // hash of each copy the CLI wrote. A copy that no longer matches its hash gets a
12
+ // warning (once a day) instead. A copy from before this record existed (no
13
+ // entry) is replaced too, after saving it to ~/.hyperdecks/skill-backups/, and
14
+ // the line says so. A copy that is a symlink (often into a repo checkout) is
15
+ // never touched: a one-line notice, once a day.
16
+ import { createHash } from "node:crypto";
17
+ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { basename, dirname, join, relative } from "node:path";
20
+ import { compareVersions, DAY_MS } from "./update.mjs";
21
+
22
+ export const SKILL_NAME = "hyperdecks";
23
+
24
+ const recordFile = (home) => join(home, ".hyperdecks", "skills.json");
25
+ const backupRoot = (home) => join(home, ".hyperdecks", "skill-backups");
26
+
27
+ function filesUnder(dir, base = dir) {
28
+ return readdirSync(dir).flatMap((name) => {
29
+ const p = join(dir, name);
30
+ return statSync(p).isDirectory() ? filesUnder(p, base) : [relative(base, p)];
31
+ }).sort();
32
+ }
33
+
34
+ // A hash of every file in a skill folder; null when it is not there.
35
+ export function skillHash(dir) {
36
+ if (!existsSync(join(dir, "SKILL.md"))) return null;
37
+ const h = createHash("sha256");
38
+ for (const f of filesUnder(dir)) h.update(f).update("\0").update(readFileSync(join(dir, f))).update("\0");
39
+ return h.digest("hex");
40
+ }
41
+
42
+ // The frontmatter of a SKILL.md: `name`, and `version` from `metadata.version`
43
+ // (or a top-level `version`). Missing fields are null.
44
+ export function skillStamp(dir) {
45
+ let text;
46
+ try {
47
+ text = readFileSync(join(dir, "SKILL.md"), "utf8");
48
+ } catch {
49
+ return null;
50
+ }
51
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? "";
52
+ const field = (re) => re.exec(fm)?.[1]?.trim().replace(/^["']|["']$/g, "") ?? null;
53
+ return {
54
+ name: field(/^name:\s*(.+)$/m),
55
+ version: field(/^metadata:\s*\n(?:[ \t]+.*\n)*?[ \t]+version:\s*(.+)$/m) ?? field(/^version:\s*(.+)$/m),
56
+ };
57
+ }
58
+
59
+ function readRecord(home) {
60
+ try {
61
+ const r = JSON.parse(readFileSync(recordFile(home), "utf8"));
62
+ return r && typeof r.copies === "object" && r.copies ? r : { copies: {} };
63
+ } catch {
64
+ return { copies: {} };
65
+ }
66
+ }
67
+
68
+ function writeRecord(home, record) {
69
+ try {
70
+ mkdirSync(dirname(recordFile(home)), { recursive: true });
71
+ writeFileSync(recordFile(home), JSON.stringify(record, null, 2));
72
+ } catch {
73
+ // Without a record the next run treats the copy as unrecorded; harmless.
74
+ }
75
+ }
76
+
77
+ const real = (p) => {
78
+ try {
79
+ return realpathSync(p);
80
+ } catch {
81
+ return p;
82
+ }
83
+ };
84
+
85
+ // Record the copies an install just wrote (dirs: the agents' skill folders,
86
+ // each holding hyperdecks/). Called by installHyperdecksSkill.
87
+ export function recordSkillInstall(skillsDirs, { home = homedir(), now = Date.now() } = {}) {
88
+ const record = readRecord(home);
89
+ for (const skillsDir of skillsDirs) {
90
+ if (isLinked(join(skillsDir, SKILL_NAME))) continue; // never refreshed, so not recorded
91
+ const dir = real(join(skillsDir, SKILL_NAME));
92
+ const hash = skillHash(dir);
93
+ if (!hash) continue;
94
+ record.copies[dir] = { version: skillStamp(dir)?.version ?? null, hash, at: now };
95
+ }
96
+ writeRecord(home, record);
97
+ }
98
+
99
+ // Leftovers of a swap that died midway (a killed process): `.hyperdecks.new-*` /
100
+ // `.hyperdecks.old-*` beside the copy. They are dot-named so agents should skip
101
+ // them, but one that didn't would load a second hyperdecks skill. Only ones
102
+ // older than a few minutes go, so another process's swap in flight is left be.
103
+ const STRAY = new RegExp(`^\\.${SKILL_NAME}\\.(new|old)-[\\w-]+$`);
104
+ const STRAY_AGE_MS = 10 * 60 * 1000;
105
+ function sweepStrays(parent, now) {
106
+ let names;
107
+ try {
108
+ names = readdirSync(parent);
109
+ } catch {
110
+ return;
111
+ }
112
+ for (const name of names) {
113
+ if (!STRAY.test(name)) continue;
114
+ const p = join(parent, name);
115
+ try {
116
+ if (now - statSync(p).mtimeMs > STRAY_AGE_MS) rmSync(p, { recursive: true, force: true });
117
+ } catch {
118
+ // Gone already, or not ours to remove.
119
+ }
120
+ }
121
+ }
122
+
123
+ // Swap `dir` for a copy of `bundledDir`: copy beside it, then two renames, so
124
+ // a failure never leaves the agent with no skill and never leaves a second one.
125
+ // Several commands may race here right after an update (an agent runs them in
126
+ // parallel): suffixes are unique per process, and a loser cleans up after itself.
127
+ function swapIn(dir, bundledDir, now) {
128
+ const tag = `${now}-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
129
+ const stage = (kind) => join(dirname(dir), `.${basename(dir)}.${kind}-${tag}`);
130
+ const fresh = stage("new");
131
+ const old = stage("old");
132
+ let moved = false;
133
+ try {
134
+ cpSync(bundledDir, fresh, { recursive: true });
135
+ renameSync(dir, old);
136
+ moved = true;
137
+ renameSync(fresh, dir);
138
+ } catch (e) {
139
+ rmSync(fresh, { recursive: true, force: true });
140
+ if (moved && !existsSync(dir)) {
141
+ try { renameSync(old, dir); } catch { /* reported below */ }
142
+ }
143
+ throw e;
144
+ }
145
+ // The swap is done; a failed cleanup is swept on a later run.
146
+ try { rmSync(old, { recursive: true, force: true }); } catch { /* swept later */ }
147
+ }
148
+
149
+ // Refresh stale copies. `skillsDirs`: the agents' skill folders to look in
150
+ // (agentTable(...).map(a => a.skills)); recorded copies are looked at too.
151
+ // Returns what it did per copy, for tests: refreshed | edited | current | failed.
152
+ export function refreshSkillCopies({ version, bundledDir, skillsDirs = [], home = homedir(), now = Date.now(), log = (line) => console.error(line) }) {
153
+ const results = [];
154
+ if (!existsSync(join(bundledDir, "SKILL.md"))) return results;
155
+ const record = readRecord(home);
156
+ // A copy that is a link (or resolves outside its skills folder) points into
157
+ // something the user manages, often a repo checkout: never swap files there.
158
+ const state = { bundledHash: null, changed: false };
159
+ const paths = [...skillsDirs.map((d) => join(d, SKILL_NAME)), ...Object.keys(record.copies)];
160
+ const linked = paths.filter(isLinked);
161
+ for (const path of linked) noteLink(path, { record, now, log, state });
162
+ // What a link points to is off limits too, even if an older run recorded it.
163
+ const targets = new Set(linked.map(real));
164
+ const candidates = new Set(paths.filter((p) => !linked.includes(p)).map(real).filter((p) => !targets.has(p)));
165
+
166
+ for (const dir of candidates) {
167
+ sweepStrays(dirname(dir), now);
168
+ try {
169
+ const r = refreshOne(dir, { version, bundledDir, home, now, log, record, state });
170
+ if (r) results.push(r);
171
+ } catch (e) {
172
+ // Another command refreshing the same copy at this moment (it was
173
+ // mid-swap when this one read it): that one says so.
174
+ if (compareVersions(skillStamp(dir)?.version ?? "0.0.0", version) >= 0) {
175
+ results.push({ dir, action: "current" });
176
+ continue;
177
+ }
178
+ // One unreadable copy must not stop the others.
179
+ results.push({ dir, action: "failed" });
180
+ warnFailed(dir, e, { record, now, log, state });
181
+ }
182
+ }
183
+ if (state.changed) writeRecord(home, record);
184
+ return results;
185
+ }
186
+
187
+ // A symlink, or a folder that resolves somewhere other than <its skills folder>/hyperdecks.
188
+ function isLinked(path) {
189
+ try {
190
+ if (lstatSync(path).isSymbolicLink()) return true;
191
+ } catch {
192
+ return false; // not there
193
+ }
194
+ return real(path) !== join(real(dirname(path)), basename(path));
195
+ }
196
+
197
+ function noteLink(path, { record, now, log, state }) {
198
+ const rec = (record.copies[path] ??= {});
199
+ if (typeof rec.linkNotedAt === "number" && now - rec.linkNotedAt < DAY_MS) return;
200
+ if (!skillStamp(path) || skillStamp(path).name !== SKILL_NAME) return;
201
+ rec.linkNotedAt = now;
202
+ state.changed = true;
203
+ log(`not updating the hyperdecks skill at ${path}: it's a link (to ${real(path)}); update what it points to yourself`);
204
+ }
205
+
206
+ // At most once a day per copy, like the hand-edit warning: a root-owned skills
207
+ // folder would otherwise print this on every command.
208
+ function warnFailed(dir, e, { record, now, log, state }) {
209
+ const rec = (record.copies[dir] ??= {});
210
+ if (typeof rec.failedAt === "number" && now - rec.failedAt < DAY_MS) return;
211
+ rec.failedAt = now;
212
+ state.changed = true;
213
+ log(`⚠ could not refresh the hyperdecks skill at ${dir} (${e?.message ?? e}); run \`hyperdecks skills install\``);
214
+ }
215
+
216
+ function refreshOne(dir, { version, bundledDir, home, now, log, record, state }) {
217
+ const stamp = skillStamp(dir);
218
+ if (!stamp) {
219
+ // Uninstalled since: forget it.
220
+ if (record.copies[dir]) { delete record.copies[dir]; state.changed = true; }
221
+ return null;
222
+ }
223
+ if (stamp.name !== SKILL_NAME) return null;
224
+ const rec = record.copies[dir]?.hash ? record.copies[dir] : null;
225
+ if (compareVersions(stamp.version ?? "0.0.0", version) >= 0) {
226
+ // Current, or newer (from a newer CLI: never downgrade it). Adopt an
227
+ // unrecorded copy that is byte-for-byte the bundled one, so a later edit to
228
+ // it is noticed.
229
+ if (!rec && compareVersions(stamp.version, version) === 0) {
230
+ state.bundledHash ??= skillHash(bundledDir);
231
+ if (skillHash(dir) === state.bundledHash) { record.copies[dir] = { version, hash: state.bundledHash, at: now }; state.changed = true; }
232
+ }
233
+ return { dir, action: "current" };
234
+ }
235
+ if (rec && skillHash(dir) !== rec.hash) {
236
+ if (!(typeof rec.warnedAt === "number" && now - rec.warnedAt < DAY_MS)) {
237
+ log(`⚠ the hyperdecks skill at ${dir} is ${stamp.version ?? "unversioned"} (this CLI is ${version}) and was edited by hand, so it was left as is; \`hyperdecks skills install\` replaces it`);
238
+ rec.warnedAt = now;
239
+ state.changed = true;
240
+ }
241
+ return { dir, action: "edited" };
242
+ }
243
+ let backup = null;
244
+ if (!rec) {
245
+ backup = join(backupRoot(home), `${basename(dirname(dirname(dir))) || "skill"}-${basename(dirname(dir))}-${now}-${process.pid}`);
246
+ mkdirSync(dirname(backup), { recursive: true });
247
+ cpSync(dir, backup, { recursive: true });
248
+ }
249
+ try {
250
+ swapIn(dir, bundledDir, now);
251
+ } catch (e) {
252
+ // Lost a race to another command doing the same refresh: that one says so.
253
+ if (compareVersions(skillStamp(dir)?.version ?? "0.0.0", version) === 0) {
254
+ if (backup) rmSync(backup, { recursive: true, force: true });
255
+ return { dir, action: "current" };
256
+ }
257
+ throw e;
258
+ }
259
+ record.copies[dir] = { version, hash: skillHash(dir), at: now };
260
+ state.changed = true;
261
+ log(backup
262
+ ? `↻ replaced the hyperdecks skill at ${dir} (${stamp.version ?? "unversioned"} → ${version}). It predates update tracking, so any edits you made to it were replaced too; the old copy is saved in ${backup}`
263
+ : `↻ refreshed the hyperdecks skill at ${dir} (${stamp.version ?? "unversioned"} → ${version})`);
264
+ return { dir, action: "refreshed", backup };
265
+ }
package/src/update.mjs ADDED
@@ -0,0 +1,140 @@
1
+ // Is this CLI out of date? Asks /api/cli/version (app/api/cli/version) at most
2
+ // once a day and keeps the answer in ~/.hyperdecks/update-check.json.
3
+ //
4
+ // - A newer `latest` prints one stderr line, at most once a day. A slow or failed
5
+ // check is silent and never blocks a command. HYPERDECKS_NO_UPDATE_CHECK=1 and
6
+ // CI skip the line.
7
+ // - Below `minimum`, the commands that make or ship a deck (GATED) refuse and
8
+ // exit 1, whatever the opt-out says; HYPERDECKS_ALLOW_OLD=1 runs them anyway,
9
+ // with a warning. Unknown (never reached the server): they run.
10
+ // - It never installs anything: it prints the command.
11
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { dirname, join } from "node:path";
14
+
15
+ export const DAY_MS = 24 * 60 * 60 * 1000;
16
+ export const CHECK_TIMEOUT_MS = 1500;
17
+ export const UPDATE_STATE_FILE = join(homedir(), ".hyperdecks", "update-check.json");
18
+
19
+ // Commands that scaffold, narrate, check or release a deck: an old CLI here
20
+ // ships retired templates or since-fixed bugs. Everything else (whoami, deck
21
+ // list, share links, stats) keeps working on any version.
22
+ export const GATED = new Set(["narrate", "check", "release", "deck new", "preview create", "init"]);
23
+
24
+ export const UPGRADE = "npm i -g hyperdecks@latest, or use npx hyperdecks@latest";
25
+
26
+ // "1.2.3" vs "1.10.0": numeric x.y.z; a prerelease (1.2.3-beta) sorts below its
27
+ // release. Anything unparsable compares as 0.0.0.
28
+ export function compareVersions(a, b) {
29
+ const parts = (v) => {
30
+ const m = /^v?(\d+)\.(\d+)\.(\d+)(-.+)?$/.exec(String(v ?? "").trim());
31
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ? 0 : 1] : [0, 0, 0, 1];
32
+ };
33
+ const x = parts(a);
34
+ const y = parts(b);
35
+ for (let i = 0; i < 4; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
36
+ return 0;
37
+ }
38
+
39
+ // "deck new" for `deck new foo`, "narrate" for `narrate foo` (the command table's keys).
40
+ export function commandKey(pos) {
41
+ const two = pos.slice(0, 2).join(" ");
42
+ return GATED.has(two) ? two : String(pos[0] ?? "");
43
+ }
44
+
45
+ export const noticeLine = (latest, version) => `hyperdecks ${latest} is out (you have ${version}): ${UPGRADE}`;
46
+ export const refusalLine = (command, minimum, version) =>
47
+ `hyperdecks ${version} is too old to \`${command}\` (the minimum is ${minimum}): ${UPGRADE}. In an emergency, HYPERDECKS_ALLOW_OLD=1 runs it anyway.`;
48
+
49
+ const quietEnv = (env) => env.HYPERDECKS_NO_UPDATE_CHECK === "1" || /^(1|true)$/i.test(env.CI ?? "");
50
+
51
+ function readState(file) {
52
+ try {
53
+ const s = JSON.parse(readFileSync(file, "utf8"));
54
+ return s && typeof s === "object" ? s : {};
55
+ } catch {
56
+ return {};
57
+ }
58
+ }
59
+
60
+ function writeState(file, state) {
61
+ try {
62
+ mkdirSync(dirname(file), { recursive: true });
63
+ writeFileSync(file, JSON.stringify(state, null, 2));
64
+ } catch {
65
+ // A read-only home only costs the cache.
66
+ }
67
+ }
68
+
69
+ const VERSION_RE = /^\d+\.\d+\.\d+(-[\w.]+)?$/;
70
+
71
+ // { latest, minimum, notes } from the server, or null (slow, offline, bad body).
72
+ export async function fetchVersionInfo(base, { fetchImpl = fetch, timeoutMs = CHECK_TIMEOUT_MS, headers = {} } = {}) {
73
+ try {
74
+ const res = await fetchImpl(`${base}/api/cli/version`, { headers, signal: AbortSignal.timeout(timeoutMs) });
75
+ if (!res.ok) return null;
76
+ const body = await res.json();
77
+ if (!VERSION_RE.test(body?.latest ?? "") || !VERSION_RE.test(body?.minimum ?? "")) return null;
78
+ return { latest: body.latest, minimum: body.minimum, notes: typeof body.notes === "string" ? body.notes : "" };
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ // Runs before a command. Returns { refuse } (the command must not run) and
85
+ // `after()`, which prints the daily notice once the command is done (so the
86
+ // check overlaps the command instead of delaying it).
87
+ export async function updatePreflight(pos, {
88
+ version,
89
+ base,
90
+ env = process.env,
91
+ now = Date.now(),
92
+ stateFile = UPDATE_STATE_FILE,
93
+ fetchImpl = fetch,
94
+ timeoutMs = CHECK_TIMEOUT_MS,
95
+ headers = {},
96
+ warn = (line) => console.error(line),
97
+ } = {}) {
98
+ const command = commandKey(pos);
99
+ const gated = GATED.has(command);
100
+ const quiet = quietEnv(env);
101
+ const state = readState(stateFile);
102
+ const fresh = typeof state.checkedAt === "number" && now - state.checkedAt < DAY_MS && now >= state.checkedAt;
103
+
104
+ let info;
105
+ if (fresh || !base || (quiet && !gated)) {
106
+ info = Promise.resolve(state);
107
+ } else {
108
+ info = fetchVersionInfo(base, { fetchImpl, timeoutMs, headers }).then((got) => {
109
+ // A failed check is remembered too, so an offline machine pays the
110
+ // timeout once a day, not on every command; the last answer is kept.
111
+ const next = { ...readState(stateFile), ...(got ?? {}), checkedAt: now };
112
+ writeState(stateFile, next);
113
+ return next;
114
+ });
115
+ }
116
+
117
+ if (gated) {
118
+ const { minimum } = await info;
119
+ if (minimum && compareVersions(version, minimum) < 0) {
120
+ if (env.HYPERDECKS_ALLOW_OLD !== "1") {
121
+ warn(`✗ ${refusalLine(command, minimum, version)}`);
122
+ return { refuse: true, after: async () => {} };
123
+ }
124
+ warn(`⚠ HYPERDECKS_ALLOW_OLD=1: running \`${command}\` on hyperdecks ${version}, below the minimum ${minimum}. It may ship retired templates or known bugs. Update: ${UPGRADE}`);
125
+ }
126
+ }
127
+
128
+ return {
129
+ refuse: false,
130
+ after: async () => {
131
+ if (quiet) return;
132
+ const got = await info;
133
+ if (!got.latest || compareVersions(got.latest, version) <= 0) return;
134
+ const last = readState(stateFile).notifiedAt;
135
+ if (typeof last === "number" && now - last < DAY_MS && now >= last) return;
136
+ warn(noticeLine(got.latest, version));
137
+ writeState(stateFile, { ...readState(stateFile), notifiedAt: now });
138
+ },
139
+ };
140
+ }