@zenrick/zenkit 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/INSTALL.md CHANGED
@@ -22,6 +22,37 @@ npx /caminho/para/zenkit init --layer archive:<url-do-recorte>#sha256=<hash> #
22
22
 
23
23
  Os recortes de negócio pagos (clínica, loja, prestador, dono) não vêm no pacote público: cada um é uma camada privada `archive`, entregue ao comprador como `--layer archive:<url>#sha256=<hash>`.
24
24
 
25
+ ## Kits pagos
26
+
27
+ Depois da compra, a página de retirada mostra um **token** (`zkt_…`). Guarde-o num
28
+ arquivo fora do git (por exemplo `~/.zenkit/kit-token.txt`) e **não commite** esse arquivo.
29
+
30
+ **Bash / macOS / Linux:**
31
+
32
+ ```bash
33
+ export ZENKIT_ARCHIVE_TOKEN_FILE=~/.zenkit/kit-token.txt
34
+ npx @zenrick/zenkit init --layer kit:<nome-do-kit>
35
+ ```
36
+
37
+ **PowerShell:**
38
+
39
+ ```powershell
40
+ $env:ZENKIT_ARCHIVE_TOKEN_FILE = "$HOME\.zenkit\kit-token.txt"
41
+ npx @zenrick/zenkit init --layer kit:<nome-do-kit>
42
+ ```
43
+
44
+ Para buscar de novo a versão mais nova no servidor (ou reinstalar no projeto):
45
+
46
+ ```bash
47
+ npx @zenrick/zenkit kit update <nome-do-kit>
48
+ npx @zenrick/zenkit kit update <nome-do-kit> --into /caminho/do/projeto
49
+ ```
50
+
51
+ Enquanto o acesso estiver ativo, o CLI tenta sempre a versão publicada mais recente.
52
+ Sem rede ou com acesso suspenso (pagamento em atraso, cancelamento), ele usa a **última
53
+ cópia já baixada** no cache local (`~/.zenkit/layers`, ou `ZENKIT_LAYER_CACHE`).
54
+ Servidor padrão: `https://nexus.zenrick.dev` (`ZENKIT_KITS_URL` para outro ambiente).
55
+
25
56
  Um comando grava os três alvos principais **e** a pasta do padrão aberto:
26
57
 
27
58
  | Pasta | Quem lê |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenrick/zenkit",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Agentes, skills e regras para assistentes de IA (Cursor, Claude Code, Codex, Gemini CLI), com camadas privadas por pessoa. npx @zenrick/zenkit init",
6
6
  "author": "Zenrick",
package/scripts/cli.mjs CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  packLayer,
26
26
  pullLayer,
27
27
  pushLayer,
28
+ resolveKitLayer,
28
29
  } from "./layer-remote.mjs";
29
30
  import { pluginId, ROOT, storefrontBundles } from "./product.mjs";
30
31
 
@@ -39,6 +40,7 @@ Uso:
39
40
  zenkit layer pull NOME [--version N] [--into DIR]
40
41
  zenkit layer list
41
42
  zenkit layer pack DIR --out ARQUIVO [--bundle RECEITA]
43
+ zenkit kit update NOME [--into DIR]
42
44
 
43
45
  --layer soma uma camada (diretório com zenkit-layer.yaml) por cima do núcleo;
44
46
  repita para empilhar, da mais geral para a mais específica. Sem --layer, vale
@@ -48,6 +50,10 @@ ZENKIT_LAYERS (caminhos separados pelo separador do sistema).
48
50
  --layer archive:URL#sha256=HASH usa uma camada em arquivo, baixada por https e
49
51
  conferida pelo sha256 (token, se houver: ZENKIT_ARCHIVE_TOKEN ou
50
52
  ZENKIT_ARCHIVE_TOKEN_FILE).
