@sequenceholdings/studio-cli 0.2.2 → 0.4.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.
Files changed (128) hide show
  1. package/README.md +616 -78
  2. package/dist/access/commands.d.ts +3 -0
  3. package/dist/access/commands.js +91 -0
  4. package/dist/agents/commands.d.ts +1 -1
  5. package/dist/agents/commands.js +5 -0
  6. package/dist/agents/scaffold.js +5 -7
  7. package/dist/agents/voice-authoring.d.ts +5 -0
  8. package/dist/agents/voice-authoring.js +75 -0
  9. package/dist/agents/voice-publication.d.ts +5 -0
  10. package/dist/agents/voice-publication.js +63 -0
  11. package/dist/agents/voice-shared.d.ts +20 -0
  12. package/dist/agents/voice-shared.js +112 -0
  13. package/dist/agents/voice.d.ts +3 -0
  14. package/dist/agents/voice.js +57 -0
  15. package/dist/app/adapters.d.ts +6 -0
  16. package/dist/app/adapters.js +17 -2
  17. package/dist/app/agent-refs.d.ts +16 -0
  18. package/dist/app/agent-refs.js +36 -0
  19. package/dist/app/application-registration.d.ts +36 -6
  20. package/dist/app/application-registration.js +60 -15
  21. package/dist/app/commands.js +19 -2
  22. package/dist/app/deploy.d.ts +3 -0
  23. package/dist/app/deploy.js +22 -6
  24. package/dist/app/env-bindings.d.ts +21 -0
  25. package/dist/app/env-bindings.js +184 -0
  26. package/dist/app/manifest-validation.js +8 -0
  27. package/dist/app/manifest.d.ts +32 -14
  28. package/dist/app/manifest.js +16 -6
  29. package/dist/app/primitive-scaffold.d.ts +4 -1
  30. package/dist/app/primitive-scaffold.js +4 -4
  31. package/dist/app/readme.js +1 -0
  32. package/dist/app/scaffold-files.js +1 -1
  33. package/dist/app/scaffold.d.ts +6 -4
  34. package/dist/app/scaffold.js +7 -4
  35. package/dist/app/workspace-scaffold.js +12 -7
  36. package/dist/argv.d.ts +7 -0
  37. package/dist/argv.js +56 -0
  38. package/dist/artifact/delegate.js +8 -4
  39. package/dist/atlas-client.d.ts +6 -0
  40. package/dist/atlas-client.js +39 -2
  41. package/dist/auth-cmds/commands.d.ts +1 -1
  42. package/dist/auth-cmds/commands.js +16 -0
  43. package/dist/auth.d.ts +32 -0
  44. package/dist/auth.js +170 -33
  45. package/dist/bin.js +23 -4
  46. package/dist/command-contract.d.ts +137 -0
  47. package/dist/command-contract.js +43 -0
  48. package/dist/command-help.d.ts +8 -0
  49. package/dist/command-help.js +71 -0
  50. package/dist/command-input.d.ts +15 -0
  51. package/dist/command-input.js +33 -0
  52. package/dist/functions/commands.d.ts +2 -1
  53. package/dist/functions/commands.js +78 -33
  54. package/dist/functions/deploy-preflight.d.ts +21 -0
  55. package/dist/functions/deploy-preflight.js +58 -0
  56. package/dist/functions/egress-postgres.d.ts +7 -0
  57. package/dist/functions/egress-postgres.js +36 -0
  58. package/dist/functions/manifest.d.ts +15 -1
  59. package/dist/functions/manifest.js +49 -12
  60. package/dist/functions/secret-reconcile.d.ts +3 -3
  61. package/dist/functions/secret-reconcile.js +5 -7
  62. package/dist/functions/source-selection.js +4 -1
  63. package/dist/main.d.ts +2 -0
  64. package/dist/main.js +75 -25
  65. package/dist/manifest-roles-notice.d.ts +33 -0
  66. package/dist/manifest-roles-notice.js +75 -0
  67. package/dist/orm/delegate.d.ts +16 -0
  68. package/dist/orm/delegate.js +142 -7
  69. package/dist/pipeline/clone-deploy.d.ts +37 -0
  70. package/dist/pipeline/clone-deploy.js +125 -0
  71. package/dist/pipeline/codegen.js +6 -2
  72. package/dist/pipeline/commands.js +21 -5
  73. package/dist/pipeline/lifecycle.d.ts +1 -0
  74. package/dist/pipeline/lifecycle.js +95 -44
  75. package/dist/pipeline/repin-orm.js +6 -2
  76. package/dist/pipeline/stage-secrets.d.ts +4 -1
  77. package/dist/pipeline/stage-secrets.js +7 -3
  78. package/dist/process/build.js +17 -0
  79. package/dist/process/codegen.js +16 -0
  80. package/dist/process/commands.d.ts +15 -7
  81. package/dist/process/commands.js +294 -98
  82. package/dist/process/lint.js +35 -0
  83. package/dist/process/plan-diff.js +9 -0
  84. package/dist/process/simulate.js +8 -0
  85. package/dist/release-age.d.ts +12 -0
  86. package/dist/release-age.js +24 -0
  87. package/dist/repos/commands.d.ts +10 -1
  88. package/dist/repos/commands.js +42 -8
  89. package/dist/repos/pulls.d.ts +3 -0
  90. package/dist/repos/pulls.js +131 -0
  91. package/dist/scaffold-guidance.d.ts +4 -0
  92. package/dist/scaffold-guidance.js +15 -0
  93. package/dist/secrets/commands.d.ts +1 -1
  94. package/dist/secrets/commands.js +97 -16
  95. package/dist/service-accounts/commands.d.ts +3 -0
  96. package/dist/service-accounts/commands.js +50 -0
  97. package/dist/storage/commands.js +23 -1
  98. package/dist/storage/gcs-download.d.ts +13 -0
  99. package/dist/storage/gcs-download.js +41 -0
  100. package/dist/storage/import-cycle.d.ts +41 -0
  101. package/dist/storage/import-cycle.js +123 -0
  102. package/dist/storage/import-files.d.ts +30 -0
  103. package/dist/storage/import-files.js +133 -0
  104. package/dist/storage/import-gcloud.d.ts +12 -0
  105. package/dist/storage/import-gcloud.js +54 -0
  106. package/dist/storage/import-identity.d.ts +12 -0
  107. package/dist/storage/import-identity.js +15 -0
  108. package/dist/storage/import-plan.d.ts +120 -0
  109. package/dist/storage/import-plan.js +189 -0
  110. package/dist/storage/import-preflight.d.ts +36 -0
  111. package/dist/storage/import-preflight.js +62 -0
  112. package/dist/storage/import-progress-map.d.ts +5 -0
  113. package/dist/storage/import-progress-map.js +22 -0
  114. package/dist/storage/import-recover.d.ts +97 -0
  115. package/dist/storage/import-recover.js +186 -0
  116. package/dist/storage/import-run.d.ts +14 -0
  117. package/dist/storage/import-run.js +140 -0
  118. package/dist/templates/guidance/AGENTS.md +10 -0
  119. package/dist/templates/guidance/CLAUDE.md +1 -0
  120. package/dist/templates/process/package.json +2 -2
  121. package/dist/templates/process/pnpm-workspace.yaml +7 -4
  122. package/dist/validation-detail.d.ts +2 -0
  123. package/dist/validation-detail.js +20 -0
  124. package/package.json +9 -9
  125. package/templates/guidance/AGENTS.md +10 -0
  126. package/templates/guidance/CLAUDE.md +1 -0
  127. package/templates/process/package.json +2 -2
  128. package/templates/process/pnpm-workspace.yaml +7 -4
