@zenrick/zenkit 0.5.0 → 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.0",
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",
@@ -0,0 +1,35 @@
1
+ # Archive (not delete) Codex rollout JSONL older than 30 days.
2
+ # Usage: .\scripts\archive-codex-rollouts.ps1 [-CodexHome $env:USERPROFILE\.codex]
3
+ param(
4
+ [string]$CodexHome = $(Join-Path $env:USERPROFILE ".codex"),
5
+ [int]$KeepDays = 30
6
+ )
7
+
8
+ $ErrorActionPreference = "Stop"
9
+ $sessions = Join-Path $CodexHome "sessions"
10
+ $archiveRoot = Join-Path $CodexHome ("archive-rollouts-" + (Get-Date -Format "yyyyMM"))
11
+
12
+ if (-not (Test-Path $sessions)) {
13
+ Write-Host "No sessions dir at $sessions"
14
+ exit 0
15
+ }
16
+
17
+ $cutoff = (Get-Date).AddDays(-$KeepDays)
18
+ $targets = Get-ChildItem -Path $sessions -Recurse -Filter "rollout-*.jsonl" -File -ErrorAction SilentlyContinue |
19
+ Where-Object { $_.LastWriteTime -lt $cutoff }
20
+
21
+ if (-not $targets) {
22
+ Write-Host "Nothing to archive (cutoff $cutoff)."
23
+ exit 0
24
+ }
25
+
26
+ foreach ($file in $targets) {
27
+ $rel = $file.FullName.Substring($sessions.Length).TrimStart('\\', '/')
28
+ $dest = Join-Path $archiveRoot $rel
29
+ $destDir = Split-Path $dest -Parent
30
+ New-Item -ItemType Directory -Force -Path $destDir | Out-Null
31
+ Move-Item -LiteralPath $file.FullName -Destination $dest -Force
32
+ Write-Host "Archived $rel"
33
+ }
34
+
35
+ Write-Host "Archived $($targets.Count) rollout file(s) under $archiveRoot"
@@ -70,14 +70,26 @@ export async function loadBundleFiles() {
70
70
  } catch {
71
71
  throw new Error(`⛔ ${BUNDLES_DIR} não existe — fail-closed.`);
72
72
  }
