@verentis/cli 0.2.31 → 0.2.32

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/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import * as tar from 'tar';
9
9
  import { extract } from 'tar';
10
10
  import { generateKeyPairSync, createHash, randomUUID, randomBytes, createCipheriv, createPublicKey, verify, diffieHellman, hkdfSync, sign, createPrivateKey } from 'crypto';
11
11
  import { parse, parseDocument, isScalar, stringify, Document, YAMLMap, Scalar } from 'yaml';
12
+ import semver from 'semver';
12
13
  import { createWriteStream, readFileSync, createReadStream } from 'fs';
13
14
  import { Readable } from 'stream';
14
15
  import { pipeline } from 'stream/promises';
@@ -140,7 +141,7 @@ async function refreshIdentityToken(apiUrl, refreshToken, insecure) {
140
141
  `Session could not be renewed${payload?.error ? ` (${payload.error})` : ` (${res.status})`}. Run \`verentis login\` again.`
141
142
  );
142
143
  }
143
- var sleep = (ms) => new Promise((resolve15) => setTimeout(resolve15, ms));
144
+ var sleep = (ms) => new Promise((resolve16) => setTimeout(resolve16, ms));
144
145
 
145
146
  // src/auth/githubActions.ts
146
147
  var JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
@@ -1041,21 +1042,717 @@ function contextEnv(context, contextPath) {
1041
1042
  VERENTIS_TIMEOUT: String(context.execution.timeout)
1042
1043
  };
1043
1044
  }
