@sequenceholdings/studio-cli 0.2.1 → 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.
Files changed (49) hide show
  1. package/README.md +333 -29
  2. package/dist/access/commands.d.ts +3 -0
  3. package/dist/access/commands.js +91 -0
  4. package/dist/app/adapters.js +27 -5
  5. package/dist/app/application-registration.d.ts +96 -0
  6. package/dist/app/application-registration.js +146 -0
  7. package/dist/app/deploy.d.ts +8 -0
  8. package/dist/app/deploy.js +42 -8
  9. package/dist/app/manifest-validation.d.ts +20 -1
  10. package/dist/app/manifest-validation.js +130 -6
  11. package/dist/app/manifest.d.ts +110 -2
  12. package/dist/app/manifest.js +109 -3
  13. package/dist/app/primitive-scaffold.js +11 -1
  14. package/dist/app/readme.js +2 -0
  15. package/dist/app/scaffold.js +3 -2
  16. package/dist/app/workspace-scaffold.js +3 -3
  17. package/dist/artifact/delegate.js +8 -4
  18. package/dist/auth-cmds/commands.d.ts +1 -1
  19. package/dist/auth-cmds/commands.js +16 -0
  20. package/dist/cli-errors.js +4 -0
  21. package/dist/command-input.d.ts +15 -0
  22. package/dist/command-input.js +33 -0
  23. package/dist/functions/commands.d.ts +2 -1
  24. package/dist/functions/commands.js +61 -30
  25. package/dist/functions/manifest.d.ts +7 -1
  26. package/dist/functions/manifest.js +40 -12
  27. package/dist/functions/secret-reconcile.d.ts +3 -3
  28. package/dist/functions/secret-reconcile.js +5 -7
  29. package/dist/main.d.ts +3 -1
  30. package/dist/main.js +19 -7
  31. package/dist/manifest-roles-notice.d.ts +33 -0
  32. package/dist/manifest-roles-notice.js +75 -0
  33. package/dist/orm/delegate.js +2 -0
  34. package/dist/pipeline/commands.js +11 -0
  35. package/dist/pipeline/discovery.d.ts +8 -0
  36. package/dist/pipeline/discovery.js +249 -0
  37. package/dist/pipeline/lifecycle.js +35 -10
  38. package/dist/pipeline/stage-secrets.d.ts +4 -1
  39. package/dist/pipeline/stage-secrets.js +6 -2
  40. package/dist/process/commands.js +4 -0
  41. package/dist/repos/commands.d.ts +10 -1
  42. package/dist/repos/commands.js +16 -8
  43. package/dist/repos/pulls.d.ts +3 -0
  44. package/dist/repos/pulls.js +131 -0
  45. package/dist/secrets/commands.d.ts +1 -1
  46. package/dist/secrets/commands.js +97 -16
  47. package/dist/service-accounts/commands.d.ts +3 -0
  48. package/dist/service-accounts/commands.js +50 -0
  49. package/package.json +5 -5
@@ -1,7 +1,7 @@
1
1
  import type { ParsedArgs } from '../process/commands.js';
2
2
  declare const PAT_SCOPES: readonly ["repo:read", "repo:write", "repo:admin"];
3
3
  type PatScope = (typeof PAT_SCOPES)[number];
