@verentis/cli 0.2.23 → 0.2.25

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
@@ -139,9 +139,10 @@ async function refreshIdentityToken(apiUrl, refreshToken, insecure) {
139
139
  `Session could not be renewed${payload?.error ? ` (${payload.error})` : ` (${res.status})`}. Run \`verentis login\` again.`
140
140
  );
141
141
  }
142
- var sleep = (ms) => new Promise((resolve12) => setTimeout(resolve12, ms));
142
+ var sleep = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
143
143
 
144
144
  // src/auth/githubActions.ts
145
+ var JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
145
146
  var PUBLISHING_SCOPES = /* @__PURE__ */ new Set([
146
147
  "marketplace.publisher.read",
147
148
  "marketplace.package.read",
@@ -180,20 +181,26 @@ async function exchangeGitHubPublisherToken(apiUrl, audience) {
180
181
  if (!assertion.value) {
181
182
  throw new Error("GitHub Actions did not provide an OIDC assertion.");
182
183
  }
183
- const exchangeResponse = await fetch(`${apiUrl}/v1/publisher-federation/exchange`, {
184
+ const exchangeResponse = await fetch(`${apiUrl}/connect/token`, {
184
185
  method: "POST",
185
- headers: { "Content-Type": "application/json" },
186
- body: JSON.stringify({ assertion: assertion.value })
186
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
187
+ body: new URLSearchParams({
188
+ grant_type: JWT_BEARER_GRANT_TYPE,
189
+ assertion: assertion.value,
190
+ scope: [...PUBLISHING_SCOPES].join(" ")
191
+ })
187
192
  });
188
193
  if (!exchangeResponse.ok) {
189
- throw new Error(`Verentis publisher federation rejected the GitHub assertion (${exchangeResponse.status}).`);
194
+ const error = await exchangeResponse.json().catch(() => ({}));
195
+ const reason = error.error ? `${exchangeResponse.status} ${error.error}` : `${exchangeResponse.status}`;
196
+ throw new Error(`Verentis rejected the GitHub assertion (${reason}).`);
190
197
  }
191
198
  const result = await exchangeResponse.json();
192
- const payload = result.accessToken ? decodeJwtPayload(result.accessToken) : null;
193
- if (!result.accessToken || typeof payload?.exp !== "number" || !Number.isFinite(payload.exp) || payload.exp * 1e3 <= Date.now()) {
194
- throw new Error("Publisher federation did not return a valid, unexpired access token.");
199
+ const payload = result.access_token ? decodeJwtPayload(result.access_token) : null;
200
+ if (!result.access_token || result.token_type?.toLowerCase() !== "bearer" || typeof payload?.exp !== "number" || !Number.isFinite(payload.exp) || payload.exp * 1e3 <= Date.now()) {
201
+ throw new Error("The token endpoint did not return a valid, unexpired bearer access token.");
195
202
  }
196
- return result.accessToken;
203
+ return result.access_token;
197
204
  }
198
205
 
199
206
  // src/http.ts
@@ -388,7 +395,6 @@ var SCOPES = {
388
395
  packageCreate: "marketplace.package.create",
389
396
  packagePublish: "marketplace.package.publish",
390
397
  installCreate: "marketplace.install.create",
391
- installDelete: "marketplace.install.delete",
392
398
  resourceReadAll: "resources.resource.read-all",
393
399
  resourceUpdate: "resources.resource.update"
394
400
  };
@@ -447,7 +453,9 @@ var EXECUTION = {
447
453
  run: "execution.execution.run"
448
454
  };
449
455
  var MARKETPLACE = {
456
+ installDelete: "marketplace.install.delete",
450
457
  installRead: "marketplace.install.read",
458
+ installUpdate: "marketplace.install.update",
451
459
  packageDelete: "marketplace.package.delete",
452
460
  packageRead: "marketplace.package.read",
453
461
  packageUpdate: "marketplace.package.update",
@@ -558,7 +566,9 @@ var marketplace = {
558
566
  grantVisibility: e({ method: "POST", path: "/v1/packages/{packageId}/visibility-grants", scopes: [MARKETPLACE.packageVisibilityManage] }),
559
567
  revokeVisibility: e({ method: "DELETE", path: "/v1/packages/{packageId}/visibility-grants/{grantId}", scopes: [MARKETPLACE.packageVisibilityManage] }),
560
568
  getPackageStats: e({ method: "GET", path: "/v1/packages/{packageId}/stats", scopes: [MARKETPLACE.statsRead] }),
561
- listInstallations: e({ method: "GET", path: "/v1/installations", scopes: [MARKETPLACE.installRead], paged: true })};
569
+ listInstallations: e({ method: "GET", path: "/v1/installations", scopes: [MARKETPLACE.installRead], paged: true }),
570
+ uninstall: e({ method: "DELETE", path: "/v1/installations/{id}", scopes: [MARKETPLACE.installDelete, NODE.fileDelete, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate], workspaceBound: true })
571
+ };
562
572
 
563
573
  // src/api/client.ts
564
574
  function fillPath(template, params = {}) {
@@ -1032,11 +1042,14 @@ function contextEnv(context, contextPath) {
1032
1042
  var KIND_MAP = {
1033
1043
  application: "Application",
1034
1044
  executionengine: "ExecutionEngine",
1045
+ agent: "Agent",
1046
+ skill: "Skill",
1047
+ tool: "Tool",
1035
1048
  bundle: "Bundle"
1036
1049
  };
1037
1050
  function normalizeKind(kind) {
1038
1051
  const mapped = KIND_MAP[kind.replace(/[^a-z]/gi, "").toLowerCase()];
1039
- if (!mapped) throw new Error(`Unsupported manifest kind '${kind}' \u2014 expected Application, ExecutionEngine or Bundle.`);
1052
+ if (!mapped) throw new Error(`Unsupported manifest kind '${kind}' \u2014 expected Application, ExecutionEngine, Agent, Skill, Tool or Bundle.`);
1040
1053
  return mapped;
1041
1054
  }
1042
1055
  function validateLaunchManifestKind(kind, spec) {
@@ -1054,12 +1067,20 @@ async function loadManifest(path) {
1054
1067
  if (!manifest.metadata?.version) throw new Error(`Manifest at ${path} is missing 'metadata.version'.`);
1055
1068
  validatePackageName(manifest.metadata["package-id"], "package ID");
1056
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
+ }
1057
1074
  const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
1058
1075
  if (launchKindError) throw new Error(`Invalid manifest at ${path}: ${launchKindError}.`);
1059
1076
  const operationErrors = validateWopiOperationsSection(manifest.spec);
1060
1077
  if (operationErrors.length > 0) {
1061
1078
  throw new Error(`Invalid manifest at ${path}: ${operationErrors.join(" ")}`);
1062
1079
  }
1080
+ const dependencyErrors = validateDependencies(manifest.spec);
1081
+ if (dependencyErrors.length > 0) {
1082
+ throw new Error(`Invalid manifest at ${path}: ${dependencyErrors.join(" ")}`);
1083
+ }
1063
1084
  const splashErrors = validateApplicationSplashSection(kind, manifest.spec);
1064
1085
  if (splashErrors.length > 0) {
1065
1086
  throw new Error(`Invalid manifest at ${path}: ${splashErrors.join(" ")}`);
@@ -1108,6 +1129,16 @@ function validateApplicationSplashSection(kind, spec) {
1108
1129
  }
1109
1130
  return errors;
1110
1131
  }
1132
+ function validateHostedBackendDeclaration(kind, spec) {
1133
+ if (kind === "Application" || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1134
+ const value = spec;
1135
+ const capabilities = value.capabilities;
1136
+ const requestsCapability = Array.isArray(capabilities) && capabilities.some((capability) => typeof capability === "string" && capability.trim().toLowerCase() === "hosted-backend");
1137
+ if (requestsCapability || Object.prototype.hasOwnProperty.call(value, "hosted-backend")) {
1138
+ return [`${kind} packages cannot declare a hosted backend.`];
1139
+ }
1140
+ return [];
1141
+ }
1111
1142
  function validateWopiOperationsSection(spec) {
1112
1143
  if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1113
1144
  const wopi = spec.wopi;
@@ -1188,14 +1219,65 @@ async function findManifest(dir) {
1188
1219
  } catch {
1189
1220
  }
1190
1221
  const entries = await readdir(dir);
1191
- const candidates = entries.filter((name) => /\.(app|engine|bundle)\.ya?ml$/.test(name));
1222
+ const candidates = entries.filter((name) => /\.(app|engine|agent|skill|tool|bundle|policy)\.ya?ml$/.test(name));
1192
1223
  if (candidates.length === 1) return join(dir, candidates[0]);
1193
1224
  if (candidates.length === 0) {
1194
- throw new Error(`No manifest found in ${dir}. Expected manifest.yaml or *.app.yaml / *.engine.yaml / *.bundle.yaml.`);
1225
+ 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.`);
1195
1226
  }
1196
1227
  throw new Error(`Multiple manifests found in ${dir} (${candidates.join(", ")}). Pass --manifest to disambiguate.`);
1197
1228
  }
1198
1229
  var NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
1230
+ var DEPENDENCY_IDENTITY = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
1231
+ 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-]+)*)?$/;
1232
+ function validateDependencies(spec) {
1233
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1234
+ const value = spec;
1235
+ const errors = [];
1236
+ const required = /* @__PURE__ */ new Set();
1237
+ const seen = /* @__PURE__ */ new Set();
1238
+ if (value.dependencies !== void 0) {
1239
+ if (!Array.isArray(value.dependencies) || value.dependencies.length > 32) {
1240
+ errors.push("spec.dependencies must be a list of at most 32 exact package pins.");
1241
+ } else {
1242
+ for (const dependency of value.dependencies) {
1243
+ if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) {
1244
+ errors.push("Each dependency must be an object.");
1245
+ continue;
1246
+ }
1247
+ const item = dependency;
1248
+ if (Object.keys(item).some((key) => !["package", "version", "install-path", "optional"].includes(key))) {
1249
+ errors.push("Each dependency accepts only package, version, install-path and optional.");
1250
+ }
1251
+ if (typeof item.package !== "string" || !DEPENDENCY_IDENTITY.test(item.package) || typeof item.version !== "string" || !EXACT_VERSION.test(item.version)) {
1252
+ errors.push("Dependencies require a lowercase publisher/package-id and an exact semantic version.");
1253
+ }
1254
+ if (item.optional !== void 0 && typeof item.optional !== "boolean") {
1255
+ errors.push("Dependency optional must be true or false.");
1256
+ }
1257
+ if (item["install-path"] !== void 0) {
1258
+ const path = item["install-path"];
1259
+ const normalized = typeof path === "string" ? path.trim().replace(/^\/+|\/+$/g, "") : "";
1260
+ if (!normalized || normalized.length > 512 || /[\\\u0000-\u001f\u007f]/.test(normalized) || normalized.split("/").some((segment) => ["", ".", ".."].includes(segment))) {
1261
+ errors.push("Dependency install-path must be a nonempty workspace path without traversal.");
1262
+ }
1263
+ }
1264
+ if (typeof item.package === "string") {
1265
+ if (seen.has(item.package)) errors.push(`Duplicate dependency '${item.package}'.`);
1266
+ seen.add(item.package);
1267
+ if (item.optional !== true) required.add(item.package);
1268
+ }
1269
+ }
1270
+ }
1271
+ }
1272
+ if (value.engine !== void 0) {
1273
+ if (typeof value.engine !== "string" || !DEPENDENCY_IDENTITY.test(value.engine) || !required.has(value.engine)) {
1274
+ errors.push("spec.engine must name a required publisher-qualified dependency.");
1275
+ }
1276
+ } else if (value.scripts !== void 0) {
1277
+ errors.push("Script packages must declare spec.engine and its required dependency.");
1278
+ }
1279
+ return errors;
1280
+ }
1199
1281
  function validatePackageName(name, label) {
1200
1282
  if (!NAME_PATTERN.test(name)) {
1201
1283
  throw new Error(`Invalid ${label} '${name}' \u2014 use lowercase letters, digits and hyphens (no leading/trailing hyphen).`);
@@ -1219,28 +1301,42 @@ function validateManifest(manifest) {
1219
1301
  const error = (message) => issues.push({ level: "error", message });
1220
1302
  const warning = (message) => issues.push({ level: "warning", message });
1221
1303
  const kind = manifest.kind;
1304
+ const knownKinds = ["ExecutionEngine", "Application", "Agent", "Skill", "Tool", "Bundle", "Policy"];
1222
1305
  if (!kind) {
1223
- error("missing 'kind' (ExecutionEngine | Application | Bundle)");
1306
+ error("missing 'kind' (ExecutionEngine | Application | Agent | Skill | Tool | Bundle | Policy)");
1224
1307
  return issues;
1225
1308
  }
1226
- if (!["ExecutionEngine", "Application", "Bundle"].includes(kind)) {
1227
- error(`unknown kind '${kind}' (expected ExecutionEngine, Application or Bundle)`);
1309
+ if (!knownKinds.includes(kind)) {
1310
+ error(`unknown kind '${kind}' (expected ExecutionEngine, Application, Agent, Skill, Tool, Bundle or Policy)`);
1311
+ }
1312
+ if (!manifest["api-version"]) {
1313
+ warning("missing 'api-version' (expected verentis.io/v1)");
1314
+ } else if (manifest["api-version"] !== "verentis.io/v1") {
1315
+ error("api-version must be 'verentis.io/v1'");
1228
1316
  }
1229
- if (!manifest["api-version"]) warning("missing 'api-version' (expected verentis.io/v1)");
1230
1317
  const meta = manifest.metadata ?? {};
1231
- for (const field of ["name", "display-name", "version"]) {
1232
- if (!meta[field]) error(`metadata.${field} is required`);
1318
+ if (!meta.name) {
1319
+ error("metadata.name is required");
1320
+ } else if (!NAME_PATTERN.test(meta.name)) {
1321
+ error("metadata.name must use lowercase letters, digits and internal hyphens");
1233
1322
  }
1234
- if (!meta["package-id"]) {
1235
- error("metadata.package-id is required");
1236
- } else if (!NAME_PATTERN.test(meta["package-id"])) {
1237
- error("metadata.package-id must use lowercase letters, digits and internal hyphens");
1323
+ if (kind !== "Policy") {
1324
+ for (const field of ["display-name", "version"]) {
1325
+ if (!meta[field]) error(`metadata.${field} is required`);
1326
+ }
1327
+ if (!meta["package-id"]) {
1328
+ error("metadata.package-id is required");
1329
+ } else if (!NAME_PATTERN.test(meta["package-id"])) {
1330
+ error("metadata.package-id must use lowercase letters, digits and internal hyphens");
1331
+ }
1238
1332
  }
1239
1333
  const spec = manifest.spec ?? {};
1240
1334
  validateManifestIcons(meta, spec, issues);
1241
1335
  const launchKindError = validateLaunchManifestKind(kind, spec);
1242
1336
  if (launchKindError) error(launchKindError);
1243
1337
  for (const message of validateWopiOperationsSection(spec)) error(message);
1338
+ for (const message of validateHostedBackendDeclaration(kind, spec)) error(message);
1339
+ for (const message of validateDependencies(spec)) error(message);
1244
1340
  if (kind === "ExecutionEngine") {
1245
1341
  const runtimes = spec.runtimes ?? {};
1246
1342
  if (Object.keys(runtimes).length === 0) {
@@ -1272,13 +1368,117 @@ function validateManifest(manifest) {
1272
1368
  for (const message of validateApplicationSplashSection(kind, spec)) error(message);
1273
1369
  validateApplicationLaunch(spec, issues);
1274
1370
  }
1371
+ if (kind === "Agent") validateAgentManifest(spec, issues);
1372
+ if (kind === "Skill") validateSkillManifest(spec, issues);
1373
+ if (kind === "Tool") validateToolManifest(spec, issues);
1374
+ if (kind === "Policy") validatePolicyManifest(spec, issues);
1275
1375
  validateInstallDirectives(spec.install, issues);
1276
1376
  validateSettingDeclarations(kind, spec, issues);
1277
1377
  for (const message of validateMarketplaceSection(manifest.marketplace)) error(message);
1278
1378
  const packaging = manifest.packaging ?? {};
1279
- if (!packaging.publisher) warning("packaging.publisher is not set \u2014 `verentis pack`/`publish` will refuse the package");
1379
+ if (kind !== "Policy" && !packaging.publisher) warning("packaging.publisher is not set \u2014 `verentis pack`/`publish` will refuse the package");
1280
1380
  return issues;
1281
1381
  }
1382
+ function validateAgentManifest(spec, issues) {
1383
+ const error = (message) => issues.push({ level: "error", message });
1384
+ if (spec.instructions !== void 0 && typeof spec.instructions !== "string") error("spec.instructions must be a string");
1385
+ if (spec["system-prompt"] !== void 0 && typeof spec["system-prompt"] !== "string") error("spec.system-prompt must be a string");
1386
+ if (spec.instructions !== void 0 && spec["system-prompt"] !== void 0) {
1387
+ error("spec.instructions and spec.system-prompt cannot both be set");
1388
+ }
1389
+ if (spec["instructions-file"] !== void 0 && (spec.instructions !== void 0 || spec["system-prompt"] !== void 0)) {
1390
+ error("spec.instructions-file cannot be combined with inline instructions");
1391
+ }
1392
+ validateUniqueStrings(spec.skills, "spec.skills", issues);
1393
+ validateUniqueStrings(spec.tools, "spec.tools", issues);
1394
+ }
1395
+ function validateSkillManifest(spec, issues) {
1396
+ const error = (message) => issues.push({ level: "error", message });
1397
+ if (typeof spec.description !== "string" || spec.description.trim().length === 0) {
1398
+ error("spec.description is required for Skill manifests");
1399
+ }
1400
+ if (spec.instructions !== void 0 && spec["instructions-file"] !== void 0) {
1401
+ error("spec.instructions and spec.instructions-file cannot both be set");
1402
+ }
1403
+ validateUniqueStrings(spec.skills, "spec.skills", issues);
1404
+ validateUniqueStrings(spec.tools, "spec.tools", issues);
1405
+ }
1406
+ function validateToolManifest(spec, issues) {
1407
+ const error = (message) => issues.push({ level: "error", message });
1408
+ const tools = spec.tools;
1409
+ if (!Array.isArray(tools) || tools.length === 0) {
1410
+ error("spec.tools must contain at least one tool definition");
1411
+ return;
1412
+ }
1413
+ const serverNames = /* @__PURE__ */ new Set();
1414
+ const servers = spec.mcp && typeof spec.mcp === "object" && !Array.isArray(spec.mcp) ? spec.mcp.servers : void 0;
1415
+ if (Array.isArray(servers)) {
1416
+ for (const server of servers) {
1417
+ if (server && typeof server === "object" && !Array.isArray(server)) {
1418
+ const name = server.name;
1419
+ if (typeof name === "string") serverNames.add(name);
1420
+ }
1421
+ }
1422
+ }
1423
+ const keys = /* @__PURE__ */ new Set();
1424
+ tools.forEach((tool, index) => {
1425
+ const at = `spec.tools[${index}]`;
1426
+ if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
1427
+ error(`${at} must be an object`);
1428
+ return;
1429
+ }
1430
+ const item = tool;
1431
+ if (typeof item.key !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(item.key)) error(`${at}.key is required`);
1432
+ else if (keys.has(item.key)) error(`duplicate tool key '${item.key}'`);
1433
+ else keys.add(item.key);
1434
+ if (typeof item.description !== "string" || item.description.trim().length === 0) error(`${at}.description is required`);
1435
+ if (item["input-schema"] === void 0) error(`${at}.input-schema is required`);
1436
+ if (!["read", "write", "execute", "external", "interactive"].includes(String(item.effect))) error(`${at}.effect is invalid`);
1437
+ const implementation = item.implementation;
1438
+ if (!implementation || typeof implementation !== "object" || Array.isArray(implementation)) {
1439
+ error(`${at}.implementation is required`);
1440
+ } else if (implementation.type === "mcp") {
1441
+ const server = implementation.server;
1442
+ if (typeof server !== "string" || !serverNames.has(server)) error(`${at}.implementation.server is not declared in spec.mcp.servers`);
1443
+ }
1444
+ const retry = item.retry;
1445
+ 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))) {
1446
+ error(`${at}.retry requires a reconciliation contract for non-read tools`);
1447
+ }
1448
+ });
1449
+ }
1450
+ function validatePolicyManifest(spec, issues) {
1451
+ const error = (message) => issues.push({ level: "error", message });
1452
+ if (spec.area !== "agent") error("spec.area must be agent");
1453
+ if (!Array.isArray(spec.rules)) {
1454
+ error("spec.rules must be an array");
1455
+ return;
1456
+ }
1457
+ spec.rules.forEach((rule, index) => {
1458
+ const at = `spec.rules[${index}]`;
1459
+ if (!rule || typeof rule !== "object" || Array.isArray(rule)) {
1460
+ error(`${at} must be an object`);
1461
+ return;
1462
+ }
1463
+ const item = rule;
1464
+ if (typeof item.id !== "string" || item.id.trim().length === 0) error(`${at}.id is required`);
1465
+ if (!["permit", "deny", "require-approval"].includes(String(item.effect))) error(`${at}.effect must be permit, deny or require-approval`);
1466
+ if (typeof item.capability !== "string" || item.capability.trim().length === 0) error(`${at}.capability is required`);
1467
+ });
1468
+ }
1469
+ function validateUniqueStrings(value, path, issues) {
1470
+ if (value === void 0) return;
1471
+ if (!Array.isArray(value)) {
1472
+ issues.push({ level: "error", message: `${path} must be an array` });
1473
+ return;
1474
+ }
1475
+ const seen = /* @__PURE__ */ new Set();
1476
+ for (const item of value) {
1477
+ if (typeof item !== "string") continue;
1478
+ if (seen.has(item)) issues.push({ level: "error", message: `${path} contains duplicate '${item}'` });
1479
+ seen.add(item);
1480
+ }
1481
+ }
1282
1482
  function validateManifestIcons(metadata, spec, issues) {
1283
1483
  validateOptionalIcon(metadata.icon, "metadata.icon", issues);
1284
1484
  validateBindingIcons(spec["mime-types"], "spec.mime-types", issues);
@@ -1797,7 +1997,7 @@ async function followExecution(api, workspaceId, executionId, json) {
1797
1997
  if (exec.status !== "Completed") process.exitCode = 1;
1798
1998
  return;
1799
1999
  }
1800
- await new Promise((resolve12) => setTimeout(resolve12, 1e3));
2000
+ await new Promise((resolve13) => setTimeout(resolve13, 1e3));
1801
2001
  }
1802
2002
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
1803
2003
  process.exitCode = 1;
@@ -2908,6 +3108,10 @@ async function pack(options) {
2908
3108
  overrideApplied = true;
2909
3109
  }
2910
3110
  const kind = normalizeKind(manifest.kind);
3111
+ const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
3112
+ if (hostedBackendErrors.length > 0) throw new Error(`Invalid manifest: ${hostedBackendErrors.join(" ")}`);
3113
+ const dependencyErrors = validateDependencies(manifest.spec);
3114
+ if (dependencyErrors.length > 0) throw new Error(`Invalid dependencies: ${dependencyErrors.join(" ")}`);
2911
3115
  const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
2912
3116
  if (launchKindError) throw new Error(`Invalid manifest: ${launchKindError}.`);
2913
3117
  const marketplaceErrors = validateMarketplaceSection(manifest.marketplace);
@@ -3310,6 +3514,88 @@ function registerPackage(program2) {
3310
3514
  output(pageItems(page), { packageName: "Package", version: "Version", status: "Status", installPath: "Path", id: "Id" }, options, page);
3311
3515
  });
3312
3516
  }
3517
+ var POLICY_READ_SCOPE = "fabric.policy.read";
3518
+ var POLICY_UPDATE_SCOPE = "fabric.policy.update";
3519
+ function registerPolicy(program2) {
3520
+ const policyCmd = program2.command("policy").description("Export and apply workspace policy manifests");
3521
+ policyCmd.command("export [area]").description("Export a workspace policy manifest").requiredOption("--workspace <workspaceId>", "workspace whose policy is exported").option("-o, --out <file>", "write the manifest to a file instead of stdout").option("--json", "output JSON").action(async (area, options) => {
3522
+ const api = await createApiClient();
3523
+ const result = await exportPolicy(api, options.workspace, area ?? "agent");
3524
+ if (options.out) await writeFile(resolve(options.out), result.manifest);
3525
+ if (options.json) {
3526
+ printJson({ ...result, ...options.out ? { out: resolve(options.out) } : {} });
3527
+ } else if (options.out) {
3528
+ console.log(`Wrote ${result.area} policy manifest to ${resolve(options.out)}.`);
3529
+ console.error(`revision ${result.revision}`);
3530
+ } else {
3531
+ process.stdout.write(result.manifest.endsWith("\n") ? result.manifest : `${result.manifest}
3532
+ `);
3533
+ console.error(`revision ${result.revision}`);
3534
+ }
3535
+ });
3536
+ policyCmd.command("apply <file>").description("Apply a workspace policy manifest").requiredOption("--workspace <workspaceId>", "workspace whose policy is updated").option("--area <area>", "policy area (default: spec.area, else agent)").option("--expected-revision <revision>", "optimistic-concurrency revision").option("--dry-run", "validate and diff without writing").option("--json", "output JSON").action(async (file, options) => {
3537
+ const manifestPath = resolve(file);
3538
+ const manifest = await readFile(manifestPath, "utf8");
3539
+ const area = options.area ?? areaFromManifest(manifest) ?? "agent";
3540
+ const api = await createApiClient();
3541
+ const expectedRevision = options.expectedRevision !== void 0 ? parseExpectedRevision(options.expectedRevision) : await currentRevisionOrZero(api, options.workspace, area);
3542
+ try {
3543
+ const result = await applyPolicy(api, options.workspace, area, manifest, expectedRevision, options.dryRun === true);
3544
+ if (options.json) {
3545
+ printJson(result);
3546
+ } else {
3547
+ console.log(`${result.dryRun ? "Dry run" : result.applied ? "Applied" : "No changes"}: ${area} policy revision ${result.revision}.`);
3548
+ for (const change of result.changes ?? []) console.log(` ${change}`);
3549
+ }
3550
+ } catch (error) {
3551
+ if (error instanceof ApiError && error.status === 409) {
3552
+ throw new Error(`Policy revision conflict for area '${area}'. Re-export the policy, reapply your edits, then retry.`);
3553
+ }
3554
+ throw error;
3555
+ }
3556
+ });
3557
+ }
3558
+ async function exportPolicy(api, workspaceId, area) {
3559
+ const response = await api.request("GET", `/v1/policies/${encodeURIComponent(area)}/manifest`, {
3560
+ scopes: [POLICY_READ_SCOPE],
3561
+ tokenWorkspaceId: workspaceId,
3562
+ query: { workspaceId }
3563
+ });
3564
+ return unwrap2(response);
3565
+ }
3566
+ async function applyPolicy(api, workspaceId, area, manifest, expectedRevision, dryRun) {
3567
+ const response = await api.request("POST", `/v1/policies/${encodeURIComponent(area)}/apply`, {
3568
+ scopes: [dryRun ? POLICY_READ_SCOPE : POLICY_UPDATE_SCOPE],
3569
+ tokenWorkspaceId: workspaceId,
3570
+ query: { workspaceId },
3571
+ body: { workspaceId, area, manifest, expectedRevision, dryRun }
3572
+ });
3573
+ return unwrap2(response);
3574
+ }
3575
+ async function currentRevisionOrZero(api, workspaceId, area) {
3576
+ try {
3577
+ return (await exportPolicy(api, workspaceId, area)).revision;
3578
+ } catch (error) {
3579
+ if (error instanceof ApiError && error.status === 404) return 0;
3580
+ throw error;
3581
+ }
3582
+ }
3583
+ function areaFromManifest(manifest) {
3584
+ const document = parse(manifest);
3585
+ const area = document?.spec?.area;
3586
+ return typeof area === "string" && area.trim().length > 0 ? area : void 0;
3587
+ }
3588
+ function parseExpectedRevision(value) {
3589
+ const revision = Number(value);
3590
+ if (!Number.isInteger(revision) || revision < 0) throw new Error("--expected-revision must be a non-negative integer.");
3591
+ return revision;
3592
+ }
3593
+ function unwrap2(value) {
3594
+ if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 1 && "value" in value) {
3595
+ return value.value;
3596
+ }
3597
+ return value;
3598
+ }
3313
3599
  var MAX_LOGO_BYTES2 = 1024 * 1024;
3314
3600
  var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
3315
3601
  async function readPublisherLogo(path) {
@@ -3427,8 +3713,8 @@ function isNewerVersion(candidate, base) {
3427
3713
  return compareVersions(candidate, base) > 0;
3428
3714
  }
3429
3715
  function compareVersions(a, b) {
3430
- const pa = parse5(a);
3431
- const pb = parse5(b);
3716
+ const pa = parse6(a);
3717
+ const pb = parse6(b);
3432
3718
  for (let i = 0; i < 3; i++) {
3433
3719
  if (pa.main[i] !== pb.main[i]) return pa.main[i] < pb.main[i] ? -1 : 1;
3434
3720
  }
@@ -3455,7 +3741,7 @@ function compareVersions(a, b) {
3455
3741
  }
3456
3742
  return 0;
3457
3743
  }
3458
- function parse5(version) {
3744
+ function parse6(version) {
3459
3745
  const cleaned = version.trim().replace(/^v/i, "").split("+", 1)[0];
3460
3746
  const dash = cleaned.indexOf("-");
3461
3747
  const core = dash === -1 ? cleaned : cleaned.slice(0, dash);
@@ -3464,6 +3750,45 @@ function parse5(version) {
3464
3750
  return { main: [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0], pre: pre ? pre.split(".") : [] };
3465
3751
  }
3466
3752
 
3753
+ // src/commands/installation-graph.ts
3754
+ async function installGraph(api, workspaceId, packageId, options) {
3755
+ if (options.operation || options.consent) {
3756
+ if (!options.operation || !options.consent) throw new Error("--operation and --consent must be supplied together.");
3757
+ const result = await api.request("POST", "/v1/installations/graphs", {
3758
+ scopes: [
3759
+ SCOPES.installCreate,
3760
+ "marketplace.install.update",
3761
+ NODE.nodeCreate,
3762
+ NODE.fileRead,
3763
+ NODE.fileDelete,
3764
+ NODE.nodeUpdate,
3765
+ NODE.journalCreate,
3766
+ SCOPES.resourceReadAll,
3767
+ SCOPES.resourceUpdate
3768
+ ],
3769
+ tokenWorkspaceId: workspaceId,
3770
+ body: { workspaceId, operationId: options.operation, fingerprint: options.consent, consent: true }
3771
+ });
3772
+ console.log(JSON.stringify(result, null, 2));
3773
+ if (result.succeeded !== true) throw new Error(`Graph installation failed. Inspect operation ${options.operation}; do not resubmit it.`);
3774
+ return;
3775
+ }
3776
+ const preview = await api.request("POST", "/v1/installations/graphs/preview", {
3777
+ scopes: [SCOPES.installCreate],
3778
+ tokenWorkspaceId: workspaceId,
3779
+ body: {
3780
+ workspaceId,
3781
+ packageId,
3782
+ packageVersion: options.version,
3783
+ installPath: options.path,
3784
+ branch: options.branch,
3785
+ installMode: options.sealed ? "Sealed" : void 0
3786
+ }
3787
+ });
3788
+ console.log(JSON.stringify(preview, null, 2));
3789
+ console.log(`No packages installed. Review every package and its permissions, then repeat with --operation ${preview.operationId} --consent ${preview.fingerprint}.`);
3790
+ }
3791
+
3467
3792
  // src/commands/registry.ts
3468
3793
  async function findLatestLocalVpkg(directory) {
3469
3794
  const entries = await readdir(directory, { withFileTypes: true });
@@ -3548,38 +3873,100 @@ function registerRegistry(program2) {
3548
3873
  console.log(`${pkg.publisherName}/${pkg.packageId}${version} \u2014 ${pkg.displayName} [${pkg.kind}, ${pkg.visibility.toLowerCase()}]`);
3549
3874
  }
3550
3875
  });
3551
- program2.command("install <ref> [version]").description("Install a package into a workspace").option("--workspace <workspaceId>", "target workspace (default: configured default workspace)").option("--path <path>", "install path override (bundles)").option("--branch <branch>", "workspace branch", "main").option("--sealed", "install as a sealed tarball instead of extracting").action(async (ref, version, options) => {
3876
+ program2.command("install <ref> [version]").description("Preview a required dependency graph; install only with explicit consent to that exact preview").option("--workspace <workspaceId>", "target workspace (default: configured default workspace)").option("--path <path>", "install path override (bundles)").option("--branch <branch>", "workspace branch", "main").option("--sealed", "install as a sealed tarball instead of extracting").option("--operation <id>", "previously displayed graph operation ID").option("--consent <fingerprint>", "explicitly approve the exact displayed graph fingerprint (single-use)").option("--preview", "preview even a package without dependencies instead of using its legacy install/reinstall behavior").action(async (ref, version, options) => {
3552
3877
  const config = await loadConfig();
3553
3878
  const workspaceId = options.workspace ?? config.defaultWorkspaceId;
3554
3879
  if (!workspaceId) throw new Error("No workspace: pass --workspace <id> or set defaultWorkspaceId in ~/.verentis/config.json.");
3555
3880
  const api = await createApiClient();
3556
3881
  const { package: pkg } = await resolvePackageRef(api, ref);
3557
- const installationId = await api.request("POST", "/v1/installations", {
3558
- // Marketplace forwards this workspace-bound token to Node for extraction
3559
- // and to Resource for the administrator's consent decision.
3560
- scopes: [
3561
- SCOPES.installCreate,
3562
- "node.node.create",
3563
- ...pkg.kind === "Application" ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : []
3564
- ],
3565
- tokenWorkspaceId: workspaceId,
3566
- body: {
3567
- workspaceId,
3568
- packageId: pkg.id,
3569
- version: version ?? null,
3570
- installPath: options.path ?? null,
3571
- branch: options.branch,
3572
- installMode: options.sealed ? "Sealed" : "Extracted"
3882
+ if (options.operation || options.consent || options.preview) {
3883
+ await installGraph(api, workspaceId, pkg.id, { ...options, version });
3884
+ return;
3885
+ }
3886
+ const effectiveVersion = version ?? pkg.latestPublishedVersion;
3887
+ if (!effectiveVersion) throw new Error(`Package '${ref}' has no published version.`);
3888
+ const detail = await api.request(
3889
+ "GET",
3890
+ `/v1/packages/${encodeURIComponent(pkg.id)}/versions/${encodeURIComponent(effectiveVersion)}`,
3891
+ {
3892
+ scopes: [MARKETPLACE.packageRead],
3893
+ tokenWorkspaceId: workspaceId,
3894
+ query: { workspaceId }
3573
3895
  }
3896
+ );
3897
+ if (!detail.manifestYaml) throw new Error("The selected package version has no manifest baseline.");
3898
+ const manifest = parse(detail.manifestYaml);
3899
+ if (!manifest || typeof manifest !== "object" || !("kind" in manifest)) throw new Error("Invalid package manifest baseline.");
3900
+ const spec = "spec" in manifest ? manifest.spec : void 0;
3901
+ const errors = validateDependencies(spec);
3902
+ if (errors.length) throw new Error(errors.join(" "));
3903
+ if (spec && typeof spec === "object" && "dependencies" in spec && Array.isArray(spec.dependencies) && spec.dependencies.length > 0) {
3904
+ await installGraph(api, workspaceId, pkg.id, { ...options, version });
3905
+ return;
3906
+ }
3907
+ const page = await api.request(
3908
+ "GET",
3909
+ "/v1/installations",
3910
+ {
3911
+ scopes: [MARKETPLACE.installRead],
3912
+ tokenWorkspaceId: workspaceId,
3913
+ query: { workspaceId, packageId: pkg.id, branch: options.branch, pageNo: 1, pageSize: 100, orderBy: "createdAt desc" }
3914
+ }
3915
+ );
3916
+ const existing = pageItems(page).find((installation) => installation.status !== "Uninstalled");
3917
+ const nodeScopes = [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate];
3918
+ const consentScopes = pkg.kind === "Application" ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
3919
+ if (existing) {
3920
+ if (options.path && existing.installPath !== options.path.replace(/^\/+|\/+$/g, "")) {
3921
+ throw new Error(`${ref} is already installed at '${existing.installPath}'. Uninstall it before moving it.`);
3922
+ }
3923
+ const result = await api.request("PUT", `/v1/installations/${encodeURIComponent(existing.id)}`, {
3924
+ scopes: [MARKETPLACE.installUpdate, NODE.fileDelete, ...nodeScopes, ...consentScopes],
3925
+ tokenWorkspaceId: workspaceId,
3926
+ body: {
3927
+ id: existing.id,
3928
+ workspaceId,
3929
+ packageVersion: effectiveVersion,
3930
+ installMode: options.sealed ? "Sealed" : existing.installMode
3931
+ }
3932
+ });
3933
+ if (result.succeeded !== true) throw new Error(result.error ?? "Package replacement failed.");
3934
+ console.log(`Replaced installation ${existing.id} with ${ref}@${effectiveVersion}.`);
3935
+ } else {
3936
+ const id = await api.request("POST", "/v1/installations", {
3937
+ scopes: [SCOPES.installCreate, ...nodeScopes, ...consentScopes],
3938
+ tokenWorkspaceId: workspaceId,
3939
+ body: {
3940
+ workspaceId,
3941
+ packageId: pkg.id,
3942
+ packageVersion: effectiveVersion,
3943
+ installPath: options.path,
3944
+ branch: options.branch,
3945
+ installMode: options.sealed ? "Sealed" : void 0
3946
+ }
3947
+ });
3948
+ if (!id) throw new Error("The installation result is missing its ledger ID.");
3949
+ console.log(`Installed ${ref}@${effectiveVersion} (${id}).`);
3950
+ }
3951
+ });
3952
+ program2.command("install-result <operationId>").description("Inspect durable outcomes after a failure or lost response; never retry accepted installs").option("--workspace <workspaceId>").action(async (operationId, options) => {
3953
+ const config = await loadConfig();
3954
+ const workspaceId = options.workspace ?? config.defaultWorkspaceId;
3955
+ if (!workspaceId) throw new Error("A workspace is required.");
3956
+ const api = await createApiClient();
3957
+ const result = await api.request("GET", `/v1/installations/graphs/${encodeURIComponent(operationId)}`, {
3958
+ scopes: [MARKETPLACE.installRead],
3959
+ tokenWorkspaceId: workspaceId,
3960
+ query: { workspaceId }
3574
3961
  });
3575
- console.log(`Installation ${installationId} started for ${ref} in workspace ${workspaceId}.`);
3962
+ console.log(JSON.stringify(result, null, 2));
3576
3963
  });
3577
3964
  program2.command("uninstall <installationId>").description("Uninstall a package from a workspace").requiredOption("--workspace <workspaceId>", "the workspace the installation belongs to").action(async (installationId, options) => {
3578
3965
  const api = await createApiClient();
3579
- await api.request("DELETE", `/v1/installations/${installationId}`, {
3580
- scopes: [SCOPES.installDelete, "node.file.delete"],
3581
- tokenWorkspaceId: options.workspace,
3582
- body: { id: installationId, workspaceId: options.workspace }
3966
+ await call(api, marketplace.uninstall, {
3967
+ params: { id: installationId },
3968
+ query: { workspaceId: options.workspace },
3969
+ workspaceId: options.workspace
3583
3970
  });
3584
3971
  console.log(`Uninstalled ${installationId}.`);
3585
3972
  });
@@ -3950,7 +4337,7 @@ function registerUser(program2) {
3950
4337
  });
3951
4338
  }
3952
4339
  function registerValidate(program2) {
3953
- program2.command("validate [pathOrDir]").description("Validate an engine/app/bundle manifest (structure + registration-time checks)").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) => {
4340
+ 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) => {
3954
4341
  const target = resolve(pathOrDir ?? ".");
3955
4342
  const info = await stat(target).catch(() => null);
3956
4343
  const manifestPath = info?.isDirectory() ? await findManifest(target) : target;
@@ -4081,6 +4468,7 @@ registerApiKey(program);
4081
4468
  registerSettings(program);
4082
4469
  registerFiles(program);
4083
4470
  registerExec(program);
4471
+ registerPolicy(program);
4084
4472
  registerDev(program);
4085
4473
  registerValidate(program);
4086
4474
  registerCreate(program);