@sequenceholdings/studio-cli 0.7.1 → 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 (87) hide show
  1. package/README.md +390 -54
  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.d.ts +3 -1
  22. package/dist/app/commands.js +88 -12
  23. package/dist/app/manifest.d.ts +2 -2
  24. package/dist/app/official-source.d.ts +4 -2
  25. package/dist/app/official-source.js +6 -4
  26. package/dist/app/readme.js +2 -2
  27. package/dist/app/validate.d.ts +16 -0
  28. package/dist/app/validate.js +40 -0
  29. package/dist/app/workspace-model.js +4 -0
  30. package/dist/app/workspace-scaffold.js +5 -3
  31. package/dist/app/workspace.d.ts +2 -0
  32. package/dist/app/workspace.js +1 -1
  33. package/dist/artifact/delegate.js +26 -3
  34. package/dist/artifact/sandbox.js +2 -1
  35. package/dist/atlas-client.d.ts +17 -8
  36. package/dist/atlas-client.js +146 -62
  37. package/dist/bin.js +10 -1
  38. package/dist/cli-errors.js +12 -3
  39. package/dist/command-contract.d.ts +14 -2
  40. package/dist/command-contract.js +4 -2
  41. package/dist/command-help.d.ts +9 -7
  42. package/dist/command-help.js +56 -12
  43. package/dist/env-flags.d.ts +7 -0
  44. package/dist/env-flags.js +23 -0
  45. package/dist/functions/commands.d.ts +4 -0
  46. package/dist/functions/commands.js +127 -11
  47. package/dist/functions/manifest.d.ts +5 -0
  48. package/dist/functions/manifest.js +44 -23
  49. package/dist/functions/service-account-guidance.d.ts +21 -0
  50. package/dist/functions/service-account-guidance.js +62 -0
  51. package/dist/functions/workspace.d.ts +11 -0
  52. package/dist/functions/workspace.js +52 -0
  53. package/dist/main.d.ts +2 -1
  54. package/dist/main.js +17 -3
  55. package/dist/orm/delegate.d.ts +1 -0
  56. package/dist/orm/delegate.js +65 -12
  57. package/dist/orm/discover-schema.d.ts +26 -0
  58. package/dist/orm/discover-schema.js +5 -0
  59. package/dist/orm/execute.js +11 -5
  60. package/dist/orm/failures.d.ts +32 -0
  61. package/dist/orm/failures.js +75 -0
  62. package/dist/orm/operation-show.d.ts +2 -0
  63. package/dist/orm/operation-show.js +35 -0
  64. package/dist/orm/read.js +3 -3
  65. package/dist/orm/version-guard.d.ts +3 -0
  66. package/dist/orm/version-guard.js +63 -0
  67. package/dist/pipeline/commands.js +4 -1
  68. package/dist/principals/commands.d.ts +3 -0
  69. package/dist/principals/commands.js +124 -0
  70. package/dist/process/runs.d.ts +4 -3
  71. package/dist/process/runs.js +52 -10
  72. package/dist/release-age.d.ts +1 -1
  73. package/dist/release-age.js +1 -0
  74. package/dist/repos/commands.d.ts +44 -0
  75. package/dist/repos/commands.js +55 -15
  76. package/dist/repos/init-repo.d.ts +45 -0
  77. package/dist/repos/init-repo.js +257 -0
  78. package/dist/sandbox-unpushed-warning.d.ts +23 -0
  79. package/dist/sandbox-unpushed-warning.js +86 -0
  80. package/dist/service-accounts/commands.js +15 -3
  81. package/dist/templates/commands.d.ts +14 -2
  82. package/dist/templates/commands.js +70 -16
  83. package/dist/templates/process/pnpm-workspace.yaml +1 -0
  84. package/dist/transient-503.d.ts +4 -0
  85. package/dist/transient-503.js +25 -0
  86. package/package.json +14 -10
  87. package/templates/process/pnpm-workspace.yaml +1 -0
@@ -1,14 +1,23 @@
1
1
  /** Help text reachable before command implementations, auth, optional SDKs, or Atlas clients load. */
2
+ /** `--repo` on every init command; shared so the commands describe it identically. */
3
+ export const INIT_INTO_REPO_HELP = ` Init into a repo: --repo <ns>/<name> on an init command creates that platform
4
+ git-service repo if missing (same name rules as repos create), then clones it
5
+ into <dir> and scaffolds there, or, when <dir> is inside a Git checkout, sets
6
+ it as that checkout's origin (a different existing origin is refused). It
7
+ needs -e <env>, or an agent sandbox. Nothing is committed or pushed; the
8
+ command prints the git add, commit, and push to run.
9
+ `;
2
10
  export const ORM_HELP = `usage:
3
- seq-studio orm init <dir>
11
+ seq-studio orm init <dir> [--repo <ns>/<name>]
4
12
  seq-studio orm generate [dir] [--migration-export] [--check]
5
13
  seq-studio orm validate [dir]
6
14
  seq-studio orm plan [dir] -e <env>
7
- seq-studio orm apply [dir] -e <env>
15
+ seq-studio orm apply [dir] -e <env> [--timeout <duration>] [--no-wait]
8
16
  seq-studio orm execute <namespace> <operation> -e <env> [--variables-file <file>] [--var <name>=<value>]...
9
17
  seq-studio orm execute <operation> [dir] --variables-file <file> -e <env>
10
18
  seq-studio orm namespaces -e <env> [--limit N] [--offset N] [--json]
11
19
  seq-studio orm describe <namespace> [<table> | --operations] -e <env> [--json]
20
+ seq-studio orm operation show <namespace> <name> -e <env> [--json]
12
21
  seq-studio orm read <namespace> <table> -e <env> [--where <column>=<op>.<value>]... [--select <cols>] [--order <col>[.desc]] [--limit N] [--offset N] [--json|--jsonl]
13
22
  seq-studio orm sql <namespace> --query <sql> | --file <path> -e <env> [--param <name>[:<type>]=<value>]... | [--params <json-object>] [--json|--jsonl]
14
23
  seq-studio orm diff [dir] [--check] [--allow-destructive] [--rebase]
@@ -17,6 +26,10 @@ export const ORM_HELP = `usage:
17
26
 
