{
  "version": 3,
  "sources": ["../../src/ActorBuilderCatalog.ts", "../../src/ActorSupervisor.ts", "../../src/CliActorSystem.ts", "../../src/runtimeInterrupt.ts", "../../src/handleRuntimeInterrupt.ts", "../../src/ProcessHost.ts", "../../src/InterruptJoin.ts", "../../src/RuntimeSession.ts", "../../src/cliErrors.ts", "../../src/CommandCatalog.ts", "../../src/createProcessIoLogger.ts", "../../src/sysExits.ts", "../../src/createSysExitFailureMapper.ts", "../../src/formatStartupBanner.ts", "../../src/GlobalErrorEscalation.ts", "../../src/ProcessApplication.ts", "../../src/redactUrlCredentials.ts", "../../src/redactConfig.ts", "../../src/resourceTeardown.ts", "../../src/runServiceUntilInterrupt.ts"],
  "sourcesContent": ["export interface ActorBuilderDefinition<TContext, TActor> {\n  readonly name: string\n  build(context: TContext): Promise<TActor>\n}\n\nexport interface ActorBuilderCatalog<TContext, TActor> {\n  readonly names: readonly string[]\n  build(name: string, context: TContext): Promise<TActor>\n}\n\n/** Creates an ordered, instance-scoped actor builder catalog. */\nexport function createActorBuilderCatalog<TContext, TActor>(\n  definitions: readonly ActorBuilderDefinition<TContext, TActor>[],\n): ActorBuilderCatalog<TContext, TActor> {\n  const definitionsByName = new Map<string, ActorBuilderDefinition<TContext, TActor>>()\n  const names: string[] = []\n  for (const definition of definitions) {\n    if (definitionsByName.has(definition.name)) {\n      throw new Error(`Actor builder \"${definition.name}\" is already registered`)\n    }\n    definitionsByName.set(definition.name, definition)\n    names.push(definition.name)\n  }\n\n  return {\n    names: Object.freeze(names),\n    async build(name: string, context: TContext): Promise<TActor> {\n      const definition = definitionsByName.get(name)\n      if (definition === undefined) throw new Error(`Unknown actor: ${name}`)\n      return await definition.build(context)\n    },\n  }\n}\n", "import type {\n  ManagedActor, ManagedActorLifecycleResult, ReadinessSignal, ReadyState,\n} from './ManagedActor.ts'\n\nexport type ActorSupervisorState = 'failed' | 'idle' | 'started' | 'starting' | 'stopped' | 'stopping'\n\nexport class ActorRegistrationError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = 'ActorRegistrationError'\n  }\n}\n\nexport class ActorSupervisorStateError extends Error {\n  readonly state: ActorSupervisorState\n\n  constructor(operation: string, state: ActorSupervisorState) {\n    super(`Cannot ${operation} while actor supervisor is ${state}`)\n    this.name = 'ActorSupervisorStateError'\n    this.state = state\n  }\n}\n\nexport class ActorStartupError extends Error {\n  readonly actorName: string\n  readonly rollbackErrors: readonly Error[]\n\n  constructor(actorName: string, cause: unknown, rollbackErrors: readonly Error[]) {\n    super(`Actor \"${actorName}\" failed to start`, { cause })\n    this.name = 'ActorStartupError'\n    this.actorName = actorName\n    this.rollbackErrors = rollbackErrors\n  }\n}\n\nexport class ActorReadinessError extends Error {\n  readonly actorName: string\n\n  constructor(actorName: string, cause: unknown) {\n    super(`Actor \"${actorName}\" failed to become ready`, { cause })\n    this.name = 'ActorReadinessError'\n    this.actorName = actorName\n  }\n}\n\nexport class ActorReadinessTimeoutError extends Error {\n  readonly timeoutMs: number\n\n  constructor(timeoutMs: number) {\n    super(`Actors did not become ready within ${timeoutMs}ms`)\n    this.name = 'ActorReadinessTimeoutError'\n    this.timeoutMs = timeoutMs\n  }\n}\n\nexport class ActorShutdownError extends AggregateError {\n  constructor(errors: readonly Error[]) {\n    super(errors, `${errors.length} actor(s) failed to stop`)\n    this.name = 'ActorShutdownError'\n  }\n}\n\ninterface TimerHost {\n  clearTimeout(handle: unknown): void\n  setTimeout(callback: () => void, timeoutMs: number): unknown\n}\n\nfunction asError(error: unknown): Error {\n  return error instanceof Error ? error : new Error(String(error))\n}\n\nfunction assertLifecycleSucceeded(actor: ManagedActor, operation: 'start' | 'stop', result: ManagedActorLifecycleResult): void {\n  if (result === false) {\n    throw new Error(`Actor \"${actor.name}\" ${operation}() reported failure`)\n  }\n}\n\nfunction assertTimeout(timeoutMs: number): void {\n  if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {\n    throw new RangeError('Readiness timeout must be a finite, non-negative number')\n  }\n}\n\nasync function shutdownAfterFailedStart(actor: ManagedActor): Promise<Error | undefined> {\n  const shutdown = actor.shutdown?.bind(actor)\n  if (shutdown === undefined) return undefined\n  try {\n    await shutdown()\n  } catch (error) {\n    return new Error(`Actor \"${actor.name}\" failed to shut down after startup failure`, { cause: asError(error) })\n  }\n}\n\nasync function stopOrShutdownActor(actor: ManagedActor): Promise<void> {\n  let stopError: Error\n  try {\n    const result = await actor.stop()\n    assertLifecycleSucceeded(actor, 'stop', result)\n    return\n  } catch (error) {\n    stopError = new Error(`Actor \"${actor.name}\" failed to stop`, { cause: asError(error) })\n  }\n\n  const shutdown = actor.shutdown?.bind(actor)\n  if (shutdown === undefined) throw stopError\n  try {\n    await shutdown()\n  } catch (error) {\n    const shutdownError = new Error(`Actor \"${actor.name}\" failed to shut down`, { cause: asError(error) })\n    throw new AggregateError(\n      [stopError, shutdownError],\n      `Actor \"${actor.name}\" failed to stop and shut down`,\n      { cause: error },\n    )\n  }\n}\n\nasync function waitWithTimeout(signal: ReadinessSignal, timeoutMs: number): Promise<void> {\n  const timerHost = globalThis as unknown as TimerHost\n  let timeoutHandle: unknown\n  const expired = new Promise<never>((_resolve, reject) => {\n    timeoutHandle = timerHost.setTimeout(() => reject(new ActorReadinessTimeoutError(timeoutMs)), timeoutMs)\n  })\n  try {\n    await Promise.race([signal.whenReady(timeoutMs), expired])\n  } finally {\n    timerHost.clearTimeout(timeoutHandle)\n  }\n}\n\n/**\n * Instance-scoped coordinator for structural managed actors.\n *\n * Startup and readiness follow registration order. Rollback and ordinary shutdown\n * follow reverse startup order. A supervisor is single-use after it has stopped or\n * failed; construct a new instance for a new lifecycle.\n */\nexport class ActorSupervisor implements ReadinessSignal {\n  private readonly _actorNames = new Set<string>()\n  private readonly _actors: ManagedActor[] = []\n  private _readyError?: Error\n  private _startPromise?: Promise<void>\n  private readonly _startedActors: ManagedActor[] = []\n  private _state: ActorSupervisorState = 'idle'\n  private _stopPromise?: Promise<void>\n\n  constructor(actors: readonly ManagedActor[] = []) {\n    for (const actor of actors) this.register(actor)\n  }\n\n  get actors(): readonly ManagedActor[] {\n    return [...this._actors]\n  }\n\n  get readyError(): Error | undefined {\n    return this._readyError ?? this._actors.find(actor => actor.readyState === 'failed')?.readyError\n  }\n\n  get readyState(): ReadyState {\n    if (this._readyError !== undefined || this._state === 'failed' || this._actors.some(actor => actor.readyState === 'failed')) {\n      return 'failed'\n    }\n    return this._state === 'started' && this._actors.every(actor => actor.readyState === 'ready') ? 'ready' : 'pending'\n  }\n\n  get state(): ActorSupervisorState {\n    return this._state\n  }\n\n  isReady(): boolean {\n    return this.readyState === 'ready'\n  }\n\n  register(actor: ManagedActor): void {\n    if (this._state !== 'idle') throw new ActorSupervisorStateError('register an actor', this._state)\n    if (actor.name.trim().length === 0) throw new ActorRegistrationError('Actor name must not be empty')\n    if (this._actorNames.has(actor.name)) {\n      throw new ActorRegistrationError(`Actor \"${actor.name}\" is already registered`)\n    }\n    this._actorNames.add(actor.name)\n    this._actors.push(actor)\n  }\n\n  start(): Promise<void> {\n    if (this._startPromise !== undefined) return this._startPromise\n    if (this._state !== 'idle') return Promise.reject(new ActorSupervisorStateError('start', this._state))\n    this._state = 'starting'\n    this._startPromise = this.startActors()\n    return this._startPromise\n  }\n\n  stop(): Promise<void> {\n    this._stopPromise ??= this.stopActors()\n    return this._stopPromise\n  }\n\n  async whenReady(timeoutMs?: number): Promise<void> {\n    if (timeoutMs !== undefined) assertTimeout(timeoutMs)\n    if (this._state === 'starting' && this._startPromise !== undefined) {\n      await this._startPromise\n    }\n    if (this._state !== 'started') throw new ActorSupervisorStateError('wait for readiness', this._state)\n\n    const startedAt = Date.now()\n    for (const actor of this._actors) {\n      try {\n        if (timeoutMs === undefined) {\n          await actor.whenReady()\n        } else {\n          const elapsed = Date.now() - startedAt\n          const remainingTimeoutMs = timeoutMs - elapsed\n          if (remainingTimeoutMs < 0) throw new ActorReadinessTimeoutError(timeoutMs)\n          await waitWithTimeout(actor, remainingTimeoutMs)\n        }\n      } catch (error) {\n        const readinessError = new ActorReadinessError(actor.name, error)\n        this._readyError = readinessError\n        throw readinessError\n      }\n    }\n  }\n\n  private async startActors(): Promise<void> {\n    for (const actor of this._actors) {\n      try {\n        const result = await actor.start()\n        assertLifecycleSucceeded(actor, 'start', result)\n        this._startedActors.push(actor)\n      } catch (error) {\n        const failedActorShutdownError = await shutdownAfterFailedStart(actor)\n        const rollbackErrors = [\n          ...failedActorShutdownError === undefined ? [] : [failedActorShutdownError],\n          ...await this.stopStartedActors(),\n        ]\n        const startupError = new ActorStartupError(actor.name, error, rollbackErrors)\n        this._readyError = startupError\n        this._state = 'failed'\n        throw startupError\n      }\n    }\n    this._state = 'started'\n  }\n\n  private async stopActors(): Promise<void> {\n    if (this._state === 'starting' && this._startPromise !== undefined) {\n      try {\n        await this._startPromise\n      } catch {\n        // Startup already rolled back every actor that reached started state.\n      }\n    }\n\n    if (this._state === 'stopped') return\n    if (this._state === 'idle' || (this._state === 'failed' && this._startedActors.length === 0)) {\n      this._state = 'stopped'\n      return\n    }\n\n    this._state = 'stopping'\n    const errors = await this.stopStartedActors()\n    this._state = 'stopped'\n    if (errors.length > 0) throw new ActorShutdownError(errors)\n  }\n\n  private async stopStartedActors(): Promise<Error[]> {\n    const errors: Error[] = []\n    while (this._startedActors.length > 0) {\n      const actor = this._startedActors.pop()\n      if (actor === undefined) continue\n      try {\n        await stopOrShutdownActor(actor)\n      } catch (error) {\n        errors.push(asError(error))\n      }\n    }\n    return errors\n  }\n}\n", "import type { RawInstanceLocator } from '@ariestools/actor-model'\nimport type {\n  ActorSystemActor,\n  ActorSystemConfig,\n  ActorSystemProviderDeclaration,\n  ActorSystemProviderDescriptor,\n  ActorSystemSelection,\n  ActorSystemSession,\n  ActorSystemSupervision,\n  LaunchActorSystemOptions,\n  LaunchCompiledActorSystemOptions,\n  ResolvedActorSystemConfig,\n  ResolvedActorSystemProviderPlan,\n} from '@ariestools/actor-system'\nimport {\n  launchActorSystem,\n  launchCompiledActorSystem,\n  sequentialActorSystemSupervision,\n} from '@ariestools/actor-system'\n\nimport {\n  InterruptJoin, type InterruptJoinHost, type InterruptJoinOptions,\n} from './InterruptJoin.ts'\nimport { RuntimeSession } from './RuntimeSession.ts'\n\n/** Compatibility alias for the neutral actor-system lifecycle contract. */\nexport type CliSystemActor = ActorSystemActor\n\n/** Keep the existing cli-kit import site while using actor-system's neutral policy. */\nexport { sequentialActorSystemSupervision } from '@ariestools/actor-system'\n\n/** Running config-defined actor system supervised for a CLI process. */\nexport type CliSystemSession<\n  TActor extends CliSystemActor = CliSystemActor,\n  TLocator extends RawInstanceLocator = RawInstanceLocator,\n  TConfig extends ResolvedActorSystemConfig = ResolvedActorSystemConfig,\n  TResolution = ResolvedActorSystemProviderPlan,\n  TIdentity = unknown,\n> = ActorSystemSession<TActor, TLocator, TConfig, TResolution, TIdentity>\n\n/** Neutral actor-system launch inputs with the CLI supervision default. */\nexport type LaunchCliSystemOptions<\n  TActor extends CliSystemActor = CliSystemActor,\n  TLocator extends RawInstanceLocator = RawInstanceLocator,\n  TProvider extends ActorSystemProviderDeclaration = ActorSystemProviderDescriptor,\n  TAuthoredConfig extends ActorSystemConfig = ActorSystemConfig,\n  TResolvedConfig extends ResolvedActorSystemConfig = ResolvedActorSystemConfig,\n  TResolution = ResolvedActorSystemProviderPlan,\n  TSelection extends ActorSystemSelection = ActorSystemSelection,\n  TIdentity = unknown,\n> = LaunchActorSystemOptions<\n  TActor,\n  TLocator,\n  TProvider,\n  TAuthoredConfig,\n  TResolvedConfig,\n  TResolution,\n  TSelection,\n  TIdentity\n>\n\n/** Already-compiled actor-system launch inputs with the CLI policy default. */\nexport type LaunchCompiledCliSystemOptions<\n  TActor extends CliSystemActor = CliSystemActor,\n  TLocator extends RawInstanceLocator = RawInstanceLocator,\n  TProvider extends ActorSystemProviderDeclaration = ActorSystemProviderDescriptor,\n  TAuthoredConfig extends ActorSystemConfig = ActorSystemConfig,\n  TResolvedConfig extends ResolvedActorSystemConfig = ResolvedActorSystemConfig,\n  TResolution = ResolvedActorSystemProviderPlan,\n  TSelection extends ActorSystemSelection = ActorSystemSelection,\n  TIdentity = unknown,\n> = LaunchCompiledActorSystemOptions<\n  TActor,\n  TLocator,\n  TProvider,\n  TAuthoredConfig,\n  TResolvedConfig,\n  TResolution,\n  TSelection,\n  TIdentity\n>\n\n/** Launches one compiled actor system using sequential CLI supervision by default. */\nexport async function launchCompiledCliSystem<\n  TActor extends CliSystemActor = CliSystemActor,\n  TLocator extends RawInstanceLocator = RawInstanceLocator,\n  TProvider extends ActorSystemProviderDeclaration = ActorSystemProviderDescriptor,\n  TAuthoredConfig extends ActorSystemConfig = ActorSystemConfig,\n  TResolvedConfig extends ResolvedActorSystemConfig = ResolvedActorSystemConfig,\n  TResolution = ResolvedActorSystemProviderPlan,\n  TSelection extends ActorSystemSelection = ActorSystemSelection,\n  TIdentity = unknown,\n>(\n  options: LaunchCompiledCliSystemOptions<\n    TActor,\n    TLocator,\n    TProvider,\n    TAuthoredConfig,\n    TResolvedConfig,\n    TResolution,\n    TSelection,\n    TIdentity\n  >,\n): Promise<CliSystemSession<TActor, TLocator, TResolvedConfig, TResolution, TIdentity>> {\n  const supervision: ActorSystemSupervision<TActor>\n    = options.supervision ?? sequentialActorSystemSupervision\n  return await launchCompiledActorSystem({ ...options, supervision })\n}\n\n/**\n * Resolves and launches one config-defined actor system using sequential CLI\n * supervision by default. Applications may inject another actor-system\n * supervision policy explicitly without changing provider resolution.\n */\nexport async function launchCliSystem<\n  TActor extends CliSystemActor = CliSystemActor,\n  TLocator extends RawInstanceLocator = RawInstanceLocator,\n  TProvider extends ActorSystemProviderDeclaration = ActorSystemProviderDescriptor,\n  TAuthoredConfig extends ActorSystemConfig = ActorSystemConfig,\n  TResolvedConfig extends ResolvedActorSystemConfig = ResolvedActorSystemConfig,\n  TResolution = ResolvedActorSystemProviderPlan,\n  TSelection extends ActorSystemSelection = ActorSystemSelection,\n  TIdentity = unknown,\n>(\n  options: LaunchCliSystemOptions<\n    TActor,\n    TLocator,\n    TProvider,\n    TAuthoredConfig,\n    TResolvedConfig,\n    TResolution,\n    TSelection,\n    TIdentity\n  >,\n): Promise<CliSystemSession<TActor, TLocator, TResolvedConfig, TResolution, TIdentity>> {\n  const supervision: ActorSystemSupervision<TActor>\n    = options.supervision ?? sequentialActorSystemSupervision\n  return await launchActorSystem({ ...options, supervision })\n}\n\n/**\n * Joins a launched CLI system to the process interrupt boundary and resident\n * actor terminal failures. Either outcome stops the system exactly once;\n * actor failures are rethrown after cooperative cleanup. Cleanup uses the\n * configured join deadline; a second interrupt also escalates the join.\n * Hosts with an exit capability request termination on escalation, while\n * minimal hosts reject with an ordinary join escalation error.\n */\nexport async function runCliSystemUntilInterrupt(\n  host: InterruptJoinHost,\n  session: Pick<CliSystemSession, 'stop' | 'whenFailed'>,\n  options: InterruptJoinOptions = {},\n): Promise<void> {\n  const join = new InterruptJoin(host, options)\n  const runtime = new RuntimeSession(() => session.stop())\n  const interrupt = Promise.withResolvers<void>()\n  await join.run(async () => {\n    let terminal: Promise<never>\n    try {\n      try {\n        join.bind(async () => {\n          try {\n            await join.wait(runtime.stop())\n            interrupt.resolve()\n          } catch (error) {\n            interrupt.reject(error)\n          }\n        })\n      } finally {\n        terminal = Promise.try(() => session.whenFailed())\n        void observeActorFailure(terminal)\n      }\n      await join.wait(Promise.race([interrupt.promise, terminal]))\n    } catch (failure) {\n      if (join.isEscalation(failure)) throw failure\n      if (runtime.state === 'failed' && runtime.stopError === failure) throw failure\n      join.beginShutdown()\n      try {\n        await join.wait(runtime.stop())\n      } catch (stopError) {\n        if (stopError === failure || join.isEscalation(stopError)) throw stopError\n        throw new AggregateError(\n          [failure, stopError],\n          'CLI actor system failed and did not stop cleanly',\n          { cause: stopError },\n        )\n      }\n      throw failure\n    }\n  })\n}\n\nasync function observeActorFailure(terminal: Promise<never>): Promise<void> {\n  try {\n    await terminal\n  } catch {\n    // The join's race owns failure propagation; failed registration still observes later rejection.\n  }\n}\n", "import type { ProcessHost } from './ProcessHost.ts'\n\n/** Conventional exit code for a process terminated by SIGINT (128 + 2). */\nexport const INTERRUPT_EXIT_CODE = 130\n\n/**\n * How long the pre-session startup path gets to unwind on its own after an\n * interrupt before the process is terminated. Startup checkpoints normally\n * unwind well inside this; the timer exists for the awaits that never return.\n */\nexport const DEFAULT_STARTUP_INTERRUPT_TIMEOUT_MS = 10_000\n\n/** Output sink used on the interrupt path; failures in it are swallowed. */\nexport interface RuntimeInterruptLogger {\n  error(...values: readonly unknown[]): void\n  info(...values: readonly unknown[]): void\n}\n\nexport function logInterruptError(logger: RuntimeInterruptLogger, ...values: readonly unknown[]): void {\n  try {\n    logger.error(...values)\n  } catch {\n    // Diagnostics must not prevent the process exit request.\n  }\n}\n\nexport function logInterruptInfo(logger: RuntimeInterruptLogger, ...values: readonly unknown[]): void {\n  try {\n    logger.info(...values)\n  } catch {\n    // Diagnostics must not prevent cleanup or the process exit request.\n  }\n}\n\n/** Adapts a {@link ProcessHost}'s IO into the interrupt-path logger shape. */\nexport function hostInterruptLogger(host: Pick<ProcessHost, 'io'>): RuntimeInterruptLogger {\n  return {\n    error: (...values: readonly unknown[]) => host.io.error(...values),\n    info: (...values: readonly unknown[]) => host.io.log(...values),\n  }\n}\n\nexport interface RuntimeInterruptControllerParams {\n  readonly host: ProcessHost\n  /** Overrides {@link DEFAULT_STARTUP_INTERRUPT_TIMEOUT_MS}. Zero or less disables the timer. */\n  readonly startupTimeoutMs?: number\n}\n\ninterface UnrefableTimer {\n  unref(): unknown\n}\n\nfunction isUnrefableTimer(value: unknown): value is UnrefableTimer {\n  return typeof value === 'object' && value !== null && 'unref' in value && typeof value.unref === 'function'\n}\n\nexport interface RuntimeInterruptController {\n  /** True once at least one interrupt has been observed. */\n  readonly isInterrupted: boolean\n  /** True once {@link adoptSession} has handed the graceful path to a session. */\n  readonly isSessionAdopted: boolean\n  /**\n   * Aborted on the first interrupt. Startup work that can be cut short should\n   * watch this instead of running to completion.\n   */\n  readonly signal: AbortSignal\n  /**\n   * Hands the graceful path to a bound runtime session. After this the\n   * controller only escalates repeat interrupts \u2014 the session owns the first.\n   */\n  adoptSession(): void\n  /** Removes the process listener. Only needed when startup never reaches a session. */\n  dispose(): void\n}\n\n/**\n * Installs the process-wide interrupt policy for one CLI run.\n *\n * Two gaps make an un-escalated Ctrl+C look like a dead key, and this closes\n * both:\n *\n * 1. **Before the runtime session exists** nothing is bound, so the whole\n *    startup path \u2014 wallet resolution, connection setup, provider graph\n *    construction \u2014 relies on the host's default interrupt behavior.\n *    Installing this controller takes on the job of getting the process out:\n *    it aborts {@link RuntimeInterruptController.signal} for the startup\n *    checkpoints and arms a timer for awaits that never return.\n * 2. **After the session is bound** `RuntimeSession.handleInterrupt` coalesces\n *    every later interrupt into the first one and keeps its process listener\n *    registered, so a shutdown that stalls swallows every subsequent Ctrl+C.\n *    This controller stays registered alongside it and turns the second\n *    interrupt into an immediate exit.\n */\nexport function installRuntimeInterruptController(\n  { host, startupTimeoutMs = DEFAULT_STARTUP_INTERRUPT_TIMEOUT_MS }: RuntimeInterruptControllerParams,\n): RuntimeInterruptController {\n  const logger = hostInterruptLogger(host)\n  const abortController = new AbortController()\n  let interruptCount = 0\n  let isSessionAdopted = false\n  let startupTimer: ReturnType<typeof setTimeout> | undefined\n\n  function forceExit(): void {\n    clearTimeout(startupTimer)\n    startupTimer = undefined\n    try {\n      host.exit(INTERRUPT_EXIT_CODE)\n    } catch (error) {\n      logInterruptError(logger, 'Error requesting immediate exit:', error)\n    }\n  }\n\n  function armStartupTimer(): void {\n    if (startupTimer !== undefined || startupTimeoutMs <= 0) return\n    startupTimer = setTimeout(() => {\n      startupTimer = undefined\n      logInterruptError(logger, `Startup did not stop within ${startupTimeoutMs}ms of the interrupt; exiting now.`)\n      forceExit()\n    }, startupTimeoutMs)\n    // The timer is a backstop, not a reason to keep the process alive.\n    if (isUnrefableTimer(startupTimer)) startupTimer.unref()\n  }\n\n  function handleInterrupt(): void {\n    interruptCount += 1\n    if (interruptCount === 1) {\n      abortController.abort(new Error('Runtime interrupt requested'))\n      // A session owns its own first-interrupt handling and prints its own\n      // message; only the startup window is this controller's to report.\n      if (!isSessionAdopted) {\n        logInterruptInfo(logger, '\\nShutdown requested during startup. Cancelling...')\n        armStartupTimer()\n      }\n      return\n    }\n    logInterruptInfo(logger, '\\nSecond interrupt received. Exiting immediately.')\n    forceExit()\n  }\n\n  const disposeListener = host.onInterrupt(handleInterrupt)\n\n  return {\n    get isInterrupted(): boolean {\n      return interruptCount > 0\n    },\n    get isSessionAdopted(): boolean {\n      return isSessionAdopted\n    },\n    get signal(): AbortSignal {\n      return abortController.signal\n    },\n    adoptSession(): void {\n      isSessionAdopted = true\n      // The session's own shutdown watchdog takes over from here \u2014 but only\n      // for interrupts it will actually see. One that landed before the\n      // handover has no session handler behind it, so its timer stands.\n      if (interruptCount > 0) return\n      clearTimeout(startupTimer)\n      startupTimer = undefined\n    },\n    dispose(): void {\n      clearTimeout(startupTimer)\n      startupTimer = undefined\n      disposeListener()\n    },\n  }\n}\n", "import type { ProcessHost } from './ProcessHost.ts'\nimport {\n  logInterruptError, logInterruptInfo, type RuntimeInterruptLogger,\n} from './runtimeInterrupt.ts'\n\n/**\n * Maximum time a cooperative shutdown gets before the process is terminated\n * anyway. Without a ceiling, one resource that never settles (an actor still\n * inside `startHandler`, a socket that will not drain) holds the process open\n * forever while every further Ctrl+C is coalesced into the shutdown already\n * in flight.\n */\nexport const DEFAULT_SHUTDOWN_TIMEOUT_MS = 15_000\n\n/** Session surface the graceful-interrupt path drives. */\nexport interface InterruptibleSession {\n  requestExit(host: Pick<ProcessHost, 'exit'>, exitCode: number): Promise<void>\n  stop(): Promise<void>\n}\n\nexport interface ResolveShutdownTimeoutOptions {\n  /** Fallback when neither an override nor an env value applies. Defaults to {@link DEFAULT_SHUTDOWN_TIMEOUT_MS}. */\n  readonly defaultMs?: number\n  /** Environment variable consulted between the override and the default. */\n  readonly environmentVariable?: string\n  /** Explicit override; wins over everything. Zero or less disables the watchdog. */\n  readonly override?: number\n}\n\n/**\n * Resolves the shutdown watchdog delay: an explicit override wins, then the\n * configured environment variable, then the default. A non-numeric or\n * negative env value is ignored rather than disabling the watchdog by\n * accident; `0` is honored as \"no watchdog\".\n */\nexport function resolveShutdownTimeoutMs(\n  host: Pick<ProcessHost, 'environment'>,\n  options: ResolveShutdownTimeoutOptions = {},\n): number {\n  const {\n    defaultMs = DEFAULT_SHUTDOWN_TIMEOUT_MS, environmentVariable, override,\n  } = options\n  if (override !== undefined) return override\n  const configured = environmentVariable === undefined ? undefined : host.environment?.[environmentVariable]\n  if (configured === undefined || configured === '') return defaultMs\n  const parsed = Number(configured)\n  return Number.isFinite(parsed) && parsed >= 0 ? parsed : defaultMs\n}\n\ninterface ShutdownOutcome {\n  readonly error?: unknown\n  readonly kind: 'failed' | 'stopped' | 'timeout'\n}\n\n/**\n * Shares one watchdog across the awaited pre-stop hook and cooperative stop.\n * Both promises stay observed after timeout; cleanup is not started later if\n * the hook only settles after the watchdog has already requested termination.\n */\nasync function stopWithinTimeout(\n  session: InterruptibleSession,\n  timeoutMs: number,\n  logger: RuntimeInterruptLogger,\n  onBeforeStop?: HandleRuntimeInterruptOptions['onBeforeStop'],\n): Promise<ShutdownOutcome> {\n  let timer: ReturnType<typeof setTimeout> | undefined\n  let timedOut = false\n  const expired = timeoutMs <= 0\n    ? undefined\n    : new Promise<ShutdownOutcome>((resolve) => {\n        timer = setTimeout(() => {\n          timedOut = true\n          resolve({ kind: 'timeout' })\n        }, timeoutMs)\n      })\n  const stopped: Promise<ShutdownOutcome> = (async (): Promise<ShutdownOutcome> => {\n    if (onBeforeStop !== undefined) {\n      try {\n        await onBeforeStop()\n      } catch (error) {\n        logInterruptError(logger, 'Error cancelling in-flight work during shutdown:', error)\n      }\n    }\n    if (timedOut) return { kind: 'timeout' }\n    try {\n      await session.stop()\n      return { kind: 'stopped' }\n    } catch (error) {\n      return { error, kind: 'failed' }\n    }\n  })()\n  try {\n    return expired === undefined ? await stopped : await Promise.race([stopped, expired])\n  } finally {\n    clearTimeout(timer)\n  }\n}\n\nexport interface HandleRuntimeInterruptOptions {\n  /**\n   * Best-effort pre-stop hook, invoked before `session.stop()` \u2014 the place to\n   * ask in-flight work to abandon early (cancel provider work, abort long\n   * backfills) so the cooperative stop does not sit behind it. The hook is\n   * awaited within the shutdown watchdog. A throwing or rejecting hook is\n   * reported and does not prevent the stop while time remains.\n   */\n  readonly onBeforeStop?: () => Promise<void> | void\n  /** Named in the watchdog-timeout hint so an operator knows which knob allows more time. */\n  readonly shutdownTimeoutEnvironmentVariable?: string\n  /** Overrides the resolved shutdown timeout. Zero or less disables the watchdog. */\n  readonly shutdownTimeoutMs?: number\n}\n\n/**\n * Drives one graceful shutdown in response to a process interrupt: announces\n * it, runs the {@link HandleRuntimeInterruptOptions.onBeforeStop} hook, stops\n * the session under the watchdog, and requests the outcome-coded exit \u2014\n * `0` for a clean stop, `1` for a failed or timed-out one.\n */\nexport async function handleRuntimeInterrupt(\n  host: ProcessHost,\n  logger: RuntimeInterruptLogger,\n  session: InterruptibleSession,\n  options: HandleRuntimeInterruptOptions = {},\n): Promise<void> {\n  const timeoutMs = resolveShutdownTimeoutMs(host, {\n    environmentVariable: options.shutdownTimeoutEnvironmentVariable,\n    ...options.shutdownTimeoutMs !== undefined && { override: options.shutdownTimeoutMs },\n  })\n  logInterruptInfo(logger, '\\nShutdown requested. Attempting graceful shutdown...')\n  const outcome = await stopWithinTimeout(session, timeoutMs, logger, options.onBeforeStop)\n  let exitCode = 0\n  switch (outcome.kind) {\n    case 'stopped': {\n      logInterruptInfo(logger, 'Runtime stopped, exiting now.')\n      break\n    }\n    case 'failed': {\n      exitCode = 1\n      logInterruptError(logger, 'Error stopping runtime:', outcome.error)\n      break\n    }\n    default: {\n      exitCode = 1\n      const environmentHint = options.shutdownTimeoutEnvironmentVariable === undefined\n        ? ''\n        : ` Set ${options.shutdownTimeoutEnvironmentVariable} to allow more time.`\n      logInterruptError(\n        logger,\n        `Graceful shutdown did not finish within ${timeoutMs}ms; exiting anyway.${environmentHint}`,\n      )\n    }\n  }\n  await session.requestExit(host, exitCode)\n}\n", "/** Process-facing input and output used by a command-line app. */\nexport interface ProcessIO {\n  /** Available terminal width when output is attached to a sized terminal. */\n  readonly columns?: number\n  readonly isInteractive: boolean\n  error(...values: readonly unknown[]): void\n  log(...values: readonly unknown[]): void\n  question(prompt: string): Promise<string>\n  warn(...values: readonly unknown[]): void\n}\n\n/** Control-flow signal used when a non-terminating host records an immediate exit. */\nexport class ProcessExitError extends Error {\n  readonly exitCode: number\n\n  constructor(exitCode: number) {\n    super(`Process requested exit with code ${exitCode}`)\n    this.name = 'ProcessExitError'\n    this.exitCode = exitCode\n  }\n}\n\n/**\n * Structural process boundary for a command-line app.\n *\n * Production implementations may terminate from {@link exit}; recording hosts\n * may return after retaining the requested status.\n */\nexport interface ProcessHost {\n  /** Full argument vector, including the executable and script entries. */\n  readonly argv: readonly string[]\n  /** Environment visible to this app invocation. */\n  readonly environment: Readonly<Record<string, string | undefined>>\n  readonly io: ProcessIO\n  readonly isDevelopment: boolean\n  exit(code: number): void\n  onInterrupt(listener: () => Promise<void> | void): () => void\n}\n\n/**\n * Requests immediate process termination and prevents a recording host from\n * accidentally continuing through code that follows the exit point.\n */\nexport function exitProcess(host: Pick<ProcessHost, 'exit'>, exitCode: number): never {\n  host.exit(exitCode)\n  throw new ProcessExitError(exitCode)\n}\n", "import { DEFAULT_SHUTDOWN_TIMEOUT_MS } from './handleRuntimeInterrupt.ts'\nimport {\n  exitProcess, ProcessExitError, type ProcessHost,\n} from './ProcessHost.ts'\n\n/** Minimal structural hosts remain accepted; an exit capability enables hard escalation. */\nexport type InterruptJoinHost = Pick<ProcessHost, 'onInterrupt'> & Partial<Pick<ProcessHost, 'exit' | 'io'>>\n\nexport interface InterruptJoinOptions {\n  /** Optional synchronous exit boundary when the interrupt host does not expose one. */\n  readonly exitHost?: Pick<ProcessHost, 'exit'>\n  /** Cleanup budget, default 15 seconds. Finite 0..2,147,483,647 ms; zero disables the watchdog. */\n  readonly shutdownTimeoutMs?: number\n}\n\n/** A minimal host can settle the join but cannot request process termination. */\nexport class InterruptJoinEscalationError extends Error {\n  readonly exitCode: number\n  readonly reason: 'interrupt' | 'timeout'\n\n  constructor(exitCode: number, reason: 'interrupt' | 'timeout') {\n    super(reason === 'timeout' ? 'Runtime join shutdown exceeded its deadline' : 'Runtime join received a second interrupt')\n    this.name = 'InterruptJoinEscalationError'\n    this.exitCode = exitCode\n    this.reason = reason\n  }\n}\n\nfunction isExitSignal(error: unknown): boolean {\n  try {\n    return error instanceof ProcessExitError\n  } catch {\n    return false\n  }\n}\n\n/** Internal owner of one join's process binding, cleanup deadline, and escalation. */\nexport class InterruptJoin {\n  #disposer?: () => void\n  readonly #escalation = Promise.withResolvers<never>()\n  #escalationError: unknown\n  readonly #exitHost?: Pick<ProcessHost, 'exit'>\n  #hasEscalated = false\n  readonly #host: InterruptJoinHost\n  #interruptCount = 0\n  #isBound = false\n  #isDisposed = false\n  #isInterruptDisposed = false\n  #isShutdownStarted = false\n  readonly #shutdownTimeoutMs: number\n  #timer?: ReturnType<typeof setTimeout>\n\n  constructor(host: InterruptJoinHost, options: InterruptJoinOptions = {}) {\n    const timeout = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS\n    if (!Number.isFinite(timeout) || timeout < 0 || timeout > 2_147_483_647) {\n      throw new Error('Join shutdownTimeoutMs must be finite and between 0 and 2147483647')\n    }\n    this.#shutdownTimeoutMs = timeout\n    this.#host = host\n    const exitHost = options.exitHost ?? host\n    const exit = exitHost.exit\n    if (typeof exit !== 'function' && options.exitHost !== undefined) throw new Error('Join exitHost must provide a synchronous exit function')\n    if (typeof exit === 'function') this.#exitHost = { exit: code => exit.call(exitHost, code) }\n    // Registration can synchronously deliver two interrupts before the caller\n    // attaches its race. Keep the control promise observed from construction.\n    void this.#observeEscalation()\n  }\n\n  get hasExitCapability(): boolean {\n    return this.#exitHost !== undefined\n  }\n\n  beginShutdown(): void {\n    if (this.#isDisposed || this.#hasEscalated || this.#isShutdownStarted) return\n    this.#isShutdownStarted = true\n    if (this.#shutdownTimeoutMs === 0) return\n    this.#timer = setTimeout(() => this.#forceExit(1, 'timeout'), this.#shutdownTimeoutMs)\n  }\n\n  bind(listener: () => Promise<void> | void): void {\n    if (this.#isBound || this.#isDisposed) throw new Error('Runtime join interrupt binding cannot be reused')\n    this.#isBound = true\n    let registrationComplete = false\n    let pendingInterrupts = 0\n    this.#disposer = this.#host.onInterrupt(() => {\n      if (!registrationComplete) {\n        pendingInterrupts += 1\n        return\n      }\n      return this.#handleInterrupt(listener)\n    })\n    registrationComplete = true\n    for (let index = 0; index < pendingInterrupts; index += 1) void this.#handleInterrupt(listener)\n  }\n\n  disposeInterrupt(): void {\n    if (this.#isInterruptDisposed) return\n    this.#isInterruptDisposed = true\n    const dispose = this.#disposer\n    this.#disposer = undefined\n    dispose?.()\n  }\n\n  isEscalation(error: unknown): boolean {\n    return this.#hasEscalated && error === this.#escalationError\n  }\n\n  async run(operation: () => Promise<void>): Promise<void> {\n    let hasFailure = false\n    let failure: unknown\n    try {\n      await operation()\n    } catch (error) {\n      hasFailure = true\n      failure = error\n    }\n    if (this.#hasEscalated) {\n      hasFailure = true\n      failure = this.#escalationError\n    }\n    try {\n      this.#dispose()\n    } catch (disposalError) {\n      if (!hasFailure) throw disposalError\n      if (isExitSignal(failure)) {\n        this.#report('Error removing the runtime join interrupt listener after an exit request:', disposalError)\n      } else if (failure !== disposalError) {\n        throw new AggregateError([failure, disposalError], 'Runtime join failed and could not remove its interrupt listener', { cause: disposalError })\n      }\n    }\n    if (hasFailure) throw failure\n  }\n\n  async wait<T>(promise: Promise<T>): Promise<T> {\n    try {\n      const result = await Promise.race([promise, this.#escalation.promise])\n      if (!this.#hasEscalated) return result\n    } catch (error) {\n      if (!this.#hasEscalated) throw error\n    }\n    // An exit adapter or reporter may settle cleanup synchronously while\n    // escalating. Recorded termination must still prevent normal continuation.\n    throw this.#escalationError\n  }\n\n  #clearTimer(): void {\n    clearTimeout(this.#timer)\n    this.#timer = undefined\n  }\n\n  #dispose(): void {\n    this.#isDisposed = true\n    this.#clearTimer()\n    this.disposeInterrupt()\n  }\n\n  #forceExit(exitCode: number, reason: 'interrupt' | 'timeout'): void {\n    if (this.#isDisposed || this.#hasEscalated) return\n    this.#hasEscalated = true\n    this.#clearTimer()\n    const action = this.#exitHost === undefined ? 'Ending the shutdown wait.' : 'Exiting immediately.'\n    this.#report(reason === 'timeout'\n      ? `Runtime shutdown did not finish within ${this.#shutdownTimeoutMs}ms. ${action}`\n      : `Second interrupt received. ${action}`)\n    let failure: unknown = new InterruptJoinEscalationError(exitCode, reason)\n    if (this.#exitHost !== undefined) {\n      try {\n        exitProcess(this.#exitHost, exitCode)\n      } catch (error) {\n        failure = error\n      }\n    }\n    this.#escalationError = failure\n    this.#escalation.reject(failure)\n  }\n\n  #handleInterrupt(listener: () => Promise<void> | void): Promise<void> | void {\n    if (this.#isDisposed || this.#hasEscalated || this.#isInterruptDisposed) return\n    this.#interruptCount += 1\n    if (this.#interruptCount > 1) {\n      this.#forceExit(130, 'interrupt')\n      return\n    }\n    this.beginShutdown()\n    return this.#invokeListener(listener)\n  }\n\n  async #invokeListener(listener: () => Promise<void> | void): Promise<void> {\n    try {\n      await Promise.try(listener)\n    } catch (error) {\n      if (this.#hasEscalated) {\n        this.#report('Error handling a runtime interrupt after join escalation:', error)\n        return\n      }\n      this.#hasEscalated = true\n      this.#clearTimer()\n      this.#escalationError = error\n      this.#escalation.reject(error)\n    }\n  }\n\n  async #observeEscalation(): Promise<void> {\n    try {\n      await this.#escalation.promise\n    } catch {\n      // The caller's wait owns failure propagation, including registration-time delivery.\n    }\n  }\n\n  #report(message: string, error?: unknown): void {\n    try {\n      if (error === undefined) this.#host.io?.error(message)\n      else this.#host.io?.error(message, error)\n    } catch {\n      // Diagnostics cannot defeat cleanup or an escalation request.\n    }\n  }\n}\n", "import type { ProcessHost } from './ProcessHost.ts'\n\n/** Lifecycle state of one active runtime session. */\nexport type RuntimeSessionState = 'active' | 'failed' | 'stopped' | 'stopping'\n\n/** Application-owned cleanup invoked when a runtime session stops. */\nexport type RuntimeStopDelegate = () => Promise<void> | void\n\n/** Application-owned work invoked for the first process interrupt. */\nexport type RuntimeInterruptListener = () => Promise<void> | void\n\n/**\n * Instance-scoped owner for one runtime cleanup operation.\n *\n * Every call to {@link stop} returns the same promise. A cleanup failure is\n * retained and rethrown without wrapping so callers can preserve their\n * existing fail-fast behavior.\n */\nexport class RuntimeSession {\n  private _exitCode?: number\n  private _exitHost?: Pick<ProcessHost, 'exit'>\n  private _exitPromise?: Promise<void>\n  private _hasInterruptBinding = false\n  private _interruptDisposer?: () => void\n  private _interruptPromise?: Promise<void>\n  private _isInterruptDisposed = false\n  private _state: RuntimeSessionState = 'active'\n  private readonly _stopDelegate: RuntimeStopDelegate\n  private _stopError?: unknown\n  private _stopPromise?: Promise<void>\n\n  constructor(stopDelegate: RuntimeStopDelegate) {\n    this._stopDelegate = stopDelegate\n  }\n\n  get state(): RuntimeSessionState {\n    return this._state\n  }\n\n  get stopError(): unknown {\n    return this._stopError\n  }\n\n  bindInterrupt(host: Pick<ProcessHost, 'onInterrupt'>, listener: RuntimeInterruptListener): void {\n    if (this._hasInterruptBinding) throw new Error('An interrupt listener is already bound to this runtime session.')\n    if (this.state !== 'active') throw new Error('An interrupt listener cannot be bound after runtime shutdown has started.')\n\n    this._hasInterruptBinding = true\n    let isRegistrationComplete = false\n    let isInterruptPending = false\n    const handleInterrupt = (): Promise<void> | void => {\n      if (!isRegistrationComplete) {\n        isInterruptPending = true\n        return\n      }\n      return this.handleInterrupt(listener)\n    }\n    this._interruptDisposer = host.onInterrupt(handleInterrupt)\n    isRegistrationComplete = true\n\n    // A structural host may deliver an interrupt while registering the listener.\n    // Defer that delivery until the returned disposer is retained so it can be\n    // removed after the interrupt handler settles.\n    if (isInterruptPending) void this.handleInterrupt(listener)\n  }\n\n  /**\n   * Coalesces competing process-exit requests for this session. Requests made\n   * in the same turn retain the highest exit code and every caller observes\n   * the same exactly-once exit operation.\n   */\n  requestExit(host: Pick<ProcessHost, 'exit'>, exitCode: number): Promise<void> {\n    this._exitCode = Math.max(this._exitCode ?? exitCode, exitCode)\n    this._exitHost ??= host\n    this._exitPromise ??= Promise.try(async () => {\n      await Promise.resolve()\n      this._exitHost?.exit(this._exitCode ?? exitCode)\n    })\n    return this._exitPromise\n  }\n\n  stop(): Promise<void> {\n    // Manual shutdown owns listener disposal immediately. Interrupt-driven\n    // shutdown retains the listener until its handler settles so repeated\n    // interrupts are coalesced instead of reaching the host's default handler.\n    if (this._interruptPromise === undefined) this.disposeInterrupt()\n    if (this._stopPromise === undefined) {\n      this._state = 'stopping'\n      this._stopPromise = Promise.try(async () => {\n        await Promise.resolve()\n        await this.stopOnce()\n      })\n    }\n    return this._stopPromise\n  }\n\n  private disposeInterrupt(): void {\n    if (!this._hasInterruptBinding || this._isInterruptDisposed) return\n    this._isInterruptDisposed = true\n    const dispose = this._interruptDisposer\n    this._interruptDisposer = undefined\n    dispose?.()\n  }\n\n  private handleInterrupt(listener: RuntimeInterruptListener): Promise<void> {\n    if (this._interruptPromise === undefined) {\n      if (this._isInterruptDisposed) return Promise.resolve()\n      this._interruptPromise = Promise.try(async () => {\n        await Promise.resolve()\n        try {\n          await listener()\n        } finally {\n          this.disposeInterrupt()\n        }\n      })\n    }\n    return this._interruptPromise\n  }\n\n  private async stopOnce(): Promise<void> {\n    try {\n      await this._stopDelegate()\n      this._state = 'stopped'\n    } catch (error) {\n      this._stopError = error\n      this._state = 'failed'\n      throw error\n    }\n  }\n}\n", "/**\n * Raised when flags or environment values resolve to an invalid app\n * configuration. Mapped to `SYS_EXITS.config` (78) by\n * {@link createSysExitFailureMapper} so misconfiguration stays distinct from\n * unexpected software failures (70).\n *\n * Apps may throw this class directly, subclass it (the mapper's `instanceof`\n * ladder matches subclasses), or keep their own error classes and enroll them\n * through the factory's options.\n */\nexport class CliConfigError extends Error {\n  constructor(message: string, options?: ErrorOptions) {\n    super(message, options)\n    this.name = 'CliConfigError'\n  }\n}\n\n/**\n * Raised when input data \u2014 a payload, a file, a record \u2014 was well-formed as an\n * invocation but incorrect as data. Mapped to `SYS_EXITS.dataErr` (65) by\n * {@link createSysExitFailureMapper}.\n */\nexport class CliDataError extends Error {\n  constructor(message: string, options?: ErrorOptions) {\n    super(message, options)\n    this.name = 'CliDataError'\n  }\n}\n\n/**\n * Raised for a mis-invocation the parser accepted but the command surface\n * rejects \u2014 for example a stray positional token reaching a `$0` handler.\n * Mapped to `SYS_EXITS.usage` (64) by {@link createSysExitFailureMapper} by\n * error class, so the exit code never depends on whether a parser-level check\n * happened to surface first.\n */\nexport class CliUsageError extends Error {\n  constructor(message: string, options?: ErrorOptions) {\n    super(message, options)\n    this.name = 'CliUsageError'\n  }\n}\n\n/** Cause links walked by {@link describeError} before the chain is cut off. */\nconst DESCRIBE_ERROR_DEPTH_LIMIT = 5\n\n/**\n * One chain link as operator-facing text: an `Error`'s message, a string as\n * itself, any other object as JSON (never `[object Object]`), and remaining\n * primitives stringified.\n */\nfunction describeCauseValue(value: unknown): string {\n  if (value instanceof Error) return value.message\n  if (typeof value === 'string') return value\n  if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint' || typeof value === 'symbol') {\n    return String(value)\n  }\n  if (typeof value === 'function') return '[function]'\n  try {\n    return JSON.stringify(value) ?? '[unserializable value]'\n  } catch {\n    return '[unserializable value]'\n  }\n}\n\n/**\n * The message plus its `cause` chain \u2014 a bare \"fetch failed\" names no host, but\n * its cause carries the address and errno an operator actually needs. Used for\n * the operator-facing one-liner on a `usage` / `config` exit, where a stack\n * trace through an app's own internals is pure noise.\n * @param error The failure to describe.\n * @returns The message chain, innermost cause last, joined by `\u2190`.\n */\nexport function describeError(error: unknown): string {\n  const parts: string[] = []\n  let current: unknown = error\n  for (let depth = 0; depth < DESCRIBE_ERROR_DEPTH_LIMIT; depth++) {\n    if (current === undefined || current === null) break\n    parts.push(describeCauseValue(current))\n    current = current instanceof Error ? current.cause : undefined\n  }\n  return parts.join(' \u2190 ')\n}\n", "import type { ProcessHost } from './ProcessHost.ts'\n\n/** Process capability shared by every command created for one CLI app. */\nexport interface CliApplicationContext {\n  readonly host: ProcessHost\n}\n\n/** Adapter-neutral factory for one parser-specific command object. */\nexport interface CommandDefinition<TContext extends CliApplicationContext, TCommand> {\n  readonly create: (context: TContext) => TCommand\n  /** Internal registration identity; it does not define parser syntax or aliases. */\n  readonly id: string\n}\n\n/** Ordered command factories materialized for one app context. */\nexport interface CommandCatalog<TContext extends CliApplicationContext, TCommand> {\n  readonly createCommands: (context: TContext) => readonly TCommand[]\n  readonly ids: readonly string[]\n}\n\n/** Creates an immutable, adapter-neutral command catalog. */\nexport function createCommandCatalog<TContext extends CliApplicationContext, TCommand>(\n  definitions: readonly CommandDefinition<TContext, TCommand>[],\n): CommandCatalog<TContext, TCommand> {\n  const registeredIds = new Set<string>()\n  const retainedDefinitions = definitions.map(definition => Object.freeze({\n    create: definition.create,\n    id: definition.id,\n  }))\n  const ids: string[] = []\n\n  for (const definition of retainedDefinitions) {\n    if (definition.id.trim().length === 0) throw new Error('Command id must not be empty')\n    if (registeredIds.has(definition.id)) throw new Error(`Command \"${definition.id}\" is already registered`)\n    registeredIds.add(definition.id)\n    ids.push(definition.id)\n  }\n\n  return Object.freeze({\n    ids: Object.freeze(ids),\n    createCommands: (context: TContext): readonly TCommand[] =>\n      Object.freeze(retainedDefinitions.map(definition => definition.create(context))),\n  })\n}\n", "import type { ProcessIO } from './ProcessHost.ts'\n\n/**\n * Structural logger contract produced by {@link createProcessIoLogger}.\n *\n * Deliberately a local structural type rather than an import: the shape is\n * assignment-compatible with `@ariestools/sdk`'s `Logger` (the contract the\n * actor and gateway stacks consume), and declaring it here keeps the core\n * package dependency-free.\n */\nexport interface CliLogger {\n  debug(...values: readonly unknown[]): void\n  error(...values: readonly unknown[]): void\n  info(...values: readonly unknown[]): void\n  log(...values: readonly unknown[]): void\n  trace(...values: readonly unknown[]): void\n  warn(...values: readonly unknown[]): void\n}\n\nexport interface ProcessIoLoggerOptions {\n  /**\n   * Emit `debug` and `trace` output. Defaults to `false`, keeping diagnostic\n   * chatter out of ordinary invocations; wire this to the app's `--verbose`\n   * flag.\n   */\n  readonly isVerbose?: boolean\n}\n\n/**\n * Adapts the CLI process boundary's IO into the logger shape shared by the\n * actor and gateway stacks, so command handlers can hand SDK components a\n * logger without touching the console directly. `info`/`log` route to\n * {@link ProcessIO.log}, `warn` to {@link ProcessIO.warn}, `error` to\n * {@link ProcessIO.error}; `debug`/`trace` stay quiet unless verbose.\n */\nexport function createProcessIoLogger(io: ProcessIO, options: ProcessIoLoggerOptions = {}): CliLogger {\n  const isVerbose = options.isVerbose ?? false\n  const quiet = (): void => undefined\n  const emit = (...values: readonly unknown[]): void => {\n    io.log(...values)\n  }\n  return {\n    debug: isVerbose ? emit : quiet,\n    error: (...values: readonly unknown[]): void => {\n      io.error(...values)\n    },\n    info: emit,\n    log: emit,\n    trace: isVerbose ? emit : quiet,\n    warn: (...values: readonly unknown[]): void => {\n      io.warn(...values)\n    },\n  }\n}\n", "/**\n * BSD `sysexits.h` exit codes shared across the CLI fleet.\n *\n * Only the subset actually used by apps is included so exit-code\n * policy stays reviewable. Use these with {@link exitProcess} or a\n * failure-to-exit-code mapper instead of repeating numeric literals.\n */\nexport const SYS_EXITS = {\n  /** `EX_OK` (0): successful termination. */\n  ok: 0,\n  /** `EX_USAGE` (64): command line usage error, such as bad arguments or flags. */\n  usage: 64,\n  /** `EX_DATAERR` (65): input data was incorrect in some way. */\n  dataErr: 65,\n  /** `EX_NOINPUT` (66): an input file did not exist or was not readable. */\n  noInput: 66,\n  /** `EX_SOFTWARE` (70): internal software error not caused by the operating system. */\n  software: 70,\n  /** `EX_IOERR` (74): an error occurred while doing I/O on a file. */\n  ioErr: 74,\n  /** `EX_CONFIG` (78): something was found in an unconfigured or misconfigured state. */\n  config: 78,\n} as const\n\n/** Exit code drawn from the supported `sysexits.h` vocabulary. */\nexport type SysExitCode = typeof SYS_EXITS[keyof typeof SYS_EXITS]\n", "import {\n  CliConfigError, CliDataError, CliUsageError,\n} from './cliErrors.ts'\nimport type { FailureExitCodeMapper } from './ProcessApplication.ts'\nimport { SYS_EXITS, type SysExitCode } from './sysExits.ts'\n\n/** Error class matched by `instanceof`; abstract constructors are accepted. */\nexport type CliErrorClass = abstract new (...args: never[]) => Error\n\nexport interface SysExitFailureMapperOptions {\n  /** App error classes mapped to `config` (78), alongside {@link CliConfigError}. */\n  readonly config?: readonly CliErrorClass[]\n  /** App error classes mapped to `dataErr` (65), alongside {@link CliDataError}. */\n  readonly dataErr?: readonly CliErrorClass[]\n  /**\n   * Exit code for a handler-origin failure no class matched \u2014 chain, IO, or\n   * other runtime failures. Defaults to `software` (70).\n   */\n  readonly fallback?: SysExitCode\n  /** App error classes mapped to `usage` (64), alongside {@link CliUsageError}. */\n  readonly usage?: readonly CliErrorClass[]\n}\n\n/**\n * Creates the `sysexits.h` failure policy shared by the CLI fleet.\n *\n * Every app-level mapper had the same ladder; this factory replaces the\n * per-app copies:\n *\n * - `parse` origin \u2014 an unknown command (rejected by `rejectUnknownCommands`),\n *   an unrecognized flag (rejected by `.strictOptions()`), or a bad option\n *   type \u2014 \u2192 `usage` (64). Parse origin wins over the error type so a\n *   mis-invocation is always usage.\n * - A mis-invocation the command surface rejects after parsing\n *   ({@link CliUsageError} or an enrolled app class) \u2192 `usage` (64) by error\n *   class, so the code does not depend on which check fired first.\n * - Misconfiguration ({@link CliConfigError} or enrolled) \u2192 `config` (78).\n * - Incorrect input data ({@link CliDataError} or enrolled) \u2192 `dataErr` (65).\n * - Everything else \u2192 {@link SysExitFailureMapperOptions.fallback}\n *   (`software`, 70, by default).\n *\n * Classes are matched by `instanceof`, so subclasses of the built-in\n * vocabulary need no enrollment at all. When one error matches several\n * buckets, evaluation order is usage, then config, then dataErr.\n */\nexport function createSysExitFailureMapper(options: SysExitFailureMapperOptions = {}): FailureExitCodeMapper {\n  const usageClasses: readonly CliErrorClass[] = [CliUsageError, ...options.usage ?? []]\n  const configClasses: readonly CliErrorClass[] = [CliConfigError, ...options.config ?? []]\n  const dataErrClasses: readonly CliErrorClass[] = [CliDataError, ...options.dataErr ?? []]\n  const fallback = options.fallback ?? SYS_EXITS.software\n\n  function matchesAny(error: unknown, classes: readonly CliErrorClass[]): boolean {\n    return classes.some(errorClass => error instanceof errorClass)\n  }\n\n  return (error, origin) => {\n    if (origin === 'parse') return SYS_EXITS.usage\n    if (matchesAny(error, usageClasses)) return SYS_EXITS.usage\n    if (matchesAny(error, configClasses)) return SYS_EXITS.config\n    return matchesAny(error, dataErrClasses) ? SYS_EXITS.dataErr : fallback\n  }\n}\n", "export interface StartupBannerOptions {\n  /** Names of the actors that will run in this process. */\n  readonly actors: readonly string[]\n  /** App display name shown on the first banner line. */\n  readonly title: string\n  /** Full version string (\"Major.Minor.Patch (githash)\" when built from a Git checkout). */\n  readonly version: string\n}\n\n/** Formats the startup banner shown at the top of the console output. */\nexport function formatStartupBanner({\n  actors, title, version,\n}: StartupBannerOptions): string {\n  return [\n    '',\n    title,\n    `   Version: ${version}`,\n    `   Actors:  ${actors.join(', ')}`,\n    '',\n  ].join('\\n')\n}\n", "import type { ProcessHost } from './ProcessHost.ts'\nimport type { RuntimeSessionState } from './RuntimeSession.ts'\n\nconst DEFAULT_GLOBAL_ERROR_EXIT_TIMEOUT_MS = 10_000\n\n/** Process boundary retained for fatal-error escalation. */\nexport type GlobalErrorHost = Pick<ProcessHost, 'exit' | 'io'>\n\n/** Session surface the escalation drives; `stop` must be the owner's full teardown. */\nexport interface EscalatableSession {\n  readonly state: RuntimeSessionState\n  requestExit(host: Pick<ProcessHost, 'exit'>, exitCode: number): Promise<void>\n  stop(): Promise<void>\n}\n\nexport interface GlobalErrorEscalationParams {\n  /** Maximum graceful-cleanup delay before a fatal error requests hard process termination. */\n  readonly exitTimeoutMs?: number\n  /**\n   * Returns true when a fatal notification should be ignored because an\n   * orderly shutdown is already in progress. A throwing predicate cannot\n   * suppress the notification.\n   */\n  readonly isShutdownInProgress?: () => boolean\n  readonly session: EscalatableSession\n}\n\nfunction logFailure(host: GlobalErrorHost, message: string, error: unknown): void {\n  try {\n    host.io.error(message, error)\n  } catch {\n    // Process termination must not be defeated by a failing output adapter.\n  }\n}\n\n/**\n * Escalates a fatal out-of-band error signal \u2014 a health reporter entering an\n * error state, a supervisor declaring the run unrecoverable \u2014 into process\n * termination that stays serialized with normal lifecycle cleanup.\n *\n * The escalation runs in two phases so a fatal signal raised during command\n * startup cannot race the synchronous failure path:\n *\n * - {@link arm} retains the process boundary while startup is still running.\n *   From this point a non-cooperative startup cannot suppress termination\n *   forever: a retained notification arms the exit watchdog even before\n *   activation.\n * - {@link activate} enables the graceful path once startup has completed;\n *   any notification retained in the meantime is handled here.\n *\n * On escalation the session is stopped (cleanup failures are reported, never\n * rethrown) and exit code 1 is requested. Once fatal cleanup owns the shutdown,\n * the watchdog remains active until that cleanup settles. A retained startup\n * notification is discarded if external shutdown takes over first. An owner\n * may call {@link clearExitTimer} to cancel promptly after external cleanup;\n * this session interface does not expose an external stop-settlement event.\n */\nexport class GlobalErrorEscalation {\n  #escalationPromise?: Promise<void>\n  #exitPromise?: Promise<void>\n  readonly #exitTimeoutMs: number\n  #exitTimer?: ReturnType<typeof setTimeout>\n  #hasNotification = false\n  #hasReportedExitFailure = false\n  #host?: GlobalErrorHost\n  #isActive = false\n  readonly #isShutdownInProgress?: () => boolean\n  #isStopSettled = false\n  #ownsShutdown = false\n  readonly #session: EscalatableSession\n\n  constructor(params: GlobalErrorEscalationParams) {\n    this.#exitTimeoutMs = Math.max(0, params.exitTimeoutMs ?? DEFAULT_GLOBAL_ERROR_EXIT_TIMEOUT_MS)\n    if (params.isShutdownInProgress !== undefined) this.#isShutdownInProgress = params.isShutdownInProgress\n    this.#session = params.session\n  }\n\n  /**\n   * Enables process termination for fatal errors after startup has completed.\n   * Any notification retained while startup was still in progress is handled\n   * here instead of racing the synchronous failure path.\n   */\n  activate(host: GlobalErrorHost): Promise<void> {\n    this.arm(host)\n    this.#isActive = true\n    return this.#handleNotification()\n  }\n\n  /**\n   * Retains the process boundary while startup is running. Fatal errors stay\n   * serialized with normal lifecycle cleanup, but a non-cooperative startup\n   * cannot suppress process termination forever.\n   */\n  arm(host: GlobalErrorHost): void {\n    this.#host = host\n    this.#scheduleExitTimer()\n  }\n\n  /** Cancels a pending watchdog, including from an external owner's settled-stop hook. */\n  clearExitTimer(): void {\n    if (this.#exitTimer === undefined) return\n    clearTimeout(this.#exitTimer)\n    this.#exitTimer = undefined\n  }\n\n  /** Reports one fatal out-of-band error signal. Idempotent; ignored after shutdown has begun. */\n  notify(): void {\n    if (this.#ownsShutdown || this.#discardExternalNotification()) return\n    this.#hasNotification = true\n    this.#scheduleExitTimer()\n    void this.#handleNotification()\n  }\n\n  #beginEscalation(host: GlobalErrorHost): Promise<void> {\n    if (this.#escalationPromise !== undefined) return this.#escalationPromise\n    this.#ownsShutdown = true\n    // Retain the shared promise before invoking stop, including reentrant notifications.\n    this.#escalationPromise = Promise.try(async () => {\n      await Promise.resolve()\n      await this.#stopAndExit(host)\n    })\n    void this.#escalationPromise.catch((error: unknown) => this.#reportExitFailure(host, error))\n    return this.#escalationPromise\n  }\n\n  #discardExternalNotification(): boolean {\n    if (this.#ownsShutdown) return false\n    let externalShutdown = this.#session.state !== 'active'\n    try {\n      externalShutdown ||= this.#isShutdownInProgress?.() === true\n    } catch {\n      // A broken predicate cannot suppress a fatal notification.\n    }\n    if (!externalShutdown) return false\n    this.#hasNotification = false\n    this.clearExitTimer()\n    return true\n  }\n\n  #handleNotification(): Promise<void> {\n    if (this.#escalationPromise !== undefined) return this.#escalationPromise\n    if (!this.#hasNotification || !this.#isActive) return Promise.resolve()\n    const host = this.#host\n    if (host === undefined) return Promise.resolve()\n    return this.#discardExternalNotification() ? Promise.resolve() : this.#beginEscalation(host)\n  }\n\n  #onExitTimeout(): void {\n    this.#exitTimer = undefined\n    const host = this.#host\n    if (host === undefined || this.#isStopSettled || this.#discardExternalNotification()) return\n    void this.#beginEscalation(host)\n    void this.#requestExit(host)\n  }\n\n  #reportExitFailure(host: GlobalErrorHost, error: unknown): void {\n    if (this.#hasReportedExitFailure) return\n    this.#hasReportedExitFailure = true\n    logFailure(host, 'Error requesting process exit after a fatal runtime error:', error)\n  }\n\n  #requestExit(host: GlobalErrorHost): Promise<void> {\n    if (this.#exitPromise === undefined) {\n      const completion = Promise.withResolvers<void>()\n      this.#exitPromise = completion.promise\n      void this.#exitPromise.catch((error: unknown) => this.#reportExitFailure(host, error))\n      // Register fatal severity in the caller's turn before a competing exit can run.\n      void Promise.try(async () => {\n        try {\n          await this.#session.requestExit(host, 1)\n          completion.resolve()\n        } catch (error) {\n          completion.reject(error)\n        }\n      })\n    }\n    return this.#exitPromise\n  }\n\n  #scheduleExitTimer(): void {\n    if (\n      this.#exitTimer !== undefined\n      || this.#exitPromise !== undefined\n      || this.#host === undefined\n      || !this.#hasNotification\n      || this.#isStopSettled\n      || this.#discardExternalNotification()\n    ) return\n    this.#exitTimer = setTimeout(() => this.#onExitTimeout(), this.#exitTimeoutMs)\n  }\n\n  async #stopAndExit(host: GlobalErrorHost): Promise<void> {\n    try {\n      await this.#session.stop()\n    } catch (error) {\n      logFailure(host, 'Error cleaning up after a fatal runtime error:', error)\n    } finally {\n      // The watchdog exists to bound a hung stop; once the stop has settled\n      // (either way) a still-armed timer would only escalate a second time.\n      this.#isStopSettled = true\n      this.clearExitTimer()\n    }\n    await this.#requestExit(host)\n  }\n}\n", "import { ProcessExitError, type ProcessHost } from './ProcessHost.ts'\n\n/** Application entry point executed against an explicit process boundary. */\nexport type ProcessApplication = (host: ProcessHost) => Promise<void>\n\n/**\n * Where an unexpected failure originated.\n *\n * - `'parse'`: argument parsing or validation failed before any command\n *   handler ran (for example a Yargs usage error).\n * - `'handler'`: the app body, command handler, or middleware failed after\n *   arguments were accepted.\n */\nexport type FailureOrigin = 'handler' | 'parse'\n\n/**\n * Optional application-supplied failure policy. Returning a number selects\n * the exit code for that failure; returning `undefined` retains the default\n * exit code one. The `origin` argument distinguishes parse/validation\n * failures from handler failures so mappers such as `usage` (64) versus\n * `software` (70) need no runner-specific error sniffing. Intentional exits\n * carried by `ProcessExitError` are never offered to the mapper.\n *\n * Results outside the integer range 0\u2013255 (including `NaN`) and errors\n * thrown by the mapper itself fall back to exit code one; the mapper is\n * inside the failure boundary, not above it. Prefer drawing codes from\n * `SYS_EXITS`.\n */\nexport type FailureExitCodeMapper = (error: unknown, origin: FailureOrigin) => number | undefined\n\n/**\n * Resolves the exit code for an unexpected failure through an optional\n * mapper. A missing mapper, an `undefined` result, a thrown mapper, or a\n * result outside the integer range 0\u2013255 all resolve to the default exit\n * code one, keeping the failure boundary intact.\n */\nexport function resolveFailureExitCode(\n  mapFailureToExitCode: FailureExitCodeMapper | undefined,\n  error: unknown,\n  origin: FailureOrigin,\n): number {\n  if (mapFailureToExitCode === undefined) return 1\n  try {\n    const code = mapFailureToExitCode(error, origin)\n    return code !== undefined && Number.isSafeInteger(code) && code >= 0 && code <= 255 ? code : 1\n  } catch {\n    return 1\n  }\n}\n\nexport interface RunProcessApplicationOptions {\n  readonly application: ProcessApplication\n  readonly host: ProcessHost\n  readonly mapFailureToExitCode?: FailureExitCodeMapper\n}\n\n/**\n * Runs one CLI app at the outermost process boundary.\n *\n * Immediate exits requested through `exitProcess` have already been\n * routed to the host and are absorbed here. Unexpected failures retain the\n * established CLI policy of logging details only in development before\n * requesting exit code one, or the code selected by `mapFailureToExitCode`.\n */\nexport async function runProcessApplication({\n  application,\n  host,\n  mapFailureToExitCode,\n}: RunProcessApplicationOptions): Promise<void> {\n  try {\n    await application(host)\n  } catch (error) {\n    if (error instanceof ProcessExitError) return\n    if (host.isDevelopment) host.io.error('An error occurred during startup:', error)\n    host.exit(resolveFailureExitCode(mapFailureToExitCode, error, 'handler'))\n  }\n}\n", "const AUTHORITY_PREFIX = /^[\\t\\n\\r ]*(?:[a-z][a-z\\d+.-]*:)?\\/\\//iu\nconst SPECIAL_SCHEME = /^[\\t\\n\\r ]*(?:https?|wss?|ftp):/iu\nconst AMBIGUOUS_AUTHORITY = /[\\s\\\\\\p{Cc}]/u\n\n/**\n * Removes the entire userinfo component from a hierarchical URL value.\n * Supports scheme://authority and //authority without canonicalizing the\n * remaining bytes. Noncanonical special-scheme values containing @, and\n * ambiguous credential-bearing authorities, are masked completely.\n *\n * This is a diagnostic string transformation, not URL validation. It does\n * not sanitize embedded prose, opaque URIs, URL objects, query/fragment\n * secrets, or credentials in paths. Use only the returned value for output;\n * keep the original value for connections and other app behavior.\n */\nexport function redactUrlCredentials(value: string): string {\n  const prefix = AUTHORITY_PREFIX.exec(value)?.[0]\n  if (prefix === undefined) {\n    return SPECIAL_SCHEME.test(value) && value.includes('@') ? '[REDACTED]' : value\n  }\n  const remainder = value.slice(prefix.length)\n  const delimiter = remainder.search(/[/?#]/u)\n  const authority = delimiter === -1 ? remainder : remainder.slice(0, delimiter)\n  const separator = authority.lastIndexOf('@')\n  if (separator === -1) {\n    // WHATWG network URL parsers can accept extra slashes/backslashes.\n    // Avoid echoing a credential-looking noncanonical network URL.\n    return SPECIAL_SCHEME.test(value) && /^[\\/\\\\]/u.test(remainder) && remainder.includes('@') ? '[REDACTED]' : value\n  }\n  const host = authority.slice(separator + 1)\n  if (host.length === 0 || AMBIGUOUS_AUTHORITY.test(authority)) return '[REDACTED]'\n  return prefix + host + (delimiter === -1 ? '' : remainder.slice(delimiter))\n}\n", "import { redactUrlCredentials } from './redactUrlCredentials.ts'\n\nconst REDACTED = '[REDACTED]'\n\n/**\n * Credential names that always redact, regardless of nesting, case, or\n * snake/hyphen separators. `connectionString` commonly embeds URL credentials.\n * Ambiguous public metadata names such as `seed` and `token` are not included.\n */\nexport const DEFAULT_REDACTED_KEY_NAMES: readonly string[] = [\n  'mnemonic',\n  'connectionString',\n  'apiKey',\n  'accessToken',\n  'refreshToken',\n  'sessionToken',\n  'authToken',\n  'authorization',\n]\n\n/**\n * Suffix-matched key names that redact. Catches any future `*PrivateKey`,\n * `*Secret`, or `*Password` field without enumerating them.\n */\nexport const DEFAULT_REDACTED_KEY_SUFFIX = /(PrivateKey|Secret|Password)$/i\n\nexport interface RedactConfigOptions {\n  /** Extra key names; case and snake/hyphen separators are ignored. */\n  readonly keyNames?: readonly string[]\n  /** Replaces the default suffix pattern; tests original keys without global/sticky state. */\n  readonly keySuffixPattern?: RegExp\n  /** Remove URL userinfo from string values by default. 'preserve' opts out; other string secrets and non-plain objects remain outside this policy. */\n  readonly urlCredentials?: 'preserve' | 'remove'\n}\n\nfunction normalizeKeyName(key: string): string {\n  return key.replaceAll(/[-_]/g, '').toLowerCase()\n}\n\nfunction isPlainRecord(value: object): value is Record<string, unknown> {\n  const prototype: unknown = Object.getPrototypeOf(value)\n  return prototype === Object.prototype || prototype === null\n}\n\nfunction redactValue(node: unknown, shouldRedactKey: (key: string) => boolean, sanitizeUrls: boolean): unknown {\n  if (typeof node === 'string' && sanitizeUrls) return redactUrlCredentials(node)\n  if (Array.isArray(node)) return node.map(item => redactValue(item, shouldRedactKey, sanitizeUrls))\n  if (node === null || typeof node !== 'object' || !isPlainRecord(node)) return node\n  const redacted: Record<string, unknown> = {}\n  for (const [key, value] of Object.entries(node)) {\n    redacted[key] = value !== undefined && value !== null && shouldRedactKey(key)\n      ? REDACTED\n      : redactValue(value, shouldRedactKey, sanitizeUrls)\n  }\n  return redacted\n}\n\n/**\n * Returns a copy of `config` with secret-bearing leaf values replaced by\n * `'[REDACTED]'` \u2014 the shape to hand to a config dump or startup log. The\n * input is never mutated: plain objects and arrays are rebuilt along the walk,\n * while non-plain values (dates, class instances) pass through by reference.\n * URL userinfo is removed from string values by default; query/fragment/path\n * secrets, embedded prose, and non-plain URL instances remain unredacted.\n * Set urlCredentials: 'preserve' to retain the previous string behavior.\n */\nexport function redactConfig<T>(config: T, options: RedactConfigOptions = {}): T {\n  const keyNames = new Set([...DEFAULT_REDACTED_KEY_NAMES, ...options.keyNames ?? []].map(normalizeKeyName))\n  const suppliedPattern = options.keySuffixPattern ?? DEFAULT_REDACTED_KEY_SUFFIX\n  const keySuffixPattern = new RegExp(suppliedPattern.source, suppliedPattern.flags.replaceAll(/[gy]/g, ''))\n  const shouldRedactKey = (key: string): boolean => {\n    const normalized = normalizeKeyName(key)\n    return keyNames.has(normalized)\n      || keySuffixPattern.test(options.keySuffixPattern === undefined ? normalized : key)\n  }\n  return redactValue(config, shouldRedactKey, options.urlCredentials !== 'preserve') as T\n}\n", "/** Resource offering an idempotent full shutdown (OpenTelemetry-style providers). */\nexport interface ShutdownResource {\n  shutdown(): unknown\n}\n\n/** Resource offering a cooperative stop; `false` means the stop failed. */\nexport interface StoppableResource {\n  stop(): unknown\n}\n\n/** Resource offering only hard disposal. */\nexport interface DestroyableResource {\n  destroy(): unknown\n}\n\nexport function isShutdownResource(value: unknown): value is ShutdownResource {\n  return typeof value === 'object' && value !== null && 'shutdown' in value && typeof value.shutdown === 'function'\n}\n\nexport function isStoppableResource(value: unknown): value is StoppableResource {\n  return typeof value === 'object' && value !== null && 'stop' in value && typeof value.stop === 'function'\n}\n\nexport function isDestroyableResource(value: unknown): value is DestroyableResource {\n  return typeof value === 'object' && value !== null && 'destroy' in value && typeof value.destroy === 'function'\n}\n\n/**\n * Stops one runtime resource at most once, by duck type.\n *\n * The value may be the resource itself or a promise of it (registries commonly\n * store creation promises). A stoppable resource is stopped \u2014 a literal\n * `false` result is promoted to a thrown failure so callers on a\n * first-error-wins sweep see it \u2014 otherwise a destroyable resource is\n * destroyed, or a shutdown-only resource is shut down. This preserves the\n * preference for stop() over destroy() when several methods are available.\n * Values offering none of these methods, and repeats of an already-stopped\n * resource (the same instance is often registered under several names), are skipped.\n * The caller must share the set across its cleanup paths or leave separately\n * owned resources to their owner. Calling a resource's teardown directly does\n * not participate in this invocation guarantee.\n */\nexport async function stopUniqueResource(value: unknown, stoppedResources: Set<object>): Promise<void> {\n  const resource: unknown = await value\n  if (typeof resource !== 'object' || resource === null || stoppedResources.has(resource)) return\n  stoppedResources.add(resource)\n  if (isStoppableResource(resource)) {\n    const stopped = await resource.stop()\n    if (stopped === false) throw new Error('Runtime resource stop() reported failure')\n  } else if (isDestroyableResource(resource)) {\n    await resource.destroy()\n  } else if (isShutdownResource(resource)) {\n    await resource.shutdown()\n  }\n}\n", "import {\n  InterruptJoin, type InterruptJoinHost, type InterruptJoinOptions,\n} from './InterruptJoin.ts'\n\n/** Application-owned cleanup invoked on the first process interrupt. */\nexport type ServiceStop = () => Promise<void> | void\n\n/**\n * Blocks until the first process interrupt (SIGINT/SIGTERM via the host),\n * then awaits exactly one `stop()` under a shutdown deadline.\n *\n * Resolves once shutdown completes so the caller can drain to a clean exit.\n * Rejects if `stop()` fails so the failure surfaces through the normal exit-code\n * mapper (typically `software`, 70) rather than being reported as success.\n * Hosts with an exit capability retain escalation until cleanup settles;\n * a second interrupt exits 130 and a timeout exits 1. Minimal hosts preserve\n * early listener disposal, restoring their native second-signal behavior,\n * while timeout rejects the pending join without inventing a process exit.\n * A registration failure still attempts cleanup of the already-running\n * service under the same deadline. The default is 15 seconds; zero disables\n * the watchdog. Invalid options reject before registration or cleanup.\n *\n * Use this for long-running command handlers that start a server or actor and\n * should exit only when the operator interrupts the process.\n */\nexport async function runServiceUntilInterrupt(\n  host: InterruptJoinHost,\n  stop: ServiceStop,\n  options: InterruptJoinOptions = {},\n): Promise<void> {\n  const join = new InterruptJoin(host, options)\n  const completion = Promise.withResolvers<void>()\n  let stopPromise: Promise<void> | undefined\n  function stopOnce(): Promise<void> {\n    stopPromise ??= (async () => {\n      try {\n        await stop()\n      } catch (error) {\n        throw serviceStopError(error)\n      }\n    })()\n    return stopPromise\n  }\n  await join.run(async () => {\n    try {\n      join.bind(async () => {\n        if (!join.hasExitCapability) {\n          try {\n            join.disposeInterrupt()\n          } catch (error) {\n            completion.reject(error)\n          }\n        }\n        try {\n          await stopOnce()\n          completion.resolve()\n        } catch (error) {\n          completion.reject(error)\n        }\n      })\n    } catch (registrationError) {\n      join.beginShutdown()\n      try {\n        await join.wait(stopOnce())\n      } catch (cleanupError) {\n        if (join.isEscalation(cleanupError)) throw cleanupError\n        if (cleanupError !== registrationError) {\n          throw new AggregateError([registrationError, cleanupError], 'Service interrupt registration failed and cleanup failed', { cause: cleanupError })\n        }\n      }\n      throw registrationError\n    }\n    await join.wait(completion.promise)\n  })\n}\n\nfunction serviceStopError(error: unknown): Error {\n  try {\n    return error instanceof Error ? error : new Error(String(error))\n  } catch (conversionError) {\n    return new AggregateError([error, conversionError], 'Service stop failed and its rejection could not be converted to an Error', { cause: error })\n  }\n}\n"],
  "mappings": ";AAWO,SAAS,0BACd,aACuC;AACvC,QAAM,oBAAoB,oBAAI,IAAsD;AACpF,QAAM,QAAkB,CAAC;AACzB,aAAW,cAAc,aAAa;AACpC,QAAI,kBAAkB,IAAI,WAAW,IAAI,GAAG;AAC1C,YAAM,IAAI,MAAM,kBAAkB,WAAW,IAAI,yBAAyB;AAAA,IAC5E;AACA,sBAAkB,IAAI,WAAW,MAAM,UAAU;AACjD,UAAM,KAAK,WAAW,IAAI;AAAA,EAC5B;AAEA,SAAO;AAAA,IACL,OAAO,OAAO,OAAO,KAAK;AAAA,IAC1B,MAAM,MAAM,MAAc,SAAoC;AAC5D,YAAM,aAAa,kBAAkB,IAAI,IAAI;AAC7C,UAAI,eAAe,OAAW,OAAM,IAAI,MAAM,kBAAkB,IAAI,EAAE;AACtE,aAAO,MAAM,WAAW,MAAM,OAAO;AAAA,IACvC;AAAA,EACF;AACF;;;AC1BO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAChD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,4BAAN,cAAwC,MAAM;AAAA,EAC1C;AAAA,EAET,YAAY,WAAmB,OAA6B;AAC1D,UAAM,UAAU,SAAS,8BAA8B,KAAK,EAAE;AAC9D,SAAK,OA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