4
- export declare const AUTH_USAGE = "usage:\n seq-studio auth pat create --name <n> -e <env> [--scopes repo:read,repo:write]\n [--expires 1d|7d|30d|90d|1y|never] [--store-credentials]\n seq-studio auth pat list -e <env>\n seq-studio auth pat revoke <id> -e <env> [--yes]\n\n Issue a personal access token for git clone / git push against the platform\n git service.\n\n Authenticate with `seq-studio login`, then run `auth pat create -e <env>`.\n Alternatively, open Atlas \u2192 Settings \u2192 Tokens:\n https://<atlas-host>/settings/tokens\n Sign in, create a token (repo:read / repo:write), copy once, then:\n export ATLAS_GIT_PAT=<token>\n repo:write covers push and PR open; merging a PR requires an FGA Merge\n (or Admin) grant on the repository, not a PAT scope.\n\n On create the raw token is printed ONCE \u2014 store it; Atlas cannot re-show it.\n Git Basic auth: any username (e.g. git), PAT as the password.\n\n Flags: -e/--env <env> (required; see: seq-studio envs list)\n";
4
+ export declare const AUTH_USAGE = "usage:\n seq-studio auth whoami -e <env> [--json] server-verified identity and target (no tokens)\n seq-studio auth pat create --name <n> -e <env> [--scopes repo:read,repo:write]\n [--expires 1d|7d|30d|90d|1y|never] [--store-credentials]\n seq-studio auth pat list -e <env>\n seq-studio auth pat revoke <id> -e <env> [--yes]\n\n Issue a personal access token for git clone / git push against the platform\n git service.\n\n Authenticate with `seq-studio login`, then run `auth pat create -e <env>`.\n Alternatively, open Atlas \u2192 Settings \u2192 Tokens:\n https://<atlas-host>/settings/tokens\n Sign in, create a token (repo:read / repo:write), copy once, then:\n export ATLAS_GIT_PAT=<token>\n repo:write covers push and PR open; merging a PR requires an FGA Merge\n (or Admin) grant on the repository, not a PAT scope.\n\n On create the raw token is printed ONCE \u2014 store it; Atlas cannot re-show it.\n Git Basic auth: any username (e.g. git), PAT as the password.\n\n Flags: -e/--env <env> (required; see: seq-studio envs list)\n";
5
5
  export declare function parsePatScopes(raw: string | undefined): PatScope[];
6
6
  /**
7
7
  * Map UI-style duration choices to an absolute ISO-8601 expiresAt, or undefined
@@ -8,6 +8,7 @@
8
8
  * The raw token is printed exactly once on create; use it as the Basic-auth
9
9
  * password for `git clone` / `git push` (username is ignored).
10
10
  */
11
+ import { validateCommandInput, wantsHelp } from '../command-input.js';
11
12
  import { deleteNoContent, getJson, postJson } from '../atlas-client.js';
12
13
  import { printCliError } from '../cli-errors.js';
13
14
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
@@ -39,6 +40,7 @@ function stringFlag(flags, key) {
39
40
  return value;
40
41
  }
