@verentis/cli 0.2.30 → 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
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import { mkdir, stat, writeFile, readFile, readdir, glob, realpath, mkdtemp, rm, access } from 'fs/promises';
3
+ import { mkdir, stat, readFile, writeFile, readdir, glob, realpath, mkdtemp, rm, access } from 'fs/promises';
4
4
  import { tmpdir, homedir } from 'os';
5
5
  import { resolve, basename, dirname, posix, join, isAbsolute, relative, sep, extname } from 'path';
6
6
  import { execFile, spawn, spawnSync } from 'child_process';
@@ -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";
@@ -535,7 +536,9 @@ var files = {
535
536
  workspaceBound: true
536
537
  }),
537
538
  update: e({ method: "PUT", path: "/v1/files/{path}", scopes: [NODE.nodeUpdate, NODE.fileRead, NODE.journalCreate], workspaceBound: true }),
538
- delete: e({ method: "DELETE", path: "/v1/files/{path}", scopes: [NODE.fileDelete], workspaceBound: true })
539
+ delete: e({ method: "DELETE", path: "/v1/files/{path}", scopes: [NODE.fileDelete], workspaceBound: true }),
540
+ /** Status of a background archive import started by an archive upload (202 + Location). */
541
+ archiveImportStatus: e({ method: "GET", path: "/v1/archive-imports/{id}", scopes: [NODE.fileRead], workspaceBound: true })
539
542
  };
540
543
  var execution = {
541
544
  request: e({ method: "POST", path: "/v1/executions", scopes: [EXECUTION.run, ...ENGINE_DEFAULT_PERMISSIONS], workspaceBound: true }),
@@ -1039,717 +1042,1479 @@ function contextEnv(context, contextPath) {
1039
1042
  VERENTIS_TIMEOUT: String(context.execution.timeout)
1040
1043
  };
1041
1044
  }
1042
- var KIND_MAP = {
1043
- application: "Application",
1044
- executionengine: "ExecutionEngine",
1045
- agent: "Agent",
1046
- skill: "Skill",
1047
- tool: "Tool",
1048
- 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
+ ]
1049
1160
  };
1050
- function normalizeKind(kind) {
1051
- const mapped = KIND_MAP[kind.replace(/[^a-z]/gi, "").toLowerCase()];
1052
- if (!mapped) throw new Error(`Unsupported manifest kind '${kind}' \u2014 expected Application, ExecutionEngine, Agent, Skill, Tool or Bundle.`);
1053
- return mapped;
1054
- }
1055
- function validateLaunchManifestKind(kind, spec) {
1056
- if (kind === "Application" || !spec || typeof spec !== "object" || Array.isArray(spec)) return void 0;
1057
- if (!Object.prototype.hasOwnProperty.call(spec, "launch")) return void 0;
1058
- return "spec.launch is only supported for Application manifests";
1059
- }
1060
- async function loadManifest(path) {
1061
- const text = await readFile(path, "utf8");
1062
- const manifest = parse(text);
1063
- if (!manifest || typeof manifest !== "object") throw new Error(`Failed to parse manifest at ${path}.`);
1064
- if (!manifest.kind) throw new Error(`Manifest at ${path} is missing 'kind'.`);
1065
- if (!manifest.metadata?.name) throw new Error(`Manifest at ${path} is missing 'metadata.name'.`);
1066
- if (!manifest.metadata?.["package-id"]) throw new Error(`Manifest at ${path} is missing 'metadata.package-id'.`);
1067
- if (!manifest.metadata?.version) throw new Error(`Manifest at ${path} is missing 'metadata.version'.`);
1068
- validatePackageName(manifest.metadata["package-id"], "package ID");
1069
- const kind = normalizeKind(manifest.kind);
1070
- const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
1071
- if (hostedBackendErrors.length > 0) {
1072
- throw new Error(`Invalid manifest at ${path}: ${hostedBackendErrors.join(" ")}`);
1073
- }
1074
- const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
1075
- if (launchKindError) throw new Error(`Invalid manifest at ${path}: ${launchKindError}.`);
1076
- const collaborationErrors = validateNativeCollaborationSection(kind, manifest.spec);
1077
- if (collaborationErrors.length > 0) {
1078
- throw new Error(`Invalid manifest at ${path}: ${collaborationErrors.join(" ")}`);
1079
- }
1080
- const messageErrors = validateMessageChannelsSection(kind, manifest.spec);
1081
- if (messageErrors.length > 0) {
1082
- throw new Error(`Invalid manifest at ${path}: ${messageErrors.join(" ")}`);
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
+ }
1083
1187
  }
1084
- const actorErrors = validateActorSection(kind, manifest.spec);
1085
- if (actorErrors.length > 0) {
1086
- throw new Error(`Invalid manifest at ${path}: ${actorErrors.join(" ")}`);
1188
+ find(type) {
1189
+ if (typeof type !== "string" || type.trim().length === 0) return void 0;
1190
+ return this.byKey.get(normalizePackageTypeKey(type));
1087
1191
  }
1088
- const operationErrors = validateWopiOperationsSection(manifest.spec);
1089
- if (operationErrors.length > 0) {
1090
- throw new Error(`Invalid manifest at ${path}: ${operationErrors.join(" ")}`);
1192
+ get(type) {
1193
+ const descriptor = this.find(type);
1194
+ if (!descriptor) throw new Error(unknownPackageTypeMessage(type, this));
1195
+ return descriptor;
1091
1196
  }
1092
- const dependencyErrors = validateDependencies(manifest.spec);
1093
- if (dependencyErrors.length > 0) {
1094
- throw new Error(`Invalid manifest at ${path}: ${dependencyErrors.join(" ")}`);
1197
+ canonical(type) {
1198
+ return this.find(type)?.type;
1095
1199
  }
1096
- const splashErrors = validateApplicationSplashSection(kind, manifest.spec);
1097
- if (splashErrors.length > 0) {
1098
- throw new Error(`Invalid manifest at ${path}: ${splashErrors.join(" ")}`);
1200
+ typeNames() {
1201
+ return this.types.map((t) => t.type);
1099
1202
  }
1100
- const marketplaceErrors = validateMarketplaceSection(manifest.marketplace);
1101
- if (marketplaceErrors.length > 0) {
1102
- throw new Error(`Invalid marketplace section in ${path}: ${marketplaceErrors.join(" ")}`);
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);
1103
1224
  }
1104
- return manifest;
1105
1225
  }
1106
- function bumpPatchVersion(version) {
1107
- const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
1108
- if (!match) {
1109
- throw new Error(`Cannot bump version '${version}' \u2014 expected a semantic version like 1.2.3.`);
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;
1110
1232
  }
1111
- return `${match[1]}.${match[2]}.${Number(match[3]) + 1}`;
1112
1233
  }
1113
- async function bumpManifestPatchVersion(path, currentVersion) {
1114
- const text = await readFile(path, "utf8");
1115
- const nextVersion = bumpPatchVersion(currentVersion);
1116
- const document = parseDocument(text);
1117
- if (document.errors.length > 0) {
1118
- throw new Error(`Failed to parse manifest at ${path}: ${document.errors.map((error) => error.message).join(" ")}`);
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;
1119
1261
  }
1120
- document.setIn(["metadata", "version"], nextVersion);
1121
- await writeFile(path, document.toString());
1122
- return nextVersion;
1123
1262
  }
1124
- function validateApplicationSplashSection(kind, spec) {
1125
- if (kind !== "Application" || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1126
- const applicationSpec = spec;
1127
- const errors = [];
1128
- const splash = applicationSpec.splash;
1129
- if (splash !== void 0 && (typeof splash !== "string" || splash.trim().length === 0)) {
1130
- errors.push("spec.splash must be a non-empty URL string.");
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;
1131
1294
  }
1132
- const entryPoints = applicationSpec["entry-points"];
1133
- if (Array.isArray(entryPoints)) {
1134
- entryPoints.forEach((value, index) => {
1135
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
1136
- const entryPointSplash = value.splash;
1137
- if (entryPointSplash !== void 0 && (typeof entryPointSplash !== "string" || entryPointSplash.trim().length === 0)) {
1138
- errors.push(`spec.entry-points[${index}].splash must be a non-empty URL string.`);
1139
- }
1140
- });
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;
1141
1305
  }
1142
- return errors;
1143
1306
  }
1144
- function validateHostedBackendDeclaration(kind, spec) {
1145
- if (kind === "Application" || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1146
- const value = spec;
1147
- const capabilities = value.capabilities;
1148
- const requestsCapability = Array.isArray(capabilities) && capabilities.some((capability) => typeof capability === "string" && capability.trim().toLowerCase() === "hosted-backend");
1149
- if (requestsCapability || Object.prototype.hasOwnProperty.call(value, "hosted-backend")) {
1150
- return [`${kind} packages cannot declare a hosted backend.`];
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
+ });
1151
1336
  }
1152
- return [];
1337
+ bindings(spec["mime-types"], ["spec", "mime-types"]);
1338
+ bindings(spec["file-types"], ["spec", "file-types"]);
1339
+ return fields;
1153
1340
  }
1154
- var MESSAGE_CHANNEL_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
1155
- var MAX_MESSAGE_CHANNELS = 32;
1156
- function validateMessageChannelsSection(kind, spec) {
1157
- if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "messages")) return [];
1158
- if (kind !== "Application") return ["spec.messages is only supported for Application manifests."];
1159
- const messages = spec.messages;
1160
- if (!Array.isArray(messages)) return ["spec.messages must be a list of { channel, description, schema? }."];
1161
- if (messages.length > MAX_MESSAGE_CHANNELS) return [`spec.messages declares more than ${MAX_MESSAGE_CHANNELS} channels.`];
1341
+ async function resolveManifestIcons(manifest, manifestDir) {
1162
1342
  const errors = [];
1163
- const seen = /* @__PURE__ */ new Set();
1164
- messages.forEach((value, index) => {
1165
- const path = `spec.messages[${index}]`;
1166
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1167
- errors.push(`${path} must be an object with channel and description.`);
1168
- return;
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());
1169
1357
  }
1170
- const { channel, description, schema } = value;
1171
- if (typeof channel !== "string" || !MESSAGE_CHANNEL_PATTERN.test(channel)) {
1172
- errors.push(`${path}.channel must match ${MESSAGE_CHANNEL_PATTERN.source}.`);
1173
- } else if (seen.has(channel)) {
1174
- errors.push(`${path}.channel '${channel}' is declared more than once.`);
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");
1175
1377
  } else {
1176
- seen.add(channel);
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
+ }
1177
1387
  }
1178
- if (typeof description !== "string" || description.trim().length === 0) {
1179
- errors.push(`${path}.description is required so agents know when to use the channel.`);
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;
1180
1393
  }
1181
- if (schema !== void 0 && (!schema || typeof schema !== "object" || Array.isArray(schema))) {
1182
- errors.push(`${path}.schema must be a JSON Schema object.`);
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;
1183
1400
  }
1184
- });
1185
- return errors;
1186
- }
1187
- var ACTOR_SURFACE_KINDS = ["app-backend", "mcp", "native-collaboration", "document", "raw-file"];
1188
- var ACTOR_FILE_KINDS = /* @__PURE__ */ new Set(["native-collaboration", "document", "raw-file"]);
1189
- var MAX_ACTOR_SURFACES = 16;
1190
- function validateActorSection(kind, spec) {
1191
- if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "actor")) return [];
1192
- if (kind !== "Application") return ["spec.actor is only supported for Application manifests."];
1193
- const applicationSpec = spec;
1194
- const actor = applicationSpec.actor;
1195
- if (!actor || typeof actor !== "object" || Array.isArray(actor)) {
1196
- return ["spec.actor must be an object with live-channel and/or surfaces."];
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 });
1197
1413
  }
1198
- const { "live-channel": liveChannel, surfaces } = actor;
1199
- const errors = [];
1200
- if (liveChannel !== void 0) {
1201
- const declared = Array.isArray(applicationSpec.messages) && applicationSpec.messages.some((m) => m && typeof m === "object" && m.channel === liveChannel);
1202
- if (typeof liveChannel !== "string" || !declared) {
1203
- errors.push("spec.actor.live-channel must name a channel declared in spec.messages.");
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);
1204
1425
  }
1205
1426
  }
1206
- if (surfaces === void 0) {
1207
- if (liveChannel === void 0) errors.push("spec.actor must declare live-channel and/or surfaces.");
1208
- return errors;
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`);
1209
1430
  }
1210
- if (!Array.isArray(surfaces) || surfaces.length === 0) {
1211
- errors.push("spec.actor.surfaces must be a non-empty list of { kind, ... }.");
1212
- return errors;
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` };
1213
1437
  }
1214
- if (surfaces.length > MAX_ACTOR_SURFACES) {
1215
- errors.push(`spec.actor.surfaces declares more than ${MAX_ACTOR_SURFACES} surfaces.`);
1216
- return errors;
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` };
1217
1447
  }
1218
- const appTools = declaredTools(applicationSpec);
1219
- surfaces.forEach((value, index) => {
1220
- const path = `spec.actor.surfaces[${index}]`;
1221
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1222
- errors.push(`${path} must be an object with a kind.`);
1223
- return;
1224
- }
1225
- const surface = value;
1226
- const surfaceKind = surface.kind;
1227
- if (typeof surfaceKind !== "string" || !ACTOR_SURFACE_KINDS.includes(surfaceKind)) {
1228
- errors.push(`${path}.kind must be one of ${ACTOR_SURFACE_KINDS.join(", ")}.`);
1229
- return;
1230
- }
1231
- const mimeTypes = surface["mime-types"];
1232
- const extensions = surface.extensions;
1233
- for (const [name, list] of [["mime-types", mimeTypes], ["extensions", extensions]]) {
1234
- if (list !== void 0 && (!Array.isArray(list) || list.some((item) => typeof item !== "string" || item.trim().length === 0))) {
1235
- errors.push(`${path}.${name} must be a list of non-empty strings.`);
1236
- }
1237
- }
1238
- const filters = (Array.isArray(mimeTypes) ? mimeTypes.length : 0) + (Array.isArray(extensions) ? extensions.length : 0);
1239
- if (ACTOR_FILE_KINDS.has(surfaceKind)) {
1240
- if (filters === 0) errors.push(`${path} (${surfaceKind}) must list mime-types and/or extensions.`);
1241
- } else if (mimeTypes !== void 0 || extensions !== void 0) {
1242
- errors.push(`${path} (${surfaceKind}) is not a file surface and cannot list mime-types or extensions.`);
1243
- }
1244
- if (surface.format !== void 0 && (surfaceKind !== "raw-file" || surface.format !== "text" && surface.format !== "json")) {
1245
- errors.push(`${path}.format is only for raw-file surfaces and must be text or json.`);
1246
- }
1247
- if (surface.description !== void 0 && typeof surface.description !== "string") {
1248
- errors.push(`${path}.description must be a string.`);
1249
- }
1250
- if (surfaceKind === "native-collaboration" && applicationSpec.collaboration?.mode !== "native-scene-v1") {
1251
- errors.push(`${path} (native-collaboration) requires spec.collaboration.mode native-scene-v1.`);
1252
- }
1253
- for (const name of ["read-tool", "apply-tool"]) {
1254
- const key = surface[name];
1255
- if (key === void 0) continue;
1256
- if (!ACTOR_FILE_KINDS.has(surfaceKind)) {
1257
- errors.push(`${path}.${name} is only for file surfaces (${[...ACTOR_FILE_KINDS].join(", ")}).`);
1258
- continue;
1259
- }
1260
- const tool = typeof key === "string" ? appTools.get(key) : void 0;
1261
- if (!tool) {
1262
- errors.push(`${path}.${name} must name a tool declared in spec.tools.`);
1263
- } else if (name === "read-tool" && (tool.effect !== "read" || tool.approval === "always")) {
1264
- errors.push(`${path}.read-tool '${key}' must be a read tool (effect: read) without approval: always.`);
1265
- }
1266
- }
1267
- if (surfaceKind === "document" && surface["read-tool"] === void 0 && !Object.prototype.hasOwnProperty.call(applicationSpec, "wopi")) {
1268
- errors.push(`${path} (document) requires spec.wopi or a read-tool.`);
1269
- }
1270
- });
1271
- return errors;
1272
- }
1273
- function declaredTools(spec) {
1274
- const tools = /* @__PURE__ */ new Map();
1275
- if (!Array.isArray(spec.tools)) return tools;
1276
- for (const tool of spec.tools) {
1277
- if (tool && typeof tool === "object" && typeof tool.key === "string") {
1278
- tools.set(tool.key, tool);
1279
- }
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?)` };
1280
1454
  }
1281
- return tools;
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 };
1282
1459
  }
