@prisma/cli-engine 0.0.2 → 0.0.3

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.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as TokenStorage, A as OpenUrlRequest, B as EngineEvent, C as LoadedConfig, D as BrowserWaitRequest, E as Runtime, F as PRESENTED, G as Credential, H as StreamEvent, I as Presentations, J as CredentialOrigin, K as CredentialIdentity, L as PresentedResult, M as Block, N as Format, O as CommandContext, P as Outcome, Q as ManagementApiClientConfig, R as TreeNode, S as InputStream, T as PRISMA_CONFIG_VERSION, U as StreamMeta, V as Severity, W as ActiveCredential, X as StoredSessions, Y as Session, Z as ManagementApiClient, _ as SessionCommandDefinition, a as defineCommandFamily, at as Char, b as defineSessionCommand, c as CommandHandler, ct as PositionalSpec, d as CompletedEnvelope, et as ConfigSection, f as ErroredEnvelope, g as ServerCommandDefinition, h as NeedsSpec, i as MountedTree, it as ArgsSpec, j as PromptSurface, k as OpenUrlOutcome, l as CommandHelp, lt as flag, m as HelpSpec, n as RunSummary, nt as defineConfigSection, o as AnyCommand, ot as CommandArgs, p as Handler, q as CredentialManager, r as CommandFamily, rt as Args, s as CommandDefinition, st as FlagSpec, t as EngineCommandSnapshot, tt as SectionValidation, u as CommandNeeds, ut as positional, v as defineCommand, w as OutputStream, x as HostProcess, y as defineServerCommand, z as Ui } from "./run-summary-CZITSYO_.js";
1
+ import { $ as ActiveCredential, A as OpenUrlOutcome, B as exitWithChildStatus, C as InputStream, D as Runtime, E as PRISMA_CONFIG_VERSION, F as ExitWithChildStatusOptions, G as Presentations, H as Format, I as SpawnChild, J as Ui, K as PresentedResult, L as SpawnOptions, M as PromptSurface, N as ChildResult, O as BrowserWaitRequest, P as ChildStatusSettlement, Q as StreamMeta, R as SpawnRequest, S as HostProcess, T as OutputStream, U as Outcome, V as Block, W as PRESENTED, X as Severity, Y as EngineEvent, Z as StreamEvent, _ as SessionCommandDefinition, _t as PositionalSpec, a as defineCommandFamily, at as StoredSessions, b as defineServerCommand, c as CommandHandler, ct as TokenStorage, d as CompletedEnvelope, dt as defineConfigSection, et as Credential, f as ErroredEnvelope, ft as Args, g as ServerCommandDefinition, gt as FlagSpec, h as NeedsSpec, ht as CommandArgs, i as MountedTree, it as Session, j as OpenUrlRequest, k as CommandContext, l as CommandHelp, lt as ConfigSection, m as HelpSpec, mt as Char, n as RunSummary, nt as CredentialManager, o as AnyCommand, ot as ManagementApiClient, p as Handler, pt as ArgsSpec, q as TreeNode, r as CommandFamily, rt as CredentialOrigin, s as CommandDefinition, st as ManagementApiClientConfig, t as EngineCommandSnapshot, tt as CredentialIdentity, u as CommandNeeds, ut as SectionValidation, v as SpawnDeclarations, vt as flag, w as LoadedConfig, x as defineSessionCommand, y as defineCommand, yt as positional, z as SpawnedChild } from "./run-summary-DMFNIvjx.js";
2
2
  import { n as CliStructuredError } from "./protocol-CpZLdxML.js";
3
3
 
4
4
  //#region src/cli.d.ts
@@ -56,11 +56,11 @@ declare function defineConfig<T extends Record<string, unknown>>(config: T): T &
56
56
  declare function loadConfig(cwd: string): Promise<LoadedConfig>;
57
57
  //#endregion
58
58
  //#region src/credential-errors.d.ts
59
- type CredentialsRequiredReason = "unauthenticated" | "expired" | "session-ended" | "sessions-held-none-selected";
59
+ type CredentialsRequiredReason = "unauthenticated" | "expired" | "expiring-soon" | "session-ended" | "sessions-held-none-selected";
60
60
  /**
61
61
  * The single constructor of CLI.CREDENTIALS_REQUIRED. Raised
62
- * identically by the needs check, ctx.session, and the engine's
63
- * request path.
62
+ * identically by the needs check, ctx.activeCredential, and the
63
+ * engine's request path.
64
64
  */
65
65
  declare function credentialsRequiredError(reason?: CredentialsRequiredReason): CliStructuredError;
66
66
  /**
@@ -75,10 +75,17 @@ declare function authServiceError(): CliStructuredError;
75
75
  * nothing else compares against `origin.source`.
76
76
  */
77
77
  declare function credentialRejectedError(origin: CredentialOrigin, envVar: string): CliStructuredError;
78
+ /**
79
+ * A credential's workspace_id claim disagrees with the workspace it is
80
+ * being stored under, or a rotated token would re-scope a session.
81
+ * Raised by every CredentialManager, so a test sees what production
82
+ * raises.
83
+ */
84
+ declare function credentialWorkspaceMismatchError(workspaceId: string): CliStructuredError;
78
85
  /**
79
86
  * The env var that supplies a session is set to a blank value. The one
80
- * structured error for it, raised identically by currentSession(), the
81
- * needs check, and the engine's request path.
87
+ * structured error for it, raised identically by activeCredential(),
88
+ * the needs check, and the engine's request path.
82
89
  */
