@verentis/cli 0.2.24 → 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
@@ -1035,11 +1042,14 @@ function contextEnv(context, contextPath) {
1035
1042
  var KIND_MAP = {
1036
1043
  application: "Application",
1037
1044
  executionengine: "ExecutionEngine",
1045
+ agent: "Agent",
1046
+ skill: "Skill",
1047
+ tool: "Tool",
1038
1048
  bundle: "Bundle"
1039
1049
  };
1040
1050
  function normalizeKind(kind) {
1041
1051
  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.`);
1052
+ if (!mapped) throw new Error(`Unsupported manifest kind '${kind}' \u2014 expected Application, ExecutionEngine, Agent, Skill, Tool or Bundle.`);
1043
1053
  return mapped;
1044
1054
  }
1045
1055
  function validateLaunchManifestKind(kind, spec) {
@@ -1057,12 +1067,20 @@ async function loadManifest(path) {
1057
1067
  if (!manifest.metadata?.version) throw new Error(`Manifest at ${path} is missing 'metadata.version'.`);
1058
1068
  validatePackageName(manifest.metadata["package-id"], "package ID");
1059
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
+ }
1060
1074
  const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
1061
1075
  if (launchKindError) throw new Error(`Invalid manifest at ${path}: ${launchKindError}.`);
1062
1076
  const operationErrors = validateWopiOperationsSection(manifest.spec);
1063
1077
  if (operationErrors.length > 0) {
1064
1078
  throw new Error(`Invalid manifest at ${path}: ${operationErrors.join(" ")}`);
1065
1079
  }
1080
+ const dependencyErrors = validateDependencies(manifest.spec);
1081
+ if (dependencyErrors.length > 0) {
1082
+ throw new Error(`Invalid manifest at ${path}: ${dependencyErrors.join(" ")}`);
1083
+ }
1066
1084
  const splashErrors = validateApplicationSplashSection(kind, manifest.spec);
1067
1085
  if (splashErrors.length > 0) {
1068
1086
  throw new Error(`Invalid manifest at ${path}: ${splashErrors.join(" ")}`);
@@ -1111,6 +1129,16 @@ function validateApplicationSplashSection(kind, spec) {
1111
1129
  }
1112
1130
  return errors;
1113
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
+ }
1114
1142
  function validateWopiOperationsSection(spec) {
1115
1143
  if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1116
1144
  const wopi = spec.wopi;
@@ -1191,14 +1219,65 @@ async function findManifest(dir) {
1191
1219
  } catch {
1192
1220
  }
1193
1221
  const entries = await readdir(dir);
1194
- 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));
1195
1223
  if (candidates.length === 1) return join(dir, candidates[0]);
1196
1224
  if (candidates.length === 0) {
1197
- 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.`);
1198
1226
  }
1199
1227
  throw new Error(`Multiple manifests found in ${dir} (${candidates.join(", ")}). Pass --manifest to disambiguate.`);
1200
1228
  }