18
27
  -e/--env is required for commands that contact Atlas. Use seq-studio envs list
19
28
  to discover environments and seq-studio login to authenticate.
29
+ Schema commands require the ORM loaded by seq-studio to satisfy the v2
30
+ namespace's package.json @sequenceholdings/orm range before compiling.
31
+ apply waits until the new version is live and serving (default up to 20m), then
32
+ prints "live:"; --no-wait returns once the apply is queued.
20
33
  namespaces lists what you can read; describe shows its tables and operations.
21
34
  Run seq-studio orm describe --help for the output.
22
35
  execute <namespace> <operation> runs the deployed version's persisted operation by
@@ -24,7 +37,8 @@ export const ORM_HELP = `usage:
24
37
  read and sql query a v2 namespace as you through its built-in read-only SQL.
25
38
  sql must name tables as <namespace>.<table> (FROM lending.loans, not FROM loans).
26
39
  Run seq-studio orm read --help for the filter grammar, parameters, and output formats.
27
- `;
40
+
41
+ ${INIT_INTO_REPO_HELP}`;
28
42
  /** Artifact commands in sandbox token mode; shared by the offline and delegate usage. */
29
43
  export const ARTIFACT_SANDBOX_HELP = ` In an agent sandbox (SEQ_STUDIO_BASE_URL + SEQ_STUDIO_TOKEN_FILE), build, plan
30
44
  and deploy take --repo: push the app to a Git Service repository and deploy
@@ -35,7 +49,7 @@ export const ARTIFACT_SANDBOX_HELP = ` In an agent sandbox (SEQ_STUDIO_BASE_URL
35
49
  unavailable there, and -e is ignored.
36
50
  `;
37
51
  export const ARTIFACT_HELP = `usage:
38
- seq-studio artifact init <dir> [--template react-vite|nextjs]
52
+ seq-studio artifact init <dir> [--template react-vite|nextjs] [--repo <namespace>/<name>]
39
53
  seq-studio artifact whoami -e <env>
40
54
  seq-studio artifact link [dir] -e <env> [--project <id>]
41
55
  seq-studio artifact env list|use <env>
@@ -54,6 +68,7 @@ export const ARTIFACT_HELP = `usage:
54
68
  deployment workflows have different source and approval rules; see the public
55
69
  CLI README.
56
70
 
71
+ ${INIT_INTO_REPO_HELP}
57
72
  ${ARTIFACT_SANDBOX_HELP}`;
58
73
  export const PIPELINE_HELP = `usage:
59
74
  seq-studio pipeline list -e <env> [--limit 1..200] [--offset N] [--json]
@@ -72,6 +87,8 @@ export const PIPELINE_HELP = `usage:
72
87
  Source identity must be adopted and belong to the destination tenant.
73
88
  Registered OpCo source origins are not supported yet. The target verifies
74
89
  and snapshots source before planning; no target repository is created.
90
+ Reviewed pipeline.config.yml source_paths can select runtime files and
91
+ directories, retaining pipeline metadata, release identity and size limits.
75
92
  Not compatible with --dir, existing IDs, or coordinated migrations.
76
93
  Rollback uses retained snapshots; historical source commits can be re-planned
77
94
  explicitly with deploy --ref <sha> --source-env <env>.
@@ -87,12 +104,14 @@ export const PIPELINE_HELP = `usage:
87
104
  Help is available offline.
88
105
  `;
89
106
  export const FUNCTIONS_USAGE = `usage:
90
- seq-studio functions init <dir> scaffold manifest, TypeScript handler, and docs pointers
107
+ seq-studio functions init <dir> [--repo <ns>/<name>] scaffold manifest, TypeScript handler, and docs pointers;
108
+ --repo scaffolds into a git-service repo (see Init into a repo)
91
109
  seq-studio functions build [--dir d] local pre-flight (manifest, lockfile, SDK timeout cap)
92
110
  seq-studio functions register -e <env> [--dir d] register a shell + initial secret declarations; no deploy
93
111
  seq-studio functions deploy -e <env> [-m msg] preflight, upload, then show version and lifecycle progress
94
112
  seq-studio functions list -e <env> [--match-local] functions visible on the environment
95
113
  seq-studio functions show -e <env> [--fn slug] detail for one function (versions, secrets)
114
+ [--json] [--version id|name] reader-gated release provenance
96
115
  seq-studio functions limits [-e <env>] [--json] bundled defaults/caps, or deployed policy
97
116
  [--fn slug] also show effective runtime limits (requires -e)
98
117
  seq-studio functions dev [--dir path] [--port 8080] local HTTP server with cache context