41
42
  export const AUTH_USAGE = `usage:
43
+ seq-studio auth whoami -e <env> [--json] server-verified identity and target (no tokens)
42
44
  seq-studio auth pat create --name <n> -e <env> [--scopes repo:read,repo:write]
43
45
  [--expires 1d|7d|30d|90d|1y|never] [--store-credentials]
44
46
  seq-studio auth pat list -e <env>
@@ -223,7 +225,21 @@ export async function authPatRevokeCommand(args) {
223
225
  }
224
226
  export async function runAuthCommand(sub, args) {
225
227
  try {
228
+ if (wantsHelp({ sub, args })) {
229
+ console.log(AUTH_USAGE);
230
+ return 0;
231
+ }
226
232
  switch (sub) {
233
+ case 'whoami': {
234
+ validateCommandInput({ args, flags: {}, positional: 0 });
235
+ const ctx = await buildContext(args);
236
+ const { sub: subject, email, name, tenantSlug, roles, permissions } = await getJson({ ...clientOptions(ctx), path: '/api/me' });
237
+ console.log(JSON.stringify({
238
+ environment: ctx.env.name, url: ctx.env.url, authMode: ctx.authMode,
239
+ identity: { sub: subject, email, name, tenantSlug, roles, permissions },
240
+ }, null, 2));
241
+ return 0;
242
+ }
227
243
  case 'pat': {
228
244
  const action = args.positional[0];
229
245
  const nested = {
@@ -49,12 +49,16 @@ function nextStepForAtlasError(error) {
49
49
  return 'Next step: rerun deploy — another upload may have taken the version slot.';
50
50
  }
51
51
  if (error.status === 413 || msg.includes('too large')) {
52
+ if (error.path.startsWith('/api/data-pipelines/'))
53
+ return 'Next step: reduce the request size and retry; pipeline query accepts up to 10,000 SQL characters.';
52
54
  return 'Next step: run `seq-studio functions build` and reduce bundle size or dependencies.';
53
55
  }
54
56
  if (error.status === 503) {
55
57
  return 'Next step: wait a few seconds and retry (backend may still be warming up).';
56
58
  }
57
59
  if (error.status === 524 || msg.includes('timeout') || msg.includes('timed out')) {
60
+ if (error.path.startsWith('/api/data-pipelines/'))
61
+ return 'Next step: retry the read; if it persists, confirm the environment and backend availability.';
58
62
  return 'Next step: retry; if it persists check VPN/network, then `seq-studio functions list` or logs to see whether the operation completed.';
59
63
  }
60
64
  return null;
@@ -0,0 +1,15 @@
1
+ import type { ParsedArgs } from './process/commands.js';
2
+ /** Validate before authentication: a typo must never silently widen a mutation. */
3
+ export declare function validateCommandInput({ args, flags, positional, }: {
4
+ args: ParsedArgs;
5
+ flags: Record<string, 'string' | 'boolean'>;
6
+ positional: number;
7
+ }): void;
8
+ export declare function requiredStringFlag({ args, key }: {
9
+ args: ParsedArgs;
10
+ key: string;
11
+ }): string;
12
+ export declare function wantsHelp({ sub, args }: {
13
+ sub?: string;
14
+ args: ParsedArgs;
15
+ }): boolean;
@@ -0,0 +1,33 @@
1
+ import { REQUIRE_EXPLICIT_ENV_MESSAGE } from './env-flags.js';
2
+ /** Validate before authentication: a typo must never silently widen a mutation. */
3
+ export function validateCommandInput({ args, flags, positional, }) {
4
+ const allowed = { ...flags, env: 'string', e: 'string', json: 'boolean' };
5
+ for (const [key, value] of Object.entries(args.flags)) {
6
+ if (!Object.hasOwn(allowed, key))
7
+ throw new Error(`Unknown flag --${key}. See --help.`);
8
+ if (allowed[key] === 'string' && (typeof value !== 'string' || !value.trim())) {
9
+ throw new Error(`--${key} requires a non-empty value.`);
10
+ }
11
+ if (allowed[key] === 'boolean' && value !== true) {
12
+ throw new Error(`--${key} does not take a value.`);
13
+ }
14
+ }
15
+ const envs = [args.flags.env, args.flags.e, ...(args.repeatedFlags?.env ?? []), ...(args.repeatedFlags?.e ?? [])]
16
+ .filter((value) => typeof value === 'string');
17
+ if (new Set(envs).size > 1)
18
+ throw new Error('Specify only one environment per command.');
19
+ if (envs.length === 0)
20
+ throw new Error(REQUIRE_EXPLICIT_ENV_MESSAGE);
21
+ if (args.positional.length !== positional) {
22
+ throw new Error(`Expected ${positional} positional argument(s). See --help.`);
23
+ }
24
+ }
25
+ export function requiredStringFlag({ args, key }) {
26
+ const value = args.flags[key];
27
+ if (typeof value !== 'string' || !value.trim())
28
+ throw new Error(`--${key} requires a value.`);
29
+ return value;
30
+ }
31
+ export function wantsHelp({ sub, args }) {
32
+ return sub === 'help' || sub === '--help' || sub === '-h' || args.flags.help === true || args.positional.includes('-h');
33
+ }
@@ -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}`;
@@ -313,6 +327,8 @@ const TEMPLATE_NPMRC = `# Pins installs to Chainguard, Sequence's internal packa
313
327
  # always re-resolves dependencies against Chainguard server-side, and this
314
328
  # file is never included in the deployed bundle either way.
315
329
  registry=https://libraries.cgr.dev/javascript/
330
+ # Sequence's own packages publish to public npm, as on the deploy worker.
331
+ @sequenceholdings:registry=https://registry.npmjs.org/
316
332
  //libraries.cgr.dev/javascript/:always-auth=true
317
333
  //libraries.cgr.dev/javascript-upstream/:always-auth=true
318
334
  `;
