@sequenceholdings/studio-cli 0.7.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +351 -49
  2. package/dist/access/commands.d.ts +1 -1
  3. package/dist/access/commands.js +102 -55
  4. package/dist/access/custom-role-hosts.d.ts +3 -0
  5. package/dist/access/custom-role-hosts.js +88 -0
  6. package/dist/access/group-rosters.d.ts +6 -0
  7. package/dist/access/group-rosters.js +33 -0
  8. package/dist/access/host-contract.d.ts +55 -0
  9. package/dist/access/host-contract.js +33 -0
  10. package/dist/access/hosts.d.ts +4 -0
  11. package/dist/access/hosts.js +60 -0
  12. package/dist/access/principal.d.ts +16 -0
  13. package/dist/access/principal.js +36 -0
  14. package/dist/access/roles.d.ts +18 -0
  15. package/dist/access/roles.js +89 -0
  16. package/dist/access/tier-hosts.d.ts +12 -0
  17. package/dist/access/tier-hosts.js +206 -0
  18. package/dist/agents/commands.d.ts +1 -1
  19. package/dist/agents/commands.js +76 -16
  20. package/dist/agents/scaffold.js +8 -3
  21. package/dist/app/commands.js +37 -12
  22. package/dist/app/manifest.d.ts +2 -2
  23. package/dist/app/official-source.d.ts +4 -2
  24. package/dist/app/official-source.js +6 -4
  25. package/dist/app/readme.js +2 -2
  26. package/dist/app/workspace-model.js +4 -0
  27. package/dist/app/workspace-scaffold.js +5 -3
  28. package/dist/app/workspace.d.ts +2 -0
  29. package/dist/app/workspace.js +1 -1
  30. package/dist/artifact/delegate.js +26 -3
  31. package/dist/artifact/sandbox.js +2 -1
  32. package/dist/atlas-client.d.ts +15 -8
  33. package/dist/atlas-client.js +140 -64
  34. package/dist/bin.js +9 -1
  35. package/dist/cli-errors.js +4 -0
  36. package/dist/command-contract.d.ts +8 -2
  37. package/dist/command-contract.js +3 -2
  38. package/dist/command-help.d.ts +8 -6
  39. package/dist/command-help.js +50 -12
  40. package/dist/env-flags.d.ts +7 -0
  41. package/dist/env-flags.js +23 -0
  42. package/dist/functions/commands.js +66 -11
  43. package/dist/functions/manifest.d.ts +5 -0
  44. package/dist/functions/manifest.js +44 -23
  45. package/dist/functions/service-account-guidance.d.ts +21 -0
  46. package/dist/functions/service-account-guidance.js +62 -0
  47. package/dist/functions/workspace.d.ts +11 -0
  48. package/dist/functions/workspace.js +52 -0
  49. package/dist/main.d.ts +2 -1
  50. package/dist/main.js +12 -3
  51. package/dist/orm/delegate.js +49 -6
  52. package/dist/orm/execute.js +11 -5
  53. package/dist/orm/failures.d.ts +32 -0
  54. package/dist/orm/failures.js +75 -0
  55. package/dist/orm/read.js +3 -3
  56. package/dist/orm/version-guard.d.ts +3 -0
  57. package/dist/orm/version-guard.js +63 -0
  58. package/dist/pipeline/commands.js +4 -1
  59. package/dist/principals/commands.d.ts +3 -0
  60. package/dist/principals/commands.js +124 -0
  61. package/dist/process/runs.d.ts +4 -3
  62. package/dist/process/runs.js +52 -10
  63. package/dist/release-age.d.ts +1 -1
  64. package/dist/release-age.js +1 -0
  65. package/dist/repos/commands.d.ts +44 -0
  66. package/dist/repos/commands.js +55 -15
  67. package/dist/repos/init-repo.d.ts +45 -0
  68. package/dist/repos/init-repo.js +257 -0
  69. package/dist/sandbox-unpushed-warning.d.ts +23 -0
  70. package/dist/sandbox-unpushed-warning.js +86 -0
  71. package/dist/service-accounts/commands.js +15 -3
  72. package/dist/templates/commands.d.ts +14 -2
  73. package/dist/templates/commands.js +70 -16
  74. package/dist/templates/process/pnpm-workspace.yaml +1 -0
  75. package/package.json +14 -11
  76. package/templates/process/pnpm-workspace.yaml +1 -0
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Official artifact deploys need committed, clean source on `main` (or
3
- * `staging` for a staging target). A dry-run deploys nothing, so there it
4
- * reports what a real deploy would refuse instead of failing.
3
+ * `staging` for a staging target). `env` is the CLI's name for the target,
4
+ * not the deployment's own environment, so Atlas decides whether `staging`
5
+ * is official there. A dry-run deploys nothing, so there it reports what a
6
+ * real deploy would refuse instead of failing.
5
7
  */