@@ -11,15 +11,19 @@ import { getAccessTokenWithMode, tryGetAccessTokenWithMode } from '../auth.js';
11
11
  import { resolveEnvWithDiscovery } from '../config.js';
12
12
  import { AtlasApiError, deleteJson, getJson, postJson, postJsonResponse, } from '../atlas-client.js';
13
13
  import { clarifyApplyFailureReason, printCliError } from '../cli-errors.js';
14
+ import { currentVersion } from '../update-check.js';
15
+ import { localSdkPreflight, preflightBeforeUpload, reportPreflight } from './deploy-preflight.js';
14
16
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
15
17
  import { confirmYes } from '../prompt.js';
18
+ import { writeScaffoldGuidance } from '../scaffold-guidance.js';
16
19
  import { collectBundleFiles, isDirectory, validateLocalBundle, } from './bundle.js';
17
- import { managedFunctionManifestSchema, MF_MANIFEST_FILENAME, manifestEgressHosts, manifestEgressIpRanges, } from './manifest.js';
20
+ import { managedFunctionManifestSchema, MF_MANIFEST_FILENAME, manifestEgressHosts, manifestEgressIpRanges, manifestSecretNames, } from './manifest.js';
18
21
  import { buildEgressPreviewLines, egressPropagationNote, formatEgressSummary, printFunctionEgressHosts, } from './egress-preview.js';
19
22
  import { resolveArtifactSource, } from '@sequenceholdings/artifact-studio/source-resolver';
20
23
  import { buildSecretPreviewLines, classifySecrets, } from './secret-reconcile.js';
21
24
  import { parseFunctionsSourceSelection, resolveFunctionSourceDir } from './source-selection.js';
