@verentis/cli 0.2.33 → 1.0.1

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,14 +1,14 @@
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
- import { resolve, basename, dirname, posix, join, isAbsolute, sep, relative, extname } from 'path';
5
+ import { resolve, basename, dirname, posix, join, isAbsolute, relative, sep, extname } from 'path';
6
6
  import { execFile, spawn, spawnSync } from 'child_process';
7
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((resolve17) => setTimeout(resolve17, 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,6 +1641,8 @@ var THEME_ASSET_NAMES = [
1501
1641
  "theme.css",
1502
1642
  "background",
1503
1643
  "background.dark",
1644
+ "hero",
1645
+ "hero.dark",
1504
1646
  "logo",
1505
1647
  "logo.dark",
1506
1648
  "mark",
@@ -1672,7 +1814,7 @@ async function validateThemePayload(projectDir, manifest) {
1672
1814
  else errors.push(...lintThemeCss(text).map((message) => `${at}: ${message}`));
1673
1815
  continue;
1674
1816
  }
1675
- const limit = name === "background" || name === "background.dark" ? THEME_LIMITS.background : THEME_LIMITS.image;
1817
+ const limit = ["background", "background.dark", "hero", "hero.dark"].includes(name) ? THEME_LIMITS.background : THEME_LIMITS.image;
1676
1818
  if (bytes.length > limit) errors.push(`${at} exceeds ${limit / (1024 * 1024)} MiB.`);
1677
1819
  if (mime === "image/svg+xml") {
1678
1820
  const text = decodeUtf8(bytes);
@@ -1701,8 +1843,136 @@ function validatorForKind(kind) {
1701
1843
  const name = findPackageType(kind)?.validator;
1702
1844
  return name ? PACKAGE_TYPE_VALIDATORS[name] : void 0;
1703
1845
  }
1846
+ var DOTLOTTIE_V2_FORMAT = "dotlottie/v2";
1847
+ var DOTLOTTIE_MAX_BYTES = 4 * 1024 * 1024;
1848
+ var AVATAR_FALLBACK_MAX_BYTES = 1024 * 1024;
1849
+ var isRecord3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1850
+ function normalizeAvatarAssetPath(value) {
1851
+ 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;
1852
+ const segments = value.slice(2).split("/");
1853
+ if (segments.length === 0 || segments.some((segment) => segment.length === 0 || segment === "." || segment === ".." || /\s/u.test(segment))) return void 0;
1854
+ return segments.join("/");
1855
+ }
1856
+ function isStaticImagePath(path) {
1857
+ return /\.(svg|png|jpe?g|webp)$/.test(path);
1858
+ }
1859
+ function validateAgentAvatarManifest(kind, spec) {
1860
+ if (kind !== "Agent" || !isRecord3(spec) || spec.avatar === void 0) return [];
1861
+ const errors = [];
1862
+ const avatar = spec.avatar;
1863
+ if (!isRecord3(avatar)) return ["spec.avatar must be an object."];
1864
+ for (const key of Object.keys(avatar)) {
1865
+ if (!["format", "definition", "fallback"].includes(key)) {
1866
+ errors.push(`spec.avatar.${key} is not supported.`);
1867
+ }
1868
+ }
1869
+ if (avatar.format !== DOTLOTTIE_V2_FORMAT) {
1870
+ errors.push(`spec.avatar.format must be '${DOTLOTTIE_V2_FORMAT}'.`);
1871
+ }
1872
+ const definition = normalizeAvatarAssetPath(avatar.definition);
1873
+ if (!definition || !definition.endsWith(".lottie")) {
1874
+ errors.push("spec.avatar.definition must be a safe relative .lottie package path (no absolute paths, traversal, URLs or encoded separators).");
1875
+ }
1876
+ if (avatar.fallback !== void 0) {
1877
+ const fallback = normalizeAvatarAssetPath(avatar.fallback);
1878
+ if (!fallback || !isStaticImagePath(fallback)) {
1879
+ errors.push("spec.avatar.fallback must be a safe relative .svg, .png, .jpg, .jpeg or .webp package path.");
1880
+ }
1881
+ }
1882
+ return errors;
1883
+ }
1884
+ function agentAvatarPayloadPaths(manifest) {
1885
+ if (manifest.kind !== "Agent" || !isRecord3(manifest.spec) || !isRecord3(manifest.spec.avatar)) return [];
1886
+ const avatar = manifest.spec.avatar;
1887
+ return [avatar.definition, avatar.fallback].map(normalizeAvatarAssetPath).filter((path) => path !== void 0);
1888
+ }
1889
+ function validateAgentAvatarPayloadFiles(manifest, payloadFiles) {
1890
+ const included = new Set(payloadFiles.map((path) => path.replaceAll("\\", "/").replace(/^\.\//, "")));
1891
+ 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.`);
1892
+ }
1893
+ async function validateAgentAvatarPayload(projectDir, manifest) {
1894
+ if (manifest.kind !== "Agent" || !isRecord3(manifest.spec) || !isRecord3(manifest.spec.avatar)) return [];
1895
+ const avatar = manifest.spec.avatar;
1896
+ const errors = [];
1897
+ const root = await realpath(projectDir).catch(() => resolve(projectDir));
1898
+ const assets = [
1899
+ { path: avatar.definition, kind: "definition" },
1900
+ ...avatar.fallback === void 0 ? [] : [{ path: avatar.fallback, kind: "fallback" }]
1901
+ ];
1902
+ for (const asset of assets) {
1903
+ const path = normalizeAvatarAssetPath(asset.path);
1904
+ if (!path) continue;
1905
+ const at = `spec.avatar.${asset.kind} (${path})`;
1906
+ try {
1907
+ const absolute = await realpath(resolve(root, path));
1908
+ const fromRoot = relative(root, absolute);
1909
+ if (fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
1910
+ errors.push(`${at} resolves outside the package directory.`);
1911
+ continue;
1912
+ }
1913
+ if (!(await stat(absolute)).isFile()) {
1914
+ errors.push(`${at} must be a file.`);
1915
+ continue;
1916
+ }
1917
+ const bytes = await readFile(absolute);
1918
+ if (asset.kind === "definition") {
1919
+ if (bytes.length > DOTLOTTIE_MAX_BYTES) {
1920
+ errors.push(`${at} exceeds ${DOTLOTTIE_MAX_BYTES / (1024 * 1024)} MiB.`);
1921
+ } else if (bytes.length < 22 || bytes[0] !== 80 || bytes[1] !== 75) {
1922
+ errors.push(`${at} is not a dotLottie ZIP bundle.`);
1923
+ }
1924
+ } else {
1925
+ if (bytes.length === 0 || bytes.length > AVATAR_FALLBACK_MAX_BYTES) {
1926
+ errors.push(`${at} must be non-empty and no larger than ${AVATAR_FALLBACK_MAX_BYTES / (1024 * 1024)} MiB.`);
1927
+ } else if (path.endsWith(".svg")) {
1928
+ const text = decodeUtf8(bytes);
1929
+ const reason = text === null ? "SVG must be UTF-8 text" : validateThemeSvg(text);
1930
+ if (reason) errors.push(`${at}: ${reason}.`);
1931
+ } else if (!hasRasterSignature(path, bytes)) {
1932
+ errors.push(`${at} does not match its declared image format.`);
1933
+ }
1934
+ }
1935
+ } catch {
1936
+ errors.push(`${at} does not exist inside the package directory.`);
1937
+ }
1938
+ }
1939
+ return errors;
1940
+ }
1941
+ function hasRasterSignature(path, bytes) {
1942
+ if (path.endsWith(".png")) return bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
1943
+ if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
1944
+ if (path.endsWith(".webp")) return bytes.length >= 12 && bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP";
1945
+ return false;
1946
+ }
1704
1947
 
1705
1948
  // src/vpkg/manifest.ts
1949
+ var METADATA_ID_REQUIRED_MESSAGE = "metadata.id is required";
1950
+ var LEGACY_PACKAGE_ID_MESSAGE = "metadata.package-id is no longer supported; use metadata.id";
1951
+ var LEGACY_DISPLAY_NAME_MESSAGE = "metadata.display-name is no longer supported; use metadata.name";
1952
+ function validateDocumentMetadata(metadata) {
1953
+ const meta = metadata && typeof metadata === "object" && !Array.isArray(metadata) ? metadata : {};
1954
+ const has = (key) => Object.prototype.hasOwnProperty.call(meta, key);
1955
+ const errors = [];
1956
+ if (has("package-id")) errors.push(LEGACY_PACKAGE_ID_MESSAGE);
1957
+ if (has("display-name")) errors.push(LEGACY_DISPLAY_NAME_MESSAGE);
1958
+ if (typeof meta.id !== "string" || !meta.id.trim()) errors.push(METADATA_ID_REQUIRED_MESSAGE);
1959
+ if (has("name") && (typeof meta.name !== "string" || !meta.name.trim())) errors.push("metadata.name must be a non-empty string");
1960
+ return errors;
1961
+ }
1962
+ function isVerentisDocument(value) {
1963
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1964
+ const record = value;
1965
+ return typeof record["api-version"] === "string" && /(^|\.)verentis\.io\/v1$/.test(record["api-version"]) && typeof record.kind === "string";
1966
+ }
1967
+ function payloadDocumentMetadataErrors(text) {
1968
+ let documents;
1969
+ try {
1970
+ documents = parseAllDocuments(text).map((document) => document.toJS());
1971
+ } catch {
1972
+ return [];
1973
+ }
1974
+ return documents.filter(isVerentisDocument).flatMap((document) => validateDocumentMetadata(document.metadata).map((message) => `${document.kind}: ${message}`));
1975
+ }
1706
1976
  function normalizeKind(kind) {
1707
1977
  const canonical = canonicalPackageType(kind);
1708
1978
  if (!canonical) throw new Error(unknownPackageTypeMessage(kind));
@@ -1748,7 +2018,8 @@ function validatePackageManifestRules(kind, manifest) {
1748
2018
  ...validateApplicationSplashSection(kind, manifest.spec),
1749
2019
  ...validateMetadataTags(manifest.metadata?.tags),
1750
2020
  ...validateTypeSpecFields(kind, manifest.spec),
1751
- ...validateTypeManifest(kind, manifest)
2021
+ ...validateTypeManifest(kind, manifest),
2022
+ ...validateAgentAvatarManifest(kind, manifest.spec)
1752
2023
  ];
1753
2024
  }
1754
2025
  function validateLaunchManifestKind(kind, spec) {
@@ -1761,10 +2032,10 @@ async function loadManifest(path) {
1761
2032
  const manifest = parse(text);
1762
2033
  if (!manifest || typeof manifest !== "object") throw new Error(`Failed to parse manifest at ${path}.`);
1763
2034
  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'.`);
2035
+ const metadataErrors = validateDocumentMetadata(manifest.metadata);
2036
+ if (metadataErrors.length > 0) throw new Error(`Invalid manifest at ${path}: ${metadataErrors.join("; ")}.`);
1766
2037
  if (!manifest.metadata?.version) throw new Error(`Manifest at ${path} is missing 'metadata.version'.`);
1767
- validatePackageName(manifest.metadata["package-id"], "package ID");
2038
+ validatePackageName(manifest.metadata.id, "package ID");
1768
2039
  const kind = normalizeKind(manifest.kind);
1769
2040
  const hostedBackendErrors = validateHostedBackendDeclaration(kind, manifest.spec);
1770
2041
  if (hostedBackendErrors.length > 0) {
@@ -2231,21 +2502,13 @@ function validateManifest(manifest) {
2231
2502
  error("api-version must be 'verentis.io/v1'");
2232
2503
  }
2233
2504
  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");
2505
+ for (const message of validateDocumentMetadata(meta)) error(message);
2506
+ if (typeof meta.id === "string" && meta.id.trim() && !NAME_PATTERN.test(meta.id)) {
2507
+ error("metadata.id must use lowercase letters, digits and internal hyphens");
2238
2508
  }
2239
2509
  if (!isPolicy) {
2240
2510
  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
- }
2511
+ if (!meta.version) error("metadata.version is required");
2249
2512
  }
2250
2513
  const spec = manifest.spec ?? {};
2251
2514
  validateManifestIcons(meta, spec, issues);
@@ -2294,6 +2557,7 @@ function validateManifest(manifest) {
2294
2557
  if (descriptor?.resourceKind === "Skill") validateSkillManifest(spec, issues);
2295
2558
  if (descriptor?.resourceKind === "Tool") validateToolManifest(spec, issues);
2296
2559
  if (isPolicy) validatePolicyManifest(spec, issues);
2560
+ for (const message of validateAgentAvatarManifest(kind, spec)) error(message);
2297
2561
  validateInstallDirectives(spec.install, issues);
2298
2562
  validateSettingDeclarations(descriptor?.profile === "engine", spec, issues);
2299
2563
  for (const message of validateMarketplaceSection(manifest.marketplace)) error(message);
@@ -2523,7 +2787,7 @@ function validateSettingDeclarations(isEngine, spec, issues) {
2523
2787
  return;
2524
2788
  }
2525
2789
  if (!declaration.key || typeof declaration.key !== "string") {
2526
- error(`${at}.key is required (short key, stored namespaced as '{metadata.name}.{key}')`);
2790
+ error(`${at}.key is required (short key, stored namespaced as '{metadata.id}.{key}')`);
2527
2791
  } else if (!SETTING_KEY_PATTERN.test(declaration.key)) {
2528
2792
  error(`${at}.key '${declaration.key}' must be lowercase kebab/dot notation (e.g. 'api-key' or 'smtp.host')`);
2529
2793
  } else if (seen.has(declaration.key)) {
@@ -2678,7 +2942,9 @@ function registerDev(program2) {
2678
2942
  const env = {
2679
2943
  ...process.env,
2680
2944
  ...context.input.environment,
2681
- ...contextEnv(context, contextPath)
2945
+ ...contextEnv(context, contextPath),
2946
+ // Lets the SDK prompt for missing declared arguments in this terminal (never on the platform).
2947
+ VERENTIS_LOCAL_RUN: "1"
2682
2948
  };
2683
2949
  const pythonArgs = [];
2684
2950
  if (options.debug !== void 0) {
@@ -2719,7 +2985,7 @@ function registerDev(program2) {
2719
2985
  program: "${file}",
2720
2986
  console: "integratedTerminal",
2721
2987
  justMyCode: true,
2722
- env: { VERENTIS_CONTEXT_PATH: "${workspaceFolder}/.verentis/context.json" }
2988
+ env: { VERENTIS_CONTEXT_PATH: "${workspaceFolder}/.verentis/context.json", VERENTIS_LOCAL_RUN: "1" }
2723
2989
  }
2724
2990
  ]
2725
2991
  };
@@ -2919,7 +3185,7 @@ async function followExecution(api, workspaceId, executionId, json) {
2919
3185
  if (exec.status !== "Completed") process.exitCode = 1;
2920
3186
  return;
2921
3187
  }
2922
- await new Promise((resolve17) => setTimeout(resolve17, 1e3));
3188
+ await new Promise((resolve18) => setTimeout(resolve18, 1e3));
2923
3189
  }
2924
3190
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
2925
3191
  process.exitCode = 1;
@@ -3603,9 +3869,8 @@ var TEMPLATES = {
3603
3869
  kind: Application
3604
3870
 
3605
3871
  metadata:
3606
- name: ${name}
3607
- package-id: ${name}
3608
- display-name: ${titleCase(name)}
3872
+ id: ${name}
3873
+ name: ${titleCase(name)}
3609
3874
  description: ""
3610
3875
  icon: ./icons/app.svg
3611
3876
  version: 0.1.0
@@ -3655,9 +3920,8 @@ packaging:
3655
3920
  kind: ExecutionEngine
3656
3921
 
3657
3922
  metadata:
3658
- name: ${name}
3659
- package-id: ${name}
3660
- display-name: ${titleCase(name)}
3923
+ id: ${name}
3924
+ name: ${titleCase(name)}
3661
3925
  description: ""
3662
3926
  icon: ./icons/app.svg
3663
3927
  version: 0.1.0
@@ -3692,9 +3956,8 @@ packaging:
3692
3956
  kind: Bundle
3693
3957
 
3694
3958
  metadata:
3695
- name: ${name}
3696
- package-id: ${name}
3697
- display-name: ${titleCase(name)}
3959
+ id: ${name}
3960
+ name: ${titleCase(name)}
3698
3961
  description: ""
3699
3962
  version: 0.1.0
3700
3963
  author: ""
@@ -3725,9 +3988,8 @@ packaging:
3725
3988
  kind: Theme
3726
3989
 
3727
3990
  metadata:
3728
- name: ${name}
3729
- package-id: ${name}
3730
- display-name: ${titleCase(name)}
3991
+ id: ${name}
3992
+ name: ${titleCase(name)}
3731
3993
  description: ""
3732
3994
  version: 0.1.0
3733
3995
  author: ""
@@ -3739,8 +4001,8 @@ metadata:
3739
4001
  # readme: ./README.md
3740
4002
 
3741
4003
  # 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, logo.dark, mark, mark.dark, favicon,
3743
- # apple-touch-icon (PNG only). Images may be SVG, PNG, JPEG or WebP (1 MiB each, backgrounds 2 MiB,
4004
+ # theme.css, background, background.dark, hero, hero.dark, logo, logo.dark, mark, mark.dark, favicon,
4005
+ # apple-touch-icon (PNG only). Images may be SVG, PNG, JPEG or WebP (1 MiB each, backgrounds and heroes 2 MiB,
3744
4006
  # 4 MiB in total). \`verentis pack\` installs each one at /.theme/<asset>.
3745
4007
  spec:
3746
4008
  assets:
@@ -3752,6 +4014,8 @@ spec:
3752
4014
  favicon: theme/favicon.svg
3753
4015
  # background: theme/background.jpg
3754
4016
  # background.dark: theme/background-dark.jpg
4017
+ # hero: theme/hero.jpg
4018
+ # hero.dark: theme/hero-dark.jpg
3755
4019
  # apple-touch-icon: theme/apple-touch-icon.png # 180\xD7180 PNG
3756
4020
 
3757
4021
  packaging:
@@ -3771,12 +4035,12 @@ function resolveInitTemplate(type) {
3771
4035
  return key;
3772
4036
  }
3773
4037
  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) => {
4038
+ 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
4039
  const templateKey = resolveInitTemplate(options.type ?? options.kind ?? "application");
3776
4040
  const template = TEMPLATES[templateKey];
3777
4041
  const targetDir = resolve(dir ?? ".");
3778
4042
  await mkdir(targetDir, { recursive: true });
3779
- const name = (options.name ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
4043
+ const name = (options.id ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
3780
4044
  const manifestPath = join(targetDir, "manifest.yaml");
3781
4045
  if (await exists3(manifestPath)) throw new Error(`${manifestPath} already exists.`);
3782
4046
  await writeFile(manifestPath, template(name));
@@ -3854,56 +4118,148 @@ async function loadKey(name) {
3854
4118
  }
3855
4119
  var pageItems2 = (page) => page.data ?? page.items ?? [];
3856
4120
  async function getMyPublisher(api) {
3857
- const result = await api.request("GET", "/v1/publishers/me", {
4121
+ const result = await api.request("GET", `${REGISTRY_BASE}/publishers/me`, {
3858
4122
  scopes: [SCOPES.publisherRead]
3859
4123
  });
3860
- return result ?? null;
4124
+ return result && typeof result === "object" && result.id ? result : null;
3861
4125
  }
3862
4126
  async function requireMyPublisher(api) {
3863
4127
  const publisher = await getMyPublisher(api);
3864
4128
  if (!publisher) {
3865
- throw new Error("No publisher profile for this account. Create one with `verentis publisher create --name <name> --display-name <display>`.");
4129
+ throw new Error(noPublisherMessage(api.apiUrl));
3866
4130
  }
3867
4131
  return publisher;
3868
4132
  }
4133
+ async function requireRegistryPublisher(api) {
4134
+ const claims = decodeJwtPayload(await api.registryToken());
4135
+ if (typeof claims?.publisher_id === "string") {
4136
+ return { id: claims.publisher_id, name: typeof claims.publisher_name === "string" ? claims.publisher_name : void 0 };
4137
+ }
4138
+ const me = await api.request("GET", `${REGISTRY_BASE}/publishers/me`, { plane: "registry" }).catch(() => null);
4139
+ if (!me?.id) {
4140
+ throw new Error(noPublisherMessage(api.apiUrl));
4141
+ }
4142
+ return { id: me.id, name: me.name };
4143
+ }
3869
4144
  async function findPackageByPackageId(api, publisherId, packageId) {
3870
4145
  const page = await api.request("GET", `/v1/publishers/${publisherId}/packages`, {
3871
- scopes: [SCOPES.packageRead],
4146
+ scopes: [SCOPES.packageList],
3872
4147
  query: { PageNo: 1, PageSize: 100 }
3873
4148
  });
3874
4149
  return pageItems2(page).find((pkg) => pkg.packageId === packageId) ?? null;
3875
4150
  }
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
- });
4151
+ async function findRegistryVersion(api, publisher, packageId, version) {
4152
+ try {
4153
+ return await api.request(
4154
+ "GET",
4155
+ `${REGISTRY_BASE}/packages/${encodeURIComponent(publisher)}/${encodeURIComponent(packageId)}/versions/${encodeURIComponent(version)}`,
4156
+ { plane: "registry" }
4157
+ );
4158
+ } catch (error) {
4159
+ if (error instanceof ApiError && error.status === 404) return null;
4160
+ throw error;
4161
+ }
3891
4162
  }
3892
- async function uploadVersion(api, packageId, vpkgPath) {
3893
- (await stat(vpkgPath)).size;
4163
+ function sameTreeDigest(a, b) {
4164
+ const normalize = (value) => (value ?? "").trim().toLowerCase().replace(/^sha256:/, "");
4165
+ return normalize(a) !== "" && normalize(a) === normalize(b);
4166
+ }
4167
+ async function uploadRegistryVersion(api, publisher, packageId, vpkgPath, options = {}) {
3894
4168
  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
- });
4169
+ const res = await api.requestRaw(
4170
+ "POST",
4171
+ `${REGISTRY_BASE}/packages/${encodeURIComponent(publisher)}/${encodeURIComponent(packageId)}/versions`,
4172
+ {
4173
+ plane: "registry",
4174
+ rawBody: stream,
4175
+ contentType: "application/vnd.verentis.package+tar+gzip",
4176
+ query: { visibility: options.visibility }
4177
+ }
4178
+ );
3900
4179
  return await res.json();
3901
4180
  }
3902
- async function yankVersion(api, packageId, version) {
3903
- await api.request("POST", `/v1/packages/${packageId}/versions/${encodeURIComponent(version)}/yank`, {
3904
- scopes: [SCOPES.packagePublish]
4181
+ var publisherEmailSenderPath = (publisherId, packageOwner) => `${REGISTRY_BASE}/publishers/${encodeURIComponent(publisherId)}/packages/${encodeURIComponent(packageOwner)}/notifications/sender`;
4182
+ async function setPublisherEmailSender(api, publisherId, packageOwner, request) {
4183
+ return api.request("PUT", publisherEmailSenderPath(publisherId, packageOwner), { plane: "registry", body: request });
4184
+ }
4185
+ async function getPublisherEmailSender(api, publisherId, packageOwner) {
4186
+ return api.request("GET", publisherEmailSenderPath(publisherId, packageOwner), { plane: "registry" });
4187
+ }
4188
+ async function revokePublisherEmailSender(api, publisherId, packageOwner) {
4189
+ return api.request("DELETE", publisherEmailSenderPath(publisherId, packageOwner), { plane: "registry" });
4190
+ }
4191
+ async function resolveRegistryPackageRef(api, ref) {
4192
+ const trimmed = ref.trim().replace(/^@/, "");
4193
+ if (trimmed.includes("/")) {
4194
+ const [publisher2, packageId] = trimmed.split("/", 2);
4195
+ if (!publisher2 || !packageId) throw new Error(`Invalid package reference '${ref}'. Use 'package-id' or 'publisher/package-id'.`);
4196
+ return { publisher: publisher2, packageId };
4197
+ }
4198
+ const publisher = await requireRegistryPublisher(api);
4199
+ if (!publisher.name) throw new Error(`Cannot resolve your publisher name; pass the package as 'publisher/${trimmed}'.`);
4200
+ return { publisher: publisher.name, packageId: trimmed };
4201
+ }
4202
+ var registryPackagePath = (ref) => `${REGISTRY_BASE}/packages/${encodeURIComponent(ref.publisher)}/${encodeURIComponent(ref.packageId)}`;
4203
+ var registryVersionPath = (ref, version) => `${registryPackagePath(ref)}/versions/${encodeURIComponent(version)}`;
4204
+ async function listRegistryPackages(api, publisher) {
4205
+ const result = await api.request(
4206
+ "GET",
4207
+ `${REGISTRY_BASE}/publishers/${encodeURIComponent(publisher)}/packages`,
4208
+ { plane: "registry" }
4209
+ );
4210
+ return Array.isArray(result) ? result : [];
4211
+ }
4212
+ async function getRegistryPackage(api, ref) {
4213
+ const pkg = (await listRegistryPackages(api, ref.publisher)).find((p) => p.packageId === ref.packageId);
4214
+ if (!pkg) throw new Error(`Package '${ref.publisher}/${ref.packageId}' not found in the registry (or you do not own it).`);
4215
+ return pkg;
4216
+ }
4217
+ async function yankVersion(api, ref, version, reason) {
4218
+ await api.request("POST", `${registryVersionPath(ref, version)}/yank`, { plane: "registry", body: { reason: reason || void 0 } });
4219
+ }
4220
+ async function deprecateVersion(api, ref, version, message) {
4221
+ await api.request("POST", `${registryVersionPath(ref, version)}/deprecate`, { plane: "registry", body: { message: message || void 0 } });
4222
+ }
4223
+ async function undeprecateVersion(api, ref, version) {
4224
+ await api.request("DELETE", `${registryVersionPath(ref, version)}/deprecate`, { plane: "registry" });
4225
+ }
4226
+ async function deprecatePackage(api, ref, message) {
4227
+ await api.request("POST", `${registryPackagePath(ref)}/deprecate`, { plane: "registry", body: { message: message || void 0 } });
4228
+ }
4229
+ async function undeprecatePackage(api, ref) {
4230
+ await api.request("DELETE", `${registryPackagePath(ref)}/deprecate`, { plane: "registry" });
4231
+ }
4232
+ async function archivePackage(api, ref) {
4233
+ await api.request("POST", `${registryPackagePath(ref)}/archive`, { plane: "registry" });
4234
+ }
4235
+ async function setPackageVisibility(api, ref, visibility) {
4236
+ await api.request("PUT", `${registryPackagePath(ref)}/visibility`, { plane: "registry", body: { visibility } });
4237
+ }
4238
+ async function listVisibilityGrants(api, ref) {
4239
+ const result = await api.request("GET", `${registryPackagePath(ref)}/visibility-grants`, { plane: "registry" });
4240
+ return Array.isArray(result) ? result : result ? pageItems2(result) : [];
4241
+ }
4242
+ async function grantVisibility(api, ref, granteeType, granteeId) {
4243
+ return api.request("POST", `${registryPackagePath(ref)}/visibility-grants`, {
4244
+ plane: "registry",
4245
+ body: { granteeType, granteeId }
3905
4246
  });
3906
4247
  }
4248
+ async function revokeVisibility(api, ref, grantId) {
4249
+ await api.request("DELETE", `${registryPackagePath(ref)}/visibility-grants/${encodeURIComponent(grantId)}`, { plane: "registry" });
4250
+ }
4251
+ function parseVisibility(value) {
4252
+ const normalized = value.trim().toLowerCase();
4253
+ if (normalized === "public") return "Public";
4254
+ if (normalized === "private") return "Private";
4255
+ throw new Error(`Invalid visibility '${value}'. Use Public or Private.`);
4256
+ }
4257
+ function parseGranteeType(value) {
4258
+ const normalized = value.trim().toLowerCase();
4259
+ if (normalized === "account") return "Account";
4260
+ if (normalized === "workspace") return "Workspace";
4261
+ throw new Error(`Invalid grantee type '${value}'. Use Account or Workspace.`);
4262
+ }
3907
4263
  async function downloadTarball(api, packageId, version, workspaceId) {
3908
4264
  return api.requestRaw("GET", `/v1/packages/${packageId}/versions/${encodeURIComponent(version)}/tarball`, {
3909
4265
  scopes: [SCOPES.packageRead],
@@ -3919,7 +4275,7 @@ async function resolvePackageRef(api, ref) {
3919
4275
  return { package: pkg2, publisherName: me.name };
3920
4276
  }
3921
4277
  const page = await api.request("GET", "/v1/packages", {
3922
- scopes: [SCOPES.packageReadAll],
4278
+ scopes: [SCOPES.packageList],
3923
4279
  query: { SearchText: packageId, PageNo: 1, PageSize: 100 }
3924
4280
  });
3925
4281
  const pkg = pageItems2(page).find((p) => p.packageId === packageId && p.publisherName === publisherName);
@@ -3941,12 +4297,8 @@ function registerKeygen(program2) {
3941
4297
  }
3942
4298
  if (options.register) {
3943
4299
  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}'.`);
4300
+ const publisher = await registerKey(api, key.publicKey);
4301
+ console.log(`Registered public key with publisher '${publisher.name ?? publisher.id}'.`);
3950
4302
  } else {
3951
4303
  console.log("Public key NOT registered (use `verentis key register` later).");
3952
4304
  }
@@ -3955,36 +4307,48 @@ function registerKeygen(program2) {
3955
4307
  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
4308
  const key = await loadKey(options.name);
3957
4309
  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}'.`);
4310
+ const publisher = await registerKey(api, key.publicKey);
4311
+ console.log(`Registered key '${options.name}' (kid ${key.kid}) with publisher '${publisher.name ?? publisher.id}'.`);
3964
4312
  });
3965
4313
  keyCmd.command("revoke <kid>").description("Revoke a registered signing key").action(async (kid) => {
3966
4314
  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]
4315
+ const publisher = await requireRegistryPublisher(api);
4316
+ await api.request("DELETE", `${REGISTRY_BASE}/publishers/${encodeURIComponent(publisher.id)}/keys/${encodeURIComponent(kid)}`, {
4317
+ plane: "registry"
3970
4318
  });
3971
4319
  console.log(`Revoked key ${kid}.`);
3972
4320
  });
3973
4321
  }
4322
+ async function registerKey(api, publicKey) {
4323
+ const publisher = await requireRegistryPublisher(api);
4324
+ await api.request("POST", `${REGISTRY_BASE}/publishers/${encodeURIComponent(publisher.id)}/keys`, {
4325
+ plane: "registry",
4326
+ body: { publicKey, algorithm: "Ed25519" }
4327
+ });
4328
+ return publisher;
4329
+ }
3974
4330
  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) => {
4331
+ 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
4332
  const config = await loadConfig();
3977
4333
  if (options.apiUrl) config.apiUrl = options.apiUrl;
3978
4334
  if (options.sealingKey) config.sealingPublicKey = options.sealingKey;
3979
4335
  if (options.insecure !== void 0) config.insecure = options.insecure;
3980
4336
  const apiUrl = (options.apiUrl ?? process.env.VERENTIS_API_URL ?? config.apiUrl ?? PRODUCTION_API_URL).replace(/\/+$/, "");
3981
4337
  if (options.apiKey) {
3982
- if (!options.apiKey.startsWith("vrt_")) throw new Error('API keys start with "vrt_".');
4338
+ if (options.apiKey.startsWith(PUBLISHER_API_KEY_PREFIX)) {
4339
+ config.publisherApiKey = options.apiKey;
4340
+ delete config.publishAccessToken;
4341
+ delete config.publishRefreshToken;
4342
+ await saveConfig(config);
4343
+ console.log(`Configuration saved (publisher API key @ ${apiUrl}).`);
4344
+ return;
4345
+ }
4346
+ if (!options.apiKey.startsWith("vrt_")) throw new Error('API keys start with "pub_" (publisher) or "vrt_" (regional).');
3983
4347
  config.apiKey = options.apiKey;
3984
4348
  delete config.identityToken;
3985
4349
  delete config.refreshToken;
3986
4350
  await saveConfig(config);
3987
- console.log(`Configuration saved (API key @ ${apiUrl}).`);
4351
+ console.log(`Configuration saved (regional API key @ ${apiUrl}).`);
3988
4352
  return;
3989
4353
  }
3990
4354
  if (options.token) {
@@ -3996,6 +4360,26 @@ function registerLogin(program2) {
3996
4360
  return;
3997
4361
  }
3998
4362
  const insecure = config.insecure;
4363
+ if (!options.regional) {
4364
+ const authorization2 = await startRegistryDeviceAuthorization(apiUrl, insecure);
4365
+ console.log("To sign in, open this URL in a browser:");
4366
+ console.log(`
4367
+ ${authorization2.verification_uri_complete ?? authorization2.verification_uri}
4368
+ `);
4369
+ console.log(`and confirm the code: ${authorization2.user_code}`);
4370
+ console.log("\nWaiting for approval\u2026");
4371
+ const tokens = await pollForRegistryTokens(apiUrl, authorization2, insecure, () => process.stderr.write("."));
4372
+ process.stderr.write("\n");
4373
+ config.publishAccessToken = tokens.accessToken;
4374
+ if (tokens.refreshToken) config.publishRefreshToken = tokens.refreshToken;
4375
+ else delete config.publishRefreshToken;
4376
+ delete config.publisherApiKey;
4377
+ await saveConfig(config);
4378
+ const claims2 = decodeJwtPayload(tokens.accessToken);
4379
+ if (claims2?.publisher_name) console.log(`Signed in to publish as '${claims2.publisher_name}' @ ${apiUrl}.`);
4380
+ else console.log(`Signed in @ ${apiUrl}. ${noPublisherMessage(apiUrl)}`);
4381
+ return;
4382
+ }
3999
4383
  const authorization = await startDeviceAuthorization(apiUrl, insecure);
4000
4384
  console.log("To sign in, open this URL in a browser:");
4001
4385
  console.log(`
@@ -4021,20 +4405,23 @@ function registerLogin(program2) {
4021
4405
  delete config.apiKey;
4022
4406
  delete config.identityToken;
4023
4407
  delete config.refreshToken;
4408
+ delete config.publishAccessToken;
4409
+ delete config.publishRefreshToken;
4410
+ delete config.publisherApiKey;
4024
4411
  await saveConfig(config);
4025
4412
  console.log("Credentials removed.");
4026
4413
  });
4027
- program2.command("whoami").description("Show the current identity, account and publisher profile").action(async () => {
4414
+ program2.command("whoami").description("Show the current regional identity/account and the global publishing session").action(async () => {
4028
4415
  const config = await loadConfig();
4029
4416
  const identityToken = process.env.VERENTIS_TOKEN ?? config.identityToken;
4030
4417
  if (identityToken) {
4031
- const claims = decodeJwtPayload(identityToken);
4032
- if (claims) {
4033
- const expiry = claims.exp ? new Date(claims.exp * 1e3) : void 0;
4418
+ const claims2 = decodeJwtPayload(identityToken);
4419
+ if (claims2) {
4420
+ const expiry = claims2.exp ? new Date(claims2.exp * 1e3) : void 0;
4034
4421
  const expired = expiry && expiry.getTime() <= Date.now();
4035
4422
  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}`);
4423
+ console.log(`User: ${claims2.name ?? claims2.email ?? claims2.sub ?? "(unknown)"}${claims2.sub ? ` (${claims2.sub})` : ""}`);
4424
+ if (claims2.account_id) console.log(`Account: ${claims2.account_id}`);
4038
4425
  if (expiry) {
4039
4426
  const state = expired ? renewable ? "expired (auto-renews)" : "EXPIRED" : "expires";
4040
4427
  console.log(`Token ${state}: ${expiry.toISOString()}`);
@@ -4045,20 +4432,26 @@ function registerLogin(program2) {
4045
4432
  console.log("Credential: API key (identity claims not available)");
4046
4433
  }
4047
4434
  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>"`');
4435
+ const apiUrl = requireApiUrl(config);
4436
+ const publisherKey = process.env.VERENTIS_PUBLISHER_API_KEY ?? config.publisherApiKey;
4437
+ if (!publisherKey && !config.publishAccessToken && process.env.VERENTIS_GITHUB_OIDC_AUDIENCE === void 0) {
4438
+ console.log(`Publishing: not signed in \u2014 run \`verentis login\` (registry ${apiUrl}${REGISTRY_BASE})`);
4056
4439
  return;
4057
4440
  }
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
- }
4441
+ const api = await createApiClient();
4442
+ console.log(`Publishing: global registry @ ${apiUrl}${REGISTRY_BASE}`);
4443
+ const credential = process.env.VERENTIS_GITHUB_OIDC_AUDIENCE !== void 0 ? "GitHub OIDC" : publisherKey ? "publisher API key" : "device-flow session";
4444
+ console.log(` credential: ${credential}`);
4445
+ const token = await api.registryToken().catch((err) => {
4446
+ console.log(` ${err.message}`);
4447
+ return void 0;
4448
+ });
4449
+ const claims = token ? decodeJwtPayload(token) : null;
4450
+ if (!claims) return;
4451
+ if (claims.publisher_name) console.log(` publisher: ${claims.publisher_name}${claims.publisher_id ? ` (${claims.publisher_id})` : ""}`);
4452
+ else console.log(` publisher: none. ${noPublisherMessage(apiUrl)}`);
4453
+ if (claims.scope) console.log(` scope: ${claims.scope}`);
4454
+ if (claims.exp) console.log(` token expires: ${new Date(claims.exp * 1e3).toISOString()}`);
4062
4455
  });
4063
4456
  }
4064
4457
 
@@ -4147,6 +4540,85 @@ function rawX25519Private(key) {
4147
4540
  function publicKeyFromRaw(raw) {
4148
4541
  return createPublicKey({ key: { kty: "OKP", crv: "X25519", x: raw.toString("base64url") }, format: "jwk" });
4149
4542
  }
4543
+ function isPlainObject(value) {
4544
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4545
+ }
4546
+ function deepMerge(base, overlay) {
4547
+ if (!isPlainObject(base) || !isPlainObject(overlay)) {
4548
+ return overlay;
4549
+ }
4550
+ const result = { ...base };
4551
+ for (const [key, value] of Object.entries(overlay)) {
4552
+ result[key] = key in result ? deepMerge(result[key], value) : value;
4553
+ }
4554
+ return result;
4555
+ }
4556
+ function applyOverlay(base, overlay) {
4557
+ return deepMerge(base, overlay);
4558
+ }
4559
+ function resolveOverlayPath(projectDir, selector) {
4560
+ if (selector.overlay) {
4561
+ return isAbsolute(selector.overlay) ? selector.overlay : resolve(selector.overlay);
4562
+ }
4563
+ if (selector.env) {
4564
+ return join(projectDir, "environments", `${selector.env}.yaml`);
4565
+ }
4566
+ return void 0;
4567
+ }
4568
+ var PARAM_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
4569
+ var PARAM_PLACEHOLDER_PATTERN = /(\$?)\$\{param:([^}]*)\}/g;
4570
+ function parseOverlayParams(pairs = []) {
4571
+ const params = {};
4572
+ for (const pair of pairs) {
4573
+ const eq = pair.indexOf("=");
4574
+ const name = eq < 0 ? pair : pair.slice(0, eq);
4575
+ if (eq < 0 || !PARAM_NAME_PATTERN.test(name)) {
4576
+ throw new Error(`Invalid --param '${pair}' (expected name=value with a lowercase kebab-case name).`);
4577
+ }
4578
+ if (name in params) throw new Error(`--param '${name}' is set more than once.`);
4579
+ params[name] = pair.slice(eq + 1);
4580
+ }
4581
+ return params;
4582
+ }
4583
+ function interpolateOverlay(overlay, params, source) {
4584
+ const missing = /* @__PURE__ */ new Set();
4585
+ const visit = (value) => {
4586
+ if (typeof value === "string") {
4587
+ return value.replace(PARAM_PLACEHOLDER_PATTERN, (raw, escape, name) => {
4588
+ if (escape) return raw.slice(1);
4589
+ if (Object.hasOwn(params, name)) return params[name];
4590
+ missing.add(name);
4591
+ return raw;
4592
+ });
4593
+ }
4594
+ if (Array.isArray(value)) return value.map(visit);
4595
+ if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
4596
+ return value;
4597
+ };
4598
+ const result = visit(overlay);
4599
+ if (missing.size > 0) {
4600
+ const names = [...missing].sort();
4601
+ throw new Error(`Overlay ${source} needs ${names.map((name) => `--param ${name}=<value>`).join(", ")}.`);
4602
+ }
4603
+ return result;
4604
+ }
4605
+ async function loadOverlay(path, params = {}) {
4606
+ let text;
4607
+ try {
4608
+ text = await readFile(path, "utf8");
4609
+ } catch (error) {
4610
+ if (error?.code === "ENOENT") {
4611
+ throw new Error(`Overlay file not found: ${path}`);
4612
+ }
4613
+ throw error;
4614
+ }
4615
+ const parsed = parse(text);
4616
+ if (parsed === null || parsed === void 0) return {};
4617
+ if (!isPlainObject(parsed)) {
4618
+ throw new Error(`Overlay ${path} must be a YAML mapping (got ${Array.isArray(parsed) ? "a list" : typeof parsed}).`);
4619
+ }
4620
+ return interpolateOverlay(parsed, params, path);
4621
+ }
4150
4622
  var MIB = 1024 * 1024;
4151
4623
  var MAX_LOGO_BYTES = MIB;
4152
4624
  var MAX_IMAGE_BYTES = 5 * MIB;
@@ -4351,6 +4823,7 @@ function defaultIncludes(manifest) {
4351
4823
  const sources = /* @__PURE__ */ new Set();
4352
4824
  collectSchemaSources(manifest.spec, sources);
4353
4825
  collectInstallSources(manifest, sources);
4826
+ for (const path of agentAvatarPayloadPaths(manifest)) sources.add(path);
4354
4827
  if (sources.size === 0) return [];
4355
4828
  return [...sources];
4356
4829
  }
@@ -4383,48 +4856,6 @@ function collectSchemaSources(node, sources) {
4383
4856
  function toEntryPath2(file) {
4384
4857
  return file.split(sep).join("/");
4385
4858
  }
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
4859
  var VARIABLE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
4429
4860
  var PLACEHOLDER_PATTERN = /(?<!\$)\$\{var:([^}]*)\}/g;
4430
4861
  var ESCAPED_PLACEHOLDER_PATTERN = /\$\$\{var:([^}]*)\}/g;
@@ -4597,11 +5028,98 @@ function findPlaceholders(text) {
4597
5028
  }
4598
5029
  return placeholders;
4599
5030
  }
5031
+ var ARGUMENTS_SCHEMA = "verentis.io/script-arguments/v1";
5032
+ var ARGUMENTS_SUFFIX = ".arguments.json";
5033
+ var KINDS = /* @__PURE__ */ new Set(["option", "positional"]);
5034
+ var TYPES = /* @__PURE__ */ new Set(["string", "integer", "number", "boolean", "date"]);
5035
+ async function checkScriptArgumentDescriptors(projectDir, payloadFiles, readBytes) {
5036
+ const errors = [];
5037
+ const entries = new Map(payloadFiles.map((file) => [toEntryPath2(file), file]));
5038
+ for (const [entry, file] of entries) {
5039
+ if (entry.endsWith(ARGUMENTS_SUFFIX)) {
5040
+ errors.push(...await checkDescriptor(entry, file, entries, readBytes));
5041
+ } else if (!entries.has(entry + ARGUMENTS_SUFFIX) && await isFile(join(projectDir, file + ARGUMENTS_SUFFIX))) {
5042
+ errors.push(`${entry + ARGUMENTS_SUFFIX}: argument descriptor exists but is not included in packaging.files.`);
5043
+ }
5044
+ }
5045
+ return errors;
5046
+ }
5047
+ async function checkDescriptor(entry, file, entries, readBytes) {
5048
+ let descriptor;
5049
+ try {
5050
+ descriptor = JSON.parse((await readBytes(file)).toString("utf8"));
5051
+ } catch (error) {
5052
+ return [`${entry}: invalid JSON (${error instanceof Error ? error.message : String(error)}).`];
5053
+ }
5054
+ if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor)) return [`${entry}: must be a JSON object.`];
5055
+ const errors = [];
5056
+ const fail = (message) => errors.push(`${entry}: ${message}`);
5057
+ if (descriptor.schema !== ARGUMENTS_SCHEMA) fail(`schema must be '${ARGUMENTS_SCHEMA}'.`);
5058
+ const scriptEntry = entry.slice(0, -ARGUMENTS_SUFFIX.length);
5059
+ const scriptName = posix.basename(scriptEntry);
5060
+ if (descriptor.script !== void 0 && descriptor.script !== scriptName) {
5061
+ fail(`script '${String(descriptor.script)}' does not match the file it describes ('${scriptName}').`);
5062
+ }
5063
+ const scriptFile = entries.get(scriptEntry);
5064
+ if (!scriptFile) {
5065
+ fail(`describes '${scriptEntry}', which is not in the package.`);
5066
+ } else if (typeof descriptor.sourceSha256 === "string" && descriptor.sourceSha256) {
5067
+ const actual = createHash("sha256").update(await readBytes(scriptFile)).digest("hex");
5068
+ if (actual !== descriptor.sourceSha256.toLowerCase()) {
5069
+ fail(`is stale: '${scriptEntry}' changed since it was exported. Re-run the SDK argument export.`);
5070
+ }
5071
+ }
5072
+ const definitions = descriptor.arguments;
5073
+ if (!Array.isArray(definitions)) {
5074
+ fail("arguments must be an array.");
5075
+ } else {
5076
+ const names = /* @__PURE__ */ new Set();
5077
+ const flags = /* @__PURE__ */ new Set();
5078
+ for (const [index, raw] of definitions.entries()) {
5079
+ const definition = raw ?? {};
5080
+ const name = typeof definition.name === "string" ? definition.name : "";
5081
+ const at = name ? `argument '${name}'` : `arguments[${index}]`;
5082
+ if (!name) fail(`${at} needs a name.`);
5083
+ else if (names.has(name)) fail(`${at} is declared twice.`);
5084
+ names.add(name);
5085
+ if (!KINDS.has(String(definition.kind))) fail(`${at} has unsupported kind '${String(definition.kind)}'.`);
5086
+ if (!TYPES.has(String(definition.type))) fail(`${at} has unsupported type '${String(definition.type)}'.`);
5087
+ if (definition.kind === "option") {
5088
+ const declared = [...asStrings(definition.flags), ...asStrings([definition.negation])];
5089
+ if (!asStrings(definition.flags).length) fail(`${at} needs at least one flag.`);
5090
+ for (const flag of declared) {
5091
+ if (flags.has(flag)) fail(`flag '${flag}' is declared twice.`);
5092
+ flags.add(flag);
5093
+ }
5094
+ }
5095
+ }
5096
+ for (const group of Array.isArray(descriptor.exclusiveGroups) ? descriptor.exclusiveGroups : []) {
5097
+ for (const name of asStrings(group?.arguments)) {
5098
+ if (!names.has(name)) fail(`exclusive group refers to unknown argument '${name}'.`);
5099
+ }
5100
+ }
5101
+ }
5102
+ const variants = descriptor.variants;
5103
+ for (const sibling of asStrings(Object.values(variants?.scripts ?? {}))) {
5104
+ if (/[\\/]/.test(sibling) || sibling === "." || sibling === "..") {
5105
+ fail(`variant script '${sibling}' must be a file next to '${scriptName}'.`);
5106
+ continue;
5107
+ }
5108
+ const siblingEntry = posix.join(posix.dirname(scriptEntry), sibling);
5109
+ if (!entries.has(siblingEntry)) fail(`variant script '${siblingEntry}' is not in the package.`);
5110
+ }
5111
+ return errors;
5112
+ }
5113
+ var asStrings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string" && item.length > 0) : [];
5114
+ async function isFile(path) {
5115
+ return (await stat(path).catch(() => null))?.isFile() ?? false;
5116
+ }
5117
+ var RUN_SIZES = ["xsmall", "small", "medium", "large", "xlarge", "xxlarge", "gpu"];
4600
5118
  var MAX_SCRIPT_FILE_ACCESS = 16;
4601
5119
  var MAX_PACKAGE_FILE_ACCESS = 64;
4602
5120
  var MAX_BOUNDARY_BYTES = 2048;
4603
- var READ_ACTIONS = ["node.file.read"];
4604
- var WRITE_ACTIONS = ["node.file.read", "node.node.create", "node.node.update", "node.journal.create"];
5121
+ var READ_ACTIONS = ["file.read"];
5122
+ var WRITE_ACTIONS = ["file.read", "file.write"];
4605
5123
  var IDENTIFIER = "00000000-0000-0000-0000-000000000000";
4606
5124
  var boundaryEntry = (type, mode) => ({ type, identifier: IDENTIFIER, actions: mode === "write" ? WRITE_ACTIONS : READ_ACTIONS });
4607
5125
  function estimateBoundaryBytes(modes, kind) {
@@ -4628,8 +5146,10 @@ function validateFileAccess(value, label, max, kind = "document") {
4628
5146
  if (pathError) errors.push(`${at}.path ${pathError}`);
4629
5147
  if (item.origin !== void 0) {
4630
5148
  const origin = item.origin;
4631
- if (!origin || typeof origin !== "object" || origin.kind !== "script" && origin.kind !== "document" || typeof origin.name !== "string" || !origin.name.trim()) {
4632
- errors.push(`${at}.origin needs kind 'script' or 'document' and a name.`);
5149
+ if (!origin || typeof origin !== "object" || origin.kind !== "script" && origin.kind !== "document" || typeof origin.id !== "string" || !origin.id.trim()) {
5150
+ errors.push(`${at}.origin needs kind 'script' or 'document' and an id.`);
5151
+ } else if (Object.prototype.hasOwnProperty.call(origin, "name")) {
5152
+ errors.push(`${at}.origin.name is no longer supported; use origin.id.`);
4633
5153
  }
4634
5154
  }
4635
5155
  });
@@ -4643,9 +5163,9 @@ function boundarySizeErrors(entries, label, kind) {
4643
5163
  if (item.mode !== "read" && item.mode !== "write" || typeof item.path !== "string") continue;
4644
5164
  const origin = item.origin;
4645
5165
  const originKind = origin?.kind === "script" || origin?.kind === "document" ? origin.kind : kind;
4646
- const name = typeof origin?.name === "string" ? origin.name.trim() : void 0;
4647
- const key = `${originKind}:${name ?? ""}`;
4648
- const group = origins.get(key) ?? { kind: originKind, name, paths: /* @__PURE__ */ new Map() };
5166
+ const id = typeof origin?.id === "string" ? origin.id.trim() : void 0;
5167
+ const key = `${originKind}:${id ?? ""}`;
5168
+ const group = origins.get(key) ?? { kind: originKind, id, paths: /* @__PURE__ */ new Map() };
4649
5169
  origins.set(key, group);
4650
5170
  const path = item.path.trim();
4651
5171
  group.paths.set(path, group.paths.get(path) === "write" ? "write" : item.mode);
@@ -4654,7 +5174,7 @@ function boundarySizeErrors(entries, label, kind) {
4654
5174
  for (const group of origins.values()) {
4655
5175
  const bytes = estimateBoundaryBytes([...group.paths.values()], group.kind);
4656
5176
  if (bytes <= MAX_BOUNDARY_BYTES) continue;
4657
- const subject = group.name ? ` for ${group.kind} '${group.name}'` : "";
5177
+ const subject = group.id ? ` for ${group.kind} '${group.id}'` : "";
4658
5178
  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).`);
4659
5179
  }
4660
5180
  return errors;
@@ -4691,24 +5211,35 @@ async function collectScriptFileAccess(projectDir, spec) {
4691
5211
  if (!(await stat(directory).catch(() => null))?.isDirectory()) continue;
4692
5212
  const manifest = await findScriptRun(directory);
4693
5213
  if (!manifest) continue;
5214
+ const metadataErrors = validateDocumentMetadata(manifest.document.metadata);
5215
+ if (metadataErrors.length > 0) {
5216
+ errors.push(...metadataErrors.map((message) => `${script}: ScriptRun ${message}.`));
5217
+ continue;
5218
+ }
5219
+ const sizeError = validateRunSize(manifest.document.resources);
5220
+ if (sizeError) errors.push(`${script}: ScriptRun ${sizeError}`);
4694
5221
  const label = `${script}: file-access`;
4695
5222
  const declared = manifest.document["file-access"];
4696
5223
  const scriptErrors = validateFileAccess(declared, label, MAX_SCRIPT_FILE_ACCESS, "script");
4697
5224
  errors.push(...scriptErrors);
4698
5225
  if (scriptErrors.length > 0 || !Array.isArray(declared)) continue;
4699
- const metadata = manifest.document.metadata;
4700
- const name = typeof metadata?.name === "string" && metadata.name.trim() ? metadata.name.trim() : basename(directory);
5226
+ const id = manifest.document.metadata.id.trim();
4701
5227
  for (const entry of declared) {
4702
5228
  entries.push({
4703
5229
  path: entry.path.trim(),
4704
5230
  mode: entry.mode,
4705
5231
  ...typeof entry.reason === "string" ? { reason: entry.reason } : {},
4706
- origin: { kind: "script", name }
5232
+ origin: { kind: "script", id }
4707
5233
  });
4708
5234
  }
4709
5235
  }
4710
5236
  return { entries, errors };
4711
5237
  }
5238
+ function validateRunSize(resources) {
5239
+ const size = resources && typeof resources === "object" ? resources.size : void 0;
5240
+ if (typeof size !== "string" || size.trim() === "") return `resources.size is required: one of ${RUN_SIZES.join(", ")}.`;
5241
+ return RUN_SIZES.includes(size.trim().toLowerCase()) ? void 0 : `resources.size '${size.trim()}' is not one of ${RUN_SIZES.join(", ")}.`;
5242
+ }
4712
5243
  async function findScriptRun(directory) {
4713
5244
  const names = (await readdir(directory)).filter((name) => /\.ya?ml$/i.test(name)).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
4714
5245
  for (const name of names) {
@@ -4726,7 +5257,7 @@ var rank = (name) => name === "verentis.run.yaml" ? 0 : name === "manifest.yaml"
4726
5257
  function mergeFileAccess(spec, additions) {
4727
5258
  if (!spec || additions.length === 0) return spec;
4728
5259
  const existing = Array.isArray(spec["file-access"]) ? spec["file-access"] : [];
4729
- const key = (entry) => `${entry.mode}|${entry.path}|${entry.origin ? `${entry.origin.kind}:${entry.origin.name}` : ""}`;
5260
+ const key = (entry) => `${entry.mode}|${entry.path}|${entry.origin ? `${entry.origin.kind}:${entry.origin.id}` : ""}`;
4730
5261
  const seen = new Set(existing.map(key));
4731
5262
  const added = additions.filter((entry) => !seen.has(key(entry)) && seen.add(key(entry)));
4732
5263
  return added.length === 0 ? spec : { ...spec, "file-access": [...existing, ...added] };
@@ -4741,15 +5272,15 @@ async function pack(options) {
4741
5272
  throw new Error("Use either --set-version or --bump-version, not both.");
4742
5273
  }
4743
5274
  const overlayPath = resolveOverlayPath(projectDir, { env: options.env, overlay: options.overlay });
4744
- const overlay = overlayPath ? await loadOverlay(overlayPath) : void 0;
5275
+ const overlay = overlayPath ? await loadOverlay(overlayPath, options.params) : void 0;
4745
5276
  if (options.bumpVersion) {
4746
5277
  const nextVersion = await bumpManifestPatchVersion(manifestPath, base.metadata.version);
4747
5278
  base.metadata.version = nextVersion;
4748
5279
  }
4749
5280
  let manifest = overlay ? applyOverlay(base, overlay) : base;
4750
5281
  let overrideApplied = overlayPath !== void 0 || options.bumpVersion === true;
4751
- if (options.name !== void 0) {
4752
- manifest = { ...manifest, metadata: { ...manifest.metadata, "package-id": options.name } };
5282
+ if (options.packageId !== void 0) {
5283
+ manifest = { ...manifest, metadata: { ...manifest.metadata, id: options.packageId } };
4753
5284
  overrideApplied = true;
4754
5285
  }
4755
5286
  if (options.version !== void 0) {
@@ -4765,8 +5296,10 @@ async function pack(options) {
4765
5296
  if (marketplaceErrors.length > 0) throw new Error(`Invalid marketplace section: ${marketplaceErrors.join(" ")}`);
4766
5297
  const typeValidator = validatorForKind(kind);
4767
5298
  const payloadErrors = await typeValidator?.validatePayload?.(projectDir, manifest) ?? [];
4768
- if (payloadErrors.length > 0) throw new Error(`Invalid ${kind} payload:
4769
- ${payloadErrors.join("\n ")}`);
5299
+ const avatarPayloadErrors = await validateAgentAvatarPayload(projectDir, manifest);
5300
+ const allPayloadErrors = [...payloadErrors, ...avatarPayloadErrors];
5301
+ if (allPayloadErrors.length > 0) throw new Error(`Invalid ${kind} payload:
5302
+ ${allPayloadErrors.join("\n ")}`);
4770
5303
  const authoredManifest = manifest;
4771
5304
  manifest = typeValidator?.expandForPack ? typeValidator.expandForPack(manifest) : manifest;
4772
5305
  const normalizedSpec = normalizeDependencies(manifest.spec);
@@ -4782,19 +5315,27 @@ async function pack(options) {
4782
5315
  if (packageAccessErrors.length > 0) throw new Error(`Invalid file-access: ${packageAccessErrors.join(" ")}`);
4783
5316
  if (manifest !== authoredManifest) overrideApplied = true;
4784
5317
  const expandedInstall = expandedInstallSources(authoredManifest, manifest);
4785
- const packageId = manifest.metadata["package-id"].toLowerCase();
4786
- const name = manifest.metadata.name.toLowerCase();
5318
+ const packageId = manifest.metadata.id.toLowerCase();
4787
5319
  const publisher = options.publisher.toLowerCase();
4788
5320
  validatePackageName(packageId, "package ID");
4789
- validatePackageName(name, "runtime name");
4790
5321
  validatePackageName(publisher, "publisher name");
4791
5322
  const version = manifest.metadata.version;
4792
5323
  const payloadFiles = await resolvePayloadFiles(projectDir, manifestPath, manifest);
5324
+ const avatarInclusionErrors = validateAgentAvatarPayloadFiles(manifest, payloadFiles);
5325
+ if (avatarInclusionErrors.length > 0) throw new Error(`Invalid ${kind} payload:
5326
+ ${avatarInclusionErrors.join("\n ")}`);
4793
5327
  const missingSources = expandedInstall.filter((from) => !payloadFiles.some((file) => toEntryPath2(file) === from));
4794
5328
  if (missingSources.length > 0) {
4795
5329
  throw new Error(`packaging.files does not include ${missingSources.join(", ")} declared by spec.assets.`);
4796
5330
  }
4797
5331
  const templatePlan = await createTemplatePlan(projectDir, manifest, payloadFiles);
5332
+ const argumentErrors = await checkScriptArgumentDescriptors(
5333
+ projectDir,
5334
+ payloadFiles,
5335
+ (file) => readTemplatedPayloadBytes(projectDir, file, templatePlan)
5336
+ );
5337
+ if (argumentErrors.length > 0) throw new Error(`Invalid script argument descriptors:
5338
+ ${argumentErrors.join("\n ")}`);
4798
5339
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
4799
5340
  const packedManifest = stripTemplatePackagingFields(manifest);
4800
5341
  const manifestSanitized = packedManifest !== manifest;
@@ -4816,15 +5357,21 @@ async function pack(options) {
4816
5357
  const digests = {
4817
5358
  "manifest.yaml": sha256Hex(Buffer.from(manifestText, "utf8"))
4818
5359
  };
5360
+ const documentErrors = [];
4819
5361
  for (const file of payloadFiles) {
4820
5362
  const entryName = `files/${toEntryPath2(file)}`;
4821
5363
  const targetPath = join(staging, "files", file);
4822
5364
  await mkdir(dirname(targetPath), { recursive: true });
4823
5365
  const payloadBytes = await readTemplatedPayloadBytes(projectDir, file, templatePlan);
5366
+ if (/\.ya?ml$/i.test(file)) {
5367
+ documentErrors.push(...payloadDocumentMetadataErrors(Buffer.from(payloadBytes).toString("utf8")).map((message) => `${toEntryPath2(file)}: ${message}`));
5368
+ }
4824
5369
  const bytes = contentKey ? encryptBytes(contentKey, payloadBytes) : payloadBytes;
4825
5370
  await writeFile(targetPath, bytes);
4826
5371
  digests[entryName] = sha256Hex(bytes);
4827
5372
  }
5373
+ if (documentErrors.length > 0) throw new Error(`Invalid documents:
5374
+ ${documentErrors.join("\n ")}`);
4828
5375
  if (catalog) {
4829
5376
  for (const entry of catalog.entries) {
4830
5377
  const targetPath = join(staging, entry.path);
@@ -4848,12 +5395,11 @@ async function pack(options) {
4848
5395
  const digestsJson = JSON.stringify({ algorithm: "sha256", entries: digests }, null, 2);
4849
5396
  await writeFile(join(staging, ".verentis", "digests.json"), digestsJson);
4850
5397
  const packageYaml = [
4851
- `package-id: ${packageId}`,
4852
- `name: ${name}`,
5398
+ `id: ${packageId}`,
4853
5399
  `publisher: ${publisher}`,
4854
5400
  `version: ${version}`,
4855
5401
  `kind: ${kind}`,
4856
- ...manifest.metadata["display-name"] ? [`display-name: ${JSON.stringify(manifest.metadata["display-name"])}`] : [],
5402
+ ...manifest.metadata.name ? [`name: ${JSON.stringify(manifest.metadata.name)}`] : [],
4857
5403
  ""
4858
5404
  ].join("\n");
4859
5405
  await writeFile(join(staging, ".verentis", "package.yaml"), packageYaml);
@@ -4880,7 +5426,6 @@ async function pack(options) {
4880
5426
  return {
4881
5427
  outFile,
4882
5428
  packageId,
4883
- name,
4884
5429
  publisher,
4885
5430
  version,
4886
5431
  kind,
@@ -4920,8 +5465,8 @@ async function readVpkg(vpkgPath) {
4920
5465
  throw new Error("Invalid package: missing .verentis/digests.json.");
4921
5466
  });
4922
5467
  const metadata = parse(packageYaml);
4923
- if (!metadata?.["package-id"]) {
4924
- throw new Error("Invalid package: .verentis/package.yaml is missing package-id.");
5468
+ if (!metadata?.id) {
5469
+ throw new Error("Invalid package: .verentis/package.yaml is missing id.");
4925
5470
  }
4926
5471
  const declared = JSON.parse(digestsJson);
4927
5472
  const files2 = await listFiles(staging, "files/**/*");
@@ -4998,8 +5543,10 @@ async function readJsonIfExists(path) {
4998
5543
  }
4999
5544
 
5000
5545
  // src/commands/pack.ts
5546
+ 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.";
5001
5547
  function registerPack(program2) {
5002
- 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) => {
5548
+ 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) => {
5549
+ const params = parseOverlayParams(options.param);
5003
5550
  const projectDir = resolve(dir ?? ".");
5004
5551
  const manifestPath = options.manifest ? resolve(options.manifest) : await findManifest(projectDir);
5005
5552
  await ensurePackageTypeKnown((await readManifestDocument(manifestPath)).kind);
@@ -5012,11 +5559,10 @@ function registerPack(program2) {
5012
5559
  let signingKey;
5013
5560
  if (options.sign) {
5014
5561
  const keyName = options.key ?? config.defaultKey;
5015
- if (keyName) {
5016
- signingKey = await loadKey(keyName);
5017
- } else {
5018
- console.warn("Warning: no signing key configured \u2014 producing an UNSIGNED package. Run `verentis keygen` to create one.");
5019
- }
5562
+ if (!keyName) throw new Error(noSigningKeyMessage);
5563
+ signingKey = await loadKey(keyName);
5564
+ } else {
5565
+ console.warn("Warning: --no-sign produces an UNSIGNED package. The registry rejects unsigned packages, so it cannot be published.");
5020
5566
  }
5021
5567
  let encryptFor;
5022
5568
  if (options.encrypt || manifest.packaging?.encryption === "required") {
@@ -5034,9 +5580,10 @@ function registerPack(program2) {
5034
5580
  const result = await pack({
5035
5581
  manifestPath,
5036
5582
  publisher,
5037
- name: options.name,
5583
+ packageId: options.id,
5038
5584
  env: options.env,
5039
5585
  overlay: options.overlay,
5586
+ params,
5040
5587
  version: options.setVersion,
5041
5588
  bumpVersion: options.bumpVersion || options.bump,
5042
5589
  outDir: options.out,
@@ -5057,7 +5604,7 @@ function registerPack(program2) {
5057
5604
  });
5058
5605
  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) => {
5059
5606
  const contents = await readVpkg(resolve(vpkgPath));
5060
- console.log(`${contents.metadata.publisher}/${contents.metadata["package-id"]}@${contents.metadata.version} (${contents.metadata.kind})`);
5607
+ console.log(`${contents.metadata.publisher}/${contents.metadata.id}@${contents.metadata.version} (${contents.metadata.kind})`);
5061
5608
  console.log(` payload files: ${contents.files.length}, catalog files: ${contents.catalogFiles.length}, tree digest ${contents.treeDigest.slice(0, 16)}\u2026`);
5062
5609
  if (contents.catalog) {
5063
5610
  const docs = Number(!!contents.catalog.readme) + Number(!!contents.catalog.changelog);
@@ -5091,6 +5638,9 @@ function registerPack(program2) {
5091
5638
  if (contents.marketplaceSignature) console.log(" \u2713 marketplace countersignature present");
5092
5639
  });
5093
5640
  }
5641
+ function collectParams(value, previous) {
5642
+ return [...previous, value];
5643
+ }
5094
5644
  function collectRecipients(value, previous) {
5095
5645
  const eq = value.indexOf("=");
5096
5646
  if (eq <= 0) throw new Error(`Invalid --recipient '${value}' \u2014 expected id=base64PublicKey.`);
@@ -5100,66 +5650,59 @@ function collectRecipients(value, previous) {
5100
5650
  // src/commands/package.ts
5101
5651
  function registerPackage(program2) {
5102
5652
  const pkgCmd = program2.command("package").description("Manage marketplace packages");
5103
- pkgCmd.command("list").description("List your publisher's packages").option("--json", "output JSON").action(async (options) => {
5653
+ pkgCmd.command("list").description("List your publisher's packages in the registry").option("--json", "output JSON").action(async (options) => {
5104
5654
  const api = await createApiClient();
5105
- const publisher = await requireMyPublisher(api);
5106
- const page = await call(api, marketplace.listPublisherPackages, {
5107
- params: { publisherId: publisher.id },
5108
- query: { PageNo: 1, PageSize: 100 }
5109
- });
5110
- output(pageItems(page), { packageId: "Package", name: "Runtime", kind: "Kind", visibility: "Visibility", latestPublishedVersion: "Latest", id: "Id" }, options, page);
5655
+ const publisher = await requireRegistryPublisher(api);
5656
+ if (!publisher.name) throw new Error("Cannot resolve your publisher name. Run `verentis login` again.");
5657
+ const packages = await listRegistryPackages(api, publisher.name);
5658
+ output(
5659
+ packages.map((p) => ({ ...p, versionCount: p.versions.length })),
5660
+ { packageId: "Package", kind: "Kind", visibility: "Visibility", latestVersion: "Latest", versionCount: "Versions", archived: "Archived", id: "Id" },
5661
+ options
5662
+ );
5111
5663
  });
5112
- pkgCmd.command("info <ref>").description("Show package details (ref: 'package-id' or 'publisher/package-id')").option("--json", "output JSON").action(async (ref, options) => {
5664
+ 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) => {
5113
5665
  const api = await createApiClient();
5114
- const { package: pkg } = await resolvePackageRef(api, ref);
5115
- const detail = await call(api, marketplace.getPackage, { params: { id: pkg.id } });
5116
- outputRecord(detail, options);
5666
+ const { versions, ...pkg } = await getRegistryPackage(api, await resolveRegistryPackageRef(api, ref));
5667
+ outputRecord({ ...pkg, versionCount: versions.length }, options);
5117
5668
  });
5118
- pkgCmd.command("versions <ref>").description("List versions of a package").option("--json", "output JSON").action(async (ref, options) => {
5669
+ 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) => {
5119
5670
  const api = await createApiClient();
5120
- const { package: pkg } = await resolvePackageRef(api, ref);
5121
- const page = await call(api, marketplace.listVersions, {
5122
- params: { packageId: pkg.id },
5123
- query: { PageNo: 1, PageSize: 100 }
5124
- });
5125
- output(pageItems(page), { version: "Version", status: "Status", sizeBytes: "Size", hasMarketplaceSignature: "Countersigned", id: "Id" }, options, page);
5671
+ const pkg = await getRegistryPackage(api, await resolveRegistryPackageRef(api, ref));
5672
+ output(pkg.versions.map((v) => ({ ...v })), { version: "Version", status: "Status", deprecated: "Deprecated", publishedAt: "Published", yankedAt: "Yanked", sizeBytes: "Size", id: "Id" }, options);
5126
5673
  });
5127
- 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) => {
5128
- const api = await createApiClient();
5129
- const { package: pkg } = await resolvePackageRef(api, ref);
5130
- const current2 = await call(api, marketplace.getPackage, { params: { id: pkg.id } });
5131
- await call(api, marketplace.updatePackage, {
5132
- params: { id: pkg.id },
5133
- body: {
5134
- id: pkg.id,
5135
- displayName: options.displayName ?? current2.displayName,
5136
- description: options.description ?? current2.description ?? null,
5137
- icon: options.icon ?? current2.icon ?? null,
5138
- categories: options.categories ?? current2.categories ?? []
5139
- }
5140
- });
5141
- console.log(`Package ${ref} updated.`);
5674
+ pkgCmd.command("update <ref>").description("(removed) Package metadata comes from the signed manifest \u2014 edit it, `verentis pack`, then `verentis publish`").allowUnknownOption().action(() => {
5675
+ throw new Error(
5676
+ "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."
5677
+ );
5142
5678
  });
5143
- 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) => {
5679
+ 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) => {
5144
5680
  const api = await createApiClient();
5145
- const { package: pkg } = await resolvePackageRef(api, ref);
5146
- await call(api, marketplace.deprecatePackage, {
5147
- params: { id: pkg.id },
5148
- body: { id: pkg.id, message: options.message ?? null, replacementPackageId: options.replacement ?? null }
5149
- });
5150
- console.log(`Package ${ref} deprecated.`);
5681
+ const target = await resolveRegistryPackageRef(api, ref);
5682
+ if (version) {
5683
+ await deprecateVersion(api, target, version, options.message);
5684
+ console.log(`Version ${target.publisher}/${target.packageId}@${version} deprecated.`);
5685
+ } else {
5686
+ await deprecatePackage(api, target, options.message);
5687
+ console.log(`Package ${target.publisher}/${target.packageId} deprecated.`);
5688
+ }
5151
5689
  });
5152
- pkgCmd.command("undeprecate <ref>").description("Remove the deprecation flag from a package").action(async (ref) => {
5690
+ pkgCmd.command("undeprecate <ref> [version]").description("Remove the deprecation flag from a package (or one version)").action(async (ref, version) => {
5153
5691
  const api = await createApiClient();
5154
- const { package: pkg } = await resolvePackageRef(api, ref);
5155
- await call(api, marketplace.undeprecatePackage, { params: { id: pkg.id } });
5156
- console.log(`Package ${ref} restored.`);
5692
+ const target = await resolveRegistryPackageRef(api, ref);
5693
+ if (version) {
5694
+ await undeprecateVersion(api, target, version);
5695
+ console.log(`Version ${target.publisher}/${target.packageId}@${version} restored.`);
5696
+ } else {
5697
+ await undeprecatePackage(api, target);
5698
+ console.log(`Package ${target.publisher}/${target.packageId} restored.`);
5699
+ }
5157
5700
  });
5158
- pkgCmd.command("archive <ref>").description("Archive (soft-delete) a package \u2014 it disappears from the catalog").action(async (ref) => {
5701
+ 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) => {
5159
5702
  const api = await createApiClient();
5160
- const { package: pkg } = await resolvePackageRef(api, ref);
5161
- await call(api, marketplace.archivePackage, { params: { id: pkg.id } });
5162
- console.log(`Package ${ref} archived.`);
5703
+ const target = await resolveRegistryPackageRef(api, ref);
5704
+ await archivePackage(api, target);
5705
+ console.log(`Package ${target.publisher}/${target.packageId} archived.`);
5163
5706
  });
5164
5707
  pkgCmd.command("stats <ref>").description("Show download/install statistics for a package").action(async (ref) => {
5165
5708
  const api = await createApiClient();
@@ -5167,32 +5710,31 @@ function registerPackage(program2) {
5167
5710
  const stats = await call(api, marketplace.getPackageStats, { params: { packageId: pkg.id } });
5168
5711
  printJson(stats);
5169
5712
  });
5170
- const visibilityCmd = pkgCmd.command("visibility").description("Manage private-package visibility");
5713
+ const visibilityCmd = pkgCmd.command("visibility").description("Manage package visibility in the registry");
5171
5714
  visibilityCmd.command("set <ref> <visibility>").description("Set catalog visibility: Public | Private").action(async (ref, visibility) => {
5715
+ const value = parseVisibility(visibility);
5172
5716
  const api = await createApiClient();
5173
- const { package: pkg } = await resolvePackageRef(api, ref);
5174
- await call(api, marketplace.setPackageVisibility, { params: { id: pkg.id }, body: { id: pkg.id, visibility } });
5175
- console.log(`Package ${ref} visibility \u2192 ${visibility}.`);
5717
+ const target = await resolveRegistryPackageRef(api, ref);
5718
+ await setPackageVisibility(api, target, value);
5719
+ console.log(`Package ${target.publisher}/${target.packageId} visibility \u2192 ${value}.`);
5176
5720
  });
5177
5721
  visibilityCmd.command("grants <ref>").description("List visibility grants of a private package").option("--json", "output JSON").action(async (ref, options) => {
5178
5722
  const api = await createApiClient();
5179
- const { package: pkg } = await resolvePackageRef(api, ref);
5180
- const grants = await call(api, marketplace.listVisibilityGrants, { params: { packageId: pkg.id } });
5181
- output(grants ?? [], { granteeType: "Type", granteeId: "Grantee", id: "GrantId" }, options, grants);
5723
+ const target = await resolveRegistryPackageRef(api, ref);
5724
+ const grants = await listVisibilityGrants(api, target);
5725
+ output(grants, { granteeType: "Type", granteeId: "Grantee", id: "GrantId" }, options, grants);
5182
5726
  });
5183
5727
  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) => {
5728
+ const granteeType = parseGranteeType(options.type);
5184
5729
  const api = await createApiClient();
5185
- const { package: pkg } = await resolvePackageRef(api, ref);
5186
- await call(api, marketplace.grantVisibility, {
5187
- params: { packageId: pkg.id },
5188
- body: { packageId: pkg.id, granteeType: options.type, granteeId }
5189
- });
5190
- console.log(`Visibility of ${ref} granted to ${options.type} ${granteeId}.`);
5730
+ const target = await resolveRegistryPackageRef(api, ref);
5731
+ const grant = await grantVisibility(api, target, granteeType, granteeId);
5732
+ console.log(`Visibility of ${target.publisher}/${target.packageId} granted to ${granteeType} ${granteeId}${grant?.id ? ` (grant ${grant.id})` : ""}.`);
5191
5733
  });
5192
5734
  visibilityCmd.command("revoke <ref> <grantId>").description("Revoke a visibility grant").action(async (ref, grantId) => {
5193
5735
  const api = await createApiClient();
5194
- const { package: pkg } = await resolvePackageRef(api, ref);
5195
- await call(api, marketplace.revokeVisibility, { params: { packageId: pkg.id, grantId } });
5736
+ const target = await resolveRegistryPackageRef(api, ref);
5737
+ await revokeVisibility(api, target, grantId);
5196
5738
  console.log(`Visibility grant ${grantId} revoked.`);
5197
5739
  });
5198
5740
  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) => {
@@ -5203,8 +5745,58 @@ function registerPackage(program2) {
5203
5745
  output(pageItems(page), { packageName: "Package", version: "Version", status: "Status", installPath: "Path", id: "Id" }, options, page);
5204
5746
  });
5205
5747
  }
5206
- var POLICY_READ_SCOPE = "fabric.policy.read";
5207
- var POLICY_UPDATE_SCOPE = "fabric.policy.update";
5748
+
5749
+ // src/commands/notifications.ts
5750
+ function registerNotifications(program2) {
5751
+ const notifications = program2.command("notifications").description("Manage package notification delivery");
5752
+ const sender = notifications.command("sender").description("Manage a package email sender connection");
5753
+ sender.command("show <package>").description("Show the configured notification email sender without revealing its API key").option("--json", "output JSON").action(async (packageRef, options) => {
5754
+ const { api, publisherId, packageOwner } = await resolveSenderTarget(packageRef);
5755
+ const status = await getPublisherEmailSender(api, publisherId, packageOwner);
5756
+ outputRecord({
5757
+ packageOwner: status.packageOwner,
5758
+ provider: status.provider,
5759
+ from: status.from,
5760
+ replyTo: status.replyTo,
5761
+ domain: status.domain,
5762
+ region: status.region,
5763
+ keyLastFour: status.keyLastFour,
5764
+ keyFingerprint: status.keyFingerprint,
5765
+ validationStatus: status.validationStatus,
5766
+ validationMessage: status.validationMessage,
5767
+ validatedAt: status.validatedAt,
5768
+ version: status.version,
5769
+ revoked: status.revoked,
5770
+ webhookStatus: status.webhookStatus,
5771
+ webhookMessage: status.webhookMessage,
5772
+ webhookUrl: status.webhookUrl
5773
+ }, options);
5774
+ });
5775
+ sender.command("revoke <package>").description("Revoke a package email sender connection").action(async (packageRef) => {
5776
+ const { api, publisherId, packageOwner, publisherName } = await resolveSenderTarget(packageRef);
5777
+ const status = await revokePublisherEmailSender(api, publisherId, packageOwner);
5778
+ console.log(`Revoked notification sender for ${publisherName}/${packageOwner} (version ${status.version}).`);
5779
+ });
5780
+ }
5781
+ async function resolveSenderTarget(packageRef) {
5782
+ const api = await createApiClient();
5783
+ const publisher = await requireRegistryPublisher(api);
5784
+ if (!publisher.name) {
5785
+ throw new Error("Cannot resolve your publisher name. Run `verentis login` again.");
5786
+ }
5787
+ const target = await resolveRegistryPackageRef(api, packageRef);
5788
+ if (target.publisher.toLowerCase() !== publisher.name.toLowerCase()) {
5789
+ throw new Error("You can only manage notification senders for your own publisher packages.");
5790
+ }
5791
+ return {
5792
+ api,
5793
+ publisherId: publisher.id,
5794
+ publisherName: publisher.name,
5795
+ packageOwner: target.packageId.toLowerCase()
5796
+ };
5797
+ }
5798
+ var POLICY_READ_SCOPE = "governance.read";
5799
+ var POLICY_UPDATE_SCOPE = "governance.write";
5208
5800
  function registerPolicy(program2) {
5209
5801
  const policyCmd = program2.command("policy").description("Export and apply workspace policy manifests");
5210
5802
  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) => {
@@ -5332,29 +5924,9 @@ function unsupportedLogoError() {
5332
5924
 
5333
5925
  // src/commands/publisher.ts
5334
5926
  function registerPublisher(program2) {
5335
- const publisherCmd = program2.command("publisher").description("Manage your publisher profile");
5336
- 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) => {
5337
- const api = await createApiClient();
5338
- const existing = await getMyPublisher(api);
5339
- if (existing) {
5340
- console.log(`This account already has publisher '${existing.name}'.`);
5341
- return;
5342
- }
5343
- const id = await call(api, marketplace.createPublisher, {
5344
- body: {
5345
- name: options.name,
5346
- displayName: options.displayName,
5347
- description: options.description ?? null,
5348
- websiteUrl: options.website ?? null,
5349
- contactEmail: options.email ?? null
5350
- }
5351
- });
5352
- console.log(`Publisher '${options.name}' created (${id}).`);
5353
- if (options.logo) {
5354
- await uploadPublisherLogo(api, id, options.logo);
5355
- console.log(`Publisher logo uploaded from ${options.logo}.`);
5356
- }
5357
- console.log("Next: generate and register a signing key with `verentis keygen`.");
5927
+ const publisherCmd = program2.command("publisher").description("Manage your publisher profile (global registry)");
5928
+ publisherCmd.command("create").description("Publishers are created in the account app (they belong to an account)").allowUnknownOption().allowExcessArguments().action(async () => {
5929
+ throw new Error(noPublisherMessage(requireApiUrl(await loadConfig())));
5358
5930
  });
5359
5931
  publisherCmd.command("update").description("Update your publisher profile").option("--display-name <displayName>").option("--description <description>").option("--website <url>").option("--email <email>").action(async (options) => {
5360
5932
  if (Object.values(options).every((value) => value === void 0)) {
@@ -5365,7 +5937,6 @@ function registerPublisher(program2) {
5365
5937
  await call(api, marketplace.updatePublisher, {
5366
5938
  params: { id: current2.id },
5367
5939
  body: {
5368
- id: current2.id,
5369
5940
  displayName: options.displayName ?? current2.displayName,
5370
5941
  description: options.description ?? current2.description ?? null,
5371
5942
  websiteUrl: options.website ?? current2.websiteUrl ?? null,
@@ -5444,17 +6015,7 @@ async function installGraph(api, workspaceId, packageId, options) {
5444
6015
  if (options.operation || options.consent) {
5445
6016
  if (!options.operation || !options.consent) throw new Error("--operation and --consent must be supplied together.");
5446
6017
  const result = await api.request("POST", "/v1/installations/graphs", {
5447
- scopes: [
5448
- SCOPES.installCreate,
5449
- "marketplace.install.update",
5450
- NODE.nodeCreate,
5451
- NODE.fileRead,
5452
- NODE.fileDelete,
5453
- NODE.nodeUpdate,
5454
- NODE.journalCreate,
5455
- SCOPES.resourceReadAll,
5456
- SCOPES.resourceUpdate
5457
- ],
6018
+ scopes: [SCOPES.installCreate, NODE.nodeCreate, NODE.fileRead, NODE.fileDelete, SCOPES.installationRead, SCOPES.resourceReadAll],
5458
6019
  tokenWorkspaceId: workspaceId,
5459
6020
  body: { workspaceId, operationId: options.operation, fingerprint: options.consent, consent: true }
5460
6021
  });
@@ -5463,7 +6024,7 @@ async function installGraph(api, workspaceId, packageId, options) {
5463
6024
  return;
5464
6025
  }
5465
6026
  const preview = await api.request("POST", "/v1/installations/graphs/preview", {
5466
- scopes: [SCOPES.installCreate],
6027
+ scopes: [SCOPES.installRead],
5467
6028
  tokenWorkspaceId: workspaceId,
5468
6029
  body: {
5469
6030
  workspaceId,
@@ -5479,6 +6040,7 @@ async function installGraph(api, workspaceId, packageId, options) {
5479
6040
  }
5480
6041
 
5481
6042
  // src/commands/registry.ts
6043
+ var unsignedPublishMessage = "Refusing to publish: the package is unsigned. Packages must be signed \u2014 run `verentis keygen`, then `verentis pack` again.";
5482
6044
  async function findLatestLocalVpkg(directory) {
5483
6045
  const entries = await readdir(directory, { withFileTypes: true });
5484
6046
  const candidates = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".vpkg")).map((entry) => resolve(directory, entry.name));
@@ -5497,45 +6059,118 @@ async function findLatestLocalVpkg(directory) {
5497
6059
  return latest.path;
5498
6060
  }
5499
6061
  function registerRegistry(program2) {
5500
- 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) => {
6062
+ 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) => {
5501
6063
  const selectedPath = vpkgPath ? resolve(vpkgPath) : await findLatestLocalVpkg(process.cwd());
5502
6064
  const contents = await readVpkg(selectedPath);
5503
6065
  if (contents.digestErrors.length > 0) {
5504
6066
  throw new Error(`Refusing to publish: package failed digest verification:
5505
6067
  ${contents.digestErrors.join("\n ")}`);
5506
6068
  }
6069
+ if (!contents.developerSignature) {
6070
+ throw new Error(unsignedPublishMessage);
6071
+ }
5507
6072
  const api = await createApiClient();
5508
6073
  const config = await loadConfig();
6074
+ const apiKey = options["notifications.apiKey"] ?? process.env.VERENTIS_NOTIFICATIONS_API_KEY;
6075
+ const webhookSigningKey = options["notifications.webhookSigningKey"] ?? process.env.VERENTIS_NOTIFICATIONS_WEBHOOK_SIGNING_KEY;
6076
+ if (webhookSigningKey && !apiKey) {
6077
+ throw new Error("Provide the notification provider API key when setting its webhook signing key.");
6078
+ }
5509
6079
  await refreshPackageTypes(requireApiUrl(config), { insecure: config.insecure });
5510
- const publisher = await requireMyPublisher(api);
5511
- if (publisher.name !== contents.metadata.publisher) {
6080
+ const publisher = await requireRegistryPublisher(api);
6081
+ if (publisher.name && publisher.name !== contents.metadata.publisher) {
5512
6082
  throw new Error(`Package declares publisher '${contents.metadata.publisher}' but you are '${publisher.name}'.`);
5513
6083
  }
5514
- let pkg = await findPackageByPackageId(api, publisher.id, contents.metadata["package-id"]);
5515
- if (!pkg) {
5516
- const visibility = options.visibility === "Public" ? "Public" : "Private";
5517
- const id = await createPackage(api, {
5518
- publisherId: publisher.id,
5519
- packageId: contents.metadata["package-id"],
5520
- name: contents.metadata.name,
5521
- displayName: contents.metadata["display-name"] ?? contents.metadata.name,
5522
- kind: contents.metadata.kind,
5523
- visibility
5524
- });
5525
- console.log(`Created package ${publisher.name}/${contents.metadata["package-id"]} (${visibility.toLowerCase()}).`);
5526
- pkg = { id };
5527
- }
5528
- const version = await uploadVersion(api, pkg.id, selectedPath);
5529
- console.log(`Published ${publisher.name}/${contents.metadata["package-id"]}@${version.version} \u2192 ${version.status}`);
6084
+ const visibility = options.visibility === "Public" ? "Public" : "Private";
6085
+ const packageId = contents.metadata.id;
6086
+ const requested = contents.metadata.version;
6087
+ const alreadyPublished = async () => {
6088
+ const existing = await findRegistryVersion(api, contents.metadata.publisher, packageId, requested);
6089
+ if (!existing) return false;
6090
+ if (!sameTreeDigest(existing.treeDigest, contents.treeDigest)) {
6091
+ throw new Error(`${contents.metadata.publisher}/${packageId}@${requested} already exists with different content. Versions are immutable; publish a new version.`);
6092
+ }
6093
+ console.log(`Already published ${contents.metadata.publisher}/${packageId}@${requested} (identical tree digest) \u2192 ${existing.status}`);
6094
+ return true;
6095
+ };
6096
+ if (await alreadyPublished()) return;
6097
+ const version = await uploadRegistryVersion(api, contents.metadata.publisher, packageId, selectedPath, { visibility }).catch(async (error) => {
6098
+ if (error instanceof ApiError && error.status === 422 && await alreadyPublished()) return null;
6099
+ const detail = error instanceof ApiError && error.status === 422 ? problemDetail(error) : void 0;
6100
+ throw detail ? new Error(`Publish rejected: ${detail}`) : error;
6101
+ });
6102
+ if (!version) return;
6103
+ console.log(`Published ${contents.metadata.publisher}/${packageId}@${version.version} \u2192 ${version.status}`);
5530
6104
  if (version.status === "Submitted") {
5531
6105
  console.log("The version is queued for moderation; it becomes installable once approved and published.");
5532
6106
  }
6107
+ const senderSettingsKey = `${contents.metadata.publisher}/${packageId}`;
6108
+ const storedSettings = config.notificationSenderSettings?.[senderSettingsKey] ?? {};
6109
+ const settingOptions = [
6110
+ ["provider", "notifications.provider", "VERENTIS_NOTIFICATIONS_PROVIDER"],
6111
+ ["from", "notifications.from", "VERENTIS_NOTIFICATIONS_FROM"],
6112
+ ["replyTo", "notifications.replyTo", "VERENTIS_NOTIFICATIONS_REPLY_TO"],
6113
+ ["domain", "notifications.domain", "VERENTIS_NOTIFICATIONS_DOMAIN"],
6114
+ ["region", "notifications.region", "VERENTIS_NOTIFICATIONS_REGION"]
6115
+ ];
6116
+ const resolved = { ...storedSettings };
6117
+ const updatedSettings = { ...storedSettings };
6118
+ let hasStickyUpdates = false;
6119
+ for (const [key, optionName, envName] of settingOptions) {
6120
+ const optionValue = options[optionName];
6121
+ const envValue = process.env[envName];
6122
+ if (optionValue !== void 0) {
6123
+ updatedSettings[key] = optionValue;
6124
+ hasStickyUpdates = true;
6125
+ }
6126
+ resolved[key] = optionValue ?? envValue ?? storedSettings[key];
6127
+ }
6128
+ if (hasStickyUpdates) {
6129
+ await saveConfig({
6130
+ ...config,
6131
+ notificationSenderSettings: {
6132
+ ...config.notificationSenderSettings ?? {},
6133
+ [senderSettingsKey]: updatedSettings
6134
+ }
6135
+ });
6136
+ }
6137
+ if (apiKey) {
6138
+ const missing = ["provider", "from", "region"].filter((key) => !resolved[key]);
6139
+ if (resolved.provider?.toLowerCase() === "mailgun" && !resolved.domain) missing.push("domain");
6140
+ if (missing.length > 0) {
6141
+ throw new Error(`Notification sender setup needs --notifications.${missing.join(", --notifications.")}.`);
6142
+ }
6143
+ let sender;
6144
+ try {
6145
+ sender = await setPublisherEmailSender(api, publisher.id, packageId, {
6146
+ provider: resolved.provider,
6147
+ from: resolved.from,
6148
+ replyTo: resolved.replyTo,
6149
+ domain: resolved.domain,
6150
+ region: resolved.region,
6151
+ apiKey,
6152
+ webhookSigningKey
6153
+ });
6154
+ } catch (error) {
6155
+ if (error instanceof Error) {
6156
+ let message = error.message;
6157
+ for (const secret of [apiKey, webhookSigningKey]) {
6158
+ if (secret) message = message.split(secret).join("[REDACTED]");
6159
+ }
6160
+ if (message !== error.message) throw new Error(message);
6161
+ }
6162
+ throw error;
6163
+ }
6164
+ console.log(`Configured ${sender.provider} notification sender for ${contents.metadata.publisher}/${packageId} (key ending ${sender.keyLastFour}).`);
6165
+ if (sender.webhookStatus) console.log(`Webhook: ${sender.webhookStatus}`);
6166
+ if (sender.webhookUrl) console.log(`Webhook URL: ${sender.webhookUrl}`);
6167
+ }
5533
6168
  });
5534
- program2.command("yank <ref> <version>").description("Withdraw a published version from the catalog (ref: 'name' or 'publisher/name')").action(async (ref, version) => {
6169
+ 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) => {
5535
6170
  const api = await createApiClient();
5536
- const { package: pkg } = await resolvePackageRef(api, ref);
5537
- await yankVersion(api, pkg.id, version);
5538
- console.log(`Yanked ${ref}@${version}.`);
6171
+ const target = await resolveRegistryPackageRef(api, ref);
6172
+ await yankVersion(api, target, version, options.reason);
6173
+ console.log(`Yanked ${target.publisher}/${target.packageId}@${version}.`);
5539
6174
  });
5540
6175
  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) => {
5541
6176
  const api = await createApiClient();
@@ -5553,7 +6188,7 @@ function registerRegistry(program2) {
5553
6188
  const requested = options.type ?? options.kind;
5554
6189
  const type = requested ? packageTypes().canonical(requested) ?? requested : void 0;
5555
6190
  const page = await api.request("GET", "/v1/packages", {
5556
- scopes: [SCOPES.packageReadAll],
6191
+ scopes: [SCOPES.packageList],
5557
6192
  query: { SearchText: text, Kind: type, PageNo: 1, PageSize: 50 }
5558
6193
  });
5559
6194
  const items = page.data ?? page.items ?? [];
@@ -5601,14 +6236,14 @@ function registerRegistry(program2) {
5601
6236
  "GET",
5602
6237
  "/v1/installations",
5603
6238
  {
5604
- scopes: [MARKETPLACE.installRead],
6239
+ scopes: [MARKETPLACE.installList],
5605
6240
  tokenWorkspaceId: workspaceId,
5606
6241
  query: { workspaceId, packageId: pkg.id, branch: options.branch, pageNo: 1, pageSize: 100, orderBy: "createdAt desc" }
5607
6242
  }
5608
6243
  );
5609
6244
  const existing = pageItems(page).find((installation) => installation.status !== "Uninstalled");
5610
- const nodeScopes = [NODE.nodeCreate, NODE.fileRead, NODE.nodeUpdate, NODE.journalCreate];
5611
- const consentScopes = isApplicationProfile(pkg.type ?? pkg.kind) ? [SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
6245
+ const nodeScopes = [NODE.nodeCreate, NODE.fileRead];
6246
+ const consentScopes = isApplicationProfile(pkg.type ?? pkg.kind) ? [SCOPES.installationRead, SCOPES.resourceReadAll, SCOPES.resourceUpdate] : [];
5612
6247
  if (existing) {
5613
6248
  if (options.path && existing.installPath !== options.path.replace(/^\/+|\/+$/g, "")) {
5614
6249
  throw new Error(`${ref} is already installed at '${existing.installPath}'. Uninstall it before moving it.`);
@@ -5725,11 +6360,11 @@ function getCliVersion() {
5725
6360
  }
5726
6361
  function readVersion() {
5727
6362
  const candidates = ["../package.json", "../../package.json"];
5728
- for (const relative6 of candidates) {
6363
+ for (const relative7 of candidates) {
5729
6364
  try {
5730
- const raw = readFileSync(fileURLToPath(new URL(relative6, import.meta.url)), "utf8");
6365
+ const raw = readFileSync(fileURLToPath(new URL(relative7, import.meta.url)), "utf8");
5731
6366
  const pkg = JSON.parse(raw);
5732
- if (pkg.version && (relative6 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
6367
+ if (pkg.version && (relative7 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
5733
6368
  } catch {
5734
6369
  }
5735
6370
  }
@@ -5941,6 +6576,7 @@ function detectPackageManager(location) {
5941
6576
  }
5942
6577
 
5943
6578
  // src/commands/use.ts
6579
+ var registryUrl2 = (apiUrl) => requireApiUrl({ apiUrl }) + REGISTRY_BASE;
5944
6580
  function registerUse(program2) {
5945
6581
  const useCmd = program2.command("use").description("Set default context for subsequent commands");
5946
6582
  useCmd.command("workspace <workspaceId>").description("Set the default workspace (files, exec, install, dev commands)").action(async (workspaceId) => {
@@ -5955,12 +6591,14 @@ function registerUse(program2) {
5955
6591
  await saveConfig(config);
5956
6592
  console.log(`Default account set to ${accountId}.`);
5957
6593
  });
5958
- program2.command("context").description("Show the current CLI context (API URL, credential kind, defaults)").option("--json", "output JSON").action(async (options) => {
6594
+ program2.command("context").description("Show the current CLI context (API URL, publish and regional credential kinds, defaults)").option("--json", "output JSON").action(async (options) => {
5959
6595
  const config = await loadConfig();
5960
6596
  outputRecord(
5961
6597
  {
5962
6598
  apiUrl: process.env.VERENTIS_API_URL ?? config.apiUrl ?? "(not set)",
5963
- credential: process.env.VERENTIS_API_KEY ?? config.apiKey ? "api key" : process.env.VERENTIS_TOKEN ?? config.identityToken ? "identity token" : "(none)",
6599
+ 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)",
6600
+ registry: registryUrl2(config.apiUrl),
6601
+ regionalCredential: process.env.VERENTIS_API_KEY ?? config.apiKey ? "api key" : process.env.VERENTIS_TOKEN ?? config.identityToken ? "identity token" : "(none)",
5964
6602
  defaultWorkspaceId: config.defaultWorkspaceId ?? "(not set)",
5965
6603
  defaultAccountId: config.defaultAccountId ?? "(not set)",
5966
6604
  defaultKey: config.defaultKey ?? "(not set)"
@@ -6012,7 +6650,7 @@ function registerUser(program2) {
6012
6650
  const result = await call(api, security.getUserGrants, { params: { userId }, query: scope });
6013
6651
  output(result ?? [], { scope: "Scope", resourceKind: "ResourceKind", resourceId: "ResourceId", effect: "Effect", id: "GrantId" }, options, result);
6014
6652
  });
6015
- 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) => {
6653
+ 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) => {
6016
6654
  const api = await createApiClient();
6017
6655
  const scope = await managementScope(options);
6018
6656
  await call(api, security.grantUserPermission, {
@@ -6030,18 +6668,26 @@ function registerUser(program2) {
6030
6668
  });
6031
6669
  }
6032
6670
  function registerValidate(program2) {
6033
- 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) => {
6671
+ 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(
6672
+ "--param <name=value>",
6673
+ "value for a ${param:name} placeholder in the overlay (repeatable)",
6674
+ (value, previous) => [...previous, value],
6675
+ []
6676
+ ).action(async (pathOrDir, options) => {
6677
+ const params = parseOverlayParams(options.param);
6034
6678
  const target = resolve(pathOrDir ?? ".");
6035
6679
  const info = await stat(target).catch(() => null);
6036
6680
  const manifestPath = info?.isDirectory() ? await findManifest(target) : target;
6037
6681
  if (!info) throw new Error(`${target} does not exist.`);
6038
6682
  const base = await readManifestDocument(manifestPath);
6039
6683
  const overlayPath = resolveOverlayPath(dirname(manifestPath), { env: options.env, overlay: options.overlay });
6040
- const manifest = overlayPath ? applyOverlay(base, await loadOverlay(overlayPath)) : base;
6684
+ const manifest = overlayPath ? applyOverlay(base, await loadOverlay(overlayPath, params)) : base;
6041
6685
  if (!NON_PACKAGE_KINDS.includes(manifest.kind)) await ensurePackageTypeKnown(manifest.kind);
6042
6686
  const issues = validateManifest(manifest);
6043
6687
  const payloadErrors = await validatorForKind(manifest.kind)?.validatePayload?.(dirname(manifestPath), manifest) ?? [];
6044
6688
  issues.push(...payloadErrors.map((message) => ({ level: "error", message })));
6689
+ const avatarPayloadErrors = await validateAgentAvatarPayload(dirname(manifestPath), manifest);
6690
+ issues.push(...avatarPayloadErrors.map((message) => ({ level: "error", message })));
6045
6691
  const spec = manifest.spec;
6046
6692
  const scriptAccess = await collectScriptFileAccess(dirname(manifestPath), spec);
6047
6693
  issues.push(...[
@@ -6055,8 +6701,15 @@ function registerValidate(program2) {
6055
6701
  ].map((message) => ({ level: "error", message })));
6056
6702
  try {
6057
6703
  const payloadFiles = await resolvePayloadFiles(dirname(manifestPath), manifestPath, manifest);
6704
+ issues.push(...validateAgentAvatarPayloadFiles(manifest, payloadFiles).map((message) => ({ level: "error", message })));
6058
6705
  const templateInspection = await inspectPackagingTemplates(dirname(manifestPath), manifest, payloadFiles);
6059
6706
  issues.push(...templateInspection.issues);
6707
+ const argumentErrors = await checkScriptArgumentDescriptors(
6708
+ dirname(manifestPath),
6709
+ payloadFiles,
6710
+ (file) => readTemplatedPayloadBytes(dirname(manifestPath), file, templateInspection)
6711
+ );
6712
+ issues.push(...argumentErrors.map((message) => ({ level: "error", message })));
6060
6713
  } catch (error) {
6061
6714
  issues.push({ level: "error", message: error instanceof Error ? error.message : String(error) });
6062
6715
  }
@@ -6072,7 +6725,7 @@ function registerValidate(program2) {
6072
6725
  }
6073
6726
  const errors = issues.filter((issue) => issue.level === "error");
6074
6727
  const warnings = issues.filter((issue) => issue.level === "warning");
6075
- console.log(`${manifestPath} \u2014 kind ${manifest.kind ?? "(unknown)"}, ${manifest.metadata?.name ?? "?"}@${manifest.metadata?.version ?? "?"}`);
6728
+ console.log(`${manifestPath} \u2014 kind ${manifest.kind ?? "(unknown)"}, ${manifest.metadata?.id ?? "?"}@${manifest.metadata?.version ?? "?"}`);
6076
6729
  for (const issue of errors) console.error(` error: ${issue.message}`);
6077
6730
  for (const issue of warnings) console.warn(` warning: ${issue.message}`);
6078
6731
  if (errors.length === 0) {
@@ -6167,6 +6820,56 @@ function registerWorkspace(program2) {
6167
6820
  });
6168
6821
  }
6169
6822
 
6823
+ // src/accessHeaders.ts
6824
+ var REDIRECTS = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
6825
+ var MAX_REDIRECTS = 10;
6826
+ function installAccessHeaders(env = process.env) {
6827
+ const clientId = env.VERENTIS_CF_ACCESS_CLIENT_ID;
6828
+ const clientSecret = env.VERENTIS_CF_ACCESS_CLIENT_SECRET;
6829
+ if (!clientId && !clientSecret) return false;
6830
+ if (!clientId || !clientSecret) {
6831
+ throw new Error("Set both VERENTIS_CF_ACCESS_CLIENT_ID and VERENTIS_CF_ACCESS_CLIENT_SECRET, or neither.");
6832
+ }
6833
+ const apiUrl = env.VERENTIS_API_URL;
6834
+ if (!apiUrl || !apiUrl.startsWith("https://")) {
6835
+ throw new Error("Cloudflare Access headers require an explicit HTTPS VERENTIS_API_URL.");
6836
+ }
6837
+ const origin = new URL(apiUrl).origin;
6838
+ const inner = globalThis.fetch;
6839
+ const accessFetch = async (input, init) => {
6840
+ const first = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
6841
+ if (first.origin !== origin) return inner(input, init);
6842
+ let url = first;
6843
+ let method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
6844
+ let body = init?.body ?? void 0;
6845
+ const baseHeaders = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
6846
+ const followRedirects = (init?.redirect ?? "follow") === "follow";
6847
+ for (let hop = 0; ; hop++) {
6848
+ const headers = new Headers(baseHeaders);
6849
+ if (url.origin === origin) {
6850
+ headers.set("CF-Access-Client-Id", clientId);
6851
+ headers.set("CF-Access-Client-Secret", clientSecret);
6852
+ } else {
6853
+ headers.delete("CF-Access-Client-Id");
6854
+ headers.delete("CF-Access-Client-Secret");
6855
+ headers.delete("Authorization");
6856
+ }
6857
+ const response = await inner(url, { ...init, method, body, headers, redirect: "manual" });
6858
+ const location = response.headers.get("location");
6859
+ if (!followRedirects || !REDIRECTS.has(response.status) || !location) return response;
6860
+ if (hop >= MAX_REDIRECTS) throw new Error(`Too many redirects from ${first.href}`);
6861
+ url = new URL(location, url);
6862
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && method === "POST") {
6863
+ method = "GET";
6864
+ body = void 0;
6865
+ baseHeaders.delete("Content-Type");
6866
+ }
6867
+ }
6868
+ };
6869
+ globalThis.fetch = accessFetch;
6870
+ return true;
6871
+ }
6872
+
6170
6873
  // src/index.ts
6171
6874
  var program = new Command().enablePositionalOptions().name("verentis").description("Verentis CLI \u2014 admin, marketplace publishing, and the engine/app developer loop").version(getCliVersion());
6172
6875
  registerLogin(program);
@@ -6189,10 +6892,12 @@ registerInit(program);
6189
6892
  registerPack(program);
6190
6893
  registerRegistry(program);
6191
6894
  registerPackage(program);
6895
+ registerNotifications(program);
6192
6896
  registerApi(program);
6193
6897
  registerUpdate(program);
6194
6898
  async function main() {
6195
6899
  try {
6900
+ installAccessHeaders();
6196
6901
  await program.parseAsync();
6197
6902
  } catch (error) {
6198
6903
  if (error instanceof ApiError || error instanceof Error) {