1283
- function validateNativeCollaborationSection(kind, spec) {
1284
- if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "collaboration")) return [];
1285
- if (kind !== "Application") return ["spec.collaboration is only supported for Application manifests."];
1286
- const applicationSpec = spec;
1287
- const declaration = applicationSpec.collaboration;
1288
- if (!declaration || typeof declaration !== "object" || Array.isArray(declaration) || Object.keys(declaration).length !== 1 || !Object.prototype.hasOwnProperty.call(declaration, "mode") || declaration.mode !== "native-scene-v1") {
1289
- return ["spec.collaboration must be exactly { mode: native-scene-v1 }."];
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}`));
1290
1475
  }
1291
- if (Object.prototype.hasOwnProperty.call(applicationSpec, "wopi") || Array.isArray(applicationSpec.capabilities) && applicationSpec.capabilities.includes("wopi")) {
1292
- return ["Native collaboration and WOPI must use separate application declarations."];
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}`));
1293
1480
  }
1294
- return [];
1295
- }
1296
- function validateWopiOperationsSection(spec) {
1297
- if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1298
- const wopi = spec.wopi;
1299
- if (!wopi || typeof wopi !== "object" || Array.isArray(wopi) || !Object.prototype.hasOwnProperty.call(wopi, "operations")) return [];
1300
- const operations = wopi.operations;
1301
- if (!Array.isArray(operations) || operations.length > 2 || operations.some((operation) => operation !== "rename" && operation !== "delete") || new Set(operations).size !== operations.length) {
1302
- return ["spec.wopi.operations must be a unique list containing only rename and delete; omit it to request neither."];
1481
+ if (icons.size === 0) {
1482
+ if (document.has("icons")) document.delete("icons");
1483
+ return;
1303
1484
  }
1304
- return [];
1305
- }
1306
- function validateMarketplaceSection(marketplace2) {
1307
- if (marketplace2 === void 0) return [];
1308
- if (!marketplace2 || typeof marketplace2 !== "object" || Array.isArray(marketplace2)) {
1309
- return ["marketplace must be an object."];
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 }));
1310
1488
  }
1311
- const section = marketplace2;
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 : {};
1312
1540
  const errors = [];
1313
- for (const field of ["logo", "readme", "changelog"]) {
1314
- const value = section[field];
1315
- if (value !== void 0 && (typeof value !== "string" || value.trim().length === 0)) {
1316
- errors.push(`marketplace.${field} must be a non-empty relative path.`);
1317
- }
1318
- }
1319
- if (section.hero !== void 0) {
1320
- if (!section.hero || typeof section.hero !== "object" || Array.isArray(section.hero)) {
1321
- errors.push("marketplace.hero must be an object.");
1322
- } else {
1323
- const hero = section.hero;
1324
- if (typeof hero.source !== "string" || hero.source.trim().length === 0) {
1325
- errors.push("marketplace.hero.source must be a non-empty relative path.");
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;
1326
1549
  }
1327
- if (typeof hero.alt !== "string" || hero.alt.trim().length === 0) {
1328
- errors.push("marketplace.hero.alt is required and must not be empty.");
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.`);
1329
1563
  }
1330
1564
  }
1331
1565
  }
1332
- if (section.images !== void 0) {
1333
- if (!Array.isArray(section.images)) {
1334
- errors.push("marketplace.images must be a list.");
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.");
1335
1569
  } else {
1336
- if (section.images.length > 8) errors.push("marketplace.images may contain at most 8 images.");
1337
- section.images.forEach((value, index) => {
1338
- const at = `marketplace.images[${index}]`;
1339
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1340
- errors.push(`${at} must be an object.`);
1341
- return;
1342
- }
1343
- const image = value;
1344
- if (typeof image.source !== "string" || image.source.trim().length === 0) {
1345
- errors.push(`${at}.source must be a non-empty relative path.`);
1346
- }
1347
- if (typeof image.alt !== "string" || image.alt.trim().length === 0) {
1348
- errors.push(`${at}.alt is required and must not be empty.`);
1349
- }
1350
- if (image.caption !== void 0 && typeof image.caption !== "string") {
1351
- errors.push(`${at}.caption must be a string when provided.`);
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.`);
1352
1580
  }
1353
1581
  });
1354
1582
  }
1355
1583
  }
1356
- if (section.assets !== void 0) {
1357
- if (!Array.isArray(section.assets)) {
1358
- errors.push("marketplace.assets must be a list of relative glob strings.");
1359
- } else {
1360
- section.assets.forEach((value, index) => {
1361
- if (typeof value !== "string" || value.trim().length === 0) {
1362
- errors.push(`marketplace.assets[${index}] must be a non-empty relative glob string.`);
1363
- }
1364
- });
1365
- }
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.");
1366
1586
  }
1367
1587
  return errors;
1368
1588
  }
1369
- async function findManifest(dir) {
1370
- const explicit = join(dir, "manifest.yaml");
1371
- try {
1372
- if ((await stat(explicit)).isFile()) return explicit;
1373
- } catch {
1374
- }
1375
- const entries = await readdir(dir);
1376
- const candidates = entries.filter((name) => /\.(app|engine|agent|skill|tool|bundle|policy)\.ya?ml$/.test(name));
1377
- if (candidates.length === 1) return join(dir, candidates[0]);
1378
- if (candidates.length === 0) {
1379
- 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.`);
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
+ }
1380
1624
  }
1381
- throw new Error(`Multiple manifests found in ${dir} (${candidates.join(", ")}). Pass --manifest to disambiguate.`);
1625
+ return errors;
1382
1626
  }
1383
- var NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
1384
- var DEPENDENCY_IDENTITY = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
1385
- 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-]+)*)?$/;
1386
- function validateDependencies(spec) {
1387
- if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1388
- const value = spec;
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) {
1389
1645
  const errors = [];
1390
- const required = /* @__PURE__ */ new Set();
1391
- const seen = /* @__PURE__ */ new Set();
1392
- if (value.dependencies !== void 0) {
1393
- if (!Array.isArray(value.dependencies) || value.dependencies.length > 32) {
1394
- errors.push("spec.dependencies must be a list of at most 32 exact package pins.");
1395
- } else {
1396
- for (const dependency of value.dependencies) {
1397
- if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) {
1398
- errors.push("Each dependency must be an object.");
1399
- continue;
1400
- }
1401
- const item = dependency;
1402
- if (Object.keys(item).some((key) => !["package", "version", "install-path", "optional"].includes(key))) {
1403
- errors.push("Each dependency accepts only package, version, install-path and optional.");
1404
- }
1405
- if (typeof item.package !== "string" || !DEPENDENCY_IDENTITY.test(item.package) || typeof item.version !== "string" || !EXACT_VERSION.test(item.version)) {
1406
- errors.push("Dependencies require a lowercase publisher/package-id and an exact semantic version.");
1407
- }
1408
- if (item.optional !== void 0 && typeof item.optional !== "boolean") {
1409
- errors.push("Dependency optional must be true or false.");
1410
- }
1411
- if (item["install-path"] !== void 0) {
1412
- const path = item["install-path"];
1413
- const normalized = typeof path === "string" ? path.trim().replace(/^\/+|\/+$/g, "") : "";
1414
- if (!normalized || normalized.length > 512 || /[\\\u0000-\u001f\u007f]/.test(normalized) || normalized.split("/").some((segment) => ["", ".", ".."].includes(segment))) {
1415
- errors.push("Dependency install-path must be a nonempty workspace path without traversal.");
1416
- }
1417
- }
1418
- if (typeof item.package === "string") {
1419
- if (seen.has(item.package)) errors.push(`Duplicate dependency '${item.package}'.`);
1420
- seen.add(item.package);
1421
- if (item.optional !== true) required.add(item.package);
1422
- }
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;
1423
1661
  }
1662
+ bytes = await readFile(absolute);
1663
+ } catch {
1664
+ errors.push(`${at} does not exist.`);
1665
+ continue;
1424
1666
  }
1425
- }
1426
- if (value.engine !== void 0) {
1427
- if (typeof value.engine !== "string" || !DEPENDENCY_IDENTITY.test(value.engine) || !required.has(value.engine)) {
1428
- errors.push("spec.engine must name a required publisher-qualified dependency.");
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;
1429
1674
  }
1430
- } else if (value.scripts !== void 0) {
1431
- errors.push("Script packages must declare spec.engine and its required dependency.");
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.`);
1432
1687
  }
1433
1688
  return errors;
1434
1689
  }
1435
- function validatePackageName(name, label) {
1436
- if (!NAME_PATTERN.test(name)) {
1437
- throw new Error(`Invalid ${label} '${name}' \u2014 use lowercase letters, digits and hyphens (no leading/trailing hyphen).`);
1438
- }
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
1699
+ };
1700
+ function validatorForKind(kind) {
1701
+ const name = findPackageType(kind)?.validator;
1702
+ return name ? PACKAGE_TYPE_VALIDATORS[name] : void 0;
1439
1703
  }
1440
1704
 
1441
- // src/dev/manifest.ts
1442
- async function readManifestDocument(path) {
1443
- const text = await readFile(path, "utf8");
1444
- const doc = parse(text);
1445
- if (!doc || typeof doc !== "object") throw new Error(`${path} is not a YAML manifest.`);
1446
- return doc;
1705
+ // src/vpkg/manifest.ts
1706
+ function normalizeKind(kind) {
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;
1447
1730
  }
1448
- function manifestPermissions(manifest) {
1449
- const permissions = manifest.spec?.permissions;
1450
- if (!Array.isArray(permissions)) return [];
1451
- return permissions.filter((p) => typeof p === "string");
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.`);
1452
1735
  }
1453
- function validateManifest(manifest) {
1454
- const issues = [];
1455
- const error = (message) => issues.push({ level: "error", message });
1456
- const warning = (message) => issues.push({ level: "warning", message });
1457
- const kind = manifest.kind;
1458
- const knownKinds = ["ExecutionEngine", "Application", "Agent", "Skill", "Tool", "Bundle", "Policy"];
1459
- if (!kind) {
1460
- error("missing 'kind' (ExecutionEngine | Application | Agent | Skill | Tool | Bundle | Policy)");
1461
- return issues;
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
+ ];
1753
+ }
1754
+ function validateLaunchManifestKind(kind, spec) {
1755
+ if (isApplicationProfile(kind) || !spec || typeof spec !== "object" || Array.isArray(spec)) return void 0;
1756
+ if (!Object.prototype.hasOwnProperty.call(spec, "launch")) return void 0;
1757
+ return "spec.launch is only supported for Application manifests";
1758
+ }
1759
+ async function loadManifest(path) {
1760
+ const text = await readFile(path, "utf8");
1761
+ const manifest = parse(text);
1762
+ if (!manifest || typeof manifest !== "object") throw new Error(`Failed to parse manifest at ${path}.`);
1763
+ if (!manifest.kind) throw new Error(`Manifest at ${path} is missing 'kind'.`);
1764
+ if (!manifest.metadata?.name) throw new Error(`Manifest at ${path} is missing 'metadata.name'.`);
1765
+ if (!manifest.metadata?.["package-id"]) throw new Error(`Manifest at ${path} is missing 'metadata.package-id'.`);
1766
+ if (!manifest.metadata?.version) throw new Error(`Manifest at ${path} is missing 'metadata.version'.`);
1767
+ validatePackageName(manifest.metadata["package-id"], "package ID");
1768
+ const kind = normalizeKind(manifest.kind);
1769
+ const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
1770
+ if (hostedBackendErrors.length > 0) {
1771
+ throw new Error(`Invalid manifest at ${path}: ${hostedBackendErrors.join(" ")}`);
1462
1772
  }
1463
- if (!knownKinds.includes(kind)) {
1464
- error(`unknown kind '${kind}' (expected ExecutionEngine, Application, Agent, Skill, Tool, Bundle or Policy)`);
1773
+ const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
1774
+ if (launchKindError) throw new Error(`Invalid manifest at ${path}: ${launchKindError}.`);
1775
+ const collaborationErrors = validateNativeCollaborationSection(kind, manifest.spec);
1776
+ if (collaborationErrors.length > 0) {
1777
+ throw new Error(`Invalid manifest at ${path}: ${collaborationErrors.join(" ")}`);
1465
1778
  }
1466
- if (!manifest["api-version"]) {
1467
- warning("missing 'api-version' (expected verentis.io/v1)");
1468
- } else if (manifest["api-version"] !== "verentis.io/v1") {
1469
- error("api-version must be 'verentis.io/v1'");
1779
+ const messageErrors = validateMessageChannelsSection(kind, manifest.spec);
1780
+ if (messageErrors.length > 0) {
1781
+ throw new Error(`Invalid manifest at ${path}: ${messageErrors.join(" ")}`);
1470
1782
  }
1471
- const meta = manifest.metadata ?? {};
1472
- if (!meta.name) {
1473
- error("metadata.name is required");
1474
- } else if (!NAME_PATTERN.test(meta.name)) {
1475
- error("metadata.name must use lowercase letters, digits and internal hyphens");
1783
+ const actorErrors = validateActorSection(kind, manifest.spec);
1784
+ if (actorErrors.length > 0) {
1785
+ throw new Error(`Invalid manifest at ${path}: ${actorErrors.join(" ")}`);
1476
1786
  }
1477
- if (kind !== "Policy") {
1478
- for (const field of ["display-name", "version"]) {
1479
- if (!meta[field]) error(`metadata.${field} is required`);
1480
- }
1481
- if (!meta["package-id"]) {
1482
- error("metadata.package-id is required");
1483
- } else if (!NAME_PATTERN.test(meta["package-id"])) {
1484
- error("metadata.package-id must use lowercase letters, digits and internal hyphens");
1485
- }
1787
+ const operationErrors = validateWopiOperationsSection(manifest.spec);
1788
+ if (operationErrors.length > 0) {
1789
+ throw new Error(`Invalid manifest at ${path}: ${operationErrors.join(" ")}`);
1486
1790
  }
1487
- const spec = manifest.spec ?? {};
1488
- validateManifestIcons(meta, spec, issues);
1489
- const launchKindError = validateLaunchManifestKind(kind, spec);
1490
- if (launchKindError) error(launchKindError);
1491
- for (const message of validateWopiOperationsSection(spec)) error(message);
1492
- for (const message of validateHostedBackendDeclaration(kind, spec)) error(message);
1493
- for (const message of validateDependencies(spec)) error(message);
1494
- for (const message of validateNativeCollaborationSection(kind, spec)) error(message);
1495
- for (const message of validateMessageChannelsSection(kind, spec)) error(message);
1496
- for (const message of validateActorSection(kind, spec)) error(message);
1497
- if (kind === "ExecutionEngine") {
1498
- const runtimes = spec.runtimes ?? {};
1499
- if (Object.keys(runtimes).length === 0) {
1500
- error("spec.runtimes must declare at least one runtime (docker and/or wasm)");
1501
- }
1502
- const docker = runtimes["docker"];
1503
- if (docker && !docker.image) error("spec.runtimes.docker.image is required");
1504
- const wasm = runtimes["wasm"];
1505
- if (wasm && !wasm.module) error("spec.runtimes.wasm.module is required");
1506
- if (!spec["file-types"]?.length) warning("spec.file-types is empty \u2014 the engine will never be auto-resolved for a file");
1507
- for (const fileType of spec["file-types"] ?? []) {
1508
- if (!fileType.pattern) error("every spec.file-types[] entry needs a 'pattern' (MIME type)");
1509
- }
1510
- for (const tool of spec.tools ?? []) {
1511
- if (!tool.name) error("every spec.tools[] entry needs a 'name'");
1512
- }
1513
- if (!spec["execution-modes"]?.length) warning("spec.execution-modes is empty (expected e.g. request-response)");
1514
- if (!manifestPermissions(manifest).length) warning("spec.permissions is empty \u2014 the run token will carry no VFS scopes");
1791
+ const dependencyErrors = validateDependencies(manifest.spec);
1792
+ if (dependencyErrors.length > 0) {
1793
+ throw new Error(`Invalid manifest at ${path}: ${dependencyErrors.join(" ")}`);
1515
1794
  }
1516
- if (kind === "Application") {
1517
- const hasIframe = !!spec.entry || !!spec["entry-points"]?.length;
1518
- const hasInstall = Array.isArray(spec.install) && spec.install.length > 0;
1519
- const hasScopes = Array.isArray(spec.scopes) && spec.scopes.length > 0;
1520
- if (!hasIframe && !hasInstall && !hasScopes) {
1521
- error(
1522
- "an Application must declare at least one contribution: spec.entry / spec.entry-points[] (iframe UI), spec.install[] (installed files), or spec.scopes[] (identity)"
1523
- );
1524
- }
1525
- for (const message of validateApplicationSplashSection(kind, spec)) error(message);
1526
- validateApplicationLaunch(spec, issues);
1795
+ const splashErrors = validateApplicationSplashSection(kind, manifest.spec);
1796
+ if (splashErrors.length > 0) {
1797
+ throw new Error(`Invalid manifest at ${path}: ${splashErrors.join(" ")}`);
1527
1798
  }
1528
- if (kind === "Agent") validateAgentManifest(spec, issues);
1529
- if (kind === "Skill") validateSkillManifest(spec, issues);
1530
- if (kind === "Tool") validateToolManifest(spec, issues);
1531
- if (kind === "Policy") validatePolicyManifest(spec, issues);
1532
- validateInstallDirectives(spec.install, issues);
1533
- validateSettingDeclarations(kind, spec, issues);
1534
- for (const message of validateMarketplaceSection(manifest.marketplace)) error(message);
1535
- const packaging = manifest.packaging ?? {};
1536
- if (kind !== "Policy" && !packaging.publisher) warning("packaging.publisher is not set \u2014 `verentis pack`/`publish` will refuse the package");
1537
- return issues;
1538
- }
1539
- function validateAgentManifest(spec, issues) {
1540
- const error = (message) => issues.push({ level: "error", message });
1541
- if (spec.instructions !== void 0 && typeof spec.instructions !== "string") error("spec.instructions must be a string");
1542
- if (spec["system-prompt"] !== void 0 && typeof spec["system-prompt"] !== "string") error("spec.system-prompt must be a string");
1543
- if (spec.instructions !== void 0 && spec["system-prompt"] !== void 0) {
1544
- error("spec.instructions and spec.system-prompt cannot both be set");
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(" ")}`);
1545
1806
  }
