@lssm/lib.ai-agent 0.2.0

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.
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # @lssm/lib.ai-agent
2
+
3
+ Stateful AI agent orchestration for ContractSpec apps. The library wraps LLM providers, tool execution, knowledge bindings, and per-tenant guardrails so that agents can triage tickets, run growth experiments, or automate DevOps tasks with the same primitives used by workflows.
4
+
5
+ ## Features
6
+
7
+ - Type-safe `AgentSpec` + registry for declarative agent definitions
8
+ - `AgentRunner` with tool calling, iteration caps, and confidence-aware escalation
9
+ - Memory framework that mixes working memory with long-term persistence hooks
10
+ - Tool registry/executor with structured input validation and telemetry hooks
11
+ - Approval workflow helpers for human-in-the-loop gates (see `/approval`)
12
+
13
+ ## Quickstart
14
+
15
+ ```ts
16
+ import { AgentRegistry, AgentRunner, defineAgent } from '@lssm/lib.ai-agent';
17
+ import { ToolExecutor } from '@lssm/lib.ai-agent/tools';
18
+ import { InMemoryAgentMemory } from '@lssm/lib.ai-agent/memory';
19
+
20
+ const SupportAgent = defineAgent({
21
+ meta: { name: 'support.bot', version: 1, owners: ['team-support'], domain: 'operations' },
22
+ instructions: 'Resolve support tickets. Escalate whenever confidence < 0.75.',
23
+ tools: [{ name: 'search_knowledge', description: 'Query support corpus', schema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] } }],
24
+ policy: { confidence: { min: 0.75 }, escalation: { auto: true } },
25
+ });
26
+
27
+ const registry = new AgentRegistry().register(SupportAgent);
28
+ const runner = new AgentRunner({
29
+ registry,
30
+ llm: mistralProvider,
31
+ toolExecutor: new ToolExecutor({ tools: [searchKnowledgeTool] }),
32
+ memoryManager: new InMemoryAgentMemory(),
33
+ });
34
+
35
+ const result = await runner.run({ agent: 'support.bot', input: 'My payout failed.', tenantId: 'acme' });
36
+ if (result.requiresEscalation) notifyHuman(result);
37
+ ```
38
+
39
+ See `examples/ai-support-bot` for a full workflow including ticket ingestion and approval queues.
@@ -0,0 +1,2 @@
1
+ import { ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, ApprovalWorkflowOptions, InMemoryApprovalStore } from "./workflow.js";
2
+ export { ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, ApprovalWorkflowOptions, InMemoryApprovalStore };
@@ -0,0 +1 @@
1
+ import{ApprovalWorkflow as e,InMemoryApprovalStore as t}from"./workflow.js";export{e as ApprovalWorkflow,t as InMemoryApprovalStore};
@@ -0,0 +1,41 @@
1
+ import { AgentSessionState } from "../types.js";
2
+
3
+ //#region src/approval/workflow.d.ts
4
+ type ApprovalStatus = 'pending' | 'approved' | 'rejected';
5
+ interface ApprovalRequest {
6
+ id: string;
7
+ sessionId: string;
8
+ agent: string;
9
+ tenantId?: string;
10
+ reason: string;
11
+ requestedAt: Date;
12
+ status: ApprovalStatus;
13
+ payload?: Record<string, unknown>;
14
+ reviewer?: string;
15
+ resolvedAt?: Date;
16
+ notes?: string;
17
+ }
18
+ interface ApprovalStore {
19
+ create(request: ApprovalRequest): Promise<void>;
20
+ update(id: string, updates: Partial<Omit<ApprovalRequest, 'id' | 'sessionId'>>): Promise<void>;
21
+ list(status?: ApprovalStatus): Promise<ApprovalRequest[]>;
22
+ }
23
+ declare class InMemoryApprovalStore implements ApprovalStore {
24
+ private readonly items;
25
+ create(request: ApprovalRequest): Promise<void>;
26
+ update(id: string, updates: Partial<Omit<ApprovalRequest, 'id' | 'sessionId'>>): Promise<void>;
27
+ list(status?: ApprovalStatus): Promise<ApprovalRequest[]>;
28
+ }
29
+ interface ApprovalWorkflowOptions {
30
+ store?: ApprovalStore;
31
+ }
32
+ declare class ApprovalWorkflow {
33
+ private readonly store;
34
+ constructor(store?: ApprovalStore);
35
+ requestApproval(session: AgentSessionState, reason: string, payload?: Record<string, unknown>): Promise<ApprovalRequest>;
36
+ resolve(id: string, status: Exclude<ApprovalStatus, 'pending'>, reviewer: string, notes?: string): Promise<void>;
37
+ listPending(): Promise<ApprovalRequest[]>;
38
+ }
39
+ //#endregion
40
+ export { ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, ApprovalWorkflowOptions, InMemoryApprovalStore };
41
+ //# sourceMappingURL=workflow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.d.ts","names":[],"sources":["../../src/approval/workflow.ts"],"sourcesContent":[],"mappings":";;;KAGY,cAAA;UAEK,eAAA;EAFL,EAAA,EAAA,MAAA;EAEK,SAAA,EAAA,MAAA;EAMF,KAAA,EAAA,MAAA;EACL,QAAA,CAAA,EAAA,MAAA;EACE,MAAA,EAAA,MAAA;EAEG,WAAA,EAJA,IAIA;EAAI,MAAA,EAHT,cAGS;EAIF,OAAA,CAAA,EANL,MAMkB,CAAA,MAAA,EAAA,OAAA,CAAA;EACZ,QAAA,CAAA,EAAA,MAAA;EAAkB,UAAA,CAAA,EALrB,IAKqB;EAGV,KAAA,CAAA,EAAA,MAAA;;AAAb,UAJI,aAAA,CAIJ;EACR,MAAA,CAAA,OAAA,EAJa,eAIb,CAAA,EAJ+B,OAI/B,CAAA,IAAA,CAAA;EACW,MAAA,CAAA,EAAA,EAAA,MAAA,EAAA,OAAA,EAFH,OAEG,CAFK,IAEL,CAFU,eAEV,EAAA,IAAA,GAAA,WAAA,CAAA,CAAA,CAAA,EADX,OACW,CAAA,IAAA,CAAA;EAAyB,IAAA,CAAA,MAAA,CAAA,EAAzB,cAAyB,CAAA,EAAR,OAAQ,CAAA,eAAA,EAAA,CAAA;;AAAD,cAG3B,qBAAA,YAAiC,aAHN,CAAA;EAG3B,iBAAA,KAAA;EAGW,MAAA,CAAA,OAAA,EAAA,eAAA,CAAA,EAAkB,OAAlB,CAAA,IAAA,CAAA;EAAkB,MAAA,CAAA,EAAA,EAAA,MAAA,EAAA,OAAA,EAM7B,OAN6B,CAMrB,IANqB,CAMhB,eANgB,EAAA,IAAA,GAAA,WAAA,CAAA,CAAA,CAAA,EAOrC,OAPqC,CAAA,IAAA,CAAA;EAMhB,IAAA,CAAA,MAAA,CAAA,EAOJ,cAPI,CAAA,EAOa,OAPb,CAOqB,eAPrB,EAAA,CAAA;;AAAb,UAcI,uBAAA,CAdJ;EACR,KAAA,CAAA,EAcK,aAdL;;AAM0C,cAWlC,gBAAA,CAXkC;EAAR,iBAAA,KAAA;EAhBO,WAAA,CAAA,KAAA,CAAA,EA6BlB,aA7BkB;EAAa,eAAA,CAAA,OAAA,EAiC9C,iBAjC8C,EAAA,MAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EAmC7C,MAnC6C,CAAA,MAAA,EAAA,OAAA,CAAA,CAAA,EAmCtB,OAnCsB,CAmCtB,eAnCsB,CAAA;EAuB1C,OAAA,CAAA,EAAA,EAAA,MAAA,EAAA,MAAuB,EA8B5B,OA9B4B,CA8BpB,cA7BV,EAAa,SAAA,CAAA,EAAA,QAAA,EAAA,MAAA,EAAA,KAAA,CAAA,EAAA,MAAA,CAAA,EA+BL,OA/BK,CAAA,IAAA,CAAA;EAGV,WAAA,CAAA,CAAA,EAsCM,OAtCU,CAsCV,eAtCU,EAAA,CAAA"}
@@ -0,0 +1,2 @@
1
+ import{randomUUID as e}from"node:crypto";var t=class{items=[];async create(e){this.items.push(e)}async update(e,t){let n=this.items.findIndex(t=>t.id===e);n!==-1&&(this.items[n]={...this.items[n],...t})}async list(e){return e?this.items.filter(t=>t.status===e):[...this.items]}},n=class{constructor(e=new t){this.store=e}async requestApproval(t,n,r){let i={id:e(),sessionId:t.sessionId,agent:t.agent,tenantId:t.tenantId,reason:n,requestedAt:new Date,status:`pending`,payload:r};return await this.store.create(i),i}async resolve(e,t,n,r){await this.store.update(e,{status:t,reviewer:n,resolvedAt:new Date,notes:r})}async listPending(){return this.store.list(`pending`)}};export{n as ApprovalWorkflow,t as InMemoryApprovalStore};
2
+ //# sourceMappingURL=workflow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.js","names":["store: ApprovalStore","request: ApprovalRequest"],"sources":["../../src/approval/workflow.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { AgentSessionState } from '../types';\n\nexport type ApprovalStatus = 'pending' | 'approved' | 'rejected';\n\nexport interface ApprovalRequest {\n id: string;\n sessionId: string;\n agent: string;\n tenantId?: string;\n reason: string;\n requestedAt: Date;\n status: ApprovalStatus;\n payload?: Record<string, unknown>;\n reviewer?: string;\n resolvedAt?: Date;\n notes?: string;\n}\n\nexport interface ApprovalStore {\n create(request: ApprovalRequest): Promise<void>;\n update(\n id: string,\n updates: Partial<Omit<ApprovalRequest, 'id' | 'sessionId'>>\n ): Promise<void>;\n list(status?: ApprovalStatus): Promise<ApprovalRequest[]>;\n}\n\nexport class InMemoryApprovalStore implements ApprovalStore {\n private readonly items: ApprovalRequest[] = [];\n\n async create(request: ApprovalRequest): Promise<void> {\n this.items.push(request);\n }\n\n async update(\n id: string,\n updates: Partial<Omit<ApprovalRequest, 'id' | 'sessionId'>>\n ): Promise<void> {\n const index = this.items.findIndex((item) => item.id === id);\n if (index === -1) return;\n this.items[index] = { ...this.items[index], ...updates } as ApprovalRequest;\n }\n\n async list(status?: ApprovalStatus): Promise<ApprovalRequest[]> {\n return status\n ? this.items.filter((item) => item.status === status)\n : [...this.items];\n }\n}\n\nexport interface ApprovalWorkflowOptions {\n store?: ApprovalStore;\n}\n\nexport class ApprovalWorkflow {\n constructor(\n private readonly store: ApprovalStore = new InMemoryApprovalStore()\n ) {}\n\n async requestApproval(\n session: AgentSessionState,\n reason: string,\n payload?: Record<string, unknown>\n ) {\n const request: ApprovalRequest = {\n id: randomUUID(),\n sessionId: session.sessionId,\n agent: session.agent,\n tenantId: session.tenantId,\n reason,\n requestedAt: new Date(),\n status: 'pending',\n payload,\n };\n await this.store.create(request);\n return request;\n }\n\n async resolve(\n id: string,\n status: Exclude<ApprovalStatus, 'pending'>,\n reviewer: string,\n notes?: string\n ) {\n await this.store.update(id, {\n status,\n reviewer,\n resolvedAt: new Date(),\n notes,\n });\n }\n\n async listPending() {\n return this.store.list('pending');\n }\n}\n"],"mappings":"yCA4BA,IAAa,EAAb,KAA4D,CAC1D,MAA4C,EAAE,CAE9C,MAAM,OAAO,EAAyC,CACpD,KAAK,MAAM,KAAK,EAAQ,CAG1B,MAAM,OACJ,EACA,EACe,CACf,IAAM,EAAQ,KAAK,MAAM,UAAW,GAAS,EAAK,KAAO,EAAG,CACxD,IAAU,KACd,KAAK,MAAM,GAAS,CAAE,GAAG,KAAK,MAAM,GAAQ,GAAG,EAAS,EAG1D,MAAM,KAAK,EAAqD,CAC9D,OAAO,EACH,KAAK,MAAM,OAAQ,GAAS,EAAK,SAAW,EAAO,CACnD,CAAC,GAAG,KAAK,MAAM,GAQV,EAAb,KAA8B,CAC5B,YACE,EAAwC,IAAI,EAC5C,CADiB,KAAA,MAAA,EAGnB,MAAM,gBACJ,EACA,EACA,EACA,CACA,IAAMC,EAA2B,CAC/B,GAAI,GAAY,CAChB,UAAW,EAAQ,UACnB,MAAO,EAAQ,MACf,SAAU,EAAQ,SAClB,SACA,YAAa,IAAI,KACjB,OAAQ,UACR,UACD,CAED,OADA,MAAM,KAAK,MAAM,OAAO,EAAQ,CACzB,EAGT,MAAM,QACJ,EACA,EACA,EACA,EACA,CACA,MAAM,KAAK,MAAM,OAAO,EAAI,CAC1B,SACA,WACA,WAAY,IAAI,KAChB,QACD,CAAC,CAGJ,MAAM,aAAc,CAClB,OAAO,KAAK,MAAM,KAAK,UAAU"}
@@ -0,0 +1,8 @@
1
+ import { AgentEventName, AgentEventPayload, AgentMessage, AgentMessageMetadata, AgentRunRequestInput, AgentRunResult, AgentRunnerEventEmitter, AgentSessionState, AgentStatus, AgentToolContext, AgentToolDefinitionWithHandler, AgentToolInvocation, AgentToolResult } from "./types.js";
2
+ import { ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, ApprovalWorkflowOptions, InMemoryApprovalStore } from "./approval/workflow.js";
3
+ import { AgentConfidencePolicy, AgentEscalationPolicy, AgentKnowledgeRef, AgentMemoryConfig, AgentMeta, AgentPolicy, AgentRegistry, AgentSpec, AgentToolConfig, defineAgent } from "./spec.js";
4
+ import { ToolExecutor, ToolExecutorOptions } from "./tools/executor.js";
5
+ import { AgentMemoryEntry, AgentMemoryManager, AgentMemorySnapshot, AgentSessionMemory, BaseAgentMemoryManager, trackMessageInMemory } from "./memory/manager.js";
6
+ import { AgentRunner, AgentRunnerConfig } from "./runner.js";
7
+ import { InMemoryAgentMemory, InMemoryAgentMemoryOptions } from "./memory/in-memory.js";
8
+ export { AgentConfidencePolicy, AgentEscalationPolicy, AgentEventName, AgentEventPayload, AgentKnowledgeRef, AgentMemoryConfig, AgentMemoryEntry, AgentMemoryManager, AgentMemorySnapshot, AgentMessage, AgentMessageMetadata, AgentMeta, AgentPolicy, AgentRegistry, AgentRunRequestInput, AgentRunResult, AgentRunner, AgentRunnerConfig, AgentRunnerEventEmitter, AgentSessionMemory, AgentSessionState, AgentSpec, AgentStatus, AgentToolConfig, AgentToolContext, AgentToolDefinitionWithHandler, AgentToolInvocation, AgentToolResult, ApprovalRequest, ApprovalStatus, ApprovalStore, ApprovalWorkflow, ApprovalWorkflowOptions, BaseAgentMemoryManager, InMemoryAgentMemory, InMemoryAgentMemoryOptions, InMemoryApprovalStore, ToolExecutor, ToolExecutorOptions, defineAgent, trackMessageInMemory };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{AgentRegistry as e,defineAgent as t}from"./spec.js";import{ToolExecutor as n}from"./tools/executor.js";import{BaseAgentMemoryManager as r,trackMessageInMemory as i}from"./memory/manager.js";import{AgentRunner as a}from"./runner.js";import{InMemoryAgentMemory as o}from"./memory/in-memory.js";import"./memory/index.js";import"./tools/index.js";import{ApprovalWorkflow as s,InMemoryApprovalStore as c}from"./approval/workflow.js";import"./approval/index.js";export{e as AgentRegistry,a as AgentRunner,s as ApprovalWorkflow,r as BaseAgentMemoryManager,o as InMemoryAgentMemory,c as InMemoryApprovalStore,n as ToolExecutor,t as defineAgent,i as trackMessageInMemory};
@@ -0,0 +1,22 @@
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 };
22
+ //# sourceMappingURL=in-memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.d.ts","names":[],"sources":["../../src/memory/in-memory.ts"],"sourcesContent":[],"mappings":";;;;UAaiB,0BAAA;;EAAA,UAAA,CAAA,EAAA,MAAA;AAKjB;AAKwB,cALX,mBAAA,SAA4B,sBAAA,CAKjB;EAMiB,iBAAA,KAAA;EAAR,iBAAA,UAAA;EASV,iBAAA,KAAA;EAAqB,WAAA,CAAA,OAAA,CAAA,EAfpB,0BAeoB;EAQjB,IAAA,CAAA,SAAA,EAAA,MAAA,CAAA,EAjBM,OAiBN,CAjBc,kBAiBd,GAAA,IAAA,CAAA;EAA4B,IAAA,CAAA,QAAA,EARhC,kBAQgC,CAAA,EARX,OAQW,CAAA,IAAA,CAAA;EAAR,SAAA,CAAA,OAAA,EAApB,iBAAoB,CAAA,EAAA,OAAA,CAAQ,mBAAR,CAAA;EA5BN,QAAA,IAAA;EAAsB,QAAA,YAAA"}
@@ -0,0 +1,3 @@
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};
3
+ //# sourceMappingURL=in-memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.js","names":[],"sources":["../../src/memory/in-memory.ts"],"sourcesContent":["import type { AgentSessionState } from '../types';\nimport {\n BaseAgentMemoryManager,\n type AgentMemoryEntry,\n type AgentMemorySnapshot,\n type AgentSessionMemory,\n} from './manager';\n\ninterface StoredSession {\n data: AgentSessionMemory;\n expiresAt: number;\n}\n\nexport interface InMemoryAgentMemoryOptions {\n ttlMinutes?: number;\n maxEntries?: number;\n}\n\nexport class InMemoryAgentMemory extends BaseAgentMemoryManager {\n private readonly ttlMs: number;\n private readonly maxEntries: number;\n private readonly store = new Map<string, StoredSession>();\n\n constructor(options?: InMemoryAgentMemoryOptions) {\n super();\n this.ttlMs = (options?.ttlMinutes ?? 60) * 60 * 1000;\n this.maxEntries = options?.maxEntries ?? 250;\n }\n\n async load(sessionId: string): Promise<AgentSessionMemory | null> {\n this.evictExpired();\n const stored = this.store.get(sessionId);\n if (!stored) return null;\n stored.data.session.updatedAt = new Date();\n stored.expiresAt = Date.now() + this.ttlMs;\n return stored.data;\n }\n\n async save(snapshot: AgentSessionMemory): Promise<void> {\n this.trim(snapshot.memory.entries);\n this.store.set(snapshot.session.sessionId, {\n data: snapshot,\n expiresAt: Date.now() + this.ttlMs,\n });\n }\n\n async summarize(session: AgentSessionState): Promise<AgentMemorySnapshot> {\n const current =\n (await this.load(session.sessionId)) ?? this.bootstrapMemory(session);\n const content = current.memory.entries\n .slice(-10)\n .map((entry) => `- ${entry.type}: ${entry.content}`)\n .join('\\n');\n current.memory.summary = content;\n current.memory.lastSummarizedAt = new Date();\n await this.save(current);\n return current.memory;\n }\n\n private trim(entries: AgentMemoryEntry[]) {\n if (entries.length <= this.maxEntries) return;\n entries.splice(0, entries.length - this.maxEntries);\n }\n\n private evictExpired() {\n const now = Date.now();\n for (const [sessionId, stored] of this.store.entries()) {\n if (stored.expiresAt <= now) {\n this.store.delete(sessionId);\n }\n }\n }\n}\n"],"mappings":"sDAkBA,IAAa,EAAb,cAAyC,CAAuB,CAC9D,MACA,WACA,MAAyB,IAAI,IAE7B,YAAY,EAAsC,CAChD,OAAO,CACP,KAAK,OAAS,GAAS,YAAc,IAAM,GAAK,IAChD,KAAK,WAAa,GAAS,YAAc,IAG3C,MAAM,KAAK,EAAuD,CAChE,KAAK,cAAc,CACnB,IAAM,EAAS,KAAK,MAAM,IAAI,EAAU,CAIxC,OAHK,GACL,EAAO,KAAK,QAAQ,UAAY,IAAI,KACpC,EAAO,UAAY,KAAK,KAAK,CAAG,KAAK,MAC9B,EAAO,MAHM,KAMtB,MAAM,KAAK,EAA6C,CACtD,KAAK,KAAK,EAAS,OAAO,QAAQ,CAClC,KAAK,MAAM,IAAI,EAAS,QAAQ,UAAW,CACzC,KAAM,EACN,UAAW,KAAK,KAAK,CAAG,KAAK,MAC9B,CAAC,CAGJ,MAAM,UAAU,EAA0D,CACxE,IAAM,EACH,MAAM,KAAK,KAAK,EAAQ,UAAU,EAAK,KAAK,gBAAgB,EAAQ,CACjE,EAAU,EAAQ,OAAO,QAC5B,MAAM,IAAI,CACV,IAAK,GAAU,KAAK,EAAM,KAAK,IAAI,EAAM,UAAU,CACnD,KAAK;EAAK,CAIb,MAHA,GAAQ,OAAO,QAAU,EACzB,EAAQ,OAAO,iBAAmB,IAAI,KACtC,MAAM,KAAK,KAAK,EAAQ,CACjB,EAAQ,OAGjB,KAAa,EAA6B,CACpC,EAAQ,QAAU,KAAK,YAC3B,EAAQ,OAAO,EAAG,EAAQ,OAAS,KAAK,WAAW,CAGrD,cAAuB,CACrB,IAAM,EAAM,KAAK,KAAK,CACtB,IAAK,GAAM,CAAC,EAAW,KAAW,KAAK,MAAM,SAAS,CAChD,EAAO,WAAa,GACtB,KAAK,MAAM,OAAO,EAAU"}
@@ -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,42 @@
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 };
42
+ //# sourceMappingURL=manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manager.d.ts","names":[],"sources":["../../src/memory/manager.ts"],"sourcesContent":[],"mappings":";;;UAGiB,gBAAA;;EAAA,IAAA,EAAA,MAAA,GAAA,WAAgB,GAAA,MAIpB,GACA,QAAM;EAGF,OAAA,EAAA,MAAA;EAMA,SAAA,EAVJ,IAUI;EAKA,QAAA,CAAA,EAdJ,MAcI,CAAA,MAAkB,EAAA,MAAA,CAAA;;AACR,UAZV,mBAAA,CAYU;EACV,OAAA,EAZN,gBAYM,EAAA;EAAqB,OAAA,CAAA,EAAA,MAAA;EAEzB,gBAAA,CAAA,EAZQ,IAYR;;AACF,UAVM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ATvB,CAAA,EAS2C,kBAT3C;;AACT,iBA0BW,oBAAA,CA1BX,OAAA,EA2BM,kBA3BN,GAAA,SAAA,EAAA,OAAA,EA4BM,iBA5BN,EAAA,OAAA,EA6BM,YA7BN,CAAA,EAAA,IAAA"}
@@ -0,0 +1,2 @@
1
+ import{randomUUID as e}from"node:crypto";var t=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(t){return{session:t,memory:{entries:t.messages.map(t=>({id:e(),createdAt:new Date,type:t.role===`assistant`?`assistant`:`user`,content:t.content.map(e=>`text`in e?e.text:``).join(``),metadata:t.metadata}))}}}};function n(e,t,n){e&&e.append(t,{type:n.role,content:n.content.map(e=>`text`in e?e.text:``).join(``),metadata:n.metadata})}export{t as BaseAgentMemoryManager,n as trackMessageInMemory};
2
+ //# sourceMappingURL=manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manager.js","names":["finalEntry: AgentMemoryEntry"],"sources":["../../src/memory/manager.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { AgentMessage, AgentSessionState } from '../types';\n\nexport interface AgentMemoryEntry {\n id: string;\n type: 'user' | 'assistant' | 'tool' | 'system';\n content: string;\n createdAt: Date;\n metadata?: Record<string, string>;\n}\n\nexport interface AgentMemorySnapshot {\n entries: AgentMemoryEntry[];\n summary?: string;\n lastSummarizedAt?: Date;\n}\n\nexport interface AgentSessionMemory {\n session: AgentSessionState;\n memory: AgentMemorySnapshot;\n}\n\nexport interface AgentMemoryManager {\n load(sessionId: string): Promise<AgentSessionMemory | null>;\n save(snapshot: AgentSessionMemory): Promise<void>;\n append(\n session: AgentSessionState,\n entry: Omit<AgentMemoryEntry, 'id' | 'createdAt'> & { createdAt?: Date }\n ): Promise<AgentSessionMemory>;\n summarize(\n session: AgentSessionState\n ): Promise<AgentMemorySnapshot | undefined>;\n prune(session: AgentSessionState): Promise<void>;\n}\n\nexport abstract class BaseAgentMemoryManager implements AgentMemoryManager {\n abstract load(sessionId: string): Promise<AgentSessionMemory | null>;\n abstract save(snapshot: AgentSessionMemory): Promise<void>;\n\n async append(\n session: AgentSessionState,\n entry: Omit<AgentMemoryEntry, 'id' | 'createdAt'> & { createdAt?: Date }\n ): Promise<AgentSessionMemory> {\n const current =\n (await this.load(session.sessionId)) ?? this.bootstrapMemory(session);\n const finalEntry: AgentMemoryEntry = {\n id: randomUUID(),\n createdAt: entry.createdAt ?? new Date(),\n ...entry,\n };\n current.memory.entries.push(finalEntry);\n await this.save(current);\n return current;\n }\n\n async summarize(\n _session: AgentSessionState\n ): Promise<AgentMemorySnapshot | undefined> {\n return undefined;\n }\n\n async prune(_session: AgentSessionState): Promise<void> {\n // noop by default\n }\n\n protected bootstrapMemory(session: AgentSessionState): AgentSessionMemory {\n return {\n session,\n memory: {\n entries: session.messages.map<AgentMemoryEntry>((message) => ({\n id: randomUUID(),\n createdAt: new Date(),\n type: message.role === 'assistant' ? 'assistant' : 'user',\n content: message.content\n .map((part) => ('text' in part ? part.text : ''))\n .join(''),\n metadata: message.metadata,\n })),\n },\n };\n }\n}\n\nexport function trackMessageInMemory(\n manager: AgentMemoryManager | undefined,\n session: AgentSessionState,\n message: AgentMessage\n) {\n if (!manager) return;\n void manager.append(session, {\n type: message.role,\n content: message.content\n .map((part) => ('text' in part ? part.text : ''))\n .join(''),\n metadata: message.metadata,\n });\n}\n"],"mappings":"yCAmCA,IAAsB,EAAtB,KAA2E,CAIzE,MAAM,OACJ,EACA,EAC6B,CAC7B,IAAM,EACH,MAAM,KAAK,KAAK,EAAQ,UAAU,EAAK,KAAK,gBAAgB,EAAQ,CACjEA,EAA+B,CACnC,GAAI,GAAY,CAChB,UAAW,EAAM,WAAa,IAAI,KAClC,GAAG,EACJ,CAGD,OAFA,EAAQ,OAAO,QAAQ,KAAK,EAAW,CACvC,MAAM,KAAK,KAAK,EAAQ,CACjB,EAGT,MAAM,UACJ,EAC0C,EAI5C,MAAM,MAAM,EAA4C,EAIxD,gBAA0B,EAAgD,CACxE,MAAO,CACL,UACA,OAAQ,CACN,QAAS,EAAQ,SAAS,IAAuB,IAAa,CAC5D,GAAI,GAAY,CAChB,UAAW,IAAI,KACf,KAAM,EAAQ,OAAS,YAAc,YAAc,OACnD,QAAS,EAAQ,QACd,IAAK,GAAU,SAAU,EAAO,EAAK,KAAO,GAAI,CAChD,KAAK,GAAG,CACX,SAAU,EAAQ,SACnB,EAAE,CACJ,CACF,GAIL,SAAgB,EACd,EACA,EACA,EACA,CACK,GACA,EAAQ,OAAO,EAAS,CAC3B,KAAM,EAAQ,KACd,QAAS,EAAQ,QACd,IAAK,GAAU,SAAU,EAAO,EAAK,KAAO,GAAI,CAChD,KAAK,GAAG,CACX,SAAU,EAAQ,SACnB,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { AgentRunRequestInput, AgentRunResult, AgentRunnerEventEmitter, AgentSessionState } from "./types.js";
2
+ import { ApprovalWorkflow } from "./approval/workflow.js";
3
+ import { AgentRegistry } from "./spec.js";
4
+ import { ToolExecutor } from "./tools/executor.js";
5
+ import { AgentMemoryManager } from "./memory/manager.js";
6
+ import { LLMProvider } from "@lssm/lib.contracts/integrations/providers/llm";
7
+
8
+ //#region src/runner.d.ts
9
+ interface AgentSessionStore {
10
+ get(sessionId: string): Promise<AgentSessionState | null>;
11
+ save(session: AgentSessionState): Promise<void>;
12
+ }
13
+ interface AgentRunnerConfig {
14
+ registry: AgentRegistry;
15
+ llm: LLMProvider;
16
+ toolExecutor: ToolExecutor;
17
+ memoryManager?: AgentMemoryManager;
18
+ sessionStore?: AgentSessionStore;
19
+ eventEmitter?: AgentRunnerEventEmitter;
20
+ maxIterations?: number;
21
+ defaultSystemPrompt?: string;
22
+ approvalWorkflow?: ApprovalWorkflow;
23
+ }
24
+ declare class AgentRunner {
25
+ private readonly registry;
26
+ private readonly llm;
27
+ private readonly toolExecutor;
28
+ private readonly memoryManager?;
29
+ private readonly sessionStore;
30
+ private readonly eventEmitter?;
31
+ private readonly maxIterations;
32
+ private readonly defaultSystemPrompt;
33
+ private readonly approvalWorkflow?;
34
+ constructor(config: AgentRunnerConfig);
35
+ run(request: AgentRunRequestInput): Promise<AgentRunResult>;
36
+ private loadSession;
37
+ private appendUserMessage;
38
+ private buildMessages;
39
+ private renderKnowledgeInstructions;
40
+ private persistSession;
41
+ private emit;
42
+ private ensureTools;
43
+ }
44
+ //#endregion
45
+ export { AgentRunner, AgentRunnerConfig };
46
+ //# sourceMappingURL=runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner.d.ts","names":[],"sources":["../src/runner.ts"],"sourcesContent":[],"mappings":";;;;;;;;UAuBU,iBAAA;0BACgB,QAAQ;EADxB,IAAA,CAAA,OAAA,EAEM,iBAFW,CAAA,EAES,OAFT,CAAA,IAAA,CAAA;;AACD,UAgBT,iBAAA,CAhBS;EACV,QAAA,EAgBJ,aAhBI;EAAoB,GAAA,EAiB7B,WAjB6B;EAAO,YAAA,EAkB3B,YAlB2B;EAe1B,aAAA,CAAA,EAIC,kBAJgB;EACtB,YAAA,CAAA,EAIK,iBAJL;EACL,YAAA,CAAA,EAIU,uBAJV;EACS,aAAA,CAAA,EAAA,MAAA;EACE,mBAAA,CAAA,EAAA,MAAA;EACD,gBAAA,CAAA,EAII,gBAJJ;;AAII,cAGR,WAAA,CAHQ;EAAgB,iBAAA,QAAA;EAGxB,iBAAW,GAAA;EAWF,iBAAA,YAAA;EAcD,iBAAA,aAAA;EAA+B,iBAAA,YAAA;EAAR,iBAAA,YAAA;EAAO,iBAAA,aAAA;;;sBAd7B;eAcD,uBAAuB,QAAQ"}
package/dist/runner.js ADDED
@@ -0,0 +1,5 @@
1
+ import"./tools/executor.js";import{trackMessageInMemory as e}from"./memory/manager.js";import{randomUUID as t}from"node:crypto";var n=class{store=new Map;async get(e){return this.store.get(e)??null}async save(e){this.store.set(e.sessionId,{...e})}},r=class{registry;llm;toolExecutor;memoryManager;sessionStore;eventEmitter;maxIterations;defaultSystemPrompt;approvalWorkflow;constructor(e){this.registry=e.registry,this.llm=e.llm,this.toolExecutor=e.toolExecutor,this.memoryManager=e.memoryManager,this.sessionStore=e.sessionStore??new n,this.eventEmitter=e.eventEmitter,this.maxIterations=e.maxIterations??6,this.defaultSystemPrompt=e.defaultSystemPrompt??`You are a ContractSpec agent. Follow policies, cite sources, and escalate when unsure.`,this.approvalWorkflow=e.approvalWorkflow}async run(t){let n=this.registry.require(t.agent,t.version);this.ensureTools(n);let r=await this.loadSession(n,t);this.appendUserMessage(r,t),await this.persistSession(r);let l=[],u=null,d;for(let f=0;f<this.maxIterations;f++){await this.emit(`agent.iteration.started`,{sessionId:r.sessionId,agent:n.meta.name,iteration:f+1,tenantId:t.tenantId}),u=await this.llm.chat(this.buildMessages(n,r,t),{tools:this.toolExecutor.listLLMTools(n.tools.map(e=>e.name)),metadata:{agent:n.meta.name,tenantId:t.tenantId??``},userId:t.actorId});let p=u.message;r.messages.push(p),r.iterations+=1,r.updatedAt=new Date,e(this.memoryManager,r,p),await this.persistSession(r);let m=i(p);if(m.length>0){for(let i of m){let o=a(i.arguments),{invocation:s,result:c}=await this.toolExecutor.execute(i.name,o,{session:r,tenantId:t.tenantId,actorId:t.actorId,metadata:t.metadata,emit:(e,t)=>this.emit(e,t)});l.push(s);let u={role:`tool`,name:i.name,toolCallId:i.id,content:[{type:`tool-result`,toolCallId:i.id,output:JSON.stringify(c??{})}]};r.messages.push(u),e(this.memoryManager,r,u),await this.persistSession(r),await this.emit(`agent.tool.completed`,{sessionId:r.sessionId,agent:n.meta.name,toolName:i.name,tenantId:t.tenantId})}continue}let h=o(p),g=s(p,n.policy?.confidence),_=c(g,n);if(r.status=_?`escalated`:`completed`,r.lastConfidence=g,await this.persistSession(r),_&&this.approvalWorkflow){let e=await this.approvalWorkflow.requestApproval(r,`Low confidence response`,{confidence:g,outputText:h});d=e.id,await this.emit(`agent.approval_requested`,{sessionId:r.sessionId,agent:n.meta.name,tenantId:t.tenantId,metadata:{approvalId:e.id}})}return await this.emit(_?`agent.escalated`:`agent.completed`,{sessionId:r.sessionId,agent:n.meta.name,tenantId:t.tenantId,metadata:{confidence:g,finishReason:u.finishReason??`stop`}}),{session:r,response:u,outputText:h,confidence:g,iterations:r.iterations,requiresEscalation:_,approvalRequestId:d,finishReason:u.finishReason??`stop`,toolInvocations:l}}return r.status=`failed`,await this.persistSession(r),await this.emit(`agent.failed`,{sessionId:r.sessionId,agent:n.meta.name,tenantId:t.tenantId,metadata:{reason:`max_iterations`}}),{session:r,response:u??{message:{role:`assistant`,content:[{type:`text`,text:``}]}},outputText:u?o(u.message):``,confidence:r.lastConfidence??0,iterations:r.iterations,requiresEscalation:!0,approvalRequestId:d,finishReason:`max_iterations`,toolInvocations:l}}async loadSession(e,n){if(n.sessionId){let e=await this.sessionStore.get(n.sessionId);if(e)return e}let r=new Date,i={sessionId:n.sessionId??t(),agent:e.meta.name,version:e.meta.version,tenantId:n.tenantId,status:`running`,messages:[],createdAt:r,updatedAt:r,iterations:0,metadata:n.metadata};return await this.emit(`agent.session.created`,{sessionId:i.sessionId,agent:e.meta.name,tenantId:n.tenantId}),i}appendUserMessage(t,n){let r={role:`user`,content:[{type:`text`,text:n.input}],metadata:n.metadata};t.messages.push(r),e(this.memoryManager,t,r)}buildMessages(e,t,n){return[{role:`system`,content:[{type:`text`,text:[this.defaultSystemPrompt,e.instructions,n.instructionsOverride,this.renderKnowledgeInstructions(e)].filter(Boolean).join(`
2
+
3
+ `)}]},...t.messages]}renderKnowledgeInstructions(e){return e.knowledge?.length?`Knowledge spaces available:\n${e.knowledge.map(e=>{let t=e.category??`unspecified`,n=e.instructions?` Guidance: ${e.instructions}`:``;return`- ${e.key} (category: ${t})${n}`}).join(`
4
+ `)}`:``}async persistSession(e){e.updatedAt=new Date,await this.sessionStore.save(e),await this.emit(`agent.session.updated`,{sessionId:e.sessionId,agent:e.agent,tenantId:e.tenantId,metadata:{status:e.status}})}async emit(e,t){await this.eventEmitter?.(e,t)}ensureTools(e){for(let t of e.tools)if(!this.toolExecutor.has(t.name))throw Error(`Agent ${e.meta.name} requires tool "${t.name}" but it is not registered.`)}};function i(e){return e.content.filter(e=>e.type===`tool-call`)}function a(e){if(!e)return{};try{return JSON.parse(e)}catch{return e}}function o(e){return e.content.map(e=>`text`in e?e.text:``).join(``).trim()}function s(e,t){let n=e.metadata?.confidence??e.metadata?.Confidence,r=n?Number.parseFloat(n):NaN;return Number.isNaN(r)?t?.default??.5:Math.max(0,Math.min(1,r))}function c(e,t){let n=t.policy?.confidence?.min??.7;return e<(t.policy?.escalation?.confidenceThreshold??n)}export{r as AgentRunner};
5
+ //# sourceMappingURL=runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner.js","names":["toolInvocations: AgentToolInvocation[]","response: LLMResponse | null","approvalRequestId: string | undefined","toolMessage: AgentMessage","session: AgentSessionState","userMessage: AgentMessage"],"sources":["../src/runner.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type {\n LLMMessage,\n LLMProvider,\n LLMResponse,\n LLMToolCallPart,\n} from '@lssm/lib.contracts/integrations/providers/llm';\nimport type { AgentSpec, AgentRegistry } from './spec';\nimport type {\n AgentEventName,\n AgentEventPayload,\n AgentMessage,\n AgentRunRequestInput,\n AgentRunResult,\n AgentSessionState,\n AgentToolInvocation,\n AgentRunnerEventEmitter,\n} from './types';\nimport { ToolExecutor } from './tools/executor';\nimport type { AgentMemoryManager } from './memory/manager';\nimport { trackMessageInMemory } from './memory/manager';\nimport type { ApprovalWorkflow } from './approval';\n\ninterface AgentSessionStore {\n get(sessionId: string): Promise<AgentSessionState | null>;\n save(session: AgentSessionState): Promise<void>;\n}\n\nclass InMemoryAgentSessionStore implements AgentSessionStore {\n private readonly store = new Map<string, AgentSessionState>();\n\n async get(sessionId: string): Promise<AgentSessionState | null> {\n return this.store.get(sessionId) ?? null;\n }\n\n async save(session: AgentSessionState): Promise<void> {\n this.store.set(session.sessionId, { ...session });\n }\n}\n\nexport interface AgentRunnerConfig {\n registry: AgentRegistry;\n llm: LLMProvider;\n toolExecutor: ToolExecutor;\n memoryManager?: AgentMemoryManager;\n sessionStore?: AgentSessionStore;\n eventEmitter?: AgentRunnerEventEmitter;\n maxIterations?: number;\n defaultSystemPrompt?: string;\n approvalWorkflow?: ApprovalWorkflow;\n}\n\nexport class AgentRunner {\n private readonly registry: AgentRegistry;\n private readonly llm: LLMProvider;\n private readonly toolExecutor: ToolExecutor;\n private readonly memoryManager?: AgentMemoryManager;\n private readonly sessionStore: AgentSessionStore;\n private readonly eventEmitter?: AgentRunnerEventEmitter;\n private readonly maxIterations: number;\n private readonly defaultSystemPrompt: string;\n private readonly approvalWorkflow?: ApprovalWorkflow;\n\n constructor(config: AgentRunnerConfig) {\n this.registry = config.registry;\n this.llm = config.llm;\n this.toolExecutor = config.toolExecutor;\n this.memoryManager = config.memoryManager;\n this.sessionStore = config.sessionStore ?? new InMemoryAgentSessionStore();\n this.eventEmitter = config.eventEmitter;\n this.maxIterations = config.maxIterations ?? 6;\n this.defaultSystemPrompt =\n config.defaultSystemPrompt ??\n 'You are a ContractSpec agent. Follow policies, cite sources, and escalate when unsure.';\n this.approvalWorkflow = config.approvalWorkflow;\n }\n\n async run(request: AgentRunRequestInput): Promise<AgentRunResult> {\n const spec = this.registry.require(request.agent, request.version);\n this.ensureTools(spec);\n const session = await this.loadSession(spec, request);\n this.appendUserMessage(session, request);\n await this.persistSession(session);\n\n const toolInvocations: AgentToolInvocation[] = [];\n let response: LLMResponse | null = null;\n let approvalRequestId: string | undefined;\n\n for (let iteration = 0; iteration < this.maxIterations; iteration++) {\n await this.emit('agent.iteration.started', {\n sessionId: session.sessionId,\n agent: spec.meta.name,\n iteration: iteration + 1,\n tenantId: request.tenantId,\n });\n\n response = await this.llm.chat(\n this.buildMessages(spec, session, request),\n {\n tools: this.toolExecutor.listLLMTools(\n spec.tools.map((tool) => tool.name)\n ),\n metadata: {\n agent: spec.meta.name,\n tenantId: request.tenantId ?? '',\n },\n userId: request.actorId,\n }\n );\n\n const assistantMessage = response.message as AgentMessage;\n session.messages.push(assistantMessage);\n session.iterations += 1;\n session.updatedAt = new Date();\n trackMessageInMemory(this.memoryManager, session, assistantMessage);\n await this.persistSession(session);\n\n const toolCalls = extractToolCalls(assistantMessage);\n if (toolCalls.length > 0) {\n for (const call of toolCalls) {\n const args = safeParse(call.arguments);\n const { invocation, result } = await this.toolExecutor.execute(\n call.name,\n args,\n {\n session,\n tenantId: request.tenantId,\n actorId: request.actorId,\n metadata: request.metadata,\n emit: (event, payload) => this.emit(event, payload),\n }\n );\n toolInvocations.push(invocation);\n const toolMessage: AgentMessage = {\n role: 'tool',\n name: call.name,\n toolCallId: call.id,\n content: [\n {\n type: 'tool-result',\n toolCallId: call.id,\n output: JSON.stringify(result ?? {}),\n },\n ],\n } as LLMMessage;\n session.messages.push(toolMessage);\n trackMessageInMemory(this.memoryManager, session, toolMessage);\n await this.persistSession(session);\n await this.emit('agent.tool.completed', {\n sessionId: session.sessionId,\n agent: spec.meta.name,\n toolName: call.name,\n tenantId: request.tenantId,\n });\n }\n continue;\n }\n\n const outputText = getAssistantText(assistantMessage);\n const confidence = deriveConfidence(\n assistantMessage,\n spec.policy?.confidence\n );\n const requiresEscalation = shouldEscalate(confidence, spec);\n session.status = requiresEscalation ? 'escalated' : 'completed';\n session.lastConfidence = confidence;\n await this.persistSession(session);\n if (requiresEscalation && this.approvalWorkflow) {\n const approval = await this.approvalWorkflow.requestApproval(\n session,\n 'Low confidence response',\n {\n confidence,\n outputText,\n }\n );\n approvalRequestId = approval.id;\n await this.emit('agent.approval_requested', {\n sessionId: session.sessionId,\n agent: spec.meta.name,\n tenantId: request.tenantId,\n metadata: { approvalId: approval.id },\n });\n }\n await this.emit(\n requiresEscalation ? 'agent.escalated' : 'agent.completed',\n {\n sessionId: session.sessionId,\n agent: spec.meta.name,\n tenantId: request.tenantId,\n metadata: {\n confidence,\n finishReason: response.finishReason ?? 'stop',\n },\n }\n );\n\n return {\n session,\n response,\n outputText,\n confidence,\n iterations: session.iterations,\n requiresEscalation,\n approvalRequestId,\n finishReason: response.finishReason ?? 'stop',\n toolInvocations,\n };\n }\n\n session.status = 'failed';\n await this.persistSession(session);\n await this.emit('agent.failed', {\n sessionId: session.sessionId,\n agent: spec.meta.name,\n tenantId: request.tenantId,\n metadata: { reason: 'max_iterations' },\n });\n\n return {\n session,\n response:\n response ??\n ({\n message: { role: 'assistant', content: [{ type: 'text', text: '' }] },\n } as LLMResponse),\n outputText: response\n ? getAssistantText(response.message as AgentMessage)\n : '',\n confidence: session.lastConfidence ?? 0,\n iterations: session.iterations,\n requiresEscalation: true,\n approvalRequestId,\n finishReason: 'max_iterations',\n toolInvocations,\n };\n }\n\n private async loadSession(\n spec: AgentSpec,\n request: AgentRunRequestInput\n ): Promise<AgentSessionState> {\n if (request.sessionId) {\n const existing = await this.sessionStore.get(request.sessionId);\n if (existing) return existing;\n }\n const now = new Date();\n const session: AgentSessionState = {\n sessionId: request.sessionId ?? randomUUID(),\n agent: spec.meta.name,\n version: spec.meta.version,\n tenantId: request.tenantId,\n status: 'running',\n messages: [],\n createdAt: now,\n updatedAt: now,\n iterations: 0,\n metadata: request.metadata,\n };\n await this.emit('agent.session.created', {\n sessionId: session.sessionId,\n agent: spec.meta.name,\n tenantId: request.tenantId,\n });\n return session;\n }\n\n private appendUserMessage(\n session: AgentSessionState,\n request: AgentRunRequestInput\n ) {\n const userMessage: AgentMessage = {\n role: 'user',\n content: [{ type: 'text', text: request.input }],\n metadata: request.metadata,\n } as LLMMessage;\n session.messages.push(userMessage);\n trackMessageInMemory(this.memoryManager, session, userMessage);\n }\n\n private buildMessages(\n spec: AgentSpec,\n session: AgentSessionState,\n request: AgentRunRequestInput\n ): AgentMessage[] {\n const systemPrompt = [\n this.defaultSystemPrompt,\n spec.instructions,\n request.instructionsOverride,\n this.renderKnowledgeInstructions(spec),\n ]\n .filter(Boolean)\n .join('\\n\\n');\n\n const systemMessage: AgentMessage = {\n role: 'system',\n content: [{ type: 'text', text: systemPrompt }],\n } as LLMMessage;\n\n return [systemMessage, ...session.messages];\n }\n\n private renderKnowledgeInstructions(spec: AgentSpec): string {\n if (!spec.knowledge?.length) return '';\n const bullets = spec.knowledge\n .map((binding) => {\n const category = binding.category ?? 'unspecified';\n const instruction = binding.instructions\n ? ` Guidance: ${binding.instructions}`\n : '';\n return `- ${binding.key} (category: ${category})${instruction}`;\n })\n .join('\\n');\n return `Knowledge spaces available:\\n${bullets}`;\n }\n\n private async persistSession(session: AgentSessionState) {\n session.updatedAt = new Date();\n await this.sessionStore.save(session);\n await this.emit('agent.session.updated', {\n sessionId: session.sessionId,\n agent: session.agent,\n tenantId: session.tenantId,\n metadata: { status: session.status },\n });\n }\n\n private async emit(event: AgentEventName, payload: AgentEventPayload) {\n await this.eventEmitter?.(event, payload);\n }\n\n private ensureTools(spec: AgentSpec) {\n for (const tool of spec.tools) {\n if (!this.toolExecutor.has(tool.name)) {\n throw new Error(\n `Agent ${spec.meta.name} requires tool \"${tool.name}\" but it is not registered.`\n );\n }\n }\n }\n}\n\nfunction extractToolCalls(message: AgentMessage): LLMToolCallPart[] {\n return message.content.filter(\n (part): part is LLMToolCallPart => part.type === 'tool-call'\n );\n}\n\nfunction safeParse(payload?: string): unknown {\n if (!payload) return {};\n try {\n return JSON.parse(payload);\n } catch {\n return payload;\n }\n}\n\nfunction getAssistantText(message: AgentMessage): string {\n return message.content\n .map((part) => ('text' in part ? part.text : ''))\n .join('')\n .trim();\n}\n\nfunction deriveConfidence(\n message: AgentMessage,\n config?: { min?: number; default?: number }\n): number {\n const raw = message.metadata?.confidence ?? message.metadata?.Confidence;\n const parsed = raw ? Number.parseFloat(raw) : NaN;\n if (!Number.isNaN(parsed)) return Math.max(0, Math.min(1, parsed));\n return config?.default ?? 0.5;\n}\n\nfunction shouldEscalate(confidence: number, spec: AgentSpec): boolean {\n const min = spec.policy?.confidence?.min ?? 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,KAAQ,EAAK,MACtB,GAAI,CAAC,KAAK,aAAa,IAAI,EAAK,KAAK,CACnC,MAAU,MACR,SAAS,EAAK,KAAK,KAAK,kBAAkB,EAAK,KAAK,6BACrD,GAMT,SAAS,EAAiB,EAA0C,CAClE,OAAO,EAAQ,QAAQ,OACpB,GAAkC,EAAK,OAAS,YAClD,CAGH,SAAS,EAAU,EAA2B,CAC5C,GAAI,CAAC,EAAS,MAAO,EAAE,CACvB,GAAI,CACF,OAAO,KAAK,MAAM,EAAQ,MACpB,CACN,OAAO,GAIX,SAAS,EAAiB,EAA+B,CACvD,OAAO,EAAQ,QACZ,IAAK,GAAU,SAAU,EAAO,EAAK,KAAO,GAAI,CAChD,KAAK,GAAG,CACR,MAAM,CAGX,SAAS,EACP,EACA,EACQ,CACR,IAAM,EAAM,EAAQ,UAAU,YAAc,EAAQ,UAAU,WACxD,EAAS,EAAM,OAAO,WAAW,EAAI,CAAG,IAE9C,OADK,OAAO,MAAM,EAAO,CAClB,GAAQ,SAAW,GADQ,KAAK,IAAI,EAAG,KAAK,IAAI,EAAG,EAAO,CAAC,CAIpE,SAAS,EAAe,EAAoB,EAA0B,CACpE,IAAM,EAAM,EAAK,QAAQ,YAAY,KAAO,GAE5C,OAAO,GADW,EAAK,QAAQ,YAAY,qBAAuB"}
package/dist/spec.d.ts ADDED
@@ -0,0 +1,78 @@
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.d.ts
6
+ interface AgentMeta extends OwnerShipMeta {
7
+ name: string;
8
+ version: number;
9
+ }
10
+ interface AgentToolConfig {
11
+ name: string;
12
+ description?: string;
13
+ /** JSON Schema fragment forwarded to the LLM tool definition. */
14
+ schema?: Record<string, unknown>;
15
+ /** Optional cooldown in milliseconds. */
16
+ cooldownMs?: number;
17
+ timeoutMs?: number;
18
+ /** Whether the tool can be executed without human approval. */
19
+ automationSafe?: boolean;
20
+ /** Optional policy guard that must evaluate to allow the tool call. */
21
+ policy?: PolicyRef;
22
+ }
23
+ interface AgentKnowledgeRef {
24
+ key: string;
25
+ version?: number;
26
+ category?: KnowledgeCategory;
27
+ required?: boolean;
28
+ /** Additional instructions appended when the space is available. */
29
+ instructions?: string;
30
+ }
31
+ interface AgentMemoryConfig {
32
+ maxEntries?: number;
33
+ ttlMinutes?: number;
34
+ summaryTrigger?: number;
35
+ persistLongTerm?: boolean;
36
+ }
37
+ interface AgentConfidencePolicy {
38
+ /** Minimum acceptable confidence before escalation. Defaults to 0.7. */
39
+ min?: number;
40
+ /** Default value used when provider does not report confidence. */
41
+ default?: number;
42
+ }
43
+ interface AgentEscalationPolicy {
44
+ /** Auto escalate when confidence < threshold. */
45
+ confidenceThreshold?: number;
46
+ /** Escalate when a tool throws irrecoverable errors. */
47
+ onToolFailure?: boolean;
48
+ /** Escalate when iteration budget exceeded. */
49
+ onTimeout?: boolean;
50
+ /** Optional human approval workflow ID. */
51
+ approvalWorkflow?: string;
52
+ }
53
+ interface AgentPolicy {
54
+ confidence?: AgentConfidencePolicy;
55
+ escalation?: AgentEscalationPolicy;
56
+ flags?: string[];
57
+ }
58
+ interface AgentSpec {
59
+ meta: AgentMeta;
60
+ instructions: string;
61
+ description?: string;
62
+ tags?: string[];
63
+ tools: AgentToolConfig[];
64
+ memory?: AgentMemoryConfig;
65
+ knowledge?: AgentKnowledgeRef[];
66
+ policy?: AgentPolicy;
67
+ }
68
+ declare function defineAgent(spec: AgentSpec): AgentSpec;
69
+ declare class AgentRegistry {
70
+ private readonly specs;
71
+ register(spec: AgentSpec): this;
72
+ list(): AgentSpec[];
73
+ get(name: string, version?: number): AgentSpec | undefined;
74
+ require(name: string, version?: number): AgentSpec;
75
+ }
76
+ //#endregion
77
+ export { AgentConfidencePolicy, AgentEscalationPolicy, AgentKnowledgeRef, AgentMemoryConfig, AgentMeta, AgentPolicy, AgentRegistry, AgentSpec, AgentToolConfig, defineAgent };
78
+ //# sourceMappingURL=spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spec.d.ts","names":[],"sources":["../src/spec.ts"],"sourcesContent":[],"mappings":";;;;;UAIiB,SAAA,SAAkB;;EAAlB,OAAA,EAAA,MAAU;AAK3B;AAciB,UAdA,eAAA,CAciB;EASjB,IAAA,EAAA,MAAA;EAOA,WAAA,CAAA,EAAA,MAAA;EAOA;EAWA,MAAA,CAAA,EA5CN,MA4CiB,CAAA,MAAA,EAAA,OACb,CAAA;EAKE;EACT,UAAA,CAAA,EAAA,MAAA;EAIC,SAAA,CAAA,EAAA,MAAA;EACE;EACG,cAAA,CAAA,EAAA,OAAA;EACH;EAAW,MAAA,CAAA,EAnDX,SAmDW;AAKtB;AAca,UAnEI,iBAAA,CAmES;EAGT,GAAA,EAAA,MAAA;EASP,OAAA,CAAA,EAAA,MAAA;EAI6B,QAAA,CAAA,EAhF1B,iBAgF0B;EAgBI,QAAA,CAAA,EAAA,OAAA;EAAS;;;UA1FnC,iBAAA;;;;;;UAOA,qBAAA;;;;;;UAOA,qBAAA;;;;;;;;;;UAWA,WAAA;eACF;eACA;;;UAIE,SAAA;QACT;;;;SAIC;WACE;cACG;WACH;;iBAKK,WAAA,OAAkB,YAAY;cAcjC,aAAA;;iBAGI;UASP;uCAI6B;2CAgBI"}
package/dist/spec.js ADDED
@@ -0,0 +1,2 @@
1
+ const e=e=>`${e.name}.v${e.version}`;function t(e){if(!e.meta?.name)throw Error(`Agent name is required`);if(!Number.isFinite(e.meta.version))throw Error(`Agent ${e.meta.name} is missing a numeric version`);if(!e.instructions?.trim())throw Error(`Agent ${e.meta.name} requires instructions`);if(!e.tools?.length)throw Error(`Agent ${e.meta.name} must expose at least one tool`);return Object.freeze(e)}var n=class{specs=new Map;register(t){let n=e(t.meta);if(this.specs.has(n))throw Error(`Duplicate agent spec registered for ${n}`);return this.specs.set(n,t),this}list(){return[...this.specs.values()]}get(e,t){if(t!=null)return this.specs.get(`${e}.v${t}`);let n,r=-1/0;for(let t of this.specs.values())t.meta.name===e&&t.meta.version>r&&(n=t,r=t.meta.version);return n}require(e,t){let n=this.get(e,t);if(!n)throw Error(`Agent spec not found for ${e}${t?`.v${t}`:``}`);return n}};export{n as AgentRegistry,t as defineAgent};
2
+ //# sourceMappingURL=spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spec.js","names":["latest: AgentSpec | undefined"],"sources":["../src/spec.ts"],"sourcesContent":["import type { OwnerShipMeta } from '@lssm/lib.contracts/ownership';\nimport type { KnowledgeCategory } from '@lssm/lib.contracts/knowledge/spec';\nimport type { PolicyRef } from '@lssm/lib.contracts/policy/spec';\n\nexport interface AgentMeta extends OwnerShipMeta {\n name: string;\n version: number;\n}\n\nexport interface AgentToolConfig {\n name: string;\n description?: string;\n /** JSON Schema fragment forwarded to the LLM tool definition. */\n schema?: Record<string, unknown>;\n /** Optional cooldown in milliseconds. */\n cooldownMs?: number;\n timeoutMs?: number;\n /** Whether the tool can be executed without human approval. */\n automationSafe?: boolean;\n /** Optional policy guard that must evaluate to allow the tool call. */\n policy?: PolicyRef;\n}\n\nexport interface AgentKnowledgeRef {\n key: string;\n version?: number;\n category?: KnowledgeCategory;\n required?: boolean;\n /** Additional instructions appended when the space is available. */\n instructions?: string;\n}\n\nexport interface AgentMemoryConfig {\n maxEntries?: number;\n ttlMinutes?: number;\n summaryTrigger?: number;\n persistLongTerm?: boolean;\n}\n\nexport interface AgentConfidencePolicy {\n /** Minimum acceptable confidence before escalation. Defaults to 0.7. */\n min?: number;\n /** Default value used when provider does not report confidence. */\n default?: number;\n}\n\nexport interface AgentEscalationPolicy {\n /** Auto escalate when confidence < threshold. */\n confidenceThreshold?: number;\n /** Escalate when a tool throws irrecoverable errors. */\n onToolFailure?: boolean;\n /** Escalate when iteration budget exceeded. */\n onTimeout?: boolean;\n /** Optional human approval workflow ID. */\n approvalWorkflow?: string;\n}\n\nexport interface AgentPolicy {\n confidence?: AgentConfidencePolicy;\n escalation?: AgentEscalationPolicy;\n flags?: string[];\n}\n\nexport interface AgentSpec {\n meta: AgentMeta;\n instructions: string;\n description?: string;\n tags?: string[];\n tools: AgentToolConfig[];\n memory?: AgentMemoryConfig;\n knowledge?: AgentKnowledgeRef[];\n policy?: AgentPolicy;\n}\n\nconst agentKey = (meta: AgentMeta) => `${meta.name}.v${meta.version}`;\n\nexport function defineAgent(spec: AgentSpec): AgentSpec {\n if (!spec.meta?.name) throw new Error('Agent name is required');\n if (!Number.isFinite(spec.meta.version)) {\n throw new Error(`Agent ${spec.meta.name} is missing a numeric version`);\n }\n if (!spec.instructions?.trim()) {\n throw new Error(`Agent ${spec.meta.name} requires instructions`);\n }\n if (!spec.tools?.length) {\n throw new Error(`Agent ${spec.meta.name} must expose at least one tool`);\n }\n return Object.freeze(spec);\n}\n\nexport class AgentRegistry {\n private readonly specs = new Map<string, AgentSpec>();\n\n register(spec: AgentSpec): this {\n const key = agentKey(spec.meta);\n if (this.specs.has(key)) {\n throw new Error(`Duplicate agent spec registered for ${key}`);\n }\n this.specs.set(key, spec);\n return this;\n }\n\n list(): AgentSpec[] {\n return [...this.specs.values()];\n }\n\n get(name: string, version?: number): AgentSpec | undefined {\n if (version != null) {\n return this.specs.get(`${name}.v${version}`);\n }\n let latest: AgentSpec | undefined;\n let maxVersion = -Infinity;\n for (const spec of this.specs.values()) {\n if (spec.meta.name !== name) continue;\n if (spec.meta.version > maxVersion) {\n latest = spec;\n maxVersion = spec.meta.version;\n }\n }\n return latest;\n }\n\n require(name: string, version?: number): AgentSpec {\n const spec = this.get(name, version);\n if (!spec) {\n throw new Error(\n `Agent spec not found for ${name}${version ? `.v${version}` : ''}`\n );\n }\n return spec;\n }\n}\n"],"mappings":"AA0EA,MAAM,EAAY,GAAoB,GAAG,EAAK,KAAK,IAAI,EAAK,UAE5D,SAAgB,EAAY,EAA4B,CACtD,GAAI,CAAC,EAAK,MAAM,KAAM,MAAU,MAAM,yBAAyB,CAC/D,GAAI,CAAC,OAAO,SAAS,EAAK,KAAK,QAAQ,CACrC,MAAU,MAAM,SAAS,EAAK,KAAK,KAAK,+BAA+B,CAEzE,GAAI,CAAC,EAAK,cAAc,MAAM,CAC5B,MAAU,MAAM,SAAS,EAAK,KAAK,KAAK,wBAAwB,CAElE,GAAI,CAAC,EAAK,OAAO,OACf,MAAU,MAAM,SAAS,EAAK,KAAK,KAAK,gCAAgC,CAE1E,OAAO,OAAO,OAAO,EAAK,CAG5B,IAAa,EAAb,KAA2B,CACzB,MAAyB,IAAI,IAE7B,SAAS,EAAuB,CAC9B,IAAM,EAAM,EAAS,EAAK,KAAK,CAC/B,GAAI,KAAK,MAAM,IAAI,EAAI,CACrB,MAAU,MAAM,uCAAuC,IAAM,CAG/D,OADA,KAAK,MAAM,IAAI,EAAK,EAAK,CAClB,KAGT,MAAoB,CAClB,MAAO,CAAC,GAAG,KAAK,MAAM,QAAQ,CAAC,CAGjC,IAAI,EAAc,EAAyC,CACzD,GAAI,GAAW,KACb,OAAO,KAAK,MAAM,IAAI,GAAG,EAAK,IAAI,IAAU,CAE9C,IAAIA,EACA,EAAa,KACjB,IAAK,IAAM,KAAQ,KAAK,MAAM,QAAQ,CAChC,EAAK,KAAK,OAAS,GACnB,EAAK,KAAK,QAAU,IACtB,EAAS,EACT,EAAa,EAAK,KAAK,SAG3B,OAAO,EAGT,QAAQ,EAAc,EAA6B,CACjD,IAAM,EAAO,KAAK,IAAI,EAAM,EAAQ,CACpC,GAAI,CAAC,EACH,MAAU,MACR,4BAA4B,IAAO,EAAU,KAAK,IAAY,KAC/D,CAEH,OAAO"}
@@ -0,0 +1,25 @@
1
+ import { AgentToolContext, AgentToolDefinitionWithHandler, AgentToolInvocation, AgentToolResult } from "../types.js";
2
+ import { LLMToolDefinition } from "@lssm/lib.contracts/integrations/providers/llm";
3
+
4
+ //#region src/tools/executor.d.ts
5
+ interface ToolExecutorOptions {
6
+ tools?: AgentToolDefinitionWithHandler[];
7
+ /** Maximum time to wait for graceful cancellation after timeout. */
8
+ abortGracePeriodMs?: number;
9
+ }
10
+ declare class ToolExecutor {
11
+ private readonly tools;
12
+ private readonly abortGracePeriodMs;
13
+ constructor(options?: ToolExecutorOptions);
14
+ register(tool: AgentToolDefinitionWithHandler): this;
15
+ listLLMTools(allowed?: string[]): LLMToolDefinition[];
16
+ has(name: string): boolean;
17
+ execute(name: string, args: unknown, ctx: AgentToolContext): Promise<{
18
+ invocation: AgentToolInvocation;
19
+ result?: AgentToolResult;
20
+ }>;
21
+ private rejectOnAbort;
22
+ }
23
+ //#endregion
24
+ export { ToolExecutor, ToolExecutorOptions };
25
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","names":[],"sources":["../../src/tools/executor.ts"],"sourcesContent":[],"mappings":";;;;UASiB,mBAAA;UACP;EADO;EAMJ,kBAAY,CAAA,EAAA,MAAA;;AASR,cATJ,YAAA,CASI;EAKmB,iBAAA,KAAA;EAgB3B,iBAAA,kBAAA;EACkB,WAAA,CAAA,OAAA,CAAA,EA3BH,mBA2BG;EAA8B,QAAA,CAAA,IAAA,EAtBxC,8BAsBwC,CAAA,EAAA,IAAA;EAApD,YAAA,CAAA,OAAA,CAAA,EAAA,MAAA,EAAA,CAAA,EAjB+B,iBAiB/B,EAAA;EAAO,GAAA,CAAA,IAAA,EAAA,MAAA,CAAA,EAAA,OAAA;4CADH,mBACJ;gBAAsB;aAA8B"}
@@ -0,0 +1,2 @@
1
+ import{setTimeout as e}from"node:timers/promises";var t=class{tools=new Map;abortGracePeriodMs;constructor(e){this.abortGracePeriodMs=e?.abortGracePeriodMs??250,e?.tools?.forEach(e=>this.register(e))}register(e){return this.tools.set(e.definition.name,e),this}listLLMTools(e){return e?.length?e.map(e=>this.tools.get(e)?.definition).filter(e=>!!e):[...this.tools.values()].map(e=>e.definition)}has(e){return this.tools.has(e)}async execute(t,n,r){let i=this.tools.get(t);if(!i)throw Error(`Agent tool ${t} is not registered`);let a={name:t,arguments:n,startedAt:new Date,success:!1};try{let t=new AbortController,o=i.timeoutMs??1e4,s=setTimeout(()=>t.abort(),o);try{let e=await Promise.race([i.handler(n,{...r,emit:r.emit}),this.rejectOnAbort(t.signal,o)]);return a.success=!0,{invocation:a,result:e}}finally{clearTimeout(s),t.signal.aborted&&await e(this.abortGracePeriodMs).catch(()=>void 0)}}catch(e){throw a.error=e instanceof Error?e.message:String(e),e}finally{a.completedAt=new Date,a.durationMs=a.completedAt.getTime()-a.startedAt.getTime()}}async rejectOnAbort(e,t){if(e.aborted)throw Error(`Tool execution aborted`);return new Promise((n,r)=>{e.addEventListener(`abort`,()=>r(Error(`Tool execution timed out after ${t}ms`)),{once:!0})})}};export{t as ToolExecutor};
2
+ //# sourceMappingURL=executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.js","names":["invocation: AgentToolInvocation","delay"],"sources":["../../src/tools/executor.ts"],"sourcesContent":["import { setTimeout as delay } from 'node:timers/promises';\nimport type { LLMToolDefinition } from '@lssm/lib.contracts/integrations/providers/llm';\nimport type {\n AgentToolContext,\n AgentToolDefinitionWithHandler,\n AgentToolInvocation,\n AgentToolResult,\n} from '../types';\n\nexport interface ToolExecutorOptions {\n tools?: AgentToolDefinitionWithHandler[];\n /** Maximum time to wait for graceful cancellation after timeout. */\n abortGracePeriodMs?: number;\n}\n\nexport class ToolExecutor {\n private readonly tools = new Map<string, AgentToolDefinitionWithHandler>();\n private readonly abortGracePeriodMs: number;\n\n constructor(options?: ToolExecutorOptions) {\n this.abortGracePeriodMs = options?.abortGracePeriodMs ?? 250;\n options?.tools?.forEach((tool) => this.register(tool));\n }\n\n register(tool: AgentToolDefinitionWithHandler): this {\n this.tools.set(tool.definition.name, tool);\n return this;\n }\n\n listLLMTools(allowed?: string[]): LLMToolDefinition[] {\n if (!allowed?.length) {\n return [...this.tools.values()].map((tool) => tool.definition);\n }\n return allowed\n .map((name) => this.tools.get(name)?.definition)\n .filter((tool): tool is LLMToolDefinition => Boolean(tool));\n }\n\n has(name: string): boolean {\n return this.tools.has(name);\n }\n\n async execute(\n name: string,\n args: unknown,\n ctx: AgentToolContext\n ): Promise<{ invocation: AgentToolInvocation; result?: AgentToolResult }> {\n const tool = this.tools.get(name);\n if (!tool) {\n throw new Error(`Agent tool ${name} is not registered`);\n }\n\n const invocation: AgentToolInvocation = {\n name,\n arguments: args,\n startedAt: new Date(),\n success: false,\n };\n\n try {\n const controller = new AbortController();\n const timeout = tool.timeoutMs ?? 10_000;\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const result = await Promise.race([\n tool.handler(args, {\n ...ctx,\n emit: ctx.emit,\n }),\n this.rejectOnAbort(controller.signal, timeout),\n ]);\n invocation.success = true;\n return { invocation, result };\n } finally {\n clearTimeout(timer);\n if (controller.signal.aborted) {\n await delay(this.abortGracePeriodMs).catch(() => undefined);\n }\n }\n } catch (error) {\n invocation.error = error instanceof Error ? error.message : String(error);\n throw error;\n } finally {\n invocation.completedAt = new Date();\n invocation.durationMs =\n invocation.completedAt.getTime() - invocation.startedAt.getTime();\n }\n }\n\n private async rejectOnAbort(signal: AbortSignal, timeout: number) {\n if (signal.aborted) {\n throw new Error('Tool execution aborted');\n }\n return new Promise<never>((_, reject) => {\n signal.addEventListener(\n 'abort',\n () => reject(new Error(`Tool execution timed out after ${timeout}ms`)),\n { once: true }\n );\n });\n }\n}\n"],"mappings":"kDAeA,IAAa,EAAb,KAA0B,CACxB,MAAyB,IAAI,IAC7B,mBAEA,YAAY,EAA+B,CACzC,KAAK,mBAAqB,GAAS,oBAAsB,IACzD,GAAS,OAAO,QAAS,GAAS,KAAK,SAAS,EAAK,CAAC,CAGxD,SAAS,EAA4C,CAEnD,OADA,KAAK,MAAM,IAAI,EAAK,WAAW,KAAM,EAAK,CACnC,KAGT,aAAa,EAAyC,CAIpD,OAHK,GAAS,OAGP,EACJ,IAAK,GAAS,KAAK,MAAM,IAAI,EAAK,EAAE,WAAW,CAC/C,OAAQ,GAA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ecutorOptions };
@@ -0,0 +1 @@
1
+ import{ToolExecutor as e}from"./executor.js";export{e as ToolExecutor};
@@ -0,0 +1,96 @@
1
+ import { LLMMessage, LLMResponse, LLMToolDefinition } from "@lssm/lib.contracts/integrations/providers/llm";
2
+
3
+ //#region src/types.d.ts
4
+ type AgentStatus = 'idle' | 'running' | 'waiting' | 'completed' | 'failed' | 'escalated';
5
+ type AgentEventName = 'agent.session.created' | 'agent.session.updated' | 'agent.iteration.started' | 'agent.iteration.completed' | 'agent.tool.called' | 'agent.tool.completed' | 'agent.tool.failed' | 'agent.escalated' | 'agent.approval_requested' | 'agent.approval_resolved' | 'agent.completed' | 'agent.failed';
6
+ interface AgentEventPayload {
7
+ sessionId: string;
8
+ agent: string;
9
+ tenantId?: string;
10
+ iteration?: number;
11
+ toolName?: string;
12
+ metadata?: Record<string, unknown>;
13
+ }
14
+ type AgentMessageMetadata = Record<string, string>;
15
+ interface AgentMessage extends Omit<LLMMessage, 'metadata'> {
16
+ metadata?: AgentMessageMetadata;
17
+ }
18
+ interface AgentSessionState {
19
+ sessionId: string;
20
+ agent: string;
21
+ version: number;
22
+ tenantId?: string;
23
+ status: AgentStatus;
24
+ messages: AgentMessage[];
25
+ createdAt: Date;
26
+ updatedAt: Date;
27
+ iterations: number;
28
+ lastConfidence?: number;
29
+ lastToolName?: string;
30
+ metadata?: Record<string, string>;
31
+ }
32
+ interface AgentRunRequestInput {
33
+ /** Agent name, e.g. `support.bot`. */
34
+ agent: string;
35
+ /** Optional version. Defaults to latest registered version. */
36
+ version?: number;
37
+ /** User-provided input or ticket description. */
38
+ input: string;
39
+ /** Tenant scoping for guardrails. */
40
+ tenantId?: string;
41
+ /** Unique end-user identifier (for personalization). */
42
+ actorId?: string;
43
+ /** Session to resume; new session created when omitted. */
44
+ sessionId?: string;
45
+ /** Arbitrary metadata forwarded to events and tool handlers. */
46
+ metadata?: Record<string, string>;
47
+ /** Optional additional system instructions appended to the agent spec. */
48
+ instructionsOverride?: string;
49
+ }
50
+ interface AgentRunResult {
51
+ session: AgentSessionState;
52
+ response: LLMResponse;
53
+ outputText: string;
54
+ confidence: number;
55
+ iterations: number;
56
+ requiresEscalation: boolean;
57
+ approvalRequestId?: string;
58
+ finishReason: 'stop' | 'tool_call' | 'timeout' | 'max_iterations' | 'length' | 'content_filter';
59
+ toolInvocations: AgentToolInvocation[];
60
+ }
61
+ interface AgentToolInvocation {
62
+ name: string;
63
+ arguments: unknown;
64
+ startedAt: Date;
65
+ completedAt?: Date;
66
+ durationMs?: number;
67
+ success: boolean;
68
+ error?: string;
69
+ }
70
+ interface AgentToolContext {
71
+ session: AgentSessionState;
72
+ tenantId?: string;
73
+ actorId?: string;
74
+ metadata?: Record<string, string>;
75
+ emit: (event: AgentEventName, payload: AgentEventPayload) => void;
76
+ }
77
+ interface AgentToolResult {
78
+ content: string;
79
+ citations?: {
80
+ label: string;
81
+ url?: string;
82
+ snippet?: string;
83
+ }[];
84
+ metadata?: Record<string, string>;
85
+ }
86
+ interface AgentToolDefinitionWithHandler {
87
+ definition: LLMToolDefinition;
88
+ timeoutMs?: number;
89
+ requiresApproval?: boolean;
90
+ allowedAgents?: string[];
91
+ handler: (input: unknown, ctx: AgentToolContext) => Promise<AgentToolResult>;
92
+ }
93
+ type AgentRunnerEventEmitter = (event: AgentEventName, payload: AgentEventPayload) => void | Promise<void>;
94
+ //#endregion
95
+ export { AgentEventName, AgentEventPayload, AgentMessage, AgentMessageMetadata, AgentRunRequestInput, AgentRunResult, AgentRunnerEventEmitter, AgentSessionState, AgentStatus, AgentToolContext, AgentToolDefinitionWithHandler, AgentToolInvocation, AgentToolResult };
96
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;KAMY,WAAA;KAQA,cAAA;AARA,UAsBK,iBAAA,CAtBM;EAQX,SAAA,EAAA,MAAc;EAcT,KAAA,EAAA,MAAA;EASL,QAAA,C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types.js ADDED
File without changes
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@lssm/lib.ai-agent",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "README.md"
11
+ ],
12
+ "scripts": {
13
+ "build": "bun build:bundle && bun build:types",
14
+ "build:bundle": "tsdown",
15
+ "build:types": "tsc --noEmit",
16
+ "dev": "bun build:bundle --watch",
17
+ "clean": "rimraf dist .turbo",
18
+ "lint": "bun lint:fix",
19
+ "lint:fix": "eslint src --fix",
20
+ "lint:check": "eslint src",
21
+ "test": "vitest run"
22
+ },
23
+ "dependencies": {
24
+ "@lssm/lib.contracts": "workspace:*"
25
+ },
26
+ "devDependencies": {
27
+ "@lssm/tool.tsdown": "workspace:*",
28
+ "@lssm/tool.typescript": "workspace:*",
29
+ "tsdown": "^0.16.6",
30
+ "typescript": "^5.9.3",
31
+ "vitest": "^1.6.0"
32
+ },
33
+ "exports": {
34
+ ".": "./dist/index.js",
35
+ "./approval": "./dist/approval/index.js",
36
+ "./approval/workflow": "./dist/approval/workflow.js",
37
+ "./memory": "./dist/memory/index.js",
38
+ "./memory/in-memory": "./dist/memory/in-memory.js",
39
+ "./memory/manager": "./dist/memory/manager.js",
40
+ "./runner": "./dist/runner.js",
41
+ "./spec": "./dist/spec.js",
42
+ "./tools": "./dist/tools/index.js",
43
+ "./tools/executor": "./dist/tools/executor.js",
44
+ "./types": "./dist/types.js",
45
+ "./*": "./*"
46
+ }
47
+ }