@lssm/lib.ai-agent 0.0.0-canary-20251206160926

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.
Files changed (56) hide show
  1. package/README.md +41 -0
  2. package/dist/agent/agent-factory.d.ts +103 -0
  3. package/dist/agent/agent-factory.js +1 -0
  4. package/dist/agent/contract-spec-agent.d.ts +74 -0
  5. package/dist/agent/contract-spec-agent.js +1 -0
  6. package/dist/agent/index.d.ts +3 -0
  7. package/dist/agent/index.js +1 -0
  8. package/dist/approval/index.d.ts +2 -0
  9. package/dist/approval/index.js +1 -0
  10. package/dist/approval/workflow.d.ts +155 -0
  11. package/dist/approval/workflow.js +1 -0
  12. package/dist/index.d.ts +23 -0
  13. package/dist/index.js +1 -0
  14. package/dist/knowledge/index.d.ts +2 -0
  15. package/dist/knowledge/index.js +1 -0
  16. package/dist/knowledge/injector.d.ts +37 -0
  17. package/dist/knowledge/injector.js +13 -0
  18. package/dist/memory/in-memory.d.ts +21 -0
  19. package/dist/memory/in-memory.js +2 -0
  20. package/dist/memory/index.d.ts +3 -0
  21. package/dist/memory/index.js +1 -0
  22. package/dist/memory/manager.d.ts +41 -0
  23. package/dist/memory/manager.js +1 -0
  24. package/dist/schema/index.d.ts +3 -0
  25. package/dist/schema/index.js +1 -0
  26. package/dist/schema/json-schema-to-zod.d.ts +54 -0
  27. package/dist/schema/json-schema-to-zod.js +1 -0
  28. package/dist/schema/schema-output.d.ts +76 -0
  29. package/dist/schema/schema-output.js +1 -0
  30. package/dist/session/index.d.ts +2 -0
  31. package/dist/session/index.js +1 -0
  32. package/dist/session/store.d.ts +73 -0
  33. package/dist/session/store.js +1 -0
  34. package/dist/spec/index.d.ts +3 -0
  35. package/dist/spec/index.js +1 -0
  36. package/dist/spec/registry.d.ts +77 -0
  37. package/dist/spec/registry.js +1 -0
  38. package/dist/spec/spec.d.ts +129 -0
  39. package/dist/spec/spec.js +1 -0
  40. package/dist/telemetry/adapter.d.ts +72 -0
  41. package/dist/telemetry/adapter.js +1 -0
  42. package/dist/telemetry/index.d.ts +2 -0
  43. package/dist/telemetry/index.js +1 -0
  44. package/dist/tools/index.d.ts +5 -0
  45. package/dist/tools/index.js +1 -0
  46. package/dist/tools/knowledge-tool.d.ts +20 -0
  47. package/dist/tools/knowledge-tool.js +9 -0
  48. package/dist/tools/mcp-client.d.ts +58 -0
  49. package/dist/tools/mcp-client.js +1 -0
  50. package/dist/tools/mcp-server.d.ts +45 -0
  51. package/dist/tools/mcp-server.js +1 -0
  52. package/dist/tools/tool-adapter.d.ts +49 -0
  53. package/dist/tools/tool-adapter.js +1 -0
  54. package/dist/types.d.ts +194 -0
  55. package/dist/types.js +0 -0
  56. package/package.json +74 -0
