@sequenceholdings/studio-cli 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -61,6 +61,7 @@ export declare function resolveOrRegisterFunction({ ctx, slug, title, descriptio
61
61
  fn: FunctionSummary;
62
62
  created: boolean;
63
63
  }>;
64
+ export declare function functionsRegisterCommand(args: ParsedArgs): Promise<number>;
64
65
  export declare function predictNextVersion(latest: string | undefined): string;
65
66
  /** Prompt on the TTY with echo suppressed — secret values are never displayed. */
66
67
  export declare function promptHidden(question: string): Promise<string>;
@@ -92,5 +93,5 @@ export declare function functionsRollbackCommand(args: ParsedArgs): Promise<numb
92
93
  /** Minimal dotenv parser — KEY=VALUE lines, quotes stripped, comments skipped. */
93
94
  export declare function parseDotenv(content: string): Record<string, string>;
94
95
  export declare function functionsDeleteCommand(args: ParsedArgs): Promise<number>;
95
- export declare const FUNCTIONS_USAGE = "usage:\n seq-studio functions init <dir> scaffold manifest + TypeScript hello-world handler\n seq-studio functions build [--dir d] local pre-flight (manifest, lockfile, size)\n seq-studio functions deploy -e <env> [-m msg] preview + confirm secrets + upload and deploy\n seq-studio functions list -e <env> [--match-local] functions visible on the environment\n seq-studio functions show -e <env> [--fn slug] detail for one function (versions, secrets)\n seq-studio functions limits [-e <env>] [--json] bundled defaults/caps, or deployed policy\n [--fn slug] also show effective runtime limits (requires -e)\n seq-studio functions dev [--dir path] [--port 8080] local HTTP server with cache context\n seq-studio functions invoke -e <env> [--data JSON | --data @file | --stdin]\n invoke a function and print its response\n seq-studio functions logs -e <env> [--limit N] [--since t] function logs (reader-gated)\n seq-studio functions promote <version> -e <env> make a version live\n seq-studio functions rollback [<version>] -e <env> redeploy a prior version\n seq-studio functions delete -e <env> [--yes] archive function + tear down its runtime\n (version history is retained)\n\n Flags: -e/--env <env|preview:<slug>> (required for network commands; see: seq-studio envs list) \u00B7 --fn <slug> \u00B7 --dir <path>\n --path <repo-subdirectory> (remote build/deploy only) select one function in a multi-function repo\n --from-env-file <path> (default: .env) source file for secret values\n --no-wait \u00B7 --yes\n --no-provision (deploy) update-only: error instead of registering a new\n shell, writing secret values, or attaching secrets (CI sweep)\n\n Local Atlas builds and runs deployed functions on this computer, including teardown.\n \"functions dev\" runs a standalone handler without Atlas registration.\n\n Configure per-function CPU and concurrency in managed-function.yml under limits.\n Run \"functions limits\" for valid settings; redeploy to apply manifest changes.\n Invocation rates are shared across Atlas replicas; 429 includes Retry-After.\n If the shared rate limiter is unavailable, invocation fails closed with 503.\n\n Source for build/deploy: a local --dir (default .), a platform git-service\n repo (--repo <ns>/<name>), or a public HTTPS git URL (--git-url <url>). --path selects\n a function directory within a remote repo; omit it for the existing root-manifest\n layout. --ref selects a branch/tag/commit (default: the repo's default branch).\n Remote sources record the pinned commit as provenance (never dirty) and NEVER\n read a repo-committed .env for secret values \u2014 provision secrets server-side\n or pass a local --from-env-file (resolved against your cwd).\n\n Interactive --repo builds clone over smart-HTTP and require a repo:read git\n PAT in ATLAS_GIT_PAT (`seq-studio auth pat create --scopes repo:read`, or\n Atlas \u2192 Settings \u2192 Tokens). Headless M2M builds use JSON materialize and\n accept only platform-managed --repo sources. Interactive builds also need\n --env + seq-studio login to resolve the repo and deploy.\n";
96
+ export declare const FUNCTIONS_USAGE = "usage:\n seq-studio functions init <dir> scaffold manifest + TypeScript hello-world handler\n seq-studio functions build [--dir d] local pre-flight (manifest, lockfile, size)\n seq-studio functions register -e <env> [--dir d] register a function shell without deploying\n seq-studio functions deploy -e <env> [-m msg] preview + confirm secrets + upload and deploy\n seq-studio functions list -e <env> [--match-local] functions visible on the environment\n seq-studio functions show -e <env> [--fn slug] detail for one function (versions, secrets)\n seq-studio functions limits [-e <env>] [--json] bundled defaults/caps, or deployed policy\n [--fn slug] also show effective runtime limits (requires -e)\n seq-studio functions dev [--dir path] [--port 8080] local HTTP server with cache context\n seq-studio functions invoke -e <env> [--data JSON | --data @file | --stdin]\n invoke a function and print its response\n seq-studio functions logs -e <env> [--limit N] [--since t] function logs (reader-gated)\n seq-studio functions promote <version> -e <env> make a version live\n seq-studio functions rollback [<version>] -e <env> redeploy a prior version\n seq-studio functions delete -e <env> [--yes] archive function + tear down its runtime\n (version history is retained)\n\n Flags: -e/--env <env|preview:<slug>> (required for network commands; see: seq-studio envs list) \u00B7 --fn <slug> \u00B7 --dir <path>\n --path <repo-subdirectory> (remote build/deploy only) select one function in a multi-function repo\n --from-env-file <path> (default: .env) source file for secret values\n --no-wait \u00B7 --yes\n --no-provision (deploy) update-only: error instead of registering a new\n shell, writing secret values, or attaching secrets (CI sweep)\n\n Local Atlas builds and runs deployed functions on this computer, including teardown.\n \"functions dev\" runs a standalone handler without Atlas registration.\n\n Configure per-function CPU and concurrency in managed-function.yml under limits.\n Run \"functions limits\" for valid settings; redeploy to apply manifest changes.\n Invocation rates are shared across Atlas replicas; 429 includes Retry-After.\n If the shared rate limiter is unavailable, invocation fails closed with 503.\n\n Source for build/deploy: a local --dir (default .), a platform git-service\n repo (--repo <ns>/<name>), or a public HTTPS git URL (--git-url <url>). --path selects\n a function directory within a remote repo; omit it for the existing root-manifest\n layout. --ref selects a branch/tag/commit (default: the repo's default branch).\n Remote sources record the pinned commit as provenance (never dirty) and NEVER\n read a repo-committed .env for secret values \u2014 provision secrets server-side\n or pass a local --from-env-file (resolved against your cwd).\n\n Interactive --repo builds clone over smart-HTTP and require a repo:read git\n PAT in ATLAS_GIT_PAT (`seq-studio auth pat create --scopes repo:read`, or\n Atlas \u2192 Settings \u2192 Tokens). Headless M2M builds use JSON materialize and\n accept only platform-managed --repo sources. Interactive builds also need\n --env + seq-studio login to resolve the repo and deploy.\n";
96
97
  export declare function runFunctionsCommand(sub: string | undefined, args: ParsedArgs): Promise<number>;
@@ -14,12 +14,13 @@ import { clarifyApplyFailureReason, printCliError } from '../cli-errors.js';
14
14
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
15
15
  import { confirmYes } from '../prompt.js';
16
16
  import { collectBundleFiles, isDirectory, validateLocalBundle, } from './bundle.js';
17
- import { managedFunctionManifestSchema, MF_MANIFEST_FILENAME, manifestEgressHosts, manifestEgressIpRanges, } from './manifest.js';
17
+ import { managedFunctionManifestSchema, MF_MANIFEST_FILENAME, manifestEgressHosts, manifestEgressIpRanges, manifestSecretNames, } from './manifest.js';
18
18
  import { buildEgressPreviewLines, egressPropagationNote, formatEgressSummary, printFunctionEgressHosts, } from './egress-preview.js';
19
19
  import { resolveArtifactSource, } from '@sequenceholdings/artifact-studio/source-resolver';
20
20
  import { buildSecretPreviewLines, classifySecrets, } from './secret-reconcile.js';
21
21
  import { parseFunctionsSourceSelection, resolveFunctionSourceDir } from './source-selection.js';
22
22
  export { parseFunctionsSourceSelection, parseFunctionsSourceSpec, resolveFunctionSourceDir, } from './source-selection.js';
23
+ import { warnOnManifestRoles } from '../manifest-roles-notice.js';
23
24
  const execFileAsync = promisify(execFile);
24
25
  export const LOG = '[seq-studio]';
25
26
  const POLL_INTERVAL_MS = 5_000;
@@ -136,6 +137,19 @@ export async function resolveOrRegisterFunction({ ctx, slug, title, description,
136
137
  });
137
138
  return { fn: created.function, created: true };
138
139
  }