22
25
  export { parseFunctionsSourceSelection, parseFunctionsSourceSpec, resolveFunctionSourceDir, } from './source-selection.js';
26
+ import { warnOnManifestRoles } from '../manifest-roles-notice.js';
23
27
  const execFileAsync = promisify(execFile);
24
28
  export const LOG = '[seq-studio]';
25
29
  const POLL_INTERVAL_MS = 5_000;
@@ -136,6 +140,19 @@ export async function resolveOrRegisterFunction({ ctx, slug, title, description,
136
140
  });
137
141
  return { fn: created.function, created: true };
138
142
  }
143
+ export async function functionsRegisterCommand(args) {
144
+ const dir = resolve(typeof args.flags.dir === 'string' ? args.flags.dir : process.cwd());
145
+ const manifest = await readManifest(dir);
146
+ const ctx = await buildContext(args);
147
+ const { fn, created } = await resolveOrRegisterFunction({
148
+ ctx,
149
+ slug: manifest.function.id,
150
+ title: manifest.function.title,
151
+ description: manifest.function.description ?? null,
152
+ });
153
+ console.log(`${LOG} ${created ? 'registered' : 'found'} managed function "${manifest.function.id}" (${fn.id}) on ${ctx.env.name}`);
154
+ return 0;
155
+ }
139
156
  export function predictNextVersion(latest) {
140
157
  const parsed = latest ? Number.parseInt(latest.replace(/^v/, ''), 10) : 0;
141
158
  return `v${(Number.isFinite(parsed) ? parsed : 0) + 1}`;
@@ -346,7 +363,9 @@ export async function functionsInitCommand(args) {
346
363
  await writeFile(join(dir, 'package.json'), TEMPLATE_PACKAGE_JSON(id));
347
364
  await writeFile(join(dir, '.gitignore'), TEMPLATE_GITIGNORE);
348
365
  await writeFile(join(dir, '.npmrc'), TEMPLATE_NPMRC);
366
+ await writeScaffoldGuidance({ directory: dir });
349
367
  console.log(`${LOG} scaffolded managed function "${id}" (TypeScript) in ${dir}`);
368
+ console.log(`${LOG} AGENTS.md points to your environment's live docs; CLAUDE.md imports it`);
350
369
  console.log('');
351
370
  console.log('Next steps (init is only needed when creating a function from scratch):');
352
371
  console.log(` cd ${target}`);
@@ -385,7 +404,7 @@ async function buildFromResolvedSource({ spec, source, }) {
385
404
  console.log(`${LOG} function: ${manifest.function.id} (${manifest.function.title})`);
386
405
  console.log(`${LOG} runtime: ${manifest.runtime}, entrypoint: ${manifest.entrypoint}`);
387
406
  console.log(`${LOG} files: ${files.length}`);
388
- console.log(`${LOG} secrets: ${manifest.secrets.length > 0 ? manifest.secrets.join(', ') : '(none declared)'}`);
407
+ console.log(`${LOG} secrets: ${manifest.secrets.length > 0 ? manifestSecretNames(manifest).join(', ') : '(none declared)'}`);
389
408
  console.log(`${LOG} egress: ${formatEgressSummary([
390
409
  ...manifestEgressHosts(manifest.egress),
391
410
  ...manifestEgressIpRanges(manifest.egress),
@@ -398,6 +417,9 @@ async function buildFromResolvedSource({ spec, source, }) {
398
417
  log(`${LOG} ${issue.level}: ${issue.message}`);
399
418
  }
400
419
  const errors = issues.filter((i) => i.level === 'error');
420
+ const sdkIssues = await localSdkPreflight({ rootDir: dir, manifest, cliVersion: currentVersion() });
421
+ if (reportPreflight(sdkIssues))
422
+ return 1;
401
423
  if (errors.length > 0) {
402
424
  console.error(`${LOG} build check failed (${errors.length} error${errors.length === 1 ? '' : 's'})`);
403
425
  return 1;
@@ -446,6 +468,7 @@ export async function functionsDeployCommand(args) {
446
468
  const source = await resolveArtifactSource(spec, ctx ? sourceClientOptions(ctx) : {});
447
469
  try {
448
470
  const dir = await resolveFunctionSourceDir({ repoDir: source.dir, path });
471
+ await warnOnManifestRoles({ dir, file: 'managed-function.yml', kind: 'host' });
449
472
  return await deployFromResolvedSource({ args, spec, ctx, source: { ...source, dir } });
450
473
  }
451
474
  finally {
@@ -495,7 +518,17 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
495
518
  // A --repo source authenticated before materialization; local / git-url
496
519
  // sources authenticate only now, after local validation passed.
497
520
  const ctx = earlyCtx ?? (await buildContext(args));
521
+ const capabilityIssues = await preflightBeforeUpload({
522
+ client: clientOptions(ctx),
523
+ rootDir: dir,
524
+ manifest,
525
+ cliVersion: currentVersion(),
526
+ });
527
+ if (reportPreflight(capabilityIssues))
528
+ return 1;
498
529
  const slug = manifest.function.id;
530
+ const singleSecrets = manifest.secrets.filter((entry) => typeof entry === 'string');
531
+ const declaredSecretNames = manifestSecretNames(manifest);
499
532
  const { functions } = await getJson({
500
533
  ...clientOptions(ctx),
501
534
  path: `/api/managed-functions?slug=${encodeURIComponent(slug)}`,
@@ -538,6 +571,21 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
538
571
  s.name,
539
572
  { id: s.id, hasDefaultValue: s.hasDefaultValue, attachmentCount: s.attachmentCount },
540
573
  ]));
574
+ for (const binding of manifest.secrets) {
575
+ if (typeof binding === 'string')
576
+ continue;
577
+ const source = serverSecrets.find((secret) => secret.name === binding.secret);
578
+ if (!source || source.valueType !== 'key_value' || !source.hasDefaultValue) {
579
+ console.error(`${LOG} key/value set "${binding.secret}" must exist with a default value before deploying`);
580
+ return 1;
581
+ }
582
+ for (const envName of Object.values(binding.entries)) {
583
+ if (!envValues[envName])
584
+ continue;
585
+ 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`);
586
+ return 1;
587
+ }
588
+ }
541
589
  // Build envVar → secretId map so the classifier can detect when an env
542
590
  // var is already attached to a *different* secret and not skip reconcile.
543
591
  const attachedByEnvVar = new Map();
@@ -546,10 +594,22 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
546
594
  for (const a of detail?.attachments ?? []) {
547
595
  if (a.secretId)
548
596
  attachedByEnvVar.set(a.envVarName, a.secretId);
597
+ if (a.secretId && a.entryMappings) {
598
+ const secret = serverSecrets.find((row) => row.id === a.secretId);
599
+ for (const envName of Object.values(a.entryMappings)) {
600
+ attachedByEnvVar.set(envName, a.secretId);
601
+ if (secret)
602
+ serverInfoByName.set(envName, { id: secret.id, hasDefaultValue: secret.hasDefaultValue, attachmentCount: secret.attachmentCount });
603
+ if (envValues[envName]) {
604
+ 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`);
605
+ return 1;
606
+ }
607
+ }
608
+ }
549
609
  }
550
610
  }
551
611
  classification = classifySecrets({
552
- manifestSecrets: manifest.secrets,
612
+ manifestSecrets: singleSecrets,
553
613
  envValues,
554
614
  serverInfoByName,
555
615
  attachedByEnvVar,
@@ -565,7 +625,7 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
565
625
  }
566
626
  }
567
627
  // 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));
628
+ const undeclaredEnvKeys = Object.keys(envValues).filter((k) => envValues[k]?.length && !declaredSecretNames.includes(k));
569
629
  const preview = [
570
630
  `${LOG} deploy preview:`,
571
631
  `${LOG} environment: ${ctx.env.name}`,
@@ -580,9 +640,15 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
580
640
  preview.push(`${LOG} git: ${git.gitBranch ?? '?'}@${git.gitCommit.slice(0, 8)}${git.gitDirty ? ' (dirty)' : ''}`);
581
641
  }
582
642
  if (classification) {
583
- preview.push(...buildSecretPreviewLines(LOG, classification.secrets));
643
+ preview.push(...(classification.secrets.length === 0 && manifest.secrets.length > 0
644
+ ? [`${LOG} secrets:`]
645
+ : buildSecretPreviewLines(LOG, classification.secrets)));
646
+ for (const binding of manifest.secrets) {
647
+ if (typeof binding !== 'string')
648
+ preview.push(`${LOG} - set ${binding.secret}: ${Object.entries(binding.entries).map(([key, env]) => `${key} → ${env}`).join(', ')}`);
649
+ }
584
650
  if (classification.secrets.some((c) => c.category === 'OVERWRITE')) {
585
- preview.push(`${LOG} note: overwriting a shared default changes it for all attached functions`);
651
+ preview.push(`${LOG} note: overwriting a shared default changes it for all functions using that secret`);
586
652
  }
587
653
  }
588
654
  else {
@@ -615,10 +681,6 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
615
681
  problems.push(`secret "${c.name}" would be written from a local value — provision it server-side first: ` +
616
682
  `\`seq-studio secrets set ${c.name} -e ${ctx.env.name}\``);
617
683
  }
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
684
  }
623
685
  if (problems.length > 0) {
624
686
  for (const problem of problems)
@@ -666,26 +728,6 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
666
728
  return 1;
667
729
  }
668
730
  }
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
731
  }
