@chainai/core 1.0.4 → 1.1.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.
@@ -1,47 +0,0 @@
1
- /**
2
- * IC Service - Manages connections to Internet Computer canisters
3
- */
4
- import type { ValidationResult, ResponseCustomization } from '../types';
5
- export interface ICServiceConfig {
6
- host: string;
7
- nlpEdgeCanisterId: string;
8
- developerManagerCanisterId: string;
9
- }
10
- export declare class ICService {
11
- private agent;
12
- private nlpEdgeActor;
13
- private developerManagerActor;
14
- private config;
15
- constructor(config: ICServiceConfig);
16
- /**
17
- * Validate an API key with the developer_manager canister
18
- */
19
- validateApiKey(apiKey: string): Promise<ValidationResult>;
20
- /**
21
- * Get response customization for an API key
22
- */
23
- getResponseCustomization(apiKey: string): Promise<ResponseCustomization | null>;
24
- /**
25
- * Set response customization for an API key
26
- */
27
- setResponseCustomization(apiKey: string, customization: Partial<ResponseCustomization>): Promise<{
28
- ok: boolean;
29
- message?: string;
30
- error?: string;
31
- }>;
32
- /**
33
- * Delete response customization (reset to defaults)
34
- */
35
- deleteResponseCustomization(apiKey: string): Promise<{
36
- ok: boolean;
37
- message?: string;
38
- }>;
39
- /**
40
- * Get the NLP Edge actor for direct canister calls
41
- */
42
- getNLPEdgeActor(): any;
43
- /**
44
- * Get the Developer Manager actor for direct canister calls
45
- */
46
- getDeveloperManagerActor(): any;
47
- }
@@ -1,165 +0,0 @@
1
- "use strict";
2
- /**
3
- * IC Service - Manages connections to Internet Computer canisters
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ICService = void 0;
7
- const agent_1 = require("@dfinity/agent");
8
- const principal_1 = require("@dfinity/principal");
9
- // IDL factory for NLP Edge canister
10
- const createNLPEdgeIdl = (idlFactory) => {
11
- const { IDL } = idlFactory;
12
- // AIResponse type matches the canister's AIResponse record
13
- const AIResponseType = IDL.Record({
14
- 'intent': IDL.Text,
15
- 'kind': IDL.Text,
16
- 'response': IDL.Text,
17
- 'toolData': IDL.Text,
18
- 'confidence': IDL.Nat,
19
- 'conversationId': IDL.Text,
20
- });
21
- // ChatResponse is Result<AIResponse, Text> = variant { ok: AIResponse; err: Text }
22
- const ChatResponseType = IDL.Variant({
23
- 'ok': AIResponseType,
24
- 'err': IDL.Text,
25
- });
26
- return IDL.Service({
27
- 'chat': IDL.Func([IDL.Record({
28
- 'message': IDL.Text,
29
- 'conversationId': IDL.Text,
30
- 'language': IDL.Opt(IDL.Text),
31
- 'userContext': IDL.Opt(IDL.Text),
32
- 'apiKey': IDL.Opt(IDL.Text),
33
- })], [ChatResponseType], []),
34
- 'health': IDL.Func([], [IDL.Text], ['query']),
35
- });
36
- };
37
- // IDL factory for Developer Manager canister
38
- const createDeveloperManagerIdl = (idlFactory) => {
39
- const { IDL } = idlFactory;
40
- return IDL.Service({
41
- 'validateApiKey': IDL.Func([IDL.Text], [IDL.Text], ['query']),
42
- 'getResponseCustomization': IDL.Func([IDL.Text], [IDL.Text], ['query']),
43
- 'setResponseCustomization': IDL.Func([IDL.Text, IDL.Text, IDL.Text, IDL.Text, IDL.Text, IDL.Text, IDL.Text], [IDL.Text], []),
44
- 'deleteResponseCustomization': IDL.Func([IDL.Text], [IDL.Text], []),
45
- 'recordUsage': IDL.Func([IDL.Text], [], []),
46
- });
47
- };
48
- class ICService {
49
- constructor(config) {
50
- this.config = config;
51
- this.agent = new agent_1.HttpAgent({ host: config.host });
52
- // For local development, fetch root key
53
- if (config.host.includes('localhost') || config.host.includes('127.0.0.1')) {
54
- this.agent.fetchRootKey().catch(console.warn);
55
- }
56
- // Create actors (using simplified IDL for now)
57
- this.nlpEdgeActor = agent_1.Actor.createActor(createNLPEdgeIdl, {
58
- agent: this.agent,
59
- canisterId: principal_1.Principal.fromText(config.nlpEdgeCanisterId),
60
- });
61
- this.developerManagerActor = agent_1.Actor.createActor(createDeveloperManagerIdl, {
62
- agent: this.agent,
63
- canisterId: principal_1.Principal.fromText(config.developerManagerCanisterId),
64
- });
65
- }
66
- /**
67
- * Validate an API key with the developer_manager canister
68
- */
69
- async validateApiKey(apiKey) {
70
- try {
71
- const result = await this.developerManagerActor.validateApiKey(apiKey);
72
- const parsed = JSON.parse(result);
73
- if (parsed.ok) {
74
- return {
75
- ok: true,
76
- developerId: parsed.developerId,
77
- tier: parsed.tier,
78
- rateLimit: parsed.rateLimit,
79
- hasCustomization: parsed.hasCustomization || false,
80
- };
81
- }
82
- else {
83
- return {
84
- ok: false,
85
- error: parsed.error,
86
- };
87
- }
88
- }
89
- catch (error) {
90
- return {
91
- ok: false,
92
- error: error instanceof Error ? error.message : 'Unknown error',
93
- };
94
- }
95
- }
96
- /**
97
- * Get response customization for an API key
98
- */
99
- async getResponseCustomization(apiKey) {
100
- try {
101
- const result = await this.developerManagerActor.getResponseCustomization(apiKey);
102
- const parsed = JSON.parse(result);
103
- if (parsed.ok && parsed.customization) {
104
- return {
105
- apiKey,
106
- ...parsed.customization,
107
- };
108
- }
109
- return null;
110
- }
111
- catch (error) {
112
- console.error('Error fetching customization:', error);
113
- return null;
114
- }
115
- }
116
- /**
117
- * Set response customization for an API key
118
- */
119
- async setResponseCustomization(apiKey, customization) {
120
- try {
121
- const styleText = customization.style || 'professional';
122
- const lengthText = customization.length || 'medium';
123
- const responseFormatText = customization.responseFormat || 'text';
124
- const actionTemplatesJson = JSON.stringify(customization.actionTemplates || {});
125
- const actionSchemasJson = JSON.stringify(customization.actionSchemas || {});
126
- const dataFormatJson = JSON.stringify(customization.dataFormat || {});
127
- const result = await this.developerManagerActor.setResponseCustomization(apiKey, styleText, lengthText, responseFormatText, actionTemplatesJson, actionSchemasJson, dataFormatJson);
128
- return JSON.parse(result);
129
- }
130
- catch (error) {
131
- return {
132
- ok: false,
133
- error: error instanceof Error ? error.message : 'Unknown error',
134
- };
135
- }
136
- }
137
- /**
138
- * Delete response customization (reset to defaults)
139
- */
140
- async deleteResponseCustomization(apiKey) {
141
- try {
142
- const result = await this.developerManagerActor.deleteResponseCustomization(apiKey);
143
- return JSON.parse(result);
144
- }
145
- catch (error) {
146
- return {
147
- ok: false,
148
- message: error instanceof Error ? error.message : 'Unknown error',
149
- };
150
- }
151
- }
152
- /**
153
- * Get the NLP Edge actor for direct canister calls
154
- */
155
- getNLPEdgeActor() {
156
- return this.nlpEdgeActor;
157
- }
158
- /**
159
- * Get the Developer Manager actor for direct canister calls
160
- */
161
- getDeveloperManagerActor() {
162
- return this.developerManagerActor;
163
- }
164
- }
165
- exports.ICService = ICService;
@@ -1,21 +0,0 @@
1
- /**
2
- * NLP Service - Handles chat requests and streaming responses
3
- */
4
- import type { ICService } from './ic-service';
5
- import type { ChatRequest, ChatResponse, StreamCallbacks } from '../types';
6
- export declare class NLPService {
7
- private icService;
8
- constructor(icService: ICService);
9
- /**
10
- * Send a chat message and get AI response
11
- */
12
- chat(request: ChatRequest): Promise<ChatResponse>;
13
- /**
14
- * Stream chat response word-by-word for better UX
15
- */
16
- streamChat(request: ChatRequest, callbacks: StreamCallbacks): Promise<void>;
17
- /**
18
- * Check canister health
19
- */
20
- health(): Promise<string>;
21
- }
@@ -1,104 +0,0 @@
1
- "use strict";
2
- /**
3
- * NLP Service - Handles chat requests and streaming responses
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.NLPService = void 0;
7
- class NLPService {
8
- constructor(icService) {
9
- this.icService = icService;
10
- }
11
- /**
12
- * Send a chat message and get AI response
13
- */
14
- async chat(request) {
15
- const actor = this.icService.getNLPEdgeActor();
16
- // Build user context with wallet information
17
- const userContextData = {};
18
- // Include legacy userContext if provided
19
- if (request.userContext) {
20
- Object.assign(userContextData, request.userContext);
21
- }
22
- // Include wallet context (this is the key addition for wallet addresses)
23
- if (request.walletContext) {
24
- userContextData.wallets = request.walletContext.wallets;
25
- if (request.walletContext.activeChain) {
26
- userContextData.activeChain = request.walletContext.activeChain;
27
- }
28
- if (request.walletContext.activeAddress) {
29
- userContextData.activeAddress = request.walletContext.activeAddress;
30
- }
31
- }
32
- const hasContext = Object.keys(userContextData).length > 0;
33
- const chatRequest = {
34
- message: request.text,
35
- conversationId: request.conversationId || '',
36
- language: request.language ? [request.language] : [],
37
- userContext: hasContext ? [JSON.stringify(userContextData)] : [],
38
- apiKey: request.apiKey ? [request.apiKey] : [],
39
- };
40
- try {
41
- const result = await actor.chat(chatRequest);
42
- if (result.ok) {
43
- return {
44
- ok: true,
45
- data: {
46
- response: result.ok.response,
47
- intent: result.ok.intent,
48
- kind: result.ok.kind,
49
- toolData: result.ok.toolData,
50
- confidence: result.ok.confidence,
51
- conversationId: result.ok.conversationId,
52
- },
53
- };
54
- }
55
- else {
56
- return {
57
- ok: false,
58
- error: result.err,
59
- };
60
- }
61
- }
62
- catch (error) {
63
- return {
64
- ok: false,
65
- error: error instanceof Error ? error.message : 'Unknown error',
66
- };
67
- }
68
- }
69
- /**
70
- * Stream chat response word-by-word for better UX
71
- */
72
- async streamChat(request, callbacks) {
73
- try {
74
- // Send start event
75
- callbacks.onChunk?.('');
76
- const result = await this.chat(request);
77
- if (result.ok && result.data) {
78
- const response = result.data.response;
79
- // Stream response word-by-word with 15ms delay
80
- const words = response.split(' ');
81
- for (let i = 0; i < words.length; i++) {
82
- const chunk = words[i] + (i < words.length - 1 ? ' ' : '');
83
- callbacks.onChunk?.(chunk);
84
- await new Promise(resolve => setTimeout(resolve, 15));
85
- }
86
- callbacks.onDone?.(result.data);
87
- }
88
- else {
89
- callbacks.onError?.(result.error || 'An error occurred');
90
- }
91
- }
92
- catch (error) {
93
- callbacks.onError?.(error instanceof Error ? error.message : 'Unknown error');
94
- }
95
- }
96
- /**
97
- * Check canister health
98
- */
99
- async health() {
100
- const actor = this.icService.getNLPEdgeActor();
101
- return await actor.health();
102
- }
103
- }
104
- exports.NLPService = NLPService;
@@ -1,66 +0,0 @@
1
- /**
2
- * Chat request and response types for Chain AI
3
- */
4
- /**
5
- * Wallet address for a specific chain
6
- */
7
- export interface WalletAddress {
8
- chain: 'ethereum' | 'bitcoin' | 'solana' | 'icp' | string;
9
- address: string;
10
- /** Optional label (e.g., "MetaMask", "Phantom") */
11
- label?: string;
12
- /** Whether this is the primary wallet for the chain */
13
- isPrimary?: boolean;
14
- }
15
- /**
16
- * Wallet context included with each request
17
- * Contains all connected wallet addresses so the AI can access them
18
- * for queries like balance, transaction history, etc.
19
- */
20
- export interface WalletContext {
21
- /** All connected wallet addresses */
22
- wallets: WalletAddress[];
23
- /** Currently active/selected chain (optional) */
24
- activeChain?: string;
25
- /** Currently active wallet address (optional) */
26
- activeAddress?: string;
27
- }
28
- /**
29
- * Function type for dynamically fetching wallet addresses
30
- * Useful when wallet state may change between requests
31
- */
32
- export type WalletProvider = () => WalletContext | Promise<WalletContext>;
33
- export interface ChatRequest {
34
- text: string;
35
- conversationId?: string;
36
- /** @deprecated Use walletContext instead for wallet data */
37
- userContext?: any;
38
- /** Wallet addresses to include with the request */
39
- walletContext?: WalletContext;
40
- language?: string;
41
- apiKey?: string;
42
- }
43
- export interface AIResponse {
44
- response: string;
45
- intent: string;
46
- kind: string;
47
- toolData: string;
48
- confidence: number;
49
- conversationId: string;
50
- }
51
- export interface ChatResponse {
52
- ok: boolean;
53
- data?: AIResponse;
54
- error?: string;
55
- }
56
- export interface Message {
57
- id: string;
58
- role: 'user' | 'assistant';
59
- content: string;
60
- timestamp: number;
61
- }
62
- export interface StreamCallbacks {
63
- onChunk?: (chunk: string) => void;
64
- onDone?: (data: AIResponse) => void;
65
- onError?: (error: string) => void;
66
- }
@@ -1,5 +0,0 @@
1
- "use strict";
2
- /**
3
- * Chat request and response types for Chain AI
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,55 +0,0 @@
1
- /**
2
- * Response customization types for Chain AI
3
- * Allows per-API-key customization of AI responses
4
- */
5
- export type ResponseStyle = 'professional' | 'casual' | 'technical' | 'friendly' | 'concise';
6
- export type ResponseLength = 'short' | 'medium' | 'detailed';
7
- export type ResponseFormat = 'text' | 'json' | 'hybrid';
8
- export type DateFormat = 'relative' | 'absolute' | 'both';
9
- export type AddressFormat = 'full' | 'truncated' | 'ens';
10
- export type NumberFormat = 'us' | 'eu' | 'scientific';
11
- export interface ActionSchema {
12
- required: string[];
13
- optional?: string[];
14
- inferRules?: {
15
- [field: string]: string;
16
- };
17
- }
18
- export interface ActionSchemas {
19
- send?: ActionSchema;
20
- swap?: ActionSchema;
21
- approve?: ActionSchema;
22
- transfer?: ActionSchema;
23
- stake?: ActionSchema;
24
- [key: string]: ActionSchema | undefined;
25
- }
26
- export interface ActionTemplates {
27
- send?: string;
28
- swap?: string;
29
- approve?: string;
30
- price?: string;
31
- balance?: string;
32
- fees?: string;
33
- transaction_status?: string;
34
- transaction_history?: string;
35
- }
36
- export interface DataFormatOptions {
37
- priceDecimals: number;
38
- showUsdEquivalent: boolean;
39
- dateFormat: DateFormat;
40
- addressDisplay: AddressFormat;
41
- numberFormat: NumberFormat;
42
- }
43
- export interface ResponseCustomization {
44
- apiKey: string;
45
- style: ResponseStyle;
46
- length: ResponseLength;
47
- responseFormat: ResponseFormat;
48
- actionTemplates: ActionTemplates;
49
- actionSchemas?: ActionSchemas;
50
- dataFormat: DataFormatOptions;
51
- createdAt: number;
52
- updatedAt: number;
53
- }
54
- export declare const DEFAULT_ACTION_SCHEMAS: ActionSchemas;
55
- export declare const DEFAULT_CUSTOMIZATION: Omit<ResponseCustomization, 'apiKey' | 'createdAt' | 'updatedAt'>;
@@ -1,35 +0,0 @@
1
- "use strict";
2
- /**
3
- * Response customization types for Chain AI
4
- * Allows per-API-key customization of AI responses
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.DEFAULT_CUSTOMIZATION = exports.DEFAULT_ACTION_SCHEMAS = void 0;
8
- // Example action schema for common wallet operations
9
- exports.DEFAULT_ACTION_SCHEMAS = {
10
- send: {
11
- required: ['amount', 'currency', 'address'],
12
- optional: ['fee', 'memo'],
13
- inferRules: {
14
- chain: 'Infer from address format (e.g., bc1q... = Bitcoin, 0x... = Ethereum)',
15
- },
16
- },
17
- swap: {
18
- required: ['fromCurrency', 'toCurrency', 'amount'],
19
- optional: ['slippage', 'deadline'],
20
- },
21
- };
22
- exports.DEFAULT_CUSTOMIZATION = {
23
- style: 'professional',
24
- length: 'medium',
25
- responseFormat: 'text',
26
- actionTemplates: {},
27
- actionSchemas: undefined, // Wallet providers can define their own
28
- dataFormat: {
29
- priceDecimals: 2,
30
- showUsdEquivalent: true,
31
- dateFormat: 'relative',
32
- addressDisplay: 'truncated',
33
- numberFormat: 'us',
34
- },
35
- };
@@ -1,39 +0,0 @@
1
- /**
2
- * Main types export for @chainai/core
3
- */
4
- export type { ResponseCustomization, ResponseStyle, ResponseLength, ActionTemplates, DataFormatOptions, DateFormat, AddressFormat, NumberFormat, } from './customization';
5
- export { DEFAULT_CUSTOMIZATION } from './customization';
6
- export type { ChatRequest, ChatResponse, AIResponse, Message, StreamCallbacks, WalletAddress, WalletContext, WalletProvider, } from './chat';
7
- export interface ChainAIConfig {
8
- apiKey: string;
9
- host?: string;
10
- nlpEdgeCanisterId?: string;
11
- developerManagerCanisterId?: string;
12
- /**
13
- * Wallet provider function that returns connected wallet addresses.
14
- * Called automatically before each request to include current wallet state.
15
- *
16
- * @example
17
- * ```ts
18
- * const config = {
19
- * apiKey: 'your-api-key',
20
- * walletProvider: () => ({
21
- * wallets: [
22
- * { chain: 'ethereum', address: '0x...', label: 'MetaMask' },
23
- * { chain: 'solana', address: 'ABC...', label: 'Phantom' },
24
- * ],
25
- * activeChain: 'ethereum',
26
- * }),
27
- * };
28
- * ```
29
- */
30
- walletProvider?: import('./chat').WalletProvider;
31
- }
32
- export interface ValidationResult {
33
- ok: boolean;
34
- developerId?: string;
35
- tier?: string;
36
- rateLimit?: number;
37
- hasCustomization?: boolean;
38
- error?: string;
39
- }
@@ -1,8 +0,0 @@
1
- "use strict";
2
- /**
3
- * Main types export for @chainai/core
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_CUSTOMIZATION = void 0;
7
- var customization_1 = require("./customization");
8
- Object.defineProperty(exports, "DEFAULT_CUSTOMIZATION", { enumerable: true, get: function () { return customization_1.DEFAULT_CUSTOMIZATION; } });