83
90
  declare function emptyServiceTokenError(spec: {
84
91
  readonly envVar: string;
@@ -89,12 +96,37 @@ declare function emptyServiceTokenError(spec: {
89
96
  * you have.
90
97
  */
91
98
  declare function noSessionForWorkspaceError(workspaceRef: string): CliStructuredError;
99
+ //#endregion
100
+ //#region src/environment-credential-manager.d.ts
101
+ declare class EnvironmentCredentialManager implements CredentialManager {
102
+ #private;
103
+ constructor(spec: {
104
+ readonly env: Readonly<Record<string, string | undefined>>;
105
+ });
106
+ activeCredential(): Promise<ActiveCredential | null>;
107
+ sessions(): Promise<StoredSessions>;
108
+ createSession(_credential: Credential, _workspaceId: string): Promise<Session>;
109
+ selectSession(_workspaceId: string): Promise<Session>;
110
+ endSession(_workspaceId: string): Promise<void>;
111
+ endAllSessions(): Promise<void>;
112
+ activeCredentialStorage(): Promise<TokenStorage>;
113
+ /** The spawn path's read: the env token passes through directly. It
114
+ * is already a snapshot with no refresh token behind it. */
115
+ activeAccessToken(): Promise<string | null>;
116
+ }
117
+ //#endregion
118
+ //#region src/token-claims.d.ts
119
+ /** The `workspace_id` claim, which is what sessions are keyed by. */
120
+ declare function claimedWorkspaceId(token: string): string | undefined;
121
+ /** The workspace a credential names: its `workspace_id` claim, or the
122
+ * workspace its subject names when it is a service token. */
123
+ declare function credentialWorkspaceId(token: string): string | undefined;
124
+ declare function claimedExpiresAt(token: string): Date | undefined;
92
125
  /**
93
- * The management API rejected the env-supplied service token (401).
94
- * There is no refresh for it and nothing stored is cleared.
126
+ * Who a credential belongs to, from its own claims. A service token's
127
+ * subject names a workspace rather than a person, so it yields no user
128
+ * — reporting `workspace:ws_1` as a user id was a real defect.
95
129
  */
96
- declare function serviceTokenRejectedError(spec: {
97
- readonly envVar: string;
98
- }): CliStructuredError;
130
+ declare function claimedIdentity(token: string): CredentialIdentity | undefined;
99
131
  //#endregion
100
- export { type ActiveCredential, type AnyCommand, type Args, type ArgsSpec, type Block, type BrowserWaitRequest, type Char, type Cli, type CliRunHooks, type CommandArgs, type CommandContext, type CommandDefinition, type CommandFamily, type CommandHandler, type CommandHelp, type CommandNeeds, type CompletedEnvelope, type ConfigSection, type Credential, type CredentialIdentity, type CredentialManager, type CredentialOrigin, type CredentialsRequiredReason, type EngineCommandSnapshot, type EngineEvent, type ErroredEnvelope, type FlagSpec, type Format, type Handler, type HelpSpec, type HostProcess, type InputStream, type LoadedConfig, type ManagementApiClient, type ManagementApiClientConfig, type MountedTree, type NeedsSpec, type OpenUrlOutcome, type OpenUrlRequest, type Outcome, type OutputStream, PRESENTED, PRISMA_CONFIG_VERSION, type PositionalSpec, type Presentations, type PresentedResult, type PromptSurface, type RunSummary, type Runtime, type SectionValidation, type ServerCommandDefinition, type Session, type SessionCommandDefinition, type Severity, type StoredSessions, type StreamEvent, type StreamMeta, type TokenStorage, type TreeNode, type Ui, authServiceError, createCli, credentialRejectedError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, defineServerCommand, defineSessionCommand, emptyServiceTokenError, flag, loadConfig, noSessionForWorkspaceError, positional, serviceTokenRejectedError };
132
+ export { type ActiveCredential, type AnyCommand, type Args, type ArgsSpec, type Block, type BrowserWaitRequest, type Char, type ChildResult, type ChildStatusSettlement, type Cli, type CliRunHooks, type CommandArgs, type CommandContext, type CommandDefinition, type CommandFamily, type CommandHandler, type CommandHelp, type CommandNeeds, type CompletedEnvelope, type ConfigSection, type Credential, type CredentialIdentity, type CredentialManager, type CredentialOrigin, type CredentialsRequiredReason, type EngineCommandSnapshot, type EngineEvent, EnvironmentCredentialManager, type ErroredEnvelope, type ExitWithChildStatusOptions, type FlagSpec, type Format, type Handler, type HelpSpec, type HostProcess, type InputStream, type LoadedConfig, type ManagementApiClient, type ManagementApiClientConfig, type MountedTree, type NeedsSpec, type OpenUrlOutcome, type OpenUrlRequest, type Outcome, type OutputStream, PRESENTED, PRISMA_CONFIG_VERSION, type PositionalSpec, type Presentations, type PresentedResult, type PromptSurface, type RunSummary, type Runtime, type SectionValidation, type ServerCommandDefinition, type Session, type SessionCommandDefinition, type Severity, type SpawnChild, type SpawnDeclarations, type SpawnOptions, type SpawnRequest, type SpawnedChild, type StoredSessions, type StreamEvent, type StreamMeta, type TokenStorage, type TreeNode, type Ui, authServiceError, claimedExpiresAt, claimedIdentity, claimedWorkspaceId, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, defineServerCommand, defineSessionCommand, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional };
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { a as emptyServiceTokenError, c as PRESENTED, i as credentialsRequiredError, l as flag, n as authServiceError, o as noSessionForWorkspaceError, r as credentialRejectedError, s as serviceTokenRejectedError, t as buildEngine, u as positional } from "./engine-vF4FiZqo.js";
1
+ import { a as buildEngine, c as credentialWorkspaceMismatchError, d as noSessionForWorkspaceError, f as PRESENTED, h as positional, i as credentialWorkspaceId, l as credentialsRequiredError, m as flag, n as claimedIdentity, o as authServiceError, p as exitWithChildStatus, r as claimedWorkspaceId, s as credentialRejectedError, t as claimedExpiresAt, u as emptyServiceTokenError } from "./token-claims-DXO0q52l.js";
2
+ import { t as CliStructuredError } from "./protocol-C1JQcGl9.js";
2
3
  import { join } from "node:path";
3
4
  import { existsSync } from "node:fs";
4
5
  import { pathToFileURL } from "node:url";
@@ -40,7 +41,7 @@ function normalizeArgs(spec) {
40
41
  function normalizeNeeds(spec) {
41
42
  return Object.freeze({
42
43
  config: spec?.config,
43
- credentials: spec?.credentials === true,
44
+ credentials: spec?.credentials ?? false,
44
45
  dependencies: spec?.dependencies ?? [],
45
46
  interaction: spec?.interaction === true
46
47
  });
@@ -53,6 +54,7 @@ function defineCommand(def) {
53
54
  needs: normalizeNeeds(def.needs),
54
55
  exitCodes: def.exitCodes ?? {},
55
56
  managesCredentials: def.managesCredentials ?? false,
57
+ maySpawn: def.maySpawn ?? false,
56
58
  handler: def.handler
57
59
  });
58
60
  }
@@ -62,6 +64,7 @@ function defineSessionCommand(def) {
62
64
  help: normalizeHelp(def.help),
63
65
  args: normalizeArgs(def.args),
64
66
  needs: normalizeNeeds(def.needs),
67
+ maySpawn: def.maySpawn ?? false,
65
68
  handler: def.handler
66
69
  });
67
70
  }
@@ -71,6 +74,7 @@ function defineServerCommand(def) {
71
74
  help: normalizeHelp(def.help),
72
75
  args: normalizeArgs(def.args),
73
76
  needs: normalizeNeeds(def.needs),
77
+ maySpawn: false,
74
78
  handler: def.handler
75
79
  });
76
80
  }