6
8
  export declare function checkOfficialArtifactSource({ dir, env, dryRun, }: {
7
9
  dir: string;
@@ -1,10 +1,12 @@
1
- import { ActiveDeployPolicyError, assertActiveDeployProvenance, } from '@sequenceholdings/artifact-studio/active-deploy-policy';
1
+ import { ActiveDeployPolicyError, assertActiveDeploySourceBeforeUpload, } from '@sequenceholdings/artifact-studio/active-deploy-policy';
2
2
  import { localGitMetadata } from '@sequenceholdings/artifact-studio/source-resolver';
3
3
  const LOG = '[seq-studio]';
4
4
  /**
5
5
  * Official artifact deploys need committed, clean source on `main` (or
6
- * `staging` for a staging target). A dry-run deploys nothing, so there it
7
- * reports what a real deploy would refuse instead of failing.
6
+ * `staging` for a staging target). `env` is the CLI's name for the target,
7
+ * not the deployment's own environment, so Atlas decides whether `staging`
8
+ * is official there. A dry-run deploys nothing, so there it reports what a
9
+ * real deploy would refuse instead of failing.
8
10
  */
9
11
  export function checkOfficialArtifactSource({ dir, env, dryRun = false, }) {
10
12
  const provenance = localGitMetadata(dir);
@@ -13,7 +15,7 @@ export function checkOfficialArtifactSource({ dir, env, dryRun = false, }) {
13
15
  throw new ActiveDeployPolicyError(`${dir} is not in a git repository with a commit. Official artifact deploys need committed ` +
14
16
  'source on `main`: run `git init`, commit, then deploy, or use a preview deploy.');
15
17
  }
16
- assertActiveDeployProvenance({ ...provenance, environment: env });
18
+ assertActiveDeploySourceBeforeUpload(provenance);
17
19
  }
18
20
  catch (error) {
19
21
  if (!dryRun || !(error instanceof ActiveDeployPolicyError))
@@ -135,13 +135,13 @@ Use the environment name your administrator supplies. \`local\` means a real Atl
135
135
 
136
136
  ## Shared packages
137
137
 
138
- Export common types, validation, and helpers from \`packages/shared/src/index.ts\`. Artifacts and processes depend on \`@${input.appId}/shared\` through \`workspace:*\`; ordinary imports work across the app. A function's dependencies ship as-is and a deployed bundle cannot follow a \`workspace:*\` link, so functions don't get one by default:
138
+ Export common types, validation, and helpers from \`packages/shared/src/index.ts\`. Processes depend on \`@${input.appId}/shared\` through \`workspace:*\`; ordinary imports work across the app. Functions and artifacts don't get the link by default: a function's dependencies ship as-is and a deployed bundle cannot follow a \`workspace:*\` link, and an artifact deployed on its own with \`seq-studio artifact deploy --repo\` builds from its directory alone. Import the package wherever it is linked:
139
139
 
140
140
  \`\`\`ts
141
141
  import { /* your exports */ } from '@${input.appId}/shared'
142
142
  \`\`\`
143
143
 
144
- Create another shared package with \`seq-studio add package contracts\`, then add it to a consumer using pnpm:
144
+ Create another shared package with \`seq-studio add package contracts\`, then add it (or \`shared\`) to a consumer using pnpm:
145
145
 
146
146
  \`\`\`bash
147
147
  pnpm --filter @${input.appId}/primitive-<primitive-id> add '@${input.appId}/contracts@workspace:*'
@@ -135,6 +135,10 @@ function subpathExport({ exports, key, browser, requireImport }) {
135
135
  return undefined;
136
136
  }
137
137
  function workspaceExport({ pkg, subpath, browser, requireImport }) {
138
+ // Explicit source entry avoids missing/stale dist output in clean repository
139
+ // function builds. Browser conditions and package subpath exports stay intact.
140
+ if (!browser && !subpath && pkg.json.seqStudio?.source)
141
+ return pkg.json.seqStudio.source;
138
142
  const exports = pkg.json.exports;
139
143
  if (exports && typeof exports === 'object' && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith('.'))) {
140
144
  return subpathExport({ exports, key: subpath ? `.${subpath}` : '.', browser, requireImport });
@@ -67,9 +67,11 @@ export async function joinAppWorkspace({ rootDir, manifest, entries, }) {
67
67
  const { pnpm, ...packageFields } = pkg;
68
68
  mergeOverrides({ existing: overrides, incoming: pnpm?.overrides ?? {} });
69
69
  // A function's packaged dependencies ship as-is and a deployed bundle cannot
70
- // resolve a workspace: link, so functions opt in to shared packages explicitly.
71
- // Artifacts and processes are bundled at build time, so the link is safe there.
72
- const shared = entry.kind === 'function' ? [] : manifest.packages ?? [];
70
+ // resolve a workspace: link. An artifact deployed on its own
71
+ // (`artifact deploy --repo`) builds from its directory alone, where the link
72
+ // is an unresolvable production dependency, and the scaffold never imports
73
+ // it. Both opt in to shared packages explicitly; processes get the link.
74
+ const shared = entry.kind === 'function' || entry.kind === 'artifact' ? [] : manifest.packages ?? [];
73
75
  await writeFile(packagePath, `${JSON.stringify({
74
76
  ...packageFields,
75
77
  name: `@${manifest.app.id}/primitive-${entry.id}`,
@@ -5,6 +5,8 @@ export interface AppWorkspaceOptions {
5
5
  manifest: WorkspaceManifest;
6
6
  entries: readonly PrimitiveEntry[];
7
7
  paths: ReadonlyMap<string, string>;
8
+ /** Standalone function commands read secrets from the original local dir. */
9
+ preserveFunctionEnv?: boolean;
8
10
  }
9
11
  /** Read-only dependency/path validation, suitable for deploy --dry-run. */
10
12
  export declare function validateAppWorkspace(options: AppWorkspaceOptions): Promise<void>;
@@ -126,7 +126,7 @@ export async function prepareAppWorkspace(options) {
126
126
  for (const [index, consumer] of staged.entries()) {
127
127
  const stageDir = join(temporary, String(index));
128
128
  await mkdir(stageDir, { recursive: true });
129
- const sourceFiles = await copyPrimitiveSources({ sourceDir: consumer.dir, stageDir, preserveEnv: consumer.entry.kind === 'function' });
129
+ const sourceFiles = await copyPrimitiveSources({ sourceDir: consumer.dir, stageDir, preserveEnv: consumer.entry.kind === 'function' && options.preserveFunctionEnv !== false });
130
130
  const compilerOptions = { sourceDir: consumer.dir, stageDir, json: consumer.json, packages, closure: consumer.closure };
131
131
  if (consumer.entry.kind === 'function')
132
132
  await compileWorkspaceFunction(compilerOptions);
@@ -16,14 +16,14 @@
16
16
  * package registry run: an agent sandbox reaches its Atlas origin and nothing else.
17
17
  */
18
18
  import { getAccessTokenWithMode, tryGetAccessTokenWithMode } from '../auth.js';
19
- import { ARTIFACT_SANDBOX_HELP } from '../command-help.js';
19
+ import { ARTIFACT_SANDBOX_HELP, INIT_INTO_REPO_HELP } from '../command-help.js';
20
20
  import { readConfig, resolveConfiguredEnv } from '../config.js';
21
- import { normalizeShortEnvFlag, readEnvFromArgv } from '../env-flags.js';
21
+ import { normalizeShortEnvFlag, readEnvFromArgv, withoutEnvFlag } from '../env-flags.js';
22
22
  import { PREVIEW_DOMAIN, PREVIEW_PROJECT, resolvePreviewByPr } from '../preview.js';
23
23
  import { sandboxTarget } from '../sandbox-auth.js';
24
24
  import { runSandboxArtifactCommand } from './sandbox.js';
25
25
  const ARTIFACT_USAGE = `usage:
26
- seq-studio artifact init <dir> [--template react-vite|nextjs]
26
+ seq-studio artifact init <dir> [--template react-vite|nextjs] [--repo <ns>/<name>]
27
27
  seq-studio artifact validate [dir]
28
28
  seq-studio artifact build [dir | --repo <ns>/<name> | --git-url <url>] [--ref <ref>] [--path <dir>] [--source-env <env>] [--out file.json]
29
29
  seq-studio artifact plan [dir | --repo <ns>/<name> | --git-url <url>] [--ref <ref>] [--path <dir>] [--source-env <env>] -e <env>
@@ -80,7 +80,27 @@ const ARTIFACT_USAGE = `usage:
80
80
 
81
81
  Authenticate with: seq-studio login
82
82
 
83
+ ${INIT_INTO_REPO_HELP}
83
84
  ${ARTIFACT_SANDBOX_HELP}`;
85
+ /**
86
+ * `init --repo` prepares the git-service checkout, then scaffolds into it
87
+ * through the ordinary init (sandbox or not). Null when `--repo` is absent.
88
+ * The environment is for the repository setup only: artifact-studio's init
89
+ * accepts no --env, so the delegated scaffold never sees one.
90
+ */
91
+ async function runArtifactInitWithRepo(rest) {
92
+ const { extractRepoFlag, runInitWithRepo } = await import('../repos/init-repo.js');
93
+ const { repo, rest: initArgv } = extractRepoFlag(rest);
94
+ if (repo === undefined)
95
+ return null;
96
+ const { parseArgs } = await import('../argv.js');
97
+ const args = parseArgs(normalizeShortEnvFlag(rest));
98
+ return runInitWithRepo({
99
+ args,
100
+ target: args.positional[0] ?? '.',
101
+ scaffold: () => runArtifactCommand('init', withoutEnvFlag(initArgv)),
102
+ });
103
+ }
84
104
  export async function runArtifactCommand(sub, rest) {
85
105
  if (rest.some((arg) => arg === '--token' || arg.startsWith('--token='))) {
86
106
  console.error('seq-studio artifact does not accept bearer tokens via --token. ' +
@@ -96,6 +116,9 @@ export async function runArtifactCommand(sub, rest) {
96
116
  }
97
117
  // Never pass a legacy bearer environment variable into the embedded package.
98
118
  delete process.env['ARTIFACT_STUDIO_TOKEN'];
119
+ const repoInit = sub === 'init' ? await runArtifactInitWithRepo(rest) : null;
120
+ if (repoInit !== null)
121
+ return repoInit;
99
122
  const sandbox = sandboxTarget();
100
123
  if (sandbox)
101
124
  return runSandboxArtifactCommand({ sandbox, sub, rest });
@@ -13,7 +13,8 @@ import { SANDBOX_ENV_NAME, sourceAuthMode } from '../sandbox-auth.js';
13
13
  /** How an agent gets an app deployed when a sandbox refuses the local path. */
14
14
  const SANDBOX_DEPLOY_GUIDANCE = 'Push the app to a Git Service repository and deploy from it: `seq-studio repos create <ns>/<name>`, ' +
15
15
  '`seq-studio repos clone <ns>/<name>`, commit and `git push` the app on main, then ' +
16
- '`seq-studio artifact deploy --repo <ns>/<name>`.';
16
+ '`seq-studio artifact deploy --repo <ns>/<name>`. To try a branch first, add `--ref <branch> --preview` ' +
17
+ 'for a private preview link that leaves the live app unchanged.';
17
18
  /** Shown when a static build would need `pnpm install`, which a sandbox cannot run. */
18
19
  const SANDBOX_INSTALL_GUIDANCE = 'An agent sandbox cannot reach a package registry. Remove the package.json dependencies and optionalDependencies ' +
19
20
  '(scaffold imports such as React, atlas-ui and the Artifact Studio SDK need none), ' +
@@ -1,9 +1,4 @@
1
- /**
2
- * Minimal authenticated HTTP client for Atlas. Same retry-on-503 contract
3
- * as `shared/services/artifact-studio/src/api.ts` so behavior is
4
- * consistent across both Sequence CLIs. Token + baseUrl are passed in by
5
- * the caller — this file knows nothing about token files or config TOMLs.
6
- */
1
+ import { createOperatorPlatformClient } from "@sequenceholdings/platform/server";
7
2
  export interface ClientOptions {
8
3
  baseUrl: string;
9
4
  token: string;
@@ -28,7 +23,7 @@ export declare class AtlasApiError extends Error {
28
23
  /** Bounded single attempt for commands whose uncertain result must be reconciled by the caller. */
29
24
  export declare function requestJsonOnce({ baseUrl, token, path, method, body, }: ClientOptions & {
30
25
  path: string;
31
- method: 'GET' | 'POST' | 'PUT';
26
+ method: "GET" | "POST" | "PUT" | "DELETE";
32
27
  body?: unknown;
33
28
  }): Promise<unknown>;
34
29
  export declare function getJson<T>({ baseUrl, token, path, }: ClientOptions & {
@@ -47,10 +42,11 @@ export declare function postJson<T>({ baseUrl, token, path, body, sourceAuthoriz
47
42
  * necessarily JSON and whose non-2xx status may belong to the downstream
48
43
  * application. The caller decides how to render and interpret the status.
49
44
  */
50
- export declare function postJsonResponse({ baseUrl, token, path, body, headers, }: ClientOptions & {
45
+ export declare function postJsonResponse({ baseUrl, token, path, body, headers, timeoutMs, }: ClientOptions & {
51
46
  path: string;
52
47
  body?: unknown;
53
48
  headers?: Record<string, string>;
49
+ timeoutMs?: number;
54
50
  }): Promise<AtlasResponse>;
55
51
  export declare function putJson<T>({ baseUrl, token, path, body, }: ClientOptions & {
56
52
  path: string;
@@ -64,7 +60,18 @@ export declare function deleteJson<T>({ baseUrl, token, path, body, }: ClientOpt
64
60
  path: string;
65
61
  body?: unknown;
66
62
  }): Promise<T>;
63
+ /**
64
+ * JSON POST/DELETE for mutations that answer either a JSON body or 204 No
65
+ * Content (git-service principals, for example). Resolves `undefined` for 204.
66
+ */
67
+ export declare function sendJsonOrNoContent({ baseUrl, token, path, method, body, }: ClientOptions & {
68
+ path: string;
69
+ method: 'POST' | 'DELETE';
70
+ body?: unknown;
71
+ }): Promise<unknown>;
67
72
  /** DELETE for endpoints that return 204 with an empty body (deleteJson would choke on it). */
68
73
  export declare function deleteNoContent({ baseUrl, token, path, }: ClientOptions & {
69
74
  path: string;
70
75
  }): Promise<void>;
76
+ /** Shared platform transport owns origin, redirect, deadline and response bounds. CLI supplies only its current session and trusted edge credentials. */
77
+ export declare function operatorPlatformClient({ baseUrl, token, }: ClientOptions): ReturnType<typeof createOperatorPlatformClient>;
@@ -1,26 +1,27 @@
1
+ import { authenticatedRequestUrl } from "@sequenceholdings/artifact-studio/deployment-validation";
2
+ import { createPlatformTransport, createOperatorPlatformClient, } from "@sequenceholdings/platform/server";
1
3
  /**
2
4
  * Minimal authenticated HTTP client for Atlas. Same retry-on-503 contract
3
5
  * as `shared/services/artifact-studio/src/api.ts` so behavior is
4
6
  * consistent across both Sequence CLIs. Token + baseUrl are passed in by
5
7
  * the caller — this file knows nothing about token files or config TOMLs.
6
8
  */
7
- import { authenticatedRequestUrl } from '@sequenceholdings/artifact-studio/deployment-validation';
8
- import { validationDetail } from './validation-detail.js';
9
- import { PREVIEW_DOMAIN } from './preview.js';
10
- import { sandboxBearerFor } from './sandbox-auth.js';
11
- import { errorCode, isTransient503 } from './transient-503.js';
9
+ import { validationDetail } from "./validation-detail.js";
10
+ import { PREVIEW_DOMAIN } from "./preview.js";
11
+ import { sandboxBearerFor } from "./sandbox-auth.js";
12
+ import { errorCode, isTransient503 } from "./transient-503.js";
12
13
  const MAX_503_RETRIES = 5;
13
14
  const DEFAULT_RETRY_AFTER_SECONDS = 2;
14
- const LOG_PREFIX = '[seq-studio]';
15
- const CF_ACCESS_DOMAIN = 'seqholdings.com';
15
+ const LOG_PREFIX = "[seq-studio]";
16
+ const CF_ACCESS_DOMAIN = "seqholdings.com";
16
17
  export class AtlasApiError extends Error {
17
18
  status;
18
19
  path;
19
20
  statusText;
20
21
  body;
21
- name = 'AtlasApiError';
22
+ name = "AtlasApiError";
22
23
  retryAfterSeconds = null;
23
- constructor(status, message, path, statusText = '', body = null) {
24
+ constructor(status, message, path, statusText = "", body = null) {
24
25
  super(message);
25
26
  this.status = status;
26
27
  this.path = path;
@@ -32,47 +33,73 @@ export class AtlasApiError extends Error {
32
33
  return errorCode(this.body);
33
34
  }
34
35
  }
35
- async function fetchWith503Retry(input, init) {
36
+ async function fetchWith503Retry(send) {
36
37
  let attempt = 0;
37
38
  for (;;) {
38
- const response = await fetch(input, init);
39
+ const response = await send();
39
40
  if (response.status !== 503 || attempt >= MAX_503_RETRIES)
40
41
  return response;
41
- const body = parseErrorBody(await response.clone().text(), response.headers.get('content-type') ?? '');
42
+ const body = parseErrorBody(await response.clone().text(), response.headers.get("content-type") ?? "");
42
43
  if (!isTransient503(body))
43
44
  return response;
44
- const retryAfter = Number(response.headers.get('Retry-After')) || DEFAULT_RETRY_AFTER_SECONDS;
45
+ const retryAfter = Number(response.headers.get("Retry-After")) ||
46
+ DEFAULT_RETRY_AFTER_SECONDS;
45
47
  attempt += 1;
46
48
  console.warn(`${LOG_PREFIX} backend warming up (503); retrying in ${retryAfter}s (attempt ${attempt}/${MAX_503_RETRIES})`);
47
49
  await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
48
50
  }
49
51
  }
50
- async function authenticatedFetch({ baseUrl, init = {}, path, token, retry503 = true, }) {
51
- const url = authenticatedRequestUrl({ baseUrl, path });
52
- // Sandbox tokens rotate between requests, so a long command re-reads the file
53
- // for every call instead of reusing the token it resolved at startup.
54
- const bearer = (await sandboxBearerFor(baseUrl)) ?? token;
55
- const send = retry503 ? fetchWith503Retry : fetch;
56
- return send(url, {
57
- ...init,
58
- redirect: 'manual',
59
- headers: {
52
+ async function authenticatedFetch({ baseUrl, init = {}, path, token, retry503 = true, timeoutMs, }) {
53
+ authenticatedRequestUrl({ baseUrl, path });
54
+ const transport = createPlatformTransport({
55
+ baseUrl,
56
+ timeoutMs,
57
+ auth: {
58
+ kind: "operator",
59
+ bearer: async () => (await sandboxBearerFor(baseUrl)) ?? token,
60
+ },
61
+ edgeHeaders: () => ({
60
62
  ...previewAccessHeaders(baseUrl),
61
63
  ...cfAccessHeaders(baseUrl),
62
- ...init.headers,
63
- Authorization: `Bearer ${bearer}`,
64
- },
64
+ }),
65
65
  });
66
+ const send = async () => {
67
+ const method = (init.method ?? "GET").toUpperCase();
68
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method))
69
+ throw new Error("Unsupported CLI HTTP method");
70
+ const result = await transport.requestRaw({
71
+ path,
72
+ method: method,
73
+ headers: init.headers,
74
+ body: typeof init.body === "string" ? JSON.parse(init.body) : undefined,
75
+ signal: init.signal,
76
+ });
77
+ return new Response([204, 205, 304].includes(result.status) ? null : result.text, {
78
+ status: result.status,
79
+ statusText: result.statusText,
80
+ headers: result.headers,
81
+ });
82
+ };
83
+ // Existing pre-execution warmup receipts are replay-safe. All other responses, including uncertain mutations, are single-attempt.
84
+ return retry503 ? fetchWith503Retry(send) : send();
66
85
  }
67
86
  /** Bounded single attempt for commands whose uncertain result must be reconciled by the caller. */
68
87
  export async function requestJsonOnce({ baseUrl, token, path, method, body, }) {
69
- const response = await authenticatedFetch({ baseUrl, token, path, retry503: false,
70
- init: { method, signal: AbortSignal.timeout(30_000),
71
- headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
72
- ...(body === undefined ? {} : { body: JSON.stringify(body) }) } });
88
+ const response = await authenticatedFetch({
89
+ baseUrl,
90
+ token,
91
+ path,
92
+ retry503: false,
93
+ init: {
94
+ method,
95
+ signal: AbortSignal.timeout(30_000),
96
+ headers: body === undefined ? {} : { "Content-Type": "application/json" },
97
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
98
+ },
99
+ });
73
100
  const reader = response.body?.getReader();
74
101
  if (!reader)
75
- throw new Error('Missing response body');
102
+ throw new Error("Missing response body");
76
103
  const chunks = [];
77
104
  let size = 0;
78
105
  try {
@@ -82,7 +109,7 @@ export async function requestJsonOnce({ baseUrl, token, path, method, body, }) {
82
109
  break;
83
110
  size += item.value.byteLength;
84
111
  if (size > 8_388_608)
85
- throw new Error('Response exceeds 8 MiB');
112
+ throw new Error("Response exceeds 8 MiB");
86
113
  chunks.push(item.value);
87
114
  }
88
115
  }
@@ -90,11 +117,14 @@ export async function requestJsonOnce({ baseUrl, token, path, method, body, }) {
90
117
  void reader.cancel().catch(() => { });
91
118
  reader.releaseLock();
92
119
  }
93
- const raw = Buffer.concat(chunks).toString('utf8');
94
- const parsed = parseErrorBody(raw, response.headers.get('content-type') ?? '');
120
+ const raw = Buffer.concat(chunks).toString("utf8");
121
+ const parsed = parseErrorBody(raw, response.headers.get("content-type") ?? "");
95
122
  if (!response.ok) {
96
123
  const error = new AtlasApiError(response.status, messageFromBody(parsed, response.status, response.statusText), path, response.statusText, parsed);
97
- error.retryAfterSeconds = response.status === 429 ? parseRetryAfter(response.headers.get('Retry-After')) : null;
124
+ error.retryAfterSeconds =
125
+ response.status === 429
126
+ ? parseRetryAfter(response.headers.get("Retry-After"))
127
+ : null;
98
128
  throw error;
99
129
  }
100
130
  return parsed;
@@ -110,11 +140,11 @@ function previewAccessHeaders(baseUrl) {
110
140
  return {};
111
141
  try {
112
142
  const parsed = new URL(baseUrl);
113
- if (parsed.protocol !== 'https:')
143
+ if (parsed.protocol !== "https:")
114
144
  return {};
115
145
  if (!parsed.hostname.toLowerCase().endsWith(`.${PREVIEW_DOMAIN}`))
116
146
  return {};
117
- return { 'x-preview-access': secret };
147
+ return { "x-preview-access": secret };
118
148
  }
119
149
  catch {
120
150
  return {};
@@ -136,12 +166,16 @@ function cfAccessHeaders(baseUrl) {
136
166
  return {};
137
167
  try {
138
168
  const parsed = new URL(baseUrl);
139
- if (parsed.protocol !== 'https:')
169
+ if (parsed.protocol !== "https:")
140
170
  return {};
141
171
  const hostname = parsed.hostname.toLowerCase();
142
- if (hostname !== CF_ACCESS_DOMAIN && !hostname.endsWith(`.${CF_ACCESS_DOMAIN}`))
172
+ if (hostname !== CF_ACCESS_DOMAIN &&
173
+ !hostname.endsWith(`.${CF_ACCESS_DOMAIN}`))
143
174
  return {};
144
- return { 'CF-Access-Client-Id': clientId, 'CF-Access-Client-Secret': clientSecret };
175
+ return {
176
+ "CF-Access-Client-Id": clientId,
177
+ "CF-Access-Client-Secret": clientSecret,
178
+ };
145
179
  }
146
180
  catch {
147
181
  return {};
@@ -158,34 +192,39 @@ function violationLines(violations) {
158
192
  return [];
159
193
  const lines = [];
160
194
  for (const v of violations) {
161
- if (v && typeof v === 'object' && typeof v.message === 'string') {
195
+ if (v &&
196
+ typeof v === "object" &&
197
+ typeof v.message === "string") {
162
198
  lines.push(` - ${v.message}`);
163
199
  }
164
200
  }
165
201
  return lines;
166
202
  }
167
203
  function messageFromBody(body, status, statusText) {
168
- if (body && typeof body === 'object') {
204
+ if (body && typeof body === "object") {
169
205
  const record = body;
170
206
  const violations = violationLines(record.violations);
171
- const withViolations = (headline) => violations.length > 0 ? [headline, ...violations].join('\n') : headline;
207
+ const withViolations = (headline) => violations.length > 0 ? [headline, ...violations].join("\n") : headline;
172
208
  const fields = validationDetail(record.errors);
173
209
  if (fields)
174
210
  return withViolations(fields);
175
- if (typeof record.detail === 'string' && record.detail.length > 0) {
211
+ if (typeof record.detail === "string" && record.detail.length > 0) {
176
212
  return withViolations(record.detail);
177
213
  }
178
- if (typeof record.error === 'string' && record.error.length > 0) {
214
+ if (typeof record.error === "string" && record.error.length > 0) {
179
215
  return withViolations(record.error);
180
216
  }
181
- if (record.error && typeof record.error === 'object' && 'message' in record.error && typeof record.error.message === 'string') {
217
+ if (record.error &&
218
+ typeof record.error === "object" &&
219
+ "message" in record.error &&
220
+ typeof record.error.message === "string") {
182
221
  return withViolations(record.error.message);
183
222
  }
184
- if (typeof record.message === 'string' && record.message.length > 0) {
223
+ if (typeof record.message === "string" && record.message.length > 0) {
185
224
  return withViolations(record.message);
186
225
  }
187
226
  }
188
- if (typeof body === 'string' && body.trim().length > 0) {
227
+ if (typeof body === "string" && body.trim().length > 0) {
189
228
  const trimmed = body.trim();
190
229
  return trimmed.length > 500 ? `${trimmed.slice(0, 500)}…` : trimmed;
191
230
  }
@@ -196,7 +235,7 @@ function messageFromBody(body, status, statusText) {
196
235
  function parseErrorBody(rawText, contentType) {
197
236
  if (rawText.length === 0)
198
237
  return null;
199
- const looksLikeJson = contentType.toLowerCase().includes('json') || /^\s*[{[]/.test(rawText);
238
+ const looksLikeJson = contentType.toLowerCase().includes("json") || /^\s*[{[]/.test(rawText);
200
239
  if (!looksLikeJson)
201
240
  return rawText;
202
241
  try {
@@ -207,7 +246,7 @@ function parseErrorBody(rawText, contentType) {
207
246
  }
208
247
  }
209
248
  async function responseError(response, path) {
210
- const contentType = response.headers.get('content-type') ?? '';
249
+ const contentType = response.headers.get("content-type") ?? "";
211
250
  const rawText = await response.text();
212
251
  const body = parseErrorBody(rawText, contentType);
213
252
  const message = messageFromBody(body, response.status, response.statusText);
@@ -233,8 +272,13 @@ export async function postJson({ baseUrl, token, path, body, sourceAuthorization
233
272
  token,
234
273
  path,
235
274
  init: {
236
- method: 'POST',
237
- headers: { 'Content-Type': 'application/json', ...(sourceAuthorization ? { 'x-sequence-source-authorization': sourceAuthorization } : {}) },
275
+ method: "POST",
276
+ headers: {
277
+ "Content-Type": "application/json",
278
+ ...(sourceAuthorization
279
+ ? { "x-sequence-source-authorization": sourceAuthorization }
280
+ : {}),
281
+ },
238
282
  body: body === undefined ? undefined : JSON.stringify(body),
239
283
  },
240
284
  });
@@ -247,21 +291,22 @@ export async function postJson({ baseUrl, token, path, body, sourceAuthorization
247
291
  * necessarily JSON and whose non-2xx status may belong to the downstream
248
292
  * application. The caller decides how to render and interpret the status.
249
293
  */
250
- export async function postJsonResponse({ baseUrl, token, path, body, headers = {}, }) {
294
+ export async function postJsonResponse({ baseUrl, token, path, body, headers = {}, timeoutMs, }) {
251
295
  const response = await authenticatedFetch({
252
296
  baseUrl,
253
297
  token,
254
298
  path,
299
+ timeoutMs,
255
300
  init: {
256
- method: 'POST',
257
- headers: { 'Content-Type': 'application/json', ...headers },
301
+ method: "POST",
302
+ headers: { "Content-Type": "application/json", ...headers },
258
303
  body: body === undefined ? undefined : JSON.stringify(body),
259
304
  },
260
305
  });
261
306
  return {
262
307
  status: response.status,
263
- contentType: response.headers.get('content-type') ?? '',
264
- invocationId: response.headers.get('x-invocation-id'),
308
+ contentType: response.headers.get("content-type") ?? "",
309
+ invocationId: response.headers.get("x-invocation-id"),
265
310
  body: await response.text(),
266
311
  };
267
312
  }
@@ -271,8 +316,8 @@ export async function putJson({ baseUrl, token, path, body, }) {
271
316
  token,
272
317
  path,
273
318
  init: {
274
- method: 'PUT',
275
- headers: { 'Content-Type': 'application/json' },
319
+ method: "PUT",
320
+ headers: { "Content-Type": "application/json" },
276
321
  body: body === undefined ? undefined : JSON.stringify(body),
277
322
  },
278
323
  });
@@ -286,8 +331,8 @@ export async function patchJson({ baseUrl, token, path, body, }) {
286
331
  token,
287
332
  path,
288
333
  init: {
289
- method: 'PATCH',
290
- headers: { 'Content-Type': 'application/json' },
334
+ method: "PATCH",
335
+ headers: { "Content-Type": "application/json" },
291
336
  body: body === undefined ? undefined : JSON.stringify(body),
292
337
  },
293
338
  });
@@ -301,8 +346,8 @@ export async function deleteJson({ baseUrl, token, path, body, }) {
301
346
  token,
302
347
  path,
303
348
  init: {
304
- method: 'DELETE',
305
- headers: { 'Content-Type': 'application/json' },
349
+ method: "DELETE",
350
+ headers: { "Content-Type": "application/json" },
306
351
  body: body === undefined ? undefined : JSON.stringify(body),
307
352
  },
308
353
  });
@@ -310,14 +355,45 @@ export async function deleteJson({ baseUrl, token, path, body, }) {
310
355
  throw await responseError(response, path);
311
356
  return response.json();
312
357
  }
358
+ /**
359
+ * JSON POST/DELETE for mutations that answer either a JSON body or 204 No
360
+ * Content (git-service principals, for example). Resolves `undefined` for 204.
361
+ */
362
+ export async function sendJsonOrNoContent({ baseUrl, token, path, method, body, }) {
363
+ const response = await authenticatedFetch({
364
+ baseUrl,
365
+ token,
366
+ path,
367
+ init: {
368
+ method,
369
+ headers: { 'Content-Type': 'application/json' },
370
+ body: body === undefined ? undefined : JSON.stringify(body),
371
+ },
372
+ });
373
+ if (!response.ok)
374
+ throw await responseError(response, path);
375
+ return response.status === 204 ? undefined : response.json();
376
+ }
313
377
  /** DELETE for endpoints that return 204 with an empty body (deleteJson would choke on it). */
314
378
  export async function deleteNoContent({ baseUrl, token, path, }) {
315
379
  const response = await authenticatedFetch({
316
380
  baseUrl,
317
381
  token,
318
382
  path,
319
- init: { method: 'DELETE' },
383
+ init: { method: "DELETE" },
320
384
  });
321
385
  if (!response.ok)
322
386
  throw await responseError(response, path);
323
387
  }
388
+ /** Shared platform transport owns origin, redirect, deadline and response bounds. CLI supplies only its current session and trusted edge credentials. */
389
+ export function operatorPlatformClient({ baseUrl, token, }) {
390
+ authenticatedRequestUrl({ baseUrl, path: "/api/auth/cli-config" });
391
+ return createOperatorPlatformClient({
392
+ baseUrl,
393
+ bearer: async () => (await sandboxBearerFor(baseUrl)) ?? token,
394
+ edgeHeaders: () => ({
395
+ ...previewAccessHeaders(baseUrl),
396
+ ...cfAccessHeaders(baseUrl),
397
+ }),
398
+ });
399
+ }
package/dist/bin.js CHANGED
@@ -24,10 +24,18 @@ run(argv)
24
24
  // The update notice runs after the command so it never delays real output,
25
25
  // and it is best-effort (never throws, never changes the exit code).
26
26
  .then(async (code) => {
27
- if (!isHelpOrDiscovery && !isOfflineCommand && !(argv[0] === 'auth' && argv[1] === 'git-credential')) {
27
+ const isGitCredential = argv[0] === 'auth' && argv[1] === 'git-credential';
28
+ if (!isHelpOrDiscovery && !isOfflineCommand && !isGitCredential) {
28
29
  const { maybeNotifyUpdate } = await import('./update-check.js');
29
30
  await maybeNotifyUpdate();
30
31
  }
32
+ // Sandbox token mode only: a stderr reminder when the cwd's checkout holds
33
+ // work that is not pushed. Never during a git push's own credential call.
34
+ if (!isGitCredential) {
35
+ await import('./sandbox-unpushed-warning.js')
36
+ .then(({ warnUnpushedSandboxWork }) => warnUnpushedSandboxWork())
37
+ .catch(() => undefined);
38
+ }
31
39
  // Forced exit discards queued stdout/stderr when callers pipe large JSON
32
40
  // responses. Let Node drain pending writes before exiting with this status.
33
41
  process.exitCode = code;
@@ -1,3 +1,4 @@
1
+ import { PlatformError } from '@sequenceholdings/platform';
1
2
  import { AtlasApiError } from './atlas-client.js';
2
3
  export const LOG = '[seq-studio]';
3
4
  /** Map common apply failure reasons to clearer copy (original reason is preserved). */
@@ -69,6 +70,9 @@ function nextStepForAtlasError(error) {
69
70
  return null;
70
71
  }
71
72
  export function formatCliError(error) {
73
+ // Shared domain clients retain the CLI's existing status/path guidance.
74
+ if (error instanceof PlatformError)
75
+ return formatCliError(new AtlasApiError(error.status, error.message, error.path ?? '', '', { code: error.code }));
72
76
  if (error instanceof AtlasApiError) {
73
77
  const lines = [`${LOG} ${error.status}${error.statusText ? ` ${error.statusText}` : ''}: ${error.message}`];
74
78
  if (error.path)