import { ToolRegistry } from './core/tool-registry.js'; import type { SemanticSearchResult } from './core/skill-registry.js'; import { ToolDefinition, SkillDefinition, SkillSummary, SearchSkillsOptions, SkillContentOptions, EmbeddingProvider } from './core/types.js'; import { MatimoLogger, LoggerConfig } from './logging/index.js'; import type { ExecuteOptions } from './core/types.js'; import type { PolicyEngine, PolicyContext, PolicyConfig, HITLCallback } from './policy/types.js'; import { ToolIntegrityTracker } from './policy/integrity-tracker.js'; import { ApprovalManifest } from './policy/approval-manifest.js'; import type { MatimoEventHandler } from './policy/events.js'; /** * Result of a hot-reload operation */ export interface ReloadResult { loaded: number; removed: number; revalidated: number; rejected: string[]; /** True if a mid-load failure caused the registry to be restored to its previous state. */ rolledBack?: boolean; } /** * Options for MatimoInstance initialization */ export interface InitOptions extends LoggerConfig { toolPaths?: string[]; /** Skill paths for discovering SKILL.md files (Level 1 discovery) */ skillPaths?: string[]; autoDiscover?: boolean; includeCore?: boolean; /** Custom PolicyEngine implementation. Mutually exclusive with policyConfig and policyFile. */ policy?: PolicyEngine; /** Shorthand to create a DefaultPolicyEngine. Ignored if `policy` is provided. */ policyConfig?: PolicyConfig; /** Path to a policy.yaml file. Loaded into a DefaultPolicyEngine. Ignored if `policy` is provided. */ policyFile?: string; /** Paths containing trusted (developer-authored) tools. Defaults to auto-discovered @matimo/* paths. */ trustedPaths?: string[]; /** Paths containing untrusted (agent-created) tools. These tools undergo content validation. */ untrustedPaths?: string[]; /** HMAC secret for approval manifest. Overrides MATIMO_APPROVAL_SECRET env. */ approvalSecret?: string; /** Directory for .matimo-approvals.json. Defaults to process.cwd(). */ approvalDir?: string; /** * Approval TTL in seconds. Approvals older than this are treated as expired * and the tool must be re-approved. If not set, approvals never expire. */ approvalTtlSeconds?: number; /** Event handler for audit events (tool creation, approval, execution, etc.) */ onEvent?: MatimoEventHandler; /** * Human-in-the-loop callback for quarantined tools. * Called when a tool enters `pending_approval` state (medium-risk in prod with enableHITL). * Return `true` to approve, `false` to reject. * If not set, quarantined tools are rejected by default. */ onHITL?: HITLCallback; /** * Timeout in milliseconds for the HITL callback. * If the callback does not resolve within this time, the tool is auto-rejected. * Defaults to no timeout (waits indefinitely). */ hitlTimeoutMs?: number; } /** * Matimo Instance - Single initialization point for tool execution * Combines loader, registry, and executors into one interface */ export declare class MatimoInstance { #private; private static readonly HITL_TIMEOUT_SENTINEL; private toolPaths; private skillPaths; private loader; private registry; private skillLoader; private skillRegistry; private commandExecutor; private httpExecutor; private functionExecutor; private logger; private approvalHandler; private constructor(); /** * Initialize Matimo with tools from directory or auto-discovery * @param options - Initialization options (string for backward compatibility) * @returns MatimoInstance ready to execute tools * * @example * // Backward compatible - single path * const matimo = await MatimoInstance.init('./tools'); * * // New - auto-discovery * const matimo = await MatimoInstance.init({ autoDiscover: true }); * * // Explicit paths with logging config * const matimo = await MatimoInstance.init({ * toolPaths: ['./tools'], * logLevel: 'debug', * logFormat: 'json' * }); * * // Custom logger * const matimo = await MatimoInstance.init({ * toolPaths: ['./tools'], * logger: myCustomLogger * }); */ static init(options?: InitOptions | string): Promise; /** * Get tool paths * @returns Array of tool paths */ getToolPaths(): string[]; /** * Get the logger instance * @returns MatimoLogger instance */ getLogger(): MatimoLogger; /** * Execute a tool by name with parameters. * * @param toolName - Name of the tool to execute * @param params - Tool parameters * @param options - Optional execution options * @param options.timeout - Execution timeout in milliseconds * @param options.credentials - Per-call credential overrides (multi-tenant support). * Keys must match the env-var names the tool references (e.g. `SLACK_BOT_TOKEN`). * When provided, they take precedence over `process.env` for that single call. * Values are never logged and held in memory only for the duration of the call. * @returns Tool execution result */ execute(toolName: string, params: Record, options?: ExecuteOptions): Promise; /** * Get a tool definition by name * @param toolName - Name of the tool * @returns Tool definition or undefined */ getTool(toolName: string): ToolDefinition | undefined; /** * List all available tools, optionally filtered by policy. * @param context - PolicyContext for filtering. If omitted and policy is active, returns all tools (backward compatible). * @returns Array of tool definitions */ listTools(context?: PolicyContext): ToolDefinition[]; /** * Get all available tools (alias for listTools) * @returns Array of tool definitions */ getAllTools(context?: PolicyContext): ToolDefinition[]; /** * Return only the tools this agent context is permitted to use. * Mirrors: Matimo.get_tools_for_agent() in Python SDK. * * @param context - PolicyContext (agentId, roles, environment) * @returns Tools permitted for this context, filtered through the policy engine */ getToolsForAgent(context: PolicyContext): ToolDefinition[]; /** * Search tools by name or description * @param query - Search query * @returns Matching tools */ searchTools(query: string, context?: PolicyContext): ToolDefinition[]; /** * Get tools by tag * @param tag - Tag to search for * @returns Tools with the given tag */ getToolsByTag(tag: string, context?: PolicyContext): ToolDefinition[]; /** * Return the credential key names that a tool expects. * * This lets multi-tenant callers know exactly what to put in `options.credentials` * without having to read the tool's YAML definition. * * The returned strings are the keys you pass to `execute()`: * ```typescript * const keys = matimo.getRequiredCredentials('slack-send-message'); * // → ['SLACK_BOT_TOKEN'] * * // Then collect from your secrets store: * const credentials = Object.fromEntries( * keys.map(k => [k, tenant.secrets[k]]) * ); * await matimo.execute('slack-send-message', params, { credentials }); * ``` * * @param toolName - Exact tool name * @returns Array of credential key names (may be empty if the tool needs no auth) * @throws `MatimoError(TOOL_NOT_FOUND)` if the tool doesn't exist */ getRequiredCredentials(toolName: string): string[]; /** * List all available skills (Level 1 discovery - minimal context) * @returns Array of skill summaries */ listSkills(): SkillSummary[]; /** * Get a single skill by name (Level 2 activation - full content) * @param name - Skill name * @returns Skill definition or null */ getSkill(name: string): SkillDefinition | null; /** * Get selective skill content — only the sections an agent needs. * Prevents dumping entire SKILL.md files into the LLM context window. * * @example * // Get only error handling, max 500 tokens * matimo.getSkillContent('postgres-query-operations', { * sections: ['Error Handling'], * maxTokens: 500, * }) */ getSkillContent(name: string, options?: SkillContentOptions): string | null; /** * List all sections of a skill with their token costs. * Agents use this to decide which sections to load before activating. */ getSkillSections(name: string): Array<{ path: string; level: number; tokenEstimate: number; }> | null; /** * Search skills by keyword, category, difficulty, etc. * Set `options.semantic = true` for embedding-based similarity ranking. * @param options - Search options * @returns Matching skills */ searchSkills(options?: SearchSkillsOptions): SkillSummary[]; /** * Semantic search with relevance scores. * Uses embeddings to find skills by meaning, not just keywords. * * @example * const results = await matimo.semanticSearchSkills('How do I handle Postgres locking?'); * // → [{ skill: { name: 'postgres-query-operations' }, score: 0.82 }] */ semanticSearchSkills(query: string, options?: { limit?: number; minScore?: number; }): Promise; /** * Set a custom embedding provider for semantic skill search. * If not set, a built-in TF-IDF provider is used. */ setSkillEmbeddingProvider(provider: EmbeddingProvider): void; /** * Get a bundled resource from a skill (Level 3 resources) * @param skillName - Skill name * @param resourcePath - Relative path to resource (e.g., "scripts/extract.py") * @returns Resource content */ getSkillResource(skillName: string, resourcePath: string): string; /** * Get all skill paths * @returns Array of skill paths */ getSkillPaths(): string[]; /** * Automatically inject parameters from environment variables * Uses a YAML-native, scale-friendly approach: * * 1. Scans the execution config for all parameter placeholders * 2. For each parameter not provided by user, checks if it looks like auth (TOKEN, KEY, SECRET, etc.) * 3. If yes, attempts to load from (in order of priority): * a. `credentials[paramName]` — per-call override (multi-tenant) * b. `credentials[MATIMO_${paramName}]` — prefixed per-call override * c. `process.env[MATIMO_${paramName}]` — prefixed env var * d. `process.env[paramName]` — direct env var * * Credential values are never logged. */ private injectAuthParameters; /** * After injectAuthParameters(), verify no auth-looking placeholders remain unfilled. * Only checks HTTP headers (where auth credentials are injected) — not query params or body. * Throws AUTH_FAILED with actionable guidance naming the missing env var(s). */ private assertAuthParamsFilled; /** * Extract all parameter placeholders from execution config * Scans headers, body, URL, and query_params for {paramName} patterns */ private extractParameterPlaceholders; /** * Recursively scan object for parameter placeholders */ private scanObjectForParams; /** * Get the appropriate executor for a tool */ private getExecutor; /** * Hot-reload tools from all configured paths. * Re-validates untrusted tools via content validator and integrity tracker. * Tools that fail validation are rejected and not loaded. * * Atomic: if loading fails mid-way (e.g. I/O error), the registry is restored * to its previous state and `rolledBack: true` is included in the result. */ reloadTools(): Promise; /** * Check if a policy engine is active. */ hasPolicy(): boolean; /** * Get the approval manifest (if policy engine is active). */ getApprovalManifest(): ApprovalManifest | null; /** * Get the integrity tracker. */ getIntegrityTracker(): ToolIntegrityTracker; /** * Get the tool registry (for advanced use cases). */ getRegistry(): ToolRegistry; /** * Set a Human-in-the-Loop callback for quarantined tools. * The callback is invoked when a tool with `pending_approval` status is executed. * Return `true` to approve, `false` to reject. */ setHITLCallback(callback: HITLCallback | null): void; /** * Hot-reload the policy engine at runtime. * * - If `configOrFile` is a `PolicyConfig` object, creates a new `DefaultPolicyEngine`. * - If `configOrFile` is a string, re-reads and parses the YAML file. * - If omitted and the instance was initialized with `policyFile`, re-reads that file. * * The new policy is validated before swap — if validation fails, the old policy remains active. * After swap, all tools are re-validated against the new policy via `reloadTools()`. * * @returns The ReloadResult from the subsequent tool re-validation. */ reloadPolicy(configOrFile?: PolicyConfig | string): Promise; } /** * Matimo namespace - Entry point for the SDK */ export declare const matimo: { /** * Initialize Matimo with a tools directory * @param toolsPath - Path to tools directory * @returns MatimoInstance ready to use */ init(toolsPath: string): Promise; }; //# sourceMappingURL=matimo-instance.d.ts.map