690
732
  if (git.gitDirty) {
691
733
  console.warn(`${LOG} working tree is dirty — recording gitDirty=true on this version`);
@@ -1124,9 +1166,10 @@ export async function functionsDeleteCommand(args) {
1124
1166
  // dispatcher
1125
1167
  // ---------------------------------------------------------------------------
1126
1168
  export const FUNCTIONS_USAGE = `usage:
1127
- seq-studio functions init <dir> scaffold manifest + TypeScript hello-world handler
1128
- seq-studio functions build [--dir d] local pre-flight (manifest, lockfile, size)
1129
- seq-studio functions deploy -e <env> [-m msg] preview + confirm secrets + upload and deploy
1169
+ seq-studio functions init <dir> scaffold manifest, TypeScript handler, and docs pointers
1170
+ seq-studio functions build [--dir d] local pre-flight (manifest, lockfile, SDK timeout cap)
1171
+ seq-studio functions register -e <env> [--dir d] register a function shell without deploying
1172
+ seq-studio functions deploy -e <env> [-m msg] preflight deployed capabilities, then upload and deploy
1130
1173
  seq-studio functions list -e <env> [--match-local] functions visible on the environment
1131
1174
  seq-studio functions show -e <env> [--fn slug] detail for one function (versions, secrets)
1132
1175
  seq-studio functions limits [-e <env>] [--json] bundled defaults/caps, or deployed policy
@@ -1180,6 +1223,8 @@ export async function runFunctionsCommand(sub, args) {
1180
1223
  }
1181
1224
  case 'build':
1182
1225
  return await functionsBuildCommand(args);
1226
+ case 'register':
1227
+ return await functionsRegisterCommand(args);
1183
1228
  case 'deploy':
1184
1229
  return await functionsDeployCommand(args);
1185
1230
  case 'list':
@@ -0,0 +1,21 @@
1
+ import { type PreflightIssue, type PreflightManifest } from '@sequenceholdings/managed-functions/config';
2
+ /**
3
+ * Compare the manifest with the environment's published limits and features.
4
+ * A 404 means that deployment has no policy route yet; local SDK checks still run.
5
+ */
6
+ export declare function preflightBeforeUpload({ client, rootDir, manifest, cliVersion, }: {
7
+ client: {
8
+ baseUrl: string;
9
+ token: string;
10
+ };
11
+ rootDir: string;
12
+ manifest: PreflightManifest;
13
+ cliVersion: string;
14
+ }): Promise<PreflightIssue[]>;
15
+ /** Offline check for an SDK pin whose client timeout sits behind the platform. */
16
+ export declare function localSdkPreflight({ rootDir, manifest, cliVersion, }: {
17
+ rootDir: string;
18
+ manifest: PreflightManifest;
19
+ cliVersion: string;
20
+ }): Promise<PreflightIssue[]>;
21
+ export declare function reportPreflight(issues: readonly PreflightIssue[]): boolean;
@@ -0,0 +1,58 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { parseDeployedPolicy, preflightManagedFunction, sdkVersionFromPackageJson, } from '@sequenceholdings/managed-functions/config';
4
+ import { AtlasApiError, getJson } from '../atlas-client.js';
5
+ import { LOG } from '../cli-errors.js';
6
+ /**
7
+ * Compare the manifest with the environment's published limits and features.
8
+ * A 404 means that deployment has no policy route yet; local SDK checks still run.
9
+ */
10
+ export async function preflightBeforeUpload({ client, rootDir, manifest, cliVersion, }) {
11
+ let body = null;
12
+ try {
13
+ body = await getJson({ ...client, path: '/api/managed-functions/limits' });
14
+ }
15
+ catch (error) {
16
+ if (!(error instanceof AtlasApiError) || error.status !== 404)
17
+ throw error;
18
+ }
19
+ const policy = parseDeployedPolicy(body);
20
+ return preflightManagedFunction({
21
+ manifest,
22
+ limits: policy.limits,
23
+ capabilities: policy.capabilities,
24
+ cliVersion,
25
+ sdkVersion: await declaredSdkVersion(rootDir),
26
+ });
27
+ }
28
+ /** Offline check for an SDK pin whose client timeout sits behind the platform. */
29
+ export async function localSdkPreflight({ rootDir, manifest, cliVersion, }) {
30
+ return preflightManagedFunction({
31
+ manifest,
32
+ limits: null,
33
+ capabilities: null,
34
+ cliVersion,
35
+ sdkVersion: await declaredSdkVersion(rootDir),
36
+ });
37
+ }
38
+ export function reportPreflight(issues) {
39
+ if (issues.length === 0)
40
+ return false;
41
+ for (const issue of issues)
42
+ console.error(`${LOG} ${issue.message}`);
43
+ console.error(`${LOG} fix the above before deploying`);
44
+ return true;
45
+ }
46
+ async function declaredSdkVersion(rootDir) {
47
+ try {
48
+ return sdkVersionFromPackageJson(await readFile(join(rootDir, 'package.json'), 'utf8'));
49
+ }
50
+ catch (error) {
51
+ if (isMissingFile(error))
52
+ return null;
53
+ throw error;
54
+ }
55
+ }
56
+ function isMissingFile(error) {
57
+ return !!error && typeof error === 'object' && Reflect.get(error, 'code') === 'ENOENT';
58
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * CLI-side copy of atlas/.../managed-functions/egress-postgres.ts. Authors
3
+ * usually do not have the deployment pin, so this checks shape only: Lakebase
4
+ * hostname class, port 5432, and sslmode=verify-full. The server checks the
5
+ * pin at upload.
6
+ */
7
+ export declare function postgresEgressError(input: string): string | null;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * CLI-side copy of atlas/.../managed-functions/egress-postgres.ts. Authors
3
+ * usually do not have the deployment pin, so this checks shape only: Lakebase
4
+ * hostname class, port 5432, and sslmode=verify-full. The server checks the
5
+ * pin at upload.
6
+ */
7
+ const LAKEBASE_POSTGRES_HOST_RE = /^ep-[a-z0-9-]+\.database\.[a-z0-9-]+\.cloud\.databricks\.com$/;
8
+ export function postgresEgressError(input) {
9
+ let url;
10
+ try {
11
+ url = new URL(input.trim());
12
+ }
13
+ catch {
14
+ return `egress entry is not a valid PostgreSQL URL: ${input}`;
15
+ }
16
+ if (url.protocol !== 'postgres:' && url.protocol !== 'postgresql:') {
17
+ return `PostgreSQL egress URLs must use the postgres:// scheme: ${input}`;
18
+ }
19
+ if (url.username !== '' || url.password !== '') {
20
+ return `PostgreSQL egress URLs must not embed credentials: ${input}`;
21
+ }
22
+ if (url.hash !== '')
23
+ return `PostgreSQL egress URLs must not include a fragment: ${input}`;
24
+ if (url.port !== '' && url.port !== '5432') {
25
+ return `PostgreSQL egress is restricted to port 5432: ${input}`;
26
+ }
27
+ const params = [...url.searchParams.entries()];
28
+ if (params.length !== 1 || params[0]?.[0] !== 'sslmode' || params[0]?.[1] !== 'verify-full') {
29
+ return `PostgreSQL egress requires exactly sslmode=verify-full: ${input}`;
30
+ }
31
+ const host = url.hostname.toLowerCase().replace(/\.$/, '');
32
+ if (!LAKEBASE_POSTGRES_HOST_RE.test(host)) {
33
+ return `PostgreSQL egress is restricted to the approved Lakebase database destination: ${input}`;
34
+ }
35
+ return null;
36
+ }
@@ -67,6 +67,13 @@ export declare function manifestEgressIpRanges(entries: readonly string[]): stri
67
67
  */