1044
- var KIND_MAP = {
1045
- application: "Application",
1046
- executionengine: "ExecutionEngine",
1047
- agent: "Agent",
1048
- skill: "Skill",
1049
- tool: "Tool",
1050
- bundle: "Bundle"
1045
+
1046
+ // src/vpkg/package-types.json
1047
+ var package_types_default = {
1048
+ $schema: "./package-types.schema.json",
1049
+ version: 1,
1050
+ profiles: {
1051
+ application: "Launchable application: entry points, scopes/consent, optional hosted backend, Resource registration.",
1052
+ engine: "Execution engine that applications declare as a required runtime.",
1053
+ content: "Files placed into the workspace via spec.install; no launch, no hosted backend, no consent."
1054
+ },
1055
+ types: [
1056
+ {
1057
+ type: "Application",
1058
+ aliases: ["app"],
1059
+ profile: "application",
1060
+ label: "App",
1061
+ plural: "Apps",
1062
+ description: "Applications that open in your workspace.",
1063
+ icon: "app-window",
1064
+ accent: "primary",
1065
+ mediaSlug: "application",
1066
+ sealedMediaSlug: "application",
1067
+ resourceKind: "Application",
1068
+ installRoot: "applications/{name}",
1069
+ installRootFromManifest: true,
1070
+ order: 10
1071
+ },
1072
+ {
1073
+ type: "ExecutionEngine",
1074
+ aliases: ["engine"],
1075
+ profile: "engine",
1076
+ label: "Engine",
1077
+ plural: "Engines",
1078
+ description: "Runtimes that power applications.",
1079
+ icon: "cpu",
1080
+ accent: "engine",
1081
+ mediaSlug: "engine",
1082
+ sealedMediaSlug: "execution-engine",
1083
+ resourceKind: "ExecutionEngine",
1084
+ installRoot: "applications/{name}",
1085
+ order: 20
1086
+ },
1087
+ {
1088
+ type: "Agent",
1089
+ profile: "content",
1090
+ label: "Agent",
1091
+ plural: "Agents",
1092
+ description: "AI agents that work alongside you.",
1093
+ icon: "bot",
1094
+ accent: "agent",
1095
+ mediaSlug: "agent",
1096
+ sealedMediaSlug: "agent",
1097
+ resourceKind: "Agent",
1098
+ order: 30
1099
+ },
1100
+ {
1101
+ type: "Skill",
1102
+ profile: "content",
1103
+ label: "Skill",
1104
+ plural: "Skills",
1105
+ description: "Reusable skills agents can load.",
1106
+ icon: "sparkles",
1107
+ accent: "skill",
1108
+ mediaSlug: "skill",
1109
+ sealedMediaSlug: "skill",
1110
+ resourceKind: "Skill",
1111
+ order: 40
1112
+ },
1113
+ {
1114
+ type: "Tool",
1115
+ profile: "content",
1116
+ label: "Tool",
1117
+ plural: "Tools",
1118
+ description: "Tools agents and apps can call.",
1119
+ icon: "wrench",
1120
+ accent: "tool",
1121
+ mediaSlug: "tool",
1122
+ sealedMediaSlug: "tool",
1123
+ resourceKind: "Tool",
1124
+ order: 50
1125
+ },
1126
+ {
1127
+ type: "Bundle",
1128
+ profile: "content",
1129
+ label: "Bundle",
1130
+ plural: "Bundles",
1131
+ description: "Curated sets of files, templates and packages.",
1132
+ icon: "package",
1133
+ accent: "bundle",
1134
+ mediaSlug: "bundle",
1135
+ sealedMediaSlug: "bundle",
1136
+ resourceKind: "Custom",
1137
+ order: 60
1138
+ },
1139
+ {
1140
+ type: "Theme",
1141
+ profile: "content",
1142
+ label: "Theme",
1143
+ plural: "Themes",
1144
+ description: "Branding for your workspace: colours, logos and backgrounds.",
1145
+ icon: "palette",
1146
+ accent: "theme",
1147
+ mediaSlug: "theme",
1148
+ sealedMediaSlug: "theme",
1149
+ installRoot: "themes/{name}",
1150
+ exclusiveSlot: "workspace-theme",
1151
+ forceBranch: "main",
1152
+ forceMode: "Extracted",
1153
+ validator: "theme",
1154
+ protectedRoots: [".theme"],
1155
+ hooks: { onUninstall: "workspace.theme.restore-defaults" },
1156
+ forbiddenSpecFields: ["entry", "entry-points", "scopes", "permissions", "settings", "dependencies", "scripts", "engine", "launch", "install-root"],
1157
+ order: 70
1158
+ }
1159
+ ]
1160
+ };
1161
+
1162
+ // src/vpkg/package-types.ts
1163
+ var PACKAGE_PROFILES = ["application", "engine", "content"];
1164
+ function normalizePackageTypeKey(value) {
1165
+ return value.replace(/[^\p{L}\p{N}]/gu, "").toLowerCase();
1166
+ }
1167
+ var PackageTypeRegistry = class {
1168
+ version;
1169
+ types;
1170
+ byKey = /* @__PURE__ */ new Map();
1171
+ constructor(document) {
1172
+ this.version = document.version ?? 1;
1173
+ this.types = [...document.types].sort((a, b) => (a.order ?? 0) - (b.order ?? 0) || (a.type < b.type ? -1 : a.type > b.type ? 1 : 0));
1174
+ for (const descriptor of this.types) {
1175
+ if (!PACKAGE_PROFILES.includes(descriptor.profile)) {
1176
+ throw new Error(`Package type '${descriptor.type}' has unknown profile '${String(descriptor.profile)}'.`);
1177
+ }
1178
+ for (const key of [descriptor.type, ...descriptor.aliases ?? []]) {
1179
+ const normalized = normalizePackageTypeKey(key);
1180
+ const existing = this.byKey.get(normalized);
1181
+ if (existing && existing !== descriptor) {
1182
+ throw new Error(`Package type key '${normalized}' is declared by both '${existing.type}' and '${descriptor.type}'.`);
1183
+ }
1184
+ this.byKey.set(normalized, descriptor);
1185
+ }
1186
+ }
1187
+ }
1188
+ find(type) {
1189
+ if (typeof type !== "string" || type.trim().length === 0) return void 0;
1190
+ return this.byKey.get(normalizePackageTypeKey(type));
1191
+ }
1192
+ get(type) {
1193
+ const descriptor = this.find(type);
1194
+ if (!descriptor) throw new Error(unknownPackageTypeMessage(type, this));
1195
+ return descriptor;
1196
+ }
1197
+ canonical(type) {
1198
+ return this.find(type)?.type;
1199
+ }
1200
+ typeNames() {
1201
+ return this.types.map((t) => t.type);
1202
+ }
1203
+ };
1204
+ function unknownPackageTypeMessage(type, registry = packageTypes()) {
1205
+ return `Unsupported manifest kind '${String(type)}' \u2014 expected one of: ${registry.typeNames().join(", ")}.`;
1206
+ }
1207
+ var BUNDLED_PACKAGE_TYPES = package_types_default;
1208
+ var current;
1209
+ var cachePath = () => join(configDir(), "package-types.json");
1210
+ function mergeDocuments(bundled, fetched) {
1211
+ if (!fetched || !Array.isArray(fetched.types) || (fetched.version ?? 1) < (bundled.version ?? 1)) return bundled;
1212
+ const keys = new Set(fetched.types.map((t) => normalizePackageTypeKey(t.type)));
1213
+ return {
1214
+ version: fetched.version,
1215
+ profiles: { ...bundled.profiles, ...fetched.profiles },
1216
+ types: [...fetched.types, ...bundled.types.filter((t) => !keys.has(normalizePackageTypeKey(t.type)))]
1217
+ };
1218
+ }
1219
+ function buildRegistry(fetched) {
1220
+ try {
1221
+ return new PackageTypeRegistry(mergeDocuments(BUNDLED_PACKAGE_TYPES, fetched));
1222
+ } catch {
1223
+ return new PackageTypeRegistry(BUNDLED_PACKAGE_TYPES);
1224
+ }
1225
+ }
1226
+ function readCache() {
1227
+ if (process.env.VERENTIS_PACKAGE_TYPES_CACHE === "0") return void 0;
1228
+ try {
1229
+ return JSON.parse(readFileSync(cachePath(), "utf8"));
1230
+ } catch {
1231
+ return void 0;
1232
+ }
1233
+ }
1234
+ function packageTypes() {
1235
+ current ??= buildRegistry(readCache());
1236
+ return current;
1237
+ }
1238
+ var findPackageType = (type) => packageTypes().find(type);
1239
+ var canonicalPackageType = (type) => packageTypes().canonical(type);
1240
+ var packageTypeProfile = (type) => packageTypes().find(type)?.profile;
1241
+ var isApplicationProfile = (type) => packageTypeProfile(type) === "application";
1242
+ async function refreshPackageTypes(apiUrl, options = {}) {
1243
+ if (process.env.VERENTIS_PACKAGE_TYPES_CACHE === "0") return false;
1244
+ try {
1245
+ const response = await (options.fetchImpl ?? fetch)(`${apiUrl.replace(/\/+$/, "")}/v1/package-types`, {
1246
+ headers: { accept: "application/json" },
1247
+ signal: AbortSignal.timeout(options.timeoutMs ?? 3e3),
1248
+ ...insecureFetchOptions(options.insecure)
1249
+ });
1250
+ if (!response.ok) return false;
1251
+ const text = await response.text();
1252
+ const document = JSON.parse(text);
1253
+ new PackageTypeRegistry(document);
1254
+ if (!Array.isArray(document.types) || document.types.length === 0) return false;
1255
+ current = buildRegistry(document);
1256
+ await mkdir(configDir(), { recursive: true, mode: 448 }).catch(() => void 0);
1257
+ await writeFile(cachePath(), text).catch(() => void 0);
1258
+ return true;
1259
+ } catch {
1260
+ return false;
1261
+ }
1262
+ }
1263
+ async function ensurePackageTypeKnown(type) {
1264
+ if (!type || findPackageType(type)) return;
1265
+ const config = await loadConfig();
1266
+ await refreshPackageTypes(requireApiUrl(config), { insecure: config.insecure });
1267
+ }
1268
+ var MAX_ICON_BYTES = 32 * 1024;
1269
+ var MAX_TOTAL_ICON_BYTES = 256 * 1024;
1270
+ var LEGACY_ICON_PATTERN = /^[a-z0-9-]+(:[a-z0-9-]+)?$/;
1271
+ var SVG_START = /^(?:<\?xml[\s\S]*?\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg\b/i;
1272
+ var SVG_END_CLOSING = /<\/svg>\s*$/i;
1273
+ var SVG_END_SELF_CLOSING = /<svg\b[\s\S]*\/>\s*$/i;
1274
+ var SVG_REJECTIONS = [
1275
+ [/&#/i, "numeric character references (&#) are not allowed"],
1276
+ [/<!DOCTYPE|<!ENTITY/i, "<!DOCTYPE>/<!ENTITY> declarations are not allowed"],
1277
+ [/<(?:script|foreignObject|iframe|object|embed|audio|video)\b/i, "script, foreignObject, iframe, object, embed, audio and video elements are not allowed"],
1278
+ [/\son[a-z]+\s*=/i, "event handler (on*=) attributes are not allowed"],
1279
+ [/(?:javascript|vbscript)\s*:/i, "javascript:/vbscript: URLs are not allowed"],
1280
+ [/data\s*:\s*text\/html/i, "data:text/html URLs are not allowed"],
1281
+ [/(?:xlink:href|href)\s*=\s*["']?\s*(?:https?:|ftp:|\/\/)/i, "external href/xlink:href references are not allowed"],
1282
+ [/url\(\s*["']?\s*(?:https?:|\/\/)/i, "external url(...) references are not allowed"]
1283
+ ];
1284
+ function validateSvgIcon(text) {
1285
+ if (Buffer.byteLength(text, "utf8") > MAX_ICON_BYTES) return `SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit`;
1286
+ return validateSvgMarkup(text);
1287
+ }
1288
+ function validateSvgMarkup(text) {
1289
+ const markup = canonicalizeSvg(text);
1290
+ if (!SVG_START.test(markup)) return "SVG must have an <svg> root element (only an <?xml ?> declaration and comments may precede it)";
1291
+ if (!SVG_END_CLOSING.test(markup) && !SVG_END_SELF_CLOSING.test(markup)) return "SVG must end with </svg>";
1292
+ for (const [pattern, reason] of SVG_REJECTIONS) {
1293
+ if (pattern.test(markup)) return reason;
1294
+ }
1295
+ return null;
1296
+ }
1297
+ function canonicalizeSvg(text) {
1298
+ return text.replace(/^\uFEFF+/, "").trim();
1299
+ }
1300
+ function decodeUtf8(bytes) {
1301
+ try {
1302
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1303
+ } catch {
1304
+ return null;
1305
+ }
1306
+ }
1307
+ function classifyIconValue(value) {
1308
+ const trimmed = value.trim();
1309
+ if (trimmed.startsWith("<")) return "inline";
1310
+ if (trimmed.startsWith("#")) return "ref";
1311
+ if (/\.svg$/i.test(trimmed)) return "path";
1312
+ if (LEGACY_ICON_PATTERN.test(trimmed)) return "legacy";
1313
+ return "invalid";
1314
+ }
1315
+ function collectIconFields(manifest) {
1316
+ const fields = [];
1317
+ if (!isRecord(manifest)) return fields;
1318
+ const add = (path, value) => {
1319
+ if (value !== void 0) fields.push({ path, label: formatPath(path), value });
1320
+ };
1321
+ const bindings = (container, path) => {
1322
+ if (!Array.isArray(container)) return;
1323
+ container.forEach((item, index) => {
1324
+ if (isRecord(item)) add([...path, index, "icon"], item.icon);
1325
+ });
1326
+ };
1327
+ if (isRecord(manifest.metadata)) add(["metadata", "icon"], manifest.metadata.icon);
1328
+ const spec = manifest.spec;
1329
+ if (!isRecord(spec)) return fields;
1330
+ if (Array.isArray(spec["entry-points"])) {
1331
+ spec["entry-points"].forEach((entryPoint, index) => {
1332
+ if (!isRecord(entryPoint)) return;
1333
+ add(["spec", "entry-points", index, "icon"], entryPoint.icon);
1334
+ bindings(entryPoint["mime-types"], ["spec", "entry-points", index, "mime-types"]);
1335
+ });
1336
+ }
1337
+ bindings(spec["mime-types"], ["spec", "mime-types"]);
1338
+ bindings(spec["file-types"], ["spec", "file-types"]);
1339
+ return fields;
1340
+ }
1341
+ async function resolveManifestIcons(manifest, manifestDir) {
1342
+ const errors = [];
1343
+ const warnings = [];
1344
+ const fields = [];
1345
+ const root = resolve(manifestDir);
1346
+ const distinct = /* @__PURE__ */ new Set();
1347
+ const resolveSvg = async (label, value, allowLegacy) => {
1348
+ const kind = classifyIconValue(value);
1349
+ if (kind === "inline") return checkMarkup(label, value.trim(), "inline SVG");
1350
+ if (kind === "path") {
1351
+ const loaded = await readIconFile(root, value.trim());
1352
+ if ("error" in loaded) {
1353
+ errors.push(`${label}: ${loaded.error}`);
1354
+ return void 0;
1355
+ }
1356
+ return checkMarkup(label, loaded.text, value.trim());
1357
+ }
1358
+ if (kind === "legacy" && allowLegacy) return void 0;
1359
+ errors.push(allowLegacy ? `${label}: '${value}' is not a relative .svg path, "#key" reference, inline <svg> markup or Iconify id` : `${label}: '${value}' must be a relative .svg path or inline <svg> markup`);
1360
+ return void 0;
1361
+ };
1362
+ const checkMarkup = (label, text, source) => {
1363
+ const problem = validateSvgIcon(text);
1364
+ if (problem) {
1365
+ errors.push(`${label}: ${source}: ${problem}`);
1366
+ return void 0;
1367
+ }
1368
+ const markup = canonicalizeSvg(text);
1369
+ distinct.add(markup);
1370
+ return markup;
1371
+ };
1372
+ const map = /* @__PURE__ */ new Map();
1373
+ const iconsSection = isRecord(manifest) ? manifest.icons : void 0;
1374
+ if (iconsSection !== void 0) {
1375
+ if (!isRecord(iconsSection)) {
1376
+ errors.push("icons must be a map of key -> SVG file path or inline <svg> markup");
1377
+ } else {
1378
+ for (const [key, value] of Object.entries(iconsSection)) {
1379
+ const label = `icons.${key}`;
1380
+ if (typeof value !== "string" || value.trim().length === 0) {
1381
+ errors.push(`${label} must be a non-empty string`);
1382
+ map.set(key, void 0);
1383
+ continue;
1384
+ }
1385
+ map.set(key, await resolveSvg(label, value, false));
1386
+ }
1387
+ }
1388
+ }
1389
+ for (const field of collectIconFields(manifest)) {
1390
+ if (typeof field.value !== "string" || field.value.trim().length === 0) {
1391
+ errors.push(`${field.label} must be a non-empty string`);
1392
+ continue;
1393
+ }
1394
+ const value = field.value;
1395
+ const kind = classifyIconValue(value);
1396
+ if (kind === "legacy") {
1397
+ warnings.push(`${field.label}: '${value}' is a legacy Iconify icon; run \`verentis icons migrate\` to convert it to SVG`);
1398
+ fields.push({ ...field, value, legacy: true });
1399
+ continue;
1400
+ }
1401
+ if (kind === "ref") {
1402
+ const key = value.trim().slice(1);
1403
+ if (!map.has(key)) {
1404
+ errors.push(`${field.label}: ${value.trim()} does not match a key in the top-level icons map`);
1405
+ continue;
1406
+ }
1407
+ const markup2 = map.get(key);
1408
+ if (markup2 !== void 0) fields.push({ ...field, value, markup: markup2, legacy: false });
1409
+ continue;
1410
+ }
1411
+ const markup = await resolveSvg(field.label, value, true);
1412
+ if (markup !== void 0) fields.push({ ...field, value, markup, legacy: false });
1413
+ }
1414
+ let logoIcon;
1415
+ const metadata = isRecord(manifest) && isRecord(manifest.metadata) ? manifest.metadata : void 0;
1416
+ const marketplace2 = isRecord(manifest) && isRecord(manifest.marketplace) ? manifest.marketplace : void 0;
1417
+ if (metadata && metadata.icon === void 0 && typeof marketplace2?.logo === "string" && /\.svg$/i.test(marketplace2.logo.trim())) {
1418
+ const loaded = await readIconFile(root, marketplace2.logo.trim());
1419
+ const problem = "error" in loaded ? loaded.error : validateSvgIcon(loaded.text);
1420
+ if (problem || "error" in loaded) {
1421
+ warnings.push(`marketplace.logo cannot be used as the app icon (metadata.icon fallback): ${problem}`);
1422
+ } else {
1423
+ logoIcon = canonicalizeSvg(loaded.text);
1424
+ distinct.add(logoIcon);
1425
+ }
1426
+ }
1427
+ const total = [...distinct].reduce((sum, markup) => sum + Buffer.byteLength(markup, "utf8"), 0);
1428
+ if (total > MAX_TOTAL_ICON_BYTES) {
1429
+ errors.push(`icons: total distinct SVG markup is ${(total / 1024).toFixed(1)} KiB, exceeding the ${MAX_TOTAL_ICON_BYTES / 1024} KiB per-manifest limit`);
1430
+ }
1431
+ const needsInlining = logoIcon !== void 0 || iconsSection !== void 0 || fields.some((field) => !field.legacy);
1432
+ return { errors, warnings, fields, logoIcon, needsInlining };
1433
+ }
1434
+ async function readIconFile(root, source) {
1435
+ if (isAbsolute(source) || /^[a-z][a-z0-9+.-]*:/i.test(source) || source.includes("\\")) {
1436
+ return { error: `${source} must be a path relative to the manifest directory` };
1437
+ }
1438
+ const candidate = resolve(root, source);
1439
+ if (escapes(root, candidate)) return { error: `${source} escapes the package directory` };
1440
+ let actual;
1441
+ let realRoot;
1442
+ try {
1443
+ actual = await realpath(candidate);
1444
+ realRoot = await realpath(root);
1445
+ } catch {
1446
+ return { error: `${source} not found` };
1447
+ }
1448
+ if (escapes(realRoot, actual)) return { error: `${source} escapes the package directory` };
1449
+ let bytes;
1450
+ try {
1451
+ bytes = await readFile(actual);
1452
+ } catch {
1453
+ return { error: `${source} could not be read (is it a file?)` };
1454
+ }
1455
+ if (bytes.length > MAX_ICON_BYTES) return { error: `${source}: SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit` };
1456
+ const text = decodeUtf8(bytes);
1457
+ if (text === null) return { error: `${source} is not valid UTF-8` };
1458
+ return { text };
1459
+ }
1460
+ function escapes(root, candidate) {
1461
+ const fromRoot = relative(root, candidate);
1462
+ return fromRoot === "" || fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot);
1463
+ }
1464
+ function iconKey(markup) {
1465
+ return createHash("sha256").update(markup, "utf8").digest("hex").slice(0, 12);
1466
+ }
1467
+ function inlineIconsIntoDocument(document, resolution) {
1468
+ const icons = /* @__PURE__ */ new Map();
1469
+ const quoted = (text) => Object.assign(new Scalar(text), { type: Scalar.QUOTE_DOUBLE });
1470
+ for (const field of resolution.fields) {
1471
+ if (field.markup === void 0) continue;
1472
+ const key = iconKey(field.markup);
1473
+ icons.set(key, field.markup);
1474
+ document.setIn(field.path, quoted(`#${key}`));
1475
+ }
1476
+ if (resolution.logoIcon !== void 0) {
1477
+ const key = iconKey(resolution.logoIcon);
1478
+ icons.set(key, resolution.logoIcon);
1479
+ document.setIn(["metadata", "icon"], quoted(`#${key}`));
1480
+ }
1481
+ if (icons.size === 0) {
1482
+ if (document.has("icons")) document.delete("icons");
1483
+ return;
1484
+ }
1485
+ const node = new YAMLMap();
1486
+ for (const [key, markup] of [...icons.entries()].sort(([a], [b]) => a.localeCompare(b))) {
1487
+ node.set(key, Object.assign(new Scalar(markup), { type: Scalar.BLOCK_LITERAL }));
1488
+ }
1489
+ document.set("icons", node);
1490
+ }
1491
+ function formatPath(path) {
1492
+ return path.reduce((text, segment) => typeof segment === "number" ? `${text}[${segment}]` : text ? `${text}.${segment}` : segment, "");
1493
+ }
1494
+ function isRecord(value) {
1495
+ return !!value && typeof value === "object" && !Array.isArray(value);
1496
+ }
1497
+
1498
+ // src/vpkg/validators/theme.ts
1499
+ var THEME_ROOT = "/.theme";
1500
+ var THEME_ASSET_NAMES = [
1501
+ "theme.css",
1502
+ "background",
1503
+ "background.dark",
1504
+ "logo.light",
1505
+ "logo.dark",
1506
+ "mark.light",
1507
+ "mark.dark",
1508
+ "favicon",
1509
+ "apple-touch-icon"
1510
+ ];
1511
+ var THEME_LIMITS = {
1512
+ css: 64 * 1024,
1513
+ image: 1024 * 1024,
1514
+ background: 2 * 1024 * 1024,
1515
+ total: 4 * 1024 * 1024
1516
+ };
1517
+ var IMAGE_MIME_BY_EXTENSION = {
1518
+ svg: "image/svg+xml",
1519
+ png: "image/png",
1520
+ jpg: "image/jpeg",
1521
+ jpeg: "image/jpeg",
1522
+ webp: "image/webp"
1523
+ };
1524
+ var isAssetName = (name) => THEME_ASSET_NAMES.includes(name);
1525
+ var isRecord2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1526
+ function themeAssetMime(name, path) {
1527
+ const extension = /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase();
1528
+ if (!extension) return void 0;
1529
+ if (name === "theme.css") return extension === "css" ? "text/css" : void 0;
1530
+ return IMAGE_MIME_BY_EXTENSION[extension];
1531
+ }
1532
+ function normalizePayloadPath(path) {
1533
+ return path.trim().replace(/^\.\//, "");
1534
+ }
1535
+ function declaredAssets(spec) {
1536
+ return isRecord2(spec) && isRecord2(spec.assets) ? Object.entries(spec.assets) : [];
1537
+ }
1538
+ function validateThemeManifest(manifest) {
1539
+ const spec = isRecord2(manifest.spec) ? manifest.spec : {};
1540
+ const errors = [];
1541
+ if (!isRecord2(spec.assets) || Object.keys(spec.assets).length === 0) {
1542
+ errors.push(`spec.assets must map theme asset names (${THEME_ASSET_NAMES.join(", ")}) to payload paths.`);
1543
+ } else {
1544
+ for (const [name, value] of Object.entries(spec.assets)) {
1545
+ const at = `spec.assets.${name}`;
1546
+ if (!isAssetName(name)) {
1547
+ errors.push(`${at} is not a theme asset \u2014 allowed: ${THEME_ASSET_NAMES.join(", ")}.`);
1548
+ continue;
1549
+ }
1550
+ if (typeof value !== "string" || value.trim().length === 0) {
1551
+ errors.push(`${at} must be a non-empty relative payload path.`);
1552
+ continue;
1553
+ }
1554
+ const path = normalizePayloadPath(value);
1555
+ if (path.startsWith("/") || path.split("/").includes("..") || path.includes("\\")) {
1556
+ errors.push(`${at} must be a relative path inside the package (no leading '/' or '..').`);
1557
+ continue;
1558
+ }
1559
+ if (name === "apple-touch-icon" && !/\.png$/i.test(path)) {
1560
+ errors.push(`${at} must be a PNG image.`);
1561
+ } else if (!themeAssetMime(name, path)) {
1562
+ errors.push(name === "theme.css" ? `${at} must be a .css file.` : `${at} must be a .png, .jpg, .jpeg, .webp or .svg image.`);
1563
+ }
1564
+ }
1565
+ }
1566
+ if (spec.install !== void 0) {
1567
+ if (!Array.isArray(spec.install)) {
1568
+ errors.push("spec.install must be a list; theme packages should declare spec.assets instead.");
1569
+ } else {
1570
+ const declared = new Set(declaredAssets(spec).map(([name]) => name));
1571
+ spec.install.forEach((directive, index) => {
1572
+ const to = isRecord2(directive) ? directive.to : void 0;
1573
+ const asset = typeof to === "string" && to.startsWith(`${THEME_ROOT}/`) ? to.slice(THEME_ROOT.length + 1) : void 0;
1574
+ if (!asset || !isAssetName(asset)) {
1575
+ errors.push(`spec.install[${index}] must target ${THEME_ROOT}/<asset>; theme packages only install theme assets (declare them in spec.assets).`);
1576
+ } else if (declared.has(asset)) {
1577
+ errors.push(`spec.install[${index}] duplicates spec.assets.${asset}.`);
1578
+ } else if (isRecord2(directive) && directive.mode !== void 0 && directive.mode !== "managed") {
1579
+ errors.push(`spec.install[${index}].mode must be managed for theme assets.`);
1580
+ }
1581
+ });
1582
+ }
1583
+ }
1584
+ if (isRecord2(manifest.packaging) && manifest.packaging.encryption === "required") {
1585
+ errors.push("packaging.encryption: required is not supported for theme packages \u2014 theme assets are public.");
1586
+ }
1587
+ return errors;
1588
+ }
1589
+ function expandThemeManifest(manifest) {
1590
+ const assets = declaredAssets(manifest.spec);
1591
+ if (assets.length === 0) return manifest;
1592
+ const spec = manifest.spec;
1593
+ const existing = Array.isArray(spec.install) ? spec.install : [];
1594
+ const install = [
1595
+ ...existing,
1596
+ ...assets.map(([name, value]) => {
1597
+ const from = normalizePayloadPath(String(value));
1598
+ return { from, to: `${THEME_ROOT}/${name}`, mode: "managed", mime: themeAssetMime(name, from) };
1599
+ })
1600
+ ];
1601
+ return { ...manifest, spec: { ...spec, install } };
1602
+ }
1603
+ var SIGNATURES = {
1604
+ "image/png": (b) => b.length >= 8 && b.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),
1605
+ "image/jpeg": (b) => b.length >= 3 && b[0] === 255 && b[1] === 216 && b[2] === 255,
1606
+ "image/webp": (b) => b.length >= 12 && b.subarray(0, 4).toString("latin1") === "RIFF" && b.subarray(8, 12).toString("latin1") === "WEBP"
1607
+ };
1608
+ var CSS_URL = /url\(\s*(?:"([^"]*)"?|'([^']*)'?|([^)]*))\s*\)?/gi;
1609
+ var CSS_STRING_URL_FUNCTION = /\b(?:-webkit-)?(?:image-set|src|image|cross-fade)\s*\(/i;
1610
+ function lintThemeCss(text) {
1611
+ const errors = [];
1612
+ const css = text.replace(/\/\*[\s\S]*?\*\//g, "");
1613
+ if (css.includes("\\")) errors.push("theme.css must not use CSS escape sequences (\\).");
1614
+ if (/@import\b/i.test(css)) errors.push("theme.css must not use @import.");
1615
+ if (/expression\s*\(/i.test(css)) errors.push("theme.css must not use expression().");
1616
+ if (/behavior\s*:/i.test(css)) errors.push("theme.css must not use behavior:.");
1617
+ if (/javascript\s*:/i.test(css)) errors.push("theme.css must not use javascript: URLs.");
1618
+ if (CSS_STRING_URL_FUNCTION.test(css)) errors.push("theme.css must not use image-set(), src(), image() or cross-fade().");
1619
+ for (const match of css.matchAll(CSS_URL)) {
1620
+ const target = (match[1] ?? match[2] ?? match[3] ?? "").trim();
1621
+ if (!/^data:image\//i.test(target) && !target.startsWith("/_theme/")) {
1622
+ errors.push(`theme.css url(${target}) is not allowed \u2014 use data:image/\u2026 or /_theme/<asset>.`);
1623
+ }
1624
+ }
1625
+ return errors;
1626
+ }
1627
+ var isLocalSvgReference = (target) => target.startsWith("#") || /^data:image\//i.test(target);
1628
+ function validateThemeSvg(text) {
1629
+ const markupError = validateSvgMarkup(text);
1630
+ if (markupError) return markupError;
1631
+ if (text.includes("\\")) return "SVG must not contain backslash (CSS escape) sequences";
1632
+ if (/&#/.test(text)) return "SVG must not contain numeric character references (&#\u2026;)";
1633
+ if (CSS_STRING_URL_FUNCTION.test(text)) return "SVG must not use image-set(), src(), image() or cross-fade()";
1634
+ for (const match of text.matchAll(/(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)) {
1635
+ const target = (match[1] ?? match[2] ?? match[3] ?? "").trim();
1636
+ if (!isLocalSvgReference(target)) return `href '${target}' is not allowed \u2014 only #fragments and data:image URLs`;
1637
+ }
1638
+ for (const match of text.matchAll(CSS_URL)) {
1639
+ const target = (match[1] ?? match[2] ?? match[3] ?? "").trim();
1640
+ if (!isLocalSvgReference(target)) return `url(${target}) is not allowed \u2014 only #fragments and data:image URLs`;
1641
+ }
1642
+ return null;
1643
+ }
1644
+ async function validateThemePayload(projectDir, manifest) {
1645
+ const errors = [];
1646
+ const root = await realpath(projectDir).catch(() => resolve(projectDir));
1647
+ let total = 0;
1648
+ for (const [name, value] of declaredAssets(manifest.spec)) {
1649
+ if (!isAssetName(name) || typeof value !== "string") continue;
1650
+ const path = normalizePayloadPath(value);
1651
+ const mime = themeAssetMime(name, path);
1652
+ if (!mime) continue;
1653
+ const at = `spec.assets.${name} (${path})`;
1654
+ let bytes;
1655
+ try {
1656
+ const absolute = await realpath(resolve(root, path));
1657
+ const fromRoot = relative(root, absolute);
1658
+ if (fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
1659
+ errors.push(`${at} resolves outside the package directory.`);
1660
+ continue;
1661
+ }
1662
+ bytes = await readFile(absolute);
1663
+ } catch {
1664
+ errors.push(`${at} does not exist.`);
1665
+ continue;
1666
+ }
1667
+ total += bytes.length;
1668
+ if (mime === "text/css") {
1669
+ if (bytes.length > THEME_LIMITS.css) errors.push(`${at} exceeds ${THEME_LIMITS.css / 1024} KiB.`);
1670
+ const text = decodeUtf8(bytes);
1671
+ if (text === null) errors.push(`${at} must be UTF-8 text.`);
1672
+ else errors.push(...lintThemeCss(text).map((message) => `${at}: ${message}`));
1673
+ continue;
1674
+ }
1675
+ const limit = name === "background" || name === "background.dark" ? THEME_LIMITS.background : THEME_LIMITS.image;
1676
+ if (bytes.length > limit) errors.push(`${at} exceeds ${limit / (1024 * 1024)} MiB.`);
1677
+ if (mime === "image/svg+xml") {
1678
+ const text = decodeUtf8(bytes);
1679
+ const reason = text === null ? "SVG must be UTF-8 text" : validateThemeSvg(text);
1680
+ if (reason) errors.push(`${at}: ${reason}.`);
1681
+ } else if (!SIGNATURES[mime]?.(bytes)) {
1682
+ errors.push(`${at} is not a valid ${mime} file.`);
1683
+ }
1684
+ }
1685
+ if (total > THEME_LIMITS.total) {
1686
+ errors.push(`theme assets total ${total} bytes, over the ${THEME_LIMITS.total / (1024 * 1024)} MiB limit.`);
1687
+ }
1688
+ return errors;
1689
+ }
1690
+ var themeValidator = {
1691
+ validateManifest: validateThemeManifest,
1692
+ validatePayload: validateThemePayload,
1693
+ expandForPack: expandThemeManifest
1694
+ };
1695
+
1696
+ // src/vpkg/validators/index.ts
1697
+ var PACKAGE_TYPE_VALIDATORS = {
1698
+ theme: themeValidator
1051
1699
  };
1700
+ function validatorForKind(kind) {
1701
+ const name = findPackageType(kind)?.validator;
1702
+ return name ? PACKAGE_TYPE_VALIDATORS[name] : void 0;
1703
+ }
1704
+
1705
+ // src/vpkg/manifest.ts
1052
1706
  function normalizeKind(kind) {
1053
- const mapped = KIND_MAP[kind.replace(/[^a-z]/gi, "").toLowerCase()];
1054
- if (!mapped) throw new Error(`Unsupported manifest kind '${kind}' \u2014 expected Application, ExecutionEngine, Agent, Skill, Tool or Bundle.`);
1055
- return mapped;
1707
+ const canonical = canonicalPackageType(kind);
1708
+ if (!canonical) throw new Error(unknownPackageTypeMessage(kind));
1709
+ return canonical;
1710
+ }
1711
+ var TAG_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
1712
+ var MAX_TAGS = 10;
1713
+ var MAX_TAG_LENGTH = 32;
1714
+ function validateMetadataTags(tags) {
1715
+ if (tags === void 0) return [];
1716
+ if (!Array.isArray(tags)) return ["metadata.tags must be a list of lowercase slugs."];
1717
+ const errors = [];
1718
+ if (tags.length > MAX_TAGS) errors.push(`metadata.tags may contain at most ${MAX_TAGS} tags.`);
1719
+ const seen = /* @__PURE__ */ new Set();
1720
+ tags.forEach((tag, index) => {
1721
+ if (typeof tag !== "string" || tag.length > MAX_TAG_LENGTH || !TAG_PATTERN.test(tag)) {
1722
+ errors.push(`metadata.tags[${index}] must be a lowercase slug (a-z, 0-9, single hyphens) of at most ${MAX_TAG_LENGTH} characters.`);
1723
+ } else if (seen.has(tag)) {
1724
+ errors.push(`metadata.tags contains duplicate '${tag}'.`);
1725
+ } else {
1726
+ seen.add(tag);
1727
+ }
1728
+ });
1729
+ return errors;
1730
+ }
1731
+ function validateTypeSpecFields(kind, spec) {
1732
+ const descriptor = findPackageType(kind);
1733
+ if (!descriptor || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1734
+ return (descriptor.forbiddenSpecFields ?? []).filter((field) => Object.prototype.hasOwnProperty.call(spec, field)).map((field) => `spec.${field} is not allowed for ${descriptor.type} packages.`);
1735
+ }
1736
+ function validateTypeManifest(kind, manifest) {
1737
+ return validatorForKind(kind)?.validateManifest(manifest) ?? [];
1738
+ }
1739
+ function validatePackageManifestRules(kind, manifest) {
1740
+ const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
1741
+ return [
1742
+ ...validateHostedBackendDeclaration(kind, manifest.spec),
1743
+ ...launchKindError ? [`${launchKindError}.`] : [],
1744
+ ...validateNativeCollaborationSection(kind, manifest.spec),
1745
+ ...validateMessageChannelsSection(kind, manifest.spec),
1746
+ ...validateActorSection(kind, manifest.spec),
1747
+ ...validateWopiOperationsSection(manifest.spec),
1748
+ ...validateApplicationSplashSection(kind, manifest.spec),
1749
+ ...validateMetadataTags(manifest.metadata?.tags),
1750
+ ...validateTypeSpecFields(kind, manifest.spec),
1751
+ ...validateTypeManifest(kind, manifest)
1752
+ ];
1056
1753
  }
1057
1754
  function validateLaunchManifestKind(kind, spec) {
1058
- if (kind === "Application" || !spec || typeof spec !== "object" || Array.isArray(spec)) return void 0;
1755
+ if (isApplicationProfile(kind) || !spec || typeof spec !== "object" || Array.isArray(spec)) return void 0;
1059
1756
  if (!Object.prototype.hasOwnProperty.call(spec, "launch")) return void 0;
1060
1757
  return "spec.launch is only supported for Application manifests";
1061
1758
  }
@@ -1099,6 +1796,14 @@ async function loadManifest(path) {
1099
1796
  if (splashErrors.length > 0) {
1100
1797
  throw new Error(`Invalid manifest at ${path}: ${splashErrors.join(" ")}`);
1101
1798
  }
1799
+ const typeErrors = [
1800
+ ...validateMetadataTags(manifest.metadata.tags),
1801
+ ...validateTypeSpecFields(kind, manifest.spec),
1802
+ ...validateTypeManifest(kind, manifest)
1803
+ ];
1804
+ if (typeErrors.length > 0) {
1805
+ throw new Error(`Invalid manifest at ${path}: ${typeErrors.join(" ")}`);
1806
+ }
1102
1807
  const marketplaceErrors = validateMarketplaceSection(manifest.marketplace);
1103
1808
  if (marketplaceErrors.length > 0) {
1104
1809
  throw new Error(`Invalid marketplace section in ${path}: ${marketplaceErrors.join(" ")}`);
@@ -1124,7 +1829,10 @@ async function bumpManifestPatchVersion(path, currentVersion) {
1124
1829
  return nextVersion;
1125
1830
  }
1126
1831
  function validateApplicationSplashSection(kind, spec) {
1127
- if (kind !== "Application" || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1832
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1833
+ if (!isApplicationProfile(kind)) {
1834
+ return Object.prototype.hasOwnProperty.call(spec, "splash") ? ["spec.splash is only supported for Application manifests."] : [];
1835
+ }
1128
1836
  const applicationSpec = spec;
1129
1837
  const errors = [];
1130
1838
  const splash = applicationSpec.splash;
@@ -1144,7 +1852,7 @@ function validateApplicationSplashSection(kind, spec) {
1144
1852
  return errors;
1145
1853
  }
1146
1854
  function validateHostedBackendDeclaration(kind, spec) {
1147
- if (kind === "Application" || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1855
+ if (isApplicationProfile(kind) || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1148
1856
  const value = spec;
1149
1857
  const capabilities = value.capabilities;
1150
1858
  const requestsCapability = Array.isArray(capabilities) && capabilities.some((capability) => typeof capability === "string" && capability.trim().toLowerCase() === "hosted-backend");
@@ -1157,7 +1865,7 @@ var MESSAGE_CHANNEL_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
1157
1865
  var MAX_MESSAGE_CHANNELS = 32;
1158
1866
  function validateMessageChannelsSection(kind, spec) {
1159
1867
  if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "messages")) return [];
1160
- if (kind !== "Application") return ["spec.messages is only supported for Application manifests."];
1868
+ if (!isApplicationProfile(kind)) return ["spec.messages is only supported for Application manifests."];
1161
1869
  const messages = spec.messages;
1162
1870
  if (!Array.isArray(messages)) return ["spec.messages must be a list of { channel, description, schema? }."];
1163
1871
  if (messages.length > MAX_MESSAGE_CHANNELS) return [`spec.messages declares more than ${MAX_MESSAGE_CHANNELS} channels.`];
@@ -1191,7 +1899,7 @@ var ACTOR_FILE_KINDS = /* @__PURE__ */ new Set(["native-collaboration", "documen
1191
1899
  var MAX_ACTOR_SURFACES = 16;
1192
1900
  function validateActorSection(kind, spec) {
1193
1901
  if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "actor")) return [];
1194
- if (kind !== "Application") return ["spec.actor is only supported for Application manifests."];
1902
+ if (!isApplicationProfile(kind)) return ["spec.actor is only supported for Application manifests."];
1195
1903
  const applicationSpec = spec;
1196
1904
  const actor = applicationSpec.actor;
1197
1905
  if (!actor || typeof actor !== "object" || Array.isArray(actor)) {
@@ -1284,7 +1992,7 @@ function declaredTools(spec) {
1284
1992
  }
1285
1993
  function validateNativeCollaborationSection(kind, spec) {
1286
1994
  if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "collaboration")) return [];
1287
- if (kind !== "Application") return ["spec.collaboration is only supported for Application manifests."];
1995
+ if (!isApplicationProfile(kind)) return ["spec.collaboration is only supported for Application manifests."];
1288
1996
  const applicationSpec = spec;
1289
1997
  const declaration = applicationSpec.collaboration;
1290
1998
  if (!declaration || typeof declaration !== "object" || Array.isArray(declaration) || Object.keys(declaration).length !== 1 || !Object.prototype.hasOwnProperty.call(declaration, "mode") || declaration.mode !== "native-scene-v1") {
@@ -1375,16 +2083,42 @@ async function findManifest(dir) {
1375
2083
  } catch {
1376
2084
  }
1377
2085
  const entries = await readdir(dir);
1378
- const candidates = entries.filter((name) => /\.(app|engine|agent|skill|tool|bundle|policy)\.ya?ml$/.test(name));
2086
+ const suffixes = manifestFileSuffixes();
2087
+ const candidates = entries.filter((name) => {
2088
+ const match = /\.([a-z0-9-]+)\.ya?ml$/.exec(name);
2089
+ return !!match && suffixes.includes(match[1]);
2090
+ });
1379
2091
  if (candidates.length === 1) return join(dir, candidates[0]);
1380
2092
  if (candidates.length === 0) {
1381
- throw new Error(`No manifest found in ${dir}. Expected manifest.yaml or a single *.app.yaml / *.engine.yaml / *.agent.yaml / *.skill.yaml / *.tool.yaml / *.bundle.yaml / *.policy.yaml.`);
2093
+ throw new Error(`No manifest found in ${dir}. Expected manifest.yaml or a single ${suffixes.map((suffix) => `*.${suffix}.yaml`).join(" / ")}.`);
1382
2094
  }
1383
2095
  throw new Error(`Multiple manifests found in ${dir} (${candidates.join(", ")}). Pass --manifest to disambiguate.`);
1384
2096
  }
2097
+ function manifestFileSuffixes() {
2098
+ const suffixes = packageTypes().types.flatMap((type) => [...type.aliases ?? [], type.mediaSlug]);
2099
+ return [.../* @__PURE__ */ new Set([...suffixes.map((suffix) => suffix.toLowerCase()), "policy"])];
2100
+ }
1385
2101
  var NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
1386
2102
  var DEPENDENCY_IDENTITY = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
2103
+ var DEPENDENCY_SHORTHAND = /^([a-z0-9](?:[a-z0-9-]*[a-z0-9])?\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)@(.+)$/;
1387
2104
  var EXACT_VERSION = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;
2105
+ var RANGE_COMPARATOR = /^(?:\^|~|>=|<=|>|<|=)?(?:0|[1-9][0-9]*|[xX*])(?:\.(?:0|[1-9][0-9]*|[xX*])){0,2}(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
2106
+ var MAX_VERSION_LENGTH = 128;
2107
+ var LATEST_VERSION = "latest";
2108
+ function isValidDependencyVersion(version) {
2109
+ const value = version.trim();
2110
+ if (value.length === 0 || value.length > MAX_VERSION_LENGTH) return false;
2111
+ if (value === LATEST_VERSION || EXACT_VERSION.test(value)) return true;
2112
+ const comparators = value.split(/\s+/);
2113
+ return comparators.length <= 4 && comparators.every((comparator) => RANGE_COMPARATOR.test(comparator)) && semver.validRange(value) !== null;
2114
+ }
2115
+ function resolveDependencyReference(item) {
2116
+ if (typeof item.package !== "string") return void 0;
2117
+ const shorthand = DEPENDENCY_SHORTHAND.exec(item.package);
2118
+ if (shorthand) return { package: shorthand[1], version: shorthand[2].trim() };
2119
+ const version = typeof item.version === "string" ? item.version.trim() : LATEST_VERSION;
2120
+ return { package: item.package, version };
2121
+ }
1388
2122
  function validateDependencies(spec) {
1389
2123
  if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1390
2124
  const value = spec;
@@ -1393,7 +2127,7 @@ function validateDependencies(spec) {
1393
2127
  const seen = /* @__PURE__ */ new Set();
1394
2128
  if (value.dependencies !== void 0) {
1395
2129
  if (!Array.isArray(value.dependencies) || value.dependencies.length > 32) {
1396
- errors.push("spec.dependencies must be a list of at most 32 exact package pins.");
2130
+ errors.push("spec.dependencies must be a list of at most 32 package dependencies.");
1397
2131
  } else {
1398
2132
  for (const dependency of value.dependencies) {
1399
2133
  if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) {
@@ -1404,8 +2138,17 @@ function validateDependencies(spec) {
1404
2138
  if (Object.keys(item).some((key) => !["package", "version", "install-path", "optional"].includes(key))) {
1405
2139
  errors.push("Each dependency accepts only package, version, install-path and optional.");
1406
2140
  }
1407
- if (typeof item.package !== "string" || !DEPENDENCY_IDENTITY.test(item.package) || typeof item.version !== "string" || !EXACT_VERSION.test(item.version)) {
1408
- errors.push("Dependencies require a lowercase publisher/package-id and an exact semantic version.");
2141
+ const shorthand = typeof item.package === "string" ? DEPENDENCY_SHORTHAND.exec(item.package) : null;
2142
+ const identity = shorthand ? shorthand[1] : item.package;
2143
+ if (typeof identity !== "string" || !DEPENDENCY_IDENTITY.test(identity)) {
2144
+ errors.push("Dependencies require a lowercase publisher/package-id (optionally publisher/package-id@<version>).");
2145
+ } else if (shorthand && item.version !== void 0) {
2146
+ errors.push(`Dependency '${identity}' declares a version both in package (@${shorthand[2]}) and in version; use one.`);
2147
+ } else {
2148
+ const version = shorthand ? shorthand[2] : item.version;
2149
+ if (version !== void 0 && (typeof version !== "string" || !isValidDependencyVersion(version))) {
2150
+ errors.push(`Dependency '${identity}' has invalid version '${String(version)}' \u2014 use an exact semantic version (1.2.3), a range (^1.2, ~1.2.3, >=1.2.0 <2.0.0, 1.x, *) or latest.`);
2151
+ }
1409
2152
  }
1410
2153
  if (item.optional !== void 0 && typeof item.optional !== "boolean") {
1411
2154
  errors.push("Dependency optional must be true or false.");
@@ -1417,10 +2160,10 @@ function validateDependencies(spec) {
1417
2160
  errors.push("Dependency install-path must be a nonempty workspace path without traversal.");
1418
2161
  }
1419
2162
  }
1420
- if (typeof item.package === "string") {
1421
- if (seen.has(item.package)) errors.push(`Duplicate dependency '${item.package}'.`);
1422
- seen.add(item.package);
1423
- if (item.optional !== true) required.add(item.package);
2163
+ if (typeof identity === "string") {
2164
+ if (seen.has(identity)) errors.push(`Duplicate dependency '${identity}'.`);
2165
+ seen.add(identity);
2166
+ if (item.optional !== true) required.add(identity);
1424
2167
  }
1425
2168
  }
1426
2169
  }
@@ -1434,6 +2177,20 @@ function validateDependencies(spec) {
1434
2177
  }
1435
2178
  return errors;
1436
2179
  }
2180
+ function normalizeDependencies(spec) {
2181
+ if (!spec || !Array.isArray(spec.dependencies)) return spec;
2182
+ let changed = false;
2183
+ const dependencies = spec.dependencies.map((dependency) => {
2184
+ if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) return dependency;
2185
+ const item = dependency;
2186
+ const reference = resolveDependencyReference(item);
2187
+ if (!reference || reference.package === item.package && reference.version === item.version) return dependency;
2188
+ changed = true;
2189
+ const { package: _package, version: _version, ...rest } = item;
2190
+ return { package: reference.package, version: reference.version, ...rest };
2191
+ });
2192
+ return changed ? { ...spec, dependencies } : spec;
2193
+ }
1437
2194
  function validatePackageName(name, label) {
1438
2195
  if (!NAME_PATTERN.test(name)) {
1439
2196
  throw new Error(`Invalid ${label} '${name}' \u2014 use lowercase letters, digits and hyphens (no leading/trailing hyphen).`);
@@ -1441,6 +2198,7 @@ function validatePackageName(name, label) {
1441
2198
  }
1442
2199
 
1443
2200
  // src/dev/manifest.ts
2201
+ var NON_PACKAGE_KINDS = ["Policy"];
1444
2202
  async function readManifestDocument(path) {
1445
2203
  const text = await readFile(path, "utf8");
1446
2204
  const doc = parse(text);
@@ -1456,14 +2214,16 @@ function validateManifest(manifest) {
1456
2214
  const issues = [];
1457
2215
  const error = (message) => issues.push({ level: "error", message });
1458
2216
  const warning = (message) => issues.push({ level: "warning", message });
1459
- const kind = manifest.kind;
1460
- const knownKinds = ["ExecutionEngine", "Application", "Agent", "Skill", "Tool", "Bundle", "Policy"];
1461
- if (!kind) {
1462
- error("missing 'kind' (ExecutionEngine | Application | Agent | Skill | Tool | Bundle | Policy)");
2217
+ const knownKinds = [...packageTypes().typeNames(), ...NON_PACKAGE_KINDS];
2218
+ if (!manifest.kind) {
2219
+ error(`missing 'kind' (${knownKinds.join(" | ")})`);
1463
2220
  return issues;
1464
2221
  }
1465
- if (!knownKinds.includes(kind)) {
1466
- error(`unknown kind '${kind}' (expected ExecutionEngine, Application, Agent, Skill, Tool, Bundle or Policy)`);
2222
+ const descriptor = findPackageType(manifest.kind);
2223
+ const isPolicy = manifest.kind === "Policy";
2224
+ const kind = descriptor?.type ?? manifest.kind;
2225
+ if (!descriptor && !isPolicy) {
2226
+ error(`unknown kind '${manifest.kind}' (expected one of ${knownKinds.join(", ")})`);
1467
2227
  }
1468
2228
  if (!manifest["api-version"]) {
1469
2229
  warning("missing 'api-version' (expected verentis.io/v1)");
@@ -1476,7 +2236,8 @@ function validateManifest(manifest) {
1476
2236
  } else if (!NAME_PATTERN.test(meta.name)) {
1477
2237
  error("metadata.name must use lowercase letters, digits and internal hyphens");
1478
2238
  }
1479
- if (kind !== "Policy") {
2239
+ if (!isPolicy) {
2240
+ for (const message of validateMetadataTags(meta.tags)) error(message);
1480
2241
  for (const field of ["display-name", "version"]) {
1481
2242
  if (!meta[field]) error(`metadata.${field} is required`);
1482
2243
  }
@@ -1496,7 +2257,10 @@ function validateManifest(manifest) {
1496
2257
  for (const message of validateNativeCollaborationSection(kind, spec)) error(message);
1497
2258
  for (const message of validateMessageChannelsSection(kind, spec)) error(message);
1498
2259
  for (const message of validateActorSection(kind, spec)) error(message);
1499
- if (kind === "ExecutionEngine") {
2260
+ for (const message of validateApplicationSplashSection(kind, spec)) error(message);
2261
+ for (const message of validateTypeSpecFields(kind, spec)) error(message);
2262
+ for (const message of validateTypeManifest(kind, manifest)) error(message);
2263
+ if (descriptor?.profile === "engine") {
1500
2264
  const runtimes = spec.runtimes ?? {};
1501
2265
  if (Object.keys(runtimes).length === 0) {
1502
2266
  error("spec.runtimes must declare at least one runtime (docker and/or wasm)");
@@ -1515,7 +2279,7 @@ function validateManifest(manifest) {
1515
2279
  if (!spec["execution-modes"]?.length) warning("spec.execution-modes is empty (expected e.g. request-response)");
1516
2280
  if (!manifestPermissions(manifest).length) warning("spec.permissions is empty \u2014 the run token will carry no VFS scopes");
1517
2281
  }
1518
- if (kind === "Application") {
2282
+ if (descriptor?.profile === "application") {
1519
2283
  const hasIframe = !!spec.entry || !!spec["entry-points"]?.length;
1520
2284
  const hasInstall = Array.isArray(spec.install) && spec.install.length > 0;
1521
2285
  const hasScopes = Array.isArray(spec.scopes) && spec.scopes.length > 0;
@@ -1524,18 +2288,17 @@ function validateManifest(manifest) {
1524
2288
  "an Application must declare at least one contribution: spec.entry / spec.entry-points[] (iframe UI), spec.install[] (installed files), or spec.scopes[] (identity)"
1525
2289
  );
1526
2290
  }
1527
- for (const message of validateApplicationSplashSection(kind, spec)) error(message);
1528
2291
  validateApplicationLaunch(spec, issues);
1529
2292
  }
1530
- if (kind === "Agent") validateAgentManifest(spec, issues);
1531
- if (kind === "Skill") validateSkillManifest(spec, issues);
1532
- if (kind === "Tool") validateToolManifest(spec, issues);
1533
- if (kind === "Policy") validatePolicyManifest(spec, issues);
2293
+ if (descriptor?.resourceKind === "Agent") validateAgentManifest(spec, issues);
2294
+ if (descriptor?.resourceKind === "Skill") validateSkillManifest(spec, issues);
2295
+ if (descriptor?.resourceKind === "Tool") validateToolManifest(spec, issues);
2296
+ if (isPolicy) validatePolicyManifest(spec, issues);
1534
2297
  validateInstallDirectives(spec.install, issues);
1535
- validateSettingDeclarations(kind, spec, issues);
2298
+ validateSettingDeclarations(descriptor?.profile === "engine", spec, issues);
1536
2299
  for (const message of validateMarketplaceSection(manifest.marketplace)) error(message);
1537
2300
  const packaging = manifest.packaging ?? {};
1538
- if (kind !== "Policy" && !packaging.publisher) warning("packaging.publisher is not set \u2014 `verentis pack`/`publish` will refuse the package");
2301
+ if (!isPolicy && !packaging.publisher) warning("packaging.publisher is not set \u2014 `verentis pack`/`publish` will refuse the package");
1539
2302
  return issues;
1540
2303
  }
1541
2304
  function validateAgentManifest(spec, issues) {
@@ -1744,7 +2507,7 @@ function validateInstallDirectives(install, issues) {
1744
2507
  var SETTING_KEY_PATTERN = /^[a-z0-9]+([.-][a-z0-9]+)*$/;
1745
2508
  var ENV_VAR_PATTERN = /^[A-Z][A-Z0-9_]*$/;
1746
2509
  var SETTING_TYPES = ["string", "number", "boolean", "select", "file"];
1747
- function validateSettingDeclarations(kind, spec, issues) {
2510
+ function validateSettingDeclarations(isEngine, spec, issues) {
1748
2511
  const settings2 = spec.settings;
1749
2512
  if (settings2 === void 0) return;
1750
2513
  const error = (message) => issues.push({ level: "error", message });
@@ -1795,7 +2558,7 @@ function validateSettingDeclarations(kind, spec, issues) {
1795
2558
  error(`${at}.options is only allowed for type 'select'`);
1796
2559
  }
1797
2560
  });
1798
- if (kind === "ExecutionEngine") {
2561
+ if (isEngine) {
1799
2562
  const declaresSecret = settings2.some(
1800
2563
  (declaration) => declaration && typeof declaration === "object" && declaration.secret === true
1801
2564
  );
@@ -2156,7 +2919,7 @@ async function followExecution(api, workspaceId, executionId, json) {
2156
2919
  if (exec.status !== "Completed") process.exitCode = 1;
2157
2920
  return;
2158
2921
  }
2159
- await new Promise((resolve15) => setTimeout(resolve15, 1e3));
2922
+ await new Promise((resolve16) => setTimeout(resolve16, 1e3));
2160
2923
  }
2161
2924
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
2162
2925
  process.exitCode = 1;
@@ -2342,338 +3105,110 @@ function registerFiles(program2) {
2342
3105
  async (localPath, remotePath, options) => {
2343
3106
  if (options.extract && options.asZip) throw new Error("--extract and --as-zip are mutually exclusive.");
2344
3107
  const conflict = options.conflict?.toLowerCase();
2345
- if (conflict && !CONFLICT_POLICIES.has(conflict)) throw new Error(`Unknown conflict policy '${options.conflict}'. Use merge or reject.`);
2346
- const workspaceId = await resolveWorkspaceId(options);
2347
- const api = await createApiClient();
2348
- const local = resolve(localPath);
2349
- const info = await stat(local);
2350
- if (info.isDirectory()) {
2351
- const remoteBase = normalizeRemote(remotePath ?? basename(local));
2352
- const uploaded = await uploadDirectory(api, workspaceId, local, remoteBase, options.branch);
2353
- console.log(`Uploaded ${uploaded} file(s) to /${remoteBase}.`);
2354
- return;
2355
- }
2356
- const autoExtract = options.extract ? true : options.asZip ? false : void 0;
2357
- const asFolder = autoExtract === true || autoExtract === void 0 && isZipName(local) && zipHasRootManifest(await readFile(local)) === true;
2358
- const remote = asFolder ? normalizeRemote(remotePath ?? "/") : remotePath && remotePath.endsWith("/") ? posix.join(normalizeRemote(remotePath), basename(local)) : normalizeRemote(remotePath ?? basename(local));
2359
- const result = await uploadWithHeaders(api, workspaceId, remote, local, {
2360
- branch: options.branch,
2361
- contentType: options.contentType,
2362
- autoExtract,
2363
- conflict
2364
- });
2365
- if (result.status === 202) {
2366
- const id = importJobId(result);
2367
- if (!id) throw new Error("The server accepted the archive import but returned no job id.");
2368
- const accepted = result.body && typeof result.body === "object" ? result.body : void 0;
2369
- if (!options.wait) {
2370
- if (options.json) printJson(accepted ?? { id });
2371
- else console.log(`Archive import started: ${id}
2372
- Check progress with: verentis files import-status ${id} --branch ${options.branch}`);
2373
- return;
2374
- }
2375
- if (!options.json) console.error(`Archive import started: ${id}`);
2376
- const final = await waitForArchiveImport(api, workspaceId, id, options.branch, accepted?.state ? accepted : void 0);
2377
- reportImport(final, options);
2378
- return;
2379
- }
2380
- if (options.json) {
2381
- printJson(result.body);
2382
- return;
2383
- }
2384
- if (Array.isArray(result.body)) {
2385
- console.log(`Uploaded ${localPath} \u2192 /${remote} (extracted ${result.body.length} file(s))`);
2386
- return;
2387
- }
2388
- console.log(`Uploaded ${localPath} \u2192 /${result.body?.path ?? remote}`);
2389
- }
2390
- );
2391
- filesCmd.command("import-status <id>").description("Show the status of an archive import job").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--wait", "poll until the import finishes").option("--json", "output JSON").action(async (id, options) => {
2392
- const workspaceId = await resolveWorkspaceId(options);
2393
- const api = await createApiClient();
2394
- if (options.wait) {
2395
- reportImport(await waitForArchiveImport(api, workspaceId, id, options.branch), options);
2396
- return;
2397
- }
2398
- const status = await getImportStatus(api, workspaceId, id, options.branch);
2399
- const { errors, ...rest } = status;
2400
- if (options.json) printJson(status);
2401
- else {
2402
- outputRecord(rest, options);
2403
- if (errors?.length) {
2404
- console.log("errors:");
2405
- for (const err of errors) console.log(` ${err.path ? `${err.path}: ` : ""}${err.message}`);
2406
- }
2407
- }
2408
- if (status.state === "Failed" || status.state === "Cancelled") process.exitCode = 1;
2409
- });
2410
- filesCmd.command("rm <path>").description("Delete a file or directory").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--recursive", "delete directory contents recursively").action(async (path, options) => {
2411
- const workspaceId = await resolveWorkspaceId(options);
2412
- const api = await createApiClient();
2413
- await api.requestRaw("DELETE", fillPath(files.delete.path, { path: normalizeRemote(path) }), {
2414
- scopes: [...files.delete.scopes],
2415
- tokenWorkspaceId: workspaceId,
2416
- query: { branch: options.branch },
2417
- headers: options.recursive ? { "X-Delete-Mode": "Deep" } : {}
2418
- });
2419
- console.log(`Deleted /${normalizeRemote(path)}.`);
2420
- });
2421
- filesCmd.command("mv <fromPath> <toPath>").description("Move or rename a file").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").action(async (fromPath, toPath, options) => {
2422
- const workspaceId = await resolveWorkspaceId(options);
2423
- const api = await createApiClient();
2424
- await call(api, files.update, {
2425
- params: { path: normalizeRemote(fromPath) },
2426
- workspaceId,
2427
- body: { branch: options.branch, path: normalizeRemote(fromPath), toPath: normalizeRemote(toPath) }
2428
- });
2429
- console.log(`Moved /${normalizeRemote(fromPath)} \u2192 /${normalizeRemote(toPath)}.`);
2430
- });
2431
- }
2432
- async function uploadDirectory(api, workspaceId, localDir, remoteBase, branch) {
2433
- let count = 0;
2434
- const entries = await readdir(localDir, { withFileTypes: true });
2435
- for (const entry of entries) {
2436
- if (entry.name.startsWith(".git") || entry.name === "node_modules" || entry.name === "__pycache__") continue;
2437
- const localEntry = join(localDir, entry.name);
2438
- const remoteEntry = posix.join(remoteBase, entry.name);
2439
- if (entry.isDirectory()) {
2440
- count += await uploadDirectory(api, workspaceId, localEntry, remoteEntry, branch);
2441
- } else if (entry.isFile()) {
2442
- await uploadWithHeaders(api, workspaceId, remoteEntry, localEntry, { branch, autoExtract: isZipName(entry.name) ? false : void 0 });
2443
- console.log(` /${remoteEntry}`);
2444
- count += 1;
2445
- }
2446
- }
2447
- return count;
2448
- }
2449
- var MAX_ICON_BYTES = 32 * 1024;
2450
- var MAX_TOTAL_ICON_BYTES = 256 * 1024;
2451
- var LEGACY_ICON_PATTERN = /^[a-z0-9-]+(:[a-z0-9-]+)?$/;
2452
- var SVG_START = /^(?:<\?xml[\s\S]*?\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg\b/i;
2453
- var SVG_END_CLOSING = /<\/svg>\s*$/i;
2454
- var SVG_END_SELF_CLOSING = /<svg\b[\s\S]*\/>\s*$/i;
2455
- var SVG_REJECTIONS = [
2456
- [/&#/i, "numeric character references (&#) are not allowed"],
2457
- [/<!DOCTYPE|<!ENTITY/i, "<!DOCTYPE>/<!ENTITY> declarations are not allowed"],
2458
- [/<(?:script|foreignObject|iframe|object|embed|audio|video)\b/i, "script, foreignObject, iframe, object, embed, audio and video elements are not allowed"],
2459
- [/\son[a-z]+\s*=/i, "event handler (on*=) attributes are not allowed"],
2460
- [/(?:javascript|vbscript)\s*:/i, "javascript:/vbscript: URLs are not allowed"],
2461
- [/data\s*:\s*text\/html/i, "data:text/html URLs are not allowed"],
2462
- [/(?:xlink:href|href)\s*=\s*["']?\s*(?:https?:|ftp:|\/\/)/i, "external href/xlink:href references are not allowed"],
2463
- [/url\(\s*["']?\s*(?:https?:|\/\/)/i, "external url(...) references are not allowed"]
2464
- ];
2465
- function validateSvgIcon(text) {
2466
- if (Buffer.byteLength(text, "utf8") > MAX_ICON_BYTES) return `SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit`;
2467
- const markup = canonicalizeSvg(text);
2468
- if (!SVG_START.test(markup)) return "SVG must have an <svg> root element (only an <?xml ?> declaration and comments may precede it)";
2469
- if (!SVG_END_CLOSING.test(markup) && !SVG_END_SELF_CLOSING.test(markup)) return "SVG must end with </svg>";
2470
- for (const [pattern, reason] of SVG_REJECTIONS) {
2471
- if (pattern.test(markup)) return reason;
2472
- }
2473
- return null;
2474
- }
2475
- function canonicalizeSvg(text) {
2476
- return text.replace(/^\uFEFF+/, "").trim();
2477
- }
2478
- function decodeUtf8(bytes) {
2479
- try {
2480
- return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2481
- } catch {
2482
- return null;
2483
- }
2484
- }
2485
- function classifyIconValue(value) {
2486
- const trimmed = value.trim();
2487
- if (trimmed.startsWith("<")) return "inline";
2488
- if (trimmed.startsWith("#")) return "ref";
2489
- if (/\.svg$/i.test(trimmed)) return "path";
2490
- if (LEGACY_ICON_PATTERN.test(trimmed)) return "legacy";
2491
- return "invalid";
2492
- }
2493
- function collectIconFields(manifest) {
2494
- const fields = [];
2495
- if (!isRecord(manifest)) return fields;
2496
- const add = (path, value) => {
2497
- if (value !== void 0) fields.push({ path, label: formatPath(path), value });
2498
- };
2499
- const bindings = (container, path) => {
2500
- if (!Array.isArray(container)) return;
2501
- container.forEach((item, index) => {
2502
- if (isRecord(item)) add([...path, index, "icon"], item.icon);
2503
- });
2504
- };
2505
- if (isRecord(manifest.metadata)) add(["metadata", "icon"], manifest.metadata.icon);
2506
- const spec = manifest.spec;
2507
- if (!isRecord(spec)) return fields;
2508
- if (Array.isArray(spec["entry-points"])) {
2509
- spec["entry-points"].forEach((entryPoint, index) => {
2510
- if (!isRecord(entryPoint)) return;
2511
- add(["spec", "entry-points", index, "icon"], entryPoint.icon);
2512
- bindings(entryPoint["mime-types"], ["spec", "entry-points", index, "mime-types"]);
2513
- });
2514
- }
2515
- bindings(spec["mime-types"], ["spec", "mime-types"]);
2516
- bindings(spec["file-types"], ["spec", "file-types"]);
2517
- return fields;
2518
- }
2519
- async function resolveManifestIcons(manifest, manifestDir) {
2520
- const errors = [];
2521
- const warnings = [];
2522
- const fields = [];
2523
- const root = resolve(manifestDir);
2524
- const distinct = /* @__PURE__ */ new Set();
2525
- const resolveSvg = async (label, value, allowLegacy) => {
2526
- const kind = classifyIconValue(value);
2527
- if (kind === "inline") return checkMarkup(label, value.trim(), "inline SVG");
2528
- if (kind === "path") {
2529
- const loaded = await readIconFile(root, value.trim());
2530
- if ("error" in loaded) {
2531
- errors.push(`${label}: ${loaded.error}`);
2532
- return void 0;
2533
- }
2534
- return checkMarkup(label, loaded.text, value.trim());
2535
- }
2536
- if (kind === "legacy" && allowLegacy) return void 0;
2537
- errors.push(allowLegacy ? `${label}: '${value}' is not a relative .svg path, "#key" reference, inline <svg> markup or Iconify id` : `${label}: '${value}' must be a relative .svg path or inline <svg> markup`);
2538
- return void 0;
2539
- };
2540
- const checkMarkup = (label, text, source) => {
2541
- const problem = validateSvgIcon(text);
2542
- if (problem) {
2543
- errors.push(`${label}: ${source}: ${problem}`);
2544
- return void 0;
2545
- }
2546
- const markup = canonicalizeSvg(text);
2547
- distinct.add(markup);
2548
- return markup;
2549
- };
2550
- const map = /* @__PURE__ */ new Map();
2551
- const iconsSection = isRecord(manifest) ? manifest.icons : void 0;
2552
- if (iconsSection !== void 0) {
2553
- if (!isRecord(iconsSection)) {
2554
- errors.push("icons must be a map of key -> SVG file path or inline <svg> markup");
2555
- } else {
2556
- for (const [key, value] of Object.entries(iconsSection)) {
2557
- const label = `icons.${key}`;
2558
- if (typeof value !== "string" || value.trim().length === 0) {
2559
- errors.push(`${label} must be a non-empty string`);
2560
- map.set(key, void 0);
2561
- continue;
3108
+ if (conflict && !CONFLICT_POLICIES.has(conflict)) throw new Error(`Unknown conflict policy '${options.conflict}'. Use merge or reject.`);
3109
+ const workspaceId = await resolveWorkspaceId(options);
3110
+ const api = await createApiClient();
3111
+ const local = resolve(localPath);
3112
+ const info = await stat(local);
3113
+ if (info.isDirectory()) {
3114
+ const remoteBase = normalizeRemote(remotePath ?? basename(local));
3115
+ const uploaded = await uploadDirectory(api, workspaceId, local, remoteBase, options.branch);
3116
+ console.log(`Uploaded ${uploaded} file(s) to /${remoteBase}.`);
3117
+ return;
3118
+ }
3119
+ const autoExtract = options.extract ? true : options.asZip ? false : void 0;
3120
+ const asFolder = autoExtract === true || autoExtract === void 0 && isZipName(local) && zipHasRootManifest(await readFile(local)) === true;
3121
+ const remote = asFolder ? normalizeRemote(remotePath ?? "/") : remotePath && remotePath.endsWith("/") ? posix.join(normalizeRemote(remotePath), basename(local)) : normalizeRemote(remotePath ?? basename(local));
3122
+ const result = await uploadWithHeaders(api, workspaceId, remote, local, {
3123
+ branch: options.branch,
3124
+ contentType: options.contentType,
3125
+ autoExtract,
3126
+ conflict
3127
+ });
3128
+ if (result.status === 202) {
3129
+ const id = importJobId(result);
3130
+ if (!id) throw new Error("The server accepted the archive import but returned no job id.");
3131
+ const accepted = result.body && typeof result.body === "object" ? result.body : void 0;
3132
+ if (!options.wait) {
3133
+ if (options.json) printJson(accepted ?? { id });
3134
+ else console.log(`Archive import started: ${id}
3135
+ Check progress with: verentis files import-status ${id} --branch ${options.branch}`);
3136
+ return;
2562
3137
  }
2563
- map.set(key, await resolveSvg(label, value, false));
3138
+ if (!options.json) console.error(`Archive import started: ${id}`);
3139
+ const final = await waitForArchiveImport(api, workspaceId, id, options.branch, accepted?.state ? accepted : void 0);
3140
+ reportImport(final, options);
3141
+ return;
2564
3142
  }
3143
+ if (options.json) {
3144
+ printJson(result.body);
3145
+ return;
3146
+ }
3147
+ if (Array.isArray(result.body)) {
3148
+ console.log(`Uploaded ${localPath} \u2192 /${remote} (extracted ${result.body.length} file(s))`);
3149
+ return;
3150
+ }
3151
+ console.log(`Uploaded ${localPath} \u2192 /${result.body?.path ?? remote}`);
2565
3152
  }
2566
- }
2567
- for (const field of collectIconFields(manifest)) {
2568
- if (typeof field.value !== "string" || field.value.trim().length === 0) {
2569
- errors.push(`${field.label} must be a non-empty string`);
2570
- continue;
2571
- }
2572
- const value = field.value;
2573
- const kind = classifyIconValue(value);
2574
- if (kind === "legacy") {
2575
- warnings.push(`${field.label}: '${value}' is a legacy Iconify icon; run \`verentis icons migrate\` to convert it to SVG`);
2576
- fields.push({ ...field, value, legacy: true });
2577
- continue;
3153
+ );
3154
+ filesCmd.command("import-status <id>").description("Show the status of an archive import job").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--wait", "poll until the import finishes").option("--json", "output JSON").action(async (id, options) => {
3155
+ const workspaceId = await resolveWorkspaceId(options);
3156
+ const api = await createApiClient();
3157
+ if (options.wait) {
3158
+ reportImport(await waitForArchiveImport(api, workspaceId, id, options.branch), options);
3159
+ return;
2578
3160
  }
2579
- if (kind === "ref") {
2580
- const key = value.trim().slice(1);
2581
- if (!map.has(key)) {
2582
- errors.push(`${field.label}: ${value.trim()} does not match a key in the top-level icons map`);
2583
- continue;
3161
+ const status = await getImportStatus(api, workspaceId, id, options.branch);
3162
+ const { errors, ...rest } = status;
3163
+ if (options.json) printJson(status);
3164
+ else {
3165
+ outputRecord(rest, options);
3166
+ if (errors?.length) {
3167
+ console.log("errors:");
3168
+ for (const err of errors) console.log(` ${err.path ? `${err.path}: ` : ""}${err.message}`);
2584
3169
  }
2585
- const markup2 = map.get(key);
2586
- if (markup2 !== void 0) fields.push({ ...field, value, markup: markup2, legacy: false });
2587
- continue;
2588
- }
2589
- const markup = await resolveSvg(field.label, value, true);
2590
- if (markup !== void 0) fields.push({ ...field, value, markup, legacy: false });
2591
- }
2592
- let logoIcon;
2593
- const metadata = isRecord(manifest) && isRecord(manifest.metadata) ? manifest.metadata : void 0;
2594
- const marketplace2 = isRecord(manifest) && isRecord(manifest.marketplace) ? manifest.marketplace : void 0;
2595
- if (metadata && metadata.icon === void 0 && typeof marketplace2?.logo === "string" && /\.svg$/i.test(marketplace2.logo.trim())) {
2596
- const loaded = await readIconFile(root, marketplace2.logo.trim());
2597
- const problem = "error" in loaded ? loaded.error : validateSvgIcon(loaded.text);
2598
- if (problem || "error" in loaded) {
2599
- warnings.push(`marketplace.logo cannot be used as the app icon (metadata.icon fallback): ${problem}`);
2600
- } else {
2601
- logoIcon = canonicalizeSvg(loaded.text);
2602
- distinct.add(logoIcon);
2603
3170
  }
2604
- }
2605
- const total = [...distinct].reduce((sum, markup) => sum + Buffer.byteLength(markup, "utf8"), 0);
2606
- if (total > MAX_TOTAL_ICON_BYTES) {
2607
- errors.push(`icons: total distinct SVG markup is ${(total / 1024).toFixed(1)} KiB, exceeding the ${MAX_TOTAL_ICON_BYTES / 1024} KiB per-manifest limit`);
2608
- }
2609
- const needsInlining = logoIcon !== void 0 || iconsSection !== void 0 || fields.some((field) => !field.legacy);
2610
- return { errors, warnings, fields, logoIcon, needsInlining };
2611
- }
2612
- async function readIconFile(root, source) {
2613
- if (isAbsolute(source) || /^[a-z][a-z0-9+.-]*:/i.test(source) || source.includes("\\")) {
2614
- return { error: `${source} must be a path relative to the manifest directory` };
2615
- }
2616
- const candidate = resolve(root, source);
2617
- if (escapes(root, candidate)) return { error: `${source} escapes the package directory` };
2618
- let actual;
2619
- let realRoot;
2620
- try {
2621
- actual = await realpath(candidate);
2622
- realRoot = await realpath(root);
2623
- } catch {
2624
- return { error: `${source} not found` };
2625
- }
2626
- if (escapes(realRoot, actual)) return { error: `${source} escapes the package directory` };
2627
- let bytes;
2628
- try {
2629
- bytes = await readFile(actual);
2630
- } catch {
2631
- return { error: `${source} could not be read (is it a file?)` };
2632
- }
2633
- if (bytes.length > MAX_ICON_BYTES) return { error: `${source}: SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit` };
2634
- const text = decodeUtf8(bytes);
2635
- if (text === null) return { error: `${source} is not valid UTF-8` };
2636
- return { text };
2637
- }
2638
- function escapes(root, candidate) {
2639
- const fromRoot = relative(root, candidate);
2640
- return fromRoot === "" || fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot);
2641
- }
2642
- function iconKey(markup) {
2643
- return createHash("sha256").update(markup, "utf8").digest("hex").slice(0, 12);
3171
+ if (status.state === "Failed" || status.state === "Cancelled") process.exitCode = 1;
3172
+ });
3173
+ filesCmd.command("rm <path>").description("Delete a file or directory").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--recursive", "delete directory contents recursively").action(async (path, options) => {
3174
+ const workspaceId = await resolveWorkspaceId(options);
3175
+ const api = await createApiClient();
3176
+ await api.requestRaw("DELETE", fillPath(files.delete.path, { path: normalizeRemote(path) }), {
3177
+ scopes: [...files.delete.scopes],
3178
+ tokenWorkspaceId: workspaceId,
3179
+ query: { branch: options.branch },
3180
+ headers: options.recursive ? { "X-Delete-Mode": "Deep" } : {}
3181
+ });
3182
+ console.log(`Deleted /${normalizeRemote(path)}.`);
3183
+ });
3184
+ filesCmd.command("mv <fromPath> <toPath>").description("Move or rename a file").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").action(async (fromPath, toPath, options) => {
3185
+ const workspaceId = await resolveWorkspaceId(options);
3186
+ const api = await createApiClient();
3187
+ await call(api, files.update, {
3188
+ params: { path: normalizeRemote(fromPath) },
3189
+ workspaceId,
3190
+ body: { branch: options.branch, path: normalizeRemote(fromPath), toPath: normalizeRemote(toPath) }
3191
+ });
3192
+ console.log(`Moved /${normalizeRemote(fromPath)} \u2192 /${normalizeRemote(toPath)}.`);
3193
+ });
2644
3194
  }
2645
- function inlineIconsIntoDocument(document, resolution) {
2646
- const icons = /* @__PURE__ */ new Map();
2647
- const quoted = (text) => Object.assign(new Scalar(text), { type: Scalar.QUOTE_DOUBLE });
2648
- for (const field of resolution.fields) {
2649
- if (field.markup === void 0) continue;
2650
- const key = iconKey(field.markup);
2651
- icons.set(key, field.markup);
2652
- document.setIn(field.path, quoted(`#${key}`));
2653
- }
2654
- if (resolution.logoIcon !== void 0) {
2655
- const key = iconKey(resolution.logoIcon);
2656
- icons.set(key, resolution.logoIcon);
2657
- document.setIn(["metadata", "icon"], quoted(`#${key}`));
2658
- }
2659
- if (icons.size === 0) {
2660
- if (document.has("icons")) document.delete("icons");
2661
- return;
2662
- }
2663
- const node = new YAMLMap();
2664
- for (const [key, markup] of [...icons.entries()].sort(([a], [b]) => a.localeCompare(b))) {
2665
- node.set(key, Object.assign(new Scalar(markup), { type: Scalar.BLOCK_LITERAL }));
3195
+ async function uploadDirectory(api, workspaceId, localDir, remoteBase, branch) {
3196
+ let count = 0;
3197
+ const entries = await readdir(localDir, { withFileTypes: true });
3198
+ for (const entry of entries) {
3199
+ if (entry.name.startsWith(".git") || entry.name === "node_modules" || entry.name === "__pycache__") continue;
3200
+ const localEntry = join(localDir, entry.name);
3201
+ const remoteEntry = posix.join(remoteBase, entry.name);
3202
+ if (entry.isDirectory()) {
3203
+ count += await uploadDirectory(api, workspaceId, localEntry, remoteEntry, branch);
3204
+ } else if (entry.isFile()) {
3205
+ await uploadWithHeaders(api, workspaceId, remoteEntry, localEntry, { branch, autoExtract: isZipName(entry.name) ? false : void 0 });
3206
+ console.log(` /${remoteEntry}`);
3207
+ count += 1;
3208
+ }
2666
3209
  }
2667
- document.set("icons", node);
2668
- }
2669
- function formatPath(path) {
2670
- return path.reduce((text, segment) => typeof segment === "number" ? `${text}[${segment}]` : text ? `${text}.${segment}` : segment, "");
2671
- }
2672
- function isRecord(value) {
2673
- return !!value && typeof value === "object" && !Array.isArray(value);
3210
+ return count;
2674
3211
  }
2675
-
2676
- // src/vpkg/iconMigration.ts
2677
3212
  var DEFAULT_ICONIFY_API = "https://api.iconify.design";
2678
3213
  function createIconSetLoader(options = {}) {
2679
3214
  const apiBase = (options.apiBase ?? process.env.VERENTIS_ICONIFY_API ?? DEFAULT_ICONIFY_API).replace(/\/+$/, "");
@@ -2848,6 +3383,178 @@ function registerIcons(program2) {
2848
3383
  function collect(value, previous) {
2849
3384
  return [...previous, value];
2850
3385
  }
3386
+
3387
+ // src/templates/theme-css.ts
3388
+ var THEME_CSS = `/*
3389
+ * Workspace theme. Installing this package replaces the workspace theme (/.theme/theme.css), so it lists
3390
+ * every token. Edit any value (any CSS colour syntax works). Light values live in :root and dark values
3391
+ * in .dark. Allowed: no @import, url() only for data:image/\u2026 or /_theme/<asset>, no expression().
3392
+ */
3393
+
3394
+ :root {
3395
+ --background: oklch(1 0 0);
3396
+ --foreground: oklch(0.145 0 0);
3397
+ --card: oklch(1 0 0);
3398
+ --card-foreground: oklch(0.145 0 0);
3399
+ --popover: oklch(1 0 0);
3400
+ --popover-foreground: oklch(0.145 0 0);
3401
+ --primary: oklch(0.48 0.13 40);
3402
+ --primary-hover: oklch(0.42 0.13 40);
3403
+ --primary-foreground: oklch(1 0 0);
3404
+ --secondary: oklch(0.955 0.010 82.6);
3405
+ --secondary-foreground: oklch(0.270 0.012 55.8);
3406
+ --muted: oklch(0.955 0.010 82.6);
3407
+ --muted-foreground: oklch(0.478 0.024 69.7);
3408
+ --accent: oklch(0.941 0.014 82.6);
3409
+ --accent-foreground: oklch(0.270 0.012 55.8);
3410
+ --destructive: oklch(0.489 0.161 32.8);
3411
+ --destructive-foreground: oklch(0.951 0.017 84.6);
3412
+ --warning: oklch(0.714 0.109 78.1);
3413
+ --warning-foreground: oklch(0.270 0.012 55.8);
3414
+ --border: oklch(0.270 0.012 55.8 / 14%);
3415
+ --input: oklch(0.270 0.012 55.8 / 22%);
3416
+ --ring: var(--primary);
3417
+
3418
+ --brand: var(--primary);
3419
+ --brand-foreground: var(--primary-foreground);
3420
+ --brand-soft: oklch(0.58 0.13 45);
3421
+ --brand-rust: oklch(0.58 0.13 45);
3422
+ --brand-mustard: oklch(0.75 0.13 75);
3423
+ --brand-olive: oklch(0.62 0.08 120);
3424
+
3425
+ --ink-band: oklch(0.270 0.012 55.8);
3426
+ --ink-band-foreground: oklch(0.951 0.017 84.6);
3427
+ --ink-band-muted: oklch(0.951 0.017 84.6 / 55%);
3428
+ --ink-band-line: oklch(0.951 0.017 84.6 / 16%);
3429
+
3430
+ --field-clay: var(--brand-rust);
3431
+ --field-ochre: var(--brand-mustard);
3432
+ --field-sage: var(--brand-olive);
3433
+ --field-slate: oklch(0.480 0.036 228);
3434
+
3435
+ --chart-1: var(--brand);
3436
+ --chart-2: oklch(0.270 0.012 55.8);
3437
+ --chart-3: var(--field-clay);
3438
+ --chart-4: var(--field-sage);
3439
+ --chart-5: var(--field-slate);
3440
+
3441
+ --sidebar: oklch(0.270 0.012 55.8);
3442
+ --sidebar-foreground: oklch(0.951 0.017 84.6);
3443
+ --sidebar-primary: oklch(0.951 0.017 84.6);
3444
+ --sidebar-primary-foreground: oklch(0.270 0.012 55.8);
3445
+ --sidebar-accent: oklch(0.951 0.017 84.6 / 8%);
3446
+ --sidebar-accent-foreground: oklch(0.951 0.017 84.6);
3447
+ --sidebar-border: oklch(0.951 0.017 84.6 / 16%);
3448
+ --sidebar-ring: oklch(0.488 0.126 35.4);
3449
+
3450
+ --radius: 0rem;
3451
+ --spacing: 0.25rem;
3452
+ --tracking-normal: 0em;
3453
+
3454
+ --shadow-2xs: 0 0 0 0 transparent;
3455
+ --shadow-xs: 0 0 0 0 transparent;
3456
+ --shadow-sm: 0 0 0 0 transparent;
3457
+ --shadow: 0 0 0 0 transparent;
3458
+ --shadow-md: 6px 6px 0 0 oklch(0.270 0.012 55.8 / 12%);
3459
+ --shadow-lg: 8px 8px 0 0 oklch(0.270 0.012 55.8 / 12%);
3460
+ --shadow-xl: 8px 8px 0 0 oklch(0.270 0.012 55.8 / 16%);
3461
+ --shadow-2xl: 10px 10px 0 0 oklch(0.270 0.012 55.8 / 18%);
3462
+
3463
+ /* Compatibility scale for existing workspace brand utilities. */
3464
+ --brand-50: oklch(0.977 0.011 84.6);
3465
+ --brand-100: oklch(0.951 0.017 84.6);
3466
+ --brand-200: oklch(0.898 0.029 82.6);
3467
+ --brand-300: oklch(0.785 0.071 60);
3468
+ --brand-400: oklch(0.665 0.106 48.4);
3469
+ --brand-500: oklch(0.548 0.133 37.9);
3470
+ --brand-600: oklch(0.488 0.126 35.4);
3471
+ --brand-700: oklch(0.430 0.112 34);
3472
+ --brand-800: oklch(0.365 0.089 33);
3473
+ --brand-900: oklch(0.310 0.061 31);
3474
+ --brand-950: oklch(0.270 0.012 55.8);
3475
+ --brand-hover: oklch(0.430 0.112 34);
3476
+ --brand-soft-foreground: var(--foreground);
3477
+ --brand-border: oklch(0.270 0.012 55.8 / 22%);
3478
+
3479
+ --ink: var(--ink-band);
3480
+ --ink-foreground: var(--ink-band-foreground);
3481
+
3482
+ --ws-content-max: 100rem;
3483
+ --ws-gutter: clamp(1rem, 2.5vw, 2.5rem);
3484
+ --ws-page-gap: clamp(1.5rem, 3vw, 3rem);
3485
+ --ws-panel-padding: clamp(1rem, 2vw, 1.5rem);
3486
+ --ws-terminal-background: var(--ink-band);
3487
+ --ws-terminal-foreground: var(--ink-band-foreground);
3488
+ --ws-ai-background: var(--card);
3489
+ --ws-ai-foreground: var(--card-foreground);
3490
+ --ws-ai-accent: var(--brand);
3491
+ --ws-file-background: var(--card);
3492
+ --ws-file-selected: var(--secondary);
3493
+ --ws-file-accent: var(--brand);
3494
+ }
3495
+
3496
+ .dark {
3497
+ --background: oklch(0.231 0.010 53);
3498
+ --foreground: oklch(0.951 0.017 84.6);
3499
+ --card: oklch(0.270 0.012 55.8);
3500
+ --card-foreground: oklch(0.951 0.017 84.6);
3501
+ --popover: oklch(0.270 0.012 55.8);
3502
+ --popover-foreground: oklch(0.951 0.017 84.6);
3503
+ --primary: oklch(0.68 0.13 45);
3504
+ --primary-hover: oklch(0.74 0.13 45);
3505
+ --primary-foreground: oklch(0.145 0 0);
3506
+ --secondary: oklch(0.299 0.014 57.7);
3507
+ --secondary-foreground: oklch(0.951 0.017 84.6);
3508
+ --muted: oklch(0.299 0.014 57.7);
3509
+ --muted-foreground: oklch(0.698 0.024 74);
3510
+ --accent: oklch(0.324 0.016 59.1);
3511
+ --accent-foreground: oklch(0.951 0.017 84.6);
3512
+ --destructive: oklch(0.560 0.165 33.2);
3513
+ --destructive-foreground: oklch(0.951 0.017 84.6);
3514
+ --warning: oklch(0.714 0.109 78.1);
3515
+ --warning-foreground: oklch(0.270 0.012 55.8);
3516
+ --border: oklch(0.951 0.017 84.6 / 16%);
3517
+ --input: oklch(0.951 0.017 84.6 / 24%);
3518
+ --ring: var(--primary);
3519
+
3520
+ --brand: var(--primary);
3521
+ --brand-foreground: var(--primary-foreground);
3522
+ --brand-soft: oklch(0.68 0.13 45);
3523
+ --brand-rust: oklch(0.68 0.13 45);
3524
+ --brand-mustard: oklch(0.79 0.12 78);
3525
+ --brand-olive: oklch(0.7 0.08 120);
3526
+
3527
+ --ink-band: oklch(0.270 0.012 55.8);
3528
+ --ink-band-foreground: oklch(0.951 0.017 84.6);
3529
+ --ink-band-muted: oklch(0.951 0.017 84.6 / 55%);
3530
+ --ink-band-line: oklch(0.951 0.017 84.6 / 16%);
3531
+
3532
+ --field-clay: var(--brand-rust);
3533
+ --field-ochre: var(--brand-mustard);
3534
+ --field-sage: var(--brand-olive);
3535
+ --field-slate: oklch(0.480 0.036 228);
3536
+
3537
+ --sidebar: oklch(0.270 0.012 55.8);
3538
+ --sidebar-foreground: oklch(0.951 0.017 84.6);
3539
+ --sidebar-primary: oklch(0.951 0.017 84.6);
3540
+ --sidebar-primary-foreground: oklch(0.270 0.012 55.8);
3541
+ --sidebar-accent: oklch(0.951 0.017 84.6 / 8%);
3542
+ --sidebar-accent-foreground: oklch(0.951 0.017 84.6);
3543
+ --sidebar-border: oklch(0.951 0.017 84.6 / 16%);
3544
+ --sidebar-ring: oklch(0.548 0.133 37.9);
3545
+
3546
+ --shadow-md: 6px 6px 0 0 oklch(0 0 0 / 45%);
3547
+ --shadow-lg: 8px 8px 0 0 oklch(0 0 0 / 50%);
3548
+ --shadow-xl: 8px 8px 0 0 oklch(0 0 0 / 55%);
3549
+ --shadow-2xl: 10px 10px 0 0 oklch(0 0 0 / 60%);
3550
+
3551
+ --brand-hover: oklch(0.605 0.137 40);
3552
+ --brand-soft-foreground: var(--foreground);
3553
+ --brand-border: oklch(0.951 0.017 84.6 / 24%);
3554
+ }
3555
+ `;
3556
+
3557
+ // src/commands/init.ts
2851
3558
  var APP_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
2852
3559
  <rect x="2" y="2" width="28" height="28" rx="7" fill="#475569"/>
2853
3560
  <rect x="8" y="8" width="7" height="7" rx="1.5" fill="#f8fafc"/>
@@ -2862,10 +3569,34 @@ var ENGINE_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 3
2862
3569
  <path d="M16 21h7" fill="none" stroke="#f8fafc" stroke-width="2.5" stroke-linecap="round"/>
2863
3570
  </svg>
2864
3571
  `;
3572
+ var themeLogoSvg = (fill) => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 32">
3573
+ <rect x="0" y="4" width="24" height="24" rx="5" fill="${fill}"/>
3574
+ <rect x="34" y="10" width="120" height="12" rx="3" fill="${fill}"/>
3575
+ </svg>
3576
+ `;
3577
+ var themeMarkSvg = (fill) => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
3578
+ <rect x="4" y="4" width="24" height="24" rx="5" fill="${fill}"/>
3579
+ </svg>
3580
+ `;
3581
+ var THEME_TEMPLATE_FILES = {
3582
+ "theme/theme.css": THEME_CSS,
3583
+ "theme/logo-light.svg": themeLogoSvg("#2B2521"),
3584
+ "theme/logo-dark.svg": themeLogoSvg("#F4EFE6"),
3585
+ "theme/mark-light.svg": themeMarkSvg("#2B2521"),
3586
+ "theme/mark-dark.svg": themeMarkSvg("#F4EFE6"),
3587
+ "theme/favicon.svg": themeMarkSvg("#2B2521")
3588
+ };
2865
3589
  var TEMPLATE_FILES = {
2866
3590
  application: { "icons/app.svg": APP_ICON_SVG },
2867
3591
  engine: { "icons/app.svg": ENGINE_ICON_SVG },
2868
- bundle: {}
3592
+ bundle: {},
3593
+ theme: THEME_TEMPLATE_FILES
3594
+ };
3595
+ var TEMPLATE_BY_TYPE = {
3596
+ Application: "application",
3597
+ ExecutionEngine: "engine",
3598
+ Bundle: "bundle",
3599
+ Theme: "theme"
2869
3600
  };
2870
3601
  var TEMPLATES = {
2871
3602
  application: (name) => `api-version: verentis.io/v1
@@ -2989,27 +3720,75 @@ packaging:
2989
3720
  bundle:
2990
3721
  default-path: /data/${name}
2991
3722
  encryption: none
3723
+ `,
3724
+ theme: (name) => `api-version: verentis.io/v1
3725
+ kind: Theme
3726
+
3727
+ metadata:
3728
+ name: ${name}
3729
+ package-id: ${name}
3730
+ display-name: ${titleCase(name)}
3731
+ description: ""
3732
+ version: 0.1.0
3733
+ author: ""
3734
+ tags: [branding]
3735
+
3736
+ # Marketplace presentation (optional):
3737
+ # marketplace:
3738
+ # logo: ./theme/logo-light.svg
3739
+ # readme: ./README.md
3740
+
3741
+ # A theme replaces the workspace theme (/.theme). Map any of the theme assets to files in this package:
3742
+ # theme.css, background, background.dark, logo.light, logo.dark, mark.light, mark.dark, favicon,
3743
+ # apple-touch-icon (PNG only). Images may be SVG, PNG, JPEG or WebP (1 MiB each, backgrounds 2 MiB,
3744
+ # 4 MiB in total). \`verentis pack\` installs each one at /.theme/<asset>.
3745
+ spec:
3746
+ assets:
3747
+ theme.css: theme/theme.css
3748
+ logo.light: theme/logo-light.svg
3749
+ logo.dark: theme/logo-dark.svg
3750
+ mark.light: theme/mark-light.svg
3751
+ mark.dark: theme/mark-dark.svg
3752
+ favicon: theme/favicon.svg
3753
+ # background: theme/background.jpg
3754
+ # background.dark: theme/background-dark.jpg
3755
+ # apple-touch-icon: theme/apple-touch-icon.png # 180\xD7180 PNG
3756
+
3757
+ packaging:
3758
+ publisher: "" # your publisher name
3759
+ files:
3760
+ - "theme/*"
3761
+ encryption: none # theme assets are public; encryption: required is rejected
2992
3762
  `
2993
3763
  };
3764
+ function resolveInitTemplate(type) {
3765
+ const canonical = packageTypes().canonical(type);
3766
+ const key = canonical ? TEMPLATE_BY_TYPE[canonical] : TEMPLATES[type.toLowerCase()] ? type.toLowerCase() : void 0;
3767
+ if (!key) {
3768
+ const available = Object.keys(TEMPLATES).join(", ");
3769
+ throw new Error(canonical ? `There is no init template for ${canonical} packages yet \u2014 available: ${available}. See the samples/ directory.` : `Unknown package type '${type}' \u2014 available templates: ${available}.`);
3770
+ }
3771
+ return key;
3772
+ }
2994
3773
  function registerInit(program2) {
2995
- program2.command("init [dir]").description("Scaffold a manifest.yaml for a new package").option("--kind <kind>", "application | engine | bundle", "application").option("--name <name>", "package name (defaults to the directory name)").action(async (dir, options) => {
2996
- const template = TEMPLATES[options.kind.toLowerCase()];
2997
- if (!template) throw new Error(`Unknown kind '${options.kind}' \u2014 use application, engine or bundle.`);
3774
+ program2.command("init [dir]").description("Scaffold a manifest.yaml for a new package").option("--type <type>", "package type: application | engine | bundle | theme").option("--kind <kind>", "alias for --type").option("--name <name>", "package name (defaults to the directory name)").action(async (dir, options) => {
3775
+ const templateKey = resolveInitTemplate(options.type ?? options.kind ?? "application");
3776
+ const template = TEMPLATES[templateKey];
2998
3777
  const targetDir = resolve(dir ?? ".");
2999
3778
  await mkdir(targetDir, { recursive: true });
3000
3779
  const name = (options.name ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
3001
3780
  const manifestPath = join(targetDir, "manifest.yaml");
3002
3781
  if (await exists3(manifestPath)) throw new Error(`${manifestPath} already exists.`);
3003
3782
  await writeFile(manifestPath, template(name));
3004
- console.log(`Created ${manifestPath} (kind: ${options.kind}).`);
3005
- for (const [relativePath, content] of Object.entries(TEMPLATE_FILES[options.kind.toLowerCase()] ?? {})) {
3783
+ console.log(`Created ${manifestPath} (type: ${templateKey}).`);
3784
+ for (const [relativePath, content] of Object.entries(TEMPLATE_FILES[templateKey] ?? {})) {
3006
3785
  const path = join(targetDir, relativePath);
3007
3786
  if (await exists3(path)) continue;
3008
3787
  await mkdir(dirname(path), { recursive: true });
3009
3788
  await writeFile(path, content);
3010
3789
  console.log(`Created ${path}.`);
3011
3790
  }
3012
- console.log("Fill in packaging.publisher and packaging.files, then run `verentis pack`.");
3791
+ console.log(templateKey === "theme" ? "Fill in packaging.publisher, replace the placeholder artwork in theme/, then run `verentis pack`." : "Fill in packaging.publisher and packaging.files, then run `verentis pack`.");
3013
3792
  });
3014
3793
  }
3015
3794
  async function exists3(path) {
@@ -3844,14 +4623,22 @@ async function pack(options) {
3844
4623
  overrideApplied = true;
3845
4624
  }
3846
4625
  const kind = normalizeKind(manifest.kind);
3847
- const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
3848
- if (hostedBackendErrors.length > 0) throw new Error(`Invalid manifest: ${hostedBackendErrors.join(" ")}`);
4626
+ const manifestErrors = validatePackageManifestRules(kind, manifest);
4627
+ if (manifestErrors.length > 0) throw new Error(`Invalid manifest: ${manifestErrors.join(" ")}`);
3849
4628
  const dependencyErrors = validateDependencies(manifest.spec);
3850
4629
  if (dependencyErrors.length > 0) throw new Error(`Invalid dependencies: ${dependencyErrors.join(" ")}`);
3851
- const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
3852
- if (launchKindError) throw new Error(`Invalid manifest: ${launchKindError}.`);
3853
4630
  const marketplaceErrors = validateMarketplaceSection(manifest.marketplace);
3854
4631
  if (marketplaceErrors.length > 0) throw new Error(`Invalid marketplace section: ${marketplaceErrors.join(" ")}`);
4632
+ const typeValidator = validatorForKind(kind);
4633
+ const payloadErrors = await typeValidator?.validatePayload?.(projectDir, manifest) ?? [];
4634
+ if (payloadErrors.length > 0) throw new Error(`Invalid ${kind} payload:
4635
+ ${payloadErrors.join("\n ")}`);
4636
+ const authoredManifest = manifest;
4637
+ manifest = typeValidator?.expandForPack ? typeValidator.expandForPack(manifest) : manifest;
4638
+ const normalizedSpec = normalizeDependencies(manifest.spec);
4639
+ if (normalizedSpec !== manifest.spec) manifest = { ...manifest, spec: normalizedSpec };
4640
+ if (manifest !== authoredManifest) overrideApplied = true;
4641
+ const expandedInstall = expandedInstallSources(authoredManifest, manifest);
3855
4642
  const packageId = manifest.metadata["package-id"].toLowerCase();
3856
4643
  const name = manifest.metadata.name.toLowerCase();
3857
4644
  const publisher = options.publisher.toLowerCase();
@@ -3860,6 +4647,10 @@ async function pack(options) {
3860
4647
  validatePackageName(publisher, "publisher name");
3861
4648
  const version = manifest.metadata.version;
3862
4649
  const payloadFiles = await resolvePayloadFiles(projectDir, manifestPath, manifest);
4650
+ const missingSources = expandedInstall.filter((from) => !payloadFiles.some((file) => toEntryPath2(file) === from));
4651
+ if (missingSources.length > 0) {
4652
+ throw new Error(`packaging.files does not include ${missingSources.join(", ")} declared by spec.assets.`);
4653
+ }
3863
4654
  const templatePlan = await createTemplatePlan(projectDir, manifest, payloadFiles);
3864
4655
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
3865
4656
  const packedManifest = stripTemplatePackagingFields(manifest);
@@ -3962,6 +4753,13 @@ async function pack(options) {
3962
4753
  await rm(staging, { recursive: true, force: true });
3963
4754
  }
3964
4755
  }
4756
+ function expandedInstallSources(authored, packed) {
4757
+ const installOf = (manifest) => {
4758
+ const install = manifest.spec?.install;
4759
+ return Array.isArray(install) ? install : [];
4760
+ };
4761
+ return installOf(packed).slice(installOf(authored).length).map((directive) => directive.from).filter((from) => typeof from === "string");
4762
+ }
3965
4763
  function sha256Hex(data) {
3966
4764
  return createHash("sha256").update(data).digest("hex");
3967
4765
  }
@@ -4061,6 +4859,7 @@ function registerPack(program2) {
4061
4859
  program2.command("pack [dir]").description("Build a signed .vpkg from a project directory").option("--manifest <path>", "manifest path (default: auto-detected in the project directory)").option("--publisher <name>", "publisher name (default: packaging.publisher in the manifest)").option("--name <name>", "override metadata.package-id").option("--env <name>", "merge a per-environment overlay (environments/<name>.yaml) before packing").option("--overlay <path>", "merge an explicit overlay file before packing (wins over --env)").option("--set-version <version>", "override metadata.version (e.g. a CI-derived build number)").option("--bump-version", "increment metadata.version.patch and update the manifest").option("--bump", "alias for --bump-version").option("--out <dir>", "output directory (default: the project directory)").option("--key <name>", "signing key name (default: the configured default key)").option("--no-sign", "produce an unsigned package").option("--encrypt", "seal the payload (AES-256-GCM); requires at least one recipient").option("--recipient <id=base64key...>", "additional X25519 recipient (repeatable)", collectRecipients, []).action(async (dir, options) => {
4062
4860
  const projectDir = resolve(dir ?? ".");
4063
4861
  const manifestPath = options.manifest ? resolve(options.manifest) : await findManifest(projectDir);
4862
+ await ensurePackageTypeKnown((await readManifestDocument(manifestPath)).kind);
4064
4863
  const manifest = await loadManifest(manifestPath);
4065
4864
  const publisher = options.publisher ?? manifest.packaging?.publisher;
4066
4865
  if (!publisher) {
@@ -4185,15 +4984,15 @@ function registerPackage(program2) {
4185
4984
  pkgCmd.command("update <ref>").description("Update package metadata").option("--display-name <displayName>").option("--description <description>").option("--icon <icon>").option("--categories <category...>", "category list (replaces existing)").action(async (ref, options) => {
4186
4985
  const api = await createApiClient();
4187
4986
  const { package: pkg } = await resolvePackageRef(api, ref);
4188
- const current = await call(api, marketplace.getPackage, { params: { id: pkg.id } });
4987
+ const current2 = await call(api, marketplace.getPackage, { params: { id: pkg.id } });
4189
4988
  await call(api, marketplace.updatePackage, {
4190
4989
  params: { id: pkg.id },
4191
4990
  body: {
4192
4991
  id: pkg.id,
4193
- displayName: options.displayName ?? current.displayName,
4194
- description: options.description ?? current.description ?? null,
4195
- icon: options.icon ?? current.icon ?? null,
4196
- categories: options.categories ?? current.categories ?? []
4992
+ displayName: options.displayName ?? current2.displayName,
4993
+ description: options.description ?? current2.description ?? null,
4994
+ icon: options.icon ?? current2.icon ?? null,
4995
+ categories: options.categories ?? current2.categories ?? []
4197
4996
  }
4198
4997
  });
4199
4998
  console.log(`Package ${ref} updated.`);
@@ -4419,18 +5218,18 @@ function registerPublisher(program2) {
4419
5218
  throw new Error("No publisher fields supplied. Pass --display-name, --description, --website or --email.");
4420
5219
  }
4421
5220
  const api = await createApiClient();
4422
- const current = await requireMyPublisher(api);
5221
+ const current2 = await requireMyPublisher(api);
4423
5222
  await call(api, marketplace.updatePublisher, {
4424
- params: { id: current.id },
5223
+ params: { id: current2.id },
4425
5224
  body: {
4426
- id: current.id,
4427
- displayName: options.displayName ?? current.displayName,
4428
- description: options.description ?? current.description ?? null,
4429
- websiteUrl: options.website ?? current.websiteUrl ?? null,
4430
- contactEmail: options.email ?? current.contactEmail ?? null
5225
+ id: current2.id,
5226
+ displayName: options.displayName ?? current2.displayName,
5227
+ description: options.description ?? current2.description ?? null,
5228
+ websiteUrl: options.website ?? current2.websiteUrl ?? null,
5229
+ contactEmail: options.email ?? current2.contactEmail ?? null
4431
5230
  }
4432
5231
  });
4433
- console.log(`Publisher '${current.name}' updated.`);
5232
+ console.log(`Publisher '${current2.name}' updated.`);
4434
5233
  });
4435
5234
  const logoCmd = publisherCmd.command("logo").description("Manage your publisher logo");
4436
5235
  logoCmd.command("set <file>").description("Upload a PNG, JPEG, WebP or SVG publisher logo (maximum 1 MiB)").action(async (file) => {
@@ -4563,6 +5362,8 @@ function registerRegistry(program2) {
4563
5362
  ${contents.digestErrors.join("\n ")}`);
4564
5363
  }
4565
5364
  const api = await createApiClient();
5365
+ const config = await loadConfig();
5366
+ await refreshPackageTypes(requireApiUrl(config), { insecure: config.insecure });
4566
5367
  const publisher = await requireMyPublisher(api);
4567
5368
  if (publisher.name !== contents.metadata.publisher) {
4568
5369
  throw new Error(`Package declares publisher '${contents.metadata.publisher}' but you are '${publisher.name}'.`);
@@ -4604,11 +5405,13 @@ function registerRegistry(program2) {
4604
5405
  await pipeline(Readable.fromWeb(res.body), createWriteStream(outPath));
4605
5406
  console.log(`Downloaded ${ref}@${effectiveVersion} \u2192 ${outPath}`);
4606
5407
  });
4607
- program2.command("search [text]").description("Search the marketplace catalog").option("--kind <kind>", "Application | ExecutionEngine | Bundle").action(async (text, options) => {
5408
+ program2.command("search [text]").description("Search the marketplace catalog").option("--type <type>", `package type: ${packageTypes().typeNames().join(" | ")}`).option("--kind <kind>", "alias for --type").action(async (text, options) => {
4608
5409
  const api = await createApiClient();
5410
+ const requested = options.type ?? options.kind;
5411
+ const type = requested ? packageTypes().canonical(requested) ?? requested : void 0;
4609
5412
  const page = await api.request("GET", "/v1/packages", {
4610
5413
  scopes: [SCOPES.packageReadAll],
4611
- query: { SearchText: text, Kind: options.kind, PageNo: 1, PageSize: 50 }
5414
+ query: { SearchText: text, Kind: type, PageNo: 1, PageSize: 50 }
4612
5415
  });
4613
5416
  const items = page.data ?? page.items ?? [];
4614
5417
  if (items.length === 0) {
@@ -4662,7 +5465,7 @@ function registerRegistry(program2) {
4662
5465
  );
4663
5466
  const existing = pageItems(page).find((installation) => installation.status !== "Uninstalled");
4664
5467
  const nodeScopes = [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate];
4665
- const consentScopes = pkg.kind === "Application" ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
5468
+ const consentScopes = isApplicationProfile(pkg.type ?? pkg.kind) ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
4666
5469
  if (existing) {
4667
5470
  if (options.path && existing.installPath !== options.path.replace(/^\/+|\/+$/g, "")) {
4668
5471
  throw new Error(`${ref} is already installed at '${existing.installPath}'. Uninstall it before moving it.`);
@@ -4779,11 +5582,11 @@ function getCliVersion() {
4779
5582
  }
4780
5583
  function readVersion() {
4781
5584
  const candidates = ["../package.json", "../../package.json"];
4782
- for (const relative5 of candidates) {
5585
+ for (const relative6 of candidates) {
4783
5586
  try {
4784
- const raw = readFileSync(fileURLToPath(new URL(relative5, import.meta.url)), "utf8");
5587
+ const raw = readFileSync(fileURLToPath(new URL(relative6, import.meta.url)), "utf8");
4785
5588
  const pkg = JSON.parse(raw);
4786
- if (pkg.version && (relative5 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
5589
+ if (pkg.version && (relative6 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
4787
5590
  } catch {
4788
5591
  }
4789
5592
  }
@@ -4839,10 +5642,10 @@ var SUPPRESSED_COMMANDS = /* @__PURE__ */ new Set(["update", "__update-check", "
4839
5642
  async function notifyOnExit(argv) {
4840
5643
  if (isUpdateCheckSuppressed(argv)) return;
4841
5644
  try {
4842
- const current = getCliVersion();
5645
+ const current2 = getCliVersion();
4843
5646
  const state = await readUpdateState();
4844
- if (state?.latestVersion && isNewerVersion(state.latestVersion, current)) {
4845
- printUpdateNotice(current, state.latestVersion);
5647
+ if (state?.latestVersion && isNewerVersion(state.latestVersion, current2)) {
5648
+ printUpdateNotice(current2, state.latestVersion);
4846
5649
  }
4847
5650
  if (isStale(state)) spawnBackgroundRefresh();
4848
5651
  } catch {
@@ -4870,9 +5673,9 @@ function isEnvDisabled() {
4870
5673
  const explicit = process.env.VERENTIS_UPDATE_CHECK;
4871
5674
  return explicit !== void 0 && off.has(explicit.toLowerCase());
4872
5675
  }
4873
- function printUpdateNotice(current, latest) {
5676
+ function printUpdateNotice(current2, latest) {
4874
5677
  const message = [
4875
- `Update available ${current} \u2192 ${latest}`,
5678
+ `Update available ${current2} \u2192 ${latest}`,
4876
5679
  "Run `verentis update` to install the latest version."
4877
5680
  ];
4878
5681
  const width = Math.max(...message.map((line) => line.length));
@@ -4899,14 +5702,14 @@ function spawnBackgroundRefresh() {
4899
5702
  // src/commands/update.ts
4900
5703
  function registerUpdate(program2) {
4901
5704
  program2.command("update").description("Update the Verentis CLI to the latest published version").option("--check", "report whether a newer version is available without installing").option("--to <version>", "install a specific version instead of the latest").action(async (options) => {
4902
- const current = getCliVersion();
5705
+ const current2 = getCliVersion();
4903
5706
  const target = await resolveTarget(options.to);
4904
5707
  if (options.check) {
4905
- reportCheck(current, target, Boolean(options.to));
5708
+ reportCheck(current2, target, Boolean(options.to));
4906
5709
  return;
4907
5710
  }
4908
- if (!options.to && !isNewerVersion(target, current)) {
4909
- console.log(`Already on the latest version (${current}).`);
5711
+ if (!options.to && !isNewerVersion(target, current2)) {
5712
+ console.log(`Already on the latest version (${current2}).`);
4910
5713
  return;
4911
5714
  }
4912
5715
  const install = resolveInstallCommand(`${PACKAGE_NAME}@${target}`);
@@ -4917,7 +5720,7 @@ Update manually, for example:
4917
5720
  npm install -g ${PACKAGE_NAME}@${target}`
4918
5721
  );
4919
5722
  }
4920
- console.log(`Updating ${PACKAGE_NAME}: ${current} \u2192 ${target}`);
5723
+ console.log(`Updating ${PACKAGE_NAME}: ${current2} \u2192 ${target}`);
4921
5724
  console.log(`$ ${install.command} ${install.args.join(" ")}`);
4922
5725
  const result = spawnSync(install.command, install.args, { stdio: "inherit" });
4923
5726
  if (result.error) {
@@ -4952,17 +5755,17 @@ async function resolveTarget(requested) {
4952
5755
  });
4953
5756
  return latest;
4954
5757
  }
4955
- function reportCheck(current, target, pinned) {
5758
+ function reportCheck(current2, target, pinned) {
4956
5759
  if (pinned) {
4957
- console.log(`Current version: ${current}`);
5760
+ console.log(`Current version: ${current2}`);
4958
5761
  console.log(`Requested version: ${target}`);
4959
5762
  return;
4960
5763
  }
4961
- if (isNewerVersion(target, current)) {
4962
- console.log(`A new version is available: ${current} \u2192 ${target}`);
5764
+ if (isNewerVersion(target, current2)) {
5765
+ console.log(`A new version is available: ${current2} \u2192 ${target}`);
4963
5766
  console.log("Run `verentis update` to install it.");
4964
5767
  } else {
4965
- console.log(`You are on the latest version (${current}).`);
5768
+ console.log(`You are on the latest version (${current2}).`);
4966
5769
  }
4967
5770
  }
4968
5771
  function resolveInstallCommand(spec) {
@@ -5084,7 +5887,7 @@ function registerUser(program2) {
5084
5887
  });
5085
5888
  }
5086
5889
  function registerValidate(program2) {
5087
- program2.command("validate [pathOrDir]").description("Validate an engine/app/agent/skill/tool/bundle/policy manifest").option("--env <name>", "merge a per-environment overlay (environments/<name>.yaml) before validating").option("--overlay <path>", "merge an explicit overlay file before validating (wins over --env)").action(async (pathOrDir, options) => {
5890
+ program2.command("validate [pathOrDir]").description("Validate a package manifest (any registered package type) or a policy manifest").option("--env <name>", "merge a per-environment overlay (environments/<name>.yaml) before validating").option("--overlay <path>", "merge an explicit overlay file before validating (wins over --env)").action(async (pathOrDir, options) => {
5088
5891
  const target = resolve(pathOrDir ?? ".");
5089
5892
  const info = await stat(target).catch(() => null);
5090
5893
  const manifestPath = info?.isDirectory() ? await findManifest(target) : target;
@@ -5092,7 +5895,10 @@ function registerValidate(program2) {
5092
5895
  const base = await readManifestDocument(manifestPath);
5093
5896
  const overlayPath = resolveOverlayPath(dirname(manifestPath), { env: options.env, overlay: options.overlay });
5094
5897
  const manifest = overlayPath ? applyOverlay(base, await loadOverlay(overlayPath)) : base;
5898
+ if (!NON_PACKAGE_KINDS.includes(manifest.kind)) await ensurePackageTypeKnown(manifest.kind);
5095
5899
  const issues = validateManifest(manifest);
5900
+ const payloadErrors = await validatorForKind(manifest.kind)?.validatePayload?.(dirname(manifestPath), manifest) ?? [];
5901
+ issues.push(...payloadErrors.map((message) => ({ level: "error", message })));
5096
5902
  try {
5097
5903
  const payloadFiles = await resolvePayloadFiles(dirname(manifestPath), manifestPath, manifest);
5098
5904
  const templateInspection = await inspectPackagingTemplates(dirname(manifestPath), manifest, payloadFiles);