import { realpath } from 'node:fs/promises'; import { isAbsolute, relative, resolve, sep } from 'node:path'; import type { AgentActivity, AgentBackgroundWork, AgentScheduledWakeup, AgentTurnStart, SubagentNames, AppContext, ComputerControlService, ClientSession, EmittedEvent, LoopGuardSettings, MoxxyEvent, Principal, ReasoningEffort, RunTurnOptions, SessionId, SessionInfo, GovernanceInfo, LLMProvider, } from '@moxxy/sdk'; import { newSessionId, newTurnId } from './events/factory.js'; import { runTurn as runTurnImpl } from './run-turn.js'; import type { SessionRuntime } from './session-runtime.js'; import { resolveTurnModel } from './turn-model.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 { defaultViewRenderer } from './view/default-renderer.js'; import { TunnelProviderRegistry } from './registries/tunnel-providers.js'; import { localhostTunnel } from './tunnel/localhost.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 { ToolRegistryImpl, 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 { jsonlAuditSink } from './audit/jsonl-audit-sink.js'; import { ReflectorRegistry } from './registries/reflectors.js'; import { ServiceRegistryImpl } from './registries/services.js'; import { jsonlEventStore } from './sessions/jsonl-event-store.js'; import { RequirementRegistry } from './requirements.js'; import { PermissionEngine } from './permissions/engine.js'; import { autoAllowResolver } from './permissions/resolvers.js'; import { currentPermissionScope } from './permissions/scope.js'; import { agentActivityRecord, AUTO_APPROVE_PLUGIN_ID, AUTO_APPROVE_SUBTYPE, recordedContextWindows, withRecordedContextWindows, autoApproveFromEvents, autoApproveFromAgent, autoApproveRecorded, evaluateToolRule, isSelectableMode, } from '@moxxy/sdk'; import type { ApprovalResolver, CredentialResolver, ElisionSettings, McpAdminView, ProviderAdminView, WorkflowsView, PluginsAdminView, ProviderSetupView, SessionLike, PendingToolCall, PermissionContext, PermissionDecision, PermissionResolver, PermissionRule, } from '@moxxy/sdk'; import { createLogger, silentLogger, type Logger } from './logger.js'; import { clearRetainedChildren } from './subagents/registry.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 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 = 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 = null; /** Lazy tool loading, from `config.context.lazyTools`. Unset = automatic (on for a long tool list). */ lazyTools: boolean | undefined = undefined; /** The end-of-turn reminder about a step that did not get done, from `config.context.unfinishedStepCheck`. Unset = on. */ unfinishedStepCheck: boolean | undefined = 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 = undefined; /** Ask for the provider's faster tier (OpenAI fast mode), from `config.context.fast`. */ fast = false; /** * 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 = 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 = null; lastResolvedProvider: string | null = 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 = new AbortController(); constructor(opts: SessionOptions) { this.id = opts.sessionId ?? newSessionId(); this.cwd = opts.cwd; this.logger = opts.logger ?? (opts.silent ? silentLogger : createLogger()); if (opts.governance) this.governance = Object.freeze({ ...opts.governance }); this.log = opts.log ?? new EventLog(); this.questions = new SessionQuestionsImpl({ log: this.log, sessionId: this.id }); if (opts.log) { this.questions.closeLeftOver().catch((err: unknown) => { this.logger.warn('could not close questions left open by an earlier run', { err: String(err) }); }); } this.tools = new ToolRegistryImpl({ logger: this.logger, cwd: this.cwd, ...(opts.secretResolver ? { secretResolver: opts.secretResolver } : {}), questionAsker: this.questions.ask, }); if (opts.secretResolver) this.resolveSecret = opts.secretResolver; this.providers = new ProviderRegistry(); this.agentClis = new AgentCliWatch(() => this.providers.list(), this.logger); const stopTakingUp = this.providers.onAgentTurn((start) => this.takeUpAgentTurn(start)); // One after another, so the log keeps the order the agent reported them in. const stopRecording = this.providers.onAgentActivity((activity) => { this.recordingActivity = this.recordingActivity.then(() => this.recordAgentActivity(activity)).catch((err: unknown) => { this.logger.warn('recording the agent background work failed', { error: err instanceof Error ? err.message : String(err) }); }); }); this.stopWatchingAgentTurns = () => { stopTakingUp(); stopRecording(); }; // A conversation on an agent connection shows how the agent really runs from the first moment. const stopAdopting = this.providers.onActiveChange(() => void this.adoptOwnAutoApprove()); const stopAdoptingOnClear = this.log.onClear(() => void this.adoptOwnAutoApprove()); this.stopAdoptingOwnAutoApprove = () => { stopAdopting(); stopAdoptingOnClear(); }; // `/new` (here or through the runner) starts a new conversation: the model the // old one ran on no longer comes first, the chosen default or the starter does. this.log.onClear(() => { this.lastResolvedModel = null; this.lastResolvedProvider = null; }); this.modes = new ModeRegistry(); this.compactors = new CompactorRegistry(); this.cacheStrategies = new CacheStrategyRegistry(); this.viewRenderers = new ViewRendererRegistry(); // Seed the built-in renderer as the protected floor so `present_view` // always has one to parse with; plugins can register/replace and // `setActive` an alternative, but it can never be removed (reverts here). this.viewRenderers.register(defaultViewRenderer, { protected: true }); this.tunnelProviders = new TunnelProviderRegistry(); // Seed the no-op localhost provider as the protected floor so the web // surface always resolves a URL; plugins (the proxy relay) register/ // setActive a real tunnel, reverting here if it's removed. this.tunnelProviders.register(localhostTunnel, { protected: true }); this.channels = new ChannelRegistryImpl(); this.surfaceRegistry = new SurfaceRegistryImpl(); this.surfaces = new SurfaceHostImpl(this.surfaceRegistry, { cwd: this.cwd, logger: this.logger }, this.logger); this.skills = new SkillRegistryImpl(); this.agents = new AgentRegistry(); this.commands = new CommandRegistry(); this.transcribers = new TranscriberRegistry(); this.synthesizers = new SynthesizerRegistry({ ...(opts.secretResolver ? { secretResolver: opts.secretResolver } : {}), }); this.embedders = new EmbedderRegistry(); this.isolators = new IsolatorRegistry(); this.workflowExecutors = new WorkflowExecutorRegistry(); this.services = new ServiceRegistryImpl(); // Publish the core registries on the inter-plugin service registry under // well-known names, so a discovery-loaded plugin can resolve one in its // onInit (typed as the SDK's minimal NamedRegistry) instead of being // hand-built with a `() => session.` closure. The registry // objects are stable; their contents grow as plugins register — consumers // read them lazily at tool-call time, after all registration has run. this.services.register('agents', this.agents); this.services.register('tools', this.tools); this.services.register('providers', this.providers); this.services.register('viewRenderers', this.viewRenderers); this.services.register('synthesizers', this.synthesizers); this.services.register('skills', this.skills); this.services.register('tunnelProviders', this.tunnelProviders); // The memory plugin (discovery-loadable) resolves its lazy embedder here. this.services.register('embedders', this.embedders); // A stable accessor for the active provider's stored credentials. The // resolver itself is installed late (by activateProvider, after plugins are // built), so close over `this` and read it lazily at call time — lets // provider-admin rebuild a reconfigured provider's instance without a // host-injected `resolveActiveConfig` closure. this.services.register( 'resolveCredentials', (name: string): Promise> | Record => this.credentialResolver ? this.credentialResolver(name) : {}, ); // A live registry-name snapshot (per kind) + a writable event-append fn, for // plugins (self-update) that need them in onInit without a host closure. // appendEvent is the writable counterpart to the read-only `ctx.log`. this.services.register('registrySnapshot', () => ({ tools: this.tools.list().map((t) => t.name), agents: this.agents.list().map((a) => a.name), providers: this.providers.list().map((p) => p.name), modes: this.modes.list().filter(isSelectableMode).map((m) => m.name), compactors: this.compactors.list().map((c) => c.name), channels: this.channels.list().map((c) => c.name), })); this.services.register( 'appendEvent', (event: EmittedEvent): Promise => this.log.append(event).then(() => undefined), ); this.eventStores = new EventStoreRegistry(); // Seed the built-in JSONL store as the protected floor — the storage backend // behind the event log always exists and can be swapped but never removed. this.eventStores.register(jsonlEventStore, { protected: true }); this.auditSinks = new AuditSinkRegistry(); this.auditExporters = new AuditExporterRegistry(); // The hash-chained local sink is the protected floor. A discovered plugin's // sink registers alongside it but never auto-activates: a sink's whole job // is to send recorded actions somewhere else, so silent adoption would be // an exfiltration path wearing a compliance hat. this.auditSinks.register(jsonlAuditSink, { protected: true }); this.secretProviders = new SecretProviderRegistry(); // Reflectors are nullable — no core floor is seeded, so reflection stays off // until a reflector plugin registers one. Published on the service registry // so a discovery-loaded driver (the reflector plugin's own hooks) can resolve // the active reflector in onTurnEnd without importing @moxxy/core. this.reflectors = new ReflectorRegistry(); this.services.register('reflectors', this.reflectors); this.requirements = new RequirementRegistry({ tools: this.tools, providers: this.providers, modes: this.modes, compactors: this.compactors, channels: this.channels, agents: this.agents, commands: this.commands, transcribers: this.transcribers, synthesizers: this.synthesizers, }); this.permissions = opts.permissionEngine ?? new PermissionEngine(); // Always wrap the user-supplied resolver with the persistent // policy engine, so saved `allow_always` / `deny` rules from // ~/.moxxy/permissions.json short-circuit the resolver's prompt // path. Without this wrap the engine is dead weight — the // permissions JSON updates on every "allow always" click but no // future turn ever consults it. this.resolver = wrapWithPolicy( opts.permissionResolver ?? autoAllowResolver, this.permissions, (name) => this.tools.get(name)?.permission, this.cwd, () => this.autoApprove, ); this.dispatcher = new HookDispatcherImpl({ logger: this.logger, hookTimeoutMs: opts.hookTimeoutMs, }); this.pluginHost = new PluginHost({ cwd: this.cwd, logger: this.logger, tools: this.tools, providers: this.providers, modes: this.modes, compactors: this.compactors, cacheStrategies: this.cacheStrategies, viewRenderers: this.viewRenderers, tunnelProviders: this.tunnelProviders, channels: this.channels, surfaces: this.surfaceRegistry, agents: this.agents, commands: this.commands, transcribers: this.transcribers, synthesizers: this.synthesizers, embedders: this.embedders, isolators: this.isolators, workflowExecutors: this.workflowExecutors, eventStores: this.eventStores, auditSinks: this.auditSinks, auditExporters: this.auditExporters, secretProviders: this.secretProviders, reflectors: this.reflectors, requirements: this.requirements, dispatcher: this.dispatcher, loader: opts.pluginLoader, ...(opts.pluginDiscoveryPaths ? { userPaths: opts.pluginDiscoveryPaths } : {}), ...(opts.isPluginDisabled ? { isDisabled: opts.isPluginDisabled } : {}), }); // Published after construction (the host is built late) so a discovery-loaded // plugin (self-update) can reach reload/unload/listSkipped in its onInit. this.services.register('pluginHost', this.pluginHost); // Fan every appended event out to plugin `onEvent` hooks. Without this // wiring the hook is dead code — declared on the SDK, dispatched by // HookDispatcherImpl, but nothing ever calls dispatchEvent. this.log.subscribe((event) => { // appContext() clones the whole process.env; only pay that per-event cost // when a plugin actually has an onEvent hook to receive it. With none, // dispatchEvent would iterate an empty hook list anyway. if (!this.dispatcher.hasEventHooks()) return; return this.dispatcher.dispatchEvent(event, this.appContext()); }); } get signal(): AbortSignal { return this.controller.signal; } abort(reason = 'user-requested abort'): void { this.controller.abort(reason); } /** * 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 { // Re-wrap so policy rules continue to short-circuit prompts when a // channel installs its own resolver mid-session. this.resolver = wrapWithPolicy( resolver, this.permissions, (name) => this.tools.get(name)?.permission, this.cwd, () => this.autoApprove, ); } /** 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 { return autoApproveFromEvents(this.log.slice()); } /** Switch auto-approve for this conversation. Recorded in the log so every * attached client (desktop, TUI, channel bot) sees the same state. */ async setAutoApprove(enabled: boolean): Promise { if (this.autoApprove === enabled) return; await this.log.append({ type: 'plugin_event', sessionId: this.id, turnId: newTurnId(), source: 'user', pluginId: AUTO_APPROVE_PLUGIN_ID, subtype: AUTO_APPROVE_SUBTYPE, payload: { enabled }, }); } /** Install/replace the generic approval resolver. Pass null to clear. */ setApprovalResolver(resolver: ApprovalResolver | null): void { this.approvalResolver = resolver; } /** * 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 { this.log.setPrincipal(principal); } /** The identity this session currently attributes to, if any. */ get principal(): Principal | undefined { return this.log.getPrincipal(); } /** * `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()`). */ async reset(): Promise { this.log.clear(); } /** * 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.). */ async close(reason = 'shutdown'): Promise { if (this.closed) return; this.closed = true; this.stopWatchingAgentTurns(); this.stopAdoptingOwnAutoApprove(); this.agentClis.stop(); // Stop deferred approvals/provider calls before disposers await them. this.abort(reason); try { // Tear down any open surfaces (PTYs, browser screencasts) before the // plugin shutdown hooks dispose their underlying resources. Isolated in // its own try/catch: a flaky native surface throwing during teardown must // not pre-empt the plugin shutdown hooks below, which are how plugins // flush state (memory journal, vault, audit logs). try { await this.surfaces.closeAll(); } catch (err) { this.logger.warn('surface teardown failed during close', { error: err instanceof Error ? err.message : String(err), }); } await this.dispatcher.dispatchShutdown(this.appContext()); } finally { // Drop THIS session's retained child sessions (the workflow `awaitInput` // flow keeps them in a process-local registry until a // `continue()`/`release()`). A paused run that never resumes would // otherwise pin them for the whole process lifetime — release them on // shutdown so they don't leak. Scoped to this session's id so closing one // session never wipes another live session's paused children. clearRetainedChildren(this.id); this.abort(reason); } } private closed = false; /** * 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: Readonly | null = null; /** * 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 { return this.services.get('providerAdmin'); } get computerControl(): ComputerControlService | undefined { return this.services.get('computerControl'); } /** * 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 { return this.services.get('mcpAdmin'); } appContext(): AppContext { if (!this.envSnapshot) { this.envSnapshot = Object.freeze({ ...process.env }); } // Read the principal per call rather than caching it with `envSnapshot`: // a channel can re-attribute mid-session (a second user pairs, a token // rotates) and a hook must see the identity in force NOW. const actor = this.log.getPrincipal(); return { sessionId: this.id, cwd: this.cwd, log: this.log.asReader(), env: this.envSnapshot, services: this.services, ...(actor ? { actor } : {}), }; } startTurn(): { turnId: ReturnType } { return { turnId: newTurnId() }; } subscribe(fn: (e: MoxxyEvent) => void | Promise): () => void { return this.log.subscribe(fn); } /** * 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 { return runTurnImpl(this, prompt, opts); } private readonly stopWatchingAgentTurns: () => void; private readonly stopAdoptingOwnAutoApprove: () => void; /** * 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 async adoptOwnAutoApprove(): Promise { const name = this.providers.getActiveName(); const def = this.providers.list().find((p) => p.name === name); if (this.personChoseAutoApprove()) return; let own: boolean | undefined; if (def?.ownAutoApprove) { try { own = await def.ownAutoApprove({ cwd: this.cwd }); } catch (err) { this.logger.warn('could not read how the agent runs on its own', { provider: name, err: String(err) }); } } // An agent whose own settings say nothing does not take over another agent's. own ??= autoApproveFromAgent(this.log.slice()) ? false : undefined; if (own === undefined || own === this.autoApprove || this.closed) return; if (this.providers.getActiveName() !== name || this.personChoseAutoApprove()) return; await this.log.append({ type: 'plugin_event', sessionId: this.id, turnId: newTurnId(), source: 'system', pluginId: AUTO_APPROVE_PLUGIN_ID, subtype: AUTO_APPROVE_SUBTYPE, payload: { enabled: own }, }); } private personChoseAutoApprove(): boolean { const events = this.log.slice(); return autoApproveRecorded(events) && !autoApproveFromAgent(events); } /** * 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(start: AgentTurnStart): void { if (this.closed || start.sessionId !== String(this.id)) return; // What the agent reported of its background work before taking the turn up goes in the log first. void this.recordingActivity.then(() => this.runAgentTurn(start)); } private runAgentTurn(start: AgentTurnStart): void { if (this.closed) return; const turn = this.runTurn(start.name, { origin: { kind: 'agent', name: start.name, ...(start.workId ? { workId: start.workId } : {}) } }); void (async () => { try { for await (const _event of turn) { // Every client reads the turn from the log. } } catch (err) { this.logger.error('a turn the agent started by itself failed', { error: err instanceof Error ? err.message : String(err) }); } })(); } /** What the agent reported of its background work, recorded one report after another. */ private recordingActivity: Promise = Promise.resolve(); /** * 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: ReadonlyArray = []; /** When the agent set itself to come back by itself, as it last said; like `runningWork`, gone with the process. */ private scheduledWakeups: ReadonlyArray = []; private readonly workListeners = new Set<() => void>(); /** The agent's helpers between turns, by id, to name them in what they do later. */ private readonly agentHelpers: SubagentNames = new Map(); /** * 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 async recordAgentActivity(activity: AgentActivity): Promise { if (this.closed || activity.sessionId !== String(this.id)) return; const provider = this.providers.getActiveName() ?? ''; for (const event of activity.events) { if (event.type === 'scheduled_wakeups') { this.scheduledWakeups = event.wakeups; for (const listener of [...this.workListeners]) listener(); continue; } const record = agentActivityRecord(event, provider, this.agentHelpers); if (!record) continue; await this.log.append({ type: 'plugin_event', sessionId: this.id, turnId: newTurnId(), ...record }); if (event.type !== 'background_work') continue; this.runningWork = event.work; for (const listener of [...this.workListeners]) listener(); } } /** * 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. */ async stopBackgroundWork(workId: string): Promise { const provider = this.providers.getActiveName() ? this.providers.getActive() : undefined; if (!provider?.stopBackgroundWork) return false; return provider.stopBackgroundWork(String(this.id), workId); } /** * 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 { const tell = () => listener(this.getInfo()); const stopCli = this.agentClis.onChange(tell); this.workListeners.add(tell); return () => { stopCli(); this.workListeners.delete(tell); }; } /** * 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'] { const set = typeof this.reasoning === 'object' ? this.reasoning : {}; if (set.effort !== undefined || !this.activeIsAgentConnection()) return this.reasoning; return { ...set, effort: 'low' }; } private activeIsAgentConnection(): boolean { const active = this.providers.getActiveName(); if (!active) return false; try { return typeof this.providers.getActive().agentStep === 'function'; } catch { // Selected before credentials built an instance: the definition says whether it is an agent. return this.providers.list().some((p) => p.name === active && p.agentName !== undefined); } } getInfo(): SessionInfo { let activeMode: string | null = null; let activeModeBadge: SessionInfo['activeModeBadge'] = null; try { const mode = this.modes.getActive(); activeMode = mode.name; // Surface the active mode's presentation hint so channels can render a // persistent badge (e.g. goal mode) without hard-coding mode names. activeModeBadge = mode.badge ? { label: mode.badge.label, ...(mode.badge.tone ? { tone: mode.badge.tone } : {}) } : null; } catch { // No mode active yet (registry empty pre-boot) - report null. } const active = this.providers.getActiveName(); let activeProviderModels: LLMProvider['models'] | null = null; let activeStarterModel: string | undefined; if (active) { try { const provider = this.providers.getActive(); activeProviderModels = provider.models; activeStarterModel = provider.starterModel; } catch { // A definition can be registered/selected before credentials build an // instance. Fall back to its declared catalog until activation lands. } } const declared = this.providers.list().find((p) => p.name === active); const defaultModel = active ? resolveTurnModel(this, { name: active, models: activeProviderModels ?? (declared ? declared.models : []), starterModel: activeStarterModel ?? declared?.starterModel, }) : undefined; const ready = this.readyProviders; const contextWindowEvents = this.log.ofType('plugin_event'); return { sessionId: this.id, cwd: this.cwd, ...(this.governance ? { governance: this.governance } : {}), clientChrome: this.pluginHost.listClientChrome(), activeProvider: active, providers: this.providers.list().map((p) => { const agentCli = this.agentClis.report(p.name); const starterModel = (p.name === active ? activeStarterModel : undefined) ?? p.starterModel; return { name: p.name, models: withRecordedContextWindows( this.agentClis.models(p.name) ?? (p.name === active && activeProviderModels ? activeProviderModels : p.models), recordedContextWindows(contextWindowEvents, p.name), ), authKind: p.auth?.kind === 'oauth' ? 'oauth' : 'api-key', ...(starterModel ? { starterModel } : {}), ...(p.agentName ? { agentName: p.agentName } : {}), ...(agentCli ? { agentCli } : {}), supportsLiveModelDiscovery: p.supportsLiveModelDiscovery === true, enabled: this.providers.isEnabled(p.name), }; }), activeMode, activeModeBadge, modes: this.modes.list().filter(isSelectableMode).map((m) => m.name), tools: this.tools.list().map((t) => ({ name: t.name, description: t.description, ...(t.compact ? { compact: t.compact } : {}), ...(t.icon ? { icon: t.icon } : {}), })), skills: this.skills.list().map((s) => ({ id: s.id, name: s.frontmatter.name, description: s.frontmatter.description, ...(s.frontmatter.label ? { label: s.frontmatter.label } : {}), ...(s.frontmatter.aliases?.length ? { aliases: s.frontmatter.aliases } : {}), })), commands: this.commands.list().map((c) => ({ name: c.name, description: c.description, ...(c.aliases ? { aliases: c.aliases } : {}), ...(c.channels ? { channels: c.channels } : {}), ...(c.pendingNotice ? { pendingNotice: c.pendingNotice } : {}), })), readyProviders: ready ? [...ready] : active ? [active] : [], // hasTranscriber reports whether any backend is *registered*, // not whether one is active. The active selection is per-flow // (the TUI activates Codex on its first voice toggle; the // desktop relies on handleTranscribe's candidate fallback). // For UI affordance gating (showing / hiding a mic button), // any registered transcriber means "voice is wired." hasTranscriber: this.transcribers.list().length > 0, activeTranscriber: this.transcribers.getActiveName(), hasSynthesizer: this.synthesizers.list().length > 0, activeSynthesizer: this.synthesizers.getActiveName(), autoApprove: this.autoApprove, reasoningEffort: reasoningEffortOf(this.turnReasoning()), fast: this.fast, ...(defaultModel !== undefined ? { defaultModel } : {}), backgroundWork: this.runningWork, scheduledWakeups: this.scheduledWakeups, }; } } /** * Wrap a `PermissionResolver` so the persistent `PermissionEngine` runs * first. If the engine has a matching allow/deny rule from * `~/.moxxy/permissions.json`, that decision short-circuits the * resolver's prompt path. Otherwise the resolver runs as usual. * * The wrapper is a Proxy that intercepts only `check` (and provides the * prompt-free `policyCheck` probe); every other property (e.g. `abortAll` * and any channel-specific helpers) passes straight through to the * underlying resolver, so callers reach those methods exactly as before. */ function wrapWithPolicy( inner: PermissionResolver, engine: PermissionEngine, getToolRule: (name: string) => PermissionRule | undefined, cwd: string, isAutoApprove: () => boolean, ): PermissionResolver { // The policy-only decision: user policy (permissions.json) wins, then the // tool's own declared rule (so a tool marked `allow` is never blocked in // headless runs). Returns null when neither decides — `check` then falls // through to the channel resolver's prompt / deny-by-default path, while // `policyCheck` callers (auto-approving modes) supply their own fallback // so no prompt can ever fire. const policyDecision = async (call: PendingToolCall, ctx?: PermissionContext): Promise => { const policy = engine.check(call); if (policy) return policy; return evaluateWorkspaceToolRule(ctx?.toolPermission ?? getToolRule(call.name), call, cwd); }; // Use a Proxy so any extra methods on the underlying resolver // (`abortAll`, channel-specific helpers) remain accessible — only // `check`/`policyCheck` are intercepted. return new Proxy(inner, { get(target, prop, receiver) { if (prop === 'check') { return async (call: PendingToolCall, ctx: PermissionContext) => { const decided = await policyDecision(call, ctx); if (decided) return decided; // Auto-approve replaces only the asking: policy denies above still // win, and a scoped resolver (subagent, goal run) keeps its own say. const scoped = currentPermissionScope(); if (!scoped && isAutoApprove() && !ctx.askPerson) return { mode: 'allow', reason: 'auto-approve', decidedNow: true }; return (scoped ?? target).check(call, ctx); }; } if (prop === 'policyCheck') { return async (call: PendingToolCall, ctx?: PermissionContext) => policyDecision(call, ctx); } if (prop === 'mandatoryCheck') { return async (call: PendingToolCall, ctx: PermissionContext) => { const scoped = currentPermissionScope(); if (!scoped) return null; const policy = await policyDecision(call, ctx); return policy ?? scoped.check(call, ctx); }; } return Reflect.get(target, prop, receiver); }, }); } async function evaluateWorkspaceToolRule( rule: PermissionRule | undefined, call: PendingToolCall, cwd: string, ): Promise { if (!rule?.workspace) return evaluateToolRule(rule, call); if (!(await pathsStayInWorkspace(rule, call, cwd))) return null; const { workspace: _workspace, ...unscopedRule } = rule; return evaluateToolRule(unscopedRule, call); } async function pathsStayInWorkspace( rule: PermissionRule, call: PendingToolCall, cwd: string, ): Promise { const scope = rule.workspace; if (!scope) return true; const input = isRecord(call.input) ? call.input : {}; let workspace: string; try { workspace = await realpath(cwd); } catch { return false; } for (const pathInput of scope.pathInputs) { const value = input[pathInput.key]; if (value === undefined && pathInput.defaultToWorkspace) continue; if (typeof value !== 'string') return false; try { const target = await realpath(resolve(cwd, value)); const fromWorkspace = relative(workspace, target); if ( fromWorkspace === '..' || fromWorkspace.startsWith(`..${sep}`) || isAbsolute(fromWorkspace) ) { return false; } } catch { return false; } } return true; } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } /** The effort `SessionInfo` reports: reasoning on without a set effort runs at the provider's default. */ function reasoningEffortOf(reasoning: Session['reasoning']): ReasoningEffort | 'default' | null { if (!reasoning) return null; return reasoning === true ? 'default' : reasoning.effort ?? 'default'; }