@contractspec/lib.ai-agent 0.0.0-canary-20260113162409
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/LICENSE +21 -0
- package/README.md +49 -0
- package/dist/_virtual/rolldown_runtime.js +8 -0
- package/dist/agent/agent-factory.d.ts +104 -0
- package/dist/agent/agent-factory.d.ts.map +1 -0
- package/dist/agent/agent-factory.js +103 -0
- package/dist/agent/agent-factory.js.map +1 -0
- package/dist/agent/contract-spec-agent.d.ts +75 -0
- package/dist/agent/contract-spec-agent.d.ts.map +1 -0
- package/dist/agent/contract-spec-agent.js +148 -0
- package/dist/agent/contract-spec-agent.js.map +1 -0
- package/dist/agent/index.d.ts +3 -0
- package/dist/agent/index.js +4 -0
- package/dist/agent/unified-agent.d.ts +131 -0
- package/dist/agent/unified-agent.d.ts.map +1 -0
- package/dist/agent/unified-agent.js +267 -0
- package/dist/agent/unified-agent.js.map +1 -0
- package/dist/approval/index.d.ts +2 -0
- package/dist/approval/index.js +3 -0
- package/dist/approval/workflow.d.ts +156 -0
- package/dist/approval/workflow.d.ts.map +1 -0
- package/dist/approval/workflow.js +160 -0
- package/dist/approval/workflow.js.map +1 -0
- package/dist/exporters/claude-agent-exporter.d.ts +64 -0
- package/dist/exporters/claude-agent-exporter.d.ts.map +1 -0
- package/dist/exporters/claude-agent-exporter.js +210 -0
- package/dist/exporters/claude-agent-exporter.js.map +1 -0
- package/dist/exporters/index.d.ts +4 -0
- package/dist/exporters/index.js +4 -0
- package/dist/exporters/opencode-exporter.d.ts +64 -0
- package/dist/exporters/opencode-exporter.d.ts.map +1 -0
- package/dist/exporters/opencode-exporter.js +200 -0
- package/dist/exporters/opencode-exporter.js.map +1 -0
- package/dist/exporters/types.d.ts +239 -0
- package/dist/exporters/types.d.ts.map +1 -0
- package/dist/exporters/types.js +0 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +31 -0
- package/dist/interop/index.d.ts +4 -0
- package/dist/interop/index.js +4 -0
- package/dist/interop/spec-consumer.d.ts +81 -0
- package/dist/interop/spec-consumer.d.ts.map +1 -0
- package/dist/interop/spec-consumer.js +287 -0
- package/dist/interop/spec-consumer.js.map +1 -0
- package/dist/interop/tool-consumer.d.ts +68 -0
- package/dist/interop/tool-consumer.d.ts.map +1 -0
- package/dist/interop/tool-consumer.js +220 -0
- package/dist/interop/tool-consumer.js.map +1 -0
- package/dist/interop/types.d.ts +262 -0
- package/dist/interop/types.d.ts.map +1 -0
- package/dist/interop/types.js +0 -0
- package/dist/knowledge/index.d.ts +2 -0
- package/dist/knowledge/index.js +3 -0
- package/dist/knowledge/injector.d.ts +38 -0
- package/dist/knowledge/injector.d.ts.map +1 -0
- package/dist/knowledge/injector.js +58 -0
- package/dist/knowledge/injector.js.map +1 -0
- package/dist/memory/in-memory.d.ts +22 -0
- package/dist/memory/in-memory.d.ts.map +1 -0
- package/dist/memory/in-memory.js +48 -0
- package/dist/memory/in-memory.js.map +1 -0
- package/dist/memory/index.d.ts +3 -0
- package/dist/memory/index.js +4 -0
- package/dist/memory/manager.d.ts +42 -0
- package/dist/memory/manager.d.ts.map +1 -0
- package/dist/memory/manager.js +80 -0
- package/dist/memory/manager.js.map +1 -0
- package/dist/providers/claude-agent-sdk/adapter.d.ts +58 -0
- package/dist/providers/claude-agent-sdk/adapter.d.ts.map +1 -0
- package/dist/providers/claude-agent-sdk/adapter.js +306 -0
- package/dist/providers/claude-agent-sdk/adapter.js.map +1 -0
- package/dist/providers/claude-agent-sdk/index.d.ts +4 -0
- package/dist/providers/claude-agent-sdk/index.js +5 -0
- package/dist/providers/claude-agent-sdk/session-bridge.d.ts +101 -0
- package/dist/providers/claude-agent-sdk/session-bridge.d.ts.map +1 -0
- package/dist/providers/claude-agent-sdk/session-bridge.js +158 -0
- package/dist/providers/claude-agent-sdk/session-bridge.js.map +1 -0
- package/dist/providers/claude-agent-sdk/tool-bridge.d.ts +110 -0
- package/dist/providers/claude-agent-sdk/tool-bridge.d.ts.map +1 -0
- package/dist/providers/claude-agent-sdk/tool-bridge.js +122 -0
- package/dist/providers/claude-agent-sdk/tool-bridge.js.map +1 -0
- package/dist/providers/index.d.ts +7 -0
- package/dist/providers/index.js +8 -0
- package/dist/providers/opencode-sdk/adapter.d.ts +54 -0
- package/dist/providers/opencode-sdk/adapter.d.ts.map +1 -0
- package/dist/providers/opencode-sdk/adapter.js +276 -0
- package/dist/providers/opencode-sdk/adapter.js.map +1 -0
- package/dist/providers/opencode-sdk/agent-bridge.d.ts +94 -0
- package/dist/providers/opencode-sdk/agent-bridge.d.ts.map +1 -0
- package/dist/providers/opencode-sdk/agent-bridge.js +165 -0
- package/dist/providers/opencode-sdk/agent-bridge.js.map +1 -0
- package/dist/providers/opencode-sdk/index.d.ts +4 -0
- package/dist/providers/opencode-sdk/index.js +5 -0
- package/dist/providers/opencode-sdk/tool-bridge.d.ts +81 -0
- package/dist/providers/opencode-sdk/tool-bridge.d.ts.map +1 -0
- package/dist/providers/opencode-sdk/tool-bridge.js +127 -0
- package/dist/providers/opencode-sdk/tool-bridge.js.map +1 -0
- package/dist/providers/registry.d.ts +22 -0
- package/dist/providers/registry.d.ts.map +1 -0
- package/dist/providers/registry.js +52 -0
- package/dist/providers/registry.js.map +1 -0
- package/dist/providers/types.d.ts +243 -0
- package/dist/providers/types.d.ts.map +1 -0
- package/dist/providers/types.js +44 -0
- package/dist/providers/types.js.map +1 -0
- package/dist/schema/index.d.ts +3 -0
- package/dist/schema/index.js +4 -0
- package/dist/schema/json-schema-to-zod.d.ts +55 -0
- package/dist/schema/json-schema-to-zod.d.ts.map +1 -0
- package/dist/schema/json-schema-to-zod.js +124 -0
- package/dist/schema/json-schema-to-zod.js.map +1 -0
- package/dist/schema/schema-output.d.ts +77 -0
- package/dist/schema/schema-output.d.ts.map +1 -0
- package/dist/schema/schema-output.js +65 -0
- package/dist/schema/schema-output.js.map +1 -0
- package/dist/session/index.d.ts +2 -0
- package/dist/session/index.js +3 -0
- package/dist/session/store.d.ts +74 -0
- package/dist/session/store.d.ts.map +1 -0
- package/dist/session/store.js +79 -0
- package/dist/session/store.js.map +1 -0
- package/dist/spec/index.d.ts +3 -0
- package/dist/spec/index.js +4 -0
- package/dist/spec/registry.d.ts +47 -0
- package/dist/spec/registry.d.ts.map +1 -0
- package/dist/spec/registry.js +65 -0
- package/dist/spec/registry.js.map +1 -0
- package/dist/spec/spec.d.ts +127 -0
- package/dist/spec/spec.d.ts.map +1 -0
- package/dist/spec/spec.js +30 -0
- package/dist/spec/spec.js.map +1 -0
- package/dist/telemetry/adapter.d.ts +73 -0
- package/dist/telemetry/adapter.d.ts.map +1 -0
- package/dist/telemetry/adapter.js +103 -0
- package/dist/telemetry/adapter.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/tools/index.d.ts +5 -0
- package/dist/tools/index.js +6 -0
- package/dist/tools/knowledge-tool.d.ts +21 -0
- package/dist/tools/knowledge-tool.d.ts.map +1 -0
- package/dist/tools/knowledge-tool.js +54 -0
- package/dist/tools/knowledge-tool.js.map +1 -0
- package/dist/tools/mcp-client.d.ts +59 -0
- package/dist/tools/mcp-client.d.ts.map +1 -0
- package/dist/tools/mcp-client.js +58 -0
- package/dist/tools/mcp-client.js.map +1 -0
- package/dist/tools/mcp-server.d.ts +46 -0
- package/dist/tools/mcp-server.d.ts.map +1 -0
- package/dist/tools/mcp-server.js +69 -0
- package/dist/tools/mcp-server.js.map +1 -0
- package/dist/tools/tool-adapter.d.ts +50 -0
- package/dist/tools/tool-adapter.d.ts.map +1 -0
- package/dist/tools/tool-adapter.js +80 -0
- package/dist/tools/tool-adapter.js.map +1 -0
- package/dist/types.d.ts +146 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +0 -0
- package/package.json +155 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry.js","names":[],"sources":["../../src/spec/registry.ts"],"sourcesContent":["import type { AgentSpec } from './spec';\nimport { compareVersions } from 'compare-versions';\nimport { SpecContractRegistry } from '@contractspec/lib.contracts/registry';\n\n/**\n * Registry for managing agent specifications.\n *\n * Provides registration, lookup, and version management for agent specs.\n */\nexport class AgentRegistry extends SpecContractRegistry<'agent', AgentSpec> {\n public constructor(items?: AgentSpec[]) {\n super('agent', items);\n }\n\n /**\n * List all unique agent names (without versions).\n */\n listNames(): string[] {\n const names = new Set<string>();\n for (const spec of this.items.values()) {\n names.add(spec.meta.key);\n }\n return [...names];\n }\n\n /**\n * Get an agent specification or throw if not found.\n *\n * @param name - Agent name\n * @param version - Optional version\n * @returns The agent spec\n * @throws Error if the spec is not found\n */\n require(name: string, version?: string): AgentSpec {\n const spec = this.get(name, version);\n if (!spec) {\n throw new Error(\n `Agent spec not found for ${name}${version != null ? `.v${version}` : ''}`\n );\n }\n return spec;\n }\n\n /**\n * Check if an agent is registered.\n *\n * @param name - Agent name\n * @param version - Optional version\n */\n has(name: string, version?: string): boolean {\n return this.get(name, version) !== undefined;\n }\n\n /**\n * Get all versions of an agent.\n *\n * @param name - Agent name\n * @returns Array of specs sorted by version (ascending)\n */\n getVersions(name: string): AgentSpec[] {\n const versions: AgentSpec[] = [];\n for (const spec of this.items.values()) {\n if (spec.meta.key === name) {\n versions.push(spec);\n }\n }\n return versions.sort((a, b) =>\n compareVersions(a.meta.version, b.meta.version)\n );\n }\n}\n\n/**\n * Create a new agent registry.\n */\nexport function createAgentRegistry(): AgentRegistry {\n return new AgentRegistry();\n}\n"],"mappings":";;;;;;;;;AASA,IAAa,gBAAb,cAAmC,qBAAyC;CAC1E,AAAO,YAAY,OAAqB;AACtC,QAAM,SAAS,MAAM;;;;;CAMvB,YAAsB;EACpB,MAAM,wBAAQ,IAAI,KAAa;AAC/B,OAAK,MAAM,QAAQ,KAAK,MAAM,QAAQ,CACpC,OAAM,IAAI,KAAK,KAAK,IAAI;AAE1B,SAAO,CAAC,GAAG,MAAM;;;;;;;;;;CAWnB,QAAQ,MAAc,SAA6B;EACjD,MAAM,OAAO,KAAK,IAAI,MAAM,QAAQ;AACpC,MAAI,CAAC,KACH,OAAM,IAAI,MACR,4BAA4B,OAAO,WAAW,OAAO,KAAK,YAAY,KACvE;AAEH,SAAO;;;;;;;;CAST,IAAI,MAAc,SAA2B;AAC3C,SAAO,KAAK,IAAI,MAAM,QAAQ,KAAK;;;;;;;;CASrC,YAAY,MAA2B;EACrC,MAAM,WAAwB,EAAE;AAChC,OAAK,MAAM,QAAQ,KAAK,MAAM,QAAQ,CACpC,KAAI,KAAK,KAAK,QAAQ,KACpB,UAAS,KAAK,KAAK;AAGvB,SAAO,SAAS,MAAM,GAAG,MACvB,gBAAgB,EAAE,KAAK,SAAS,EAAE,KAAK,QAAQ,CAChD;;;;;;AAOL,SAAgB,sBAAqC;AACnD,QAAO,IAAI,eAAe"}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { OwnerShipMeta } from "@contractspec/lib.contracts/ownership";
|
|
2
|
+
import { KnowledgeCategory } from "@contractspec/lib.contracts/knowledge/spec";
|
|
3
|
+
import { PolicyRef } from "@contractspec/lib.contracts/policy/spec";
|
|
4
|
+
|
|
5
|
+
//#region src/spec/spec.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Metadata for an agent specification.
|
|
9
|
+
*/
|
|
10
|
+
type AgentMeta = OwnerShipMeta;
|
|
11
|
+
/**
|
|
12
|
+
* Configuration for a tool that an agent can use.
|
|
13
|
+
*/
|
|
14
|
+
interface AgentToolConfig {
|
|
15
|
+
/** Tool name (unique within the agent) */
|
|
16
|
+
name: string;
|
|
17
|
+
/** Human-readable description for the LLM */
|
|
18
|
+
description?: string;
|
|
19
|
+
/** JSON Schema fragment for tool parameters */
|
|
20
|
+
schema?: Record<string, unknown>;
|
|
21
|
+
/** Optional cooldown in milliseconds between invocations */
|
|
22
|
+
cooldownMs?: number;
|
|
23
|
+
/** Maximum execution time before timeout */
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
/** Whether the tool can be executed without human approval (AI SDK needsApproval = !automationSafe) */
|
|
26
|
+
automationSafe?: boolean;
|
|
27
|
+
/** Explicit approval requirement (overrides automationSafe) */
|
|
28
|
+
requiresApproval?: boolean;
|
|
29
|
+
/** Optional policy guard that must evaluate to allow the tool call */
|
|
30
|
+
policy?: PolicyRef;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Reference to a knowledge space that the agent can access.
|
|
34
|
+
*/
|
|
35
|
+
interface AgentKnowledgeRef {
|
|
36
|
+
/** Knowledge space key */
|
|
37
|
+
key: string;
|
|
38
|
+
/** Optional specific version */
|
|
39
|
+
version?: number;
|
|
40
|
+
/** Filter by knowledge category */
|
|
41
|
+
category?: KnowledgeCategory;
|
|
42
|
+
/** Whether the knowledge is required (static injection) or optional (dynamic RAG) */
|
|
43
|
+
required?: boolean;
|
|
44
|
+
/** Additional instructions appended when the space is available */
|
|
45
|
+
instructions?: string;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Memory configuration for agent session persistence.
|
|
49
|
+
*/
|
|
50
|
+
interface AgentMemoryConfig {
|
|
51
|
+
/** Maximum entries to keep in memory */
|
|
52
|
+
maxEntries?: number;
|
|
53
|
+
/** Time-to-live in minutes */
|
|
54
|
+
ttlMinutes?: number;
|
|
55
|
+
/** Number of messages before triggering summarization */
|
|
56
|
+
summaryTrigger?: number;
|
|
57
|
+
/** Whether to persist to long-term storage */
|
|
58
|
+
persistLongTerm?: boolean;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Confidence policy for agent responses.
|
|
62
|
+
*/
|
|
63
|
+
interface AgentConfidencePolicy {
|
|
64
|
+
/** Minimum acceptable confidence before escalation. Defaults to 0.7 */
|
|
65
|
+
min?: number;
|
|
66
|
+
/** Default value used when provider does not report confidence */
|
|
67
|
+
default?: number;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Escalation policy for handling uncertain or failed agent responses.
|
|
71
|
+
*/
|
|
72
|
+
interface AgentEscalationPolicy {
|
|
73
|
+
/** Auto escalate when confidence < threshold */
|
|
74
|
+
confidenceThreshold?: number;
|
|
75
|
+
/** Escalate when a tool throws irrecoverable errors */
|
|
76
|
+
onToolFailure?: boolean;
|
|
77
|
+
/** Escalate when iteration budget exceeded */
|
|
78
|
+
onTimeout?: boolean;
|
|
79
|
+
/** Optional human approval workflow ID */
|
|
80
|
+
approvalWorkflow?: string;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Combined policy configuration for an agent.
|
|
84
|
+
*/
|
|
85
|
+
interface AgentPolicy {
|
|
86
|
+
confidence?: AgentConfidencePolicy;
|
|
87
|
+
escalation?: AgentEscalationPolicy;
|
|
88
|
+
/** Feature flags to apply to this agent */
|
|
89
|
+
flags?: string[];
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Complete specification for a ContractSpec agent.
|
|
93
|
+
*/
|
|
94
|
+
interface AgentSpec {
|
|
95
|
+
meta: AgentMeta;
|
|
96
|
+
/** System instructions for the agent */
|
|
97
|
+
instructions: string;
|
|
98
|
+
/** Human-readable description */
|
|
99
|
+
description?: string;
|
|
100
|
+
/** Tags for categorization */
|
|
101
|
+
tags?: string[];
|
|
102
|
+
/** Tools the agent can use */
|
|
103
|
+
tools: AgentToolConfig[];
|
|
104
|
+
/** Memory/session configuration */
|
|
105
|
+
memory?: AgentMemoryConfig;
|
|
106
|
+
/** Knowledge spaces the agent can access */
|
|
107
|
+
knowledge?: AgentKnowledgeRef[];
|
|
108
|
+
/** Policy configuration */
|
|
109
|
+
policy?: AgentPolicy;
|
|
110
|
+
/** Maximum steps per generation (defaults to 10) */
|
|
111
|
+
maxSteps?: number;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Define and validate an agent specification.
|
|
115
|
+
*
|
|
116
|
+
* @param spec - The agent specification
|
|
117
|
+
* @returns The frozen, validated specification
|
|
118
|
+
* @throws Error if the specification is invalid
|
|
119
|
+
*/
|
|
120
|
+
declare function defineAgent(spec: AgentSpec): AgentSpec;
|
|
121
|
+
/**
|
|
122
|
+
* Generate a unique key for an agent spec.
|
|
123
|
+
*/
|
|
124
|
+
declare function agentKey(meta: AgentMeta): string;
|
|
125
|
+
//#endregion
|
|
126
|
+
export { AgentConfidencePolicy, AgentEscalationPolicy, AgentKnowledgeRef, AgentMemoryConfig, AgentMeta, AgentPolicy, AgentSpec, AgentToolConfig, agentKey, defineAgent };
|
|
127
|
+
//# sourceMappingURL=spec.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spec.d.ts","names":[],"sources":["../../src/spec/spec.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAOA;AAKiB,KALL,SAAA,GAAY,aAWb;AAgBX;AAgBA;AAcA;AAUiB,UA9DA,eAAA,CA8DqB;EAcrB;EAUA,IAAA,EAAA,MAAS;EAClB;EAQC,WAAA,CAAA,EAAA,MAAA;EAEE;EAEG,MAAA,CAAA,EA7FH,MA6FG,CAAA,MAAA,EAAA,OAAA,CAAA;EAEH;EAAW,UAAA,CAAA,EAAA,MAAA;EAYN;EA+BA,SAAA,CAAA,EAAQ,MAAA;;;;;;WAhIb;;;;;UAMM,iBAAA;;;;;;aAMJ;;;;;;;;;UAUI,iBAAA;;;;;;;;;;;;;UAcA,qBAAA;;;;;;;;;UAUA,qBAAA;;;;;;;;;;;;;UAcA,WAAA;eACF;eACA;;;;;;;UAQE,SAAA;QACT;;;;;;;;SAQC;;WAEE;;cAEG;;WAEH;;;;;;;;;;;iBAYK,WAAA,OAAkB,YAAY;;;;iBA+B9B,QAAA,OAAe"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/spec/spec.ts
|
|
2
|
+
/**
|
|
3
|
+
* Define and validate an agent specification.
|
|
4
|
+
*
|
|
5
|
+
* @param spec - The agent specification
|
|
6
|
+
* @returns The frozen, validated specification
|
|
7
|
+
* @throws Error if the specification is invalid
|
|
8
|
+
*/
|
|
9
|
+
function defineAgent(spec) {
|
|
10
|
+
if (!spec.meta?.key) throw new Error("Agent key is required");
|
|
11
|
+
if (typeof spec.meta.version !== "string") throw new Error(`Agent ${spec.meta.key} is missing a string version`);
|
|
12
|
+
if (!spec.instructions?.trim()) throw new Error(`Agent ${spec.meta.key} requires instructions`);
|
|
13
|
+
if (!spec.tools?.length) throw new Error(`Agent ${spec.meta.key} must expose at least one tool`);
|
|
14
|
+
const toolNames = /* @__PURE__ */ new Set();
|
|
15
|
+
for (const tool of spec.tools) {
|
|
16
|
+
if (toolNames.has(tool.name)) throw new Error(`Agent ${spec.meta.key} has duplicate tool name: ${tool.name}`);
|
|
17
|
+
toolNames.add(tool.name);
|
|
18
|
+
}
|
|
19
|
+
return Object.freeze(spec);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Generate a unique key for an agent spec.
|
|
23
|
+
*/
|
|
24
|
+
function agentKey(meta) {
|
|
25
|
+
return `${meta.key}.v${meta.version}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
//#endregion
|
|
29
|
+
export { agentKey, defineAgent };
|
|
30
|
+
//# sourceMappingURL=spec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spec.js","names":[],"sources":["../../src/spec/spec.ts"],"sourcesContent":["import type { OwnerShipMeta } from '@contractspec/lib.contracts/ownership';\nimport type { KnowledgeCategory } from '@contractspec/lib.contracts/knowledge/spec';\nimport type { PolicyRef } from '@contractspec/lib.contracts/policy/spec';\n\n/**\n * Metadata for an agent specification.\n */\nexport type AgentMeta = OwnerShipMeta;\n\n/**\n * Configuration for a tool that an agent can use.\n */\nexport interface AgentToolConfig {\n /** Tool name (unique within the agent) */\n name: string;\n /** Human-readable description for the LLM */\n description?: string;\n /** JSON Schema fragment for tool parameters */\n schema?: Record<string, unknown>;\n /** Optional cooldown in milliseconds between invocations */\n cooldownMs?: number;\n /** Maximum execution time before timeout */\n timeoutMs?: number;\n /** Whether the tool can be executed without human approval (AI SDK needsApproval = !automationSafe) */\n automationSafe?: boolean;\n /** Explicit approval requirement (overrides automationSafe) */\n requiresApproval?: boolean;\n /** Optional policy guard that must evaluate to allow the tool call */\n policy?: PolicyRef;\n}\n\n/**\n * Reference to a knowledge space that the agent can access.\n */\nexport interface AgentKnowledgeRef {\n /** Knowledge space key */\n key: string;\n /** Optional specific version */\n version?: number;\n /** Filter by knowledge category */\n category?: KnowledgeCategory;\n /** Whether the knowledge is required (static injection) or optional (dynamic RAG) */\n required?: boolean;\n /** Additional instructions appended when the space is available */\n instructions?: string;\n}\n\n/**\n * Memory configuration for agent session persistence.\n */\nexport interface AgentMemoryConfig {\n /** Maximum entries to keep in memory */\n maxEntries?: number;\n /** Time-to-live in minutes */\n ttlMinutes?: number;\n /** Number of messages before triggering summarization */\n summaryTrigger?: number;\n /** Whether to persist to long-term storage */\n persistLongTerm?: boolean;\n}\n\n/**\n * Confidence policy for agent responses.\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\n/**\n * Escalation policy for handling uncertain or failed agent responses.\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\n/**\n * Combined policy configuration for an agent.\n */\nexport interface AgentPolicy {\n confidence?: AgentConfidencePolicy;\n escalation?: AgentEscalationPolicy;\n /** Feature flags to apply to this agent */\n flags?: string[];\n}\n\n/**\n * Complete specification for a ContractSpec agent.\n */\nexport interface AgentSpec {\n meta: AgentMeta;\n /** System instructions for the agent */\n instructions: string;\n /** Human-readable description */\n description?: string;\n /** Tags for categorization */\n tags?: string[];\n /** Tools the agent can use */\n tools: AgentToolConfig[];\n /** Memory/session configuration */\n memory?: AgentMemoryConfig;\n /** Knowledge spaces the agent can access */\n knowledge?: AgentKnowledgeRef[];\n /** Policy configuration */\n policy?: AgentPolicy;\n /** Maximum steps per generation (defaults to 10) */\n maxSteps?: number;\n}\n\n/**\n * Define and validate an agent specification.\n *\n * @param spec - The agent specification\n * @returns The frozen, validated specification\n * @throws Error if the specification is invalid\n */\nexport function defineAgent(spec: AgentSpec): AgentSpec {\n if (!spec.meta?.key) {\n throw new Error('Agent key is required');\n }\n if (typeof spec.meta.version !== 'string') {\n throw new Error(`Agent ${spec.meta.key} is missing a string version`);\n }\n if (!spec.instructions?.trim()) {\n throw new Error(`Agent ${spec.meta.key} requires instructions`);\n }\n if (!spec.tools?.length) {\n throw new Error(`Agent ${spec.meta.key} must expose at least one tool`);\n }\n\n // Validate tool names are unique\n const toolNames = new Set<string>();\n for (const tool of spec.tools) {\n if (toolNames.has(tool.name)) {\n throw new Error(\n `Agent ${spec.meta.key} has duplicate tool name: ${tool.name}`\n );\n }\n toolNames.add(tool.name);\n }\n\n return Object.freeze(spec);\n}\n\n/**\n * Generate a unique key for an agent spec.\n */\nexport function agentKey(meta: AgentMeta): string {\n return `${meta.key}.v${meta.version}`;\n}\n"],"mappings":";;;;;;;;AA6HA,SAAgB,YAAY,MAA4B;AACtD,KAAI,CAAC,KAAK,MAAM,IACd,OAAM,IAAI,MAAM,wBAAwB;AAE1C,KAAI,OAAO,KAAK,KAAK,YAAY,SAC/B,OAAM,IAAI,MAAM,SAAS,KAAK,KAAK,IAAI,8BAA8B;AAEvE,KAAI,CAAC,KAAK,cAAc,MAAM,CAC5B,OAAM,IAAI,MAAM,SAAS,KAAK,KAAK,IAAI,wBAAwB;AAEjE,KAAI,CAAC,KAAK,OAAO,OACf,OAAM,IAAI,MAAM,SAAS,KAAK,KAAK,IAAI,gCAAgC;CAIzE,MAAM,4BAAY,IAAI,KAAa;AACnC,MAAK,MAAM,QAAQ,KAAK,OAAO;AAC7B,MAAI,UAAU,IAAI,KAAK,KAAK,CAC1B,OAAM,IAAI,MACR,SAAS,KAAK,KAAK,IAAI,4BAA4B,KAAK,OACzD;AAEH,YAAU,IAAI,KAAK,KAAK;;AAG1B,QAAO,OAAO,OAAO,KAAK;;;;;AAM5B,SAAgB,SAAS,MAAyB;AAChD,QAAO,GAAG,KAAK,IAAI,IAAI,KAAK"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { StepResult, ToolSet } from "ai";
|
|
2
|
+
|
|
3
|
+
//#region src/telemetry/adapter.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Metric sample compatible with @contractspec/lib.evolution OperationMetricSample.
|
|
7
|
+
*/
|
|
8
|
+
interface OperationMetricSample {
|
|
9
|
+
operation: {
|
|
10
|
+
name: string;
|
|
11
|
+
version: string;
|
|
12
|
+
};
|
|
13
|
+
durationMs: number;
|
|
14
|
+
success: boolean;
|
|
15
|
+
timestamp: Date;
|
|
16
|
+
metadata?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Interface for collecting telemetry metrics.
|
|
20
|
+
*
|
|
21
|
+
* Implementations can send metrics to:
|
|
22
|
+
* - @contractspec/lib.evolution for self-improvement
|
|
23
|
+
* - PostHog for analytics
|
|
24
|
+
* - Custom monitoring systems
|
|
25
|
+
*/
|
|
26
|
+
interface TelemetryCollector {
|
|
27
|
+
/**
|
|
28
|
+
* Collect a metric sample.
|
|
29
|
+
*/
|
|
30
|
+
collect(sample: OperationMetricSample): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Track an agent step for telemetry.
|
|
34
|
+
*
|
|
35
|
+
* Called from ContractSpecAgent.onStepFinish to feed metrics
|
|
36
|
+
* to the evolution engine.
|
|
37
|
+
*
|
|
38
|
+
* @param collector - Telemetry collector
|
|
39
|
+
* @param agentId - Agent identifier (e.g., "support.bot.v1")
|
|
40
|
+
* @param step - AI SDK step result
|
|
41
|
+
* @param durationMs - Optional step duration in milliseconds
|
|
42
|
+
*/
|
|
43
|
+
declare function trackAgentStep(collector: TelemetryCollector, agentId: string, step: StepResult<ToolSet>, durationMs?: number): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* In-memory telemetry collector for testing.
|
|
46
|
+
*/
|
|
47
|
+
declare class InMemoryTelemetryCollector implements TelemetryCollector {
|
|
48
|
+
private readonly samples;
|
|
49
|
+
collect(sample: OperationMetricSample): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Get all collected samples.
|
|
52
|
+
*/
|
|
53
|
+
getSamples(): OperationMetricSample[];
|
|
54
|
+
/**
|
|
55
|
+
* Get samples for a specific operation.
|
|
56
|
+
*/
|
|
57
|
+
getSamplesForOperation(operationName: string): OperationMetricSample[];
|
|
58
|
+
/**
|
|
59
|
+
* Clear all samples.
|
|
60
|
+
*/
|
|
61
|
+
clear(): void;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Create an in-memory telemetry collector.
|
|
65
|
+
*/
|
|
66
|
+
declare function createInMemoryTelemetryCollector(): InMemoryTelemetryCollector;
|
|
67
|
+
/**
|
|
68
|
+
* No-op telemetry collector that discards all metrics.
|
|
69
|
+
*/
|
|
70
|
+
declare const noopTelemetryCollector: TelemetryCollector;
|
|
71
|
+
//#endregion
|
|
72
|
+
export { InMemoryTelemetryCollector, OperationMetricSample, TelemetryCollector, createInMemoryTelemetryCollector, noopTelemetryCollector, trackAgentStep };
|
|
73
|
+
//# sourceMappingURL=adapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","names":[],"sources":["../../src/telemetry/adapter.ts"],"sourcesContent":[],"mappings":";;;;;;AAKA;AAgBiB,UAhBA,qBAAA,CAoBC;EA0BI,SAAA,EAAA;IACT,IAAA,EAAA,MAAA;IAEM,OAAA,EAAA,MAAA;EAAX,CAAA;EAEL,UAAA,EAAA,MAAA;EAAO,OAAA,EAAA,OAAA;EAyCG,SAAA,EAxFA,IAwFA;EAGW,QAAA,CAAA,EA1FX,MA0FW,CAAA,MAAA,EAAA,OAAA,CAAA;;;;;;AA6BxB;AAOA;;;UAnHiB,kBAAA;;;;kBAIC,wBAAwB;;;;;;;;;;;;;iBA0BpB,cAAA,YACT,2CAEL,WAAW,gCAEhB;;;;cAyCU,0BAAA,YAAsC;;kBAG3B,wBAAwB;;;;gBAOhC;;;;iDAOiC;;;;;;;;;iBAejC,gCAAA,CAAA,GAAoC;;;;cAOvC,wBAAwB"}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
//#region src/telemetry/adapter.ts
|
|
2
|
+
/**
|
|
3
|
+
* Parse agent ID into name and version.
|
|
4
|
+
*/
|
|
5
|
+
function parseAgentId(agentId) {
|
|
6
|
+
const match = agentId.match(/^(.+)\.v(\s+)$/);
|
|
7
|
+
if (match) return {
|
|
8
|
+
name: match[1],
|
|
9
|
+
version: match[2]
|
|
10
|
+
};
|
|
11
|
+
return {
|
|
12
|
+
name: agentId,
|
|
13
|
+
version: "1.0.0"
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Track an agent step for telemetry.
|
|
18
|
+
*
|
|
19
|
+
* Called from ContractSpecAgent.onStepFinish to feed metrics
|
|
20
|
+
* to the evolution engine.
|
|
21
|
+
*
|
|
22
|
+
* @param collector - Telemetry collector
|
|
23
|
+
* @param agentId - Agent identifier (e.g., "support.bot.v1")
|
|
24
|
+
* @param step - AI SDK step result
|
|
25
|
+
* @param durationMs - Optional step duration in milliseconds
|
|
26
|
+
*/
|
|
27
|
+
async function trackAgentStep(collector, agentId, step, durationMs) {
|
|
28
|
+
const { name, version } = parseAgentId(agentId);
|
|
29
|
+
for (const toolCall of step.toolCalls ?? []) {
|
|
30
|
+
const toolSample = {
|
|
31
|
+
operation: {
|
|
32
|
+
name: `${name}.${toolCall.toolName}`,
|
|
33
|
+
version
|
|
34
|
+
},
|
|
35
|
+
durationMs: durationMs ?? 0,
|
|
36
|
+
success: step.toolResults?.some((r) => r.toolCallId === toolCall.toolCallId && r.output !== void 0) ?? false,
|
|
37
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
38
|
+
metadata: {
|
|
39
|
+
agentId,
|
|
40
|
+
toolName: toolCall.toolName,
|
|
41
|
+
finishReason: step.finishReason
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
await collector.collect(toolSample);
|
|
45
|
+
}
|
|
46
|
+
const stepSample = {
|
|
47
|
+
operation: {
|
|
48
|
+
name,
|
|
49
|
+
version
|
|
50
|
+
},
|
|
51
|
+
durationMs: durationMs ?? 0,
|
|
52
|
+
success: step.finishReason !== "error",
|
|
53
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
54
|
+
metadata: {
|
|
55
|
+
agentId,
|
|
56
|
+
finishReason: step.finishReason,
|
|
57
|
+
tokenUsage: step.usage,
|
|
58
|
+
toolCallCount: step.toolCalls?.length ?? 0
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
await collector.collect(stepSample);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* In-memory telemetry collector for testing.
|
|
65
|
+
*/
|
|
66
|
+
var InMemoryTelemetryCollector = class {
|
|
67
|
+
samples = [];
|
|
68
|
+
async collect(sample) {
|
|
69
|
+
this.samples.push(sample);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Get all collected samples.
|
|
73
|
+
*/
|
|
74
|
+
getSamples() {
|
|
75
|
+
return [...this.samples];
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Get samples for a specific operation.
|
|
79
|
+
*/
|
|
80
|
+
getSamplesForOperation(operationName) {
|
|
81
|
+
return this.samples.filter((s) => s.operation.name === operationName);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Clear all samples.
|
|
85
|
+
*/
|
|
86
|
+
clear() {
|
|
87
|
+
this.samples.length = 0;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Create an in-memory telemetry collector.
|
|
92
|
+
*/
|
|
93
|
+
function createInMemoryTelemetryCollector() {
|
|
94
|
+
return new InMemoryTelemetryCollector();
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* No-op telemetry collector that discards all metrics.
|
|
98
|
+
*/
|
|
99
|
+
const noopTelemetryCollector = { collect: async () => {} };
|
|
100
|
+
|
|
101
|
+
//#endregion
|
|
102
|
+
export { InMemoryTelemetryCollector, createInMemoryTelemetryCollector, noopTelemetryCollector, trackAgentStep };
|
|
103
|
+
//# sourceMappingURL=adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter.js","names":[],"sources":["../../src/telemetry/adapter.ts"],"sourcesContent":["import type { StepResult, ToolSet } from 'ai';\n\n/**\n * Metric sample compatible with @contractspec/lib.evolution OperationMetricSample.\n */\nexport interface OperationMetricSample {\n operation: { name: string; version: string };\n durationMs: number;\n success: boolean;\n timestamp: Date;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Interface for collecting telemetry metrics.\n *\n * Implementations can send metrics to:\n * - @contractspec/lib.evolution for self-improvement\n * - PostHog for analytics\n * - Custom monitoring systems\n */\nexport interface TelemetryCollector {\n /**\n * Collect a metric sample.\n */\n collect(sample: OperationMetricSample): Promise<void>;\n}\n\n/**\n * Parse agent ID into name and version.\n */\nfunction parseAgentId(agentId: string): { name: string; version: string } {\n const match = agentId.match(/^(.+)\\.v(\\s+)$/);\n if (match) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return { name: match[1]!, version: match[2]! };\n }\n return { name: agentId, version: '1.0.0' };\n}\n\n/**\n * Track an agent step for telemetry.\n *\n * Called from ContractSpecAgent.onStepFinish to feed metrics\n * to the evolution engine.\n *\n * @param collector - Telemetry collector\n * @param agentId - Agent identifier (e.g., \"support.bot.v1\")\n * @param step - AI SDK step result\n * @param durationMs - Optional step duration in milliseconds\n */\nexport async function trackAgentStep(\n collector: TelemetryCollector,\n agentId: string,\n step: StepResult<ToolSet>,\n durationMs?: number\n): Promise<void> {\n const { name, version } = parseAgentId(agentId);\n\n // Track tool invocations\n for (const toolCall of step.toolCalls ?? []) {\n const toolSample: OperationMetricSample = {\n operation: { name: `${name}.${toolCall.toolName}`, version },\n durationMs: durationMs ?? 0,\n success:\n step.toolResults?.some(\n (r) => r.toolCallId === toolCall.toolCallId && r.output !== undefined\n ) ?? false,\n timestamp: new Date(),\n metadata: {\n agentId,\n toolName: toolCall.toolName,\n finishReason: step.finishReason,\n },\n };\n await collector.collect(toolSample);\n }\n\n // Track overall step\n const stepSample: OperationMetricSample = {\n operation: { name, version },\n durationMs: durationMs ?? 0,\n success: step.finishReason !== 'error',\n timestamp: new Date(),\n metadata: {\n agentId,\n finishReason: step.finishReason,\n tokenUsage: step.usage,\n toolCallCount: step.toolCalls?.length ?? 0,\n },\n };\n await collector.collect(stepSample);\n}\n\n/**\n * In-memory telemetry collector for testing.\n */\nexport class InMemoryTelemetryCollector implements TelemetryCollector {\n private readonly samples: OperationMetricSample[] = [];\n\n async collect(sample: OperationMetricSample): Promise<void> {\n this.samples.push(sample);\n }\n\n /**\n * Get all collected samples.\n */\n getSamples(): OperationMetricSample[] {\n return [...this.samples];\n }\n\n /**\n * Get samples for a specific operation.\n */\n getSamplesForOperation(operationName: string): OperationMetricSample[] {\n return this.samples.filter((s) => s.operation.name === operationName);\n }\n\n /**\n * Clear all samples.\n */\n clear(): void {\n this.samples.length = 0;\n }\n}\n\n/**\n * Create an in-memory telemetry collector.\n */\nexport function createInMemoryTelemetryCollector(): InMemoryTelemetryCollector {\n return new InMemoryTelemetryCollector();\n}\n\n/**\n * No-op telemetry collector that discards all metrics.\n */\nexport const noopTelemetryCollector: TelemetryCollector = {\n collect: async () => {\n /* noop */\n },\n};\n"],"mappings":";;;;AA+BA,SAAS,aAAa,SAAoD;CACxE,MAAM,QAAQ,QAAQ,MAAM,iBAAiB;AAC7C,KAAI,MAEF,QAAO;EAAE,MAAM,MAAM;EAAK,SAAS,MAAM;EAAK;AAEhD,QAAO;EAAE,MAAM;EAAS,SAAS;EAAS;;;;;;;;;;;;;AAc5C,eAAsB,eACpB,WACA,SACA,MACA,YACe;CACf,MAAM,EAAE,MAAM,YAAY,aAAa,QAAQ;AAG/C,MAAK,MAAM,YAAY,KAAK,aAAa,EAAE,EAAE;EAC3C,MAAM,aAAoC;GACxC,WAAW;IAAE,MAAM,GAAG,KAAK,GAAG,SAAS;IAAY;IAAS;GAC5D,YAAY,cAAc;GAC1B,SACE,KAAK,aAAa,MACf,MAAM,EAAE,eAAe,SAAS,cAAc,EAAE,WAAW,OAC7D,IAAI;GACP,2BAAW,IAAI,MAAM;GACrB,UAAU;IACR;IACA,UAAU,SAAS;IACnB,cAAc,KAAK;IACpB;GACF;AACD,QAAM,UAAU,QAAQ,WAAW;;CAIrC,MAAM,aAAoC;EACxC,WAAW;GAAE;GAAM;GAAS;EAC5B,YAAY,cAAc;EAC1B,SAAS,KAAK,iBAAiB;EAC/B,2BAAW,IAAI,MAAM;EACrB,UAAU;GACR;GACA,cAAc,KAAK;GACnB,YAAY,KAAK;GACjB,eAAe,KAAK,WAAW,UAAU;GAC1C;EACF;AACD,OAAM,UAAU,QAAQ,WAAW;;;;;AAMrC,IAAa,6BAAb,MAAsE;CACpE,AAAiB,UAAmC,EAAE;CAEtD,MAAM,QAAQ,QAA8C;AAC1D,OAAK,QAAQ,KAAK,OAAO;;;;;CAM3B,aAAsC;AACpC,SAAO,CAAC,GAAG,KAAK,QAAQ;;;;;CAM1B,uBAAuB,eAAgD;AACrE,SAAO,KAAK,QAAQ,QAAQ,MAAM,EAAE,UAAU,SAAS,cAAc;;;;;CAMvE,QAAc;AACZ,OAAK,QAAQ,SAAS;;;;;;AAO1B,SAAgB,mCAA+D;AAC7E,QAAO,IAAI,4BAA4B;;;;;AAMzC,MAAa,yBAA6C,EACxD,SAAS,YAAY,IAGtB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { InMemoryTelemetryCollector, OperationMetricSample, TelemetryCollector, createInMemoryTelemetryCollector, noopTelemetryCollector, trackAgentStep } from "./adapter.js";
|
|
2
|
+
export { InMemoryTelemetryCollector, OperationMetricSample, TelemetryCollector, createInMemoryTelemetryCollector, noopTelemetryCollector, trackAgentStep };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { McpClientConfig, McpClientResult, createMcpToolsets, mcpServerToTools } from "./mcp-client.js";
|
|
2
|
+
import { buildToolHandlers, createToolHandler, specToolToAISDKTool, specToolsToAISDKTools } from "./tool-adapter.js";
|
|
3
|
+
import { createKnowledgeQueryTool } from "./knowledge-tool.js";
|
|
4
|
+
import { AgentMcpServerConfig, agentToMcpServer, createAgentMcpServer } from "./mcp-server.js";
|
|
5
|
+
export { AgentMcpServerConfig, McpClientConfig, McpClientResult, agentToMcpServer, buildToolHandlers, createAgentMcpServer, createKnowledgeQueryTool, createMcpToolsets, createToolHandler, mcpServerToTools, specToolToAISDKTool, specToolsToAISDKTools };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { buildToolHandlers, createToolHandler, specToolToAISDKTool, specToolsToAISDKTools } from "./tool-adapter.js";
|
|
2
|
+
import { createKnowledgeQueryTool } from "./knowledge-tool.js";
|
|
3
|
+
import { createMcpToolsets, mcpServerToTools } from "./mcp-client.js";
|
|
4
|
+
import { agentToMcpServer, createAgentMcpServer } from "./mcp-server.js";
|
|
5
|
+
|
|
6
|
+
export { agentToMcpServer, buildToolHandlers, createAgentMcpServer, createKnowledgeQueryTool, createMcpToolsets, createToolHandler, mcpServerToTools, specToolToAISDKTool, specToolsToAISDKTools };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { AgentKnowledgeRef } from "../spec/spec.js";
|
|
2
|
+
import { Tool } from "ai";
|
|
3
|
+
import { KnowledgeRetriever } from "@contractspec/lib.knowledge/retriever";
|
|
4
|
+
|
|
5
|
+
//#region src/tools/knowledge-tool.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Create a knowledge query tool for dynamic RAG.
|
|
9
|
+
*
|
|
10
|
+
* This tool allows the agent to query optional knowledge spaces
|
|
11
|
+
* at runtime. Required knowledge is injected statically via
|
|
12
|
+
* the knowledge injector.
|
|
13
|
+
*
|
|
14
|
+
* @param retriever - The knowledge retriever to use
|
|
15
|
+
* @param knowledgeRefs - Knowledge references from the agent spec
|
|
16
|
+
* @returns AI SDK CoreTool for knowledge queries
|
|
17
|
+
*/
|
|
18
|
+
declare function createKnowledgeQueryTool(retriever: KnowledgeRetriever, knowledgeRefs: AgentKnowledgeRef[]): Tool<any, any> | null;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { createKnowledgeQueryTool };
|
|
21
|
+
//# sourceMappingURL=knowledge-tool.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knowledge-tool.d.ts","names":[],"sources":["../../src/tools/knowledge-tool.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAgBA;;;;;;;;;iBAAgB,wBAAA,YACH,mCACI,sBAEd"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { tool } from "ai";
|
|
2
|
+
import * as z$1 from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/tools/knowledge-tool.ts
|
|
5
|
+
/**
|
|
6
|
+
* Create a knowledge query tool for dynamic RAG.
|
|
7
|
+
*
|
|
8
|
+
* This tool allows the agent to query optional knowledge spaces
|
|
9
|
+
* at runtime. Required knowledge is injected statically via
|
|
10
|
+
* the knowledge injector.
|
|
11
|
+
*
|
|
12
|
+
* @param retriever - The knowledge retriever to use
|
|
13
|
+
* @param knowledgeRefs - Knowledge references from the agent spec
|
|
14
|
+
* @returns AI SDK CoreTool for knowledge queries
|
|
15
|
+
*/
|
|
16
|
+
function createKnowledgeQueryTool(retriever, knowledgeRefs) {
|
|
17
|
+
const optionalSpaces = knowledgeRefs.filter((k) => !k.required).map((k) => k.key).filter((key) => retriever.supportsSpace(key));
|
|
18
|
+
if (optionalSpaces.length === 0) return null;
|
|
19
|
+
return tool({
|
|
20
|
+
description: `Query knowledge bases for relevant information. Use this tool when you need to look up specific information that may not be in your context.
|
|
21
|
+
|
|
22
|
+
Available knowledge spaces:
|
|
23
|
+
${knowledgeRefs.filter((k) => !k.required && retriever.supportsSpace(k.key)).map((k) => `- ${k.key}: ${k.instructions ?? "Knowledge space"}`).join("\n")}`,
|
|
24
|
+
inputSchema: z$1.object({
|
|
25
|
+
query: z$1.string().describe("The question or search query to find relevant information"),
|
|
26
|
+
spaceKey: z$1.enum(optionalSpaces).optional().describe("Specific knowledge space to query. If omitted, searches all available spaces."),
|
|
27
|
+
topK: z$1.number().optional().default(5).describe("Maximum number of results to return")
|
|
28
|
+
}),
|
|
29
|
+
execute: async ({ query, spaceKey, topK }) => {
|
|
30
|
+
const spacesToSearch = spaceKey ? [spaceKey] : optionalSpaces;
|
|
31
|
+
const allResults = [];
|
|
32
|
+
for (const space of spacesToSearch) try {
|
|
33
|
+
const results = await retriever.retrieve(query, {
|
|
34
|
+
spaceKey: space,
|
|
35
|
+
topK: topK ?? 5
|
|
36
|
+
});
|
|
37
|
+
for (const result of results) allResults.push({
|
|
38
|
+
space,
|
|
39
|
+
content: result.content,
|
|
40
|
+
score: result.score
|
|
41
|
+
});
|
|
42
|
+
} catch (error) {
|
|
43
|
+
console.warn(`Failed to query knowledge space ${space}:`, error);
|
|
44
|
+
}
|
|
45
|
+
if (allResults.length === 0) return "No relevant information found in the knowledge bases.";
|
|
46
|
+
allResults.sort((a, b) => b.score - a.score);
|
|
47
|
+
return allResults.slice(0, topK ?? 5).map((r, i) => `[Source ${i + 1} - ${r.space}] (relevance: ${(r.score * 100).toFixed(0)}%)\n${r.content}`).join("\n\n---\n\n");
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
//#endregion
|
|
53
|
+
export { createKnowledgeQueryTool };
|
|
54
|
+
//# sourceMappingURL=knowledge-tool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knowledge-tool.js","names":["z"],"sources":["../../src/tools/knowledge-tool.ts"],"sourcesContent":["import { tool, type Tool } from 'ai';\nimport * as z from 'zod';\nimport type { KnowledgeRetriever } from '@contractspec/lib.knowledge/retriever';\nimport type { AgentKnowledgeRef } from '../spec/spec';\n\n/**\n * Create a knowledge query tool for dynamic RAG.\n *\n * This tool allows the agent to query optional knowledge spaces\n * at runtime. Required knowledge is injected statically via\n * the knowledge injector.\n *\n * @param retriever - The knowledge retriever to use\n * @param knowledgeRefs - Knowledge references from the agent spec\n * @returns AI SDK CoreTool for knowledge queries\n */\nexport function createKnowledgeQueryTool(\n retriever: KnowledgeRetriever,\n knowledgeRefs: AgentKnowledgeRef[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Tool<any, any> | null {\n // Only include optional (non-required) knowledge spaces\n const optionalSpaces = knowledgeRefs\n .filter((k) => !k.required)\n .map((k) => k.key)\n .filter((key) => retriever.supportsSpace(key));\n\n if (optionalSpaces.length === 0) {\n return null;\n }\n\n // Build space descriptions for the tool\n const spaceDescriptions = knowledgeRefs\n .filter((k) => !k.required && retriever.supportsSpace(k.key))\n .map((k) => `- ${k.key}: ${k.instructions ?? 'Knowledge space'}`)\n .join('\\n');\n\n return tool({\n description: `Query knowledge bases for relevant information. Use this tool when you need to look up specific information that may not be in your context.\n\nAvailable knowledge spaces:\n${spaceDescriptions}`,\n // AI SDK v6 uses inputSchema instead of parameters\n inputSchema: z.object({\n query: z\n .string()\n .describe('The question or search query to find relevant information'),\n spaceKey: z\n .enum(optionalSpaces as [string, ...string[]])\n .optional()\n .describe(\n 'Specific knowledge space to query. If omitted, searches all available spaces.'\n ),\n topK: z\n .number()\n .optional()\n .default(5)\n .describe('Maximum number of results to return'),\n }),\n execute: async ({ query, spaceKey, topK }) => {\n const spacesToSearch = spaceKey ? [spaceKey] : optionalSpaces;\n const allResults: { space: string; content: string; score: number }[] =\n [];\n\n for (const space of spacesToSearch) {\n try {\n const results = await retriever.retrieve(query, {\n spaceKey: space,\n topK: topK ?? 5,\n });\n\n for (const result of results) {\n allResults.push({\n space,\n content: result.content,\n score: result.score,\n });\n }\n } catch (error) {\n // Log but don't fail on individual space errors\n console.warn(`Failed to query knowledge space ${space}:`, error);\n }\n }\n\n if (allResults.length === 0) {\n return 'No relevant information found in the knowledge bases.';\n }\n\n // Sort by score and format results\n allResults.sort((a, b) => b.score - a.score);\n const topResults = allResults.slice(0, topK ?? 5);\n\n return topResults\n .map(\n (r, i) =>\n `[Source ${i + 1} - ${r.space}] (relevance: ${(r.score * 100).toFixed(0)}%)\\n${r.content}`\n )\n .join('\\n\\n---\\n\\n');\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,yBACd,WACA,eAEuB;CAEvB,MAAM,iBAAiB,cACpB,QAAQ,MAAM,CAAC,EAAE,SAAS,CAC1B,KAAK,MAAM,EAAE,IAAI,CACjB,QAAQ,QAAQ,UAAU,cAAc,IAAI,CAAC;AAEhD,KAAI,eAAe,WAAW,EAC5B,QAAO;AAST,QAAO,KAAK;EACV,aAAa;;;EANW,cACvB,QAAQ,MAAM,CAAC,EAAE,YAAY,UAAU,cAAc,EAAE,IAAI,CAAC,CAC5D,KAAK,MAAM,KAAK,EAAE,IAAI,IAAI,EAAE,gBAAgB,oBAAoB,CAChE,KAAK,KAAK;EAQX,aAAaA,IAAE,OAAO;GACpB,OAAOA,IACJ,QAAQ,CACR,SAAS,4DAA4D;GACxE,UAAUA,IACP,KAAK,eAAwC,CAC7C,UAAU,CACV,SACC,gFACD;GACH,MAAMA,IACH,QAAQ,CACR,UAAU,CACV,QAAQ,EAAE,CACV,SAAS,sCAAsC;GACnD,CAAC;EACF,SAAS,OAAO,EAAE,OAAO,UAAU,WAAW;GAC5C,MAAM,iBAAiB,WAAW,CAAC,SAAS,GAAG;GAC/C,MAAM,aACJ,EAAE;AAEJ,QAAK,MAAM,SAAS,eAClB,KAAI;IACF,MAAM,UAAU,MAAM,UAAU,SAAS,OAAO;KAC9C,UAAU;KACV,MAAM,QAAQ;KACf,CAAC;AAEF,SAAK,MAAM,UAAU,QACnB,YAAW,KAAK;KACd;KACA,SAAS,OAAO;KAChB,OAAO,OAAO;KACf,CAAC;YAEG,OAAO;AAEd,YAAQ,KAAK,mCAAmC,MAAM,IAAI,MAAM;;AAIpE,OAAI,WAAW,WAAW,EACxB,QAAO;AAIT,cAAW,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM;AAG5C,UAFmB,WAAW,MAAM,GAAG,QAAQ,EAAE,CAG9C,KACE,GAAG,MACF,WAAW,IAAI,EAAE,KAAK,EAAE,MAAM,iBAAiB,EAAE,QAAQ,KAAK,QAAQ,EAAE,CAAC,MAAM,EAAE,UACpF,CACA,KAAK,cAAc;;EAEzB,CAAC"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Tool } from "ai";
|
|
2
|
+
|
|
3
|
+
//#region src/tools/mcp-client.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Configuration for connecting to an MCP server.
|
|
7
|
+
*/
|
|
8
|
+
interface McpClientConfig {
|
|
9
|
+
/** Display name for the MCP server */
|
|
10
|
+
name: string;
|
|
11
|
+
/** Command to spawn the MCP server process */
|
|
12
|
+
command: string;
|
|
13
|
+
/** Arguments to pass to the command */
|
|
14
|
+
args?: string[];
|
|
15
|
+
/** Environment variables for the process */
|
|
16
|
+
env?: Record<string, string>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Result of creating an MCP client with tools.
|
|
20
|
+
*/
|
|
21
|
+
interface McpClientResult {
|
|
22
|
+
/** AI SDK tools from the MCP server */
|
|
23
|
+
tools: Record<string, Tool<unknown, unknown>>;
|
|
24
|
+
/** Cleanup function to close the connection */
|
|
25
|
+
cleanup: () => Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Create AI SDK tools from an MCP server.
|
|
29
|
+
*
|
|
30
|
+
* This adapter allows ContractSpec agents to consume tools
|
|
31
|
+
* from external MCP servers (e.g., filesystem, database, etc.).
|
|
32
|
+
*
|
|
33
|
+
* @param config - MCP server configuration
|
|
34
|
+
* @returns Tools and cleanup function
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* const { tools, cleanup } = await mcpServerToTools({
|
|
39
|
+
* name: 'filesystem',
|
|
40
|
+
* command: 'npx',
|
|
41
|
+
* args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],
|
|
42
|
+
* });
|
|
43
|
+
*
|
|
44
|
+
* // Use tools in agent...
|
|
45
|
+
*
|
|
46
|
+
* await cleanup();
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
declare function mcpServerToTools(config: McpClientConfig): Promise<McpClientResult>;
|
|
50
|
+
/**
|
|
51
|
+
* Create multiple MCP tool sets from configurations.
|
|
52
|
+
*
|
|
53
|
+
* @param configs - Array of MCP server configurations
|
|
54
|
+
* @returns Combined tools and cleanup function
|
|
55
|
+
*/
|
|
56
|
+
declare function createMcpToolsets(configs: McpClientConfig[]): Promise<McpClientResult>;
|
|
57
|
+
//#endregion
|
|
58
|
+
export { McpClientConfig, McpClientResult, createMcpToolsets, mcpServerToTools };
|
|
59
|
+
//# sourceMappingURL=mcp-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-client.d.ts","names":[],"sources":["../../src/tools/mcp-client.ts"],"sourcesContent":[],"mappings":";;;;;;AAOA;AAciB,UAdA,eAAA,CAce;EAER;EAAf,IAAA,EAAA,MAAA;EAEQ;EAAO,OAAA,EAAA,MAAA;EAyBF;EACZ,IAAA,CAAA,EAAA,MAAA,EAAA;EACC;EAAR,GAAA,CAAA,EArCK,MAqCL,CAAA,MAAA,EAAA,MAAA,CAAA;;AAsBH;;;AAEG,UAvDc,eAAA,CAuDd;EAAO;SArDD,eAAe;;iBAEP;;;;;;;;;;;;;;;;;;;;;;;;iBAyBK,gBAAA,SACZ,kBACP,QAAQ;;;;;;;iBAsBW,iBAAA,UACX,oBACR,QAAQ"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { experimental_createMCPClient } from "@ai-sdk/mcp";
|
|
2
|
+
import { Experimental_StdioMCPTransport } from "@ai-sdk/mcp/mcp-stdio";
|
|
3
|
+
|
|
4
|
+
//#region src/tools/mcp-client.ts
|
|
5
|
+
/**
|
|
6
|
+
* Create AI SDK tools from an MCP server.
|
|
7
|
+
*
|
|
8
|
+
* This adapter allows ContractSpec agents to consume tools
|
|
9
|
+
* from external MCP servers (e.g., filesystem, database, etc.).
|
|
10
|
+
*
|
|
11
|
+
* @param config - MCP server configuration
|
|
12
|
+
* @returns Tools and cleanup function
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* const { tools, cleanup } = await mcpServerToTools({
|
|
17
|
+
* name: 'filesystem',
|
|
18
|
+
* command: 'npx',
|
|
19
|
+
* args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* // Use tools in agent...
|
|
23
|
+
*
|
|
24
|
+
* await cleanup();
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
async function mcpServerToTools(config) {
|
|
28
|
+
const client = await experimental_createMCPClient({ transport: new Experimental_StdioMCPTransport({
|
|
29
|
+
command: config.command,
|
|
30
|
+
args: config.args,
|
|
31
|
+
env: config.env
|
|
32
|
+
}) });
|
|
33
|
+
return {
|
|
34
|
+
tools: await client.tools(),
|
|
35
|
+
cleanup: () => client.close()
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Create multiple MCP tool sets from configurations.
|
|
40
|
+
*
|
|
41
|
+
* @param configs - Array of MCP server configurations
|
|
42
|
+
* @returns Combined tools and cleanup function
|
|
43
|
+
*/
|
|
44
|
+
async function createMcpToolsets(configs) {
|
|
45
|
+
const results = await Promise.all(configs.map(mcpServerToTools));
|
|
46
|
+
const combinedTools = {};
|
|
47
|
+
for (const result of results) Object.assign(combinedTools, result.tools);
|
|
48
|
+
return {
|
|
49
|
+
tools: combinedTools,
|
|
50
|
+
cleanup: async () => {
|
|
51
|
+
await Promise.all(results.map((r) => r.cleanup()));
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
//#endregion
|
|
57
|
+
export { createMcpToolsets, mcpServerToTools };
|
|
58
|
+
//# sourceMappingURL=mcp-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-client.js","names":["StdioClientTransport"],"sources":["../../src/tools/mcp-client.ts"],"sourcesContent":["import { experimental_createMCPClient } from '@ai-sdk/mcp';\nimport { Experimental_StdioMCPTransport as StdioClientTransport } from '@ai-sdk/mcp/mcp-stdio';\nimport type { Tool } from 'ai';\n\n/**\n * Configuration for connecting to an MCP server.\n */\nexport interface McpClientConfig {\n /** Display name for the MCP server */\n name: string;\n /** Command to spawn the MCP server process */\n command: string;\n /** Arguments to pass to the command */\n args?: string[];\n /** Environment variables for the process */\n env?: Record<string, string>;\n}\n\n/**\n * Result of creating an MCP client with tools.\n */\nexport interface McpClientResult {\n /** AI SDK tools from the MCP server */\n tools: Record<string, Tool<unknown, unknown>>;\n /** Cleanup function to close the connection */\n cleanup: () => Promise<void>;\n}\n\n/**\n * Create AI SDK tools from an MCP server.\n *\n * This adapter allows ContractSpec agents to consume tools\n * from external MCP servers (e.g., filesystem, database, etc.).\n *\n * @param config - MCP server configuration\n * @returns Tools and cleanup function\n *\n * @example\n * ```typescript\n * const { tools, cleanup } = await mcpServerToTools({\n * name: 'filesystem',\n * command: 'npx',\n * args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],\n * });\n *\n * // Use tools in agent...\n *\n * await cleanup();\n * ```\n */\nexport async function mcpServerToTools(\n config: McpClientConfig\n): Promise<McpClientResult> {\n const transport = new StdioClientTransport({\n command: config.command,\n args: config.args,\n env: config.env,\n });\n\n const client = await experimental_createMCPClient({ transport });\n const tools = await client.tools();\n\n return {\n tools: tools as Record<string, Tool<unknown, unknown>>,\n cleanup: () => client.close(),\n };\n}\n\n/**\n * Create multiple MCP tool sets from configurations.\n *\n * @param configs - Array of MCP server configurations\n * @returns Combined tools and cleanup function\n */\nexport async function createMcpToolsets(\n configs: McpClientConfig[]\n): Promise<McpClientResult> {\n const results = await Promise.all(configs.map(mcpServerToTools));\n\n const combinedTools: Record<string, Tool<unknown, unknown>> = {};\n for (const result of results) {\n Object.assign(combinedTools, result.tools);\n }\n\n return {\n tools: combinedTools,\n cleanup: async () => {\n await Promise.all(results.map((r) => r.cleanup()));\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,eAAsB,iBACpB,QAC0B;CAO1B,MAAM,SAAS,MAAM,6BAA6B,EAAE,WANlC,IAAIA,+BAAqB;EACzC,SAAS,OAAO;EAChB,MAAM,OAAO;EACb,KAAK,OAAO;EACb,CAAC,EAE6D,CAAC;AAGhE,QAAO;EACL,OAHY,MAAM,OAAO,OAAO;EAIhC,eAAe,OAAO,OAAO;EAC9B;;;;;;;;AASH,eAAsB,kBACpB,SAC0B;CAC1B,MAAM,UAAU,MAAM,QAAQ,IAAI,QAAQ,IAAI,iBAAiB,CAAC;CAEhE,MAAM,gBAAwD,EAAE;AAChE,MAAK,MAAM,UAAU,QACnB,QAAO,OAAO,eAAe,OAAO,MAAM;AAG5C,QAAO;EACL,OAAO;EACP,SAAS,YAAY;AACnB,SAAM,QAAQ,IAAI,QAAQ,KAAK,MAAM,EAAE,SAAS,CAAC,CAAC;;EAErD"}
|