import { At as FasedAgentConfig, Bt as WalletProviderId, Ct as RuntimeEnv, F as ChannelAccountSnapshot, Ft as ModelThinkingLevel, G as ChannelId, Ht as WalletRuntimeMode, It as ModelThinkingMode, Mt as ModelCompatConfig, Nt as ModelProviderAuthMode, Ot as sendMessageDiscord, Sn as SecretRef, St as sendMessageIMessage, Ut as WalletToolAccessMode, Vt as WalletRuntimeKind, Wt as CronConfig, bt as sendMessageSlack, gt as sendMessageWhatsApp, jt as ModelCapabilityConfig, o as WizardPrompter, vt as sendMessageTelegram, xt as sendMessageSignal } from "./types.plugin-BcSBq42x.js"; import { Api, Model, OAuthCredentials } from "@mariozechner/pi-ai"; import * as _sinclair_typebox0 from "@sinclair/typebox"; import { Static } from "@sinclair/typebox"; import { lookup } from "node:dns/promises"; import { WebSocket as WebSocket$1 } from "ws"; //#region src/config/paths.d.ts /** * State directory for mutable data (sessions, logs, caches). * Can be overridden via FASED_STATE_DIR. * Default: ~/.fased */ declare function resolveStateDir(env?: NodeJS.ProcessEnv, homedir?: () => string): string; declare function resolveGatewayPort(cfg?: FasedAgentConfig, env?: NodeJS.ProcessEnv): number; //#endregion //#region src/infra/exec-approvals.d.ts type ExecHost = "sandbox" | "gateway" | "node"; type ExecTarget = "auto" | ExecHost; type ExecSecurity = "deny" | "allowlist" | "full"; type ExecAsk = "off" | "on-miss" | "always"; type SystemRunApprovalBindingV1 = { version: 1; argv: string[]; cwd: string | null; agentId: string | null; sessionKey: string | null; envHash: string | null; }; type SystemRunApprovalPlanV2 = { version: 2; argv: string[]; cwd: string | null; rawCommand: string | null; agentId: string | null; sessionKey: string | null; }; type ExecApprovalRequestPayload$1 = { command: string; commandArgv?: string[]; envKeys?: string[]; systemRunBindingV1?: SystemRunApprovalBindingV1 | null; systemRunPlanV2?: SystemRunApprovalPlanV2 | null; cwd?: string | null; nodeId?: string | null; host?: string | null; security?: string | null; ask?: string | null; agentId?: string | null; resolvedPath?: string | null; sessionKey?: string | null; turnSourceChannel?: string | null; turnSourceTo?: string | null; turnSourceAccountId?: string | null; turnSourceThreadId?: string | number | null; }; type ExecApprovalDecision = "allow-once" | "allow-always" | "deny"; //#endregion //#region src/infra/net/ssrf.d.ts declare class SsrFBlockedError extends Error { constructor(message: string); } type LookupFn = typeof lookup; type SsrFPolicy = { allowPrivateNetwork?: boolean; dangerouslyAllowPrivateNetwork?: boolean; allowRfc2544BenchmarkRange?: boolean; allowedHostnames?: string[]; hostnameAllowlist?: string[]; }; declare function isPrivateIpAddress(address: string, policy?: SsrFPolicy): boolean; declare function isBlockedHostname(hostname: string): boolean; declare function isBlockedHostnameOrIp(hostname: string, policy?: SsrFPolicy): boolean; //#endregion //#region src/logging/levels.d.ts declare const ALLOWED_LOG_LEVELS: readonly ["silent", "fatal", "error", "warn", "info", "debug", "trace"]; type LogLevel = (typeof ALLOWED_LOG_LEVELS)[number]; //#endregion //#region src/logging/subsystem.d.ts type SubsystemLogger$1 = { subsystem: string; isEnabled: (level: LogLevel, target?: "any" | "console" | "file") => boolean; trace: (message: string, meta?: Record) => void; debug: (message: string, meta?: Record) => void; info: (message: string, meta?: Record) => void; warn: (message: string, meta?: Record) => void; error: (message: string, meta?: Record) => void; fatal: (message: string, meta?: Record) => void; raw: (message: string) => void; child: (name: string) => SubsystemLogger$1; }; declare function createSubsystemLogger(subsystem: string): SubsystemLogger$1; //#endregion //#region src/utils.d.ts declare function clampNumber(value: number, min: number, max: number): number; /** Alias for clampNumber (shorter, more common name) */ declare const clamp: typeof clampNumber; /** * Escapes special regex characters in a string so it can be used in a RegExp constructor. */ declare function escapeRegExp(value: string): string; /** * Safely parse JSON, returning null on error instead of throwing. */ declare function safeParseJson(raw: string): T | null; declare function normalizeE164(number: string): string; declare function sleep(ms: number): Promise; //#endregion //#region src/web/auth-store.d.ts declare function webAuthExists(authDir?: string): Promise; declare function logoutWeb(params: { authDir?: string; isLegacyAuthDir?: boolean; runtime?: RuntimeEnv; }): Promise; declare function readWebSelfId(authDir?: string): { readonly e164: string | null; readonly jid: string | null; }; /** * Return the age (in milliseconds) of the cached WhatsApp web auth state, or null when missing. * Helpful for heartbeats/observability to spot stale credentials. */ declare function getWebAuthAgeMs(authDir?: string): number | null; declare function logWebSelfId(authDir?: string, runtime?: RuntimeEnv, includeChannelPrefix?: boolean): void; //#endregion //#region src/gateway/protocol/schema/channels.d.ts declare const WebLoginStartParamsSchema: _sinclair_typebox0.TObject<{ channel: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; force: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>; timeoutMs: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>; verbose: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>; accountId: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; }>; declare const WebLoginWaitParamsSchema: _sinclair_typebox0.TObject<{ channel: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; timeoutMs: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>; accountId: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; }>; //#endregion //#region src/gateway/protocol/schema/commands.d.ts declare const CommandsListResultSchema: _sinclair_typebox0.TObject<{ commands: _sinclair_typebox0.TArray<_sinclair_typebox0.TObject<{ name: _sinclair_typebox0.TString; nativeName: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; textAliases: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>; description: _sinclair_typebox0.TString; category: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"session">, _sinclair_typebox0.TLiteral<"options">, _sinclair_typebox0.TLiteral<"status">, _sinclair_typebox0.TLiteral<"management">, _sinclair_typebox0.TLiteral<"media">, _sinclair_typebox0.TLiteral<"tools">, _sinclair_typebox0.TLiteral<"docks">]>>; source: _sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"native">, _sinclair_typebox0.TLiteral<"skill">, _sinclair_typebox0.TLiteral<"plugin">]>; scope: _sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"text">, _sinclair_typebox0.TLiteral<"native">, _sinclair_typebox0.TLiteral<"both">]>; acceptsArgs: _sinclair_typebox0.TBoolean; args: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TObject<{ name: _sinclair_typebox0.TString; description: _sinclair_typebox0.TString; type: _sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"string">, _sinclair_typebox0.TLiteral<"number">, _sinclair_typebox0.TLiteral<"boolean">]>; required: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>; choices: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TObject<{ value: _sinclair_typebox0.TString; label: _sinclair_typebox0.TString; }>>>; dynamic: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>; }>>>; }>>; }>; //#endregion //#region src/gateway/protocol/schema/frames.d.ts declare const ConnectParamsSchema: _sinclair_typebox0.TObject<{ minProtocol: _sinclair_typebox0.TInteger; maxProtocol: _sinclair_typebox0.TInteger; client: _sinclair_typebox0.TObject<{ id: _sinclair_typebox0.TUnion<_sinclair_typebox0.TLiteral<"webchat-ui" | "fased-control-ui" | "webchat" | "cli" | "gateway-client" | "fased-macos" | "fased-ios" | "fased-android" | "node-host" | "test" | "fingerprint" | "fased-probe">[]>; displayName: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; version: _sinclair_typebox0.TString; platform: _sinclair_typebox0.TString; deviceFamily: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; modelIdentifier: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; mode: _sinclair_typebox0.TUnion<_sinclair_typebox0.TLiteral<"webchat" | "cli" | "test" | "ui" | "backend" | "node" | "probe">[]>; instanceId: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; }>; caps: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>; commands: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>; permissions: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TBoolean>>; pathEnv: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; role: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; scopes: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>; device: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{ id: _sinclair_typebox0.TString; publicKey: _sinclair_typebox0.TString; signature: _sinclair_typebox0.TString; signedAt: _sinclair_typebox0.TInteger; nonce: _sinclair_typebox0.TString; }>>; auth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{ token: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; deviceToken: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; password: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; }>>; locale: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; userAgent: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; }>; declare const ErrorShapeSchema: _sinclair_typebox0.TObject<{ code: _sinclair_typebox0.TString; message: _sinclair_typebox0.TString; details: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnknown>; retryable: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>; retryAfterMs: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>; }>; declare const RequestFrameSchema: _sinclair_typebox0.TObject<{ type: _sinclair_typebox0.TLiteral<"req">; id: _sinclair_typebox0.TString; method: _sinclair_typebox0.TString; params: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnknown>; }>; //#endregion //#region src/gateway/protocol/schema/logs-chat.d.ts declare const ChatInjectParamsSchema: _sinclair_typebox0.TObject<{ sessionKey: _sinclair_typebox0.TString; message: _sinclair_typebox0.TString; label: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; }>; //#endregion //#region src/gateway/protocol/schema/push.d.ts declare const PushTestParamsSchema: _sinclair_typebox0.TObject<{ nodeId: _sinclair_typebox0.TString; title: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; body: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; environment: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>; }>; //#endregion //#region src/gateway/protocol/schema/types.d.ts type ConnectParams = Static; type RequestFrame = Static; type ErrorShape = Static; type PushTestParams = Static; type CommandsListResult = Static; type WebLoginStartParams = Static; type WebLoginWaitParams = Static; type ChatInjectParams = Static; //#endregion //#region src/commands/daemon-runtime.d.ts type GatewayDaemonRuntime = "node" | "bun"; //#endregion //#region src/commands/onboard-types.d.ts type OnboardMode = "local" | "remote"; type KnownAuthChoice = "oauth" | "anthropic-oauth" | "setup-token" | "claude-cli" | "token" | "chutes" | "chutes-api-key" | "vllm" | "openai-codex" | "openai-api-key" | "openrouter-api-key" | "litellm-api-key" | "ai-gateway-api-key" | "cloudflare-ai-gateway-api-key" | "moonshot-api-key" | "moonshot-api-key-cn" | "kimi-code-api-key" | "synthetic-api-key" | "venice-api-key" | "together-api-key" | "huggingface-api-key" | "codex-cli" | "apiKey" | "gemini-api-key" | "google-gemini-cli" | "zai-api-key" | "zai-coding-global" | "zai-coding-cn" | "zai-global" | "zai-cn" | "xiaomi-api-key" | "minimax-cloud" | "minimax" | "minimax-api" | "minimax-api-key-cn" | "minimax-api-lightning" | "minimax-portal" | "opencode-zen" | "github-copilot" | "copilot-proxy" | "qwen-api-key" | "qwen-coding-plan-api-key" | "xai-oauth" | "xai-device-code" | "xai-api-key" | "qianfan-api-key" | "custom-api-key" | "skip"; type AuthChoice = KnownAuthChoice | (string & {}); type GatewayAuthChoice = "token" | "password"; type OnboardRepairScope = "sessions" | "auth" | "auth+sessions"; type GatewayBind = "loopback" | "lan" | "auto" | "custom" | "tailnet"; type TailscaleMode = "off" | "serve" | "funnel"; type NodeManagerChoice = "npm" | "pnpm" | "bun"; type OnboardOptions = { hostProfile?: "local" | "hosting"; /** Internal flag set by root-started installer sessions that already provisioned host-maintenance capability. */ hostSecurityCapable?: boolean; /** Internal flag for post-bootstrap hosted reruns from the app user over Tailscale. */ hostMaintenanceSession?: boolean; /** Internal flag for root-only host security preflight/prep flows. */ hostSecurityOnly?: boolean; allowInsecure?: boolean; swapGb?: number; mode?: OnboardMode; /** "manual" is an alias for "advanced". */ flow?: "quickstart" | "advanced" | "manual"; workspace?: string; nonInteractive?: boolean; /** Required for non-interactive onboarding; skips the interactive risk prompt when true. */ acceptRisk?: boolean; reset?: boolean; resetScope?: OnboardRepairScope; 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; /** Store prompted credentials as plaintext config value or SecretRef. */ secretInputMode?: string; anthropicApiKey?: string; openaiApiKey?: string; openrouterApiKey?: string; mistralApiKey?: string; litellmApiKey?: string; aiGatewayApiKey?: string; cloudflareAiGatewayAccountId?: string; cloudflareAiGatewayGatewayId?: string; cloudflareAiGatewayApiKey?: string; moonshotApiKey?: string; kimiCodeApiKey?: string; geminiApiKey?: string; zaiApiKey?: string; xiaomiApiKey?: string; minimaxApiKey?: string; syntheticApiKey?: string; veniceApiKey?: string; togetherApiKey?: string; huggingfaceApiKey?: string; byteplusApiKey?: string; volcengineApiKey?: string; opencodeZenApiKey?: string; xaiApiKey?: string; qianfanApiKey?: string; qwenApiKey?: string; qwenCodingPlanApiKey?: string; customBaseUrl?: string; customApiKey?: string; customModelId?: string; customProviderId?: string; customCompatibility?: "openai" | "anthropic"; allowPrivateNetwork?: boolean; gatewayPort?: number; gatewayBind?: GatewayBind; gatewayAuth?: GatewayAuthChoice; gatewayToken?: string; gatewayPassword?: string; tailscale?: TailscaleMode; tailscaleResetOnExit?: boolean; installDaemon?: boolean; daemonRuntime?: GatewayDaemonRuntime; skipChannels?: boolean; /** @deprecated Legacy alias for `skipChannels`. */ skipProviders?: boolean; skipSkills?: boolean; skipHealth?: boolean; /** Use a short-circuit health check path when gateway is already healthy. */ fastHealth?: boolean; skipUi?: boolean; nodeManager?: NodeManagerChoice; remoteUrl?: string; remoteToken?: string; walletEnabled?: boolean; walletMode?: WalletRuntimeMode; walletRuntime?: WalletRuntimeKind; walletProviders?: string; walletDefaultProvider?: WalletProviderId; walletChains?: string; walletHost?: string; walletPort?: number; walletInstallEnabled?: boolean; walletInstallVersion?: string; walletDirectSigning?: boolean; walletSolanaAllowPrograms?: string; walletSolanaMaxPerTx?: string; walletSolanaMaxDaily?: string; walletToolAccessMode?: WalletToolAccessMode; walletToolAccessAllowAgents?: string; json?: boolean; [key: string]: unknown; }; //#endregion //#region src/agents/model-catalog-normalized.d.ts type ModelCatalogSource = "configured" | "runtime" | "provider-api" | "current-preview" | "provider-index" | "manifest"; //#endregion //#region src/agents/model-metadata.d.ts type ModelFeature = "text" | "vision" | "reasoning" | "tools" | "json" | "audio" | "video" | "speech"; type ModelCapabilityConfidence = "verified" | "declared" | "inferred" | "unknown"; type ModelAvailabilitySource = "provider-api" | "runtime-catalog" | "configured" | "provider-plugin" | "reviewed-catalog" | "curated-recommendation"; type ModelCapabilitySource = "provider-api" | "official-docs" | "runtime" | "configured" | "inferred" | "unknown"; type ModelPriceMetadata = { input: number; output: number; cacheRead: number; cacheWrite: number; unit: "usd-per-million-tokens"; }; type ModelCredentialRouteMetadata = { id: string; label: string; authMode: ModelProviderAuthMode; }; type ModelMetadata = { ref: string; provider: string; publicProviderId: string; publicProviderLabel: string; model: string; label: string; contextWindow?: number; maxTokens?: number; apiRoute?: string; features: ModelFeature[]; thinkingLevels?: ModelThinkingLevel[]; defaultThinkingLevel?: ModelThinkingLevel; thinkingMode?: ModelThinkingMode; reasoningBudgetSupported?: boolean; streaming: boolean; capabilityConfidence: ModelCapabilityConfidence; capabilitySource: ModelCapabilitySource; capabilityRetrievedAt?: string; retrievedAt: string; availabilitySource: ModelAvailabilitySource; authRoute: string; authMode: ModelProviderAuthMode; credentialRoute: ModelCredentialRouteMetadata; credentialRoutes: ModelCredentialRouteMetadata[]; price?: ModelPriceMetadata; privateNetwork: boolean; privateNetworkAllowed: boolean; recommended?: boolean; recommendationRank?: number; default?: boolean; }; //#endregion //#region src/agents/model-catalog.d.ts type ModelCatalogEntry = { id: string; name: string; provider: string; contextWindow?: number; maxTokens?: number; reasoning?: boolean; input?: Array<"text" | "image">; capabilities?: ModelCapabilityConfig; compat?: ModelCompatConfig; baseUrl?: string; api?: string; catalogSource?: ModelCatalogSource; metadata?: ModelMetadata; cost?: { input: number; output: number; cacheRead: number; cacheWrite: number; }; }; //#endregion //#region src/cli/deps.d.ts type CliDeps = { sendMessageWhatsApp: typeof sendMessageWhatsApp; sendMessageTelegram: typeof sendMessageTelegram; sendMessageDiscord: typeof sendMessageDiscord; sendMessageSlack: typeof sendMessageSlack; sendMessageSignal: typeof sendMessageSignal; sendMessageIMessage: typeof sendMessageIMessage; }; declare function createDefaultDeps(): CliDeps; //#endregion //#region src/gateway/server-channels.d.ts type ChannelRuntimeSnapshot = { channels: Partial>; channelAccounts: Partial>>; }; //#endregion //#region src/gateway/server-startup-trace.d.ts type GatewayStartupTraceEntry = { name: string; durationMs: number; }; type GatewayStartupTraceSnapshot = { entries: GatewayStartupTraceEntry[]; totalMs: number; summary: string; recordedAtMs: number; }; //#endregion //#region src/gateway/server-startup-readiness.d.ts type GatewayStartupServiceStatus = "unknown" | "ready"; type GatewayStartupServicePhase = { name: string; durationMs: number; }; type GatewayStartupServiceReadiness = { id: string; label: string; status: GatewayStartupServiceStatus; durationMs: number; phases: GatewayStartupServicePhase[]; }; type GatewayStartupReadinessSnapshot = { status: GatewayStartupServiceStatus; recordedAtMs?: number; totalMs?: number; summary?: string; services: GatewayStartupServiceReadiness[]; }; //#endregion //#region src/infra/heartbeat-wake.d.ts type HeartbeatRunResult = { status: "ran"; durationMs: number; } | { status: "skipped"; reason: string; } | { status: "failed"; reason: string; }; //#endregion //#region src/infra/heartbeat-runner.d.ts type HeartbeatSummary = { enabled: boolean; every: string; everyMs: number | null; prompt: string; target: string; model?: string; ackMaxChars: number; }; //#endregion //#region src/commands/health.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 AgentHeartbeatSummary = HeartbeatSummary; type AgentHealthSummary = { agentId: string; name?: string; isDefault: boolean; heartbeat: AgentHeartbeatSummary; sessions: HealthSummary["sessions"]; }; type HealthSummary = { /** * Convenience top-level flag for UIs (e.g. WebChat) that only need a binary * "can talk to the gateway" signal. If this payload exists, the gateway RPC * succeeded, so this is always `true`. */ ok: true; ts: number; durationMs: number; channels: Record; channelOrder: string[]; channelLabels: Record; /** Legacy: default agent heartbeat seconds (rounded). */ heartbeatSeconds: number; defaultAgentId: string; agents: AgentHealthSummary[]; sessions: { path: string; count: number; recent: Array<{ key: string; updatedAt: number | null; age: number | null; }>; }; startup?: GatewayStartupReadinessSnapshot; }; //#endregion //#region src/cron/types.d.ts type CronSchedule = { kind: "at"; at: string; } | { kind: "every"; everyMs: number; anchorMs?: number; } | { kind: "cron"; expr: string; tz?: string; /** Optional deterministic stagger window in milliseconds (0 keeps exact schedule). */ staggerMs?: number; }; type CronSessionTarget = "main" | "isolated"; type CronWakeMode = "next-heartbeat" | "now"; type CronMessageChannel = ChannelId | "last"; type CronDeliveryMode = "none" | "announce" | "webhook"; type CronDelivery = { mode: CronDeliveryMode; channel?: CronMessageChannel; to?: string; accountId?: string; bestEffort?: boolean; }; type CronDeliveryPatch = Partial; type CronFailureAlert = { after?: number; channel?: CronMessageChannel; to?: string; cooldownMs?: number; mode?: "announce" | "webhook"; accountId?: string; }; type CronTaskTriggerKind = "schedule" | "heartbeat" | "webhook" | "channel" | "manual" | "event"; type CronTaskExecutionMode = "auto" | "agent-turn" | "skill-only" | "no-model"; type CronTaskMemoryScope = "none" | "session-summary" | "pinned" | "search" | "agent"; type CronTaskSkillScope = "none" | "selected" | "agent-default"; type CronTaskModelPolicy = { mode?: "agent-default" | "task-override" | "auto" | "none"; role?: "cheapCheck" | "strong" | "escalation" | "coding" | "summarizer"; model?: string; thinking?: string; escalationModel?: string; }; type CronTaskBudgetPolicy = { maxTokensPerRun?: number; maxCostUsdPerRun?: number; maxRunsPerHour?: number; }; type CronTaskStopPolicy = { /** * Disable the task after the first successful run. Useful for tasks that * keep retrying until they produce a valid result. */ onSuccess?: boolean; /** * Disable the task when the run summary/output includes one of these * markers. Comparisons are case-insensitive. */ outputIncludes?: string[]; /** Disable after this many successful runs. */ maxSuccessfulRuns?: number; /** Disable after this many total terminal runs, including skipped/error. */ maxTotalRuns?: number; }; type CronTaskSkillAction = { /** Exact runtime tool name to execute without model inference. */toolName: string; /** JSON object passed directly to the tool. */ input?: Record; }; type CronTaskCoordinationMode = "none" | "consult" | "parallel"; type CronTaskCoordinationEvidenceStatus = "needs_approval" | "accepted" | "completed" | "forbidden" | "error" | "skipped"; type CronTaskCoordinationEvidence = { agentId: string; mode: CronTaskCoordinationMode; status: CronTaskCoordinationEvidenceStatus; childSessionKey?: string; runId?: string; summary?: string; outputText?: string; error?: string; createdAtMs?: number; }; type CronTaskCoordinationPolicy = { /** * Stored coordination intent for local task rooms. The coordination graph node * consumes this policy and records task-room evidence for any consulted Agent. */ mode?: CronTaskCoordinationMode; /** Agent ids to consult or run beside the owner Agent. */ agents?: string[]; /** Upper bound for planner-selected helpers when agents are not fully explicit. */ maxAgents?: number; /** Max evaluator/requested coordination rounds for one task. Default: 1. */ maxRounds?: number; /** Require user approval before a task actually delegates work to other Agents. */ requireApproval?: boolean; /** Stop cleanly when consulted Agents provide usable evidence. */ stopWhenAdvisorsAgree?: boolean; /** Use stronger model escalation when consulted Agents disagree or fail. */ escalateWhenAdvisorsConflict?: boolean; }; type CronTaskPlannerStrategy = "agent-default" | "cheap-model" | "strong-model" | "skill-only" | "no-model"; type CronTaskAdaptiveRoute = "agent-default" | "cheap-model" | "strong-model" | "skill-only" | "no-model" | "agent-evidence"; type CronTaskAdaptiveRunSample = { atMs: number; status: CronRunStatus; route: CronTaskAdaptiveRoute; taskType: string; durationMs?: number; totalTokens?: number; model?: string; provider?: string; resultSource?: CronRunResultSource; resultAdapter?: string; modelUsed?: boolean; deliveryStatus?: CronDeliveryStatus; evaluatorAction?: CronTaskEvaluatorDecision["action"]; }; type CronTaskAdaptiveRoutingDecision = { source: "history"; route: CronTaskAdaptiveRoute; reason: string; confidence?: "low" | "medium" | "high"; taskType: string; sampleSize: number; successRate?: number; failureRate?: number; averageDurationMs?: number; averageTokens?: number; signals?: string[]; createdAtMs: number; }; type CronTaskAdaptiveRoutingState = { taskType?: string; samples?: CronTaskAdaptiveRunSample[]; totalRuns?: number; successfulRuns?: number; failedRuns?: number; blockedRuns?: number; modelRuns?: number; noModelRuns?: number; skillOnlyRuns?: number; agentEvidenceRuns?: number; totalDurationMs?: number; totalTokens?: number; lastDecision?: CronTaskAdaptiveRoutingDecision; }; type CronTaskWorkflowStepKind = "collect" | "analyze" | "evaluate" | "deliver"; type CronTaskWorkflowSubstep = { id: "plan-analysis" | "execute-tool-or-model" | "synthesize"; label: string; description?: string; usesModel?: boolean; usesTool?: boolean; retryable?: boolean; checkpointKeys?: string[]; }; type CronTaskWorkflowStep = { id: CronTaskWorkflowStepKind; label: string; description?: string; usesModel?: boolean; usesTool?: boolean; retryable?: boolean; checkpointKeys?: string[]; substeps?: CronTaskWorkflowSubstep[]; }; type CronTaskWorkflowGraphNodeKind = "collect" | "tool" | "model" | "coordination" | "validation" | "synthesize" | "deliver"; type CronTaskSourceRole = "primary" | "verification" | "enrichment"; type CronTaskSourceVerificationStatus = "compatible" | "insufficient_evidence" | "conflict_suspected"; type CronTaskSourceQualityBand = "high" | "medium" | "low" | "unavailable"; type CronTaskSourceAuthority = "runtime" | "direct" | "live" | "generic" | "unknown"; type CronTaskWorkflowGraphNode = { id: string; label: string; kind: CronTaskWorkflowGraphNodeKind; description?: string; dependsOn?: string[]; /** Optional graph nodes may fail/skipped without blocking downstream analysis. */ optional?: boolean; sourceRole?: CronTaskSourceRole; sourcePriority?: number; sourceFreshness?: "static" | "runtime" | "live"; sourceExpectedOutputType?: string; /** Concrete URL for trusted/direct source nodes. */ sourceUrl?: string; /** Concrete trusted source text when a URL is not available. */ sourceText?: string; /** Saved trusted-source registry id, when this node came from source memory. */ trustedSourceId?: string; sourceLabel?: string; usesModel?: boolean; usesTool?: boolean; retryable?: boolean; checkpointKeys?: string[]; }; type CronTaskWorkflowGraph = { version: 1; /** Monotonic workflow graph revision. Repaired graphs increment this. */ graphRevision?: number; /** Previous graph revision when this graph was produced by repair. */ parentRevision?: number; /** Monotonic repair revision applied to this graph. */ repairRevision?: number; entryNodeId: string; terminalNodeIds: string[]; nodes: CronTaskWorkflowGraphNode[]; }; type CronTaskPlannerDecision = { source: "heuristic"; strategy: CronTaskPlannerStrategy; rationale: string; confidence?: "low" | "medium" | "high"; signals?: string[]; steps?: CronTaskWorkflowStep[]; graph?: CronTaskWorkflowGraph; }; type CronTaskEvaluatorPolicy = { /** Enable one-shot escalation when the run output includes an escalation cue. */escalateOnSignal?: boolean; /** Case-insensitive line-leading cues that request escalation. */ signalIncludes?: string[]; /** Max evaluator-triggered escalations for this task. Default: 1. */ maxEscalations?: number; }; type CronTaskRepairPolicy = { /** Allow safe automatic retry when the evaluator has already produced a replacement source graph. */autoRetryReplacement?: boolean; /** Allow optional/enrichment source paths to be stopped automatically after repeated source failures. */ autoStopOptionalSources?: boolean; /** Max automatic source graph repairs from one evaluator decision. Default: 1. */ maxAutoRepairsPerRun?: number; /** Require user approval before replacing primary/verification sources with non-deterministic replacements. */ requireApprovalForPrimarySource?: boolean; }; type CronTaskEvaluatorDecision = { source: "heuristic"; action: "none" | "escalate" | "needs_access" | "request_sources" | "retry_sources" | "ask_agent" | "stop"; reason: string; signal?: string; stopCode?: CronTaskRepairStopCode; history?: { consecutiveNoSignalRuns?: number; escalationRuns?: number; maxEscalations?: number; lastSignalAtMs?: number; lastSignal?: string; repairAttempts?: number; maxRepairAttempts?: number; coordinationRuns?: number; maxCoordinationRuns?: number; }; }; type CronTaskRepairStopCode = "insufficient_sources" | "source_access_missing" | "repair_limit_reached" | "conflicting_sources" | "needs_user_source"; type CronTaskRepairStop = { code: CronTaskRepairStopCode; reason: string; atMs: number; sourceNodeId?: string; sourceRole?: CronTaskSourceRole; limit?: number; }; type CronTaskPendingEscalation = { reason: string; signal?: string; createdAtMs: number; sourceRunAtMs: number; }; type CronTaskPendingCoordination = { reason: string; signal?: string; agents: string[]; mode?: CronTaskCoordinationMode; createdAtMs: number; sourceRunAtMs: number; }; type CronTaskGraphRepairPlan = { action: "add_source" | "replace_source"; nodeId: string; toolName: "web_search" | "web_fetch" | "gateway" | "wallet" | "mining" | "offers"; reason: string; createdAtMs: number; replacesNodeId?: string; graphRevision?: number; parentRevision?: number; repairRevision?: number; reusedNodeIds?: string[]; invalidatedNodeIds?: string[]; requeuedNodeIds?: string[]; }; type CronTaskGraphRepairReplay = { runId?: string; parentRunId?: string; graphRevision: number; parentRevision?: number; repairRevision: number; repairAttempt: number; maxRepairAttempts: number; repairedAtMs: number; reusedNodeIds: string[]; invalidatedNodeIds: string[]; requeuedNodeIds: string[]; reason: string; }; type CronTaskRepairRecoveryAction = "configure_source" | "add_trusted_source" | "retry_replacement" | "stop_source_path"; type CronTaskTrustedSourceKind = "url" | "note"; type CronTaskTrustedSource = { id: string; source: string; kind: CronTaskTrustedSourceKind; createdAtMs: number; updatedAtMs?: number; lastUsedAtMs?: number; useCount?: number; agentId?: string; sessionKey?: string; taskType?: string; addedFromTaskId?: string; label?: string; active?: boolean; lastRunAtMs?: number; lastOutcome?: CronRunStatus; lastQualityScore?: number; lastQualityBand?: CronTaskSourceQualityBand; lastError?: string; successCount?: number; failureCount?: number; }; type CronTaskSourceListFilters = { includeInactive?: boolean; agentId?: string; sessionKey?: string; taskType?: string; query?: string; }; type CronTaskSourceListResult = { sources: CronTaskTrustedSource[]; total: number; }; type CronTaskSourceUpdateResult = { ok: true; source: CronTaskTrustedSource; } | { ok: false; reason: string; }; type CronTaskSourceRemoveResult = { ok: true; id: string; removed: boolean; } | { ok: false; id: string; removed: false; reason: string; }; type CronTaskExecutionPolicy = { /** User-facing objective for planner/evaluator surfaces. */objective?: string; /** User-facing success condition. Current runtime stores and displays it. */ successCriteria?: string; triggerKind?: CronTaskTriggerKind; executionMode?: CronTaskExecutionMode; memoryScope?: CronTaskMemoryScope; skillScope?: CronTaskSkillScope; allowedSkills?: string[]; skillAction?: CronTaskSkillAction; modelPolicy?: CronTaskModelPolicy; coordination?: CronTaskCoordinationPolicy; budget?: CronTaskBudgetPolicy; stop?: CronTaskStopPolicy; planner?: CronTaskPlannerDecision; evaluator?: CronTaskEvaluatorPolicy; repairPolicy?: CronTaskRepairPolicy; trustedSources?: CronTaskTrustedSource[]; }; type CronRunStatus = "ok" | "error" | "skipped" | "blocked"; type CronDeliveryStatus = "delivered" | "not-delivered" | "unknown" | "not-requested"; type CronUsageSummary = { input_tokens?: number; output_tokens?: number; total_tokens?: number; cache_read_tokens?: number; cache_write_tokens?: number; }; type CronRunTelemetry = { model?: string; provider?: string; usage?: CronUsageSummary; policy?: CronRunPolicyTelemetry; }; type CronRunResultSource = "model" | "direct-tool" | "direct-text"; type CronTaskRunCheckpointPhase = "reserved" | "running" | "finalizing"; type CronTaskRunCheckpointTrigger = "schedule" | "startup" | "manual"; type CronTaskRunCheckpoint = { runId: string; phase: CronTaskRunCheckpointPhase; trigger: CronTaskRunCheckpointTrigger; attempt: number; startedAtMs: number; heartbeatAtMs: number; leaseExpiresAtMs: number; }; type CronTaskRunCheckpointSummary = { runId?: string; phase?: CronTaskRunCheckpointPhase | "finished" | "recovered"; trigger?: CronTaskRunCheckpointTrigger; attempt?: number; startedAtMs?: number; heartbeatAtMs?: number; leaseExpiresAtMs?: number; completedAtMs?: number; recoveredAtMs?: number; reason?: string; }; type CronRunPolicyTelemetry = { objective?: string; successCriteria?: string; requestedExecutionMode?: CronTaskExecutionMode; effectiveExecutionMode?: Exclude; memoryScope?: CronTaskMemoryScope; skillScope?: CronTaskSkillScope; skills?: { count: number; names: string[]; skillFilter?: string[]; }; modelPolicyMode?: CronTaskModelPolicy["mode"]; modelOverride?: string; escalationModel?: string; modelSource?: string; budget?: CronTaskBudgetPolicy; stop?: CronTaskStopPolicy; planner?: CronTaskPlannerDecision; evaluator?: CronTaskEvaluatorDecision; adaptive?: CronTaskAdaptiveRoutingDecision; sourceVerificationStatus?: CronTaskSourceVerificationStatus; sourceConflictCount?: number; needsSourceReview?: boolean; escalatedBecause?: "source_conflict"; coordination?: { total: number; completed: number; needsApproval: number; failed: number; agents: string[]; }; sourceQuality?: { bestSourceId?: string; bestScore?: number; lowQualityCount?: number; lowQualitySourceIds?: string[]; unavailableCount?: number; unavailableSourceIds?: string[]; sources?: Array<{ id: string; trustedSourceId?: string; status?: CronRunStatus; role?: CronTaskSourceRole; optional?: boolean; required?: boolean; score?: number; }>; }; resultSource?: CronRunResultSource; resultAdapter?: string; modelUsed?: boolean; runCheckpoint?: CronTaskRunCheckpointSummary; }; type CronRunOutcome = { status: CronRunStatus; error?: string; /** Optional classifier for execution errors to guide fallback behavior. */ errorKind?: "delivery-target" | "needs-access"; summary?: string; /** Last non-empty run output. Used by task stop/evaluation policy. */ outputText?: string; sessionId?: string; sessionKey?: string; }; type CronTaskAccessBlock = { code: string; service?: string; reason: string; setupCommand?: string; setupPath?: string; source?: "preflight" | "run-output"; detectedAtMs?: number; }; type CronPayload = { kind: "systemEvent"; text: string; } | { kind: "agentTurn"; message: string; /** Optional model override (provider/model or alias). */ model?: string; thinking?: string; timeoutSeconds?: number; lightContext?: boolean; allowUnsafeExternalContent?: boolean; deliver?: boolean; channel?: CronMessageChannel; to?: string; bestEffortDeliver?: boolean; }; type CronPayloadPatch = { kind: "systemEvent"; text?: string; } | { kind: "agentTurn"; message?: string; model?: string; thinking?: string; timeoutSeconds?: number; lightContext?: boolean; allowUnsafeExternalContent?: boolean; deliver?: boolean; channel?: CronMessageChannel; to?: string; bestEffortDeliver?: boolean; }; type CronJobState = { nextRunAtMs?: number; /** Back-compat scalar marker for old stores and read paths. */ runningAtMs?: number; /** Durable active task run lease/checkpoint. */ activeRun?: CronTaskRunCheckpoint; /** Last completed run checkpoint. */ lastRunCheckpoint?: CronTaskRunCheckpointSummary; /** Last interrupted run recovered on startup or maintenance. */ lastRecoveredRun?: CronTaskRunCheckpointSummary; lastRunAtMs?: number; /** Preferred execution outcome field. */ lastRunStatus?: CronRunStatus; /** Back-compat alias for lastRunStatus. */ lastStatus?: CronRunStatus; lastError?: string; lastDurationMs?: number; /** Number of consecutive execution errors (reset on success). Used for backoff. */ consecutiveErrors?: number; /** Number of consecutive schedule computation errors. Auto-disables job after threshold. */ scheduleErrorCount?: number; /** Explicit delivery outcome, separate from execution outcome. */ lastDeliveryStatus?: CronDeliveryStatus; /** Delivery-specific error text when available. */ lastDeliveryError?: string; /** Whether the last run's output was delivered to the target channel. */ lastDelivered?: boolean; /** Start of the current per-task run budget accounting window. */ budgetWindowStartedAtMs?: number; /** Runs reserved in the current per-task run budget accounting window. */ budgetRunsInWindow?: number; /** Total terminal run count. */ totalRuns?: number; /** Total successful run count. */ successfulRuns?: number; /** Why the scheduler disabled this task automatically. */ stopReason?: string; /** Missing credential/access state that blocks recurring execution until fixed. */ needsAccess?: CronTaskAccessBlock; /** One-shot evaluator request to run the next cycle with stronger planning. */ pendingEscalation?: CronTaskPendingEscalation; /** One-shot evaluator/user request to rerun with selected Agent evidence. */ pendingCoordination?: CronTaskPendingCoordination; /** Last dynamic graph repair applied after evaluator source-quality review. */ lastGraphRepair?: CronTaskGraphRepairPlan & { applied?: boolean; }; /** All dynamic graph repairs applied after the latest evaluator source-quality review. */ lastGraphRepairs?: Array; /** Current workflow graph revision after dynamic repair. */ graphRevision?: number; /** Current workflow repair revision. */ repairRevision?: number; /** Total graph repair attempts for this task. */ graphRepairAttempts?: number; /** Repair attempts by original/repaired source node id. */ graphRepairSourceAttempts?: Record; /** Repair attempts by source role. */ graphRepairRoleAttempts?: Partial>; /** Last terminal repair stop state, when repair was not safe to continue. */ lastGraphRepairStop?: CronTaskRepairStop; /** Last planned/applied repair replay metadata. */ lastGraphRepairReplay?: CronTaskGraphRepairReplay; /** Explicit approval marker allowing a coordination graph node to spawn Agents. */ coordinationApprovedAtMs?: number; /** Latest task-room evidence recorded by a coordination graph node. */ lastCoordinationEvidence?: CronTaskCoordinationEvidence[]; /** Total evaluator-triggered escalation runs queued for this task. */ evaluatorEscalationRuns?: number; /** Total evaluator/user-triggered Agent coordination runs queued for this task. */ evaluatorCoordinationRuns?: number; /** Consecutive successful cheap checks that did not request escalation. */ evaluatorConsecutiveNoSignalRuns?: number; /** Last escalation signal observed by the evaluator. */ evaluatorLastSignal?: string; /** Timestamp for the last escalation signal observed by the evaluator. */ evaluatorLastSignalAtMs?: number; /** Number of evaluator-requested source retry runs after weak/incomplete evidence. */ evaluatorSourceRetryRuns?: number; /** Last post-run evaluator decision. */ lastEvaluatorDecision?: CronTaskEvaluatorDecision; /** How the last run produced its output: model, direct tool adapter, or direct text. */ lastRunResultSource?: CronRunResultSource; /** Deterministic adapter id used by the last run, when applicable. */ lastRunResultAdapter?: string; /** Whether the last run invoked a model. */ lastRunModelUsed?: boolean; /** Source of the model selected for the last run, when model-backed. */ lastRunModelSource?: string; /** Compact run-history telemetry and next-run adaptive routing decision. */ adaptiveRouting?: CronTaskAdaptiveRoutingState; /** Session id created for the latest isolated task run, when one exists. */ lastRunSessionId?: string; /** Session key created for the latest isolated task run, when one exists. */ lastRunSessionKey?: string; }; type CronJob = { id: string; agentId?: string; /** Origin session namespace for reminder delivery and wake routing. */ sessionKey?: string; name: string; description?: string; enabled: boolean; deleteAfterRun?: boolean; createdAtMs: number; updatedAtMs: number; schedule: CronSchedule; sessionTarget: CronSessionTarget; wakeMode: CronWakeMode; payload: CronPayload; delivery?: CronDelivery; executionPolicy?: CronTaskExecutionPolicy; failureAlert?: CronFailureAlert | false; state: CronJobState; }; type CronJobCreate = Omit & { state?: Partial; }; type CronJobPatch = Partial> & { payload?: CronPayloadPatch; delivery?: CronDeliveryPatch; executionPolicy?: CronTaskExecutionPolicy | null; state?: Partial; }; type CronTaskRepairRecoveryResult = { ok: true; action: CronTaskRepairRecoveryAction; job: CronJob; message: string; setupPath?: string; setupCommand?: string; } | { ok: false; action: CronTaskRepairRecoveryAction; reason: string; job?: CronJob; setupPath?: string; setupCommand?: string; }; //#endregion //#region src/cron/task-run-queue.d.ts type CronTaskRunQueueStatus = "queued" | "running" | "ok" | "error" | "skipped" | "blocked" | "canceled" | "recovered"; type CronTaskRunQueueStepRetryPolicy = { maxAttempts: number; retryDelayMs: number; backoffMultiplier: number; retryOn: "error" | "lease-expired" | "error-or-lease-expired"; }; type CronTaskRunQueueStepResumeState = { resumable: boolean; reason: string; checkpointKeys: string[]; updatedAtMs: number; }; type CronTaskRunQueueWorkerSummary = { workerId: string; running: number; expired: number; runIds: string[]; nextLeaseExpiresAtMs?: number; lastLeaseAtMs?: number; }; type CronTaskRunQueueActiveRunSummary = { runId: string; jobId: string; jobName: string; agentId?: string; sessionKey?: string; status: CronTaskRunQueueStatus; stepId: string; attempt: number; maxAttempts: number; retryPolicy?: CronTaskRunQueueStepRetryPolicy; nextRetryAtMs?: number; resume?: CronTaskRunQueueStepResumeState; leaseOwner?: string; leaseExpiresAtMs?: number; leaseExpired: boolean; queuedAtMs: number; startedAtMs?: number; updatedAtMs: number; }; type CronTaskRunQueueRecentRunSummary = { runId: string; jobId: string; jobName: string; agentId?: string; sessionKey?: string; status: CronTaskRunQueueStatus; error?: string; resultStatus?: CronRunStatus; queuedAtMs: number; startedAtMs?: number; completedAtMs?: number; updatedAtMs: number; }; type CronTaskRunQueueSummary = { path: string; total: number; queued: number; running: number; terminal: number; cancelRequested: number; expiredLeases: number; byStatus: Record; workers: CronTaskRunQueueWorkerSummary[]; activeRuns: CronTaskRunQueueActiveRunSummary[]; recentRuns: CronTaskRunQueueRecentRunSummary[]; }; //#endregion //#region src/cron/graph-context.d.ts type CronTaskGraphContextItem = { nodeId: string; nodeKind?: CronTaskWorkflowGraphNodeKind; label?: string; optional?: boolean; sourceRole?: CronTaskSourceRole; sourcePriority?: number; sourceFreshness?: "static" | "runtime" | "live"; sourceExpectedOutputType?: string; trustedSourceId?: string; toolName?: string; status?: CronRunStatus; summary?: string; outputText?: string; error?: string; sourceQualityScore?: number; sourceQualityBand?: CronTaskSourceQualityBand; sourceAuthority?: CronTaskSourceAuthority; sourceQualityRationale?: string[]; verificationStatus?: CronTaskSourceVerificationStatus; sourceConflictCount?: number; needsReview?: boolean; evaluatorSignal?: string; coordinationEvidence?: CronTaskCoordinationEvidence[]; }; type CronGraphNodeHandlerResult = { status: CronRunStatus; summary?: string; outputText?: string; error?: string; toolName?: string; toolInput?: Record; rawResult?: unknown; coordinationEvidence?: CronTaskCoordinationEvidence[]; }; type CronGraphNodeHandlerParams = { job: CronJob; message: string; runId: string; nodeId: string; nodeKind: CronTaskWorkflowGraphNodeKind; graphContext: CronTaskGraphContextItem[]; abortSignal?: AbortSignal; }; //#endregion //#region src/cron/service/state.d.ts type CronEvent = { jobId: string; action: "added" | "updated" | "removed" | "started" | "finished" | "blocked"; runAtMs?: number; durationMs?: number; status?: CronRunStatus; error?: string; summary?: string; delivered?: boolean; deliveryStatus?: CronDeliveryStatus; deliveryError?: string; sessionId?: string; sessionKey?: string; nextRunAtMs?: number; } & CronRunTelemetry; type Logger = { debug: (obj: unknown, msg?: string) => void; info: (obj: unknown, msg?: string) => void; warn: (obj: unknown, msg?: string) => void; error: (obj: unknown, msg?: string) => void; }; type CronServiceDeps = { nowMs?: () => number; log: Logger; storePath: string; cronEnabled: boolean; /** CronConfig for session retention settings. */ cronConfig?: CronConfig; /** Default agent id for jobs without an agent id. */ defaultAgentId?: string; /** Resolve session store path for a given agent id. */ resolveSessionStorePath?: (agentId?: string) => string; /** Path to the session store (sessions.json) for reaper use. */ sessionStorePath?: string; enqueueSystemEvent: (text: string, opts?: { agentId?: string; sessionKey?: string; contextKey?: string; }) => void; requestHeartbeatNow: (opts?: { reason?: string; agentId?: string; sessionKey?: string; }) => void; runHeartbeatOnce?: (opts?: { reason?: string; agentId?: string; sessionKey?: string; }) => Promise; /** * WakeMode=now: max time to wait for runHeartbeatOnce to stop returning * { status:"skipped", reason:"requests-in-flight" } before falling back to * requestHeartbeatNow. */ wakeNowHeartbeatBusyMaxWaitMs?: number; /** WakeMode=now: delay between runHeartbeatOnce retries while busy. */ wakeNowHeartbeatBusyRetryDelayMs?: number; runIsolatedAgentJob: (params: { job: CronJob; message: string; abortSignal?: AbortSignal; graphContext?: CronTaskGraphContextItem[]; /** * When true, execution should produce a replayable result but leave * outbound channel delivery to the durable queue's `deliver` step. */ deferDelivery?: boolean; }) => Promise<{ summary?: string; /** Last non-empty agent text output (not truncated). */ outputText?: string; /** * `true` when the isolated run already delivered its output to the target * channel (including matching messaging-tool sends). See: * https://github.com/fased-ai/fased/issues/15692 */ delivered?: boolean; /** * `true` when announce/direct delivery was attempted for this run, even * if the final per-message ack status is uncertain. */ deliveryAttempted?: boolean; } & CronRunOutcome & CronRunTelemetry>; runGraphNodeHandler?: (params: CronGraphNodeHandlerParams) => Promise; deliverIsolatedAgentJobResult?: (params: { job: CronJob; runId: string; result: CronRunOutcome & CronRunTelemetry & { delivered?: boolean; deliveryAttempted?: boolean; }; abortSignal?: AbortSignal; }) => Promise<{ delivered?: boolean; deliveryAttempted?: boolean; } & CronRunOutcome & CronRunTelemetry>; preflightJobAccess?: (job: CronJob) => CronTaskAccessBlock | undefined; onEvent?: (evt: CronEvent) => void; }; //#endregion //#region src/cron/service/ops.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; }; type CronQueueControlAction = "cancel" | "retry" | "clear-stale"; type CronQueueControlResult = { ok: true; action: CronQueueControlAction; runId: string; jobId: string; message: string; aborted?: boolean; processed?: number; } | { ok: false; action: CronQueueControlAction; runId: string; reason: string; }; //#endregion //#region src/cron/service.d.ts declare class CronService { private readonly state; constructor(deps: CronServiceDeps); start(): Promise; stop(): void; status(): Promise<{ enabled: boolean; storePath: string; jobs: number; nextWakeAtMs: number | null; queue: CronTaskRunQueueSummary; }>; list(opts?: { includeDisabled?: boolean; }): Promise; listPage(opts?: CronListPageOptions): Promise<{ jobs: CronJob[]; total: number; offset: number; limit: number; hasMore: boolean; nextOffset: number | null; }>; add(input: CronJobCreate): Promise; update(id: string, patch: CronJobPatch): Promise; repair(id: string, params: { action: CronTaskRepairRecoveryAction; source?: string; sourceNodeId?: string; }): Promise; sourcesList(opts?: CronTaskSourceListFilters): Promise; sourcesUpdate(id: string, patch: { active?: boolean; }): Promise; sourcesRemove(id: string): Promise; remove(id: string): Promise<{ readonly ok: false; readonly removed: false; } | { readonly ok: true; readonly removed: boolean; }>; run(id: string, mode?: "due" | "force"): Promise<{ ok: boolean; ran: boolean; reason: "already-running"; readonly jobId?: undefined; readonly runId?: undefined; } | { ok: boolean; ran: boolean; reason: "not-due"; readonly jobId?: undefined; readonly runId?: undefined; } | { ok: boolean; ran: boolean; reason: "needs-access"; readonly jobId?: undefined; readonly runId?: undefined; } | { readonly ok: false; readonly ran?: undefined; reason?: undefined; readonly runId?: undefined; readonly detail?: undefined; } | { readonly ok: true; readonly ran: false; readonly reason: "running" | "queued"; readonly runId: string; readonly detail: string | undefined; } | { readonly ok: true; readonly ran: false; readonly reason: "error" | "blocked"; readonly runId: string; readonly detail: string | undefined; } | { readonly ok: true; readonly ran: true; reason?: undefined; readonly runId?: undefined; readonly detail?: undefined; }>; queueCancel(runId: string, reason?: string): Promise; queueRetry(runId: string, reason?: string): Promise; queueClearStale(runId: string, reason?: string): Promise; work(opts?: { maxRuns?: number; leaseOwner?: string; }): Promise<{ ok: true; processed: number; outcomes: { jobId: string; status: CronRunStatus; error: string | undefined; sessionId: string | undefined; sessionKey: string | undefined; delivered: boolean | undefined; startedAt: number; endedAt: number; model: string | undefined; provider: string | undefined; policy: CronRunPolicyTelemetry | undefined; }[]; }>; getJob(id: string): CronJob | undefined; wake(opts: { mode: "now" | "next-heartbeat"; text: string; }): { readonly ok: false; } | { readonly ok: true; }; } //#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; 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 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/chat-abort.d.ts type ChatAbortControllerEntry = { controller: AbortController; sessionId: string; sessionKey: string; startedAtMs: number; expiresAtMs: number; ownerConnId?: string; ownerDeviceId?: string; kind?: "chat-send" | "agent"; }; //#endregion //#region src/gateway/exec-approval-manager.d.ts type ExecApprovalRequestPayload = ExecApprovalRequestPayload$1; type ExecApprovalRecord = { id: string; request: ExecApprovalRequestPayload; createdAtMs: number; expiresAtMs: number; requestedByConnId?: string | null; requestedByDeviceId?: string | null; requestedByClientId?: string | null; resolvedAtMs?: number; decision?: ExecApprovalDecision; resolvedBy?: string | null; }; declare class ExecApprovalManager { private pending; create(request: ExecApprovalRequestPayload, 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; } //#endregion //#region src/gateway/server/ws-types.d.ts type GatewayWsClient = { socket: WebSocket$1; connect: ConnectParams; connId: string; presenceKey?: string; clientIp?: string; canvasHostUrl?: string; canvasCapability?: string; canvasCapabilityExpiresAtMs?: number; }; //#endregion //#region src/gateway/node-registry.d.ts type NodeSession = { nodeId: string; connId: string; client: GatewayWsClient; displayName?: string; platform?: string; version?: string; coreVersion?: string; uiVersion?: string; deviceFamily?: string; modelIdentifier?: string; remoteIp?: string; caps: string[]; commands: string[]; permissions?: Record; pathEnv?: string; connectedAtMs: number; }; type NodeInvokeResult = { ok: boolean; payload?: unknown; payloadJSON?: string | null; error?: { code?: string; message?: string; } | null; }; declare class NodeRegistry { private nodesById; private nodesByConn; private pendingInvokes; register(client: GatewayWsClient, opts: { remoteIp?: string | undefined; }): NodeSession; unregister(connId: string): string | null; listConnected(): NodeSession[]; get(nodeId: string): NodeSession | undefined; invoke(params: { nodeId: string; command: string; params?: unknown; timeoutMs?: number; idempotencyKey?: string; }): Promise; handleInvokeResult(params: { id: string; nodeId: string; ok: boolean; payload?: unknown; payloadJSON?: string | null; error?: { code?: string; message?: string; } | null; }): boolean; sendEvent(nodeId: string, event: string, payload?: unknown): boolean; private sendEventInternal; private sendEventToSession; } //#endregion //#region src/gateway/server-broadcast.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-shared.d.ts type DedupeEntry = { ts: number; ok: boolean; payload?: unknown; error?: ErrorShape; }; //#endregion //#region src/gateway/server-methods/types.d.ts type SubsystemLogger = ReturnType; type GatewayClient = { connect: ConnectParams; connId?: string; clientIp?: string; canvasHostUrl?: string; canvasCapability?: string; canvasCapabilityExpiresAtMs?: number; }; type RespondFn = (ok: boolean, payload?: unknown, error?: ErrorShape, meta?: Record) => void; type GatewayRequestContext = { deps: ReturnType; cron: CronService; cronStorePath: string; execApprovalManager?: ExecApprovalManager; loadGatewayModelCatalog: () => 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; subscribeSessionEvents: (connId: string) => void; unsubscribeSessionEvents: (connId: string) => void; broadcastSessionLifecycleEvent: (params: { sessionKey: string | undefined; phase: string; runId?: string; reason?: string; }) => void; subscribeSessionMessageEvents: (connId: string, sessionKey: string) => void; unsubscribeSessionMessageEvents: (connId: string, sessionKey: string) => void; unsubscribeAllSessionEvents: (connId: string) => void; hasConnectedMobileNode: () => boolean; hasExecApprovalClients?: () => boolean; nodeRegistry: NodeRegistry; agentRunSeq: Map; chatAbortControllers: Map; chatAbortedRuns: Map; chatRunBuffers: Map; chatDeltaSentAt: Map; addChatRun: (sessionId: string, entry: { sessionKey: string; clientRunId: string; }) => void; removeChatRun: (sessionId: string, clientRunId: string, sessionKey?: string) => { sessionKey: string; clientRunId: string; } | undefined; registerToolEventRecipient: (runId: string, connId: string) => void; dedupe: Map; wizardSessions: Map; findRunningWizard: () => string | null; purgeWizardSession: (id: string) => void; getRuntimeSnapshot: () => ChannelRuntimeSnapshot; 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; }; type GatewayRequestHandlerOptions = { req: RequestFrame; /** @deprecated Older tests used frame for the request envelope. */ frame?: 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 //#region src/gateway/method-scopes.d.ts declare const ADMIN_SCOPE: "operator.admin"; declare const READ_SCOPE: "operator.read"; declare const WRITE_SCOPE: "operator.write"; declare const APPROVALS_SCOPE: "operator.approvals"; declare const PAIRING_SCOPE: "operator.pairing"; type OperatorScope = typeof ADMIN_SCOPE | typeof READ_SCOPE | typeof WRITE_SCOPE | typeof APPROVALS_SCOPE | typeof PAIRING_SCOPE; //#endregion //#region src/agents/auth-profiles/types.d.ts type ApiKeyCredential = { type: "api_key"; provider: string; key?: string; keyRef?: SecretRef; email?: string; /** Optional provider-specific metadata (e.g., account IDs, gateway IDs). */ metadata?: Record; }; type TokenCredential = { /** * Static bearer-style token (often OAuth access token / PAT). * Not refreshable by FasedAgent (unlike `type: "oauth"`). */ type: "token"; provider: string; token: string; tokenRef?: SecretRef; /** Optional expiry timestamp (ms since epoch). */ expires?: number; email?: string; }; type OAuthCredential = OAuthCredentials & { type: "oauth"; provider: string; clientId?: string; email?: string; }; type AuthProfileCredential = ApiKeyCredential | TokenCredential | OAuthCredential; type AuthProfileFailureReason = "auth" | "auth_permanent" | "format" | "rate_limit" | "overloaded" | "billing" | "timeout" | "model_not_found" | "session_expired" | "unknown"; /** Per-profile usage statistics for round-robin and cooldown tracking */ type ProfileUsageStats = { lastUsed?: number; cooldownUntil?: number; disabledUntil?: number; disabledReason?: AuthProfileFailureReason; cooldownReason?: AuthProfileFailureReason; cooldownModel?: string; errorCount?: number; failureCounts?: Partial>; lastFailureAt?: number; }; type AuthProfileStore = { version: number; profiles: Record; /** * Optional per-agent preferred profile order overrides. * This lets you lock/override auth rotation for a specific agent without * changing the global config. */ order?: Record; lastGood?: Record; /** Usage statistics per profile for round-robin rotation */ usageStats?: Record; }; //#endregion export { createSubsystemLogger as A, ExecTarget as B, readWebSelfId as C, normalizeE164 as D, escapeRegExp as E, isBlockedHostname as F, resolveStateDir as H, isBlockedHostnameOrIp as I, isPrivateIpAddress as L, LookupFn as M, SsrFBlockedError as N, safeParseJson as O, SsrFPolicy as P, ExecAsk as R, logoutWeb as S, clamp as T, resolveGatewayPort as V, PushTestParams as _, GatewayClient as a, getWebAuthAgeMs as b, GatewayRequestHandlerOptions as c, GatewayStartupTraceSnapshot as d, ModelCatalogEntry as f, ErrorShape as g, CommandsListResult as h, OperatorScope as i, LogLevel as j, sleep as k, GatewayRequestHandlers as l, ChatInjectParams as m, AuthProfileStore as n, GatewayRequestContext as o, ModelFeature as p, OAuthCredential as r, GatewayRequestHandler as s, AuthProfileCredential as t, RespondFn as u, WebLoginStartParams as v, webAuthExists as w, logWebSelfId as x, WebLoginWaitParams as y, ExecSecurity as z };