68
68
  export declare function egressBudgetError(entries: string[]): string | null;
69
69
  export declare const managedFunctionManifestSchema: z.ZodObject<{
70
+ ontology: z.ZodOptional<z.ZodObject<{
71
+ version: z.ZodLiteral<1>;
72
+ read: z.ZodDefault<z.ZodArray<z.ZodString>>;
73
+ write: z.ZodDefault<z.ZodArray<z.ZodString>>;
74
+ produce: z.ZodDefault<z.ZodArray<z.ZodString>>;
75
+ invoke: z.ZodDefault<z.ZodArray<z.ZodString>>;
76
+ }, z.core.$strict>>;
70
77
  cache: z.ZodOptional<z.ZodObject<{
71
78
  enabled: z.ZodDefault<z.ZodBoolean>;
72
79
  tier: z.ZodDefault<z.ZodEnum<{
@@ -90,6 +97,7 @@ export declare const managedFunctionManifestSchema: z.ZodObject<{
90
97
  cpu: z.ZodDefault<z.ZodUnion<readonly [z.ZodLiteral<"auto">, z.ZodNumber]>>;
91
98
  concurrency: z.ZodDefault<z.ZodNumber>;
92
99
  timeout_seconds: z.ZodDefault<z.ZodNumber>;
100
+ max_response_bytes: z.ZodDefault<z.ZodNumber>;
93
101
  min_instances: z.ZodDefault<z.ZodNumber>;
94
102
  max_instances: z.ZodDefault<z.ZodNumber>;
95
103
  invoke_rate_per_minute: z.ZodDefault<z.ZodNumber>;
@@ -97,7 +105,10 @@ export declare const managedFunctionManifestSchema: z.ZodObject<{
97
105
  invocation: z.ZodDefault<z.ZodObject<{
98
106
  allowed_ip_ranges: z.ZodDefault<z.ZodArray<z.ZodString>>;
99
107
  }, z.core.$strip>>;
100
- secrets: z.ZodDefault<z.ZodArray<z.ZodString>>;
108
+ secrets: z.ZodDefault<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
109
+ secret: z.ZodString;
110
+ entries: z.ZodRecord<z.ZodString, z.ZodString>;
111
+ }, z.core.$strict>]>>>;
101
112
  egress: z.ZodDefault<z.ZodArray<z.ZodString>>;
102
113
  service_account: z.ZodOptional<z.ZodString>;
103
114
  authorization: z.ZodOptional<z.ZodObject<{
@@ -150,3 +161,6 @@ export declare const managedFunctionManifestSchema: z.ZodObject<{
150
161
  }, z.core.$strip>>;
151
162
  }, z.core.$strip>;
152
163
  export type ManagedFunctionManifest = z.infer<typeof managedFunctionManifestSchema>;
164
+ export declare function manifestSecretNames(value: {
165
+ secrets: ManagedFunctionManifest['secrets'];
166
+ }): string[];
@@ -1,7 +1,9 @@
1
1
  import { storageScopesSchema, readStorageScopes } from '@sequenceholdings/storage';
2
+ import { postgresEgressError } from './egress-postgres.js';
2
3
  import { cacheManifestSchema, managedFunctionWorkloadLimitsSchema } from '@sequenceholdings/managed-functions/config';
3
4
  import { isIP } from 'node:net';
4
5
  import { z } from 'zod';
6
+ import { ontologyContractSchema } from '@sequenceholdings/orm/canonical';
5
7
  /**
6
8
  * CLI-side mirror of the server manifest schema at
7
9
  * atlas/src/server/services/managed-functions/manifest.ts — same pattern
@@ -62,6 +64,10 @@ export function egressEntryError(input) {
62
64
  const raw = input.trim();
63
65
  if (!raw)
64
66
  return 'egress entry is empty';
67
+ // Before the IPv4 check: a postgres URL whose host is an address is still
68
+ // a database entry, not an IP bypass.
69
+ if (/^postgres(ql)?:/i.test(raw))
70
+ return postgresEgressError(raw);
65
71
  if (looksLikeIpv4EntryCli(raw)) {
66
72
  return egressIpError(raw);
67
73
  }
@@ -306,6 +312,8 @@ function partitionEgressEntries(entries) {
306
312
  for (const entry of entries) {
307
313
  if (egressEntryError(entry) !== null)
308
314
  continue;
315
+ if (/^postgres(ql)?:/i.test(entry.trim()))
316
+ continue;
309
317
  if (looksLikeIpv4EntryCli(entry.trim())) {
310
318
  const normalized = normalizeEgressIpCli(entry);
311
319
  if (!('error' in normalized))
@@ -478,16 +486,19 @@ const customRolesBlockSchema = z.object({
478
486
  }
479
487
  }
480
488
  });
481
- const CUSTOM_CAPABILITY_PIN_RE = /^(?:org\/)?[a-z0-9-]+$/;
489
+ // `app/<application-id>/<key>`: a capability the Application defines; live only while this is a member.
490
+ const CUSTOM_CAPABILITY_PIN_RE = /^(?:org\/|app\/[a-z][a-z0-9-]{0,63}\/)?[a-z0-9-]+$/;
482
491
  const MAX_CAPABILITY_PINS = 100;
483
492
  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-]+'))
493
+ .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
494
  .max(MAX_CAPABILITY_PINS)
486
495
  .default([]);
487
496
  function parseCapabilityPin(pin) {
488
- return pin.startsWith('org/')
489
- ? { scope: 'org', key: pin.slice('org/'.length) }
490
- : { scope: 'host', key: pin };
497
+ if (pin.startsWith('org/'))
498
+ return { scope: 'org', key: pin.slice('org/'.length) };
499
+ if (pin.startsWith('app/'))
500
+ return { scope: 'app', key: pin.split('/')[2] ?? '' };
501
+ return { scope: 'host', key: pin };
491
502
  }
492
503
  function validateCapabilityPins({ uses, roles, }) {
493
504
  const errors = [];
@@ -506,7 +517,7 @@ function validateCapabilityPins({ uses, roles, }) {
506
517
  }
507
518
  const MAX_CAPABILITY_GATES = 20;
508
519
  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-]+'),
520
+ 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
521
  when: z.object({
511
522
  field: z.string().min(1).max(128),
512
523
  equals: z.union([z.string().max(256), z.number(), z.boolean()]),
@@ -522,11 +533,11 @@ function validateCapabilityGates({ gates, uses, roles, }) {
522
533
  const declaredCapabilities = new Set(Object.keys(roles?.capabilities ?? {}));
523
534
  for (const gate of gates) {
524
535
  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);
536
+ const claimable = parsed.scope === 'host'
537
+ ? declaredCapabilities.has(parsed.key) || pinSet.has(parsed.key)
538
+ : pinSet.has(gate.requires);
528
539
  if (!claimable) {
529
- errors.push(parsed.scope === 'org'
540
+ errors.push(parsed.scope !== 'host'
530
541
  ? `Gate requires "${gate.requires}" which is not pinned in capabilities.uses`
531
542
  : `Gate requires "${gate.requires}" which is neither declared in capabilities.roles.capabilities nor pinned in capabilities.uses`);
532
543
  }
@@ -582,6 +593,7 @@ const invocationIpRangeSchema = z
582
593
  }
583
594
  });
584
595
  export const managedFunctionManifestSchema = z.object({
596
+ ontology: ontologyContractSchema.optional(),
585
597
  cache: cacheManifestSchema.optional(),
586
598
  schema_version: z.literal(1).default(1),
587
599
  function: z.object({
@@ -607,7 +619,13 @@ export const managedFunctionManifestSchema = z.object({
607
619
  })
608
620
  .default({ allowed_ip_ranges: [] }),
609
621
  secrets: z
610
- .array(z.string().regex(SECRET_NAME_RE, 'secret names must be UPPER_SNAKE_CASE'))
622
+ .array(z.union([
623
+ z.string().regex(SECRET_NAME_RE, 'secret names must be UPPER_SNAKE_CASE'),
624
+ z.object({
625
+ secret: z.string().regex(SECRET_NAME_RE, 'secret names must be UPPER_SNAKE_CASE'),
626
+ 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'),
627
+ }).strict(),
628
+ ]))
611
629
  .max(32)
612
630
  .default([]),
613
631
  /**
@@ -692,8 +710,22 @@ export const managedFunctionManifestSchema = z.object({
692
710
  .default({}),
693
711
  }).default({ uses: [], gates: [], data: {} }),
694
712
  }).superRefine((manifest, ctx) => {
713
+ const declaredNames = manifestSecretNames(manifest);
714
+ if (declaredNames.length > 32)
715
+ ctx.addIssue({
716
+ code: 'custom', path: ['secrets'], message: 'A function may declare at most 32 secret environment variables',
717
+ });
718
+ if (new Set(declaredNames).size !== declaredNames.length)
719
+ ctx.addIssue({
720
+ code: 'custom', path: ['secrets'], message: 'Secret environment variable names must be unique',
721
+ });
722
+ const sourceNames = manifest.secrets.map((entry) => typeof entry === 'string' ? entry : entry.secret);
723
+ if (new Set(sourceNames).size !== sourceNames.length)
724
+ ctx.addIssue({
725
+ code: 'custom', path: ['secrets'], message: 'A secret may appear only once in the manifest',
726
+ });
695
727
  if (manifest.cache?.enabled) {
696
- manifest.secrets.forEach((name, index) => {
728
+ declaredNames.forEach((name, index) => {
697
729
  if (name.startsWith('SEQUENCE_FUNCTION_'))
698
730
  ctx.addIssue({
699
731
  code: 'custom', path: ['secrets', index],
@@ -758,3 +790,8 @@ export const managedFunctionManifestSchema = z.object({
758
790
  });
759
791
  }
760
792
  });
793
+ export function manifestSecretNames(value) {
794
+ return value.secrets.flatMap((entry) => typeof entry === 'string'
795
+ ? [entry]
796
+ : Object.values(entry.entries));
797
+ }
@@ -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
  }
@@ -11,7 +11,10 @@ export function parseFunctionsSourceSpec(args) {
11
11
  if (dir !== undefined && (args.flags.repo !== undefined || args.flags['git-url'] !== undefined)) {
12
12
  throw new Error('--dir cannot be combined with --repo / --git-url.');
13
13
  }
14
- return parseSourceSpec({ positional: dir === undefined ? [] : [dir], flags: args.flags });
14
+ // Functions select --path themselves after materializing (parseFunctionsSourceSelection /
15
+ // resolveFunctionSourceDir); the shared parser would otherwise apply it a second time.
16
+ const { path: _functionPath, ...flags } = args.flags;
17
+ return parseSourceSpec({ positional: dir === undefined ? [] : [dir], flags });
15
18
  }
16
19
  function validateFunctionRepoPath(path) {
17
20
  const segments = path.split('/');
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