1201
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
+ }
1202
1281
  function validatePackageName(name, label) {
1203
1282
  if (!NAME_PATTERN.test(name)) {
1204
1283
  throw new Error(`Invalid ${label} '${name}' \u2014 use lowercase letters, digits and hyphens (no leading/trailing hyphen).`);
@@ -1222,28 +1301,42 @@ function validateManifest(manifest) {
1222
1301
  const error = (message) => issues.push({ level: "error", message });
1223
1302
  const warning = (message) => issues.push({ level: "warning", message });
1224
1303
  const kind = manifest.kind;
1304
+ const knownKinds = ["ExecutionEngine", "Application", "Agent", "Skill", "Tool", "Bundle", "Policy"];
1225
1305
  if (!kind) {
1226
- error("missing 'kind' (ExecutionEngine | Application | Bundle)");
1306
+ error("missing 'kind' (ExecutionEngine | Application | Agent | Skill | Tool | Bundle | Policy)");
1227
1307
  return issues;
1228
1308
  }
1229
- if (!["ExecutionEngine", "Application", "Bundle"].includes(kind)) {
1230
- 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'");
1231
1316
  }
1232
- if (!manifest["api-version"]) warning("missing 'api-version' (expected verentis.io/v1)");
1233
1317
  const meta = manifest.metadata ?? {};
1234
- for (const field of ["name", "display-name", "version"]) {
1235
- 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");
1236
1322
  }
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");
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
+ }
1241
1332
  }
1242
1333
  const spec = manifest.spec ?? {};
1243
1334
  validateManifestIcons(meta, spec, issues);
1244
1335
  const launchKindError = validateLaunchManifestKind(kind, spec);
1245
1336
  if (launchKindError) error(launchKindError);
1246
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);
1247
1340
  if (kind === "ExecutionEngine") {
1248
1341
  const runtimes = spec.runtimes ?? {};
1249
1342
  if (Object.keys(runtimes).length === 0) {
@@ -1275,13 +1368,117 @@ function validateManifest(manifest) {
1275
1368
  for (const message of validateApplicationSplashSection(kind, spec)) error(message);
1276
1369
  validateApplicationLaunch(spec, issues);
1277
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);
1278
1375
  validateInstallDirectives(spec.install, issues);
1279
1376
  validateSettingDeclarations(kind, spec, issues);
1280
1377
  for (const message of validateMarketplaceSection(manifest.marketplace)) error(message);
1281
1378
  const packaging = manifest.packaging ?? {};
1282
- 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");
1283
1380
  return issues;
1284
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
+ }
1285
1482
  function validateManifestIcons(metadata, spec, issues) {
1286
1483
  validateOptionalIcon(metadata.icon, "metadata.icon", issues);
1287
1484
  validateBindingIcons(spec["mime-types"], "spec.mime-types", issues);
@@ -1800,7 +1997,7 @@ async function followExecution(api, workspaceId, executionId, json) {
1800
1997
  if (exec.status !== "Completed") process.exitCode = 1;
1801
1998
  return;
1802
1999
  }
1803
- await new Promise((resolve12) => setTimeout(resolve12, 1e3));
2000
+ await new Promise((resolve13) => setTimeout(resolve13, 1e3));
1804
2001
  }
1805
2002
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
1806
2003
  process.exitCode = 1;
@@ -2911,6 +3108,10 @@ async function pack(options) {
2911
3108
  overrideApplied = true;
2912
3109
  }
2913
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(" ")}`);
2914
3115
  const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
2915
3116
  if (launchKindError) throw new Error(`Invalid manifest: ${launchKindError}.`);
2916
3117
  const marketplaceErrors = validateMarketplaceSection(manifest.marketplace);
@@ -3313,6 +3514,88 @@ function registerPackage(program2) {
3313
3514
  output(pageItems(page), { packageName: "Package", version: "Version", status: "Status", installPath: "Path", id: "Id" }, options, page);
3314
3515
  });
3315
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
+ }
3316
3599
  var MAX_LOGO_BYTES2 = 1024 * 1024;
3317
3600
  var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
3318
3601
  async function readPublisherLogo(path) {
@@ -3430,8 +3713,8 @@ function isNewerVersion(candidate, base) {
3430
3713
  return compareVersions(candidate, base) > 0;
3431
3714
  }
3432
3715
  function compareVersions(a, b) {
3433
- const pa = parse5(a);
3434
- const pb = parse5(b);
3716
+ const pa = parse6(a);
3717
+ const pb = parse6(b);
3435
3718
  for (let i = 0; i < 3; i++) {
3436
3719
  if (pa.main[i] !== pb.main[i]) return pa.main[i] < pb.main[i] ? -1 : 1;
3437
3720
  }
@@ -3458,7 +3741,7 @@ function compareVersions(a, b) {
3458
3741
  }
3459
3742
  return 0;
3460
3743
  }
3461
- function parse5(version) {
3744
+ function parse6(version) {
3462
3745
  const cleaned = version.trim().replace(/^v/i, "").split("+", 1)[0];
3463
3746
  const dash = cleaned.indexOf("-");
3464
3747
  const core = dash === -1 ? cleaned : cleaned.slice(0, dash);
@@ -3467,6 +3750,45 @@ function parse5(version) {
3467
3750
  return { main: [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0], pre: pre ? pre.split(".") : [] };
3468
3751
  }
3469
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
+
3470
3792
  // src/commands/registry.ts
3471
3793
  async function findLatestLocalVpkg(directory) {
3472
3794
  const entries = await readdir(directory, { withFileTypes: true });
@@ -3551,48 +3873,93 @@ function registerRegistry(program2) {
3551
3873
  console.log(`${pkg.publisherName}/${pkg.packageId}${version} \u2014 ${pkg.displayName} [${pkg.kind}, ${pkg.visibility.toLowerCase()}]`);
3552
3874
  }
3553
3875
  });
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) => {
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) => {
3555
3877
  const config = await loadConfig();
3556
3878
  const workspaceId = options.workspace ?? config.defaultWorkspaceId;
3557
3879
  if (!workspaceId) throw new Error("No workspace: pass --workspace <id> or set defaultWorkspaceId in ~/.verentis/config.json.");
3558
3880
  const api = await createApiClient();
3559
3881
  const { package: pkg } = await resolvePackageRef(api, ref);
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 }
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];
3560
3918
  const consentScopes = pkg.kind === "Application" ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
3561
- const existing = await findActiveInstallation(api, workspaceId, pkg.id, options.branch);
3562
3919
  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}'.`);
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.`);
3565
3922
  }
3566
- const result = await api.request("PUT", `/v1/installations/${existing.id}`, {
3567
- scopes: [MARKETPLACE.installUpdate, NODE.fileDelete, ...INSTALL_NODE_SCOPES, ...consentScopes],
3923
+ const result = await api.request("PUT", `/v1/installations/${encodeURIComponent(existing.id)}`, {
3924
+ scopes: [MARKETPLACE.installUpdate, NODE.fileDelete, ...nodeScopes, ...consentScopes],
3568
3925
  tokenWorkspaceId: workspaceId,
3569
3926
  body: {
3570
3927
  id: existing.id,
3571
3928
  workspaceId,
3572
- packageVersion: version ?? void 0,
3573
- installMode: options.sealed ? "Sealed" : existing.installMode ?? "Extracted"
3929
+ packageVersion: effectiveVersion,
3930
+ installMode: options.sealed ? "Sealed" : existing.installMode
3574
3931
  }
3575
3932
  });
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;
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}).`);
3582
3950
  }
