@sequenceholdings/studio-cli 0.9.20 → 0.9.22

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 (65) hide show
  1. package/README.md +159 -12
  2. package/dist/app/commands.js +37 -7
  3. package/dist/app/deploy.js +2 -0
  4. package/dist/app/lockfile-preflight.d.ts +31 -0
  5. package/dist/app/lockfile-preflight.js +47 -0
  6. package/dist/app/repository-index.d.ts +5 -1
  7. package/dist/app/repository-index.js +9 -3
  8. package/dist/app/scaffold.d.ts +3 -1
  9. package/dist/app/scaffold.js +5 -3
  10. package/dist/auth.d.ts +13 -9
  11. package/dist/auth.js +98 -20
  12. package/dist/cli-errors.js +6 -1
  13. package/dist/command-contract.d.ts +13 -1
  14. package/dist/command-contract.js +3 -1
  15. package/dist/command-help.d.ts +1 -1
  16. package/dist/command-help.js +8 -1
  17. package/dist/config.d.ts +14 -0
  18. package/dist/config.js +29 -3
  19. package/dist/docs/commands.d.ts +16 -0
  20. package/dist/docs/commands.js +168 -0
  21. package/dist/docs/help.d.ts +2 -0
  22. package/dist/docs/help.js +12 -0
  23. package/dist/envs/commands.js +10 -2
  24. package/dist/host-token.d.ts +19 -4
  25. package/dist/host-token.js +50 -10
  26. package/dist/main.d.ts +1 -0
  27. package/dist/main.js +20 -2
  28. package/dist/orm/discover-operations.d.ts +1 -1
  29. package/dist/orm/discover-operations.js +3 -3
  30. package/dist/orm/discover-schema.d.ts +0 -5
  31. package/dist/orm/discover-schema.js +0 -3
  32. package/dist/pipeline/commands.d.ts +0 -7
  33. package/dist/pipeline/commands.js +16 -67
  34. package/dist/pipeline/discovery.d.ts +1 -1
  35. package/dist/pipeline/discovery.js +6 -6
  36. package/dist/process/build.d.ts +2 -5
  37. package/dist/process/build.js +4 -49
  38. package/dist/repos/commands.d.ts +11 -1
  39. package/dist/repos/commands.js +78 -11
  40. package/dist/repos/git-credential.d.ts +12 -5
  41. package/dist/repos/git-credential.js +63 -36
  42. package/dist/repos/github-connect-command.d.ts +35 -0
  43. package/dist/repos/github-connect-command.js +250 -0
  44. package/dist/repos/github-init-command.d.ts +16 -0
  45. package/dist/repos/github-init-command.js +116 -0
  46. package/dist/repos/github-init.d.ts +146 -0
  47. package/dist/repos/github-init.js +355 -0
  48. package/dist/repos/init-github.d.ts +50 -0
  49. package/dist/repos/init-github.js +181 -0
  50. package/dist/repos/pulls.d.ts +5 -1
  51. package/dist/repos/pulls.js +31 -9
  52. package/dist/scaffold-guidance.d.ts +10 -2
  53. package/dist/scaffold-guidance.js +27 -2
  54. package/dist/templates/github/pr-type.mjs +285 -0
  55. package/dist/templates/github/pr-types.json +40 -0
  56. package/dist/templates/guidance/AGENTS.md +15 -8
  57. package/package.json +7 -7
  58. package/release-summary.json +3 -1
  59. package/templates/github/pr-type.mjs +285 -0
  60. package/templates/github/pr-types.json +40 -0
  61. package/templates/guidance/AGENTS.md +15 -8
  62. package/dist/pipeline/active-orm-contracts.d.ts +0 -16
  63. package/dist/pipeline/active-orm-contracts.js +0 -36
  64. package/dist/pipeline/repin-orm.d.ts +0 -2
  65. package/dist/pipeline/repin-orm.js +0 -207
package/dist/auth.js CHANGED
@@ -6,7 +6,7 @@ import { join } from 'node:path';
6
6
  import { validateDeploymentAudience, validateDeploymentBaseUrl, } from '@sequenceholdings/artifact-studio/deployment-validation';
7
7
  import { withCrossProcessFileLock } from './file-lock.js';
8
8
  import { isSandboxOrigin, readSandboxToken, SandboxAuthError, sandboxTarget } from './sandbox-auth.js';
9
- import { devboxHostToken } from './host-token.js';
9
+ import { DEVBOX_TOKEN_DIR_ENV, devboxHostToken, devboxTokenFile, devboxTokenHost, isLoopbackUrl } from './host-token.js';
10
10
  function hasErrorCode(error, code) {
11
11
  return error instanceof Error && Reflect.get(error, 'code') === code;
12
12
  }
@@ -407,26 +407,46 @@ export class NotLoggedInError extends Error {
407
407
  }
408
408
  }
409
409
  /**
410
- * Return a valid access token for an environment's auth realm.
411
- *
412
- * Precedence (default `SEQAPI_AUTH_MODE=auto`), matching seqapi:
413
- * 1. Valid cached user access token
414
- * 2. M2M client-credentials when the realm's secret env var is set
415
- * 3. Bounded PKCE login when browser auto-login is enabled
416
- *
417
- * Set `SEQAPI_AUTH_MODE=m2m` to skip the user token. No `env` (or a built-in
418
- * Sequence env) means the shared Sequence realm.
410
+ * A devbox that receives owner tokens has no live one for this hosted
411
+ * deployment, and no live login of the user's own stood in for it (absent or
412
+ * expired alike). Raised instead of falling back to the shared M2M service
413
+ * account, which would silently act as an admin machine identity rather than
414
+ * the box owner.
419
415
  */
416
+ export class DevboxOwnerTokenMissingError extends NotLoggedInError {
417
+ constructor({ realmName, envName, host, tokenFile, }) {
418
+ super(realmName);
419
+ const target = host ? `'${envName}' (${host})` : `'${envName}'`;
420
+ const where = tokenFile ? `${tokenFile} is missing or expired` : `$${DEVBOX_TOKEN_DIR_ENV} has no token for it`;
421
+ this.message =
422
+ `This devbox has no accepted owner token for ${target}: ${where}. ` +
423
+ 'Not falling back to the shared M2M service account.\n' +
424
+ 'For a deployment that should get an owner token, check `ls "$' + DEVBOX_TOKEN_DIR_ENV + '"` after the next refresh (about every 10 minutes). ' +
425
+ 'Set SEQAPI_AUTH_MODE=m2m only if you deliberately want the machine identity.';
426
+ }
427
+ }
420
428
  export class UnsafeAuthTargetError extends Error {
421
429
  }
422
430
  const AUTO_LOGIN_TIMEOUT_MS = 120_000;
423
431
  let autoLoginSuppressed = 0;