@@ -198,4 +202,117 @@ function defineConfigSection(spec) {
198
202
  });
199
203
  }
200
204
  //#endregion
201
- export { PRESENTED, PRISMA_CONFIG_VERSION, authServiceError, createCli, credentialRejectedError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, defineServerCommand, defineSessionCommand, emptyServiceTokenError, flag, loadConfig, noSessionForWorkspaceError, positional, serviceTokenRejectedError };
205
+ //#region src/environment-credential-manager.ts
206
+ /**
207
+ * The production, environment-only CredentialManager (S3, R-S3-1): for
208
+ * hosts whose sole credential source is the inter-process protocol —
209
+ * PRISMA_SERVICE_TOKEN plus PRISMA_WORKSPACE_ID — such as composer's
210
+ * rebuilt CLI. It holds no stored sessions and cannot: every mutation
211
+ * refuses with a structured error. Env is a construction input; nothing
212
+ * here reads process.env.
213
+ */
214
+ const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
215
+ const WORKSPACE_ID_ENV_VAR = "PRISMA_WORKSPACE_ID";
216
+ /** The SDK's Tokens requires a workspace id; an environment credential
217
+ * that names none is given this instead. It never leaves the manager
218
+ * and is never the empty string. */
219
+ const NO_WORKSPACE_NAMED = "(no workspace)";
220
+ function sessionsUnsupportedError() {
221
+ return new CliStructuredError("AUTH.SESSIONS_UNSUPPORTED", "This host manages no stored workspace sessions.", {
222
+ why: `Its credentials come only from ${SERVICE_TOKEN_ENV_VAR} (and ${WORKSPACE_ID_ENV_VAR}); there is nothing to create, select, or end.`,
223
+ nextActions: [{
224
+ kind: "user-choice",
225
+ label: `Set or change ${SERVICE_TOKEN_ENV_VAR} in the environment instead.`
226
+ }]
227
+ });
228
+ }
229
+ var EnvironmentCredentialManager = class {
230
+ #env;
231
+ #refreshLock = Promise.resolve();
232
+ #activeStorage;
233
+ constructor(spec) {
234
+ this.#env = spec.env;
235
+ }
236
+ async activeCredential() {
237
+ const token = this.#token();
238
+ if (token === void 0) return null;
239
+ return {
240
+ workspaceId: this.#workspaceId(token),
241
+ workspaceName: void 0,
242
+ expiresAt: claimedExpiresAt(token),
243
+ identity: claimedIdentity(token),
244
+ origin: { source: "environment" }
245
+ };
246
+ }
247
+ async sessions() {
248
+ return {
249
+ sessions: [],
250
+ selectedWorkspaceId: void 0
251
+ };
252
+ }
253
+ async createSession(_credential, _workspaceId) {
254
+ throw sessionsUnsupportedError();
255
+ }
256
+ async selectSession(_workspaceId) {
257
+ throw sessionsUnsupportedError();
258
+ }
259
+ async endSession(_workspaceId) {
260
+ throw sessionsUnsupportedError();
261
+ }
262
+ async endAllSessions() {
263
+ throw sessionsUnsupportedError();
264
+ }
265
+ async activeCredentialStorage() {
266
+ this.#activeStorage ??= this.#buildActiveStorage();
267
+ return this.#activeStorage;
268
+ }
269
+ /** The spawn path's read: the env token passes through directly. It
270
+ * is already a snapshot with no refresh token behind it. */
271
+ async activeAccessToken() {
272
+ return this.#token() ?? null;
273
+ }
274
+ #buildActiveStorage() {
275
+ const token = this.#token();
276
+ if (token === void 0) throw new Error("@prisma/cli-engine: activeCredentialStorage() is only valid once activeCredential() has returned non-null");
277
+ let tokens = {
278
+ workspaceId: this.#workspaceId(token) ?? NO_WORKSPACE_NAMED,
279
+ accessToken: token,
280
+ refreshToken: void 0
281
+ };
282
+ const singleFlight = (fn) => {
283
+ const queued = this.#refreshLock.then(fn, fn);
284
+ this.#refreshLock = queued.then(() => void 0, () => void 0);
285
+ return queued;
286
+ };
287
+ return {
288
+ getTokens: async () => tokens,
289
+ setTokens: async (rotated) => {
290
+ tokens = rotated;
291
+ },
292
+ clearTokens: async () => {
293
+ tokens = null;
294
+ },
295
+ withRefreshLock: (fn) => singleFlight(fn)
296
+ };
297
+ }
298
+ /** The raw variable, resolved fresh on every read. Unset or missing
299
+ * means no credential; set-but-blank is the structured error state
300
+ * (a blank token authenticates nothing and would silently shadow
301
+ * nothing here — surface it). */
302
+ #token() {
303
+ const raw = this.#env[SERVICE_TOKEN_ENV_VAR];
304
+ if (raw === void 0) return;
305
+ if (raw.trim() === "") throw emptyServiceTokenError({ envVar: SERVICE_TOKEN_ENV_VAR });
306
+ return raw;
307
+ }
308
+ /** The credential's workspace: its own claims first (the token is
309
+ * authoritative about itself), the companion variable otherwise. */
310
+ #workspaceId(token) {
311
+ const claimed = credentialWorkspaceId(token);
312
+ if (claimed !== void 0) return claimed;
313
+ const fromEnv = this.#env[WORKSPACE_ID_ENV_VAR]?.trim();
314
+ return fromEnv === void 0 || fromEnv === "" ? void 0 : fromEnv;
315
+ }
316
+ };
317
+ //#endregion
318
+ export { EnvironmentCredentialManager, PRESENTED, PRISMA_CONFIG_VERSION, authServiceError, claimedExpiresAt, claimedIdentity, claimedWorkspaceId, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, defineServerCommand, defineSessionCommand, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional };
@@ -267,8 +267,22 @@ interface CredentialManager {
267
267
  * already ruled there is one credential per process, and an
268
268
  * environment credential may have no workspace id to key on. Only
269
269
  * valid once `activeCredential()` has returned non-null.
270
+ *
271
+ * The engine forwards the storage into SDK client config and never
272
+ * calls its methods itself — no exceptions. The engine's own read of
273
+ * token material goes through `activeAccessToken()`.
270
274
  */
271
275
  activeCredentialStorage(): Promise<TokenStorage$1>;
276
+ /**
277
+ * ENGINE-FACING. The active credential's ACCESS token, read fresh on
278
+ * every call, for handing to a child process that authenticates as
279
+ * this process does. Never the refresh token: the child gets a
280
+ * snapshot it cannot refresh. Null when the material is gone (the
281
+ * session ended). Single consumer: ctx.spawn's credential injection
282
+ * (credential-manager-design.md §11.5) — the read builds no second
283
+ * API client, so the one-client-per-process invariant holds.
284
+ */
285
+ activeAccessToken(): Promise<string | null>;
272
286
  }
