@trikhub/gateway 0.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.
- package/LICENSE +21 -0
- package/dist/gateway.d.ts +97 -0
- package/dist/gateway.d.ts.map +1 -0
- package/dist/gateway.js +421 -0
- package/dist/gateway.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/langchain/adapter.d.ts +20 -0
- package/dist/langchain/adapter.d.ts.map +1 -0
- package/dist/langchain/adapter.js +102 -0
- package/dist/langchain/adapter.js.map +1 -0
- package/dist/langchain/index.d.ts +3 -0
- package/dist/langchain/index.d.ts.map +1 -0
- package/dist/langchain/index.js +3 -0
- package/dist/langchain/index.js.map +1 -0
- package/dist/langchain/schema-converter.d.ts +4 -0
- package/dist/langchain/schema-converter.d.ts.map +1 -0
- package/dist/langchain/schema-converter.js +74 -0
- package/dist/langchain/schema-converter.js.map +1 -0
- package/dist/session-storage.d.ts +45 -0
- package/dist/session-storage.d.ts.map +1 -0
- package/dist/session-storage.js +84 -0
- package/dist/session-storage.js.map +1 -0
- package/package.json +75 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Muffles
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { type TrikManifest, type GatewayResult, type ClarificationQuestion, type ClarificationAnswer, type ResponseTemplate, type ResponseMode, type PassthroughContent, type PassthroughDeliveryReceipt } from '@trikhub/manifest';
|
|
2
|
+
import { type SessionStorage } from './session-storage.js';
|
|
3
|
+
export interface TrikGatewayConfig {
|
|
4
|
+
allowedTriks?: string[];
|
|
5
|
+
onClarificationNeeded?: (trikId: string, questions: ClarificationQuestion[]) => Promise<ClarificationAnswer[]>;
|
|
6
|
+
sessionStorage?: SessionStorage;
|
|
7
|
+
/**
|
|
8
|
+
* Directory containing installed triks (triks) for auto-discovery.
|
|
9
|
+
* Supports scoped directory structure: triksDirectory/@scope/trik-name/
|
|
10
|
+
* Use '~' for home directory (e.g., '~/.trikhub/triks')
|
|
11
|
+
*/
|
|
12
|
+
triksDirectory?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ExecuteTrikOptions {
|
|
15
|
+
sessionId?: string;
|
|
16
|
+
}
|
|
17
|
+
export type GatewayResultWithSession<TAgent = unknown> = GatewayResult<TAgent> & {
|
|
18
|
+
sessionId?: string;
|
|
19
|
+
};
|
|
20
|
+
export interface ToolDefinition {
|
|
21
|
+
name: string;
|
|
22
|
+
description: string;
|
|
23
|
+
inputSchema: import('@trikhub/manifest').JSONSchema;
|
|
24
|
+
responseMode: ResponseMode;
|
|
25
|
+
isGatewayTool?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface TrikInfo {
|
|
28
|
+
id: string;
|
|
29
|
+
name: string;
|
|
30
|
+
description: string;
|
|
31
|
+
tools: ToolDefinition[];
|
|
32
|
+
sessionEnabled: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface GetToolDefinitionsOptions {
|
|
35
|
+
includeReadContent?: boolean;
|
|
36
|
+
}
|
|
37
|
+
export declare class TrikGateway {
|
|
38
|
+
private validator;
|
|
39
|
+
private config;
|
|
40
|
+
private sessionStorage;
|
|
41
|
+
private triks;
|
|
42
|
+
private contentReferences;
|
|
43
|
+
private static CONTENT_REF_TTL_MS;
|
|
44
|
+
constructor(config?: TrikGatewayConfig);
|
|
45
|
+
loadTrik(trikPath: string): Promise<TrikManifest>;
|
|
46
|
+
/**
|
|
47
|
+
* Load all triks from a directory.
|
|
48
|
+
* Supports scoped directory structure: directory/@scope/trik-name/
|
|
49
|
+
*
|
|
50
|
+
* @param directory - Path to the directory containing triks.
|
|
51
|
+
* Use '~' prefix for home directory (e.g., '~/.trikhub/triks')
|
|
52
|
+
* @returns Array of successfully loaded manifests
|
|
53
|
+
*/
|
|
54
|
+
loadTriksFromDirectory(directory: string): Promise<TrikManifest[]>;
|
|
55
|
+
/**
|
|
56
|
+
* Load triks from the configured triksDirectory (if set).
|
|
57
|
+
* This is a convenience method for loading the default TrikHub directory.
|
|
58
|
+
*/
|
|
59
|
+
loadInstalledTriks(): Promise<TrikManifest[]>;
|
|
60
|
+
getManifest(trikId: string): TrikManifest | undefined;
|
|
61
|
+
getLoadedTriks(): string[];
|
|
62
|
+
isLoaded(trikId: string): boolean;
|
|
63
|
+
getAvailableTriks(): TrikInfo[];
|
|
64
|
+
getToolDefinitions(_options?: GetToolDefinitionsOptions): ToolDefinition[];
|
|
65
|
+
private actionToToolDefinition;
|
|
66
|
+
execute<TAgent = unknown>(trikId: string, actionName: string, input: unknown, options?: ExecuteTrikOptions): Promise<GatewayResultWithSession<TAgent>>;
|
|
67
|
+
private executeWithTimeout;
|
|
68
|
+
private processResult;
|
|
69
|
+
/**
|
|
70
|
+
* Add sessionId to result if session exists
|
|
71
|
+
*/
|
|
72
|
+
private addSessionId;
|
|
73
|
+
/**
|
|
74
|
+
* Store passthrough content and return a reference
|
|
75
|
+
*/
|
|
76
|
+
private storePassthroughContent;
|
|
77
|
+
/**
|
|
78
|
+
* Clean up expired content references
|
|
79
|
+
*/
|
|
80
|
+
private cleanupExpiredContentReferences;
|
|
81
|
+
/**
|
|
82
|
+
* Deliver passthrough content to the user.
|
|
83
|
+
* One-time delivery - the reference is deleted after delivery.
|
|
84
|
+
*/
|
|
85
|
+
deliverContent(ref: string): {
|
|
86
|
+
content: PassthroughContent;
|
|
87
|
+
receipt: PassthroughDeliveryReceipt;
|
|
88
|
+
} | null;
|
|
89
|
+
hasContentRef(ref: string): boolean;
|
|
90
|
+
getContentRefInfo(ref: string): {
|
|
91
|
+
contentType: string;
|
|
92
|
+
metadata?: Record<string, unknown>;
|
|
93
|
+
} | null;
|
|
94
|
+
resolveTemplate(template: ResponseTemplate, agentData: Record<string, unknown>): string;
|
|
95
|
+
getActionTemplates(trikId: string, actionName: string): Record<string, ResponseTemplate> | undefined;
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=gateway.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gateway.d.ts","sourceRoot":"","sources":["../src/gateway.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,aAAa,EAGlB,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EAExB,KAAK,gBAAgB,EACrB,KAAK,YAAY,EAEjB,KAAK,kBAAkB,EACvB,KAAK,0BAA0B,EAKhC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,KAAK,cAAc,EAA0B,MAAM,sBAAsB,CAAC;AAwBnF,MAA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AM,EAAE,OAAO,CAAC,GAAG,MAAM;IAYvF,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAAG,SAAS;CASrG"}
|
package/dist/gateway.js
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { readFile, readdir, stat } from 'node:fs/promises';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { validateManifest, SchemaValidator, } from '@trikhub/manifest';
|
|
7
|
+
import { InMemorySessionStorage } from './session-storage.js';
|
|
8
|
+
export class TrikGateway {
|
|
9
|
+
validator = new SchemaValidator();
|
|
10
|
+
config;
|
|
11
|
+
sessionStorage;
|
|
12
|
+
// Loaded triks (by trik ID)
|
|
13
|
+
triks = new Map();
|
|
14
|
+
contentReferences = new Map();
|
|
15
|
+
static CONTENT_REF_TTL_MS = 10 * 60 * 1000;
|
|
16
|
+
constructor(config = {}) {
|
|
17
|
+
this.config = config;
|
|
18
|
+
this.sessionStorage = config.sessionStorage ?? new InMemorySessionStorage();
|
|
19
|
+
}
|
|
20
|
+
async loadTrik(trikPath) {
|
|
21
|
+
const manifestPath = join(trikPath, 'manifest.json');
|
|
22
|
+
const manifestContent = await readFile(manifestPath, 'utf-8');
|
|
23
|
+
const manifestData = JSON.parse(manifestContent);
|
|
24
|
+
const validation = validateManifest(manifestData);
|
|
25
|
+
if (!validation.valid) {
|
|
26
|
+
throw new Error(`Invalid manifest at ${manifestPath}: ${validation.errors?.join(', ')}`);
|
|
27
|
+
}
|
|
28
|
+
const manifest = manifestData;
|
|
29
|
+
if (this.config.allowedTriks && !this.config.allowedTriks.includes(manifest.id)) {
|
|
30
|
+
throw new Error(`Trik "${manifest.id}" is not in the allowlist`);
|
|
31
|
+
}
|
|
32
|
+
const modulePath = join(trikPath, manifest.entry.module);
|
|
33
|
+
const moduleUrl = pathToFileURL(modulePath).href;
|
|
34
|
+
const module = await import(moduleUrl);
|
|
35
|
+
const graph = module[manifest.entry.export];
|
|
36
|
+
if (!graph || typeof graph.invoke !== 'function') {
|
|
37
|
+
throw new Error(`Invalid graph at ${modulePath}: export "${manifest.entry.export}" must have an invoke function`);
|
|
38
|
+
}
|
|
39
|
+
this.triks.set(manifest.id, { manifest, graph, path: trikPath });
|
|
40
|
+
return manifest;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Load all triks from a directory.
|
|
44
|
+
* Supports scoped directory structure: directory/@scope/trik-name/
|
|
45
|
+
*
|
|
46
|
+
* @param directory - Path to the directory containing triks.
|
|
47
|
+
* Use '~' prefix for home directory (e.g., '~/.trikhub/triks')
|
|
48
|
+
* @returns Array of successfully loaded manifests
|
|
49
|
+
*/
|
|
50
|
+
async loadTriksFromDirectory(directory) {
|
|
51
|
+
// Resolve ~ to home directory
|
|
52
|
+
const resolvedDir = directory.startsWith('~')
|
|
53
|
+
? join(homedir(), directory.slice(1))
|
|
54
|
+
: resolve(directory);
|
|
55
|
+
const manifests = [];
|
|
56
|
+
const errors = [];
|
|
57
|
+
try {
|
|
58
|
+
const entries = await readdir(resolvedDir, { withFileTypes: true });
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
if (!entry.isDirectory())
|
|
61
|
+
continue;
|
|
62
|
+
const entryPath = join(resolvedDir, entry.name);
|
|
63
|
+
// Check if this is a scoped directory (starts with @)
|
|
64
|
+
if (entry.name.startsWith('@')) {
|
|
65
|
+
// Scoped directory: @scope/trik-name structure
|
|
66
|
+
const scopedEntries = await readdir(entryPath, { withFileTypes: true });
|
|
67
|
+
for (const scopedEntry of scopedEntries) {
|
|
68
|
+
if (!scopedEntry.isDirectory())
|
|
69
|
+
continue;
|
|
70
|
+
const trikPath = join(entryPath, scopedEntry.name);
|
|
71
|
+
const manifestPath = join(trikPath, 'manifest.json');
|
|
72
|
+
try {
|
|
73
|
+
const manifestStat = await stat(manifestPath);
|
|
74
|
+
if (manifestStat.isFile()) {
|
|
75
|
+
const manifest = await this.loadTrik(trikPath);
|
|
76
|
+
manifests.push(manifest);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
// Trik failed to load, record error but continue
|
|
81
|
+
errors.push({
|
|
82
|
+
path: trikPath,
|
|
83
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
// Non-scoped directory: direct trik-name structure
|
|
90
|
+
const trikPath = entryPath;
|
|
91
|
+
const manifestPath = join(trikPath, 'manifest.json');
|
|
92
|
+
try {
|
|
93
|
+
const manifestStat = await stat(manifestPath);
|
|
94
|
+
if (manifestStat.isFile()) {
|
|
95
|
+
const manifest = await this.loadTrik(trikPath);
|
|
96
|
+
manifests.push(manifest);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
// Trik failed to load, record error but continue
|
|
101
|
+
errors.push({
|
|
102
|
+
path: trikPath,
|
|
103
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
// Directory doesn't exist or isn't readable - not necessarily an error
|
|
111
|
+
// (e.g., user hasn't installed any triks yet)
|
|
112
|
+
if (error.code !== 'ENOENT') {
|
|
113
|
+
throw new Error(`Failed to read triks directory "${resolvedDir}": ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
// Log errors for debugging (triks that failed to load)
|
|
117
|
+
if (errors.length > 0) {
|
|
118
|
+
console.warn(`[TrikGateway] Failed to load ${errors.length} trik(s):`);
|
|
119
|
+
for (const { path, error } of errors) {
|
|
120
|
+
console.warn(` - ${path}: ${error}`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return manifests;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Load triks from the configured triksDirectory (if set).
|
|
127
|
+
* This is a convenience method for loading the default TrikHub directory.
|
|
128
|
+
*/
|
|
129
|
+
async loadInstalledTriks() {
|
|
130
|
+
if (!this.config.triksDirectory) {
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
return this.loadTriksFromDirectory(this.config.triksDirectory);
|
|
134
|
+
}
|
|
135
|
+
getManifest(trikId) {
|
|
136
|
+
return this.triks.get(trikId)?.manifest;
|
|
137
|
+
}
|
|
138
|
+
getLoadedTriks() {
|
|
139
|
+
return Array.from(this.triks.keys());
|
|
140
|
+
}
|
|
141
|
+
isLoaded(trikId) {
|
|
142
|
+
return this.triks.has(trikId);
|
|
143
|
+
}
|
|
144
|
+
getAvailableTriks() {
|
|
145
|
+
return Array.from(this.triks.values()).map(({ manifest }) => ({
|
|
146
|
+
id: manifest.id,
|
|
147
|
+
name: manifest.name,
|
|
148
|
+
description: manifest.description,
|
|
149
|
+
sessionEnabled: manifest.capabilities?.session?.enabled ?? false,
|
|
150
|
+
tools: Object.entries(manifest.actions).map(([actionName, action]) => this.actionToToolDefinition(manifest.id, actionName, action)),
|
|
151
|
+
}));
|
|
152
|
+
}
|
|
153
|
+
getToolDefinitions(_options = {}) {
|
|
154
|
+
const tools = [];
|
|
155
|
+
for (const { manifest } of this.triks.values()) {
|
|
156
|
+
for (const [actionName, action] of Object.entries(manifest.actions)) {
|
|
157
|
+
const tool = this.actionToToolDefinition(manifest.id, actionName, action);
|
|
158
|
+
tools.push(tool);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return tools;
|
|
162
|
+
}
|
|
163
|
+
actionToToolDefinition(trikId, actionName, action) {
|
|
164
|
+
return {
|
|
165
|
+
name: `${trikId}:${actionName}`,
|
|
166
|
+
description: action.description || `Execute ${actionName} on ${trikId}`,
|
|
167
|
+
inputSchema: action.inputSchema,
|
|
168
|
+
responseMode: action.responseMode,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
async execute(trikId, actionName, input, options) {
|
|
172
|
+
const loaded = this.triks.get(trikId);
|
|
173
|
+
if (!loaded) {
|
|
174
|
+
return {
|
|
175
|
+
success: false,
|
|
176
|
+
code: 'TRIK_NOT_FOUND',
|
|
177
|
+
error: `Trik "${trikId}" is not loaded. Call loadTrik() first.`,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
const { manifest, graph } = loaded;
|
|
181
|
+
const action = manifest.actions[actionName];
|
|
182
|
+
if (!action) {
|
|
183
|
+
return {
|
|
184
|
+
success: false,
|
|
185
|
+
code: 'INVALID_INPUT',
|
|
186
|
+
error: `Action "${actionName}" not found. Available: ${Object.keys(manifest.actions).join(', ')}`,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
const inputValidation = this.validator.validate(`${trikId}:${actionName}:input`, action.inputSchema, input);
|
|
190
|
+
if (!inputValidation.valid) {
|
|
191
|
+
return {
|
|
192
|
+
success: false,
|
|
193
|
+
code: 'INVALID_INPUT',
|
|
194
|
+
error: `Invalid input: ${inputValidation.errors?.join(', ')}`,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
let session = null;
|
|
198
|
+
if (manifest.capabilities?.session?.enabled) {
|
|
199
|
+
if (options?.sessionId) {
|
|
200
|
+
session = await this.sessionStorage.get(options.sessionId);
|
|
201
|
+
}
|
|
202
|
+
if (!session) {
|
|
203
|
+
session = await this.sessionStorage.create(trikId, manifest.capabilities.session);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
const trikInput = {
|
|
208
|
+
action: actionName,
|
|
209
|
+
input,
|
|
210
|
+
session: session
|
|
211
|
+
? {
|
|
212
|
+
sessionId: session.sessionId,
|
|
213
|
+
history: session.history,
|
|
214
|
+
}
|
|
215
|
+
: undefined,
|
|
216
|
+
};
|
|
217
|
+
const result = await this.executeWithTimeout(graph, trikInput, manifest.limits.maxExecutionTimeMs);
|
|
218
|
+
if (result.needsClarification && result.clarificationQuestions?.length) {
|
|
219
|
+
if (this.config.onClarificationNeeded) {
|
|
220
|
+
await this.config.onClarificationNeeded(trikId, result.clarificationQuestions);
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
success: false,
|
|
224
|
+
code: 'CLARIFICATION_NEEDED',
|
|
225
|
+
sessionId: session?.sessionId ?? '',
|
|
226
|
+
questions: result.clarificationQuestions,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
return this.processResult(trikId, actionName, action, session, result);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
if (error instanceof Error && error.message === 'TIMEOUT') {
|
|
233
|
+
return {
|
|
234
|
+
success: false,
|
|
235
|
+
code: 'TIMEOUT',
|
|
236
|
+
error: `Execution timed out after ${manifest.limits.maxExecutionTimeMs}ms`,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
success: false,
|
|
241
|
+
code: 'EXECUTION_ERROR',
|
|
242
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
async executeWithTimeout(graph, input, timeoutMs) {
|
|
247
|
+
return Promise.race([
|
|
248
|
+
graph.invoke(input),
|
|
249
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('TIMEOUT')), timeoutMs)),
|
|
250
|
+
]);
|
|
251
|
+
}
|
|
252
|
+
async processResult(trikId, actionName, action, session, result) {
|
|
253
|
+
const effectiveMode = result.responseMode || action.responseMode;
|
|
254
|
+
if (session) {
|
|
255
|
+
if (result.endSession) {
|
|
256
|
+
await this.sessionStorage.delete(session.sessionId);
|
|
257
|
+
session = null;
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
await this.sessionStorage.addHistory(session.sessionId, {
|
|
261
|
+
action: actionName,
|
|
262
|
+
input: {},
|
|
263
|
+
agentData: result.agentData,
|
|
264
|
+
userContent: result.userContent,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if (effectiveMode === 'passthrough') {
|
|
269
|
+
if (result.userContent === undefined) {
|
|
270
|
+
return { success: false, code: 'INVALID_OUTPUT', error: 'Passthrough mode requires userContent' };
|
|
271
|
+
}
|
|
272
|
+
if (action.userContentSchema) {
|
|
273
|
+
const userValidation = this.validator.validate(`${trikId}:${actionName}:userContent`, action.userContentSchema, result.userContent);
|
|
274
|
+
if (!userValidation.valid) {
|
|
275
|
+
return {
|
|
276
|
+
success: false,
|
|
277
|
+
code: 'INVALID_OUTPUT',
|
|
278
|
+
error: `Invalid userContent: ${userValidation.errors?.join(', ')}`,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const userContent = result.userContent;
|
|
283
|
+
const contentRef = this.storePassthroughContent(trikId, actionName, userContent);
|
|
284
|
+
const gatewayResult = {
|
|
285
|
+
success: true,
|
|
286
|
+
responseMode: 'passthrough',
|
|
287
|
+
userContentRef: contentRef,
|
|
288
|
+
contentType: userContent.contentType,
|
|
289
|
+
metadata: userContent.metadata,
|
|
290
|
+
};
|
|
291
|
+
return this.addSessionId(gatewayResult, session);
|
|
292
|
+
}
|
|
293
|
+
if (result.agentData === undefined) {
|
|
294
|
+
return { success: false, code: 'INVALID_OUTPUT', error: 'Template mode requires agentData' };
|
|
295
|
+
}
|
|
296
|
+
if (action.agentDataSchema) {
|
|
297
|
+
const agentValidation = this.validator.validate(`${trikId}:${actionName}:agentData`, action.agentDataSchema, result.agentData);
|
|
298
|
+
if (!agentValidation.valid) {
|
|
299
|
+
return {
|
|
300
|
+
success: false,
|
|
301
|
+
code: 'INVALID_OUTPUT',
|
|
302
|
+
error: `Invalid agentData: ${agentValidation.errors?.join(', ')}`,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
// Get template text if available
|
|
307
|
+
const agentData = result.agentData;
|
|
308
|
+
const templateId = agentData.template;
|
|
309
|
+
const templateText = templateId && action.responseTemplates?.[templateId]?.text;
|
|
310
|
+
const gatewayResult = {
|
|
311
|
+
success: true,
|
|
312
|
+
responseMode: 'template',
|
|
313
|
+
agentData: result.agentData,
|
|
314
|
+
templateText,
|
|
315
|
+
};
|
|
316
|
+
return this.addSessionId(gatewayResult, session);
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Add sessionId to result if session exists
|
|
320
|
+
*/
|
|
321
|
+
addSessionId(result, session) {
|
|
322
|
+
if (session) {
|
|
323
|
+
return { ...result, sessionId: session.sessionId };
|
|
324
|
+
}
|
|
325
|
+
return result;
|
|
326
|
+
}
|
|
327
|
+
// ============================================
|
|
328
|
+
// Passthrough Content Management
|
|
329
|
+
// ============================================
|
|
330
|
+
/**
|
|
331
|
+
* Store passthrough content and return a reference
|
|
332
|
+
*/
|
|
333
|
+
storePassthroughContent(trikId, actionName, content) {
|
|
334
|
+
this.cleanupExpiredContentReferences();
|
|
335
|
+
const ref = randomUUID();
|
|
336
|
+
const now = Date.now();
|
|
337
|
+
this.contentReferences.set(ref, {
|
|
338
|
+
ref,
|
|
339
|
+
trikId,
|
|
340
|
+
actionName,
|
|
341
|
+
content,
|
|
342
|
+
createdAt: now,
|
|
343
|
+
expiresAt: now + TrikGateway.CONTENT_REF_TTL_MS,
|
|
344
|
+
});
|
|
345
|
+
return ref;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Clean up expired content references
|
|
349
|
+
*/
|
|
350
|
+
cleanupExpiredContentReferences() {
|
|
351
|
+
const now = Date.now();
|
|
352
|
+
for (const [ref, contentRef] of this.contentReferences) {
|
|
353
|
+
if (contentRef.expiresAt < now) {
|
|
354
|
+
this.contentReferences.delete(ref);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Deliver passthrough content to the user.
|
|
360
|
+
* One-time delivery - the reference is deleted after delivery.
|
|
361
|
+
*/
|
|
362
|
+
deliverContent(ref) {
|
|
363
|
+
const contentRef = this.contentReferences.get(ref);
|
|
364
|
+
if (!contentRef) {
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
if (contentRef.expiresAt < Date.now()) {
|
|
368
|
+
this.contentReferences.delete(ref);
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
// One-time delivery
|
|
372
|
+
this.contentReferences.delete(ref);
|
|
373
|
+
return {
|
|
374
|
+
content: contentRef.content,
|
|
375
|
+
receipt: {
|
|
376
|
+
delivered: true,
|
|
377
|
+
contentType: contentRef.content.contentType,
|
|
378
|
+
metadata: contentRef.content.metadata,
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
hasContentRef(ref) {
|
|
383
|
+
const contentRef = this.contentReferences.get(ref);
|
|
384
|
+
if (!contentRef)
|
|
385
|
+
return false;
|
|
386
|
+
if (contentRef.expiresAt < Date.now()) {
|
|
387
|
+
this.contentReferences.delete(ref);
|
|
388
|
+
return false;
|
|
389
|
+
}
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
getContentRefInfo(ref) {
|
|
393
|
+
const contentRef = this.contentReferences.get(ref);
|
|
394
|
+
if (!contentRef || contentRef.expiresAt < Date.now()) {
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
contentType: contentRef.content.contentType,
|
|
399
|
+
metadata: contentRef.content.metadata,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
resolveTemplate(template, agentData) {
|
|
403
|
+
let text = template.text;
|
|
404
|
+
const placeholderRegex = /\{\{(\w+)\}\}/g;
|
|
405
|
+
text = text.replace(placeholderRegex, (_, fieldName) => {
|
|
406
|
+
const value = agentData[fieldName];
|
|
407
|
+
return value !== undefined ? String(value) : `{{${fieldName}}}`;
|
|
408
|
+
});
|
|
409
|
+
return text;
|
|
410
|
+
}
|
|
411
|
+
getActionTemplates(trikId, actionName) {
|
|
412
|
+
const manifest = this.triks.get(trikId)?.manifest;
|
|
413
|
+
if (!manifest)
|
|
414
|
+
return undefined;
|
|
415
|
+
const action = manifest.actions[actionName];
|
|
416
|
+
if (!action)
|
|
417
|
+
return undefined;
|
|
418
|
+
return action.responseTemplates;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
//# sourceMappingURL=gateway.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gateway.js","sourceRoot":"","sources":["../src/gateway.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAeL,gBAAgB,EAChB,eAAe,GAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAuB,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAyEnF,MAAM,OAAO,WAAW;IACd,SAAS,GAAG,IAAI,eAAe,EAAE,CAAC;IAClC,MAAM,CAAoB;IAC1B,cAAc,CAAiB;IAEvC,4BAA4B;IACpB,KAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;IACtC,iBAAiB,GAAG,IAAI,GAAG,EAAgC,CAAC;IAC5D,MAAM,CAAC,kBAAkB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAEnD,YAAY,SAA4B,EAAE;QACxC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,MAAM,CAAC,cAAc,IAAI,IAAI,sBAAsB,EAAE,CAAC;IAC9E,CAAC;IA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AAG,SAAS,CAAC,SAAS,CAAC,CAAC;YACnC,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,CAAC;QAClE,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IACd,CAAC;IAED,kBAAkB,CAAC,MAAc,EAAE,UAAkB;QACnD,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC;QAClD,IAAI,CAAC,QAAQ;YAAE,OAAO,SAAS,CAAC;QAEhC,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAC5C,IAAI,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC;QAE9B,OAAO,MAAM,CAAC,iBAAiB,CAAC;IAClC,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { TrikGateway, type TrikGatewayConfig, type ExecuteTrikOptions, type GatewayResultWithSession, type ToolDefinition, type TrikInfo, type GetToolDefinitionsOptions, } from './gateway.js';
|
|
2
|
+
export { type SessionStorage, InMemorySessionStorage } from './session-storage.js';
|
|
3
|
+
export type { TrikManifest, ActionDefinition, ResponseMode, JSONSchema, ResponseTemplate, GatewayResult, GatewaySuccess, GatewaySuccessTemplate, GatewaySuccessPassthrough, GatewayError, GatewayClarification, ClarificationQuestion, ClarificationAnswer, SessionCapabilities, SessionHistoryEntry, TrikSession, SessionContext, PassthroughContent, PassthroughDeliveryReceipt, UserContentReference, } from '@trikhub/manifest';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,WAAW,EACX,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,wBAAwB,EAE7B,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,yBAAyB,GAC/B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,KAAK,cAAc,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAGnF,YAAY,EACV,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,UAAU,EACV,gBAAgB,EAChB,aAAa,EACb,cAAc,EACd,sBAAsB,EACtB,yBAAyB,EACzB,YAAY,EACZ,oBAAoB,EACpB,qBAAqB,EACrB,mBAAmB,EAEnB,mBAAmB,EACnB,mBAAmB,EACnB,WAAW,EACX,cAAc,EAEd,kBAAkB,EAClB,0BAA0B,EAC1B,oBAAoB,GACrB,MAAM,mBAAmB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,OAAO,EACL,WAAW,GAQZ,MAAM,cAAc,CAAC;AAEtB,kBAAkB;AAClB,OAAO,EAAuB,sBAAsB,EAAE,MAAM,sBAAsB,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type DynamicStructuredTool } from '@langchain/core/tools';
|
|
2
|
+
import type { TrikGateway } from '../gateway.js';
|
|
3
|
+
import type { PassthroughContent } from '@trikhub/manifest';
|
|
4
|
+
export interface LangChainAdapterOptions {
|
|
5
|
+
/** Get session ID for a trik (for multi-turn conversations) */
|
|
6
|
+
getSessionId?: (trikId: string) => string | undefined;
|
|
7
|
+
/** Store session ID for a trik */
|
|
8
|
+
setSessionId?: (trikId: string, sessionId: string) => void;
|
|
9
|
+
/** Callback when passthrough content is delivered */
|
|
10
|
+
onPassthrough?: (content: PassthroughContent) => void;
|
|
11
|
+
/** Enable debug logging */
|
|
12
|
+
debug?: boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare function parseToolName(toolName: string): {
|
|
15
|
+
trikId: string;
|
|
16
|
+
actionName: string;
|
|
17
|
+
};
|
|
18
|
+
export declare function createLangChainTools(gateway: TrikGateway, options?: LangChainAdapterOptions): DynamicStructuredTool[];
|
|
19
|
+
export declare function getToolNameMap(gateway: TrikGateway): Map<string, string>;
|
|
20
|
+
//# sourceMappingURL=adapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/langchain/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAEzE,OAAO,KAAK,EAAE,WAAW,EAAkB,MAAM,eAAe,CAAC;AACjE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAG5D,MAAM,WAAW,uBAAuB;IACtC,+DAA+D;IAC/D,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IACtD,kCAAkC;IAClC,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3D,qDAAqD;IACrD,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACtD,2BAA2B;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAeD,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAUtF;AAyFD,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,WAAW,EACpB,OAAO,GAAE,uBAA4B,GACpC,qBAAqB,EAAE,CAYzB;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAUxE"}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { tool } from '@langchain/core/tools';
|
|
2
|
+
import { jsonSchemaToZod } from './schema-converter.js';
|
|
3
|
+
function fillTemplate(template, data) {
|
|
4
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => String(data[key] ?? `{{${key}}}`));
|
|
5
|
+
}
|
|
6
|
+
function toToolName(gatewayName) {
|
|
7
|
+
return gatewayName
|
|
8
|
+
.replace(/\//g, '_')
|
|
9
|
+
.replace(/-/g, '_')
|
|
10
|
+
.replace(/:/g, '__');
|
|
11
|
+
}
|
|
12
|
+
export function parseToolName(toolName) {
|
|
13
|
+
const parts = toolName.split('__');
|
|
14
|
+
if (parts.length !== 2) {
|
|
15
|
+
throw new Error(`Invalid tool name format: ${toolName}`);
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
trikId: parts[0],
|
|
19
|
+
actionName: parts[1],
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function createToolFromDefinition(toolDef, gateway, options) {
|
|
23
|
+
const { getSessionId, setSessionId, onPassthrough, debug } = options;
|
|
24
|
+
const langChainName = toToolName(toolDef.name);
|
|
25
|
+
const [trikIdPart, actionName] = toolDef.name.split(':');
|
|
26
|
+
const trikId = trikIdPart;
|
|
27
|
+
const zodSchema = jsonSchemaToZod(toolDef.inputSchema);
|
|
28
|
+
return tool(async (input) => {
|
|
29
|
+
if (debug) {
|
|
30
|
+
console.log(`[Tool] ${toolDef.name}: ${JSON.stringify(input)}`);
|
|
31
|
+
}
|
|
32
|
+
const sessionId = getSessionId?.(trikId);
|
|
33
|
+
const result = await gateway.execute(trikId, actionName, input, { sessionId });
|
|
34
|
+
if (!result.success) {
|
|
35
|
+
return JSON.stringify({
|
|
36
|
+
success: false,
|
|
37
|
+
error: 'error' in result ? result.error : 'Unknown error',
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
if ('sessionId' in result && result.sessionId) {
|
|
41
|
+
setSessionId?.(trikId, result.sessionId);
|
|
42
|
+
if (debug) {
|
|
43
|
+
console.log(`[Tool] Session tracked: ${result.sessionId}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (result.responseMode === 'passthrough') {
|
|
47
|
+
const delivery = gateway.deliverContent(result.userContentRef);
|
|
48
|
+
if (!delivery) {
|
|
49
|
+
return JSON.stringify({
|
|
50
|
+
success: false,
|
|
51
|
+
error: 'Content not found or expired',
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
if (debug) {
|
|
55
|
+
console.log(`[Tool] Auto-delivered passthrough content: ${delivery.receipt.contentType}`);
|
|
56
|
+
}
|
|
57
|
+
if (onPassthrough) {
|
|
58
|
+
onPassthrough(delivery.content);
|
|
59
|
+
}
|
|
60
|
+
return JSON.stringify({
|
|
61
|
+
success: true,
|
|
62
|
+
response: 'Content delivered.',
|
|
63
|
+
_directOutput: delivery.content.content,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const response = result.templateText
|
|
67
|
+
? fillTemplate(result.templateText, result.agentData)
|
|
68
|
+
: JSON.stringify(result.agentData);
|
|
69
|
+
if (debug) {
|
|
70
|
+
console.log(`[Tool] Auto-filled template response: ${response}`);
|
|
71
|
+
}
|
|
72
|
+
return JSON.stringify({
|
|
73
|
+
success: true,
|
|
74
|
+
response,
|
|
75
|
+
});
|
|
76
|
+
}, {
|
|
77
|
+
name: langChainName,
|
|
78
|
+
description: toolDef.description,
|
|
79
|
+
schema: zodSchema,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
export function createLangChainTools(gateway, options = {}) {
|
|
83
|
+
const { debug } = options;
|
|
84
|
+
const toolDefs = gateway.getToolDefinitions();
|
|
85
|
+
if (debug) {
|
|
86
|
+
console.log(`[LangChainAdapter] Creating ${toolDefs.length} tools from gateway:`);
|
|
87
|
+
for (const def of toolDefs) {
|
|
88
|
+
console.log(` - ${def.name} (${def.responseMode})`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return toolDefs.map((def) => createToolFromDefinition(def, gateway, options));
|
|
92
|
+
}
|
|
93
|
+
export function getToolNameMap(gateway) {
|
|
94
|
+
const toolDefs = gateway.getToolDefinitions();
|
|
95
|
+
const map = new Map();
|
|
96
|
+
for (const def of toolDefs) {
|
|
97
|
+
const langChainName = toToolName(def.name);
|
|
98
|
+
map.set(langChainName, def.name);
|
|
99
|
+
}
|
|
100
|
+
return map;
|
|
101
|
+
}
|
|
102
|
+
//# sourceMappingURL=adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../src/langchain/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAA8B,MAAM,uBAAuB,CAAC;AAIzE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAaxD,SAAS,YAAY,CAAC,QAAgB,EAAE,IAA6B;IACnE,OAAO,QAAQ,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,CACnD,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,KAAK,GAAG,IAAI,CAAC,CAClC,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,WAAmB;IACrC,OAAO,WAAW;SACf,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC;SAClB,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACzB,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,QAAgB;IAC5C,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,6BAA6B,QAAQ,EAAE,CAAC,CAAC;IAC3D,CAAC;IAED,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;QAChB,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC;KACrB,CAAC;AACJ,CAAC;AAED,SA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AAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/langchain/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,aAAa,EACb,cAAc,GAEf,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-converter.d.ts","sourceRoot":"","sources":["../../src/langchain/schema-converter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAK,KAAK,UAAU,EAAE,MAAM,KAAK,CAAC;AACzC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,wBAAgB,eAAe,CAAC,MAAM,EAAE,UAAU,EAAE,IAAI,GAAE,MAAe,GAAG,UAAU,CAqFrF"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export function jsonSchemaToZod(schema, path = 'root') {
|
|
3
|
+
if (!schema.type && !schema.$ref) {
|
|
4
|
+
return z.unknown();
|
|
5
|
+
}
|
|
6
|
+
if (schema.type === 'string') {
|
|
7
|
+
let zodSchema = z.string();
|
|
8
|
+
if (schema.description) {
|
|
9
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
10
|
+
}
|
|
11
|
+
if (schema.minLength !== undefined) {
|
|
12
|
+
zodSchema = zodSchema.min(schema.minLength);
|
|
13
|
+
}
|
|
14
|
+
if (schema.maxLength !== undefined) {
|
|
15
|
+
zodSchema = zodSchema.max(schema.maxLength);
|
|
16
|
+
}
|
|
17
|
+
if (schema.pattern !== undefined) {
|
|
18
|
+
zodSchema = zodSchema.regex(new RegExp(schema.pattern));
|
|
19
|
+
}
|
|
20
|
+
if (schema.enum && schema.enum.length > 0) {
|
|
21
|
+
return z.enum(schema.enum).describe(schema.description || '');
|
|
22
|
+
}
|
|
23
|
+
return zodSchema;
|
|
24
|
+
}
|
|
25
|
+
if (schema.type === 'number' || schema.type === 'integer') {
|
|
26
|
+
let zodSchema = schema.type === 'integer' ? z.number().int() : z.number();
|
|
27
|
+
if (schema.description) {
|
|
28
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
29
|
+
}
|
|
30
|
+
if (schema.minimum !== undefined) {
|
|
31
|
+
zodSchema = zodSchema.min(schema.minimum);
|
|
32
|
+
}
|
|
33
|
+
if (schema.maximum !== undefined) {
|
|
34
|
+
zodSchema = zodSchema.max(schema.maximum);
|
|
35
|
+
}
|
|
36
|
+
return zodSchema;
|
|
37
|
+
}
|
|
38
|
+
if (schema.type === 'boolean') {
|
|
39
|
+
let zodSchema = z.boolean();
|
|
40
|
+
if (schema.description) {
|
|
41
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
42
|
+
}
|
|
43
|
+
return zodSchema;
|
|
44
|
+
}
|
|
45
|
+
if (schema.type === 'array') {
|
|
46
|
+
const itemSchema = schema.items ? jsonSchemaToZod(schema.items, `${path}.items`) : z.unknown();
|
|
47
|
+
let zodSchema = z.array(itemSchema);
|
|
48
|
+
if (schema.description) {
|
|
49
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
50
|
+
}
|
|
51
|
+
return zodSchema;
|
|
52
|
+
}
|
|
53
|
+
if (schema.type === 'object') {
|
|
54
|
+
const shape = {};
|
|
55
|
+
if (schema.properties) {
|
|
56
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
57
|
+
const propZod = jsonSchemaToZod(propSchema, `${path}.${key}`);
|
|
58
|
+
if (!schema.required?.includes(key)) {
|
|
59
|
+
shape[key] = propZod.optional();
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
shape[key] = propZod;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
let zodSchema = z.object(shape);
|
|
67
|
+
if (schema.description) {
|
|
68
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
69
|
+
}
|
|
70
|
+
return zodSchema;
|
|
71
|
+
}
|
|
72
|
+
return z.unknown();
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=schema-converter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-converter.js","sourceRoot":"","sources":["../../src/langchain/schema-converter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAmB,MAAM,KAAK,CAAC;AAGzC,MAAM,UAAU,eAAe,CAAC,MAAkB,EAAE,OAAe,MAAM;IACvE,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QACjC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;IACrB,CAAC;IAED,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,IAAI,SAAS,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;QAE3B,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;YACvB,SAAS,GAAG,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QACrD,CAAC;QAED,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YACnC,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC9C,CAAC;QACD,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YACnC,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC9C,CAAC;QACD,IAAI,MAAM,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YACjC,SAAS,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1D,CAAC;QAED,IAAI,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC1C,OAAO,CAAC,CAAC,IAAI,CAA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@
|
|
|
1
|
+
import type { TrikSession, SessionHistoryEntry, SessionCapabilities } from '@trikhub/manifest';
|
|
2
|
+
/**
|
|
3
|
+
* Interface for session storage implementations
|
|
4
|
+
*/
|
|
5
|
+
export interface SessionStorage {
|
|
6
|
+
/**
|
|
7
|
+
* Create a new session for a trik
|
|
8
|
+
*/
|
|
9
|
+
create(trikId: string, config?: SessionCapabilities): Promise<TrikSession>;
|
|
10
|
+
/**
|
|
11
|
+
* Get an existing session by ID
|
|
12
|
+
* Returns null if session doesn't exist or is expired
|
|
13
|
+
*/
|
|
14
|
+
get(sessionId: string): Promise<TrikSession | null>;
|
|
15
|
+
/**
|
|
16
|
+
* Add a history entry to a session
|
|
17
|
+
*/
|
|
18
|
+
addHistory(sessionId: string, entry: Omit<SessionHistoryEntry, 'timestamp'>): Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* Delete a session
|
|
21
|
+
*/
|
|
22
|
+
delete(sessionId: string): Promise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* Clean up expired sessions
|
|
25
|
+
* Returns the number of sessions cleaned up
|
|
26
|
+
*/
|
|
27
|
+
cleanup(): Promise<number>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* In-memory session storage implementation.
|
|
31
|
+
* Sessions are lost when the process restarts.
|
|
32
|
+
*/
|
|
33
|
+
export declare class InMemorySessionStorage implements SessionStorage {
|
|
34
|
+
private sessions;
|
|
35
|
+
create(trikId: string, config?: SessionCapabilities): Promise<TrikSession>;
|
|
36
|
+
get(sessionId: string): Promise<TrikSession | null>;
|
|
37
|
+
addHistory(sessionId: string, entry: Omit<SessionHistoryEntry, 'timestamp'>): Promise<void>;
|
|
38
|
+
delete(sessionId: string): Promise<void>;
|
|
39
|
+
cleanup(): Promise<number>;
|
|
40
|
+
/**
|
|
41
|
+
* Get the number of active sessions (for debugging/monitoring)
|
|
42
|
+
*/
|
|
43
|
+
getActiveSessionCount(): number;
|
|
44
|
+
}
|
|
45
|
+
//# source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OAAO,CAAC,MAAM,CAAC;IAchC;;OAEG;IACH,qBAAqB,IAAI,MAAM;CAGhC"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generate a random session ID
|
|
3
|
+
*/
|
|
4
|
+
function generateSessionId() {
|
|
5
|
+
return `sess_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Default values for session configuration
|
|
9
|
+
*/
|
|
10
|
+
const DEFAULT_MAX_DURATION_MS = 30 * 60 * 1000; // 30 minutes
|
|
11
|
+
const DEFAULT_MAX_HISTORY_ENTRIES = 20;
|
|
12
|
+
/**
|
|
13
|
+
* In-memory session storage implementation.
|
|
14
|
+
* Sessions are lost when the process restarts.
|
|
15
|
+
*/
|
|
16
|
+
export class InMemorySessionStorage {
|
|
17
|
+
sessions = new Map();
|
|
18
|
+
async create(trikId, config) {
|
|
19
|
+
const now = Date.now();
|
|
20
|
+
const maxDurationMs = config?.maxDurationMs ?? DEFAULT_MAX_DURATION_MS;
|
|
21
|
+
const session = {
|
|
22
|
+
sessionId: generateSessionId(),
|
|
23
|
+
trikId,
|
|
24
|
+
createdAt: now,
|
|
25
|
+
lastActivityAt: now,
|
|
26
|
+
expiresAt: now + maxDurationMs,
|
|
27
|
+
history: [],
|
|
28
|
+
};
|
|
29
|
+
this.sessions.set(session.sessionId, session);
|
|
30
|
+
return session;
|
|
31
|
+
}
|
|
32
|
+
async get(sessionId) {
|
|
33
|
+
const session = this.sessions.get(sessionId);
|
|
34
|
+
if (!session) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
// Check if session has expired
|
|
38
|
+
if (Date.now() > session.expiresAt) {
|
|
39
|
+
this.sessions.delete(sessionId);
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
// Update last activity
|
|
43
|
+
session.lastActivityAt = Date.now();
|
|
44
|
+
return session;
|
|
45
|
+
}
|
|
46
|
+
async addHistory(sessionId, entry) {
|
|
47
|
+
const session = await this.get(sessionId);
|
|
48
|
+
if (!session) {
|
|
49
|
+
throw new Error(`Session ${sessionId} not found`);
|
|
50
|
+
}
|
|
51
|
+
// Add the history entry with timestamp
|
|
52
|
+
const historyEntry = {
|
|
53
|
+
...entry,
|
|
54
|
+
timestamp: Date.now(),
|
|
55
|
+
};
|
|
56
|
+
session.history.push(historyEntry);
|
|
57
|
+
// Trim history if it exceeds the limit
|
|
58
|
+
// We use DEFAULT_MAX_HISTORY_ENTRIES since we don't store the config
|
|
59
|
+
if (session.history.length > DEFAULT_MAX_HISTORY_ENTRIES) {
|
|
60
|
+
session.history = session.history.slice(-DEFAULT_MAX_HISTORY_ENTRIES);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async delete(sessionId) {
|
|
64
|
+
this.sessions.delete(sessionId);
|
|
65
|
+
}
|
|
66
|
+
async cleanup() {
|
|
67
|
+
const now = Date.now();
|
|
68
|
+
let cleaned = 0;
|
|
69
|
+
for (const [sessionId, session] of this.sessions) {
|
|
70
|
+
if (now > session.expiresAt) {
|
|
71
|
+
this.sessions.delete(sessionId);
|
|
72
|
+
cleaned++;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return cleaned;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Get the number of active sessions (for debugging/monitoring)
|
|
79
|
+
*/
|
|
80
|
+
getActiveSessionCount() {
|
|
81
|
+
return this.sessions.size;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=session-storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-storage.js","sourceRoot":"","sources":["../src/session-storage.ts"],"names":[],"mappings":"AAyCA;;GAEG;AACH,SAAS,iBAAiB;IACxB,OAAO,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,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0 +1,75 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@trikhub/gateway",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Secure trik execution gateway for AI agents with prompt injection protection",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
},
|
|
13
|
+
"./langchain": {
|
|
14
|
+
"import": "./dist/langchain/index.js",
|
|
15
|
+
"types": "./dist/langchain/index.d.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"keywords": [
|
|
24
|
+
"ai",
|
|
25
|
+
"agent",
|
|
26
|
+
"trik",
|
|
27
|
+
"gateway",
|
|
28
|
+
"security",
|
|
29
|
+
"prompt-injection",
|
|
30
|
+
"langchain",
|
|
31
|
+
"typescript",
|
|
32
|
+
"trikhub"
|
|
33
|
+
],
|
|
34
|
+
"author": "Muffles",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/Muffles/trikhub.git",
|
|
39
|
+
"directory": "packages/trik-gateway"
|
|
40
|
+
},
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/Muffles/trikhub/issues"
|
|
43
|
+
},
|
|
44
|
+
"homepage": "https://github.com/Muffles/trikhub/tree/main/packages/trik-gateway#readme",
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=18.0.0"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"ajv": "^8.17.1",
|
|
53
|
+
"@trikhub/manifest": "0.1.0"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@langchain/core": "^0.3.0",
|
|
57
|
+
"zod": "^3.0.0"
|
|
58
|
+
},
|
|
59
|
+
"peerDependencies": {
|
|
60
|
+
"@langchain/core": ">=0.3.0",
|
|
61
|
+
"zod": ">=3.0.0"
|
|
62
|
+
},
|
|
63
|
+
"peerDependenciesMeta": {
|
|
64
|
+
"@langchain/core": {
|
|
65
|
+
"optional": true
|
|
66
|
+
},
|
|
67
|
+
"zod": {
|
|
68
|
+
"optional": true
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"scripts": {
|
|
72
|
+
"build": "tsc",
|
|
73
|
+
"clean": "rm -rf dist *.tsbuildinfo"
|
|
74
|
+
}
|
|
75
|
+
}
|