@lssm/lib.ai-agent 0.0.0-canary-20251217052941 → 0.0.0-canary-20251217060433

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,73 @@
1
+ import { AgentSessionState } from "../types.js";
2
+ import { ModelMessage, StepResult, ToolSet } from "ai";
3
+
4
+ //#region src/session/store.d.ts
5
+
6
+ /**
7
+ * Interface for persisting agent session state.
8
+ *
9
+ * Implementations can use in-memory storage, databases,
10
+ * or external services like Redis.
11
+ */
12
+ interface AgentSessionStore {
13
+ /**
14
+ * Get a session by ID.
15
+ */
16
+ get(sessionId: string): Promise<AgentSessionState | null>;
17
+ /**
18
+ * Create a new session.
19
+ */
20
+ create(session: Omit<AgentSessionState, 'createdAt' | 'updatedAt'>): Promise<AgentSessionState>;
21
+ /**
22
+ * Append a step to a session.
23
+ */
24
+ appendStep(sessionId: string, step: StepResult<ToolSet>): Promise<void>;
25
+ /**
26
+ * Append a message to a session.
27
+ */
28
+ appendMessage(sessionId: string, message: ModelMessage): Promise<void>;
29
+ /**
30
+ * Update session properties.
31
+ */
32
+ update(sessionId: string, updates: Partial<Pick<AgentSessionState, 'status' | 'metadata'>>): Promise<void>;
33
+ /**
34
+ * Delete a session.
35
+ */
36
+ delete(sessionId: string): Promise<boolean>;
37
+ /**
38
+ * List sessions by agent ID.
39
+ */
40
+ listByAgent(agentId: string, limit?: number): Promise<AgentSessionState[]>;
41
+ /**
42
+ * List sessions by tenant ID.
43
+ */
44
+ listByTenant(tenantId: string, limit?: number): Promise<AgentSessionState[]>;
45
+ }
46
+ /**
47
+ * In-memory session store for development and testing.
48
+ */
49
+ declare class InMemorySessionStore implements AgentSessionStore {
50
+ private readonly sessions;
51
+ get(sessionId: string): Promise<AgentSessionState | null>;
52
+ create(session: Omit<AgentSessionState, 'createdAt' | 'updatedAt'>): Promise<AgentSessionState>;
53
+ appendStep(sessionId: string, step: StepResult<ToolSet>): Promise<void>;
54
+ appendMessage(sessionId: string, message: ModelMessage): Promise<void>;
55
+ update(sessionId: string, updates: Partial<Pick<AgentSessionState, 'status' | 'metadata'>>): Promise<void>;
56
+ delete(sessionId: string): Promise<boolean>;
57
+ listByAgent(agentId: string, limit?: number): Promise<AgentSessionState[]>;
58
+ listByTenant(tenantId: string, limit?: number): Promise<AgentSessionState[]>;
59
+ /**
60
+ * Clear all sessions (for testing).
61
+ */
62
+ clear(): void;
63
+ }
64
+ /**
65
+ * Create an in-memory session store.
66
+ */
67
+ declare function createInMemorySessionStore(): AgentSessionStore;
68
+ /**
69
+ * Generate a unique session ID.
70
+ */
71
+ declare function generateSessionId(): string;
72
+ //#endregion
73
+ export { AgentSessionStore, InMemorySessionStore, createInMemorySessionStore, generateSessionId };
@@ -0,0 +1,3 @@
1
+ import { AgentConfidencePolicy, AgentEscalationPolicy, AgentKnowledgeRef, AgentMemoryConfig, AgentMeta, AgentPolicy, AgentSpec, AgentToolConfig, agentKey, defineAgent } from "./spec.js";
2
+ import { AgentRegistry, createAgentRegistry } from "./registry.js";
3
+ export { AgentConfidencePolicy, AgentEscalationPolicy, AgentKnowledgeRef, AgentMemoryConfig, AgentMeta, AgentPolicy, AgentRegistry, AgentSpec, AgentToolConfig, agentKey, createAgentRegistry, defineAgent };
@@ -0,0 +1,77 @@
1
+ import { AgentSpec } from "./spec.js";
2
+
3
+ //#region src/spec/registry.d.ts
4
+
5
+ /**
6
+ * Registry for managing agent specifications.
7
+ *
8
+ * Provides registration, lookup, and version management for agent specs.
9
+ */
10
+ declare class AgentRegistry {
11
+ private readonly specs;
12
+ /**
13
+ * Register an agent specification.
14
+ *
15
+ * @param spec - The agent specification to register
16
+ * @returns This registry for chaining
17
+ * @throws Error if the spec is already registered
18
+ */
19
+ register(spec: AgentSpec): this;
20
+ /**
21
+ * Unregister an agent specification.
22
+ *
23
+ * @param name - Agent name
24
+ * @param version - Agent version
25
+ * @returns True if the spec was removed
26
+ */
27
+ unregister(name: string, version: number): boolean;
28
+ /**
29
+ * List all registered agent specifications.
30
+ */
31
+ list(): AgentSpec[];
32
+ /**
33
+ * List all unique agent names (without versions).
34
+ */
35
+ listNames(): string[];
36
+ /**
37
+ * Get an agent specification by name and optional version.
38
+ *
39
+ * @param name - Agent name
40
+ * @param version - Optional version. If omitted, returns the latest version.
41
+ * @returns The agent spec or undefined if not found
42
+ */
43
+ get(name: string, version?: number): AgentSpec | undefined;
44
+ /**
45
+ * Get an agent specification or throw if not found.
46
+ *
47
+ * @param name - Agent name
48
+ * @param version - Optional version
49
+ * @returns The agent spec
50
+ * @throws Error if the spec is not found
51
+ */
52
+ require(name: string, version?: number): AgentSpec;
53
+ /**
54
+ * Check if an agent is registered.
55
+ *
56
+ * @param name - Agent name
57
+ * @param version - Optional version
58
+ */
59
+ has(name: string, version?: number): boolean;
60
+ /**
61
+ * Get all versions of an agent.
62
+ *
63
+ * @param name - Agent name
64
+ * @returns Array of specs sorted by version (ascending)
65
+ */
66
+ getVersions(name: string): AgentSpec[];
67
+ /**
68
+ * Clear all registered specs.
69
+ */
70
+ clear(): void;
71
+ }
72
+ /**
73
+ * Create a new agent registry.
74
+ */
75
+ declare function createAgentRegistry(): AgentRegistry;
76
+ //#endregion
77
+ export { AgentRegistry, createAgentRegistry };
@@ -0,0 +1,129 @@
1
+ import { OwnerShipMeta } from "@lssm/lib.contracts/ownership";
2
+ import { KnowledgeCategory } from "@lssm/lib.contracts/knowledge/spec";
3
+ import { PolicyRef } from "@lssm/lib.contracts/policy/spec";
4
+
5
+ //#region src/spec/spec.d.ts
6
+
7
+ /**
8
+ * Metadata for an agent specification.
9
+ */
10
+ interface AgentMeta extends OwnerShipMeta {
11
+ name: string;
12
+ version: number;
13
+ }
14
+ /**
15
+ * Configuration for a tool that an agent can use.
16
+ */
17
+ interface AgentToolConfig {
18
+ /** Tool name (unique within the agent) */
19
+ name: string;
20
+ /** Human-readable description for the LLM */
21
+ description?: string;
22
+ /** JSON Schema fragment for tool parameters */
23
+ schema?: Record<string, unknown>;
24
+ /** Optional cooldown in milliseconds between invocations */
25
+ cooldownMs?: number;
26
+ /** Maximum execution time before timeout */
27
+ timeoutMs?: number;
28
+ /** Whether the tool can be executed without human approval (AI SDK needsApproval = !automationSafe) */
29
+ automationSafe?: boolean;
30
+ /** Explicit approval requirement (overrides automationSafe) */
31
+ requiresApproval?: boolean;
32
+ /** Optional policy guard that must evaluate to allow the tool call */
33
+ policy?: PolicyRef;
34
+ }
35
+ /**
36
+ * Reference to a knowledge space that the agent can access.
37
+ */
38
+ interface AgentKnowledgeRef {
39
+ /** Knowledge space key */
40
+ key: string;
41
+ /** Optional specific version */
42
+ version?: number;
43
+ /** Filter by knowledge category */
44
+ category?: KnowledgeCategory;
45
+ /** Whether the knowledge is required (static injection) or optional (dynamic RAG) */
46
+ required?: boolean;
47
+ /** Additional instructions appended when the space is available */
48
+ instructions?: string;
49
+ }
50
+ /**
51
+ * Memory configuration for agent session persistence.
52
+ */
53
+ interface AgentMemoryConfig {
54
+ /** Maximum entries to keep in memory */
55
+ maxEntries?: number;
56
+ /** Time-to-live in minutes */
57
+ ttlMinutes?: number;
58
+ /** Number of messages before triggering summarization */
59
+ summaryTrigger?: number;
60
+ /** Whether to persist to long-term storage */
61
+ persistLongTerm?: boolean;
62
+ }
63
+ /**
64
+ * Confidence policy for agent responses.
65
+ */
66
+ interface AgentConfidencePolicy {
67
+ /** Minimum acceptable confidence before escalation. Defaults to 0.7 */
68
+ min?: number;
69
+ /** Default value used when provider does not report confidence */
70
+ default?: number;
71
+ }
72
+ /**
73
+ * Escalation policy for handling uncertain or failed agent responses.
74
+ */
75
+ interface AgentEscalationPolicy {
76
+ /** Auto escalate when confidence < threshold */
77
+ confidenceThreshold?: number;
78
+ /** Escalate when a tool throws irrecoverable errors */
79
+ onToolFailure?: boolean;
80
+ /** Escalate when iteration budget exceeded */
81
+ onTimeout?: boolean;
82
+ /** Optional human approval workflow ID */
83
+ approvalWorkflow?: string;
84
+ }
85
+ /**
86
+ * Combined policy configuration for an agent.
87
+ */
88
+ interface AgentPolicy {
89
+ confidence?: AgentConfidencePolicy;
90
+ escalation?: AgentEscalationPolicy;
91
+ /** Feature flags to apply to this agent */
92
+ flags?: string[];
93
+ }
94
+ /**
95
+ * Complete specification for a ContractSpec agent.
96
+ */
97
+ interface AgentSpec {
98
+ meta: AgentMeta;
99
+ /** System instructions for the agent */
100
+ instructions: string;
101
+ /** Human-readable description */
102
+ description?: string;
103
+ /** Tags for categorization */
104
+ tags?: string[];
105
+ /** Tools the agent can use */
106
+ tools: AgentToolConfig[];
107
+ /** Memory/session configuration */
108
+ memory?: AgentMemoryConfig;
109
+ /** Knowledge spaces the agent can access */
110
+ knowledge?: AgentKnowledgeRef[];
111
+ /** Policy configuration */
112
+ policy?: AgentPolicy;
113
+ /** Maximum steps per generation (defaults to 10) */
114
+ maxSteps?: number;
115
+ }
116
+ /**
117
+ * Define and validate an agent specification.
118
+ *
119
+ * @param spec - The agent specification
120
+ * @returns The frozen, validated specification
121
+ * @throws Error if the specification is invalid
122
+ */
123
+ declare function defineAgent(spec: AgentSpec): AgentSpec;
124
+ /**
125
+ * Generate a unique key for an agent spec.
126
+ */
127
+ declare function agentKey(meta: AgentMeta): string;
128
+ //#endregion
129
+ export { AgentConfidencePolicy, AgentEscalationPolicy, AgentKnowledgeRef, AgentMemoryConfig, AgentMeta, AgentPolicy, AgentSpec, AgentToolConfig, agentKey, defineAgent };
@@ -0,0 +1,72 @@
1
+ import { StepResult, ToolSet } from "ai";
2
+
3
+ //#region src/telemetry/adapter.d.ts
4
+
5
+ /**
6
+ * Metric sample compatible with @lssm/lib.evolution OperationMetricSample.
7
+ */
8
+ interface OperationMetricSample {
9
+ operation: {
10
+ name: string;
11
+ version: number;
12
+ };
13
+ durationMs: number;
14
+ success: boolean;
15
+ timestamp: Date;
16
+ metadata?: Record<string, unknown>;
17
+ }
18
+ /**
19
+ * Interface for collecting telemetry metrics.
20
+ *
21
+ * Implementations can send metrics to:
22
+ * - @lssm/lib.evolution for self-improvement
23
+ * - PostHog for analytics
24
+ * - Custom monitoring systems
25
+ */
26
+ interface TelemetryCollector {
27
+ /**
28
+ * Collect a metric sample.
29
+ */
30
+ collect(sample: OperationMetricSample): Promise<void>;
31
+ }
32
+ /**
33
+ * Track an agent step for telemetry.
34
+ *
35
+ * Called from ContractSpecAgent.onStepFinish to feed metrics
36
+ * to the evolution engine.
37
+ *
38
+ * @param collector - Telemetry collector
39
+ * @param agentId - Agent identifier (e.g., "support.bot.v1")
40
+ * @param step - AI SDK step result
41
+ * @param durationMs - Optional step duration in milliseconds
42
+ */
43
+ declare function trackAgentStep(collector: TelemetryCollector, agentId: string, step: StepResult<ToolSet>, durationMs?: number): Promise<void>;
44
+ /**
45
+ * In-memory telemetry collector for testing.
46
+ */
47
+ declare class InMemoryTelemetryCollector implements TelemetryCollector {
48
+ private readonly samples;
49
+ collect(sample: OperationMetricSample): Promise<void>;
50
+ /**
51
+ * Get all collected samples.
52
+ */
53
+ getSamples(): OperationMetricSample[];
54
+ /**
55
+ * Get samples for a specific operation.
56
+ */
57
+ getSamplesForOperation(operationName: string): OperationMetricSample[];
58
+ /**
59
+ * Clear all samples.
60
+ */
61
+ clear(): void;
62
+ }
63
+ /**
64
+ * Create an in-memory telemetry collector.
65
+ */
66
+ declare function createInMemoryTelemetryCollector(): InMemoryTelemetryCollector;
67
+ /**
68
+ * No-op telemetry collector that discards all metrics.
69
+ */
70
+ declare const noopTelemetryCollector: TelemetryCollector;
71
+ //#endregion
72
+ export { InMemoryTelemetryCollector, OperationMetricSample, TelemetryCollector, createInMemoryTelemetryCollector, noopTelemetryCollector, trackAgentStep };
@@ -0,0 +1,2 @@
1
+ import { InMemoryTelemetryCollector, OperationMetricSample, TelemetryCollector, createInMemoryTelemetryCollector, noopTelemetryCollector, trackAgentStep } from "./adapter.js";
2
+ export { InMemoryTelemetryCollector, OperationMetricSample, TelemetryCollector, createInMemoryTelemetryCollector, noopTelemetryCollector, trackAgentStep };
@@ -0,0 +1,5 @@
1
+ import { buildToolHandlers, createToolHandler, specToolToAISDKTool, specToolsToAISDKTools } from "./tool-adapter.js";
2
+ import { createKnowledgeQueryTool } from "./knowledge-tool.js";
3
+ import { McpClientConfig, McpClientResult, createMcpToolsets, mcpServerToTools } from "./mcp-client.js";
4
+ import { AgentMcpServerConfig, agentToMcpServer, createAgentMcpServer } from "./mcp-server.js";
5
+ export { AgentMcpServerConfig, McpClientConfig, McpClientResult, agentToMcpServer, buildToolHandlers, createAgentMcpServer, createKnowledgeQueryTool, createMcpToolsets, createToolHandler, mcpServerToTools, specToolToAISDKTool, specToolsToAISDKTools };
@@ -0,0 +1,20 @@
1
+ import { AgentKnowledgeRef } from "../spec/spec.js";
2
+ import { Tool } from "ai";
3
+ import { KnowledgeRetriever } from "@lssm/lib.knowledge/retriever";
4
+
5
+ //#region src/tools/knowledge-tool.d.ts
6
+
7
+ /**
8
+ * Create a knowledge query tool for dynamic RAG.
9
+ *
10
+ * This tool allows the agent to query optional knowledge spaces
11
+ * at runtime. Required knowledge is injected statically via
12
+ * the knowledge injector.
13
+ *
14
+ * @param retriever - The knowledge retriever to use
15
+ * @param knowledgeRefs - Knowledge references from the agent spec
16
+ * @returns AI SDK CoreTool for knowledge queries
17
+ */
18
+ declare function createKnowledgeQueryTool(retriever: KnowledgeRetriever, knowledgeRefs: AgentKnowledgeRef[]): Tool<any, any> | null;
19
+ //#endregion
20
+ export { createKnowledgeQueryTool };
@@ -0,0 +1,58 @@
1
+ import { Tool } from "ai";
2
+
3
+ //#region src/tools/mcp-client.d.ts
4
+
5
+ /**
6
+ * Configuration for connecting to an MCP server.
7
+ */
8
+ interface McpClientConfig {
9
+ /** Display name for the MCP server */
10
+ name: string;
11
+ /** Command to spawn the MCP server process */
12
+ command: string;
13
+ /** Arguments to pass to the command */
14
+ args?: string[];
15
+ /** Environment variables for the process */
16
+ env?: Record<string, string>;
17
+ }
18
+ /**
19
+ * Result of creating an MCP client with tools.
20
+ */
21
+ interface McpClientResult {
22
+ /** AI SDK tools from the MCP server */
23
+ tools: Record<string, Tool<unknown, unknown>>;
24
+ /** Cleanup function to close the connection */
25
+ cleanup: () => Promise<void>;
26
+ }
27
+ /**
28
+ * Create AI SDK tools from an MCP server.
29
+ *
30
+ * This adapter allows ContractSpec agents to consume tools
31
+ * from external MCP servers (e.g., filesystem, database, etc.).
32
+ *
33
+ * @param config - MCP server configuration
34
+ * @returns Tools and cleanup function
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * const { tools, cleanup } = await mcpServerToTools({
39
+ * name: 'filesystem',
40
+ * command: 'npx',
41
+ * args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],
42
+ * });
43
+ *
44
+ * // Use tools in agent...
45
+ *
46
+ * await cleanup();
47
+ * ```
48
+ */
49
+ declare function mcpServerToTools(config: McpClientConfig): Promise<McpClientResult>;
50
+ /**
51
+ * Create multiple MCP tool sets from configurations.
52
+ *
53
+ * @param configs - Array of MCP server configurations
54
+ * @returns Combined tools and cleanup function
55
+ */
56
+ declare function createMcpToolsets(configs: McpClientConfig[]): Promise<McpClientResult>;
57
+ //#endregion
58
+ export { McpClientConfig, McpClientResult, createMcpToolsets, mcpServerToTools };
@@ -0,0 +1,45 @@
1
+ import { AgentSpec } from "../spec/spec.js";
2
+ import { ContractSpecAgent } from "../agent/contract-spec-agent.js";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+
5
+ //#region src/tools/mcp-server.d.ts
6
+
7
+ /**
8
+ * Generate an MCP server that exposes a ContractSpec agent as a tool.
9
+ *
10
+ * This allows other AI agents (e.g., Claude Desktop, Cursor) to use
11
+ * your ContractSpec agents as tools, enabling agent-to-agent composition.
12
+ *
13
+ * @param agent - The ContractSpec agent to expose
14
+ * @param spec - The agent specification
15
+ * @returns MCP Server instance
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const server = agentToMcpServer(myAgent, myAgentSpec);
20
+ *
21
+ * // Run via stdio transport
22
+ * const transport = new StdioServerTransport();
23
+ * await server.connect(transport);
24
+ * ```
25
+ */
26
+ declare function agentToMcpServer(agent: ContractSpecAgent, spec: AgentSpec): McpServer;
27
+ /**
28
+ * Configuration for running an agent as an MCP server.
29
+ */
30
+ interface AgentMcpServerConfig {
31
+ /** The agent to expose */
32
+ agent: ContractSpecAgent;
33
+ /** The agent specification */
34
+ spec: AgentSpec;
35
+ /** Optional server name override */
36
+ name?: string;
37
+ /** Optional version override */
38
+ version?: string;
39
+ }
40
+ /**
41
+ * Create an MCP server from configuration.
42
+ */
43
+ declare function createAgentMcpServer(config: AgentMcpServerConfig): McpServer;
44
+ //#endregion
45
+ export { AgentMcpServerConfig, agentToMcpServer, createAgentMcpServer };
@@ -0,0 +1,49 @@
1
+ import { AgentToolConfig } from "../spec/spec.js";
2
+ import { ToolExecutionContext, ToolHandler } from "../types.js";
3
+ import { Tool } from "ai";
4
+
5
+ //#region src/tools/tool-adapter.d.ts
6
+
7
+ /**
8
+ * Convert ContractSpec AgentToolConfig to AI SDK CoreTool.
9
+ *
10
+ * @param specTool - The tool configuration from AgentSpec
11
+ * @param handler - The handler function for the tool
12
+ * @param context - Partial context to inject into handler calls
13
+ * @returns AI SDK CoreTool
14
+ */
15
+ declare function specToolToAISDKTool(specTool: AgentToolConfig, handler: ToolHandler, context?: Partial<ToolExecutionContext>): Tool<any, any>;
16
+ /**
17
+ * Convert multiple ContractSpec tool configs to AI SDK tools.
18
+ *
19
+ * @param specTools - Array of tool configurations
20
+ * @param handlers - Map of tool name to handler function
21
+ * @param context - Partial context to inject into handler calls
22
+ * @returns Record of AI SDK tools keyed by name
23
+ */
24
+ declare function specToolsToAISDKTools(specTools: AgentToolConfig[], handlers: Map<string, ToolHandler>, context?: Partial<ToolExecutionContext>): Record<string, Tool<any, any>>;
25
+ /**
26
+ * Type-safe tool handler builder.
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const handler = createToolHandler<{ query: string }>((input, ctx) => {
31
+ * return `Searched for: ${input.query}`;
32
+ * });
33
+ * ```
34
+ */
35
+ declare function createToolHandler<TInput = unknown, TOutput = string>(handler: (input: TInput, context: ToolExecutionContext) => Promise<TOutput> | TOutput): ToolHandler<TInput, TOutput>;
36
+ /**
37
+ * Build a tool handlers map from an object.
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const handlers = buildToolHandlers({
42
+ * search: async (input: { query: string }) => `Found: ${input.query}`,
43
+ * calculate: async (input: { a: number, b: number }) => `${input.a + input.b}`,
44
+ * });
45
+ * ```
46
+ */
47
+ declare function buildToolHandlers(handlersObj: Record<string, ToolHandler>): Map<string, ToolHandler>;
48
+ //#endregion
49
+ export { buildToolHandlers, createToolHandler, specToolToAISDKTool, specToolsToAISDKTools };