273
287
  //#endregion
274
288
  //#region src/events.d.ts
@@ -459,6 +473,71 @@ interface Ui {
459
473
  readonly code: (text: string) => string;
460
474
  }
461
475
  //#endregion
476
+ //#region src/spawn.d.ts
477
+ /** A fully composed child invocation. `env` is the child's COMPLETE
478
+ * environment: the engine has already merged the invocation
479
+ * environment, the handler's additions, and the credential variables. */
480
+ interface SpawnRequest {
481
+ readonly command: string;
482
+ readonly args: readonly string[];
483
+ readonly cwd: string;
484
+ readonly env: Readonly<Record<string, string | undefined>>;
485
+ }
486
+ /** How a child ended. A signal-killed child carries `signal` and a null
487
+ * `exitCode`; handlers branch on `signal` first — a signal-killed child
488
+ * is an abort, not a failure. */
489
+ interface ChildResult {
490
+ readonly exitCode: number | null;
491
+ readonly signal: string | null;
492
+ }
493
+ /** The live child an adapter returns. */
494
+ interface SpawnedChild {
495
+ /** Resolves when the child ends. Rejects when it could not be
496
+ * launched at all; the engine phrases that as CLI.SPAWN_FAILED. */
497
+ readonly ended: Promise<ChildResult>;
498
+ readonly kill: (signal: "SIGTERM" | "SIGKILL") => void;
499
+ }
500
+ /**
501
+ * The Runtime seam. The adapter starts the child with INHERITED stdio,
502
+ * in the caller's own process group (POSIX) / console (Windows) — no
503
+ * `detached`, no new console — so the terminal delivers Ctrl-C to the
504
+ * child natively.
505
+ */
506
+ type SpawnChild = (request: SpawnRequest) => SpawnedChild;
507
+ /** What a handler passes to ctx.spawn. */
508
+ interface SpawnOptions {
509
+ readonly command: string;
510
+ readonly args?: readonly string[];
511
+ /** Defaults to ctx.cwd. */
512
+ readonly cwd?: string;
513
+ /** Added to, and overriding, the invocation environment. The engine's
514
+ * credential variables are applied last and cannot be overridden. */
515
+ readonly env?: Readonly<Record<string, string | undefined>>;
516
+ }
517
+ declare const CHILD_STATUS: unique symbol;
518
+ /**
519
+ * The sanctioned settlement outcome for "exit with the child's status
520
+ * verbatim": no envelope, the same settlement bypass server commands
521
+ * use. Built exclusively by exitWithChildStatus, and only settled by a
522
+ * command that declares maySpawn. `nextActions` render to stderr before
523
+ * the process exits with the child's code.
524
+ */
525
+ interface ChildStatusSettlement {
526
+ readonly [CHILD_STATUS]: true;
527
+ readonly exitCode: number;
528
+ readonly nextActions: readonly NextAction[];
529
+ }
530
+ interface ExitWithChildStatusOptions {
531
+ /** Engine-styled guidance printed to stderr before the exit — a
532
+ * failed converge's reproduce hint. The envelope stays absent. */
533
+ readonly nextActions?: readonly NextAction[];
534
+ }
535
+ /** A signal-killed child settles 128 + the signal number; otherwise the
536
+ * child's own exit code, verbatim. Unknown is never success: a signal
537
+ * outside the portable table, or an adapter that cannot say how the
538
+ * child ended (exitCode and signal both null), settles 1. */
539
+ declare function exitWithChildStatus(child: ChildResult, options?: ExitWithChildStatusOptions): ChildStatusSettlement;
540
+ //#endregion
462
541
  //#region src/context.d.ts