@@ -126,12 +145,21 @@ export const FUNCTIONS_USAGE = `usage:
126
145
  Remote sources record the pinned commit as provenance (never dirty) and NEVER
127
146
  read a repo-committed .env for secret values — provision secrets server-side
128
147
  or pass a local --from-env-file (resolved against your cwd).
148
+ Local deploys record repository-wide gitDirty, including unignored files
149
+ outside --dir. Check git status at the repository root before deploying.
150
+
151
+ Workspace dependencies are compiled from packages declared in a containing
152
+ sequence.app.yml, within the source repository. Only the selected function is
153
+ deployed: no sibling primitives or Application registration. Shared Node packages
154
+ can set package.json seqStudio.source to a root source entry for clean builds.
155
+ Package build scripts are not run. Local secret paths remain relative to --dir.
129
156
 
130
157
  Interactive --repo builds clone over smart-HTTP using your seq-studio login
131
158
  and repository read access. No PAT is needed. Headless M2M builds use JSON
132
159
  materialize and accept only platform-managed --repo sources. Use --env to
133
160
  select the same environment for source and deployment.
134
- `;
161
+
162
+ ${INIT_INTO_REPO_HELP}`;
135
163
  export const REPOS_USAGE = `usage:
136
164
  seq-studio repos list -e <env> [--namespace <slug>] [--mine] repos visible on the environment
137
165
  seq-studio repos namespaces [create <slug>] -e <env> list or create namespaces
@@ -141,7 +169,9 @@ export const REPOS_USAGE = `usage:
141
169
  seq-studio repos create <ns>/<name> -e <env> [--default-branch b] [--git-backend walgit]
142
170
  create a repo seeded with a README; --git-backend
143
171
  walgit creates it empty (for pushing existing
144
- history); needs namespace write
172
+ history); needs namespace write. The init
173
+ commands take --repo <ns>/<name> to create,
174
+ clone, and scaffold in one step
145
175
  seq-studio repos clone <ns>/<name> -e <env> [--ref r] [--output dir] [--force] [--full] [--transport auto|git|json]
146
176
  seq-studio repos clone --url <https://…/repos/<id>/git> -e <env> [--ref r] [--output dir] [--full]
147
177
  seq-studio repos clone --id <uuid> -e <env> [--ref r] [--output dir] [--full]
@@ -177,17 +207,27 @@ export const REPOS_USAGE = `usage:
177
207
  export const PROCESS_RUNS_USAGE = `usage:
178
208
  seq-studio process runs start <process-id> -e <env> [--version <v>] [--run-id <id>]
179
209
  [--metadata-file <file.json>] [--title <text>] [--entity <type>:<id>] [--json]
210
+ seq-studio process runs retry <run-id> -e <env> [--run-id <new-id>] [--json]
180
211
  seq-studio process runs list -e <env> [--process <id>] [--status <status>]
181
212
  [--entity-type <type>] [--entity-id <id>] [--archived] [--limit 1..500] [--json]
182
213
  seq-studio process runs show <run-id> -e <env> [--wait [--timeout <seconds>]] [--json]
183
214
  seq-studio process runs cancel <run-id> -e <env> [--json]
184
215
 
185
- Runs start and are read as you: start needs invoker on the process, show and
186
- list return only runs you can view, and cancel needs invoker on the process.
216
+ Runs start and are read as you: start and retry need invoker on the process,
217
+ show and list return only runs you can view, and cancel needs invoker on the
218
+ process.
219
+ start prints the new run's id. Omit --run-id for a fresh id on every start.
220
+ --run-id names exactly one run: repeating it for the same process returns that
221
+ run, whatever its status, instead of starting another. To run a failed run
222
+ again, retry it rather than inventing a new id.
187
223
  --version pins a published process version; omitted, the active version runs.
188
- --run-id makes start idempotent: repeating it for the same process returns the
189
- existing run instead of starting another. --metadata-file is a JSON object
190
- stored on the run.
224
+ --metadata-file is a JSON object stored on the run.
225
+ retry (CLI 0.9.0+) starts a new run of a failed, cancelled or timed_out run's
226
+ process version with the same metadata, entity and title, linked to the
227
+ original in its lineage, and prints the new id. Other statuses are refused.
228
+ Like start, a retry waits queued while the process is at its concurrent-run
229
+ limit.
230
+ --run-id on retry names the new run, so repeating the retry returns it.
191
231
  list returns the newest runs first, up to --limit (default 50, max 500); the run
192
232
  API has no cursor, so narrow with filters to reach older runs.
193
233
  --status: pending, running, completed, failed, cancelled, timed_out.
@@ -197,6 +237,7 @@ export const PROCESS_RUNS_USAGE = `usage:
197
237
  export const ORM_DISCOVER_HELP = `usage:
198
238
  seq-studio orm namespaces -e <env> [--limit N] [--offset N] [--json]
199
239
  seq-studio orm describe <namespace> [<table> | --operations] -e <env> [--json]
240
+ seq-studio orm operation show <namespace> <name> -e <env> [--json]
200
241
 
201
242
  Find the ORM data you can read, then query it with orm read or orm sql.
202
243
  namespaces lists only namespaces you can read, ordered by name: format (v2 or
@@ -211,6 +252,9 @@ export const ORM_DISCOVER_HELP = `usage:
211
252
  orm sql accept.
212
253
  A namespace you cannot read reports not found, the same as a missing one.
