@verentis/cli 0.2.32 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import { mkdir, stat, readFile, writeFile, readdir, glob, realpath, mkdtemp, rm, access } from 'fs/promises';
3
+ import { mkdir, stat, readFile, writeFile, readdir, realpath, glob, mkdtemp, rm, access } from 'fs/promises';
4
4
  import { tmpdir, homedir } from 'os';
5
5
  import { resolve, basename, dirname, posix, join, isAbsolute, relative, sep, extname } from 'path';
6
6
  import { execFile, spawn, spawnSync } from 'child_process';
@@ -8,7 +8,7 @@ import { promisify, TextDecoder as TextDecoder$1 } from 'util';
8
8
  import * as tar from 'tar';
9
9
  import { extract } from 'tar';
10
10
  import { generateKeyPairSync, createHash, randomUUID, randomBytes, createCipheriv, createPublicKey, verify, diffieHellman, hkdfSync, sign, createPrivateKey } from 'crypto';
11
- import { parse, parseDocument, isScalar, stringify, Document, YAMLMap, Scalar } from 'yaml';
11
+ import { parse, parseDocument, isScalar, stringify, Document, YAMLMap, Scalar, parseAllDocuments } from 'yaml';
12
12
  import semver from 'semver';
13
13
  import { createWriteStream, readFileSync, createReadStream } from 'fs';
14
14
  import { Readable } from 'stream';
