import { z } from 'zod'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import OpenAI from 'openai'; type CronSchedule = { kind: "at"; at: string; timezone?: string; } | { kind: "every"; everyMs: number; anchorAt?: string; timezone?: string; } | { kind: "cron"; expr: string; timezone?: string; staggerMs?: number; }; type CronTarget = { kind: "backgroundTask"; parentSessionId?: string; cwd?: string; agentName?: string; behaviorMode?: "chat" | "plan"; } | { kind: "chatTurn"; sessionId: string; activeTurnPolicy?: "delay" | "skip" | "fail"; }; type CronPayload = { kind: "prompt"; text: string; } | { kind: "systemEvent"; text: string; } | CronWorkflowPayload; type CronWorkflowJson = null | string | number | boolean | CronWorkflowJson[] | { [key: string]: CronWorkflowJson; }; type CronWorkflowRef = string; type CronWorkflowConditionOp = "exists" | "missing" | "truthy" | "falsy" | "empty" | "not_empty" | "eq" | "neq" | "gt" | "gte" | "lt" | "lte"; type CronWorkflowCondition = { left?: CronWorkflowJson | CronWorkflowRef; op: CronWorkflowConditionOp; right?: CronWorkflowJson | CronWorkflowRef; }; type CronWorkflowBaseStep = { id: string; name?: string; description?: string; assign?: string; next?: string; onError?: "fail" | "stop"; }; type CronWorkflowToolStep = CronWorkflowBaseStep & { kind: "tool"; capability: string; input?: Record; }; type CronWorkflowConditionStep = CronWorkflowBaseStep & { kind: "condition"; condition: CronWorkflowCondition; then?: string; else?: string; }; type CronWorkflowLlmStep = CronWorkflowBaseStep & { kind: "llm"; prompt: string; input?: Record; }; type CronWorkflowCheckpointStep = CronWorkflowBaseStep & { kind: "checkpoint"; action: "read" | "write"; key: string; value?: CronWorkflowJson | CronWorkflowRef; }; type CronWorkflowStopStep = CronWorkflowBaseStep & { kind: "stop"; status?: "success" | "skipped" | "failed"; summary?: string; }; type CronWorkflowStep = CronWorkflowToolStep | CronWorkflowConditionStep | CronWorkflowLlmStep | CronWorkflowCheckpointStep | CronWorkflowStopStep; type CronWorkflowPayload = { kind: "workflow"; intent: string; version?: 1; context?: Record; steps: CronWorkflowStep[]; cost?: { llmBudgetPolicy?: "only_after_signal" | "always"; maxLlmStepsPerRun?: number; maxPromptChars?: number; attribution?: string; }; capabilities?: { allowed?: string[]; }; }; type CronPolicy = { maxRuntimeMs?: number; maxTurns?: number; costAcknowledged?: boolean; retry?: { onFailure: boolean; maxAttempts: number; }; missedPolicy?: "skip" | "ask" | "run"; concurrencyPolicy?: "skip" | "delay" | "fail"; }; type CronDelivery = { mode: "none"; } | { mode: "session"; sessionId: string; } | { mode: "soulstore"; target?: string; bestEffort?: boolean; }; type CronRunStatus = "queued" | "submitted" | "running" /** A chat-turn target found the session busy; the run is waiting to retry (activeTurnPolicy=delay). */ | "delayed" | "success" | "failed" | "cancelled" | "skipped"; type CronDeliveryStatus = "not-requested" | "pending" | "delivered" | "failed" | "unknown"; type CronRunTrigger = "schedule" | "manual" | "retry" | "missed"; type CronJobState = { nextRunAt?: string | null; runningRunId?: string | null; runningAt?: string | null; lastRunAt?: string | null; lastRunStatus?: CronRunStatus | null; lastError?: string | null; lastDurationMs?: number | null; consecutiveFailures?: number; missedAt?: string | null; }; type CronJob = { id: string; name: string; description?: string; enabled: boolean; createdAt: string; updatedAt: string; createdBy: string; schedule: CronSchedule; target: CronTarget; payload: CronPayload; policy: CronPolicy; delivery: CronDelivery; state: CronJobState; tags?: string[]; source?: string; }; type CronJobCreate = { id?: string; name: string; description?: string; enabled?: boolean; createdBy?: string; schedule: CronSchedule; target: CronTarget; payload: CronPayload; policy?: CronPolicy; delivery?: CronDelivery; tags?: string[]; source?: string; }; type CronJobPatch = Partial>; type CronRun = { id: string; jobId: string; jobName: string; trigger: CronRunTrigger; status: CronRunStatus; deliveryStatus: CronDeliveryStatus; triggeredAt: string; reservedAt?: string; startedAt?: string; submittedAt?: string; finishedAt?: string; durationMs?: number; taskId?: string; parentSessionId?: string; transcriptSessionId?: string; turnId?: string; artifactPath?: string | null; notificationId?: string | null; summary?: string | null; error?: string | null; nextRunAtAfter?: string | null; }; type CronRunPatch = Partial>; type CronStatus = { enabled: boolean; storePath: string; schedulerOwner: { owned: boolean; pid?: number; acquiredAt?: string; }; jobsTotal: number; jobsEnabled: number; runningRuns: number; nextWakeAt: string | null; lastTickAt: string | null; lastError?: string | null; }; type CronListOptions = { enabled?: "all" | "enabled" | "disabled"; query?: string; sortBy?: "nextRunAt" | "updatedAt" | "name"; sortDir?: "asc" | "desc"; limit?: number; offset?: number; }; type CronRunsOptions = { jobId?: string; status?: CronRunStatus; deliveryStatus?: CronDeliveryStatus; trigger?: CronRunTrigger; limit?: number; offset?: number; sortDir?: "asc" | "desc"; }; type CronRunTaskLink = Pick & { parentSessionId: string; }; type CronStoreFile = { version: 1; jobs: CronJob[]; }; /** * Execution-time Track state (pmm-038, B 层). * * 与 plan mode 的审批型 `PlanDocument` 正交:Track 是 chat 执行期的"活进度视图 + 目标锚", * 全量覆盖、三态、单 in_progress。规范 read/write 接口见 `TrackStore`;可视化数据契约见 * `docs/interfaces/track-visualization.md`。 */ type TrackStepStatus = "pending" | "in_progress" | "completed"; interface TrackStep { /** 祈使句,例如 "Run unit tests"。 */ content: string; /** 进行时文案,例如 "Running unit tests";in_progress 时供 UI 显示。 */ activeForm?: string; status: TrackStepStatus; } /** 持久的目标锚:与步骤列表分离,每轮回灌进系统提示。 */ interface TrackTarget { /** 北极星:本轮长任务要达成什么。 */ goal: string; /** 硬约束,不可违反。 */ constraints: string[]; /** 验收判据(达成全部即视为完成;也是未来 C 层评估器的显式信号)。 */ acceptance: string[]; } interface TrackState { target: TrackTarget | null; steps: TrackStep[]; updatedAt: string; } interface TrackTargetPatch { goal?: string; constraints?: string[]; acceptance?: string[]; } /** 单条步骤的原始输入(来自工具调用,字段可能缺失/非法)。 */ interface TrackStepInput { content?: string; activeForm?: string; status?: string; } interface TrackProgress { total: number; completed: number; inProgress: number; pending: number; } declare function createEmptyTrackState(): TrackState; /** 归一化单条步骤;content 为空则丢弃(返回 null)。非法状态回退到 pending。 */ declare function normalizeStep(input: TrackStepInput): TrackStep | null; declare function normalizeSteps(inputs: TrackStepInput[]): TrackStep[]; /** * 单 in_progress 不变量(抄 Codex/Claude):保留第一个 in_progress,其余降级为 pending。 * 校验放在运行时这一处轻断言,行为细则仍靠系统提示约束。 */ declare function enforceSingleInProgress(steps: TrackStep[]): TrackStep[]; declare function mergeTarget(existing: TrackTarget | null, patch: TrackTargetPatch): TrackTarget; declare function computeProgress(state: TrackState): TrackProgress; declare function isTrackEmpty(state: TrackState | null | undefined): boolean; /** * 单一净化边界:把任意(可能损坏/部分/旧版)的持久态收敛成合法 `TrackState`。 * 所有下游(snapshot、prompt、TUI)都先过这里,保证不会因脏数据崩溃。 */ declare function sanitizeTrackState(raw: unknown): TrackState; /** 把 Track 渲染成纯文本块(供 `/track show` 等文本输出;用 ASCII 图标避免终端编码问题)。 */ declare function formatTrackText(state: TrackState): string; /** * 稳定可序列化快照 —— 面向可视化消费者的 read 数据契约。 * 字段一旦发布需保持向后兼容,详见 `docs/interfaces/track-visualization.md`。 */ interface TrackSnapshot { sessionId: string; target: TrackTarget | null; steps: TrackStep[]; progress: TrackProgress; updatedAt: string; } type PermissionMode = "ask" | "auto" | "bypass" | "full-access"; type BehaviorMode = "lite" | "chat" | "plan"; type TaskBehaviorMode = "chat" | "plan"; /** * User-facing thinking levels, ordered from least to most reasoning. * * These are UI levels, not wire values. Each provider dialect maps them onto whatever its upstream * accepts (see `thinkingDialect`) — a level is only offered for a model whose dialect can actually * express it, so selecting a level never silently degrades to a weaker one. * * `max` is the ceiling. OpenAI's `ultra` is NOT a level: it is a separate multi-agent orchestration * mode on gpt-5.6 Sol, unrelated to the reasoning-effort parameter. */ type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; type ThinkingDialect = "reasoning-effort" | "deepseek" | "enable-thinking" | "anthropic" | "none"; type SessionContextMode = "normal" | "isolated"; type TaskExecutionMode = "foreground" | "background"; type PermissionRisk = "low" | "medium" | "high"; type McpServerConnectionState = "disconnected" | "pending" | "connected" | "failed"; type PermissionPromptChoice = "allow" | "deny" | "always-allow"; type PermissionDecisionType = "allow" | "deny"; type PlanStatus = "idle" | "draft" | "ready_for_approval" | "approved" | "cancelled"; type CronProposalStatus = "idle" | "ready_for_approval" | "approved" | "cancelled"; type ProviderType = "openai" | "openai-compatible" | "openai-responses" | "codex"; type FailoverReason = "rate_limit" | "overloaded" | "billing" | "timeout" | "server_error" | "auth" | "auth_permanent" | "model_not_found" | "format" | "empty_response" | "unclassified" | "unknown"; type CompactStatus = "idle" | "pending" | "running" | "completed" | "failed"; type CompactStrategy = "session_memory" | "summary" | "reactive" | "manual" | "room_identity"; type SessionSummarySource = "runtime" | "compact" | "manual" | "recovery"; type DurableMemoryType = "project_fact" | "user_preference" | "workflow_hint" | "known_issue"; type DurableMemoryScope = "workspace" | "user"; type DurableMemorySource = "session" | "dream" | "manual"; type DurableMemoryRecall = "primary" | "archive_only"; type SessionTitleSource = "auto" | "manual"; type BusyMessageMode = "queue" | "collect" | "steer" | "btw" | "reject"; type BusyMessageSource = "cli" | "tui" | "web" | "gateway" | "cron" | "room"; type BusyQueueStatus = "queued" | "running" | "completed" | "cancelled" | "dropped" | "failed"; type BusyCollectStatus = "collecting" | "queued" | "running" | "completed" | "cancelled" | "dropped" | "failed"; type BusySteerStatus = "accepted" | "applied" | "expired" | "failed" | "fallback"; type AgentProfileKind = "default" | "profile" | "legacy" | "inline"; type AgentProfileSourceScope = "user-xigua" | "workspace-xigua" | "global-default"; type AgentWorkspaceMode = "shared" | "dedicated"; interface SessionAgentBinding { kind: AgentProfileKind; name: string; description?: string | null; profilePath?: string | null; profileRootDir?: string | null; soulRootDir?: string | null; soulFile?: string | null; identityFile?: string | null; userFile?: string | null; sourceScope?: AgentProfileSourceScope; resolvedAt: string; profileHash?: string | null; workspaceMode?: AgentWorkspaceMode | null; memoryRootDir?: string | null; dreamRootDir?: string | null; plansRootDir?: string | null; tasksRootDir?: string | null; } interface LiteToolOverride { enable?: string[]; disable?: string[]; allowMcp?: boolean; allowWeb?: boolean; allowAgent?: boolean; allowSkills?: boolean; } interface LiteSkillOverride { enable?: string[]; disable?: string[]; allowlist?: string[] | null; autoTrigger?: boolean; } interface LiteOverride { tools?: LiteToolOverride; skills?: LiteSkillOverride; } interface LiteModeConfig { description?: string; tools: { enabled: string[]; defaultDisabled: string[]; blocked: string[]; allowMcp: boolean; allowWeb: boolean; allowAgent?: boolean; allowSkills: boolean; }; skills: { enabled: boolean; allowlist: string[] | null; autoTrigger: boolean; lazyLoad: boolean; }; memory: { recentMessages: number; includeSessionSummary: boolean; includeSessionMemory: boolean; includeDurableMemory: boolean; relevantMemoryLimit: number; }; persistence: { persistDeltas: boolean; persistFinalOnly: boolean; }; } interface BusyMessagePolicy { enabled: boolean; defaultMode: BusyMessageMode; surfaceDefaults: { tui: BusyMessageMode; web: BusyMessageMode; gateway: BusyMessageMode; cron: BusyMessageMode; }; queue: { maxItems: number; maxCharsPerItem: number; overflow: "reject" | "drop-oldest"; autoDrain: true; }; collect: { debounceMs: number; maxItems: number; maxChars: number; overflow: "reject" | "queue" | "drop-oldest"; }; steer: { fallback: "queue" | "collect" | "reject"; requireExpectedTurnId: boolean; }; btw: { enabled: false; }; } interface BusyQueueItem { id: string; sessionId: string; mode: "queue"; text: string; persistedText?: string; source: BusyMessageSource; status: BusyQueueStatus; createdAt: string; updatedAt: string; idempotencyKey?: string; thinkingLevel?: ThinkingLevel; attachments?: TurnAttachment[]; error?: string | null; } interface BusyCollectMessage { id: string; text: string; persistedText?: string; source: BusyMessageSource | string; createdAt: string; } interface BusyCollectBuffer { id: string; sessionId: string; status: BusyCollectStatus; messages: BusyCollectMessage[]; debounceUntil: string | null; createdAt: string; updatedAt: string; idempotencyKey?: string; error?: string | null; } interface BusySteerRecord { id: string; sessionId: string; turnId: string; text: string; persistedText?: string; status: BusySteerStatus; fallbackMode?: "queue" | "collect" | "reject"; acceptedAt: string; appliedAt?: string; updatedAt: string; error?: string | null; } interface SessionBusyMessagesState { queue: BusyQueueItem[]; collect: BusyCollectBuffer[]; steer: BusySteerRecord[]; } interface WebSearchProviderConfig { name: string; kind: string; enabled: boolean; apiKey?: string; apiKeyEnv?: string; baseURL?: string; headers?: Record; defaultMaxResults?: number; } interface WebSearchRegistryConfig { default: string; items: WebSearchProviderConfig[]; } interface WebSearchResult { title: string; url: string; snippet: string; source?: string; rank?: number; } interface ModelPricingConfig { /** 输入价格:美元 / 百万 Token */ promptUsdPerMillionTokens: number; /** 输出价格:美元 / 百万 Token */ completionUsdPerMillionTokens: number; } interface ProviderModelConfig { id: string; enabled: boolean; /** Preferred and supported gateway wire protocols for this model. */ apiType?: "openai-completions" | "openai-responses"; apiTypes?: Array<"openai-completions" | "openai-responses">; displayName?: string; contextWindow?: number; maxOutputTokens?: number; supportsTools?: boolean; supportsImages?: boolean; /** Whether the provider exposes reasoning controls for this model. */ reasoning?: boolean; /** Thinking levels the model/provider combination can express on the wire. */ supportedThinkingLevels?: ThinkingLevel[]; /** * Model-scoped default thinking level. `null` (or omission) falls back to * the built-in capability default for this model. */ defaultLevel?: ThinkingLevel | null; /** Optional per-model ceiling for dialects with a separate thinking budget. */ maxBudgetTokens?: number | null; dsmlToolCalls?: boolean; /** @since agent-055 可选的自定义定价,优先级高于内置定价表。 */ pricing?: ModelPricingConfig; } interface CodexAuthConfig { authFile?: string; configFile?: string; refreshSkewSeconds?: number; } interface ProviderConfig { name: string; type: ProviderType; enabled: boolean; apiKey?: string; apiKeyEnv?: string; baseURL?: string; headers?: Record; codexAuth?: CodexAuthConfig; defaultModel: string; models: ProviderModelConfig[]; dsmlToolCalls?: boolean; /** * Wire dialect used to toggle thinking for this provider. Inferred from baseURL/model when unset. * One of: reasoning-effort | deepseek | enable-thinking | anthropic | none. */ thinkingDialect?: ThinkingDialect; } interface GatewayAttributionContext { sessionKey?: string | null; runId?: string | null; source?: string | null; jobId?: string | null; taskId?: string | null; } interface ImageModelConfig { provider: string; model: string; } interface ProviderRegistryConfig { default: string; imageModel?: ImageModelConfig | null; /** Ordered fallback models. Each entry has { provider, model } — same shape as imageModel. */ fallbackModels?: Array<{ provider: string; model: string; }>; items: ProviderConfig[]; } interface ProviderToolCall { id: string; name: string; input: Record; } interface FallbackCandidate { provider: string; model: string; } interface FallbackAttempt { provider: string; model: string; error: string; reason: FailoverReason; status?: number; code?: string; } interface TurnAttachment { type: "image" | "file"; path: string; name: string; size?: number; mimeType?: string; data?: string; } interface FastGptKnowledgeScope { datasetId?: string | null; datasetName?: string | null; collectionIds: string[]; collectionNames?: string[]; datasetScopes?: Array<{ datasetId: string; datasetName?: string | null; collectionIds: string[]; collectionNames?: string[]; }>; } interface ProviderCacheUsageSummary { provider: string; model: string; rawInputTokens: number; outputTokens: number; totalTokens: number; cachedInputTokens?: number; cacheMissInputTokens?: number; cacheWriteInputTokens?: number; cacheReadInputTokens?: number; providerFields?: Record; } interface UsageSummary { promptTokens: number; completionTokens: number; totalTokens: number; estimatedCostUsd: number | null; cachedInputTokens?: number; cacheMissInputTokens?: number; cacheWriteInputTokens?: number; cacheReadInputTokens?: number; providerCacheUsage?: ProviderCacheUsageSummary[]; } interface RuntimeClockSnapshot { nowIso: string; localTime: string; timezone: string; weekday: string; } type TaskStatus = "queued" | "pending" | "running" | "backgrounded" | "completed" | "failed" | "cancelled"; type SessionTaskKind = "subagent" | "dream" | "cron"; interface TaskArtifactRef { handle: string; outputPath: string; summaryPath: string; metadataPath: string; } interface TaskBudgetState { maxTurns: number | null; timeoutMs: number | null; turnsUsed: number; concurrencyLimit: number | null; } interface TaskNotificationRecord { id: string; taskId: string; status: TaskStatus; createdAt: string; message: string; artifactPath: string | null; } interface TranscriptMessageBase { id: string; timestamp: string; role: "system" | "user" | "assistant" | "tool"; kind: "message" | "tool-result" | "event"; roomTurnPhase?: string | null; roomToolPurpose?: string | null; roomVisibility?: "private" | "published" | "discarded" | null; runtimeInternalSource?: boolean | null; roomMessageSource?: "room" | null; roomId?: string | null; roomEventId?: string | null; roomSeq?: number | null; roomRootEventId?: string | null; roomActorMemberId?: string | null; roomActorDisplayName?: string | null; roomPayloadType?: string | null; } interface ResponsesReplayState { provider: string; model: string; endpointFingerprint: string; items: Array>; } interface TextTranscriptMessage extends TranscriptMessageBase { role: "system" | "user" | "assistant"; kind: "message" | "event"; text: string; attachments?: TurnAttachment[]; reasoningContent?: string; toolCalls?: ProviderToolCall[]; /** Source-bound output items for continuing a store:false Responses conversation. */ responsesReplayState?: ResponsesReplayState; } interface ToolTranscriptMessage extends TranscriptMessageBase { role: "tool"; kind: "tool-result"; text: string; toolName: string; toolCallId: string; output: unknown; } type TranscriptMessage = TextTranscriptMessage | ToolTranscriptMessage; interface SessionTask { id: string; handle: string; parentSessionId: string; parentTaskId: string | null; transcriptSessionId: string; kind: SessionTaskKind; title: string; description: string; agentName?: string; provider?: string; model?: string; status: TaskStatus; executionMode?: "foreground" | "background"; createdAt: string; updatedAt: string; startedAt: string; finishedAt?: string; backgroundedAt?: string | null; summary: string | null; error: string | null; attempt: number; retryOfTaskId: string | null; budget: TaskBudgetState | null; artifact: TaskArtifactRef | null; notification: TaskNotificationRecord | null; phase?: string | null; progress?: { current: number; total: number; label?: string; } | null; touchedPaths?: string[]; recentToolActions?: string[]; } interface SessionPlanState { status: PlanStatus; documentPath: string | null; title: string | null; updatedAt: string | null; approvedAt: string | null; } interface CronProposal { id: string; name: string; description?: string; schedule: CronSchedule; target: CronTarget; payload: CronPayload; policy: CronPolicy; delivery: CronDelivery; enabled: boolean; createdBy: "agent" | "slash" | "system"; sourceSessionId: string; tags?: string[]; source?: string; preview: { timezone?: string; nextRunAt: string | null; humanSchedule: string; humanTarget: string; warnings: string[]; }; } interface SessionCronProposalState { status: CronProposalStatus; proposalId: string | null; updatedAt: string | null; proposal: CronProposal | null; } interface SessionSummaryState { text: string | null; updatedAt: string | null; source: SessionSummarySource | null; } interface SessionMemoryState { path: string | null; updatedAt: string | null; lastExtractedAt: string | null; } interface CompactState { status: CompactStatus; strategy: CompactStrategy | null; updatedAt: string | null; summarizedThroughMessageId: string | null; identityAware?: { agentName: string; roomId: string | null; keptRecentMessageCount: number; summaryLength: number; retrievalHintCount: number; summarizedThroughRoomSeq: number | null; } | null; } interface DurableMemoryManifest { id: string; slug: string; title: string; type: DurableMemoryType; scope: DurableMemoryScope; summary: string; path: string; source: DurableMemorySource; createdAt: string; updatedAt: string; tags: string[]; recall: DurableMemoryRecall; contentLength: number; } interface DurableMemoryRecord { id: string; slug: string; title: string; type: DurableMemoryType; scope: DurableMemoryScope; summary: string; content: string; path: string; source: DurableMemorySource; createdAt: string; updatedAt: string; tags: string[]; recall: DurableMemoryRecall; } interface SessionState { id: string; cwd: string; workspaceId: string | null; /** The most recently attached Goal. At most one Goal per session may be non-terminal. */ currentGoalId?: string | null; activeRoomId?: string | null; agent: SessionAgentBinding; provider: string; model: string; /** Preserves the selected wire protocol across config updates. */ modelApiType?: "openai-completions" | "openai-responses"; modelRoutingEnabled?: boolean; thinkingLevel?: ThinkingLevel; title: string; titleState: SessionTitleState; archivedAt?: string | null; createdAt: string; updatedAt: string; parentSessionId: string | null; parentTaskId: string | null; permissionMode: PermissionMode; behaviorMode: BehaviorMode; liteOverrides: LiteOverride | null; plan: SessionPlanState; /** 执行期任务追踪(pmm-038, B 层)。可选:旧会话反序列化时为 undefined。 */ track?: TrackState; summary: SessionSummaryState; sessionMemory: SessionMemoryState; compactState: CompactState; cronProposal: SessionCronProposalState; busyMessages: SessionBusyMessagesState; usage: UsageSummary; messages: TranscriptMessage[]; tasks: SessionTask[]; taskQueue?: { queue: string[]; updatedAt: string; }; } interface SessionTitleState { source: SessionTitleSource; updatedAt: string | null; summarizedThroughMessageId: string | null; } interface SessionTaskSummarySnapshot { total: number; active: number; pending: number; queued: number; running: number; backgrounded: number; completed: number; failed: number; cancelled: number; recentTaskId: string | null; recentTaskStatus: TaskStatus | null; } interface SessionStateSnapshot { sessionId: string; title: string; titleState: SessionTitleState; cwd: string; workspaceId?: string | null; agentName?: string | null; provider: string; model: string; thinkingLevel: ThinkingLevel | null; createdAt: string; updatedAt: string; parentSessionId: string | null; parentTaskId: string | null; permissionMode: PermissionMode; behaviorMode: BehaviorMode; planStatus: PlanStatus; planDocumentPath: string | null; messageCount: number; usage: UsageSummary; taskSummary: SessionTaskSummarySnapshot; } interface PermissionRequest { toolName: string; action: string; risk: PermissionRisk; command?: string; targetPath?: string; } interface PermissionDecision { decision: PermissionDecisionType; source: "rule" | "prompt" | "mode" | "session-rule"; reason: string; } interface PermissionManager { request(input: PermissionRequest): Promise; addSessionAllowRule(toolName: string): void; hasSessionAllowRule(toolName: string): boolean; listSessionAllowRules(): string[]; revokeSessionAllowRule(toolName: string): void; clearSessionAllowRules(): void; } interface ToolJsonSchema { type: "object"; properties?: Record; required?: string[]; additionalProperties?: boolean; } interface ToolContext { cwd: string; session: SessionState; signal?: AbortSignal; fastgptKnowledgeScope?: FastGptKnowledgeScope | null; /** * Ask the host to inspect one or more workspace images. The host routes the * request to the active vision-capable model or the configured imageModel. */ understandImages?(input: { paths: string[]; prompt?: string; signal?: AbortSignal; }): Promise; } interface ImageUnderstandingResult { kind: "image-understanding"; provider: string; model: string; summary: string; imageCount: number; usage?: Partial; } interface SubAgentRunInput { task: string; agentName?: string; provider?: string; model?: string; behaviorMode?: BehaviorMode; executionMode?: TaskExecutionMode; session: SessionState; signal?: AbortSignal; } interface SubAgentTaskResult { taskId: string; handle?: string; status: TaskStatus; summary: string; agentName?: string; transcriptSessionId: string; messageCount: number; artifactPath?: string | null; notificationId?: string | null; } interface ToolDefinition, Output = unknown> { name: string; description: string; risk: PermissionRisk; inputSchema: z.ZodType; jsonSchema: ToolJsonSchema; run(input: Input, context: ToolContext): Promise; } interface ToolExecutionRecord { toolName: string; toolCallId: string; output: unknown; } interface ProviderTurnRequest { session: SessionState; systemPrompt: string; runtimeTag?: "default" | "dream"; gatewayAttribution?: GatewayAttributionContext; signal?: AbortSignal; supportsImages?: boolean; tools: Array<{ name: string; description: string; jsonSchema: ToolJsonSchema; }>; } interface ProviderTurnResult { assistantText: string; reasoningContent?: string; toolCalls: ProviderToolCall[]; /** Source-bound Responses output items needed to continue a store:false conversation. */ responsesReplayState?: ResponsesReplayState; finishReason: "stop" | "tool_calls" | "length" | "unknown"; usage?: Partial; /** @since agent-055 实际产出本结果的模型 ID(fallback 后可能不同于会话默认模型),用于成本归因。 */ model?: string; } type RuntimeEvent = { type: "status"; status: "thinking" | "running_tool" | "idle"; } | { type: "assistant-text"; delta: string; } | { type: "assistant-reply"; text: string; reasoningContent?: string; } | { type: "assistant-narration"; text: string; reasoningContent?: string; toolCalls?: ProviderToolCall[]; } | { type: "tool-start"; toolName: string; toolCallId: string; input: unknown; targetPath?: string; } | { type: "tool-result"; toolName: string; toolCallId: string; output: unknown; targetPath?: string; } | { type: "tool-error"; toolName: string; toolCallId: string; error: string; targetPath?: string; } | { type: "permission-result"; toolName: string; toolCallId?: string; decision: PermissionDecisionType; reason: string; targetPath?: string; } | { type: "system-notice"; content: string; level: "info" | "warning" | "error"; }; interface ProviderAdapter { runTurn(input: ProviderTurnRequest): AsyncGenerator; getCacheMetrics?(): ProviderCacheMetricsSnapshot; /** Whether the resolved model can accept native image input. */ supportsImages?: boolean; } interface ProviderCacheMetricsSnapshot { hits: number; misses: number; invalidations: number; evictions: number; totalLookups: number; hitRate: number; size: number; } interface SkillDefinition { name: string; slug: string; aliases?: string[]; description: string; version?: string; content: string; path: string; rootDir: string; entryKind: "legacy-flat" | "package"; sourceScope: "bundled-xigua" | "workspace-xigua" | "workspace-claude" | "user-xigua" | "user-claude"; manifestPath?: string; } type SkillComputedState = "enabled" | "disabled" | "shadowed" | "invalid" | "missing"; interface SkillStatusEntry { name: string; slug: string; aliases?: string[]; description: string; version?: string; state: SkillComputedState; path: string; rootDir: string; entryKind: SkillDefinition["entryKind"]; sourceScope: SkillDefinition["sourceScope"]; managed: boolean; enabledByConfig: boolean; manifestPath?: string; shadowedBy?: string; invalidReason?: string; } interface AgentDefinition { name: string; description: string; systemPrompt?: string; path: string; } interface McpServerConfig { name: string; command: string; args?: string[]; env?: Record; cwd?: string; timeoutMs?: number; } interface McpServerStatus { name: string; status: McpServerConnectionState; connected: boolean; toolCount: number; promptCount?: number; resourceCount?: number; error?: string; } interface RuntimeMcpSummary { total: number; connected: number; pending: number; failed: number; disconnected: number; servers: Array<{ name: string; status: McpServerConnectionState; connected: boolean; toolCount: number; promptCount: number; resourceCount: number; error?: string; }>; } interface RuntimeFastGptKnowledgeSummary { active: boolean; mcpRequired: boolean; datasetId: string | null; datasetName: string | null; collectionIds: string[]; collectionNames: string[]; availableTools: string[]; appAskEnabled: boolean; } interface RuntimeStatusSnapshot extends RuntimeClockSnapshot { cwd: string; provider: string; model: string; thinkingLevel: ThinkingLevel | null; permissionMode: PermissionMode; behaviorMode: BehaviorMode; shell: string; platform: string; mcp: RuntimeMcpSummary; fastgptKnowledge: RuntimeFastGptKnowledgeSummary; } interface McpToolCapability { name: string; description: string; risk: PermissionRisk; jsonSchema: ToolDefinition["jsonSchema"]; } interface McpPromptCapability { name: string; description?: string; argumentNames: string[]; } interface McpResourceCapability { uri: string; name?: string; title?: string; description?: string; mimeType?: string; } interface McpServerCapabilities { name: string; tools: McpToolCapability[]; prompts: McpPromptCapability[]; resources: McpResourceCapability[]; } interface SoulMarkdownFile { path: string; exists: boolean; content: string | null; } interface SoulProfile { rootDir: string; soul: SoulMarkdownFile; identityFile: SoulMarkdownFile; user: SoulMarkdownFile; } interface GatewayConfig { enabled: boolean; host: string; port: number; authToken?: string; authTokenEnv?: string; } type WsServerConfig = GatewayConfig; interface BridgePluginEntryConfig { enabled: boolean; module: string; options: Record; } interface BridgePluginRegistryConfig { entries: Record; } interface WebAppConfig { enabled: boolean; host: string; port: number; gatewayUrl: string; gatewayAuthToken?: string; gatewayAuthTokenEnv?: string; } interface OnboardingState { lastSuccessfulCheckAt: string | null; lastFailedCheckAt: string | null; lastSkippedAt: string | null; skipSilenceHours: number; lastConfigHash?: string; } interface AppConfig { /** * Schema version persisted alongside the config. Bumped when normalization * contains value-migration steps that must not re-run against configs * written by newer releases (iss-027 M-05). */ configVersion?: number; providers: ProviderRegistryConfig; webSearch: WebSearchRegistryConfig; modelRouting: { enabled: boolean; }; gateway: GatewayConfig; bridgePlugins: BridgePluginRegistryConfig; web: WebAppConfig; tasks: { maxConcurrentTasks: number; timeoutMs: number; maxTurns: number | null; /** * Safety cap for interactive (non-task) turns. Defaults to a large value so * runaway tool loops still terminate; `null` explicitly opts into unlimited * (iss-027 P1-03). */ interactiveMaxTurns: number | null; }; cron: { enabled: boolean; storePath?: string; maxConcurrentRuns: number; defaultTimezone?: string; minEveryMs: number; runLog: { maxBytes: number; keepLines: number; }; missedPolicy: "skip" | "ask" | "run"; jitter: { enabled: boolean; maxMs: number; }; }; busyMessages: BusyMessagePolicy; permissions: { mode: PermissionMode; allowRules: string[]; denyRules: string[]; /** * How long an unanswered permission prompt waits before auto-deny. * `null` disables the timer entirely (iss-027 M-11). */ promptTimeoutMs?: number | null; }; behavior: { defaultMode: BehaviorMode; modes: { lite: LiteModeConfig; }; }; ui: { showTimestamps: boolean; showSystemMessages: boolean; showReasoning: boolean; }; compatibility: { loadClaudePaths: boolean; }; skills: { entries: Record; }; mcpServers: McpServerConfig[]; onboarding: OnboardingState; } declare class AgentCatalog { private readonly cwd; private readonly includeClaudePaths; private agents; private constructor(); static load(cwd: string, includeClaudePaths?: boolean): Promise; private static discover; private static parseAgentFile; reload(): Promise; list(): AgentDefinition[]; get(name: string): AgentDefinition | undefined; } type AgentProfileRuntimeDefaults = { provider?: string; model?: string; thinkingLevel?: ThinkingLevel; permissionMode?: PermissionMode; behaviorMode?: BehaviorMode; workspace?: { defaultPath?: string; mode?: AgentWorkspaceMode; }; }; interface ResolvedAgentProfile { name: string; description: string; kind: Exclude; sourceScope: AgentProfileSourceScope; rootDir: string; manifestPath: string | null; soulRootDir: string | null; soulFile: SoulMarkdownFile; identityFile: SoulMarkdownFile; userFile: SoulMarkdownFile; runtimeDefaults: AgentProfileRuntimeDefaults; profileHash: string; } type ResolveAgentProfileResult = { ok: true; profile: ResolvedAgentProfile; } | { ok: false; code: "AGENT_PROFILE_NOT_FOUND" | "INVALID_AGENT_PROFILE"; message: string; }; declare function createAgentProfile(input: { name: string; agentsRootDir?: string; description?: string; now?: () => string; provider?: string; model?: string; thinkingLevel?: ThinkingLevel; permissionMode?: PermissionMode; behaviorMode?: BehaviorMode; workspace?: { defaultPath?: string; mode?: AgentWorkspaceMode; }; }): Promise<{ rootDir: string; manifestPath: string; }>; declare function listAgentProfiles(input?: { agentsRootDir?: string; }): Promise>; declare function resolveAgentProfile(input: { name: string; cwd: string; agentsRootDir?: string; legacySoulDir?: string; createDefault?: boolean; }): Promise; interface AgentWorkspacePaths { rootDir: string; memoryDir: string; memoryArchiveDir: string; dreamsDir: string; sessionsIndexDir: string; plansIndexDir: string; tasksIndexDir: string; } declare function getAgentsRootDir(): string; declare function getAgentWorkspacePaths(input: { agentName: string; workspaceId: string; agentsRootDir?: string; }): AgentWorkspacePaths; declare function createSessionAgentBindingFromProfile(input: { profile: ResolvedAgentProfile; workspaceId: string | null; resolvedAt: string; agentsRootDir?: string; }): SessionAgentBinding; declare function getSessionDurableMemoryDir(session: SessionState): string; declare function getSessionMemoryArchiveDir(session: SessionState): string; declare function getSessionPlansDir(session: SessionState): string; declare function getSessionTaskArtifactsRoot(session: SessionState): string; type LegacyAppConfig = Partial & { gateway?: Partial; wsServer?: Partial; bridgePlugins?: { entries?: Record>; }; web?: Partial; provider?: { apiKey?: string; apiKeyEnv?: string; baseURL?: string; model?: string; }; permissions?: AppConfig["permissions"] & { mode?: AppConfig["permissions"]["mode"] | "plan"; }; tasks?: Partial; cron?: Partial & { runLog?: Partial; jitter?: Partial; }; busyMessages?: Partial; /** * Pre-model-scoped thinking configuration. Kept only so persisted configs * from older releases can be migrated during normalization. */ thinking?: { defaultLevel?: unknown; showReasoning?: unknown; maxBudgetTokens?: unknown; providerOverrides?: Record; }; onboarding?: Partial; }; declare const CONFIG_SCHEMA_VERSION = 2; declare const DEFAULT_INTERACTIVE_MAX_TURNS = 500; declare function getAppHomeDir(): string; declare function getConfigPath(): string; declare function getSessionsDir(): string; declare function getRoomsDir(): string; declare function getSessionMemoryDir(): string; declare function getManagedSkillsDir(): string; /** Legacy global soul directory — used only for migration to agent-specific profiles. */ declare function getSoulDir(): string; /** Default agent profile directory — the canonical home for SOUL.md / IDENTITY.md / USER.md. */ declare function getDefaultAgentDir(): string; declare function getSkillImportSessionsDir(): string; declare function getWorkspaceMemoryDir(workspaceRoot: string): string; declare function getWorkspaceMemoryArchiveDir(workspaceRoot: string): string; declare function getWorkspaceMemoryRoot(workspaceRoot: string): string; type GatewayConfigLike = { gateway?: GatewayConfig; wsServer?: GatewayConfig; }; type WebConfigLike = { web?: WebAppConfig; }; declare function resolveGatewayAuthToken(config: GatewayConfigLike, env?: Record): string | undefined; declare function isGatewayAuthConfigured(config: GatewayConfigLike, env?: Record): boolean; /** * Generate a random web/gateway access token (URL-safe, ~32 chars). * Used to secure the web console so it cannot be opened without the token. */ declare function generateServerToken(): string; declare function resolveWsServerAuthToken(config: GatewayConfigLike, env?: Record): string | undefined; declare function isWsServerAuthConfigured(config: GatewayConfigLike, env?: Record): boolean; declare function resolveWebGatewayAuthToken(config: WebConfigLike, env?: Record): string | undefined; declare function isWebGatewayAuthConfigured(config: WebConfigLike, env?: Record): boolean; declare function createDefaultConfig(): AppConfig; declare function normalizeAppConfig(config?: LegacyAppConfig | null): AppConfig; declare function loadAppConfig(): Promise; declare function saveAppConfig(config: AppConfig): Promise; /** * Pure provider/model configuration operations (tui-008). * * These fill the gaps the existing slash commands leave: adding a model to a * provider, switching the persistent default provider, and setting a specific * provider's default model. They are pure and immutable — callers persist the * returned config via saveAppConfig. */ type ProviderConfigOpResult = { ok: true; config: AppConfig; } | { ok: false; error: string; }; /** * Add a model to a provider's `models[]`. Fails on empty id, unknown provider, * or a duplicate model id (case-sensitive, matching how ids are stored). */ declare function addProviderModel(config: AppConfig, providerName: string, model: { id: string; displayName?: string; }): ProviderConfigOpResult; /** Set the persistent default provider (`config.providers.default`). */ declare function setDefaultProvider(config: AppConfig, name: string): ProviderConfigOpResult; /** * Set a specific provider's default model. Adds the model to `models[]` when it * is not already present (mirrors `/config set model`). */ declare function setProviderDefaultModel(config: AppConfig, providerName: string, modelId: string): ProviderConfigOpResult; declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 200000; declare const DEFAULT_MAX_OUTPUT_TOKENS = 32000; declare const MAX_OUTPUT_RESERVE_TOKENS = 20000; declare const AUTO_COMPACT_BUFFER_TOKENS = 13000; declare const MIN_COMPACT_RESERVE_TOKENS = 20000; type ContextWindowSource = "modelConfig" | "providerDefault" | "fallback"; interface ResolvedContextWindow { contextWindow: number; maxOutputTokens: number; outputReserveTokens: number; compactReserveTokens: number; autoCompactThreshold: number; source: ContextWindowSource; } interface ContextPressure extends ResolvedContextWindow { estimatedPromptTokens: number; pressureRatio: number; } declare function resolveContextWindow(input: { session: Pick; config?: AppConfig | null; }): ResolvedContextWindow; declare function buildContextPressure(input: { session: SessionState; config?: AppConfig | null; systemPrompt?: string | null; sessionMemoryContent?: string | null; relevantMemories?: DurableMemoryRecord[]; estimatedPromptTokens?: number; }): ContextPressure; declare function buildSystemPromptAwareContextPressure(input: { session: SessionState; config?: AppConfig | null; sessionMemoryContent?: string | null; relevantMemories?: DurableMemoryRecord[]; buildSystemPrompt(contextPressure: ContextPressure): string; }): ContextPressure; interface ContextBudget { maxRecentMessages: number; maxDurableMemories: number; maxSessionMemoryChars: number; maxDurableMemoryCharsPerMemory: number; maxTotalDurableMemoryChars: number; } declare function getDefaultContextBudget(session: SessionState, contextPressure?: ContextPressure | null): ContextBudget; declare function trimSessionMemoryContent(content: string | null | undefined, budget: ContextBudget): string | null; declare function limitRelevantMemories(memories: DurableMemoryRecord[], budget: ContextBudget): DurableMemoryRecord[]; interface ContextPackingDecision { type: "omitted" | "summarized"; reason: string; target: string; } interface PackedContextInput { session: SessionState; sessionMemoryContent?: string | null; relevantMemories?: DurableMemoryRecord[]; budget?: ContextBudget; contextPressure?: ContextPressure | null; } interface PackedContext { budget: ContextBudget; sessionMemoryContent: string | null; relevantMemories: DurableMemoryRecord[]; packingDecisions: ContextPackingDecision[]; } declare function packContext(input: PackedContextInput): PackedContext; interface BuildContextEnvelopeInput { session: SessionState; sessionMemoryContent?: string | null; relevantMemories?: DurableMemoryRecord[]; maxRecentMessages?: number; contextPressure?: ContextPressure | null; } interface ContextEnvelope { summarySection: string | null; sessionMemorySection: string | null; durableMemorySection: string | null; compactAttachmentSection: string | null; recentMessages: TranscriptMessage[]; packingDecisions: ContextPackingDecision[]; } declare function buildContextEnvelope(input: BuildContextEnvelopeInput): ContextEnvelope; declare function estimateTextTokens(input: string | null | undefined): number; declare function estimateTranscriptMessageTokens(message: TranscriptMessage): number; declare function estimateTranscriptTokens(messages: TranscriptMessage[]): number; declare function estimateSessionTokenFootprint(input: { session: SessionState; systemPrompt?: string | null; sessionMemoryContent?: string | null; durableMemoryContent?: string | null; }): number; interface ToolResultTokenProfile { messageId: string; toolName: string; textChars: number; estimatedTokens: number; } declare function getLargestToolResultProfiles(session: SessionState, limit?: number): ToolResultTokenProfile[]; declare function buildCompactAttachments(session: SessionState): string; declare function createCompactBoundary(strategy: CompactStrategy, details?: string): TranscriptMessage; declare function createCompactSummaryMessage(strategy: CompactStrategy, summaryText: string | null | undefined): TranscriptMessage; interface CompactPolicy { maxRecentMessages: number; maxRecentTokens: number; reactiveMaxRecentTokens: number; maxToolResultTokens: number; maxMessagesBeforeCompact: number; tokenThreshold: number; /** * Persisted session size (UTF-8 bytes of the stored JSON) that triggers an auto compact even when * token pressure is still below its threshold (iss-002 P2). It sits well under the 1 MiB * control-channel frame limit, so a long conversation is compressed before any single frame * (attach snapshot, session event) can grow past what a websocket client accepts. */ maxPersistedSessionBytes: number; } type CompactDecisionReason = "below_threshold" | "context_threshold" | "persisted_size_threshold" | "legacy_token_threshold" | "legacy_message_threshold" | "manual" | "reactive"; interface CompactDecision { shouldCompact: boolean; reason: CompactDecisionReason; estimatedPromptTokens: number | null; autoCompactThreshold: number | null; contextWindow: number | null; } declare function getDefaultCompactPolicy(): CompactPolicy; /** * Byte size of the session as persisted by the session store (iss-002 P2). * * Auto compact used to react to token pressure only; a transcript can stay cheap in tokens while * the stored JSON grows past the control-channel frame limit. A serialization failure returns 0 so * a reporting helper can never force (or block) a compact decision. */ declare function estimatePersistedSessionBytes(session: SessionState): number; /** Human-readable rendering of a persisted-size value for CLI/gateway diagnostics. */ declare function formatPersistedSessionBytes(bytes: number): string; declare function getCompactDecision(input: { session: SessionState; policy?: CompactPolicy; contextPressure?: ContextPressure | null; force?: boolean; reactive?: boolean; }): CompactDecision; declare function shouldCompactSession(session: SessionState, policy?: CompactPolicy, contextPressure?: ContextPressure | null): boolean; type RoomIdentityCompactContext = { roomId?: string | null; roomTitle?: string | null; roomObjective?: string | null; memberId?: string | null; displayName?: string | null; agentProfileName?: string | null; roles?: string[]; responsibility?: string | null; soulSummary?: string | null; }; type RoomIdentityCompactOptions = { keepRecentMessages: number; keepRecentTokens?: number; maxToolResultTokens?: number; sessionMemoryContent?: string | null; context?: RoomIdentityCompactContext | null; fallbackStrategy?: CompactStrategy; }; declare function hasMaterialRoomLedger(session: SessionState): boolean; declare function roomIdentityCompact(session: SessionState, options: RoomIdentityCompactOptions): SessionState; interface CompactSessionOptions { keepRecentMessages?: number; keepRecentTokens?: number; maxToolResultTokens?: number; strategy?: CompactStrategy; policy?: CompactPolicy; sessionMemoryContent?: string | null; roomIdentityContext?: RoomIdentityCompactContext | null; } declare function compactSession(session: SessionState, options?: CompactSessionOptions): SessionState; declare function postCompactCleanup(session: SessionState): SessionState; interface ReactiveCompactOptions extends Omit { } declare function reactiveCompact(session: SessionState, options?: ReactiveCompactOptions): SessionState; interface SessionMemoryCompactOptions { keepRecentMessages?: number; keepRecentTokens?: number; maxToolResultTokens?: number; strategy?: CompactStrategy; } declare function sessionMemoryCompact(session: SessionState, sessionMemoryContent: string, options?: SessionMemoryCompactOptions): SessionState; declare function compactOversizedToolResults(messages: TranscriptMessage[], maxToolResultTokens?: number | null): TranscriptMessage[]; type RemoteCommandSurface = "cli" | "gateway" | "web"; type RemoteCommandCategory = "help" | "session" | "inspection" | "configuration" | "recovery" | "tasks" | "integrations" | "room"; type RemoteCommandDescriptor = { name: string; rawExample: string; usage: string; insertText: string; description: string; category: RemoteCommandCategory; keywords?: string[]; aliases?: string[]; surfaces: RemoteCommandSurface[]; supportsWhileRunning: boolean; remoteSupported: boolean; writeIntent: boolean; /** Write-capable subcommands when the top-level command itself is readable. */ writeSubcommands?: string[]; localOnlySubcommands?: string[]; }; declare function getRemoteCommandCatalog(): RemoteCommandDescriptor[]; declare function getRemoteCommandDescriptor(name: string): RemoteCommandDescriptor | null; declare function isRemoteSlashCommandName(name: string): boolean; declare const REMOTE_CONTROL_METHOD_NAMES: readonly ["control.connect", "config.api.get", "config.api.update", "config.providers.get", "config.providers.save", "config.providers.delete", "config.providers.default", "sessions.create", "sessions.list", "sessions.runtime.status", "sessions.rename", "sessions.archive", "sessions.restore", "sessions.settings.get", "sessions.delete", "sessions.attach", "sessions.detach", "commands.catalog", "commands.slash.execute", "skills.reload", "cron.status", "cron.list", "cron.add", "cron.update", "cron.remove", "cron.run", "cron.runs", "cron.cancelRun", "turn.send", "turn.btw", "turn.enqueue", "turn.steer", "turn.queue.cancel", "turn.queue.clear", "turn.queue.reorder", "turn.abort", "permissions.respond"]; declare const REMOTE_CONTROL_EVENT_NAMES: readonly ["session.snapshot", "session.state.changed", "status.changed", "message.delta", "message.final", "message.narration", "system.notice", "btw.started", "btw.delta", "btw.final", "btw.completed", "btw.failed", "command.output", "tool.started", "tool.finished", "tool.failed", "permission.requested", "permission.resolved", "question.requested", "question.resolved", "turn.started", "turn.queued", "turn.queue.updated", "turn.collect.updated", "turn.completed", "turn.steer.accepted", "turn.steer.applied", "turn.steer.fallback", "turn.busy_message.rejected", "error"]; type RemoteControlMethodName = (typeof REMOTE_CONTROL_METHOD_NAMES)[number]; type RemoteControlEventName = (typeof REMOTE_CONTROL_EVENT_NAMES)[number]; type RemoteControlRequestFrame = { type: "req"; id: string; method: RemoteControlMethodName; params?: Record; }; type RemoteControlResponseError = { code: string; message: string; details?: unknown; }; type RemoteControlResponseFrame = { type: "res"; id: string; ok: true; payload?: unknown; } | { type: "res"; id: string; ok: false; error: RemoteControlResponseError; }; type RemoteControlEventFrame = { type: "event"; event: RemoteControlEventName; payload?: unknown; }; type RemoteControlConnectPayload = { methods: RemoteControlMethodName[]; events: RemoteControlEventName[]; commands: RemoteCommandDescriptor[]; thinking: { showReasoning: boolean; }; gateway: { enabled: boolean; host: string; port: number; authConfigured: boolean; defaultProvider: string; models: string[]; defaultModel: string; agents: Array<{ name: string; rootDir: string; manifestPath: string | null; }>; providers: Array<{ name: string; defaultModel: string; models: string[]; }>; providerConfigs: RemoteControlProviderConfigPayload[]; }; }; type RemoteControlProviderModelPayload = { id: string; enabled: boolean; displayName?: string; contextWindow?: number; maxOutputTokens?: number; supportsTools?: boolean; supportsImages?: boolean; reasoning?: boolean; supportedThinkingLevels?: ThinkingLevel[]; defaultLevel?: ThinkingLevel | null; maxBudgetTokens?: number | null; dsmlToolCalls?: boolean; pricing?: ModelPricingConfig; }; type RemoteControlProviderConfigPayload = { name: string; type: ProviderType; enabled: boolean; defaultModel: string; baseURL?: string; apiKeyEnv?: string; hasApiKey: boolean; headers?: Record; codexAuth?: CodexAuthConfig; codexAuthConfigured: boolean; dsmlToolCalls?: boolean; thinkingDialect?: ThinkingDialect; models: RemoteControlProviderModelPayload[]; }; type RemoteControlProviderRegistryPayload = { defaultProvider: string; providers: RemoteControlProviderConfigPayload[]; }; type RemoteControlProviderSaveInput = { originalName?: string; provider: Omit & { codexAuth?: CodexAuthConfig | null; }; apiKey?: string; clearApiKey?: boolean; }; type RemoteControlApiConfigPayload = { provider: string; baseURL: string; model: string; models: string[]; apiKeyConfigured: boolean; apiKeyEnv: string | null; }; declare const DEFAULT_CRON_RUN_LOG_MAX_BYTES = 2000000; declare const DEFAULT_CRON_RUN_LOG_KEEP_LINES = 2000; type CronStoreOptions = { storePath?: string; now?: () => Date; minEveryMs?: number; runLog?: { maxBytes?: number; keepLines?: number; }; jitter?: { enabled?: boolean; maxMs?: number; }; }; type LockFile = { pid: number; acquiredAt: string; }; declare function getDefaultCronStorePath(): string; declare class CronStore { readonly storePath: string; private readonly now; private readonly minEveryMs; private readonly runLogMaxBytes; private readonly runLogKeepLines; private readonly jitterMaxMs; constructor(options?: CronStoreOptions); get lockPath(): string; get runsDir(): string; loadJobs(): Promise; saveJobs(jobs: CronJob[]): Promise; private withDefaultJitter; addJob(input: CronJobCreate): Promise; updateJob(id: string, patch: CronJobPatch): Promise; removeJob(id: string, opts?: { cancelRunning?: boolean; }): Promise<{ removed: boolean; job?: CronJob; }>; listJobs(options?: CronListOptions): Promise<{ jobs: CronJob[]; total: number; offset: number; limit: number; hasMore: boolean; }>; status(input: { enabled: boolean; lastTickAt?: string | null; lastError?: string | null; }): Promise; reserveDueJobs(now?: Date, limit?: number): Promise>; reserveManualRun(jobId: string, trigger?: "manual" | "retry" | "missed"): Promise<{ job: CronJob; run: CronRun; }>; finishRun(jobId: string, runId: string, patch: CronRunPatch): Promise; cancelRun(runId: string): Promise; createRun(job: CronJob, trigger: "schedule" | "manual" | "retry" | "missed", now: Date): CronRun; appendRun(run: CronRun): Promise; readRuns(options?: CronRunsOptions): Promise<{ runs: CronRun[]; total: number; offset: number; limit: number; hasMore: boolean; }>; acquireOwnerLock(): Promise; releaseOwnerLock(): Promise; readLock(): Promise; clearStaleRunning(): Promise; runLogPath(jobId: string): string; private pruneRunLog; } declare function summarizeCronRunStatus(status: CronRunStatus): "ok" | "error" | "pending"; type CronRunExecutor = (input: { store: CronStore; job: CronJob; run: CronRun; }) => Promise; type CronCancelExecutor = (input: { store: CronStore; runId: string; }) => Promise; type CronManagementPort = { status(): Promise; list(options?: CronListOptions): Promise<{ jobs: CronJob[]; total: number; offset: number; limit: number; hasMore: boolean; }>; add(input: CronJobCreate): Promise; update(jobId: string, patch: CronJobPatch): Promise; remove(jobId: string, options?: { cancelRunning?: boolean; }): Promise<{ removed: boolean; job?: CronJob; }>; run(jobId: string, trigger?: CronRunTrigger): Promise; runs(options?: CronRunsOptions): Promise<{ runs: CronRun[]; total: number; offset: number; limit: number; hasMore: boolean; }>; cancelRun(runId: string): Promise; }; type LocalCronManagementPortOptions = { enabled?: boolean; runExecutor?: CronRunExecutor; cancelExecutor?: CronCancelExecutor; }; declare function createLocalCronManagementPort(store: CronStore, options?: LocalCronManagementPortOptions): CronManagementPort; type GatewayCronRuntimeLike = { status(): Promise; list(options?: CronListOptions): Promise<{ jobs: CronJob[]; total: number; offset: number; limit: number; hasMore: boolean; }>; add(input: CronJobCreate): Promise; update(jobId: string, patch: CronJobPatch): Promise; remove(jobId: string, options?: { cancelRunning?: boolean; }): Promise<{ removed: boolean; job?: CronJob; }>; run(jobId: string, mode?: "force" | "due"): Promise<{ ran: boolean; reason?: string; run?: CronRun; }>; runs(options?: CronRunsOptions): Promise<{ runs: CronRun[]; total: number; offset: number; limit: number; hasMore: boolean; }>; cancelRun(runId: string): Promise<{ cancelled: boolean; run?: CronRun | null; }>; }; declare function createGatewayCronManagementPort(getRuntime: () => GatewayCronRuntimeLike | null | undefined): CronManagementPort; interface SessionMemorySaveResult { path: string; updatedAt: string; } declare class SessionMemoryStore { private readonly rootDir; constructor(rootDir: string); getPath(sessionId: string): string; load(sessionId: string): Promise; save(sessionId: string, content: string): Promise; } type FileSessionSaveOptions = { preserveNewerRoomMessages?: boolean; }; declare class FileSessionStore { private readonly rootDir; private readonly pendingSaves; constructor(rootDir: string); private getPath; save(session: SessionState, options?: FileSessionSaveOptions): Promise; update(sessionId: string, updater: (session: SessionState) => SessionState | null | Promise): Promise; private saveNow; load(sessionId: string): Promise; private loadNow; list(): Promise; delete(sessionId: string): Promise; } declare class SkillCatalog { private readonly cwd; private readonly includeClaudePaths; private config?; private skills; private statuses; private constructor(); static load(cwd: string, includeClaudePaths?: boolean, config?: Pick): Promise; reload(config?: Pick | undefined): Promise; list(): SkillDefinition[]; status(): SkillStatusEntry[]; get(name: string): SkillDefinition | undefined; } type ResolvedSkillSource = { kind: "local-dir" | "local-file" | "raw-url" | "zip-url" | "github" | "clawhub"; displayName: string; sourceRef: string; fetchMode: "copy-local" | "single-file" | "archive" | "page-then-artifact"; localPath?: string; archiveUrl?: string; rawFileUrl?: string; subpath?: string; metadata?: Record; }; type SkillImportWarning = { code: string; message: string; }; type PreparedSkillAction = "list_prepared" | "read_prepared" | "write_prepared" | "edit_prepared" | "commit" | "abort"; type SkillInstallResult = { ok: true; action: "install" | "prepare" | "commit" | "abort" | "enable" | "disable" | "uninstall" | "reload"; message: string; warnings: SkillImportWarning[]; sourceType?: string; installed?: Array<{ name: string; slug: string; path: string; version?: string; }>; sessionId?: string; workDir?: string; nextStep?: "prepared_session_required"; allowedPreparedActions?: PreparedSkillAction[]; forbiddenDirectTools?: string[]; mustFinishWith?: Array<"commit" | "abort">; systemHint?: string; }; declare class SkillImportService { private readonly input; constructor(input: { skillCatalog: SkillCatalog; cwd: string; includeClaudePaths: boolean; loadConfig?: () => Promise; saveConfig?: (config: AppConfig) => Promise; }); private refreshCatalog; private loadConfig; private saveConfig; install(params: { source: string; replace?: boolean; }): Promise; prepare(params: { source: string; }): Promise; commit(params: { sessionId: string; replace?: boolean; }): Promise; abort(params: { sessionId: string; }): Promise; enable(slug: string): Promise; disable(slug: string): Promise; uninstall(slug: string): Promise; reload(): Promise; listPreparedFiles(sessionId: string, relativePath?: string): Promise<{ path: string; entries: string[]; }>; readPreparedFile(sessionId: string, relativePath: string): Promise<{ path: string; content: string; }>; writePreparedFile(sessionId: string, relativePath: string, content: string): Promise<{ path: string; }>; editPreparedFile(params: { sessionId: string; path: string; oldText: string; newText: string; replaceAll?: boolean; }): Promise<{ path: string; }>; } type LiteSettingSource = "built-in" | "config" | "agent-profile" | "session" | "turn"; type LiteSkillIndexEntry = { name: string; slug?: string; state: "enabled" | "disabled" | "shadowed" | "invalid" | "missing"; }; type LiteSkillIndex = { entries: LiteSkillIndexEntry[]; }; interface ResolvedLiteSettings { configured: { tools: LiteModeConfig["tools"]; skills: LiteModeConfig["skills"]; memory: LiteModeConfig["memory"]; persistence: LiteModeConfig["persistence"]; }; effective: { tools: string[]; skills: string[]; allowMcp: boolean; allowWeb: boolean; allowAgent: boolean; allowSkills: boolean; autoTrigger: boolean; memory: LiteModeConfig["memory"]; persistence: LiteModeConfig["persistence"]; }; available: { tools: string[]; skills: string[]; availableSkillsStatus: "loaded" | "not_loaded"; }; blocked: { tools: string[]; skills: string[]; }; sources: Record; reasons: Record; } declare function normalizeLiteToolRequestName(toolName: string): string; declare function normalizeLiteToolRequestNames(toolNames: string[]): string[]; declare function shouldLoadMcpToolsForLiteRequests(toolNames: string[]): boolean; declare function resolveLiteSettings(input: { config: AppConfig; session: Pick; turnOverride?: LiteOverride | null; availableTools: string[]; skillIndex?: LiteSkillIndex | null; }): ResolvedLiteSettings; type LoadSoulProfileOptions = { ensureDefaults?: boolean; }; declare function ensureSoulProfileFilesSync(rootDir?: string): SoulProfile; declare function loadSoulProfileSync(rootDir?: string, options?: LoadSoulProfileOptions): SoulProfile; declare function loadSoulProfileForSession(session: SessionState): SoulProfile; type RoomControlEventTypeCount = { type: string; count: number; }; type RoomRootDiagnostics = { rootEventId: string; rootSeq: number; textPreview: string; agentReplyCount: number; uniqueAgentReplyCount: number; uniqueAgentMemberIds: string[]; expectedMemberIds: string[]; publishedMemberIds: string[]; skippedMemberIds: string[]; staleMemberIds: string[]; failedMemberIds: string[]; timeoutMemberIds: string[]; decisionCounts: Record; status: "complete" | "open" | "partial" | "inconsistent"; participants: RoomRootParticipantDiagnostics[]; active: boolean; }; type RoomRootParticipantDiagnostics = { memberId: string; displayName: string; status: "pending" | "published" | "published_stale" | "skipped" | "skipped_stale" | "failed" | "timeout"; publishedEventId: string | null; publishSkippedReason: string | null; staleDecision: string | null; }; type RoomPendingMentionDiagnostics = { pendingMentionId: string; rootEventId: string; mentionEventId: string; targetMemberId: string; status: RoomPendingMention["status"]; priority: RoomPendingMention["priority"]; reason: string; inactiveRoot: boolean; }; type RoomSchedulerDecisionTraceSummary = { traceId: string; policyPreset: RoomSpeakerPreset; policyStatus: RoomSpeakerPolicyStatus; decisionKind: string; decisionReason: string; rootEventId: string | null; sourceEventId: string | null; candidateMemberIds: string[]; orderedMemberIds: string[]; selectedMemberIds: string[]; skipped: RoomPolicyDecisionSkip[]; limits: Record; state?: RoomSchedulerPolicyState | null; }; type RoomDiagnosticsSummary = { activeAgentCount: number; transcript: { total: number; human: number; agent: number; system: number; }; controlEvents: { total: number; ratioToTranscript: number; topTypes: RoomControlEventTypeCount[]; }; scheduler: { status: RoomState["scheduler"]["status"]; activeDraftingSlots: number; runningLongTurns: number; readyToAdoptLongTurns: number; activePendingMentions: number; inactiveRootPendingMentions: number; activeRootEventId: string | null; activeRootSeq: number | null; }; roots: RoomRootDiagnostics[]; pendingMentions: RoomPendingMentionDiagnostics[]; recentDecisionTrace: RoomSchedulerDecisionTraceSummary | null; }; type RoomUsageFactsSummary = { label: string; memberId?: string; phase?: string; promptTokens: number; completionTokens: number; totalTokens: number; estimatedCostUsd: number; cachedInputTokens: number | null; cacheMissInputTokens: number | null; cacheWriteInputTokens: number | null; cacheReadInputTokens: number | null; }; type RoomBudgetFactsSummary = { turnsUsed: number; maxTurns: number | null; totalTokens: number; promptTokens: number; completionTokens: number; estimatedCostUsd: number; maxCostUsd: number | null; exhausted: boolean; exhaustedAction: RoomState["budget"]["policy"]["exhaustedAction"]; exhaustedAt: string | null; cachedInputTokens: number | null; cacheMissInputTokens: number | null; cacheWriteInputTokens: number | null; cacheReadInputTokens: number | null; phaseUsage: RoomUsageFactsSummary[]; perMemberUsage: RoomUsageFactsSummary[]; }; type RoomFactsSummary = { roomId: string; title: string; lifecycle: RoomState["lifecycle"]; speakerPolicy: RoomState["speakerPolicy"]["preset"]; activeAgentCount: number; scheduler: RoomDiagnosticsSummary["scheduler"]; controlEvents: RoomDiagnosticsSummary["controlEvents"]; budget: RoomBudgetFactsSummary; activeRootSeq: number | null; latestRootStatus: RoomRootDiagnostics["status"] | null; }; declare function buildRoomDiagnostics(input: { room: RoomState; members: RoomMember[]; transcript: RoomEventEnvelope[]; controlEvents: RoomEventEnvelope[]; topControlTypeLimit?: number; }): RoomDiagnosticsSummary; declare function buildRoomFactsSummary(input: { room: RoomState; members: RoomMember[]; diagnostics?: RoomDiagnosticsSummary; phaseLimit?: number; perMemberLimit?: number; }): RoomFactsSummary; type RoomLifecycleState = "draft" | "active" | "paused" | "quiesced" | "maintenance" | "locked" | "readOnly" | "archived" | "deleted" | "recovering" | "failed"; type RoomMemberKind = "human" | "agent"; type RoomMemberState = "active" | "paused" | "muted" | "removed"; type RoomActorRef = { kind: "human" | "agent" | "system"; memberId?: string | null; sessionId?: string | null; displayName?: string | null; }; type RoomSpeakerPreset = "autonomous" | "mentionOnly" | "roundRobin" | "roundTable" | "intentRoute" | "moderated" | "custom"; type RoomSpeakerTrigger = "freeListen" | "mention" | "roundRobin" | "intentRoute" | "hybrid"; type RoomSpeakerArbitration = "moderator" | "floorLock" | "mutex" | "priorityQueue" | "none"; type RoomSpeakerOrder = "priority" | "fixed" | "random" | "immediate" | "queue" | "roundRobin"; type RoomWorkspaceAccess = "read" | "write"; type RoomWorkspaceSubject = "*" | `human:${string}` | `agent:${string}` | `session:${string}` | `member:${string}` | `role:${string}` | "room:admin"; type RoomWorkspacePolicyRule = { id: string; path: string; read: RoomWorkspaceSubject[]; write: RoomWorkspaceSubject[]; note?: string | null; createdAt: string; updatedAt: string; updatedBy?: RoomActorRef | null; }; type RoomWorkspacePolicy = { defaultRead: boolean; defaultWrite: boolean; rules: RoomWorkspacePolicyRule[]; updatedAt: string | null; }; type RoomSchedulerSafetyPolicy = { floorLockLeaseMs: number; intentCollectionTimeoutMs: number; intentDecisionConcurrency: number; intentEarlySelect: boolean; intentMentionTimeoutFallback: boolean; maxIntentCandidates: number; maxSelectedSpeakers: number; maxChainDepth: number; maxAgentRepliesPerRootEvent: number; maxPairwiseEchoes: number; duplicateFingerprintWindow: number; roomContextRecentMessageLimit: number; roomContextTokenBudget: number; }; type RoomInFlightMessagePolicy = { defaultRunningAgentMessage: "collect" | "ignore" | "queue"; mentionedRunningAgent: "collect" | "interruptAndRestart"; adminInterrupt: "cancelAndRestart" | "steerOnly"; nextObservationMode: "collectUnreadBatch"; }; type RoomDraftingPolicy = { maxConcurrentDrafts: number; publishOrder: "completionTime" | "applicationPriorityThenCompletion"; prePublishSelfCheck: boolean; }; type RoomSpeakerPolicy = { preset: RoomSpeakerPreset; trigger: RoomSpeakerTrigger; arbitration: RoomSpeakerArbitration; order: RoomSpeakerOrder; maxConcurrentSpeakers: number; allowSelfInitiated: boolean; allowSelfInitiatedTopics: boolean; allowAgentToAgentTrigger: boolean; cooldownMs: number; autonomousTickIntervalMs: number; inFlight: RoomInFlightMessagePolicy; drafting: RoomDraftingPolicy; safety: RoomSchedulerSafetyPolicy; updatedAt: string | null; }; type RoomFloorLock = { holderMemberId: string; holderAgentSessionId: string | null; batchId: string | null; rootEventId: string | null; acquiredAt: string; expiresAt: string; }; type RoomDraftingSlotStatus = "drafting" | "drafted" | "self_checking" | "ready_to_publish" | "published" | "cancelled" | "failed"; type RoomDraftingSlot = { slotId: string; roomId: string; applicationId: string; memberId: string; agentSessionId: string; batchId: string; observedThroughEventId: string | null; rootEventId: string | null; status: RoomDraftingSlotStatus; acquiredAt: string; expiresAt: string; turnId?: string | null; lastProgressAt?: string | null; progressEventCount?: number; }; type RoomLongRunningTurnStatus = "running" | "ready_to_adopt" | "adopted" | "superseded" | "cancelled" | "failed" | "expired"; type RoomLateResultAdoptionDecision = "publish" | "revise" | "discard" | "hold"; type RoomLongRunningTurn = { longTurnId: string; roomId: string; rootEventId: string; memberId: string; agentSessionId: string; turnId: string | null; applicationId: string; slotId: string; batchId: string; observedThroughEventId: string | null; observedThroughSeq: number; generation: number; status: RoomLongRunningTurnStatus; startedAt: string; lastProgressAt: string | null; leaseExpiredAt: string | null; resultReturnedAt: string | null; adoptionDecision?: RoomLateResultAdoptionDecision | null; adoptionReason?: string | null; publishedEventId?: string | null; }; type RoomPendingMentionSourceKind = "directMention" | "expectedParticipation" | "retry"; type RoomPendingMentionDeliveryMode = "collect" | "queue" | "steer"; type RoomPendingMentionStatus = "pending" | "collected" | "retry_scheduled" | "in_progress" | "resolved" | "expired" | "cancelled"; type RoomPendingMention = { pendingMentionId: string; roomId: string; rootEventId: string; mentionEventId: string; targetMemberId: string; targetAgentSessionId: string; deliveryMode: RoomPendingMentionDeliveryMode; sourceKind: RoomPendingMentionSourceKind; status: RoomPendingMentionStatus; priority: "high" | "normal"; reason: string; attempts: number; nextRetryAt: string | null; sourceEventIds: string[]; fromSeqExclusive: number; toSeqInclusive: number; createdAt: string; updatedAt: string; resolvedByEventId?: string | null; }; type RoomTopicStatus = "active" | "background" | "paused" | "completed" | "abandoned"; type RoomTopicSource = "human_latest" | "objective" | "agent_followup" | "manual"; type RoomTopicEntry = { rootEventId: string; rootSeq: number; status: RoomTopicStatus; priority: number; lastActivitySeq: number; lastHumanSeq?: number | null; agentReplyCount: number; reason: string; updatedAt: string; }; type RoomTopicState = { activeRootEventId: string | null; activeRootSeq: number | null; activeSource: RoomTopicSource | null; topics: RoomTopicEntry[]; updatedAt: string | null; }; type RoomSpeakerPolicyStatus = "stable" | "partial"; type RoomPolicyDecisionSkip = { memberId: string; reason: string; policyReason: string; retryable: boolean; }; type RoomSchedulerPolicyState = { preset: RoomSpeakerPreset; roundRobin?: { cursorMemberId: string | null; } | null; roundTable?: { rootEventId: string | null; targetMemberIds: string[]; coveredMemberIds: string[]; } | null; updatedAt: string | null; }; type RoomSchedulerState = { status: "idle" | "running" | "paused"; floorLock: RoomFloorLock | null; draftingSlots?: RoomDraftingSlot[]; longRunningTurns?: RoomLongRunningTurn[]; pendingMentions?: RoomPendingMention[]; agentTriggerCoalescing?: { rootEventId: string; sourceEventIds: string[]; fromSeqExclusive: number; toSeqInclusive: number; scheduledAt: string; status: "pending" | "running" | "completed" | "skipped" | "cancelled"; } | null; lastTickAt: string | null; nextTickAt?: string | null; pendingTick?: { tickId: string; scheduledAt: string; reason: string; status: "pending" | "running" | "retryable" | "skipped" | "cancelled"; } | null; lastAutonomousTickAt?: string | null; autonomousTickCount?: number; quiescedReason?: string | null; topicState?: RoomTopicState | null; policyState?: RoomSchedulerPolicyState | null; }; type RoomBudgetExhaustedAction = "pause" | "quiesce" | "mentionOnly"; type RoomTurnPhase = "speechIntent" | "speechApplication" | "reply" | "prePublishSelfCheck" | "retry" | "maintenance"; type RoomToolPurpose = "conversationContext" | "workspaceWork" | "roomInspection" | "externalResearch" | "unknown"; type RoomToolAuditEvent = { roomId: string; memberId: string; sessionId: string; phase: RoomTurnPhase; purpose: RoomToolPurpose; toolName: string; target?: string | null; runtimeInternalSource: boolean; allowed: boolean; reason?: string | null; }; type RoomHandoffPlan = { rootEventId: string; memberIds: string[]; createdFromEventId: string; }; type RoomStalePublishDecision = "allow" | "retry" | "discard"; type RoomSpeechApplicationDecision = "speak" | "silent" | "defer" | "decline"; type RoomSpeechApplication = { applicationId: string; roomId: string; roundId: string; memberId: string; agentSessionId: string | null; batchId: string; decision: RoomSpeechApplicationDecision; priority: "urgent" | "high" | "normal" | "low"; confidence: number; reason: string; mentioned: boolean; expectedContribution?: string | null; canWait?: boolean; replyToEventId?: string | null; allowsConcurrentDraft?: boolean; observedThroughEventId: string | null; fromSeqExclusive: number; toSeqInclusive: number; createdAt: string; deadlineAt: string; status?: "decided" | "timeout_fallback" | "failed" | "busy"; errorCode?: string | null; }; type RoomPromptMetrics = { shape: string; promptCharacters: number; estimatedPromptTokens: number; cacheablePrefixCharacters: number; dynamicSuffixCharacters: number; }; type RoomRootParticipationKind = "openDiscussion" | "mentionedOnly" | "allActiveAgents" | "targetCount" | "handoff"; type RoomRootParticipationContextSource = "heuristic" | "model" | "explicitMention" | "scheduler"; type RoomRootParticipationCompletionStatus = "open" | "sufficient" | "complete" | "partial" | "abandoned"; type RoomRootParticipationContext = { rootEventId: string; kind: RoomRootParticipationKind; oneReplyPerAgent: boolean; expectedMemberIds: string[]; optionalMemberIds: string[]; targetReplyCount: number | null; reason: string; source: RoomRootParticipationContextSource; createdAt: string; updatedAt: string; }; type RoomRootParticipationLedger = { rootEventId: string; context: RoomRootParticipationContext; memberContributions?: RoomRootMemberContributionState[]; publishedMemberIds: string[]; activeDraftMemberIds: string[]; longRunningMemberIds: string[]; pendingMemberIds: string[]; delayedMemberIds: string[]; declinedMemberIds: string[]; failedMemberIds: string[]; timedOutMemberIds: string[]; completionStatus: RoomRootParticipationCompletionStatus; updatedAt: string; }; type RoomRootFirstContributionStatus = "published" | "active_draft" | "long_running" | "declined" | "failed" | "timed_out" | "delayed" | "pending" | "optional" | "not_expected"; type RoomRootMemberContributionState = { memberId: string; firstContributionStatus: RoomRootFirstContributionStatus; publishedEventIds: string[]; supplementCount: number; }; type RoomBudgetPolicy = { maxTurns: number | null; maxCostUsd: number | null; exhaustedAction: RoomBudgetExhaustedAction; updatedAt: string | null; updatedBy?: RoomActorRef | null; }; type RoomUsageTotals = { promptTokens: number; completionTokens: number; totalTokens: number; estimatedCostUsd: number; cachedInputTokens?: number; cacheMissInputTokens?: number; cacheWriteInputTokens?: number; cacheReadInputTokens?: number; }; type RoomBudgetState = { policy: RoomBudgetPolicy; turnsUsed: number; promptTokens: number; completionTokens: number; totalTokens: number; estimatedCostUsd: number; phaseUsage?: Partial>; perMemberUsage?: Record; exhausted: boolean; exhaustedAt: string | null; }; type RoomAnnouncement = { text: string; updatedAt: string; updatedBy: RoomActorRef; }; type RoomObjective = { text: string; state: "active" | "paused" | "completed" | "cancelled"; version: number; updatedAt: string; updatedBy: RoomActorRef; }; type RoomState = { id: string; title: string; lifecycle: RoomLifecycleState; workspaceId: string; workspacePath: string; generation: number; version: number; lastSeq: number; announcement: RoomAnnouncement | null; objective: RoomObjective | null; workspacePolicy: RoomWorkspacePolicy; speakerPolicy: RoomSpeakerPolicy; scheduler: RoomSchedulerState; budget: RoomBudgetState; createdAt: string; updatedAt: string; }; type RoomInboxCursor = { lastObservedSeq: number; lastBatchId: string | null; updatedAt: string | null; }; type RoomMember = { memberId: string; kind: RoomMemberKind; displayName: string; roles: string[]; capabilities: string[]; state: RoomMemberState; humanUserId?: string | null; agentSessionId?: string | null; agentProfileName?: string | null; responsibility?: string | null; roomDigest?: RoomAgentContextDigest | null; inbox: RoomInboxCursor; createdAt: string; updatedAt: string; }; type RoomMembersFile = { roomId: string; members: RoomMember[]; updatedAt: string; }; type RoomEventKind = "transcript" | "control" | "lifecycle"; type RoomEventEnvelope = { id: string; roomId: string; seq: number; kind: RoomEventKind; payloadType: string; actor: RoomActorRef; rootEventId: string; parentEventId: string | null; chainDepth: number; contentFingerprint: string | null; payload: TPayload; observedThroughEventId?: string | null; staleAtPublish?: boolean; visibility: "room" | "control"; createdAt: string; }; type RoomTranscriptPayload = { kind: "human_message" | "agent_message" | "system_message"; text: string; targetMemberIds?: string[]; duplicateOfEventId?: string | null; suppressed?: boolean; generatedByTurnId?: string | null; observedThroughEventId?: string | null; staleAtPublish?: boolean; replyToEventId?: string | null; steeringEventId?: string | null; triggeredByEventId?: string | null; relationKind?: "root" | "reply" | "steering" | "mention_response" | "agent_to_agent_followup" | "summary"; handoff?: { targetMemberId?: string; targetRole?: string; responseKind?: string; urgency?: "low" | "normal" | "high" | "urgent"; expectsResponse?: boolean; } | null; }; type RoomControlPayload = { action: string; targetMemberIds?: string[]; message?: string | null; data?: Record; }; type RoomBatchPrioritySignal = { kind: "mention"; eventId: string; memberId: string; } | { kind: "human_message"; eventId: string; } | { kind: "handoff"; eventId: string; memberId?: string; urgency?: "low" | "normal" | "high" | "urgent"; } | { kind: "admin_control"; eventId: string; } | { kind: "risk" | "decision"; eventId: string; } | { kind: "task_update"; eventId: string; }; type RoomObservationBatch = { batchId: string; roomId: string; targetMemberId: string; targetAgentSessionId: string; fromSeqExclusive: number; toSeqInclusive: number; events: RoomEventEnvelope[]; prioritySignals: RoomBatchPrioritySignal[]; summary?: string | null; createdAt: string; }; type SpeechIntent = { memberId: string; agentSessionId: string | null; batchId: string; decision: RoomSpeechApplicationDecision; priority: "urgent" | "high" | "normal" | "low"; confidence: number; reason: string; mentioned: boolean; deadlineAt: string; roundId?: string; applicationId?: string; expectedContribution?: string | null; canWait?: boolean; replyToEventId?: string | null; allowsConcurrentDraft?: boolean; observedThroughEventId?: string | null; fromSeqExclusive?: number; toSeqInclusive?: number; createdAt?: string; status?: "decided" | "timeout_fallback" | "failed" | "busy"; errorCode?: string | null; promptMetrics?: RoomPromptMetrics; }; type RoomAgentContextDigest = { memberId: string; lastConsumedEventSeq?: number; lastDigestEventSeq?: number; lastEventSeq: number; summary: string; eventRefs: string[]; relevantEventRefs?: string[]; ignoredEventRefs?: string[]; compressionStrategy?: string; semanticSummary?: string; openQuestions?: string[]; decisions?: string[]; handoffs?: string[]; memberClaims?: Record; ownContributions?: string[]; ignoredReasonCounts?: Record; ownPublishedEventRefs?: string[]; updatedAt: string; }; type RoomAgentRuntimeStatusValue = "idle" | "running" | "queued" | "collecting" | "paused" | "aborting" | "missing"; type RoomAgentRuntimeStatus = { sessionId: string; status: RoomAgentRuntimeStatusValue; activeTurnId: string | null; activeSince: string | null; pendingPermissionCount: number; queuedCount: number; collectingCount: number; steerCount: number; lastActivityAt: string | null; }; type RoomStatusSnapshot = { room: RoomState; members: RoomMember[]; agentRuntimeStatuses: Record; diagnostics?: RoomDiagnosticsSummary; }; declare function createDefaultRoomSpeakerPolicy(now?: string | null): RoomSpeakerPolicy; declare function createMentionOnlyRoomSpeakerPolicy(now?: string | null): RoomSpeakerPolicy; declare function createDefaultRoomSchedulerSafetyPolicy(): RoomSchedulerSafetyPolicy; declare function createDefaultRoomInFlightMessagePolicy(): RoomInFlightMessagePolicy; declare function createDefaultRoomDraftingPolicy(): RoomDraftingPolicy; declare function normalizeRoomSpeakerPolicy(policy: Partial | null | undefined, now?: string | null): RoomSpeakerPolicy; declare function createLocalHumanOwnerMember(now: string): RoomMember; declare function createDefaultRoomBudgetState(now?: string | null): RoomBudgetState; declare function normalizeRoomBudgetState(value: Partial | null | undefined, now?: string | null): RoomBudgetState; type RoomTranscriptRecallQuery = { text: string; eventIds: string[]; }; type RoomTranscriptRecallSearchInput = { transcript: RoomEventEnvelope[]; query: string; speaker?: string | null; rootSeq?: number | null; minSeq?: number | null; maxSeq?: number | null; excludedEventIds?: Iterable; maxResults?: number; maxExcerptChars?: number; }; type RoomTranscriptRecallResult = { eventId: string; seq: number; rootEventId: string; rootSeq: number | null; speaker: string; speakerMemberId: string | null; kind: RoomTranscriptPayload["kind"]; createdAt: string; excerpt: string; score: number; reason: string; }; declare function isMaterialRoomTranscriptEvent(event: RoomEventEnvelope): event is RoomEventEnvelope; declare function shouldRecallRoomTranscriptForText(text: string): boolean; declare function buildRoomTranscriptRecallQueryFromBatch(batch: RoomObservationBatch): RoomTranscriptRecallQuery | null; declare function searchRoomTranscript(input: RoomTranscriptRecallSearchInput): RoomTranscriptRecallResult[]; declare function formatRoomTranscriptRecallEvidence(results: RoomTranscriptRecallResult[]): string | null; declare function fingerprintRoomTranscriptRecallQuery(text: string): string; type RoomTranscriptSearchToolInput = { query: string; speaker?: string | null; rootSeq?: number | null; minSeq?: number | null; maxSeq?: number | null; maxResults?: number; maxExcerptChars?: number; }; type RoomTranscriptSearchToolResult = { roomId: string; queryFingerprint: string; results: RoomTranscriptRecallResult[]; }; type RoomTranscriptSearchPort = (input: RoomTranscriptSearchToolInput) => Promise; declare function createRoomTranscriptSearchTool(input: { search: RoomTranscriptSearchPort; }): ToolDefinition; type RoomWorkspacePolicyMember = Pick; type RoomWorkspacePolicyContext = { roomId: string; workspacePath: string; member: RoomWorkspacePolicyMember; policy: RoomWorkspacePolicy; roomToolPurpose?: RoomToolPurpose; roomTranscriptSearch?: RoomTranscriptSearchPort; onDecision?: (input: { request: unknown; decision: RoomWorkspacePolicyDecision; }) => Promise | void; }; type RoomWorkspacePolicyDecision = { allowed: boolean; access: RoomWorkspaceAccess; reason: string; relativePath: string | null; matchedRuleId: string | null; runtimeInternalSource?: boolean; }; declare function createDefaultRoomWorkspacePolicy(now?: string | null): RoomWorkspacePolicy; declare function normalizeRoomWorkspacePolicy(policy: Partial | null | undefined, now?: string | null): RoomWorkspacePolicy; declare function createRoomWorkspacePolicyRule(input: { id: string; path: string; read?: RoomWorkspaceSubject[]; write?: RoomWorkspaceSubject[]; note?: string | null; now: string; updatedBy?: RoomWorkspacePolicyRule["updatedBy"]; }): RoomWorkspacePolicyRule; declare function evaluateRoomWorkspacePolicy(input: { context: RoomWorkspacePolicyContext; access: RoomWorkspaceAccess; targetPath?: string | null; }): Promise; declare function subjectMatchesMember(subject: RoomWorkspaceSubject, member: RoomWorkspacePolicyMember): boolean; declare function inferRoomWorkspaceAccess(input: { toolName: string; risk?: string; }): RoomWorkspaceAccess; type SkillCatalogLike$1 = { get(name: string): SkillDefinition | undefined; list(): SkillDefinition[]; status(): SkillStatusEntry[]; }; type AgentCatalogLike$1 = { get(name: string): AgentDefinition | undefined; list(): AgentDefinition[]; reload?(): Promise | unknown; }; type McpManagerLike$1 = { listStatuses(): McpServerStatus[]; getToolDefinitions(): ToolDefinition[]; }; type RemoteTurnManagerDeps = { getConfig(): AppConfig; sessionStore: FileSessionStore; skillCatalog: SkillCatalogLike$1; agentCatalog: AgentCatalogLike$1; mcpManager: McpManagerLike$1; runSubAgent?: (input: SubAgentRunInput) => Promise; createSkillImportService?: () => SkillImportService; createProviderAdapter?: (config: AppConfig, providerName: string, modelId: string) => ProviderAdapter; sessionMemoryStore?: SessionMemoryStore; loadSoulProfile?(session: SessionState): ReturnType; cronManagement?: CronManagementPort; permissionPromptTimeoutMs?: number | null; /** * Returns the current writer lease for a session, if any. Permission prompts * use lease liveness to decide whether an unanswered prompt is truly * orphaned: while a writer lease exists the human may just be slow, so the * timeout is extended instead of auto-denying (iss-027 M-11). */ getLease?(sessionId: string): unknown; }; type SendTurnInput = { sessionId: string; userMessage: string; persistedUserMessage?: string; persistMode?: "normal" | "ephemeral"; allowConcurrent?: boolean; skipPersistence?: boolean; toolMode?: "default" | "none"; subAgentMode?: "default" | "foreground"; sessionContextMode?: SessionContextMode; behaviorMode?: BehaviorMode; permissionMode?: PermissionMode; liteOverride?: LiteOverride | null; thinkingLevel?: ThinkingLevel; idempotencyKey?: string; attachments?: TurnAttachment[]; fastgptKnowledgeScope?: FastGptKnowledgeScope | null; providerAttribution?: GatewayAttributionContext; roomToolPolicy?: RoomWorkspacePolicyContext | null; roomTurnPhase?: RoomTurnPhase; roomToolPurpose?: RoomToolPurpose; onEvent(event: RemoteControlEventFrame): void; onSessionUpdated?(session: SessionState): void | Promise; }; type TurnCompletion = { status: "completed"; session: SessionState; assistantText?: string | null; } | { status: "aborted"; session: SessionState; assistantText?: string | null; } | { status: "failed"; session: SessionState; message: string; assistantText?: string | null; }; type SendTurnResult = { ok: true; turnId: string; session: SessionState; completion: Promise; } | { ok: false; code: "SESSION_NOT_FOUND" | "TURN_IN_PROGRESS" | "INVALID_REQUEST" | "RUNTIME_INIT_FAILED"; message: string; }; type EnqueueBusyMessageInput = { sessionId: string; userMessage: string; persistedUserMessage?: string; mode: "queue" | "collect"; source?: BusyMessageSource; idempotencyKey?: string; thinkingLevel?: ThinkingLevel; attachments?: TurnAttachment[]; front?: boolean; }; type SteerTurnInput = { sessionId: string; userMessage: string; persistedUserMessage?: string; source?: BusyMessageSource; expectedTurnId?: string; fallback?: "queue" | "collect" | "reject"; idempotencyKey?: string; }; type BusyMessageMutationResult = { ok: true; session: SessionState; mode: "queue" | "collect" | "steer"; itemId: string; status: string; } | { ok: false; code: "SESSION_NOT_FOUND" | "TURN_NOT_ACTIVE" | "INVALID_REQUEST" | "BUSY_MESSAGES_DISABLED" | "BUSY_MESSAGE_REJECTED"; message: string; }; declare class RemoteTurnManager { private readonly deps; private readonly activeTurns; private readonly sessionAllowRulesBySession; private readonly sessionMemoryStore; private readonly sessionCache; private readonly providerAdapterCache; constructor(deps: RemoteTurnManagerDeps); getProviderCacheMetrics(providerName: string, modelId: string): ReturnType> | null; resetProviderAdapterCache(): void; private getOrCreateProviderAdapter; send(input: SendTurnInput): Promise; abort(input: { sessionId: string; }): boolean; getRuntimeStatus(sessionId: string): Promise; getLiteSettings(input: { sessionId: string; turnOverride?: LiteOverride | null; }): Promise<{ ok: true; settings: ResolvedLiteSettings; } | { ok: false; code: "SESSION_NOT_FOUND"; message: string; }>; enqueue(input: EnqueueBusyMessageInput): Promise; steer(input: SteerTurnInput): Promise; cancelQueuedMessage(input: { sessionId: string; itemId: string; }): Promise; clearQueuedMessages(input: { sessionId: string; }): Promise; reorderQueuedMessages(input: { sessionId: string; itemIds: string[]; }): Promise; respondPermission(input: { sessionId: string; permissionId: string; decision: PermissionPromptChoice; }): boolean; private getOrCreateSessionAllowRules; getSessionAllowRules(sessionId: string): string[]; addSessionAllowRule(sessionId: string, toolName: string): void; revokeSessionAllowRule(sessionId: string, toolName: string): boolean; clearSessionAllowRules(sessionId: string): number; private emitBusyRejected; private emitBusyDrainUpdated; private getLiteSkillIndex; private shouldLoadMcpToolsForLite; private prepareRuntimeState; private runTurn; private settlePendingSteering; private runSingleTurn; private drainBusyMessages; private notifyBusyMutation; private waitForBusyMutation; private loadPromptContext; private loadLitePromptContext; private persistMemoryArtifacts; private maybeCompactSession; getSession(sessionId: string): Promise; private loadSession; private persistSession; } type GoalStatus = "draft" | "ready_for_approval" | "active" | "paused" | "waiting_for_approval" | "waiting_for_decision" | "verifying" | "stalled" | "budget_exhausted" | "interrupted" | "succeeded" | "failed" | "cancelled"; type GoalAcceptanceCheck = { id: string; kind: "command"; required: true; command: string; cwd?: string; timeoutMs: number; expectedExitCode: number; } | { id: string; kind: "file_scope"; required: true; } | { id: string; kind: "artifact"; required: true; artifactType: string; } | { id: string; kind: "model_review"; required: boolean; rubric: string[]; blockingSeverities: Array<"critical" | "high">; } | { id: string; kind: "human"; required: true; prompt: string; }; interface GoalContract { version: number; objective: string; allowedPaths: string[]; deniedPaths: string[]; acceptanceChecks: GoalAcceptanceCheck[]; budgets: { maxTurns: number; maxMinutes: number; maxCostUsd: number | null; }; authority: { allowedActions: string[]; approvalRequiredActions: string[]; }; deliverables: string[]; } interface GoalVerdict { result: "passed" | "failed" | "inconclusive"; retryable: boolean; reasons: string[]; missingEvidence: string[]; findings: Array<{ severity: "critical" | "high" | "medium" | "low"; summary: string; evidenceRefs: string[]; }>; } interface GoalRecord { goalId: string; workspaceRoot: string; sessionId: string; status: GoalStatus; revision: number; contract: GoalContract; activeWorkUnitId: string | null; workspaceRevision: number; noProgressCount: number; budgetUsage: { turns: number; elapsedMs: number; estimatedCostUsd: number | null; }; lastVerdict: GoalVerdict | null; createdAt: string; updatedAt: string; endedAt: string | null; } interface GoalEvent { eventId: string; type: string; goalId: string; revision: number; at: string; actor: "user" | "system" | "runtime" | "verifier"; reason?: string; record: GoalRecord; } interface CreateGoalDraftInput { session: Pick; objective: string; maxTurns?: number; maxMinutes?: number; maxCostUsd?: number | null; } declare function validateGoalContract(contract: GoalContract): GoalContract; declare function createGoalDraft(input: CreateGoalDraftInput): GoalRecord; declare function canTransitionGoal(from: GoalStatus, to: GoalStatus): boolean; declare function isTerminalGoalStatus(status: GoalStatus): boolean; declare function transitionGoal(record: GoalRecord, to: GoalStatus, patch?: Partial>): GoalRecord; declare function createGoalEvent(input: Omit & { at?: string; }): GoalEvent; type GoalEvidenceStatus = "passed" | "failed" | "inconclusive" | "info"; interface GoalEvidence { evidenceId: string; goalId: string; goalRevision: number; contractVersion: number; workspaceRevision: number; type: "check" | "work_unit" | "review" | "human" | "artifact"; checkId?: string; status: GoalEvidenceStatus; summary: string; artifactPath?: string; workspaceFingerprint?: string; createdAt: string; } interface GoalTransitionInput { goalId: string; expectedRevision: number; next: GoalRecord; type: string; actor: GoalEvent["actor"]; reason?: string; } declare class GoalStore { private readonly workspaceRoot; private static readonly transitionLocks; constructor(workspaceRoot: string); getGoalsDir(): string; getGoalDir(goalId: string): string; getSnapshotPath(goalId: string): string; getEventsPath(goalId: string): string; getEvidencePath(goalId: string): string; getArtifactsDir(goalId: string): string; create(record: GoalRecord): Promise; load(goalId: string): Promise; commitTransition(input: GoalTransitionInput): Promise; private withTransitionLock; private appendEvent; private readSnapshot; private replayEvents; private writeSnapshot; } declare class GoalEvidenceStore { private readonly store; constructor(store: GoalStore); append(input: Omit): Promise; list(goalId: string): Promise; } interface GoalCommandResult { exitCode: number; stdout: string; stderr: string; } interface GoalCheckRunnerOptions { execute?(command: string, cwd: string, timeoutMs: number): Promise; fingerprint?(cwd: string): Promise; } declare class GoalCheckRunner { private readonly store; private readonly evidence; private readonly execute; private readonly fingerprint; constructor(store: GoalStore, options?: GoalCheckRunnerOptions); run(record: GoalRecord, checkId: string): Promise; runFileScope(record: GoalRecord, checkId?: string): Promise; isEvidenceFresh(record: GoalRecord, evidence: GoalEvidence): Promise; fingerprintWorkspace(workspaceRoot: string): Promise; collectReviewMaterial(record: GoalRecord): Promise; private executeCommand; private createFingerprint; private parseChangedPaths; private parseUntrackedPaths; private filterRuntimeArtifactStatus; private redactReviewMaterial; private isAllowedPath; private isRuntimeArtifactPath; private matchesPattern; } type GoalReviewer = (input: { goal: GoalRecord; evidence: GoalEvidence[]; }) => Promise; type GoalEvidenceFreshness = (input: { goal: GoalRecord; evidence: GoalEvidence; }) => Promise; type GoalReviewObserver = { onReviewStarted?(goal: GoalRecord): void; onReviewCompleted?(goal: GoalRecord, verdict: GoalVerdict): void; }; declare class GoalVerifier { private readonly reviewer; private readonly isEvidenceFresh?; private readonly reviewObserver?; constructor(reviewer: GoalReviewer, isEvidenceFresh?: GoalEvidenceFreshness | undefined, reviewObserver?: GoalReviewObserver | undefined); verify(input: { goal: GoalRecord; evidence: GoalEvidence[]; }): Promise; } declare const GOAL_WORK_UNIT_TRANSCRIPT_MARKER = "[[xigua-goal-work-unit]]"; type GoalForegroundEvent = { kind: "runtime-frame"; goalId: string; sessionId: string; phase: "work_unit" | "review"; frame: RemoteControlEventFrame; } | { kind: "lifecycle"; goalId: string; sessionId: string; event: "goal.started" | "work_unit.started" | "work_unit.completed" | "work_unit.interrupted" | "verification.started" | "goal.waiting" | "goal.terminal"; status: GoalStatus; workUnitId?: string; summary?: string; } | { kind: "acceptance"; goalId: string; sessionId: string; checkId: string; checkKind: GoalAcceptanceCheck["kind"]; state: "started" | "passed" | "failed" | "inconclusive"; summary: string; artifactPath?: string; } | { kind: "review"; goalId: string; sessionId: string; state: "started" | "completed"; verdict?: GoalVerdict; }; type GoalForegroundObserver = (event: GoalForegroundEvent) => void; declare function summarizeGoalForegroundText(text: string, maxChars?: number): string; declare function emitGoalForegroundEvent(observer: GoalForegroundObserver | undefined, event: GoalForegroundEvent): void; interface GoalControllerOptions { store: GoalStore; checks?: GoalCheckRunner; reviewer?: GoalReviewer; onForegroundEvent?: GoalForegroundObserver; } interface GoalApprovalOptions { actor?: Extract; reason?: string; } interface GoalEvidenceSummary { checkId: string; kind: GoalAcceptanceCheck["kind"]; required: boolean; freshness: "current" | "missing" | "stale"; evidence: GoalEvidence | null; } declare class GoalController { private readonly options; private readonly checks; private readonly evidence; private readonly verifier; constructor(options: GoalControllerOptions); get store(): GoalStore; create(input: GoalRecord | CreateGoalDraftInput): Promise; get(goalId: string): Promise; approve(goalId: string, options?: GoalApprovalOptions): Promise; pause(goalId: string): Promise; resume(goalId: string): Promise; cancel(goalId: string): Promise; revise(goalId: string, revision: (contract: GoalContract) => GoalContract): Promise; beginWorkUnit(goalId: string): Promise; completeWorkUnit(input: { goalId: string; expectedRevision: number; elapsedMs: number; estimatedCostUsd: number | null; workspaceChanged: boolean; summary: string; }): Promise; interruptWorkUnit(input: { goalId: string; expectedRevision: number; reason: string; }): Promise; verify(goalId: string): Promise; listEvidence(goalId: string): Promise; summarizeEvidence(goalId: string): Promise; private transition; private interruptVerification; private emit; private emitLifecycleForRecord; private runForegroundCheck; private require; private toForegroundVerdict; private getBudgetExhaustionReason; private writeFinalReport; } type CreateRoomInput = { title: string; workspaceId: string; workspacePath: string; lifecycle?: RoomLifecycleState; members?: RoomMember[]; workspacePolicy?: RoomWorkspacePolicy; now?: string; }; type AppendRoomEventInput = { roomId: string; kind?: RoomEventKind; payloadType: string; payload: TPayload; actor: RoomActorRef; rootEventId?: string | null; parentEventId?: string | null; chainDepth?: number; contentFingerprint?: string | null; observedThroughEventId?: string | null; staleAtPublish?: boolean; visibility?: "room" | "control"; createdAt?: string; }; declare class RoomStore { private readonly rootDir; private readonly pendingAppends; private readonly pendingSaves; constructor(rootDir: string); private getRoomDir; private getRoomPath; private getMembersPath; private getTranscriptPath; private getTranscriptGenerationArchivePath; private getControlEventsPath; private getRoomLockPath; createRoom(input: CreateRoomInput): Promise; loadRoom(roomId: string): Promise; saveRoom(room: RoomState): Promise; updateRoom(roomId: string, update: (room: RoomState) => RoomState | null | undefined | Promise): Promise; listRooms(): Promise; loadMembers(roomId: string): Promise; saveMembers(roomId: string, members: RoomMember[]): Promise; appendTranscriptEvent(input: AppendRoomEventInput): Promise>; appendControlEvent(input: AppendRoomEventInput): Promise>; readTranscript(roomId: string, input?: { afterSeq?: number; limit?: number; }): Promise; readControlEvents(roomId: string, input?: { afterSeq?: number; limit?: number; }): Promise; clearTranscript(roomId: string, input?: { now?: string; }): Promise<{ archivePath: string; previousGeneration: number; nextGeneration: number; }>; recoverRoomRuntime(roomId: string, input?: { now?: string; }): Promise; exportRoom(roomId: string, input: { targetDir: string; }): Promise<{ targetDir: string; files: string[]; }>; cloneRoom(input: { sourceRoomId: string; title: string; fromSeq?: number; includeTranscript?: boolean; now?: string; }): Promise; saveRoomTemplate(input: { roomId: string; name: string; }): Promise<{ path: string; }>; createRoomFromTemplate(input: { name: string; title?: string; now?: string; }): Promise; private appendEvent; private readJsonl; private writeJsonFile; private withRoomWriteLock; private acquireRoomWriteLock; } type RoomRuntimeCleanupMode = "recover" | "pause" | "quiesce" | "stop" | "resume" | "activate"; type RoomRuntimeLongTurnAction = "none" | "cancel_active" | "expire_stale"; type RoomRuntimeQueueAction = "none" | "skip_active" | "cancel_active"; type RoomRuntimeSlotAction = "none" | "release_expired" | "release_all"; type RoomRuntimeCleanupLongTurnRef = { longTurnId: string; rootEventId: string; memberId: string; agentSessionId: string; turnId: string | null; applicationId: string; slotId: string; batchId: string; previousStatus: RoomLongRunningTurn["status"]; status: RoomLongRunningTurn["status"]; }; type RoomRuntimeCleanupResult = { changed: boolean; mode: RoomRuntimeCleanupMode; expiredFloorLockCount: number; releasedDraftingSlotCount: number; expiredLongTurnCount: number; cancelledLongTurnCount: number; skippedCoalescingCount: number; cancelledCoalescingCount: number; skippedPendingTickCount: number; cancelledPendingTickCount: number; before: RoomRuntimeSummary; after: RoomRuntimeSummary; expiredLongTurns: RoomRuntimeCleanupLongTurnRef[]; cancelledLongTurns: RoomRuntimeCleanupLongTurnRef[]; }; type RoomRuntimeSummary = { lifecycle: RoomLifecycleState; schedulerStatus: RoomSchedulerState["status"]; floorLock: boolean; draftingSlots: number; runningLongTurns: number; readyToAdoptLongTurns: number; coalescingStatus: string | null; pendingTickStatus: string | null; }; type RoomRuntimeCleanupOptions = { now: string; mode: RoomRuntimeCleanupMode; lifecycle?: RoomLifecycleState; schedulerStatus?: RoomSchedulerState["status"]; slots?: RoomRuntimeSlotAction; longTurns?: RoomRuntimeLongTurnAction; coalescing?: RoomRuntimeQueueAction; pendingTick?: RoomRuntimeQueueAction; quiescedReason?: string | null; }; declare function cleanupRoomRuntimeState(room: RoomState, options: RoomRuntimeCleanupOptions): { room: RoomState; result: RoomRuntimeCleanupResult; }; declare function summarizeRoomRuntime(room: RoomState): RoomRuntimeSummary; type RoomControlSessionControl = { abortTurn(input: { sessionId: string; }): boolean; steerTurn(input: { sessionId: string; userMessage: string; source?: "gateway" | "cli" | "tui" | "web" | "cron" | "room"; }): Promise<{ ok: boolean; message?: string; code?: string; }> | { ok: boolean; message?: string; code?: string; }; enqueueBusyMessage?(input: { sessionId: string; userMessage: string; mode: "queue" | "collect"; source?: "gateway" | "cli" | "tui" | "web" | "cron" | "room"; idempotencyKey?: string; }): Promise<{ ok: boolean; message?: string; code?: string; }> | { ok: boolean; message?: string; code?: string; }; clearQueuedMessages?(input: { sessionId: string; }): Promise<{ ok: boolean; message?: string; code?: string; }> | { ok: boolean; message?: string; code?: string; }; executeSlashCommand(input: { sessionId: string; raw: string; }): Promise<{ ok: boolean; output: string; }> | { ok: boolean; output: string; }; }; type RoomControlResult = { ok: boolean; roomId: string; action: string; targeted: string[]; succeeded: string[]; failed: Array<{ memberId: string; reason: string; }>; cleanup?: RoomRuntimeCleanupResult | null; cancelledLongTurns?: string[]; }; type RoomControlServiceDeps = { roomStore: RoomStore; sessionControl: RoomControlSessionControl; now?: () => string; }; declare class RoomControlService { private readonly deps; constructor(deps: RoomControlServiceDeps); pauseRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; resumeRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; stopAll(input: { roomId: string; actor: RoomActorRef; }): Promise; stopAgents(input: { roomId: string; actor: RoomActorRef; targets: string[]; clearQueue?: boolean; }): Promise; pauseAgents(input: { roomId: string; actor: RoomActorRef; targets: string[]; }): Promise; resumeAgents(input: { roomId: string; actor: RoomActorRef; targets: string[]; }): Promise; steerAgents(input: { roomId: string; actor: RoomActorRef; targets: string[]; instruction: string; }): Promise; interruptAgents(input: { roomId: string; actor: RoomActorRef; targets: string[]; instruction: string; }): Promise; compactSessions(input: { roomId: string; actor: RoomActorRef; targets?: string[] | "all"; }): Promise; clearTranscript(input: { roomId: string; actor: RoomActorRef; }): Promise; clearSessions(input: { roomId: string; actor: RoomActorRef; targets?: string[] | "all"; }): Promise; archiveRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; restoreRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; softDeleteRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; recoverRoom(input: { roomId: string; actor: RoomActorRef; activate?: boolean; }): Promise; activateRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; lockRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; unlockRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; setReadOnly(input: { roomId: string; actor: RoomActorRef; enabled: boolean; }): Promise; quiesceRoom(input: { roomId: string; actor: RoomActorRef; reason?: string | null; }): Promise; setMaintenanceMode(input: { roomId: string; actor: RoomActorRef; enabled: boolean; }): Promise; setBudgetPolicy(input: { roomId: string; actor: RoomActorRef; maxTurns?: number | null; maxCostUsd?: number | null; exhaustedAction?: RoomBudgetExhaustedAction; }): Promise; resetBudget(input: { roomId: string; actor: RoomActorRef; }): Promise; exportRoom(input: { roomId: string; actor: RoomActorRef; targetDir: string; }): Promise<{ targetDir: string; files: string[]; }>; cloneRoom(input: { roomId: string; actor: RoomActorRef; title: string; includeTranscript?: boolean; fromSeq?: number; }): Promise; saveTemplate(input: { roomId: string; actor: RoomActorRef; name: string; }): Promise<{ path: string; }>; createFromTemplate(input: { roomId: string; actor: RoomActorRef; name: string; title?: string; }): Promise; private stopMembers; private setAgentMemberState; private resolveAgentMembers; private transitionLifecycle; private lastCleanupByRoomId; private applyRoomRuntimeCleanup; private appendLongTurnTerminalEvents; private getLastCleanupSummary; private assertCan; private appendControl; private requireRoom; private now; } declare function getRoomContextCacheMetrics(): { hits: number; misses: number; invalidations: number; evictions: number; totalLookups: number; hitRate: number; }; declare function resetRoomContextCacheMetrics(): void; declare function clearRoomContextCache(): void; type RoomTurnPromptInput = { roomBasicContext: string; batch: RoomObservationBatch; selfMember?: RoomMember | null; rootParticipationLedger?: RoomRootParticipationLedger | null; recentEventsLimit?: number; includeUnreadMessages?: boolean; transcriptRecallEvidence?: string | null; }; declare function buildRoomBasicContext(input: { room: RoomState; members: RoomMember[]; selfMemberId: string; runtimeStatuses?: Record; }): string; declare function buildCompactRoomBasicContext(input: { room: RoomState; members: RoomMember[]; selfMemberId: string; runtimeStatuses?: Record; }): string; declare function buildRoomApplicationBasicContext(input: { room: RoomState; members: RoomMember[]; selfMemberId: string; runtimeStatuses?: Record; }): string; declare function buildRoomObservationPrompt(input: RoomTurnPromptInput): string; declare function buildRoomSpeechApplicationPrompt(input: RoomTurnPromptInput): string; declare function measureRoomSpeechApplicationPrompt(prompt: string): RoomPromptMetrics; declare function buildRoomPrePublishSelfCheckPrompt(input: { roomBasicContext: string; draftText: string; batch: RoomObservationBatch; newerEvents: RoomEventEnvelope[]; selfMember?: RoomMember | null; rootParticipationLedger?: RoomRootParticipationLedger | null; recentEventsLimit?: number; compactNewerEvents?: boolean; }): string; declare function buildRoomSpeechIntentPrompt(input: RoomTurnPromptInput): string; declare function buildRoleAwareRoomDigest(input: { member: RoomMember; batch: RoomObservationBatch; }): string; type ParsedSpeechIntentDecision = Pick; type ParsedSpeechApplicationDecision = Pick; type ParsedPrePublishSelfCheckDecision = { decision: "publish" | "revise" | "cancel"; finalText?: string; reason: string; }; type RoomSpeechIntentCollectorInput = { room: RoomState; entries: Array<{ member: RoomMember; batch: RoomObservationBatch; }>; now: string; disableEarlySelect?: boolean; createIntent?: (input: { room: RoomState; member: RoomMember; batch: RoomObservationBatch; now: string; }) => Promise | SpeechIntent; }; declare function collectSpeechIntents(input: RoomSpeechIntentCollectorInput): Promise; declare function collectSpeechApplications(input: RoomSpeechIntentCollectorInput & { roundId: string; }): Promise; declare function createDeterministicSpeechIntent(input: { room: RoomState; member: RoomMember; batch: RoomObservationBatch; now: string; }): SpeechIntent; declare function selectSpeechIntent(input: { intents: SpeechIntent[]; members: RoomMember[]; currentFloorLock: RoomState["scheduler"]["floorLock"]; now: string; maxSelectedSpeakers: number; }): SpeechIntent | null; declare function selectSpeechApplications(input: { intents: SpeechIntent[]; members: RoomMember[]; maxSelectedSpeakers: number; excludedMemberIds?: Set; }): SpeechIntent[]; declare function parseSpeechIntentDecisionText(text: string): ParsedSpeechIntentDecision | null; declare function parseSpeechApplicationDecisionText(text: string): ParsedSpeechApplicationDecision | null; declare function parsePrePublishSelfCheckDecisionText(text: string): ParsedPrePublishSelfCheckDecision | null; type RoomSchedulerSessionControl = { syncRoomEventsToSession?(input: { room: RoomState; member: RoomMember; events: RoomEventEnvelope[]; updatedAt: string; }): Promise<{ syncedEventIds: string[]; skipped: boolean; message?: string; }>; enqueueBusyMessage?(input: { sessionId: string; userMessage: string; mode: "queue" | "collect"; source?: "cli" | "tui" | "web" | "gateway" | "cron" | "room"; idempotencyKey?: string; }): Promise<{ ok: boolean; message?: string; code?: string; }> | { ok: boolean; message?: string; code?: string; }; sendTurn(input: { sessionId: string; userMessage: string; persistedUserMessage?: string; persistMode?: "normal" | "ephemeral"; sessionContextMode?: SessionContextMode; idempotencyKey?: string; roomToolPolicy?: RoomWorkspacePolicyContext | null; roomTurnPhase?: RoomTurnPhase; roomToolPurpose?: RoomToolPurpose; onEvent(event: unknown): void; }): Promise<{ ok: true; turnId: string; session: SessionState; completion: Promise<{ status: "completed" | "aborted" | "failed"; session: SessionState; message?: string; assistantText?: string | null; }>; } | { ok: false; code: string; message: string; }>; getRuntimeStatus?(sessionId: string): Promise<{ status: string; activeTurnId?: string | null; queuedCount?: number; collectingCount?: number; }> | { status: string; activeTurnId?: string | null; queuedCount?: number; collectingCount?: number; }; }; type RoomSchedulerResult = { started: true; memberId: string; agentSessionId: string; batchId: string; turnId: string; turnIds?: string[]; memberIds?: string[]; } | { started: false; code: "ROOM_NOT_FOUND" | "ROOM_NOT_ACTIVE" | "NO_SPEAKER" | "SEND_FAILED" | "BUDGET_EXHAUSTED" | "UNSUPPORTED_CONCURRENT_FLOORS"; message: string; }; type RoomSchedulerDeps = { roomStore: RoomStore; sessionControl: RoomSchedulerSessionControl; buildPrompt?: typeof buildRoomObservationPrompt; buildIntentPrompt?: typeof buildRoomSpeechIntentPrompt; buildApplicationPrompt?: typeof buildRoomSpeechApplicationPrompt; buildSelfCheckPrompt?: typeof buildRoomPrePublishSelfCheckPrompt; speechIntentStrategy?: "deterministic" | "model"; createSpeechIntent?: (input: { room: RoomState; member: RoomMember; batch: RoomObservationBatch; now: string; deterministicIntent: SpeechIntent; }) => Promise | SpeechIntent; now?: () => string; }; declare function collectObservationBatch(input: { room: RoomState; member: RoomMember; transcript: RoomEventEnvelope[]; maxEvents?: number; now?: string; }): RoomObservationBatch | null; declare function selectSpeaker(input: { intents: SpeechIntent[]; members: RoomMember[]; currentFloorLock: RoomFloorLock | null; now: string; }): SpeechIntent | null; declare class RoomScheduler { private readonly deps; private readonly schedulerMutationQueue; private readonly pendingMentionRetryWakeups; constructor(deps: RoomSchedulerDeps); onRoomMessage(input: { roomId: string; rootEventId: string; sourceEventId?: string | null; }): Promise; onAutonomousTick(input: { roomId: string; reason?: string; }): Promise; private scheduleFromRoomEvents; private updateSchedulerPolicyState; private recordSchedulerDecisionTrace; private startDraftTurn; private resolveRoomTranscriptRecallEvidence; private handleDraftCompletion; private runPrePublishSelfCheck; private recordPrePublishSelfCheck; private recordRoomUsageDeltaSafely; private markAutonomousIdleBackoff; private releaseFloorLock; private releaseDraftingSlot; private setDraftingSlotStatus; private withRoomSchedulerMutation; private findLongRunningTurn; private updateLongRunningTurn; private recordLateResultEvent; private touchRoomTurnProgress; private recordRootParticipationState; private recordSpeechIntentDecisions; private recordUnselectedSpeechApplications; private recordZeroSpeakerOpenDiscussionFallbackStarted; private advanceObservedApplications; private getBlockingRuntimeStatus; private filterBusyPolicyCandidates; private recordDraftTurnDelayed; private recordPendingMentionIfNeeded; private collectPendingMention; private upsertPendingMention; private recordPendingMentionLifecycleEvent; private startNextPendingMentionRetry; private startApplicationTimeoutFallback; private recordApplicationTimeoutFallbackExhausted; private startNextRootParticipationCompletion; private markPendingMentionInProgress; private schedulePendingMentionRetry; private schedulePendingMentionRetryWakeup; private scheduleNextPendingMentionRetryWakeup; private resolvePendingMentionsForPublishedEvent; private resolvePendingMention; private expirePendingMention; private syncRoomEventsToAgentSession; private convergeIdleMemberInboxes; private coalesceRunningMemberObservations; private scheduleAgentTrigger; private appendAgentTriggerSkipped; private flushAgentTriggerCoalescing; private createRoomToolPolicyContext; private handleRoomTurnEvent; private createModelSpeechIntent; private createModelSpeechApplication; private releaseExpiredFloorLock; } type WorkspaceIdentitySource = "file" | "created" | "path-hash"; interface WorkspaceIdentity { id: string; rootPath: string; source: WorkspaceIdentitySource; metadataPath: string; } declare function assertWorkspaceRootExists(input: { cwd: string; allowMissing?: boolean; }): Promise; declare function resolveWorkspaceIdentity(input: { cwd: string; ensure?: boolean; now?: () => string; }): Promise; type RoomServiceSessionControl = { createSession(input: { cwd?: string; title?: string; agentName?: string; createProfile?: boolean; ensureWorkspaceIdentity?: boolean; }): Promise; getRuntimeStatus?(sessionId: string): Promise; }; type RoomServiceDeps = { roomStore: RoomStore; sessionControl: RoomServiceSessionControl; sessionStore: FileSessionStore; resolveWorkspaceIdentity?: typeof resolveWorkspaceIdentity; now?: () => string; }; declare class RoomService { private readonly deps; constructor(deps: RoomServiceDeps); createRoom(input: { title: string; workspacePath: string; lifecycle?: RoomLifecycleState; actor?: RoomActorRef; }): Promise; getRoom(roomId: string): Promise; listRooms(): Promise; getLatestRoom(): Promise; getMembers(roomId: string): Promise; getRoomStatus(roomId: string): Promise; addAgentMember(input: { roomId: string; agentName: string; displayName?: string; responsibility?: string | null; roles?: string[]; }): Promise; addHumanMember(input: { roomId: string; userId: string; displayName?: string; roles?: string[]; actor: RoomActorRef; }): Promise; updateMemberRoles(input: { roomId: string; target: string; operation: "add" | "remove"; role: string; actor: RoomActorRef; }): Promise; removeMember(input: { roomId: string; target: string; actor: RoomActorRef; }): Promise; setAnnouncement(input: { roomId: string; text: string; actor: RoomActorRef; }): Promise; setObjective(input: { roomId: string; text: string; actor: RoomActorRef; }): Promise; setWorkspacePolicyDefaults(input: { roomId: string; defaultRead?: boolean; defaultWrite?: boolean; actor: RoomActorRef; }): Promise; addWorkspacePolicyRule(input: { roomId: string; path: string; read?: RoomWorkspaceSubject[]; write?: RoomWorkspaceSubject[]; note?: string | null; actor: RoomActorRef; }): Promise; setSpeakerPolicy(input: { roomId: string; preset: RoomSpeakerPreset; actor: RoomActorRef; }): Promise; updateSpeakerPolicy(input: { roomId: string; actor: RoomActorRef; patch?: Partial>; safetyPatch?: Partial; draftingPatch?: Partial; }): Promise; appendHumanMessage(input: { roomId: string; text: string; actor: RoomActorRef; idempotencyKey?: string; }): Promise | { payload: { kind: string; text: string; duplicateOfEventId: string; suppressed: boolean; relationKind: string; }; id: string; roomId: string; seq: number; kind: RoomEventKind; payloadType: string; actor: RoomActorRef; rootEventId: string; parentEventId: string | null; chainDepth: number; contentFingerprint: string | null; observedThroughEventId?: string | null; staleAtPublish?: boolean; visibility: "room" | "control"; createdAt: string; }>; private appendControl; private requireRoom; private now; } type SessionLease = { sessionId: string; holderId: string; holderLabel: string | null; }; type AcquireSessionLeaseInput = { sessionId: string; holderId: string; holderLabel?: string | null; }; type AcquireSessionLeaseResult = { ok: true; lease: SessionLease; } | { ok: false; code: "SESSION_BUSY"; lease: SessionLease; }; declare class SessionLeaseManager { private readonly leases; acquire(input: AcquireSessionLeaseInput): AcquireSessionLeaseResult; release(input: { sessionId: string; holderId: string; }): boolean; releaseAllForHolder(holderId: string): void; clearSession(sessionId: string): boolean; getLease(sessionId: string): SessionLease | null; listLeases(): SessionLease[]; } type AgentCatalogLike = { list(): AgentDefinition[]; get?(name: string): AgentDefinition | undefined; reload?(): Promise | unknown; }; type SkillCatalogLike = { list(): SkillDefinition[]; status(): SkillStatusEntry[]; reload?(): Promise | unknown; }; type McpManagerLike = { listStatuses(): McpServerStatus[]; connectAll?(): Promise; getToolDefinitions?(): ToolDefinition[]; }; type StopTaskCallbackResult = { requested: boolean; task: SessionState["tasks"][number] | undefined; }; type RetryTaskCallbackResult = { ok: true; originalTaskId: string; createdTaskId: string | null; } | { ok: false; code: string; message: string; }; type RoomServiceLike = Pick; type RoomControlServiceLike = Pick; type RoomSchedulerLike = Pick; type SlashCommandRouterDeps = { getConfig(): AppConfig; saveConfig(config: AppConfig): Promise; getSession(sessionId: string): Promise; saveSession(session: SessionState): Promise; sessionStore?: FileSessionStore; env?: Record; getLease?(sessionId: string): SessionLease | null; agentCatalog?: AgentCatalogLike; skillCatalog?: SkillCatalogLike; skillImportService?: SkillImportService; mcpManager?: McpManagerLike; createProviderAdapter?: (config: AppConfig, providerName: string, modelId?: string, env?: Record, modelApiType?: SessionState["modelApiType"]) => ProviderAdapter; abortTurn?(input: { sessionId: string; }): Promise | boolean; enqueueBusyMessage?(input: { sessionId: string; userMessage: string; mode: "queue" | "collect"; source?: BusyMessageSource; }): Promise | BusyMessageMutationResult; steerTurn?(input: { sessionId: string; userMessage: string; source?: BusyMessageSource; }): Promise | BusyMessageMutationResult; cancelQueuedMessage?(input: { sessionId: string; itemId: string; }): Promise | BusyMessageMutationResult; clearQueuedMessages?(input: { sessionId: string; }): Promise | BusyMessageMutationResult; reorderQueuedMessages?(input: { sessionId: string; itemIds: string[]; }): Promise | BusyMessageMutationResult; stopTask?(input: { session: SessionState; taskId: string; }): Promise | StopTaskCallbackResult; retryTask?(input: { session: SessionState; taskId: string; }): Promise | RetryTaskCallbackResult; cronManagement?: CronManagementPort; busyMessageSource?: BusyMessageSource; roomService?: RoomServiceLike; roomControlService?: RoomControlServiceLike; roomScheduler?: RoomSchedulerLike; createGoalController?(session: SessionState): GoalController; startGoal?(input: { sessionId: string; goalId: string; }): void | Promise; }; type SlashCommandExecutionInput = { sessionId: string; raw: string; actor?: RoomActorRef; }; type SlashCommandExecutionResult = { handled: false; ok: false; output: ""; writeIntent: false; events: []; } | { handled: true; ok: boolean; output: string; writeIntent: boolean; code?: string; updatedSession?: SessionState; updatedConfig?: AppConfig; events: RemoteControlEventFrame[]; }; declare class SlashCommandRouter { private readonly deps; constructor(deps: SlashCommandRouterDeps); configureRoomServices(input: Required>): void; getWriteIntent(raw: string): boolean | null; private createResult; private success; private failure; private getEnv; private getSessionMemoryStore; private getSessionStore; private getToolSkillCatalog; private getToolAgentCatalog; private reloadAgentCatalog; private getAgentDefinitions; private getLiteSkillIndex; private shouldLoadMcpToolsForLite; private resolveLiteSettingsForSession; private loadPromptContext; private persistMemoryArtifacts; private maybeCompactCurrentSession; private loadContextDiagnostics; private buildDoctorOutput; private runDream; execute(input: SlashCommandExecutionInput): Promise; private getBusyMessageSource; private renderBusyMutation; private executeBusyQueue; private executeBusyCollect; private executeBusySteer; private executeBusy; private executeClear; private executeRename; private executeExport; private executeUsage; private executeStop; private executeWebSearch; private executeConfig; private resolveExplicitAgentCommandWorkspace; private resolveAgentCommandWorkspace; private resolveProfileWorkspacePath; private createSessionForAgentCommand; private executeAgent; private executeRoom; private executeRoomControl; private resolveRoomForCommand; private rememberActiveRoom; private roomUsage; private roomSettingError; private roomControlResult; private executeTools; private executeContext; private executeMemory; private executeCompact; private executeDream; private executeResume; private executeDoctor; private executeOnboard; private getThinkingState; private renderStatus; private executeMode; private executeLite; private executeThinking; private executeModel; private renderModelRoutingReport; private executeModelRouting; private executeProvider; private executePermissions; private executePlan; configureGoalRuntime(input: Pick): void; private getGoalController; private shouldAutomaticallyApproveGoal; private startGoalInBackground; private goalApprovalNoopResult; private formatGoalRecord; private formatGoalEvidence; private createAndLinkGoal; private executeGoal; private executeTrack; private executeTasks; private renderAgents; reloadSkills(): Promise<{ message: string; }>; private executeSkills; private executeMcp; private renderMcpStatuses; private executeCron; } type RoomTuiResolvedHumanActor = { member: RoomMember; actor: RoomActorRef & { kind: "human"; memberId: string; displayName: string; }; readonly: boolean; }; type RoomTuiEnterResult = { room: RoomState; members: RoomMember[]; human: RoomTuiResolvedHumanActor; transcript: RoomEventEnvelope[]; rootSummaries: RoomRootDiagnostics[]; facts: RoomFactsSummary; }; type RoomTuiSendResult = { room: RoomState; event: RoomEventEnvelope; scheduled: RoomSchedulerResult | null; autoActivated: boolean; suppressed: boolean; rootSummaries: RoomRootDiagnostics[]; facts: RoomFactsSummary; }; type RoomTuiFacadeDeps = { roomStore: Pick; roomService: Pick; roomControlService?: Pick; roomScheduler?: Pick; now?: () => string; }; declare class RoomTuiFacade { private readonly deps; constructor(deps: RoomTuiFacadeDeps); enterRoom(input?: { roomIdOrName?: string | null; humanId?: string | null; transcriptLimit?: number; }): Promise; exitRoom(input: { roomId: string; actor: RoomActorRef; }): Promise; resolveRoom(roomIdOrName?: string | null): Promise; resolveHumanActor(input: { roomId: string; humanId?: string | null; }): Promise; readTranscript(input: { roomId: string; afterSeq?: number; limit?: number; }): Promise<{ room: RoomState; events: RoomEventEnvelope[]; rootSummaries: RoomRootDiagnostics[]; facts: RoomFactsSummary; }>; sendHumanMessage(input: { roomId: string; actor: RoomActorRef; text: string; idempotencyKey?: string; }): Promise; private readDiagnostics; private readTranscriptEvents; private requireRoom; private appendPresenceEvent; } type SessionControlServiceDeps = { config: AppConfig; getConfig?: () => AppConfig; sessionStore: FileSessionStore; saveConfig?: (config: AppConfig) => Promise; /** * Serialized entry point shared by every config writer in the process. When * provided, runConfigMutation() delegates to it so slash-command saveConfig * writes cannot interleave with control-service mutations (iss-027 M-02). * The implementation must NOT call back into saveConfig (deadlock). */ mutateConfig?: (operation: () => Promise) => Promise; leases?: SessionLeaseManager; slashCommandRouter?: SlashCommandRouter; turnManager?: RemoteTurnManager; runtimeHost?: RemoteTurnManager; skillImportService?: SkillImportService; cronManagement?: CronManagementPort; onGoalForegroundEvent?: GoalForegroundObserver; onGoalSessionUpdated?(session: SessionState): void | Promise; resolveAgentProfile?: typeof resolveAgentProfile; resolveWorkspaceIdentity?: typeof resolveWorkspaceIdentity; createAgentProfile?: typeof createAgentProfile; startRoomAutonomousLoop?: boolean; }; type AttachSessionInput = { sessionId: string; holderId: string; holderLabel?: string | null; writeIntent: boolean; /** * Whether the success result carries the full session snapshot. Defaults to true so existing * clients (web console, TUI) keep receiving the transcript. ISS-002: a long conversation can * outgrow the control-channel single-frame limit, so a writer that only needs the lease * (sem-agent) passes false and gets `session: null`. */ includeSession?: boolean; }; type AttachSessionResult = { ok: true; sessionId: string; session: SessionState | null; lease: SessionLease | null; } | { ok: false; code: "SESSION_NOT_FOUND"; } | { ok: false; code: "SESSION_BUSY"; lease: SessionLease; }; declare class SessionControlService { private readonly deps; private configMutations; private readonly leases; private readonly slashCommandRouter; private readonly runtimeHost?; private readonly goalRuntimeAdapter; private readonly roomAutonomousLoop; private readonly roomTuiFacade; constructor(deps: SessionControlServiceDeps); private liveConfig; private runConfigMutation; connect(): Promise; getDefaultApiConfig(): RemoteControlApiConfigPayload; updateDefaultApiConfig(input: { baseURL?: string; apiKey?: string; model?: string; }): Promise; getProviderRegistryConfig(): RemoteControlProviderRegistryPayload; saveProviderConfig(input: RemoteControlProviderSaveInput): Promise; deleteProviderConfig(name: string): Promise; setDefaultProviderModel(providerName: string, modelId: string): Promise; private commitProviderConfig; listSessions(): Promise; createSession(input: { cwd?: string; title?: string; agentName?: string; createProfile?: boolean; ensureWorkspaceIdentity?: boolean; provider?: string; model?: string; thinkingLevel?: ThinkingLevel; permissionMode?: PermissionMode; behaviorMode?: BehaviorMode; }): Promise; getSessionSnapshot(sessionId: string): Promise; deleteSession(input: { sessionId: string; }): Promise; renameSession(input: { sessionId: string; title: string; }): Promise; archiveSession(input: { sessionId: string; }): Promise; restoreSession(input: { sessionId: string; }): Promise; attachSession(input: AttachSessionInput): Promise; detachSession(input: { sessionId: string; holderId: string; }): boolean; getLease(sessionId: string): SessionLease | null; holderHasWriteLease(input: { sessionId: string; holderId: string; }): boolean; executeSlashCommand(input: { sessionId: string; raw: string; actor?: RoomActorRef; }): Promise; enterRoomForTui(input: { roomIdOrName?: string | null; humanId?: string | null; transcriptLimit?: number; }): Promise; exitRoomForTui(input: { roomId: string; actor: RoomActorRef; }): Promise; resolveRoomHumanActorForTui(input: { roomId: string; humanId?: string | null; }): Promise; readRoomTranscriptForTui(input: { roomId: string; afterSeq?: number; limit?: number; }): Promise<{ room: RoomState; events: RoomEventEnvelope[]; rootSummaries: RoomRootDiagnostics[]; facts: RoomFactsSummary; }>; sendRoomMessageForTui(input: { roomId: string; actor: RoomActorRef; text: string; idempotencyKey?: string; }): Promise; reloadSkills(): Promise<{ message: string; }>; getSlashCommandWriteIntent(raw: string): boolean | null; sendTurn(input: { sessionId: string; userMessage: string; persistedUserMessage?: string; persistMode?: "normal" | "ephemeral"; allowConcurrent?: boolean; skipPersistence?: boolean; toolMode?: "default" | "none"; sessionContextMode?: SessionContextMode; behaviorMode?: BehaviorMode; permissionMode?: PermissionMode; liteOverride?: LiteOverride | null; thinkingLevel?: ThinkingLevel; idempotencyKey?: string; attachments?: TurnAttachment[]; fastgptKnowledgeScope?: FastGptKnowledgeScope | null; providerAttribution?: GatewayAttributionContext; roomToolPolicy?: RoomWorkspacePolicyContext | null; roomTurnPhase?: RoomTurnPhase; roomToolPurpose?: RoomToolPurpose; onEvent(event: RemoteControlEventFrame): void; }): Promise; getSessionSettings(input: { sessionId: string; scope: "lite"; turnOverride?: LiteOverride | null; }): Promise<{ ok: true; settings: ResolvedLiteSettings; } | { ok: false; code: "SESSION_NOT_FOUND"; message: string; }>; syncRoomEventsToSession(input: { room: RoomState; member: RoomMember; events: RoomEventEnvelope[]; updatedAt: string; }): Promise<{ syncedEventIds: string[]; skipped: boolean; message?: string; }>; enqueueBusyMessage(input: EnqueueBusyMessageInput): Promise; steerTurn(input: SteerTurnInput): Promise; getRuntimeStatus(sessionId: string): Promise; cancelQueuedMessage(input: { sessionId: string; itemId: string; }): Promise; clearQueuedMessages(input: { sessionId: string; }): Promise; reorderQueuedMessages(input: { sessionId: string; itemIds: string[]; }): Promise; abortTurn(input: { sessionId: string; }): boolean; respondPermission(input: { sessionId: string; permissionId: string; decision: "allow" | "deny" | "always-allow"; }): boolean; getSessionAllowRules(sessionId: string): string[]; addSessionAllowRule(sessionId: string, toolName: string): void; revokeSessionAllowRule(sessionId: string, toolName: string): boolean; clearSessionAllowRules(sessionId: string): number; releaseAllSessionsForHolder(holderId: string): void; } type CommandReportSection = { title: string; lines: Array; }; declare function formatFieldLines(label: string, value: unknown): string[]; declare function formatNestedFieldLines(label: string, value: unknown): string[]; declare function formatSummaryValue(parts: Array<[label: string, value: unknown]>): string | null; declare function formatSummaryLine(label: string, parts: Array<[label: string, value: unknown]>): string | null; declare function formatCommandReport(input: { title: string; sections: CommandReportSection[]; }): string; declare function isCronWorkflowPayload(payload: CronPayload): payload is CronWorkflowPayload; declare function getCronPayloadText(payload: CronPayload): string; declare function describeCronPayload(payload: CronPayload): string; declare function getCronPayloadKindLabel(payload: CronPayload): string; type CronField = { any: boolean; values: Set; }; type ParsedCron = { minute: CronField; hour: CronField; dayOfMonth: CronField; month: CronField; dayOfWeek: CronField; }; declare function resolveCronTimezone(timezone?: string): string; declare function validateCronTimezone(timezone?: string): void; declare function parseCronExpression(expr: string): ParsedCron; declare function parseCronAt(schedule: Extract): Date | null; declare function computeCronNextRunAt(schedule: CronSchedule, now: Date, jobId?: string): Date | null; declare function validateCronSchedule(schedule: CronSchedule, opts?: { minEveryMs?: number; }): void; declare function computeJobNextRunAt(job: CronJob, now: Date): string | null; type CreateCronProposalInput = { name: string; description?: string; schedule: CronSchedule; target: CronTarget; payload?: CronPayload; prompt?: string; enabled?: boolean; policy?: CronPolicy; delivery?: CronDelivery; tags?: string[]; source?: string; sourceSessionId: string; createdBy?: "agent" | "slash" | "system"; minEveryMs?: number; defaultTimezone?: string; }; type CronProposalResult = { status: "ready_for_approval"; proposal: CronProposal; proposalId: string; nextAction: string; preview: CronProposal["preview"]; systemHint: string; } | { status: "needs_clarification"; proposalId: null; nextAction: string; reason: string; }; type CronApprovalPreview = { proposalId: string; name: string; description: string; schedule: string; nextRunAt: string; timezone: string; target: string; prompt: string; enabled: boolean; storePath: string; warnings: string[]; missedPolicy: string; concurrencyPolicy: string; }; declare function createIdleCronProposalState(): SessionCronProposalState; declare function normalizeCronProposalState(raw?: Partial | null): SessionCronProposalState; declare function createCronProposal(input: CreateCronProposalInput): CronProposalResult; declare function markCronProposalReady(session: SessionState, proposal: CronProposal): SessionState; declare function approveCronProposal(session: SessionState): { proposal: CronProposal; session: SessionState; } | null; declare function cancelCronProposal(session: SessionState): SessionState; declare function proposalToJobCreate(proposal: CronProposal): CronJobCreate; declare function buildCronApprovalPreview(proposal: CronProposal, storePath: string): CronApprovalPreview; declare function describeCronSchedule(schedule: CronSchedule): string; declare function describeCronTarget(target: CronTarget): string; declare const HIGH_FREQUENCY_PROMPT_CRON_MS: number; declare const DEFAULT_CRON_WORKFLOW_CAPABILITIES: readonly ["checkpoint.read", "checkpoint.write", "items.filterNew", "items.count", "text.truncate", "dws.message.listBySender", "dws.message.send"]; type CronJobValidationResult = { ok: true; warnings: string[]; } | { ok: false; code: string; message: string; suggestions: string[]; warnings: string[]; }; type CronJobValidationOptions = { minEveryMs?: number; highFrequencyPromptMs?: number; }; declare function validateCronJobCreate(input: CronJobCreate, options?: CronJobValidationOptions): CronJobValidationResult; declare function assertCronJobCreateValid(input: CronJobCreate, options?: CronJobValidationOptions): void; declare function isHighFrequencySchedule(schedule: CronSchedule, thresholdMs?: number): boolean; interface AutoDreamPolicy { enabled: boolean; minHours: number; minSessions: number; throttleMs: number; } interface AutoDreamState { status: "idle" | "running" | "completed" | "failed"; lastConsolidatedAt: string | null; lastTaskId: string | null; lastRunSessionCount: number; updatedAt: string | null; lastError: string | null; lastScanAt: string | null; } interface AutoDreamEvaluation { canRun: boolean; reason: string; candidateSessionIds: string[]; } interface AutoDreamExecutionResult { started: boolean; reason?: string; task?: SessionTask; status?: TaskStatus; } declare function getDefaultAutoDreamPolicy(): AutoDreamPolicy; declare function evaluateAutoDreamPolicy(input: { currentSessionId: string; sessions: Array<{ id: string; updatedAt: string; }>; lastConsolidatedAt: string | null; now?: number; minHours: number; minSessions: number; }): AutoDreamEvaluation; declare function createDreamSession(input: { parentSession: SessionState; taskId: string; }): SessionState; declare function registerDreamTask(parentSession: SessionState, transcriptSessionId: string, reviewedSessions: number): SessionTask; declare function updateDreamTaskPhase(parentSession: SessionState, taskId: string, input: { phase: string; current: number; total?: number; label?: string; touchedPaths?: string[]; recentToolActions?: string[]; }): SessionTask | undefined; declare function completeDreamTask(parentSession: SessionState, taskId: string, summary: string): SessionTask | undefined; declare function failDreamTask(parentSession: SessionState, taskId: string, error: string): SessionTask | undefined; declare function filterToolsForDreamRuntime(tools: T[]): T[]; declare function describeDreamToolPolicy(): string; declare function getDreamStatePath(workspaceRoot: string): string; declare function getDreamLockPath(workspaceRoot: string): string; declare function getSessionDreamStatePath(session: SessionState): string; declare function getSessionDreamLockPath(session: SessionState): string; declare function readAutoDreamState(workspaceRoot: string): Promise; declare function readSessionAutoDreamState(session: SessionState): Promise; declare function writeAutoDreamState(workspaceRoot: string, state: AutoDreamState): Promise; declare function readDreamLock(workspaceRoot: string): Promise<{ locked: boolean; acquiredAt: string | null; }>; declare function readSessionDreamLock(session: SessionState): Promise<{ locked: boolean; acquiredAt: string | null; }>; declare function executeAutoDream(input: { currentSession: SessionState; sessionStore: FileSessionStore; policy?: Partial; now?: number; force?: boolean; runDreamSession?(input: { childSession: SessionState; prompt: string; candidateSessionIds: string[]; candidateSnapshotDir: string; }): Promise; onUpdate?(session: SessionState): Promise | void; }): Promise; declare function createDreamRuntime(input: { session: SessionState; tools: ToolDefinition[]; provider: ProviderAdapter; permissionManager: PermissionManager; gatewayAttribution?: GatewayAttributionContext; compactSession?(session: SessionState, reason?: unknown): Promise | SessionState; maxTurns?: number; }): { run: (userText: string, options?: { signal?: AbortSignal; attachments?: TurnAttachment[]; fastgptKnowledgeScope?: FastGptKnowledgeScope | null; }) => AsyncGenerator; getSession(): SessionState; getStats(): { turnsUsed: number; maxTurnsReached: boolean; }; }; interface StagedDreamContext { rootDir: string; sessionDir: string; sessionFiles: string[]; } declare function stageDreamContext(workspaceRoot: string, taskId: string, sessions: SessionState[], options?: { dreamRootDir?: string | null; }): Promise; declare function toWorkspaceRelativeSnapshotDir(workspaceRoot: string, snapshotDir: string): string; interface GoalWorkUnitResult { summary: string; elapsedMs: number; estimatedCostUsd: number | null; workspaceChanged: boolean; } interface GoalRuntimeServiceOptions { controller: GoalController; runWorkUnit(input: { goal: GoalRecord; prompt: string; }): Promise; onForegroundEvent?: GoalForegroundObserver; } declare class GoalRuntimeService { private readonly options; private readonly active; constructor(options: GoalRuntimeServiceOptions); start(input: { goalId: string; }): Promise; isRunning(goalId: string): boolean; private run; private buildWorkUnitPrompt; } type GoalTurnRuntimeHost = Pick; interface GoalRuntimeAdapterOptions { runtimeHost?: GoalTurnRuntimeHost; getSession(sessionId: string): Promise; createCheckRunner?(store: GoalStore): GoalCheckRunner; fingerprintWorkspace?(workspaceRoot: string): Promise; collectReviewMaterial?(goal: GoalRecord): Promise; onForegroundEvent?: GoalForegroundObserver; onSessionUpdated?(session: SessionState): void | Promise; } declare class GoalRuntimeAdapter { private readonly options; private readonly runtimes; constructor(options: GoalRuntimeAdapterOptions); createController(session: SessionState): GoalController; start(input: { sessionId: string; goalId: string; }): Promise; private getRuntime; private runWorkUnit; private review; private fingerprintWorkspace; private collectReviewMaterial; private emit; private notifySessionUpdated; } interface RecallLogEntry { ts: string; workspaceId: string; agentName: string; slug: string; path: string; score: number; queryDigest: string; } interface RecallLogContext { workspaceId: string; agentName: string; query: string; } declare function getRecallLogPath(): string; declare function appendRecallLog(records: DurableMemoryRecord[], ctx: RecallLogContext): Promise; interface ReadRecallLogOptions { sinceMs?: number; limit?: number; now?: () => Date; path?: string; } declare function readRecallLog(options?: ReadRecallLogOptions): Promise; interface MemoryReportOptions { workspaceRoot?: string; agentName?: string; hotCount?: number; coldCount?: number; recallSinceMs?: number; now?: () => Date; recallLogReader?: () => Promise; } interface MemoryWithScore { slug: string; title: string; type: DurableMemoryType; scope: DurableMemoryScope; source: DurableMemorySource; recall: DurableMemoryRecall; path: string; recallCount: number; lastRecalledAt: string | null; createdAt: string; updatedAt: string; contentBytes: number; isArchive: boolean; } interface MemoryWarning { severity: "warn" | "info"; code: "duplicate_slug" | "orphan_archive" | "dream_failing" | "malformed_frontmatter"; message: string; } interface MemoryHealthReport { generatedAt: string; workspacePath: string; workspaceId: string; agentName: string; agentMemoryDir: string; agentArchiveDir: string; totalPrimary: number; totalArchive: number; byType: Record; bySource: Record; byScope: Record; byRecall: Record; totalContentBytes: number; malformedFiles: number; recentRecallCount: number; recentRecallSlugs: number; recentRecallWindowMs: number; avgRecallScore: number; dreamStatus: AutoDreamState["status"]; dreamLastRunAt: string | null; dreamLastConsolidatedAt: string | null; dreamLastTaskId: string | null; dreamLastError: string | null; dreamLastRunSessionCount: number; hotMemories: MemoryWithScore[]; coldMemories: MemoryWithScore[]; warnings: MemoryWarning[]; } interface FormatMemoryReportOptions { brief?: boolean; format?: "text" | "json"; } declare function buildMemoryHealthReport(options?: MemoryReportOptions): Promise; declare function formatMemoryHealthReport(report: MemoryHealthReport, options?: FormatMemoryReportOptions): string; declare function renderMemoryHotSection(report: MemoryHealthReport, now?: Date): string; declare function renderMemoryColdSection(report: MemoryHealthReport): string; declare function renderMemoryDreamSection(report: MemoryHealthReport, now?: Date): string; declare class McpCapabilityStore { private readonly capabilities; set(snapshot: McpServerCapabilities): void; get(name: string): McpServerCapabilities | undefined; list(serverNames: string[]): McpServerCapabilities[]; clear(name: string): void; clearAll(): void; } declare class McpConfigRegistry { private readonly servers; private readonly serversByName; constructor(servers: McpServerConfig[]); list(): McpServerConfig[]; get(name: string): McpServerConfig | undefined; } type ConnectedServer = { name: string; client: Client; transport: StdioClientTransport; }; declare class McpConnectionRegistry { private readonly configRegistry; private readonly capabilityStore; private readonly connections; private readonly statuses; private readonly pendingConnections; constructor(configRegistry: McpConfigRegistry, capabilityStore: McpCapabilityStore); connectAll(): Promise; connect(name: string): Promise; disconnect(name: string): Promise; reconnect(name: string): Promise; close(): Promise; listStatuses(): McpServerStatus[]; listConnections(): ConnectedServer[]; private connectServer; private discoverCapabilities; private listPrompts; private listResources; private createDisconnectedStatus; private updateStatus; private safeClose; private withTimeout; private toErrorMessage; } declare class McpService { private readonly configRegistry; private readonly capabilityStore; private readonly connectionRegistry; private readonly toolAdapter; constructor(servers: McpServerConfig[]); connectAll(): Promise; connect(name: string): Promise; disconnect(name: string): Promise; reconnect(name: string): Promise; close(): Promise; listStatuses(): McpServerStatus[]; listCapabilities(): McpServerCapabilities[]; getToolDefinitions(): ToolDefinition[]; } declare class McpManager extends McpService { constructor(servers: McpServerConfig[]); } type McpConnectedToolSource = { serverName: string; client: Pick; capabilities: McpToolCapability[]; }; declare function buildProviderSafeMcpToolName(serverName: string, toolName: string, usedNames: Set): string; declare function mapMcpToolRisk(tool: Pick): PermissionRisk; declare function buildMcpToolCapability(tool: Tool): McpToolCapability; declare class McpToolAdapter { getToolDefinitions(sources: McpConnectedToolSource[]): ToolDefinition[]; } interface DurableMemoryUpsertInput { slug: string; title: string; type: DurableMemoryType; scope: DurableMemoryScope; summary: string; content: string; tags?: string[]; source: DurableMemorySource; recall?: DurableMemoryRecall; } interface DurableMemoryQuery { scope?: DurableMemoryScope; types?: DurableMemoryType[]; tags?: string[]; limit?: number; } declare class FileMemoryStore { private readonly rootDir; constructor(rootDir: string); getPath(slug: string): string; upsert(input: DurableMemoryUpsertInput): Promise; loadBySlug(slug: string): Promise; loadByPath(path: string): Promise; listManifests(): Promise; list(): Promise; query(query: DurableMemoryQuery): Promise; getStats(): Promise; } interface FileMemoryStoreStats { totalFiles: number; totalBytes: number; malformedFiles: number; byType: Record; bySource: Record; byScope: Record; byRecall: Record; } interface DurableMemoryCandidate { slug: string; title: string; type: DurableMemoryType; scope: "workspace" | "user"; summary: string; content: string; tags?: string[]; source: DurableMemorySource; recall?: DurableMemoryRecall; } interface MemoryArtifactExtractionResult { durable: DurableMemoryCandidate[]; archive: DurableMemoryCandidate[]; } declare function buildSessionSummary(session: SessionState): SessionSummaryState; declare function buildSessionMemoryContent(session: SessionState): string; declare function extractMemoryArtifacts(session: SessionState): MemoryArtifactExtractionResult; declare function extractDurableMemoryCandidates(session: SessionState): DurableMemoryCandidate[]; interface SelectRelevantMemoriesInput { query: string; memoryManifests: DurableMemoryManifest[]; loadRecord(path: string): Promise; alreadySurfacedPaths: Set; recentTools: string[]; limit?: number; shortlistLimit?: number; } declare function selectRelevantMemories(input: SelectRelevantMemoriesInput): Promise; type SystemPromptBuildInput = { session: SessionState; selectedAgent?: AgentDefinition; skills: Array>; agents: string[]; mcpServers: string[]; sessionMemoryContent?: string | null; relevantMemories?: DurableMemoryRecord[]; contextPressure?: ContextPressure | null; runtimeSystemHints?: string[]; soulProfile?: SoulProfile | null; liteSettings?: ResolvedLiteSettings | null; modelRoutingEnabled?: boolean; }; type SystemPromptSections = { base: string; behavior: string; /** 执行期 Track 锚(pmm-038):每轮从 session.track 重建,不进 transcript,抗压缩。 */ track: string | null; agent: string | null; persona: string | null; environment: string; context: string[]; attachments: string[]; }; declare function buildSystemPromptSections(input: SystemPromptBuildInput): SystemPromptSections; declare function buildSystemPrompt(input: SystemPromptBuildInput): string; declare function buildBehaviorPrompt(session: SessionState): string; declare function buildBehaviorSystemPrompt(input: SystemPromptBuildInput): string; declare const PLAN_MODE_TOOL_NAMES: readonly ["Read", "ReadImage", "Glob", "Grep", "WebFetch", "WebSearch", "Skill", "Agent", "Plan", "SubmitPlan", "Cron"]; declare function isToolAllowedInBehaviorMode(toolName: string, behaviorMode: BehaviorMode): boolean; declare function filterToolsForBehaviorMode(tools: T[], behaviorMode: BehaviorMode, liteSettings?: ResolvedLiteSettings | null): T[]; declare function describeBehaviorToolPolicy(behaviorMode: BehaviorMode): string; declare function resolveModelRoutingEnabled(config: Pick, session: Pick): boolean; declare function formatModelRoutingState(value: boolean): "on" | "off"; /** * Determine if onboarding wizard should be triggered. * Returns false if within silence period after last skip. */ declare function shouldTriggerOnboarding(config: AppConfig): boolean; /** * Check if the default provider has passed at least one connectivity test. */ declare function hasPassedConnectivityTest(config: AppConfig): boolean; /** * Merge partial onboarding state into config. */ declare function updateOnboardingState(config: AppConfig, update: Partial): AppConfig; /** * Compute a hash of the default provider's key config fields. * Used to detect manual config changes after a successful check. */ declare function computeProviderConfigHash(config: AppConfig): string; /** * Check if provider config has changed since last successful check. */ declare function hasProviderConfigChanged(config: AppConfig): boolean; /** * Full preflight check: should the onboarding wizard run? * Returns true if any of these conditions are met: * - Not within silence period AND (auth missing OR never tested OR config changed) */ declare function needsOnboarding(config: AppConfig, isAuthConfigured: boolean): boolean; declare function createPermissionManager(input: { mode: PermissionMode; allowRules: string[]; denyRules: string[]; cwd: string; roomToolPolicy?: RoomWorkspacePolicyContext | null; onRoomPolicyDecision?(input: { request: PermissionRequest; decision: Awaited>; }): Promise | void; onPrompt(request: PermissionRequest): Promise; sessionAllowRules?: Set; }): PermissionManager; interface PlanDocument { title: string; goal: string; scope: string; approach: string; steps: string[]; risks: string[]; validation: string[]; openQuestions: string[]; updatedAt: string; status: PlanStatus; } interface PlanDocumentPatch { title?: string; goal?: string; scope?: string; approach?: string; steps?: string[]; risks?: string[]; validation?: string[]; openQuestions?: string[]; } interface PlanValidationResult { ok: boolean; missing: string[]; } interface PlanApprovalPreview { title: string; goal: string; scope: string; approach: string; steps: string[]; risks: string[]; validation: string[]; openQuestions: string[]; documentPath: string; updatedAt: string; stepCount: number; riskCount: number; validationCount: number; questionCount: number; milestones: string[]; topRisks: string[]; warnings: string[]; readinessLabel: string; } declare function createEmptyPlanDocument(): PlanDocument; declare function mergePlanDocument(existing: PlanDocument, patch: PlanDocumentPatch, status?: PlanStatus): PlanDocument; declare function validatePlanDocument(document: PlanDocument): PlanValidationResult; declare function buildPlanApprovalPreview(document: PlanDocument, documentPath: string): PlanApprovalPreview; declare function markSessionPlanDraft(session: SessionState, input: { documentPath: string; title: string; }): void; declare function markSessionPlanReadyForApproval(session: SessionState, input: { documentPath: string; title: string; }): void; declare function markSessionPlanApproved(session: SessionState, input: { documentPath: string; title: string; }): void; declare function markSessionPlanCancelled(session: SessionState): void; declare function describeMissingPlanFields(fields: string[]): string; declare class PlanDocumentStore { private readonly workspaceRoot; private readonly options?; constructor(workspaceRoot: string, options?: { plansDir?: string | null; } | undefined); static forSession(session: SessionState): PlanDocumentStore; getPlansDir(): string; getLegacyPlansDir(): string; getPathForSession(sessionId: string): string; getLegacyPathForSession(sessionId: string): string; private readPlanFile; load(session: Pick): Promise; readMarkdown(session: Pick): Promise; private writeDocument; upsert(session: SessionState, patch: PlanDocumentPatch): Promise<{ document: PlanDocument; documentPath: string; }>; submit(session: SessionState, patch?: PlanDocumentPatch): Promise<{ document: PlanDocument; documentPath: string; validation: PlanValidationResult; }>; approve(session: SessionState): Promise<{ document: PlanDocument; documentPath: string; }>; revise(session: SessionState): Promise<{ document: PlanDocument; documentPath: string; }>; cancel(session: SessionState): Promise<{ document: PlanDocument | null; documentPath: string; }>; getApprovalPreview(session: SessionState): Promise; private ensureDraft; } type PersonaPromptInput = { soulProfile?: SoulProfile | null; }; declare function buildPersonaPrompt(input: PersonaPromptInput): string | null; /** * 把 `session.track` 压缩成一个紧凑的系统提示段,由 `buildSystemPromptSections` 每轮重建注入。 * * 关键点(pmm-038 §7.3): * - 本段从持久态 `session.track` 现取现拼,不进 transcript,因此 reactive compaction 摘不掉它 * —— 这是"超长任务有 target 约束"的落地件。 * - 保持短:target 全量(小)+ 仅未完成步骤;completed 折叠成计数,避免长任务里本段自身膨胀。 */ declare function buildTrackPrompt(session: SessionState): string | null; type PromptSectionOwner = "base" | "behavior" | "agent" | "persona" | "environment" | "context" | "attachment" | "room" | "dream"; type PromptSectionLifecycle = "static" | "session" | "turn" | "runtime"; interface PromptSectionMetadata { id: string; title: string; owner: PromptSectionOwner; lifecycle: PromptSectionLifecycle; priority: number; cacheable: boolean; sensitive: boolean; source: string; characters: number; estimatedTokens: number; hash: string; preview: string; content?: string; } interface PromptAttachmentExplain { id: string; title: string; lifecycle: PromptSectionLifecycle; source: string; includedInProviderPrompt: true; characters: number; estimatedTokens: number; hash: string; preview: string; content?: string; } interface PromptVisibleSystemEventExplain { id: string; timestamp: string; kind: string; source: "transcript.system_event"; includedInProviderPrompt: false; characters: number; estimatedTokens: number; hash: string; preview: string; content?: string; } interface PromptCacheExplain { sectionCacheImplemented: boolean; status: "disabled" | "hit" | "miss"; hit: boolean; missReason: string | null; cacheableSectionIds: string[]; volatileSectionIds: string[]; invalidationSignals: string[]; } interface PromptExplainReport { finalPrompt?: string; finalPromptHash: string; mode: BehaviorMode; provider: string; model: string; contextWindow?: number; contextWindowSource?: string; liteEffectiveTools: string[]; liteEffectiveSkills: string[]; runtimeAttachmentCount: number; relevantMemories: Array<{ id: string; title: string; type: string; scope: string; path: string; recall: string; reason: string; tags: string[]; }>; contextPackingDecisions: ContextPackingDecision[]; promptAttachments: PromptAttachmentExplain[]; visibleSystemEvents: PromptVisibleSystemEventExplain[]; cache: PromptCacheExplain; sections: PromptSectionMetadata[]; } type PromptExplainOptions = { includeContent?: boolean; previewChars?: number; }; declare function buildSystemPromptExplain(input: SystemPromptBuildInput, options?: PromptExplainOptions): PromptExplainReport; declare function buildDreamPrompt(session: SessionState): string; /** * Provider thinking dialects. * * `reasoning_effort` is NOT a universal OpenAI-compatible field. Sending it to a provider that * does not implement it is silently ignored — the request succeeds, thinking never turns on, and * nothing surfaces the mismatch. Each upstream gates thinking on its own parameter: * * - `reasoning-effort` OpenAI / OpenRouter: `reasoning_effort: "low"|"medium"|"high"`. * - `deepseek` DeepSeek: `reasoning_effort` **plus** a top-level * `thinking: { type: "enabled"|"disabled" }`. The effort alone is a no-op. * - `enable-thinking` DashScope / Qwen: boolean `enable_thinking`, with an optional * `thinking_budget` token cap. Rejects/ignores `reasoning_effort`. * - `anthropic` Anthropic-style: `thinking: { type: "enabled", budget_tokens: n }`. * - `none` Provider has no thinking switch; emit nothing. * * @since thinking-fix Replaces the previous assumption that every openai-compatible base URL * understands `reasoning_effort`. */ declare const THINKING_DIALECTS: readonly ["reasoning-effort", "deepseek", "enable-thinking", "anthropic", "none"]; declare function normalizeThinkingDialect(raw: unknown): ThinkingDialect | undefined; /** * Wire values a model's `reasoning_effort` accepts. These differ by model generation, and sending an * unsupported value is a hard 400 — so this is the single source of truth for both what we emit and * which UI levels we offer. * * `EffortVocabulary` is the *superset* we know how to emit; per-model vocabularies below pick from * it. Note `none` is a real disable switch on newer OpenAI models, which is what makes `off` * meaningful on the reasoning-effort dialect at all. */ type EffortValue = "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; /** The effort vocabulary assumed when nothing more specific is known. */ declare const LEGACY_EFFORT_VOCABULARY: readonly EffortValue[]; /** * Infer the dialect from a base URL / provider type when not explicitly configured. Host matching * only — model IDs are checked separately, since a gateway host can serve many model families. */ declare function inferThinkingDialect(input: { providerType?: string; baseURL?: string; model?: string; }): ThinkingDialect; /** * Map a UI level onto a wire effort value the model actually accepts. * * Without a vocabulary this falls back to the legacy low|medium|high enum, which is why callers * should pass one: on a gpt-5.6-class model, omitting it silently downgrades `max` to `high`. * Returns undefined when the level cannot be expressed at all (caller decides how to report that). */ declare function mapLevelToEffort(level: ThinkingLevel, vocabulary?: readonly EffortValue[]): EffortValue | undefined; /** Levels a reasoning-effort vocabulary can express exactly, with no degradation. */ declare function levelsForEffortVocabulary(vocabulary: readonly EffortValue[]): ThinkingLevel[]; /** * Inverse of `levelsForEffortVocabulary`: the wire values needed to serve a set of levels. * * Used when config declares `supportedThinkingLevels` explicitly — the declared levels become the * vocabulary, so an operator can enable a value the built-in table does not know about (a new model, * or a gateway that accepts more than we assume). * * `off` deliberately contributes nothing. Config normalization always prepends `off`, so inferring * `none` from it would emit `reasoning_effort: "none"` on models that reject it (o-series, gpt-5) — * a hard 400. Whether `none` is a real value is a property of the model, not of the config list. */ declare function effortVocabularyForLevels(levels: readonly ThinkingLevel[]): readonly EffortValue[]; declare function resolveThinkingBudgetTokens(input: { level: ThinkingLevel; maxBudgetTokens?: number | null; }): number | undefined; interface ThinkingRequestFields { reasoning_effort?: EffortValue; thinking?: { type: "enabled" | "disabled"; budget_tokens?: number; }; enable_thinking?: boolean; thinking_budget?: number; } /** * Build the request fields that actually toggle thinking for a dialect. * * Explicitly emits the *disable* form when level is `off` and the dialect can express it. A model * that thinks by default cannot be quieted by omitting a field, so "off" must say so on the wire. */ declare function buildThinkingRequestFields(input: { dialect: ThinkingDialect; level: ThinkingLevel; maxBudgetTokens?: number | null; /** Wire values this model accepts. Omitting it assumes the legacy low|medium|high enum. */ effortVocabulary?: readonly EffortValue[]; }): ThinkingRequestFields; /** Whether a dialect can carry a thinking signal at all — used to warn on unsupported requests. */ declare function dialectSupportsThinking(dialect: ThinkingDialect): boolean; type OpenAICompatibleProviderConfig = { apiKey: string; providerName?: string; baseURL?: string; headers?: Record; model: string; reasoningEnabled?: boolean; supportedThinkingLevels?: ThinkingLevel[]; supportsImages?: boolean; defaultThinkingLevel?: ThinkingLevel | null; defaultEffectiveThinkingLevel?: ThinkingLevel; thinkingMaxBudgetTokens?: number | null; /** Wire dialect used to toggle thinking. Inferred from baseURL/model when unset. */ thinkingDialect?: ThinkingDialect; /** Wire values this model's `reasoning_effort` accepts; undefined falls back to low|medium|high. */ effortVocabulary?: readonly EffortValue[]; dsmlToolCalls?: boolean; /** Total per-request timeout (ms) for the underlying OpenAI client. Default 600_000. */ requestTimeoutMs?: number; /** Max idle gap (ms) between stream chunks before failing the turn. Default 120_000. */ streamIdleTimeoutMs?: number; client?: Pick; }; declare function buildOpenAIChatMessages(input: ProviderTurnRequest): Promise; declare function createOpenAICompatibleProvider(config: OpenAICompatibleProviderConfig): ProviderAdapter; type AuthStoreLike = { getRequestAuth(): Promise<{ accessToken: string; accountId: string | null; }>; forceRefresh?(): Promise<{ accessToken: string; accountId: string | null; }>; }; type ResponsesClientLike = { create(body: Record, options?: { signal?: AbortSignal; headers?: Record; }): Promise>>; }; type CodexProviderConfig = { authStore: AuthStoreLike; providerName?: string; model: string; baseURL?: string; headers?: Record; reasoningEnabled?: boolean; supportedThinkingLevels?: ThinkingLevel[]; supportsImages?: boolean; defaultThinkingLevel?: ThinkingLevel | null; defaultEffectiveThinkingLevel?: ThinkingLevel; thinkingMaxBudgetTokens?: number | null; /** Wire values this model's reasoning effort accepts; undefined falls back to low|medium|high. */ effortVocabulary?: readonly EffortValue[]; /** Total per-request timeout (ms) for the underlying OpenAI client. Default 600_000. */ requestTimeoutMs?: number; /** Max idle gap (ms) between stream chunks before failing the turn. Default 120_000. */ streamIdleTimeoutMs?: number; responsesClient?: ResponsesClientLike; providerKind?: "codex" | "openai-responses"; }; declare function buildCodexInputItems(input: ProviderTurnRequest, replaySource?: Omit): Promise>>; declare function createCodexProvider(config: CodexProviderConfig): ProviderAdapter; type OpenAIResponsesProviderConfig = Omit & { apiKey: string; }; /** * OpenAI Responses adapter authenticated with a regular API key. * * The wire format is shared with the Codex provider, but authentication is * deliberately separate: Soul's gateway key must be sent as a normal Bearer * token and must never be interpreted as ChatGPT/Codex OAuth state. */ declare function createOpenAIResponsesProvider(config: OpenAIResponsesProviderConfig): ProviderAdapter; type CodexAuthStoreOptions = { authFile?: string; refreshSkewSeconds?: number; fetch?: typeof fetch; tokenEndpoint?: string; clientId?: string; now?: () => Date; }; type CodexAuthState = { authFile: string; authMode: string | null; accountId: string | null; hasRefreshToken: boolean; lastRefresh: string | null; accessTokenExpiresAt: string | null; }; type CodexRequestAuth = { accessToken: string; accountId: string | null; }; declare class CodexAuthStore { private readonly authFile; private readonly refreshSkewSeconds; private readonly fetchImpl; private readonly tokenEndpoint; private readonly clientId; private readonly now; private refreshInFlight; constructor(options?: CodexAuthStoreOptions); getAuthState(): Promise; getAccessToken(): Promise; getRequestAuth(): Promise; forceRefresh(): Promise; private load; private refresh; private performRefresh; } interface ProviderMessageCacheKey { sessionId: string; providerKind: string; providerName: string; model: string; supportsImages: boolean; reasoningReplay: boolean; } interface CacheEntry { key: ProviderMessageCacheKey; messages: T[]; processedMessageIds: string[]; compactUpdatedAt: string | null; summaryUpdatedAt: string | null; sessionMemoryUpdatedAt: string | null; } interface CacheLookupResult { hit: boolean; incrementalFrom: number; cachedMessages: T[]; cachedIds: string[]; } interface CacheMetrics { hits: number; misses: number; invalidations: number; evictions: number; totalLookups: number; hitRate: number; } declare function splitTransientProviderMessages(session: SessionState): { durable: SessionState; transient: TextTranscriptMessage[]; }; declare class ProviderMessageCache { private entries; private hitCount; private missCount; private invalidationCount; private evictionCount; private readonly maxEntries; constructor(options?: { maxEntries?: number; }); private static makeLookupKey; lookup(key: ProviderMessageCacheKey, session: SessionState): CacheLookupResult; store(key: ProviderMessageCacheKey, session: SessionState, messages: T[], processedMessageIds: string[]): void; invalidate(sessionId: string): void; clear(): void; get size(): number; getMetrics(): CacheMetrics; resetMetrics(): void; } declare function createProviderAdapter(config: AppConfig, providerName: string, modelId?: string, env?: Record, modelApiType?: ProviderModelConfig["apiType"]): ProviderAdapter; type ResolvedProviderAuth = { kind: "api-key"; apiKey: string; } | { kind: "codex"; authStore: CodexAuthStore; }; declare function resolveProviderAuth(provider: ProviderConfig, env?: Record): ResolvedProviderAuth; /** * Image support for a provider/model pair: explicit config first, then the model * family table, then the legacy provider-type heuristic for unknown families. */ declare function isProviderModelImageSupported(provider: Pick, model: ProviderModelConfig): boolean; declare function listProviders(config: AppConfig): ProviderConfig[]; declare function getProvider(config: AppConfig, name: string): ProviderConfig | undefined; declare function getDefaultProvider(config: AppConfig): ProviderConfig; declare function getCurrentProvider(config: AppConfig, session: Pick): ProviderConfig; declare function getProviderModel(provider: ProviderConfig, modelId: string): ProviderModelConfig | undefined; declare function resolveSessionModelApiType(config: AppConfig, session: Pick): SessionState["modelApiType"]; declare function resolveProviderApiKey(provider: Pick, env?: Record): string | undefined; declare function resolveCodexAuthFile(provider: Pick, env?: Record): string; declare function isProviderAuthConfigured(provider: Pick, env?: Record): boolean; declare function describeProviderAuth(provider: Pick, env?: Record): string; declare function assertProviderSelection(config: AppConfig, providerName: string, modelId?: string): { provider: ProviderConfig; model: ProviderModelConfig; }; declare function assertImageModelSelection(config: AppConfig, env?: Record): { provider: ProviderConfig; model: ProviderModelConfig; } | null; /** * Resolve the fallback chain for a session's current model. * * Builds: [primary] + [same model on sibling providers] + configured fallbacks. * Each fallback entry is { provider, model } — same shape as imageModel. * Invalid / disabled / duplicate entries are skipped. */ declare function resolveFallbackChain(config: AppConfig, primaryProvider: string, primaryModel: string, maxCandidates?: number, primaryApiType?: SessionState["modelApiType"]): FallbackCandidate[]; declare class FailoverError extends Error { readonly reason: FailoverReason; readonly provider?: string; readonly model?: string; readonly status?: number; readonly code?: string; readonly rawError?: string; constructor(message: string, params: { reason: FailoverReason; provider?: string; model?: string; status?: number; code?: string; rawError?: string; cause?: unknown; }); } declare class FallbackSummaryError extends Error { readonly attempts: FallbackAttempt[]; readonly candidates: FallbackCandidate[]; constructor(message: string, attempts: FallbackAttempt[], candidates: FallbackCandidate[], cause?: unknown); } /** * Thrown when the prompt still exceeds the model's context window after automatic * compaction has been applied (and cannot make further progress). This is a terminal, * user-facing condition — it is NOT a failover signal and must not trigger model fallback. */ declare class ContextWindowExceededError extends Error { constructor(message: string, cause?: unknown); } type UsageLimitErrorDetails = { code: "DAILY_COST_LIMIT_EXCEEDED" | "SHORT_WINDOW_COST_LIMIT_EXCEEDED"; message: string; resetAt?: string; retryAfterSeconds?: number; }; /** * A SoulStore user-level usage limit is shared by every model. It is terminal for * the current turn: model fallback cannot change the user's remaining allowance. */ declare class UsageLimitExceededError extends Error { readonly code: UsageLimitErrorDetails["code"]; readonly recoverable = true; readonly resetAt?: string; readonly retryAfterSeconds?: number; constructor(details: UsageLimitErrorDetails, cause?: unknown); } declare function isFailoverError(err: unknown): err is FailoverError; declare function isFallbackSummaryError(err: unknown): err is FallbackSummaryError; interface ClassifyResult { reason: FailoverReason; status?: number; code?: string; } /** * Extract the structured SoulStore user quota contract from SDK/nested errors. * Returns null for ordinary provider 429 errors so those may still use fallback. */ declare function extractUsageLimitError(error: unknown): UsageLimitErrorDetails | null; /** * Classify an error from provider API calls into a failover reason. * Returns null if the error is not classifiable as a failover signal * (e.g., user abort, context overflow, unknown format). */ declare function classifyProviderError(error: unknown, context?: { provider?: string; model?: string; }): ClassifyResult | null; /** * Wrap a raw error into a FailoverError if it can be classified. * Returns null if the error is not a recognized failover signal. */ declare function toFailoverError(error: unknown, context?: { provider?: string; model?: string; }): FailoverError | null; /** * Check if an error is a context-overflow that should trigger * compaction rather than model fallback. */ declare function isContextOverflowError(error: unknown): boolean; /** * Check if the error is a user abort (AbortError) that is NOT a timeout. * Timeout-flavored aborts should still trigger fallback. */ declare function isAbortErrorExceptTimeout(error: unknown): boolean; declare const RUNTIME_NARRATION_CHECKPOINT_TOOLS = 6; type FallbackAdapterSelection = { adapter: ProviderAdapter; provider: string; model: string; }; declare function createAgentRuntime(input: { session: SessionState; tools: ToolDefinition[]; provider: ProviderAdapter; permissionManager: PermissionManager; systemPrompt?: string; buildSystemPrompt?(input: { session: SessionState; runtimeSystemHints: string[]; }): string; gatewayAttribution?: GatewayAttributionContext; compactSession?(session: SessionState, reason?: unknown): Promise | SessionState; consumeSteeringMessages?(): string[]; imageSummaryFallback?(input: { session: SessionState; userText: string; attachments: TurnAttachment[]; signal?: AbortSignal; }): Promise<{ provider: string; model: string; summary: string; usage?: Partial; } | null>; /** Model-driven image understanding used by the built-in ReadImage tool. */ understandImages?(input: { session: SessionState; paths: string[]; prompt?: string; signal?: AbortSignal; }): Promise; runtimeTag?: "default" | "dream"; maxTurns?: number | null; /** When provided, resolves config.json model-level pricing for a given model id. * Returning null/undefined falls back to the built-in pricing table (agent-055). */ resolveModelPricing?(model: string): ModelPricingConfig | null | undefined; /** When provided, enables model fallback on provider failures. * Called with (currentProvider, currentModel) and returns the next * adapter plus its provider/model identity, or null when exhausted. */ getFallbackAdapter?(currentProvider: string, currentModel: string): FallbackAdapterSelection | ProviderAdapter | null; }): { run: (userText: string, options?: { signal?: AbortSignal; attachments?: TurnAttachment[]; fastgptKnowledgeScope?: FastGptKnowledgeScope | null; }) => AsyncGenerator; getSession(): SessionState; getStats(): { turnsUsed: number; maxTurnsReached: boolean; }; }; declare function getHostTimezone(): string; declare function createRuntimeClockSnapshot(now?: Date): RuntimeClockSnapshot; declare function createSessionTaskSummarySnapshot(session: SessionState): SessionTaskSummarySnapshot; declare function createSessionStateSnapshot(session: SessionState): SessionStateSnapshot; declare function createMcpSummary(statuses: McpServerStatus[]): { total: number; connected: number; pending: number; failed: number; disconnected: number; servers: { name: string; status: McpServerConnectionState; connected: boolean; toolCount: number; promptCount: number; resourceCount: number; error: string | undefined; }[]; }; declare function createFastGptKnowledgeSummary(input?: { scope?: FastGptKnowledgeScope | null; appAskEnabled?: boolean; }): RuntimeFastGptKnowledgeSummary; declare function createRuntimeStatusSnapshot(input: { session: SessionState; mcpStatuses?: McpServerStatus[]; fastgptKnowledgeScope?: FastGptKnowledgeScope | null; fastgptAppAskEnabled?: boolean; now?: Date; shell?: string; platform?: NodeJS.Platform; }): RuntimeStatusSnapshot; declare function buildToolActiveForm(toolName: string, input: unknown): string; interface ToolInputIssue { path: Array; code?: string; message: string; expected?: unknown; received?: unknown; } declare function parseToolInputIssues(value: unknown): ToolInputIssue[] | null; declare function summarizeToolInputIssue(issue: ToolInputIssue): string; declare function buildToolInputRepairHint(toolName: string, issues: ToolInputIssue[]): string; declare function buildToolInputErrorMessage(toolName: string, issues: ToolInputIssue[]): string; declare function formatToolInputErrorForDisplay(toolName: string, error: unknown): string; type ModelPricing = ModelPricingConfig; /** * 在内置定价表中查找模型定价:先精确匹配,再前缀匹配,最后返回 null。 * 前缀匹配仅用于内置表,不适用于 config.json 的精确绑定定价。 */ declare function findBuiltinModelPricing(model: string): ModelPricing | null; /** * 从 config.json 解析模型级自定义定价(精确匹配模型 ID)。 * 跨 provider 搜索:优先返回首个携带 pricing 的匹配模型配置。 */ declare function resolveModelPricingFromConfig(config: AppConfig, model: string): ModelPricingConfig | null; /** * 估算单次调用成本。定价回退链: * 显式 pricingOverride(来自 config.json) → 内置表(精确/前缀) → null。 * 不做中间四舍五入,纯浮点返回,由显示层格式化(agent-055 §6.5)。 */ declare function estimateUsageCostUsd(model: string, usage: Pick, pricingOverride?: ModelPricingConfig | null): number | null; declare function formatRoomStatus(snapshot: RoomStatusSnapshot): string; declare function formatRoomMembers(members: RoomMember[], runtimeStatuses?: Record): string; type RoomBudgetDecision = { allowed: true; room: RoomState; } | { allowed: false; room: RoomState; reason: string; }; declare function canStartRoomTurn(room: RoomState): RoomBudgetDecision; declare function recordRoomTurnStarted(room: RoomState): RoomState; declare function recordRoomTurnUsage(room: RoomState, input: { promptTokens?: number | null; completionTokens?: number | null; totalTokens?: number | null; estimatedCostUsd?: number | null; cachedInputTokens?: number | null; cacheMissInputTokens?: number | null; cacheWriteInputTokens?: number | null; cacheReadInputTokens?: number | null; }): RoomState; declare function recordRoomUsageDelta(room: RoomState, input: { memberId?: string | null; phase: RoomTurnPhase | "discarded"; usage: { promptTokens?: number | null; completionTokens?: number | null; totalTokens?: number | null; estimatedCostUsd?: number | null; cachedInputTokens?: number | null; cacheMissInputTokens?: number | null; cacheWriteInputTokens?: number | null; cacheReadInputTokens?: number | null; }; }): RoomState; declare function applyBudgetExhaustedAction(room: RoomState, reason: string): RoomState; type RoomAdminGovernanceEvaluation = { adminMessageCount: number; invitesMembers: boolean; summarizes: boolean; redirectsOrDeduplicates: boolean; proposesNextSteps: boolean; coordinatesWithOtherAdmins: boolean; evidence: { invitesMembers: string[]; summarizes: string[]; redirectsOrDeduplicates: string[]; proposesNextSteps: string[]; coordinatesWithOtherAdmins: string[]; }; }; type EvaluationInput = { transcript: RoomEventEnvelope[]; members: RoomMember[]; adminMemberIds?: string[]; }; declare function evaluateRoomAdminGovernance(input: EvaluationInput): RoomAdminGovernanceEvaluation; type RoomAutonomousLoopDeps = { roomStore: RoomStore; scheduler: Pick; intervalMs?: number; now?: () => string; }; declare class RoomAutonomousLoop { private readonly deps; private timer; private running; constructor(deps: RoomAutonomousLoopDeps); start(): void; stop(): void; tick(): Promise; } type RoomCapability = "room.status.read" | "room.message.read" | "room.message.write" | "room.members.manage" | "room.policy.update" | "room.control.stop" | "room.control.steer" | "room.control.clear" | "room.control.compact" | "room.control.budget" | "room.lifecycle.manage"; declare function findRoomActorMember(members: RoomMember[], actor: RoomActorRef): RoomMember | null; declare function roomMemberHasCapability(member: RoomMember, capability: RoomCapability): boolean; declare function assertRoomActorCan(input: { members: RoomMember[]; actor: RoomActorRef; capability: RoomCapability; }): RoomMember; type BuildRoomRootParticipationLedgerInput = { rootEvent: RoomEventEnvelope | null; rootEventId: string; members: RoomMember[]; transcript: RoomEventEnvelope[]; activeSlots: RoomDraftingSlot[]; longRunningTurns?: RoomLongRunningTurn[]; controlEvents?: RoomEventEnvelope[]; now: string; }; declare function deriveRoomRootParticipationContext(input: { rootEvent: RoomEventEnvelope | null; rootEventId: string; members: RoomMember[]; now: string; }): RoomRootParticipationContext; declare function buildRoomRootParticipationLedger(input: BuildRoomRootParticipationLedgerInput): RoomRootParticipationLedger; declare function getRootParticipationTerminalMemberIds(ledger: RoomRootParticipationLedger): Set; declare function getMentionedMemberIds(text: string, members: RoomMember[]): string[]; declare function getRootParticipationYourStatus(ledger: RoomRootParticipationLedger, memberId: string): string; declare function getRootParticipationFirstContributionStatus(ledger: RoomRootParticipationLedger, memberId: string): string; declare function getRootParticipationSupplementCount(ledger: RoomRootParticipationLedger, memberId: string): number; declare function formatRoomRootParticipationForPrompt(input: { ledger?: RoomRootParticipationLedger | null; selfMemberId?: string | null; }): string; declare function syncRoomEventsToSession(input: { session: SessionState; room: RoomState; member: RoomMember; events: RoomEventEnvelope[]; now: string; }): { session: SessionState; syncedEventIds: string[]; }; declare function isSyncableRoomTranscriptEvent(event: RoomEventEnvelope): boolean; type SpeakerPolicyCandidate = { member: RoomMember; batch: RoomObservationBatch; }; type SpeakerPolicyDecision = { traceId: string; policyPreset: RoomSpeakerPreset; policyStatus: RoomSpeakerPolicyStatus; candidateMemberIds: string[]; orderedMemberIds: string[]; selectedCandidateMemberIds: string[]; skipped: RoomPolicyDecisionSkip[]; maxSelectedSpeakers: number | null; allowMultipleSpeakers: boolean; decisionReason: string; nextPolicyState: RoomSchedulerPolicyState; }; declare function getRoomSpeakerPolicyStatus(preset: RoomSpeakerPreset): RoomSpeakerPolicyStatus; declare function createInitialRoomPolicyState(preset: RoomSpeakerPreset, updatedAt: string | null): RoomSchedulerPolicyState; declare function decideSpeakerPolicy(input: { room: RoomState; members: RoomMember[]; rootEvent: RoomEventEnvelope | null; sourceEvent: RoomEventEnvelope | null; rootParticipationLedger: RoomRootParticipationLedger; candidates: SpeakerPolicyCandidate[]; directMentionedMemberIds: string[]; timestamp: string; }): SpeakerPolicyDecision; declare function extractRootHandoffPlan(input: { rootEvent: RoomEventEnvelope; members: RoomMember[]; }): RoomHandoffPlan | null; declare function resolveNextPlannedSpeaker(input: { rootEvent: RoomEventEnvelope | null; sourceEvent: RoomEventEnvelope | null; transcript: RoomEventEnvelope[]; members: RoomMember[]; }): string | null; declare function updateRoomDigest(member: RoomMember, batch: RoomObservationBatch, timestamp: string, ownPublishedEvent?: RoomEventEnvelope | null): RoomAgentContextDigest; declare function createEmptyRoomTopicState(): RoomTopicState; declare function normalizeRoomTopicState(input: Partial | null | undefined): RoomTopicState; declare function applyHumanRootTopicUpdate(input: { room: RoomState; event: RoomEventEnvelope; transcript: RoomEventEnvelope[]; now: string; }): { room: RoomState; previousActiveRootEventId: string | null; preemptedCoalescingRootEventId: string | null; }; declare function refreshTopicActivity(input: { topicState: RoomTopicState | null | undefined; transcript: RoomEventEnvelope[]; rootEventId: string; now: string; }): RoomTopicState; declare function isBackgroundTopicSource(room: RoomState, sourceEvent: RoomEventEnvelope | null): boolean; declare function formatRoomTopicStateForPrompt(room: RoomState): string; declare const roomBenchmarkRuntimeModeSchema: z.ZodEnum<["mock", "live"]>; type RoomBenchmarkRuntimeMode = z.infer; declare const roomBenchmarkAgentMemberSchema: z.ZodObject<{ memberId: z.ZodString; sessionId: z.ZodOptional; displayName: z.ZodOptional; roles: z.ZodDefault>; capabilities: z.ZodDefault>; responsibility: z.ZodOptional>; state: z.ZodDefault>; }, "strip", z.ZodTypeAny, { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; capabilities: string[]; displayName?: string | undefined; sessionId?: string | undefined; responsibility?: string | null | undefined; }, { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; sessionId?: string | undefined; roles?: string[] | undefined; capabilities?: string[] | undefined; responsibility?: string | null | undefined; }>; type RoomBenchmarkAgentMember = z.infer; declare const roomBenchmarkHumanMemberSchema: z.ZodObject<{ memberId: z.ZodString; displayName: z.ZodOptional; roles: z.ZodDefault>; state: z.ZodDefault>; }, "strip", z.ZodTypeAny, { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; displayName?: string | undefined; }, { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; roles?: string[] | undefined; }>; type RoomBenchmarkHumanMember = z.infer; declare const roomBenchmarkMembersSchema: z.ZodObject<{ humans: z.ZodDefault; roles: z.ZodDefault>; state: z.ZodDefault>; }, "strip", z.ZodTypeAny, { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; displayName?: string | undefined; }, { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; roles?: string[] | undefined; }>, "many">>; agents: z.ZodArray; displayName: z.ZodOptional; roles: z.ZodDefault>; capabilities: z.ZodDefault>; responsibility: z.ZodOptional>; state: z.ZodDefault>; }, "strip", z.ZodTypeAny, { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; capabilities: string[]; displayName?: string | undefined; sessionId?: string | undefined; responsibility?: string | null | undefined; }, { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; sessionId?: string | undefined; roles?: string[] | undefined; capabilities?: string[] | undefined; responsibility?: string | null | undefined; }>, "many">; }, "strip", z.ZodTypeAny, { agents: { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; capabilities: string[]; displayName?: string | undefined; sessionId?: string | undefined; responsibility?: string | null | undefined; }[]; humans: { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; displayName?: string | undefined; }[]; }, { agents: { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; sessionId?: string | undefined; roles?: string[] | undefined; capabilities?: string[] | undefined; responsibility?: string | null | undefined; }[]; humans?: { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; roles?: string[] | undefined; }[] | undefined; }>; type RoomBenchmarkMembers = z.infer; declare const roomBenchmarkSpeakerPolicySettingsSchema: z.ZodObject<{ maxConcurrentDrafts: z.ZodOptional; maxConcurrentSpeakers: z.ZodOptional; maxAgentRepliesPerRootEvent: z.ZodOptional; maxChainDepth: z.ZodOptional; intentCollectionTimeoutMs: z.ZodOptional; intentDecisionConcurrency: z.ZodOptional; intentEarlySelect: z.ZodOptional; intentMentionTimeoutFallback: z.ZodOptional; allowSelfInitiatedTopics: z.ZodOptional; allowAgentToAgentTrigger: z.ZodOptional; prePublishSelfCheck: z.ZodOptional; }, "strict", z.ZodTypeAny, { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }, { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }>; type RoomBenchmarkSpeakerPolicySettings = z.infer; declare const roomBenchmarkSpeakerPolicySchema: z.ZodObject<{ preset: z.ZodEnum<["autonomous", "mentionOnly", "roundRobin", "roundTable", "intentRoute", "moderated", "custom"]>; settings: z.ZodDefault; maxConcurrentSpeakers: z.ZodOptional; maxAgentRepliesPerRootEvent: z.ZodOptional; maxChainDepth: z.ZodOptional; intentCollectionTimeoutMs: z.ZodOptional; intentDecisionConcurrency: z.ZodOptional; intentEarlySelect: z.ZodOptional; intentMentionTimeoutFallback: z.ZodOptional; allowSelfInitiatedTopics: z.ZodOptional; allowAgentToAgentTrigger: z.ZodOptional; prePublishSelfCheck: z.ZodOptional; }, "strict", z.ZodTypeAny, { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }, { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }>>; }, "strip", z.ZodTypeAny, { preset: "autonomous" | "mentionOnly" | "roundRobin" | "roundTable" | "intentRoute" | "moderated" | "custom"; settings: { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }; }, { preset: "autonomous" | "mentionOnly" | "roundRobin" | "roundTable" | "intentRoute" | "moderated" | "custom"; settings?: { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; } | undefined; }>; type RoomBenchmarkSpeakerPolicy = z.infer; declare const roomBenchmarkExpectationSchema: z.ZodObject<{ expectedSpeakers: z.ZodDefault>; forbiddenSpeakers: z.ZodDefault>; expectedOrder: z.ZodOptional>; expectedCompletionStatus: z.ZodOptional>; allowUnexpectedSpeakers: z.ZodDefault; traceReason: z.ZodOptional; maxVisibleNoopMatches: z.ZodOptional; maxLatencyMs: z.ZodOptional; }, "strip", z.ZodTypeAny, { expectedSpeakers: string[]; forbiddenSpeakers: string[]; allowUnexpectedSpeakers: boolean; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }, { expectedSpeakers?: string[] | undefined; forbiddenSpeakers?: string[] | undefined; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; allowUnexpectedSpeakers?: boolean | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }>; type RoomBenchmarkExpectation = z.infer; declare const roomBenchmarkMessageSchema: z.ZodObject<{ id: z.ZodOptional; text: z.ZodString; expectations: z.ZodDefault>; forbiddenSpeakers: z.ZodDefault>; expectedOrder: z.ZodOptional>; expectedCompletionStatus: z.ZodOptional>; allowUnexpectedSpeakers: z.ZodDefault; traceReason: z.ZodOptional; maxVisibleNoopMatches: z.ZodOptional; maxLatencyMs: z.ZodOptional; }, "strip", z.ZodTypeAny, { expectedSpeakers: string[]; forbiddenSpeakers: string[]; allowUnexpectedSpeakers: boolean; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }, { expectedSpeakers?: string[] | undefined; forbiddenSpeakers?: string[] | undefined; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; allowUnexpectedSpeakers?: boolean | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }>>; }, "strip", z.ZodTypeAny, { text: string; expectations: { expectedSpeakers: string[]; forbiddenSpeakers: string[]; allowUnexpectedSpeakers: boolean; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }; id?: string | undefined; }, { text: string; id?: string | undefined; expectations?: { expectedSpeakers?: string[] | undefined; forbiddenSpeakers?: string[] | undefined; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; allowUnexpectedSpeakers?: boolean | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; } | undefined; }>; type RoomBenchmarkMessage = z.infer; declare const roomBenchmarkMockFailureSchema: z.ZodObject<{ code: z.ZodDefault; message: z.ZodDefault; }, "strip", z.ZodTypeAny, { message: string; code: string; }, { message?: string | undefined; code?: string | undefined; }>; type RoomBenchmarkMockFailure = z.infer; declare const roomBenchmarkMockMemberSchema: z.ZodObject<{ replyTemplate: z.ZodOptional; speechDecision: z.ZodDefault>; speechReason: z.ZodOptional; latencyMs: z.ZodDefault; status: z.ZodDefault>; failure: z.ZodOptional; message: z.ZodDefault; }, "strip", z.ZodTypeAny, { message: string; code: string; }, { message?: string | undefined; code?: string | undefined; }>>; handoffTargetMemberId: z.ZodOptional; }, "strip", z.ZodTypeAny, { status: "missing" | "queued" | "running" | "idle" | "collecting" | "busy" | "paused" | "aborting"; speechDecision: "speak" | "silent" | "defer" | "decline"; latencyMs: number; replyTemplate?: string | undefined; speechReason?: string | undefined; failure?: { message: string; code: string; } | undefined; handoffTargetMemberId?: string | undefined; }, { status?: "missing" | "queued" | "running" | "idle" | "collecting" | "busy" | "paused" | "aborting" | undefined; replyTemplate?: string | undefined; speechDecision?: "speak" | "silent" | "defer" | "decline" | undefined; speechReason?: string | undefined; latencyMs?: number | undefined; failure?: { message?: string | undefined; code?: string | undefined; } | undefined; handoffTargetMemberId?: string | undefined; }>; type RoomBenchmarkMockMember = z.infer; declare const roomBenchmarkMockRuntimeSchema: z.ZodDefault; speechDecision: z.ZodDefault>; speechReason: z.ZodOptional; latencyMs: z.ZodDefault; status: z.ZodDefault>; failure: z.ZodOptional; message: z.ZodDefault; }, "strip", z.ZodTypeAny, { message: string; code: string; }, { message?: string | undefined; code?: string | undefined; }>>; handoffTargetMemberId: z.ZodOptional; }, "strip", z.ZodTypeAny, { status: "missing" | "queued" | "running" | "idle" | "collecting" | "busy" | "paused" | "aborting"; speechDecision: "speak" | "silent" | "defer" | "decline"; latencyMs: number; replyTemplate?: string | undefined; speechReason?: string | undefined; failure?: { message: string; code: string; } | undefined; handoffTargetMemberId?: string | undefined; }, { status?: "missing" | "queued" | "running" | "idle" | "collecting" | "busy" | "paused" | "aborting" | undefined; replyTemplate?: string | undefined; speechDecision?: "speak" | "silent" | "defer" | "decline" | undefined; speechReason?: string | undefined; latencyMs?: number | undefined; failure?: { message?: string | undefined; code?: string | undefined; } | undefined; handoffTargetMemberId?: string | undefined; }>>>; }, "strip", z.ZodTypeAny, { members: Record; }, { members?: Record | undefined; }>>; type RoomBenchmarkMockRuntime = z.infer; declare const roomBenchmarkMetricsThresholdsSchema: z.ZodObject<{ maxLatencyMs: z.ZodOptional; maxVisibleNoopMatches: z.ZodOptional; minExpectedSpeakerRecall: z.ZodOptional; maxForbiddenSpeakerCount: z.ZodOptional; maxUnexpectedSpeakerCount: z.ZodOptional; }, "strict", z.ZodTypeAny, { maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; minExpectedSpeakerRecall?: number | undefined; maxForbiddenSpeakerCount?: number | undefined; maxUnexpectedSpeakerCount?: number | undefined; }, { maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; minExpectedSpeakerRecall?: number | undefined; maxForbiddenSpeakerCount?: number | undefined; maxUnexpectedSpeakerCount?: number | undefined; }>; type RoomBenchmarkMetricsThresholds = z.infer; declare const roomBenchmarkCaseSchema: z.ZodObject<{ id: z.ZodString; title: z.ZodString; description: z.ZodOptional; suiteTags: z.ZodDefault>; runtimeMode: z.ZodDefault>; timeoutMs: z.ZodDefault; room: z.ZodDefault; objective: z.ZodOptional; announcement: z.ZodOptional; }, "strip", z.ZodTypeAny, { title?: string | undefined; objective?: string | undefined; announcement?: string | undefined; }, { title?: string | undefined; objective?: string | undefined; announcement?: string | undefined; }>>; members: z.ZodObject<{ humans: z.ZodDefault; roles: z.ZodDefault>; state: z.ZodDefault>; }, "strip", z.ZodTypeAny, { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; displayName?: string | undefined; }, { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; roles?: string[] | undefined; }>, "many">>; agents: z.ZodArray; displayName: z.ZodOptional; roles: z.ZodDefault>; capabilities: z.ZodDefault>; responsibility: z.ZodOptional>; state: z.ZodDefault>; }, "strip", z.ZodTypeAny, { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; capabilities: string[]; displayName?: string | undefined; sessionId?: string | undefined; responsibility?: string | null | undefined; }, { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; sessionId?: string | undefined; roles?: string[] | undefined; capabilities?: string[] | undefined; responsibility?: string | null | undefined; }>, "many">; }, "strip", z.ZodTypeAny, { agents: { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; capabilities: string[]; displayName?: string | undefined; sessionId?: string | undefined; responsibility?: string | null | undefined; }[]; humans: { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; displayName?: string | undefined; }[]; }, { agents: { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; sessionId?: string | undefined; roles?: string[] | undefined; capabilities?: string[] | undefined; responsibility?: string | null | undefined; }[]; humans?: { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; roles?: string[] | undefined; }[] | undefined; }>; speakerPolicy: z.ZodObject<{ preset: z.ZodEnum<["autonomous", "mentionOnly", "roundRobin", "roundTable", "intentRoute", "moderated", "custom"]>; settings: z.ZodDefault; maxConcurrentSpeakers: z.ZodOptional; maxAgentRepliesPerRootEvent: z.ZodOptional; maxChainDepth: z.ZodOptional; intentCollectionTimeoutMs: z.ZodOptional; intentDecisionConcurrency: z.ZodOptional; intentEarlySelect: z.ZodOptional; intentMentionTimeoutFallback: z.ZodOptional; allowSelfInitiatedTopics: z.ZodOptional; allowAgentToAgentTrigger: z.ZodOptional; prePublishSelfCheck: z.ZodOptional; }, "strict", z.ZodTypeAny, { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }, { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }>>; }, "strip", z.ZodTypeAny, { preset: "autonomous" | "mentionOnly" | "roundRobin" | "roundTable" | "intentRoute" | "moderated" | "custom"; settings: { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }; }, { preset: "autonomous" | "mentionOnly" | "roundRobin" | "roundTable" | "intentRoute" | "moderated" | "custom"; settings?: { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; } | undefined; }>; mockRuntime: z.ZodDefault; speechDecision: z.ZodDefault>; speechReason: z.ZodOptional; latencyMs: z.ZodDefault; status: z.ZodDefault>; failure: z.ZodOptional; message: z.ZodDefault; }, "strip", z.ZodTypeAny, { message: string; code: string; }, { message?: string | undefined; code?: string | undefined; }>>; handoffTargetMemberId: z.ZodOptional; }, "strip", z.ZodTypeAny, { status: "missing" | "queued" | "running" | "idle" | "collecting" | "busy" | "paused" | "aborting"; speechDecision: "speak" | "silent" | "defer" | "decline"; latencyMs: number; replyTemplate?: string | undefined; speechReason?: string | undefined; failure?: { message: string; code: string; } | undefined; handoffTargetMemberId?: string | undefined; }, { status?: "missing" | "queued" | "running" | "idle" | "collecting" | "busy" | "paused" | "aborting" | undefined; replyTemplate?: string | undefined; speechDecision?: "speak" | "silent" | "defer" | "decline" | undefined; speechReason?: string | undefined; latencyMs?: number | undefined; failure?: { message?: string | undefined; code?: string | undefined; } | undefined; handoffTargetMemberId?: string | undefined; }>>>; }, "strip", z.ZodTypeAny, { members: Record; }, { members?: Record | undefined; }>>; messages: z.ZodArray; text: z.ZodString; expectations: z.ZodDefault>; forbiddenSpeakers: z.ZodDefault>; expectedOrder: z.ZodOptional>; expectedCompletionStatus: z.ZodOptional>; allowUnexpectedSpeakers: z.ZodDefault; traceReason: z.ZodOptional; maxVisibleNoopMatches: z.ZodOptional; maxLatencyMs: z.ZodOptional; }, "strip", z.ZodTypeAny, { expectedSpeakers: string[]; forbiddenSpeakers: string[]; allowUnexpectedSpeakers: boolean; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }, { expectedSpeakers?: string[] | undefined; forbiddenSpeakers?: string[] | undefined; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; allowUnexpectedSpeakers?: boolean | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }>>; }, "strip", z.ZodTypeAny, { text: string; expectations: { expectedSpeakers: string[]; forbiddenSpeakers: string[]; allowUnexpectedSpeakers: boolean; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }; id?: string | undefined; }, { text: string; id?: string | undefined; expectations?: { expectedSpeakers?: string[] | undefined; forbiddenSpeakers?: string[] | undefined; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; allowUnexpectedSpeakers?: boolean | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; } | undefined; }>, "many">; metricsThresholds: z.ZodDefault; maxVisibleNoopMatches: z.ZodOptional; minExpectedSpeakerRecall: z.ZodOptional; maxForbiddenSpeakerCount: z.ZodOptional; maxUnexpectedSpeakerCount: z.ZodOptional; }, "strict", z.ZodTypeAny, { maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; minExpectedSpeakerRecall?: number | undefined; maxForbiddenSpeakerCount?: number | undefined; maxUnexpectedSpeakerCount?: number | undefined; }, { maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; minExpectedSpeakerRecall?: number | undefined; maxForbiddenSpeakerCount?: number | undefined; maxUnexpectedSpeakerCount?: number | undefined; }>>; artifacts: z.ZodDefault>; }, "strip", z.ZodTypeAny, { id: string; title: string; room: { title?: string | undefined; objective?: string | undefined; announcement?: string | undefined; }; timeoutMs: number; messages: { text: string; expectations: { expectedSpeakers: string[]; forbiddenSpeakers: string[]; allowUnexpectedSpeakers: boolean; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; }; id?: string | undefined; }[]; speakerPolicy: { preset: "autonomous" | "mentionOnly" | "roundRobin" | "roundTable" | "intentRoute" | "moderated" | "custom"; settings: { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; }; }; artifacts: string[]; members: { agents: { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; capabilities: string[]; displayName?: string | undefined; sessionId?: string | undefined; responsibility?: string | null | undefined; }[]; humans: { state: "removed" | "paused" | "active" | "muted"; memberId: string; roles: string[]; displayName?: string | undefined; }[]; }; suiteTags: string[]; runtimeMode: "mock" | "live"; mockRuntime: { members: Record; }; metricsThresholds: { maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; minExpectedSpeakerRecall?: number | undefined; maxForbiddenSpeakerCount?: number | undefined; maxUnexpectedSpeakerCount?: number | undefined; }; description?: string | undefined; }, { id: string; title: string; messages: { text: string; id?: string | undefined; expectations?: { expectedSpeakers?: string[] | undefined; forbiddenSpeakers?: string[] | undefined; expectedOrder?: string[] | undefined; expectedCompletionStatus?: "open" | "complete" | "partial" | "abandoned" | "sufficient" | undefined; allowUnexpectedSpeakers?: boolean | undefined; traceReason?: string | undefined; maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; } | undefined; }[]; speakerPolicy: { preset: "autonomous" | "mentionOnly" | "roundRobin" | "roundTable" | "intentRoute" | "moderated" | "custom"; settings?: { prePublishSelfCheck?: boolean | undefined; maxConcurrentSpeakers?: number | undefined; allowSelfInitiatedTopics?: boolean | undefined; allowAgentToAgentTrigger?: boolean | undefined; intentCollectionTimeoutMs?: number | undefined; intentDecisionConcurrency?: number | undefined; intentEarlySelect?: boolean | undefined; intentMentionTimeoutFallback?: boolean | undefined; maxChainDepth?: number | undefined; maxAgentRepliesPerRootEvent?: number | undefined; maxConcurrentDrafts?: number | undefined; } | undefined; }; members: { agents: { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; sessionId?: string | undefined; roles?: string[] | undefined; capabilities?: string[] | undefined; responsibility?: string | null | undefined; }[]; humans?: { memberId: string; state?: "removed" | "paused" | "active" | "muted" | undefined; displayName?: string | undefined; roles?: string[] | undefined; }[] | undefined; }; description?: string | undefined; room?: { title?: string | undefined; objective?: string | undefined; announcement?: string | undefined; } | undefined; timeoutMs?: number | undefined; artifacts?: string[] | undefined; suiteTags?: string[] | undefined; runtimeMode?: "mock" | "live" | undefined; mockRuntime?: { members?: Record | undefined; } | undefined; metricsThresholds?: { maxVisibleNoopMatches?: number | undefined; maxLatencyMs?: number | undefined; minExpectedSpeakerRecall?: number | undefined; maxForbiddenSpeakerCount?: number | undefined; maxUnexpectedSpeakerCount?: number | undefined; } | undefined; }>; type RoomBenchmarkCase = z.infer; declare function parseRoomBenchmarkCase(input: unknown): RoomBenchmarkCase; declare function loadRoomBenchmarkCase(filePath: string): Promise; declare function loadRoomBenchmarkCases(filePaths: string[]): Promise; declare function discoverRoomBenchmarkCaseFiles(input: { rootDir: string; suiteTag?: string; }): Promise; type RoomBenchmarkMockRuntimeOptions = { rootDir?: string; now?: () => string; }; declare function createRoomBenchmarkMockRuntime(benchmarkCase: RoomBenchmarkCase, options?: RoomBenchmarkMockRuntimeOptions): RoomSchedulerSessionControl; type RoomBenchmarkStatus = "passed" | "failed" | "warning"; type RoomBenchmarkFailureType = "capability_gap" | "scheduler_regression" | "prompt_regression" | "tool_or_permission_issue" | "environment_issue" | "benchmark_case_issue" | "performance_regression" | "unclassified"; type RoomBenchmarkGitMetadata = { branch: string | null; commit: string | null; dirty: boolean; changedFiles: string[]; }; type RoomBenchmarkPolicyTrace = { traceId: string | null; policyPreset: string | null; policyStatus: string | null; decisionKind: string | null; decisionReason: string | null; candidateMemberIds: string[]; orderedMemberIds: string[]; selectedMemberIds: string[]; skipped: Array<{ memberId: string; reason: string; policyReason: string; retryable?: boolean; }>; }; type RoomBenchmarkControlEventSummary = { total: number; byType: Record; policyTraces: RoomBenchmarkPolicyTrace[]; skippedReasonDistribution: Record; }; type RoomBenchmarkTurnEvidence = { expectedSpeakers: string[]; actualSpeakers: string[]; matchedExpectedSpeakers: string[]; missingExpectedSpeakers: string[]; forbiddenSpeakers: string[]; forbiddenActualSpeakers: string[]; unexpectedSpeakers: string[]; expectedCompletionStatus: RoomRootParticipationCompletionStatus | null; actualCompletionStatus: RoomRootParticipationCompletionStatus | null; policyTraceIds: string[]; decisionReasons: string[]; }; type RoomBenchmarkTurnResult = { messageId: string; inputText: string; rootEventId: string; schedulerResult: RoomSchedulerResult; latencyMs: number; publishedSpeakers: string[]; publishedEventIds: string[]; publishedTexts: string[]; visibleNoopMatches: number; completionStatus: RoomRootParticipationCompletionStatus | null; expectations: RoomBenchmarkExpectation; evidence: RoomBenchmarkTurnEvidence; failures: string[]; warnings: string[]; failureTypes: RoomBenchmarkFailureType[]; }; type RoomBenchmarkMetrics = { messageCount: number; publishedMessageCount: number; expectedSpeakerCount: number; matchedExpectedSpeakerCount: number; expectedSpeakerRecall: number; forbiddenSpeakerCount: number; unexpectedSpeakerCount: number; visibleNoopMatches: number; maxTurnLatencyMs: number; totalLatencyMs: number; }; type RoomBenchmarkCaseResult = { caseId: string; title: string; suiteTags: string[]; runtimeMode: RoomBenchmarkCase["runtimeMode"]; speakerPolicyPreset: RoomBenchmarkCase["speakerPolicy"]["preset"]; status: RoomBenchmarkStatus; startedAt: string; completedAt: string; durationMs: number; roomId: string; turns: RoomBenchmarkTurnResult[]; metrics: RoomBenchmarkMetrics; controlEventSummary: RoomBenchmarkControlEventSummary; score: number; failureTypes: RoomBenchmarkFailureType[]; failures: string[]; warnings: string[]; error?: string; artifactDir?: string; }; type RoomBenchmarkSuiteResult = { runId: string; status: RoomBenchmarkStatus; startedAt: string; completedAt: string; durationMs: number; total: number; passed: number; failed: number; warnings: number; git?: RoomBenchmarkGitMetadata; results: RoomBenchmarkCaseResult[]; artifactDir?: string; }; declare function gradeRoomBenchmarkTurn(input: { message: RoomBenchmarkMessage; messageIndex: number; rootEventId: string; schedulerResult: RoomBenchmarkTurnResult["schedulerResult"]; latencyMs: number; publishedSpeakers: string[]; publishedEventIds: string[]; publishedTexts?: string[]; completionStatus: RoomRootParticipationCompletionStatus | null; controlEvents?: RoomEventEnvelope[]; }): RoomBenchmarkTurnResult; declare function summarizeRoomBenchmarkControlEvents(controlEvents: RoomEventEnvelope[]): RoomBenchmarkControlEventSummary; declare function summarizeRoomBenchmarkMetrics(turns: RoomBenchmarkTurnResult[]): RoomBenchmarkMetrics; declare function resolveRoomBenchmarkStatus(input: { failures: string[]; warnings: string[]; }): RoomBenchmarkStatus; declare function countVisibleNoopMatches(texts: string[]): number; declare function classifyRoomBenchmarkFailure(failure: string): RoomBenchmarkFailureType; declare function uniqueFailureTypes(values: RoomBenchmarkFailureType[]): RoomBenchmarkFailureType[]; declare function scoreRoomBenchmark(input: { failures: string[]; warnings: string[]; metrics: Pick; }): number; declare function collectRoomBenchmarkGitMetadata(input?: { cwd?: string; }): Promise; declare function writeRoomBenchmarkCaseArtifacts(input: { artifactDir: string; benchmarkCase: RoomBenchmarkCase; result: RoomBenchmarkCaseResult; transcript: RoomEventEnvelope[]; controlEvents: RoomEventEnvelope[]; }): Promise; declare function writeRoomBenchmarkSuiteArtifacts(input: { artifactDir: string; result: RoomBenchmarkSuiteResult; }): Promise; type RunRoomBenchmarkCaseOptions = { rootDir?: string; artifactsDir?: string; now?: () => string; }; type RunRoomBenchmarkSuiteOptions = { cases: RoomBenchmarkCase[]; rootDir?: string; artifactsDir?: string; runId?: string; now?: () => string; git?: RoomBenchmarkGitMetadata | false; }; declare function runRoomBenchmarkCase(benchmarkCase: RoomBenchmarkCase, options?: RunRoomBenchmarkCaseOptions): Promise; declare function runRoomBenchmarkSuite(input: RunRoomBenchmarkSuiteOptions): Promise; declare function describeSession(session: SessionState): string; declare function createDefaultAgentBinding(resolvedAt?: string): SessionAgentBinding; declare function createDefaultSession(input: { cwd: string; workspaceId?: string | null; agent?: SessionAgentBinding; provider?: string; model: string; modelApiType?: SessionState["modelApiType"]; thinkingLevel?: ThinkingLevel; permissionMode?: PermissionMode; behaviorMode?: BehaviorMode; liteOverrides?: LiteOverride | null; title?: string; parentSessionId?: string | null; parentTaskId?: string | null; }): SessionState; declare function isGenericSessionTitle(title: string | null | undefined): boolean; declare function normalizeSessionTitleState(state: Partial | null | undefined, title: string | null | undefined): SessionTitleState; declare function markSessionTitleManual(session: SessionState, title: string, timestamp?: string): SessionState; declare function refreshAutomaticSessionTitle(session: SessionState, timestamp?: string): SessionState; declare function deriveAutomaticSessionTitle(session: Pick): string; interface TaskManagerPolicy { maxTurns: number | null; timeoutMs: number; maxConcurrentTasks: number; maxQueueLength: number; } declare const DEFAULT_TASK_MANAGER_POLICY: TaskManagerPolicy; declare function resolveTaskManagerPolicy(policy?: Partial): TaskManagerPolicy; declare function createTaskBudgetState(policy: TaskManagerPolicy): TaskBudgetState; declare function createManagedAbortController(input?: { signal?: AbortSignal; timeoutMs?: number | null; }): { controller: AbortController; cancelTimeout(): void; timedOut(): boolean; }; declare class TaskQueueFullError extends Error { constructor(queueLength: number, limit: number); } type TaskRuntimeControl = { abort(): void; }; declare class TaskConcurrencyError extends Error { constructor(message: string); } declare class TaskManager { private readonly runtimeControls; private readonly basePolicy; private readonly sessionStore?; private readonly scheduler; constructor(input?: { policy?: Partial; sessionStore?: { load(sessionId: string): Promise; }; }); getPolicy(overrides?: Partial): TaskManagerPolicy; getConcurrencyState(session: SessionState, overrides?: Partial): { limit: number; active: number; queued: number; }; getQueueState(session: SessionState, overrides?: Partial): { running: number; queued: number; limit: number; queueLimit: number; }; assertCanStartTask(session: SessionState, overrides?: Partial): Promise; createTask(session: SessionState, input: { transcriptSessionId: string; title: string; description: string; agentName?: string; provider?: string; model?: string; kind?: SessionTaskKind; executionMode?: "foreground" | "background"; retryOfTaskId?: string | null; attempt?: number; policy?: Partial; }): Promise; registerRuntimeControl(taskId: string, control: TaskRuntimeControl): void; unregisterRuntimeControl(taskId: string): void; stopTask(session: SessionState, taskId: string): { requested: boolean; task: SessionTask | undefined; }; createRetryInput(session: SessionState, taskId: string): { description: string; agentName?: string; provider?: string; model?: string; retryOfTaskId: string; attempt: number; }; completeTask(session: SessionState, taskId: string, input: { summary: string; artifact: TaskArtifactRef; turnsUsed: number; }): SessionTask | undefined; failTask(session: SessionState, taskId: string, input: { error: string; artifact: TaskArtifactRef; turnsUsed: number; }): SessionTask | undefined; cancelTask(session: SessionState, taskId: string, input: { error: string; artifact: TaskArtifactRef; turnsUsed: number; }): SessionTask | undefined; recordNotification(session: SessionState, taskId: string, notification: TaskNotificationRecord): SessionTask | undefined; } declare function runSubAgentTask(input: { parentSession: SessionState; description: string; agentName?: string; kind?: SessionTaskKind; signal?: AbortSignal; taskManager?: TaskManager; taskPolicy?: Partial; sessionStore?: { load(sessionId: string): Promise; }; executionMode?: "foreground" | "background"; retryOfTaskId?: string | null; attempt?: number; createChildSession(input: { taskId: string; }): SessionState; runChildSession(childSession: SessionState, task: SessionTask, options: { signal?: AbortSignal; maxTurns?: number | null; }): Promise; persistSession?(session: SessionState): Promise; onCreated?(input: { task: SessionTask; parentSession: SessionState; childSession: SessionState; }): Promise | void; onUpdate?(input: { task: SessionTask; parentSession: SessionState; childSession: SessionState; notification?: TaskNotificationRecord; }): Promise | void; }): Promise; declare function runManagedChildSessionRuntime(input: { childSession: SessionState; userMessage: string; tools: ToolDefinition[]; provider: ProviderAdapter; permissionManager: PermissionManager; compactSession(session: SessionState, reason?: unknown): Promise | SessionState; buildSystemPrompt(input: { session: SessionState; runtimeSystemHints: string[]; }): string; gatewayAttribution?: GatewayAttributionContext; maxTurns: number | null; signal?: AbortSignal; onEvent?(event: RuntimeEvent): Promise | void; }): Promise; declare const DEFAULT_ADAPTIVE_MAX_TURNS_HARD_CAP = 24; interface ResolveMaxTurnsInput { policy: Pick; userMessage?: string | null; agentName?: string | null; tools?: Pick[]; explicitMaxTurns?: number | null; } declare function resolveMaxTurns(input: ResolveMaxTurnsInput): number | null; type LegacySessionState = Omit & { provider?: string; modelRoutingEnabled?: boolean; thinkingLevel?: SessionState["thinkingLevel"]; workspaceId?: string | null; agent?: Partial | null; permissionMode?: PermissionMode | "plan"; behaviorMode?: BehaviorMode; liteOverrides?: LiteOverride | null; plan?: Partial | null; summary?: Partial | null; titleState?: Partial | null; sessionMemory?: Partial | null; compactState?: Partial | null; cronProposal?: Partial | null; busyMessages?: Partial | null; }; declare function normalizeSessionState(session: LegacySessionState): SessionState; declare function createSessionTask(input: { id?: string; parentSessionId: string; parentTaskId?: string | null; transcriptSessionId: string; kind?: SessionTaskKind; title: string; description: string; agentName?: string; provider?: string; model?: string; status?: TaskStatus; }): SessionTask; declare function findSessionTask(session: SessionState, taskId: string): SessionTask | undefined; declare function updateSessionTask(session: SessionState, taskId: string, update: (task: SessionTask) => SessionTask): SessionTask | undefined; declare function summarizeSessionTasks(session: SessionState): { total: number; pending: number; queued: number; running: number; backgrounded: number; active: number; completed: number; failed: number; cancelled: number; recentTask: SessionTask | null; }; declare function getTaskArtifactsRoot(workspaceRoot: string): string; declare function getLegacyTaskArtifactsRoot(workspaceRoot: string): string; declare function getTaskArtifactDir(workspaceRoot: string, taskId: string): string; declare function getSessionTaskArtifactDir(session: SessionState, taskId: string): string; declare function writeTaskArtifacts(input: { workspaceRoot?: string; session?: SessionState; task: SessionTask; transcriptSessionId: string; }): Promise; declare function createTaskNotification(task: SessionTask): TaskNotificationRecord; declare function appendTaskNotification(session: SessionState, notification: TaskNotificationRecord): void; type BundledSkillRoot = { path: string; sourceScope: SkillDefinition["sourceScope"]; precedence: number; }; declare function bundledSkillRootCandidates(): string[]; declare function resolveBundledSkillRoot(): Promise; declare function resolveSkillSource(source: string): Promise; type ParsedSlashInput = { kind: "command"; name: string; args: string[]; raw: string; } | { kind: "message"; text: string; }; declare function parseSlashInput(rawInput: string): ParsedSlashInput; declare function createInMemoryTool(input: { name: string; description: string; handler(input: Record): Promise; risk?: "low" | "medium" | "high"; jsonSchema?: ToolJsonSchema; }): ToolDefinition, unknown>; declare function createDefaultTools(input: { config?: Pick; session?: Pick; env?: Record; skillCatalog: SkillCatalog; agentCatalog: AgentCatalog; behaviorMode?: BehaviorMode; runSubAgent?: (input: SubAgentRunInput) => Promise; skillImportService?: SkillImportService; getMcpStatuses?: () => McpServerStatus[]; cronManagement?: CronManagementPort; extraTools?: ToolDefinition[]; liteSettings?: ResolvedLiteSettings | null; }): ToolDefinition[]; declare function createBashTool(shell?: string): ToolDefinition<{ command: string; timeoutMs?: number; }, { stdout: string; stderr: string; exitCode: number | null; }>; declare const inputSchema$2: z.ZodDiscriminatedUnion<"action", [z.ZodObject<{ action: z.ZodLiteral<"propose">; name: z.ZodString; description: z.ZodOptional; schedule: z.ZodDiscriminatedUnion<"kind", [z.ZodObject<{ kind: z.ZodLiteral<"at">; at: z.ZodString; timezone: z.ZodOptional; }, "strip", z.ZodTypeAny, { at: string; kind: "at"; timezone?: string | undefined; }, { at: string; kind: "at"; timezone?: string | undefined; }>, z.ZodObject<{ kind: z.ZodLiteral<"every">; everyMs: z.ZodNumber; anchorAt: z.ZodOptional; timezone: z.ZodOptional; }, "strip", z.ZodTypeAny, { kind: "every"; everyMs: number; anchorAt?: string | undefined; timezone?: string | undefined; }, { kind: "every"; everyMs: number; anchorAt?: string | undefined; timezone?: string | undefined; }>, z.ZodObject<{ kind: z.ZodLiteral<"cron">; expr: z.ZodString; timezone: z.ZodOptional; staggerMs: z.ZodOptional; }, "strip", z.ZodTypeAny, { kind: "cron"; expr: string; staggerMs?: number | undefined; timezone?: string | undefined; }, { kind: "cron"; expr: string; staggerMs?: number | undefined; timezone?: string | undefined; }>]>; prompt: z.ZodOptional; workflow: z.ZodOptional>; intent: z.ZodString; version: z.ZodOptional>; context: z.ZodOptional>; steps: z.ZodArray; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">>, "many">; cost: z.ZodOptional>; maxLlmStepsPerRun: z.ZodOptional; maxPromptChars: z.ZodOptional; attribution: z.ZodOptional; }, "strip", z.ZodTypeAny, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }>>; capabilities: z.ZodOptional>; }, "strip", z.ZodTypeAny, { allowed?: string[] | undefined; }, { allowed?: string[] | undefined; }>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ kind: z.ZodOptional>; intent: z.ZodString; version: z.ZodOptional>; context: z.ZodOptional>; steps: z.ZodArray; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">>, "many">; cost: z.ZodOptional>; maxLlmStepsPerRun: z.ZodOptional; maxPromptChars: z.ZodOptional; attribution: z.ZodOptional; }, "strip", z.ZodTypeAny, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }>>; capabilities: z.ZodOptional>; }, "strip", z.ZodTypeAny, { allowed?: string[] | undefined; }, { allowed?: string[] | undefined; }>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ kind: z.ZodOptional>; intent: z.ZodString; version: z.ZodOptional>; context: z.ZodOptional>; steps: z.ZodArray; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">>, "many">; cost: z.ZodOptional>; maxLlmStepsPerRun: z.ZodOptional; maxPromptChars: z.ZodOptional; attribution: z.ZodOptional; }, "strip", z.ZodTypeAny, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }>>; capabilities: z.ZodOptional>; }, "strip", z.ZodTypeAny, { allowed?: string[] | undefined; }, { allowed?: string[] | undefined; }>>; }, z.ZodTypeAny, "passthrough">>>; target: z.ZodOptional>; enabled: z.ZodOptional; missedPolicy: z.ZodOptional>; concurrencyPolicy: z.ZodOptional>; costAcknowledged: z.ZodOptional; tags: z.ZodOptional>; }, "strip", z.ZodTypeAny, { schedule: { at: string; kind: "at"; timezone?: string | undefined; } | { kind: "every"; everyMs: number; anchorAt?: string | undefined; timezone?: string | undefined; } | { kind: "cron"; expr: string; staggerMs?: number | undefined; timezone?: string | undefined; }; name: string; action: "propose"; prompt?: string | undefined; workflow?: z.objectOutputType<{ kind: z.ZodOptional>; intent: z.ZodString; version: z.ZodOptional>; context: z.ZodOptional>; steps: z.ZodArray; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">>, "many">; cost: z.ZodOptional>; maxLlmStepsPerRun: z.ZodOptional; maxPromptChars: z.ZodOptional; attribution: z.ZodOptional; }, "strip", z.ZodTypeAny, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }>>; capabilities: z.ZodOptional>; }, "strip", z.ZodTypeAny, { allowed?: string[] | undefined; }, { allowed?: string[] | undefined; }>>; }, z.ZodTypeAny, "passthrough"> | undefined; description?: string | undefined; enabled?: boolean | undefined; target?: "background" | "current_session" | undefined; tags?: string[] | undefined; missedPolicy?: "skip" | "ask" | "run" | undefined; costAcknowledged?: boolean | undefined; concurrencyPolicy?: "delay" | "skip" | "fail" | undefined; }, { schedule: { at: string; kind: "at"; timezone?: string | undefined; } | { kind: "every"; everyMs: number; anchorAt?: string | undefined; timezone?: string | undefined; } | { kind: "cron"; expr: string; staggerMs?: number | undefined; timezone?: string | undefined; }; name: string; action: "propose"; prompt?: string | undefined; workflow?: z.objectInputType<{ kind: z.ZodOptional>; intent: z.ZodString; version: z.ZodOptional>; context: z.ZodOptional>; steps: z.ZodArray; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ id: z.ZodString; kind: z.ZodEnum<["tool", "condition", "llm", "checkpoint", "stop"]>; name: z.ZodOptional; description: z.ZodOptional; assign: z.ZodOptional; next: z.ZodOptional; onError: z.ZodOptional>; }, z.ZodTypeAny, "passthrough">>, "many">; cost: z.ZodOptional>; maxLlmStepsPerRun: z.ZodOptional; maxPromptChars: z.ZodOptional; attribution: z.ZodOptional; }, "strip", z.ZodTypeAny, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }, { maxLlmStepsPerRun?: number | undefined; llmBudgetPolicy?: "only_after_signal" | "always" | undefined; maxPromptChars?: number | undefined; attribution?: string | undefined; }>>; capabilities: z.ZodOptional>; }, "strip", z.ZodTypeAny, { allowed?: string[] | undefined; }, { allowed?: string[] | undefined; }>>; }, z.ZodTypeAny, "passthrough"> | undefined; description?: string | undefined; enabled?: boolean | undefined; target?: "background" | "current_session" | undefined; tags?: string[] | undefined; missedPolicy?: "skip" | "ask" | "run" | undefined; costAcknowledged?: boolean | undefined; concurrencyPolicy?: "delay" | "skip" | "fail" | undefined; }>, z.ZodObject<{ action: z.ZodLiteral<"status">; }, "strip", z.ZodTypeAny, { action: "status"; }, { action: "status"; }>, z.ZodObject<{ action: z.ZodLiteral<"list">; enabled: z.ZodOptional>; query: z.ZodOptional; limit: z.ZodOptional; }, "strip", z.ZodTypeAny, { action: "list"; enabled?: "enabled" | "all" | "disabled" | undefined; limit?: number | undefined; query?: string | undefined; }, { action: "list"; enabled?: "enabled" | "all" | "disabled" | undefined; limit?: number | undefined; query?: string | undefined; }>, z.ZodObject<{ action: z.ZodLiteral<"runs">; jobId: z.ZodOptional; status: z.ZodOptional>; limit: z.ZodOptional; }, "strip", z.ZodTypeAny, { action: "runs"; jobId?: string | undefined; status?: "success" | "skipped" | "failed" | "queued" | "submitted" | "running" | "cancelled" | undefined; limit?: number | undefined; }, { action: "runs"; jobId?: string | undefined; status?: "success" | "skipped" | "failed" | "queued" | "submitted" | "running" | "cancelled" | undefined; limit?: number | undefined; }>, z.ZodObject<{ action: z.ZodLiteral<"update">; jobId: z.ZodString; name: z.ZodOptional; description: z.ZodOptional; schedule: z.ZodOptional; at: z.ZodString; timezone: z.ZodOptional; }, "strip", z.ZodTypeAny, { at: string; kind: "at"; timezone?: string | undefined; }, { at: string; kind: "at"; timezone?: string | undefined; }>, z.ZodObject<{ kind: z.ZodLiteral<"every">; everyMs: z.ZodNumber; anchorAt: z.ZodOptional; timezone: z.ZodOptional; }, "strip", z.ZodTypeAny, { kind: "every"; everyMs: number; anchorAt?: string | undefined; timezone?: string | undefined; }, { kind: "every"; everyMs: number; anchorAt?: string | undefined; timezone?: string | undefined; }>, z.ZodObject<{ kind: z.ZodLiteral<"cron">; expr: z.ZodString; timezone: z.ZodOptional; staggerMs: z.ZodOptional; }, "strip", z.ZodTypeAny, { kind: "cron"; expr: string; staggerMs?: number | undefined; timezone?: string | undefined; }, { kind: "cron"; expr: string; staggerMs?: number | undefined; timezone?: string | undefined; }>]>>; prompt: z.ZodOptional; enabled: z.ZodOptional; missedPolicy: z.ZodOptional>; concurrencyPolicy: z.ZodOptional>; tags: z.ZodOptional>; }, "strip", z.ZodTypeAny, { jobId: string; action: "update"; prompt?: string | undefined; schedule?: { at: string; kind: "at"; timezone?: string | undefined; } | { kind: "every"; everyMs: number; anchorAt?: string | undefined; timezone?: string | undefined; } | { kind: "cron"; expr: string; staggerMs?: number | undefined; timezone?: string | undefined; } | undefined; name?: string | undefined; description?: string | undefined; enabled?: boolean | undefined; tags?: string[] | undefined; missedPolicy?: "skip" | "ask" | "run" | undefined; concurrencyPolicy?: "delay" | "skip" | "fail" | undefined; }, { jobId: string; action: "update"; prompt?: string | undefined; schedule?: { at: string; kind: "at"; timezone?: string | undefined; } | { kind: "every"; everyMs: number; anchorAt?: string | undefined; timezone?: string | undefined; } | { kind: "cron"; expr: string; staggerMs?: number | undefined; timezone?: string | undefined; } | undefined; name?: string | undefined; description?: string | undefined; enabled?: boolean | undefined; tags?: string[] | undefined; missedPolicy?: "skip" | "ask" | "run" | undefined; concurrencyPolicy?: "delay" | "skip" | "fail" | undefined; }>, z.ZodObject<{ action: z.ZodLiteral<"remove">; jobId: z.ZodString; cancelRunning: z.ZodOptional; }, "strip", z.ZodTypeAny, { jobId: string; action: "remove"; cancelRunning?: boolean | undefined; }, { jobId: string; action: "remove"; cancelRunning?: boolean | undefined; }>]>; type CronToolInput = z.infer; declare function createCronTool(input: { cronManagement: CronManagementPort; config?: Pick; }): ToolDefinition; declare const inputSchema$1: z.ZodObject<{ query: z.ZodString; limit: z.ZodOptional; }, "strip", z.ZodTypeAny, { query: string; limit?: number | undefined; }, { query: string; limit?: number | undefined; }>; declare const askInputSchema: z.ZodObject<{ question: z.ZodString; chatId: z.ZodOptional; }, "strip", z.ZodTypeAny, { question: string; chatId?: string | undefined; }, { question: string; chatId?: string | undefined; }>; type FastGptSearchInput = z.infer; type FastGptAskInput = z.infer; type FastGptSearchResult = { datasetId: string | null; datasetName: string | null; collectionIds: string[]; results: Array<{ id: string | null; q: string; a: string; datasetId: string | null; collectionId: string | null; sourceName: string | null; sourceId: string | null; score: number | null; }>; systemHint: string; }; type FastGptAskResult = { appId: string; chatId: string; datasetId: string | null; datasetName: string | null; collectionIds: string[]; answer: string; responseData: unknown; raw: unknown; systemHint: string; }; declare function createFastGptKnowledgeSearchTool(input: { scope: FastGptKnowledgeScope; env?: Record; }): ToolDefinition; declare function createFastGptKnowledgeAskTool(input: { scope: FastGptKnowledgeScope; env?: Record; }): ToolDefinition; declare const readImageInputSchema: z.ZodEffects; paths: z.ZodOptional>; prompt: z.ZodOptional; }, "strip", z.ZodTypeAny, { prompt?: string | undefined; path?: string | undefined; paths?: string[] | undefined; }, { prompt?: string | undefined; path?: string | undefined; paths?: string[] | undefined; }>, { prompt?: string | undefined; path?: string | undefined; paths?: string[] | undefined; }, { prompt?: string | undefined; path?: string | undefined; paths?: string[] | undefined; }>; type ReadImageInput = z.infer; /** * Expose image understanding as a normal turn tool. Discovery and selection * remain model-controlled: the model can Glob a directory and only send the * files that matter to this tool. */ declare function createReadImageTool(): ToolDefinition; declare const THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; declare const DEFAULT_THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; /** * Ascending strength order, used when clamping an unsupported level down to the nearest * supported one. Keep in sync with `THINKING_LEVELS`. */ declare const THINKING_LEVEL_ORDER: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; type ModelThinkingConfig = Pick; type ParsedThinkingDirective = { ok: true; userMessage: string; thinkingLevel?: ThinkingLevel; } | { ok: false; message: string; }; declare function normalizeThinkingLevel(raw: unknown): ThinkingLevel | undefined; declare function normalizeThinkingLevelOrNull(raw: unknown): ThinkingLevel | null; declare function parseInlineThinkingDirective(raw: string): ParsedThinkingDirective; declare function normalizeSupportedThinkingLevels(raw: unknown): ThinkingLevel[] | undefined; declare function getSupportedThinkingLevels(model?: ModelThinkingConfig | null): ThinkingLevel[]; declare function formatThinkingLevels(levels: readonly ThinkingLevel[]): string; /** * @deprecated Collapses `minimal`/`xhigh`/`max` onto the legacy three-value enum. Use * `mapLevelToEffort` from `thinkingDialect`, which respects the model's actual effort vocabulary. * Retained only for callers that specifically need the old low|medium|high shape. */ declare function mapThinkingLevelToReasoningEffort(level: ThinkingLevel | null | undefined): "low" | "medium" | "high" | undefined; /** * Clamp to the nearest supported level at or below the request, so an unsupported level degrades * predictably (`max` -> `xhigh` -> `high` -> ...) instead of jumping straight to `off`. */ declare function clampThinkingLevel(level: ThinkingLevel, supportedLevels: readonly ThinkingLevel[]): ThinkingLevel; declare function resolveThinkingDefaultLevel(input: { configuredLevel?: ThinkingLevel | null; model?: Pick | null; }): ThinkingLevel; declare function resolveEffectiveThinkingLevel(input: { sessionLevel?: ThinkingLevel; configuredLevel?: ThinkingLevel | null; model?: ModelThinkingConfig | null; }): ThinkingLevel; /** * Whether a model supports thinking, defaulting from the built-in table when config is silent. * Returns `false` for unknown models: advertising thinking that silently does nothing is worse * than requiring an explicit `reasoning: true` for an unrecognized model. */ declare function resolveModelReasoning(input: { modelId: string; configured?: boolean; }): boolean; /** * The wire values a model's `reasoning_effort` accepts. * * Returns undefined for unknown models, letting the caller fall back to the legacy enum. Budget * dialects have no vocabulary — they do not use the effort field at all. */ declare function resolveModelEffortVocabulary(input: { modelId: string; /** * Levels explicitly declared in config. When present these drive the vocabulary, so declaring a * level actually emits it — otherwise an operator could add `max` in config and still have the * field silently dropped because the built-in table did not list it. */ configuredLevels?: ThinkingLevel[]; }): readonly EffortValue[] | undefined; /** * Supported levels for a model, from config when set, otherwise derived from the built-in table. * * `configuredReasoning` is honored ahead of the table: an operator who explicitly sets * `reasoning: true` on a model the table does not know about (or classifies as non-thinking) must * not be narrowed to `["off"]`, or the override would be unusable. */ declare function resolveModelSupportedThinkingLevels(input: { modelId: string; configured?: ThinkingLevel[]; configuredReasoning?: boolean; }): ThinkingLevel[] | undefined; declare const inputSchema: z.ZodObject<{ target: z.ZodOptional; constraints: z.ZodOptional>; acceptance: z.ZodOptional>; }, "strip", z.ZodTypeAny, { goal?: string | undefined; constraints?: string[] | undefined; acceptance?: string[] | undefined; }, { goal?: string | undefined; constraints?: string[] | undefined; acceptance?: string[] | undefined; }>>; steps: z.ZodOptional; status: z.ZodEnum<["pending", "in_progress", "completed"]>; }, "strip", z.ZodTypeAny, { status: "pending" | "in_progress" | "completed"; content: string; activeForm?: string | undefined; }, { status: "pending" | "in_progress" | "completed"; content: string; activeForm?: string | undefined; }>, "many">>; }, "strip", z.ZodTypeAny, { target?: { goal?: string | undefined; constraints?: string[] | undefined; acceptance?: string[] | undefined; } | undefined; steps?: { status: "pending" | "in_progress" | "completed"; content: string; activeForm?: string | undefined; }[] | undefined; }, { target?: { goal?: string | undefined; constraints?: string[] | undefined; acceptance?: string[] | undefined; } | undefined; steps?: { status: "pending" | "in_progress" | "completed"; content: string; activeForm?: string | undefined; }[] | undefined; }>; type TrackToolInput = z.infer; declare function createTrackTool(): ToolDefinition; interface TrackWritePatch { /** 提供则覆盖/合并目标锚。 */ target?: TrackTargetPatch; /** 提供则全量覆盖步骤列表(抄 Codex update_plan 的 whole-replace 语义)。 */ steps?: TrackStepInput[]; } interface TrackWriteResult { /** 最新快照(始终返回;权威态已写入 session.track)。 */ snapshot: TrackSnapshot; /** 外部快照文件是否成功落盘。false 不影响追踪本身。 */ persisted: boolean; /** 落盘失败时的非致命说明(文件错误等)。 */ warning?: string; } /** * Track 规范读写接口(pmm-038)。 * * - 权威状态存在 `session.track`,随 session 持久化(FileSessionStore),天然可 `--resume` 恢复, * 并被 `buildSystemPromptSections` 每轮回灌进系统提示("超长任务有 target 约束"的关键件)。 * - 同时把一份稳定快照写到 `.xigua/track/{sessionId}.json`,供未来"任务可视化"等外部消费者轮询, * 无需加载整个 session。数据契约见 `docs/interfaces/track-visualization.md`。 */ declare class TrackStore { private readonly workspaceRoot; private readonly options?; constructor(workspaceRoot: string, options?: { trackDir?: string | null; } | undefined); static forSession(session: SessionState): TrackStore; getTrackDir(): string; getSnapshotPath(sessionId: string): string; /** READ:返回会话内权威 Track 状态(已净化,可视化/工具读取统一走这里)。 */ read(session: SessionState): TrackState; /** READ:构造稳定快照(含进度),用于对外展示。 */ snapshot(session: SessionState): TrackSnapshot; /** * WRITE:合并补丁,写回 `session.track`(权威态,纯内存,不会失败),再尽力落一份外部快照。 * 快照文件写失败属非致命:追踪本身已生效,仅在结果里带 warning,不抛错(否则一次文件错误会让 * 整个工具调用失败)。 */ write(session: SessionState, patch: TrackWritePatch): Promise; /** 清空当前 Track(`/track clear`)。落盘失败非致命。 */ clear(session: SessionState): Promise; /** * 由已批准的 PlanDocument 播种 Track(plan -> Track 桥): * goal -> target.goal,validation -> target.acceptance,steps -> 全部 pending 步骤。 * 不传 constraints,保留既有约束。 */ seedFromPlan(session: SessionState, plan: { goal?: string; acceptance?: string[]; steps?: string[]; }): Promise; private persistSnapshot; private writeSnapshotFile; /** * READ(外部):从快照文件读取,供不持有 session 对象的消费者使用。 * 文件缺失(ENOENT)或内容损坏(JSON 解析失败)都返回 null —— 可视化层据此显示"无追踪"而非崩溃。 */ readSnapshotFile(sessionId: string): Promise; } interface WebSearchProviderSearchInput { query: string; maxResults: number; config: WebSearchProviderConfig; signal?: AbortSignal; env?: Record; fetchImpl?: typeof fetch; } interface WebSearchProvider { id: string; label: string; kind: string; description: string; search(input: WebSearchProviderSearchInput): Promise; } interface WebSearchProviderRegistry { items: WebSearchProvider[]; } declare function createDefaultWebSearchRegistryConfig(): WebSearchRegistryConfig; declare function createDefaultWebSearchProviderRegistry(extraProviders?: WebSearchProvider[]): WebSearchProviderRegistry; declare function listWebSearchProviderConfigs(config: Pick): WebSearchProviderConfig[]; declare function getWebSearchProviderConfig(config: Pick, name: string): WebSearchProviderConfig | undefined; declare function getDefaultWebSearchProviderConfig(config: Pick): WebSearchProviderConfig; declare function getWebSearchProviderImplementation(registry: WebSearchProviderRegistry, providerConfig: Pick): WebSearchProvider; declare function resolveWebSearchApiKey(provider: Pick, env?: Record): string | undefined; declare function isWebSearchAuthConfigured(provider: Pick, env?: Record): boolean; declare function assertWebSearchProviderSelection(config: Pick, registry: WebSearchProviderRegistry, providerName?: string): { providerConfig: WebSearchProviderConfig; provider: WebSearchProvider; }; declare function normalizeTurnAttachments(value: unknown): TurnAttachment[]; declare function materializeInlineTurnAttachments(input: { session: Pick; attachments?: TurnAttachment[]; }): Promise; declare function inferImageMimeType(attachment: Pick): string | null; declare function resolveImageAttachmentPath(input: { session: Pick; attachment: Pick; /** Full-access sessions may inspect an image outside the workspace root. */ allowOutsideRoot?: boolean; }): Promise; declare function findReferencedImageAttachments(input: { session: Pick; text: string; existing?: TurnAttachment[]; allowOutsideRoot?: boolean; }): Promise; declare function loadImageAttachmentDataUrl(input: { session: Pick & Partial>; attachment: TurnAttachment; allowOutsideRoot?: boolean; }): Promise; declare function describeAttachmentForText(attachment: TurnAttachment): string; declare function appendInlineFileAttachmentsToText(text: string, attachments: TurnAttachment[] | undefined): string; declare function appendFileAttachmentsToText(input: { session: Pick; text: string; attachments: TurnAttachment[] | undefined; }): Promise; declare function createEmptyBusyMessagesState(): SessionBusyMessagesState; declare function normalizeBusyMessagesState(input?: Partial | null): SessionBusyMessagesState; declare function getDefaultBusyMessagePolicy(): BusyMessagePolicy; declare function resolveBusyMessagePolicy(input?: Partial | null): BusyMessagePolicy; declare function enqueueBusyQueueItem(state: SessionBusyMessagesState, input: { sessionId: string; text: string; persistedText?: string; source: BusyMessageSource; idempotencyKey?: string; thinkingLevel?: ThinkingLevel; attachments?: TurnAttachment[]; now?: string; front?: boolean; }): { item: BusyQueueItem; created: boolean; }; declare function appendBusyCollectMessage(state: SessionBusyMessagesState, input: { sessionId: string; text: string; persistedText?: string; source: BusyMessageSource; debounceMs: number; idempotencyKey?: string; now?: string; }): { buffer: BusyCollectBuffer; created: boolean; }; declare function formatBusyCollectPrompt(buffer: BusyCollectBuffer, persisted?: boolean): string; type BusyDrainSelection = { kind: "queue"; id: string; text: string; persistedText?: string; createdAt: string; thinkingLevel?: ThinkingLevel; attachments?: TurnAttachment[]; } | { kind: "collect"; id: string; text: string; persistedText?: string; createdAt: string; }; declare function selectNextBusyMessageForDrain(state: SessionBusyMessagesState): BusyDrainSelection | null; declare function updateBusyDrainStatus(state: SessionBusyMessagesState, selection: BusyDrainSelection, status: "running" | "completed" | "failed" | "cancelled", now?: string, error?: string): void; declare function cancelBusyQueueItem(state: SessionBusyMessagesState, itemId: string, now?: string): boolean; declare function clearBusyQueue(state: SessionBusyMessagesState, now?: string): number; declare function reorderBusyQueueItems(state: SessionBusyMessagesState, itemIds: string[], now?: string): boolean; declare function recordBusySteer(state: SessionBusyMessagesState, input: { sessionId: string; turnId: string; text: string; persistedText?: string; status: BusySteerStatus; fallbackMode?: "queue" | "collect" | "reject"; now?: string; id?: string; }): BusySteerRecord; declare function updateBusySteerStatus(state: SessionBusyMessagesState, recordId: string, status: BusySteerStatus, now?: string, error?: string): BusySteerRecord | null; declare function summarizeBusyMessages(state: SessionBusyMessagesState): { queued: number; collecting: number; latestSteerStatus: BusySteerStatus | null; }; export { AUTO_COMPACT_BUFFER_TOKENS, type AcquireSessionLeaseInput, type AcquireSessionLeaseResult, AgentCatalog, type AgentDefinition, type AgentProfileKind, type AgentProfileRuntimeDefaults, type AgentProfileSourceScope, type AgentWorkspaceMode, type AgentWorkspacePaths, type AppConfig, type AppendRoomEventInput, type AttachSessionInput, type AttachSessionResult, type AuthStoreLike, type AutoDreamEvaluation, type AutoDreamExecutionResult, type AutoDreamPolicy, type AutoDreamState, type BehaviorMode, type BridgePluginEntryConfig, type BridgePluginRegistryConfig, type BuildContextEnvelopeInput, type BuildRoomRootParticipationLedgerInput, type BundledSkillRoot, type BusyCollectBuffer, type BusyCollectMessage, type BusyCollectStatus, type BusyDrainSelection, type BusyMessageMode, type BusyMessageMutationResult, type BusyMessagePolicy, type BusyMessageSource, type BusyQueueItem, type BusyQueueStatus, type BusySteerRecord, type BusySteerStatus, CONFIG_SCHEMA_VERSION, type CacheEntry, type CacheLookupResult, type CacheMetrics, type ClassifyResult, type CodexAuthConfig, type CodexAuthState, CodexAuthStore, type CodexProviderConfig, type CodexRequestAuth, type CommandReportSection, type CompactDecision, type CompactDecisionReason, type CompactPolicy, type CompactSessionOptions, type CompactState, type CompactStatus, type CompactStrategy, type ContextBudget, type ContextEnvelope, type ContextPackingDecision, type ContextPressure, ContextWindowExceededError, type ContextWindowSource, type CreateCronProposalInput, type CreateGoalDraftInput, type CreateRoomInput, type CronApprovalPreview, type CronCancelExecutor, type CronDelivery, type CronDeliveryStatus, type CronJob, type CronJobCreate, type CronJobPatch, type CronJobState, type CronJobValidationOptions, type CronJobValidationResult, type CronListOptions, type CronManagementPort, type CronPayload, type CronPolicy, type CronProposal, type CronProposalResult, type CronProposalStatus, type CronRun, type CronRunExecutor, type CronRunPatch, type CronRunStatus, type CronRunTaskLink, type CronRunTrigger, type CronRunsOptions, type CronSchedule, type CronStatus, CronStore, type CronStoreFile, type CronStoreOptions, type CronTarget, type CronWorkflowBaseStep, type CronWorkflowCheckpointStep, type CronWorkflowCondition, type CronWorkflowConditionOp, type CronWorkflowConditionStep, type CronWorkflowJson, type CronWorkflowLlmStep, type CronWorkflowPayload, type CronWorkflowRef, type CronWorkflowStep, type CronWorkflowStopStep, type CronWorkflowToolStep, DEFAULT_ADAPTIVE_MAX_TURNS_HARD_CAP, DEFAULT_CONTEXT_WINDOW_TOKENS, DEFAULT_CRON_RUN_LOG_KEEP_LINES, DEFAULT_CRON_RUN_LOG_MAX_BYTES, DEFAULT_CRON_WORKFLOW_CAPABILITIES, DEFAULT_INTERACTIVE_MAX_TURNS, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_TASK_MANAGER_POLICY, DEFAULT_THINKING_LEVELS, type DurableMemoryCandidate, type DurableMemoryManifest, type DurableMemoryQuery, type DurableMemoryRecall, type DurableMemoryRecord, type DurableMemoryScope, type DurableMemorySource, type DurableMemoryType, type DurableMemoryUpsertInput, type EffortValue, type EnqueueBusyMessageInput, FailoverError, type FailoverReason, type FallbackAdapterSelection, type FallbackAttempt, type FallbackCandidate, FallbackSummaryError, type FastGptKnowledgeScope, FileMemoryStore, type FileMemoryStoreStats, type FileSessionSaveOptions, FileSessionStore, type FormatMemoryReportOptions, GOAL_WORK_UNIT_TRANSCRIPT_MARKER, type GatewayAttributionContext, type GatewayConfig, type GatewayCronRuntimeLike, type GoalAcceptanceCheck, type GoalApprovalOptions, GoalCheckRunner, type GoalCheckRunnerOptions, type GoalCommandResult, type GoalContract, GoalController, type GoalControllerOptions, type GoalEvent, type GoalEvidence, type GoalEvidenceFreshness, type GoalEvidenceStatus, GoalEvidenceStore, type GoalEvidenceSummary, type GoalForegroundEvent, type GoalForegroundObserver, type GoalRecord, type GoalReviewObserver, type GoalReviewer, GoalRuntimeAdapter, type GoalRuntimeAdapterOptions, GoalRuntimeService, type GoalRuntimeServiceOptions, type GoalStatus, GoalStore, type GoalTransitionInput, type GoalVerdict, GoalVerifier, type GoalWorkUnitResult, HIGH_FREQUENCY_PROMPT_CRON_MS, type ImageModelConfig, type ImageUnderstandingResult, LEGACY_EFFORT_VOCABULARY, type LiteModeConfig, type LiteOverride, type LiteSettingSource, type LiteSkillIndex, type LiteSkillIndexEntry, type LiteSkillOverride, type LiteToolOverride, type LocalCronManagementPortOptions, MAX_OUTPUT_RESERVE_TOKENS, MIN_COMPACT_RESERVE_TOKENS, McpCapabilityStore, McpConfigRegistry, type McpConnectedToolSource, McpConnectionRegistry, McpManager, type McpPromptCapability, type McpResourceCapability, type McpServerCapabilities, type McpServerConfig, type McpServerConnectionState, type McpServerStatus, McpService, McpToolAdapter, type McpToolCapability, type MemoryArtifactExtractionResult, type MemoryHealthReport, type MemoryReportOptions, type MemoryWarning, type MemoryWithScore, type ModelPricingConfig, type OnboardingState, type OpenAIResponsesProviderConfig, PLAN_MODE_TOOL_NAMES, type PackedContext, type PackedContextInput, type ParsedPrePublishSelfCheckDecision, type ParsedSlashInput, type ParsedSpeechApplicationDecision, type ParsedSpeechIntentDecision, type ParsedThinkingDirective, type PermissionDecision, type PermissionDecisionType, type PermissionManager, type PermissionMode, type PermissionPromptChoice, type PermissionRequest, type PermissionRisk, type PersonaPromptInput, type PlanApprovalPreview, type PlanDocument, type PlanDocumentPatch, PlanDocumentStore, type PlanStatus, type PlanValidationResult, type PromptAttachmentExplain, type PromptCacheExplain, type SystemPromptBuildInput as PromptContext, type PromptExplainOptions, type PromptExplainReport, type PromptSectionLifecycle, type PromptSectionMetadata, type PromptSectionOwner, type PromptVisibleSystemEventExplain, type ProviderAdapter, type ProviderCacheMetricsSnapshot, type ProviderCacheUsageSummary, type ProviderConfig, type ProviderConfigOpResult, ProviderMessageCache, type ProviderMessageCacheKey, type ProviderModelConfig, type ProviderRegistryConfig, type ProviderToolCall, type ProviderTurnRequest, type ProviderTurnResult, type ProviderType, REMOTE_CONTROL_EVENT_NAMES, REMOTE_CONTROL_METHOD_NAMES, RUNTIME_NARRATION_CHECKPOINT_TOOLS, type ReactiveCompactOptions, type ReadRecallLogOptions, type RecallLogContext, type RecallLogEntry, type RemoteCommandCategory, type RemoteCommandDescriptor, type RemoteCommandSurface, type RemoteControlApiConfigPayload, type RemoteControlConnectPayload, type RemoteControlEventFrame, type RemoteControlEventName, type RemoteControlMethodName, type RemoteControlProviderConfigPayload, type RemoteControlProviderModelPayload, type RemoteControlProviderRegistryPayload, type RemoteControlProviderSaveInput, type RemoteControlRequestFrame, type RemoteControlResponseError, type RemoteControlResponseFrame, RemoteTurnManager, type RemoteTurnManagerDeps, type ResolveAgentProfileResult, type ResolveMaxTurnsInput, type ResolvedAgentProfile, type ResolvedContextWindow, type ResolvedLiteSettings, type ResolvedProviderAuth, type ResponsesClientLike, type ResponsesReplayState, type RoomActorRef, type RoomAdminGovernanceEvaluation, type RoomAgentContextDigest, type RoomAgentRuntimeStatus, type RoomAgentRuntimeStatusValue, type RoomAnnouncement, RoomAutonomousLoop, type RoomAutonomousLoopDeps, type RoomBatchPrioritySignal, type RoomBenchmarkAgentMember, type RoomBenchmarkCase, type RoomBenchmarkCaseResult, type RoomBenchmarkControlEventSummary, type RoomBenchmarkExpectation, type RoomBenchmarkFailureType, type RoomBenchmarkGitMetadata, type RoomBenchmarkHumanMember, type RoomBenchmarkMembers, type RoomBenchmarkMessage, type RoomBenchmarkMetrics, type RoomBenchmarkMetricsThresholds, type RoomBenchmarkMockFailure, type RoomBenchmarkMockMember, type RoomBenchmarkMockRuntime, type RoomBenchmarkMockRuntimeOptions, type RoomBenchmarkPolicyTrace, type RoomBenchmarkRuntimeMode, type RoomBenchmarkSpeakerPolicy, type RoomBenchmarkSpeakerPolicySettings, type RoomBenchmarkStatus, type RoomBenchmarkSuiteResult, type RoomBenchmarkTurnEvidence, type RoomBenchmarkTurnResult, type RoomBudgetDecision, type RoomBudgetExhaustedAction, type RoomBudgetFactsSummary, type RoomBudgetPolicy, type RoomBudgetState, type RoomCapability, type RoomControlEventTypeCount, type RoomControlPayload, type RoomControlResult, RoomControlService, type RoomControlServiceDeps, type RoomControlSessionControl, type RoomDiagnosticsSummary, type RoomDraftingPolicy, type RoomDraftingSlot, type RoomDraftingSlotStatus, type RoomEventEnvelope, type RoomEventKind, type RoomFactsSummary, type RoomFloorLock, type RoomHandoffPlan, type RoomIdentityCompactContext, type RoomIdentityCompactOptions, type RoomInFlightMessagePolicy, type RoomInboxCursor, type RoomLateResultAdoptionDecision, type RoomLifecycleState, type RoomLongRunningTurn, type RoomLongRunningTurnStatus, type RoomMember, type RoomMemberKind, type RoomMemberState, type RoomMembersFile, type RoomObjective, type RoomObservationBatch, type RoomPendingMention, type RoomPendingMentionDeliveryMode, type RoomPendingMentionDiagnostics, type RoomPendingMentionSourceKind, type RoomPendingMentionStatus, type RoomPolicyDecisionSkip, type RoomPromptMetrics, type RoomRootDiagnostics, type RoomRootFirstContributionStatus, type RoomRootMemberContributionState, type RoomRootParticipantDiagnostics, type RoomRootParticipationCompletionStatus, type RoomRootParticipationContext, type RoomRootParticipationContextSource, type RoomRootParticipationKind, type RoomRootParticipationLedger, type RoomRuntimeCleanupLongTurnRef, type RoomRuntimeCleanupMode, type RoomRuntimeCleanupOptions, type RoomRuntimeCleanupResult, type RoomRuntimeLongTurnAction, type RoomRuntimeQueueAction, type RoomRuntimeSlotAction, type RoomRuntimeSummary, RoomScheduler, type RoomSchedulerDecisionTraceSummary, type RoomSchedulerDeps, type RoomSchedulerPolicyState, type RoomSchedulerResult, type RoomSchedulerSafetyPolicy, type RoomSchedulerSessionControl, type RoomSchedulerState, RoomService, type RoomServiceDeps, type RoomServiceSessionControl, type RoomSpeakerArbitration, type RoomSpeakerOrder, type RoomSpeakerPolicy, type RoomSpeakerPolicyStatus, type RoomSpeakerPreset, type RoomSpeakerTrigger, type RoomSpeechApplication, type RoomSpeechApplicationDecision, type RoomSpeechIntentCollectorInput, type RoomStalePublishDecision, type RoomState, type RoomStatusSnapshot, RoomStore, type RoomToolAuditEvent, type RoomToolPurpose, type RoomTopicEntry, type RoomTopicSource, type RoomTopicState, type RoomTopicStatus, type RoomTranscriptPayload, type RoomTranscriptRecallQuery, type RoomTranscriptRecallResult, type RoomTranscriptRecallSearchInput, type RoomTranscriptSearchPort, type RoomTranscriptSearchToolInput, type RoomTranscriptSearchToolResult, type RoomTuiEnterResult, RoomTuiFacade, type RoomTuiFacadeDeps, type RoomTuiResolvedHumanActor, type RoomTuiSendResult, type RoomTurnPhase, type RoomUsageFactsSummary, type RoomUsageTotals, type RoomWorkspaceAccess, type RoomWorkspacePolicy, type RoomWorkspacePolicyContext, type RoomWorkspacePolicyDecision, type RoomWorkspacePolicyMember, type RoomWorkspacePolicyRule, type RoomWorkspaceSubject, type RunRoomBenchmarkCaseOptions, type RunRoomBenchmarkSuiteOptions, type RuntimeClockSnapshot, type RuntimeEvent, type RuntimeFastGptKnowledgeSummary, type RuntimeMcpSummary, type RuntimeStatusSnapshot, type SelectRelevantMemoriesInput, type SendTurnInput, type SendTurnResult, type SessionAgentBinding, type SessionBusyMessagesState, type SessionContextMode, SessionControlService, type SessionControlServiceDeps, type SessionCronProposalState, type SessionLease, SessionLeaseManager, type SessionMemoryCompactOptions, type SessionMemorySaveResult, type SessionMemoryState, SessionMemoryStore, type SessionPlanState, RemoteTurnManager as SessionRuntimeHost, type RemoteTurnManagerDeps as SessionRuntimeHostDeps, type SendTurnInput as SessionRuntimeHostSendTurnInput, type SendTurnResult as SessionRuntimeHostSendTurnResult, type TurnCompletion as SessionRuntimeTurnCompletion, type SessionState, type SessionStateSnapshot, type SessionSummarySource, type SessionSummaryState, type SessionTask, type SessionTaskKind, type SessionTaskSummarySnapshot, type SessionTitleSource, type SessionTitleState, SkillCatalog, type SkillComputedState, type SkillDefinition, SkillImportService, type SkillStatusEntry, type SlashCommandExecutionInput, type SlashCommandExecutionResult, SlashCommandRouter, type SlashCommandRouterDeps, type SoulMarkdownFile, type SoulProfile, type SpeakerPolicyCandidate, type SpeakerPolicyDecision, type SpeechIntent, type StagedDreamContext, type SteerTurnInput, type SubAgentRunInput, type SubAgentTaskResult, type SystemPromptBuildInput, type SystemPromptSections, THINKING_DIALECTS, THINKING_LEVELS, THINKING_LEVEL_ORDER, type TaskArtifactRef, type TaskBehaviorMode, type TaskBudgetState, TaskConcurrencyError, type TaskExecutionMode, TaskManager, type TaskManagerPolicy, type TaskNotificationRecord, TaskQueueFullError, type TaskStatus, type TextTranscriptMessage, type ThinkingDialect, type ThinkingLevel, type ThinkingRequestFields, type ToolContext, type ToolDefinition, type ToolExecutionRecord, type ToolInputIssue, type ToolJsonSchema, type ToolResultTokenProfile, type ToolTranscriptMessage, type TrackProgress, type TrackSnapshot, type TrackState, type TrackStep, type TrackStepInput, type TrackStepStatus, TrackStore, type TrackTarget, type TrackTargetPatch, type TrackWritePatch, type TrackWriteResult, type TranscriptMessage, type TranscriptMessageBase, type TurnAttachment, type TurnCompletion, type UsageLimitErrorDetails, UsageLimitExceededError, type UsageSummary, type WebAppConfig, type WebSearchProvider, type WebSearchProviderConfig, type WebSearchProviderRegistry, type WebSearchProviderSearchInput, type WebSearchRegistryConfig, type WebSearchResult, type WorkspaceIdentity, type WorkspaceIdentitySource, type WsServerConfig, addProviderModel, appendBusyCollectMessage, appendFileAttachmentsToText, appendInlineFileAttachmentsToText, appendRecallLog, appendTaskNotification, applyBudgetExhaustedAction, applyHumanRootTopicUpdate, approveCronProposal, assertCronJobCreateValid, assertImageModelSelection, assertProviderSelection, assertRoomActorCan, assertWebSearchProviderSelection, assertWorkspaceRootExists, buildBehaviorPrompt, buildBehaviorSystemPrompt, buildCodexInputItems, buildCompactAttachments, buildCompactRoomBasicContext, buildContextEnvelope, buildContextPressure, buildCronApprovalPreview, buildDreamPrompt, buildMcpToolCapability, buildMemoryHealthReport, buildOpenAIChatMessages, buildPersonaPrompt, buildPlanApprovalPreview, buildProviderSafeMcpToolName, buildRoleAwareRoomDigest, buildRoomApplicationBasicContext, buildRoomBasicContext, buildRoomDiagnostics, buildRoomFactsSummary, buildRoomObservationPrompt, buildRoomPrePublishSelfCheckPrompt, buildRoomRootParticipationLedger, buildRoomSpeechApplicationPrompt, buildRoomSpeechIntentPrompt, buildRoomTranscriptRecallQueryFromBatch, buildSessionMemoryContent, buildSessionSummary, buildSystemPrompt, buildSystemPromptAwareContextPressure, buildSystemPromptExplain, buildSystemPromptSections, buildThinkingRequestFields, buildToolActiveForm, buildToolInputErrorMessage, buildToolInputRepairHint, buildTrackPrompt, bundledSkillRootCandidates, canStartRoomTurn, canTransitionGoal, cancelBusyQueueItem, cancelCronProposal, clampThinkingLevel, classifyProviderError, classifyRoomBenchmarkFailure, cleanupRoomRuntimeState, clearBusyQueue, clearRoomContextCache, collectObservationBatch, collectRoomBenchmarkGitMetadata, collectSpeechApplications, collectSpeechIntents, compactOversizedToolResults, compactSession, completeDreamTask, computeCronNextRunAt, computeJobNextRunAt, computeProgress, computeProviderConfigHash, countVisibleNoopMatches, createAgentProfile, createAgentRuntime, createBashTool, createCodexProvider, createCompactBoundary, createCompactSummaryMessage, createCronProposal, createCronTool, createDefaultAgentBinding, createDefaultConfig, createDefaultRoomBudgetState, createDefaultRoomDraftingPolicy, createDefaultRoomInFlightMessagePolicy, createDefaultRoomSchedulerSafetyPolicy, createDefaultRoomSpeakerPolicy, createDefaultRoomWorkspacePolicy, createDefaultSession, createDefaultTools, createDefaultWebSearchProviderRegistry, createDefaultWebSearchRegistryConfig, createDeterministicSpeechIntent, createDreamRuntime, createDreamSession, createEmptyBusyMessagesState, createEmptyPlanDocument, createEmptyRoomTopicState, createEmptyTrackState, createFastGptKnowledgeAskTool, createFastGptKnowledgeSearchTool, createFastGptKnowledgeSummary, createGatewayCronManagementPort, createGoalDraft, createGoalEvent, createIdleCronProposalState, createInMemoryTool, createInitialRoomPolicyState, createLocalCronManagementPort, createLocalHumanOwnerMember, createManagedAbortController, createMcpSummary, createMentionOnlyRoomSpeakerPolicy, createOpenAICompatibleProvider, createOpenAIResponsesProvider, createPermissionManager, createProviderAdapter, createReadImageTool, createRoomBenchmarkMockRuntime, createRoomTranscriptSearchTool, createRoomWorkspacePolicyRule, createRuntimeClockSnapshot, createRuntimeStatusSnapshot, createSessionAgentBindingFromProfile, createSessionStateSnapshot, createSessionTask, createSessionTaskSummarySnapshot, createTaskBudgetState, createTaskNotification, createTrackTool, decideSpeakerPolicy, deriveAutomaticSessionTitle, deriveRoomRootParticipationContext, describeAttachmentForText, describeBehaviorToolPolicy, describeCronPayload, describeCronSchedule, describeCronTarget, describeDreamToolPolicy, describeMissingPlanFields, describeProviderAuth, describeSession, dialectSupportsThinking, discoverRoomBenchmarkCaseFiles, effortVocabularyForLevels, emitGoalForegroundEvent, enforceSingleInProgress, enqueueBusyQueueItem, ensureSoulProfileFilesSync, estimatePersistedSessionBytes, estimateSessionTokenFootprint, estimateTextTokens, estimateTranscriptMessageTokens, estimateTranscriptTokens, estimateUsageCostUsd, evaluateAutoDreamPolicy, evaluateRoomAdminGovernance, evaluateRoomWorkspacePolicy, executeAutoDream, extractDurableMemoryCandidates, extractMemoryArtifacts, extractRootHandoffPlan, extractUsageLimitError, failDreamTask, filterToolsForBehaviorMode, filterToolsForDreamRuntime, findBuiltinModelPricing, findReferencedImageAttachments, findRoomActorMember, findSessionTask, fingerprintRoomTranscriptRecallQuery, formatBusyCollectPrompt, formatCommandReport, formatFieldLines, formatMemoryHealthReport, formatModelRoutingState, formatNestedFieldLines, formatPersistedSessionBytes, formatRoomMembers, formatRoomRootParticipationForPrompt, formatRoomStatus, formatRoomTopicStateForPrompt, formatRoomTranscriptRecallEvidence, formatSummaryLine, formatSummaryValue, formatThinkingLevels, formatToolInputErrorForDisplay, formatTrackText, generateServerToken, getAgentWorkspacePaths, getAgentsRootDir, getAppHomeDir, getCompactDecision, getConfigPath, getCronPayloadKindLabel, getCronPayloadText, getCurrentProvider, getDefaultAgentDir, getDefaultAutoDreamPolicy, getDefaultBusyMessagePolicy, getDefaultCompactPolicy, getDefaultContextBudget, getDefaultCronStorePath, getDefaultProvider, getDefaultWebSearchProviderConfig, getDreamLockPath, getDreamStatePath, getHostTimezone, getLargestToolResultProfiles, getLegacyTaskArtifactsRoot, getManagedSkillsDir, getMentionedMemberIds, getProvider, getProviderModel, getRecallLogPath, getRemoteCommandCatalog, getRemoteCommandDescriptor, getRoomContextCacheMetrics, getRoomSpeakerPolicyStatus, getRoomsDir, getRootParticipationFirstContributionStatus, getRootParticipationSupplementCount, getRootParticipationTerminalMemberIds, getRootParticipationYourStatus, getSessionDreamLockPath, getSessionDreamStatePath, getSessionDurableMemoryDir, getSessionMemoryArchiveDir, getSessionMemoryDir, getSessionPlansDir, getSessionTaskArtifactDir, getSessionTaskArtifactsRoot, getSessionsDir, getSkillImportSessionsDir, getSoulDir, getSupportedThinkingLevels, getTaskArtifactDir, getTaskArtifactsRoot, getWebSearchProviderConfig, getWebSearchProviderImplementation, getWorkspaceMemoryArchiveDir, getWorkspaceMemoryDir, getWorkspaceMemoryRoot, gradeRoomBenchmarkTurn, hasMaterialRoomLedger, hasPassedConnectivityTest, hasProviderConfigChanged, inferImageMimeType, inferRoomWorkspaceAccess, inferThinkingDialect, isAbortErrorExceptTimeout, isBackgroundTopicSource, isContextOverflowError, isCronWorkflowPayload, isFailoverError, isFallbackSummaryError, isGatewayAuthConfigured, isGenericSessionTitle, isHighFrequencySchedule, isMaterialRoomTranscriptEvent, isProviderAuthConfigured, isProviderModelImageSupported, isRemoteSlashCommandName, isSyncableRoomTranscriptEvent, isTerminalGoalStatus, isToolAllowedInBehaviorMode, isTrackEmpty, isWebGatewayAuthConfigured, isWebSearchAuthConfigured, isWsServerAuthConfigured, levelsForEffortVocabulary, limitRelevantMemories, listAgentProfiles, listProviders, listWebSearchProviderConfigs, loadAppConfig, loadImageAttachmentDataUrl, loadRoomBenchmarkCase, loadRoomBenchmarkCases, loadSoulProfileForSession, loadSoulProfileSync, mapLevelToEffort, mapMcpToolRisk, mapThinkingLevelToReasoningEffort, markCronProposalReady, markSessionPlanApproved, markSessionPlanCancelled, markSessionPlanDraft, markSessionPlanReadyForApproval, markSessionTitleManual, materializeInlineTurnAttachments, measureRoomSpeechApplicationPrompt, mergePlanDocument, mergeTarget, needsOnboarding, normalizeAppConfig, normalizeBusyMessagesState, normalizeCronProposalState, normalizeLiteToolRequestName, normalizeLiteToolRequestNames, normalizeRoomBudgetState, normalizeRoomSpeakerPolicy, normalizeRoomTopicState, normalizeRoomWorkspacePolicy, normalizeSessionState, normalizeSessionTitleState, normalizeStep, normalizeSteps, normalizeSupportedThinkingLevels, normalizeThinkingDialect, normalizeThinkingLevel, normalizeThinkingLevelOrNull, normalizeTurnAttachments, packContext, parseCronAt, parseCronExpression, parseInlineThinkingDirective, parsePrePublishSelfCheckDecisionText, parseRoomBenchmarkCase, parseSlashInput, parseSpeechApplicationDecisionText, parseSpeechIntentDecisionText, parseToolInputIssues, postCompactCleanup, proposalToJobCreate, reactiveCompact, readAutoDreamState, readDreamLock, readRecallLog, readSessionAutoDreamState, readSessionDreamLock, recordBusySteer, recordRoomTurnStarted, recordRoomTurnUsage, recordRoomUsageDelta, refreshAutomaticSessionTitle, refreshTopicActivity, registerDreamTask, renderMemoryColdSection, renderMemoryDreamSection, renderMemoryHotSection, reorderBusyQueueItems, resetRoomContextCacheMetrics, resolveAgentProfile, resolveBundledSkillRoot, resolveBusyMessagePolicy, resolveCodexAuthFile, resolveContextWindow, resolveCronTimezone, resolveEffectiveThinkingLevel, resolveFallbackChain, resolveGatewayAuthToken, resolveImageAttachmentPath, resolveLiteSettings, resolveMaxTurns, resolveModelEffortVocabulary, resolveModelPricingFromConfig, resolveModelReasoning, resolveModelRoutingEnabled, resolveModelSupportedThinkingLevels, resolveNextPlannedSpeaker, resolveProviderApiKey, resolveProviderAuth, resolveRoomBenchmarkStatus, resolveSessionModelApiType, resolveSkillSource, resolveTaskManagerPolicy, resolveThinkingBudgetTokens, resolveThinkingDefaultLevel, resolveWebGatewayAuthToken, resolveWebSearchApiKey, resolveWorkspaceIdentity, resolveWsServerAuthToken, roomBenchmarkAgentMemberSchema, roomBenchmarkCaseSchema, roomBenchmarkExpectationSchema, roomBenchmarkHumanMemberSchema, roomBenchmarkMembersSchema, roomBenchmarkMessageSchema, roomBenchmarkMetricsThresholdsSchema, roomBenchmarkMockFailureSchema, roomBenchmarkMockMemberSchema, roomBenchmarkMockRuntimeSchema, roomBenchmarkRuntimeModeSchema, roomBenchmarkSpeakerPolicySchema, roomBenchmarkSpeakerPolicySettingsSchema, roomIdentityCompact, roomMemberHasCapability, runManagedChildSessionRuntime, runRoomBenchmarkCase, runRoomBenchmarkSuite, runSubAgentTask, sanitizeTrackState, saveAppConfig, scoreRoomBenchmark, searchRoomTranscript, selectNextBusyMessageForDrain, selectRelevantMemories, selectSpeaker, selectSpeechApplications, selectSpeechIntent, sessionMemoryCompact, setDefaultProvider, setProviderDefaultModel, shouldCompactSession, shouldLoadMcpToolsForLiteRequests, shouldRecallRoomTranscriptForText, shouldTriggerOnboarding, splitTransientProviderMessages, stageDreamContext, subjectMatchesMember, summarizeBusyMessages, summarizeCronRunStatus, summarizeGoalForegroundText, summarizeRoomBenchmarkControlEvents, summarizeRoomBenchmarkMetrics, summarizeRoomRuntime, summarizeSessionTasks, summarizeToolInputIssue, syncRoomEventsToSession, toFailoverError, toWorkspaceRelativeSnapshotDir, transitionGoal, trimSessionMemoryContent, uniqueFailureTypes, updateBusyDrainStatus, updateBusySteerStatus, updateDreamTaskPhase, updateOnboardingState, updateRoomDigest, updateSessionTask, validateCronJobCreate, validateCronSchedule, validateCronTimezone, validateGoalContract, validatePlanDocument, writeAutoDreamState, writeRoomBenchmarkCaseArtifacts, writeRoomBenchmarkSuiteArtifacts, writeTaskArtifacts };