package/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # @lssm/lib.ai-agent
2
+
3
+ **AI governance for ContractSpec** — Constrain what AI agents can change, enforce contracts they must respect.
4
+
5
+ Stateful AI agent orchestration with type-safe specs, tool execution, knowledge bindings, and per-tenant guardrails. Agents read contracts as their source of truth, enabling triage, growth experiments, and DevOps automation with contract-enforced safety.
6
+
7
+ ## Features
8
+
9
+ - Type-safe `AgentSpec` + registry for declarative agent definitions
10
+ - `AgentRunner` with tool calling, iteration caps, and confidence-aware escalation
11
+ - Memory framework that mixes working memory with long-term persistence hooks
12
+ - Tool registry/executor with structured input validation and telemetry hooks
13
+ - Approval workflow helpers for human-in-the-loop gates (see `/approval`)
14
+
15
+ ## Quickstart
16
+
17
+ ```ts
18
+ import { AgentRegistry, AgentRunner, defineAgent } from '@lssm/lib.ai-agent';
19
+ import { ToolExecutor } from '@lssm/lib.ai-agent/tools';
20
+ import { InMemoryAgentMemory } from '@lssm/lib.ai-agent/memory';
21
+
22
+ const SupportAgent = defineAgent({
23
+ meta: { name: 'support.bot', version: 1, owners: ['team-support'], domain: 'operations' },
24
+ instructions: 'Resolve support tickets. Escalate whenever confidence < 0.75.',
25
+ tools: [{ name: 'search_knowledge', description: 'Query support corpus', schema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] } }],
26
+ policy: { confidence: { min: 0.75 }, escalation: { auto: true } },
27
+ });
28
+
29
+ const registry = new AgentRegistry().register(SupportAgent);
30
+ const runner = new AgentRunner({
31
+ registry,
32
+ llm: mistralProvider,
33
+ toolExecutor: new ToolExecutor({ tools: [searchKnowledgeTool] }),
34
+ memoryManager: new InMemoryAgentMemory(),
35
+ });
36
+
37
+ const result = await runner.run({ agent: 'support.bot', input: 'My payout failed.', tenantId: 'acme' });
38
+ if (result.requiresEscalation) notifyHuman(result);
39
+ ```
40
+
41
+ See `examples/ai-support-bot` for a full workflow including ticket ingestion and approval queues.
@@ -0,0 +1,103 @@
1
+ import { AgentSpec } from "../spec/spec.js";
2
+ import { AgentRegistry } from "../spec/registry.js";
3
+ import { ToolHandler } from "../types.js";
4
+ import { AgentSessionStore } from "../session/store.js";
5
+ import { TelemetryCollector } from "../telemetry/adapter.js";
6
+ import { ContractSpecAgent } from "./contract-spec-agent.js";
7
+ import { LanguageModel, Tool } from "ai";
8
+ import { KnowledgeRetriever } from "@lssm/lib.knowledge/retriever";
9
+
10
+ //#region src/agent/agent-factory.d.ts
11
+
12
+ /**
13
+ * Factory configuration for creating agents.
14
+ */
15
+ interface AgentFactoryConfig {
16
+ /** Default language model to use */
17
+ defaultModel: LanguageModel;
18
+ /** Agent registry for looking up specs */
19
+ registry: AgentRegistry;
20
+ /** Global tool handlers map */
21
+ toolHandlers: Map<string, ToolHandler>;
22
+ /** Optional knowledge retriever */
23
+ knowledgeRetriever?: KnowledgeRetriever;
24
+ /** Optional session store */
25
+ sessionStore?: AgentSessionStore;
26
+ /** Optional telemetry collector */
27
+ telemetryCollector?: TelemetryCollector;
28
+ /** Additional tools to provide to all agents */
29
+ additionalTools?: Record<string, Tool<unknown, unknown>>;
30
+ }
31
+ /**
32
+ * Options for creating an agent instance.
33
+ */
34
+ interface CreateAgentOptions {
35
+ /** Override the default model */
36
+ model?: LanguageModel;
37
+ /** Additional tool handlers specific to this instance */
38
+ toolHandlers?: Map<string, ToolHandler>;
39
+ /** Additional tools for this instance */
40
+ additionalTools?: Record<string, Tool<unknown, unknown>>;
41
+ }
42
+ /**
43
+ * Factory for creating ContractSpec agents from specs.
44
+ *
45
+ * Provides a centralized way to instantiate agents with
46
+ * consistent configuration.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const factory = createAgentFactory({
51
+ * defaultModel: mistral('mistral-large-latest'),
52
+ * registry: agentRegistry,
53
+ * toolHandlers: globalToolHandlers,
54
+ * sessionStore: mySessionStore,
55
+ * });
56
+ *
57
+ * const agent = await factory.create('support.bot');
58
+ * const result = await agent.generate({ prompt: 'Help me with...' });
59
+ * ```
60
+ */
61
+ declare class AgentFactory {
62
+ private readonly config;
63
+ private readonly cache;
64
+ constructor(config: AgentFactoryConfig);
65
+ /**
66
+ * Create an agent by name.
67
+ *
68
+ * @param name - Agent name (e.g., "support.bot")
69
+ * @param version - Optional specific version
70
+ * @param options - Optional creation options
71
+ */
72
+ create(name: string, version?: number, options?: CreateAgentOptions): Promise<ContractSpecAgent>;
73
+ /**
74
+ * Create an agent from a spec directly.
75
+ *
76
+ * @param spec - Agent specification
77
+ * @param options - Optional creation options
78
+ */
79
+ createFromSpec(spec: AgentSpec, options?: CreateAgentOptions): Promise<ContractSpecAgent>;
80
+ /**
81
+ * Get or create a cached agent instance.
82
+ *
83
+ * Use this when you want to reuse agent instances.
84
+ *
85
+ * @param name - Agent name
86
+ * @param version - Optional specific version
87
+ */
88
+ getOrCreate(name: string, version?: number): Promise<ContractSpecAgent>;
89
+ /**
90
+ * Clear the agent cache.
91
+ */
92
+ clearCache(): void;
93
+ /**
94
+ * List all available agent names.
95
+ */
96
+ listAvailable(): string[];
97
+ }
98
+ /**
99
+ * Create an agent factory.
100
+ */
101
+ declare function createAgentFactory(config: AgentFactoryConfig): AgentFactory;
102
+ //#endregion
103
+ export { AgentFactory, AgentFactoryConfig, CreateAgentOptions, createAgentFactory };
@@ -0,0 +1 @@
1
+ import{ContractSpecAgent as e}from"./contract-spec-agent.js";var t=class{config;cache=new Map;constructor(e){this.config=e}async create(e,t,n){let r=this.config.registry.require(e,t);return this.createFromSpec(r,n)}async createFromSpec(t,n){let r=new Map(this.config.toolHandlers);if(n?.toolHandlers)for(let[e,t]of n.toolHandlers)r.set(e,t);let i={...this.config.additionalTools,...n?.additionalTools};return e.create({spec:t,model:n?.model??this.config.defaultModel,toolHandlers:r,knowledgeRetriever:this.config.knowledgeRetriever,sessionStore:this.config.sessionStore,telemetryCollector:this.config.telemetryCollector,additionalTools:i})}async getOrCreate(e,t){let n=this.config.registry.require(e,t),r=`${n.meta.name}.v${n.meta.version}`,i=this.cache.get(r);return i||(i=await this.createFromSpec(n),this.cache.set(r,i)),i}clearCache(){this.cache.clear()}listAvailable(){return this.config.registry.listNames()}};function n(e){return new t(e)}export{t as AgentFactory,n as createAgentFactory};
@@ -0,0 +1,74 @@
1
+ import { AgentSpec } from "../spec/spec.js";
2
+ import { AgentGenerateParams, AgentGenerateResult, AgentStreamParams, ToolHandler } from "../types.js";
3
+ import { AgentSessionStore } from "../session/store.js";
4
+ import { TelemetryCollector } from "../telemetry/adapter.js";
5
+ import * as ai0 from "ai";
6
+ import { LanguageModel, Tool, ToolSet } from "ai";
7
+ import { KnowledgeRetriever } from "@lssm/lib.knowledge/retriever";
8
+
9
+ //#region src/agent/contract-spec-agent.d.ts
10
+
11
+ /**
12
+ * Type for tool with execute function (compatible with AI SDK Tool)
13
+ * Using `any` for broad compatibility with AI SDK tool types
14
+ */
15
+ type ExecutableTool = Tool<any, any>;
16
+ /**
17
+ * Configuration for creating a ContractSpecAgent.
18
+ */
19
+ interface ContractSpecAgentConfig {
20
+ /** The agent specification */
21
+ spec: AgentSpec;
22
+ /** AI SDK language model */
23
+ model: LanguageModel;
24
+ /** Map of tool name to handler function */
25
+ toolHandlers: Map<string, ToolHandler>;
26
+ /** Optional knowledge retriever for RAG */
27
+ knowledgeRetriever?: KnowledgeRetriever;
28
+ /** Optional session store for persistence */
29
+ sessionStore?: AgentSessionStore;
30
+ /** Optional telemetry collector for evolution */
31
+ telemetryCollector?: TelemetryCollector;
32
+ /** Additional AI SDK tools (e.g., from MCP servers) */
33
+ additionalTools?: Record<string, ExecutableTool>;
34
+ }
35
+ /**
36
+ * ContractSpec Agent implementation using AI SDK v6.
37
+ *
38
+ * Integrates ContractSpec's spec-first governance with AI SDK's
39
+ * ToolLoopAgent, providing:
40
+ * - Spec-defined tools with type-safe handlers
41
+ * - Hybrid knowledge injection (static + dynamic RAG)
42
+ * - Session persistence
43
+ * - Telemetry for evolution
44
+ * - MCP interoperability
45
+ */
46
+ declare class ContractSpecAgent {
47
+ readonly version = "agent-v1";
48
+ readonly id: string;
49
+ readonly spec: AgentSpec;
50
+ readonly tools: Record<string, ExecutableTool>;
51
+ private readonly inner;
52
+ private readonly config;
53
+ private instructions;
54
+ private constructor();
55
+ /**
56
+ * Create a ContractSpecAgent instance.
57
+ * This is async because knowledge injection may need to fetch static content.
58
+ */
59
+ static create(config: ContractSpecAgentConfig): Promise<ContractSpecAgent>;
60
+ /**
61
+ * Generate a response (non-streaming).
62
+ */
63
+ generate(params: AgentGenerateParams): Promise<AgentGenerateResult>;
64
+ /**
65
+ * Stream a response with real-time updates.
66
+ */
67
+ stream(params: AgentStreamParams): Promise<ai0.StreamTextResult<ToolSet, never>>;
68
+ /**
69
+ * Handle step completion for persistence and telemetry.
70
+ */
71
+ private handleStepFinish;
72
+ }
73
+ //#endregion
74
+ export { ContractSpecAgent, ContractSpecAgentConfig };
@@ -0,0 +1 @@
1
+ import{specToolsToAISDKTools as e}from"../tools/tool-adapter.js";import{createKnowledgeQueryTool as t}from"../tools/knowledge-tool.js";import{injectStaticKnowledge as n}from"../knowledge/injector.js";import{generateSessionId as r}from"../session/store.js";import{trackAgentStep as i}from"../telemetry/adapter.js";import{agentKey as a}from"../spec/spec.js";import{Experimental_Agent as o,stepCountIs as s}from"ai";import{z as c}from"zod";const l=c.object({tenantId:c.string().optional(),actorId:c.string().optional(),sessionId:c.string().optional(),metadata:c.record(c.string(),c.unknown()).optional()});var u=class c{version=`agent-v1`;id;spec;tools;inner;config;instructions;constructor(e,t,n){this.config=e,this.spec=e.spec,this.id=a(e.spec.meta),this.tools=n,this.instructions=t,this.inner=new o({model:e.model,instructions:t,tools:n,stopWhen:s(e.spec.maxSteps??10),callOptionsSchema:l,onStepFinish:async e=>{await this.handleStepFinish(e)}})}static async create(r){let i=await n(r.spec.instructions,r.spec.knowledge??[],r.knowledgeRetriever),o=e(r.spec.tools,r.toolHandlers,{agentId:a(r.spec.meta)}),s=r.knowledgeRetriever?t(r.knowledgeRetriever,r.spec.knowledge??[]):null;return new c(r,i,{...o,...s?{query_knowledge:s}:{},...r.additionalTools??{}})}async generate(e){let t=e.options?.sessionId??r();this.config.sessionStore&&(await this.config.sessionStore.get(t)||await this.config.sessionStore.create({sessionId:t,agentId:this.id,tenantId:e.options?.tenantId,actorId:e.options?.actorId,status:`running`,messages:[],steps:[],metadata:e.options?.metadata}));let n=e.systemOverride?`${this.instructions}\n\n${e.systemOverride}\n\n${e.prompt}`:e.prompt,i=await this.inner.generate({prompt:n,abortSignal:e.signal,options:{tenantId:e.options?.tenantId,actorId:e.options?.actorId,sessionId:t,metadata:e.options?.metadata}});return this.config.sessionStore&&await this.config.sessionStore.update(t,{status:`completed`}),{text:i.text,steps:i.steps,toolCalls:i.toolCalls.map(e=>({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,args:`args`in e?e.args:`input`in e?e.input:void 0})),toolResults:i.toolResults.map(e=>({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:e.output})),finishReason:i.finishReason,usage:i.usage}}async stream(e){let t=e.options?.sessionId??r(),n=e.systemOverride?`${this.instructions}\n\n${e.systemOverride}\n\n${e.prompt}`:e.prompt;return this.inner.stream({prompt:n,abortSignal:e.signal,options:{tenantId:e.options?.tenantId,actorId:e.options?.actorId,sessionId:t,metadata:e.options?.metadata}})}async handleStepFinish(e){let t=e.options?.sessionId;t&&this.config.sessionStore&&await this.config.sessionStore.appendStep(t,e),this.config.telemetryCollector&&await i(this.config.telemetryCollector,this.id,e)}};export{u as ContractSpecAgent};
@@ -0,0 +1,3 @@
1
+ import { ContractSpecAgent, ContractSpecAgentConfig } from "./contract-spec-agent.js";
2
+ import { AgentFactory, AgentFactoryConfig, CreateAgentOptions, createAgentFactory } from "./agent-factory.js";
3
+ export { AgentFactory, AgentFactoryConfig, ContractSpecAgent, ContractSpecAgentConfig, CreateAgentOptions, createAgentFactory };
@@ -0,0 +1 @@
1
+ import{ContractSpecAgent as e}from"./contract-spec-agent.js";import{AgentFactory as t,createAgentFactory as n}from"./agent-factory.js";export{t as AgentFactory,e as ContractSpecAgent,n as createAgentFactory};
@@ -0,0 +1,2 @@
1
+ import { ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, InMemoryApprovalStore, createApprovalWorkflow } from "./workflow.js";
2
+ export { type ApprovalRequest, type ApprovalStatus, type ApprovalStore, ApprovalWorkflow, InMemoryApprovalStore, createApprovalWorkflow };
@@ -0,0 +1 @@
1
+ import{ApprovalWorkflow as e,InMemoryApprovalStore as t,createApprovalWorkflow as n}from"./workflow.js";export{e as ApprovalWorkflow,t as InMemoryApprovalStore,n as createApprovalWorkflow};
@@ -0,0 +1,155 @@
1
+ import { ToolCallInfo } from "../types.js";
2
+
3
+ //#region src/approval/workflow.d.ts
4
+ type ApprovalStatus = 'pending' | 'approved' | 'rejected';
5
+ /**
6
+ * Approval request for a tool execution.
7
+ *
8
+ * When a tool has `needsApproval: true` in AI SDK v6, the agent
9
+ * will pause and wait for approval before executing the tool.
10
+ */
11
+ interface ApprovalRequest {
12
+ /** Unique request ID */
13
+ id: string;
14
+ /** Agent session ID */
15
+ sessionId: string;
16
+ /** Agent ID */
17
+ agentId: string;
18
+ /** Tenant ID for scoping */
19
+ tenantId?: string;
20
+ /** Tool name requiring approval */
21
+ toolName: string;
22
+ /** Tool call ID from AI SDK */
23
+ toolCallId: string;
24
+ /** Tool arguments */
25
+ toolArgs: unknown;
26
+ /** Human-readable reason for approval */
27
+ reason: string;
28
+ /** When the approval was requested */
29
+ requestedAt: Date;
30
+ /** Current status */
31
+ status: ApprovalStatus;
32
+ /** Additional context payload */
33
+ payload?: Record<string, unknown>;
34
+ /** Who resolved the approval */
35
+ reviewer?: string;
36
+ /** When the approval was resolved */
37
+ resolvedAt?: Date;
38
+ /** Reviewer notes */
39
+ notes?: string;
40
+ }
41
+ /**
42
+ * Storage interface for approval requests.
43
+ */
44
+ interface ApprovalStore {
45
+ create(request: ApprovalRequest): Promise<void>;
46
+ get(id: string): Promise<ApprovalRequest | null>;
47
+ getByToolCallId(toolCallId: string): Promise<ApprovalRequest | null>;
48
+ update(id: string, updates: Partial<Omit<ApprovalRequest, 'id' | 'sessionId'>>): Promise<void>;
49
+ list(options?: {
50
+ status?: ApprovalStatus;
51
+ agentId?: string;
52
+ tenantId?: string;
53
+ }): Promise<ApprovalRequest[]>;
54
+ }
55
+ /**
56
+ * In-memory approval store for development and testing.
57
+ */
58
+ declare class InMemoryApprovalStore implements ApprovalStore {
59
+ private readonly items;
60
+ create(request: ApprovalRequest): Promise<void>;
61
+ get(id: string): Promise<ApprovalRequest | null>;
62
+ getByToolCallId(toolCallId: string): Promise<ApprovalRequest | null>;
63
+ update(id: string, updates: Partial<Omit<ApprovalRequest, 'id' | 'sessionId'>>): Promise<void>;
64
+ list(options?: {
65
+ status?: ApprovalStatus;
66
+ agentId?: string;
67
+ tenantId?: string;
68
+ }): Promise<ApprovalRequest[]>;
69
+ clear(): void;
70
+ }
71
+ /**
72
+ * Approval workflow for managing tool execution approvals.
73
+ *
74
+ * Integrates with AI SDK v6's `needsApproval` feature on tools.
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * const workflow = new ApprovalWorkflow();
79
+ *
80
+ * // When a tool needs approval
81
+ * const request = await workflow.requestApproval({
82
+ * sessionId: 'sess_123',
83
+ * agentId: 'support.bot.v1',
84
+ * toolName: 'delete_account',
85
+ * toolCallId: 'call_abc',
86
+ * toolArgs: { userId: 'user_123' },
87
+ * reason: 'Account deletion requires human approval',
88
+ * });
89
+ *
90
+ * // When approval is granted
91
+ * await workflow.approve(request.id, 'admin@example.com', 'Verified identity');
92
+ *
93
+ * // Or rejected
94
+ * await workflow.reject(request.id, 'admin@example.com', 'Suspicious activity');
95
+ * ```
96
+ */
97
+ declare class ApprovalWorkflow {
98
+ private readonly store;
99
+ constructor(store?: ApprovalStore);
100
+ /**
101
+ * Request approval for a tool execution.
102
+ */
103
+ requestApproval(params: {
104
+ sessionId: string;
105
+ agentId: string;
106
+ tenantId?: string;
107
+ toolName: string;
108
+ toolCallId: string;
109
+ toolArgs: unknown;
110
+ reason: string;
111
+ payload?: Record<string, unknown>;
112
+ }): Promise<ApprovalRequest>;
113
+ /**
114
+ * Request approval from an AI SDK tool call.
115
+ */
116
+ requestApprovalFromToolCall(toolCall: ToolCallInfo, context: {
117
+ sessionId: string;
118
+ agentId: string;
119
+ tenantId?: string;
120
+ reason?: string;
121
+ }): Promise<ApprovalRequest>;
122
+ /**
123
+ * Approve a pending request.
124
+ */
125
+ approve(id: string, reviewer: string, notes?: string): Promise<void>;
126
+ /**
127
+ * Reject a pending request.
128
+ */
129
+ reject(id: string, reviewer: string, notes?: string): Promise<void>;
130
+ /**
131
+ * Get approval status for a tool call.
132
+ */
133
+ getStatus(toolCallId: string): Promise<ApprovalStatus | null>;
134
+ /**
135
+ * Check if a tool call is approved.
136
+ */
137
+ isApproved(toolCallId: string): Promise<boolean>;
138
+ /**
139
+ * List pending approvals.
140
+ */
141
+ listPending(options?: {
142
+ agentId?: string;
143
+ tenantId?: string;
144
+ }): Promise<ApprovalRequest[]>;
145
+ /**
146
+ * Get approval request by ID.
147
+ */
148
+ get(id: string): Promise<ApprovalRequest | null>;
149
+ }
150
+ /**
151
+ * Create an approval workflow instance.
152
+ */
153
+ declare function createApprovalWorkflow(store?: ApprovalStore): ApprovalWorkflow;
154
+ //#endregion
155
+ export { ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, InMemoryApprovalStore, createApprovalWorkflow };
@@ -0,0 +1 @@
1
+ import{randomUUID as e}from"node:crypto";var t=class{items=new Map;async create(e){this.items.set(e.id,e)}async get(e){return this.items.get(e)??null}async getByToolCallId(e){for(let t of this.items.values())if(t.toolCallId===e)return t;return null}async update(e,t){let n=this.items.get(e);n&&this.items.set(e,{...n,...t})}async list(e){let t=[...this.items.values()];return e?.status&&(t=t.filter(t=>t.status===e.status)),e?.agentId&&(t=t.filter(t=>t.agentId===e.agentId)),e?.tenantId&&(t=t.filter(t=>t.tenantId===e.tenantId)),t.sort((e,t)=>t.requestedAt.getTime()-e.requestedAt.getTime())}clear(){this.items.clear()}},n=class{constructor(e=new t){this.store=e}async requestApproval(t){let n={id:e(),sessionId:t.sessionId,agentId:t.agentId,tenantId:t.tenantId,toolName:t.toolName,toolCallId:t.toolCallId,toolArgs:t.toolArgs,reason:t.reason,requestedAt:new Date,status:`pending`,payload:t.payload};return await this.store.create(n),n}async requestApprovalFromToolCall(e,t){return this.requestApproval({sessionId:t.sessionId,agentId:t.agentId,tenantId:t.tenantId,toolName:e.toolName,toolCallId:e.toolCallId,toolArgs:e.args,reason:t.reason??`Tool "${e.toolName}" requires approval`})}async approve(e,t,n){await this.store.update(e,{status:`approved`,reviewer:t,resolvedAt:new Date,notes:n})}async reject(e,t,n){await this.store.update(e,{status:`rejected`,reviewer:t,resolvedAt:new Date,notes:n})}async getStatus(e){return(await this.store.getByToolCallId(e))?.status??null}async isApproved(e){return await this.getStatus(e)===`approved`}async listPending(e){return this.store.list({...e,status:`pending`})}async get(e){return this.store.get(e)}};function r(e){return new n(e)}export{n as ApprovalWorkflow,t as InMemoryApprovalStore,r as createApprovalWorkflow};
@@ -0,0 +1,23 @@
1
+ import { AgentConfidencePolicy, AgentEscalationPolicy, AgentKnowledgeRef, AgentMemoryConfig, AgentMeta, AgentPolicy, AgentSpec, AgentToolConfig, agentKey, defineAgent } from "./spec/spec.js";
2
+ import { AgentRegistry, createAgentRegistry } from "./spec/registry.js";
3
+ import { AgentCallOptions, AgentEventEmitter, AgentEventName, AgentEventPayload, AgentGenerateParams, AgentGenerateResult, AgentMessage, AgentRunRequestInput, AgentRunResult, AgentSessionState, AgentStatus, AgentStepMetrics, AgentStreamParams, AgentToolContext, AgentToolInvocation, AgentToolResult, ToolCallInfo, ToolExecutionContext, ToolHandler, ToolResultInfo } from "./types.js";
4
+ import { AgentSessionStore, InMemorySessionStore, createInMemorySessionStore, generateSessionId } from "./session/store.js";
5
+ import { InMemoryTelemetryCollector, OperationMetricSample, TelemetryCollector, createInMemoryTelemetryCollector, noopTelemetryCollector, trackAgentStep } from "./telemetry/adapter.js";
6
+ import { ContractSpecAgent, ContractSpecAgentConfig } from "./agent/contract-spec-agent.js";
7
+ import { AgentFactory, AgentFactoryConfig, CreateAgentOptions, createAgentFactory } from "./agent/agent-factory.js";
8
+ import "./agent/index.js";
9
+ import { ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, InMemoryApprovalStore, createApprovalWorkflow } from "./approval/workflow.js";
10
+ import "./approval/index.js";
11
+ import { buildToolHandlers, createToolHandler, specToolToAISDKTool, specToolsToAISDKTools } from "./tools/tool-adapter.js";
12
+ import { createKnowledgeQueryTool } from "./tools/knowledge-tool.js";
13
+ import { McpClientConfig, McpClientResult, createMcpToolsets, mcpServerToTools } from "./tools/mcp-client.js";
14
+ import { AgentMcpServerConfig, agentToMcpServer, createAgentMcpServer } from "./tools/mcp-server.js";
15
+ import "./tools/index.js";
16
+ import { jsonSchemaToZod, jsonSchemaToZodSafe } from "./schema/json-schema-to-zod.js";
17
+ import { SchemaOutput, enumToChoiceOutput, jsonSchemaToArrayOutput, jsonSchemaToOutput, textOutput, zodToOutput } from "./schema/schema-output.js";
18
+ import "./schema/index.js";
19
+ import { createKnowledgeInjector, injectStaticKnowledge } from "./knowledge/injector.js";
20
+ import "./session/index.js";
21
+ import "./telemetry/index.js";
22
+ import { Experimental_Agent as ToolLoopAgent, LanguageModel, LanguageModelUsage, ModelMessage, StepResult, Tool, ToolSet } from "ai";
23
+ export { AgentCallOptions, AgentConfidencePolicy, AgentEscalationPolicy, AgentEventEmitter, AgentEventName, AgentEventPayload, AgentFactory, AgentFactoryConfig, AgentGenerateParams, AgentGenerateResult, AgentKnowledgeRef, AgentMcpServerConfig, AgentMemoryConfig, AgentMessage, AgentMeta, AgentPolicy, AgentRegistry, AgentRunRequestInput, AgentRunResult, AgentSessionState, AgentSessionStore, AgentSpec, AgentStatus, AgentStepMetrics, AgentStreamParams, AgentToolConfig, AgentToolContext, AgentToolInvocation, AgentToolResult, ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, ContractSpecAgent, ContractSpecAgentConfig, CreateAgentOptions, InMemoryApprovalStore, InMemorySessionStore, InMemoryTelemetryCollector, type LanguageModel, type LanguageModelUsage, McpClientConfig, McpClientResult, type ModelMessage, OperationMetricSample, SchemaOutput, type StepResult, TelemetryCollector, type Tool, ToolCallInfo, ToolExecutionContext, ToolHandler, ToolLoopAgent, ToolResultInfo, type ToolSet, agentKey, agentToMcpServer, buildToolHandlers, createAgentFactory, createAgentMcpServer, createAgentRegistry, createApprovalWorkflow, createInMemorySessionStore, createInMemoryTelemetryCollector, createKnowledgeInjector, createKnowledgeQueryTool, createMcpToolsets, createToolHandler, defineAgent, enumToChoiceOutput, generateSessionId, injectStaticKnowledge, jsonSchemaToArrayOutput, jsonSchemaToOutput, jsonSchemaToZod, jsonSchemaToZodSafe, mcpServerToTools, noopTelemetryCollector, specToolToAISDKTool, specToolsToAISDKTools, textOutput, trackAgentStep, zodToOutput };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{jsonSchemaToZod as e,jsonSchemaToZodSafe as t}from"./schema/json-schema-to-zod.js";import{buildToolHandlers as n,createToolHandler as r,specToolToAISDKTool as i,specToolsToAISDKTools as a}from"./tools/tool-adapter.js";import{createKnowledgeQueryTool as o}from"./tools/knowledge-tool.js";import{createKnowledgeInjector as s,injectStaticKnowledge as c}from"./knowledge/injector.js";import{InMemorySessionStore as l,createInMemorySessionStore as u,generateSessionId as d}from"./session/store.js";import{InMemoryTelemetryCollector as f,createInMemoryTelemetryCollector as p,noopTelemetryCollector as m,trackAgentStep as h}from"./telemetry/adapter.js";import{agentKey as g,defineAgent as _}from"./spec/spec.js";import{ContractSpecAgent as v}from"./agent/contract-spec-agent.js";import{AgentFactory as y,createAgentFactory as b}from"./agent/agent-factory.js";import"./agent/index.js";import{AgentRegistry as x,createAgentRegistry as S}from"./spec/registry.js";import{createMcpToolsets as C,mcpServerToTools as w}from"./tools/mcp-client.js";import{agentToMcpServer as T,createAgentMcpServer as E}from"./tools/mcp-server.js";import"./tools/index.js";import{SchemaOutput as D,enumToChoiceOutput as O,jsonSchemaToArrayOutput as k,jsonSchemaToOutput as A,textOutput as j,zodToOutput as M}from"./schema/schema-output.js";import"./schema/index.js";import{ApprovalWorkflow as N,InMemoryApprovalStore as P,createApprovalWorkflow as F}from"./approval/workflow.js";import"./approval/index.js";import{Experimental_Agent as I}from"ai";export{y as AgentFactory,x as AgentRegistry,N as ApprovalWorkflow,v as ContractSpecAgent,P as InMemoryApprovalStore,l as InMemorySessionStore,f as InMemoryTelemetryCollector,D as SchemaOutput,I as ToolLoopAgent,g as agentKey,T as agentToMcpServer,n as buildToolHandlers,b as createAgentFactory,E as createAgentMcpServer,S as createAgentRegistry,F as createApprovalWorkflow,u as createInMemorySessionStore,p as createInMemoryTelemetryCollector,s as createKnowledgeInjector,o as createKnowledgeQueryTool,C as createMcpToolsets,r as createToolHandler,_ as defineAgent,O as enumToChoiceOutput,d as generateSessionId,c as injectStaticKnowledge,k as jsonSchemaToArrayOutput,A as jsonSchemaToOutput,e as jsonSchemaToZod,t as jsonSchemaToZodSafe,w as mcpServerToTools,m as noopTelemetryCollector,i as specToolToAISDKTool,a as specToolsToAISDKTools,j as textOutput,h as trackAgentStep,M as zodToOutput};
@@ -0,0 +1,2 @@
1
+ import { createKnowledgeInjector, injectStaticKnowledge } from "./injector.js";
2
+ export { createKnowledgeInjector, injectStaticKnowledge };
@@ -0,0 +1 @@
1
+ import{createKnowledgeInjector as e,injectStaticKnowledge as t}from"./injector.js";export{e as createKnowledgeInjector,t as injectStaticKnowledge};
@@ -0,0 +1,37 @@
1
+ import { AgentKnowledgeRef } from "../spec/spec.js";
2
+ import { KnowledgeRetriever } from "@lssm/lib.knowledge/retriever";
3
+
4
+ //#region src/knowledge/injector.d.ts
5
+
6
+ /**
7
+ * Inject static knowledge into agent instructions.
8
+ *
9
+ * This function handles the "required" knowledge that should be
10
+ * injected into the system prompt at agent initialization time.
11
+ * Optional knowledge is handled by the knowledge query tool.
12
+ *
13
+ * @param instructions - Base agent instructions
14
+ * @param knowledgeRefs - Knowledge references from the agent spec
15
+ * @param retriever - Optional knowledge retriever
16
+ * @returns Instructions with injected knowledge
17
+ */
18
+ declare function injectStaticKnowledge(instructions: string, knowledgeRefs: AgentKnowledgeRef[], retriever?: KnowledgeRetriever): Promise<string>;
19
+ /**
20
+ * Create a knowledge injector instance for reuse.
21
+ */
22
+ declare function createKnowledgeInjector(retriever?: KnowledgeRetriever): {
23
+ /**
24
+ * Inject static knowledge into instructions.
25
+ */
26
+ inject: (instructions: string, knowledgeRefs: AgentKnowledgeRef[]) => Promise<string>;
27
+ /**
28
+ * Check if a knowledge space is available.
29
+ */
30
+ hasSpace: (spaceKey: string) => boolean;
31
+ /**
32
+ * List available knowledge spaces.
33
+ */
34
+ listSpaces: () => string[];
35
+ };
36
+ //#endregion
37
+ export { createKnowledgeInjector, injectStaticKnowledge };
@@ -0,0 +1,13 @@
1
+ async function e(e,t,n){if(!n)return e;let r=t.filter(e=>e.required);if(r.length===0)return e;let i=[];for(let e of r){if(!n.supportsSpace(e.key)){console.warn(`Required knowledge space "${e.key}" is not available`);continue}try{let t=await n.getStatic(e.key);if(t){let n=e.instructions?`## ${e.key}\n${e.instructions}`:`## ${e.key}`;i.push(`${n}\n\n${t}`)}}catch(t){console.warn(`Failed to load required knowledge "${e.key}":`,t)}}return i.length===0?e:`${e}
2
+
3
+ ---
4
+
5
+ # Reference Knowledge
6
+
7
+ The following information is provided for your reference. Use it to inform your responses.
8
+
9
+ ${i.join(`
10
+
11
+ ---
12
+
13
+ `)}`}function t(t){return{inject:(n,r)=>e(n,r,t),hasSpace:e=>t?.supportsSpace(e)??!1,listSpaces:()=>t?.listSpaces()??[]}}export{t as createKnowledgeInjector,e as injectStaticKnowledge};
@@ -0,0 +1,21 @@
1
+ import { AgentSessionState } from "../types.js";
2
+ import { AgentMemorySnapshot, AgentSessionMemory, BaseAgentMemoryManager } from "./manager.js";
3
+
4
+ //#region src/memory/in-memory.d.ts
5
+ interface InMemoryAgentMemoryOptions {
6
+ ttlMinutes?: number;
7
+ maxEntries?: number;
8
+ }
9
+ declare class InMemoryAgentMemory extends BaseAgentMemoryManager {
10
+ private readonly ttlMs;
11
+ private readonly maxEntries;
12
+ private readonly store;
13
+ constructor(options?: InMemoryAgentMemoryOptions);
14
+ load(sessionId: string): Promise<AgentSessionMemory | null>;
15
+ save(snapshot: AgentSessionMemory): Promise<void>;
16
+ summarize(session: AgentSessionState): Promise<AgentMemorySnapshot>;
17
+ private trim;
18
+ private evictExpired;
19
+ }
20
+ //#endregion
21
+ export { InMemoryAgentMemory, InMemoryAgentMemoryOptions };
@@ -0,0 +1,2 @@
1
+ import{BaseAgentMemoryManager as e}from"./manager.js";var t=class extends e{ttlMs;maxEntries;store=new Map;constructor(e){super(),this.ttlMs=(e?.ttlMinutes??60)*60*1e3,this.maxEntries=e?.maxEntries??250}async load(e){this.evictExpired();let t=this.store.get(e);return t?(t.data.session.updatedAt=new Date,t.expiresAt=Date.now()+this.ttlMs,t.data):null}async save(e){this.trim(e.memory.entries),this.store.set(e.session.sessionId,{data:e,expiresAt:Date.now()+this.ttlMs})}async summarize(e){let t=await this.load(e.sessionId)??this.bootstrapMemory(e),n=t.memory.entries.slice(-10).map(e=>`- ${e.type}: ${e.content}`).join(`
2
+ `);return t.memory.summary=n,t.memory.lastSummarizedAt=new Date,await this.save(t),t.memory}trim(e){e.length<=this.maxEntries||e.splice(0,e.length-this.maxEntries)}evictExpired(){let e=Date.now();for(let[t,n]of this.store.entries())n.expiresAt<=e&&this.store.delete(t)}};export{t as InMemoryAgentMemory};
@@ -0,0 +1,3 @@
1
+ import { AgentMemoryEntry, AgentMemoryManager, AgentMemorySnapshot, AgentSessionMemory, BaseAgentMemoryManager, trackMessageInMemory } from "./manager.js";
2
+ import { InMemoryAgentMemory, InMemoryAgentMemoryOptions } from "./in-memory.js";
3
+ export { AgentMemoryEntry, AgentMemoryManager, AgentMemorySnapshot, AgentSessionMemory, BaseAgentMemoryManager, InMemoryAgentMemory, InMemoryAgentMemoryOptions, trackMessageInMemory };
@@ -0,0 +1 @@
1
+ import{BaseAgentMemoryManager as e,trackMessageInMemory as t}from"./manager.js";import{InMemoryAgentMemory as n}from"./in-memory.js";export{e as BaseAgentMemoryManager,n as InMemoryAgentMemory,t as trackMessageInMemory};
@@ -0,0 +1,41 @@
1
+ import { AgentMessage, AgentSessionState } from "../types.js";
2
+
3
+ //#region src/memory/manager.d.ts
4
+ interface AgentMemoryEntry {
5
+ id: string;
6
+ type: 'user' | 'assistant' | 'tool' | 'system';
7
+ content: string;
8
+ createdAt: Date;
9
+ metadata?: Record<string, string>;
10
+ }
11
+ interface AgentMemorySnapshot {
12
+ entries: AgentMemoryEntry[];
13
+ summary?: string;
14
+ lastSummarizedAt?: Date;
15
+ }
16
+ interface AgentSessionMemory {
17
+ session: AgentSessionState;
18
+ memory: AgentMemorySnapshot;
19
+ }
20
+ interface AgentMemoryManager {
21
+ load(sessionId: string): Promise<AgentSessionMemory | null>;
22
+ save(snapshot: AgentSessionMemory): Promise<void>;
23
+ append(session: AgentSessionState, entry: Omit<AgentMemoryEntry, 'id' | 'createdAt'> & {
24
+ createdAt?: Date;
25
+ }): Promise<AgentSessionMemory>;
26
+ summarize(session: AgentSessionState): Promise<AgentMemorySnapshot | undefined>;
27
+ prune(session: AgentSessionState): Promise<void>;
28
+ }
29
+ declare abstract class BaseAgentMemoryManager implements AgentMemoryManager {
30
+ abstract load(sessionId: string): Promise<AgentSessionMemory | null>;
31
+ abstract save(snapshot: AgentSessionMemory): Promise<void>;
32
+ append(session: AgentSessionState, entry: Omit<AgentMemoryEntry, 'id' | 'createdAt'> & {
33
+ createdAt?: Date;
34
+ }): Promise<AgentSessionMemory>;
35
+ summarize(_session: AgentSessionState): Promise<AgentMemorySnapshot | undefined>;
36
+ prune(_session: AgentSessionState): Promise<void>;
37
+ protected bootstrapMemory(session: AgentSessionState): AgentSessionMemory;
38
+ }
39
+ declare function trackMessageInMemory(manager: AgentMemoryManager | undefined, session: AgentSessionState, message: AgentMessage): void;
40
+ //#endregion
41
+ export { AgentMemoryEntry, AgentMemoryManager, AgentMemorySnapshot, AgentSessionMemory, BaseAgentMemoryManager, trackMessageInMemory };
@@ -0,0 +1 @@
1
+ import{randomUUID as e}from"node:crypto";function t(e){let t=e.content;return typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e==`string`?e:`text`in e&&typeof e.text==`string`?e.text:``).filter(Boolean).join(``):``}function n(e){let t=e.content;return typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e==`string`?e:`text`in e&&typeof e.text==`string`?e.text:``).filter(Boolean).join(``):``}function r(e){switch(e){case`assistant`:return`assistant`;case`system`:return`system`;case`tool`:return`tool`;case`user`:default:return`user`}}var i=class{async append(t,n){let r=await this.load(t.sessionId)??this.bootstrapMemory(t),i={id:e(),createdAt:n.createdAt??new Date,...n};return r.memory.entries.push(i),await this.save(r),r}async summarize(e){}async prune(e){}bootstrapMemory(n){return{session:n,memory:{entries:n.messages.map(n=>({id:e(),createdAt:new Date,type:r(n.role),content:t(n)}))}}}};function a(e,t,r){e&&e.append(t,{type:r.role,content:n(r),metadata:r.metadata})}export{i as BaseAgentMemoryManager,a as trackMessageInMemory};
@@ -0,0 +1,3 @@
1
+ import { jsonSchemaToZod, jsonSchemaToZodSafe } from "./json-schema-to-zod.js";
2
+ import { SchemaOutput, enumToChoiceOutput, jsonSchemaToArrayOutput, jsonSchemaToOutput, textOutput, zodToOutput } from "./schema-output.js";
3
+ export { SchemaOutput, enumToChoiceOutput, jsonSchemaToArrayOutput, jsonSchemaToOutput, jsonSchemaToZod, jsonSchemaToZodSafe, textOutput, zodToOutput };
@@ -0,0 +1 @@
1
+ import{jsonSchemaToZod as e,jsonSchemaToZodSafe as t}from"./json-schema-to-zod.js";import{SchemaOutput as n,enumToChoiceOutput as r,jsonSchemaToArrayOutput as i,jsonSchemaToOutput as a,textOutput as o,zodToOutput as s}from"./schema-output.js";export{n as SchemaOutput,r as enumToChoiceOutput,i as jsonSchemaToArrayOutput,a as jsonSchemaToOutput,e as jsonSchemaToZod,t as jsonSchemaToZodSafe,o as textOutput,s as zodToOutput};
@@ -0,0 +1,54 @@
1
+ import { ZodType } from "zod";
2
+
3
+ //#region src/schema/json-schema-to-zod.d.ts
4
+
5
+ /**
6
+ * JSON Schema type definitions for conversion.
7
+ */
8
+ interface JsonSchema {
9
+ type?: string;
10
+ properties?: Record<string, JsonSchema>;
11
+ required?: string[];
12
+ items?: JsonSchema;
13
+ enum?: (string | number | boolean)[];
14
+ const?: unknown;
15
+ anyOf?: JsonSchema[];
16
+ oneOf?: JsonSchema[];
17
+ allOf?: JsonSchema[];
18
+ description?: string;
19
+ default?: unknown;
20
+ minimum?: number;
21
+ maximum?: number;
22
+ minLength?: number;
23
+ maxLength?: number;
24
+ pattern?: string;
25
+ format?: string;
26
+ nullable?: boolean;
27
+ [key: string]: unknown;
28
+ }
29
+ /**
30
+ * Convert a JSON Schema to a Zod schema.
31
+ *
32
+ * Supports common JSON Schema types and constraints:
33
+ * - string, number, integer, boolean, null
34
+ * - object with properties and required
35
+ * - array with items
36
+ * - enum and const
37
+ * - anyOf, oneOf, allOf
38
+ * - format constraints (email, uri, uuid, date-time)
39
+ * - numeric constraints (minimum, maximum)
40
+ * - string constraints (minLength, maxLength, pattern)
41
+ *
42
+ * @param schema - JSON Schema object
43
+ * @returns Zod schema
44
+ */
45
+ declare function jsonSchemaToZod(schema: JsonSchema | Record<string, unknown>): ZodType;
46
+ /**
47
+ * Convert a JSON Schema to a Zod schema with a default empty object fallback.
48
+ *
49
+ * @param schema - Optional JSON Schema object
50
+ * @returns Zod schema (defaults to empty object schema)
51
+ */
52
+ declare function jsonSchemaToZodSafe(schema?: Record<string, unknown>): ZodType;
53
+ //#endregion
54
+ export { jsonSchemaToZod, jsonSchemaToZodSafe };