140
+ export async function functionsRegisterCommand(args) {
141
+ const dir = resolve(typeof args.flags.dir === 'string' ? args.flags.dir : process.cwd());
142
+ const manifest = await readManifest(dir);
143
+ const ctx = await buildContext(args);
144
+ const { fn, created } = await resolveOrRegisterFunction({
145
+ ctx,
146
+ slug: manifest.function.id,
147
+ title: manifest.function.title,
148
+ description: manifest.function.description ?? null,
149
+ });
150
+ console.log(`${LOG} ${created ? 'registered' : 'found'} managed function "${manifest.function.id}" (${fn.id}) on ${ctx.env.name}`);
151
+ return 0;
152
+ }
139
153
  export function predictNextVersion(latest) {
140
154
  const parsed = latest ? Number.parseInt(latest.replace(/^v/, ''), 10) : 0;
141
155
  return `v${(Number.isFinite(parsed) ? parsed : 0) + 1}`;
@@ -385,7 +399,7 @@ async function buildFromResolvedSource({ spec, source, }) {
385
399
  console.log(`${LOG} function: ${manifest.function.id} (${manifest.function.title})`);
386
400
  console.log(`${LOG} runtime: ${manifest.runtime}, entrypoint: ${manifest.entrypoint}`);
387
401
  console.log(`${LOG} files: ${files.length}`);
388
- console.log(`${LOG} secrets: ${manifest.secrets.length > 0 ? manifest.secrets.join(', ') : '(none declared)'}`);
402
+ console.log(`${LOG} secrets: ${manifest.secrets.length > 0 ? manifestSecretNames(manifest).join(', ') : '(none declared)'}`);
389
403
  console.log(`${LOG} egress: ${formatEgressSummary([
390
404
  ...manifestEgressHosts(manifest.egress),
391
405
  ...manifestEgressIpRanges(manifest.egress),
@@ -446,6 +460,7 @@ export async function functionsDeployCommand(args) {
446
460
  const source = await resolveArtifactSource(spec, ctx ? sourceClientOptions(ctx) : {});
447
461
  try {
448
462
  const dir = await resolveFunctionSourceDir({ repoDir: source.dir, path });
463
+ await warnOnManifestRoles({ dir, file: 'managed-function.yml', kind: 'host' });
449
464
  return await deployFromResolvedSource({ args, spec, ctx, source: { ...source, dir } });
450
465
  }
451
466
  finally {
@@ -496,6 +511,8 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
496
511
  // sources authenticate only now, after local validation passed.
497
512
  const ctx = earlyCtx ?? (await buildContext(args));
498
513
  const slug = manifest.function.id;
514
+ const singleSecrets = manifest.secrets.filter((entry) => typeof entry === 'string');
515
+ const declaredSecretNames = manifestSecretNames(manifest);
499
516
  const { functions } = await getJson({
500
517
  ...clientOptions(ctx),
501
518
  path: `/api/managed-functions?slug=${encodeURIComponent(slug)}`,
@@ -538,6 +555,21 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
538
555
  s.name,
539
556
  { id: s.id, hasDefaultValue: s.hasDefaultValue, attachmentCount: s.attachmentCount },
540
557
  ]));
558
+ for (const binding of manifest.secrets) {
559
+ if (typeof binding === 'string')
560
+ continue;
561
+ const source = serverSecrets.find((secret) => secret.name === binding.secret);
562
+ if (!source || source.valueType !== 'key_value' || !source.hasDefaultValue) {
563
+ console.error(`${LOG} key/value set "${binding.secret}" must exist with a default value before deploying`);
564
+ return 1;
565
+ }
566
+ for (const envName of Object.values(binding.entries)) {
567
+ if (!envValues[envName])
568
+ continue;
569
+ console.error(`${LOG} ${envName} is mapped from key/value set ${binding.secret}; remove its local .env value and update the set with seq-studio secrets set --from-json`);
570
+ return 1;
571
+ }
572
+ }
541
573
  // Build envVar → secretId map so the classifier can detect when an env
542
574
  // var is already attached to a *different* secret and not skip reconcile.
543
575
  const attachedByEnvVar = new Map();
@@ -546,10 +578,22 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
546
578
  for (const a of detail?.attachments ?? []) {
547
579
  if (a.secretId)
548
580
  attachedByEnvVar.set(a.envVarName, a.secretId);
581
+ if (a.secretId && a.entryMappings) {
582
+ const secret = serverSecrets.find((row) => row.id === a.secretId);
583
+ for (const envName of Object.values(a.entryMappings)) {
584
+ attachedByEnvVar.set(envName, a.secretId);
585
+ if (secret)
586
+ serverInfoByName.set(envName, { id: secret.id, hasDefaultValue: secret.hasDefaultValue, attachmentCount: secret.attachmentCount });
587
+ if (envValues[envName]) {
588
+ console.error(`${LOG} ${envName} is mapped from key/value set ${secret?.name ?? a.secretId}; remove its local .env value and update the set with seq-studio secrets set --from-json`);
589
+ return 1;
590
+ }
591
+ }
592
+ }
549
593
  }
550
594
  }
551
595
  classification = classifySecrets({
552
- manifestSecrets: manifest.secrets,
596
+ manifestSecrets: singleSecrets,
553
597
  envValues,
554
598
  serverInfoByName,
555
599
  attachedByEnvVar,
@@ -565,7 +609,7 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
565
609
  }
566
610
  }
567
611
  // Surface .env keys that aren't in the manifest so users know they're ignored.
568
- const undeclaredEnvKeys = Object.keys(envValues).filter((k) => envValues[k]?.length && !manifest.secrets.includes(k));
612
+ const undeclaredEnvKeys = Object.keys(envValues).filter((k) => envValues[k]?.length && !declaredSecretNames.includes(k));
569
613
  const preview = [
570
614
  `${LOG} deploy preview:`,
571
615
  `${LOG} environment: ${ctx.env.name}`,
@@ -580,9 +624,15 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
580
624
  preview.push(`${LOG} git: ${git.gitBranch ?? '?'}@${git.gitCommit.slice(0, 8)}${git.gitDirty ? ' (dirty)' : ''}`);
581
625
  }
582
626
  if (classification) {
583
- preview.push(...buildSecretPreviewLines(LOG, classification.secrets));
627
+ preview.push(...(classification.secrets.length === 0 && manifest.secrets.length > 0
628
+ ? [`${LOG} secrets:`]
629
+ : buildSecretPreviewLines(LOG, classification.secrets)));
630
+ for (const binding of manifest.secrets) {
631
+ if (typeof binding !== 'string')
632
+ preview.push(`${LOG} - set ${binding.secret}: ${Object.entries(binding.entries).map(([key, env]) => `${key} → ${env}`).join(', ')}`);
633
+ }
584
634
  if (classification.secrets.some((c) => c.category === 'OVERWRITE')) {
585
- preview.push(`${LOG} note: overwriting a shared default changes it for all attached functions`);
635
+ preview.push(`${LOG} note: overwriting a shared default changes it for all functions using that secret`);
586
636
  }
587
637
  }
588
638
  else {
@@ -615,10 +665,6 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
615
665
  problems.push(`secret "${c.name}" would be written from a local value — provision it server-side first: ` +
616
666
  `\`seq-studio secrets set ${c.name} -e ${ctx.env.name}\``);
617
667
  }
618
- else if (c.category === 'USE_EXISTING' && !c.attachedToFn) {
619
- problems.push(`secret "${c.name}" exists but is not attached to ${slug} — attach it once: ` +
620
- `\`seq-studio secrets attach ${c.name} --fn ${slug} -e ${ctx.env.name}\``);
621
- }
622
668
  }
