import { r as KlawConfig } from "./types.klaw-xKUw_Rz7.js"; import { c as ExecApprovalRequestPayload$1, o as ExecApprovalDecision } from "./exec-approvals-D24np_n8.js"; import { t as ChannelId } from "./channel-id.types-B_AcMzNT.js"; import { t as ModelCatalogEntry } from "./model-catalog.types-DT_5duBc.js"; import { n as RuntimeEnv } from "./runtime-BPmgxFyD.js"; import { i as WizardPrompter } from "./prompts-BamwNu0a.js"; import { t as SecretInputMode } from "./provider-auth-types-CMPBtz92.js"; import { r as ChannelAccountSnapshot } from "./types.core-BSyOg0vX.js"; import { s as PluginApprovalRequestPayload } from "./plugin-approvals-C1U8clbW.js"; import { Ko as OperatorScope } from "./index-D_HHRfnu.js"; import { Ut as RequestFrame, W as ConnectParams, ut as ErrorShape } from "./types-Ba0tNRpZ.js"; import { t as CliDeps } from "./deps.types-qyR-Pvbb.js"; import { t as HeartbeatSummary } from "./heartbeat-summary-DfmEKa0g.js"; import { n as CronJobCreate, r as CronJobPatch, t as CronJob } from "./types-C9ddMZvJ.js"; import { n as createSubsystemLogger } from "./subsystem-JE3Q0Wyz.js"; import { n as BufferedAgentEvent, t as ChatAbortControllerEntry } from "./chat-abort-DsCJCeT_.js"; import { monitorEventLoopDelay, performance } from "node:perf_hooks"; import { WebSocket as WebSocket$1 } from "ws"; //#region src/commands/daemon-runtime.d.ts type GatewayDaemonRuntime = "node" | "bun"; //#endregion //#region src/commands/onboard-types.d.ts type OnboardMode = "local" | "remote"; /** * Auth choices are plugin-owned contract ids plus a few legacy aliases that * are normalized elsewhere (for example `oauth` -> `setup-token`). */ type BuiltInAuthChoice = /** @deprecated Use `setup-token`. */"oauth" | "setup-token" | "token" | "apiKey" | "custom-api-key" | "skip"; type AuthChoice = BuiltInAuthChoice | (string & {}); type GatewayAuthChoice = "token" | "password"; type ResetScope = "config" | "config+creds+sessions" | "full"; type GatewayBind = "loopback" | "lan" | "auto" | "custom" | "tailnet"; type TailscaleMode = "off" | "serve" | "funnel"; type NodeManagerChoice = "npm" | "pnpm" | "bun"; type OnboardDynamicProviderOptions = { /** * Provider-specific non-interactive auth flags are plugin-owned and keyed by * manifest `providerAuthChoices[].optionKey` values. */ [optionKey: string]: unknown; }; type OnboardOptions = OnboardDynamicProviderOptions & { mode?: OnboardMode; /** "manual" is an alias for "advanced". */ flow?: "quickstart" | "advanced" | "manual" | "import"; workspace?: string; nonInteractive?: boolean; /** Required for non-interactive setup; skips the interactive risk prompt when true. */ acceptRisk?: boolean; reset?: boolean; resetScope?: ResetScope; authChoice?: AuthChoice; /** Used when `authChoice=token` in non-interactive mode. */ tokenProvider?: string; /** Used when `authChoice=token` in non-interactive mode. */ token?: string; /** Used when `authChoice=token` in non-interactive mode. */ tokenProfileId?: string; /** Used when `authChoice=token` in non-interactive mode. */ tokenExpiresIn?: string; /** API key persistence mode for setup flows (default: plaintext). */ secretInputMode?: SecretInputMode; arceeaiApiKey?: string; cloudflareAiGatewayAccountId?: string; cloudflareAiGatewayGatewayId?: string; customBaseUrl?: string; customApiKey?: string; lmstudioApiKey?: string; customModelId?: string; customProviderId?: string; customCompatibility?: "openai" | "anthropic"; customImageInput?: boolean; gatewayPort?: number; gatewayBind?: GatewayBind; gatewayAuth?: GatewayAuthChoice; gatewayToken?: string; gatewayTokenRefEnv?: string; gatewayPassword?: string; tailscale?: TailscaleMode; tailscaleResetOnExit?: boolean; installDaemon?: boolean; daemonRuntime?: GatewayDaemonRuntime; skipChannels?: boolean; /** @deprecated Legacy alias for `skipChannels`. */ skipProviders?: boolean; skipSkills?: boolean; skipBootstrap?: boolean; skipSearch?: boolean; skipHealth?: boolean; skipUi?: boolean; skipHooks?: boolean; nodeManager?: NodeManagerChoice; remoteUrl?: string; remoteToken?: string; importFrom?: string; importSource?: string; importSecrets?: boolean; json?: boolean; }; //#endregion //#region src/infra/voicewake-routing.d.ts type VoiceWakeRouteTarget = { mode: "current"; agentId?: undefined; sessionKey?: undefined; } | { agentId: string; sessionKey?: undefined; mode?: undefined; } | { sessionKey: string; agentId?: undefined; mode?: undefined; }; type VoiceWakeRouteRule = { trigger: string; target: VoiceWakeRouteTarget; }; type VoiceWakeRoutingConfig = { version: 1; defaultTarget: VoiceWakeRouteTarget; routes: VoiceWakeRouteRule[]; updatedAtMs: number; }; //#endregion //#region src/gateway/model-pricing-cache-state.d.ts type GatewayModelPricingHealthSource = "openrouter" | "litellm" | "bootstrap" | "refresh"; type GatewayModelPricingHealth = { state: "ok" | "degraded" | "disabled"; sources: Array<{ source: GatewayModelPricingHealthSource; state: "ok" | "degraded"; lastFailureAt?: number; detail?: string; }>; lastFailureAt?: number; detail?: string; }; //#endregion //#region src/gateway/server/event-loop-health.d.ts type GatewayEventLoopHealthReason = "event_loop_delay" | "event_loop_utilization" | "cpu"; type GatewayEventLoopHealth = { degraded: boolean; reasons: GatewayEventLoopHealthReason[]; intervalMs: number; delayP99Ms: number; delayMaxMs: number; utilization: number; cpuCoreRatio: number; }; //#endregion //#region src/commands/health.types.d.ts type ChannelAccountHealthSummary = { accountId: string; configured?: boolean; linked?: boolean; authAgeMs?: number | null; probe?: unknown; lastProbeAt?: number | null; [key: string]: unknown; }; type ChannelHealthSummary = ChannelAccountHealthSummary & { accounts?: Record; }; type AgentHealthSummary = { agentId: string; name?: string; isDefault: boolean; heartbeat: HeartbeatSummary; sessions: HealthSummary["sessions"]; }; type PluginHealthErrorSummary = { id: string; origin: string; activated: boolean; activationSource?: string; activationReason?: string; failurePhase?: string; error: string; }; type PluginHealthSummary = { loaded: string[]; errors: PluginHealthErrorSummary[]; }; type ModelPricingHealthSummary = GatewayModelPricingHealth; type HealthSummary = { ok: true; ts: number; durationMs: number; eventLoop?: GatewayEventLoopHealth; plugins?: PluginHealthSummary; modelPricing?: ModelPricingHealthSummary; channels: Record; channelOrder: string[]; channelLabels: Record; heartbeatSeconds: number; defaultAgentId: string; agents: AgentHealthSummary[]; sessions: { path: string; count: number; recent: Array<{ key: string; updatedAt: number | null; age: number | null; }>; }; }; //#endregion //#region src/cron/service/list-page-types.d.ts type CronJobsEnabledFilter = "all" | "enabled" | "disabled"; type CronJobsSortBy = "nextRunAtMs" | "updatedAtMs" | "name"; type CronSortDir = "asc" | "desc"; type CronListPageOptions = { includeDisabled?: boolean; limit?: number; offset?: number; query?: string; enabled?: CronJobsEnabledFilter; sortBy?: CronJobsSortBy; sortDir?: CronSortDir; agentId?: string; }; type CronListPageResult = { jobs: TJobs; total: number; offset: number; limit: number; hasMore: boolean; nextOffset: number | null; }; //#endregion //#region src/cron/service/state.d.ts type CronRunMode = "due" | "force"; type CronWakeMode = "now" | "next-heartbeat"; type CronStatusSummary = { enabled: boolean; storePath: string; jobs: number; nextWakeAtMs: number | null; }; type CronRunResult = { ok: true; ran: true; } | { ok: true; enqueued: true; runId: string; } | { ok: true; ran: false; reason: "not-due"; } | { ok: true; ran: false; reason: "already-running"; } | { ok: false; }; type CronRemoveResult = { ok: true; removed: boolean; } | { ok: false; removed: false; }; type CronAddResult = CronJob; type CronUpdateResult = CronJob; type CronListResult = CronJob[]; type CronAddInput = CronJobCreate; type CronUpdateInput = CronJobPatch; //#endregion //#region src/cron/service-contract.d.ts type CronWakeResult = { ok: true; } | { ok: false; reason?: "unwakeable-session-key"; }; type CronServiceRunResult = CronRunResult | { ok: true; ran: false; reason: "invalid-spec"; }; interface CronServiceContract { start(): Promise; stop(): void; status(): Promise; list(opts?: { includeDisabled?: boolean; }): Promise; listPage(opts?: CronListPageOptions): Promise; add(input: CronAddInput): Promise; update(id: string, patch: CronUpdateInput): Promise; remove(id: string): Promise; run(id: string, mode?: CronRunMode): Promise; enqueueRun(id: string, mode?: CronRunMode): Promise; getJob(id: string): CronJob | undefined; readJob(id: string): Promise; getDefaultAgentId(): string | undefined; wake(opts: { mode: CronWakeMode; text: string; sessionKey?: string; }): CronWakeResult; } //#endregion //#region src/wizard/session.d.ts type WizardStepOption = { value: unknown; label: string; hint?: string; }; type WizardStep = { id: string; type: "note" | "select" | "text" | "confirm" | "multiselect" | "progress" | "action"; title?: string; message?: string; format?: "plain"; options?: WizardStepOption[]; initialValue?: unknown; placeholder?: string; sensitive?: boolean; executor?: "gateway" | "client"; }; type WizardSessionStatus = "running" | "done" | "cancelled" | "error"; type WizardNextResult = { done: boolean; step?: WizardStep; status: WizardSessionStatus; error?: string; }; declare class WizardSession { private runner; private currentStep; private stepDeferred; private pendingTerminalResolution; private answerDeferred; private status; private error; constructor(runner: (prompter: WizardPrompter) => Promise); next(): Promise; answer(stepId: string, value: unknown): Promise; cancel(): void; pushStep(step: WizardStep): void; private run; awaitAnswer(step: WizardStep): Promise; private resolveStep; getStatus(): WizardSessionStatus; getError(): string | undefined; } //#endregion //#region src/gateway/exec-approval-manager.d.ts type ExecApprovalRequestPayload = ExecApprovalRequestPayload$1; type ExecApprovalRecord = { id: string; request: TPayload; createdAtMs: number; expiresAtMs: number; requestedByConnId?: string | null; requestedByDeviceId?: string | null; requestedByClientId?: string | null; requestedByDeviceTokenAuth?: boolean; resolvedAtMs?: number; decision?: ExecApprovalDecision; consumedDecision?: ExecApprovalDecision; resolvedBy?: string | null; }; type ExecApprovalIdLookupResult = { kind: "exact" | "prefix"; id: string; } | { kind: "ambiguous"; ids: string[]; } | { kind: "none"; }; declare class ExecApprovalManager { private pending; create(request: TPayload, timeoutMs: number, id?: string | null): ExecApprovalRecord; /** * Register an approval record and return a promise that resolves when the decision is made. * This separates registration (synchronous) from waiting (async), allowing callers to * confirm registration before the decision is made. */ register(record: ExecApprovalRecord, timeoutMs: number): Promise; /** * @deprecated Use register() instead for explicit separation of registration and waiting. */ waitForDecision(record: ExecApprovalRecord, timeoutMs: number): Promise; resolve(recordId: string, decision: ExecApprovalDecision, resolvedBy?: string | null): boolean; expire(recordId: string, resolvedBy?: string | null): boolean; getSnapshot(recordId: string): ExecApprovalRecord | null; listPendingRecords(): ExecApprovalRecord[]; consumeAllowOnce(recordId: string): boolean; /** * Wait for decision on an already-registered approval. * Returns the decision promise if the ID is pending, null otherwise. */ awaitDecision(recordId: string): Promise | null; lookupApprovalId(input: string, opts?: { includeResolved?: boolean; filter?: (record: ExecApprovalRecord) => boolean; }): ExecApprovalIdLookupResult; lookupPendingId(input: string): ExecApprovalIdLookupResult; } //#endregion //#region src/gateway/methods/descriptor.d.ts declare const NODE_GATEWAY_METHOD_SCOPE: "node"; declare const DYNAMIC_GATEWAY_METHOD_SCOPE: "dynamic"; type GatewayMethodScope = OperatorScope | typeof NODE_GATEWAY_METHOD_SCOPE | typeof DYNAMIC_GATEWAY_METHOD_SCOPE; type GatewayMethodOwner = { kind: "core"; area: string; } | { kind: "plugin"; pluginId: string; } | { kind: "channel"; channelId: string; } | { kind: "aux"; area: string; }; type GatewayMethodStartupAvailability = "available" | "unavailable-until-sidecars"; type GatewayMethodHandler = (opts: never) => unknown; type GatewayMethodDescriptor = { name: string; handler: GatewayMethodHandler; scope: GatewayMethodScope; owner: GatewayMethodOwner; startup?: GatewayMethodStartupAvailability; controlPlaneWrite?: boolean; advertise?: boolean; description?: string; }; type GatewayMethodRegistryView = { getHandler: (name: string) => GatewayMethodHandler | undefined; listMethods: () => string[]; listAdvertisedMethods: () => string[]; getScope: (name: string) => GatewayMethodScope | undefined; isStartupUnavailable: (name: string) => boolean; isControlPlaneWrite: (name: string) => boolean; descriptors: () => readonly GatewayMethodDescriptor[]; }; //#endregion //#region src/gateway/plugin-node-capability.d.ts declare const PLUGIN_NODE_CAPABILITY_PATH_PREFIX = "/__klaw__/cap"; declare const DEFAULT_PLUGIN_NODE_CAPABILITY_TTL_MS: number; type PluginNodeCapabilitySurface = { surface: string; ttlMs?: number; scopeKey?: string; }; type PluginNodeCapabilityClient = { pluginSurfaceUrls?: Record; pluginNodeCapabilitySurfaces?: Record; pluginNodeCapabilities?: Record; }; type NormalizedPluginNodeCapabilityUrl = { pathname: string; capability?: string; rewrittenUrl?: string; scopedPath: boolean; malformedScopedPath: boolean; }; declare function mintPluginNodeCapabilityToken(): string; declare function buildPluginNodeCapabilityScopedHostUrl(baseUrl: string, capability: string): string | undefined; declare function normalizePluginNodeCapabilityScopedUrl(rawUrl: string): NormalizedPluginNodeCapabilityUrl; //#endregion //#region src/gateway/server/ws-types.d.ts type GatewayWsClient = PluginNodeCapabilityClient & { socket: WebSocket$1; connect: ConnectParams; connId: string; isDeviceTokenAuth?: boolean; usesSharedGatewayAuth: boolean; sharedGatewaySessionGeneration?: string; presenceKey?: string; clientIp?: string; internal?: { approvalRuntime?: boolean; }; }; //#endregion //#region src/gateway/node-registry.d.ts type NodeSession = { nodeId: string; connId: string; client: GatewayWsClient; clientId?: string; clientMode?: string; displayName?: string; platform?: string; version?: string; coreVersion?: string; uiVersion?: string; deviceFamily?: string; modelIdentifier?: string; remoteIp?: string; declaredCaps: string[]; caps: string[]; declaredCommands: string[]; commands: string[]; declaredPermissions?: Record; permissions?: Record; pathEnv?: string; connectedAtMs: number; }; type NodeInvokeResult = { ok: boolean; payload?: unknown; payloadJSON?: string | null; error?: { code?: string; message?: string; } | null; }; type NodeConnectivityResult = { ok: true; } | { ok: false; error: { code: string; message: string; }; }; declare const SERIALIZED_EVENT_PAYLOAD: unique symbol; type SerializedEventPayload = { readonly json: string; readonly [SERIALIZED_EVENT_PAYLOAD]: true; }; declare class NodeRegistry { private nodesById; private nodesByConn; private pendingInvokes; private authorizedSystemRunEvents; register(client: GatewayWsClient, opts: { remoteIp?: string | undefined; }): NodeSession; unregister(connId: string): string | null; listConnected(): NodeSession[]; get(nodeId: string): NodeSession | undefined; checkConnectivity(nodeId: string, timeoutMs?: number): Promise; updateCommands(nodeId: string, commands: readonly string[]): NodeSession | null; updateSurface(nodeId: string, surface: { caps?: readonly string[]; commands: readonly string[]; permissions?: Record | undefined; }): NodeSession | null; invoke(params: { nodeId: string; command: string; params?: unknown; timeoutMs?: number; idempotencyKey?: string; }): Promise; authorizeSystemRunEvent(params: { nodeId: string; connId?: string; runId?: string; sessionKey: string; terminal: boolean; }): boolean; private rememberAuthorizedSystemRunEvent; private forgetAuthorizedSystemRunEvent; private authorizedSystemRunEventExpiresAt; private matchAuthorizedSystemRunEvent; private matchSingleAuthorizedSystemRunEvent; private authorizedSystemRunSessionMatches; private allowsLegacyMacRunIdFallback; private pruneAuthorizedSystemRunEvents; private authorizedSystemRunEventKey; handleInvokeResult(params: { id: string; nodeId: string; connId: string | undefined; ok: boolean; payload?: unknown; payloadJSON?: string | null; error?: { code?: string; message?: string; } | null; }): boolean; sendEvent(nodeId: string, event: string, payload?: unknown): boolean; sendEventRaw(nodeId: string, event: string, payloadJSON?: SerializedEventPayload | null): boolean; private sendEventInternal; private sendEventRawInternal; private sendEventToSession; } //#endregion //#region src/gateway/server-broadcast-types.d.ts type GatewayBroadcastStateVersion = { presence?: number; health?: number; }; type GatewayBroadcastOpts = { dropIfSlow?: boolean; stateVersion?: GatewayBroadcastStateVersion; }; type GatewayBroadcastFn = (event: string, payload: unknown, opts?: GatewayBroadcastOpts) => void; type GatewayBroadcastToConnIdsFn = (event: string, payload: unknown, connIds: ReadonlySet, opts?: GatewayBroadcastOpts) => void; //#endregion //#region src/gateway/server-channel-runtime.types.d.ts type ChannelRuntimeSnapshot = { channels: Partial>; channelAccounts: Partial>>; }; //#endregion //#region src/gateway/server-shared.d.ts type DedupeEntry = { ts: number; ok: boolean; payload?: unknown; error?: ErrorShape; }; //#endregion //#region src/gateway/server-methods/shared-types.d.ts type SubsystemLogger = ReturnType; type GatewayClient = { connect: ConnectParams; connId?: string; clientIp?: string; pluginSurfaceUrls?: Record; pluginNodeCapabilitySurfaces?: Record; pluginNodeCapabilities?: Record; isDeviceTokenAuth?: boolean; internal?: { allowModelOverride?: boolean; approvalRuntime?: boolean; pluginRuntimeOwnerId?: string; }; }; type RespondFn = (ok: boolean, payload?: unknown, error?: ErrorShape, meta?: Record) => void; type GatewayRequestContext = { deps: CliDeps; cron: CronServiceContract; cronStorePath: string; getRuntimeConfig: () => KlawConfig; execApprovalManager?: ExecApprovalManager; pluginApprovalManager?: ExecApprovalManager; loadGatewayModelCatalog: (params?: { readOnly?: boolean; }) => Promise; getHealthCache: () => HealthSummary | null; refreshHealthSnapshot: (opts?: { probe?: boolean; includeSensitive?: boolean; }) => Promise; logHealth: { error: (message: string) => void; }; logGateway: SubsystemLogger; incrementPresenceVersion: () => number; getHealthVersion: () => number; broadcast: GatewayBroadcastFn; broadcastToConnIds: GatewayBroadcastToConnIdsFn; nodeSendToSession: (sessionKey: string, event: string, payload: unknown) => void; nodeSendToAllSubscribed: (event: string, payload: unknown) => void; nodeSubscribe: (nodeId: string, sessionKey: string) => void; nodeUnsubscribe: (nodeId: string, sessionKey: string) => void; nodeUnsubscribeAll: (nodeId: string) => void; hasConnectedTalkNode: () => boolean; hasExecApprovalClients?: (excludeConnId?: string) => boolean; getApprovalClientConnIds?: (params?: { excludeConnId?: string; filter?: (client: GatewayClient, record?: ExecApprovalRecord) => boolean; record?: ExecApprovalRecord; }) => ReadonlySet; disconnectClientsForDevice?: (deviceId: string, opts?: { role?: string; }) => void; disconnectClientsUsingSharedGatewayAuth?: () => void; enforceSharedGatewayAuthGenerationForConfigWrite?: (nextConfig: KlawConfig) => void; nodeRegistry: NodeRegistry; agentRunSeq: Map; chatAbortControllers: Map; chatAbortedRuns: Map; chatRunBuffers: Map; chatDeltaSentAt: Map; chatDeltaLastBroadcastLen: Map; chatDeltaLastBroadcastText: Map; agentDeltaSentAt: Map; bufferedAgentEvents: Map; addChatRun: (sessionId: string, entry: { sessionKey: string; clientRunId: string; }) => void; removeChatRun: (sessionId: string, clientRunId: string, sessionKey?: string) => { sessionKey: string; clientRunId: string; } | undefined; subscribeSessionEvents: (connId: string) => void; unsubscribeSessionEvents: (connId: string) => void; subscribeSessionMessageEvents: (connId: string, sessionKey: string) => void; unsubscribeSessionMessageEvents: (connId: string, sessionKey: string) => void; unsubscribeAllSessionEvents: (connId: string) => void; getSessionEventSubscriberConnIds: () => ReadonlySet; registerToolEventRecipient: (runId: string, connId: string) => void; dedupe: Map; wizardSessions: Map; findRunningWizard: () => string | null; purgeWizardSession: (id: string) => void; getRuntimeSnapshot: () => ChannelRuntimeSnapshot; getEventLoopHealth?: () => GatewayEventLoopHealth | undefined; startChannel: (channel: ChannelId, accountId?: string) => Promise; stopChannel: (channel: ChannelId, accountId?: string) => Promise; markChannelLoggedOut: (channelId: ChannelId, cleared: boolean, accountId?: string) => void; wizardRunner: (opts: OnboardOptions, runtime: RuntimeEnv, prompter: WizardPrompter) => Promise; broadcastVoiceWakeChanged: (triggers: string[]) => void; broadcastVoiceWakeRoutingChanged: (config: VoiceWakeRoutingConfig) => void; unavailableGatewayMethods?: ReadonlySet; }; type GatewayRequestOptions = { req: RequestFrame; client: GatewayClient | null; isWebchatConnect: (params: ConnectParams | null | undefined) => boolean; respond: RespondFn; context: GatewayRequestContext; methodRegistry?: GatewayMethodRegistryView; }; type GatewayRequestHandlerOptions = { req: RequestFrame; params: Record; client: GatewayClient | null; isWebchatConnect: (params: ConnectParams | null | undefined) => boolean; respond: RespondFn; context: GatewayRequestContext; }; type GatewayRequestHandler = (opts: GatewayRequestHandlerOptions) => Promise | void; type GatewayRequestHandlers = Record; //#endregion export { CronServiceContract as _, GatewayRequestOptions as a, NodeSession as c, PLUGIN_NODE_CAPABILITY_PATH_PREFIX as d, PluginNodeCapabilitySurface as f, GatewayMethodDescriptor as g, normalizePluginNodeCapabilityScopedUrl as h, GatewayRequestHandlers as i, DEFAULT_PLUGIN_NODE_CAPABILITY_TTL_MS as l, mintPluginNodeCapabilityToken as m, GatewayRequestHandler as n, RespondFn as o, buildPluginNodeCapabilityScopedHostUrl as p, GatewayRequestHandlerOptions as r, GatewayBroadcastToConnIdsFn as s, GatewayRequestContext as t, NormalizedPluginNodeCapabilityUrl as u };