import type { SessionCatalog } from "./cms.js"; import { type ModelProviderRegistry } from "./model-providers.js"; import type { Tool } from "@github/copilot-sdk"; import type { PilotSwarmWorkerOptions, ManagedSessionConfig } from "./types.js"; import type { AgentConfig } from "./agent-loader.js"; /** @internal Resolve the worker-wide turn cap: explicit option > deployment env > SDK default. */ export declare function resolveWorkerTurnTimeoutMs(explicitValue: unknown, envValue?: unknown): number; export { buildSystemAgentBootstrapPayload } from "./system-agents.js"; /** * PilotSwarmWorker — runs activities and orchestrations. * * Owns: * - SessionManager (creates/resumes CopilotSessions, holds tools/hooks) * - duroxide Runtime (dispatches activities + orchestrations) * - Session state store (optional, for session dehydration/hydration) * * In single-process mode, pass this worker to PilotSwarmClient's * constructor so they share the database provider and the client can * forward tool/hook registrations. */ /** * Resolve the spawn-tree session IDs for a given session. * * Walks up to the root ancestor via `parentSessionId`, then returns * `[root, ...descendants_of_root]` minus the caller itself. This is the * visibility set used by `setLineageSessionLookup` so peer agents * (siblings, cousins) under a common root can share session-scoped * facts without needing `shared=true`. * * Exported so tests can verify spawn-tree visibility behavior with a * mock `SessionCatalog`. * * @internal */ export declare function resolveSpawnTreeSessionIds(sessionId: string, catalog: Pick): Promise; export declare class PilotSwarmWorker { private config; private sessionManager; private sessionStore; private blobStore; private artifactStore; private factStore; private graphStore; private runtime; private _evictionTimer; private _provider; private _catalog; private _started; /** Worker-level tool registry — name → Tool. */ private toolRegistry; /** Loaded skill directories from plugins + direct config. */ private _loadedSkillDirs; /** Loaded skills by name for agent-declared eager prompt injection. */ private _loadedSkills; /** Every loaded skill with provenance intact — the name-keyed map above collapses duplicates. */ private _loadedSkillsAll; /** Skills `load_skill` may return: everything but user-scope package skills. Refilled in place. */ private _loadableSkills; /** * A user-scope package's skills, keyed by its owner (`agentOwnerKey`). * They are private, so they are NOT in the fleet-wide `_loadableSkills` * catalog — but a session OWNED BY that person may load them, exactly as * it may already use the private agents from the same package. Held by * reference in workerDefaults; cleared and refilled in place on reload. */ private _ownerScopedSkills; /** Raw loaded user-creatable agent configs from plugins + direct config. */ private _rawLoadedAgents; /** Optional PilotSwarm-bundled user agents, loaded only when session policy opts in. */ private _availableBundledAgents; /** Loaded agent configs from plugins + direct config, composed for SDK customAgents. */ private _loadedAgents; /** Loaded MCP server configs from plugins + direct config (the deployment catalog). */ private _loadedMcpServers; /** Resolved per-agent MCP server maps, keyed by agent name (raw + system agents). */ private _agentMcpServers; /** Names of catalog servers tagged `"default": true` — the deployment default MCP set. */ private _defaultMcpServerNames; /** * Catalog servers restricted with `allowedAgents`: server name → the agent * identities allowed to reference it. Filled by `_resolveAgentMcpServers`, * which also strips the field from the catalog configs. */ private _mcpAllowedAgents; /** * Server names defined by the DEPLOYMENT (plugin dirs + direct config), * as opposed to installed packages. A package may not redefine one: the * catalog is flat, so it would swap the server every agent talks to. * Cleared in place on reload; held by reference in workerDefaults. */ private _deploymentMcpNames; /** MCP declarations gathered from base (default) agents — resolved into the base map. */ private _baseAgentMcpDecl; /** Server names from direct worker-config `mcpServers` — legacy every-session semantics. */ private _directConfigMcpNames; /** Resolved base MCP map applied to EVERY session (base-agent opt-ins + direct config). */ private _baseMcpServers; /** Model provider registry — multi-provider LLM config. */ private _modelProviders; /** Provider-type templates, including types with no static credential. */ private _modelProviderTypes; /** Mtime watcher that re-loads model_providers.json on file change. */ private _modelProvidersReloader; private _modelProvidersReloadTimer; /** Close admission when drain begins; _started stays true until teardown ends. */ private _providerReconciliationEnabled; private _providerReconciliation; /** Embedded PilotSwarm framework prompt. */ private _frameworkBasePrompt; /** Tool names declared by the embedded PilotSwarm framework default agent. */ private _frameworkBaseToolNames; /** App-level default prompt overlay from app pluginDirs and inline worker config. */ private _appDefaultPrompt; /** Tool names declared by the app-level default agent overlay. */ private _appDefaultToolNames; /** System agents loaded from plugins — started automatically on worker start. */ private _loadedSystemAgents; /** Prompt lookup used for direct named/system sessions. */ private _agentPromptLookup; /** Descriptor for the PilotSwarm framework base layer (from system default.agent.md). */ private _frameworkBaseDescriptor; /** Descriptor for the app default layer (from app default.agent.md or inline config). */ private _appDefaultDescriptor; /** Session creation policy loaded from session-policy.json. */ private _sessionPolicy; /** * Live allowed-agent-names array. registerActivities captures this exact * array once at start(); refreshAgentPackages mutates it IN PLACE so the * activity layer never sees a stale copy. Never reassign it. */ private _allowedAgentNamesLive; /** Constructor-time pluginDirs snapshot — package dirs are appended per refresh. */ private _basePluginDirs; /** * Installed-package dir → owning scope/owner, for agents loaded from * agent packages. Empty for plugin dirs the deployment configured itself. */ private _capabilitySources; private _packageDirOwners; /** Agent-package dynamic install state (docs/proposals/agent-packages.md). */ private _agentPackagesCacheDir; private _agentPackagesRefreshMs; private _agentPackagesEpoch; private _agentPackagesTimer; private _agentPackagesRefreshing; /** Tools contributed by installed packages, merged under static tools. */ private _agentPackageTools; /** Per-package tool maps — lets a session prefer ITS package's handler on a name collision. */ private _agentPackageToolsByPackage; /** Package-qualified MCP maps; package names never resolve through the legacy flat catalog. */ private _agentPackageMcpServersByPackage; /** Last install report — carried in the registry heartbeat's state. */ private _agentPackagesInstalled; /** Worker-registry lifecycle phase (docs/proposals/worker-registry.md). */ private _workerPhase; /** Write-once registration info; built on the first heartbeat. */ private _registrarInfo; /** Event-loop delay histogram for health reporting (reset each beat). */ private _eventLoopHist; /** Last refresh failure — carried in heartbeat state until a clean pass. */ private _agentPackagesRefreshError; private _featureFlags; private _registryReporting; constructor(options: PilotSwarmWorkerOptions); private _startProviderPolling; private _stopProviderPolling; private _reconcileProvidersAndSystemAgents; /** * Rebuild what the SessionManager resolves models against: the TYPES * from the file, joined to the PROVIDERS in the database. Falls back to * the file alone when there is no catalog, which is what the embedded * single-process test worker runs on. */ private _refreshProviderRegistry; /** * Register tools at the worker level. * * These tools are available to ALL sessions on this worker. * Clients can reference them by name in createSession() via * `toolNames: ["tool_name_1", "tool_name_2"]` — the names travel * through duroxide as serializable strings, and the worker * resolves them to the actual Tool objects at execution time. * * This is the primary mechanism for custom tools in remote/ * separate-process mode where client and worker run on * different machines. */ registerTools(tools: Tool[]): void; /** * SessionManager resolves tool names against one merged map: statically * registered tools win over package tools on a name collision (the * static registration is deployment code; a package must not shadow it). */ private _pushMergedToolRegistry; /** Store full config (with tools/hooks) for a session. */ setSessionConfig(sessionId: string, config: ManagedSessionConfig): void; /** Whether a durable session store is configured. */ get blobEnabled(): boolean; /** Whether the worker runtime is running. */ get isStarted(): boolean; /** @internal — shared with co-located PilotSwarmClient. */ get provider(): any; /** Session catalog (CMS) — available when store is PostgreSQL. */ get catalog(): SessionCatalog | null; /** Loaded skill directories. */ get loadedSkillDirs(): string[]; /** * Loaded agent configs. Entries may carry `mcpServers` — the agent's * RESOLVED server map, which can contain expanded credentials * (env-substituted headers). Never serialize these entries wholesale to * client-facing surfaces. */ get loadedAgents(): Array<{ name: string; description?: string; prompt: string; tools?: string[] | null; skills?: string[]; mcpServers?: Record; namespace?: string; }>; /** Loaded MCP server configs (the deployment catalog). */ get loadedMcpServers(): Record; /** Resolved per-agent MCP server maps, keyed by agent name. */ get agentMcpServers(): Record>; /** Resolved base MCP map applied to every session (base-agent opt-ins + direct config). */ get baseMcpServers(): Record; /** Names of catalog servers in the deployment default MCP set (`"default": true`). */ get defaultMcpServerNames(): string[]; /** Server names the deployment defines (plugin dirs + direct config) — names no package may redefine. */ get deploymentMcpServerNames(): string[]; /** Catalog servers restricted with `allowedAgents`: server name → allowed agent identities. */ get restrictedMcpServers(): Record; /** Model provider registry (null if no providers configured). */ get modelProviders(): ModelProviderRegistry | null; /** System agents loaded from plugins. */ get systemAgents(): AgentConfig[]; /** Session creation policy (null if no session-policy.json found). */ get sessionPolicy(): import("./types.js").SessionPolicy | null; /** Names of loaded non-system agents that can be created as top-level sessions. */ get allowedAgentNames(): string[]; start(): Promise; stop(): Promise; /** * Graceful drain (lifecycle protocol §3.8): * 1. Stop fetching — duroxide's shutdown flag makes dispatch slots * finish their in-flight item and claim nothing new. * 2. Finish in-flight — running turns complete within the drain * budget; their snapshot commits land inside the runTurn activity. * (duroxide sleeps the FULL budget before returning; turns longer * than the budget are aborted — crash semantics, lossless for * every committed turn.) * 3. Evict all — purely local for sessions with a committed marker * (the store already holds their state); legacy dehydrate for * unmarked sessions whose local files may be the only copy. * 4. Exit — anything still leased lapses within the duroxide session * lock timeout. */ gracefulShutdown(): Promise; /** Destroy a session on this worker. */ destroySession(sessionId: string): Promise; /** * Load plugin contents from SDK bundled plugins + app plugin directories. * * Tiered loading order: * 1. system/ — SDK core (always loaded: base system prompt, html-visuals skill) * 2. mgmt/ — SDK management agents (loaded unless disableManagementAgents is true) * 3. default-agents/ — optional SDK user agents, read into a separate registry * 4. app — Consumer-provided plugin dirs (from pluginDirs option) * 5. direct — Inline config (skillDirectories, customAgents, mcpServers options) * * Agents merge by name (later tiers override earlier). * Skills: every dir is read, but the registry is keyed by skill NAME, so a * later tier replaces an earlier skill of the same name. A registered * skill only reaches a prompt if some agent declares it in `skills:` * (see _applyDeclaredAgentSkills) — there is no discovery path. * MCP servers merge by name (later tiers override earlier). */ /** * Reset every plugin-derived structure IN PLACE so the shared references * held by SessionManager (workerDefaults) and the activity layer * (registerActivities args) observe the reload. Reassigning any of these * would strand a consumer on a stale snapshot — see the field comments. */ private _getCapabilitySources; /** The SDK can discover skill dirs itself, so V2 must filter this path too. */ private _getBaseV2SkillDirectories; private _resetLoadedPluginState; /** * Install (or re-install) registry agent packages and swap them into the * live catalog. Startup calls this once before the runtime exists; the * epoch poll calls it forever after. Never throws: a registry outage or * a broken package degrades to "packages unchanged/quarantined", never * to a dead worker. * * SessionManager adopts one package snapshot per turn. Handler-only changes * re-register in place; changed prompts, declarations or MCP grants recreate * the warm CLI handle at the next turn boundary. */ private _startConfigurationPolling; refreshWorkerConfiguration(): Promise; refreshAgentPackages(opts?: { force?: boolean; }): Promise; /** Stable registry identity: configured workerNodeId, else host#pid. */ private get _registryWorkerId(); private get _workerPool(); /** Write-once identity/build/capability record for the workers row. */ private _buildRegistrarInfo; /** Glanceable health snapshot — last-known values, never a time series. */ private _collectWorkerHealth; /** * Worker-registry heartbeat (migration 0040): upsert this worker's row — * presence, health, per-domain actual state — and receive the effective * directive set. Agent-packages convergence stays driven by the refresh * flow (its epoch read rides the seeded directive via the shim), so the * returned directives are bookkeeping here; unknown or externally- * actuated domains are inert by protocol. Never throws. */ private _reportAgentWorkerState; private _loadPlugins; /** * Load agents, skills, MCP config, and session policy from a single plugin directory. */ /** * Build a `PromptLayerDescriptor` from an authored agent config. * * Source of truth is the .agent.md frontmatter (`schemaVersion`, `version`, * `name`, `system`). Missing frontmatter falls back to safe defaults * (`schemaVersion=1`, `version="0.0.0"`). */ private _buildLayerDescriptor; /** * Resolve each loaded agent's MCP server references against the merged * deployment catalog (capability-profiles Phase 1). * * The catalog is the union of all plugin `.mcp.json` files (plus direct * config). Servers tagged `"default": true` form the deployment default * MCP set, granted only to agents with `inheritDefaultMcpServers: true`; * the tag is stripped from the config objects afterwards so the Copilot * CLI never sees it. Named references that miss the catalog are dropped * with a warning. Runs after every plugin dir (and direct config) has * merged, so the catalog is complete. */ private _resolveAgentMcpServers; /** * The package a loaded skill belongs to, or null for a deployment skill. * Matched by directory prefix against the installed package dirs. */ private _skillPackageOwner; /** * Progressive discovery: append a one-line-per-skill index to the * framework base prompt so every session knows which skills EXIST and * can pull one with `load_skill`. The bodies stay out of context unless * an agent declares them in `skills:`. Runs once per plugin load — the * base prompt is re-read from disk on every reload, so it never stacks. */ private _composeSkillsIndex; private _applyDeclaredAgentSkills; /** * Rebuild the by-name agent lookup after everything is loaded and skills * are composed. * * With agent-package scope shadowing one NAME can be served by several * enabled packages at once. The incremental per-dir writes above are * last-wins — load order decided which copy every session got, and one * user's private copy could silently replace the shared prompt for the * whole fleet. This pass makes the bare entry deterministic (deployment * code beats shared package beats user package) and records every copy so * session resolution can pick per session owner * (`pickAgentCopyForOwner` in session-manager). */ private _finalizeAgentPromptLookup; private _loadBundledDefaultAgents; private _mergeOptedBundledAgents; /** * Load agents, skills, MCP config, and session policy from a single plugin directory. */ private _loadPluginDir; /** * Auto-start system agents defined in plugins. * * Each system agent has a deterministic session UUID derived from its `id` slug. * Multiple workers calling this concurrently is safe — CMS upsert and * duroxide startOrchestrationVersioned are both idempotent. * * All system agents, including permanent children such as sweeper/resource * manager/facts manager, are bootstrapped directly by the worker. They are * not LLM-spawned via spawn_agent(agent_name=...). */ private _startSystemAgents; private _createProvider; } //# sourceMappingURL=worker.d.ts.map