432
+ /**
433
+ * Browser auto-login needs someone to finish it. Without a terminal on stdin
434
+ * or stderr (an agent's tool shell, CI) it would only wait out its timeout, so
435
+ * it is skipped unless SEQAPI_AUTO_LOGIN is set to an explicit on value.
436
+ */
424
437
  function autoLoginEnabled() {
425
438
  if (autoLoginSuppressed > 0)
426
439
  return false;
427
- const value = process.env.SEQAPI_AUTO_LOGIN?.trim().toLowerCase() ?? '1';
428
- return !['0', 'false', 'no', 'off'].includes(value);
440
+ const value = process.env.SEQAPI_AUTO_LOGIN?.trim().toLowerCase();
441
+ if (value !== undefined && value !== '')
442
+ return !['0', 'false', 'no', 'off'].includes(value);
443
+ return hasInteractiveTerminal();
444
+ }
445
+ function hasInteractiveTerminal() {
446
+ return Boolean(process.stdin.isTTY || process.stderr.isTTY);
429
447
  }
448
+ const NO_TERMINAL_HINT = 'Browser sign-in was skipped because this shell has no terminal. ' +
449
+ 'Sign in from an interactive terminal, or set SEQAPI_AUTO_LOGIN=1 to open the browser login anyway.';
430
450
  /**
431
451
  * Run `fn` without opening a browser login: a missing or expired session
432
452
  * raises `NotLoggedInError` instead. For commands such as `deploy --dry-run`
@@ -450,7 +470,8 @@ function autoLoginTimeoutMs() {
450
470
  }
451
471
  async function reauthenticateOrThrow({ reason, realm, }) {
452
472
  if (!autoLoginEnabled()) {
453
- throw new NotLoggedInError(realm.name, reason);
473
+ const skippedForTerminal = autoLoginSuppressed === 0 && !process.env.SEQAPI_AUTO_LOGIN?.trim() && !hasInteractiveTerminal();
474
+ throw new NotLoggedInError(realm.name, skippedForTerminal ? `${reason} ${NO_TERMINAL_HINT}` : reason);
454
475
  }
455
476
  try {
456
477
  const { loginWithPkce } = await import('./login.js');
@@ -495,6 +516,42 @@ async function devboxAccessToken(targetUrl) {
495
516
  const token = targetUrl ? await devboxHostToken(targetUrl) : null;
496
517
  return token ? { authMode: 'user', token } : null;
497
518
  }
519
+ /**
520
+ * Whether this box receives devbox owner tokens and the request targets a
521
+ * hosted deployment (not loopback), so an implicit M2M fallback is refused.
522
+ * An explicit SEQAPI_AUTH_MODE=m2m still selects the machine identity.
523
+ */
524
+ function devboxForbidsM2mFallback(options = {}) {
525
+ if (!process.env[DEVBOX_TOKEN_DIR_ENV]?.trim() || authModePrefersM2m())
526
+ return false;
527
+ // The box's own Atlas can hold a `localhost` owner token too, but it is not
528
+ // a hosted deployment, so it keeps the M2M fallback.
529
+ if (options.targetUrl)
530
+ return !isLoopbackUrl(options.targetUrl) && devboxTokenFile(options.targetUrl) !== null;
531
+ return !(options.env && isLoopbackEnvName(options.env));
532
+ }
533
+ /** Whether a configured M2M credential would actually be selected for this target. */
534
+ function m2mSelectable(configured, options) {
535
+ return configured && !devboxForbidsM2mFallback(options);
536
+ }
537
+ function devboxOwnerTokenMissing(options, realm) {
538
+ return new DevboxOwnerTokenMissingError({
539
+ realmName: realm.name,
540
+ envName: options.env ?? realm.name,
541
+ host: options.targetUrl ? devboxTokenHost(options.targetUrl) : null,
542
+ tokenFile: options.targetUrl ? devboxTokenFile(options.targetUrl) : null,
543
+ });
544
+ }
545
+ /**
546
+ * The M2M token for `realm`, except that a devbox with no owner token for a
547
+ * hosted target never borrows the shared machine identity: it throws
548
+ * DevboxOwnerTokenMissingError instead.
549
+ */
550
+ async function m2mTokenFor(realm, target) {
551
+ if (devboxForbidsM2mFallback(target))
552
+ throw devboxOwnerTokenMissing(target, realm);
553
+ return getM2mToken(realm);
554
+ }
498
555
  /**
499
556
  * The user's own unexpired cached login for this environment, or null. Never
500
557
  * refreshes, logs in, or throws: it only decides whether a login the user
@@ -520,9 +577,9 @@ async function liveCachedUserLogin(options) {
520
577
  /**
521
578
  * A token the environment supplies rather than a login: the sandbox bearer,
522
579
  * else a devbox owner token. A live login of the user's own for the same
523
- * deployment beats the devbox token: the user made it deliberately (the
524
- * box's sign-in page), and it keeps working on a deployment that does not
525
- * accept the box's token yet. Without one, the devbox token is used as before.
580
+ * deployment beats the devbox token: the user made it deliberately, and it
581
+ * keeps working on a deployment that does not accept the box's token.
582
+ * Without one, the devbox token is used.
526
583
  */