463
542
  /** The handler context — the whole world arrives as one argument. */
464
543
  interface CommandContext<TConfig = undefined, TCode extends number = never> {
@@ -490,6 +569,28 @@ interface CommandContext<TConfig = undefined, TCode extends number = never> {
490
569
  * needs.credentials check uses).
491
570
  */
492
571
  readonly api: ManagementApiClient$1;
572
+ /**
573
+ * Hands the terminal to a child process and resolves when it ends.
574
+ * The child inherits stdio and runs in this process's own group
575
+ * (POSIX) or console (Windows), so Ctrl-C reaches it natively.
576
+ *
577
+ * While a child is live the engine neither aborts nor exits on a
578
+ * delivered signal: it records signals and replays them into its
579
+ * normal ladder once the child has ended, so the engine always
580
+ * outlives the child. SIGTERM, which has no native path to the child,
581
+ * is forwarded to it. A programmatic abort of ctx.signal terminates
582
+ * the child with SIGTERM, a grace period, then SIGKILL.
583
+ *
584
+ * ctx.report is buffered for the duration and flushed in order when
585
+ * the child ends; ctx.present during a live child, and a second
586
+ * concurrent ctx.spawn, are engine-internal errors. A launch failure
587
+ * (no such command) throws CLI.SPAWN_FAILED.
588
+ *
589
+ * Only commands declaring `maySpawn` may call it. Branch on `signal`
590
+ * before `exitCode`: a signal-killed child is an abort, not a
591
+ * failure.
592
+ */
593
+ readonly spawn: (options: SpawnOptions) => Promise<ChildResult>;
493
594
  /** The one way to emit while running. */
494
595
  readonly report: (event: EngineEvent) => void;
495
596
  /** Interactive input. */
@@ -676,6 +777,14 @@ interface Runtime {
676
777
  * announces the URL instead.
677
778
  */
678
779
  readonly openUrl?: (url: string) => Promise<void> | void;
780
+ /**
781
+ * Starts a child process with inherited stdio, wired by the bin (a
782
+ * node:child_process adapter) so the engine never imports it. Absent
783
+ * means this host cannot hand the terminal to a child: a maySpawn
784
+ * command is refused as an internal error before its needs check and
785
+ * handler run, so ctx.spawn is never reached.
786
+ */
787
+ readonly spawn?: SpawnChild;
679
788
  /** Management API endpoint config; the bin derives baseUrl from env. */
680
789
  readonly managementApi: {
681
790
  readonly baseUrl: string;
@@ -775,8 +884,17 @@ interface NeedsSpec<TConfig> {
775
884
  * its error diagnostics, hand me the value as ctx.config.
776
885
  */
777
886
  readonly config?: ConfigSection<TConfig>;
778
- /** Fail early with the sign-in error when unauthenticated. */
779
- readonly credentials?: true;
887
+ /**
888
+ * Fail early with the sign-in error when unauthenticated. The
889
+ * `"child"` form (S3) additionally makes the engine compose the
890
+ * active credential into every child environment
891
+ * (PRISMA_SERVICE_TOKEN, PRISMA_WORKSPACE_ID) and refuse the run
892
+ * before the handler when that credential expires too soon to hand
893
+ * out — a child cannot refresh the snapshot it is given. It
894
+ * requires `maySpawn` (construction error otherwise) and entails
895
+ * the plain credentials need.
896
+ */
897
+ readonly credentials?: true | "child";
780
898
  /**
781
899
  * Optional peer dependencies this command cannot run without; the
782
900
  * engine probes resolvability and phrases the install error.
@@ -797,10 +915,23 @@ interface NeedsSpec<TConfig> {
797
915
  /** The normalized preconditions a definition carries. */
798
916
  interface CommandNeeds<TConfig> {
799
917
  readonly config: ConfigSection<TConfig> | undefined;
800
- readonly credentials: boolean;
918
+ readonly credentials: boolean | "child";
801
919
  readonly dependencies: readonly string[];
802
920
  readonly interaction: boolean;
803
921
  }
922
+ /**
923
+ * The terminal-handoff declaration, normalized onto every definition
924
+ * (server commands normalize to false: they own stdio already).
925
+ *
926
+ * `maySpawn` unlocks ctx.spawn and makes the command reject `--json`
927
+ * as soon as the command is known, before anything runs: output
928
+ * delegated to a child process cannot be framed. Handing credentials
929
+ * to the child is a precondition, declared as
930
+ * `needs: { credentials: "child" }`.
931
+ */
932
+ interface SpawnDeclarations {
933
+ readonly maySpawn?: boolean;
934
+ }
804
935
  interface CommandDefinition<TFlags extends Record<string, FlagSpec<unknown>> = Record<never, FlagSpec<unknown>>, TPositionals extends Record<string, PositionalSpec<unknown>> = Record<never, PositionalSpec<unknown>>, TConfig = undefined, TCode extends number = never, TManagesCredentials extends boolean = false> {
805
936
  readonly kind: "result-command";
806
937
  readonly help: CommandHelp;
@@ -821,6 +952,8 @@ interface CommandDefinition<TFlags extends Record<string, FlagSpec<unknown>> = R
821
952
  * machinery.
822
953
  */
823
954
  readonly managesCredentials: TManagesCredentials;
955
+ /** See SpawnDeclarations. */
956
+ readonly maySpawn: boolean;
824
957
  /**
825
958
  * The handler function, referenced directly — never a dynamic import
826
959
  * (operator ruling, 2026-08-09). A handler that needs heavy
@@ -832,7 +965,7 @@ interface CommandDefinition<TFlags extends Record<string, FlagSpec<unknown>> = R
832
965
  }
833
966
  type Handler<TFlags extends Record<string, FlagSpec<unknown>>, TPositionals extends Record<string, PositionalSpec<unknown>>, TConfig, TCode extends number = never, TManagesCredentials extends boolean = false> = (args: Args<TFlags, TPositionals>, ctx: CommandContext<TConfig, TCode> & (TManagesCredentials extends true ? {
834
967
  readonly credentialManager: CredentialManager;
835
- } : unknown)) => Promise<Result<PresentedResult<unknown>, CliStructuredError>>;
968
+ } : unknown)) => Promise<Result<PresentedResult<unknown> | ChildStatusSettlement, CliStructuredError>>;
836
969
  /** For impl files: `const run: CommandHandler<typeof migrateCommand> = …` */
837
970
  type CommandHandler<D> = D extends CommandDefinition<infer F, infer P, infer C, infer K, infer M> ? Handler<F, P, C, K, M> : never;
838
971
  declare function defineCommand<TFlags extends Record<string, FlagSpec<unknown>> = Record<never, FlagSpec<unknown>>, TPositionals extends Record<string, PositionalSpec<unknown>> = Record<never, PositionalSpec<unknown>>, TConfig = undefined, TCode extends number = never>(def: {
@@ -842,33 +975,42 @@ declare function defineCommand<TFlags extends Record<string, FlagSpec<unknown>>
842
975
  readonly exitCodes?: Readonly<Record<TCode, string>>;
843
976
  readonly managesCredentials: true;
844
977
  readonly handler: Handler<TFlags, TPositionals, TConfig, TCode, true>;
845
- }): CommandDefinition<TFlags, TPositionals, TConfig, TCode, true>;
978
+ } & SpawnDeclarations): CommandDefinition<TFlags, TPositionals, TConfig, TCode, true>;
846
979
  declare function defineCommand<TFlags extends Record<string, FlagSpec<unknown>> = Record<never, FlagSpec<unknown>>, TPositionals extends Record<string, PositionalSpec<unknown>> = Record<never, PositionalSpec<unknown>>, TConfig = undefined, TCode extends number = never>(def: {
847
980
  readonly help: HelpSpec;
848
981
  readonly args?: ArgsSpec<TFlags, TPositionals>;
849
982
  readonly needs?: NeedsSpec<TConfig>;
850
983
  readonly exitCodes?: Readonly<Record<TCode, string>>;
851
984
  readonly handler: Handler<TFlags, TPositionals, TConfig, TCode>;
852
- }): CommandDefinition<TFlags, TPositionals, TConfig, TCode>;
985
+ } & SpawnDeclarations): CommandDefinition<TFlags, TPositionals, TConfig, TCode>;
853
986
  /**
854
987
  * A session command (dev, log tail): runs until the signal fires,
855
988
  * speaks entirely through events, returns Result<void>. No
856
- * presentation, no exit-code set. A session always supports json mode:
857
- * the event stream is its json surface.
989
+ * presentation, no exit-code set.
990
+ *
991
+ * A session supports json mode — the event stream is its json surface —
992
+ * UNLESS it declares `maySpawn`, in which case it rejects --json as soon
993
+ * as the command is known, before anything runs (S3): output delegated
994
+ * to a child process cannot be framed. A session that returns
995
+ * ok(undefined) exits 0; one that returns ok(exitWithChildStatus(child))
996
+ * exits with the child's status, which is the only way a session
997
+ * settles non-zero without erroring.
858
998
  */
859
999
  interface SessionCommandDefinition<TFlags extends Record<string, FlagSpec<unknown>> = Record<never, FlagSpec<unknown>>, TPositionals extends Record<string, PositionalSpec<unknown>> = Record<never, PositionalSpec<unknown>>, TConfig = undefined> {
860
1000
  readonly kind: "session-command";
861
1001
  readonly help: CommandHelp;
862
1002
  readonly args: CommandArgs<TFlags, TPositionals>;
863
1003
  readonly needs: CommandNeeds<TConfig>;
864
- readonly handler: (args: Args<TFlags, TPositionals>, ctx: CommandContext<TConfig>) => Promise<Result<void, CliStructuredError>>;
1004
+ /** See SpawnDeclarations. */
1005
+ readonly maySpawn: boolean;
1006
+ readonly handler: (args: Args<TFlags, TPositionals>, ctx: CommandContext<TConfig>) => Promise<Result<undefined | ChildStatusSettlement, CliStructuredError>>;
865
1007
  }
866
1008
  declare function defineSessionCommand<TFlags extends Record<string, FlagSpec<unknown>> = Record<never, FlagSpec<unknown>>, TPositionals extends Record<string, PositionalSpec<unknown>> = Record<never, PositionalSpec<unknown>>, TConfig = undefined>(def: {
867
1009
  readonly help: HelpSpec;
868
1010
  readonly args?: ArgsSpec<TFlags, TPositionals>;
869
1011
  readonly needs?: NeedsSpec<TConfig>;
870
1012
  readonly handler: SessionCommandDefinition<TFlags, TPositionals, TConfig>["handler"];
871
- }): SessionCommandDefinition<TFlags, TPositionals, TConfig>;
1013
+ } & SpawnDeclarations): SessionCommandDefinition<TFlags, TPositionals, TConfig>;
872
1014
  /**
873
1015
  * A server command (lsp): a foreign client on the other end of stdio
874
1016
  * owns the conversation, so the engine hands over the streams. Events,
@@ -880,6 +1022,9 @@ interface ServerCommandDefinition<TFlags extends Record<string, FlagSpec<unknown
880
1022
  readonly help: CommandHelp;
881
1023
  readonly args: CommandArgs<TFlags, Record<never, PositionalSpec<unknown>>>;
882
1024
  readonly needs: CommandNeeds<TConfig>;
1025
+ /** Always false — a server command owns stdio already. Normalized so
1026
+ * every definition carries the field and callers read it directly. */
1027
+ readonly maySpawn: false;
883
1028
  readonly handler: (args: Args<TFlags, Record<never, PositionalSpec<unknown>>>, io: {
884
1029
  readonly stdin: InputStream;
885
1030
  readonly stdout: OutputStream;
@@ -1019,4 +1164,4 @@ interface RunSummary {
1019
1164
  readonly snapshot: EngineCommandSnapshot;
1020
1165
  }
1021
1166
  //#endregion
1022
- export { TokenStorage$1 as $, OpenUrlRequest as A, EngineEvent as B, LoadedConfig as C, BrowserWaitRequest as D, Runtime as E, PRESENTED as F, Credential as G, StreamEvent as H, Presentations as I, CredentialOrigin as J, CredentialIdentity as K, PresentedResult as L, Block as M, Format as N, CommandContext as O, Outcome as P, ManagementApiClientConfig as Q, TreeNode as R, InputStream as S, PRISMA_CONFIG_VERSION as T, StreamMeta as U, Severity as V, ActiveCredential as W, StoredSessions as X, Session as Y, ManagementApiClient$1 as Z, SessionCommandDefinition as _, defineCommandFamily as a, Char as at, defineSessionCommand as b, CommandHandler as c, PositionalSpec as ct, CompletedEnvelope as d, ConfigSection as et, ErroredEnvelope as f, ServerCommandDefinition as g, NeedsSpec as h, MountedTree as i, ArgsSpec as it, PromptSurface as j, OpenUrlOutcome as k, CommandHelp as l, flag as lt, HelpSpec as m, RunSummary as n, defineConfigSection as nt, AnyCommand as o, CommandArgs as ot, Handler as p, CredentialManager as q, CommandFamily as r, Args as rt, CommandDefinition as s, FlagSpec as st, EngineCommandSnapshot as t, SectionValidation as tt, CommandNeeds as u, positional as ut, defineCommand as v, OutputStream as w, HostProcess as x, defineServerCommand as y, Ui as z };
1167
+ export { ActiveCredential as $, OpenUrlOutcome as A, exitWithChildStatus as B, InputStream as C, Runtime as D, PRISMA_CONFIG_VERSION as E, ExitWithChildStatusOptions as F, Presentations as G, Format as H, SpawnChild as I, Ui as J, PresentedResult as K, SpawnOptions as L, PromptSurface as M, ChildResult as N, BrowserWaitRequest as O, ChildStatusSettlement as P, StreamMeta as Q, SpawnRequest as R, HostProcess as S, OutputStream as T, Outcome as U, Block as V, PRESENTED as W, Severity as X, EngineEvent as Y, StreamEvent as Z, SessionCommandDefinition as _, PositionalSpec as _t, defineCommandFamily as a, StoredSessions as at, defineServerCommand as b, CommandHandler as c, TokenStorage$1 as ct, CompletedEnvelope as d, defineConfigSection as dt, Credential as et, ErroredEnvelope as f, Args as ft, ServerCommandDefinition as g, FlagSpec as gt, NeedsSpec as h, CommandArgs as ht, MountedTree as i, Session as it, OpenUrlRequest as j, CommandContext as k, CommandHelp as l, ConfigSection as lt, HelpSpec as m, Char as mt, RunSummary as n, CredentialManager as nt, AnyCommand as o, ManagementApiClient$1 as ot, Handler as p, ArgsSpec as pt, TreeNode as q, CommandFamily as r, CredentialOrigin as rt, CommandDefinition as s, ManagementApiClientConfig as st, EngineCommandSnapshot as t, CredentialIdentity as tt, CommandNeeds as u, SectionValidation as ut, SpawnDeclarations as v, flag as vt, LoadedConfig as w, defineSessionCommand as x, defineCommand as y, positional as yt, SpawnedChild as z };
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as TokenStorage, B as EngineEvent, G as Credential, H as StreamEvent, L as PresentedResult, Q as ManagementApiClientConfig, W as ActiveCredential, X as StoredSessions, Y as Session, Z as ManagementApiClient, i as MountedTree, n as RunSummary, q as CredentialManager, r as CommandFamily } from "./run-summary-CZITSYO_.js";
1
+ import { $ as ActiveCredential, I as SpawnChild, K as PresentedResult, N as ChildResult, R as SpawnRequest, Y as EngineEvent, Z as StreamEvent, at as StoredSessions, ct as TokenStorage, et as Credential, i as MountedTree, it as Session, n as RunSummary, nt as CredentialManager, ot as ManagementApiClient, r as CommandFamily, st as ManagementApiClientConfig } from "./run-summary-DMFNIvjx.js";
2
2
 
3
3
  //#region src/in-memory-credential-manager.d.ts
4
4
  /** A stored session with its credential material — what the manager
@@ -40,6 +40,7 @@ declare function mintTestJwt(claims: Readonly<Record<string, unknown>>): string;
40
40
  * own tests.
41
41
  */
42
42
  declare class InMemoryCredentialManager implements CredentialManager {
43
+ #private;
43
44
  private storedSessions;
44
45
  private selection;
45
46
  private readonly environmentCredential;
@@ -60,6 +61,11 @@ declare class InMemoryCredentialManager implements CredentialManager {
60
61
  endSession(workspaceId: string): Promise<void>;
61
62
  endAllSessions(): Promise<void>;
62
63
  activeCredentialStorage(): Promise<TokenStorage>;
64
+ /** The spawn path's read: the active credential's access token,
65
+ * fresh on every call, never the refresh token. Null when there is
66
+ * no active credential to read — storage exists only once
67
+ * activeCredential() has returned non-null. */
68
+ activeAccessToken(): Promise<string | null>;
63
69
  private buildActiveStorage;
64
70
  /** The file-backed storage's analogue: the record is read afresh on
65
71
  * every call, never snapshotted. */
@@ -75,6 +81,25 @@ declare class InMemoryCredentialManager implements CredentialManager {
75
81
  }
76
82
  //#endregion
77
83
  //#region src/testing.d.ts
84
+ /**
85
+ * What a scripted fake child does. `nextKill` resolves with each signal
86
+ * the engine delivers, so a script can model a child that ignores
87
+ * SIGTERM and only dies on SIGKILL.
88
+ */
89
+ type ScriptedChildProgram = (request: SpawnRequest, child: {
90
+ readonly nextKill: () => Promise<"SIGTERM" | "SIGKILL">;
91
+ }) => ChildResult | Promise<ChildResult>;
92
+ /** One ctx.spawn call, as the harness saw it. */
93
+ interface SpawnRecord {
94
+ readonly command: string;
95
+ readonly args: readonly string[];
96
+ readonly cwd: string;
97
+ /** Environment KEYS only. Values are never recorded: a fixture file
98
+ * must not be able to carry token material. */
99
+ readonly envKeys: readonly string[];
100
+ /** The signals the engine delivered to the child, in order. */
101
+ readonly kills: readonly ("SIGTERM" | "SIGKILL")[];
102
+ }
78
103
  interface TestCli {
79
104
  /**
80
105
  * The mutable in-memory credential manager backing the runs — the
@@ -116,7 +141,8 @@ interface TestCli {
116
141
  * The PresentedResult the handler returned, for semantic assertions
117
142
  * without byte-scraping; undefined when the run never presented.
118
143
  */
119
- readonly presented: PresentedResult<unknown> | undefined;
144
+ readonly presented: PresentedResult<unknown> | undefined; /** Every ctx.spawn the run made, in order. */
145
+ readonly spawns: readonly SpawnRecord[];
120
146
  }>;
121
147
  }
122
148
  /**
@@ -163,6 +189,11 @@ declare function createTestCli(spec: {
163
189
  /** Waiting is instant under test whatever this does; pass a spy to
164
190
  * assert the interval a poll loop asked for. */
165
191
  readonly delay?: (ms: number, signal: AbortSignal) => Promise<void>;
192
+ /** The spawn adapter behind ctx.spawn. Defaults to the scripted fake;
193
+ * the real-child tests pass a node:child_process adapter, which is
194
+ * how the engine package itself never imports one. */
195
+ readonly spawn?: SpawnChild; /** Scripts the built-in fake child. Defaults to one that exits 0. */
196
+ readonly spawnScript?: ScriptedChildProgram;
166
197
  }): TestCli;
167
198
  //#endregion
168
- export { InMemoryCredentialManager, type InMemoryCredentialManagerSeed, type InMemoryCredentialManagerState, type SessionRecord, type TestCli, createTestCli, mintTestJwt };
199
+ export { InMemoryCredentialManager, type InMemoryCredentialManagerSeed, type InMemoryCredentialManagerState, type ScriptedChildProgram, type SessionRecord, type SpawnRecord, type TestCli, createTestCli, mintTestJwt };