213
254
  --json prints the full description (describe omits the generated GraphQL SDL).
255
+ operation show prints one active persisted operation's registered GraphQL
256
+ document; --json includes its hash, declared variables, and requirements.
257
+ Missing and unreadable operations both report not found.
214
258
  In an agent sandbox (SEQ_STUDIO_BASE_URL + SEQ_STUDIO_TOKEN_FILE), -e is not needed.
215
259
  `;
216
260
  export const ORM_EXECUTE_HELP = `usage:
@@ -6,6 +6,13 @@
6
6
  /** Shared copy for network commands that must not silently fall back to `local`. */
7
7
  export declare const REQUIRE_EXPLICIT_ENV_MESSAGE = "You must specify an environment you have access to with `-e <env>`. Run `seq-studio envs list` to see available environments.";
8
8
  export declare function normalizeShortEnvFlag(argv: readonly string[]): string[];
9
+ /**
10
+ * argv without any environment flag, in every spelling (`-e x`, `-e=x`,
11
+ * `--env x`, `--env=x`, or a valueless one). For an offline step delegated
12
+ * after seq-studio already used the environment, e.g. the scaffold of
13
+ * `init --repo`, whose package parser rejects an unknown `--env`.
14
+ */
15
+ export declare function withoutEnvFlag(argv: readonly string[]): string[];
9
16
  /** Only valid AFTER normalizeShortEnvFlag — recognizes the two-token form. */
10
17
  export declare function readEnvFromArgv(rest: readonly string[]): string | undefined;
11
18
  /**
package/dist/env-flags.js CHANGED
@@ -34,6 +34,29 @@ export function normalizeShortEnvFlag(argv) {
34
34
  }
35
35
  return out;
36
36
  }
37
+ /**
38
+ * argv without any environment flag, in every spelling (`-e x`, `-e=x`,
39
+ * `--env x`, `--env=x`, or a valueless one). For an offline step delegated
40
+ * after seq-studio already used the environment, e.g. the scaffold of
41
+ * `init --repo`, whose package parser rejects an unknown `--env`.
42
+ */
43
+ export function withoutEnvFlag(argv) {
44
+ const normalized = normalizeShortEnvFlag(argv);
45
+ const out = [];
46
+ for (let i = 0; i < normalized.length; i++) {
47
+ const arg = normalized[i];
48
+ if (arg === undefined)
49
+ continue;
50
+ if (arg === '--env') {
51
+ const next = normalized[i + 1];
52
+ if (next !== undefined && !next.startsWith('-'))
53
+ i += 1;
54
+ continue;
55
+ }
56
+ out.push(arg);
57
+ }
58
+ return out;
59
+ }
37
60
  /** Only valid AFTER normalizeShortEnvFlag — recognizes the two-token form. */