73
- const files = entries.filter((e) => e.isFile() && e.name.endsWith(".yaml"));
74
- if (files.length === 0) {
73
+ const byName = await readBundleDir(BUNDLES_DIR, entries);
74
+ if (byName.size === 0) {
75
75
  throw new Error("⛔ nenhum bundle em kit/bundles — fail-closed.");
76
76
  }
77
+ return byName;
78
+ }
79
+
80
+ /** Recipes kept in a layer's bundles/ (a paid pack's storefronts); empty when there are none. */
81
+ export async function loadLayerBundles(layerDir) {
82
+ const dir = path.join(layerDir, "bundles");
83
+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
84
+ return readBundleDir(dir, entries);
85
+ }
86
+
87
+ async function readBundleDir(dir, entries) {
88
+ const files = entries.filter((e) => e.isFile() && e.name.endsWith(".yaml"));
77
89
  const byName = new Map();
78
90
  for (const f of files) {
79
91
  const stem = f.name.replace(/\.yaml$/, "");
80
- const raw = await fs.readFile(path.join(BUNDLES_DIR, f.name), "utf8");
92
+ const raw = await fs.readFile(path.join(dir, f.name), "utf8");
81
93
  const data = parseSimpleYaml(raw, f.name);
82
94
  const name = (data.name || "").trim();
83
95
  if (!name) throw new Error(`${f.name}: sem 'name'`);
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
 
@@ -38,7 +39,8 @@ Uso:
38
39
  zenkit layer push DIR
39
40
  zenkit layer pull NOME [--version N] [--into DIR]
40
41
  zenkit layer list
41
- zenkit layer pack DIR --out ARQUIVO
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,10 +50,16 @@ 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).
54
60
  layer pack gera o arquivo de uma camada (recusa segredo) e mostra o sha256.
61
+ Com --bundle, só o que a receita usa da camada (uma vitrine de um pacote pago),
62
+ conferindo o carimbo de validade das skills fiscal e de privacidade.
55
63
 
56
64
  Sem comando: init no diretório atual (Kit Lite).
57
65
  O default copia o recorte para .cursor, .claude e .agents (Codex/Gemini).
@@ -62,6 +70,37 @@ a skill duas vezes.
62
70
 
63
71
  const layerArg = (value) => (isRemoteSpec(value) ? value : path.resolve(value));
64
72
 
73
+ /** `pack DIR --out FILE [--bundle NAME]`; null when the arguments do not fit. */
74
+ function parsePackFlags(args) {
75
+ const [dir, ...flags] = args;
76
+ const parsed = { dir, out: null, bundle: undefined };
77
+ for (let i = 0; i < flags.length; i += 2) {
78
+ if (flags[i] === "--out" && flags[i + 1]) parsed.out = flags[i + 1];
79
+ else if (flags[i] === "--bundle" && flags[i + 1]) parsed.bundle = flags[i + 1];
80
+ else return null;
81
+ }
82
+ return dir && parsed.out ? parsed : null;
83
+ }
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
+
65
104
  export async function runLayer(argv, { env = process.env, fetch, out = process.stdout } = {}) {
66
105
  const [sub, ...rest] = argv;
67
106
  if (sub === "push" && rest.length === 1) {
@@ -86,9 +125,13 @@ export async function runLayer(argv, { env = process.env, fetch, out = process.s
86
125
  out.write(`camada '${name}' v${res.version} em ${res.dir}\n`);
87
126
  return res;
88
127
  }
89
- if (sub === "pack" && rest.length === 3 && rest[1] === "--out") {
90
- const out_ = path.resolve(rest[2]);
91
- const packed = await packLayer(path.resolve(rest[0]), { maxBytes: MAX_ARCHIVE_BYTES });
128
+ const packFlags = sub === "pack" ? parsePackFlags(rest) : null;
129
+ if (packFlags) {
130
+ const out_ = path.resolve(packFlags.out);
131
+ const packed = await packLayer(path.resolve(packFlags.dir), {
132
+ maxBytes: MAX_ARCHIVE_BYTES,
133
+ bundle: packFlags.bundle,
134
+ });
92
135
  await fs.mkdir(path.dirname(out_), { recursive: true });
93
136
  await fs.writeFile(out_, packed.bytes);
94
137
  out.write(
@@ -105,7 +148,7 @@ export async function runLayer(argv, { env = process.env, fetch, out = process.s
105
148
  return layers;
106
149
  }
107
150
  throw new Error(
108
- `uso: zenkit layer push DIR | pull NOME [--version N] [--into DIR] | list | pack DIR --out ARQUIVO\n${USAGE}`,
151
+ `uso: zenkit layer push DIR | pull NOME [--version N] [--into DIR] | list | pack DIR --out ARQUIVO [--bundle RECEITA]\n${USAGE}`,
109
152
  );
110
153
  }
111
154
 
@@ -280,6 +323,10 @@ export async function runCli(argv) {
280
323
  await runLayer(rest);
281
324
  return;
282
325
  }
326
+ if (cmd === "kit") {
327
+ await runKit(rest);
328
+ return;
329
+ }
283
330
  throw new Error(`comando desconhecido: ${cmd}\n${USAGE}`);
284
331
  }
285
332
 
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Content rules that travel with a skill wherever it ships: the public core
3
+ * (checked by doctor) or a paid pack (checked by `zenkit layer pack --bundle`).
4
+ */
5
+
6
+ /** Skills whose output is legal or tax material: they must carry a validity stamp. */
7
+ export const STAMPED = ["negocio-fiscal", "negocio-privacidade"];
8
+ export const STAMP_RE = /legisla[cç][aã]o[^.]{0,80}agosto de 2026/i;
9
+
10
+ /** Problems in a stamped skill's SKILL.md; empty when it is fine. */
11
+ export function stampProblems(name, body) {
12
+ const problems = [];
13
+ if (!STAMP_RE.test(body)) problems.push(`${name} sem carimbo "agosto de 2026"`);
14
+ if (!(/rascunho/i.test(body) && /(contador|advogado)/i.test(body))) {
15
+ problems.push(`${name} não manda validar rascunho com contador/advogado`);
16
+ }
17
+ return problems;
18
+ }
@@ -13,6 +13,7 @@ import { fileURLToPath } from "node:url";
13
13
  import { generateKit, emitPluginPackage } from "./generate.mjs";
14
14
  import { loadBundleFiles, resolveBundle } from "./bundle.mjs";
15
15
  import { applySlots } from "./layers.mjs";
16
+ import { STAMPED, stampProblems } from "./content-checks.mjs";
16
17
  import { expectedMarketplaces, marketplacePaths } from "./marketplace.mjs";
17
18
  import { pluginId } from "./product.mjs";
18
19
  import { spawnSync } from "node:child_process";
@@ -27,8 +28,6 @@ const LITE_FORBIDDEN = [
27
28
  "negocio-agenda",
28
29
  "rust-pro",
29
30
  ];
30
- const STAMPED = ["negocio-fiscal", "negocio-privacidade"];
31
- const STAMP_RE = /legisla[cç][aã]o[^.]{0,80}agosto de 2026/i;
32
31
 
33
32
  let failed = 0;
34
33
 
@@ -525,15 +524,12 @@ async function main() {
525
524
  for (const name of STAMPED) {
526
525
  const file = path.join(ROOT, "kit", "skills", name, "SKILL.md");
527
526
  if (!(await exists(file))) {
528
- warn(`${name} não está no núcleo (camada paga); o carimbo não é conferido por este doctor`);
527
+ warn(`${name} não está no núcleo (camada paga); o carimbo é conferido no zenkit layer pack --bundle`);
529
528
  continue;
530
529
  }
531
- const body = await fs.readFile(file, "utf8");
532
- if (STAMP_RE.test(body)) ok(`carimbo de validade em ${name}`);
533
- else fail(`${name} sem carimbo "agosto de 2026"`);
534
- if (/rascunho/i.test(body) && /(contador|advogado)/i.test(body)) {
535
- ok(`${name} manda validar rascunho`);
536
- } else fail(`${name} não manda validar rascunho com contador/advogado`);
530
+ const problems = stampProblems(name, await fs.readFile(file, "utf8"));
531
+ if (problems.length === 0) ok(`carimbo de validade em ${name} e rascunho a validar`);
532
+ for (const p of problems) fail(p);
537
533
  }
538
534
 
539
535
  // §2c (P0): o encerramento tem de entregar as opções pelo MENU do runtime, não em
@@ -397,21 +397,32 @@ async function dropHomeRootAgents(target) {
397
397
  if (content.includes(GENERATED_MARK)) await fs.rm(rootAgents, { force: true });
398
398
  }
399
399
 
400
+ /**
401
+ * A skill reference the install cannot resolve becomes the plain name: a recipe
402
+ * (kit-lite, kit-engenharia) does not carry every skill the master rule cites,
403
+ * and an agent should not go looking for a skill that is not there. `installed`
404
+ * null means "no filter" (the full kit resolves every reference).
405
+ */
406
+ export function unlinkAbsentSkills(text, installed) {
407
+ if (!installed) return text;
408
+ return text.replace(/@\[skills\/([a-z0-9-]+)\]/g, (ref, name) => (installed.has(name) ? ref : name));
409
+ }
410
+
400
411
  /** Cursor reads ZENKIT.mdc itself: write it with the slots filled, never with the markers. */
401
- async function writeCursorMasterRule(rulesDir, layers = []) {
412
+ async function writeCursorMasterRule(rulesDir, layers = [], installed = null) {
402
413
  const master = await fs.readFile(path.join(KIT, "rules", "ZENKIT.mdc"), "utf8");
403
414
  // Layer sections arrive with their own line endings; keep the file in the kit's one.
404
- const rendered = applySlots(master.replace(/\r\n/g, "\n"), layers);
415
+ const rendered = unlinkAbsentSkills(applySlots(master.replace(/\r\n/g, "\n"), layers), installed);
405
416
  const eol = master.includes("\r\n") ? "\r\n" : "\n";
406
417
  await fs.writeFile(path.join(rulesDir, "ZENKIT.mdc"), rendered.replace(/\n/g, eol));
407
418
  }
408
419
 
409
- async function writeClaudeMd(target, homeDir = os.homedir(), layers = []) {
420
+ async function writeClaudeMd(target, homeDir = os.homedir(), layers = [], installed = null) {
410
421
  const atHome = samePath(target, homeDir);
411
422
  if (atHome) await dropHomeRootAgents(target);
412
423
  const masterPath = path.join(KIT, "rules", "ZENKIT.mdc");
413
424
  const master = await fs.readFile(masterPath, "utf8");
414
- const body = applySlots(splitFrontmatter(master).body, layers);
425
+ const body = unlinkAbsentSkills(applySlots(splitFrontmatter(master).body, layers), installed);
415
426
  await fs.mkdir(path.join(target, ".claude"), { recursive: true });
416
427
  await fs.mkdir(path.join(target, ".codex"), { recursive: true });
417
428
  const rulesetAppend = await readRulesetAppend();
@@ -481,7 +492,7 @@ export async function emitPluginPackage({ dest, bundle }) {
481
492
  for (const layer of ["rules", "workflows", "commands"]) {
482
493
  await copyTree(path.join(KIT, layer), path.join(cursorDest, layer));
483
494
  }
484
- await writeCursorMasterRule(path.join(cursorDest, "rules"));
495
+ await writeCursorMasterRule(path.join(cursorDest, "rules"), [], new Set(meta.skills));
485
496
  // Plugin packages ship the public core only: user layers stay private.
486
497
  const skillSources = await coreSkillSources(meta.skills);
487
498
  const agentSources = await coreAgentSources(meta.agents);
@@ -609,7 +620,8 @@ export async function generateKit({ target, bundle, homeDir, layers }) {
609
620
  await fs.copyFile(src, path.join(target, ".cursor", "rules", `${name}.mdc`));
610
621
  }
611
622
  }
612
- await writeCursorMasterRule(path.join(target, ".cursor", "rules"), loadedLayers);
623
+ const installed = new Set(skillSources.keys());
624
+ await writeCursorMasterRule(path.join(target, ".cursor", "rules"), loadedLayers, installed);
613
625
  await copySelectedSkillDirs(path.join(target, ".cursor", "skills"), skillSources);
614
626
  await emitCursorAgents(target, agentSources);
615
627
 
@@ -617,7 +629,7 @@ export async function generateKit({ target, bundle, homeDir, layers }) {
617
629
  await emitAgentsSkills(target, skillSources);
618
630
  await copySelectedAgents(path.join(target, ".claude", "agents"), agentSources);
619
631
  await copyTree(path.join(KIT, "commands"), path.join(target, ".claude", "commands"));
620
- await writeClaudeMd(target, homeDir, loadedLayers);
632
+ await writeClaudeMd(target, homeDir, loadedLayers, installed);
621
633
 
622
634
  const count = async (p) =>
623
635
  (await fs.readdir(p).catch(() => [])).filter((n) => n !== OWNED_MANIFEST).length;
@@ -16,6 +16,8 @@ import os from "node:os";
16
16
  import path from "node:path";
17
17
  import { gunzipSync, gzipSync } from "node:zlib";
18
18
  import { LAYER_MANIFEST, loadLayer } from "./layers.mjs";
19
+ import { listSkillNames, loadBundleFiles, loadLayerBundles, resolveBundle } from "./bundle.mjs";
20
+ import { STAMPED, stampProblems } from "./content-checks.mjs";
19
21
 
20
22
  export const BUNDLE_FORMAT = "zenkit-layer/1";
21
23
  /** Same cap the NexusCore route enforces (720 KB of bundle bytes). */
@@ -40,12 +42,17 @@ const SECRET_CONTENT = [
40
42
  ];
41
43
 
42
44
  export const ARCHIVE_PREFIX = "archive:";
45
+ export const KIT_PREFIX = "kit:";
46
+ export const DEFAULT_KITS_URL = "https://nexus.zenrick.dev";
43
47
  /** A paid or shared layer file can be bigger than what NexusCore accepts per version. */
44
48
  export const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
45
49
 
46
- /** 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:`. */
47
51
  export function isRemoteSpec(spec) {
48
- 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
+ );
49
56
  }
50
57
 
51
58
  /**
@@ -89,6 +96,32 @@ export function parseRemoteSpec(spec) {
89
96
  return { name, version: version ? Number(version) : undefined };
90
97
  }
91
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
+
92
125
  /** Find secret-looking material; returns `path: motivo` strings, empty when clean. */
93
126
  export function findSecrets(files) {
94
127
  const hits = [];
@@ -118,29 +151,90 @@ async function walk(root, rel, out) {
118
151
  }
119
152
  }
120
153
 
121
- /** Pack a layer directory into the bundle bytes. Refuses secrets and oversize. */
122
- export async function packLayer(dir, { maxBytes = MAX_BUNDLE_BYTES } = {}) {
154
+ /**
155
+ * Pack a layer directory into the bundle bytes. Refuses secrets and oversize.
156
+ * With `bundle`, packs only what that recipe needs from the layer (a storefront
157
+ * cut out of a paid pack): see sliceForBundle.
158
+ */
159
+ export async function packLayer(dir, { maxBytes = MAX_BUNDLE_BYTES, bundle } = {}) {
123
160
  const layer = await loadLayer(dir);
124
- const files = [{ path: LAYER_MANIFEST, data: await fs.readFile(path.join(layer.dir, LAYER_MANIFEST)) }];
125
- for (const sub of SUBTREES) await walk(layer.dir, sub, files);
161
+ const { name, files } = bundle ? await sliceForBundle(layer, bundle) : await wholeLayer(layer);
126
162
 
127
163
  const secrets = findSecrets(files);
128
164
  if (secrets.length) {
129
165
  throw new Error(
130
- `camada '${layer.name}' parece conter segredo; nada foi enviado:\n ${secrets.join("\n ")}\n` +
166
+ `camada '${name}' parece conter segredo; nada foi enviado:\n ${secrets.join("\n ")}\n` +
131
167
  "Segredo fica no ambiente (liste o nome em 'secrets:' no manifesto), nunca na camada.",
132
168
  );
133
169
  }
134
170
  const json = JSON.stringify({
135
171
  format: BUNDLE_FORMAT,
136
- name: layer.name,
172
+ name,
137
173
  files: files.map((f) => ({ path: f.path, data: f.data.toString("base64") })),
138
174
  });
139
175
  const bytes = gzipSync(Buffer.from(json, "utf8"), { level: 9 });
140
176
  if (bytes.length > maxBytes) {
141
- throw new Error(`camada '${layer.name}' tem ${bytes.length} bytes compactada; o máximo é ${maxBytes}`);
177
+ throw new Error(`camada '${name}' tem ${bytes.length} bytes compactada; o máximo é ${maxBytes}`);
142
178
  }
143
- return { name: layer.name, bytes, sha256: sha256(bytes), files: files.length };
179
+ return { name, bytes, sha256: sha256(bytes), files: files.length };
180
+ }
181
+
182
+ async function wholeLayer(layer) {
183
+ const files = [{ path: LAYER_MANIFEST, data: await fs.readFile(path.join(layer.dir, LAYER_MANIFEST)) }];
184
+ for (const sub of SUBTREES) await walk(layer.dir, sub, files);
185
+ return { name: layer.name, files };
186
+ }
187
+
188
+ const SKILL_REF = /@\[skills\/([a-z0-9-]+)\]/g;
189
+
190
+ /** Drop the lines of a section that point at a skill the buyer will not have. */
191
+ export function dropLinesCitingAbsent(text, available) {
192
+ return text
193
+ .split("\n")
194
+ .filter((line) => [...line.matchAll(SKILL_REF)].every((m) => available.has(m[1])))
195
+ .join("\n");
196
+ }
197
+
198
+ /**
199
+ * A storefront cut out of a layer. The recipe resolves against the core's and
200
+ * the layer's bundles; the pack carries only the layer skills (and agents) the
201
+ * recipe uses, since the core ones the buyer already has. Sections keep only
202
+ * lines whose skill references the buyer will have. Stamped skills must pass
203
+ * their content check, or nothing is packed.
204
+ */
205
+ async function sliceForBundle(layer, bundleName) {
206
+ const core = await loadBundleFiles();
207
+ const own = await loadLayerBundles(layer.dir);
208
+ const clash = [...own.keys()].filter((n) => core.has(n));
209
+ if (clash.length) throw new Error(`receita na camada com o nome de uma do núcleo: ${clash.join(", ")}`);
210
+ const recipe = resolveBundle(bundleName, new Map([...core, ...own]));
211
+
212
+ const coreSkills = new Set(await listSkillNames());
213
+ const keep = [...recipe.skills].filter((s) => layer.skills.has(s)).sort();
214
+ const absent = [...recipe.skills].filter((s) => !layer.skills.has(s) && !coreSkills.has(s));
215
+ if (absent.length) throw new Error(`receita '${bundleName}' cita skill que não existe no núcleo nem na camada: ${absent.join(", ")}`);
216
+ if (keep.length === 0) throw new Error(`receita '${bundleName}' não usa nenhuma skill da camada '${layer.name}'`);
217
+
218
+ const problems = [];
219
+ for (const s of keep.filter((s) => STAMPED.includes(s))) {
220
+ problems.push(...stampProblems(s, await fs.readFile(path.join(layer.skills.get(s), "SKILL.md"), "utf8")));
221
+ }
222
+ if (problems.length) throw new Error(`receita '${bundleName}' não empacotada:\n ${problems.join("\n ")}`);
223
+
224
+ const overrides = keep.filter((s) => coreSkills.has(s));
225
+ const manifest =
226
+ `name: ${bundleName}\n` + (overrides.length ? `override:\n${overrides.map((s) => ` - ${s}\n`).join("")}` : "");
227
+ const files = [{ path: LAYER_MANIFEST, data: Buffer.from(manifest, "utf8") }];
228
+ for (const s of keep) await walk(layer.dir, `skills/${s}`, files);
229
+ for (const a of [...recipe.agents].filter((a) => layer.agents.has(a)).sort()) {
230
+ files.push({ path: `agents/${a}.md`, data: await fs.readFile(layer.agents.get(a)) });
231
+ }
232
+ const available = new Set([...keep, ...coreSkills]);
233
+ for (const [id, text] of layer.sections) {
234
+ const kept = dropLinesCitingAbsent(text, available);
235
+ if (kept.trim()) files.push({ path: `sections/${id}.md`, data: Buffer.from(kept, "utf8") });
236
+ }
237
+ return { name: bundleName, files };
144
238
  }
145
239
 
146
240
  function safeRel(rel) {
@@ -297,6 +391,166 @@ async function archiveToken(env) {
297
391
  return "";
298
392
  }
299
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
+
300
554
  /**
301
555
  * Download an `archive:` layer, check its sha256 against the pin and unpack it
302
556
  * under the cache, keyed by that hash. A hash already in the cache is used
@@ -335,6 +589,9 @@ export async function resolveLayerSpecs(specs, opts = {}) {
335
589
  dirs.push(spec);
336
590
  } else if (spec.startsWith(ARCHIVE_PREFIX)) {
337
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);
338
595
  } else {
339
596
  const { name, version } = parseRemoteSpec(spec);
340
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]];