@@ -383,7 +399,7 @@ async function buildFromResolvedSource({ spec, source, }) {
383
399
  console.log(`${LOG} function: ${manifest.function.id} (${manifest.function.title})`);
384
400
  console.log(`${LOG} runtime: ${manifest.runtime}, entrypoint: ${manifest.entrypoint}`);
385
401
  console.log(`${LOG} files: ${files.length}`);
386
- 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)'}`);
387
403
  console.log(`${LOG} egress: ${formatEgressSummary([
388
404
  ...manifestEgressHosts(manifest.egress),
389
405
  ...manifestEgressIpRanges(manifest.egress),
@@ -444,6 +460,7 @@ export async function functionsDeployCommand(args) {
444
460
  const source = await resolveArtifactSource(spec, ctx ? sourceClientOptions(ctx) : {});
445
461
  try {
446
462
  const dir = await resolveFunctionSourceDir({ repoDir: source.dir, path });
463
+ await warnOnManifestRoles({ dir, file: 'managed-function.yml', kind: 'host' });
447
464
  return await deployFromResolvedSource({ args, spec, ctx, source: { ...source, dir } });
448
465
  }
449
466
  finally {
@@ -494,6 +511,8 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
494
511
  // sources authenticate only now, after local validation passed.
495
512
  const ctx = earlyCtx ?? (await buildContext(args));
496
513
  const slug = manifest.function.id;
514
+ const singleSecrets = manifest.secrets.filter((entry) => typeof entry === 'string');
515
+ const declaredSecretNames = manifestSecretNames(manifest);
497
516
  const { functions } = await getJson({
498
517
  ...clientOptions(ctx),
499
518
  path: `/api/managed-functions?slug=${encodeURIComponent(slug)}`,
@@ -536,6 +555,21 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
536
555
  s.name,
537
556
  { id: s.id, hasDefaultValue: s.hasDefaultValue, attachmentCount: s.attachmentCount },
538
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
+ }
539
573
  // Build envVar → secretId map so the classifier can detect when an env
540
574
  // var is already attached to a *different* secret and not skip reconcile.
541
575
  const attachedByEnvVar = new Map();
@@ -544,10 +578,22 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
544
578
  for (const a of detail?.attachments ?? []) {
545
579
  if (a.secretId)
546
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
+ }
547
593
  }
548
594
  }
549
595
  classification = classifySecrets({
550
- manifestSecrets: manifest.secrets,
596
+ manifestSecrets: singleSecrets,
551
597
  envValues,
552
598
  serverInfoByName,
553
599
  attachedByEnvVar,
@@ -563,7 +609,7 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
563
609
  }
564
610
  }
565
611
  // Surface .env keys that aren't in the manifest so users know they're ignored.
566
- 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));
567
613
  const preview = [
568
614
  `${LOG} deploy preview:`,
569
615
  `${LOG} environment: ${ctx.env.name}`,
@@ -578,9 +624,15 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
578
624
  preview.push(`${LOG} git: ${git.gitBranch ?? '?'}@${git.gitCommit.slice(0, 8)}${git.gitDirty ? ' (dirty)' : ''}`);
579
625
  }
580
626
  if (classification) {
581
- 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
+ }
582
634
  if (classification.secrets.some((c) => c.category === 'OVERWRITE')) {
583
- 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`);
584
636
  }
585
637
  }