3583
- const installationId = await api.request("POST", "/v1/installations", {
3584
- scopes: [SCOPES.installCreate, ...INSTALL_NODE_SCOPES, ...consentScopes],
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],
3585
3959
  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
- }
3960
+ query: { workspaceId }
3594
3961
  });
3595
- console.log(`Installation ${installationId} started for ${ref} in workspace ${workspaceId}.`);
3962
+ console.log(JSON.stringify(result, null, 2));
3596
3963
  });
3597
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) => {
3598
3965
  const api = await createApiClient();
@@ -3604,13 +3971,6 @@ function registerRegistry(program2) {
3604
3971
  console.log(`Uninstalled ${installationId}.`);
3605
3972
  });
3606
3973
  }
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
3974
 
3615
3975
  // src/commands/settings.ts
3616
3976
  async function settingScope(flags) {
@@ -3977,7 +4337,7 @@ function registerUser(program2) {
3977
4337
  });
3978
4338
  }
3979
4339
  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) => {
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) => {
3981
4341
  const target = resolve(pathOrDir ?? ".");
3982
4342
  const info = await stat(target).catch(() => null);
3983
4343
  const manifestPath = info?.isDirectory() ? await findManifest(target) : target;
@@ -4108,6 +4468,7 @@ registerApiKey(program);
4108
4468
  registerSettings(program);
4109
4469
  registerFiles(program);
4110
4470
  registerExec(program);
4471
+ registerPolicy(program);
4111
4472
  registerDev(program);
4112
4473
  registerValidate(program);
4113
4474
  registerCreate(program);