@verentis/cli 0.2.24 → 0.2.26

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
@@ -296,9 +303,8 @@ async function createApiClient(overrides) {
296
303
  body: JSON.stringify({
297
304
  audience: AUDIENCE,
298
305
  scopes: options.scopes,
299
- ...options.workspaceId ? { workspaceId: options.workspaceId } : {},
300
- ...options.accountId ? { accountId: options.accountId } : {},
301
- ...options.resourceId ? { resourceId: options.resourceId, resourceKind: options.resourceKind ?? "Node" } : {}
306
+ ...options.resourceId ?? options.workspaceId ?? options.accountId ? { resourceId: options.resourceId ?? options.workspaceId ?? options.accountId } : {},
307
+ ...options.resourceId && (options.resourceKind ?? "Node") === "Node" ? { resourceType: "Node", ...options.workspaceId ? { parentResourceId: options.workspaceId } : {} } : {}
302
308
  }),
303
309
  ...insecureFetchOptions(insecure)
304
310
  });
@@ -1035,11 +1041,14 @@ function contextEnv(context, contextPath) {
1035
1041
  var KIND_MAP = {
1036
1042
  application: "Application",
1037
1043
  executionengine: "ExecutionEngine",
1044
+ agent: "Agent",
1045
+ skill: "Skill",
1046
+ tool: "Tool",
1038
1047
  bundle: "Bundle"
1039
1048
  };
1040
1049
  function normalizeKind(kind) {
1041
1050
  const mapped = KIND_MAP[kind.replace(/[^a-z]/gi, "").toLowerCase()];
1042
- if (!mapped) throw new Error(`Unsupported manifest kind '${kind}' \u2014 expected Application, ExecutionEngine or Bundle.`);
1051
+ if (!mapped) throw new Error(`Unsupported manifest kind '${kind}' \u2014 expected Application, ExecutionEngine, Agent, Skill, Tool or Bundle.`);
1043
1052
  return mapped;
1044
1053
  }
1045
1054
  function validateLaunchManifestKind(kind, spec) {
@@ -1057,12 +1066,24 @@ async function loadManifest(path) {
1057
1066
  if (!manifest.metadata?.version) throw new Error(`Manifest at ${path} is missing 'metadata.version'.`);
1058
1067
  validatePackageName(manifest.metadata["package-id"], "package ID");
1059
1068
  const kind = normalizeKind(manifest.kind);
1069
+ const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
1070
+ if (hostedBackendErrors.length > 0) {
1071
+ throw new Error(`Invalid manifest at ${path}: ${hostedBackendErrors.join(" ")}`);
1072
+ }
1060
1073
  const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
1061
1074
  if (launchKindError) throw new Error(`Invalid manifest at ${path}: ${launchKindError}.`);
1075
+ const collaborationErrors = validateNativeCollaborationSection(kind, manifest.spec);
1076
+ if (collaborationErrors.length > 0) {
1077
+ throw new Error(`Invalid manifest at ${path}: ${collaborationErrors.join(" ")}`);
1078
+ }
1062
1079
  const operationErrors = validateWopiOperationsSection(manifest.spec);
1063
1080
  if (operationErrors.length > 0) {
1064
1081
  throw new Error(`Invalid manifest at ${path}: ${operationErrors.join(" ")}`);
1065
1082
  }
1083
+ const dependencyErrors = validateDependencies(manifest.spec);
1084
+ if (dependencyErrors.length > 0) {
1085
+ throw new Error(`Invalid manifest at ${path}: ${dependencyErrors.join(" ")}`);
1086
+ }
1066
1087
  const splashErrors = validateApplicationSplashSection(kind, manifest.spec);
1067
1088
  if (splashErrors.length > 0) {
1068
1089
  throw new Error(`Invalid manifest at ${path}: ${splashErrors.join(" ")}`);
@@ -1111,6 +1132,29 @@ function validateApplicationSplashSection(kind, spec) {
1111
1132
  }
1112
1133
  return errors;
1113
1134
  }
1135
+ function validateHostedBackendDeclaration(kind, spec) {
1136
+ if (kind === "Application" || !spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1137
+ const value = spec;
1138
+ const capabilities = value.capabilities;
1139
+ const requestsCapability = Array.isArray(capabilities) && capabilities.some((capability) => typeof capability === "string" && capability.trim().toLowerCase() === "hosted-backend");
1140
+ if (requestsCapability || Object.prototype.hasOwnProperty.call(value, "hosted-backend")) {
1141
+ return [`${kind} packages cannot declare a hosted backend.`];
1142
+ }
1143
+ return [];
1144
+ }
1145
+ function validateNativeCollaborationSection(kind, spec) {
1146
+ if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "collaboration")) return [];
1147
+ if (kind !== "Application") return ["spec.collaboration is only supported for Application manifests."];
1148
+ const applicationSpec = spec;
1149
+ const declaration = applicationSpec.collaboration;
1150
+ if (!declaration || typeof declaration !== "object" || Array.isArray(declaration) || Object.keys(declaration).length !== 1 || !Object.prototype.hasOwnProperty.call(declaration, "mode") || declaration.mode !== "native-scene-v1") {
1151
+ return ["spec.collaboration must be exactly { mode: native-scene-v1 }."];
1152
+ }
1153
+ if (Object.prototype.hasOwnProperty.call(applicationSpec, "wopi") || Array.isArray(applicationSpec.capabilities) && applicationSpec.capabilities.includes("wopi")) {
1154
+ return ["Native collaboration and WOPI must use separate application declarations."];
1155
+ }
1156
+ return [];
1157
+ }
1114
1158
  function validateWopiOperationsSection(spec) {
1115
1159
  if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1116
1160
  const wopi = spec.wopi;
@@ -1191,14 +1235,65 @@ async function findManifest(dir) {
1191
1235
  } catch {
1192
1236
  }
1193
1237
  const entries = await readdir(dir);
1194
- const candidates = entries.filter((name) => /\.(app|engine|bundle)\.ya?ml$/.test(name));
1238
+ const candidates = entries.filter((name) => /\.(app|engine|agent|skill|tool|bundle|policy)\.ya?ml$/.test(name));
1195
1239
  if (candidates.length === 1) return join(dir, candidates[0]);
1196
1240
  if (candidates.length === 0) {
1197
- throw new Error(`No manifest found in ${dir}. Expected manifest.yaml or *.app.yaml / *.engine.yaml / *.bundle.yaml.`);
1241
+ 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.`);
1198
1242
  }
1199
1243
  throw new Error(`Multiple manifests found in ${dir} (${candidates.join(", ")}). Pass --manifest to disambiguate.`);
1200
1244
  }
1201
1245
  var NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
1246
+ var DEPENDENCY_IDENTITY = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
1247
+ 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-]+)*)?$/;
1248
+ function validateDependencies(spec) {
1249
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1250
+ const value = spec;
1251
+ const errors = [];
1252
+ const required = /* @__PURE__ */ new Set();
1253
+ const seen = /* @__PURE__ */ new Set();
1254
+ if (value.dependencies !== void 0) {
1255
+ if (!Array.isArray(value.dependencies) || value.dependencies.length > 32) {
1256
+ errors.push("spec.dependencies must be a list of at most 32 exact package pins.");
1257
+ } else {
1258
+ for (const dependency of value.dependencies) {
1259
+ if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) {
1260
+ errors.push("Each dependency must be an object.");
1261
+ continue;
1262
+ }
1263
+ const item = dependency;
1264
+ if (Object.keys(item).some((key) => !["package", "version", "install-path", "optional"].includes(key))) {
1265
+ errors.push("Each dependency accepts only package, version, install-path and optional.");
1266
+ }
1267
+ if (typeof item.package !== "string" || !DEPENDENCY_IDENTITY.test(item.package) || typeof item.version !== "string" || !EXACT_VERSION.test(item.version)) {
1268
+ errors.push("Dependencies require a lowercase publisher/package-id and an exact semantic version.");
1269
+ }
1270
+ if (item.optional !== void 0 && typeof item.optional !== "boolean") {
1271
+ errors.push("Dependency optional must be true or false.");
1272
+ }
1273
+ if (item["install-path"] !== void 0) {
1274
+ const path = item["install-path"];
1275
+ const normalized = typeof path === "string" ? path.trim().replace(/^\/+|\/+$/g, "") : "";
1276
+ if (!normalized || normalized.length > 512 || /[\\\u0000-\u001f\u007f]/.test(normalized) || normalized.split("/").some((segment) => ["", ".", ".."].includes(segment))) {
1277
+ errors.push("Dependency install-path must be a nonempty workspace path without traversal.");
1278
+ }
1279
+ }
1280
+ if (typeof item.package === "string") {
1281
+ if (seen.has(item.package)) errors.push(`Duplicate dependency '${item.package}'.`);
1282
+ seen.add(item.package);
1283
+ if (item.optional !== true) required.add(item.package);
1284
+ }
1285
+ }
1286
+ }
1287
+ }
1288
+ if (value.engine !== void 0) {
1289
+ if (typeof value.engine !== "string" || !DEPENDENCY_IDENTITY.test(value.engine) || !required.has(value.engine)) {
1290
+ errors.push("spec.engine must name a required publisher-qualified dependency.");
1291
+ }
1292
+ } else if (value.scripts !== void 0) {
1293
+ errors.push("Script packages must declare spec.engine and its required dependency.");
1294
+ }
1295
+ return errors;
1296
+ }
1202
1297
  function validatePackageName(name, label) {
1203
1298
  if (!NAME_PATTERN.test(name)) {
1204
1299
  throw new Error(`Invalid ${label} '${name}' \u2014 use lowercase letters, digits and hyphens (no leading/trailing hyphen).`);
@@ -1222,28 +1317,43 @@ function validateManifest(manifest) {
1222
1317
  const error = (message) => issues.push({ level: "error", message });
1223
1318
  const warning = (message) => issues.push({ level: "warning", message });
1224
1319
  const kind = manifest.kind;
1320
+ const knownKinds = ["ExecutionEngine", "Application", "Agent", "Skill", "Tool", "Bundle", "Policy"];
1225
1321
  if (!kind) {
1226
- error("missing 'kind' (ExecutionEngine | Application | Bundle)");
1322
+ error("missing 'kind' (ExecutionEngine | Application | Agent | Skill | Tool | Bundle | Policy)");
1227
1323
  return issues;
1228
1324
  }
1229
- if (!["ExecutionEngine", "Application", "Bundle"].includes(kind)) {
1230
- error(`unknown kind '${kind}' (expected ExecutionEngine, Application or Bundle)`);
1325
+ if (!knownKinds.includes(kind)) {
1326
+ error(`unknown kind '${kind}' (expected ExecutionEngine, Application, Agent, Skill, Tool, Bundle or Policy)`);
1327
+ }
1328
+ if (!manifest["api-version"]) {
1329
+ warning("missing 'api-version' (expected verentis.io/v1)");
1330
+ } else if (manifest["api-version"] !== "verentis.io/v1") {
1331
+ error("api-version must be 'verentis.io/v1'");
1231
1332
  }
1232
- if (!manifest["api-version"]) warning("missing 'api-version' (expected verentis.io/v1)");
1233
1333
  const meta = manifest.metadata ?? {};
1234
- for (const field of ["name", "display-name", "version"]) {
1235
- if (!meta[field]) error(`metadata.${field} is required`);
1334
+ if (!meta.name) {
1335
+ error("metadata.name is required");
1336
+ } else if (!NAME_PATTERN.test(meta.name)) {
1337
+ error("metadata.name must use lowercase letters, digits and internal hyphens");
1236
1338
  }
1237
- if (!meta["package-id"]) {
1238
- error("metadata.package-id is required");
1239
- } else if (!NAME_PATTERN.test(meta["package-id"])) {
1240
- error("metadata.package-id must use lowercase letters, digits and internal hyphens");
1339
+ if (kind !== "Policy") {
1340
+ for (const field of ["display-name", "version"]) {
1341
+ if (!meta[field]) error(`metadata.${field} is required`);
1342
+ }
1343
+ if (!meta["package-id"]) {
1344
+ error("metadata.package-id is required");
1345
+ } else if (!NAME_PATTERN.test(meta["package-id"])) {
1346
+ error("metadata.package-id must use lowercase letters, digits and internal hyphens");
1347
+ }
1241
1348
  }
1242
1349
  const spec = manifest.spec ?? {};
1243
1350
  validateManifestIcons(meta, spec, issues);
1244
1351
  const launchKindError = validateLaunchManifestKind(kind, spec);
1245
1352
  if (launchKindError) error(launchKindError);
1246
1353
  for (const message of validateWopiOperationsSection(spec)) error(message);
1354
+ for (const message of validateHostedBackendDeclaration(kind, spec)) error(message);
1355
+ for (const message of validateDependencies(spec)) error(message);
1356
+ for (const message of validateNativeCollaborationSection(kind, spec)) error(message);
1247
1357
  if (kind === "ExecutionEngine") {
1248
1358
  const runtimes = spec.runtimes ?? {};
1249
1359
  if (Object.keys(runtimes).length === 0) {
@@ -1275,13 +1385,117 @@ function validateManifest(manifest) {
1275
1385
  for (const message of validateApplicationSplashSection(kind, spec)) error(message);
1276
1386
  validateApplicationLaunch(spec, issues);
1277
1387
  }
1388
+ if (kind === "Agent") validateAgentManifest(spec, issues);
1389
+ if (kind === "Skill") validateSkillManifest(spec, issues);
1390
+ if (kind === "Tool") validateToolManifest(spec, issues);
1391
+ if (kind === "Policy") validatePolicyManifest(spec, issues);
1278
1392
  validateInstallDirectives(spec.install, issues);
1279
1393
  validateSettingDeclarations(kind, spec, issues);
1280
1394
  for (const message of validateMarketplaceSection(manifest.marketplace)) error(message);
1281
1395
  const packaging = manifest.packaging ?? {};
1282
- if (!packaging.publisher) warning("packaging.publisher is not set \u2014 `verentis pack`/`publish` will refuse the package");
1396
+ if (kind !== "Policy" && !packaging.publisher) warning("packaging.publisher is not set \u2014 `verentis pack`/`publish` will refuse the package");
1283
1397
  return issues;
1284
1398
  }
1399
+ function validateAgentManifest(spec, issues) {
1400
+ const error = (message) => issues.push({ level: "error", message });
1401
+ if (spec.instructions !== void 0 && typeof spec.instructions !== "string") error("spec.instructions must be a string");
1402
+ if (spec["system-prompt"] !== void 0 && typeof spec["system-prompt"] !== "string") error("spec.system-prompt must be a string");
1403
+ if (spec.instructions !== void 0 && spec["system-prompt"] !== void 0) {
1404
+ error("spec.instructions and spec.system-prompt cannot both be set");
1405
+ }
1406
+ if (spec["instructions-file"] !== void 0 && (spec.instructions !== void 0 || spec["system-prompt"] !== void 0)) {
1407
+ error("spec.instructions-file cannot be combined with inline instructions");
1408
+ }
1409
+ validateUniqueStrings(spec.skills, "spec.skills", issues);
1410
+ validateUniqueStrings(spec.tools, "spec.tools", issues);
1411
+ }
1412
+ function validateSkillManifest(spec, issues) {
1413
+ const error = (message) => issues.push({ level: "error", message });
1414
+ if (typeof spec.description !== "string" || spec.description.trim().length === 0) {
1415
+ error("spec.description is required for Skill manifests");
1416
+ }
1417
+ if (spec.instructions !== void 0 && spec["instructions-file"] !== void 0) {
1418
+ error("spec.instructions and spec.instructions-file cannot both be set");
1419
+ }
1420
+ validateUniqueStrings(spec.skills, "spec.skills", issues);
1421
+ validateUniqueStrings(spec.tools, "spec.tools", issues);
1422
+ }
1423
+ function validateToolManifest(spec, issues) {
1424
+ const error = (message) => issues.push({ level: "error", message });
1425
+ const tools = spec.tools;
1426
+ if (!Array.isArray(tools) || tools.length === 0) {
1427
+ error("spec.tools must contain at least one tool definition");
1428
+ return;
1429
+ }
1430
+ const serverNames = /* @__PURE__ */ new Set();
1431
+ const servers = spec.mcp && typeof spec.mcp === "object" && !Array.isArray(spec.mcp) ? spec.mcp.servers : void 0;
1432
+ if (Array.isArray(servers)) {
1433
+ for (const server of servers) {
1434
+ if (server && typeof server === "object" && !Array.isArray(server)) {
1435
+ const name = server.name;
1436
+ if (typeof name === "string") serverNames.add(name);
1437
+ }
1438
+ }
1439
+ }
1440
+ const keys = /* @__PURE__ */ new Set();
1441
+ tools.forEach((tool, index) => {
1442
+ const at = `spec.tools[${index}]`;
1443
+ if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
1444
+ error(`${at} must be an object`);
1445
+ return;
1446
+ }
1447
+ const item = tool;
1448
+ if (typeof item.key !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(item.key)) error(`${at}.key is required`);
1449
+ else if (keys.has(item.key)) error(`duplicate tool key '${item.key}'`);
1450
+ else keys.add(item.key);
1451
+ if (typeof item.description !== "string" || item.description.trim().length === 0) error(`${at}.description is required`);
1452
+ if (item["input-schema"] === void 0) error(`${at}.input-schema is required`);
1453
+ if (!["read", "write", "execute", "external", "interactive"].includes(String(item.effect))) error(`${at}.effect is invalid`);
1454
+ const implementation = item.implementation;
1455
+ if (!implementation || typeof implementation !== "object" || Array.isArray(implementation)) {
1456
+ error(`${at}.implementation is required`);
1457
+ } else if (implementation.type === "mcp") {
1458
+ const server = implementation.server;
1459
+ if (typeof server !== "string" || !serverNames.has(server)) error(`${at}.implementation.server is not declared in spec.mcp.servers`);
1460
+ }
1461
+ const retry = item.retry;
1462
+ 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))) {
1463
+ error(`${at}.retry requires a reconciliation contract for non-read tools`);
1464
+ }
1465
+ });
1466
+ }
1467
+ function validatePolicyManifest(spec, issues) {
1468
+ const error = (message) => issues.push({ level: "error", message });
1469
+ if (spec.area !== "agent") error("spec.area must be agent");
1470
+ if (!Array.isArray(spec.rules)) {
1471
+ error("spec.rules must be an array");
1472
+ return;
1473
+ }
1474
+ spec.rules.forEach((rule, index) => {
1475
+ const at = `spec.rules[${index}]`;
1476
+ if (!rule || typeof rule !== "object" || Array.isArray(rule)) {
1477
+ error(`${at} must be an object`);
1478
+ return;
1479
+ }
1480
+ const item = rule;
1481
+ if (typeof item.id !== "string" || item.id.trim().length === 0) error(`${at}.id is required`);
1482
+ if (!["permit", "deny", "require-approval"].includes(String(item.effect))) error(`${at}.effect must be permit, deny or require-approval`);
1483
+ if (typeof item.capability !== "string" || item.capability.trim().length === 0) error(`${at}.capability is required`);
1484
+ });
1485
+ }
1486
+ function validateUniqueStrings(value, path, issues) {
1487
+ if (value === void 0) return;
1488
+ if (!Array.isArray(value)) {
1489
+ issues.push({ level: "error", message: `${path} must be an array` });
1490
+ return;
1491
+ }
1492
+ const seen = /* @__PURE__ */ new Set();
1493
+ for (const item of value) {
1494
+ if (typeof item !== "string") continue;
1495
+ if (seen.has(item)) issues.push({ level: "error", message: `${path} contains duplicate '${item}'` });
1496
+ seen.add(item);
1497
+ }
1498
+ }
1285
1499
  function validateManifestIcons(metadata, spec, issues) {
1286
1500
  validateOptionalIcon(metadata.icon, "metadata.icon", issues);
1287
1501
  validateBindingIcons(spec["mime-types"], "spec.mime-types", issues);
@@ -1800,7 +2014,7 @@ async function followExecution(api, workspaceId, executionId, json) {
1800
2014
  if (exec.status !== "Completed") process.exitCode = 1;
1801
2015
  return;
1802
2016
  }
1803
- await new Promise((resolve12) => setTimeout(resolve12, 1e3));
2017
+ await new Promise((resolve13) => setTimeout(resolve13, 1e3));
1804
2018
  }
1805
2019
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
1806
2020
  process.exitCode = 1;
@@ -2911,6 +3125,10 @@ async function pack(options) {
2911
3125
  overrideApplied = true;
2912
3126
  }
2913
3127
  const kind = normalizeKind(manifest.kind);
3128
+ const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
3129
+ if (hostedBackendErrors.length > 0) throw new Error(`Invalid manifest: ${hostedBackendErrors.join(" ")}`);
3130
+ const dependencyErrors = validateDependencies(manifest.spec);
3131
+ if (dependencyErrors.length > 0) throw new Error(`Invalid dependencies: ${dependencyErrors.join(" ")}`);
2914
3132
  const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
2915
3133
  if (launchKindError) throw new Error(`Invalid manifest: ${launchKindError}.`);
2916
3134
  const marketplaceErrors = validateMarketplaceSection(manifest.marketplace);
@@ -3313,6 +3531,88 @@ function registerPackage(program2) {
3313
3531
  output(pageItems(page), { packageName: "Package", version: "Version", status: "Status", installPath: "Path", id: "Id" }, options, page);
3314
3532
  });
3315
3533
  }
3534
+ var POLICY_READ_SCOPE = "fabric.policy.read";
3535
+ var POLICY_UPDATE_SCOPE = "fabric.policy.update";
3536
+ function registerPolicy(program2) {
3537
+ const policyCmd = program2.command("policy").description("Export and apply workspace policy manifests");
3538
+ 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) => {
3539
+ const api = await createApiClient();
3540
+ const result = await exportPolicy(api, options.workspace, area ?? "agent");
3541
+ if (options.out) await writeFile(resolve(options.out), result.manifest);
3542
+ if (options.json) {
3543
+ printJson({ ...result, ...options.out ? { out: resolve(options.out) } : {} });
3544
+ } else if (options.out) {
3545
+ console.log(`Wrote ${result.area} policy manifest to ${resolve(options.out)}.`);
3546
+ console.error(`revision ${result.revision}`);
3547
+ } else {
3548
+ process.stdout.write(result.manifest.endsWith("\n") ? result.manifest : `${result.manifest}
3549
+ `);
3550
+ console.error(`revision ${result.revision}`);
3551
+ }
3552
+ });
3553
+ 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) => {
3554
+ const manifestPath = resolve(file);
3555
+ const manifest = await readFile(manifestPath, "utf8");
3556
+ const area = options.area ?? areaFromManifest(manifest) ?? "agent";
3557
+ const api = await createApiClient();
3558
+ const expectedRevision = options.expectedRevision !== void 0 ? parseExpectedRevision(options.expectedRevision) : await currentRevisionOrZero(api, options.workspace, area);
3559
+ try {
3560
+ const result = await applyPolicy(api, options.workspace, area, manifest, expectedRevision, options.dryRun === true);
3561
+ if (options.json) {
3562
+ printJson(result);
3563
+ } else {
3564
+ console.log(`${result.dryRun ? "Dry run" : result.applied ? "Applied" : "No changes"}: ${area} policy revision ${result.revision}.`);
3565
+ for (const change of result.changes ?? []) console.log(` ${change}`);
3566
+ }
3567
+ } catch (error) {
3568
+ if (error instanceof ApiError && error.status === 409) {
3569
+ throw new Error(`Policy revision conflict for area '${area}'. Re-export the policy, reapply your edits, then retry.`);
3570
+ }
3571
+ throw error;
3572
+ }
3573
+ });
3574
+ }
3575
+ async function exportPolicy(api, workspaceId, area) {
3576
+ const response = await api.request("GET", `/v1/policies/${encodeURIComponent(area)}/manifest`, {
3577
+ scopes: [POLICY_READ_SCOPE],
3578
+ tokenWorkspaceId: workspaceId,
3579
+ query: { workspaceId }
3580
+ });
3581
+ return unwrap2(response);
3582
+ }
3583
+ async function applyPolicy(api, workspaceId, area, manifest, expectedRevision, dryRun) {
3584
+ const response = await api.request("POST", `/v1/policies/${encodeURIComponent(area)}/apply`, {
3585
+ scopes: [dryRun ? POLICY_READ_SCOPE : POLICY_UPDATE_SCOPE],
3586
+ tokenWorkspaceId: workspaceId,
3587
+ query: { workspaceId },
3588
+ body: { workspaceId, area, manifest, expectedRevision, dryRun }
3589
+ });
3590
+ return unwrap2(response);
3591
+ }
3592
+ async function currentRevisionOrZero(api, workspaceId, area) {
3593
+ try {
3594
+ return (await exportPolicy(api, workspaceId, area)).revision;
3595
+ } catch (error) {
3596
+ if (error instanceof ApiError && error.status === 404) return 0;
3597
+ throw error;
3598
+ }
3599
+ }
3600
+ function areaFromManifest(manifest) {
3601
+ const document = parse(manifest);
3602
+ const area = document?.spec?.area;
3603
+ return typeof area === "string" && area.trim().length > 0 ? area : void 0;
3604
+ }
3605
+ function parseExpectedRevision(value) {
3606
+ const revision = Number(value);
3607
+ if (!Number.isInteger(revision) || revision < 0) throw new Error("--expected-revision must be a non-negative integer.");
3608
+ return revision;
3609
+ }
3610
+ function unwrap2(value) {
3611
+ if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 1 && "value" in value) {
3612
+ return value.value;
3613
+ }
3614
+ return value;
3615
+ }
3316
3616
  var MAX_LOGO_BYTES2 = 1024 * 1024;
3317
3617
  var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
3318
3618
  async function readPublisherLogo(path) {
@@ -3430,8 +3730,8 @@ function isNewerVersion(candidate, base) {
3430
3730
  return compareVersions(candidate, base) > 0;
3431
3731
  }
3432
3732
  function compareVersions(a, b) {
3433
- const pa = parse5(a);
3434
- const pb = parse5(b);
3733
+ const pa = parse6(a);
3734
+ const pb = parse6(b);
3435
3735
  for (let i = 0; i < 3; i++) {
3436
3736
  if (pa.main[i] !== pb.main[i]) return pa.main[i] < pb.main[i] ? -1 : 1;
3437
3737
  }
@@ -3458,7 +3758,7 @@ function compareVersions(a, b) {
3458
3758
  }
3459
3759
  return 0;
3460
3760
  }
3461
- function parse5(version) {
3761
+ function parse6(version) {
3462
3762
  const cleaned = version.trim().replace(/^v/i, "").split("+", 1)[0];
3463
3763
  const dash = cleaned.indexOf("-");
3464
3764
  const core = dash === -1 ? cleaned : cleaned.slice(0, dash);
@@ -3467,6 +3767,45 @@ function parse5(version) {
3467
3767
  return { main: [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0], pre: pre ? pre.split(".") : [] };
3468
3768
  }
3469
3769
 
3770
+ // src/commands/installation-graph.ts
3771
+ async function installGraph(api, workspaceId, packageId, options) {
3772
+ if (options.operation || options.consent) {
3773
+ if (!options.operation || !options.consent) throw new Error("--operation and --consent must be supplied together.");
3774
+ const result = await api.request("POST", "/v1/installations/graphs", {
3775
+ scopes: [
3776
+ SCOPES.installCreate,
3777
+ "marketplace.install.update",
3778
+ NODE.nodeCreate,
3779
+ NODE.fileRead,
3780
+ NODE.fileDelete,
3781
+ NODE.nodeUpdate,
3782
+ NODE.journalCreate,
3783
+ SCOPES.resourceReadAll,
3784
+ SCOPES.resourceUpdate
3785
+ ],
3786
+ tokenWorkspaceId: workspaceId,
3787
+ body: { workspaceId, operationId: options.operation, fingerprint: options.consent, consent: true }
3788
+ });
3789
+ console.log(JSON.stringify(result, null, 2));
3790
+ if (result.succeeded !== true) throw new Error(`Graph installation failed. Inspect operation ${options.operation}; do not resubmit it.`);
3791
+ return;
3792
+ }
3793
+ const preview = await api.request("POST", "/v1/installations/graphs/preview", {
3794
+ scopes: [SCOPES.installCreate],
3795
+ tokenWorkspaceId: workspaceId,
3796
+ body: {
3797
+ workspaceId,
3798
+ packageId,
3799
+ packageVersion: options.version,
3800
+ installPath: options.path,
3801
+ branch: options.branch,
3802
+ installMode: options.sealed ? "Sealed" : void 0
3803
+ }
3804
+ });
3805
+ console.log(JSON.stringify(preview, null, 2));
3806
+ console.log(`No packages installed. Review every package and its permissions, then repeat with --operation ${preview.operationId} --consent ${preview.fingerprint}.`);
3807
+ }
3808
+
3470
3809
  // src/commands/registry.ts
3471
3810
  async function findLatestLocalVpkg(directory) {
3472
3811
  const entries = await readdir(directory, { withFileTypes: true });
@@ -3551,48 +3890,93 @@ function registerRegistry(program2) {
3551
3890
  console.log(`${pkg.publisherName}/${pkg.packageId}${version} \u2014 ${pkg.displayName} [${pkg.kind}, ${pkg.visibility.toLowerCase()}]`);
3552
3891
  }
3553
3892
  });
3554
- program2.command("install <ref> [version]").description("Install a package into a workspace (replaces an existing or failed installation of the same package in place)").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) => {
3893
+ 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) => {
3555
3894
  const config = await loadConfig();
3556
3895
  const workspaceId = options.workspace ?? config.defaultWorkspaceId;
3557
3896
  if (!workspaceId) throw new Error("No workspace: pass --workspace <id> or set defaultWorkspaceId in ~/.verentis/config.json.");
3558
3897
  const api = await createApiClient();
3559
3898
  const { package: pkg } = await resolvePackageRef(api, ref);
3899
+ if (options.operation || options.consent || options.preview) {
3900
+ await installGraph(api, workspaceId, pkg.id, { ...options, version });
3901
+ return;
3902
+ }
3903
+ const effectiveVersion = version ?? pkg.latestPublishedVersion;
3904
+ if (!effectiveVersion) throw new Error(`Package '${ref}' has no published version.`);
3905
+ const detail = await api.request(
3906
+ "GET",
3907
+ `/v1/packages/${encodeURIComponent(pkg.id)}/versions/${encodeURIComponent(effectiveVersion)}`,
3908
+ {
3909
+ scopes: [MARKETPLACE.packageRead],
3910
+ tokenWorkspaceId: workspaceId,
3911
+ query: { workspaceId }
3912
+ }
3913
+ );
3914
+ if (!detail.manifestYaml) throw new Error("The selected package version has no manifest baseline.");
3915
+ const manifest = parse(detail.manifestYaml);
3916
+ if (!manifest || typeof manifest !== "object" || !("kind" in manifest)) throw new Error("Invalid package manifest baseline.");
3917
+ const spec = "spec" in manifest ? manifest.spec : void 0;
3918
+ const errors = validateDependencies(spec);
3919
+ if (errors.length) throw new Error(errors.join(" "));
3920
+ if (spec && typeof spec === "object" && "dependencies" in spec && Array.isArray(spec.dependencies) && spec.dependencies.length > 0) {
3921
+ await installGraph(api, workspaceId, pkg.id, { ...options, version });
3922
+ return;
3923
+ }
3924
+ const page = await api.request(
3925
+ "GET",
3926
+ "/v1/installations",
3927
+ {
3928
+ scopes: [MARKETPLACE.installRead],
3929
+ tokenWorkspaceId: workspaceId,
3930
+ query: { workspaceId, packageId: pkg.id, branch: options.branch, pageNo: 1, pageSize: 100, orderBy: "createdAt desc" }
3931
+ }
3932
+ );
3933
+ const existing = pageItems(page).find((installation) => installation.status !== "Uninstalled");
3934
+ const nodeScopes = [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate];
3560
3935
  const consentScopes = pkg.kind === "Application" ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
3561
- const existing = await findActiveInstallation(api, workspaceId, pkg.id, options.branch);
3562
3936
  if (existing) {
3563
- if (options.path && existing.installPath && options.path !== existing.installPath) {
3564
- throw new Error(`${ref} is already installed at '${existing.installPath}' (installation ${existing.id}). Uninstall it before installing at '${options.path}'.`);
3937
+ if (options.path && existing.installPath !== options.path.replace(/^\/+|\/+$/g, "")) {
3938
+ throw new Error(`${ref} is already installed at '${existing.installPath}'. Uninstall it before moving it.`);
3565
3939
  }
3566
- const result = await api.request("PUT", `/v1/installations/${existing.id}`, {
3567
- scopes: [MARKETPLACE.installUpdate, NODE.fileDelete, ...INSTALL_NODE_SCOPES, ...consentScopes],
3940
+ const result = await api.request("PUT", `/v1/installations/${encodeURIComponent(existing.id)}`, {
3941
+ scopes: [MARKETPLACE.installUpdate, NODE.fileDelete, ...nodeScopes, ...consentScopes],
3568
3942
  tokenWorkspaceId: workspaceId,
3569
3943
  body: {
3570
3944
  id: existing.id,
3571
3945
  workspaceId,
3572
- packageVersion: version ?? void 0,
3573
- installMode: options.sealed ? "Sealed" : existing.installMode ?? "Extracted"
3946
+ packageVersion: effectiveVersion,
3947
+ installMode: options.sealed ? "Sealed" : existing.installMode
3574
3948
  }
3575
3949
  });
3576
- if (result && result.succeeded === false) {
3577
- throw new Error(`Reinstall of ${ref} failed (installation ${existing.id}, status ${result.status}): ${result.error ?? "unknown error"}`);
3578
- }
3579
- const from = existing.status === "Failed" ? "failed installation" : "installation";
3580
- console.log(`Replaced ${from} ${existing.id} with ${ref}${version ? `@${version}` : ""} in workspace ${workspaceId} (${result?.status ?? "Installed"}).`);
3581
- return;
3950
+ if (result.succeeded !== true) throw new Error(result.error ?? "Package replacement failed.");
3951
+ console.log(`Replaced installation ${existing.id} with ${ref}@${effectiveVersion}.`);
3952
+ } else {
3953
+ const id = await api.request("POST", "/v1/installations", {
3954
+ scopes: [SCOPES.installCreate, ...nodeScopes, ...consentScopes],
3955
+ tokenWorkspaceId: workspaceId,
3956
+ body: {
3957
+ workspaceId,
3958
+ packageId: pkg.id,
3959
+ packageVersion: effectiveVersion,
3960
+ installPath: options.path,
3961
+ branch: options.branch,
3962
+ installMode: options.sealed ? "Sealed" : void 0
3963
+ }
3964
+ });
3965
+ if (!id) throw new Error("The installation result is missing its ledger ID.");
3966
+ console.log(`Installed ${ref}@${effectiveVersion} (${id}).`);
3582
3967
  }
3583
- const installationId = await api.request("POST", "/v1/installations", {
3584
- scopes: [SCOPES.installCreate, ...INSTALL_NODE_SCOPES, ...consentScopes],
3968
+ });
3969
+ 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) => {
3970
+ const config = await loadConfig();
3971
+ const workspaceId = options.workspace ?? config.defaultWorkspaceId;
3972
+ if (!workspaceId) throw new Error("A workspace is required.");
3973
+ const api = await createApiClient();
3974
+ const result = await api.request("GET", `/v1/installations/graphs/${encodeURIComponent(operationId)}`, {
3975
+ scopes: [MARKETPLACE.installRead],
3585
3976
  tokenWorkspaceId: workspaceId,
3586
- body: {
3587
- workspaceId,
3588
- packageId: pkg.id,
3589
- version: version ?? null,
3590
- installPath: options.path ?? null,
3591
- branch: options.branch,
3592
- installMode: options.sealed ? "Sealed" : "Extracted"
3593
- }
3977
+ query: { workspaceId }
3594
3978
  });
3595
- console.log(`Installation ${installationId} started for ${ref} in workspace ${workspaceId}.`);
3979
+ console.log(JSON.stringify(result, null, 2));
3596
3980
  });
3597
3981
  program2.command("uninstall <installationId>").description("Uninstall a package from a workspace").requiredOption("--workspace <workspaceId>", "the workspace the installation belongs to").action(async (installationId, options) => {
3598
3982
  const api = await createApiClient();
@@ -3604,13 +3988,6 @@ function registerRegistry(program2) {
3604
3988
  console.log(`Uninstalled ${installationId}.`);
3605
3989
  });
3606
3990
  }
3607
- var INSTALL_NODE_SCOPES = [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate];
3608
- async function findActiveInstallation(api, workspaceId, packageId, branch) {
3609
- const page = await call(api, marketplace.listInstallations, {
3610
- query: { workspaceId, packageId, branch, pageNo: 1, pageSize: 100, orderBy: "createdAt desc" }
3611
- });
3612
- return pageItems(page).find((installation) => installation.status !== "Uninstalled") ?? null;
3613
- }
3614
3991
 
3615
3992
  // src/commands/settings.ts
3616
3993
  async function settingScope(flags) {
@@ -3977,7 +4354,7 @@ function registerUser(program2) {
3977
4354
  });
3978
4355
  }
3979
4356
  function registerValidate(program2) {
3980
- 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) => {
4357
+ 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) => {
3981
4358
  const target = resolve(pathOrDir ?? ".");
3982
4359
  const info = await stat(target).catch(() => null);
3983
4360
  const manifestPath = info?.isDirectory() ? await findManifest(target) : target;
@@ -4108,6 +4485,7 @@ registerApiKey(program);
4108
4485
  registerSettings(program);
4109
4486
  registerFiles(program);
4110
4487
  registerExec(program);
4488
+ registerPolicy(program);
4111
4489
  registerDev(program);
4112
4490
  registerValidate(program);
4113
4491
  registerCreate(program);