1546
- if (spec["instructions-file"] !== void 0 && (spec.instructions !== void 0 || spec["system-prompt"] !== void 0)) {
1547
- error("spec.instructions-file cannot be combined with inline instructions");
1807
+ const marketplaceErrors = validateMarketplaceSection(manifest.marketplace);
1808
+ if (marketplaceErrors.length > 0) {
1809
+ throw new Error(`Invalid marketplace section in ${path}: ${marketplaceErrors.join(" ")}`);
1548
1810
  }
1549
- validateUniqueStrings(spec.skills, "spec.skills", issues);
1550
- validateUniqueStrings(spec.tools, "spec.tools", issues);
1811
+ return manifest;
1551
1812
  }
1552
- function validateSkillManifest(spec, issues) {
1553
- const error = (message) => issues.push({ level: "error", message });
1554
- if (typeof spec.description !== "string" || spec.description.trim().length === 0) {
1555
- error("spec.description is required for Skill manifests");
1813
+ function bumpPatchVersion(version) {
1814
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
1815
+ if (!match) {
1816
+ throw new Error(`Cannot bump version '${version}' \u2014 expected a semantic version like 1.2.3.`);
1556
1817
  }
1557
- if (spec.instructions !== void 0 && spec["instructions-file"] !== void 0) {
1558
- error("spec.instructions and spec.instructions-file cannot both be set");
1818
+ return `${match[1]}.${match[2]}.${Number(match[3]) + 1}`;
1819
+ }
1820
+ async function bumpManifestPatchVersion(path, currentVersion) {
1821
+ const text = await readFile(path, "utf8");
1822
+ const nextVersion = bumpPatchVersion(currentVersion);
1823
+ const document = parseDocument(text);
1824
+ if (document.errors.length > 0) {
1825
+ throw new Error(`Failed to parse manifest at ${path}: ${document.errors.map((error) => error.message).join(" ")}`);
1559
1826
  }
1560
- validateUniqueStrings(spec.skills, "spec.skills", issues);
1561
- validateUniqueStrings(spec.tools, "spec.tools", issues);
1827
+ document.setIn(["metadata", "version"], nextVersion);
1828
+ await writeFile(path, document.toString());
1829
+ return nextVersion;
1562
1830
  }
1563
- function validateToolManifest(spec, issues) {
1564
- const error = (message) => issues.push({ level: "error", message });
1565
- const tools = spec.tools;
1566
- if (!Array.isArray(tools) || tools.length === 0) {
1567
- error("spec.tools must contain at least one tool definition");
1568
- return;
1831
+ function validateApplicationSplashSection(kind, spec) {
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."] : [];
1569
1835
  }
1570
- const serverNames = /* @__PURE__ */ new Set();
1571
- const servers = spec.mcp && typeof spec.mcp === "object" && !Array.isArray(spec.mcp) ? spec.mcp.servers : void 0;
1572
- if (Array.isArray(servers)) {
1573
- for (const server of servers) {
1574
- if (server && typeof server === "object" && !Array.isArray(server)) {
1575
- const name = server.name;
1576
- if (typeof name === "string") serverNames.add(name);
1836
+ const applicationSpec = spec;
1837
+ const errors = [];
1838
+ const splash = applicationSpec.splash;
1839
+ if (splash !== void 0 && (typeof splash !== "string" || splash.trim().length === 0)) {
1840
+ errors.push("spec.splash must be a non-empty URL string.");
1841
+ }
1842
+ const entryPoints = applicationSpec["entry-points"];
1843
+ if (Array.isArray(entryPoints)) {
1844
+ entryPoints.forEach((value, index) => {
1845
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
1846
+ const entryPointSplash = value.splash;
1847
+ if (entryPointSplash !== void 0 && (typeof entryPointSplash !== "string" || entryPointSplash.trim().length === 0)) {
1848
+ errors.push(`spec.entry-points[${index}].splash must be a non-empty URL string.`);
1577
1849
  }
1578
- }
1850
+ });
1579
1851
  }
1580
- const keys = /* @__PURE__ */ new Set();
1581
- tools.forEach((tool, index) => {
1582
- const at = `spec.tools[${index}]`;
1583
- if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
1584
- error(`${at} must be an object`);
1852
+ return errors;
1853
+ }
1854
+ function validateHostedBackendDeclaration(kind, spec) {
1855
+ if (isApplicationProfile(kind) || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1856
+ const value = spec;
1857
+ const capabilities = value.capabilities;
1858
+ const requestsCapability = Array.isArray(capabilities) && capabilities.some((capability) => typeof capability === "string" && capability.trim().toLowerCase() === "hosted-backend");
1859
+ if (requestsCapability || Object.prototype.hasOwnProperty.call(value, "hosted-backend")) {
1860
+ return [`${kind} packages cannot declare a hosted backend.`];
1861
+ }
1862
+ return [];
1863
+ }
1864
+ var MESSAGE_CHANNEL_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
1865
+ var MAX_MESSAGE_CHANNELS = 32;
1866
+ function validateMessageChannelsSection(kind, spec) {
1867
+ if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "messages")) return [];
1868
+ if (!isApplicationProfile(kind)) return ["spec.messages is only supported for Application manifests."];
1869
+ const messages = spec.messages;
1870
+ if (!Array.isArray(messages)) return ["spec.messages must be a list of { channel, description, schema? }."];
1871
+ if (messages.length > MAX_MESSAGE_CHANNELS) return [`spec.messages declares more than ${MAX_MESSAGE_CHANNELS} channels.`];
1872
+ const errors = [];
1873
+ const seen = /* @__PURE__ */ new Set();
1874
+ messages.forEach((value, index) => {
1875
+ const path = `spec.messages[${index}]`;
1876
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1877
+ errors.push(`${path} must be an object with channel and description.`);
1585
1878
  return;
1586
1879
  }
1587
- const item = tool;
1588
- if (typeof item.key !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(item.key)) error(`${at}.key is required`);
1589
- else if (keys.has(item.key)) error(`duplicate tool key '${item.key}'`);
1590
- else keys.add(item.key);
1591
- if (typeof item.description !== "string" || item.description.trim().length === 0) error(`${at}.description is required`);
1592
- if (item["input-schema"] === void 0) error(`${at}.input-schema is required`);
1593
- if (!["read", "write", "execute", "external", "interactive"].includes(String(item.effect))) error(`${at}.effect is invalid`);
1594
- const implementation = item.implementation;
1595
- if (!implementation || typeof implementation !== "object" || Array.isArray(implementation)) {
1596
- error(`${at}.implementation is required`);
1597
- } else if (implementation.type === "mcp") {
1598
- const server = implementation.server;
1599
- if (typeof server !== "string" || !serverNames.has(server)) error(`${at}.implementation.server is not declared in spec.mcp.servers`);
1880
+ const { channel, description, schema } = value;
1881
+ if (typeof channel !== "string" || !MESSAGE_CHANNEL_PATTERN.test(channel)) {
1882
+ errors.push(`${path}.channel must match ${MESSAGE_CHANNEL_PATTERN.source}.`);
1883
+ } else if (seen.has(channel)) {
1884
+ errors.push(`${path}.channel '${channel}' is declared more than once.`);
1885
+ } else {
1886
+ seen.add(channel);
1600
1887
  }
1601
- const retry = item.retry;
1602
- if (retry && typeof retry === "object" && !Array.isArray(retry) && Number(retry["max-attempts"]) > 1 && ["write", "execute", "external", "interactive"].includes(String(item.effect)) && !["status-query", "idempotency-key"].includes(String(retry.reconcile))) {
1603
- error(`${at}.retry requires a reconciliation contract for non-read tools`);
1888
+ if (typeof description !== "string" || description.trim().length === 0) {
1889
+ errors.push(`${path}.description is required so agents know when to use the channel.`);
1604
1890
  }
1605
- });
1606
- }
1607
- function validatePolicyManifest(spec, issues) {
1608
- const error = (message) => issues.push({ level: "error", message });
1609
- if (spec.area !== "agent") error("spec.area must be agent");
1610
- if (!Array.isArray(spec.rules)) {
1611
- error("spec.rules must be an array");
1612
- return;
1613
- }
1614
- spec.rules.forEach((rule, index) => {
1615
- const at = `spec.rules[${index}]`;
1616
- if (!rule || typeof rule !== "object" || Array.isArray(rule)) {
1617
- error(`${at} must be an object`);
1618
- return;
1891
+ if (schema !== void 0 && (!schema || typeof schema !== "object" || Array.isArray(schema))) {
1892
+ errors.push(`${path}.schema must be a JSON Schema object.`);
1619
1893
  }
1620
- const item = rule;
1621
- if (typeof item.id !== "string" || item.id.trim().length === 0) error(`${at}.id is required`);
1622
- if (!["permit", "deny", "require-approval"].includes(String(item.effect))) error(`${at}.effect must be permit, deny or require-approval`);
1623
- if (typeof item.capability !== "string" || item.capability.trim().length === 0) error(`${at}.capability is required`);
1624
1894
  });
1895
+ return errors;
1625
1896
  }
1626
- function validateUniqueStrings(value, path, issues) {
1627
- if (value === void 0) return;
1628
- if (!Array.isArray(value)) {
1629
- issues.push({ level: "error", message: `${path} must be an array` });
1630
- return;
1631
- }
1632
- const seen = /* @__PURE__ */ new Set();
1633
- for (const item of value) {
1634
- if (typeof item !== "string") continue;
1635
- if (seen.has(item)) issues.push({ level: "error", message: `${path} contains duplicate '${item}'` });
1636
- seen.add(item);
1897
+ var ACTOR_SURFACE_KINDS = ["app-backend", "mcp", "native-collaboration", "document", "raw-file"];
1898
+ var ACTOR_FILE_KINDS = /* @__PURE__ */ new Set(["native-collaboration", "document", "raw-file"]);
1899
+ var MAX_ACTOR_SURFACES = 16;
1900
+ function validateActorSection(kind, spec) {
1901
+ if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "actor")) return [];
1902
+ if (!isApplicationProfile(kind)) return ["spec.actor is only supported for Application manifests."];
1903
+ const applicationSpec = spec;
1904
+ const actor = applicationSpec.actor;
1905
+ if (!actor || typeof actor !== "object" || Array.isArray(actor)) {
1906
+ return ["spec.actor must be an object with live-channel and/or surfaces."];
1637
1907
  }
1638
- }
1639
- function validateManifestIcons(metadata, spec, issues) {
1640
- validateOptionalIcon(metadata.icon, "metadata.icon", issues);
1641
- validateBindingIcons(spec["mime-types"], "spec.mime-types", issues);
1642
- validateBindingIcons(spec["file-types"], "spec.file-types", issues);
1643
- if (!Array.isArray(spec["entry-points"])) return;
1644
- spec["entry-points"].forEach((value, index) => {
1645
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
1646
- validateOptionalIcon(value.icon, `spec.entry-points[${index}].icon`, issues);
1647
- validateBindingIcons(value["mime-types"], `spec.entry-points[${index}].mime-types`, issues);
1648
- });
1649
- }
1650
- function validateBindingIcons(bindings, path, issues) {
1651
- if (!Array.isArray(bindings)) return;
1652
- bindings.forEach((value, index) => {
1653
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
1654
- validateOptionalIcon(value.icon, `${path}[${index}].icon`, issues);
1655
- });
1656
- }
1657
- function validateOptionalIcon(value, path, issues) {
1658
- if (value !== void 0 && !isNonEmptyString(value)) {
1659
- issues.push({ level: "error", message: `${path} must be a non-empty string` });
1908
+ const { "live-channel": liveChannel, surfaces } = actor;
1909
+ const errors = [];
1910
+ if (liveChannel !== void 0) {
1911
+ const declared = Array.isArray(applicationSpec.messages) && applicationSpec.messages.some((m) => m && typeof m === "object" && m.channel === liveChannel);
1912
+ if (typeof liveChannel !== "string" || !declared) {
1913
+ errors.push("spec.actor.live-channel must name a channel declared in spec.messages.");
1914
+ }
1660
1915
  }
1661
- }
1662
- function validateApplicationLaunch(spec, issues) {
1663
- const launch = spec.launch;
1664
- if (launch === void 0) return;
1665
- const error = (message) => issues.push({ level: "error", message });
1666
- if (!launch || typeof launch !== "object" || Array.isArray(launch)) {
1667
- error("spec.launch must be an object");
1668
- return;
1916
+ if (surfaces === void 0) {
1917
+ if (liveChannel === void 0) errors.push("spec.actor must declare live-channel and/or surfaces.");
1918
+ return errors;
1669
1919
  }
1670
- if (launch.pinnable === true && launch.enabled !== true) {
1671
- error("spec.launch.pinnable requires spec.launch.enabled");
1920
+ if (!Array.isArray(surfaces) || surfaces.length === 0) {
1921
+ errors.push("spec.actor.surfaces must be a non-empty list of { kind, ... }.");
1922
+ return errors;
1672
1923
  }
1673
- if (launch.enabled !== true) return;
1674
- const launchEntryPoint = launch["entry-point"];
1675
- if (launchEntryPoint !== void 0 && (typeof launchEntryPoint !== "string" || !launchEntryPoint.trim())) {
1676
- error("spec.launch.entry-point must be a non-empty entry-point id");
1677
- return;
1924
+ if (surfaces.length > MAX_ACTOR_SURFACES) {
1925
+ errors.push(`spec.actor.surfaces declares more than ${MAX_ACTOR_SURFACES} surfaces.`);
1926
+ return errors;
1678
1927
  }
1679
- if (typeof launchEntryPoint === "string") {
1680
- const entryPoint = spec["entry-points"]?.find((candidate) => candidate.id === launchEntryPoint);
1681
- if (!entryPoint) {
1682
- error(`spec.launch.entry-point '${launchEntryPoint}' does not match spec.entry-points[].id`);
1928
+ const appTools = declaredTools(applicationSpec);
1929
+ surfaces.forEach((value, index) => {
1930
+ const path = `spec.actor.surfaces[${index}]`;
1931
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1932
+ errors.push(`${path} must be an object with a kind.`);
1683
1933
  return;
1684
1934
  }
1685
- if (!resolvesIframeEntry(spec.entry, entryPoint.entry ?? entryPoint.route)) {
1686
- error("spec.launch.enabled requires the selected entry point to resolve an iframe entry");
1687
- }
1688
- return;
1689
- }
1690
- if (!isAbsoluteHttpUrl(spec.entry)) {
1691
- error("spec.launch.enabled requires spec.entry or spec.launch.entry-point");
1692
- }
1693
- }
1694
- function isNonEmptyString(value) {
1695
- return typeof value === "string" && value.trim().length > 0;
1696
- }
1697
- function resolvesIframeEntry(baseEntry, routeOrEntry) {
1698
- if (isAbsoluteHttpUrl(routeOrEntry)) return true;
1699
- return isAbsoluteHttpUrl(baseEntry);
1700
- }
1701
- function isAbsoluteHttpUrl(value) {
1702
- if (!isNonEmptyString(value)) return false;
1703
- try {
1704
- const url = new URL(value);
1705
- return url.protocol === "http:" || url.protocol === "https:";
1706
- } catch {
1707
- return false;
1708
- }
1709
- }
1710
- function validateInstallDirectives(install, issues) {
1711
- if (install === void 0) return;
1712
- const error = (message) => issues.push({ level: "error", message });
1713
- if (!Array.isArray(install)) {
1714
- error("spec.install must be a list of install directives");
1715
- return;
1716
- }
1717
- install.forEach((directive, index) => {
1718
- const at = `spec.install[${index}]`;
1719
- if (!directive || typeof directive !== "object") {
1720
- error(`${at} must be an object with 'from' and 'to'`);
1935
+ const surface = value;
1936
+ const surfaceKind = surface.kind;
1937
+ if (typeof surfaceKind !== "string" || !ACTOR_SURFACE_KINDS.includes(surfaceKind)) {
1938
+ errors.push(`${path}.kind must be one of ${ACTOR_SURFACE_KINDS.join(", ")}.`);
1721
1939
  return;
1722
1940
  }
1723
- if (!directive.from || typeof directive.from !== "string") {
1724
- error(`${at}.from is required (a path/glob relative to the package payload)`);
1725
- } else if (directive.from.startsWith("/") || directive.from.split("/").includes("..")) {
1726
- error(`${at}.from must be a relative path inside the package payload (no leading '/' or '..')`);
1941
+ const mimeTypes = surface["mime-types"];
1942
+ const extensions = surface.extensions;
1943
+ for (const [name, list] of [["mime-types", mimeTypes], ["extensions", extensions]]) {
1944
+ if (list !== void 0 && (!Array.isArray(list) || list.some((item) => typeof item !== "string" || item.trim().length === 0))) {
1945
+ errors.push(`${path}.${name} must be a list of non-empty strings.`);
1946
+ }
1727
1947
  }
1728
- if (!directive.to || typeof directive.to !== "string") {
1729
- error(`${at}.to is required (a workspace-absolute destination path)`);
1730
- } else {
1731
- if (!directive.to.startsWith("/")) error(`${at}.to must be a workspace-absolute path (start with '/')`);
1732
- if (directive.to.split("/").includes("..")) error(`${at}.to must not contain '..'`);
1948
+ const filters = (Array.isArray(mimeTypes) ? mimeTypes.length : 0) + (Array.isArray(extensions) ? extensions.length : 0);
1949
+ if (ACTOR_FILE_KINDS.has(surfaceKind)) {
1950
+ if (filters === 0) errors.push(`${path} (${surfaceKind}) must list mime-types and/or extensions.`);
1951
+ } else if (mimeTypes !== void 0 || extensions !== void 0) {
1952
+ errors.push(`${path} (${surfaceKind}) is not a file surface and cannot list mime-types or extensions.`);
1733
1953
  }
1734
- if (directive.mode !== void 0 && directive.mode !== "seed" && directive.mode !== "managed") {
1735
- error(`${at}.mode must be 'seed' or 'managed' (got '${directive.mode}')`);
1954
+ if (surface.format !== void 0 && (surfaceKind !== "raw-file" || surface.format !== "text" && surface.format !== "json")) {
1955
+ errors.push(`${path}.format is only for raw-file surfaces and must be text or json.`);
1736
1956
  }
1737
- if (directive.phase !== void 0 && (!Number.isInteger(directive.phase) || directive.phase < 0)) {
1738
- error(`${at}.phase must be a non-negative integer (got '${String(directive.phase)}')`);
1957
+ if (surface.description !== void 0 && typeof surface.description !== "string") {
1958
+ errors.push(`${path}.description must be a string.`);
1959
+ }
1960
+ if (surfaceKind === "native-collaboration" && applicationSpec.collaboration?.mode !== "native-scene-v1") {
1961
+ errors.push(`${path} (native-collaboration) requires spec.collaboration.mode native-scene-v1.`);
1962
+ }
1963
+ for (const name of ["read-tool", "apply-tool"]) {
1964
+ const key = surface[name];
1965
+ if (key === void 0) continue;
1966
+ if (!ACTOR_FILE_KINDS.has(surfaceKind)) {
1967
+ errors.push(`${path}.${name} is only for file surfaces (${[...ACTOR_FILE_KINDS].join(", ")}).`);
1968
+ continue;
1969
+ }
1970
+ const tool = typeof key === "string" ? appTools.get(key) : void 0;
1971
+ if (!tool) {
1972
+ errors.push(`${path}.${name} must name a tool declared in spec.tools.`);
1973
+ } else if (name === "read-tool" && (tool.effect !== "read" || tool.approval === "always")) {
1974
+ errors.push(`${path}.read-tool '${key}' must be a read tool (effect: read) without approval: always.`);
1975
+ }
1976
+ }
1977
+ if (surfaceKind === "document" && surface["read-tool"] === void 0 && !Object.prototype.hasOwnProperty.call(applicationSpec, "wopi")) {
1978
+ errors.push(`${path} (document) requires spec.wopi or a read-tool.`);
1739
1979
  }
1740
1980
  });
1981
+ return errors;
1741
1982
  }
1742
- var SETTING_KEY_PATTERN = /^[a-z0-9]+([.-][a-z0-9]+)*$/;
1743
- var ENV_VAR_PATTERN = /^[A-Z][A-Z0-9_]*$/;
1744
- var SETTING_TYPES = ["string", "number", "boolean", "select", "file"];
1745
- function validateSettingDeclarations(kind, spec, issues) {
1746
- const settings2 = spec.settings;
1747
- if (settings2 === void 0) return;
1748
- const error = (message) => issues.push({ level: "error", message });
1749
- if (!Array.isArray(settings2)) {
1750
- error("spec.settings must be a list of setting declarations");
1751
- return;
1752
- }
1983
+ function declaredTools(spec) {
1984
+ const tools = /* @__PURE__ */ new Map();
1985
+ if (!Array.isArray(spec.tools)) return tools;
1986
+ for (const tool of spec.tools) {
1987
+ if (tool && typeof tool === "object" && typeof tool.key === "string") {
1988
+ tools.set(tool.key, tool);
1989
+ }
1990
+ }
1991
+ return tools;
1992
+ }
1993
+ function validateNativeCollaborationSection(kind, spec) {
1994
+ if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "collaboration")) return [];
1995
+ if (!isApplicationProfile(kind)) return ["spec.collaboration is only supported for Application manifests."];
1996
+ const applicationSpec = spec;
1997
+ const declaration = applicationSpec.collaboration;
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") {
1999
+ return ["spec.collaboration must be exactly { mode: native-scene-v1 }."];
2000
+ }
2001
+ if (Object.prototype.hasOwnProperty.call(applicationSpec, "wopi") || Array.isArray(applicationSpec.capabilities) && applicationSpec.capabilities.includes("wopi")) {
2002
+ return ["Native collaboration and WOPI must use separate application declarations."];
2003
+ }
2004
+ return [];
2005
+ }
2006
+ function validateWopiOperationsSection(spec) {
2007
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
2008
+ const wopi = spec.wopi;
2009
+ if (!wopi || typeof wopi !== "object" || Array.isArray(wopi) || !Object.prototype.hasOwnProperty.call(wopi, "operations")) return [];
2010
+ const operations = wopi.operations;
2011
+ if (!Array.isArray(operations) || operations.length > 2 || operations.some((operation) => operation !== "rename" && operation !== "delete") || new Set(operations).size !== operations.length) {
2012
+ return ["spec.wopi.operations must be a unique list containing only rename and delete; omit it to request neither."];
2013
+ }
2014
+ return [];
2015
+ }
2016
+ function validateMarketplaceSection(marketplace2) {
2017
+ if (marketplace2 === void 0) return [];
2018
+ if (!marketplace2 || typeof marketplace2 !== "object" || Array.isArray(marketplace2)) {
2019
+ return ["marketplace must be an object."];
2020
+ }
2021
+ const section = marketplace2;
2022
+ const errors = [];
2023
+ for (const field of ["logo", "readme", "changelog"]) {
2024
+ const value = section[field];
2025
+ if (value !== void 0 && (typeof value !== "string" || value.trim().length === 0)) {
2026
+ errors.push(`marketplace.${field} must be a non-empty relative path.`);
2027
+ }
2028
+ }
2029
+ if (section.hero !== void 0) {
2030
+ if (!section.hero || typeof section.hero !== "object" || Array.isArray(section.hero)) {
2031
+ errors.push("marketplace.hero must be an object.");
2032
+ } else {
2033
+ const hero = section.hero;
2034
+ if (typeof hero.source !== "string" || hero.source.trim().length === 0) {
2035
+ errors.push("marketplace.hero.source must be a non-empty relative path.");
2036
+ }
2037
+ if (typeof hero.alt !== "string" || hero.alt.trim().length === 0) {
2038
+ errors.push("marketplace.hero.alt is required and must not be empty.");
2039
+ }
2040
+ }
2041
+ }
2042
+ if (section.images !== void 0) {
2043
+ if (!Array.isArray(section.images)) {
2044
+ errors.push("marketplace.images must be a list.");
2045
+ } else {
2046
+ if (section.images.length > 8) errors.push("marketplace.images may contain at most 8 images.");
2047
+ section.images.forEach((value, index) => {
2048
+ const at = `marketplace.images[${index}]`;
2049
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2050
+ errors.push(`${at} must be an object.`);
2051
+ return;
2052
+ }
2053
+ const image = value;
2054
+ if (typeof image.source !== "string" || image.source.trim().length === 0) {
2055
+ errors.push(`${at}.source must be a non-empty relative path.`);
2056
+ }
2057
+ if (typeof image.alt !== "string" || image.alt.trim().length === 0) {
2058
+ errors.push(`${at}.alt is required and must not be empty.`);
2059
+ }
2060
+ if (image.caption !== void 0 && typeof image.caption !== "string") {
2061
+ errors.push(`${at}.caption must be a string when provided.`);
2062
+ }
2063
+ });
2064
+ }
2065
+ }
2066
+ if (section.assets !== void 0) {
2067
+ if (!Array.isArray(section.assets)) {
2068
+ errors.push("marketplace.assets must be a list of relative glob strings.");
2069
+ } else {
2070
+ section.assets.forEach((value, index) => {
2071
+ if (typeof value !== "string" || value.trim().length === 0) {
2072
+ errors.push(`marketplace.assets[${index}] must be a non-empty relative glob string.`);
2073
+ }
2074
+ });
2075
+ }
2076
+ }
2077
+ return errors;
2078
+ }
2079
+ async function findManifest(dir) {
2080
+ const explicit = join(dir, "manifest.yaml");
2081
+ try {
2082
+ if ((await stat(explicit)).isFile()) return explicit;
2083
+ } catch {
2084
+ }
2085
+ const entries = await readdir(dir);
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
+ });
2091
+ if (candidates.length === 1) return join(dir, candidates[0]);
2092
+ if (candidates.length === 0) {
2093
+ throw new Error(`No manifest found in ${dir}. Expected manifest.yaml or a single ${suffixes.map((suffix) => `*.${suffix}.yaml`).join(" / ")}.`);
2094
+ }
2095
+ throw new Error(`Multiple manifests found in ${dir} (${candidates.join(", ")}). Pass --manifest to disambiguate.`);
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
+ }
2101
+ var NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
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])?)@(.+)$/;
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
+ }
2122
+ function validateDependencies(spec) {
2123
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
2124
+ const value = spec;
2125
+ const errors = [];
2126
+ const required = /* @__PURE__ */ new Set();
2127
+ const seen = /* @__PURE__ */ new Set();
2128
+ if (value.dependencies !== void 0) {
2129
+ if (!Array.isArray(value.dependencies) || value.dependencies.length > 32) {
2130
+ errors.push("spec.dependencies must be a list of at most 32 package dependencies.");
2131
+ } else {
2132
+ for (const dependency of value.dependencies) {
2133
+ if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) {
2134
+ errors.push("Each dependency must be an object.");
2135
+ continue;
2136
+ }
2137
+ const item = dependency;
2138
+ if (Object.keys(item).some((key) => !["package", "version", "install-path", "optional"].includes(key))) {
2139
+ errors.push("Each dependency accepts only package, version, install-path and optional.");
2140
+ }
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
+ }
2152
+ }
2153
+ if (item.optional !== void 0 && typeof item.optional !== "boolean") {
2154
+ errors.push("Dependency optional must be true or false.");
2155
+ }
2156
+ if (item["install-path"] !== void 0) {
2157
+ const path = item["install-path"];
2158
+ const normalized = typeof path === "string" ? path.trim().replace(/^\/+|\/+$/g, "") : "";
2159
+ if (!normalized || normalized.length > 512 || /[\\\u0000-\u001f\u007f]/.test(normalized) || normalized.split("/").some((segment) => ["", ".", ".."].includes(segment))) {
2160
+ errors.push("Dependency install-path must be a nonempty workspace path without traversal.");
2161
+ }
2162
+ }
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);
2167
+ }
2168
+ }
2169
+ }
2170
+ }
2171
+ if (value.engine !== void 0) {
2172
+ if (typeof value.engine !== "string" || !DEPENDENCY_IDENTITY.test(value.engine) || !required.has(value.engine)) {
2173
+ errors.push("spec.engine must name a required publisher-qualified dependency.");
2174
+ }
2175
+ } else if (value.scripts !== void 0) {
2176
+ errors.push("Script packages must declare spec.engine and its required dependency.");
2177
+ }
2178
+ return errors;
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
+ }
2194
+ function validatePackageName(name, label) {
2195
+ if (!NAME_PATTERN.test(name)) {
2196
+ throw new Error(`Invalid ${label} '${name}' \u2014 use lowercase letters, digits and hyphens (no leading/trailing hyphen).`);
2197
+ }
2198
+ }
2199
+
2200
+ // src/dev/manifest.ts
2201
+ var NON_PACKAGE_KINDS = ["Policy"];
2202
+ async function readManifestDocument(path) {
2203
+ const text = await readFile(path, "utf8");
2204
+ const doc = parse(text);
2205
+ if (!doc || typeof doc !== "object") throw new Error(`${path} is not a YAML manifest.`);
2206
+ return doc;
2207
+ }
2208
+ function manifestPermissions(manifest) {
2209
+ const permissions = manifest.spec?.permissions;
2210
+ if (!Array.isArray(permissions)) return [];
2211
+ return permissions.filter((p) => typeof p === "string");
2212
+ }
2213
+ function validateManifest(manifest) {
2214
+ const issues = [];
2215
+ const error = (message) => issues.push({ level: "error", message });
2216
+ const warning = (message) => issues.push({ level: "warning", message });
2217
+ const knownKinds = [...packageTypes().typeNames(), ...NON_PACKAGE_KINDS];
2218
+ if (!manifest.kind) {
2219
+ error(`missing 'kind' (${knownKinds.join(" | ")})`);
2220
+ return issues;
2221
+ }
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(", ")})`);
2227
+ }
2228
+ if (!manifest["api-version"]) {
2229
+ warning("missing 'api-version' (expected verentis.io/v1)");
2230
+ } else if (manifest["api-version"] !== "verentis.io/v1") {
2231
+ error("api-version must be 'verentis.io/v1'");
2232
+ }
2233
+ const meta = manifest.metadata ?? {};
2234
+ if (!meta.name) {
2235
+ error("metadata.name is required");
2236
+ } else if (!NAME_PATTERN.test(meta.name)) {
2237
+ error("metadata.name must use lowercase letters, digits and internal hyphens");
2238
+ }
2239
+ if (!isPolicy) {
2240
+ for (const message of validateMetadataTags(meta.tags)) error(message);
2241
+ for (const field of ["display-name", "version"]) {
2242
+ if (!meta[field]) error(`metadata.${field} is required`);
2243
+ }
2244
+ if (!meta["package-id"]) {
2245
+ error("metadata.package-id is required");
2246
+ } else if (!NAME_PATTERN.test(meta["package-id"])) {
2247
+ error("metadata.package-id must use lowercase letters, digits and internal hyphens");
2248
+ }
2249
+ }
2250
+ const spec = manifest.spec ?? {};
2251
+ validateManifestIcons(meta, spec, issues);
2252
+ const launchKindError = validateLaunchManifestKind(kind, spec);
2253
+ if (launchKindError) error(launchKindError);
2254
+ for (const message of validateWopiOperationsSection(spec)) error(message);
2255
+ for (const message of validateHostedBackendDeclaration(kind, spec)) error(message);
2256
+ for (const message of validateDependencies(spec)) error(message);
2257
+ for (const message of validateNativeCollaborationSection(kind, spec)) error(message);
2258
+ for (const message of validateMessageChannelsSection(kind, spec)) error(message);
2259
+ for (const message of validateActorSection(kind, spec)) error(message);
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") {
2264
+ const runtimes = spec.runtimes ?? {};
2265
+ if (Object.keys(runtimes).length === 0) {
2266
+ error("spec.runtimes must declare at least one runtime (docker and/or wasm)");
2267
+ }
2268
+ const docker = runtimes["docker"];
2269
+ if (docker && !docker.image) error("spec.runtimes.docker.image is required");
2270
+ const wasm = runtimes["wasm"];
2271
+ if (wasm && !wasm.module) error("spec.runtimes.wasm.module is required");
2272
+ if (!spec["file-types"]?.length) warning("spec.file-types is empty \u2014 the engine will never be auto-resolved for a file");
2273
+ for (const fileType of spec["file-types"] ?? []) {
2274
+ if (!fileType.pattern) error("every spec.file-types[] entry needs a 'pattern' (MIME type)");
2275
+ }
2276
+ for (const tool of spec.tools ?? []) {
2277
+ if (!tool.name) error("every spec.tools[] entry needs a 'name'");
2278
+ }
2279
+ if (!spec["execution-modes"]?.length) warning("spec.execution-modes is empty (expected e.g. request-response)");
2280
+ if (!manifestPermissions(manifest).length) warning("spec.permissions is empty \u2014 the run token will carry no VFS scopes");
2281
+ }
2282
+ if (descriptor?.profile === "application") {
2283
+ const hasIframe = !!spec.entry || !!spec["entry-points"]?.length;
2284
+ const hasInstall = Array.isArray(spec.install) && spec.install.length > 0;
2285
+ const hasScopes = Array.isArray(spec.scopes) && spec.scopes.length > 0;
2286
+ if (!hasIframe && !hasInstall && !hasScopes) {
2287
+ error(
2288
+ "an Application must declare at least one contribution: spec.entry / spec.entry-points[] (iframe UI), spec.install[] (installed files), or spec.scopes[] (identity)"
2289
+ );
2290
+ }
2291
+ validateApplicationLaunch(spec, issues);
2292
+ }
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);
2297
+ validateInstallDirectives(spec.install, issues);
2298
+ validateSettingDeclarations(descriptor?.profile === "engine", spec, issues);
2299
+ for (const message of validateMarketplaceSection(manifest.marketplace)) error(message);
2300
+ const packaging = manifest.packaging ?? {};
2301
+ if (!isPolicy && !packaging.publisher) warning("packaging.publisher is not set \u2014 `verentis pack`/`publish` will refuse the package");
2302
+ return issues;
2303
+ }
2304
+ function validateAgentManifest(spec, issues) {
2305
+ const error = (message) => issues.push({ level: "error", message });
2306
+ if (spec.instructions !== void 0 && typeof spec.instructions !== "string") error("spec.instructions must be a string");
2307
+ if (spec["system-prompt"] !== void 0 && typeof spec["system-prompt"] !== "string") error("spec.system-prompt must be a string");
2308
+ if (spec.instructions !== void 0 && spec["system-prompt"] !== void 0) {
2309
+ error("spec.instructions and spec.system-prompt cannot both be set");
2310
+ }
2311
+ if (spec["instructions-file"] !== void 0 && (spec.instructions !== void 0 || spec["system-prompt"] !== void 0)) {
2312
+ error("spec.instructions-file cannot be combined with inline instructions");
2313
+ }
2314
+ validateUniqueStrings(spec.skills, "spec.skills", issues);
2315
+ validateUniqueStrings(spec.tools, "spec.tools", issues);
2316
+ }
2317
+ function validateSkillManifest(spec, issues) {
2318
+ const error = (message) => issues.push({ level: "error", message });
2319
+ if (typeof spec.description !== "string" || spec.description.trim().length === 0) {
2320
+ error("spec.description is required for Skill manifests");
2321
+ }
2322
+ if (spec.instructions !== void 0 && spec["instructions-file"] !== void 0) {
2323
+ error("spec.instructions and spec.instructions-file cannot both be set");
2324
+ }
2325
+ validateUniqueStrings(spec.skills, "spec.skills", issues);
2326
+ validateUniqueStrings(spec.tools, "spec.tools", issues);
2327
+ }
2328
+ function validateToolManifest(spec, issues) {
2329
+ const error = (message) => issues.push({ level: "error", message });
2330
+ const tools = spec.tools;
2331
+ if (!Array.isArray(tools) || tools.length === 0) {
2332
+ error("spec.tools must contain at least one tool definition");
2333
+ return;
2334
+ }
2335
+ const serverNames = /* @__PURE__ */ new Set();
2336
+ const servers = spec.mcp && typeof spec.mcp === "object" && !Array.isArray(spec.mcp) ? spec.mcp.servers : void 0;
2337
+ if (Array.isArray(servers)) {
2338
+ for (const server of servers) {
2339
+ if (server && typeof server === "object" && !Array.isArray(server)) {
2340
+ const name = server.name;
2341
+ if (typeof name === "string") serverNames.add(name);
2342
+ }
2343
+ }
2344
+ }
2345
+ const keys = /* @__PURE__ */ new Set();
2346
+ tools.forEach((tool, index) => {
2347
+ const at = `spec.tools[${index}]`;
2348
+ if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
2349
+ error(`${at} must be an object`);
2350
+ return;
2351
+ }
2352
+ const item = tool;
2353
+ if (typeof item.key !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(item.key)) error(`${at}.key is required`);
2354
+ else if (keys.has(item.key)) error(`duplicate tool key '${item.key}'`);
2355
+ else keys.add(item.key);
2356
+ if (typeof item.description !== "string" || item.description.trim().length === 0) error(`${at}.description is required`);
2357
+ if (item["input-schema"] === void 0) error(`${at}.input-schema is required`);
2358
+ if (!["read", "write", "execute", "external", "interactive"].includes(String(item.effect))) error(`${at}.effect is invalid`);
2359
+ const implementation = item.implementation;
2360
+ if (!implementation || typeof implementation !== "object" || Array.isArray(implementation)) {
2361
+ error(`${at}.implementation is required`);
2362
+ } else if (implementation.type === "mcp") {
2363
+ const server = implementation.server;
2364
+ if (typeof server !== "string" || !serverNames.has(server)) error(`${at}.implementation.server is not declared in spec.mcp.servers`);
2365
+ }
2366
+ const retry = item.retry;
2367
+ if (retry && typeof retry === "object" && !Array.isArray(retry) && Number(retry["max-attempts"]) > 1 && ["write", "execute", "external", "interactive"].includes(String(item.effect)) && !["status-query", "idempotency-key"].includes(String(retry.reconcile))) {
2368
+ error(`${at}.retry requires a reconciliation contract for non-read tools`);
2369
+ }
2370
+ });
2371
+ }
2372
+ function validatePolicyManifest(spec, issues) {
2373
+ const error = (message) => issues.push({ level: "error", message });
2374
+ if (spec.area !== "agent") error("spec.area must be agent");
2375
+ if (!Array.isArray(spec.rules)) {
2376
+ error("spec.rules must be an array");
2377
+ return;
2378
+ }
2379
+ spec.rules.forEach((rule, index) => {
2380
+ const at = `spec.rules[${index}]`;
2381
+ if (!rule || typeof rule !== "object" || Array.isArray(rule)) {
2382
+ error(`${at} must be an object`);
2383
+ return;
2384
+ }
2385
+ const item = rule;
2386
+ if (typeof item.id !== "string" || item.id.trim().length === 0) error(`${at}.id is required`);
2387
+ if (!["permit", "deny", "require-approval"].includes(String(item.effect))) error(`${at}.effect must be permit, deny or require-approval`);
2388
+ if (typeof item.capability !== "string" || item.capability.trim().length === 0) error(`${at}.capability is required`);
2389
+ });
2390
+ }
2391
+ function validateUniqueStrings(value, path, issues) {
2392
+ if (value === void 0) return;
2393
+ if (!Array.isArray(value)) {
2394
+ issues.push({ level: "error", message: `${path} must be an array` });
2395
+ return;
2396
+ }
2397
+ const seen = /* @__PURE__ */ new Set();
2398
+ for (const item of value) {
2399
+ if (typeof item !== "string") continue;
2400
+ if (seen.has(item)) issues.push({ level: "error", message: `${path} contains duplicate '${item}'` });
2401
+ seen.add(item);
2402
+ }
2403
+ }
2404
+ function validateManifestIcons(metadata, spec, issues) {
2405
+ validateOptionalIcon(metadata.icon, "metadata.icon", issues);
2406
+ validateBindingIcons(spec["mime-types"], "spec.mime-types", issues);
2407
+ validateBindingIcons(spec["file-types"], "spec.file-types", issues);
2408
+ if (!Array.isArray(spec["entry-points"])) return;
2409
+ spec["entry-points"].forEach((value, index) => {
2410
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
2411
+ validateOptionalIcon(value.icon, `spec.entry-points[${index}].icon`, issues);
2412
+ validateBindingIcons(value["mime-types"], `spec.entry-points[${index}].mime-types`, issues);
2413
+ });
2414
+ }
2415
+ function validateBindingIcons(bindings, path, issues) {
2416
+ if (!Array.isArray(bindings)) return;
2417
+ bindings.forEach((value, index) => {
2418
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
2419
+ validateOptionalIcon(value.icon, `${path}[${index}].icon`, issues);
2420
+ });
2421
+ }
2422
+ function validateOptionalIcon(value, path, issues) {
2423
+ if (value !== void 0 && !isNonEmptyString(value)) {
2424
+ issues.push({ level: "error", message: `${path} must be a non-empty string` });
2425
+ }
2426
+ }
2427
+ function validateApplicationLaunch(spec, issues) {
2428
+ const launch = spec.launch;
2429
+ if (launch === void 0) return;
2430
+ const error = (message) => issues.push({ level: "error", message });
2431
+ if (!launch || typeof launch !== "object" || Array.isArray(launch)) {
2432
+ error("spec.launch must be an object");
2433
+ return;
2434
+ }
2435
+ if (launch.pinnable === true && launch.enabled !== true) {
2436
+ error("spec.launch.pinnable requires spec.launch.enabled");
2437
+ }
2438
+ if (launch.enabled !== true) return;
2439
+ const launchEntryPoint = launch["entry-point"];
2440
+ if (launchEntryPoint !== void 0 && (typeof launchEntryPoint !== "string" || !launchEntryPoint.trim())) {
2441
+ error("spec.launch.entry-point must be a non-empty entry-point id");
2442
+ return;
2443
+ }
2444
+ if (typeof launchEntryPoint === "string") {
2445
+ const entryPoint = spec["entry-points"]?.find((candidate) => candidate.id === launchEntryPoint);
2446
+ if (!entryPoint) {
2447
+ error(`spec.launch.entry-point '${launchEntryPoint}' does not match spec.entry-points[].id`);
2448
+ return;
2449
+ }
2450
+ if (!resolvesIframeEntry(spec.entry, entryPoint.entry ?? entryPoint.route)) {
2451
+ error("spec.launch.enabled requires the selected entry point to resolve an iframe entry");
2452
+ }
2453
+ return;
2454
+ }
2455
+ if (!isAbsoluteHttpUrl(spec.entry)) {
2456
+ error("spec.launch.enabled requires spec.entry or spec.launch.entry-point");
2457
+ }
2458
+ }
2459
+ function isNonEmptyString(value) {
2460
+ return typeof value === "string" && value.trim().length > 0;
2461
+ }
2462
+ function resolvesIframeEntry(baseEntry, routeOrEntry) {
2463
+ if (isAbsoluteHttpUrl(routeOrEntry)) return true;
2464
+ return isAbsoluteHttpUrl(baseEntry);
2465
+ }
2466
+ function isAbsoluteHttpUrl(value) {
2467
+ if (!isNonEmptyString(value)) return false;
2468
+ try {
2469
+ const url = new URL(value);
2470
+ return url.protocol === "http:" || url.protocol === "https:";
2471
+ } catch {
2472
+ return false;
2473
+ }
2474
+ }
2475
+ function validateInstallDirectives(install, issues) {
2476
+ if (install === void 0) return;
2477
+ const error = (message) => issues.push({ level: "error", message });
2478
+ if (!Array.isArray(install)) {
2479
+ error("spec.install must be a list of install directives");
2480
+ return;
2481
+ }
2482
+ install.forEach((directive, index) => {
2483
+ const at = `spec.install[${index}]`;
2484
+ if (!directive || typeof directive !== "object") {
2485
+ error(`${at} must be an object with 'from' and 'to'`);
2486
+ return;
2487
+ }
2488
+ if (!directive.from || typeof directive.from !== "string") {
2489
+ error(`${at}.from is required (a path/glob relative to the package payload)`);
2490
+ } else if (directive.from.startsWith("/") || directive.from.split("/").includes("..")) {
2491
+ error(`${at}.from must be a relative path inside the package payload (no leading '/' or '..')`);
2492
+ }
2493
+ if (!directive.to || typeof directive.to !== "string") {
2494
+ error(`${at}.to is required (a workspace-absolute destination path)`);
2495
+ } else {
2496
+ if (!directive.to.startsWith("/")) error(`${at}.to must be a workspace-absolute path (start with '/')`);
2497
+ if (directive.to.split("/").includes("..")) error(`${at}.to must not contain '..'`);
2498
+ }
2499
+ if (directive.mode !== void 0 && directive.mode !== "seed" && directive.mode !== "managed") {
2500
+ error(`${at}.mode must be 'seed' or 'managed' (got '${directive.mode}')`);
2501
+ }
2502
+ if (directive.phase !== void 0 && (!Number.isInteger(directive.phase) || directive.phase < 0)) {
2503
+ error(`${at}.phase must be a non-negative integer (got '${String(directive.phase)}')`);
2504
+ }
2505
+ });
2506
+ }
2507
+ var SETTING_KEY_PATTERN = /^[a-z0-9]+([.-][a-z0-9]+)*$/;
2508
+ var ENV_VAR_PATTERN = /^[A-Z][A-Z0-9_]*$/;
2509
+ var SETTING_TYPES = ["string", "number", "boolean", "select", "file"];
2510
+ function validateSettingDeclarations(isEngine, spec, issues) {
2511
+ const settings2 = spec.settings;
2512
+ if (settings2 === void 0) return;
2513
+ const error = (message) => issues.push({ level: "error", message });
2514
+ if (!Array.isArray(settings2)) {
2515
+ error("spec.settings must be a list of setting declarations");
2516
+ return;
2517
+ }
1753
2518
  const seen = /* @__PURE__ */ new Set();
1754
2519
  settings2.forEach((declaration, index) => {
1755
2520
  const at = `spec.settings[${index}]`;
@@ -1793,7 +2558,7 @@ function validateSettingDeclarations(kind, spec, issues) {
1793
2558
  error(`${at}.options is only allowed for type 'select'`);
1794
2559
  }
1795
2560
  });
1796
- if (kind === "ExecutionEngine") {
2561
+ if (isEngine) {
1797
2562
  const declaresSecret = settings2.some(
1798
2563
  (declaration) => declaration && typeof declaration === "object" && declaration.secret === true
1799
2564
  );
@@ -2069,461 +2834,381 @@ function registerExec(program2) {
2069
2834
  if (logs.truncated) console.error("(logs truncated \u2014 the full log exceeded the inline limit)");
2070
2835
  if (logs.running) console.error("(execution still running \u2014 use --follow to stream)");
2071
2836
  });
2072
- const engineCmd = program2.command("engine").description("Inspect execution engines");
2073
- engineCmd.command("list").description("List registered execution engines").option("--json", "output JSON").action(async (options) => {
2074
- const api = await createApiClient();
2075
- const page = await call(api, execution.listEngines, {
2076
- query: { PageNo: 1, PageSize: 100 }
2077
- });
2078
- output(pageItems(page), { name: "Name", displayName: "Display", version: "Version", id: "Id" }, options, page);
2079
- });
2080
- engineCmd.command("get <engineId>").description("Show engine details (runtimes, tools, permissions)").action(async (engineId) => {
2081
- const api = await createApiClient();
2082
- const result = await call(api, execution.getEngine, { params: { id: engineId } });
2083
- printJson(result);
2084
- });
2085
- engineCmd.command("resolve <fileTypeOrPath>").description("Resolve which engine handles a MIME type or file path").option("--workspace <workspaceId>").action(async (fileTypeOrPath, options) => {
2086
- const api = await createApiClient();
2087
- const workspaceId = await resolveWorkspaceId(options, false);
2088
- const query = fileTypeOrPath.includes("/") && !fileTypeOrPath.includes(".") ? { fileType: fileTypeOrPath } : fileTypeOrPath.includes(".") && !fileTypeOrPath.includes("/") ? { fileType: fileTypeOrPath } : { filePath: fileTypeOrPath };
2089
- const result = await call(api, execution.resolveEngine, {
2090
- query: { ...query, ...workspaceId ? { workspaceId } : {} }
2091
- });
2092
- printJson(result);
2093
- });
2094
- engineCmd.command("sync").description("Re-scan the workspace for engine manifests and sync registrations").option("--workspace <workspaceId>").action(async (options) => {
2095
- const workspaceId = await resolveWorkspaceId(options);
2096
- const api = await createApiClient();
2097
- const result = await call(api, execution.syncEngines, { workspaceId, body: { workspaceId } });
2098
- printJson(result);
2099
- });
2100
- }
2101
- function printResult(exec) {
2102
- if (!exec.result) return;
2103
- if (exec.result.error) console.error(`Error: ${exec.result.error}`);
2104
- if (exec.result.data !== void 0 && exec.result.data !== null) {
2105
- console.log("Result:");
2106
- printJson(exec.result.data);
2107
- }
2108
- for (const artifact of exec.result.artifacts ?? []) console.log(`Artifact: ${artifact}`);
2109
- }
2110
- async function streamLogs(api, workspaceId, executionId) {
2111
- const res = await callRaw(api, execution.logsStream, {
2112
- params: { id: executionId },
2113
- workspaceId,
2114
- query: { workspaceId }
2115
- });
2116
- if (!res.body) return;
2117
- const decoder = new TextDecoder();
2118
- let buffer = "";
2119
- let currentEvent = "message";
2120
- const reader = res.body.getReader();
2121
- for (; ; ) {
2122
- const { done, value } = await reader.read();
2123
- if (done) break;
2124
- buffer += decoder.decode(value, { stream: true });
2125
- let newlineIdx;
2126
- while ((newlineIdx = buffer.indexOf("\n")) >= 0) {
2127
- const line = buffer.slice(0, newlineIdx).replace(/\r$/, "");
2128
- buffer = buffer.slice(newlineIdx + 1);
2129
- if (line.startsWith("event: ")) {
2130
- currentEvent = line.slice(7).trim();
2131
- } else if (line.startsWith("data: ")) {
2132
- if (currentEvent === "end") return;
2133
- console.log(line.slice(6));
2134
- } else if (line === "") {
2135
- currentEvent = "message";
2136
- }
2137
- }
2138
- }
2139
- }
2140
- async function followExecution(api, workspaceId, executionId, json) {
2141
- await streamLogs(api, workspaceId, executionId);
2142
- for (let attempt = 0; attempt < 30; attempt++) {
2143
- const exec = await call(api, execution.get, {
2144
- params: { id: executionId },
2145
- workspaceId,
2146
- query: { workspaceId }
2147
- });
2148
- if (TERMINAL_STATUSES.has(exec.status)) {
2149
- if (json) printJson(exec);
2150
- else {
2151
- console.log(`Status: ${exec.status}`);
2152
- printResult(exec);
2153
- }
2154
- if (exec.status !== "Completed") process.exitCode = 1;
2155
- return;
2156
- }
2157
- await new Promise((resolve15) => setTimeout(resolve15, 1e3));
2158
- }
2159
- console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
2160
- process.exitCode = 1;
2161
- }
2162
- var normalizeRemote = (path) => {
2163
- const trimmed = path.replace(/^\/+/, "").replace(/\/+$/, "");
2164
- return trimmed;
2165
- };
2166
- async function uploadWithHeaders(api, workspaceId, remotePath, localPath, options) {
2167
- const buffer = await readFile(localPath);
2168
- const form = new FormData();
2169
- form.append("file", new Blob([buffer], { type: options.contentType ?? "application/octet-stream" }), basename(localPath));
2170
- form.append("metadata", JSON.stringify({ branch: options.branch, contentType: options.contentType }));
2171
- const res = await api.requestRaw("POST", fillPath(files.upload.path, { path: normalizeRemote(remotePath) }), {
2172
- scopes: [...files.upload.scopes],
2173
- tokenWorkspaceId: workspaceId,
2174
- rawBody: form,
2175
- headers: {
2176
- ...options.autoExtract ? { "X-Auto-Extract": "true" } : {}
2177
- }
2178
- });
2179
- return await res.json();
2180
- }
2181
- function registerFiles(program2) {
2182
- const filesCmd = program2.command("files").description("Work with workspace files (the VFS)");
2183
- filesCmd.command("ls [path]").description("List a directory in the workspace").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--json", "output JSON").action(async (path, options) => {
2184
- const workspaceId = await resolveWorkspaceId(options);
2185
- const api = await createApiClient();
2186
- const result = await call(api, files.get, {
2187
- params: { path: normalizeRemote(path ?? "/") },
2188
- workspaceId,
2189
- query: { branch: options.branch, PageNo: 1, PageSize: 100 }
2190
- });
2191
- const entries = pageItems(result.children);
2192
- if (entries.length === 0 && result.name) {
2193
- outputRecord(result, options);
2194
- return;
2195
- }
2196
- output(
2197
- entries.map((entry) => ({ ...entry, size: entry.size ?? "" })),
2198
- { name: "Name", mimeType: "Type", size: "Size", path: "Path" },
2199
- options,
2200
- result
2201
- );
2202
- });
2203
- filesCmd.command("stat <path>").description("Show file metadata").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--json", "output JSON").action(async (path, options) => {
2204
- const workspaceId = await resolveWorkspaceId(options);
2205
- const api = await createApiClient();
2206
- const result = await call(api, files.get, {
2207
- params: { path: normalizeRemote(path) },
2208
- workspaceId,
2209
- // The Node files endpoint requires paging for its children listing; stat discards children.
2210
- query: { branch: options.branch, PageNo: 1, PageSize: 1 }
2211
- });
2212
- const { children, ...rest } = result;
2213
- outputRecord(rest, options);
2214
- });
2215
- filesCmd.command("cat <path>").description("Print raw file content to stdout").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").action(async (path, options) => {
2216
- const workspaceId = await resolveWorkspaceId(options);
2217
- const api = await createApiClient();
2218
- const res = await callRaw(api, files.raw, {
2219
- params: { path: normalizeRemote(path) },
2220
- workspaceId,
2221
- query: { branch: options.branch }
2222
- });
2223
- if (!res.body) return;
2224
- await pipeline(Readable.fromWeb(res.body), process.stdout, { end: false });
2225
- });
2226
- filesCmd.command("download <remotePath> [localPath]").description("Download a file (or directory as an archive with --format)").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--format <format>", "archive format for directories: Zip | TarGz").action(async (remotePath, localPath, options) => {
2227
- const workspaceId = await resolveWorkspaceId(options);
2837
+ const engineCmd = program2.command("engine").description("Inspect execution engines");
2838
+ engineCmd.command("list").description("List registered execution engines").option("--json", "output JSON").action(async (options) => {
2228
2839
  const api = await createApiClient();
2229
- const res = await callRaw(api, files.raw, {
2230
- params: { path: normalizeRemote(remotePath) },
2231
- workspaceId,
2232
- query: { branch: options.branch, format: options.format }
2840
+ const page = await call(api, execution.listEngines, {
2841
+ query: { PageNo: 1, PageSize: 100 }
2233
2842
  });
2234
- const suffix = options.format === "Zip" ? ".zip" : options.format === "TarGz" ? ".tar.gz" : "";
2235
- const out = resolve(localPath ?? `${basename(normalizeRemote(remotePath)) || "download"}${suffix}`);
2236
- if (!res.body) throw new Error("Empty response.");
2237
- await mkdir(dirname(out), { recursive: true });
2238
- await pipeline(Readable.fromWeb(res.body), createWriteStream(out));
2239
- console.log(`Downloaded ${remotePath} \u2192 ${out}`);
2843
+ output(pageItems(page), { name: "Name", displayName: "Display", version: "Version", id: "Id" }, options, page);
2240
2844
  });
2241
- filesCmd.command("upload <localPath> [remotePath]").description("Upload a file or directory (directories upload file-by-file)").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--content-type <type>", "content type for a single-file upload").option("--extract", "archive uploads: extract server-side into the target directory (X-Auto-Extract)").action(async (localPath, remotePath, options) => {
2242
- const workspaceId = await resolveWorkspaceId(options);
2845
+ engineCmd.command("get <engineId>").description("Show engine details (runtimes, tools, permissions)").action(async (engineId) => {
2243
2846
  const api = await createApiClient();
2244
- const local = resolve(localPath);
2245
- const info = await stat(local);
2246
- if (info.isDirectory()) {
2247
- const remoteBase = normalizeRemote(remotePath ?? basename(local));
2248
- const uploaded = await uploadDirectory(api, workspaceId, local, remoteBase, options.branch);
2249
- console.log(`Uploaded ${uploaded} file(s) to /${remoteBase}.`);
2250
- return;
2251
- }
2252
- const remote = remotePath && remotePath.endsWith("/") ? posix.join(normalizeRemote(remotePath), basename(local)) : normalizeRemote(remotePath ?? basename(local));
2253
- const result = await uploadWithHeaders(api, workspaceId, remote, local, {
2254
- branch: options.branch,
2255
- contentType: options.contentType,
2256
- autoExtract: options.extract
2257
- });
2258
- console.log(`Uploaded ${localPath} \u2192 /${result.path ?? remote}`);
2847
+ const result = await call(api, execution.getEngine, { params: { id: engineId } });
2848
+ printJson(result);
2259
2849
  });
2260
- 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) => {
2261
- const workspaceId = await resolveWorkspaceId(options);
2850
+ engineCmd.command("resolve <fileTypeOrPath>").description("Resolve which engine handles a MIME type or file path").option("--workspace <workspaceId>").action(async (fileTypeOrPath, options) => {
2262
2851
  const api = await createApiClient();
2263
- await api.requestRaw("DELETE", fillPath(files.delete.path, { path: normalizeRemote(path) }), {
2264
- scopes: [...files.delete.scopes],
2265
- tokenWorkspaceId: workspaceId,
2266
- query: { branch: options.branch },
2267
- headers: options.recursive ? { "X-Delete-Mode": "Deep" } : {}
2852
+ const workspaceId = await resolveWorkspaceId(options, false);
2853
+ const query = fileTypeOrPath.includes("/") && !fileTypeOrPath.includes(".") ? { fileType: fileTypeOrPath } : fileTypeOrPath.includes(".") && !fileTypeOrPath.includes("/") ? { fileType: fileTypeOrPath } : { filePath: fileTypeOrPath };
2854
+ const result = await call(api, execution.resolveEngine, {
2855
+ query: { ...query, ...workspaceId ? { workspaceId } : {} }
2268
2856
  });
2269
- console.log(`Deleted /${normalizeRemote(path)}.`);
2857
+ printJson(result);
2270
2858
  });
2271
- 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) => {
2859
+ engineCmd.command("sync").description("Re-scan the workspace for engine manifests and sync registrations").option("--workspace <workspaceId>").action(async (options) => {
2272
2860
  const workspaceId = await resolveWorkspaceId(options);
2273
2861
  const api = await createApiClient();
2274
- await call(api, files.update, {
2275
- params: { path: normalizeRemote(fromPath) },
2276
- workspaceId,
2277
- body: { branch: options.branch, path: normalizeRemote(fromPath), toPath: normalizeRemote(toPath) }
2278
- });
2279
- console.log(`Moved /${normalizeRemote(fromPath)} \u2192 /${normalizeRemote(toPath)}.`);
2862
+ const result = await call(api, execution.syncEngines, { workspaceId, body: { workspaceId } });
2863
+ printJson(result);
2280
2864
  });
2281
2865
  }
2282
- async function uploadDirectory(api, workspaceId, localDir, remoteBase, branch) {
2283
- let count = 0;
2284
- const entries = await readdir(localDir, { withFileTypes: true });
2285
- for (const entry of entries) {
2286
- if (entry.name.startsWith(".git") || entry.name === "node_modules" || entry.name === "__pycache__") continue;
2287
- const localEntry = join(localDir, entry.name);
2288
- const remoteEntry = posix.join(remoteBase, entry.name);
2289
- if (entry.isDirectory()) {
2290
- count += await uploadDirectory(api, workspaceId, localEntry, remoteEntry, branch);
2291
- } else if (entry.isFile()) {
2292
- await uploadWithHeaders(api, workspaceId, remoteEntry, localEntry, { branch });
2293
- console.log(` /${remoteEntry}`);
2294
- count += 1;
2295
- }
2296
- }
2297
- return count;
2298
- }
2299
- var MAX_ICON_BYTES = 32 * 1024;
2300
- var MAX_TOTAL_ICON_BYTES = 256 * 1024;
2301
- var LEGACY_ICON_PATTERN = /^[a-z0-9-]+(:[a-z0-9-]+)?$/;
2302
- var SVG_START = /^(?:<\?xml[\s\S]*?\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg\b/i;
2303
- var SVG_END_CLOSING = /<\/svg>\s*$/i;
2304
- var SVG_END_SELF_CLOSING = /<svg\b[\s\S]*\/>\s*$/i;
2305
- var SVG_REJECTIONS = [
2306
- [/&#/i, "numeric character references (&#) are not allowed"],
2307
- [/<!DOCTYPE|<!ENTITY/i, "<!DOCTYPE>/<!ENTITY> declarations are not allowed"],
2308
- [/<(?:script|foreignObject|iframe|object|embed|audio|video)\b/i, "script, foreignObject, iframe, object, embed, audio and video elements are not allowed"],
2309
- [/\son[a-z]+\s*=/i, "event handler (on*=) attributes are not allowed"],
2310
- [/(?:javascript|vbscript)\s*:/i, "javascript:/vbscript: URLs are not allowed"],
2311
- [/data\s*:\s*text\/html/i, "data:text/html URLs are not allowed"],
2312
- [/(?:xlink:href|href)\s*=\s*["']?\s*(?:https?:|ftp:|\/\/)/i, "external href/xlink:href references are not allowed"],
2313
- [/url\(\s*["']?\s*(?:https?:|\/\/)/i, "external url(...) references are not allowed"]
2314
- ];
2315
- function validateSvgIcon(text) {
2316
- if (Buffer.byteLength(text, "utf8") > MAX_ICON_BYTES) return `SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit`;
2317
- const markup = canonicalizeSvg(text);
2318
- if (!SVG_START.test(markup)) return "SVG must have an <svg> root element (only an <?xml ?> declaration and comments may precede it)";
2319
- if (!SVG_END_CLOSING.test(markup) && !SVG_END_SELF_CLOSING.test(markup)) return "SVG must end with </svg>";
2320
- for (const [pattern, reason] of SVG_REJECTIONS) {
2321
- if (pattern.test(markup)) return reason;
2322
- }
2323
- return null;
2324
- }
2325
- function canonicalizeSvg(text) {
2326
- return text.replace(/^\uFEFF+/, "").trim();
2327
- }
2328
- function decodeUtf8(bytes) {
2329
- try {
2330
- return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2331
- } catch {
2332
- return null;
2333
- }
2334
- }
2335
- function classifyIconValue(value) {
2336
- const trimmed = value.trim();
2337
- if (trimmed.startsWith("<")) return "inline";
2338
- if (trimmed.startsWith("#")) return "ref";
2339
- if (/\.svg$/i.test(trimmed)) return "path";
2340
- if (LEGACY_ICON_PATTERN.test(trimmed)) return "legacy";
2341
- return "invalid";
2342
- }
2343
- function collectIconFields(manifest) {
2344
- const fields = [];
2345
- if (!isRecord(manifest)) return fields;
2346
- const add = (path, value) => {
2347
- if (value !== void 0) fields.push({ path, label: formatPath(path), value });
2348
- };
2349
- const bindings = (container, path) => {
2350
- if (!Array.isArray(container)) return;
2351
- container.forEach((item, index) => {
2352
- if (isRecord(item)) add([...path, index, "icon"], item.icon);
2353
- });
2354
- };
2355
- if (isRecord(manifest.metadata)) add(["metadata", "icon"], manifest.metadata.icon);
2356
- const spec = manifest.spec;
2357
- if (!isRecord(spec)) return fields;
2358
- if (Array.isArray(spec["entry-points"])) {
2359
- spec["entry-points"].forEach((entryPoint, index) => {
2360
- if (!isRecord(entryPoint)) return;
2361
- add(["spec", "entry-points", index, "icon"], entryPoint.icon);
2362
- bindings(entryPoint["mime-types"], ["spec", "entry-points", index, "mime-types"]);
2363
- });
2866
+ function printResult(exec) {
2867
+ if (!exec.result) return;
2868
+ if (exec.result.error) console.error(`Error: ${exec.result.error}`);
2869
+ if (exec.result.data !== void 0 && exec.result.data !== null) {
2870
+ console.log("Result:");
2871
+ printJson(exec.result.data);
2364
2872
  }
2365
- bindings(spec["mime-types"], ["spec", "mime-types"]);
2366
- bindings(spec["file-types"], ["spec", "file-types"]);
2367
- return fields;
2873
+ for (const artifact of exec.result.artifacts ?? []) console.log(`Artifact: ${artifact}`);
2368
2874
  }
2369
- async function resolveManifestIcons(manifest, manifestDir) {
2370
- const errors = [];
2371
- const warnings = [];
2372
- const fields = [];
2373
- const root = resolve(manifestDir);
2374
- const distinct = /* @__PURE__ */ new Set();
2375
- const resolveSvg = async (label, value, allowLegacy) => {
2376
- const kind = classifyIconValue(value);
2377
- if (kind === "inline") return checkMarkup(label, value.trim(), "inline SVG");
2378
- if (kind === "path") {
2379
- const loaded = await readIconFile(root, value.trim());
2380
- if ("error" in loaded) {
2381
- errors.push(`${label}: ${loaded.error}`);
2382
- return void 0;
2383
- }
2384
- return checkMarkup(label, loaded.text, value.trim());
2385
- }
2386
- if (kind === "legacy" && allowLegacy) return void 0;
2387
- 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`);
2388
- return void 0;
2389
- };
2390
- const checkMarkup = (label, text, source) => {
2391
- const problem = validateSvgIcon(text);
2392
- if (problem) {
2393
- errors.push(`${label}: ${source}: ${problem}`);
2394
- return void 0;
2395
- }
2396
- const markup = canonicalizeSvg(text);
2397
- distinct.add(markup);
2398
- return markup;
2399
- };
2400
- const map = /* @__PURE__ */ new Map();
2401
- const iconsSection = isRecord(manifest) ? manifest.icons : void 0;
2402
- if (iconsSection !== void 0) {
2403
- if (!isRecord(iconsSection)) {
2404
- errors.push("icons must be a map of key -> SVG file path or inline <svg> markup");
2405
- } else {
2406
- for (const [key, value] of Object.entries(iconsSection)) {
2407
- const label = `icons.${key}`;
2408
- if (typeof value !== "string" || value.trim().length === 0) {
2409
- errors.push(`${label} must be a non-empty string`);
2410
- map.set(key, void 0);
2411
- continue;
2412
- }
2413
- map.set(key, await resolveSvg(label, value, false));
2875
+ async function streamLogs(api, workspaceId, executionId) {
2876
+ const res = await callRaw(api, execution.logsStream, {
2877
+ params: { id: executionId },
2878
+ workspaceId,
2879
+ query: { workspaceId }
2880
+ });
2881
+ if (!res.body) return;
2882
+ const decoder = new TextDecoder();
2883
+ let buffer = "";
2884
+ let currentEvent = "message";
2885
+ const reader = res.body.getReader();
2886
+ for (; ; ) {
2887
+ const { done, value } = await reader.read();
2888
+ if (done) break;
2889
+ buffer += decoder.decode(value, { stream: true });
2890
+ let newlineIdx;
2891
+ while ((newlineIdx = buffer.indexOf("\n")) >= 0) {
2892
+ const line = buffer.slice(0, newlineIdx).replace(/\r$/, "");
2893
+ buffer = buffer.slice(newlineIdx + 1);
2894
+ if (line.startsWith("event: ")) {
2895
+ currentEvent = line.slice(7).trim();
2896
+ } else if (line.startsWith("data: ")) {
2897
+ if (currentEvent === "end") return;
2898
+ console.log(line.slice(6));
2899
+ } else if (line === "") {
2900
+ currentEvent = "message";
2414
2901
  }
2415
2902
  }
2416
2903
  }
2417
- for (const field of collectIconFields(manifest)) {
2418
- if (typeof field.value !== "string" || field.value.trim().length === 0) {
2419
- errors.push(`${field.label} must be a non-empty string`);
2420
- continue;
2421
- }
2422
- const value = field.value;
2423
- const kind = classifyIconValue(value);
2424
- if (kind === "legacy") {
2425
- warnings.push(`${field.label}: '${value}' is a legacy Iconify icon; run \`verentis icons migrate\` to convert it to SVG`);
2426
- fields.push({ ...field, value, legacy: true });
2427
- continue;
2428
- }
2429
- if (kind === "ref") {
2430
- const key = value.trim().slice(1);
2431
- if (!map.has(key)) {
2432
- errors.push(`${field.label}: ${value.trim()} does not match a key in the top-level icons map`);
2433
- continue;
2904
+ }
2905
+ async function followExecution(api, workspaceId, executionId, json) {
2906
+ await streamLogs(api, workspaceId, executionId);
2907
+ for (let attempt = 0; attempt < 30; attempt++) {
2908
+ const exec = await call(api, execution.get, {
2909
+ params: { id: executionId },
2910
+ workspaceId,
2911
+ query: { workspaceId }
2912
+ });
2913
+ if (TERMINAL_STATUSES.has(exec.status)) {
2914
+ if (json) printJson(exec);
2915
+ else {
2916
+ console.log(`Status: ${exec.status}`);
2917
+ printResult(exec);
2434
2918
  }
2435
- const markup2 = map.get(key);
2436
- if (markup2 !== void 0) fields.push({ ...field, value, markup: markup2, legacy: false });
2437
- continue;
2438
- }
2439
- const markup = await resolveSvg(field.label, value, true);
2440
- if (markup !== void 0) fields.push({ ...field, value, markup, legacy: false });
2441
- }
2442
- let logoIcon;
2443
- const metadata = isRecord(manifest) && isRecord(manifest.metadata) ? manifest.metadata : void 0;
2444
- const marketplace2 = isRecord(manifest) && isRecord(manifest.marketplace) ? manifest.marketplace : void 0;
2445
- if (metadata && metadata.icon === void 0 && typeof marketplace2?.logo === "string" && /\.svg$/i.test(marketplace2.logo.trim())) {
2446
- const loaded = await readIconFile(root, marketplace2.logo.trim());
2447
- const problem = "error" in loaded ? loaded.error : validateSvgIcon(loaded.text);
2448
- if (problem || "error" in loaded) {
2449
- warnings.push(`marketplace.logo cannot be used as the app icon (metadata.icon fallback): ${problem}`);
2450
- } else {
2451
- logoIcon = canonicalizeSvg(loaded.text);
2452
- distinct.add(logoIcon);
2919
+ if (exec.status !== "Completed") process.exitCode = 1;
2920
+ return;
2453
2921
  }
2922
+ await new Promise((resolve16) => setTimeout(resolve16, 1e3));
2454
2923
  }
2455
- const total = [...distinct].reduce((sum, markup) => sum + Buffer.byteLength(markup, "utf8"), 0);
2456
- if (total > MAX_TOTAL_ICON_BYTES) {
2457
- errors.push(`icons: total distinct SVG markup is ${(total / 1024).toFixed(1)} KiB, exceeding the ${MAX_TOTAL_ICON_BYTES / 1024} KiB per-manifest limit`);
2458
- }
2459
- const needsInlining = logoIcon !== void 0 || iconsSection !== void 0 || fields.some((field) => !field.legacy);
2460
- return { errors, warnings, fields, logoIcon, needsInlining };
2924
+ console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
2925
+ process.exitCode = 1;
2461
2926
  }
2462
- async function readIconFile(root, source) {
2463
- if (isAbsolute(source) || /^[a-z][a-z0-9+.-]*:/i.test(source) || source.includes("\\")) {
2464
- return { error: `${source} must be a path relative to the manifest directory` };
2465
- }
2466
- const candidate = resolve(root, source);
2467
- if (escapes(root, candidate)) return { error: `${source} escapes the package directory` };
2468
- let actual;
2469
- let realRoot;
2470
- try {
2471
- actual = await realpath(candidate);
2472
- realRoot = await realpath(root);
2473
- } catch {
2474
- return { error: `${source} not found` };
2475
- }
2476
- if (escapes(realRoot, actual)) return { error: `${source} escapes the package directory` };
2477
- let bytes;
2927
+ var normalizeRemote = (path) => {
2928
+ const trimmed = path.replace(/^\/+/, "").replace(/\/+$/, "");
2929
+ return trimmed;
2930
+ };
2931
+ var TERMINAL_IMPORT_STATES = /* @__PURE__ */ new Set(["Succeeded", "Failed", "Cancelled"]);
2932
+ var archiveImportPolling = {
2933
+ initialDelayMs: 1e3,
2934
+ maxDelayMs: 5e3,
2935
+ backoff: 1.5,
2936
+ sleep: (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms))
2937
+ };
2938
+ var isZipName = (name) => name.toLowerCase().endsWith(".zip");
2939
+ async function uploadWithHeaders(api, workspaceId, remotePath, localPath, options) {
2940
+ const buffer = await readFile(localPath);
2941
+ const contentType = options.contentType ?? (isZipName(localPath) ? "application/zip" : "application/octet-stream");
2942
+ const form = new FormData();
2943
+ form.append("file", new Blob([buffer], { type: contentType }), basename(localPath));
2944
+ form.append("metadata", JSON.stringify({ branch: options.branch, contentType: options.contentType }));
2945
+ const headers = {};
2946
+ if (options.autoExtract !== void 0) headers["X-Auto-Extract"] = String(options.autoExtract);
2947
+ if (options.conflict) headers["X-Archive-Conflict"] = options.conflict;
2948
+ const res = await api.requestRaw("POST", fillPath(files.upload.path, { path: normalizeRemote(remotePath) }), {
2949
+ scopes: [...files.upload.scopes],
2950
+ tokenWorkspaceId: workspaceId,
2951
+ rawBody: form,
2952
+ headers
2953
+ });
2954
+ const text = await res.text().catch(() => "");
2955
+ let body;
2478
2956
  try {
2479
- bytes = await readFile(actual);
2957
+ body = text ? unwrap(JSON.parse(text)) : void 0;
2480
2958
  } catch {
2481
- return { error: `${source} could not be read (is it a file?)` };
2959
+ body = text;
2960
+ }
2961
+ return { status: res.status, location: res.headers?.get("Location") ?? void 0, body };
2962
+ }
2963
+ function zipHasRootManifest(buffer) {
2964
+ const EOCD = 101010256;
2965
+ const CDH = 33639248;
2966
+ const minStart = Math.max(0, buffer.length - 22 - 65535);
2967
+ for (let i = buffer.length - 22; i >= minStart; i--) {
2968
+ if (buffer.readUInt32LE(i) !== EOCD) continue;
2969
+ let offset = buffer.readUInt32LE(i + 16);
2970
+ if (offset === 4294967295 || offset >= buffer.length) return void 0;
2971
+ while (offset + 46 <= buffer.length && buffer.readUInt32LE(offset) === CDH) {
2972
+ const nameLength = buffer.readUInt16LE(offset + 28);
2973
+ const extraLength = buffer.readUInt16LE(offset + 30);
2974
+ const commentLength = buffer.readUInt16LE(offset + 32);
2975
+ const name = buffer.subarray(offset + 46, offset + 46 + nameLength).toString("utf8");
2976
+ if (name === ".verentis-manifest.json" || name === "./.verentis-manifest.json") return true;
2977
+ offset += 46 + nameLength + extraLength + commentLength;
2978
+ }
2979
+ return false;
2482
2980
  }
2483
- if (bytes.length > MAX_ICON_BYTES) return { error: `${source}: SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit` };
2484
- const text = decodeUtf8(bytes);
2485
- if (text === null) return { error: `${source} is not valid UTF-8` };
2486
- return { text };
2487
- }
2488
- function escapes(root, candidate) {
2489
- const fromRoot = relative(root, candidate);
2490
- return fromRoot === "" || fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot);
2491
- }
2492
- function iconKey(markup) {
2493
- return createHash("sha256").update(markup, "utf8").digest("hex").slice(0, 12);
2981
+ return void 0;
2494
2982
  }
2495
- function inlineIconsIntoDocument(document, resolution) {
2496
- const icons = /* @__PURE__ */ new Map();
2497
- const quoted = (text) => Object.assign(new Scalar(text), { type: Scalar.QUOTE_DOUBLE });
2498
- for (const field of resolution.fields) {
2499
- if (field.markup === void 0) continue;
2500
- const key = iconKey(field.markup);
2501
- icons.set(key, field.markup);
2502
- document.setIn(field.path, quoted(`#${key}`));
2503
- }
2504
- if (resolution.logoIcon !== void 0) {
2505
- const key = iconKey(resolution.logoIcon);
2506
- icons.set(key, resolution.logoIcon);
2507
- document.setIn(["metadata", "icon"], quoted(`#${key}`));
2983
+ var importJobId = (upload) => {
2984
+ const body = upload.body;
2985
+ if (body && typeof body === "object" && typeof body.id === "string") return body.id;
2986
+ const match = upload.location?.match(/archive-imports\/([^/?#]+)/);
2987
+ return match ? decodeURIComponent(match[1]) : void 0;
2988
+ };
2989
+ async function getImportStatus(api, workspaceId, id, branch) {
2990
+ return call(api, files.archiveImportStatus, { params: { id }, workspaceId, query: { branch } });
2991
+ }
2992
+ var progressLine = (status) => {
2993
+ const total = status.total ?? "?";
2994
+ const parts = [`${status.state}`, `${status.processed ?? 0}/${total}`];
2995
+ if (status.skipped) parts.push(`skipped ${status.skipped}`);
2996
+ if (status.failed) parts.push(`failed ${status.failed}`);
2997
+ return `Archive import ${status.id}: ${parts.join(", ")}`;
2998
+ };
2999
+ async function waitForArchiveImport(api, workspaceId, id, branch, initial) {
3000
+ const tty = Boolean(process.stderr.isTTY);
3001
+ let status = initial;
3002
+ let delay = archiveImportPolling.initialDelayMs;
3003
+ let lastLine = "";
3004
+ for (; ; ) {
3005
+ if (status) {
3006
+ const line = progressLine(status);
3007
+ if (line !== lastLine) {
3008
+ process.stderr.write(tty ? `\r\x1B[2K${line}` : `${line}
3009
+ `);
3010
+ lastLine = line;
3011
+ }
3012
+ if (TERMINAL_IMPORT_STATES.has(status.state)) break;
3013
+ await archiveImportPolling.sleep(delay);
3014
+ delay = Math.min(archiveImportPolling.maxDelayMs, Math.round(delay * archiveImportPolling.backoff));
3015
+ }
3016
+ status = await getImportStatus(api, workspaceId, id, branch);
2508
3017
  }
2509
- if (icons.size === 0) {
2510
- if (document.has("icons")) document.delete("icons");
2511
- return;
3018
+ if (tty && lastLine) process.stderr.write("\n");
3019
+ return status;
3020
+ }
3021
+ function reportImport(status, options) {
3022
+ if (options.json) printJson(status);
3023
+ else {
3024
+ const root = status.rootPath ?? status.targetPath;
3025
+ console.log(`Archive import ${status.id} ${status.state}${root ? ` \u2192 ${root}` : ""}: ${status.processed ?? 0}/${status.total ?? "?"} processed, ${status.skipped ?? 0} skipped, ${status.failed ?? 0} failed.`);
2512
3026
  }
2513
- const node = new YAMLMap();
2514
- for (const [key, markup] of [...icons.entries()].sort(([a], [b]) => a.localeCompare(b))) {
2515
- node.set(key, Object.assign(new Scalar(markup), { type: Scalar.BLOCK_LITERAL }));
3027
+ if (status.errors?.length) {
3028
+ console.error("Errors:");
3029
+ for (const err of status.errors) console.error(` ${err.path ? `${err.path}: ` : ""}${err.message}`);
2516
3030
  }
2517
- document.set("icons", node);
3031
+ if (status.state === "Failed" || status.state === "Cancelled") process.exitCode = 1;
2518
3032
  }
2519
- function formatPath(path) {
2520
- return path.reduce((text, segment) => typeof segment === "number" ? `${text}[${segment}]` : text ? `${text}.${segment}` : segment, "");
3033
+ var ARCHIVE_FORMATS = { zip: "Zip", tgz: "Tgz", targz: "Tgz", "tar.gz": "Tgz" };
3034
+ function parseArchiveFormat(value) {
3035
+ if (value === void 0) return void 0;
3036
+ const format = ARCHIVE_FORMATS[value.toLowerCase()];
3037
+ if (!format) throw new Error(`Unknown archive format '${value}'. Use zip or tgz.`);
3038
+ return format;
2521
3039
  }
2522
- function isRecord(value) {
2523
- return !!value && typeof value === "object" && !Array.isArray(value);
3040
+ var CONFLICT_POLICIES = /* @__PURE__ */ new Set(["merge", "reject"]);
3041
+ function registerFiles(program2) {
3042
+ const filesCmd = program2.command("files").description("Work with workspace files (the VFS)");
3043
+ filesCmd.command("ls [path]").description("List a directory in the workspace").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--json", "output JSON").action(async (path, options) => {
3044
+ const workspaceId = await resolveWorkspaceId(options);
3045
+ const api = await createApiClient();
3046
+ const result = await call(api, files.get, {
3047
+ params: { path: normalizeRemote(path ?? "/") },
3048
+ workspaceId,
3049
+ query: { branch: options.branch, PageNo: 1, PageSize: 100 }
3050
+ });
3051
+ const entries = pageItems(result.children);
3052
+ if (entries.length === 0 && result.name) {
3053
+ outputRecord(result, options);
3054
+ return;
3055
+ }
3056
+ output(
3057
+ entries.map((entry) => ({ ...entry, size: entry.size ?? "" })),
3058
+ { name: "Name", mimeType: "Type", size: "Size", path: "Path" },
3059
+ options,
3060
+ result
3061
+ );
3062
+ });
3063
+ filesCmd.command("stat <path>").description("Show file metadata").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--json", "output JSON").action(async (path, options) => {
3064
+ const workspaceId = await resolveWorkspaceId(options);
3065
+ const api = await createApiClient();
3066
+ const result = await call(api, files.get, {
3067
+ params: { path: normalizeRemote(path) },
3068
+ workspaceId,
3069
+ // The Node files endpoint requires paging for its children listing; stat discards children.
3070
+ query: { branch: options.branch, PageNo: 1, PageSize: 1 }
3071
+ });
3072
+ const { children, ...rest } = result;
3073
+ outputRecord(rest, options);
3074
+ });
3075
+ filesCmd.command("cat <path>").description("Print raw file content to stdout").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").action(async (path, options) => {
3076
+ const workspaceId = await resolveWorkspaceId(options);
3077
+ const api = await createApiClient();
3078
+ const res = await callRaw(api, files.raw, {
3079
+ params: { path: normalizeRemote(path) },
3080
+ workspaceId,
3081
+ query: { branch: options.branch }
3082
+ });
3083
+ if (!res.body) return;
3084
+ await pipeline(Readable.fromWeb(res.body), process.stdout, { end: false });
3085
+ });
3086
+ filesCmd.command("download <remotePath> [localPath]").description("Download a file, or a folder / file with children as an archive (--archive or --format)").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--archive", "download as an archive (with .verentis-manifest.json); also for files with children").option("--format <format>", "archive format: zip | tgz (implies --archive; default zip)").option("-o, --output <file>", "local output file (same as [localPath])").action(async (remotePath, localPath, options) => {
3087
+ const format = parseArchiveFormat(options.format) ?? (options.archive ? "Zip" : void 0);
3088
+ const workspaceId = await resolveWorkspaceId(options);
3089
+ const api = await createApiClient();
3090
+ const res = await callRaw(api, files.raw, {
3091
+ params: { path: normalizeRemote(remotePath) },
3092
+ workspaceId,
3093
+ query: { branch: options.branch, format }
3094
+ });
3095
+ const suffix = format === "Zip" ? ".zip" : format === "Tgz" ? ".tar.gz" : "";
3096
+ const out = resolve(options.output ?? localPath ?? `${basename(normalizeRemote(remotePath)) || "download"}${suffix}`);
3097
+ if (!res.body) throw new Error("Empty response.");
3098
+ await mkdir(dirname(out), { recursive: true });
3099
+ await pipeline(Readable.fromWeb(res.body), createWriteStream(out));
3100
+ console.log(`Downloaded ${remotePath} \u2192 ${out}`);
3101
+ });
3102
+ filesCmd.command("upload <localPath> [remotePath]").description(
3103
+ "Upload a file or directory (directories upload file-by-file). A .zip with a root .verentis-manifest.json is imported as an archive under [remotePath] (a background job); other zips are stored as-is."
3104
+ ).option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--content-type <type>", "content type for a single-file upload").option("--extract", "always extract archives server-side, even without a manifest (X-Auto-Extract: true)").option("--as-zip", "store the zip as a plain file, never import/extract it (X-Auto-Extract: false)").option("--conflict <policy>", "archive import conflict policy: merge | reject (X-Archive-Conflict)").option("--no-wait", "archive imports: print the job id and return without waiting").option("--json", "output JSON").action(
3105
+ async (localPath, remotePath, options) => {
3106
+ if (options.extract && options.asZip) throw new Error("--extract and --as-zip are mutually exclusive.");
3107
+ const conflict = options.conflict?.toLowerCase();
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;
3137
+ }
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;
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}`);
3152
+ }
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;
3160
+ }
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}`);
3169
+ }
3170
+ }
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
+ });
3194
+ }
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
+ }
3209
+ }
3210
+ return count;
2524
3211
  }
