@hypersocial/decks-cli 0.9.15 → 0.9.17

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
@@ -86,8 +111,38 @@ deck new <slug> "<title>" --narrated [--dir <path>]
86
111
  check <slug|deck-dir> [--forbid "<phrase>,<phrase>"] [--max-duration <s>] [--json]
87
112
  play <slug|deck-dir> [--voice <v>] [--slug <slug>] [--port <n>] [--no-open] [--json]
88
113
  release <slug|deck-dir> [--to "<name>" [--email <e>]]... [--qa] [--no-notify] [--title t] [--voice v]
114
+
115
+ avatar import <head.glb> --metadata <file.json> [--thumbnail <png>] [--pack <packId>] [--expect-account <ownerId>] [--json]
89
116
  ```
90
117
 
118
+ ### Importing a private avatar head (for tools)
119
+
120
+ `avatar import` puts a baked, owner-private Minimoji head (bake v17–18,
121
+ `privateFormat: 1`) into the signed-in account, or into one of its own private
122
+ packs that has no grants. Tools such as Minimoji's character creator shell out
123
+ to it rather than reading Hyperdecks credentials.
124
+
125
+ - The metadata file may hold only `name`, `provenance` (both required),
126
+ `limitations`, `stockVoice` (`stock:<name>`), `sha256` and `packId`.
127
+ `sha256` is filled from the file when absent; `--pack` must agree with
128
+ `packId`.
129
+ - Every check runs before anything is uploaded: the GLB, thumbnail (a PNG up to
130
+ 1 MiB, 2048 px a side) and metadata locally, then `--expect-account` (an
131
+ account id or email), avatars being switched on, and the pack. A refusal
132
+ exits 2; a failure during or after the upload exits 1.
133
+ - `--json` prints the stored values, read back after the upload, so re-importing
134
+ the same head and name reports `reused: true` with the stored voice:
135
+
136
+ ```json
137
+ { "ok": true, "owner": { "id": "…", "email": "…" }, "avatarId": "…", "packId": null,
138
+ "sha256": "…", "bakeVersion": 17, "stockVoice": "stock:brian", "created": true,
139
+ "reused": false, "visibility": "private", "defaultChanged": false }
140
+ ```
141
+
142
+ Errors print `{ "ok": false, "error": "…", "code": "account_mismatch" }`. The
143
+ output never holds a token or an avatar URL, and the default presenter is
144
+ never changed.
145
+
91
146
  ## Narrated decks
92
147
 
93
148
  `deck new --narrated` scaffolds `decks/<slug>/` (`index.html` with eight slides for
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.17",
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.17"
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,
@@ -81,6 +85,7 @@ for an import, a code): hand it to them, word for word, and wait.
81
85
  | Make one the default (the person named it) | `hyperdecks avatar default <name>` | `set_default_avatar` |
82
86
  | Remove one (confirm first) | `hyperdecks avatar remove <name>` | `remove_avatar` |
83
87
  | One deck's own presenter | `hyperdecks deck avatar <slug> <name\|none\|default>` | `set_deck_avatar` |
88
+ | A tool imports a baked private head (owner-only; see the CLI README) | `hyperdecks avatar import <head.glb> --metadata <file.json> [--pack <id>] [--expect-account <id>] --json` | — (CLI only) |
84
89
 
85
90
  ## Target Selection
86
91
 
@@ -0,0 +1,260 @@
1
+ // hyperdecks avatar import <head.glb> --metadata <file.json> [--thumbnail <png>]
2
+ // [--pack <packId>] [--expect-account <ownerId|email>] [--json]
3
+ //
4
+ // Puts an owner-private baked Minimoji head into the signed-in account (or one
5
+ // of its private, ungranted packs) through the deployment's
6
+ // POST /avatars/private-bakes route (convex/lib/avatars/privateBakeHttp.ts),
7
+ // so another tool (Minimoji's character creator) shells out to this command
8
+ // instead of reading our credentials or importing our source.
9
+ //
10
+ // Everything that can be refused is refused before a byte is uploaded, and
11
+ // those refusals exit 2; a failure during or after the upload exits 1. The
12
+ // server stays authoritative: the checks here mirror its cheap ones
13
+ // (convex/lib/avatars/privateBake.ts) so a bad file fails fast and offline.
14
+ //
15
+ // --json prints exactly one object on stdout:
16
+ // { ok: true, owner: { id, email }, avatarId, packId, sha256, bakeVersion,
17
+ // stockVoice, created, reused, visibility: "private", defaultChanged: false }
18
+ // { ok: false, error, code[, avatarId] } (avatarId: stored, but not confirmed)
19
+ // The values come from the stored avatar read back after the upload, so a
20
+ // re-import of the same head reports what is stored, not what was sent. No
21
+ // token, avatar URL or view token is ever printed.
22
+ import { createHash } from "node:crypto";
23
+ import { readFileSync, statSync } from "node:fs";
24
+ import { makeFunctionReference } from "convex/server";
25
+ import { client as defaultClient, routeAuth as defaultRouteAuth } from "./runtime.mjs";
26
+
27
+ export const MAX_BAKE_BYTES = 8 * 1024 * 1024;
28
+ export const MAX_THUMBNAIL_BYTES = 1024 * 1024;
29
+ const MIN_BAKE_VERSION = 17, MAX_BAKE_VERSION = 18;
30
+ const ALLOWED_EXTENSIONS = new Set(["KHR_materials_sheen", "KHR_materials_clearcoat", "KHR_materials_unlit", "KHR_materials_ior", "KHR_materials_specular", "KHR_materials_emissive_strength"]);
31
+ const METADATA_KEYS = ["name", "sha256", "provenance", "limitations", "stockVoice", "packId"];
32
+ const UPLOAD_TIMEOUT_MS = 120_000;
33
+ export const IMPORT_USAGE = "usage: avatar import <head.glb> --metadata <file.json> [--thumbnail <png>] [--pack <packId>] [--expect-account <ownerId>] [--json]";
34
+
35
+ const fn = {
36
+ whoami: makeFunctionReference("decks:whoami"),
37
+ listAvatars: makeFunctionReference("avatars:listAvatars"),
38
+ packGet: makeFunctionReference("avatarPacks:get"),
39
+ packGrants: makeFunctionReference("avatarPacks:grants"),
40
+ };
41
+
42
+ // A refusal (exit 2, nothing uploaded) or a failure (exit 1), with a stable
43
+ // code. A failure after the server may have stored the head carries its
44
+ // avatarId when known; re-running is safe, since the route dedups.
45
+ export class ImportError extends Error {
46
+ constructor(code, message, exitCode = 2, avatarId = undefined) {
47
+ super(message);
48
+ this.code = code;
49
+ this.exitCode = exitCode;
50
+ if (avatarId) this.avatarId = avatarId;
51
+ }
52
+ }
53
+ const refuse = (code, message) => { throw new ImportError(code, message, 2); };
54
+ const failed = (code, message, avatarId) => { throw new ImportError(code, message, 1, avatarId); };
55
+ const RERUN = "the head may be stored; re-run the same command to confirm (a re-import reuses it)";
56
+
57
+ const option = (opts, key) => {
58
+ if (!Object.hasOwn(opts, key)) return undefined;
59
+ const value = opts[key];
60
+ if (typeof value !== "string" || !value.trim()) refuse("bad_usage", `--${key} requires a value`);
61
+ return value.trim();
62
+ };
63
+
64
+ function readLocal(path, label, max, code) {
65
+ let stat;
66
+ try { stat = statSync(path); } catch (e) { refuse("bad_usage", `${label} cannot be read: ${path} (${e?.code ?? "error"})`); }
67
+ if (!stat.isFile()) refuse("bad_usage", `${label} is not a file: ${path}`);
68
+ if (stat.size > max) refuse(code, `${label} is ${stat.size} bytes; the limit is ${max}`);
69
+ try { return readFileSync(path); } catch (e) { refuse("bad_usage", `${label} cannot be read: ${path} (${e?.code ?? "error"})`); }
70
+ }
71
+
72
+ // The cheap half of validatePrivateBake: the container, the JSON's shape and
73
+ // the Mini rig header. Geometry budgets and accessor bounds stay server-side.
74
+ export function checkBake(buffer) {
75
+ const bad = (message) => refuse("invalid_glb", message);
76
+ if (buffer.byteLength > MAX_BAKE_BYTES) refuse("glb_too_large", `GLB is ${buffer.byteLength} bytes; the limit is 8 MiB`);
77
+ if (buffer.byteLength < 28) bad("GLB must be 28 bytes to 8 MiB");
78
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
79
+ if (view.getUint32(0, true) !== 0x46546c67 || view.getUint32(4, true) !== 2 || view.getUint32(8, true) !== buffer.byteLength) bad("invalid GLB header");
80
+ const jsonLength = view.getUint32(12, true), binHeader = 20 + jsonLength;
81
+ if (jsonLength > 1024 * 1024 || jsonLength % 4 || binHeader + 8 > buffer.byteLength || view.getUint32(16, true) !== 0x4e4f534a) bad("invalid GLB JSON chunk");
82
+ const binLength = view.getUint32(binHeader, true);
83
+ if (view.getUint32(binHeader + 4, true) !== 0x004e4942 || binLength % 4 || binHeader + 8 + binLength !== buffer.byteLength) bad("expected one embedded GLB binary chunk");
84
+ let doc;
85
+ try { doc = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(20, binHeader))); } catch { bad("GLB JSON chunk does not parse"); }
86
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) bad("GLB JSON must be an object");
87
+ const inspect = (x, depth = 0) => {
88
+ if (depth > 24) bad("GLB JSON is too deeply nested");
89
+ if (Array.isArray(x)) { for (const value of x) inspect(value, depth + 1); return; }
90
+ if (!x || typeof x !== "object") return;
91
+ for (const [key, value] of Object.entries(x)) {
92
+ if (["uri", "url", "__proto__", "constructor", "prototype"].includes(key)) bad("external resources and executable metadata are not allowed");
93
+ if (/texture$/i.test(key)) bad("textures are not supported in private head bakes");
94
+ if (key === "extensions" && value && typeof value === "object") for (const extension of Object.keys(value)) if (!ALLOWED_EXTENSIONS.has(extension)) bad(`unsupported GLB extension ${extension}`);
95
+ inspect(value, depth + 1);
96
+ }
97
+ };
98
+ inspect(doc);
99
+ if (doc.asset?.version !== "2.0" || doc.images?.length || doc.textures?.length || doc.animations?.length || doc.skins?.length) bad("expected a texture-free static Mini head rig");
100
+ for (const extension of [...(doc.extensionsUsed ?? []), ...(doc.extensionsRequired ?? [])]) if (!ALLOWED_EXTENSIONS.has(extension)) bad(`unsupported GLB extension ${extension}`);
101
+ const nodes = Array.isArray(doc.nodes) ? doc.nodes : [];
102
+ const roots = nodes.filter((node) => node?.name === "minimoji"), heads = nodes.filter((node) => node?.name === "head");
103
+ if (roots.length !== 1 || heads.length !== 1) bad("expected unique minimoji and head nodes");
104
+ const meta = roots[0].extras?.minimoji;
105
+ if (!meta || typeof meta !== "object") bad("the minimoji node carries no rig metadata");
106
+ if (!Number.isInteger(meta.v) || meta.v < MIN_BAKE_VERSION || meta.v > MAX_BAKE_VERSION) bad(`unsupported Mini bake version ${meta.v} (expected ${MIN_BAKE_VERSION}-${MAX_BAKE_VERSION})`);
107
+ if (meta.privateFormat !== 1 || meta.character != null || meta.avatar != null) bad("not a private-format head (privateFormat must be 1, with no character or avatar)");
108
+ for (const key of ["u", "H", "W"]) if (typeof meta[key] !== "number" || !Number.isFinite(meta[key]) || meta[key] <= 0) bad(`invalid rig ${key}`);
109
+ return { bakeVersion: meta.v, sha256: createHash("sha256").update(buffer).digest("hex") };
110
+ }
111
+
112
+ // The server's validateThumbnail: a PNG up to 1 MiB and 2048 px per side.
113
+ export function checkThumbnail(buffer) {
114
+ const v = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
115
+ const signature = [137, 80, 78, 71, 13, 10, 26, 10];
116
+ if (buffer.byteLength < 33 || buffer.byteLength > MAX_THUMBNAIL_BYTES || signature.some((value, i) => buffer[i] !== value) || v.getUint32(8) !== 13 || v.getUint32(12) !== 0x49484452 || !v.getUint32(16) || !v.getUint32(20) || v.getUint32(16) > 2048 || v.getUint32(20) > 2048) refuse("invalid_thumbnail", "thumbnail must be a PNG up to 1 MiB and 2048 pixels per side");
117
+ }
118
+
119
+ // The server's parseImportMetadata, plus what the CLI fills in: sha256 (from
120
+ // the file) and limitations (none) when absent, and --pack as the pack.
121
+ export function buildMetadata(raw, { sha256, pack }) {
122
+ const bad = (message) => refuse("invalid_metadata", message);
123
+ let m;
124
+ try { m = JSON.parse(raw); } catch { bad("metadata is not valid JSON"); }
125
+ if (!m || typeof m !== "object" || Array.isArray(m)) bad("metadata must be a JSON object");
126
+ const unknown = Object.keys(m).filter((key) => !METADATA_KEYS.includes(key));
127
+ if (unknown.length) bad(`unsupported metadata field ${unknown.join(", ")} (allowed: ${METADATA_KEYS.join(", ")}; owner, visibility and default are server-controlled)`);
128
+ if (typeof m.name !== "string" || !m.name.trim() || m.name.length > 80) bad("name is required (up to 80 characters)");
129
+ if (typeof m.provenance !== "string" || !m.provenance.trim() || m.provenance.length > 300) bad("provenance is required (up to 300 characters)");
130
+ if (m.limitations !== undefined && (!Array.isArray(m.limitations) || m.limitations.length > 20 || m.limitations.some((x) => typeof x !== "string" || x.length > 400))) bad("limitations must be up to 20 short strings");
131
+ if (m.stockVoice !== undefined && (typeof m.stockVoice !== "string" || !/^stock:[a-z0-9-]{1,40}$/.test(m.stockVoice))) bad("stockVoice must be a stock voice reference (stock:<name>)");
132
+ if (m.packId !== undefined && (typeof m.packId !== "string" || !/^[a-z0-9]{16,64}$/.test(m.packId))) bad("invalid packId");
133
+ if (m.sha256 !== undefined && (typeof m.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(m.sha256))) bad("sha256 must be 64 lowercase hex characters");
134
+ if (m.sha256 !== undefined && m.sha256 !== sha256) refuse("sha256_mismatch", `metadata sha256 ${m.sha256} does not match the GLB (${sha256})`);
135
+ if (pack && m.packId !== undefined && m.packId !== pack) refuse("pack_conflict", `--pack ${pack} conflicts with metadata packId ${m.packId}`);
136
+ const packId = pack ?? m.packId;
137
+ if (packId !== undefined && !/^[a-z0-9]{16,64}$/.test(packId)) refuse("bad_usage", "invalid --pack id");
138
+ const out = { name: m.name, sha256, provenance: m.provenance, limitations: m.limitations ?? [], ...(m.stockVoice ? { stockVoice: m.stockVoice } : {}), ...(packId ? { packId } : {}) };
139
+ if (JSON.stringify(out).length > 8192) bad("metadata is too large");
140
+ return out;
141
+ }
142
+
143
+ // No credential at all is "not signed in"; a dropped connection or a 5xx is
144
+ // "server unreachable" (retry), never an account or pack verdict; a refused
145
+ // token exchange is "auth failed" (log in again).
146
+ const UNREACHABLE = /fetch failed|ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket|network|did not respond|could not reach|timed? ?out|\b5\d\d\b/i;
147
+ const signInCode = (e) => {
148
+ const text = String(e?.message ?? e);
149
+ if (/not authenticated/i.test(text)) return "not_signed_in";
150
+ if (/HSDECKS_CONVEX_SITE_URL|needs --convex/.test(text)) return "bad_config";
151
+ return UNREACHABLE.test(text) ? "server_unreachable" : "auth_failed";
152
+ };
153
+ const unreachable = (e, what) => refuse("server_unreachable", `could not ${what}; nothing was uploaded (${errorText(e)})`);
154
+ const errorText = (e) => String(typeof e?.data === "string" ? e.data : e?.message ?? e).replace(/\s+/g, " ").slice(0, 300);
155
+
156
+ // An owner-only import never lands in a pack anyone else can see.
157
+ async function checkPack(c, packId) {
158
+ let pack;
159
+ try { pack = await c.query(fn.packGet, { packId }); } catch (e) { if (UNREACHABLE.test(String(e?.message ?? e))) unreachable(e, `check pack ${packId}`); refuse("pack_not_found", `pack ${packId} not found (${errorText(e)})`); }
160
+ if (!pack) refuse("pack_not_found", `pack ${packId} not found or unavailable to your account`);
161
+ if (pack.access !== "owner") refuse("pack_not_owned", `pack ${packId} belongs to another account`);
162
+ if (pack.visibility !== "private") refuse("pack_not_private", `pack ${packId} is ${pack.visibility}; an owner-only import goes only into a private pack`);
163
+ let grants;
164
+ try { grants = await c.query(fn.packGrants, { packId }); } catch (e) { refuse(UNREACHABLE.test(String(e?.message ?? e)) ? "server_unreachable" : "pack_check_failed", `could not read the grants of pack ${packId}; nothing was uploaded (${errorText(e)})`); }
165
+ if (!Array.isArray(grants) || grants.length) refuse("pack_has_grants", `pack ${packId} is shared with ${grants?.length ?? "some"} grant(s); an owner-only import goes only into an ungranted pack`);
166
+ }
167
+
168
+ export async function avatarImport(file, opts = {}, { client = defaultClient, routeAuth = defaultRouteAuth, fetchImpl = fetch } = {}) {
169
+ if (!file || typeof file !== "string" || file.startsWith("--")) refuse("bad_usage", IMPORT_USAGE);
170
+ const metadataPath = option(opts, "metadata");
171
+ if (!metadataPath) refuse("bad_usage", `--metadata is required. ${IMPORT_USAGE}`);
172
+ const thumbnailPath = option(opts, "thumbnail"), pack = option(opts, "pack"), expect = option(opts, "expect-account");
173
+
174
+ // 1. Local checks: offline, before any sign-in.
175
+ const head = readLocal(file, "GLB", MAX_BAKE_BYTES, "glb_too_large");
176
+ const bake = checkBake(head);
177
+ let thumbnail = null;
178
+ if (thumbnailPath) { thumbnail = readLocal(thumbnailPath, "thumbnail", MAX_THUMBNAIL_BYTES, "invalid_thumbnail"); checkThumbnail(thumbnail); }
179
+ let rawMetadata;
180
+ try { rawMetadata = readFileSync(metadataPath, "utf8"); } catch { refuse("bad_usage", `metadata file not found: ${metadataPath}`); }
181
+ if (rawMetadata.length > 64 * 1024) refuse("invalid_metadata", "metadata is too large");
182
+ const metadata = buildMetadata(rawMetadata, { sha256: bake.sha256, pack });
183
+
184
+ // 2. The account: who this would land under, and whether avatars are on.
185
+ let c, who;
186
+ try { c = await client(opts); who = await c.query(fn.whoami, {}); } catch (e) { refuse(signInCode(e), errorText(e)); }
187
+ if (!who?.subject) refuse("not_signed_in", "not signed in; run `hyperdecks login`");
188
+ const owner = { id: who.subject, email: who.email ?? null };
189
+ if (expect && expect !== owner.id && expect.toLowerCase() !== String(owner.email ?? "").toLowerCase()) refuse("account_mismatch", `signed in as ${owner.id}${owner.email ? ` (${owner.email})` : ""}, not ${expect}; nothing was uploaded`);
190
+ let before;
191
+ try { before = await c.query(fn.listAvatars, {}); } catch (e) { unreachable(e, "read your avatars"); }
192
+ if (before?.enabled === false) refuse("avatars_disabled", "avatars are not switched on for this account (AVATARS_ENABLED)");
193
+
194
+ // 3. The destination.
195
+ if (metadata.packId) await checkPack(c, metadata.packId);
196
+
197
+ // 4. The upload, with the CLI's own sign-in.
198
+ let auth;
199
+ try { auth = await routeAuth(opts); } catch (e) { refuse(signInCode(e), errorText(e)); }
200
+ const form = new FormData();
201
+ form.set("metadata", JSON.stringify(metadata));
202
+ form.set("head", new Blob([head], { type: "model/gltf-binary" }), "head.glb");
203
+ if (thumbnail) form.set("thumbnail", new Blob([thumbnail], { type: "image/png" }), "thumbnail.png");
204
+ let res;
205
+ try {
206
+ res = await fetchImpl(`${auth.siteUrl}/avatars/private-bakes`, { method: "POST", headers: { authorization: `Bearer ${auth.token}` }, body: form, signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS) });
207
+ } catch (e) {
208
+ // The body may have reached the server before the connection dropped.
209
+ failed("upload_uncertain", `${e?.name === "TimeoutError" ? `upload exceeded ${UPLOAD_TIMEOUT_MS / 1000}s` : `upload interrupted: ${errorText(e)}`}; ${RERUN}`);
210
+ }
211
+ let body = null;
212
+ try { body = await res.json(); } catch { /* reported below by status */ }
213
+ if (!res.ok) {
214
+ const message = typeof body?.error === "string" ? body.error.slice(0, 300) : `HTTP ${res.status}`;
215
+ if (res.status === 401) failed("auth_failed", `the server did not accept the sign-in: ${message}`);
216
+ if (res.status === 403) failed("avatars_disabled", message);
217
+ if (res.status >= 500) failed("server_error", `the server failed (HTTP ${res.status}); ${RERUN}`);
218
+ failed("upload_rejected", `the server refused the head: ${message}`);
219
+ }
220
+ if (typeof body?.id !== "string" || typeof body.created !== "boolean") failed("stored_unverified", `the server accepted the upload (HTTP ${res.status}) but its reply could not be read; ${RERUN}`);
221
+
222
+ // 5. Read back what is stored: on a dedup, the stored digest and voice win.
223
+ let after;
224
+ try { after = await c.query(fn.listAvatars, {}); } catch (e) { failed("stored_unverified", `stored as ${body.id}, but reading it back failed (${errorText(e)}); ${RERUN}`, body.id); }
225
+ const row = after?.avatars?.find((a) => a.id === body.id);
226
+ const stored = row?.head?.bakedHead;
227
+ if (!row || !stored) failed("stored_unverified", `stored as ${body.id}, but it is missing from your avatars; ${RERUN}`, body.id);
228
+ return {
229
+ ok: true,
230
+ owner,
231
+ avatarId: body.id,
232
+ packId: row.packId ?? null,
233
+ sha256: stored.sha256,
234
+ bakeVersion: stored.bakeVersion ?? stored.version,
235
+ stockVoice: row.stockVoice ?? null,
236
+ created: body.created,
237
+ reused: !body.created,
238
+ visibility: "private",
239
+ defaultChanged: false,
240
+ };
241
+ }
242
+
243
+ // The command: prints the JSON (or a line for a person) and maps errors to the
244
+ // stable { ok:false, error, code } shape with exit 2 (refused) or 1 (failed).
245
+ export async function avatarImportCommand(pos = [], opts = {}, { log = console.log, deps } = {}) {
246
+ try {
247
+ if (pos.length > 1) refuse("bad_usage", IMPORT_USAGE);
248
+ const out = await avatarImport(pos[0], opts, deps);
249
+ if (opts.json) log(JSON.stringify(out, null, 2));
250
+ else log(`✓ ${out.reused ? "Already imported" : "Imported"} privately as ${out.avatarId}${out.packId ? ` in pack ${out.packId}` : ""} (bake v${out.bakeVersion}${out.stockVoice ? `, suggested voice ${out.stockVoice}` : ""}). Your default presenter is unchanged.`);
251
+ return out;
252
+ } catch (e) {
253
+ const error = e instanceof ImportError ? e : new ImportError("failed", errorText(e), 1);
254
+ if (opts.json) {
255
+ log(JSON.stringify({ ok: false, error: error.message, code: error.code, ...(error.avatarId ? { avatarId: error.avatarId } : {}) }, null, 2));
256
+ error.reported = true;
257
+ }
258
+ throw error;
259
+ }
260
+ }
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) {
@@ -608,6 +632,11 @@ commands:
608
632
  avatar pack [list|create|get|add|grant|grants|revoke|publish|unpublish|invitations|claim|catalog]
609
633
  owner-managed packs; create <name> --private-only permanently prevents publication
610
634
  avatar team [list|create|members|add|remove] owner-managed account groups for pack grants
635
+ avatar import <head.glb> --metadata <file.json> [--thumbnail <png>] [--pack <packId>] [--expect-account <ownerId>] [--json]
636
+ upload a baked private Minimoji head to your account (or one of your private, ungranted
637
+ packs); checked locally and against the account first (refusals exit 2, nothing uploaded).
638
+ --json: { ok, owner, avatarId, packId, sha256, bakeVersion, stockVoice, created, reused,
639
+ visibility, defaultChanged } as stored; errors { ok:false, error, code }
611
640
  avatar [--json] your avatars (who presents decks in your voice) and the default
612
641
  avatar new [--species <s>] pick a species, then an avatar (s shuffles); --json or an agent gets a pick link
613
642
  avatar from-photo [file] [--save-to-minimoji]
@@ -1041,6 +1070,7 @@ function commandTable(pos, rest, opts) {
1041
1070
  },
1042
1071
  "avatar pack": async () => (await import("./avatar-packs.mjs")).avatarPacksCommand(rest, opts),
1043
1072
  "avatar team": async () => (await import("./avatar-packs.mjs")).avatarTeamsCommand(rest, opts),
1073
+ "avatar import": async () => (await import("./avatar-import.mjs")).avatarImportCommand(rest, opts),
1044
1074
  "avatar new": async () => {
1045
1075
  const { avatarNew } = await import("./avatar.mjs");
1046
1076
  const { askLine } = await import("./init.mjs");
@@ -1250,7 +1280,52 @@ export async function runCli(argv = process.argv.slice(2)) {
1250
1280
  await handler();
1251
1281
  return 0;
1252
1282
  } catch (e) {
1253
- console.error("Error:", ops.errorText(e));
1254
- return 1;
1283
+ // A command that already printed its own error (avatar import --json)
1284
+ // says so, and may name its exit code (2: refused before any change).
1285
+ if (!e?.reported) console.error("Error:", ops.errorText(e));
1286
+ return Number.isInteger(e?.exitCode) && e.exitCode > 0 ? e.exitCode : 1;
1287
+ }
1288
+ }
1289
+
1290
+ // The installed CLI's entry point (bin/): runCli plus the version checks. Kept
1291
+ // out of runCli so tests and the repo's own cli/decks.mjs dispatch without
1292
+ // touching the network or ~/.hyperdecks.
1293
+ // 1. refresh this machine's stale hyperdecks skill copies (local, no network);
1294
+ // 2. below the server's minimum, refuse the commands that make or ship a deck;
1295
+ // 3. after the command, print the once-a-day "newer version is out" line.
1296
+ // Only an installed copy (global or an npx cache, both under node_modules) does
1297
+ // this: run from a source checkout it would push a work-in-progress skill into
1298
+ // the developer's agents, and the repo's tests spawn the bin.
1299
+ export const isInstalledCopy = (dir = PACKAGED_SKILLS_DIR) => /[\\/]node_modules[\\/]/.test(dir);
1300
+
1301
+ export async function main(argv = process.argv.slice(2), { env = process.env, home, fetchImpl = fetch, stateFile, now, log, installed = isInstalledCopy() } = {}) {
1302
+ if (!installed) return runCli(argv);
1303
+ let parsed;
1304
+ try {
1305
+ parsed = parse(argv);
1306
+ } catch {
1307
+ return runCli(argv);
1308
+ }
1309
+ const { pos, opts } = parsed;
1310
+ if (opts.version || opts.help || pos.length === 0) return runCli(argv);
1311
+
1312
+ try {
1313
+ refreshSkillCopies({ version: VERSION, bundledDir: join(PACKAGED_SKILLS_DIR, "hyperdecks"), skillsDirs: agentTable({ home, env }).map((a) => a.skills), ...(home ? { home } : {}), ...(now ? { now } : {}), ...(log ? { log } : {}) });
1314
+ } catch (e) {
1315
+ // Never let housekeeping stop a command, but say what went wrong.
1316
+ (log ?? ((line) => console.error(line)))(`⚠ hyperdecks skill freshness check failed: ${e?.message ?? e}`);
1317
+ }
1318
+
1319
+ let base = null;
1320
+ try {
1321
+ const t = target(opts);
1322
+ if (t.name === "prod") base = t.brokerBase;
1323
+ } catch {
1324
+ // A bad --dev setup is reported by the command itself.
1255
1325
  }
1326
+ const pre = await updatePreflight(pos, { version: VERSION, base, env, fetchImpl, headers: CLIENT_HEADERS, ...(stateFile ? { stateFile } : {}), ...(now ? { now } : {}), ...(log ? { warn: log } : {}) });
1327
+ if (pre.refuse) return 1;
1328
+ const code = await runCli(argv);
1329
+ await pre.after();
1330
+ return code;
1256
1331
  }
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.17";
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");
@@ -417,6 +428,29 @@ export async function client(opts = {}) {
417
428
  return c;
418
429
  }
419
430
 
431
+ // For the deployment's own HTTP routes (<deployment>.convex.site): the CLI's
432
+ // broker JWT and the site origin, so a route is called with the same sign-in
433
+ // as every other command. The token is for an Authorization header only; never
434
+ // print it. On the dev target HSDECKS_CONVEX_SITE_URL overrides the origin (a
435
+ // self-hosted or local backend whose site is not the cloud URL's sibling); prod
436
+ // ignores it, so a leftover variable never sends a prod token elsewhere.
437
+ export function siteUrlFor(convexUrl, { dev = false } = {}) {
438
+ const override = dev ? process.env.HSDECKS_CONVEX_SITE_URL?.trim() : "";
439
+ if (override) return normalizeBase(override);
440
+ const url = new URL(convexUrl);
441
+ if (url.hostname.endsWith(".convex.cloud")) url.hostname = url.hostname.replace(/\.convex\.cloud$/, ".convex.site");
442
+ else if (["127.0.0.1", "localhost"].includes(url.hostname) && url.port) url.port = String(Number(url.port) + 1);
443
+ else throw new Error(`cannot tell the HTTP site of ${convexUrl}; set HSDECKS_CONVEX_SITE_URL`);
444
+ return normalizeBase(url.toString());
445
+ }
446
+
447
+ export async function routeAuth(opts = {}) {
448
+ const t = target(opts);
449
+ const refreshToken = resolveRefreshToken(t, opts);
450
+ if (!refreshToken) throw new Error(`not authenticated for ${t.name} - run \`hyperdecks login${t.name === "dev" ? " --dev" : ""}\``);
451
+ return { siteUrl: siteUrlFor(t.convexUrl, { dev: t.name === "dev" }), token: await jwtFor(t.brokerBase, refreshToken) };
452
+ }
453
+
420
454
  export function openBrowser(url) {
421
455
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
422
456
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
@@ -513,6 +547,16 @@ export function installHyperdecksSkill(opts = {}, extraArgs = [], { spawn = spaw
513
547
  const tail = quiet ? `${result.stdout || ""}\n${result.stderr || ""}`.trim().split("\n").filter((l) => l.trim() && !/^npm warn/i.test(l)).slice(-3).join(" ") : "";
514
548
  throw new Error(`skills add failed with exit code ${result.status}${tail ? `: ${tail}` : ""}`);
515
549
  }
550
+ // Remember what was written (and its hash) so later runs can refresh these
551
+ // copies when the CLI updates, and leave hand-edited ones alone.
552
+ const table = agentTable({ home, env });
553
+ const written = agents[0] === "*" ? table : table.filter((a) => agents.includes(a.id));
554
+ try {
555
+ recordSkillInstall(written.map((a) => a.skills), home ? { home } : {});
556
+ } catch (e) {
557
+ // The install worked; only automatic refreshes of it are lost.
558
+ if (!quiet) log(`⚠ installed, but could not record it for automatic updates (${e.message})`);
559
+ }
516
560
  return { installed: true, agents, source };
517
561
  }
518
562
 
@@ -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
+ }