623
669
  if (problems.length > 0) {
624
670
  for (const problem of problems)
@@ -666,26 +712,6 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
666
712
  return 1;
667
713
  }
668
714
  }
669
- // USE_EXISTING not yet attached: attach only (no value change).
670
- const toAttach = classification.secrets.filter((c) => c.category === 'USE_EXISTING' && !c.attachedToFn && c.secretId !== null);
671
- for (const c of toAttach) {
672
- console.log(`${LOG} attaching existing secret "${c.name}" to ${slug}…`);
673
- try {
674
- await postJson({
675
- ...clientOptions(ctx),
676
- path: `/api/managed-secrets/${c.secretId}/attachments`,
677
- body: { functionId: fn.id, envVarName: c.name },
678
- });
679
- }
680
- catch (error) {
681
- if (error instanceof AtlasApiError && error.status === 409) {
682
- console.error(`${LOG} secret "${c.name}": env var is already attached to a different managed secret — ` +
683
- `detach the conflicting attachment first: \`seq-studio secrets detach <NAME> --fn ${slug} -e ${ctx.env.name}\``);
684
- return 1;
685
- }
686
- throw error;
687
- }
688
- }
689
715
  }
690
716
  if (git.gitDirty) {
691
717
  console.warn(`${LOG} working tree is dirty — recording gitDirty=true on this version`);
@@ -1126,6 +1152,7 @@ export async function functionsDeleteCommand(args) {
1126
1152
  export const FUNCTIONS_USAGE = `usage:
1127
1153
  seq-studio functions init <dir> scaffold manifest + TypeScript hello-world handler
1128
1154
  seq-studio functions build [--dir d] local pre-flight (manifest, lockfile, size)
1155
+ seq-studio functions register -e <env> [--dir d] register a function shell without deploying
1129
1156
  seq-studio functions deploy -e <env> [-m msg] preview + confirm secrets + upload and deploy
1130
1157
  seq-studio functions list -e <env> [--match-local] functions visible on the environment
1131
1158
  seq-studio functions show -e <env> [--fn slug] detail for one function (versions, secrets)
@@ -1180,6 +1207,8 @@ export async function runFunctionsCommand(sub, args) {
1180
1207
  }
1181
1208
  case 'build':
1182
1209
  return await functionsBuildCommand(args);
1210
+ case 'register':
1211
+ return await functionsRegisterCommand(args);
1183
1212
  case 'deploy':
1184
1213
  return await functionsDeployCommand(args);
1185
1214
  case 'list':
@@ -97,7 +97,10 @@ export declare const managedFunctionManifestSchema: z.ZodObject<{
97
97
  invocation: z.ZodDefault<z.ZodObject<{
98
98
  allowed_ip_ranges: z.ZodDefault<z.ZodArray<z.ZodString>>;
99
99
  }, z.core.$strip>>;
100
- secrets: z.ZodDefault<z.ZodArray<z.ZodString>>;
100
+ secrets: z.ZodDefault<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
101
+ secret: z.ZodString;
102
+ entries: z.ZodRecord<z.ZodString, z.ZodString>;
103
+ }, z.core.$strict>]>>>;
101
104
  egress: z.ZodDefault<z.ZodArray<z.ZodString>>;
102
105
  service_account: z.ZodOptional<z.ZodString>;
103
106
  authorization: z.ZodOptional<z.ZodObject<{
@@ -150,3 +153,6 @@ export declare const managedFunctionManifestSchema: z.ZodObject<{
150
153
  }, z.core.$strip>>;
151
154
  }, z.core.$strip>;
152
155
  export type ManagedFunctionManifest = z.infer<typeof managedFunctionManifestSchema>;
156
+ export declare function manifestSecretNames(value: {
157
+ secrets: ManagedFunctionManifest['secrets'];
158
+ }): string[];
@@ -478,16 +478,19 @@ const customRolesBlockSchema = z.object({
478
478
  }
479
479
  }
480
480
  });
481
- const CUSTOM_CAPABILITY_PIN_RE = /^(?:org\/)?[a-z0-9-]+$/;
481
+ // `app/<application-id>/<key>`: a capability the Application defines; live only while this is a member.
482
+ const CUSTOM_CAPABILITY_PIN_RE = /^(?:org\/|app\/[a-z][a-z0-9-]{0,63}\/)?[a-z0-9-]+$/;
482
483
  const MAX_CAPABILITY_PINS = 100;
483
484
  const capabilityPinsSchema = z
484
- .array(z.string().min(1).max(68).regex(CUSTOM_CAPABILITY_PIN_RE, 'Pins must be "org/<key>" or a bare "<key>" matching [a-z0-9-]+'))
485
+ .array(z.string().min(1).max(140).regex(CUSTOM_CAPABILITY_PIN_RE, 'Pins must be "org/<key>", "app/<application-id>/<key>", or a bare "<key>" matching [a-z0-9-]+'))
485
486
  .max(MAX_CAPABILITY_PINS)
486
487
  .default([]);
487
488
  function parseCapabilityPin(pin) {
488
- return pin.startsWith('org/')
489
- ? { scope: 'org', key: pin.slice('org/'.length) }
490
- : { scope: 'host', key: pin };
489
+ if (pin.startsWith('org/'))
490
+ return { scope: 'org', key: pin.slice('org/'.length) };
491
+ if (pin.startsWith('app/'))
492
+ return { scope: 'app', key: pin.split('/')[2] ?? '' };
493
+ return { scope: 'host', key: pin };
491
494
  }
492
495
  function validateCapabilityPins({ uses, roles, }) {
493
496
  const errors = [];
@@ -506,7 +509,7 @@ function validateCapabilityPins({ uses, roles, }) {
506
509
  }
507
510
  const MAX_CAPABILITY_GATES = 20;
508
511
  const capabilityGateSchema = z.object({
509
- requires: z.string().min(1).max(68).regex(CUSTOM_CAPABILITY_PIN_RE, 'Gate requirements must be "org/<key>" or a bare "<key>" matching [a-z0-9-]+'),
512
+ requires: z.string().min(1).max(140).regex(CUSTOM_CAPABILITY_PIN_RE, 'Gate requirements must be "org/<key>", "app/<application-id>/<key>", or a bare "<key>" matching [a-z0-9-]+'),
510
513
  when: z.object({
511
514
  field: z.string().min(1).max(128),
512
515
  equals: z.union([z.string().max(256), z.number(), z.boolean()]),
@@ -522,11 +525,11 @@ function validateCapabilityGates({ gates, uses, roles, }) {
522
525
  const declaredCapabilities = new Set(Object.keys(roles?.capabilities ?? {}));
523
526
  for (const gate of gates) {
524
527
  const parsed = parseCapabilityPin(gate.requires);
525
- const claimable = parsed.scope === 'org'
526
- ? pinSet.has(gate.requires)
527
- : declaredCapabilities.has(parsed.key) || pinSet.has(parsed.key);
528
+ const claimable = parsed.scope === 'host'
529
+ ? declaredCapabilities.has(parsed.key) || pinSet.has(parsed.key)
530
+ : pinSet.has(gate.requires);
528
531
  if (!claimable) {
529
- errors.push(parsed.scope === 'org'
532
+ errors.push(parsed.scope !== 'host'
530
533
  ? `Gate requires "${gate.requires}" which is not pinned in capabilities.uses`
531
534
  : `Gate requires "${gate.requires}" which is neither declared in capabilities.roles.capabilities nor pinned in capabilities.uses`);
532
535
  }
@@ -607,7 +610,13 @@ export const managedFunctionManifestSchema = z.object({
607
610
  })
608
611
  .default({ allowed_ip_ranges: [] }),
609
612
  secrets: z
610
- .array(z.string().regex(SECRET_NAME_RE, 'secret names must be UPPER_SNAKE_CASE'))
613
+ .array(z.union([
614
+ z.string().regex(SECRET_NAME_RE, 'secret names must be UPPER_SNAKE_CASE'),
615
+ z.object({
616
+ secret: z.string().regex(SECRET_NAME_RE, 'secret names must be UPPER_SNAKE_CASE'),
617
+ entries: z.record(z.string().regex(SECRET_NAME_RE, 'entry keys must be UPPER_SNAKE_CASE'), z.string().regex(SECRET_NAME_RE, 'env var names must be UPPER_SNAKE_CASE')).refine((entries) => Object.keys(entries).length > 0 && Object.keys(entries).length <= 32, 'A key/value set needs 1 to 32 entry mappings'),
618
+ }).strict(),
619
+ ]))
611
620
  .max(32)
612
621
  .default([]),
613
622
  /**
@@ -692,8 +701,22 @@ export const managedFunctionManifestSchema = z.object({
692
701
  .default({}),
693
702
  }).default({ uses: [], gates: [], data: {} }),
694
703
  }).superRefine((manifest, ctx) => {
704
+ const declaredNames = manifestSecretNames(manifest);
705
+ if (declaredNames.length > 32)
706
+ ctx.addIssue({
707
+ code: 'custom', path: ['secrets'], message: 'A function may declare at most 32 secret environment variables',
708
+ });
709
+ if (new Set(declaredNames).size !== declaredNames.length)
710
+ ctx.addIssue({
711
+ code: 'custom', path: ['secrets'], message: 'Secret environment variable names must be unique',
712
+ });
713
+ const sourceNames = manifest.secrets.map((entry) => typeof entry === 'string' ? entry : entry.secret);
714
+ if (new Set(sourceNames).size !== sourceNames.length)
715
+ ctx.addIssue({
716
+ code: 'custom', path: ['secrets'], message: 'A secret may appear only once in the manifest',
717
+ });
695
718
  if (manifest.cache?.enabled) {
696
- manifest.secrets.forEach((name, index) => {
719
+ declaredNames.forEach((name, index) => {
697
720
  if (name.startsWith('SEQUENCE_FUNCTION_'))
698
721
  ctx.addIssue({
699
722
  code: 'custom', path: ['secrets', index],
@@ -758,3 +781,8 @@ export const managedFunctionManifestSchema = z.object({
758
781
  });
759
782
  }
760
783
  });
784
+ export function manifestSecretNames(value) {
785
+ return value.secrets.flatMap((entry) => typeof entry === 'string'
786
+ ? [entry]
787
+ : Object.values(entry.entries));
788
+ }
@@ -54,9 +54,9 @@ export interface ApplySecretsResult {
54
54
  /**
55
55
  * Categorise each manifest-declared secret into one of four states:
56
56
  *
57
- * UPLOAD_NEW — in .env, no server default → create + set + attach via /apply
58
- * OVERWRITE — in .env, server default exists → overwrite + attach if missing via /apply
59
- * USE_EXISTING — not in .env, server default exists → attach only (no value change)
57
+ * UPLOAD_NEW — in .env, no server default → create + set via /apply
58
+ * OVERWRITE — in .env, server default exists → overwrite via /apply
59
+ * USE_EXISTING — not in .env, server default exists → manifest binding needs no write
60
60
  * BLOCKED — not in .env, no server default → unsatisfiable; deploy must abort
61
61
  */
62
62
  export declare function classifySecrets({ manifestSecrets, envValues, serverInfoByName, attachedByEnvVar, }: {
@@ -9,9 +9,9 @@
9
9
  /**
10
10
  * Categorise each manifest-declared secret into one of four states:
11
11
  *
12
- * UPLOAD_NEW — in .env, no server default → create + set + attach via /apply
13
- * OVERWRITE — in .env, server default exists → overwrite + attach if missing via /apply
14
- * USE_EXISTING — not in .env, server default exists → attach only (no value change)
12
+ * UPLOAD_NEW — in .env, no server default → create + set via /apply
13
+ * OVERWRITE — in .env, server default exists → overwrite via /apply
14
+ * USE_EXISTING — not in .env, server default exists → manifest binding needs no write
15
15
  * BLOCKED — not in .env, no server default → unsatisfiable; deploy must abort
16
16
  */
17
17
  export function classifySecrets({ manifestSecrets, envValues, serverInfoByName, attachedByEnvVar, }) {
@@ -66,7 +66,7 @@ export function buildSecretPreviewLines(log, secrets) {
66
66
  for (const c of secrets) {
67
67
  let desc;
68
68
  if (c.category === 'UPLOAD_NEW') {
69
- desc = 'new — will upload from .env and attach';
69
+ desc = 'new — will upload from .env';
70
70
  }
71
71
  else if (c.category === 'OVERWRITE') {
72
72
  // Compute how many OTHER functions the existing default serves.
@@ -76,9 +76,7 @@ export function buildSecretPreviewLines(log, secrets) {
76
76
  }
77
77
  else {
78
78
  // USE_EXISTING
79
- desc = c.attachedToFn
80
- ? 'uses existing default, no change'
81
- : 'uses existing default, linking to function (value unchanged)';
79
+ desc = 'uses existing default, no change';
82
80
  }
83
81
  lines.push(`${log} - ${c.name}: ${desc}`);
84
82
  }
package/dist/main.d.ts CHANGED
@@ -13,6 +13,8 @@
13
13
  * seq-studio repos <sub> manage platform git-service repos
14
14
  * seq-studio pipeline <sub> discover, query, author and operate Data Pipelines
15
15
  * seq-studio auth <sub> manage git-service PATs
16
+ * seq-studio service-accounts <sub> provision runtime identities
17
+ * seq-studio access <sub> manage runtime resource access
16
18
  * seq-studio envs <sub> add/list/refresh environments
17
19
  * seq-studio login authenticate interactively with Auth0
18
20
  * seq-studio logout remove cached user tokens
package/dist/main.js CHANGED
@@ -13,6 +13,8 @@
13
13
  * seq-studio repos <sub> manage platform git-service repos
14
14
  * seq-studio pipeline <sub> discover, query, author and operate Data Pipelines
15
15
  * seq-studio auth <sub> manage git-service PATs
16
+ * seq-studio service-accounts <sub> provision runtime identities
17
+ * seq-studio access <sub> manage runtime resource access
16
18
  * seq-studio envs <sub> add/list/refresh environments
17
19
  * seq-studio login authenticate interactively with Auth0
18
20
  * seq-studio logout remove cached user tokens
@@ -24,19 +26,21 @@ import { applyCommand, bundleCommand, doctorCommand, initCommand, lintCommand, p
24
26
  // Lazy-load artifact delegate: published @sequenceholdings/artifact-studio/cli
25
27
  // still auto-runs runCli() at module load; importing it here breaks doctor/process.
26
28
  const TOP_LEVEL_USAGE = `usage:
27
- seq-studio init <dir> --with <kinds> scaffold an app monorepo (sequence.app.yml)
28
- seq-studio add <kind> <name> add a primitive to the current app monorepo
29
- seq-studio deploy -e <env> deploy primitives from sequence.app.yml
29
+ seq-studio init <dir> --with <kinds> [internal] scaffold an app monorepo (sequence.app.yml)
30
+ seq-studio add <kind> <name> [internal] add a primitive to the current app monorepo
31
+ seq-studio deploy -e <env> [internal] deploy primitives from sequence.app.yml
30
32
  seq-studio process <sub> [args] lint | plan | apply | test | simulate | bundle | init
31
33
  seq-studio artifact <sub> [args] init | build | plan | deploy | dev | list | show | pull | promote | rollback
32
34
  seq-studio functions <sub> [args] init | build | deploy | list | show | limits | invoke | logs | promote | rollback | delete
33
35
  seq-studio storage <sub> [args] init | validate | apply | list | show | mkdir | upload | download | access | trash | restore | purge | operations | abort | delete
34
36
  seq-studio agents <sub> [args] init | validate | plan | apply | list | show
35
37
  seq-studio secrets <sub> [args] create | set | list | attach | detach | apply
36
- seq-studio repos <sub> [args] list | namespaces | show | create | clone | pull | delete
38
+ seq-studio repos <sub> [args] list | namespaces | show | create | clone | pull | pulls | delete
37
39
  seq-studio pipeline <sub> [args] search | describe | schema | sample | query | list | assets | init | validate | plan | deploy | status
38
- seq-studio auth <sub> [args] pat create | pat list | pat revoke
40
+ seq-studio auth <sub> [args] whoami | pat create | pat list | pat revoke
39
41
  seq-studio orm <sub> [args] init | generate | validate | plan | apply | execute | diff | migrate-from-yaml
42
+ seq-studio service-accounts <sub> list | show | create (requires provisioning authority)
43
+ seq-studio access <sub> definitions | list | grant | revoke | resolve
40
44
  seq-studio envs <sub> add | list | refresh environments
41
45
  seq-studio login [--env <name>] authenticate in the browser
42
46
  seq-studio logout [--env <name>] remove one realm's cached user tokens
@@ -114,6 +118,14 @@ export async function run(argv = process.argv.slice(2)) {
114
118
  const { runReposCommand } = await import('./repos/commands.js');
115
119
  return runReposCommand(sub, parseArgs(rest));
116
120
  }
121
+ case 'service-accounts': {
122
+ const { runServiceAccountsCommand } = await import('./service-accounts/commands.js');
123
+ return runServiceAccountsCommand(sub, parseArgs(rest));
124
+ }
125
+ case 'access': {
126
+ const { runAccessCommand } = await import('./access/commands.js');
127
+ return runAccessCommand(sub, parseArgs(rest));
128
+ }
117
129
  case 'auth': {
118
130
  const { runAuthCommand } = await import('./auth-cmds/commands.js');
119
131
  return runAuthCommand(sub, parseArgs(rest));
@@ -0,0 +1,33 @@
1
+ /** Role keys an artifact, managed function or ORM namespace manifest defines. */
2
+ export declare function hostRoleKeys(manifest: unknown): string[];
3
+ /** Runtime and collaborator role keys sequence.app.yml defines. */
4
+ export declare function applicationRoleKeys(manifest: unknown): string[];
5
+ export declare function manifestRolesNotice({ file, keys, where, }: {
6
+ file: string;
7
+ keys: readonly string[];
8
+ /** Where in Atlas these roles are managed. */
9
+ where: string;
10
+ }): string | null;
11
+ /**
12
+ * Print the notice for a manifest in `dir`, if it defines roles. Best-effort:
13
+ * a missing or unreadable file is the deploy's error to report, not this one's.
14
+ */
15
+ export declare function warnOnManifestRoles({ dir, file, kind, }: {
16
+ dir: string;
17
+ file: string;
18
+ kind: 'host' | 'application';
19
+ }): Promise<void>;
20
+ /** Before `sub` deploys a host manifest from `args`, warn if it defines roles. */
21
+ export declare function warnBeforeHostDeploy({ sub, deploySub, args, file, }: {
22
+ sub: string | undefined;
23
+ /** The subcommand that deploys (`deploy`, `apply`). */
24
+ deploySub: string;
25
+ args: readonly string[];
26
+ file: string;
27
+ }): Promise<void>;
28
+ /**
29
+ * The directory a command's argv points at that holds `file`: the first
30
+ * argument naming such a directory, else the working directory. Avoids
31
+ * guessing which arguments are flag values.
32
+ */
33
+ export declare function manifestDirFromArgs(args: readonly string[], file: string): string;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Roles are created and edited in Atlas (the Permissions UI or the roles API)
3
+ * by capability admins. Role definitions in YAML — `capabilities.roles.definitions`
4
+ * in artifact.bundle.yml, managed-function.yml and namespace.yaml, and
5
+ * `roles` / `collaborators` in sequence.app.yml — are a deprecated one-time
6
+ * seed: a deploy creates any that don't exist yet and never updates them.
7
+ * Capabilities stay in YAML; they are the code's contract.
8
+ *
9
+ * Atlas only logs the drift, so the CLI tells the author before deploying.
10
+ */
11
+ import { existsSync } from 'node:fs';
12
+ import { readFile } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ import { load as loadYaml } from 'js-yaml';
15
+ function isRecord(value) {
16
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
17
+ }
18
+ function definitionKeys(block) {
19
+ if (!isRecord(block) || !isRecord(block.definitions))
20
+ return [];
21
+ return Object.keys(block.definitions);
22
+ }
23
+ /** Role keys an artifact, managed function or ORM namespace manifest defines. */
24
+ export function hostRoleKeys(manifest) {
25
+ if (!isRecord(manifest) || !isRecord(manifest.capabilities))
26
+ return [];
27
+ return definitionKeys(manifest.capabilities.roles).sort();
28
+ }
29
+ /** Runtime and collaborator role keys sequence.app.yml defines. */
30
+ export function applicationRoleKeys(manifest) {
31
+ if (!isRecord(manifest))
32
+ return [];
33
+ return [...definitionKeys(manifest.roles), ...definitionKeys(manifest.collaborators)].sort();
34
+ }
35
+ export function manifestRolesNotice({ file, keys, where, }) {
36
+ if (keys.length === 0)
37
+ return null;
38
+ return (`[seq-studio] ${file} defines roles (${keys.join(', ')}). Roles in YAML are a deprecated one-time seed: ` +
39
+ `a deploy creates any that don't exist yet and never updates them after. Create and edit roles in Atlas ` +
40
+ `(${where}) or through the roles API; keep capabilities in YAML.`);
41
+ }
42
+ /**
43
+ * Print the notice for a manifest in `dir`, if it defines roles. Best-effort:
44
+ * a missing or unreadable file is the deploy's error to report, not this one's.
45
+ */
46
+ export async function warnOnManifestRoles({ dir, file, kind, }) {
47
+ let manifest;
48
+ try {
49
+ manifest = loadYaml(await readFile(join(dir, file), 'utf8'));
50
+ }
51
+ catch {
52
+ return;
53
+ }
54
+ const notice = manifestRolesNotice({
55
+ file,
56
+ keys: kind === 'host' ? hostRoleKeys(manifest) : applicationRoleKeys(manifest),
57
+ where: kind === 'host' ? 'Permissions → Roles' : 'Permissions → Applications → Edit roles',
58
+ });
59
+ if (notice)
60
+ console.warn(notice);
61
+ }
62
+ /** Before `sub` deploys a host manifest from `args`, warn if it defines roles. */
63
+ export async function warnBeforeHostDeploy({ sub, deploySub, args, file, }) {
64
+ if (sub !== deploySub)
65
+ return;
66
+ await warnOnManifestRoles({ dir: manifestDirFromArgs(args, file), file, kind: 'host' });
67
+ }
68
+ /**
69
+ * The directory a command's argv points at that holds `file`: the first
70
+ * argument naming such a directory, else the working directory. Avoids
71
+ * guessing which arguments are flag values.
72
+ */
73
+ export function manifestDirFromArgs(args, file) {
74
+ return args.find((arg) => !arg.startsWith('-') && existsSync(join(arg, file))) ?? '.';
75
+ }
@@ -9,6 +9,7 @@ import { getAccessToken, tryGetAccessToken } from '../auth.js';
9
9
  import { resolveEnvWithDiscovery } from '../config.js';
10
10
  import { normalizeShortEnvFlag, readEnvFromArgv } from '../env-flags.js';
11
11
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
12
+ import { warnBeforeHostDeploy } from '../manifest-roles-notice.js';
12
13
  /**
13
14
  * ORM subcommands that talk to Atlas — must not silently target `local`.
14
15
  * `init`, `generate`, `validate`, `diff`, and `migrate-from-yaml` are offline.
@@ -103,5 +104,6 @@ export async function runOrmCommand(sub, rest) {
103
104
  return null;
104
105
  }
105
106
  });
107
+ await warnBeforeHostDeploy({ sub, deploySub: 'apply', args: normalized, file: 'namespace.yaml' });
106
108
  return runCli([sub, ...normalized]);
107
109
  }
@@ -10,6 +10,7 @@ export interface StageRef {
10
10
  export interface AttachableSecret {
11
11
  id: string;
12
12
  name: string;
13
+ valueType?: 'single' | 'key_value';
13
14
  orgId: string;
14
15
  currentUserAccess: string | null;
15
16
  }
@@ -33,17 +34,19 @@ export declare function resolveStage({ client, slug, repo, }: {
33
34
  slug: string;
34
35
  repo?: string;
35
36
  }): Promise<StageRef>;
36
- export declare function attachSecretToStage({ client, stageId, deployTarget, symbolic, secretId, }: {
37
+ export declare function attachSecretToStage({ client, stageId, deployTarget, symbolic, secretId, entryKey, }: {
37
38
  client: ClientOptions;
38
39
  stageId: string;
39
40
  deployTarget: string;
40
41
  symbolic: string;
41
42
  secretId: string;
43
+ entryKey?: string;
42
44
  }): Promise<void>;
43
45
  export interface StageBinding {
44
46
  deployTarget: string;
45
47
  symbolic: string;
46
48
  secretId: string;
49
+ entryKey?: string | null;
47
50
  secretName: string;
48
51
  }
49
52
  export declare function listStageBindings({ client, stageId }: {
@@ -34,11 +34,11 @@ export async function resolveStage({ client, slug, repo, }) {
34
34
  }
35
35
  return stages[0];
36
36
  }
37
- export async function attachSecretToStage({ client, stageId, deployTarget, symbolic, secretId, }) {
37
+ export async function attachSecretToStage({ client, stageId, deployTarget, symbolic, secretId, entryKey, }) {
38
38
  await postJson({
39
39
  ...client,
40
40
  path: `/api/data-pipelines/stages/${encodeURIComponent(stageId)}/secret-bindings`,
41
- body: { deployTarget, symbolic, secretId },
41
+ body: { deployTarget, symbolic, secretId, ...(entryKey ? { entryKey } : {}) },
42
42
  });
43
43
  }
44
44
  export async function listStageBindings({ client, stageId }) {
@@ -134,6 +134,10 @@ export async function reconcileStageCredentials({ client, repo, stageIds, deploy
134
134
  result.unresolved.push({ ...credential, reason: `you are not an editor on ${credential.managedSecretName}` });
135
135
  continue;
136
136
  }
137
+ if (secret.valueType === 'key_value') {
138
+ result.unresolved.push({ ...credential, reason: `${credential.managedSecretName} is a key/value set; attach a selected entry with seq-studio secrets attach ${credential.managedSecretName} --stage ${credential.stage.slug} --credential ${credential.symbolic} --entry KEY` });
139
+ continue;
140
+ }
137
141
  await attachSecretToStage({
138
142
  client,
139
143
  stageId: credential.stage.id,
@@ -810,6 +810,10 @@ export async function simulateCommand(args) {
810
810
  // doctor (token + env + FGA gate)
811
811
  // ---------------------------------------------------------------------------
812
812
  export async function doctorCommand(args) {
813
+ if (args.flags.help || args.positional.includes('-h') || args.positional[0] === 'help') {
814
+ console.log('usage: seq-studio doctor [-e <env>]\n\nDiagnose configuration, authentication, and deployment access. Help is offline.');
815
+ return 0;
816
+ }
813
817
  const lines = [];
814
818
  let ok = true;
815
819
  const config = await readConfig().catch(() => null);