@@ -26,6 +26,22 @@ var configDir = () => process.env.VERENTIS_CONFIG_DIR ?? join(homedir(), ".veren
26
26
  var configPath = () => join(configDir(), "config.json");
27
27
  var keysDir = () => join(configDir(), "keys");
28
28
  var PRODUCTION_API_URL = "https://api.verentis.io";
29
+ function accountAppUrl(apiUrl) {
30
+ const override = process.env.VERENTIS_ACCOUNT_URL;
31
+ if (override) return override.replace(/\/+$/, "");
32
+ try {
33
+ const url = new URL(apiUrl);
34
+ if (url.hostname.startsWith("api.")) {
35
+ url.hostname = `account.${url.hostname.slice("api.".length)}`;
36
+ return url.origin;
37
+ }
38
+ } catch {
39
+ }
40
+ return "https://account.verentis.io";
41
+ }
42
+ function noPublisherMessage(apiUrl) {
43
+ return `No publisher yet \u2014 create one at ${accountAppUrl(apiUrl)}/marketplace/publisher, then run \`verentis login\` again.`;
44
+ }
29
45
  async function loadConfig() {
30
46
  try {
31
47
  return JSON.parse(await readFile(configPath(), "utf8"));
@@ -141,15 +157,105 @@ async function refreshIdentityToken(apiUrl, refreshToken, insecure) {
141
157
  `Session could not be renewed${payload?.error ? ` (${payload.error})` : ` (${res.status})`}. Run \`verentis login\` again.`
142
158
  );
143
159
  }
144
- var sleep = (ms) => new Promise((resolve16) => setTimeout(resolve16, ms));
160
+ var sleep = (ms) => new Promise((resolve18) => setTimeout(resolve18, ms));
161
+
162
+ // src/auth/registryAuth.ts
163
+ var REGISTRY_BASE = "/v1/registry";
164
+ var PUBLISHER_API_KEY_PREFIX = "pub_";
165
+ var PUBLISHER_KEY_HEADER = "X-Verentis-Publisher-Key";
166
+ var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
167
+ var jsonHeaders = { "Content-Type": "application/json", Accept: "application/json" };
168
+ async function readJson(res) {
169
+ try {
170
+ return await res.json();
171
+ } catch {
172
+ return void 0;
173
+ }
174
+ }
175
+ async function startRegistryDeviceAuthorization(apiUrl, insecure) {
176
+ const res = await fetch(`${apiUrl}${REGISTRY_BASE}/device/authorize`, {
177
+ method: "POST",
178
+ headers: jsonHeaders,
179
+ body: JSON.stringify({ client_id: CLI_CLIENT_ID }),
180
+ ...insecureFetchOptions(insecure)
181
+ });
182
+ if (!res.ok) {
183
+ const text = await res.text().catch(() => "");
184
+ throw new Error(`Could not start device sign-in (${res.status}).${text ? ` ${text.slice(0, 300)}` : ""}`);
185
+ }
186
+ return await res.json();
187
+ }
188
+ async function pollForRegistryTokens(apiUrl, authorization, insecure, onPoll) {
189
+ let intervalMs = Math.max(authorization.interval, 1) * 1e3;
190
+ const deadline = Date.now() + authorization.expires_in * 1e3;
191
+ while (Date.now() < deadline) {
192
+ await new Promise((resolve18) => setTimeout(resolve18, intervalMs));
193
+ onPoll?.();
194
+ const res = await fetch(`${apiUrl}${REGISTRY_BASE}/device/token`, {
195
+ method: "POST",
196
+ headers: jsonHeaders,
197
+ body: JSON.stringify({ grant_type: DEVICE_GRANT, device_code: authorization.device_code, client_id: CLI_CLIENT_ID }),
198
+ ...insecureFetchOptions(insecure)
199
+ });
200
+ const payload = await readJson(res);
201
+ if (res.ok && payload?.access_token) {
202
+ return { accessToken: payload.access_token, refreshToken: payload.refresh_token };
203
+ }
204
+ switch (payload?.error) {
205
+ case "authorization_pending":
206
+ continue;
207
+ case "slow_down":
208
+ intervalMs += 5e3;
209
+ continue;
210
+ case "access_denied":
211
+ throw new Error("Sign-in was denied in the browser.");
212
+ case "expired_token":
213
+ throw new Error("The device code expired before it was approved. Run `verentis login` again.");
214
+ default:
215
+ throw new Error(`Device sign-in failed (${res.status}).${payload?.error ? ` ${payload.error}` : ""}`);
216
+ }
217
+ }
218
+ throw new Error("The device code expired before it was approved. Run `verentis login` again.");
219
+ }
220
+ var RegistryRefreshError = class extends Error {
221
+ };
222
+ async function refreshRegistryTokens(apiUrl, refreshToken, insecure) {
223
+ const res = await fetch(`${apiUrl}${REGISTRY_BASE}/device/token`, {
224
+ method: "POST",
225
+ headers: jsonHeaders,
226
+ body: JSON.stringify({ grant_type: "refresh_token", refresh_token: refreshToken, client_id: CLI_CLIENT_ID }),
227
+ ...insecureFetchOptions(insecure)
228
+ });
229
+ const payload = await readJson(res);
230
+ if (res.ok && payload?.access_token) {
231
+ return { accessToken: payload.access_token, refreshToken: payload.refresh_token ?? refreshToken };
232
+ }
233
+ throw new RegistryRefreshError(
234
+ `Publish session could not be renewed${payload?.error ? ` (${payload.error})` : ` (${res.status})`}. Run \`verentis login\` again.`
235
+ );
236
+ }
237
+ async function exchangePublisherApiKey(apiUrl, apiKey, insecure) {
238
+ const res = await fetch(`${apiUrl}${REGISTRY_BASE}/token`, {
239
+ method: "POST",
240
+ headers: { Accept: "application/json", [PUBLISHER_KEY_HEADER]: apiKey },
241
+ ...insecureFetchOptions(insecure)
242
+ });
243
+ if (!res.ok) {
244
+ const error = (await readJson(res))?.error;
245
+ throw new Error(`Verentis rejected the publisher API key (${res.status}${error ? ` ${error}` : ""}).`);
246
+ }
247
+ const payload = await readJson(res);
248
+ if (!payload?.access_token) throw new Error("The registry token endpoint did not return an access token.");
249
+ return payload.access_token;
250
+ }
145
251
 
146
252
  // src/auth/githubActions.ts
147
253
  var JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
148
254
  var PUBLISHING_SCOPES = /* @__PURE__ */ new Set([
149
- "marketplace.publisher.read",
150
- "marketplace.package.read",
151
- "marketplace.package.create",
152
- "marketplace.package.publish"
255
+ "publisher.read",
256
+ "package.read",
257
+ "package.write",
258
+ "package.publish"
153
259
  ]);
154
260
  function assertPublisherScopes(scopes, options) {
155
261
  if (scopes.some((scope) => !PUBLISHING_SCOPES.has(scope)) || options.workspaceId || options.accountId || options.resourceId) {
@@ -166,7 +272,7 @@ async function exchangeGitHubPublisherToken(apiUrl, audience) {
166
272
  throw new Error("GitHub OIDC publishing requires an explicit HTTPS VERENTIS_API_URL.");
167
273
  }
168
274
  if (audience !== new URL(apiUrl).origin || apiUrl !== audience) {
169
- throw new Error("GitHub OIDC audience must equal the exact Sprint API URL origin.");
275
+ throw new Error("GitHub OIDC audience must equal the API URL origin (the registry host).");
170
276
  }
171
277
  const url = new URL(requestUrl);
172
278
  if (url.protocol !== "https:") {
@@ -183,14 +289,10 @@ async function exchangeGitHubPublisherToken(apiUrl, audience) {
183
289
  if (!assertion.value) {
184
290
  throw new Error("GitHub Actions did not provide an OIDC assertion.");
185
291
  }
186
- const exchangeResponse = await fetch(`${apiUrl}/connect/token`, {
292
+ const exchangeResponse = await fetch(`${apiUrl}${REGISTRY_BASE}/token`, {
187
293
  method: "POST",
188
- headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
189
- body: new URLSearchParams({
190
- grant_type: JWT_BEARER_GRANT_TYPE,
191
- assertion: assertion.value,
192
- scope: [...PUBLISHING_SCOPES].join(" ")
193
- })
294
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
295
+ body: JSON.stringify({ grant_type: JWT_BEARER_GRANT_TYPE, assertion: assertion.value })
194
296
  });
195
297
  if (!exchangeResponse.ok) {
196
298
  const error = await exchangeResponse.json().catch(() => ({}));
@@ -268,7 +370,71 @@ async function createApiClient(overrides) {
268
370
  }
269
371
  return refreshInflight;
270
372
  }
271
- async function credentialFor(scopes, workspaceId) {
373
+ const publisherApiKey = process.env.VERENTIS_PUBLISHER_API_KEY ?? config.publisherApiKey;
374
+ let currentPublish = config.publishAccessToken;
375
+ let currentPublishRefresh = config.publishRefreshToken;
376
+ let publishInflight;
377
+ async function githubRegistryToken() {
378
+ if (insecure) throw new Error("GitHub publisher federation does not permit insecure TLS.");
379
+ if (publisherToken && !isExpired(publisherToken, 90)) return publisherToken;
380
+ publisherExchange ??= exchangeGitHubPublisherToken(apiUrl, githubAudience).then((token) => {
381
+ publisherToken = token;
382
+ return token;
383
+ }).finally(() => {
384
+ publisherExchange = void 0;
385
+ });
386
+ return publisherExchange;
387
+ }
388
+ async function registryToken() {
389
+ if (githubAudience !== void 0) return githubRegistryToken();
390
+ if (publisherApiKey) {
391
+ if (publisherToken && !isExpired(publisherToken, 90)) return publisherToken;
392
+ publishInflight ??= exchangePublisherApiKey(apiUrl, publisherApiKey, insecure).then((token) => {
393
+ publisherToken = token;
394
+ return token;
395
+ }).finally(() => {
396
+ publishInflight = void 0;
397
+ });
398
+ return publishInflight;
399
+ }
400
+ if (!currentPublish) {
401
+ throw new ApiError(401, "Not logged in for publishing. Run `verentis login` (or set VERENTIS_PUBLISHER_API_KEY).");
402
+ }
403
+ if (!isExpired(currentPublish, 120)) return currentPublish;
404
+ if (!currentPublishRefresh) {
405
+ throw new ApiError(401, "Your publish session has expired \u2014 run `verentis login` again.");
406
+ }
407
+ publishInflight ??= (async () => {
408
+ try {
409
+ const refreshed = await refreshRegistryTokens(apiUrl, currentPublishRefresh, insecure);
410
+ currentPublish = refreshed.accessToken;
411
+ currentPublishRefresh = refreshed.refreshToken ?? currentPublishRefresh;
412
+ const disk = await loadConfig();
413
+ disk.publishAccessToken = refreshed.accessToken;
414
+ if (refreshed.refreshToken) disk.publishRefreshToken = refreshed.refreshToken;
415
+ await saveConfig(disk);
416
+ return refreshed.accessToken;
417
+ } catch (err) {
418
+ if (err instanceof RegistryRefreshError) {
419
+ const disk = await loadConfig();
420
+ delete disk.publishAccessToken;
421
+ delete disk.publishRefreshToken;
422
+ await saveConfig(disk).catch(() => {
423
+ });
424
+ throw new ApiError(401, err.message);
425
+ }
426
+ throw err;
427
+ } finally {
428
+ publishInflight = void 0;
429
+ }
430
+ })();
431
+ return publishInflight;
432
+ }
433
+ async function credentialFor(requested, workspaceId) {
434
+ const scopes = [...new Set(requested)];
435
+ if (githubAudience !== void 0) {
436
+ throw new Error("GitHub publisher federation only permits publisher and package publishing operations.");
437
+ }
272
438
  const cacheKey = `${workspaceId ?? ""}:${[...scopes].sort().join(" ")}`;
273
439
  const cached2 = tokenCache.get(cacheKey);
274
440
  if (cached2 && !isExpired(cached2)) return cached2;
@@ -279,17 +445,7 @@ async function createApiClient(overrides) {
279
445
  async function mintAccessToken(options) {
280
446
  if (githubAudience !== void 0) {
281
447
  assertPublisherScopes(options.scopes, options);
282
- if (insecure) {
283
- throw new Error("GitHub publisher federation does not permit insecure TLS.");
284
- }
285
- if (publisherToken && !isExpired(publisherToken, 90)) return publisherToken;
286
- publisherExchange ??= exchangeGitHubPublisherToken(apiUrl, githubAudience).then((token) => {
287
- publisherToken = token;
288
- return token;
289
- }).finally(() => {
290
- publisherExchange = void 0;
291
- });
292
- return publisherExchange;
448
+ return githubRegistryToken();
293
449
  }
294
450
  const apiKey = process.env.VERENTIS_API_KEY ?? config.apiKey;
295
451
  if (!apiKey && !currentIdentity) {
@@ -304,7 +460,7 @@ async function createApiClient(overrides) {
304
460
  },
305
461
  body: JSON.stringify({
306
462
  audience: AUDIENCE,
307
- scopes: options.scopes,
463
+ scopes: [...new Set(options.scopes)],
308
464
  ...options.resourceId ?? options.workspaceId ?? options.accountId ? { resourceId: options.resourceId ?? options.workspaceId ?? options.accountId } : {},
309
465
  ...options.resourceId && (options.resourceKind ?? "Node") === "Node" ? { resourceType: "Node", ...options.workspaceId ? { parentResourceId: options.workspaceId } : {} } : {}
310
466
  }),
@@ -320,7 +476,7 @@ ${truncate(text)}` : ""}`);
320
476
  return data.access_token;
321
477
  }
322
478
  async function requestRaw(method, path, options = {}) {
323
- const token = await credentialFor(options.scopes ?? [], options.tokenWorkspaceId);
479
+ const token = options.plane === "registry" ? await registryToken() : await credentialFor(options.scopes ?? [], options.tokenWorkspaceId);
324
480
  const url = new URL(`${apiUrl}${path}`);
325
481
  for (const [key, value] of Object.entries(options.query ?? {})) {
326
482
  if (value !== void 0) url.searchParams.set(key, String(value));
@@ -339,7 +495,7 @@ ${truncate(text)}` : ""}`);
339
495
  const res = await fetch(url, { method, headers, body, ...insecureFetchOptions(insecure), ...options.rawBody !== void 0 && !isFormData ? { duplex: "half" } : {} });
340
496
  if (!res.ok) {
341
497
  const text = await res.text().catch(() => "");
342
- throw new ApiError(res.status, `${method} ${path} failed (${res.status}). ${hintFor(res.status)}${formatErrorBody(text)}`);
498
+ throw new ApiError(res.status, `${method} ${path} failed (${res.status}). ${hintFor(res.status)}${formatErrorBody(text)}`, parseErrorBody(text));
343
499
  }
344
500
  return res;
345
501
  }
@@ -354,7 +510,7 @@ ${truncate(text)}` : ""}`);
354
510
  return text;
355
511
  }
356
512
  }
357
- return { apiUrl, request, requestRaw, mintAccessToken };
513
+ return { apiUrl, request, requestRaw, mintAccessToken, registryToken };
358
514
  }
359
515
  function hintFor(status) {
360
516
  switch (status) {
@@ -371,6 +527,20 @@ function hintFor(status) {
371
527
  function truncate(text, max = 400) {
372
528
  return text.length > max ? `${text.slice(0, max)}\u2026` : text;
373
529
  }
530
+ function parseErrorBody(text) {
531
+ if (!text) return void 0;
532
+ try {
533
+ return JSON.parse(text);
534
+ } catch {
535
+ return text;
536
+ }
537
+ }
538
+ function problemDetail(error) {
539
+ if (!(error instanceof ApiError) || !error.body || typeof error.body !== "object") return void 0;
540
+ const problem = error.body;
541
+ if (typeof problem.detail === "string" && problem.detail) return problem.detail;
542
+ return typeof problem.title === "string" && problem.title ? problem.title : void 0;
543
+ }
374
544
  function formatErrorBody(text) {
375
545
  if (!text) return "";
376
546
  try {
@@ -389,92 +559,74 @@ ${truncate(lines.join("\n"), 800)}`;
389
559
  ${truncate(text)}`;
390
560
  }
391
561
  var SCOPES = {
392
- publisherRead: "marketplace.publisher.read",
393
- publisherUpdate: "marketplace.publisher.update",
394
- packageRead: "marketplace.package.read",
395
- packageReadAll: "marketplace.package.read-all",
396
- packageCreate: "marketplace.package.create",
397
- packagePublish: "marketplace.package.publish",
398
- installCreate: "marketplace.install.create",
399
- resourceReadAll: "resources.resource.read-all",
400
- resourceUpdate: "resources.resource.update"
562
+ publisherRead: "publisher.read",
563
+ packageRead: "package.read",
564
+ packageList: "package.read",
565
+ installCreate: "installation.write",
566
+ installRead: "installation.read",
567
+ resourceReadAll: "app.read",
568
+ installationRead: "installation.read",
569
+ resourceUpdate: "installation.write"
401
570
  };
402
571
 
403
572
  // src/api/scopes.ts
404
573
  var SECURITY = {
405
- apiKeyCreate: "security.api-key.create",
406
- apiKeyRead: "security.api-key.read",
407
- apiKeyReadAll: "security.api-key.read-all",
408
- apiKeyUpdate: "security.api-key.update",
409
- grantsCreate: "security.grants.create",
410
- userRead: "security.user.read",
411
- userReadAll: "security.user.read-all",
412
- userUpdate: "security.user.update"};
574
+ apiKeyCreate: "api-key.write",
575
+ apiKeyRead: "api-key.read",
576
+ apiKeyReadAll: "api-key.read",
577
+ apiKeyUpdate: "api-key.write",
578
+ grantsCreate: "grant.write",
579
+ userRead: "user.read",
580
+ userReadAll: "user.read",
581
+ userUpdate: "user.write"};
413
582
  var ACCOUNT = {
414
- invitationAccept: "account.invitation.accept",
415
- invitationCreate: "account.invitation.create",
416
- invitationDelete: "account.invitation.delete",
417
- invitationRead: "account.invitation.read",
418
- invitationUpdate: "account.invitation.update"
583
+ invitationAccept: "invitation.accept",
584
+ invitationCreate: "invitation.write",
585
+ invitationDelete: "invitation.write",
586
+ invitationRead: "invitation.read",
587
+ invitationUpdate: "invitation.write"
419
588
  };
420
589
  var WORKSPACE = {
421
- create: "account.workspace.create",
422
- read: "account.workspace.read",
423
- readAll: "account.workspace.read-all",
424
- update: "account.workspace.update",
425
- urlsCreate: "account.workspace.urls.create",
426
- urlsDelete: "account.workspace.urls.delete",
427
- urlsRead: "account.workspace.urls.read",
428
- invitationAccept: "account.workspace.invitation.accept",
429
- invitationCreate: "account.workspace.invitation.create",
430
- invitationDelete: "account.workspace.invitation.delete",
431
- invitationRead: "account.workspace.invitation.read",
432
- invitationUpdate: "account.workspace.invitation.update"
590
+ create: "workspace.write",
591
+ read: "workspace.read",
592
+ readAll: "workspace.read",
593
+ update: "workspace.write",
594
+ urlsCreate: "workspace.write",
595
+ urlsDelete: "workspace.write",
596
+ urlsRead: "workspace.read",
597
+ invitationAccept: "invitation.accept",
598
+ invitationCreate: "invitation.write",
599
+ invitationDelete: "invitation.write",
600
+ invitationRead: "invitation.read",
601
+ invitationUpdate: "invitation.write"
433
602
  };
434
603
  var SETTINGS = {
435
- delete: "fabric.setting.delete",
436
- read: "fabric.setting.read",
437
- readAll: "fabric.setting.read-all",
438
- update: "fabric.setting.update"
604
+ delete: "setting.delete",
605
+ read: "setting.read",
606
+ readAll: "setting.read",
607
+ update: "setting.write"
439
608
  };
440
609
  var NODE = {
441
- branchRead: "node.branch.read",
442
- branchUpdate: "node.branch.update",
443
- contentCreate: "node.content.create",
444
- contentRead: "node.content.read",
445
- contentUpdate: "node.content.update",
446
- fileDelete: "node.file.delete",
447
- fileRead: "node.file.read",
448
- journalCreate: "node.journal.create",
449
- journalUpdate: "node.journal.update",
450
- nodeCreate: "node.node.create",
451
- nodeUpdate: "node.node.update"
610
+ fileDelete: "file.delete",
611
+ fileRead: "file.read",
612
+ nodeCreate: "file.write",
613
+ nodeUpdate: "file.write"
452
614
  };
453
615
  var EXECUTION = {
454
- run: "execution.execution.run"
616
+ run: "execution.run",
617
+ cancel: "execution.run"
455
618
  };
456
619
  var MARKETPLACE = {
457
- installDelete: "marketplace.install.delete",
458
- installRead: "marketplace.install.read",
459
- installUpdate: "marketplace.install.update",
460
- packageDelete: "marketplace.package.delete",
461
- packageRead: "marketplace.package.read",
462
- packageUpdate: "marketplace.package.update",
463
- packageVisibilityManage: "marketplace.package.visibility.manage",
464
- publisherCreate: "marketplace.publisher.create",
465
- publisherUpdate: "marketplace.publisher.update",
466
- statsRead: "marketplace.stats.read"};
620
+ installDelete: "installation.delete",
621
+ installList: "installation.read",
622
+ installRead: "installation.read",
623
+ installUpdate: "installation.write",
624
+ packageRead: "package.read",
625
+ publisherUpdate: "publisher.write",
626
+ statsRead: "stats.read"};
467
627
  var ENGINE_DEFAULT_PERMISSIONS = [
468
628
  NODE.fileRead,
469
- NODE.contentRead,
470
- NODE.branchRead,
471
629
  NODE.nodeCreate,
472
- NODE.nodeUpdate,
473
- NODE.contentCreate,
474
- NODE.contentUpdate,
475
- NODE.journalCreate,
476
- NODE.journalUpdate,
477
- NODE.branchUpdate,
478
630
  NODE.fileDelete,
479
631
  EXECUTION.run
480
632
  ];
@@ -498,8 +650,8 @@ var security = {
498
650
  addApiKeyGrant: e({ method: "POST", path: "/v1/api-keys/{apiKeyId}/grants", scopes: [SECURITY.apiKeyUpdate] }),
499
651
  removeApiKeyGrant: e({ method: "DELETE", path: "/v1/api-keys/{apiKeyId}/grants/{permissionKey}", scopes: [SECURITY.apiKeyUpdate] })};
500
652
  var account = {
501
- get: e({ method: "GET", path: "/v1/accounts/{accountId}", scopes: ["account.account.read"] }),
502
- update: e({ method: "PUT", path: "/v1/accounts/{accountId}", scopes: ["account.account.update"] }),
653
+ get: e({ method: "GET", path: "/v1/accounts/{accountId}", scopes: ["account.read"] }),
654
+ update: e({ method: "PUT", path: "/v1/accounts/{accountId}", scopes: ["account.write"] }),
503
655
  listInvitations: e({ method: "GET", path: "/v1/accounts/{accountId}/invitations", scopes: [ACCOUNT.invitationRead], paged: true }),
504
656
  createInvitation: e({ method: "POST", path: "/v1/accounts/{accountId}/invitations", scopes: [ACCOUNT.invitationCreate] }),
505
657
  resendInvitation: e({ method: "POST", path: "/v1/accounts/{accountId}/invitations/{invitationId}/resend", scopes: [ACCOUNT.invitationUpdate] }),
@@ -532,10 +684,10 @@ var files = {
532
684
  upload: e({
533
685
  method: "POST",
534
686
  path: "/v1/files/{path}",
535
- scopes: [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate],
687
+ scopes: [NODE.nodeCreate, NODE.fileRead],
536
688
  workspaceBound: true
537
689
  }),
538
- update: e({ method: "PUT", path: "/v1/files/{path}", scopes: [NODE.nodeUpdate, NODE.fileRead, NODE.journalCreate], workspaceBound: true }),
690
+ update: e({ method: "PUT", path: "/v1/files/{path}", scopes: [NODE.nodeUpdate, NODE.fileRead], workspaceBound: true }),
539
691
  delete: e({ method: "DELETE", path: "/v1/files/{path}", scopes: [NODE.fileDelete], workspaceBound: true }),
540
692
  /** Status of a background archive import started by an archive upload (202 + Location). */
541
693
  archiveImportStatus: e({ method: "GET", path: "/v1/archive-imports/{id}", scopes: [NODE.fileRead], workspaceBound: true })
@@ -544,7 +696,7 @@ var execution = {
544
696
  request: e({ method: "POST", path: "/v1/executions", scopes: [EXECUTION.run, ...ENGINE_DEFAULT_PERMISSIONS], workspaceBound: true }),
545
697
  list: e({ method: "GET", path: "/v1/executions", scopes: [EXECUTION.run], workspaceBound: true, paged: true }),
546
698
  get: e({ method: "GET", path: "/v1/executions/{id}", scopes: [EXECUTION.run], workspaceBound: true }),
547
- cancel: e({ method: "POST", path: "/v1/executions/{id}/cancel", scopes: [EXECUTION.run], workspaceBound: true }),
699
+ cancel: e({ method: "POST", path: "/v1/executions/{id}/cancel", scopes: [EXECUTION.cancel], workspaceBound: true }),
548
700
  logs: e({ method: "GET", path: "/v1/executions/{id}/logs", scopes: [EXECUTION.run], workspaceBound: true }),
549
701
  logsStream: e({ method: "GET", path: "/v1/executions/{id}/logs/stream", scopes: [EXECUTION.run], workspaceBound: true }),
550
702
  listEngines: e({ method: "GET", path: "/v1/engines", scopes: [EXECUTION.run], paged: true }),
@@ -553,24 +705,12 @@ var execution = {
553
705
  syncEngines: e({ method: "POST", path: "/v1/engines/sync", scopes: [EXECUTION.run], workspaceBound: true })
554
706
  };
555
707
  var marketplace = {
556
- createPublisher: e({ method: "POST", path: "/v1/publishers", scopes: [MARKETPLACE.publisherCreate] }),
557
- updatePublisher: e({ method: "PUT", path: "/v1/publishers/{id}", scopes: [MARKETPLACE.publisherUpdate] }),
558
- setPublisherLogo: e({ method: "PUT", path: "/v1/publishers/{id}/logo", scopes: [MARKETPLACE.publisherUpdate] }),
559
- removePublisherLogo: e({ method: "DELETE", path: "/v1/publishers/{id}/logo", scopes: [MARKETPLACE.publisherUpdate] }),
560
- getPackage: e({ method: "GET", path: "/v1/packages/{id}", scopes: [MARKETPLACE.packageRead] }),
561
- updatePackage: e({ method: "PUT", path: "/v1/packages/{id}", scopes: [MARKETPLACE.packageUpdate] }),
562
- archivePackage: e({ method: "DELETE", path: "/v1/packages/{id}", scopes: [MARKETPLACE.packageDelete] }),
563
- deprecatePackage: e({ method: "POST", path: "/v1/packages/{id}/deprecate", scopes: [MARKETPLACE.packageUpdate] }),
564
- undeprecatePackage: e({ method: "DELETE", path: "/v1/packages/{id}/deprecate", scopes: [MARKETPLACE.packageUpdate] }),
565
- setPackageVisibility: e({ method: "PUT", path: "/v1/packages/{id}/visibility", scopes: [MARKETPLACE.packageVisibilityManage] }),
566
- listPublisherPackages: e({ method: "GET", path: "/v1/publishers/{publisherId}/packages", scopes: [MARKETPLACE.packageRead], paged: true }),
567
- listVersions: e({ method: "GET", path: "/v1/packages/{packageId}/versions", scopes: [MARKETPLACE.packageRead], paged: true }),
568
- listVisibilityGrants: e({ method: "GET", path: "/v1/packages/{packageId}/visibility-grants", scopes: [MARKETPLACE.packageVisibilityManage] }),
569
- grantVisibility: e({ method: "POST", path: "/v1/packages/{packageId}/visibility-grants", scopes: [MARKETPLACE.packageVisibilityManage] }),
570
- revokeVisibility: e({ method: "DELETE", path: "/v1/packages/{packageId}/visibility-grants/{grantId}", scopes: [MARKETPLACE.packageVisibilityManage] }),
708
+ updatePublisher: e({ method: "PUT", path: `${REGISTRY_BASE}/publishers/{id}`, scopes: [MARKETPLACE.publisherUpdate] }),
709
+ setPublisherLogo: e({ method: "PUT", path: `${REGISTRY_BASE}/publishers/{id}/logo`, scopes: [MARKETPLACE.publisherUpdate] }),
710
+ removePublisherLogo: e({ method: "DELETE", path: `${REGISTRY_BASE}/publishers/{id}/logo`, scopes: [MARKETPLACE.publisherUpdate] }),
571
711
  getPackageStats: e({ method: "GET", path: "/v1/packages/{packageId}/stats", scopes: [MARKETPLACE.statsRead] }),
572
- listInstallations: e({ method: "GET", path: "/v1/installations", scopes: [MARKETPLACE.installRead], paged: true }),
573
- uninstall: e({ method: "DELETE", path: "/v1/installations/{id}", scopes: [MARKETPLACE.installDelete, NODE.fileDelete, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate], workspaceBound: true })
712
+ listInstallations: e({ method: "GET", path: "/v1/installations", scopes: [MARKETPLACE.installList], paged: true }),
713
+ uninstall: e({ method: "DELETE", path: "/v1/installations/{id}", scopes: [MARKETPLACE.installDelete, NODE.fileDelete, NODE.fileRead, NODE.nodeUpdate], workspaceBound: true })
574
714
  };
575
715
 
576
716
  // src/api/client.ts
@@ -883,7 +1023,7 @@ function registerApiKey(program2) {
883
1023
  console.log("This value is shown ONCE. The previous secret no longer works.");
884
1024
  });
885
1025
  const grantCmd = keyCmd.command("grant").description("Manage permission grants on an API key");
886
- grantCmd.command("add <apiKeyId> <scope>").description("Grant a permission scope to an API key (e.g. node.file.read)").option("--deny", "add as a Deny grant instead of Allow").option("--account <accountId>").option("--workspace <workspaceId>").action(async (apiKeyId, scopeName, options) => {
1026
+ grantCmd.command("add <apiKeyId> <scope>").description("Grant a permission scope to an API key (e.g. file.read)").option("--deny", "add as a Deny grant instead of Allow").option("--account <accountId>").option("--workspace <workspaceId>").action(async (apiKeyId, scopeName, options) => {
887
1027
  const api = await createApiClient();
888
1028
  const scope = await managementScope(options);
889
1029
  await call(api, security.addApiKeyGrant, {
@@ -1501,9 +1641,9 @@ var THEME_ASSET_NAMES = [
1501
1641
  "theme.css",
1502
1642
  "background",
1503
1643
  "background.dark",
1504
- "logo.light",
1644
+ "logo",
1505
1645
  "logo.dark",
1506
- "mark.light",
1646
+ "mark",
1507
1647
  "mark.dark",
1508
1648
  "favicon",
1509
1649
  "apple-touch-icon"
@@ -1701,8 +1841,136 @@ function validatorForKind(kind) {
1701
1841
  const name = findPackageType(kind)?.validator;
1702
1842
  return name ? PACKAGE_TYPE_VALIDATORS[name] : void 0;
1703
1843
  }
1844
+ var DOTLOTTIE_V2_FORMAT = "dotlottie/v2";
1845
+ var DOTLOTTIE_MAX_BYTES = 4 * 1024 * 1024;
1846
+ var AVATAR_FALLBACK_MAX_BYTES = 1024 * 1024;
1847
+ var isRecord3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1848
+ function normalizeAvatarAssetPath(value) {
1849
+ if (typeof value !== "string" || value.length > 512 || !value.startsWith("./") || /[\\%?#:\p{Cc}]/u.test(value) || /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value) || value.normalize("NFC") !== value) return void 0;
1850
+ const segments = value.slice(2).split("/");
1851
+ if (segments.length === 0 || segments.some((segment) => segment.length === 0 || segment === "." || segment === ".." || /\s/u.test(segment))) return void 0;
1852
+ return segments.join("/");
1853
+ }
1854
+ function isStaticImagePath(path) {
1855
+ return /\.(svg|png|jpe?g|webp)$/.test(path);
1856
+ }
1857
+ function validateAgentAvatarManifest(kind, spec) {
1858
+ if (kind !== "Agent" || !isRecord3(spec) || spec.avatar === void 0) return [];
1859
+ const errors = [];
1860
+ const avatar = spec.avatar;
1861
+ if (!isRecord3(avatar)) return ["spec.avatar must be an object."];
1862
+ for (const key of Object.keys(avatar)) {
1863
+ if (!["format", "definition", "fallback"].includes(key)) {
1864
+ errors.push(`spec.avatar.${key} is not supported.`);
1865
+ }
1866
+ }
1867
+ if (avatar.format !== DOTLOTTIE_V2_FORMAT) {
1868
+ errors.push(`spec.avatar.format must be '${DOTLOTTIE_V2_FORMAT}'.`);
1869
+ }
1870
+ const definition = normalizeAvatarAssetPath(avatar.definition);
1871
+ if (!definition || !definition.endsWith(".lottie")) {
1872
+ errors.push("spec.avatar.definition must be a safe relative .lottie package path (no absolute paths, traversal, URLs or encoded separators).");
1873
+ }
1874
+ if (avatar.fallback !== void 0) {
1875
+ const fallback = normalizeAvatarAssetPath(avatar.fallback);
1876
+ if (!fallback || !isStaticImagePath(fallback)) {
1877
+ errors.push("spec.avatar.fallback must be a safe relative .svg, .png, .jpg, .jpeg or .webp package path.");
1878
+ }
1879
+ }
1880
+ return errors;
1881
+ }
1882
+ function agentAvatarPayloadPaths(manifest) {
1883
+ if (manifest.kind !== "Agent" || !isRecord3(manifest.spec) || !isRecord3(manifest.spec.avatar)) return [];
1884
+ const avatar = manifest.spec.avatar;
1885
+ return [avatar.definition, avatar.fallback].map(normalizeAvatarAssetPath).filter((path) => path !== void 0);
1886
+ }
1887
+ function validateAgentAvatarPayloadFiles(manifest, payloadFiles) {
1888
+ const included = new Set(payloadFiles.map((path) => path.replaceAll("\\", "/").replace(/^\.\//, "")));
1889
+ return agentAvatarPayloadPaths(manifest).filter((path) => !included.has(path)).map((path) => `Avatar asset '${path}' is not included in the package payload; add it to packaging.files.`);
1890
+ }
1891
+ async function validateAgentAvatarPayload(projectDir, manifest) {
1892
+ if (manifest.kind !== "Agent" || !isRecord3(manifest.spec) || !isRecord3(manifest.spec.avatar)) return [];
1893
+ const avatar = manifest.spec.avatar;
1894
+ const errors = [];
1895
+ const root = await realpath(projectDir).catch(() => resolve(projectDir));
1896
+ const assets = [
1897
+ { path: avatar.definition, kind: "definition" },
1898
+ ...avatar.fallback === void 0 ? [] : [{ path: avatar.fallback, kind: "fallback" }]
1899
+ ];
1900
+ for (const asset of assets) {
1901
+ const path = normalizeAvatarAssetPath(asset.path);
1902
+ if (!path) continue;
1903
+ const at = `spec.avatar.${asset.kind} (${path})`;
1904
+ try {
1905
+ const absolute = await realpath(resolve(root, path));
1906
+ const fromRoot = relative(root, absolute);
1907
+ if (fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
1908
+ errors.push(`${at} resolves outside the package directory.`);
1909
+ continue;
1910
+ }
1911
+ if (!(await stat(absolute)).isFile()) {
1912
+ errors.push(`${at} must be a file.`);
1913
+ continue;
1914
+ }
1915
+ const bytes = await readFile(absolute);
1916
+ if (asset.kind === "definition") {
1917
+ if (bytes.length > DOTLOTTIE_MAX_BYTES) {
1918
+ errors.push(`${at} exceeds ${DOTLOTTIE_MAX_BYTES / (1024 * 1024)} MiB.`);
1919
+ } else if (bytes.length < 22 || bytes[0] !== 80 || bytes[1] !== 75) {
1920
+ errors.push(`${at} is not a dotLottie ZIP bundle.`);
1921
+ }
1922
+ } else {
1923
+ if (bytes.length === 0 || bytes.length > AVATAR_FALLBACK_MAX_BYTES) {
1924
+ errors.push(`${at} must be non-empty and no larger than ${AVATAR_FALLBACK_MAX_BYTES / (1024 * 1024)} MiB.`);
1925
+ } else if (path.endsWith(".svg")) {
1926
+ const text = decodeUtf8(bytes);
1927
+ const reason = text === null ? "SVG must be UTF-8 text" : validateThemeSvg(text);
1928
+ if (reason) errors.push(`${at}: ${reason}.`);
1929
+ } else if (!hasRasterSignature(path, bytes)) {
1930
+ errors.push(`${at} does not match its declared image format.`);
1931
+ }
1932
+ }
1933
+ } catch {
1934
+ errors.push(`${at} does not exist inside the package directory.`);
1935
+ }
1936
+ }
1937
+ return errors;
1938
+ }
1939
+ function hasRasterSignature(path, bytes) {
1940
+ if (path.endsWith(".png")) return bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
1941
+ if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
1942
+ if (path.endsWith(".webp")) return bytes.length >= 12 && bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP";
1943
+ return false;
1944
+ }
1704
1945
 
1705
1946
  // src/vpkg/manifest.ts
1947
+ var METADATA_ID_REQUIRED_MESSAGE = "metadata.id is required";
1948
+ var LEGACY_PACKAGE_ID_MESSAGE = "metadata.package-id is no longer supported; use metadata.id";
1949
+ var LEGACY_DISPLAY_NAME_MESSAGE = "metadata.display-name is no longer supported; use metadata.name";
1950
+ function validateDocumentMetadata(metadata) {
1951
+ const meta = metadata && typeof metadata === "object" && !Array.isArray(metadata) ? metadata : {};
1952
+ const has = (key) => Object.prototype.hasOwnProperty.call(meta, key);
1953
+ const errors = [];
1954
+ if (has("package-id")) errors.push(LEGACY_PACKAGE_ID_MESSAGE);
1955
+ if (has("display-name")) errors.push(LEGACY_DISPLAY_NAME_MESSAGE);
1956
+ if (typeof meta.id !== "string" || !meta.id.trim()) errors.push(METADATA_ID_REQUIRED_MESSAGE);
1957
+ if (has("name") && (typeof meta.name !== "string" || !meta.name.trim())) errors.push("metadata.name must be a non-empty string");
1958
+ return errors;
1959
+ }
1960
+ function isVerentisDocument(value) {
1961
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1962
+ const record = value;
1963
+ return typeof record["api-version"] === "string" && /(^|\.)verentis\.io\/v1$/.test(record["api-version"]) && typeof record.kind === "string";
1964
+ }
1965
+ function payloadDocumentMetadataErrors(text) {
1966
+ let documents;
1967
+ try {
1968
+ documents = parseAllDocuments(text).map((document) => document.toJS());
1969
+ } catch {
1970
+ return [];
1971
+ }
1972
+ return documents.filter(isVerentisDocument).flatMap((document) => validateDocumentMetadata(document.metadata).map((message) => `${document.kind}: ${message}`));
1973
+ }
1706
1974
  function normalizeKind(kind) {
1707
1975
  const canonical = canonicalPackageType(kind);
1708
1976
  if (!canonical) throw new Error(unknownPackageTypeMessage(kind));
@@ -1748,7 +2016,8 @@ function validatePackageManifestRules(kind, manifest) {
1748
2016
  ...validateApplicationSplashSection(kind, manifest.spec),
1749
2017
  ...validateMetadataTags(manifest.metadata?.tags),
1750
2018
  ...validateTypeSpecFields(kind, manifest.spec),
1751
- ...validateTypeManifest(kind, manifest)
2019
+ ...validateTypeManifest(kind, manifest),
2020
+ ...validateAgentAvatarManifest(kind, manifest.spec)
1752
2021
  ];
1753
2022
  }
1754
2023
  function validateLaunchManifestKind(kind, spec) {
@@ -1761,10 +2030,10 @@ async function loadManifest(path) {
1761
2030
  const manifest = parse(text);
1762
2031
  if (!manifest || typeof manifest !== "object") throw new Error(`Failed to parse manifest at ${path}.`);
1763
2032
  if (!manifest.kind) throw new Error(`Manifest at ${path} is missing 'kind'.`);
1764
- if (!manifest.metadata?.name) throw new Error(`Manifest at ${path} is missing 'metadata.name'.`);
1765
- if (!manifest.metadata?.["package-id"]) throw new Error(`Manifest at ${path} is missing 'metadata.package-id'.`);
2033
+ const metadataErrors = validateDocumentMetadata(manifest.metadata);
2034
+ if (metadataErrors.length > 0) throw new Error(`Invalid manifest at ${path}: ${metadataErrors.join("; ")}.`);
1766
2035
  if (!manifest.metadata?.version) throw new Error(`Manifest at ${path} is missing 'metadata.version'.`);
1767
- validatePackageName(manifest.metadata["package-id"], "package ID");
2036
+ validatePackageName(manifest.metadata.id, "package ID");
1768
2037
  const kind = normalizeKind(manifest.kind);
1769
2038
  const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
1770
2039
  if (hostedBackendErrors.length > 0) {
@@ -2231,21 +2500,13 @@ function validateManifest(manifest) {
2231
2500
  error("api-version must be 'verentis.io/v1'");
2232
2501
  }
2233
2502
  const meta = manifest.metadata ?? {};
2234
- if (!meta.name) {
2235
- error("metadata.name is required");
2236
- } else if (!NAME_PATTERN.test(meta.name)) {
2237
- error("metadata.name must use lowercase letters, digits and internal hyphens");
2503
+ for (const message of validateDocumentMetadata(meta)) error(message);
2504
+ if (typeof meta.id === "string" && meta.id.trim() && !NAME_PATTERN.test(meta.id)) {
2505
+ error("metadata.id must use lowercase letters, digits and internal hyphens");
2238
2506
  }
2239
2507
  if (!isPolicy) {
2240
2508
  for (const message of validateMetadataTags(meta.tags)) error(message);
2241
- for (const field of ["display-name", "version"]) {
2242
- if (!meta[field]) error(`metadata.${field} is required`);
2243
- }
2244
- if (!meta["package-id"]) {
2245
- error("metadata.package-id is required");
2246
- } else if (!NAME_PATTERN.test(meta["package-id"])) {
2247
- error("metadata.package-id must use lowercase letters, digits and internal hyphens");
2248
- }
2509
+ if (!meta.version) error("metadata.version is required");
2249
2510
  }
2250
2511
  const spec = manifest.spec ?? {};
2251
2512
  validateManifestIcons(meta, spec, issues);
@@ -2294,6 +2555,7 @@ function validateManifest(manifest) {
2294
2555
  if (descriptor?.resourceKind === "Skill") validateSkillManifest(spec, issues);
2295
2556
  if (descriptor?.resourceKind === "Tool") validateToolManifest(spec, issues);
2296
2557
  if (isPolicy) validatePolicyManifest(spec, issues);
2558
+ for (const message of validateAgentAvatarManifest(kind, spec)) error(message);
2297
2559
  validateInstallDirectives(spec.install, issues);
2298
2560
  validateSettingDeclarations(descriptor?.profile === "engine", spec, issues);
2299
2561
  for (const message of validateMarketplaceSection(manifest.marketplace)) error(message);
@@ -2523,7 +2785,7 @@ function validateSettingDeclarations(isEngine, spec, issues) {
2523
2785
  return;
2524
2786
  }
2525
2787
  if (!declaration.key || typeof declaration.key !== "string") {
2526
- error(`${at}.key is required (short key, stored namespaced as '{metadata.name}.{key}')`);
2788
+ error(`${at}.key is required (short key, stored namespaced as '{metadata.id}.{key}')`);
2527
2789
  } else if (!SETTING_KEY_PATTERN.test(declaration.key)) {
2528
2790
  error(`${at}.key '${declaration.key}' must be lowercase kebab/dot notation (e.g. 'api-key' or 'smtp.host')`);
2529
2791
  } else if (seen.has(declaration.key)) {
@@ -2678,7 +2940,9 @@ function registerDev(program2) {
2678
2940
  const env = {
2679
2941
  ...process.env,
2680
2942
  ...context.input.environment,
2681
- ...contextEnv(context, contextPath)
2943
+ ...contextEnv(context, contextPath),
2944
+ // Lets the SDK prompt for missing declared arguments in this terminal (never on the platform).
2945
+ VERENTIS_LOCAL_RUN: "1"
2682
2946
  };
2683
2947
  const pythonArgs = [];
2684
2948
  if (options.debug !== void 0) {
@@ -2719,7 +2983,7 @@ function registerDev(program2) {
2719
2983
  program: "${file}",
2720
2984
  console: "integratedTerminal",
2721
2985
  justMyCode: true,
2722
- env: { VERENTIS_CONTEXT_PATH: "${workspaceFolder}/.verentis/context.json" }
2986
+ env: { VERENTIS_CONTEXT_PATH: "${workspaceFolder}/.verentis/context.json", VERENTIS_LOCAL_RUN: "1" }
2723
2987
  }
2724
2988
  ]
2725
2989
  };
@@ -2919,7 +3183,7 @@ async function followExecution(api, workspaceId, executionId, json) {
2919
3183
  if (exec.status !== "Completed") process.exitCode = 1;
2920
3184
  return;
2921
3185
  }
2922
- await new Promise((resolve16) => setTimeout(resolve16, 1e3));
3186
+ await new Promise((resolve18) => setTimeout(resolve18, 1e3));
2923
3187
  }
2924
3188
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
2925
3189
  process.exitCode = 1;
@@ -3603,9 +3867,8 @@ var TEMPLATES = {
3603
3867
  kind: Application
3604
3868
 
3605
3869
  metadata:
3606
- name: ${name}
3607
- package-id: ${name}
3608
- display-name: ${titleCase(name)}
3870
+ id: ${name}
3871
+ name: ${titleCase(name)}
3609
3872
  description: ""
3610
3873
  icon: ./icons/app.svg
3611
3874
  version: 0.1.0
@@ -3655,9 +3918,8 @@ packaging:
3655
3918
  kind: ExecutionEngine
3656
3919
 
3657
3920
  metadata:
3658
- name: ${name}
3659
- package-id: ${name}
3660
- display-name: ${titleCase(name)}
3921
+ id: ${name}
3922
+ name: ${titleCase(name)}
3661
3923
  description: ""
3662
3924
  icon: ./icons/app.svg
3663
3925
  version: 0.1.0
@@ -3692,9 +3954,8 @@ packaging:
3692
3954
  kind: Bundle
3693
3955
 
3694
3956
  metadata:
3695
- name: ${name}
3696
- package-id: ${name}
3697
- display-name: ${titleCase(name)}
3957
+ id: ${name}
3958
+ name: ${titleCase(name)}
3698
3959
  description: ""
3699
3960
  version: 0.1.0
3700
3961
  author: ""
@@ -3725,9 +3986,8 @@ packaging:
3725
3986
  kind: Theme
3726
3987
 
3727
3988
  metadata:
3728
- name: ${name}
3729
- package-id: ${name}
3730
- display-name: ${titleCase(name)}
3989
+ id: ${name}
3990
+ name: ${titleCase(name)}
3731
3991
  description: ""
3732
3992
  version: 0.1.0
3733
3993
  author: ""
@@ -3739,15 +3999,15 @@ metadata:
3739
3999
  # readme: ./README.md
3740
4000
 
3741
4001
  # A theme replaces the workspace theme (/.theme). Map any of the theme assets to files in this package:
3742
- # theme.css, background, background.dark, logo.light, logo.dark, mark.light, mark.dark, favicon,
4002
+ # theme.css, background, background.dark, logo, logo.dark, mark, mark.dark, favicon,
3743
4003
  # apple-touch-icon (PNG only). Images may be SVG, PNG, JPEG or WebP (1 MiB each, backgrounds 2 MiB,
3744
4004
  # 4 MiB in total). \`verentis pack\` installs each one at /.theme/<asset>.
3745
4005
  spec:
3746
4006
  assets:
3747
4007
  theme.css: theme/theme.css
3748
- logo.light: theme/logo-light.svg
4008
+ logo: theme/logo-light.svg
3749
4009
  logo.dark: theme/logo-dark.svg
3750
- mark.light: theme/mark-light.svg
4010
+ mark: theme/mark-light.svg
3751
4011
  mark.dark: theme/mark-dark.svg
3752
4012
  favicon: theme/favicon.svg
3753
4013
  # background: theme/background.jpg
@@ -3771,12 +4031,12 @@ function resolveInitTemplate(type) {
3771
4031
  return key;
3772
4032
  }
3773
4033
  function registerInit(program2) {
3774
- program2.command("init [dir]").description("Scaffold a manifest.yaml for a new package").option("--type <type>", "package type: application | engine | bundle | theme").option("--kind <kind>", "alias for --type").option("--name <name>", "package name (defaults to the directory name)").action(async (dir, options) => {
4034
+ program2.command("init [dir]").description("Scaffold a manifest.yaml for a new package").option("--type <type>", "package type: application | engine | bundle | theme").option("--kind <kind>", "alias for --type").option("--id <id>", "package ID (defaults to the directory name)").action(async (dir, options) => {
3775
4035
  const templateKey = resolveInitTemplate(options.type ?? options.kind ?? "application");
3776
4036
  const template = TEMPLATES[templateKey];
3777
4037
  const targetDir = resolve(dir ?? ".");
3778
4038
  await mkdir(targetDir, { recursive: true });
3779
- const name = (options.name ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
4039
+ const name = (options.id ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
3780
4040
  const manifestPath = join(targetDir, "manifest.yaml");
3781
4041
  if (await exists3(manifestPath)) throw new Error(`${manifestPath} already exists.`);
3782
4042
  await writeFile(manifestPath, template(name));
@@ -3854,56 +4114,148 @@ async function loadKey(name) {
3854
4114
  }
3855
4115
  var pageItems2 = (page) => page.data ?? page.items ?? [];
3856
4116
  async function getMyPublisher(api) {
3857
- const result = await api.request("GET", "/v1/publishers/me", {
4117
+ const result = await api.request("GET", `${REGISTRY_BASE}/publishers/me`, {
3858
4118
  scopes: [SCOPES.publisherRead]
3859
4119
  });
3860
- return result ?? null;
4120
+ return result && typeof result === "object" && result.id ? result : null;
3861
4121
  }
3862
4122
  async function requireMyPublisher(api) {
3863
4123
  const publisher = await getMyPublisher(api);
3864
4124
  if (!publisher) {
3865
- throw new Error("No publisher profile for this account. Create one with `verentis publisher create --name <name> --display-name <display>`.");
4125
+ throw new Error(noPublisherMessage(api.apiUrl));
3866
4126
  }
3867
4127
  return publisher;
3868
4128
  }
4129
+ async function requireRegistryPublisher(api) {
4130
+ const claims = decodeJwtPayload(await api.registryToken());
4131
+ if (typeof claims?.publisher_id === "string") {
4132
+ return { id: claims.publisher_id, name: typeof claims.publisher_name === "string" ? claims.publisher_name : void 0 };
4133
+ }
4134
+ const me = await api.request("GET", `${REGISTRY_BASE}/publishers/me`, { plane: "registry" }).catch(() => null);
4135
+ if (!me?.id) {
4136
+ throw new Error(noPublisherMessage(api.apiUrl));
4137
+ }
4138
+ return { id: me.id, name: me.name };
4139
+ }
3869
4140
  async function findPackageByPackageId(api, publisherId, packageId) {
3870
4141
  const page = await api.request("GET", `/v1/publishers/${publisherId}/packages`, {
3871
- scopes: [SCOPES.packageRead],
4142
+ scopes: [SCOPES.packageList],
3872
4143
  query: { PageNo: 1, PageSize: 100 }
3873
4144
  });
3874
4145
  return pageItems2(page).find((pkg) => pkg.packageId === packageId) ?? null;
3875
4146
  }
3876
- async function createPackage(api, input) {
3877
- return api.request("POST", "/v1/packages", {
3878
- scopes: [SCOPES.packageCreate],
3879
- body: {
3880
- publisherId: input.publisherId,
3881
- packageId: input.packageId,
3882
- name: input.name,
3883
- displayName: input.displayName,
3884
- kind: input.kind,
3885
- description: input.description ?? null,
3886
- icon: null,
3887
- categories: [],
3888
- visibility: input.visibility ?? "Private"
3889
- }
3890
- });
4147
+ async function findRegistryVersion(api, publisher, packageId, version) {
4148
+ try {
4149
+ return await api.request(
4150
+ "GET",
4151
+ `${REGISTRY_BASE}/packages/${encodeURIComponent(publisher)}/${encodeURIComponent(packageId)}/versions/${encodeURIComponent(version)}`,
4152
+ { plane: "registry" }
4153
+ );
4154
+ } catch (error) {
4155
+ if (error instanceof ApiError && error.status === 404) return null;
4156
+ throw error;
4157
+ }
3891
4158
  }
3892
- async function uploadVersion(api, packageId, vpkgPath) {
3893
- (await stat(vpkgPath)).size;
4159
+ function sameTreeDigest(a, b) {
4160
+ const normalize = (value) => (value ?? "").trim().toLowerCase().replace(/^sha256:/, "");
4161
+ return normalize(a) !== "" && normalize(a) === normalize(b);
4162
+ }
4163
+ async function uploadRegistryVersion(api, publisher, packageId, vpkgPath, options = {}) {
3894
4164
  const stream = Readable.toWeb(createReadStream(vpkgPath));
3895
- const res = await api.requestRaw("POST", `/v1/packages/${packageId}/versions`, {
3896
- scopes: [SCOPES.packagePublish],
3897
- rawBody: stream,
3898
- contentType: "application/vnd.verentis.package+tar+gzip"
3899
- });
4165
+ const res = await api.requestRaw(
4166
+ "POST",
4167
+ `${REGISTRY_BASE}/packages/${encodeURIComponent(publisher)}/${encodeURIComponent(packageId)}/versions`,
4168
+ {
4169
+ plane: "registry",
4170
+ rawBody: stream,
4171
+ contentType: "application/vnd.verentis.package+tar+gzip",
4172
+ query: { visibility: options.visibility }
4173
+ }
4174
+ );
3900
4175
  return await res.json();
3901
4176
  }
3902
- async function yankVersion(api, packageId, version) {
3903
- await api.request("POST", `/v1/packages/${packageId}/versions/${encodeURIComponent(version)}/yank`, {
3904
- scopes: [SCOPES.packagePublish]
4177
+ var publisherEmailSenderPath = (publisherId, packageOwner) => `${REGISTRY_BASE}/publishers/${encodeURIComponent(publisherId)}/packages/${encodeURIComponent(packageOwner)}/notifications/sender`;
4178
+ async function setPublisherEmailSender(api, publisherId, packageOwner, request) {
4179
+ return api.request("PUT", publisherEmailSenderPath(publisherId, packageOwner), { plane: "registry", body: request });
4180
+ }
4181
+ async function getPublisherEmailSender(api, publisherId, packageOwner) {
4182
+ return api.request("GET", publisherEmailSenderPath(publisherId, packageOwner), { plane: "registry" });
4183
+ }
4184
+ async function revokePublisherEmailSender(api, publisherId, packageOwner) {
4185
+ return api.request("DELETE", publisherEmailSenderPath(publisherId, packageOwner), { plane: "registry" });
4186
+ }
4187
+ async function resolveRegistryPackageRef(api, ref) {
4188
+ const trimmed = ref.trim().replace(/^@/, "");
4189
+ if (trimmed.includes("/")) {
4190
+ const [publisher2, packageId] = trimmed.split("/", 2);
4191
+ if (!publisher2 || !packageId) throw new Error(`Invalid package reference '${ref}'. Use 'package-id' or 'publisher/package-id'.`);
4192
+ return { publisher: publisher2, packageId };
4193
+ }
4194
+ const publisher = await requireRegistryPublisher(api);
4195
+ if (!publisher.name) throw new Error(`Cannot resolve your publisher name; pass the package as 'publisher/${trimmed}'.`);
4196
+ return { publisher: publisher.name, packageId: trimmed };
4197
+ }
4198
+ var registryPackagePath = (ref) => `${REGISTRY_BASE}/packages/${encodeURIComponent(ref.publisher)}/${encodeURIComponent(ref.packageId)}`;
4199
+ var registryVersionPath = (ref, version) => `${registryPackagePath(ref)}/versions/${encodeURIComponent(version)}`;
4200
+ async function listRegistryPackages(api, publisher) {
4201
+ const result = await api.request(
4202
+ "GET",
4203
+ `${REGISTRY_BASE}/publishers/${encodeURIComponent(publisher)}/packages`,
4204
+ { plane: "registry" }
4205
+ );
4206
+ return Array.isArray(result) ? result : [];
4207
+ }
4208
+ async function getRegistryPackage(api, ref) {
4209
+ const pkg = (await listRegistryPackages(api, ref.publisher)).find((p) => p.packageId === ref.packageId);
4210
+ if (!pkg) throw new Error(`Package '${ref.publisher}/${ref.packageId}' not found in the registry (or you do not own it).`);
4211
+ return pkg;
4212
+ }
4213
+ async function yankVersion(api, ref, version, reason) {
4214
+ await api.request("POST", `${registryVersionPath(ref, version)}/yank`, { plane: "registry", body: { reason: reason || void 0 } });
4215
+ }
4216
+ async function deprecateVersion(api, ref, version, message) {
4217
+ await api.request("POST", `${registryVersionPath(ref, version)}/deprecate`, { plane: "registry", body: { message: message || void 0 } });
4218
+ }
4219
+ async function undeprecateVersion(api, ref, version) {
4220
+ await api.request("DELETE", `${registryVersionPath(ref, version)}/deprecate`, { plane: "registry" });
4221
+ }
4222
+ async function deprecatePackage(api, ref, message) {
4223
+ await api.request("POST", `${registryPackagePath(ref)}/deprecate`, { plane: "registry", body: { message: message || void 0 } });
4224
+ }
4225
+ async function undeprecatePackage(api, ref) {
4226
+ await api.request("DELETE", `${registryPackagePath(ref)}/deprecate`, { plane: "registry" });
4227
+ }
4228
+ async function archivePackage(api, ref) {
4229
+ await api.request("POST", `${registryPackagePath(ref)}/archive`, { plane: "registry" });
4230
+ }
4231
+ async function setPackageVisibility(api, ref, visibility) {
4232
+ await api.request("PUT", `${registryPackagePath(ref)}/visibility`, { plane: "registry", body: { visibility } });
4233
+ }
4234
+ async function listVisibilityGrants(api, ref) {
4235
+ const result = await api.request("GET", `${registryPackagePath(ref)}/visibility-grants`, { plane: "registry" });
4236
+ return Array.isArray(result) ? result : result ? pageItems2(result) : [];
4237
+ }
4238
+ async function grantVisibility(api, ref, granteeType, granteeId) {
4239
+ return api.request("POST", `${registryPackagePath(ref)}/visibility-grants`, {
4240
+ plane: "registry",
4241
+ body: { granteeType, granteeId }
3905
4242
  });
3906
4243
  }
4244
+ async function revokeVisibility(api, ref, grantId) {
4245
+ await api.request("DELETE", `${registryPackagePath(ref)}/visibility-grants/${encodeURIComponent(grantId)}`, { plane: "registry" });
4246
+ }
4247
+ function parseVisibility(value) {
4248
+ const normalized = value.trim().toLowerCase();
4249
+ if (normalized === "public") return "Public";
4250
+ if (normalized === "private") return "Private";
4251
+ throw new Error(`Invalid visibility '${value}'. Use Public or Private.`);
4252
+ }
4253
+ function parseGranteeType(value) {
4254
+ const normalized = value.trim().toLowerCase();
4255
+ if (normalized === "account") return "Account";
4256
+ if (normalized === "workspace") return "Workspace";
4257
+ throw new Error(`Invalid grantee type '${value}'. Use Account or Workspace.`);
4258
+ }
3907
4259
  async function downloadTarball(api, packageId, version, workspaceId) {
3908
4260
  return api.requestRaw("GET", `/v1/packages/${packageId}/versions/${encodeURIComponent(version)}/tarball`, {
3909
4261
  scopes: [SCOPES.packageRead],
@@ -3919,7 +4271,7 @@ async function resolvePackageRef(api, ref) {
3919
4271
  return { package: pkg2, publisherName: me.name };
3920
4272
  }
3921
4273
  const page = await api.request("GET", "/v1/packages", {
3922
- scopes: [SCOPES.packageReadAll],
4274
+ scopes: [SCOPES.packageList],
3923
4275
  query: { SearchText: packageId, PageNo: 1, PageSize: 100 }
3924
4276
  });
3925
4277
  const pkg = pageItems2(page).find((p) => p.packageId === packageId && p.publisherName === publisherName);
@@ -3941,12 +4293,8 @@ function registerKeygen(program2) {
3941
4293
  }
3942
4294
  if (options.register) {
3943
4295
  const api = await createApiClient();
3944
- const publisher = await requireMyPublisher(api);
3945
- await api.request("POST", `/v1/publishers/${publisher.id}/keys`, {
3946
- scopes: [SCOPES.publisherUpdate],
3947
- body: { publisherId: publisher.id, algorithm: "Ed25519", publicKey: key.publicKey }
3948
- });
3949
- console.log(`Registered public key with publisher '${publisher.name}'.`);
4296
+ const publisher = await registerKey(api, key.publicKey);
4297
+ console.log(`Registered public key with publisher '${publisher.name ?? publisher.id}'.`);
3950
4298
  } else {
3951
4299
  console.log("Public key NOT registered (use `verentis key register` later).");
3952
4300
  }
@@ -3955,36 +4303,48 @@ function registerKeygen(program2) {
3955
4303
  keyCmd.command("register").description("Register a local key's public half with your publisher profile").option("--name <name>", "key name", "default").action(async (options) => {
3956
4304
  const key = await loadKey(options.name);
3957
4305
  const api = await createApiClient();
3958
- const publisher = await requireMyPublisher(api);
3959
- await api.request("POST", `/v1/publishers/${publisher.id}/keys`, {
3960
- scopes: [SCOPES.publisherUpdate],
3961
- body: { publisherId: publisher.id, algorithm: "Ed25519", publicKey: key.publicKey }
3962
- });
3963
- console.log(`Registered key '${options.name}' (kid ${key.kid}) with publisher '${publisher.name}'.`);
4306
+ const publisher = await registerKey(api, key.publicKey);
4307
+ console.log(`Registered key '${options.name}' (kid ${key.kid}) with publisher '${publisher.name ?? publisher.id}'.`);
3964
4308
  });
3965
4309
  keyCmd.command("revoke <kid>").description("Revoke a registered signing key").action(async (kid) => {
3966
4310
  const api = await createApiClient();
3967
- const publisher = await requireMyPublisher(api);
3968
- await api.request("DELETE", `/v1/publishers/${publisher.id}/keys/${encodeURIComponent(kid)}`, {
3969
- scopes: [SCOPES.publisherUpdate]
4311
+ const publisher = await requireRegistryPublisher(api);
4312
+ await api.request("DELETE", `${REGISTRY_BASE}/publishers/${encodeURIComponent(publisher.id)}/keys/${encodeURIComponent(kid)}`, {
4313
+ plane: "registry"
3970
4314
  });
3971
4315
  console.log(`Revoked key ${kid}.`);
3972
4316
  });
3973
4317
  }
4318
+ async function registerKey(api, publicKey) {
4319
+ const publisher = await requireRegistryPublisher(api);
4320
+ await api.request("POST", `${REGISTRY_BASE}/publishers/${encodeURIComponent(publisher.id)}/keys`, {
4321
+ plane: "registry",
4322
+ body: { publicKey, algorithm: "Ed25519" }
4323
+ });
4324
+ return publisher;
4325
+ }
3974
4326
  function registerLogin(program2) {
3975
- program2.command("login").description("Sign in to Verentis (browser device flow by default; --api-key/--token for non-interactive use)").addOption(new Option("--api-url <url>", "Verentis API gateway URL (defaults to production)").hideHelp()).option("--api-key <key>", "Verentis API key (vrt_...)").option("--token <token>", "Verentis identity token (exchanged per request for scoped access tokens)").option("--sealing-key <key>", "the platform's base64 X25519 sealing PUBLIC key (used by `pack --encrypt`)").option("--insecure", "skip TLS certificate verification (for local dev with self-signed certs)").action(async (options) => {
4327
+ program2.command("login").description("Sign in to Verentis for publishing (browser device flow; --api-key pub_\u2026 for CI; --regional for workspace/account commands)").addOption(new Option("--api-url <url>", "Verentis API gateway URL (defaults to production)").hideHelp()).option("--api-key <key>", "publisher API key (pub_\u2026, global publishing) or regional Verentis API key (vrt_\u2026)").option("--regional", "sign in to the regional Security service instead (workspace/account commands, not publishing)").option("--token <token>", "Verentis identity token (exchanged per request for scoped access tokens)").option("--sealing-key <key>", "the platform's base64 X25519 sealing PUBLIC key (used by `pack --encrypt`)").option("--insecure", "skip TLS certificate verification (for local dev with self-signed certs)").action(async (options) => {
3976
4328
  const config = await loadConfig();
3977
4329
  if (options.apiUrl) config.apiUrl = options.apiUrl;
3978
4330
  if (options.sealingKey) config.sealingPublicKey = options.sealingKey;
3979
4331
  if (options.insecure !== void 0) config.insecure = options.insecure;
3980
4332
  const apiUrl = (options.apiUrl ?? process.env.VERENTIS_API_URL ?? config.apiUrl ?? PRODUCTION_API_URL).replace(/\/+$/, "");
3981
4333
  if (options.apiKey) {
3982
- if (!options.apiKey.startsWith("vrt_")) throw new Error('API keys start with "vrt_".');
4334
+ if (options.apiKey.startsWith(PUBLISHER_API_KEY_PREFIX)) {
4335
+ config.publisherApiKey = options.apiKey;
4336
+ delete config.publishAccessToken;
4337
+ delete config.publishRefreshToken;
4338
+ await saveConfig(config);
4339
+ console.log(`Configuration saved (publisher API key @ ${apiUrl}).`);
4340
+ return;
4341
+ }
4342
+ if (!options.apiKey.startsWith("vrt_")) throw new Error('API keys start with "pub_" (publisher) or "vrt_" (regional).');
3983
4343
  config.apiKey = options.apiKey;
3984
4344
  delete config.identityToken;
3985
4345
  delete config.refreshToken;
3986
4346
  await saveConfig(config);
3987
- console.log(`Configuration saved (API key @ ${apiUrl}).`);
4347
+ console.log(`Configuration saved (regional API key @ ${apiUrl}).`);
3988
4348
  return;
3989
4349
  }
3990
4350
  if (options.token) {
@@ -3996,6 +4356,26 @@ function registerLogin(program2) {
3996
4356
  return;
3997
4357
  }
3998
4358
  const insecure = config.insecure;
4359
+ if (!options.regional) {
4360
+ const authorization2 = await startRegistryDeviceAuthorization(apiUrl, insecure);
4361
+ console.log("To sign in, open this URL in a browser:");
4362
+ console.log(`
4363
+ ${authorization2.verification_uri_complete ?? authorization2.verification_uri}
4364
+ `);
4365
+ console.log(`and confirm the code: ${authorization2.user_code}`);
4366
+ console.log("\nWaiting for approval\u2026");
4367
+ const tokens = await pollForRegistryTokens(apiUrl, authorization2, insecure, () => process.stderr.write("."));
4368
+ process.stderr.write("\n");
4369
+ config.publishAccessToken = tokens.accessToken;
4370
+ if (tokens.refreshToken) config.publishRefreshToken = tokens.refreshToken;
4371
+ else delete config.publishRefreshToken;
4372
+ delete config.publisherApiKey;
4373
+ await saveConfig(config);
4374
+ const claims2 = decodeJwtPayload(tokens.accessToken);
4375
+ if (claims2?.publisher_name) console.log(`Signed in to publish as '${claims2.publisher_name}' @ ${apiUrl}.`);
4376
+ else console.log(`Signed in @ ${apiUrl}. ${noPublisherMessage(apiUrl)}`);
4377
+ return;
4378
+ }
3999
4379
  const authorization = await startDeviceAuthorization(apiUrl, insecure);
4000
4380
  console.log("To sign in, open this URL in a browser:");
4001
4381
  console.log(`
@@ -4021,20 +4401,23 @@ function registerLogin(program2) {
4021
4401
  delete config.apiKey;
4022
4402
  delete config.identityToken;
4023
4403
  delete config.refreshToken;
4404
+ delete config.publishAccessToken;
4405
+ delete config.publishRefreshToken;
4406
+ delete config.publisherApiKey;
4024
4407
  await saveConfig(config);
4025
4408
  console.log("Credentials removed.");
4026
4409
  });
4027
- program2.command("whoami").description("Show the current identity, account and publisher profile").action(async () => {
4410
+ program2.command("whoami").description("Show the current regional identity/account and the global publishing session").action(async () => {
4028
4411
  const config = await loadConfig();
4029
4412
  const identityToken = process.env.VERENTIS_TOKEN ?? config.identityToken;
4030
4413
  if (identityToken) {
4031
- const claims = decodeJwtPayload(identityToken);
4032
- if (claims) {
4033
- const expiry = claims.exp ? new Date(claims.exp * 1e3) : void 0;
4414
+ const claims2 = decodeJwtPayload(identityToken);
4415
+ if (claims2) {
4416
+ const expiry = claims2.exp ? new Date(claims2.exp * 1e3) : void 0;
4034
4417
  const expired = expiry && expiry.getTime() <= Date.now();
4035
4418
  const renewable = Boolean(config.refreshToken) && !process.env.VERENTIS_TOKEN;
4036
- console.log(`User: ${claims.name ?? claims.email ?? claims.sub ?? "(unknown)"}${claims.sub ? ` (${claims.sub})` : ""}`);
4037
- if (claims.account_id) console.log(`Account: ${claims.account_id}`);
4419
+ console.log(`User: ${claims2.name ?? claims2.email ?? claims2.sub ?? "(unknown)"}${claims2.sub ? ` (${claims2.sub})` : ""}`);
4420
+ if (claims2.account_id) console.log(`Account: ${claims2.account_id}`);
4038
4421
  if (expiry) {
4039
4422
  const state = expired ? renewable ? "expired (auto-renews)" : "EXPIRED" : "expires";
4040
4423
  console.log(`Token ${state}: ${expiry.toISOString()}`);
@@ -4045,20 +4428,26 @@ function registerLogin(program2) {
4045
4428
  console.log("Credential: API key (identity claims not available)");
4046
4429
  }
4047
4430
  if (config.defaultWorkspaceId) console.log(`Workspace: ${config.defaultWorkspaceId} (default)`);
4048
- const api = await createApiClient();
4049
- const publisher = await api.request(
4050
- "GET",
4051
- "/v1/publishers/me",
4052
- { scopes: [SCOPES.publisherRead] }
4053
- ).catch(() => null);
4054
- if (!publisher) {
4055
- console.log('Publisher: none \u2014 create one with `verentis publisher create --name <name> --display-name "<display name>"`');
4431
+ const apiUrl = requireApiUrl(config);
4432
+ const publisherKey = process.env.VERENTIS_PUBLISHER_API_KEY ?? config.publisherApiKey;
4433
+ if (!publisherKey && !config.publishAccessToken && process.env.VERENTIS_GITHUB_OIDC_AUDIENCE === void 0) {
4434
+ console.log(`Publishing: not signed in \u2014 run \`verentis login\` (registry ${apiUrl}${REGISTRY_BASE})`);
4056
4435
  return;
4057
4436
  }
4058
- console.log(`Publisher: ${publisher.name} (${publisher.displayName})${publisher.isVerified ? " \u2713 verified" : ""}`);
4059
- for (const key of publisher.signingKeys ?? []) {
4060
- console.log(` key ${key.kid} [${key.status}]`);
4061
- }
4437
+ const api = await createApiClient();
4438
+ console.log(`Publishing: global registry @ ${apiUrl}${REGISTRY_BASE}`);
4439
+ const credential = process.env.VERENTIS_GITHUB_OIDC_AUDIENCE !== void 0 ? "GitHub OIDC" : publisherKey ? "publisher API key" : "device-flow session";
4440
+ console.log(` credential: ${credential}`);
4441
+ const token = await api.registryToken().catch((err) => {
4442
+ console.log(` ${err.message}`);
4443
+ return void 0;
4444
+ });
4445
+ const claims = token ? decodeJwtPayload(token) : null;
4446
+ if (!claims) return;
4447
+ if (claims.publisher_name) console.log(` publisher: ${claims.publisher_name}${claims.publisher_id ? ` (${claims.publisher_id})` : ""}`);
4448
+ else console.log(` publisher: none. ${noPublisherMessage(apiUrl)}`);
4449
+ if (claims.scope) console.log(` scope: ${claims.scope}`);
4450
+ if (claims.exp) console.log(` token expires: ${new Date(claims.exp * 1e3).toISOString()}`);
4062
4451
  });
4063
4452
  }
4064
4453
 
@@ -4147,6 +4536,85 @@ function rawX25519Private(key) {
4147
4536
  function publicKeyFromRaw(raw) {
4148
4537
  return createPublicKey({ key: { kty: "OKP", crv: "X25519", x: raw.toString("base64url") }, format: "jwk" });
4149
4538
  }
4539
+ function isPlainObject(value) {
4540
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4541
+ }
4542
+ function deepMerge(base, overlay) {
4543
+ if (!isPlainObject(base) || !isPlainObject(overlay)) {
4544
+ return overlay;
4545
+ }
4546
+ const result = { ...base };
4547
+ for (const [key, value] of Object.entries(overlay)) {
4548
+ result[key] = key in result ? deepMerge(result[key], value) : value;
4549
+ }
4550
+ return result;
4551
+ }
4552
+ function applyOverlay(base, overlay) {
4553
+ return deepMerge(base, overlay);
4554
+ }
4555
+ function resolveOverlayPath(projectDir, selector) {
4556
+ if (selector.overlay) {
4557
+ return isAbsolute(selector.overlay) ? selector.overlay : resolve(selector.overlay);
4558
+ }
4559
+ if (selector.env) {
4560
+ return join(projectDir, "environments", `${selector.env}.yaml`);
4561
+ }
4562
+ return void 0;
4563
+ }
4564
+ var PARAM_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
4565
+ var PARAM_PLACEHOLDER_PATTERN = /(\$?)\$\{param:([^}]*)\}/g;
4566
+ function parseOverlayParams(pairs = []) {
4567
+ const params = {};
4568
+ for (const pair of pairs) {
4569
+ const eq = pair.indexOf("=");
4570
+ const name = eq < 0 ? pair : pair.slice(0, eq);
4571
+ if (eq < 0 || !PARAM_NAME_PATTERN.test(name)) {
4572
+ throw new Error(`Invalid --param '${pair}' (expected name=value with a lowercase kebab-case name).`);
4573
+ }
4574
+ if (name in params) throw new Error(`--param '${name}' is set more than once.`);
4575
+ params[name] = pair.slice(eq + 1);
4576
+ }
4577
+ return params;
4578
+ }
4579
+ function interpolateOverlay(overlay, params, source) {
4580
+ const missing = /* @__PURE__ */ new Set();
4581
+ const visit = (value) => {
4582
+ if (typeof value === "string") {
4583
+ return value.replace(PARAM_PLACEHOLDER_PATTERN, (raw, escape, name) => {
4584
+ if (escape) return raw.slice(1);
4585
+ if (Object.hasOwn(params, name)) return params[name];
4586
+ missing.add(name);
4587
+ return raw;
4588
+ });
4589
+ }
4590
+ if (Array.isArray(value)) return value.map(visit);
4591
+ if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
4592
+ return value;
4593
+ };
4594
+ const result = visit(overlay);
4595
+ if (missing.size > 0) {
4596
+ const names = [...missing].sort();
4597
+ throw new Error(`Overlay ${source} needs ${names.map((name) => `--param ${name}=<value>`).join(", ")}.`);
4598
+ }
4599
+ return result;
4600
+ }
4601
+ async function loadOverlay(path, params = {}) {
4602
+ let text;
4603
+ try {
4604
+ text = await readFile(path, "utf8");
4605
+ } catch (error) {
4606
+ if (error?.code === "ENOENT") {
4607
+ throw new Error(`Overlay file not found: ${path}`);
4608
+ }
4609
+ throw error;
4610
+ }
4611
+ const parsed = parse(text);
4612
+ if (parsed === null || parsed === void 0) return {};
4613
+ if (!isPlainObject(parsed)) {
4614
+ throw new Error(`Overlay ${path} must be a YAML mapping (got ${Array.isArray(parsed) ? "a list" : typeof parsed}).`);
4615
+ }
4616
+ return interpolateOverlay(parsed, params, path);
4617
+ }
4150
4618
  var MIB = 1024 * 1024;
4151
4619
  var MAX_LOGO_BYTES = MIB;
4152
4620
  var MAX_IMAGE_BYTES = 5 * MIB;
@@ -4351,6 +4819,7 @@ function defaultIncludes(manifest) {
4351
4819
  const sources = /* @__PURE__ */ new Set();
4352
4820
  collectSchemaSources(manifest.spec, sources);
4353
4821
  collectInstallSources(manifest, sources);
4822
+ for (const path of agentAvatarPayloadPaths(manifest)) sources.add(path);
4354
4823
  if (sources.size === 0) return [];
4355
4824
  return [...sources];
4356
4825
  }
@@ -4383,48 +4852,6 @@ function collectSchemaSources(node, sources) {
4383
4852
  function toEntryPath2(file) {
4384
4853
  return file.split(sep).join("/");
4385
4854
  }
4386
- function isPlainObject(value) {
4387
- return typeof value === "object" && value !== null && !Array.isArray(value);
4388
- }
4389
- function deepMerge(base, overlay) {
4390
- if (!isPlainObject(base) || !isPlainObject(overlay)) {
4391
- return overlay;
4392
- }
4393
- const result = { ...base };
4394
- for (const [key, value] of Object.entries(overlay)) {
4395
- result[key] = key in result ? deepMerge(result[key], value) : value;
4396
- }
4397
- return result;
4398
- }
4399
- function applyOverlay(base, overlay) {
4400
- return deepMerge(base, overlay);
4401
- }
4402
- function resolveOverlayPath(projectDir, selector) {
4403
- if (selector.overlay) {
4404
- return isAbsolute(selector.overlay) ? selector.overlay : resolve(selector.overlay);
4405
- }
4406
- if (selector.env) {
4407
- return join(projectDir, "environments", `${selector.env}.yaml`);
4408
- }
4409
- return void 0;
4410
- }
4411
- async function loadOverlay(path) {
4412
- let text;
4413
- try {
4414
- text = await readFile(path, "utf8");
4415
- } catch (error) {
4416
- if (error?.code === "ENOENT") {
4417
- throw new Error(`Overlay file not found: ${path}`);
4418
- }
4419
- throw error;
4420
- }
4421
- const parsed = parse(text);
4422
- if (parsed === null || parsed === void 0) return {};
4423
- if (!isPlainObject(parsed)) {
4424
- throw new Error(`Overlay ${path} must be a YAML mapping (got ${Array.isArray(parsed) ? "a list" : typeof parsed}).`);
4425
- }
4426
- return parsed;
4427
- }
4428
4855
  var VARIABLE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
4429
4856
  var PLACEHOLDER_PATTERN = /(?<!\$)\$\{var:([^}]*)\}/g;
4430
4857
  var ESCAPED_PLACEHOLDER_PATTERN = /\$\$\{var:([^}]*)\}/g;
@@ -4597,6 +5024,240 @@ function findPlaceholders(text) {
4597
5024
  }
4598
5025
  return placeholders;
4599
5026
  }
5027
+ var ARGUMENTS_SCHEMA = "verentis.io/script-arguments/v1";
5028
+ var ARGUMENTS_SUFFIX = ".arguments.json";
5029
+ var KINDS = /* @__PURE__ */ new Set(["option", "positional"]);
5030
+ var TYPES = /* @__PURE__ */ new Set(["string", "integer", "number", "boolean", "date"]);
5031
+ async function checkScriptArgumentDescriptors(projectDir, payloadFiles, readBytes) {
5032
+ const errors = [];
5033
+ const entries = new Map(payloadFiles.map((file) => [toEntryPath2(file), file]));
5034
+ for (const [entry, file] of entries) {
5035
+ if (entry.endsWith(ARGUMENTS_SUFFIX)) {
5036
+ errors.push(...await checkDescriptor(entry, file, entries, readBytes));
5037
+ } else if (!entries.has(entry + ARGUMENTS_SUFFIX) && await isFile(join(projectDir, file + ARGUMENTS_SUFFIX))) {
5038
+ errors.push(`${entry + ARGUMENTS_SUFFIX}: argument descriptor exists but is not included in packaging.files.`);
5039
+ }
5040
+ }
5041
+ return errors;
5042
+ }
5043
+ async function checkDescriptor(entry, file, entries, readBytes) {
5044
+ let descriptor;
5045
+ try {
5046
+ descriptor = JSON.parse((await readBytes(file)).toString("utf8"));
5047
+ } catch (error) {
5048
+ return [`${entry}: invalid JSON (${error instanceof Error ? error.message : String(error)}).`];
5049
+ }
5050
+ if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor)) return [`${entry}: must be a JSON object.`];
5051
+ const errors = [];
5052
+ const fail = (message) => errors.push(`${entry}: ${message}`);
5053
+ if (descriptor.schema !== ARGUMENTS_SCHEMA) fail(`schema must be '${ARGUMENTS_SCHEMA}'.`);
5054
+ const scriptEntry = entry.slice(0, -ARGUMENTS_SUFFIX.length);
5055
+ const scriptName = posix.basename(scriptEntry);
5056
+ if (descriptor.script !== void 0 && descriptor.script !== scriptName) {
5057
+ fail(`script '${String(descriptor.script)}' does not match the file it describes ('${scriptName}').`);
5058
+ }
5059
+ const scriptFile = entries.get(scriptEntry);
5060
+ if (!scriptFile) {
5061
+ fail(`describes '${scriptEntry}', which is not in the package.`);
5062
+ } else if (typeof descriptor.sourceSha256 === "string" && descriptor.sourceSha256) {
5063
+ const actual = createHash("sha256").update(await readBytes(scriptFile)).digest("hex");
5064
+ if (actual !== descriptor.sourceSha256.toLowerCase()) {
5065
+ fail(`is stale: '${scriptEntry}' changed since it was exported. Re-run the SDK argument export.`);
5066
+ }
5067
+ }
5068
+ const definitions = descriptor.arguments;
5069
+ if (!Array.isArray(definitions)) {
5070
+ fail("arguments must be an array.");
5071
+ } else {
5072
+ const names = /* @__PURE__ */ new Set();
5073
+ const flags = /* @__PURE__ */ new Set();
5074
+ for (const [index, raw] of definitions.entries()) {
5075
+ const definition = raw ?? {};
5076
+ const name = typeof definition.name === "string" ? definition.name : "";
5077
+ const at = name ? `argument '${name}'` : `arguments[${index}]`;
5078
+ if (!name) fail(`${at} needs a name.`);
5079
+ else if (names.has(name)) fail(`${at} is declared twice.`);
5080
+ names.add(name);
5081
+ if (!KINDS.has(String(definition.kind))) fail(`${at} has unsupported kind '${String(definition.kind)}'.`);
5082
+ if (!TYPES.has(String(definition.type))) fail(`${at} has unsupported type '${String(definition.type)}'.`);
5083
+ if (definition.kind === "option") {
5084
+ const declared = [...asStrings(definition.flags), ...asStrings([definition.negation])];
5085
+ if (!asStrings(definition.flags).length) fail(`${at} needs at least one flag.`);
5086
+ for (const flag of declared) {
5087
+ if (flags.has(flag)) fail(`flag '${flag}' is declared twice.`);
5088
+ flags.add(flag);
5089
+ }
5090
+ }
5091
+ }
5092
+ for (const group of Array.isArray(descriptor.exclusiveGroups) ? descriptor.exclusiveGroups : []) {
5093
+ for (const name of asStrings(group?.arguments)) {
5094
+ if (!names.has(name)) fail(`exclusive group refers to unknown argument '${name}'.`);
5095
+ }
5096
+ }
5097
+ }
5098
+ const variants = descriptor.variants;
5099
+ for (const sibling of asStrings(Object.values(variants?.scripts ?? {}))) {
5100
+ if (/[\\/]/.test(sibling) || sibling === "." || sibling === "..") {
5101
+ fail(`variant script '${sibling}' must be a file next to '${scriptName}'.`);
5102
+ continue;
5103
+ }
5104
+ const siblingEntry = posix.join(posix.dirname(scriptEntry), sibling);
5105
+ if (!entries.has(siblingEntry)) fail(`variant script '${siblingEntry}' is not in the package.`);
5106
+ }
5107
+ return errors;
5108
+ }
5109
+ var asStrings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string" && item.length > 0) : [];
5110
+ async function isFile(path) {
5111
+ return (await stat(path).catch(() => null))?.isFile() ?? false;
5112
+ }
5113
+ var RUN_SIZES = ["xsmall", "small", "medium", "large", "xlarge", "xxlarge", "gpu"];
5114
+ var MAX_SCRIPT_FILE_ACCESS = 16;
5115
+ var MAX_PACKAGE_FILE_ACCESS = 64;
5116
+ var MAX_BOUNDARY_BYTES = 2048;
5117
+ var READ_ACTIONS = ["file.read"];
5118
+ var WRITE_ACTIONS = ["file.read", "file.write"];
5119
+ var IDENTIFIER = "00000000-0000-0000-0000-000000000000";
5120
+ var boundaryEntry = (type, mode) => ({ type, identifier: IDENTIFIER, actions: mode === "write" ? WRITE_ACTIONS : READ_ACTIONS });
5121
+ function estimateBoundaryBytes(modes, kind) {
5122
+ const implicit = kind === "script" ? [boundaryEntry("Node", "write")] : [boundaryEntry("Node", "write"), boundaryEntry("NodeExact", "read")];
5123
+ return Buffer.byteLength(JSON.stringify([...implicit, ...modes.map((mode) => boundaryEntry("NodePath", mode))]));
5124
+ }
5125
+ function validateFileAccess(value, label, max, kind = "document") {
5126
+ if (value === void 0) return [];
5127
+ if (!Array.isArray(value)) return [`${label} must be a list of { path, mode, reason } entries.`];
5128
+ const errors = [];
5129
+ if (value.length > max) errors.push(`${label} declares ${value.length} entries; at most ${max} are allowed.`);
5130
+ value.forEach((entry, index) => {
5131
+ const at = `${label}[${index}]`;
5132
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5133
+ errors.push(`${at} must be a mapping with path and mode.`);
5134
+ return;
5135
+ }
5136
+ const item = entry;
5137
+ if (item.mode !== "read" && item.mode !== "write") errors.push(`${at}.mode must be 'read' or 'write'.`);
5138
+ if (item.reason !== void 0 && (typeof item.reason !== "string" || item.reason.length > 500)) {
5139
+ errors.push(`${at}.reason must be a string of at most 500 characters.`);
5140
+ }
5141
+ const pathError = filePathError(item.path);
5142
+ if (pathError) errors.push(`${at}.path ${pathError}`);
5143
+ if (item.origin !== void 0) {
5144
+ const origin = item.origin;
5145
+ if (!origin || typeof origin !== "object" || origin.kind !== "script" && origin.kind !== "document" || typeof origin.id !== "string" || !origin.id.trim()) {
5146
+ errors.push(`${at}.origin needs kind 'script' or 'document' and an id.`);
5147
+ } else if (Object.prototype.hasOwnProperty.call(origin, "name")) {
5148
+ errors.push(`${at}.origin.name is no longer supported; use origin.id.`);
5149
+ }
5150
+ }
5151
+ });
5152
+ return [...errors, ...boundarySizeErrors(value, label, kind)];
5153
+ }
5154
+ function boundarySizeErrors(entries, label, kind) {
5155
+ const origins = /* @__PURE__ */ new Map();
5156
+ for (const entry of entries) {
5157
+ if (!entry || typeof entry !== "object") continue;
5158
+ const item = entry;
5159
+ if (item.mode !== "read" && item.mode !== "write" || typeof item.path !== "string") continue;
5160
+ const origin = item.origin;
5161
+ const originKind = origin?.kind === "script" || origin?.kind === "document" ? origin.kind : kind;
5162
+ const id = typeof origin?.id === "string" ? origin.id.trim() : void 0;
5163
+ const key = `${originKind}:${id ?? ""}`;
5164
+ const group = origins.get(key) ?? { kind: originKind, id, paths: /* @__PURE__ */ new Map() };
5165
+ origins.set(key, group);
5166
+ const path = item.path.trim();
5167
+ group.paths.set(path, group.paths.get(path) === "write" ? "write" : item.mode);
5168
+ }
5169
+ const errors = [];
5170
+ for (const group of origins.values()) {
5171
+ const bytes = estimateBoundaryBytes([...group.paths.values()], group.kind);
5172
+ if (bytes <= MAX_BOUNDARY_BYTES) continue;
5173
+ const subject = group.id ? ` for ${group.kind} '${group.id}'` : "";
5174
+ errors.push(`${label}${subject} resolves to up to ${bytes} bytes of token boundaries, over the ${MAX_BOUNDARY_BYTES}-byte limit; declare fewer or broader grants (write grants are larger than read grants).`);
5175
+ }
5176
+ return errors;
5177
+ }
5178
+ function filePathError(value) {
5179
+ if (typeof value !== "string" || !value.trim()) return "is required.";
5180
+ const path = value.trim();
5181
+ if (path.length > 1024) return "exceeds 1024 characters.";
5182
+ if (/[\\*?[\]@\u0000-\u001f\u007f]/.test(path)) {
5183
+ return "must be a plain workspace path (no wildcards, backslashes or control characters).";
5184
+ }
5185
+ if (path.startsWith("/")) {
5186
+ let depth = 0;
5187
+ for (const segment of path.split("/").filter((part) => part && part !== ".")) {
5188
+ depth += segment === ".." ? -1 : 1;
5189
+ if (depth < 0) return "climbs above the workspace root.";
5190
+ }
5191
+ }
5192
+ return void 0;
5193
+ }
5194
+ async function collectScriptFileAccess(projectDir, spec) {
5195
+ const entries = [];
5196
+ const errors = [];
5197
+ const scripts = spec && typeof spec === "object" ? spec.scripts : void 0;
5198
+ if (!Array.isArray(scripts)) return { entries, errors };
5199
+ const root = resolve(projectDir);
5200
+ for (const script of scripts) {
5201
+ if (typeof script !== "string") continue;
5202
+ const directory = resolve(root, script);
5203
+ if (directory !== root && !directory.startsWith(root + sep)) {
5204
+ errors.push(`spec.scripts entry '${script}' is outside the package.`);
5205
+ continue;
5206
+ }
5207
+ if (!(await stat(directory).catch(() => null))?.isDirectory()) continue;
5208
+ const manifest = await findScriptRun(directory);
5209
+ if (!manifest) continue;
5210
+ const metadataErrors = validateDocumentMetadata(manifest.document.metadata);
5211
+ if (metadataErrors.length > 0) {
5212
+ errors.push(...metadataErrors.map((message) => `${script}: ScriptRun ${message}.`));
5213
+ continue;
5214
+ }
5215
+ const sizeError = validateRunSize(manifest.document.resources);
5216
+ if (sizeError) errors.push(`${script}: ScriptRun ${sizeError}`);
5217
+ const label = `${script}: file-access`;
5218
+ const declared = manifest.document["file-access"];
5219
+ const scriptErrors = validateFileAccess(declared, label, MAX_SCRIPT_FILE_ACCESS, "script");
5220
+ errors.push(...scriptErrors);
5221
+ if (scriptErrors.length > 0 || !Array.isArray(declared)) continue;
5222
+ const id = manifest.document.metadata.id.trim();
5223
+ for (const entry of declared) {
5224
+ entries.push({
5225
+ path: entry.path.trim(),
5226
+ mode: entry.mode,
5227
+ ...typeof entry.reason === "string" ? { reason: entry.reason } : {},
5228
+ origin: { kind: "script", id }
5229
+ });
5230
+ }
5231
+ }
5232
+ return { entries, errors };
5233
+ }
5234
+ function validateRunSize(resources) {
5235
+ const size = resources && typeof resources === "object" ? resources.size : void 0;
5236
+ if (typeof size !== "string" || size.trim() === "") return `resources.size is required: one of ${RUN_SIZES.join(", ")}.`;
5237
+ return RUN_SIZES.includes(size.trim().toLowerCase()) ? void 0 : `resources.size '${size.trim()}' is not one of ${RUN_SIZES.join(", ")}.`;
5238
+ }
5239
+ async function findScriptRun(directory) {
5240
+ const names = (await readdir(directory)).filter((name) => /\.ya?ml$/i.test(name)).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
5241
+ for (const name of names) {
5242
+ try {
5243
+ const document = parse(await readFile(join(directory, name), "utf8"));
5244
+ if (document && typeof document === "object" && String(document.kind).replace(/-/g, "").toLowerCase() === "scriptrun") {
5245
+ return { document };
5246
+ }
5247
+ } catch {
5248
+ }
5249
+ }
5250
+ return void 0;
5251
+ }
5252
+ var rank = (name) => name === "verentis.run.yaml" ? 0 : name === "manifest.yaml" ? 1 : 2;
5253
+ function mergeFileAccess(spec, additions) {
5254
+ if (!spec || additions.length === 0) return spec;
5255
+ const existing = Array.isArray(spec["file-access"]) ? spec["file-access"] : [];
5256
+ const key = (entry) => `${entry.mode}|${entry.path}|${entry.origin ? `${entry.origin.kind}:${entry.origin.id}` : ""}`;
5257
+ const seen = new Set(existing.map(key));
5258
+ const added = additions.filter((entry) => !seen.has(key(entry)) && seen.add(key(entry)));
5259
+ return added.length === 0 ? spec : { ...spec, "file-access": [...existing, ...added] };
5260
+ }
4600
5261
 
4601
5262
  // src/vpkg/pack.ts
4602
5263
  async function pack(options) {
@@ -4607,15 +5268,15 @@ async function pack(options) {
4607
5268
  throw new Error("Use either --set-version or --bump-version, not both.");
4608
5269
  }
4609
5270
  const overlayPath = resolveOverlayPath(projectDir, { env: options.env, overlay: options.overlay });
4610
- const overlay = overlayPath ? await loadOverlay(overlayPath) : void 0;
5271
+ const overlay = overlayPath ? await loadOverlay(overlayPath, options.params) : void 0;
4611
5272
  if (options.bumpVersion) {
4612
5273
  const nextVersion = await bumpManifestPatchVersion(manifestPath, base.metadata.version);
4613
5274
  base.metadata.version = nextVersion;
4614
5275
  }
4615
5276
  let manifest = overlay ? applyOverlay(base, overlay) : base;
4616
5277
  let overrideApplied = overlayPath !== void 0 || options.bumpVersion === true;
4617
- if (options.name !== void 0) {
4618
- manifest = { ...manifest, metadata: { ...manifest.metadata, "package-id": options.name } };
5278
+ if (options.packageId !== void 0) {
5279
+ manifest = { ...manifest, metadata: { ...manifest.metadata, id: options.packageId } };
4619
5280
  overrideApplied = true;
4620
5281
  }
4621
5282
  if (options.version !== void 0) {
@@ -4631,27 +5292,46 @@ async function pack(options) {
4631
5292
  if (marketplaceErrors.length > 0) throw new Error(`Invalid marketplace section: ${marketplaceErrors.join(" ")}`);
4632
5293
  const typeValidator = validatorForKind(kind);
4633
5294
  const payloadErrors = await typeValidator?.validatePayload?.(projectDir, manifest) ?? [];
4634
- if (payloadErrors.length > 0) throw new Error(`Invalid ${kind} payload:
4635
- ${payloadErrors.join("\n ")}`);
5295
+ const avatarPayloadErrors = await validateAgentAvatarPayload(projectDir, manifest);
5296
+ const allPayloadErrors = [...payloadErrors, ...avatarPayloadErrors];
5297
+ if (allPayloadErrors.length > 0) throw new Error(`Invalid ${kind} payload:
5298
+ ${allPayloadErrors.join("\n ")}`);
4636
5299
  const authoredManifest = manifest;
4637
5300
  manifest = typeValidator?.expandForPack ? typeValidator.expandForPack(manifest) : manifest;
4638
5301
  const normalizedSpec = normalizeDependencies(manifest.spec);
4639
5302
  if (normalizedSpec !== manifest.spec) manifest = { ...manifest, spec: normalizedSpec };
5303
+ const fileAccessErrors = validateFileAccess(manifest.spec?.["file-access"], "spec.file-access", MAX_PACKAGE_FILE_ACCESS);
5304
+ const scriptAccess = await collectScriptFileAccess(projectDir, manifest.spec);
5305
+ fileAccessErrors.push(...scriptAccess.errors);
5306
+ if (fileAccessErrors.length > 0) throw new Error(`Invalid file-access:
5307
+ ${fileAccessErrors.join("\n ")}`);
5308
+ const accessSpec = mergeFileAccess(manifest.spec, scriptAccess.entries);
5309
+ if (accessSpec !== manifest.spec) manifest = { ...manifest, spec: accessSpec };
5310
+ const packageAccessErrors = validateFileAccess(manifest.spec?.["file-access"], "spec.file-access", MAX_PACKAGE_FILE_ACCESS);
5311
+ if (packageAccessErrors.length > 0) throw new Error(`Invalid file-access: ${packageAccessErrors.join(" ")}`);
4640
5312
  if (manifest !== authoredManifest) overrideApplied = true;
4641
5313
  const expandedInstall = expandedInstallSources(authoredManifest, manifest);
4642
- const packageId = manifest.metadata["package-id"].toLowerCase();
4643
- const name = manifest.metadata.name.toLowerCase();
5314
+ const packageId = manifest.metadata.id.toLowerCase();
4644
5315
  const publisher = options.publisher.toLowerCase();
4645
5316
  validatePackageName(packageId, "package ID");
4646
- validatePackageName(name, "runtime name");
4647
5317
  validatePackageName(publisher, "publisher name");
4648
5318
  const version = manifest.metadata.version;
4649
5319
  const payloadFiles = await resolvePayloadFiles(projectDir, manifestPath, manifest);
5320
+ const avatarInclusionErrors = validateAgentAvatarPayloadFiles(manifest, payloadFiles);
5321
+ if (avatarInclusionErrors.length > 0) throw new Error(`Invalid ${kind} payload:
5322
+ ${avatarInclusionErrors.join("\n ")}`);
4650
5323
  const missingSources = expandedInstall.filter((from) => !payloadFiles.some((file) => toEntryPath2(file) === from));
4651
5324
  if (missingSources.length > 0) {
4652
5325
  throw new Error(`packaging.files does not include ${missingSources.join(", ")} declared by spec.assets.`);
4653
5326
  }
4654
5327
  const templatePlan = await createTemplatePlan(projectDir, manifest, payloadFiles);
5328
+ const argumentErrors = await checkScriptArgumentDescriptors(
5329
+ projectDir,
5330
+ payloadFiles,
5331
+ (file) => readTemplatedPayloadBytes(projectDir, file, templatePlan)
5332
+ );
5333
+ if (argumentErrors.length > 0) throw new Error(`Invalid script argument descriptors:
5334
+ ${argumentErrors.join("\n ")}`);
4655
5335
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
4656
5336
  const packedManifest = stripTemplatePackagingFields(manifest);
4657
5337
  const manifestSanitized = packedManifest !== manifest;
@@ -4673,15 +5353,21 @@ async function pack(options) {
4673
5353
  const digests = {
4674
5354
  "manifest.yaml": sha256Hex(Buffer.from(manifestText, "utf8"))
4675
5355
  };
5356
+ const documentErrors = [];
4676
5357
  for (const file of payloadFiles) {
4677
5358
  const entryName = `files/${toEntryPath2(file)}`;
4678
5359
  const targetPath = join(staging, "files", file);
4679
5360
  await mkdir(dirname(targetPath), { recursive: true });
4680
5361
  const payloadBytes = await readTemplatedPayloadBytes(projectDir, file, templatePlan);
5362
+ if (/\.ya?ml$/i.test(file)) {
5363
+ documentErrors.push(...payloadDocumentMetadataErrors(Buffer.from(payloadBytes).toString("utf8")).map((message) => `${toEntryPath2(file)}: ${message}`));
5364
+ }
4681
5365
  const bytes = contentKey ? encryptBytes(contentKey, payloadBytes) : payloadBytes;
4682
5366
  await writeFile(targetPath, bytes);
4683
5367
  digests[entryName] = sha256Hex(bytes);
4684
5368
  }
5369
+ if (documentErrors.length > 0) throw new Error(`Invalid documents:
5370
+ ${documentErrors.join("\n ")}`);
4685
5371
  if (catalog) {
4686
5372
  for (const entry of catalog.entries) {
4687
5373
  const targetPath = join(staging, entry.path);
@@ -4705,12 +5391,11 @@ async function pack(options) {
4705
5391
  const digestsJson = JSON.stringify({ algorithm: "sha256", entries: digests }, null, 2);
4706
5392
  await writeFile(join(staging, ".verentis", "digests.json"), digestsJson);
4707
5393
  const packageYaml = [
4708
- `package-id: ${packageId}`,
4709
- `name: ${name}`,
5394
+ `id: ${packageId}`,
4710
5395
  `publisher: ${publisher}`,
4711
5396
  `version: ${version}`,
4712
5397
  `kind: ${kind}`,
4713
- ...manifest.metadata["display-name"] ? [`display-name: ${JSON.stringify(manifest.metadata["display-name"])}`] : [],
5398
+ ...manifest.metadata.name ? [`name: ${JSON.stringify(manifest.metadata.name)}`] : [],
4714
5399
  ""
4715
5400
  ].join("\n");
4716
5401
  await writeFile(join(staging, ".verentis", "package.yaml"), packageYaml);
@@ -4737,7 +5422,6 @@ async function pack(options) {
4737
5422
  return {
4738
5423
  outFile,
4739
5424
  packageId,
4740
- name,
4741
5425
  publisher,
4742
5426
  version,
4743
5427
  kind,
@@ -4777,8 +5461,8 @@ async function readVpkg(vpkgPath) {
4777
5461
  throw new Error("Invalid package: missing .verentis/digests.json.");
4778
5462
  });
4779
5463
  const metadata = parse(packageYaml);
4780
- if (!metadata?.["package-id"]) {
4781
- throw new Error("Invalid package: .verentis/package.yaml is missing package-id.");
5464
+ if (!metadata?.id) {
5465
+ throw new Error("Invalid package: .verentis/package.yaml is missing id.");
4782
5466
  }
4783
5467
  const declared = JSON.parse(digestsJson);
4784
5468
  const files2 = await listFiles(staging, "files/**/*");
@@ -4855,8 +5539,10 @@ async function readJsonIfExists(path) {
4855
5539
  }
4856
5540
 
4857
5541
  // src/commands/pack.ts
5542
+ var noSigningKeyMessage = "No signing key configured. Packages must be signed to be published \u2014 run `verentis keygen` to create and register one (or pass --key <name>). Use --no-sign only for local, unpublishable test packages.";
4858
5543
  function registerPack(program2) {
4859
- program2.command("pack [dir]").description("Build a signed .vpkg from a project directory").option("--manifest <path>", "manifest path (default: auto-detected in the project directory)").option("--publisher <name>", "publisher name (default: packaging.publisher in the manifest)").option("--name <name>", "override metadata.package-id").option("--env <name>", "merge a per-environment overlay (environments/<name>.yaml) before packing").option("--overlay <path>", "merge an explicit overlay file before packing (wins over --env)").option("--set-version <version>", "override metadata.version (e.g. a CI-derived build number)").option("--bump-version", "increment metadata.version.patch and update the manifest").option("--bump", "alias for --bump-version").option("--out <dir>", "output directory (default: the project directory)").option("--key <name>", "signing key name (default: the configured default key)").option("--no-sign", "produce an unsigned package").option("--encrypt", "seal the payload (AES-256-GCM); requires at least one recipient").option("--recipient <id=base64key...>", "additional X25519 recipient (repeatable)", collectRecipients, []).action(async (dir, options) => {
5544
+ program2.command("pack [dir]").description("Build a signed .vpkg from a project directory").option("--manifest <path>", "manifest path (default: auto-detected in the project directory)").option("--publisher <name>", "publisher name (default: packaging.publisher in the manifest)").option("--id <id>", "override metadata.id").option("--env <name>", "merge a per-environment overlay (environments/<name>.yaml) before packing").option("--overlay <path>", "merge an explicit overlay file before packing (wins over --env)").option("--param <name=value>", "value for a ${param:name} placeholder in the overlay (repeatable)", collectParams, []).option("--set-version <version>", "override metadata.version (e.g. a CI-derived build number)").option("--bump-version", "increment metadata.version.patch and update the manifest").option("--bump", "alias for --bump-version").option("--out <dir>", "output directory (default: the project directory)").option("--key <name>", "signing key name (default: the configured default key)").option("--no-sign", "produce an unsigned package for local testing (the registry will not accept it)").option("--encrypt", "seal the payload (AES-256-GCM); requires at least one recipient").option("--recipient <id=base64key...>", "additional X25519 recipient (repeatable)", collectRecipients, []).action(async (dir, options) => {
5545
+ const params = parseOverlayParams(options.param);
4860
5546
  const projectDir = resolve(dir ?? ".");
4861
5547
  const manifestPath = options.manifest ? resolve(options.manifest) : await findManifest(projectDir);
4862
5548
  await ensurePackageTypeKnown((await readManifestDocument(manifestPath)).kind);
@@ -4869,11 +5555,10 @@ function registerPack(program2) {
4869
5555
  let signingKey;
4870
5556
  if (options.sign) {
4871
5557
  const keyName = options.key ?? config.defaultKey;
4872
- if (keyName) {
4873
- signingKey = await loadKey(keyName);
4874
- } else {
4875
- console.warn("Warning: no signing key configured \u2014 producing an UNSIGNED package. Run `verentis keygen` to create one.");
4876
- }
5558
+ if (!keyName) throw new Error(noSigningKeyMessage);
5559
+ signingKey = await loadKey(keyName);
5560
+ } else {
5561
+ console.warn("Warning: --no-sign produces an UNSIGNED package. The registry rejects unsigned packages, so it cannot be published.");
4877
5562
  }
4878
5563
  let encryptFor;
4879
5564
  if (options.encrypt || manifest.packaging?.encryption === "required") {
@@ -4891,9 +5576,10 @@ function registerPack(program2) {
4891
5576
  const result = await pack({
4892
5577
  manifestPath,
4893
5578
  publisher,
4894
- name: options.name,
5579
+ packageId: options.id,
4895
5580
  env: options.env,
4896
5581
  overlay: options.overlay,
5582
+ params,
4897
5583
  version: options.setVersion,
4898
5584
  bumpVersion: options.bumpVersion || options.bump,
4899
5585
  outDir: options.out,
@@ -4914,7 +5600,7 @@ function registerPack(program2) {
4914
5600
  });
4915
5601
  program2.command("verify <vpkg>").description("Verify the digests (and, when possible, the developer signature) of a .vpkg").option("--key <name>", "verify the developer signature against a local key").action(async (vpkgPath, options) => {
4916
5602
  const contents = await readVpkg(resolve(vpkgPath));
4917
- console.log(`${contents.metadata.publisher}/${contents.metadata["package-id"]}@${contents.metadata.version} (${contents.metadata.kind})`);
5603
+ console.log(`${contents.metadata.publisher}/${contents.metadata.id}@${contents.metadata.version} (${contents.metadata.kind})`);
4918
5604
  console.log(` payload files: ${contents.files.length}, catalog files: ${contents.catalogFiles.length}, tree digest ${contents.treeDigest.slice(0, 16)}\u2026`);
4919
5605
  if (contents.catalog) {
4920
5606
  const docs = Number(!!contents.catalog.readme) + Number(!!contents.catalog.changelog);
@@ -4948,6 +5634,9 @@ function registerPack(program2) {
4948
5634
  if (contents.marketplaceSignature) console.log(" \u2713 marketplace countersignature present");
4949
5635
  });
4950
5636
  }
5637
+ function collectParams(value, previous) {
5638
+ return [...previous, value];
5639
+ }
4951
5640
  function collectRecipients(value, previous) {
4952
5641
  const eq = value.indexOf("=");
4953
5642
  if (eq <= 0) throw new Error(`Invalid --recipient '${value}' \u2014 expected id=base64PublicKey.`);
@@ -4957,66 +5646,59 @@ function collectRecipients(value, previous) {
4957
5646
  // src/commands/package.ts
4958
5647
  function registerPackage(program2) {
4959
5648
  const pkgCmd = program2.command("package").description("Manage marketplace packages");
4960
- pkgCmd.command("list").description("List your publisher's packages").option("--json", "output JSON").action(async (options) => {
5649
+ pkgCmd.command("list").description("List your publisher's packages in the registry").option("--json", "output JSON").action(async (options) => {
4961
5650
  const api = await createApiClient();
4962
- const publisher = await requireMyPublisher(api);
4963
- const page = await call(api, marketplace.listPublisherPackages, {
4964
- params: { publisherId: publisher.id },
4965
- query: { PageNo: 1, PageSize: 100 }
4966
- });
4967
- output(pageItems(page), { packageId: "Package", name: "Runtime", kind: "Kind", visibility: "Visibility", latestPublishedVersion: "Latest", id: "Id" }, options, page);
5651
+ const publisher = await requireRegistryPublisher(api);
5652
+ if (!publisher.name) throw new Error("Cannot resolve your publisher name. Run `verentis login` again.");
5653
+ const packages = await listRegistryPackages(api, publisher.name);
5654
+ output(
5655
+ packages.map((p) => ({ ...p, versionCount: p.versions.length })),
5656
+ { packageId: "Package", kind: "Kind", visibility: "Visibility", latestVersion: "Latest", versionCount: "Versions", archived: "Archived", id: "Id" },
5657
+ options
5658
+ );
4968
5659
  });
4969
- pkgCmd.command("info <ref>").description("Show package details (ref: 'package-id' or 'publisher/package-id')").option("--json", "output JSON").action(async (ref, options) => {
5660
+ pkgCmd.command("info <ref>").description("Show a package from the registry (ref: 'package-id' or 'publisher/package-id')").option("--json", "output JSON").action(async (ref, options) => {
4970
5661
  const api = await createApiClient();
4971
- const { package: pkg } = await resolvePackageRef(api, ref);
4972
- const detail = await call(api, marketplace.getPackage, { params: { id: pkg.id } });
4973
- outputRecord(detail, options);
5662
+ const { versions, ...pkg } = await getRegistryPackage(api, await resolveRegistryPackageRef(api, ref));
5663
+ outputRecord({ ...pkg, versionCount: versions.length }, options);
4974
5664
  });
4975
- pkgCmd.command("versions <ref>").description("List versions of a package").option("--json", "output JSON").action(async (ref, options) => {
5665
+ pkgCmd.command("versions <ref>").description("List every version of a package in the registry, including pending, rejected and yanked ones").option("--json", "output JSON").action(async (ref, options) => {
4976
5666
  const api = await createApiClient();
4977
- const { package: pkg } = await resolvePackageRef(api, ref);
4978
- const page = await call(api, marketplace.listVersions, {
4979
- params: { packageId: pkg.id },
4980
- query: { PageNo: 1, PageSize: 100 }
4981
- });
4982
- output(pageItems(page), { version: "Version", status: "Status", sizeBytes: "Size", hasMarketplaceSignature: "Countersigned", id: "Id" }, options, page);
5667
+ const pkg = await getRegistryPackage(api, await resolveRegistryPackageRef(api, ref));
5668
+ output(pkg.versions.map((v) => ({ ...v })), { version: "Version", status: "Status", deprecated: "Deprecated", publishedAt: "Published", yankedAt: "Yanked", sizeBytes: "Size", id: "Id" }, options);
4983
5669
  });
4984
- pkgCmd.command("update <ref>").description("Update package metadata").option("--display-name <displayName>").option("--description <description>").option("--icon <icon>").option("--categories <category...>", "category list (replaces existing)").action(async (ref, options) => {
4985
- const api = await createApiClient();
4986
- const { package: pkg } = await resolvePackageRef(api, ref);
4987
- const current2 = await call(api, marketplace.getPackage, { params: { id: pkg.id } });
4988
- await call(api, marketplace.updatePackage, {
4989
- params: { id: pkg.id },
4990
- body: {
4991
- id: pkg.id,
4992
- displayName: options.displayName ?? current2.displayName,
4993
- description: options.description ?? current2.description ?? null,
4994
- icon: options.icon ?? current2.icon ?? null,
4995
- categories: options.categories ?? current2.categories ?? []
4996
- }
4997
- });
4998
- console.log(`Package ${ref} updated.`);
5670
+ pkgCmd.command("update <ref>").description("(removed) Package metadata comes from the signed manifest \u2014 edit it, `verentis pack`, then `verentis publish`").allowUnknownOption().action(() => {
5671
+ throw new Error(
5672
+ "Package metadata (display name, description, icon, categories) is part of the signed manifest. Edit manifest.yaml, then run `verentis pack` and `verentis publish` to submit a new version."
5673
+ );
4999
5674
  });
5000
- pkgCmd.command("deprecate <ref>").description("Mark a package as deprecated (optionally with a successor)").option("--message <message>", "deprecation message shown in the catalog").option("--replacement <packageId>", "suggested replacement package id").action(async (ref, options) => {
5675
+ pkgCmd.command("deprecate <ref> [version]").description("Mark a package (or one published version) as deprecated in the registry").option("--message <message>", "deprecation message shown in the catalog").action(async (ref, version, options) => {
5001
5676
  const api = await createApiClient();
5002
- const { package: pkg } = await resolvePackageRef(api, ref);
5003
- await call(api, marketplace.deprecatePackage, {
5004
- params: { id: pkg.id },
5005
- body: { id: pkg.id, message: options.message ?? null, replacementPackageId: options.replacement ?? null }
5006
- });
5007
- console.log(`Package ${ref} deprecated.`);
5677
+ const target = await resolveRegistryPackageRef(api, ref);
5678
+ if (version) {
5679
+ await deprecateVersion(api, target, version, options.message);
5680
+ console.log(`Version ${target.publisher}/${target.packageId}@${version} deprecated.`);
5681
+ } else {
5682
+ await deprecatePackage(api, target, options.message);
5683
+ console.log(`Package ${target.publisher}/${target.packageId} deprecated.`);
5684
+ }
5008
5685
  });
5009
- pkgCmd.command("undeprecate <ref>").description("Remove the deprecation flag from a package").action(async (ref) => {
5686
+ pkgCmd.command("undeprecate <ref> [version]").description("Remove the deprecation flag from a package (or one version)").action(async (ref, version) => {
5010
5687
  const api = await createApiClient();
5011
- const { package: pkg } = await resolvePackageRef(api, ref);
5012
- await call(api, marketplace.undeprecatePackage, { params: { id: pkg.id } });
5013
- console.log(`Package ${ref} restored.`);
5688
+ const target = await resolveRegistryPackageRef(api, ref);
5689
+ if (version) {
5690
+ await undeprecateVersion(api, target, version);
5691
+ console.log(`Version ${target.publisher}/${target.packageId}@${version} restored.`);
5692
+ } else {
5693
+ await undeprecatePackage(api, target);
5694
+ console.log(`Package ${target.publisher}/${target.packageId} restored.`);
5695
+ }
5014
5696
  });
5015
- pkgCmd.command("archive <ref>").description("Archive (soft-delete) a package \u2014 it disappears from the catalog").action(async (ref) => {
5697
+ pkgCmd.command("archive <ref>").description("Archive a package in the registry \u2014 it is hidden from the catalog and no longer installable").action(async (ref) => {
5016
5698
  const api = await createApiClient();
5017
- const { package: pkg } = await resolvePackageRef(api, ref);
5018
- await call(api, marketplace.archivePackage, { params: { id: pkg.id } });
5019
- console.log(`Package ${ref} archived.`);
5699
+ const target = await resolveRegistryPackageRef(api, ref);
5700
+ await archivePackage(api, target);
5701
+ console.log(`Package ${target.publisher}/${target.packageId} archived.`);
5020
5702
  });
5021
5703
  pkgCmd.command("stats <ref>").description("Show download/install statistics for a package").action(async (ref) => {
5022
5704
  const api = await createApiClient();
@@ -5024,32 +5706,31 @@ function registerPackage(program2) {
5024
5706
  const stats = await call(api, marketplace.getPackageStats, { params: { packageId: pkg.id } });
5025
5707
  printJson(stats);
5026
5708
  });
5027
- const visibilityCmd = pkgCmd.command("visibility").description("Manage private-package visibility");
5709
+ const visibilityCmd = pkgCmd.command("visibility").description("Manage package visibility in the registry");
5028
5710
  visibilityCmd.command("set <ref> <visibility>").description("Set catalog visibility: Public | Private").action(async (ref, visibility) => {
5711
+ const value = parseVisibility(visibility);
5029
5712
  const api = await createApiClient();
5030
- const { package: pkg } = await resolvePackageRef(api, ref);
5031
- await call(api, marketplace.setPackageVisibility, { params: { id: pkg.id }, body: { id: pkg.id, visibility } });
5032
- console.log(`Package ${ref} visibility \u2192 ${visibility}.`);
5713
+ const target = await resolveRegistryPackageRef(api, ref);
5714
+ await setPackageVisibility(api, target, value);
5715
+ console.log(`Package ${target.publisher}/${target.packageId} visibility \u2192 ${value}.`);
5033
5716
  });
5034
5717
  visibilityCmd.command("grants <ref>").description("List visibility grants of a private package").option("--json", "output JSON").action(async (ref, options) => {
5035
5718
  const api = await createApiClient();
5036
- const { package: pkg } = await resolvePackageRef(api, ref);
5037
- const grants = await call(api, marketplace.listVisibilityGrants, { params: { packageId: pkg.id } });
5038
- output(grants ?? [], { granteeType: "Type", granteeId: "Grantee", id: "GrantId" }, options, grants);
5719
+ const target = await resolveRegistryPackageRef(api, ref);
5720
+ const grants = await listVisibilityGrants(api, target);
5721
+ output(grants, { granteeType: "Type", granteeId: "Grantee", id: "GrantId" }, options, grants);
5039
5722
  });
5040
5723
  visibilityCmd.command("grant <ref> <granteeId>").description("Grant a workspace/account visibility of a private package").option("--type <granteeType>", "Workspace | Account", "Workspace").action(async (ref, granteeId, options) => {
5724
+ const granteeType = parseGranteeType(options.type);
5041
5725
  const api = await createApiClient();
5042
- const { package: pkg } = await resolvePackageRef(api, ref);
5043
- await call(api, marketplace.grantVisibility, {
5044
- params: { packageId: pkg.id },
5045
- body: { packageId: pkg.id, granteeType: options.type, granteeId }
5046
- });
5047
- console.log(`Visibility of ${ref} granted to ${options.type} ${granteeId}.`);
5726
+ const target = await resolveRegistryPackageRef(api, ref);
5727
+ const grant = await grantVisibility(api, target, granteeType, granteeId);
5728
+ console.log(`Visibility of ${target.publisher}/${target.packageId} granted to ${granteeType} ${granteeId}${grant?.id ? ` (grant ${grant.id})` : ""}.`);
5048
5729
  });
5049
5730
  visibilityCmd.command("revoke <ref> <grantId>").description("Revoke a visibility grant").action(async (ref, grantId) => {
5050
5731
  const api = await createApiClient();
5051
- const { package: pkg } = await resolvePackageRef(api, ref);
5052
- await call(api, marketplace.revokeVisibility, { params: { packageId: pkg.id, grantId } });
5732
+ const target = await resolveRegistryPackageRef(api, ref);
5733
+ await revokeVisibility(api, target, grantId);
5053
5734
  console.log(`Visibility grant ${grantId} revoked.`);
5054
5735
  });
5055
5736
  program2.command("installs").description("List package installations in a workspace").option("--workspace <workspaceId>").option("--page <n>").option("--page-size <n>").option("--json", "output JSON").action(async (options) => {
@@ -5060,8 +5741,58 @@ function registerPackage(program2) {
5060
5741
  output(pageItems(page), { packageName: "Package", version: "Version", status: "Status", installPath: "Path", id: "Id" }, options, page);
5061
5742
  });
5062
5743
  }
5063
- var POLICY_READ_SCOPE = "fabric.policy.read";
5064
- var POLICY_UPDATE_SCOPE = "fabric.policy.update";
5744
+
5745
+ // src/commands/notifications.ts
5746
+ function registerNotifications(program2) {
5747
+ const notifications = program2.command("notifications").description("Manage package notification delivery");
5748
+ const sender = notifications.command("sender").description("Manage a package email sender connection");
5749
+ sender.command("show <package>").description("Show the configured notification email sender without revealing its API key").option("--json", "output JSON").action(async (packageRef, options) => {
5750
+ const { api, publisherId, packageOwner } = await resolveSenderTarget(packageRef);
5751
+ const status = await getPublisherEmailSender(api, publisherId, packageOwner);
5752
+ outputRecord({
5753
+ packageOwner: status.packageOwner,
5754
+ provider: status.provider,
5755
+ from: status.from,
5756
+ replyTo: status.replyTo,
5757
+ domain: status.domain,
5758
+ region: status.region,
5759
+ keyLastFour: status.keyLastFour,
5760
+ keyFingerprint: status.keyFingerprint,
5761
+ validationStatus: status.validationStatus,
5762
+ validationMessage: status.validationMessage,
5763
+ validatedAt: status.validatedAt,
5764
+ version: status.version,
5765
+ revoked: status.revoked,
5766
+ webhookStatus: status.webhookStatus,
5767
+ webhookMessage: status.webhookMessage,
5768
+ webhookUrl: status.webhookUrl
5769
+ }, options);
5770
+ });
5771
+ sender.command("revoke <package>").description("Revoke a package email sender connection").action(async (packageRef) => {
5772
+ const { api, publisherId, packageOwner, publisherName } = await resolveSenderTarget(packageRef);
5773
+ const status = await revokePublisherEmailSender(api, publisherId, packageOwner);
5774
+ console.log(`Revoked notification sender for ${publisherName}/${packageOwner} (version ${status.version}).`);
5775
+ });
5776
+ }
5777
+ async function resolveSenderTarget(packageRef) {
5778
+ const api = await createApiClient();
5779
+ const publisher = await requireRegistryPublisher(api);
5780
+ if (!publisher.name) {
5781
+ throw new Error("Cannot resolve your publisher name. Run `verentis login` again.");
5782
+ }
5783
+ const target = await resolveRegistryPackageRef(api, packageRef);
5784
+ if (target.publisher.toLowerCase() !== publisher.name.toLowerCase()) {
5785
+ throw new Error("You can only manage notification senders for your own publisher packages.");
5786
+ }
5787
+ return {
5788
+ api,
5789
+ publisherId: publisher.id,
5790
+ publisherName: publisher.name,
5791
+ packageOwner: target.packageId.toLowerCase()
5792
+ };
5793
+ }
5794
+ var POLICY_READ_SCOPE = "governance.read";
5795
+ var POLICY_UPDATE_SCOPE = "governance.write";
5065
5796
  function registerPolicy(program2) {
5066
5797
  const policyCmd = program2.command("policy").description("Export and apply workspace policy manifests");
5067
5798
  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) => {
@@ -5189,29 +5920,9 @@ function unsupportedLogoError() {
5189
5920
 
5190
5921
  // src/commands/publisher.ts
5191
5922
  function registerPublisher(program2) {
5192
- const publisherCmd = program2.command("publisher").description("Manage your publisher profile");
5193
- publisherCmd.command("create").description("Onboard your account as a marketplace publisher").requiredOption("--name <name>", "URL-safe publisher name (e.g. acme)").requiredOption("--display-name <displayName>", "human-readable publisher name").option("--description <description>").option("--website <url>").option("--email <email>").option("--logo <file>", "PNG, JPEG, WebP or SVG logo (maximum 1 MiB)").action(async (options) => {
5194
- const api = await createApiClient();
5195
- const existing = await getMyPublisher(api);
5196
- if (existing) {
5197
- console.log(`This account already has publisher '${existing.name}'.`);
5198
- return;
5199
- }
5200
- const id = await call(api, marketplace.createPublisher, {
5201
- body: {
5202
- name: options.name,
5203
- displayName: options.displayName,
5204
- description: options.description ?? null,
5205
- websiteUrl: options.website ?? null,
5206
- contactEmail: options.email ?? null
5207
- }
5208
- });
5209
- console.log(`Publisher '${options.name}' created (${id}).`);
5210
- if (options.logo) {
5211
- await uploadPublisherLogo(api, id, options.logo);
5212
- console.log(`Publisher logo uploaded from ${options.logo}.`);
5213
- }
5214
- console.log("Next: generate and register a signing key with `verentis keygen`.");
5923
+ const publisherCmd = program2.command("publisher").description("Manage your publisher profile (global registry)");
5924
+ publisherCmd.command("create").description("Publishers are created in the account app (they belong to an account)").allowUnknownOption().allowExcessArguments().action(async () => {
5925
+ throw new Error(noPublisherMessage(requireApiUrl(await loadConfig())));
5215
5926
  });
5216
5927
  publisherCmd.command("update").description("Update your publisher profile").option("--display-name <displayName>").option("--description <description>").option("--website <url>").option("--email <email>").action(async (options) => {
5217
5928
  if (Object.values(options).every((value) => value === void 0)) {
@@ -5222,7 +5933,6 @@ function registerPublisher(program2) {
5222
5933
  await call(api, marketplace.updatePublisher, {
5223
5934
  params: { id: current2.id },
5224
5935
  body: {
5225
- id: current2.id,
5226
5936
  displayName: options.displayName ?? current2.displayName,
5227
5937
  description: options.description ?? current2.description ?? null,
5228
5938
  websiteUrl: options.website ?? current2.websiteUrl ?? null,
@@ -5259,8 +5969,8 @@ function isNewerVersion(candidate, base) {
5259
5969
  return compareVersions(candidate, base) > 0;
5260
5970
  }
5261
5971
  function compareVersions(a, b) {
5262
- const pa = parse6(a);
5263
- const pb = parse6(b);
5972
+ const pa = parse7(a);
5973
+ const pb = parse7(b);
5264
5974
  for (let i = 0; i < 3; i++) {
5265
5975
  if (pa.main[i] !== pb.main[i]) return pa.main[i] < pb.main[i] ? -1 : 1;
5266
5976
  }
@@ -5287,7 +5997,7 @@ function compareVersions(a, b) {
5287
5997
  }
5288
5998
  return 0;
5289
5999
  }
5290
- function parse6(version) {
6000
+ function parse7(version) {
5291
6001
  const cleaned = version.trim().replace(/^v/i, "").split("+", 1)[0];
5292
6002
  const dash = cleaned.indexOf("-");
5293
6003
  const core = dash === -1 ? cleaned : cleaned.slice(0, dash);
@@ -5301,17 +6011,7 @@ async function installGraph(api, workspaceId, packageId, options) {
5301
6011
  if (options.operation || options.consent) {
5302
6012
  if (!options.operation || !options.consent) throw new Error("--operation and --consent must be supplied together.");
5303
6013
  const result = await api.request("POST", "/v1/installations/graphs", {
5304
- scopes: [
5305
- SCOPES.installCreate,
5306
- "marketplace.install.update",
5307
- NODE.nodeCreate,
5308
- NODE.fileRead,
5309
- NODE.fileDelete,
5310
- NODE.nodeUpdate,
5311
- NODE.journalCreate,
5312
- SCOPES.resourceReadAll,
5313
- SCOPES.resourceUpdate
5314
- ],
6014
+ scopes: [SCOPES.installCreate, NODE.nodeCreate, NODE.fileRead, NODE.fileDelete, SCOPES.installationRead, SCOPES.resourceReadAll],
5315
6015
  tokenWorkspaceId: workspaceId,
5316
6016
  body: { workspaceId, operationId: options.operation, fingerprint: options.consent, consent: true }
5317
6017
  });
@@ -5320,7 +6020,7 @@ async function installGraph(api, workspaceId, packageId, options) {
5320
6020
  return;
5321
6021
  }
5322
6022
  const preview = await api.request("POST", "/v1/installations/graphs/preview", {
5323
- scopes: [SCOPES.installCreate],
6023
+ scopes: [SCOPES.installRead],
5324
6024
  tokenWorkspaceId: workspaceId,
5325
6025
  body: {
5326
6026
  workspaceId,
@@ -5336,6 +6036,7 @@ async function installGraph(api, workspaceId, packageId, options) {
5336
6036
  }
5337
6037
 
5338
6038
  // src/commands/registry.ts
6039
+ var unsignedPublishMessage = "Refusing to publish: the package is unsigned. Packages must be signed \u2014 run `verentis keygen`, then `verentis pack` again.";
5339
6040
  async function findLatestLocalVpkg(directory) {
5340
6041
  const entries = await readdir(directory, { withFileTypes: true });
5341
6042
  const candidates = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".vpkg")).map((entry) => resolve(directory, entry.name));
@@ -5354,45 +6055,118 @@ async function findLatestLocalVpkg(directory) {
5354
6055
  return latest.path;
5355
6056
  }
5356
6057
  function registerRegistry(program2) {
5357
- program2.command("publish [vpkg]").description("Upload a packed .vpkg to the marketplace registry (creates the package on first publish)").option("--visibility <visibility>", "catalog visibility for a newly created package: Public | Private", "Private").action(async (vpkgPath, options) => {
6058
+ program2.command("publish [vpkg]").description("Upload a packed .vpkg to the marketplace registry (creates the package on first publish)").option("--visibility <visibility>", "catalog visibility applied when the package is first created: Public | Private", "Private").option("--notifications.api-key <apiKey>", "email provider key for this package (prefer VERENTIS_NOTIFICATIONS_API_KEY in CI)").option("--notifications.webhook-signing-key <key>", "Mailgun webhook signing key (prefer VERENTIS_NOTIFICATIONS_WEBHOOK_SIGNING_KEY in CI)").option("--notifications.provider <provider>", "notification email provider (sticky per package)").option("--notifications.from <address>", "notification sender address (sticky per package)").option("--notifications.reply-to <address>", "notification reply-to address (sticky per package)").option("--notifications.domain <domain>", "Mailgun sending domain (sticky per package)").option("--notifications.region <region>", "provider region (sticky per package)").action(async (vpkgPath, options) => {
5358
6059
  const selectedPath = vpkgPath ? resolve(vpkgPath) : await findLatestLocalVpkg(process.cwd());
5359
6060
  const contents = await readVpkg(selectedPath);
5360
6061
  if (contents.digestErrors.length > 0) {
5361
6062
  throw new Error(`Refusing to publish: package failed digest verification:
5362
6063
  ${contents.digestErrors.join("\n ")}`);
5363
6064
  }
6065
+ if (!contents.developerSignature) {
6066
+ throw new Error(unsignedPublishMessage);
6067
+ }
5364
6068
  const api = await createApiClient();
5365
6069
  const config = await loadConfig();
6070
+ const apiKey = options["notifications.apiKey"] ?? process.env.VERENTIS_NOTIFICATIONS_API_KEY;
6071
+ const webhookSigningKey = options["notifications.webhookSigningKey"] ?? process.env.VERENTIS_NOTIFICATIONS_WEBHOOK_SIGNING_KEY;
6072
+ if (webhookSigningKey && !apiKey) {
6073
+ throw new Error("Provide the notification provider API key when setting its webhook signing key.");
6074
+ }
5366
6075
  await refreshPackageTypes(requireApiUrl(config), { insecure: config.insecure });
5367
- const publisher = await requireMyPublisher(api);
5368
- if (publisher.name !== contents.metadata.publisher) {
6076
+ const publisher = await requireRegistryPublisher(api);
6077
+ if (publisher.name && publisher.name !== contents.metadata.publisher) {
5369
6078
  throw new Error(`Package declares publisher '${contents.metadata.publisher}' but you are '${publisher.name}'.`);
5370
6079
  }
5371
- let pkg = await findPackageByPackageId(api, publisher.id, contents.metadata["package-id"]);
5372
- if (!pkg) {
5373
- const visibility = options.visibility === "Public" ? "Public" : "Private";
5374
- const id = await createPackage(api, {
5375
- publisherId: publisher.id,
5376
- packageId: contents.metadata["package-id"],
5377
- name: contents.metadata.name,
5378
- displayName: contents.metadata["display-name"] ?? contents.metadata.name,
5379
- kind: contents.metadata.kind,
5380
- visibility
5381
- });
5382
- console.log(`Created package ${publisher.name}/${contents.metadata["package-id"]} (${visibility.toLowerCase()}).`);
5383
- pkg = { id };
5384
- }
5385
- const version = await uploadVersion(api, pkg.id, selectedPath);
5386
- console.log(`Published ${publisher.name}/${contents.metadata["package-id"]}@${version.version} \u2192 ${version.status}`);
6080
+ const visibility = options.visibility === "Public" ? "Public" : "Private";
6081
+ const packageId = contents.metadata.id;
6082
+ const requested = contents.metadata.version;
6083
+ const alreadyPublished = async () => {
6084
+ const existing = await findRegistryVersion(api, contents.metadata.publisher, packageId, requested);
6085
+ if (!existing) return false;
6086
+ if (!sameTreeDigest(existing.treeDigest, contents.treeDigest)) {
6087
+ throw new Error(`${contents.metadata.publisher}/${packageId}@${requested} already exists with different content. Versions are immutable; publish a new version.`);
6088
+ }
6089
+ console.log(`Already published ${contents.metadata.publisher}/${packageId}@${requested} (identical tree digest) \u2192 ${existing.status}`);
6090
+ return true;
6091
+ };
6092
+ if (await alreadyPublished()) return;
6093
+ const version = await uploadRegistryVersion(api, contents.metadata.publisher, packageId, selectedPath, { visibility }).catch(async (error) => {
6094
+ if (error instanceof ApiError && error.status === 422 && await alreadyPublished()) return null;
6095
+ const detail = error instanceof ApiError && error.status === 422 ? problemDetail(error) : void 0;
6096
+ throw detail ? new Error(`Publish rejected: ${detail}`) : error;
6097
+ });
6098
+ if (!version) return;
6099
+ console.log(`Published ${contents.metadata.publisher}/${packageId}@${version.version} \u2192 ${version.status}`);
5387
6100
  if (version.status === "Submitted") {
5388
6101
  console.log("The version is queued for moderation; it becomes installable once approved and published.");
5389
6102
  }
6103
+ const senderSettingsKey = `${contents.metadata.publisher}/${packageId}`;
6104
+ const storedSettings = config.notificationSenderSettings?.[senderSettingsKey] ?? {};
6105
+ const settingOptions = [
6106
+ ["provider", "notifications.provider", "VERENTIS_NOTIFICATIONS_PROVIDER"],
6107
+ ["from", "notifications.from", "VERENTIS_NOTIFICATIONS_FROM"],
6108
+ ["replyTo", "notifications.replyTo", "VERENTIS_NOTIFICATIONS_REPLY_TO"],
6109
+ ["domain", "notifications.domain", "VERENTIS_NOTIFICATIONS_DOMAIN"],
6110
+ ["region", "notifications.region", "VERENTIS_NOTIFICATIONS_REGION"]
6111
+ ];
6112
+ const resolved = { ...storedSettings };
6113
+ const updatedSettings = { ...storedSettings };
6114
+ let hasStickyUpdates = false;
6115
+ for (const [key, optionName, envName] of settingOptions) {
6116
+ const optionValue = options[optionName];
6117
+ const envValue = process.env[envName];
6118
+ if (optionValue !== void 0) {
6119
+ updatedSettings[key] = optionValue;
6120
+ hasStickyUpdates = true;
6121
+ }
6122
+ resolved[key] = optionValue ?? envValue ?? storedSettings[key];
6123
+ }
6124
+ if (hasStickyUpdates) {
6125
+ await saveConfig({
6126
+ ...config,
6127
+ notificationSenderSettings: {
6128
+ ...config.notificationSenderSettings ?? {},
6129
+ [senderSettingsKey]: updatedSettings
6130
+ }
6131
+ });
6132
+ }
6133
+ if (apiKey) {
6134
+ const missing = ["provider", "from", "region"].filter((key) => !resolved[key]);
6135
+ if (resolved.provider?.toLowerCase() === "mailgun" && !resolved.domain) missing.push("domain");
6136
+ if (missing.length > 0) {
6137
+ throw new Error(`Notification sender setup needs --notifications.${missing.join(", --notifications.")}.`);
6138
+ }
6139
+ let sender;
6140
+ try {
6141
+ sender = await setPublisherEmailSender(api, publisher.id, packageId, {
6142
+ provider: resolved.provider,
6143
+ from: resolved.from,
6144
+ replyTo: resolved.replyTo,
6145
+ domain: resolved.domain,
6146
+ region: resolved.region,
6147
+ apiKey,
6148
+ webhookSigningKey
6149
+ });
6150
+ } catch (error) {
6151
+ if (error instanceof Error) {
6152
+ let message = error.message;
6153
+ for (const secret of [apiKey, webhookSigningKey]) {
6154
+ if (secret) message = message.split(secret).join("[REDACTED]");
6155
+ }
6156
+ if (message !== error.message) throw new Error(message);
6157
+ }
6158
+ throw error;
6159
+ }
6160
+ console.log(`Configured ${sender.provider} notification sender for ${contents.metadata.publisher}/${packageId} (key ending ${sender.keyLastFour}).`);
6161
+ if (sender.webhookStatus) console.log(`Webhook: ${sender.webhookStatus}`);
6162
+ if (sender.webhookUrl) console.log(`Webhook URL: ${sender.webhookUrl}`);
6163
+ }
5390
6164
  });
5391
- program2.command("yank <ref> <version>").description("Withdraw a published version from the catalog (ref: 'name' or 'publisher/name')").action(async (ref, version) => {
6165
+ program2.command("yank <ref> <version>").description("Withdraw a published version from the registry (ref: 'package-id' or 'publisher/package-id'); existing installs keep working").option("--reason <text>", "reason shown to users of the yanked version").action(async (ref, version, options) => {
5392
6166
  const api = await createApiClient();
5393
- const { package: pkg } = await resolvePackageRef(api, ref);
5394
- await yankVersion(api, pkg.id, version);
5395
- console.log(`Yanked ${ref}@${version}.`);
6167
+ const target = await resolveRegistryPackageRef(api, ref);
6168
+ await yankVersion(api, target, version, options.reason);
6169
+ console.log(`Yanked ${target.publisher}/${target.packageId}@${version}.`);
5396
6170
  });
5397
6171
  program2.command("download <ref> [version]").description("Download a package tarball (defaults to the latest published version)").option("--out <path>", "output file path").option("--workspace <workspaceId>", "workspace context for visibility checks").action(async (ref, version, options) => {
5398
6172
  const api = await createApiClient();
@@ -5410,7 +6184,7 @@ function registerRegistry(program2) {
5410
6184
  const requested = options.type ?? options.kind;
5411
6185
  const type = requested ? packageTypes().canonical(requested) ?? requested : void 0;
5412
6186
  const page = await api.request("GET", "/v1/packages", {
5413
- scopes: [SCOPES.packageReadAll],
6187
+ scopes: [SCOPES.packageList],
5414
6188
  query: { SearchText: text, Kind: type, PageNo: 1, PageSize: 50 }
5415
6189
  });
5416
6190
  const items = page.data ?? page.items ?? [];
@@ -5458,14 +6232,14 @@ function registerRegistry(program2) {
5458
6232
  "GET",
5459
6233
  "/v1/installations",
5460
6234
  {
5461
- scopes: [MARKETPLACE.installRead],
6235
+ scopes: [MARKETPLACE.installList],
5462
6236
  tokenWorkspaceId: workspaceId,
5463
6237
  query: { workspaceId, packageId: pkg.id, branch: options.branch, pageNo: 1, pageSize: 100, orderBy: "createdAt desc" }
5464
6238
  }
5465
6239
  );
5466
6240
  const existing = pageItems(page).find((installation) => installation.status !== "Uninstalled");
5467
- const nodeScopes = [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate];
5468
- const consentScopes = isApplicationProfile(pkg.type ?? pkg.kind) ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
6241
+ const nodeScopes = [NODE.nodeCreate, NODE.fileRead];
6242
+ const consentScopes = isApplicationProfile(pkg.type ?? pkg.kind) ? [SCOPES.installationRead, SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
5469
6243
  if (existing) {
5470
6244
  if (options.path && existing.installPath !== options.path.replace(/^\/+|\/+$/g, "")) {
5471
6245
  throw new Error(`${ref} is already installed at '${existing.installPath}'. Uninstall it before moving it.`);
@@ -5582,11 +6356,11 @@ function getCliVersion() {
5582
6356
  }
5583
6357
  function readVersion() {
5584
6358
  const candidates = ["../package.json", "../../package.json"];
5585
- for (const relative6 of candidates) {
6359
+ for (const relative7 of candidates) {
5586
6360
  try {
5587
- const raw = readFileSync(fileURLToPath(new URL(relative6, import.meta.url)), "utf8");
6361
+ const raw = readFileSync(fileURLToPath(new URL(relative7, import.meta.url)), "utf8");
5588
6362
  const pkg = JSON.parse(raw);
5589
- if (pkg.version && (relative6 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
6363
+ if (pkg.version && (relative7 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
5590
6364
  } catch {
5591
6365
  }
5592
6366
  }
@@ -5798,6 +6572,7 @@ function detectPackageManager(location) {
5798
6572
  }
5799
6573
 
5800
6574
  // src/commands/use.ts
6575
+ var registryUrl2 = (apiUrl) => requireApiUrl({ apiUrl }) + REGISTRY_BASE;
5801
6576
  function registerUse(program2) {
5802
6577
  const useCmd = program2.command("use").description("Set default context for subsequent commands");
5803
6578
  useCmd.command("workspace <workspaceId>").description("Set the default workspace (files, exec, install, dev commands)").action(async (workspaceId) => {
@@ -5812,12 +6587,14 @@ function registerUse(program2) {
5812
6587
  await saveConfig(config);
5813
6588
  console.log(`Default account set to ${accountId}.`);
5814
6589
  });
5815
- program2.command("context").description("Show the current CLI context (API URL, credential kind, defaults)").option("--json", "output JSON").action(async (options) => {
6590
+ program2.command("context").description("Show the current CLI context (API URL, publish and regional credential kinds, defaults)").option("--json", "output JSON").action(async (options) => {
5816
6591
  const config = await loadConfig();
5817
6592
  outputRecord(
5818
6593
  {
5819
6594
  apiUrl: process.env.VERENTIS_API_URL ?? config.apiUrl ?? "(not set)",
5820
- credential: process.env.VERENTIS_API_KEY ?? config.apiKey ? "api key" : process.env.VERENTIS_TOKEN ?? config.identityToken ? "identity token" : "(none)",
6595
+ publishCredential: process.env.VERENTIS_GITHUB_OIDC_AUDIENCE !== void 0 ? "github oidc" : process.env.VERENTIS_PUBLISHER_API_KEY ?? config.publisherApiKey ? "publisher api key" : config.publishAccessToken ? "device session" : "(none)",
6596
+ registry: registryUrl2(config.apiUrl),
6597
+ regionalCredential: process.env.VERENTIS_API_KEY ?? config.apiKey ? "api key" : process.env.VERENTIS_TOKEN ?? config.identityToken ? "identity token" : "(none)",
5821
6598
  defaultWorkspaceId: config.defaultWorkspaceId ?? "(not set)",
5822
6599
  defaultAccountId: config.defaultAccountId ?? "(not set)",
5823
6600
  defaultKey: config.defaultKey ?? "(not set)"
@@ -5869,7 +6646,7 @@ function registerUser(program2) {
5869
6646
  const result = await call(api, security.getUserGrants, { params: { userId }, query: scope });
5870
6647
  output(result ?? [], { scope: "Scope", resourceKind: "ResourceKind", resourceId: "ResourceId", effect: "Effect", id: "GrantId" }, options, result);
5871
6648
  });
5872
- grantsCmd.command("add <userId> <scope>").description("Grant a permission scope to a user (e.g. node.file.read)").requiredOption("--resource-id <id>", "resource the grant applies to (account/workspace/node id)").requiredOption("--resource-kind <kind>", "Account | Workspace | Node").option("--expires <iso8601>", "expiry timestamp").option("--account <accountId>").option("--workspace <workspaceId>").action(async (userId, scopeName, options) => {
6649
+ grantsCmd.command("add <userId> <scope>").description("Grant a permission scope to a user (e.g. file.read)").requiredOption("--resource-id <id>", "resource the grant applies to (account/workspace/node id)").requiredOption("--resource-kind <kind>", "Account | Workspace | Node").option("--expires <iso8601>", "expiry timestamp").option("--account <accountId>").option("--workspace <workspaceId>").action(async (userId, scopeName, options) => {
5873
6650
  const api = await createApiClient();
5874
6651
  const scope = await managementScope(options);
5875
6652
  await call(api, security.grantUserPermission, {
@@ -5887,22 +6664,48 @@ function registerUser(program2) {
5887
6664
  });
5888
6665
  }
5889
6666
  function registerValidate(program2) {
5890
- program2.command("validate [pathOrDir]").description("Validate a package manifest (any registered package type) or a policy manifest").option("--env <name>", "merge a per-environment overlay (environments/<name>.yaml) before validating").option("--overlay <path>", "merge an explicit overlay file before validating (wins over --env)").action(async (pathOrDir, options) => {
6667
+ program2.command("validate [pathOrDir]").description("Validate a package manifest (any registered package type) or a policy manifest").option("--env <name>", "merge a per-environment overlay (environments/<name>.yaml) before validating").option("--overlay <path>", "merge an explicit overlay file before validating (wins over --env)").option(
6668
+ "--param <name=value>",
6669
+ "value for a ${param:name} placeholder in the overlay (repeatable)",
6670
+ (value, previous) => [...previous, value],
6671
+ []
6672
+ ).action(async (pathOrDir, options) => {
6673
+ const params = parseOverlayParams(options.param);
5891
6674
  const target = resolve(pathOrDir ?? ".");
5892
6675
  const info = await stat(target).catch(() => null);
5893
6676
  const manifestPath = info?.isDirectory() ? await findManifest(target) : target;
5894
6677
  if (!info) throw new Error(`${target} does not exist.`);
5895
6678
  const base = await readManifestDocument(manifestPath);
5896
6679
  const overlayPath = resolveOverlayPath(dirname(manifestPath), { env: options.env, overlay: options.overlay });
5897
- const manifest = overlayPath ? applyOverlay(base, await loadOverlay(overlayPath)) : base;
6680
+ const manifest = overlayPath ? applyOverlay(base, await loadOverlay(overlayPath, params)) : base;
5898
6681
  if (!NON_PACKAGE_KINDS.includes(manifest.kind)) await ensurePackageTypeKnown(manifest.kind);
5899
6682
  const issues = validateManifest(manifest);
5900
6683
  const payloadErrors = await validatorForKind(manifest.kind)?.validatePayload?.(dirname(manifestPath), manifest) ?? [];
5901
6684
  issues.push(...payloadErrors.map((message) => ({ level: "error", message })));
6685
+ const avatarPayloadErrors = await validateAgentAvatarPayload(dirname(manifestPath), manifest);
6686
+ issues.push(...avatarPayloadErrors.map((message) => ({ level: "error", message })));
6687
+ const spec = manifest.spec;
6688
+ const scriptAccess = await collectScriptFileAccess(dirname(manifestPath), spec);
6689
+ issues.push(...[
6690
+ ...validateFileAccess(spec?.["file-access"], "spec.file-access", MAX_PACKAGE_FILE_ACCESS),
6691
+ ...scriptAccess.errors,
6692
+ ...validateFileAccess(
6693
+ mergeFileAccess(spec, scriptAccess.entries)?.["file-access"],
6694
+ "spec.file-access (with scripts)",
6695
+ MAX_PACKAGE_FILE_ACCESS
6696
+ ).filter((message) => message.includes("at most"))
6697
+ ].map((message) => ({ level: "error", message })));
5902
6698
  try {
5903
6699
  const payloadFiles = await resolvePayloadFiles(dirname(manifestPath), manifestPath, manifest);
6700
+ issues.push(...validateAgentAvatarPayloadFiles(manifest, payloadFiles).map((message) => ({ level: "error", message })));
5904
6701
  const templateInspection = await inspectPackagingTemplates(dirname(manifestPath), manifest, payloadFiles);
5905
6702
  issues.push(...templateInspection.issues);
6703
+ const argumentErrors = await checkScriptArgumentDescriptors(
6704
+ dirname(manifestPath),
6705
+ payloadFiles,
6706
+ (file) => readTemplatedPayloadBytes(dirname(manifestPath), file, templateInspection)
6707
+ );
6708
+ issues.push(...argumentErrors.map((message) => ({ level: "error", message })));
5906
6709
  } catch (error) {
5907
6710
  issues.push({ level: "error", message: error instanceof Error ? error.message : String(error) });
5908
6711
  }
@@ -5918,7 +6721,7 @@ function registerValidate(program2) {
5918
6721
  }
5919
6722
  const errors = issues.filter((issue) => issue.level === "error");
5920
6723
  const warnings = issues.filter((issue) => issue.level === "warning");
5921
- console.log(`${manifestPath} \u2014 kind ${manifest.kind ?? "(unknown)"}, ${manifest.metadata?.name ?? "?"}@${manifest.metadata?.version ?? "?"}`);
6724
+ console.log(`${manifestPath} \u2014 kind ${manifest.kind ?? "(unknown)"}, ${manifest.metadata?.id ?? "?"}@${manifest.metadata?.version ?? "?"}`);
5922
6725
  for (const issue of errors) console.error(` error: ${issue.message}`);
5923
6726
  for (const issue of warnings) console.warn(` warning: ${issue.message}`);
5924
6727
  if (errors.length === 0) {
@@ -6013,6 +6816,56 @@ function registerWorkspace(program2) {
6013
6816
  });
6014
6817
  }
6015
6818
 
6819
+ // src/accessHeaders.ts
6820
+ var REDIRECTS = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
6821
+ var MAX_REDIRECTS = 10;
6822
+ function installAccessHeaders(env = process.env) {
6823
+ const clientId = env.VERENTIS_CF_ACCESS_CLIENT_ID;
6824
+ const clientSecret = env.VERENTIS_CF_ACCESS_CLIENT_SECRET;
6825
+ if (!clientId && !clientSecret) return false;
6826
+ if (!clientId || !clientSecret) {
6827
+ throw new Error("Set both VERENTIS_CF_ACCESS_CLIENT_ID and VERENTIS_CF_ACCESS_CLIENT_SECRET, or neither.");
6828
+ }
6829
+ const apiUrl = env.VERENTIS_API_URL;
6830
+ if (!apiUrl || !apiUrl.startsWith("https://")) {
6831
+ throw new Error("Cloudflare Access headers require an explicit HTTPS VERENTIS_API_URL.");
6832
+ }
6833
+ const origin = new URL(apiUrl).origin;
6834
+ const inner = globalThis.fetch;
6835
+ const accessFetch = async (input, init) => {
6836
+ const first = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
6837
+ if (first.origin !== origin) return inner(input, init);
6838
+ let url = first;
6839
+ let method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
6840
+ let body = init?.body ?? void 0;
6841
+ const baseHeaders = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
6842
+ const followRedirects = (init?.redirect ?? "follow") === "follow";
6843
+ for (let hop = 0; ; hop++) {
6844
+ const headers = new Headers(baseHeaders);
6845
+ if (url.origin === origin) {
6846
+ headers.set("CF-Access-Client-Id", clientId);
6847
+ headers.set("CF-Access-Client-Secret", clientSecret);
6848
+ } else {
6849
+ headers.delete("CF-Access-Client-Id");
6850
+ headers.delete("CF-Access-Client-Secret");
6851
+ headers.delete("Authorization");
6852
+ }
6853
+ const response = await inner(url, { ...init, method, body, headers, redirect: "manual" });
6854
+ const location = response.headers.get("location");
6855
+ if (!followRedirects || !REDIRECTS.has(response.status) || !location) return response;
6856
+ if (hop >= MAX_REDIRECTS) throw new Error(`Too many redirects from ${first.href}`);
6857
+ url = new URL(location, url);
6858
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && method === "POST") {
6859
+ method = "GET";
6860
+ body = void 0;
6861
+ baseHeaders.delete("Content-Type");
6862
+ }
6863
+ }
6864
+ };
6865
+ globalThis.fetch = accessFetch;
6866
+ return true;
6867
+ }
6868
+
6016
6869
  // src/index.ts
6017
6870
  var program = new Command().enablePositionalOptions().name("verentis").description("Verentis CLI \u2014 admin, marketplace publishing, and the engine/app developer loop").version(getCliVersion());
6018
6871
  registerLogin(program);
@@ -6035,10 +6888,12 @@ registerInit(program);
6035
6888
  registerPack(program);
6036
6889
  registerRegistry(program);
6037
6890
  registerPackage(program);
6891
+ registerNotifications(program);
6038
6892
  registerApi(program);
6039
6893
  registerUpdate(program);
6040
6894
  async function main() {
6041
6895
  try {
6896
+ installAccessHeaders();
6042
6897
  await program.parseAsync();
6043
6898
  } catch (error) {
6044
6899
  if (error instanceof ApiError || error instanceof Error) {