527
584
  async function ambientAccessToken(options) {
528
585
  const sandbox = await sandboxAccessToken(options.targetUrl);
@@ -533,10 +590,24 @@ async function ambientAccessToken(options) {
533
590
  return null;
534
591
  return (await liveCachedUserLogin(options)) ?? devbox;
535
592
  }
593
+ /**
594
+ * Return a valid access token for an environment's auth realm.
595
+ *
596
+ * Precedence (default `SEQAPI_AUTH_MODE=auto`), matching seqapi:
597
+ * 0. Sandbox bearer, else a devbox owner token for the target host
598
+ * 1. Valid cached user access token
599
+ * 2. M2M client-credentials when the realm's secret env var is set, except
600
+ * on a devbox targeting a hosted deployment (DevboxOwnerTokenMissingError)
601
+ * 3. Bounded PKCE login when browser auto-login is enabled and a terminal exists
602
+ *
603
+ * Set `SEQAPI_AUTH_MODE=m2m` to skip the user token. No `env` (or a built-in
604
+ * Sequence env) means the shared Sequence realm.
605
+ */
536
606
  async function resolveAccessTokenWithMode(options) {
607
+ const target = { env: options?.env, targetUrl: options?.targetUrl };
537
608
  // Sandbox token mode replaces every other source, before any realm lookup;
538
609
  // then a devbox owner's login for the target host.
539
- const ambient = await ambientAccessToken({ env: options?.env, targetUrl: options?.targetUrl });
610
+ const ambient = await ambientAccessToken(target);
540
611
  if (ambient)
541
612
  return ambient;
542
613
  const realm = await realmForEnv(options?.env, { targetUrl: options?.targetUrl });
@@ -551,7 +622,7 @@ async function resolveAccessTokenWithMode(options) {
551
622
  return { authMode: 'user', token: tokens.access_token };
552
623
  }
553
624
  }
554
- const m2m = await getM2mToken(realm);
625
+ const m2m = await m2mTokenFor(realm, target);
555
626
  if (m2m)
556
627
  return { authMode: 'm2m', token: m2m };
557
628
  if (forceM2m) {
@@ -612,6 +683,11 @@ export async function tryGetAccessTokenWithMode(options) {
612
683
  throw err;
613
684
  if (err instanceof SandboxAuthError)
614
685
  throw err;
686
+ // A lookup that names no deployment (offline ORM codegen and validation)
687
+ // still refuses the shared M2M identity on a devbox, but runs without a
688
+ // token rather than failing, as seqapi does for env=None.
689
+ if (err instanceof DevboxOwnerTokenMissingError && !options?.env && !options?.targetUrl)
690
+ return null;
615
691
  if (options?.failClosedForM2m) {
616
692
  // Do not replace an invalid tenant registration with the Sequence realm:
617
693
  // that could hide a rejected discovery token host or inspect the wrong
@@ -643,6 +719,8 @@ export async function inspectAuthPreflight(options) {
643
719
  const realmVerified = !(options?.offline && options.env && isLoopbackEnvName(options.env));
644
720
  const cachePath = seqapiTokenPath();
645
721
  const credentialConfigured = Boolean(realm.m2mClientId && process.env[m2mSecretEnvName(realm)]?.trim());
722
+ // A devbox refuses the implicit M2M fallback for hosted targets (see resolveAccessTokenWithMode).
723
+ const m2mUsable = m2mSelectable(credentialConfigured, options);
646
724
  let file;
647
725
  try {
648
726
  file = await readTokenFile();
@@ -668,7 +746,7 @@ export async function inspectAuthPreflight(options) {
668
746
  };
669
747
  }
670
748
  if (!file) {
671
- const selectedCredential = credentialConfigured ? 'm2m' : 'none';
749
+ const selectedCredential = m2mUsable ? 'm2m' : 'none';
672
750
  return {
673
751
  authMode,
674
752
  realm: realm.name,
@@ -699,7 +777,7 @@ export async function inspectAuthPreflight(options) {
699
777
  : 'none'
700
778
  : userState === 'valid'
701
779
  ? 'user'
702
- : credentialConfigured
780
+ : m2mUsable
703
781
  ? 'm2m'
704
782
  : 'none';
705
783
  return {
@@ -1,6 +1,7 @@
1
1
  import { PlatformError } from '@sequenceholdings/platform';
2
2
  import { recordTerminalCommandError } from './command-telemetry.js';
3
3
  import { AtlasApiError } from './atlas-client.js';
4
+ import { DEVBOX_TOKEN_DIR_ENV, devboxUnauthorizedHint } from './host-token.js';
4
5
  export const LOG = '[seq-studio]';
5
6
  /** Map common apply failure reasons to clearer copy (original reason is preserved). */
6
7
  export function clarifyApplyFailureReason(reason) {
@@ -38,6 +39,9 @@ export function clarifyApplyFailureReason(reason) {
38
39
  }
39
40
  function nextStepFor503(error) {
40
41
  if (error.code === 'storage_configuration') {
42
+ if (process.env[DEVBOX_TOKEN_DIR_ENV]) {
43
+ return 'Next step: a devbox\'s local Atlas runs without blob storage, and restarting it will not add one. Exercise storage against a deployed environment (`-e staging`) or a laptop Atlas instead.';
44
+ }
41
45
  return 'Next step: this Atlas has no storage bucket configured. For a local Atlas, restart it with `make dev-all` from `atlas/` (it provisions dev storage); for a deployed environment, ask its operator to configure storage.';
42
46
  }
43
47
  return 'Next step: wait a few seconds and retry (backend may still be warming up).';
@@ -45,7 +49,8 @@ function nextStepFor503(error) {
45
49
  function nextStepForAtlasError(error) {
46
50
  const msg = error.message.toLowerCase();
47
51
  if (error.status === 401) {
48
- return 'Next step: run `seq-studio login` and retry.';
52
+ const devbox = devboxUnauthorizedHint();
53
+ return devbox ? `Next step: ${devbox}` : 'Next step: run `seq-studio login` and retry.';
49
54
  }
50
55
  if (error.status === 403) {
51
56
  return 'Next step: confirm `-e` targets the right environment and you have the required access grant.';
@@ -58,7 +58,13 @@ export declare const COMMAND_CONTRACT: readonly [{
58
58
  readonly description: "Manage repositories and native CI; ci init is offline";
59
59
  readonly lifecycle: "stable";
60
60
  readonly access: "mixed";
61
- readonly subcommands: readonly ["list", "namespaces", "show", "identity", "create", "clone", "pull", "pulls", "delete", "ci"];
61
+ readonly subcommands: readonly ["list", "namespaces", "show", "identity", "create", "clone", "attach-login", "pull", "pulls", "delete", "ci"];
62
+ }, {
63
+ readonly name: "repo";
64
+ readonly description: "Set up a GitHub repository and connect it to Atlas deploys";
65
+ readonly lifecycle: "preview";
66
+ readonly access: "mixed";
67
+ readonly subcommands: readonly ["init", "connect", "bind", "disconnect", "status"];
62
68
  }, {
63
69
  readonly name: "templates";
64
70
  readonly description: "Publish, synchronize, and list repository templates";
@@ -71,6 +77,12 @@ export declare const COMMAND_CONTRACT: readonly [{
71
77
  readonly lifecycle: "preview";
72
78
  readonly access: "staff";
73
79
  readonly subcommands: readonly ["list", "assets", "search", "describe", "schema", "sample", "query", "init", "validate", "plan", "deploy", "status", "migrate", "adopt", "unbind", "retire", "run-now", "promote", "rollback"];
80
+ }, {
81
+ readonly name: "docs";
82
+ readonly description: "Search and read the environment's developer documentation";
83
+ readonly lifecycle: "preview";
84
+ readonly access: "public";
85
+ readonly subcommands: readonly ["search", "read", "list"];
74
86
  }, {
75
87
  readonly name: "feedback";
76
88
  readonly description: "Submit agent feedback";
@@ -9,9 +9,11 @@ export const COMMAND_CONTRACT = [
9
9
  { name: 'functions', description: 'Build and operate Managed Functions', lifecycle: 'stable', access: 'authenticated', subcommands: ['init', 'build', 'deploy', 'list', 'show', 'limits', 'invoke', 'logs', 'promote', 'rollback', 'delete'] },
10
10
  { name: 'agents', description: 'Validate and deploy typed agent definitions', lifecycle: 'preview', access: 'mixed', subcommands: ['init', 'validate', 'bundle', 'plan', 'apply', 'list', 'show'] },
11
11
  { name: 'secrets', description: 'Manage organization-owned secrets', lifecycle: 'stable', access: 'authenticated', subcommands: ['create', 'set', 'list', 'attach', 'detach', 'apply'] },
12
- { name: 'repos', description: 'Manage repositories and native CI; ci init is offline', lifecycle: 'stable', access: 'mixed', subcommands: ['list', 'namespaces', 'show', 'identity', 'create', 'clone', 'pull', 'pulls', 'delete', 'ci'] },
12
+ { name: 'repos', description: 'Manage repositories and native CI; ci init is offline', lifecycle: 'stable', access: 'mixed', subcommands: ['list', 'namespaces', 'show', 'identity', 'create', 'clone', 'attach-login', 'pull', 'pulls', 'delete', 'ci'] },
13
+ { name: 'repo', description: 'Set up a GitHub repository and connect it to Atlas deploys', lifecycle: 'preview', access: 'mixed', subcommands: ['init', 'connect', 'bind', 'disconnect', 'status'] },
13
14
  { name: 'templates', description: 'Publish, synchronize, and list repository templates', lifecycle: 'internal', access: 'mixed', subcommands: ['publish', 'sync', 'list'] },
14
15
  { name: 'pipeline', description: 'Discover and operate Data Pipelines', lifecycle: 'preview', access: 'staff', subcommands: ['list', 'assets', 'search', 'describe', 'schema', 'sample', 'query', 'init', 'validate', 'plan', 'deploy', 'status', 'migrate', 'adopt', 'unbind', 'retire', 'run-now', 'promote', 'rollback'] },
16
+ { name: 'docs', description: 'Search and read the environment\'s developer documentation', lifecycle: 'preview', access: 'public', subcommands: ['search', 'read', 'list'] },
15
17
  { name: 'feedback', description: 'Submit agent feedback', lifecycle: 'preview', access: 'authenticated', subcommands: ['submit'] },
16
18
  { name: 'auth', description: 'Manage Git authentication', lifecycle: 'stable', access: 'authenticated', subcommands: ['whoami', 'git-credential', 'pat'] },
17
19
  { name: 'orm', description: 'Author and operate ORM namespaces', lifecycle: 'preview', access: 'mixed', subcommands: ['init', 'generate', 'validate', 'plan', 'apply', 'history', 'deployment-policy', 'execute', 'namespaces', 'describe', 'read', 'sql', 'diff', 'migrate-from-yaml', 'import'] },
@@ -8,7 +8,7 @@ export declare const ORM_HELP = "usage:\n seq-studio orm init <dir> [--repo <ns
8
8
  export declare const ARTIFACT_SANDBOX_HELP = " In an agent sandbox (SEQ_STUDIO_BASE_URL + SEQ_STUDIO_TOKEN_FILE), build, plan\n and deploy take --repo: push the app to a Git Service repository and deploy\n from it. Atlas builds Next.js applications; static applications are bundled\n from the repository and must declare no package.json dependencies or\n optionalDependencies, because the sandbox cannot reach a package registry.\n dev, login, logout, --git-url, --source-env, --pr and --env-url are\n unavailable there, and -e is ignored.\n";
9
9
  export declare const ARTIFACT_HELP = "usage:\n seq-studio artifact init <dir> [--template react-vite|nextjs] [--repo <namespace>/<name>]\n seq-studio artifact whoami -e <env>\n seq-studio artifact link [dir] -e <env> [--project <id>]\n seq-studio artifact env list|use <env>\n seq-studio artifact status [-e <env>]\n seq-studio artifact list -e <env> [--json]\n seq-studio artifact show <slug-or-id> -e <env> [--json]\n seq-studio artifact validate [dir]\n seq-studio artifact build|plan|deploy [dir | --repo <namespace>/<name> | --git-url <url>] [--ref <ref>] -e <env>\n seq-studio artifact dev [dir] -e <env> [--once] [--key <name>] [--link <package-dir>] [--port <port>] [--secret-source local|hosted|none] [--local-secrets <bindings.json>] [--bundler turbopack|webpack]\n seq-studio artifact pull <project-id> -e <env> --out <dir>\n seq-studio artifact promote|rollback <deployment-id> -e <env>\n\n Help is available offline. Authenticate with seq-studio login. Build and deploy\n sources may be local, a platform git-service repo, or a public HTTPS Git URL;\n deployments target a named environment with -e. Local, preview, and official\n deployment workflows have different source and approval rules; see the public\n CLI README.\n\n Init into a repo: --repo <ns>/<name> on an init command creates that platform\n git-service repo if missing (same name rules as repos create), then clones it\n into <dir> and scaffolds there, or, when <dir> is inside a Git checkout, sets\n it as that checkout's origin (a different existing origin is refused). It\n needs -e <env>, or an agent sandbox. Nothing is committed or pushed; the\n command prints the git add, commit, and push to run.\n In a git-service checkout (with or without --repo), orm init, functions init\n and artifact init also declare the scaffold under resources in\n .seq/repository.yml, so repository CI checks and deploys it. A scaffold inside\n a declared application is not declared; add it to that app with seq-studio add.\n\n In an agent sandbox (SEQ_STUDIO_BASE_URL + SEQ_STUDIO_TOKEN_FILE), build, plan\n and deploy take --repo: push the app to a Git Service repository and deploy\n from it. Atlas builds Next.js applications; static applications are bundled\n from the repository and must declare no package.json dependencies or\n optionalDependencies, because the sandbox cannot reach a package registry.\n dev, login, logout, --git-url, --source-env, --pr and --env-url are\n unavailable there, and -e is ignored.\n";
10
10
  export declare const FUNCTIONS_USAGE = "usage:\n seq-studio functions init <dir> [--repo <ns>/<name>] scaffold manifest, TypeScript handler, and docs pointers;\n --repo scaffolds into a git-service repo (see Init into a repo)\n seq-studio functions build [--dir d] local pre-flight (manifest, lockfile, SDK timeout cap)\n seq-studio functions register -e <env> [--dir d] register a shell + initial secret declarations; no deploy\n seq-studio functions deploy -e <env> [-m msg] preflight, upload, then show version and lifecycle progress\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 (input/output schemas, versions, secrets)\n [--schema] function identity plus input/output JSON Schemas, as JSON (any caller who can see it)\n [--json] [--version id|name] reader-gated release provenance\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> [--fn <slug>]\n make a version live\n seq-studio functions rollback [<version>] -e <env> [--fn <slug>]\n redeploy a prior version\n seq-studio functions delete -e <env> [--fn <slug>] [--yes]\n 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 --fn selects a deployed function without a local manifest; otherwise the manifest in --dir (default .) supplies its slug\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 Local deploys record repository-wide gitDirty, including unignored files\n outside --dir. Check git status at the repository root before deploying.\n\n Workspace dependencies are compiled from packages declared in a containing\n sequence.app.yml, within the source repository. Only the selected function is\n deployed: no sibling primitives or Application registration. Shared Node packages\n can set package.json seqStudio.source to a root source entry for clean builds.\n Package build scripts are not run. Local secret paths remain relative to --dir.\n\n Interactive --repo builds clone over smart-HTTP using your seq-studio login\n and repository read access. No PAT is needed. Headless M2M builds use JSON\n materialize and accept only platform-managed --repo sources. Use --env to\n select the same environment for source and deployment.\n\n Init into a repo: --repo <ns>/<name> on an init command creates that platform\n git-service repo if missing (same name rules as repos create), then clones it\n into <dir> and scaffolds there, or, when <dir> is inside a Git checkout, sets\n it as that checkout's origin (a different existing origin is refused). It\n needs -e <env>, or an agent sandbox. Nothing is committed or pushed; the\n command prints the git add, commit, and push to run.\n In a git-service checkout (with or without --repo), orm init, functions init\n and artifact init also declare the scaffold under resources in\n .seq/repository.yml, so repository CI checks and deploys it. A scaffold inside\n a declared application is not declared; add it to that app with seq-studio add.\n";
11
- export declare const REPOS_USAGE = "usage:\n seq-studio repos list -e <env> [--namespace <slug>] [--mine] repos visible on the environment\n seq-studio repos namespaces [create <slug>] -e <env> list or create namespaces\n seq-studio repos show <ns>/<name> -e <env> repo detail (branches, clone URL)\n seq-studio repos identity <ns>/<name> -e <env> [--write --dir .] show/install the server-issued identity receipt\n --adopt --write --yes admin-only legacy binding; commit the receipt via PR\n seq-studio repos create <ns>/<name> -e <env> [--default-branch b] [--git-backend walgit]\n create a repo seeded with a README; --git-backend\n walgit creates it empty (for pushing existing\n history); needs namespace write. Returns once\n the repo resolves by name, so clone can follow\n at once. The init commands take --repo\n <ns>/<name> to create, clone, and scaffold\n seq-studio repos clone <ns>/<name> -e <env> [--ref r] [--output dir] [--force] [--full] [--transport auto|git|json]\n seq-studio repos clone --url <https://\u2026/repos/<id>/git> -e <env> [--ref r] [--output dir] [--full]\n seq-studio repos clone --id <uuid> -e <env> [--ref r] [--output dir] [--full]\n real Git clone using seq-studio login;\n configures login for subsequent git pull/push\n seq-studio repos pull <ns>/<name> -e <env> [--ref r] [--out dir] [--force]\n materialize the tree at a ref (JSON API)\n seq-studio repos pulls <list|show|create|diff|merge|edit|close|comment|comments|resolve|unresolve|review|reviews|checks> [args]\n review requests (see pulls --help)\n seq-studio repos delete <ns>/<name> -e <env> [--yes] delete a repo (confirm prompt)\n seq-studio repos ci init [--dir <repository>] create a native pipeline using platform defaults\n seq-studio repos ci show <ns>/<name> -e <env> --pr <number> [--json] inspect the server CI plan and runs\n seq-studio repos ci show <ns>/<name> -e <env> [--ref r] preview pipeline discovery or legacy checks\n seq-studio repos ci require <ns>/<name> --check <name> -e <env> disabled legacy control\n seq-studio repos ci import <ns>/<name> -e <env> [--ref r] disabled legacy control\n\n Flags: -e/--env <env> (required; see: seq-studio envs list)\n\n clone uses your login token (never written into the remote URL or Git config).\n A repository-local credential helper reads your current login for git pull/push.\n After expiry, run seq-studio login --env <env> again.\n --transport auto (default) and git both create a real Git checkout.\n Personal access tokens are retired; ATLAS_GIT_PAT is ignored.\n --transport json downloads files without .git; requires\n <ns>/<name>. repos pull also provides this files-only workflow.\n --ref accepts a branch, tag, or commit SHA (SHA \u2192 full clone, then checkout).\n Branch and tag clones are shallow (--depth 1). Pass --full for history.\n --output selects the clone directory (--out remains an alias).\n\n Authenticate JSON API calls with: seq-studio login\n Authenticate git clone/push with: seq-studio login --env <env>\n";
11
+ export declare const REPOS_USAGE = "usage:\n seq-studio repos list -e <env> [--namespace <slug>] [--mine] repos visible on the environment\n seq-studio repos namespaces [create <slug>] -e <env> list or create namespaces\n seq-studio repos show <ns>/<name> -e <env> repo detail (branches, clone URL)\n seq-studio repos identity <ns>/<name> -e <env> [--write --dir .] show/install the server-issued identity receipt\n --adopt --write --yes admin-only legacy binding; commit the receipt via PR\n seq-studio repos create <ns>/<name> -e <env> [--default-branch b] [--git-backend walgit]\n create a repo seeded with a README; --git-backend\n walgit creates it empty (for pushing existing\n history); needs namespace write. Returns once\n the repo resolves by name, so clone can follow\n at once. The init commands take --repo\n <ns>/<name> to create, clone, and scaffold\n seq-studio repos clone <ns>/<name> -e <env> [--ref r] [--output dir] [--force] [--full] [--transport auto|git|json]\n seq-studio repos clone --url <https://\u2026/repos/<id>/git> -e <env> [--ref r] [--output dir] [--full]\n seq-studio repos clone --id <uuid> -e <env> [--ref r] [--output dir] [--full]\n real Git clone using seq-studio login;\n configures login for subsequent git pull/push;\n a failed clone leaves no partial checkout\n seq-studio repos attach-login [dir] -e <env> [--remote origin] bind the login credential helper to an\n existing checkout (plain git clone, or\n after an upgrade moved seq-studio)\n seq-studio repos pull <ns>/<name> -e <env> [--ref r] [--out dir] [--force]\n materialize the tree at a ref (JSON API)\n seq-studio repos pulls <list|show|create|diff|merge|edit|close|comment|comments|resolve|unresolve|review|reviews|checks> [args]\n review requests (see pulls --help)\n seq-studio repos delete <ns>/<name> -e <env> [--yes] delete a repo (confirm prompt)\n seq-studio repos ci init [--dir <repository>] create a native pipeline using platform defaults\n seq-studio repos ci show <ns>/<name> -e <env> --pr <number> [--json] inspect the server CI plan and runs\n seq-studio repos ci show <ns>/<name> -e <env> [--ref r] preview pipeline discovery or legacy checks\n seq-studio repos ci require <ns>/<name> --check <name> -e <env> disabled legacy control\n seq-studio repos ci import <ns>/<name> -e <env> [--ref r] disabled legacy control\n\n Flags: -e/--env <env> (required; see: seq-studio envs list)\n\n clone uses your login token (never written into the remote URL or Git config).\n A repository-local credential helper reads your current login for git pull/push.\n After expiry, run seq-studio login --env <env> again.\n --transport auto (default) and git both create a real Git checkout.\n Personal access tokens are retired; ATLAS_GIT_PAT is ignored.\n --transport json downloads files without .git; requires\n <ns>/<name>. repos pull also provides this files-only workflow.\n --ref accepts a branch, tag, or commit SHA (SHA \u2192 full clone, then checkout).\n Branch and tag clones are shallow (--depth 1). Pass --full for history.\n --output selects the clone directory (--out remains an alias).\n\n Authenticate JSON API calls with: seq-studio login\n Authenticate git clone/push with: seq-studio login --env <env>\n";
12
12
  export declare const PROCESS_RUNS_USAGE = "usage:\n seq-studio process runs start <process-id> -e <env> [--version <v>] [--run-id <id>]\n [--metadata-file <file.json>] [--title <text>] [--entity <type>:<id>] [--json]\n seq-studio process runs retry <run-id> -e <env> [--run-id <new-id>] [--json]\n seq-studio process runs list -e <env> [--process <id>] [--status <status>]\n [--entity-type <type>] [--entity-id <id>] [--archived] [--limit 1..500] [--json]\n seq-studio process runs show <run-id> -e <env> [--wait [--timeout <seconds>]]\n [--steps [--node <node-id>] [--full]] [--json]\n seq-studio process runs cancel <run-id> -e <env> [--json]\n\n Runs start and are read as you: start and retry need invoker on the process,\n show and list return only runs you can view, and cancel needs invoker on the\n process.\n start prints the new run's id. Omit --run-id for a fresh id on every start.\n --run-id names exactly one run: repeating it for the same process returns that\n run, whatever its status, instead of starting another. To run a failed run\n again, retry it rather than inventing a new id.\n --version pins a published process version; omitted, the active version runs.\n --metadata-file is a JSON object stored on the run.\n retry (CLI 0.9.0+) starts a new run of a failed, cancelled or timed_out run's\n process version with the same metadata, entity and title, linked to the\n original in its lineage, and prints the new id. Other statuses are refused.\n Like start, a retry waits queued while the process is at its concurrent-run\n limit.\n --run-id on retry names the new run, so repeating the retry returns it.\n list returns the newest runs first, up to --limit (default 50, max 500); the run\n API has no cursor, so narrow with filters to reach older runs.\n --status: pending, running, completed, failed, cancelled, timed_out.\n show --wait polls until the run finishes (default timeout 600s); the run keeps\n going if the wait times out. show prints the run's error when it failed.\n show --steps (CLI 0.9.1+) prints each step's status, edge, error, input and\n output, with the same viewer permission as show. Inputs, outputs and errors\n over 2000 characters are cut to a preview; --full prints them whole.\n --node narrows to one node. With --json, --steps returns { run, steps } with\n the same bounds; each step's truncated map names its cut fields and their full\n length. A failure in a node's input mapper happens before its step\n starts, so it shows only as the run's error.\n";
13
13
  export declare const ORM_DISCOVER_HELP = "usage:\n seq-studio orm namespaces -e <env> [--limit N] [--offset N] [--json]\n seq-studio orm describe <namespace> [<table> | --operations] -e <env> [--json]\n seq-studio orm operation show <namespace> <name> -e <env> [--json]\n\n Find the ORM data you can read, then query it with orm read or orm sql.\n namespaces lists only namespaces you can read, ordered by name: format (v2 or\n v1), table and persisted-operation counts. It pages with --limit (default 50)\n and --offset; the total and the next page go to stderr.\n describe <namespace> lists its tables and views and the persisted operations\n it serves, with what each requires and the variables it declares (name: type,\n ! when required). --operations prints only the operations, ready for\n orm execute <namespace> <operation>. describe <namespace> <table> lists the\n table's columns (types, nullability, keys), enum values, links, actions, and\n the persisted operations that write it. Column names are the ones orm read and\n orm sql accept.\n A namespace you cannot read reports not found, the same as a missing one.\n --json omits SDL, adds active set/schema IDs and ops hash; retry on a mismatch.\n operation show prints one active persisted operation's registered GraphQL\n document; --json includes its hash, declared variables, and requirements.\n Missing and unreadable operations both report not found.\n In an agent sandbox (SEQ_STUDIO_BASE_URL + SEQ_STUDIO_TOKEN_FILE), -e is not needed.\n";
14
14
  export declare const ORM_EXECUTE_HELP = "usage:\n seq-studio orm execute <namespace> <operation> -e <env> [--variables-file <file>] [--var <name>=<value>]...\n seq-studio orm execute <operation> [dir] --variables-file <file> -e <env>\n\n Run one persisted operation as you. The server applies the operation's\n required capability or role and the namespace's row policies.\n By name: execute <namespace> <operation> looks the operation up in the\n namespace's deployed version and runs it. No checkout is needed, so it runs\n what is deployed even when a local clone is behind. List what you can run:\n seq-studio orm describe <namespace> --operations\n From a checkout: execute <operation> [dir] delegates to the installed ORM\n package using the directory's operations.manifest.json (default dir: .).\n Updated ORM packages validate the name and kind, then call the active named\n operation. Older packages may still select the manifest hash. Confirm the\n installed package and platform support name selection before upgrading.\n The form is chosen by the second argument: an existing directory means a\n checkout; otherwise it is <namespace> <operation>.\n --variables-file takes a JSON object; - or /dev/stdin reads UTF-8 stdin until EOF\n (the checkout form requires an ORM package with stdin support).\n --var <name>=<value> (repeatable, by\n name only) sets one variable and wins over the file: numbers and booleans\n parse by the declared type, lists, filter inputs and jsonb take JSON, and other\n types take the text as is. Use the file for null.\n Output is the JSON response: {\"data\": ...}.\n In an agent sandbox (SEQ_STUDIO_BASE_URL + SEQ_STUDIO_TOKEN_FILE), -e is not needed.\n";
@@ -1,4 +1,5 @@
1
1
  /** Help text reachable before command implementations, auth, optional SDKs, or Atlas clients load. */
2
+ import { DOCS_HELP } from './docs/help.js';
2
3
  import { PIPELINE_HELP } from './pipeline/help.js';
3
4
  export { PIPELINE_HELP } from './pipeline/help.js';
4
5
  /** `--repo` on every init command; shared so the commands describe it identically. */
@@ -196,7 +197,11 @@ export const REPOS_USAGE = `usage:
196
197
  seq-studio repos clone --url <https://…/repos/<id>/git> -e <env> [--ref r] [--output dir] [--full]
197
198
  seq-studio repos clone --id <uuid> -e <env> [--ref r] [--output dir] [--full]
198
199
  real Git clone using seq-studio login;
199
- configures login for subsequent git pull/push
200
+ configures login for subsequent git pull/push;
201
+ a failed clone leaves no partial checkout
202
+ seq-studio repos attach-login [dir] -e <env> [--remote origin] bind the login credential helper to an
203
+ existing checkout (plain git clone, or
204
+ after an upgrade moved seq-studio)
200
205
  seq-studio repos pull <ns>/<name> -e <env> [--ref r] [--out dir] [--force]
201
206
  materialize the tree at a ref (JSON API)
202
207
  seq-studio repos pulls <list|show|create|diff|merge|edit|close|comment|comments|resolve|unresolve|review|reviews|checks> [args]
@@ -334,6 +339,8 @@ export function staticHelp({ namespace, sub }) {
334
339
  return FUNCTIONS_USAGE;
335
340
  if (namespace === 'repos' && sub !== 'pulls' && sub !== 'ci')
336
341
  return REPOS_USAGE;
342
+ if (namespace === 'docs')
343
+ return DOCS_HELP;
337
344
  if (namespace === 'doctor') {
338
345
  return `usage: seq-studio doctor [-e <env>] [--json] [--offline]\n\nDiagnose config, auth, local service availability, CLI/SDK resolution, and deployment access. --offline reads local metadata without discovery or HTTP requests. Help is available offline.\n`;
339
346
  }
package/dist/config.d.ts CHANGED
@@ -71,6 +71,20 @@ export declare function addSharedLoginEnvironment({ name, baseUrl: rawBaseUrl, f
71
71
  baseUrl: string;
72
72
  changed: boolean;
73
73
  }>;
74
+ /**
75
+ * Save `local:<name>` for an Atlas on a loopback port that is not a
76
+ * discovered worktree, such as a devbox's Atlas forwarded to this machine.
77
+ * Auth needs no registration: like every local target, it is discovered from
78
+ * the running Atlas when the environment is used.
79
+ */
80
+ export declare function addLocalEnvironment({ name, baseUrl: rawBaseUrl, }: {
81
+ name: string;
82
+ baseUrl: string;
83
+ }): Promise<{
84
+ name: string;
85
+ baseUrl: string;
86
+ changed: boolean;
87
+ }>;
74
88
  /** Resolve `--env <name>` against the config on disk. */
75
89
  export declare function resolveConfiguredEnv({ requested, }: {
76
90
  requested?: string;
package/dist/config.js CHANGED
@@ -158,7 +158,7 @@ export async function writeConfig(config) {
158
158
  // (which only reads top-level `default_env`) would ignore it.
159
159
  const lines = [`default_env = "${config.defaultEnv}"`, ''];
160
160
  for (const [name, value] of Object.entries(config.envs)) {
161
- lines.push(`[env.${name}]`);
161
+ lines.push(`[env.${tomlKey(name)}]`);
162
162
  lines.push(`url = ${stringifyToml({ url: value.url }).trim().replace(/^url = /, '')}`);
163
163
  lines.push('');
164
164
  }
@@ -227,17 +227,43 @@ export async function addSharedLoginEnvironment({ name, baseUrl: rawBaseUrl, fet
227
227
  throw new Error(`'${name}' is reserved for a deployment on the shared Sequence login, and ${baseUrl} uses its own ` +
228
228
  `login. Register it under another name: seq-studio envs add <name> ${baseUrl}`);
229
229
  }
230
+ return appendEnvTable({ name, baseUrl });
231
+ }
232
+ /**
233
+ * Save `local:<name>` for an Atlas on a loopback port that is not a
234
+ * discovered worktree, such as a devbox's Atlas forwarded to this machine.
235
+ * Auth needs no registration: like every local target, it is discovered from
236
+ * the running Atlas when the environment is used.
237
+ */
238
+ export async function addLocalEnvironment({ name, baseUrl: rawBaseUrl, }) {
239
+ const alias = name.slice(WORKTREE_ENV_PREFIX.length);
240
+ if (!name.startsWith(WORKTREE_ENV_PREFIX) || !WORKTREE_NAME_PATTERN.test(alias)) {
241
+ throw new Error(`Invalid local environment name '${name}': use local:<name> with lowercase letters, digits, '.', '_' and '-'.`);
242
+ }
243
+ const baseUrl = validateDeploymentBaseUrl(rawBaseUrl).replace(/\/$/, '');
244
+ if (!LOOPBACK_HOSTS.has(new URL(baseUrl).hostname)) {
245
+ throw new Error(`'${name}' must point at a loopback address (localhost, 127.0.0.1 or [::1]), not ${baseUrl}. Forward the remote Atlas to a local port first.`);
246
+ }
247
+ return appendEnvTable({ name, baseUrl });
248
+ }
249
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
250
+ /** A TOML key for an environment name: bare when it can be, quoted otherwise (`local:x`). */
251
+ function tomlKey(name) {
252
+ return /^[A-Za-z0-9_-]+$/.test(name) ? name : JSON.stringify(name);
253
+ }
254
+ /** Append `[env.<name>]` to config.toml unless it already holds that URL; never overwrites another. */
255
+ async function appendEnvTable({ name, baseUrl }) {
230
256
  const path = configPath();
231
257
  const existing = existsSync(path) ? await readFile(path, 'utf8') : '';
232
258
  const current = parseToml(existing).env?.[name]?.url;
233
259
  if (current === baseUrl)
234
260
  return { name, baseUrl, changed: false };
235
261
  if (current !== undefined) {
236
- throw new Error(`[env.${name}] in ${path} already points at ${current}; edit it there to change it.`);
262
+ throw new Error(`[env.${tomlKey(name)}] in ${path} already points at ${current}; edit it there to change it.`);
237
263
  }
238
264
  await mkdir(dirname(path), { recursive: true });
239
265
  const separator = existing === '' || existing.endsWith('\n\n') ? '' : existing.endsWith('\n') ? '\n' : '\n\n';
240
- const table = `[env.${name}]\nurl = ${stringifyToml({ url: baseUrl }).trim().replace(/^url = /, '')}\n`;
266
+ const table = `[env.${tomlKey(name)}]\nurl = ${stringifyToml({ url: baseUrl }).trim().replace(/^url = /, '')}\n`;
241
267
  await writeFile(path, existing + separator + table, { encoding: 'utf8', mode: 0o600 });
242
268
  return { name, baseUrl, changed: true };
243
269
  }
@@ -0,0 +1,16 @@
1
+ import { type ParsedArgs } from '../argv.js';
2
+ type DocsRequest = (path: string) => Promise<unknown>;
3
+ interface DocsClient {
4
+ request: DocsRequest;
5
+ origin?: string;
6
+ }
7
+ /**
8
+ * Edge credentials are scoped to the origin `edgeAuthHeaders` checked, so redirects are refused rather than followed:
9
+ * a followed redirect would forward those headers to another host. Same policy as the platform transport.
10
+ */
11
+ export declare function anonymousDocsRequest({ origin, fetchImpl }: {
12
+ origin: string;
13
+ fetchImpl?: typeof fetch;
14
+ }): DocsRequest;
15
+ export declare function runDocsCommand(sub: string | undefined, args: ParsedArgs, client?: DocsClient): Promise<number>;
16
+ export {};
@@ -0,0 +1,168 @@
1
+ /**
2
+ * `seq-studio docs`: read the target environment's published developer docs from the terminal, so an agent in any
3
+ * checkout (cloned, created or scaffolded) reaches the docs that match the deployment it builds against, through the
4
+ * same origin, edge credentials and login the rest of the CLI uses. The docs routes are anonymous on Atlas; the
5
+ * login is only sent when one is already available, because some origins sit behind an edge or sandbox proxy.
6
+ */
7
+ import { z } from 'zod';
8
+ import { AtlasApiError, getJson } from '../atlas-client.js';
9
+ import { fetchWithCliAttribution } from '../cli-attribution.js';
10
+ import { resolveConfiguredEnv } from '../config.js';
11
+ import { edgeAuthHeaders } from '../edge-auth-headers.js';
12
+ import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
13
+ import { requestedEnvironment } from '../functions/commands.js';
14
+ import { DOCS_HELP } from './help.js';
15
+ const SUBCOMMANDS = new Set(['search', 'read', 'list']);
16
+ const ALLOWED_FLAGS = new Set(['env', 'e', 'json', 'limit']);
17
+ const searchResponseSchema = z.object({
18
+ query: z.string(),
19
+ version: z.string(),
20
+ total: z.number(),
21
+ results: z.array(z.object({
22
+ slug: z.string(), title: z.string(), sectionTitle: z.string().optional(), url: z.string(), excerpt: z.string(),
23
+ }).loose()),
24
+ });
25
+ const pageResponseSchema = z.object({ slug: z.string(), title: z.string(), url: z.string(), version: z.string(), markdown: z.string() }).loose();
26
+ const listResponseSchema = z.object({
27
+ version: z.string(),
28
+ pages: z.array(z.object({ slug: z.string(), title: z.string(), description: z.string(), group: z.string() }).loose()),
29
+ }).loose();
30
+ class DocsUsageError extends Error {
31
+ }
32
+ /** Send the login when one is cached or injected; never start a browser login just to read public docs. */
33
+ async function docsRequester(env) {
34
+ const { getAccessTokenWithMode } = await import('../auth.js');
35
+ const token = await getAccessTokenWithMode({ env: env.name, targetUrl: env.url, allowInteractiveLogin: false })
36
+ .then(({ token }) => token).catch(() => null);
37
+ if (token)
38
+ return (path) => getJson({ baseUrl: env.url, token, path });
39
+ return anonymousDocsRequest({ origin: env.url });
40
+ }
41
+ /**
42
+ * Edge credentials are scoped to the origin `edgeAuthHeaders` checked, so redirects are refused rather than followed:
43
+ * a followed redirect would forward those headers to another host. Same policy as the platform transport.
44
+ */
45
+ export function anonymousDocsRequest({ origin, fetchImpl = fetchWithCliAttribution }) {
46
+ return async (path) => {
47
+ const response = await fetchImpl(new URL(path, origin), {
48
+ headers: { accept: 'application/json', ...edgeAuthHeaders(origin) },
49
+ redirect: 'error',
50
+ signal: AbortSignal.timeout(30_000),
51
+ });
52
+ if (!response.ok)
53
+ throw new AtlasApiError(response.status, `HTTP ${response.status} ${response.statusText}`.trim(), path);
54
+ return response.json();
55
+ };
56
+ }
57
+ function parseLimit(value) {
58
+ if (value === undefined)
59
+ return undefined;
60
+ const limit = typeof value === 'string' ? Number(value) : Number.NaN;
61
+ if (!Number.isInteger(limit) || limit < 1 || limit > 20)
62
+ throw new DocsUsageError('--limit must be an integer from 1 to 20');
63
+ return limit;
64
+ }
65
+ /** The docs API returns origin-relative links; agents need ones they can cite and open. */
66
+ function absolute({ url, origin }) {
67
+ return origin ? new URL(url, origin).href : url;
68
+ }
69
+ function renderSearch(response) {
70
+ if (response.results.length === 0)
71
+ return `No documentation matched "${response.query}". Try other words, or run seq-studio docs list.`;
72
+ const lines = response.results.map((result, index) => [
73
+ `${index + 1}. ${result.title}${result.sectionTitle && result.sectionTitle !== result.title ? ` › ${result.sectionTitle}` : ''}`,
74
+ ` slug: ${result.slug} ${result.url}`,
75
+ ` ${result.excerpt}`,
76
+ ].join('\n'));
77
+ return `${lines.join('\n\n')}\n\nRead a page in full with: seq-studio docs read <slug> -e <env>`;
78
+ }
79
+ function renderList(response) {
80
+ const lines = [];
81
+ let group = null;
82
+ for (const page of response.pages) {
83
+ if (page.group !== group) {
84
+ group = page.group;
85
+ lines.push(`${lines.length ? '\n' : ''}${group}`);
86
+ }
87
+ lines.push(` ${page.slug} — ${page.title}: ${page.description}`);
88
+ }
89
+ return lines.join('\n');
90
+ }
91
+ export async function runDocsCommand(sub, args, client) {
92
+ if (!sub || sub === 'help' || args.flags.help === true) {
93
+ console.log(DOCS_HELP);
94
+ return sub ? 0 : 1;
95
+ }
96
+ try {
97
+ const unknownFlag = Object.keys(args.flags).find((flag) => !ALLOWED_FLAGS.has(flag));
98
+ if (!SUBCOMMANDS.has(sub) || unknownFlag)
99
+ throw new DocsUsageError(unknownFlag ? `unknown flag --${unknownFlag}` : `unknown docs command: ${sub}`);
100
+ const json = args.flags.json === true;
101
+ const path = docsPath({ sub, args });
102
+ const { request, origin } = client ?? await (async () => {
103
+ const requested = requestedEnvironment(args);
104
+ if (!requested)
105
+ throw new DocsUsageError(REQUIRE_EXPLICIT_ENV_MESSAGE);
106
+ const env = await resolveConfiguredEnv({ requested });
107
+ return { request: await docsRequester(env), origin: env.url };
108
+ })();
109
+ const body = await request(path);
110
+ if (sub === 'search') {
111
+ const parsed = searchResponseSchema.parse(body);
112
+ const response = { ...parsed, results: parsed.results.map((result) => ({ ...result, url: absolute({ url: result.url, origin }) })) };
113
+ console.log(json ? JSON.stringify(response) : renderSearch(response));
114
+ }
115
+ else if (sub === 'read') {
116
+ const parsed = pageResponseSchema.parse(body);
117
+ const page = { ...parsed, url: absolute({ url: parsed.url, origin }) };
118
+ console.log(json ? JSON.stringify(page) : `<!-- Source: ${page.url} (docs version ${page.version}) -->\n\n${page.markdown}`);
119
+ }
120
+ else {
121
+ const response = listResponseSchema.parse(body);
122
+ console.log(json ? JSON.stringify(response) : renderList(response));
123
+ }
124
+ return 0;
125
+ }
126
+ catch (error) {
127
+ console.error(docsErrorMessage({ error, sub }));
128
+ if (error instanceof DocsUsageError)
129
+ console.error(DOCS_HELP);
130
+ return 1;
131
+ }
132
+ }
133
+ function docsPath({ sub, args }) {
134
+ if (sub === 'list') {
135
+ if (args.positional.length)
136
+ throw new DocsUsageError('docs list takes no arguments');
137
+ return '/api/developer-docs';
138
+ }
139
+ if (sub === 'read') {
140
+ const slug = args.positional.join('/').trim().replace(/^\/+|\/+$/g, '').replace(/\.md$/, '');
141
+ if (!slug || args.positional.length !== 1)
142
+ throw new DocsUsageError('docs read takes exactly one slug, for example: seq-studio docs read getting-started -e <env>');
143
+ return `/api/developer-docs/pages/${slug.split('/').map(encodeURIComponent).join('/')}`;
144
+ }
145
+ const query = args.positional.join(' ').trim();
146
+ if (!query)
147
+ throw new DocsUsageError('docs search needs a query, for example: seq-studio docs search "deploy a function" -e <env>');
148
+ if (query.length > 200)
149
+ throw new DocsUsageError('docs search queries are limited to 200 characters');
150
+ const params = new URLSearchParams({ q: query });
151
+ const limit = parseLimit(args.flags.limit);
152
+ if (limit !== undefined)
153
+ params.set('limit', String(limit));
154
+ return `/api/developer-docs/search?${params}`;
155
+ }
156
+ function docsErrorMessage({ error, sub }) {
157
+ if (error instanceof DocsUsageError)
158
+ return error.message;
159
+ if (error instanceof AtlasApiError && error.status === 404) {
160
+ return sub === 'read'
161
+ ? 'Documentation page not found. Find a published slug with seq-studio docs search <query> or seq-studio docs list.'
162
+ : 'This environment does not serve developer docs yet. Try another environment from seq-studio envs list.';
163
+ }
164
+ if (error instanceof z.ZodError)
165
+ return 'The environment returned an unexpected docs response. It may run an older platform version; try another environment.';
166
+ const detail = error instanceof Error ? error.message : String(error);
167
+ return `Could not read the docs: ${detail}. Check the environment URL with seq-studio envs list, or open <url>/docs in a signed-in browser.`;
168
+ }
@@ -0,0 +1,2 @@
1
+ /** Kept free of network imports so offline `--help` stays cheap. */
2
+ export declare const DOCS_HELP = "usage:\n seq-studio docs search <query> -e <env> [--limit N] [--json]\n seq-studio docs read <slug> -e <env> [--json]\n seq-studio docs list -e <env> [--json]\n\nRead the Sequence developer documentation published by an environment. The docs\nmatch the platform version that environment runs, so prefer them over memory or\ncopied snippets. Search first, then read the matching page in full before\nrunning unfamiliar commands. Use `index` as the slug for the homepage.\n`seq-studio envs list` prints the available environments.\n";