53
+ --layer kit:NOME usa um kit pago comprado (token em ZENKIT_ARCHIVE_TOKEN ou
54
+ ZENKIT_ARCHIVE_TOKEN_FILE; servidor em ZENKIT_KITS_URL, padrão https://nexus.zenrick.dev).
55
+ Sempre busca a versão mais nova enquanto o acesso estiver ativo; sem acesso ou sem rede,
56
+ usa a última baixada.
51
57
 
52
58
  layer push publica uma nova versão da camada no NexusCore (recusa segredo).
53
59
  NexusCore: ZENKIT_NEXUS_URL e ZENKIT_NEXUS_KEY (ou ZENKIT_NEXUS_KEY_FILE).
@@ -76,6 +82,25 @@ function parsePackFlags(args) {
76
82
  return dir && parsed.out ? parsed : null;
77
83
  }
78
84
 
85
+ export async function runKit(argv, { env = process.env, fetch, warn = console.warn, out = process.stdout } = {}) {
86
+ const [sub, ...rest] = argv;
87
+ if (sub === "update" && rest.length >= 1) {
88
+ const [name, ...flags] = rest;
89
+ let into;
90
+ for (let i = 0; i < flags.length; i++) {
91
+ if (flags[i] === "--into" && flags[i + 1]) into = path.resolve(flags[++i]);
92
+ else throw new Error(`flag desconhecida: ${flags[i]}`);
93
+ }
94
+ const res = await resolveKitLayer(name, { env, fetch, warn });
95
+ await runInit({ into, bundle: "kit-lite", layers: [res.dir] });
96
+ out.write(`kit '${name}' v${res.version} (${res.cached ? "cache" : "atualizado"})\n`);
97
+ return res;
98
+ }
99
+ const err = new Error(`uso: zenkit kit update NOME [--into DIR]\n${USAGE}`);
100
+ err.exitCode = 1;
101
+ throw err;
102
+ }
103
+
79
104
  export async function runLayer(argv, { env = process.env, fetch, out = process.stdout } = {}) {
80
105
  const [sub, ...rest] = argv;
81
106
  if (sub === "push" && rest.length === 1) {
@@ -298,6 +323,10 @@ export async function runCli(argv) {
298
323
  await runLayer(rest);
299
324
  return;
300
325
  }
326
+ if (cmd === "kit") {
327
+ await runKit(rest);
328
+ return;
329
+ }
301
330
  throw new Error(`comando desconhecido: ${cmd}\n${USAGE}`);
302
331
  }
303
332
 
@@ -42,12 +42,17 @@ const SECRET_CONTENT = [
42
42
  ];
43
43
 
44
44
  export const ARCHIVE_PREFIX = "archive:";
45
+ export const KIT_PREFIX = "kit:";
46
+ export const DEFAULT_KITS_URL = "https://nexus.zenrick.dev";
45
47
  /** A paid or shared layer file can be bigger than what NexusCore accepts per version. */
46
48
  export const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
47
49
 
48
- /** A layer spec that is not a local directory: `nexuscore:` or `archive:`. */
50
+ /** A layer spec that is not a local directory: `nexuscore:`, `archive:` or `kit:`. */
49
51
  export function isRemoteSpec(spec) {
50
- return typeof spec === "string" && (spec.startsWith(REMOTE_PREFIX) || spec.startsWith(ARCHIVE_PREFIX));
52
+ return (
53
+ typeof spec === "string" &&
54
+ (spec.startsWith(REMOTE_PREFIX) || spec.startsWith(ARCHIVE_PREFIX) || spec.startsWith(KIT_PREFIX))
55
+ );
51
56
  }
52
57
 
53
58
  /**
@@ -91,6 +96,32 @@ export function parseRemoteSpec(spec) {
91
96
  return { name, version: version ? Number(version) : undefined };
92
97
  }
93
98
 
99
+ export function parseKitSpec(spec) {
100
+ const name = spec.slice(KIT_PREFIX.length);
101
+ if (!NAME_RE.test(name || "")) {
102
+ throw new Error("kit inválido: use kit:<nome>");
103
+ }
104
+ return { name };
105
+ }
106
+
107
+ /** Paid-kit API base URL (`ZENKIT_KITS_URL` or {@link DEFAULT_KITS_URL}). */
108
+ export function kitsBaseUrl(env = process.env) {
109
+ let url;
110
+ try {
111
+ url = new URL(env.ZENKIT_KITS_URL || DEFAULT_KITS_URL);
112
+ } catch {
113
+ throw new Error("ZENKIT_KITS_URL inválida");
114
+ }
115
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
116
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
117
+ throw new Error(`servidor de kits só por https (recebido ${url.protocol}//${url.host})`);
118
+ }
119
+ if (url.username || url.password) {
120
+ throw new Error("ZENKIT_KITS_URL com credencial; use ZENKIT_ARCHIVE_TOKEN ou ZENKIT_ARCHIVE_TOKEN_FILE");
121
+ }
122
+ return url;
123
+ }
124
+
94
125
  /** Find secret-looking material; returns `path: motivo` strings, empty when clean. */
95
126
  export function findSecrets(files) {
96
127
  const hits = [];
@@ -360,6 +391,166 @@ async function archiveToken(env) {
360
391
  return "";
361
392
  }
362
393
 
394
+ async function readKitsState(env) {
395
+ const file = path.join(layerCacheDir(env), "kits.json");
396
+ try {
397
+ const data = JSON.parse(await fs.readFile(file, "utf8"));
398
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
399
+ } catch {
400
+ return {};
401
+ }
402
+ }
403
+
404
+ async function writeKitsState(env, state) {
405
+ const root = layerCacheDir(env);
406
+ await fs.mkdir(root, { recursive: true });
407
+ const file = path.join(root, "kits.json");
408
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
409
+ await fs.writeFile(tmp, JSON.stringify(state), { mode: 0o600 });
410
+ await fs.rename(tmp, file);
411
+ }
412
+
413
+ async function archiveCacheReady(env, pin) {
414
+ try {
415
+ await fs.access(path.join(layerCacheDir(env), "archive", pin, LAYER_MANIFEST));
416
+ return true;
417
+ } catch {
418
+ return false;
419
+ }
420
+ }
421
+
422
+ /**
423
+ * Resolve a paid kit by name: consult the kits API for the latest release,
424
+ * download the bundle with the archive token, and track state in `kits.json`
425
+ * (never the token). Falls back to the last downloaded version when offline or
426
+ * when access ended but the archive cache still has the bundle.
427
+ */
428
+ export async function resolveKitLayer(
429
+ name,
430
+ { env = process.env, fetch: fetchImpl = globalThis.fetch, warn = console.warn } = {},
431
+ ) {
432
+ const token = await archiveToken(env);
433
+ if (!token) {
434
+ throw new Error(
435
+ "kit pago precisa do token: defina ZENKIT_ARCHIVE_TOKEN ou ZENKIT_ARCHIVE_TOKEN_FILE (veio no link de retirada)",
436
+ );
437
+ }
438
+
439
+ const base = kitsBaseUrl(env);
440
+ const baseOrigin = base.origin;
441
+ const apiRoot = base.href.replace(/\/+$/, "");
442
+ const state = await readKitsState(env);
443
+ const prev = state[name];
444
+
445
+ async function fromCache(warnMsg) {
446
+ if (!prev?.sha256 || !(await archiveCacheReady(env, prev.sha256))) return null;
447
+ warn(`[zenkit] ${warnMsg}`);
448
+ return {
449
+ name,
450
+ version: prev.versao,
451
+ sha256: prev.sha256,
452
+ dir: path.join(layerCacheDir(env), "archive", prev.sha256),
453
+ cached: true,
454
+ };
455
+ }
456
+
457
+ const latestUrl = `${apiRoot}/v1/kits/${encodeURIComponent(name)}/latest`;
458
+ let res;
459
+ try {
460
+ res = await fetchImpl(latestUrl, {
461
+ headers: { authorization: `Bearer ${token}` },
462
+ signal: AbortSignal.timeout(15000),
463
+ });
464
+ } catch {
465
+ if (prev) {
466
+ const hit = await fromCache(`servidor de kits indisponível; usando kit ${name} v${prev.versao} do cache`);
467
+ if (hit) return hit;
468
+ }
469
+ throw new Error("servidor de kits indisponível e kit sem cópia local");
470
+ }
471
+
472
+ if (!res.ok) {
473
+ if (res.status === 401) {
474
+ if (prev) {
475
+ const hit = await fromCache(
476
+ `token do kit inválido ou revogado; usando kit ${name} v${prev.versao} já baixado, sem atualizações`,
477
+ );
478
+ if (hit) return hit;
479
+ }
480
+ throw new Error("token do kit inválido ou revogado");
481
+ }
482
+ if (res.status === 403) {
483
+ if (prev) {
484
+ const hit = await fromCache(
485
+ `acesso ao kit suspenso; usando kit ${name} v${prev.versao} já baixado, sem atualizações`,
486
+ );
487
+ if (hit) return hit;
488
+ }
489
+ throw new Error("acesso ao kit suspenso ou token de outro kit");
490
+ }
491
+ if (res.status === 404) {
492
+ throw new Error(`kit '${name}' não encontrado ou sem versão publicada`);
493
+ }
494
+ if (res.status === 503) {
495
+ if (prev) {
496
+ const hit = await fromCache(`servidor de kits indisponível; usando kit ${name} v${prev.versao} do cache`);
497
+ if (hit) return hit;
498
+ }
499
+ throw new Error("venda de kits indisponível no momento");
500
+ }
501
+ if (res.status >= 500) {
502
+ if (prev) {
503
+ const hit = await fromCache(`servidor de kits indisponível; usando kit ${name} v${prev.versao} do cache`);
504
+ if (hit) return hit;
505
+ }
506
+ throw new Error("servidor de kits indisponível e kit sem cópia local");
507
+ }
508
+ throw new Error(`kit '${name}': HTTP ${res.status}`);
509
+ }
510
+
511
+ let body;
512
+ try {
513
+ body = await res.json();
514
+ } catch {
515
+ throw new Error("resposta inválida do servidor de kits");
516
+ }
517
+
518
+ const pin = String(body.sha256 || "").toLowerCase();
519
+ if (!/^[0-9a-f]{64}$/.test(pin)) {
520
+ throw new Error(`kit '${name}': sha256 inválido na resposta`);
521
+ }
522
+ const versao = body.versao;
523
+ if (!Number.isInteger(versao) || versao < 1) {
524
+ throw new Error(`kit '${name}': versão inválida na resposta`);
525
+ }
526
+
527
+ let downloadUrl;
528
+ try {
529
+ downloadUrl = new URL(body.url);
530
+ } catch {
531
+ throw new Error(`kit '${name}': URL de download inválida`);
532
+ }
533
+ if (downloadUrl.origin !== baseOrigin) {
534
+ throw new Error(
535
+ "endereço de download do kit fora do servidor configurado; recusado para não enviar o token a outro host",
536
+ );
537
+ }
538
+
539
+ const archived = await fetchArchiveLayer(`${ARCHIVE_PREFIX}${body.url}#sha256=${pin}`, {
540
+ env,
541
+ fetch: fetchImpl,
542
+ });
543
+
544
+ state[name] = { versao, sha256: pin, url: body.url, resolvido_em: new Date().toISOString() };
545
+ await writeKitsState(env, state);
546
+
547
+ if (prev?.versao && prev.versao !== versao) {
548
+ warn(`[zenkit] kit '${name}' atualizado da v${prev.versao} para a v${versao}`);
549
+ }
550
+
551
+ return { name, version: versao, sha256: pin, dir: archived.dir, cached: false };
552
+ }
553
+
363
554
  /**
364
555
  * Download an `archive:` layer, check its sha256 against the pin and unpack it
365
556
  * under the cache, keyed by that hash. A hash already in the cache is used
@@ -398,6 +589,9 @@ export async function resolveLayerSpecs(specs, opts = {}) {
398
589
  dirs.push(spec);
399
590
  } else if (spec.startsWith(ARCHIVE_PREFIX)) {
400
591
  dirs.push((await fetchArchiveLayer(spec, opts)).dir);
592
+ } else if (spec.startsWith(KIT_PREFIX)) {
593
+ const { name } = parseKitSpec(spec);
594
+ dirs.push((await resolveKitLayer(name, opts)).dir);
401
595
  } else {
402
596
  const { name, version } = parseRemoteSpec(spec);
403
597
  dirs.push((await pullLayer(name, { ...opts, version })).dir);
@@ -142,6 +142,8 @@ export function layerDirsFromEnv(env = process.env, delimiter = path.delimiter)
142
142
  for (let i = 0; i < parts.length; i++) {
143
143
  if (delimiter === ":" && parts[i] === "nexuscore" && parts[i + 1]) {
144
144
  specs.push(`nexuscore:${parts[++i]}`);
145
+ } else if (delimiter === ":" && parts[i] === "kit" && parts[i + 1]) {
146
+ specs.push(`kit:${parts[++i]}`);
145
147
  } else if (delimiter === ":" && parts[i] === "archive") {
146
148
  // archive:https://host[:port]/file#sha256=... spans several ':' pieces; it ends at the pin.
147
149
  const pieces = [parts[i]];