38
61
  export function readEnvFromArgv(rest) {
39
62
  for (let i = 0; i < rest.length; i++) {
@@ -27,9 +27,13 @@ export interface VersionSummary {
27
27
  id: string;
28
28
  functionId: string;
29
29
  version: string;
30
+ sourceHash?: string | null;
30
31
  status: string;
31
32
  statusDetail: string | null;
32
33
  deployMessage: string | null;
34
+ gitCommit?: string | null;
35
+ gitBranch?: string | null;
36
+ gitDirty?: boolean | null;
33
37
  createdAt: string;
34
38
  deployedAt: string | null;
35
39
  isActive: boolean;
@@ -20,17 +20,23 @@ import { REQUIRE_EXPLICIT_ENV_MESSAGE, explicitOrSandboxEnv } from '../env-flags
20
20
  import { confirmYes } from '../prompt.js';
21
21
  import { writeScaffoldGuidance } from '../scaffold-guidance.js';
22
22
  import { collectBundleFiles, isDirectory, validateLocalBundle, } from './bundle.js';
23
- import { managedFunctionManifestSchema, MF_MANIFEST_FILENAME, manifestEgressHosts, manifestEgressIpRanges, manifestSecretNames, } from './manifest.js';
23
+ import { managedFunctionManifestSchema, missingServiceAccountMessage, MF_MANIFEST_FILENAME, manifestEgressHosts, manifestEgressIpRanges, manifestSecretNames, } from './manifest.js';
24
+ import { missingServiceAccountGuidance, missingServiceAccountRequirements } from './service-account-guidance.js';
24
25
  import { buildEgressPreviewLines, egressPropagationNote, formatEgressSummary, printFunctionEgressHosts, } from './egress-preview.js';
25
26
  import { resolveArtifactSource, } from '@sequenceholdings/artifact-studio/source-resolver';
26
27
  import { buildSecretPreviewLines, classifySecrets, } from './secret-reconcile.js';
27
28
  import { parseFunctionsSourceSelection, resolveFunctionSourceDir } from './source-selection.js';
29
+ import { prepareFunctionWorkspace } from './workspace.js';
28
30
  export { parseFunctionsSourceSelection, parseFunctionsSourceSpec, resolveFunctionSourceDir, } from './source-selection.js';
29
31
  import { warnOnManifestRoles } from '../manifest-roles-notice.js';
30
32
  const execFileAsync = promisify(execFile);
31
33
  export const LOG = '[seq-studio]';
32
34
  const POLL_INTERVAL_MS = 5_000;
33
35
  const POLL_TIMEOUT_MS = 20 * 60 * 1000;
36
+ // The invoke route can spend two startup windows plus readiness retries before
37
+ // a one-hour execution. Outlast its maximum 4,190-second client budget while
38
+ // retaining a finite deadline; ordinary metadata requests keep their default.
39
+ const FUNCTION_INVOKE_TIMEOUT_MS = 70 * 60 * 1000;
34
40
  const DEPLOY_PROGRESS_STAGES = new Set([
35
41
  'prepare', 'build', 'identity', 'subnet', 'cache', 'secrets',
36
42
  'publish', 'egress', 'readiness', 'activate', 'revoke',
@@ -277,6 +283,23 @@ limits:
277
283
  # allowed_ip_ranges:
278
284
  # - 203.0.113.0/24
279
285
 
286
+ # ORM data access: the namespace's read tables/views and persisted mutation
287
+ # names. Call operations by name with createFunctionOrmExecutor from
288
+ # @sequenceholdings/managed-functions/orm (no operations.manifest.json copy).
289
+ # Data access on behalf of the caller needs no service account. To also act as
290
+ # the function itself (createFunctionServiceOrmExecutor, Lattice runs), name a
291
+ # service_account you hold the actor role on (seq-studio service-accounts list |
292
+ # create): the account then acts in every namespace, or only in the ones you
293
+ # mark service: true. service: true requires a service_account.
294
+ # capabilities:
295
+ # data:
296
+ # my_namespace:
297
+ # tables: [my_table]
298
+ # operations: [UpdateMyTable]
299
+ # query: false
300
+ # # service: true # limit the account to the marked namespaces
301
+ # service_account: <account-id-or-slug>
302
+
280
303
  # Env-var names the function expects (UPPER_SNAKE_CASE). Values are read
281
304
  # from a local .env file at deploy time — they are never committed or bundled.
282
305
  secrets: []
@@ -380,9 +403,13 @@ registry=https://libraries.cgr.dev/javascript/
380
403
  export async function functionsInitCommand(args) {
381
404
  const target = args.positional[0];
382
405
  if (!target) {
383
- console.error('usage: seq-studio functions init <dir>');
406
+ console.error('usage: seq-studio functions init <dir> [--repo <ns>/<name> -e <env>]');
384
407
  return 1;
385
408
  }
409
+ if (args.flags.repo !== undefined) {
410
+ const { runInitWithRepo, withoutRepoFlag } = await import('../repos/init-repo.js');
411
+ return runInitWithRepo({ args, target, scaffold: () => functionsInitCommand(withoutRepoFlag(args)) });
412
+ }
386
413
  const dir = resolve(target);
387
414
  // Derive the slug from the resolved directory name so `init .` and
388
415
  // trailing-slash paths work (the raw argument would yield an empty id).
@@ -428,7 +455,13 @@ export async function functionsBuildCommand(args) {
428
455
  const source = await resolveArtifactSource(spec, remote);
429
456
  try {
430
457
  const dir = await resolveFunctionSourceDir({ repoDir: source.dir, path });
431
- return await buildFromResolvedSource({ spec, source: { ...source, dir } });
458
+ const prepared = await prepareFunctionWorkspace({ dir, ...(spec.kind === 'local' ? {} : { repoDir: source.dir }) });
459
+ try {
460
+ return await buildFromResolvedSource({ spec, source: { ...source, dir: prepared.dir } });
461
+ }
462
+ finally {
463
+ await prepared.cleanup();
464
+ }
432
465
  }
433
466
  finally {
434
467
  await source.cleanup();
@@ -511,15 +544,36 @@ export async function functionsDeployCommand(args) {
511
544
  try {
512
545
  const dir = await resolveFunctionSourceDir({ repoDir: source.dir, path });
513
546
  await warnOnManifestRoles({ dir, file: 'managed-function.yml', kind: 'host' });
514
- return await deployFromResolvedSource({ args, spec, ctx, source: { ...source, dir } });
547
+ const provenance = spec.kind === 'local' ? await gitMetadata(dir) : source.provenance;
548
+ const prepared = await prepareFunctionWorkspace({ dir, ...(spec.kind === 'local' ? {} : { repoDir: source.dir }) });
549
+ try {
550
+ return await deployFromResolvedSource({ args, spec, ctx, originalDir: dir, source: { ...source, dir: prepared.dir, provenance } });
551
+ }
552
+ finally {
553
+ await prepared.cleanup();
554
+ }
515
555
  }
516
556
  finally {
517
557
  await source.cleanup();
518
558
  }
519
559
  }
520
- async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, }) {
560
+ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, originalDir, }) {
521
561
  const dir = source.dir;
522
- const manifest = await readSourceManifest(dir, spec);
562
+ let manifest;
563
+ try {
564
+ manifest = await readSourceManifest(dir, spec);
565
+ }
566
+ catch (error) {
567
+ // A function that needs a service account and names none: say what this
568
+ // caller can do about it (create one, or attach one they already act as).
569
+ const requirements = missingServiceAccountRequirements(error);
570
+ if (!requirements)
571
+ throw error;
572
+ const ctx = earlyCtx ?? await buildContext(args).catch(() => null);
573
+ const guidance = ctx ? await missingServiceAccountGuidance({ client: clientOptions(ctx), requirements }) : null;
574
+ console.error(`${LOG} ${guidance ?? missingServiceAccountMessage(requirements)}`);
575
+ return 1;
576
+ }
523
577
  const { files, excludedEnvFiles } = await collectBundleFiles(dir);
524
578
  for (const excluded of excludedEnvFiles) {
525
579
  console.warn(`${LOG} excluded ${excluded} — dotenv files never enter bundles`);
@@ -542,9 +596,9 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
542
596
  const envFilePath = envFileFlag
543
597
  ? isAbsolute(envFileFlag)
544
598
  ? envFileFlag
545
- : resolve(spec.kind === 'local' ? dir : process.cwd(), envFileFlag)
599
+ : resolve(spec.kind === 'local' ? originalDir : process.cwd(), envFileFlag)
546
600
  : spec.kind === 'local'
547
- ? join(dir, '.env')
601
+ ? join(originalDir, '.env')
548
602
  : null;
549
603
  let envValues = {};
550
604
  if (envFileFlag) {
@@ -607,7 +661,7 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
607
661
  null;
608
662
  // Local deploys record best-effort working-tree provenance; remote sources
609
663
  // carry the resolver's pinned commit (gitCommit = resolved SHA, never dirty).
610
- const git = spec.kind === 'local' ? await gitMetadata(dir) : source.provenance;
664
+ const git = source.provenance;
611
665
  // Classify each declared secret so the deploy preview and reconcile step
612
666
  // know exactly what action to take for each one.
613
667
  let classification = null;
@@ -686,7 +740,7 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
686
740
  if (deployMessage)
687
741
  preview.push(`${LOG} message: ${deployMessage}`);
688
742
  if (git.gitCommit) {
689
- preview.push(`${LOG} git: ${git.gitBranch ?? '?'}@${git.gitCommit.slice(0, 8)}${git.gitDirty ? ' (dirty)' : ''}`);
743
+ preview.push(`${LOG} git: ${git.gitBranch ?? '?'}@${git.gitCommit.slice(0, 8)}${git.gitDirty ? ' (repository dirty)' : ''}`);
690
744
  }
691
745
  if (classification) {
692
746
  preview.push(...(classification.secrets.length === 0 && manifest.secrets.length > 0
@@ -779,7 +833,7 @@ async function deployFromResolvedSource({ args, spec, ctx: earlyCtx, source, })
779
833
  }
780
834
  }
781
835
  if (git.gitDirty) {
782
- console.warn(`${LOG} working tree is dirty — recording gitDirty=true on this version`);
836
+ console.warn(`${LOG} repository working tree is dirty (not limited to the function source directory) — recording gitDirty=true on this version`);
783
837
  }
784
838
  console.log(`${LOG} uploading bundle (${files.length} files) to ${ctx.env.name}…`);
785
839
  let version;
@@ -955,11 +1009,72 @@ async function printFunctionShowDetails({ ctx, fn, }) {
955
1009
  egressEnforced: detail?.function.egressEnforced ?? fn.egressEnforced ?? false,
956
1010
  });
957
1011
  }
1012
+ async function printFunctionReleaseJson(ctx, fn, selected) {
1013
+ if (!fn.currentUserAccess) {
1014
+ throw new Error('Release provenance requires read access to this function');
1015
+ }
1016
+ const detail = await getFunctionDetail(ctx, fn.id);
1017
+ if (!detail)
1018
+ throw new Error(`Function ${fn.slug} is no longer available on ${ctx.env.name}`);
1019
+ const release = detail.function;
1020
+ if (release.activeVersionId === undefined || typeof release.immutableRelease !== 'boolean') {
1021
+ throw new Error('This environment does not expose activeVersionId and immutableRelease for release inspection');
1022
+ }
1023
+ const versions = await listVersions(ctx, fn.id);
1024
+ const active = release.activeVersionId
1025
+ ? versions.find((version) => version.id === release.activeVersionId)
1026
+ : undefined;
1027
+ if (release.activeVersionId && !active) {
1028
+ throw new Error(`Active version ${release.activeVersionId} is missing from the version list; retry inspection`);
1029
+ }
1030
+ const selectedVersion = selected === undefined
1031
+ ? undefined
1032
+ : versions.find((version) => version.id === selected || version.version === selected);
1033
+ if (selected !== undefined && !selectedVersion) {
1034
+ throw new Error(`Version ${selected} was not found for ${fn.slug} on ${ctx.env.name}`);
1035
+ }
1036
+ const projectVersion = (version) => ({
1037
+ id: version.id,
1038
+ version: version.version,
1039
+ status: version.status ?? null,
1040
+ isActive: version.id === release.activeVersionId,
1041
+ sourceHash: version.sourceHash ?? null,
1042
+ gitCommit: version.gitCommit ?? null,
1043
+ gitBranch: version.gitBranch ?? null,
1044
+ gitDirty: version.gitDirty ?? null,
1045
+ createdAt: version.createdAt ?? null,
1046
+ deployedAt: version.deployedAt ?? null,
1047
+ });
1048
+ console.log(JSON.stringify({
1049
+ environment: ctx.env.name,
1050
+ function: {
1051
+ id: release.id,
1052
+ slug: release.slug,
1053
+ title: release.title,
1054
+ deployed: release.deployed,
1055
+ activeVersionId: release.activeVersionId,
1056
+ immutableRelease: release.immutableRelease,
1057
+ },
1058
+ activeVersion: active ? projectVersion(active) : null,
1059
+ versions: versions.map(projectVersion),
1060
+ ...(selectedVersion ? { selectedVersion: projectVersion(selectedVersion) } : {}),
1061
+ }, null, 2));
1062
+ return 0;
1063
+ }
958
1064
  export async function functionsShowCommand(args) {
1065
+ const selected = args.flags.version;
1066
+ if (selected !== undefined && (typeof selected !== 'string' || !selected.trim())) {
1067
+ throw new Error('--version requires a version ID or name');
1068
+ }
1069
+ if (selected !== undefined && !flagBool(args.flags, 'json')) {
1070
+ throw new Error('--version requires --json');
1071
+ }
959
1072
  const ctx = await buildContext(args);
960
1073
  const fn = await resolveFunction({ ctx, args, required: true });
961
1074
  if (!fn)
962
1075
  return 1;
1076
+ if (flagBool(args.flags, 'json'))
1077
+ return printFunctionReleaseJson(ctx, fn, selected);
963
1078
  console.log(`${LOG} function on ${ctx.env.name}:`);
964
1079
  console.log(` id: ${fn.id}`);
965
1080
  console.log(` slug: ${fn.slug}`);
@@ -1108,6 +1223,7 @@ export async function functionsInvokeCommand(args) {
1108
1223
  path: `/api/managed-functions/${fn.id}/invoke`,
1109
1224
  body: payload,
1110
1225
  headers: { 'X-Invocation-Source': 'cli' },
1226
+ timeoutMs: FUNCTION_INVOKE_TIMEOUT_MS,
1111
1227
  });
1112
1228
  const rendered = formatInvokeBody(result.body, result.contentType);
1113
1229
  process.stdout.write(rendered.endsWith('\n') ? rendered : `${rendered}\n`);
@@ -50,6 +50,10 @@ export declare function manifestEgressIpRanges(entries: readonly string[]): stri
50
50
  * bypass the matcher and are capped separately (per-function route count).
51
51
  */
52
52
  export declare function egressBudgetError(entries: string[]): string | null;
53
+ /** Issue param that marks the missing-account refusal, so deploy can add caller-specific guidance. */
54
+ export declare const SERVICE_ACCOUNT_REQUIRED = "SERVICE_ACCOUNT_REQUIRED";
55
+ /** The refusal for a manifest that needs a service account and names none, without caller-specific guidance. */
56
+ export declare function missingServiceAccountMessage(requirements: readonly string[]): string;
53
57
  export declare const managedFunctionManifestSchema: z.ZodObject<{
54
58
  ontology: z.ZodOptional<z.ZodObject<{
55
59
  version: z.ZodLiteral<1>;
@@ -179,6 +183,7 @@ export declare const managedFunctionManifestSchema: z.ZodObject<{
179
183
  actions: z.ZodDefault<z.ZodArray<z.ZodString>>;
180
184
  operations: z.ZodDefault<z.ZodArray<z.ZodString>>;
181
185
  query: z.ZodDefault<z.ZodBoolean>;
186
+ service: z.ZodOptional<z.ZodBoolean>;
182
187
  }, z.core.$strip>>>;
183
188
  }, z.core.$strip>>;
184
189
  }, z.core.$strip>;
@@ -564,19 +564,28 @@ const invocationIpRangeSchema = z
564
564
  });
565
565
  }
566
566
  });
567
- function refineServiceAccountAttachment({ requiresServiceAccount, serviceAccount, ctx }) {
568
- if (requiresServiceAccount && serviceAccount === undefined) {
567
+ /** Issue param that marks the missing-account refusal, so deploy can add caller-specific guidance. */
568
+ export const SERVICE_ACCOUNT_REQUIRED = 'SERVICE_ACCOUNT_REQUIRED';
569
+ /** The refusal for a manifest that needs a service account and names none, without caller-specific guidance. */
570
+ export function missingServiceAccountMessage(requirements) {
571
+ return `This function acts as itself, not as its caller, for ${requirements.join(', ')}, so managed-function.yml must name ` +
572
+ 'a service_account. Create one with `seq-studio service-accounts create <slug> --display-name "<name>"` (needs Can create ' +
573
+ 'on Service Accounts) or use an existing account you hold the actor role on, then add `service_account: <slug>`. ' +
574
+ 'Data access on behalf of the caller alone (capabilities.data without service: true) needs no account.';
575
+ }
576
+ function refineServiceAccountAttachment({ requirements, acceptsServiceAccount, serviceAccount, ctx }) {
577
+ if (requirements.length > 0 && serviceAccount === undefined) {
569
578
  ctx.addIssue({
570
579
  code: 'custom',
571
- message: 'Service access capabilities require a top-level service_account — the platform service ' +
572
- 'account this function acts as for service access (the deployer needs the actor role on it)',
580
+ message: missingServiceAccountMessage(requirements),
573
581
  path: ['service_account'],
582
+ params: { code: SERVICE_ACCOUNT_REQUIRED, requirements: [...requirements] },
574
583
  });
575
584
  }
576
- if (!requiresServiceAccount && serviceAccount !== undefined) {
585
+ if (!acceptsServiceAccount && serviceAccount !== undefined) {
577
586
  ctx.addIssue({
578
587
  code: 'custom',
579
- message: 'service_account requires at least one declared service access capability',
588
+ message: 'service_account requires at least one declared service access capability or data namespace',
580
589
  path: ['service_account'],
581
590
  });
582
591
  }
@@ -705,6 +714,14 @@ export const managedFunctionManifestSchema = z.object({
705
714
  .max(64)
706
715
  .default([]),
707
716
  query: z.boolean().default(false),
717
+ /**
718
+ * Act AS the function's attached service account in this namespace
719
+ * (`createFunctionServiceOrmExecutor`, system-runner invocations),
720
+ * not only on behalf of the caller; requires `service_account`.
721
+ * Marking any namespace narrows the account to the marked ones;
722
+ * with none marked, a named account acts in every declared namespace.
723
+ */
724
+ service: z.boolean().optional(),
708
725
  }))
709
726
  .default({}),
710
727
  }).default({ uses: [], gates: [], data: {} }),
@@ -747,24 +764,28 @@ export const managedFunctionManifestSchema = z.object({
747
764
  }
748
765
  // A namespace is "reached" when its block declares at least one table,
749
766
  // action, operation, or raw query — the same rule the server's floor
750
- // reconciliation uses (readManifestDataNamespaces).
751
- const reachesData = Object.keys(readStorageScopes(manifest)).length > 0 || Object.values(manifest.capabilities.data).some((block) => block.tables.length > 0 || block.actions.length > 0 || block.operations.length > 0 || block.query);
752
- const reachesProcesses = (manifest.capabilities.processes?.read.length ?? 0) > 0;
753
- const reachesAgents = (manifest.capabilities.agents?.read?.length ?? 0) > 0 || (manifest.capabilities.agents?.evidence?.length ?? 0) > 0;
754
- const reachesWorkflows = (manifest.capabilities.workflows?.read?.length ?? 0) > 0 || (manifest.capabilities.workflows?.evidence?.length ?? 0) > 0;
755
- const receivesLatticeContext = manifest.capabilities.lattice?.context === true;
767
+ // reconciliation uses (readManifestDataNamespaces). Reaching data on behalf
768
+ // of the caller needs no account; `service: true` asks to act as the function.
769
+ const reachedData = Object.entries(manifest.capabilities.data).filter(([, block]) => block.tables.length > 0 || block.actions.length > 0 || block.operations.length > 0 || block.query);
770
+ const requirements = [
771
+ ...reachedData.filter(([, block]) => block.service === true).map(([namespace]) => `capabilities.data.${namespace}.service`),
772
+ ...[
773
+ ['capabilities.storage', Object.keys(readStorageScopes(manifest)).length > 0],
774
+ ['capabilities.processes.read', (manifest.capabilities.processes?.read.length ?? 0) > 0],
775
+ ['capabilities.agents.read', (manifest.capabilities.agents?.read?.length ?? 0) > 0],
776
+ ['capabilities.agents.evidence', (manifest.capabilities.agents?.evidence?.length ?? 0) > 0],
777
+ ['capabilities.workflows.read', (manifest.capabilities.workflows?.read?.length ?? 0) > 0],
778
+ ['capabilities.workflows.evidence', (manifest.capabilities.workflows?.evidence?.length ?? 0) > 0],
779
+ ['capabilities.monitoring.producers', (manifest.capabilities.monitoring?.producers.length ?? 0) > 0],
780
+ ['capabilities.lattice.context', manifest.capabilities.lattice?.context === true],
781
+ ['capabilities.invocation.identity', manifest.capabilities.invocation?.identity === true],
782
+ ['capabilities.directory.resolve', (manifest.capabilities.directory?.resolve?.length ?? 0) > 0],
783
+ ['capabilities.abrigo.read', (manifest.capabilities.abrigo?.read.length ?? 0) > 0],
784
+ ].filter(([, present]) => present).map(([path]) => path),
785
+ ];
756
786
  refineServiceAccountAttachment({
757
- requiresServiceAccount: [
758
- reachesData,
759
- reachesProcesses,
760
- reachesAgents,
761
- reachesWorkflows,
762
- (manifest.capabilities.abrigo?.read.length ?? 0) > 0,
763
- receivesLatticeContext,
764
- manifest.capabilities.invocation?.identity === true,
765
- (manifest.capabilities.directory?.resolve?.length ?? 0) > 0,
766
- (manifest.capabilities.monitoring?.producers.length ?? 0) > 0,
767
- ].includes(true),
787
+ requirements,
788
+ acceptsServiceAccount: requirements.length > 0 || reachedData.length > 0,
768
789
  serviceAccount: manifest.service_account,
769
790
  ctx,
770
791
  });
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Deploy-time guidance for a Managed Function that needs a service account and
3
+ * names none. The manifest schema refuses it offline with a generic message;
4
+ * `functions deploy` can reach Atlas, so it also says whether this caller may
5
+ * create an account and which accounts they can already attach — the same
6
+ * facts `seq-studio service-accounts list` shows. Mirrors the server's refusal
7
+ * (atlas/src/server/services/managed-functions/service-account-guidance.ts).
8
+ */
9
+ import { type ClientOptions } from '../atlas-client.js';
10
+ /** The requirements carried by the manifest schema's missing-account issue, or null for any other error. */
11
+ export declare function missingServiceAccountRequirements(error: unknown): string[] | null;
12
+ export declare function formatMissingServiceAccount({ requirements, canCreate, attachable }: {
13
+ requirements: readonly string[];
14
+ canCreate: boolean;
15
+ attachable: readonly string[];
16
+ }): string;
17
+ /** Null when Atlas cannot answer; the caller then falls back to the schema's message. */
18
+ export declare function missingServiceAccountGuidance({ client, requirements }: {
19
+ client: ClientOptions;
20
+ requirements: readonly string[];
21
+ }): Promise<string | null>;