2525
-
2526
- // src/vpkg/iconMigration.ts
2527
3212
  var DEFAULT_ICONIFY_API = "https://api.iconify.design";
2528
3213
  function createIconSetLoader(options = {}) {
2529
3214
  const apiBase = (options.apiBase ?? process.env.VERENTIS_ICONIFY_API ?? DEFAULT_ICONIFY_API).replace(/\/+$/, "");
@@ -2698,6 +3383,178 @@ function registerIcons(program2) {
2698
3383
  function collect(value, previous) {
2699
3384
  return [...previous, value];
2700
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
2701
3558
  var APP_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
2702
3559
  <rect x="2" y="2" width="28" height="28" rx="7" fill="#475569"/>
2703
3560
  <rect x="8" y="8" width="7" height="7" rx="1.5" fill="#f8fafc"/>
@@ -2712,10 +3569,34 @@ var ENGINE_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 3
2712
3569
  <path d="M16 21h7" fill="none" stroke="#f8fafc" stroke-width="2.5" stroke-linecap="round"/>
2713
3570
  </svg>
2714
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
+ };
2715
3589
  var TEMPLATE_FILES = {
2716
3590
  application: { "icons/app.svg": APP_ICON_SVG },
2717
3591
  engine: { "icons/app.svg": ENGINE_ICON_SVG },
2718
- 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"
2719
3600
  };
2720
3601
  var TEMPLATES = {
2721
3602
  application: (name) => `api-version: verentis.io/v1
@@ -2839,27 +3720,75 @@ packaging:
2839
3720
  bundle:
2840
3721
  default-path: /data/${name}
2841
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
2842
3762
  `
2843
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
+ }
2844
3773
  function registerInit(program2) {
2845
- 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) => {
2846
- const template = TEMPLATES[options.kind.toLowerCase()];
2847
- 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];
2848
3777
  const targetDir = resolve(dir ?? ".");
2849
3778
  await mkdir(targetDir, { recursive: true });
2850
3779
  const name = (options.name ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
2851
3780
  const manifestPath = join(targetDir, "manifest.yaml");
2852
3781
  if (await exists3(manifestPath)) throw new Error(`${manifestPath} already exists.`);
2853
3782
  await writeFile(manifestPath, template(name));
2854
- console.log(`Created ${manifestPath} (kind: ${options.kind}).`);
2855
- 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] ?? {})) {
2856
3785
  const path = join(targetDir, relativePath);
2857
3786
  if (await exists3(path)) continue;
2858
3787
  await mkdir(dirname(path), { recursive: true });
2859
3788
  await writeFile(path, content);
2860
3789
  console.log(`Created ${path}.`);
2861
3790
  }
