import { Agent, type AgentMessage, type AgentEvent, type ThinkingLevel } from '@earendil-works/pi-agent-core'; import type { AgentInstanceGateway } from './agent-instance-gateway.js'; import { type Config } from '../config/schema.js'; import { type EffectiveAgentProfile } from '../config/agent-profile.js'; import type { ModelManager } from './models/manager.js'; import type { SkillInstallToolOptions, SkillInstallToolResult, MarketplaceSkillInstallToolOptions, MarketplaceSkillInstallToolResult } from './tools/skill-install-tool.js'; import { type AgentCapabilityCatalogEntry, type AgentCapabilitySessionState } from './capabilities/index.js'; import type { GatewayClarifyRequestFn } from './tools/clarify-tool.js'; import type { GatewaySecretRequestFn } from './tools/request-secret-tool.js'; import type { ExtensionRegistryImpl as ExtensionRegistry } from '../extensions/index.js'; import type { MessageBus } from '../infra/bus/index.js'; import type { AutomationService } from '../automations/index.js'; import type { SessionStore } from '../session/store.js'; import type { NotesService } from '../notes/index.js'; import type { ProjectService } from '../projects/index.js'; import type { SessionContext } from './session/session-context.js'; import type { Skill, SkillDiagnostic, SkillMarkdownPreviewPayload, SkillRuntimeStatus } from './skills/types.js'; import { type SkillHubLockEntry } from './skills/hub-lock.js'; import { type ExecutionContextPlan } from './context/coordinator.js'; import { type AgentTurnPolicy } from './orchestration/agent-turn-policy.js'; export interface SkillCatalogEntry { plugin?: { id: string; name: string; title?: string; authorizationStatus: string; active: boolean; readiness: string; }; directoryId: string; name: string; description: string; localizations?: Skill['localizations']; category?: string; source: Skill['source']; origin: Skill['origin']['id']; path: string; managed: boolean; writable: boolean; /** User toggle in ~/.xopc/skills.json (`entries[name].enabled`). Default true. */ enabled: boolean; /** When true, skill is never injected into `` (SKILL.md frontmatter). */ disableModelInvocation: boolean; /** Hub install provenance when under ~/.xopc/skills and listed in skills-lock.json. */ hub?: SkillHubLockEntry; } export interface SkillCatalogRuntimeMeta { version: string; loadedAt: number; diagnostics: SkillDiagnostic[]; status: SkillRuntimeStatus; } export interface SkillCatalogSnapshot extends SkillCatalogRuntimeMeta { catalog: SkillCatalogEntry[]; } export type AgentSkillUnavailableReason = 'agent-denied' | 'disabled' | 'requirements-unmet' | 'model-invocation-disabled' | 'tool-gated'; export interface AgentSkillAvailabilityEntry extends SkillCatalogEntry { availableForCurrentAgent: boolean; unavailableReason: AgentSkillUnavailableReason | null; } export interface AgentSkillAvailabilityPayload { agentId: string; workspacePath: string; version: string; loadedAt: number; diagnostics: SkillDiagnostic[]; status: SkillRuntimeStatus; defaultsAllowlist?: string[]; agentAllowlist?: string[]; effectiveAllowlist?: string[]; skills: AgentSkillAvailabilityEntry[]; } export interface WorkspaceTrustState { workspacePath: string; required: boolean; decision: boolean | null; trusted: boolean; } export interface AgentManagerConfig { workspace: string; model?: string; config?: Config; extensionRegistry?: ExtensionRegistry; endpointTools?: import('../endpoint-tools/index.js').EndpointToolRuntime; hookRunner?: import('../extensions/index.js').ExtensionHookRunner; bus: MessageBus; getCurrentContext: () => SessionContext | null; /** Session persistence (enables `session_search` when set). */ getSessionStore?: () => SessionStore; /** Clears per-session profile default on teardown. */ getModelManager?: () => ModelManager; thinkingLevel?: ThinkingLevel; reasoningLevel?: 'off' | 'on' | 'stream'; verboseLevel?: 'off' | 'on' | 'full'; gatewayClarify?: { requestClarification: GatewayClarifyRequestFn; }; gatewaySecretRequest?: { requestSecret: GatewaySecretRequestFn; savePastedSecret?: (context: { conversationId: string; runId: string; toolCallId: string; }, input: { label: string; value: string; }) => Promise<{ file: string; }>; consumeSecretRef?: (input: { ref: string; conversationId: string; }) => Promise; }; /** Gateway: exposes AutomationService for the `automation` tool. */ getAutomationService?: () => AutomationService | undefined; getChatScheduleService?: () => import('../chat-schedules/index.js').ChatScheduleService | undefined; getCalendarService?: () => import('../calendar/index.js').CalendarService | undefined; getProactiveHubService?: () => import('../proactive-hub/triage-service.js').ProactiveHubService | undefined; getMatterInvestigator?: () => import('../proactive-hub/matter-investigator.js').MatterInvestigatorService | undefined; onMatterMutated?: (info: { matterId: string; kind: 'created' | 'updated' | 'resolved'; }) => void; canConfigureEndpoint?: (endpointId: string) => boolean; deliverOutbound?: (msg: import('../infra/bus/index.js').OutboundMessage) => Promise; getBrowserSetupService?: () => import('../browser/setup/service.js').BrowserSetupService | undefined; getMcpSetupService?: () => import('./mcp/conversation-setup.js').McpConversationSetup | undefined; getSelfConfigService?: () => import('../self-config/service.js').SelfConfigService | undefined; getSetupSceneService?: () => import('../self-config/setup-engine.js').UnifiedSetupSceneService | undefined; getCapabilityChannelState?: () => import('../capabilities/capability-catalog.js').CapabilityChannelState; emitBrowserEvent?: (type: string, payload: unknown) => void; embeddedBrowserGrants?: import('../browser/embedded/grant-registry.js').EmbeddedBrowserGrantRegistry; /** Gateway: exposes first-class xopc product objects for the `xopc_use` tool. */ getNotesService?: () => NotesService | undefined; getProjectService?: () => ProjectService | undefined; getWorkDiscovery?: () => import('../work-discovery/service.js').WorkDiscoveryService | undefined; getLocalAppService?: () => import('../local-apps/index.js').LocalAppService | undefined; getChatPreviewService?: () => import('../chat-previews/index.js').ChatPreviewService | undefined; dispatchTaskEvents?: () => void; dispatchTaskRuns?: () => void; retryTask?: import('./service.types.js').AgentServiceConfig['retryTask']; onAgentCatalogMutate?: () => void; /** Runtime notification for UI/CLI shells that cache skill catalogs. */ onSkillsUpdated?: (payload: { reason: 'disk' | 'config'; }) => void; /** Install a managed skill from an explicit source and refresh runtime state. */ installSkillFromSource?: (opts: SkillInstallToolOptions) => Promise; /** Install a managed skill from Store or ClawHub and refresh runtime state. */ installSkillFromMarketplace?: (opts: MarketplaceSkillInstallToolOptions) => Promise; /** * Runtime trust override. Persistent "do not trust" entries still take precedence. */ isWorkspaceTrusted?: (workspaceDir: string) => boolean | null | undefined; } export interface AgentInstance { agent: Agent; conversationId: string; createdAt: number; lastUsedAt: number; effectiveProfile: EffectiveAgentProfile; resolvedWorkspacePath: string; projectId?: string; /** Tool names registered on this agent (for skill indexing / tool gating). */ registeredToolNames: string[]; /** Capability packs activated by explicit skills or UI entry points in this session. */ activeCapabilities: Map; activeProjectContext?: string; interactionStateVersion?: number; userContextAccessVersion: string; executionToolPolicyVersion: string; toolAvailabilityVersion: string; pluginRuntimeAccessVersion?: string; /** Declared env var names from skill_view; exec_command reads values from process.env at spawn time. */ skillEnvPassthroughKeys: Set; } export interface PreparedSkillTurn { text: string; activatedCapabilityNames: string[]; } export declare class AgentManager implements AgentInstanceGateway { private agents; private config; private toolsFactory; private mergedConfig; private activeCapabilityNames; private buildActiveCapabilityContext; private resolveCapabilityCatalogForInstance; /** Default agent workspace (effective profile for `getDefaultAgentId`). */ private baseWorkspacePath; /** Per-session absolute markdown workspace when `SessionAgentConfig.workingDirectoryOverride` is set. */ private sessionWorkspaceOverrides; private defaultModel; private credentialCache; private credentialResolver; private workspaceRuntimes; private executionContext; private memoryLearning; private skillFilesystemWatcher; private skillDiskRefreshInProgress; private skillDiskRefreshPending; private lastExplicitSkillDiskRefreshAt; private skillsUpdatedTimer; private pendingSkillsUpdatedReason; private projectTrustStore; constructor(config: AgentManagerConfig); private computeBaseWorkspacePath; /** * Workspace root for inbound attachments / side effects for this session's agent id. * Uses in-memory session workspace overrides when the session has a persisted `workingDirectoryOverride`. */ getResolvedWorkspaceForSession(conversationId: string): string; private getWorkspaceRuntimeForSession; private projectIdForSession; private workspaceRuntime; private getCurrentWorkspaceRuntime; /** * Sync in-memory workspace override from session config (after load or PATCH). * Pass `null` to clear when the session has no `workingDirectoryOverride` on disk. */ setSessionWorkspaceOverride(conversationId: string, absolutePath: string | null): void; private pickDefaultModelRef; private resolveModelStringToModel; /** * Refresh config-backed services and SQLite-backed Agent defaults after a settings change. * * The previous implementation rebuilt the entire `AgentToolsFactory` (80+ lines * of dependency wiring) on every reload. The factory's deps are now built from * a single helper ({@link buildToolsFactoryDeps}) and read `this.*` through * closures, so existing instances automatically see the new config without * reconstruction. Browser and computer resources are released when their * configuration changes or an active agent's tool policy changes. */ updateRuntimeConfiguration(config: Config): void; getSecretRefConsumer(): ((input: { ref: string; conversationId: string; }) => Promise) | undefined; /** * Construct the dep bag passed to `AgentToolsFactory`. Closures reference * `this.*` so they remain valid across hot reloads (no rebuild needed). */ private buildToolsFactoryDeps; /** Build the bounded, policy-filtered context used for this model turn. */ prepareUserTurnContext(userMessage: AgentMessage, conversationId: string, turnId: string, options?: { disableDeepRecall?: boolean; }): Promise; /** Recover previously committed learning intent before an interactive turn starts. */ beginBackgroundReviewUserTurn(conversationId: string): void; /** After a successful main turn, may run a quiet follow-up for context review and skills. */ scheduleBackgroundReviewAfterUserTurn(conversationId: string): void; /** * Expand `/skill:name` user text into the full skill block for the current turn (WebChat, channels). */ expandSkillUserText(text: string): string; /** * Expand a leading `/skill:name` token for an isolated background prompt (e.g. sidecar watcher) * without mutating the main session's active capabilities. */ expandSkillTextForSession(conversationId: string, text: string, agentId?: string): string; prepareSkillTurn(conversationId: string, text: string): PreparedSkillTurn; withSkillCapabilities(conversationId: string, capabilityNames: readonly string[], run: () => Promise): Promise; private buildSystemPromptForInstance; /** Structured SKILL.md preview for the gateway console. */ getSkillMarkdownSource(skillName: string): SkillMarkdownPreviewPayload | null; isProjectWorkspaceTrusted(workspaceDir: string): boolean; private resolveContextFilesForSession; private skillCatalogEntryFromSkill; getSkillCatalog(): SkillCatalogEntry[]; getSkillCatalogSnapshot(): SkillCatalogSnapshot; private buildAgentSkillAvailability; private materializeSkillAllowlist; getAgentToolAvailability(agentId: string, name: string): { condition: string; state: "verified" | "blocked"; reasonCode: string; detail: string; }; getAgentRegisteredToolNames(agentId: string): string[]; getAgentSkillAvailability(agentId: string, projectId?: string): AgentSkillAvailabilityPayload; getSessionSkillAvailability(conversationId: string): AgentSkillAvailabilityPayload; getSessionWorkspaceTrust(conversationId: string): WorkspaceTrustState; getWorkspaceTrust(workspacePath: string): WorkspaceTrustState; setSessionWorkspaceTrust(conversationId: string, trusted: boolean): WorkspaceTrustState; setWorkspaceTrust(workspacePath: string, trusted: boolean): WorkspaceTrustState; /** * After ~/.xopc/skills.json changes (enable/disable), refresh `` on active agents. */ refreshSkillsAfterSkillConfigChange(): void; refreshActionTrustPolicy(): void; refreshUserProfileContext(): void; /** * Reload skills from disk and refresh system prompt on all active Agent instances. */ refreshSkillsAfterDiskChange(source?: 'explicit' | 'watch' | 'trust'): void; refreshSkillsAfterTrustChange(): void; private scheduleSkillsUpdated; private applySkillsAfterDiskChange; /** * Get or create an Agent instance for a session */ getOrCreateAgent(conversationId: string, options?: { fallbackModelRef?: string; }): Agent; createEphemeralAgentContext(parentConversationId: string, options?: { agentId?: string; fallbackModelRef?: string; }): { agent: Agent; agentId: string; workspaceDir: string; turnPolicy: AgentTurnPolicy; }; createAgentTurnPolicy(conversationId: string): AgentTurnPolicy; /** * Get existing agent for a session (if any) */ getAgent(conversationId: string): Agent | undefined; /** * Check if an agent exists for a session */ hasAgent(conversationId: string): boolean; private static readonly IDLE_AGENT_TTL_MS; private static readonly SOFT_IDLE_AGENT_LIMIT; private static readonly HARD_AGENT_LIMIT; private evictIdleAgentsIfNeeded; /** * Remove an agent instance */ removeAgent(conversationId: string): boolean; /** * Get all active session keys */ hasBrowserSessions(): boolean; getActiveSessions(): string[]; /** * Get agent count */ getAgentCount(): number; /** * Merge per-turn channel system prompt (e.g. Telegram group/topic override) into the agent. */ applyTurnChannelSystemPrompt(conversationId: string, channelSystemPrompt: string): void; /** * Set thinking level for a session's agent */ setThinkingLevel(conversationId: string, level: ThinkingLevel): void; /** * Dispose all agents */ dispose(): void; warmCredentialCache(): Promise; refreshCredentials(): Promise; private resolveApiKeyWithCache; private composeDynamicProjectContext; private readonly personalPromptContext; private buildExecutionScopeContext; private getInteractionStateVersion; private getUserContextAccessVersion; getCapabilityCatalogForSession(conversationId?: string): AgentCapabilityCatalogEntry[]; private createAgentForProfile; private buildAgentTurnPolicy; private resolveToolPolicy; private requestToolConfirmation; private refreshDynamicContextIfChanged; /** * Set model for a specific session */ setModelForSession(conversationId: string, modelId: string): boolean; /** * Get last assistant content from a session's agent */ getLastAssistantContent(conversationId: string): string | null; /** * Replace messages for a session's agent */ replaceMessages(conversationId: string, messages: AgentMessage[]): boolean; /** * Get messages for a session's agent */ getMessages(conversationId: string): AgentMessage[] | null; /** * Subscribe to agent events for a session */ subscribeToSession(conversationId: string, callback: (event: AgentEvent) => void): (() => void) | null; private readonly runtimeListeners; emitRuntimeEvent(conversationId: string, event: AgentEvent): void; }