import type { AppContext, ComputerControlService, ClientSession, LoopGuardSettings, MoxxyEvent, Principal, ReasoningEffort, RunTurnOptions, SessionId, SessionInfo, GovernanceInfo } from '@moxxy/sdk'; import { newTurnId } from './events/factory.js'; import type { SessionRuntime } from './session-runtime.js'; import { EventLog } from './events/log.js'; import { SessionQuestionsImpl } from './questions/session-questions.js'; import { HookDispatcherImpl } from './plugins/lifecycle.js'; import { PluginHost, type PluginLoader } from './plugins/host.js'; import { ProviderRegistry } from './registries/providers.js'; import { ModeRegistry } from './registries/modes.js'; import { CacheStrategyRegistry } from './registries/cache-strategies.js'; import { ViewRendererRegistry } from './registries/view-renderers.js'; import { TunnelProviderRegistry } from './registries/tunnel-providers.js'; import { CompactorRegistry } from './registries/compactors.js'; import { ChannelRegistryImpl } from './registries/channels.js'; import { SurfaceRegistryImpl } from './registries/surfaces.js'; import { SurfaceHostImpl } from './surfaces/host.js'; import { SkillRegistryImpl } from './registries/skills.js'; import { type ToolRegistry } from './registries/tools.js'; import { AgentRegistry } from './registries/agents.js'; import { CommandRegistry } from './registries/commands.js'; import { TranscriberRegistry } from './registries/transcribers.js'; import { SynthesizerRegistry } from './registries/synthesizers.js'; import { EmbedderRegistry } from './registries/embedders.js'; import { IsolatorRegistry } from './registries/isolators.js'; import { WorkflowExecutorRegistry } from './registries/workflow-executors.js'; import { EventStoreRegistry } from './registries/event-stores.js'; import { AuditExporterRegistry } from './registries/audit-exporters.js'; import { AuditSinkRegistry } from './registries/audit-sinks.js'; import { SecretProviderRegistry } from './registries/secret-providers.js'; import { ReflectorRegistry } from './registries/reflectors.js'; import { ServiceRegistryImpl } from './registries/services.js'; import { RequirementRegistry } from './requirements.js'; import { PermissionEngine } from './permissions/engine.js'; import type { ApprovalResolver, CredentialResolver, ElisionSettings, McpAdminView, ProviderAdminView, WorkflowsView, PluginsAdminView, ProviderSetupView, SessionLike, PermissionResolver } from '@moxxy/sdk'; import { type Logger } from './logger.js'; import { AgentCliWatch } from './agent-cli-watch.js'; export interface SessionOptions { readonly cwd: string; readonly logger?: Logger; readonly sessionId?: SessionId; readonly permissionEngine?: PermissionEngine; readonly permissionResolver?: PermissionResolver; readonly hookTimeoutMs?: number; readonly silent?: boolean; /** Organization policy summary rendered by local and remote clients. */ readonly governance?: GovernanceInfo; /** * Optional plugin loader. When provided, `session.pluginHost.discoverAndLoad()` * can dynamic-import discovered plugins; without one, only static plugins * registered via `registerStatic()` are wired up. */ readonly pluginLoader?: PluginLoader; /** * Extra directories to scan for plugins, on top of the cwd-rooted * `node_modules` walk. The CLI sets this to `~/.moxxy/plugins` (and its * `node_modules` subtree) so runtime-installed / scaffolded plugins are * discoverable. Crucially these are remembered by the host and reused on * `pluginHost.reload()`, so a hot-reload neither drops user plugins nor * fails to pick up freshly written ones. */ readonly pluginDiscoveryPaths?: ReadonlyArray; /** * Predicate (by package name) for whether a discovered plugin is disabled. * Forwarded to the PluginHost so `pluginHost.reload()` never resurrects a * plugin the user turned off via config `plugins[name].enabled = false`. * Reads live state, so a runtime enable/disable applies on the next reload. */ readonly isPluginDisabled?: (packageName: string) => boolean; /** * Vault-backed secret resolver. When provided, every tool handler gets * `ctx.getSecret(name)` so plugins can read an API key / token at call * time. The plaintext never enters the model's context or `process.env`; * only the handler that asks receives it. The CLI/runner wires this to * the session vault's `get`. */ readonly secretResolver?: (name: string) => Promise; /** * Pre-seeded event log. Used by `moxxy resume` to restore the * conversation from a persisted JSONL. Subscribers don't re-fire for * seeded events (the constructor pushes them directly), so plugin * hooks won't run for historical entries. */ readonly log?: EventLog; } export declare class Session implements ClientSession, SessionRuntime { readonly id: SessionId; readonly cwd: string; readonly log: EventLog; /** Questions the agent asks the person, recorded in {@link log} (see `SessionQuestionsImpl`). */ readonly questions: SessionQuestionsImpl; readonly logger: Logger; readonly governance?: GovernanceInfo; readonly tools: ToolRegistry; readonly providers: ProviderRegistry; /** Where each agent connection's CLI stands; a long-lived host calls `start()` on it. */ readonly agentClis: AgentCliWatch; readonly modes: ModeRegistry; readonly compactors: CompactorRegistry; readonly cacheStrategies: CacheStrategyRegistry; readonly viewRenderers: ViewRendererRegistry; readonly tunnelProviders: TunnelProviderRegistry; readonly channels: ChannelRegistryImpl; /** Registry of surface defs (terminal, browser, …) contributed by plugins. */ readonly surfaceRegistry: SurfaceRegistryImpl; /** * Manages the live, open surface instances for this session. The runner * drives it for thin clients; the agent's tools reach the same resources via * plugin module state. See {@link SurfaceHostImpl}. */ readonly surfaces: SurfaceHostImpl; readonly skills: SkillRegistryImpl; readonly agents: AgentRegistry; readonly commands: CommandRegistry; readonly transcribers: TranscriberRegistry; readonly synthesizers: SynthesizerRegistry; readonly embedders: EmbedderRegistry; readonly isolators: IsolatorRegistry; readonly workflowExecutors: WorkflowExecutorRegistry; readonly eventStores: EventStoreRegistry; readonly auditSinks: AuditSinkRegistry; readonly auditExporters: AuditExporterRegistry; /** * Resolve a named secret, through whatever SecretProvider the host wired. * The same function tool handlers receive as `ctx.getSecret`; exposed here so * a HOST-side caller (resolving a credential for an internal registry, say) * goes through the active provider instead of reaching past it to the vault. * Undefined when no resolver was supplied. */ readonly resolveSecret?: (name: string) => Promise; /** External secret stores. No core floor: the vault is a plugin, so the * host registers it as the protected floor at boot. */ readonly secretProviders: SecretProviderRegistry; /** * The learning-loop block: watches finished turns and proposes memory/skill * improvements. NULLABLE — no core-seeded floor, so it stays empty until a * reflector plugin (e.g. @moxxy/reflector-default) registers one. */ readonly reflectors: ReflectorRegistry; /** Inter-plugin service registry — plugins publish/consume services in onInit. */ readonly services: ServiceRegistryImpl; readonly requirements: RequirementRegistry; readonly permissions: PermissionEngine; /** Current PermissionResolver. Update via `setPermissionResolver(r)`. */ resolver: PermissionResolver; /** * Optional generic approval resolver. Loop strategies use this to ask * the user a checkpoint question (plan validation, command preview, * diff review, etc.). Null when running headless or before the TUI * registers one — strategies that have no resolver simply skip the * approval step. */ approvalResolver: ApprovalResolver | null; /** * Elision (context-on-demand) settings, resolved from `config.context.elision` * at setup and updated on config reload. Null → built-in defaults apply * (elision on). Read into each turn's ModeContext. */ elisionSettings: ElisionSettings | null; /** Lazy tool loading, from `config.context.lazyTools`. Unset = automatic (on for a long tool list). */ lazyTools: boolean | undefined; /** The end-of-turn reminder about a step that did not get done, from `config.context.unfinishedStepCheck`. Unset = on. */ unfinishedStepCheck: boolean | undefined; /** * Reasoning/thinking preference, from `config.context.reasoning`. Forwarded * to each turn's ModeContext and on to the provider, which honors it only * when the active model advertises `supportsReasoning`. Undefined → off. */ reasoning: { readonly effort?: ReasoningEffort; } | boolean | undefined; /** Ask for the provider's faster tier (OpenAI fast mode), from `config.context.fast`. */ fast: boolean; /** * Stuck-loop guard tuning, from `config.context.loopGuard`. Forwarded to each * turn's ModeContext and on to the mode's stuck-loop detector. Undefined → * the detector's defaults. */ loopGuard: LoopGuardSettings | undefined; /** * Model id resolved by the most recent `runTurn()` (see SessionRuntime). * Last-writer-wins for concurrent turns; null until the first turn runs. */ lastResolvedModel: string | null; lastResolvedProvider: string | null; /** The model each provider is set to run when a turn names none, from `plugins.provider.items..model`. */ defaultModels: Readonly>; /** * Live runtime capabilities the host installs on a local Session (see * SessionLike). A RemoteSession leaves them undefined. Declared here — rather * than monkey-patched on via `as unknown as` — so the host and channels get * type-checked access. */ readyProviders?: Set; credentialResolver?: CredentialResolver; workflows?: WorkflowsView; pluginsAdmin?: PluginsAdminView; providerSetup?: ProviderSetupView; configAdmin?: SessionLike['configAdmin']; readonly dispatcher: HookDispatcherImpl; readonly pluginHost: PluginHost; private readonly controller; constructor(opts: SessionOptions); get signal(): AbortSignal; abort(reason?: string): void; /** * Swap the active PermissionResolver. Channels call this after they're * constructed so the session uses the channel's interactive resolver * (TUI prompt, Telegram inline keyboard, HTTP allow-list, etc.). * Replaces the previous monkey-patching of the private `resolver` field * from CLI command code. */ setPermissionResolver(resolver: PermissionResolver): void; /** Whether tool calls run without asking: a fold over the log, so a reset * conversation starts with it off and a resumed one keeps its last switch. */ get autoApprove(): boolean; /** Switch auto-approve for this conversation. Recorded in the log so every * attached client (desktop, TUI, channel bot) sees the same state. */ setAutoApprove(enabled: boolean): Promise; /** Install/replace the generic approval resolver. Pass null to clear. */ setApprovalResolver(resolver: ApprovalResolver | null): void; /** * Attribute everything this session appends to `principal`. * * Set by whoever owns the surface and can actually vouch for the identity: * the CLI resolves the OS account, an authenticated channel resolves its * token's subject. Core never guesses one, because an identity core invented * would be worth nothing to an auditor. * * Pass `undefined` to go back to unattributed, which is what a surface with * no notion of a user should do rather than inventing a placeholder. */ setPrincipal(principal: Principal | undefined): void; /** The identity this session currently attributes to, if any. */ get principal(): Principal | undefined; /** * `SessionLike.reset` — the authoritative `/new`. Clears the event log; * the log's clear listeners propagate the wipe to whatever observes it * (the persistence sidecar truncates its JSONL so `--resume` sees an * empty session; a wrapping RunnerServer broadcasts a reset so attached * mirrors clear in lockstep). Registries, resolvers, and the active * provider survive — only the conversation context vanishes. Callers * must abort any in-flight turn first (same contract as `log.clear()`). */ reset(): Promise; /** * Graceful shutdown: cancel in-flight work before awaiting plugin shutdown * hooks. Idempotent — safe to call multiple times (subsequent * calls are no-ops once `closed` is set). * * Channels' SIGINT handlers should call this before exiting so plugins * can flush state (memory journal, vault, audit logs, etc.). */ close(reason?: string): Promise; private closed; /** * Memoized one-time snapshot of `process.env`. `appContext()` is called per * dispatched event (hundreds per turn during a streaming reply), per turn, * and on every shutdown — eagerly spreading the whole env each time is * thousands of O(envVars) clones of GC pressure for a value that does not * change over a session's life. Frozen so a plugin can't mutate the shared * snapshot out from under another. */ private envSnapshot; /** * The provider-admin capability (configure/refresh stored providers), read by * the runner's provider handlers + the desktop. The @moxxy/plugin-provider-admin * plugin publishes it on the service registry in its onInit, so discovery-loading * it needs no host stash. (RemoteSession sets its own field for thin clients.) */ get providerAdmin(): ProviderAdminView | undefined; get computerControl(): ComputerControlService | undefined; /** * The MCP-admin capability (enable/detach/list MCP servers), read by the * runner's mcp handlers + the desktop. @moxxy/plugin-mcp publishes it on the * service registry in its onInit. (RemoteSession sets its own field.) */ get mcpAdmin(): McpAdminView | undefined; appContext(): AppContext; startTurn(): { turnId: ReturnType; }; subscribe(fn: (e: MoxxyEvent) => void | Promise): () => void; /** * Drive one turn against this session. Method form of the `runTurn` free * function so a local `Session` satisfies `SessionLike` (the channel-facing * contract a `RemoteSession` proxy also implements). */ runTurn(prompt: string, opts?: RunTurnOptions): AsyncIterable; private readonly stopWatchingAgentTurns; private readonly stopAdoptingOwnAutoApprove; /** * The person's switch stands on every connection the conversation goes to. * Until they choose, the auto-approve is the active agent's own setup * (`ProviderDef.ownAutoApprove`), recorded as the system's, and that is not * handed on: a connection whose settings say nothing goes back to asking. * Another connection made active meanwhile wins. */ private adoptOwnAutoApprove; private personChoseAutoApprove; /** * The agent of an agent connection started a turn by itself: run it as a * turn of this conversation, marked as the agent's, so every client sees * it in the log like any turn. Goes through `this.runTurn`, so a host that * wraps it (the runner, to list and stop running turns) sees this one too. */ private takeUpAgentTurn; private runAgentTurn; /** What the agent reported of its background work, recorded one report after another. */ private recordingActivity; /** * What the agent runs in the background now, as it last said. Held here, not * read from the log: an agent does not outlive the process that ran it, so a * restarted runner starts with nothing running whatever the log says. */ private runningWork; /** When the agent set itself to come back by itself, as it last said; like `runningWork`, gone with the process. */ private scheduledWakeups; private readonly workListeners; /** The agent's helpers between turns, by id, to name them in what they do later. */ private readonly agentHelpers; /** * What the agent's background work did while no turn ran, recorded at once * the way a turn records it, so every surface shows it as it happens. */ private recordAgentActivity; /** * Stop one work the conversation's agent runs in the background * (`AgentBackgroundWork.id`). `false` when the agent runs no such work, or * its connection cannot stop it. */ stopBackgroundWork(workId: string): Promise; /** * Wire-friendly snapshot of the registries for channels to render. Mirrors * what a `RemoteSession` fetches from the runner over RPC - keep the two in * sync. */ /** * Called with the new info when it changes outside the log: an agent * connection's CLI was found missing, outdated or updated, or what its agent * runs in the background changed. Returns the unsubscribe. */ onInfoChanged(listener: (info: SessionInfo) => void): () => void; /** * The reasoning a turn runs with. An agent connection always thinks, so it * has no "off": one without an effort set runs at low, its lowest level. */ turnReasoning(): Session['reasoning']; private activeIsAgentConnection; getInfo(): SessionInfo; } //# sourceMappingURL=session.d.ts.map