586
638
  else {
@@ -613,10 +665,6 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
613
665
  problems.push(`secret "${c.name}" would be written from a local value — provision it server-side first: ` +
614
666
  `\`seq-studio secrets set ${c.name} -e ${ctx.env.name}\``);
615
667
  }
616
- else if (c.category === 'USE_EXISTING' && !c.attachedToFn) {
617
- problems.push(`secret "${c.name}" exists but is not attached to ${slug} — attach it once: ` +
618
- `\`seq-studio secrets attach ${c.name} --fn ${slug} -e ${ctx.env.name}\``);
619
- }
620
668
  }
621
669
  if (problems.length > 0) {
622
670
  for (const problem of problems)
@@ -664,26 +712,6 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
664
712
  return 1;
665
713
  }
666
714
  }
667
- // USE_EXISTING not yet attached: attach only (no value change).
668
- const toAttach = classification.secrets.filter((c) => c.category === 'USE_EXISTING' && !c.attachedToFn && c.secretId !== null);
669
- for (const c of toAttach) {
670
- console.log(`${LOG} attaching existing secret "${c.name}" to ${slug}…`);
671
- try {
672
- await postJson({
673
- ...clientOptions(ctx),
674
- path: `/api/managed-secrets/${c.secretId}/attachments`,
675
- body: { functionId: fn.id, envVarName: c.name },
676
- });
677
- }
678
- catch (error) {
679
- if (error instanceof AtlasApiError && error.status === 409) {
680
- console.error(`${LOG} secret "${c.name}": env var is already attached to a different managed secret — ` +
681
- `detach the conflicting attachment first: \`seq-studio secrets detach <NAME> --fn ${slug} -e ${ctx.env.name}\``);
682
- return 1;
683
- }
684
- throw error;
685
- }
686
- }
687
715
  }
688
716
  if (git.gitDirty) {
689
717
  console.warn(`${LOG} working tree is dirty — recording gitDirty=true on this version`);
@@ -1124,6 +1152,7 @@ export async function functionsDeleteCommand(args) {
1124
1152
  export const FUNCTIONS_USAGE = `usage:
1125
1153
  seq-studio functions init <dir> scaffold manifest + TypeScript hello-world handler
1126
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
1127
1156
  seq-studio functions deploy -e <env> [-m msg] preview + confirm secrets + upload and deploy
1128
1157
  seq-studio functions list -e <env> [--match-local] functions visible on the environment
1129
1158
  seq-studio functions show -e <env> [--fn slug] detail for one function (versions, secrets)
@@ -1178,6 +1207,8 @@ export async function runFunctionsCommand(sub, args) {
1178
1207
  }
1179
1208
  case 'build':
1180
1209
  return await functionsBuildCommand(args);
1210
+ case 'register':
1211
+ return await functionsRegisterCommand(args);
1181
1212
  case 'deploy':
1182
1213
  return await functionsDeployCommand(args);
1183
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
@@ -11,8 +11,10 @@
11
11
  * seq-studio agents <sub> manage typed agent definitions
12
12
  * seq-studio secrets <sub> manage org-owned Managed Secrets
13
13
  * seq-studio repos <sub> manage platform git-service repos
14
- * seq-studio pipeline <sub> author + validate Data Pipelines stage specs
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
@@ -11,8 +11,10 @@
11
11
  * seq-studio agents <sub> manage typed agent definitions
12
12
  * seq-studio secrets <sub> manage org-owned Managed Secrets
13
13
  * seq-studio repos <sub> manage platform git-service repos
14
- * seq-studio pipeline <sub> author + validate Data Pipelines stage specs
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
37
- seq-studio pipeline <sub> [args] init | validate — Data Pipelines stage specs
38
- seq-studio auth <sub> [args] pat create | pat list | pat revoke
38
+ seq-studio repos <sub> [args] list | namespaces | show | create | clone | pull | pulls | delete
39
+ seq-studio pipeline <sub> [args] search | describe | schema | sample | query | list | assets | init | validate | plan | deploy | status
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;