2862
- 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`.");
2863
3792
  });
2864
3793
  }
2865
3794
  async function exists3(path) {
@@ -3694,14 +4623,22 @@ async function pack(options) {
3694
4623
  overrideApplied = true;
3695
4624
  }
3696
4625
  const kind = normalizeKind(manifest.kind);
3697
- const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
3698
- 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(" ")}`);
3699
4628
  const dependencyErrors = validateDependencies(manifest.spec);
3700
4629
  if (dependencyErrors.length > 0) throw new Error(`Invalid dependencies: ${dependencyErrors.join(" ")}`);
3701
- const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
3702
- if (launchKindError) throw new Error(`Invalid manifest: ${launchKindError}.`);
3703
4630
  const marketplaceErrors = validateMarketplaceSection(manifest.marketplace);
3704
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);
3705
4642
  const packageId = manifest.metadata["package-id"].toLowerCase();
3706
4643
  const name = manifest.metadata.name.toLowerCase();
3707
4644
  const publisher = options.publisher.toLowerCase();
@@ -3710,6 +4647,10 @@ async function pack(options) {
3710
4647
  validatePackageName(publisher, "publisher name");
3711
4648
  const version = manifest.metadata.version;
3712
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
+ }
3713
4654
  const templatePlan = await createTemplatePlan(projectDir, manifest, payloadFiles);
3714
4655
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
3715
4656
  const packedManifest = stripTemplatePackagingFields(manifest);
@@ -3812,6 +4753,13 @@ async function pack(options) {
3812
4753
  await rm(staging, { recursive: true, force: true });
3813
4754
  }
3814
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
+ }
3815
4763
  function sha256Hex(data) {
3816
4764
  return createHash("sha256").update(data).digest("hex");
3817
4765
  }
@@ -3911,6 +4859,7 @@ function registerPack(program2) {
3911
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) => {
3912
4860
  const projectDir = resolve(dir ?? ".");
3913
4861
  const manifestPath = options.manifest ? resolve(options.manifest) : await findManifest(projectDir);
4862
+ await ensurePackageTypeKnown((await readManifestDocument(manifestPath)).kind);
3914
4863
  const manifest = await loadManifest(manifestPath);
3915
4864
  const publisher = options.publisher ?? manifest.packaging?.publisher;
3916
4865
  if (!publisher) {
@@ -4035,15 +4984,15 @@ function registerPackage(program2) {
4035
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) => {
4036
4985
  const api = await createApiClient();
4037
4986
  const { package: pkg } = await resolvePackageRef(api, ref);
4038
- const current = await call(api, marketplace.getPackage, { params: { id: pkg.id } });
4987
+ const current2 = await call(api, marketplace.getPackage, { params: { id: pkg.id } });
4039
4988
  await call(api, marketplace.updatePackage, {
4040
4989
  params: { id: pkg.id },
4041
4990
  body: {
4042
4991
  id: pkg.id,
4043
- displayName: options.displayName ?? current.displayName,
4044
- description: options.description ?? current.description ?? null,
4045
- icon: options.icon ?? current.icon ?? null,
4046
- 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 ?? []
4047
4996
  }
4048
4997
  });
4049
4998
  console.log(`Package ${ref} updated.`);
@@ -4269,18 +5218,18 @@ function registerPublisher(program2) {
4269
5218
  throw new Error("No publisher fields supplied. Pass --display-name, --description, --website or --email.");
4270
5219
  }
4271
5220
  const api = await createApiClient();
4272
- const current = await requireMyPublisher(api);
5221
+ const current2 = await requireMyPublisher(api);
4273
5222
  await call(api, marketplace.updatePublisher, {
4274
- params: { id: current.id },
5223
+ params: { id: current2.id },
4275
5224
  body: {
4276
- id: current.id,
4277
- displayName: options.displayName ?? current.displayName,
4278
- description: options.description ?? current.description ?? null,
4279
- websiteUrl: options.website ?? current.websiteUrl ?? null,
4280
- 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
4281
5230
  }
4282
5231
  });
4283
- console.log(`Publisher '${current.name}' updated.`);
5232
+ console.log(`Publisher '${current2.name}' updated.`);
4284
5233
  });
4285
5234
  const logoCmd = publisherCmd.command("logo").description("Manage your publisher logo");
4286
5235
  logoCmd.command("set <file>").description("Upload a PNG, JPEG, WebP or SVG publisher logo (maximum 1 MiB)").action(async (file) => {
@@ -4413,6 +5362,8 @@ function registerRegistry(program2) {
4413
5362
  ${contents.digestErrors.join("\n ")}`);
4414
5363
  }
4415
5364
  const api = await createApiClient();
5365
+ const config = await loadConfig();
5366
+ await refreshPackageTypes(requireApiUrl(config), { insecure: config.insecure });
4416
5367
  const publisher = await requireMyPublisher(api);
4417
5368
  if (publisher.name !== contents.metadata.publisher) {
4418
5369
  throw new Error(`Package declares publisher '${contents.metadata.publisher}' but you are '${publisher.name}'.`);
@@ -4454,11 +5405,13 @@ function registerRegistry(program2) {
4454
5405
  await pipeline(Readable.fromWeb(res.body), createWriteStream(outPath));
4455
5406
  console.log(`Downloaded ${ref}@${effectiveVersion} \u2192 ${outPath}`);
4456
5407
  });
4457
- 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) => {
4458
5409
  const api = await createApiClient();
5410
+ const requested = options.type ?? options.kind;
5411
+ const type = requested ? packageTypes().canonical(requested) ?? requested : void 0;
4459
5412
  const page = await api.request("GET", "/v1/packages", {
4460
5413
  scopes: [SCOPES.packageReadAll],
4461
- query: { SearchText: text, Kind: options.kind, PageNo: 1, PageSize: 50 }
5414
+ query: { SearchText: text, Kind: type, PageNo: 1, PageSize: 50 }
4462
5415
  });
4463
5416
  const items = page.data ?? page.items ?? [];
4464
5417
  if (items.length === 0) {
@@ -4512,7 +5465,7 @@ function registerRegistry(program2) {
4512
5465
  );
4513
5466
  const existing = pageItems(page).find((installation) => installation.status !== "Uninstalled");
4514
5467
  const nodeScopes = [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate];
4515
- const consentScopes = pkg.kind === "Application" ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
5468
+ const consentScopes = isApplicationProfile(pkg.type ?? pkg.kind) ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
4516
5469
  if (existing) {
4517
5470
  if (options.path && existing.installPath !== options.path.replace(/^\/+|\/+$/g, "")) {
4518
5471
  throw new Error(`${ref} is already installed at '${existing.installPath}'. Uninstall it before moving it.`);
@@ -4629,11 +5582,11 @@ function getCliVersion() {
4629
5582
  }
4630
5583
  function readVersion() {
4631
5584
  const candidates = ["../package.json", "../../package.json"];
4632
- for (const relative5 of candidates) {
5585
+ for (const relative6 of candidates) {
4633
5586
  try {
4634
- const raw = readFileSync(fileURLToPath(new URL(relative5, import.meta.url)), "utf8");
5587
+ const raw = readFileSync(fileURLToPath(new URL(relative6, import.meta.url)), "utf8");
4635
5588
  const pkg = JSON.parse(raw);
4636
- 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;
4637
5590
  } catch {
4638
5591
  }
4639
5592
  }
@@ -4689,10 +5642,10 @@ var SUPPRESSED_COMMANDS = /* @__PURE__ */ new Set(["update", "__update-check", "
4689
5642
  async function notifyOnExit(argv) {
4690
5643
  if (isUpdateCheckSuppressed(argv)) return;
4691
5644
  try {
4692
- const current = getCliVersion();
5645
+ const current2 = getCliVersion();
4693
5646
  const state = await readUpdateState();
4694
- if (state?.latestVersion && isNewerVersion(state.latestVersion, current)) {
4695
- printUpdateNotice(current, state.latestVersion);
5647
+ if (state?.latestVersion && isNewerVersion(state.latestVersion, current2)) {
5648
+ printUpdateNotice(current2, state.latestVersion);
4696
5649
  }
4697
5650
  if (isStale(state)) spawnBackgroundRefresh();
4698
5651
  } catch {
@@ -4720,9 +5673,9 @@ function isEnvDisabled() {
4720
5673
  const explicit = process.env.VERENTIS_UPDATE_CHECK;
4721
5674
  return explicit !== void 0 && off.has(explicit.toLowerCase());
4722
5675
  }
4723
- function printUpdateNotice(current, latest) {
5676
+ function printUpdateNotice(current2, latest) {
4724
5677
  const message = [
4725
- `Update available ${current} \u2192 ${latest}`,
5678
+ `Update available ${current2} \u2192 ${latest}`,
4726
5679
  "Run `verentis update` to install the latest version."
4727
5680
  ];
4728
5681
  const width = Math.max(...message.map((line) => line.length));
@@ -4749,14 +5702,14 @@ function spawnBackgroundRefresh() {
4749
5702
  // src/commands/update.ts
4750
5703
  function registerUpdate(program2) {
4751
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) => {
4752
- const current = getCliVersion();
5705
+ const current2 = getCliVersion();
4753
5706
  const target = await resolveTarget(options.to);
4754
5707
  if (options.check) {
4755
- reportCheck(current, target, Boolean(options.to));
5708
+ reportCheck(current2, target, Boolean(options.to));
4756
5709
  return;
4757
5710
  }
4758
- if (!options.to && !isNewerVersion(target, current)) {
4759
- console.log(`Already on the latest version (${current}).`);
5711
+ if (!options.to && !isNewerVersion(target, current2)) {
5712
+ console.log(`Already on the latest version (${current2}).`);
4760
5713
  return;
4761
5714
  }
4762
5715
  const install = resolveInstallCommand(`${PACKAGE_NAME}@${target}`);
@@ -4767,7 +5720,7 @@ Update manually, for example:
4767
5720
  npm install -g ${PACKAGE_NAME}@${target}`
4768
5721
  );
4769
5722
  }
4770
- console.log(`Updating ${PACKAGE_NAME}: ${current} \u2192 ${target}`);
5723
+ console.log(`Updating ${PACKAGE_NAME}: ${current2} \u2192 ${target}`);
4771
5724
  console.log(`$ ${install.command} ${install.args.join(" ")}`);
4772
5725
  const result = spawnSync(install.command, install.args, { stdio: "inherit" });
4773
5726
  if (result.error) {
@@ -4802,17 +5755,17 @@ async function resolveTarget(requested) {
4802
5755
  });
4803
5756
  return latest;
4804
5757
  }
4805
- function reportCheck(current, target, pinned) {
5758
+ function reportCheck(current2, target, pinned) {
4806
5759
  if (pinned) {
4807
- console.log(`Current version: ${current}`);
5760
+ console.log(`Current version: ${current2}`);
4808
5761
  console.log(`Requested version: ${target}`);
4809
5762
  return;
4810
5763
  }
4811
- if (isNewerVersion(target, current)) {
4812
- 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}`);
4813
5766
  console.log("Run `verentis update` to install it.");
4814
5767
  } else {
4815
- console.log(`You are on the latest version (${current}).`);
5768
+ console.log(`You are on the latest version (${current2}).`);
4816
5769
  }
4817
5770
  }
4818
5771
  function resolveInstallCommand(spec) {
@@ -4934,7 +5887,7 @@ function registerUser(program2) {
4934
5887
  });
4935
5888
  }
4936
5889
  function registerValidate(program2) {
4937
- 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) => {
4938
5891
  const target = resolve(pathOrDir ?? ".");
4939
5892
  const info = await stat(target).catch(() => null);
4940
5893
  const manifestPath = info?.isDirectory() ? await findManifest(target) : target;
@@ -4942,7 +5895,10 @@ function registerValidate(program2) {
4942
5895
  const base = await readManifestDocument(manifestPath);
4943
5896
  const overlayPath = resolveOverlayPath(dirname(manifestPath), { env: options.env, overlay: options.overlay });
4944
5897
  const manifest = overlayPath ? applyOverlay(base, await loadOverlay(overlayPath)) : base;
5898
+ if (!NON_PACKAGE_KINDS.includes(manifest.kind)) await ensurePackageTypeKnown(manifest.kind);
4945
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 })));
4946
5902
  try {
4947
5903
  const payloadFiles = await resolvePayloadFiles(dirname(manifestPath), manifestPath, manifest);
4948
5904
  const templateInspection = await inspectPackagingTemplates(dirname(manifestPath), manifest, payloadFiles);