@veris-ai/sdk
Version:
A TypeScript package for Veris AI tools
177 lines • 8.26 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.veris = exports.ToolMock = void 0;
const axios_1 = __importDefault(require("axios"));
const zod_to_json_schema_1 = require("zod-to-json-schema");
const types_1 = require("./types");
class ToolMock {
_sessionId;
get sessionId() {
return this._sessionId || null;
}
setSessionId(sessionId) {
this._sessionId = sessionId;
console.log(`Session ID set to ${sessionId} - mocking enabled`);
}
clearSessionId() {
this._sessionId = undefined;
console.log('Session ID cleared - mocking disabled');
}
createMockPayload(functionName, description, args, parametersSchema, outputSchema, mode = 'tool', expectsResponse, cacheResponse) {
const returnType = outputSchema ? JSON.stringify((0, zod_to_json_schema_1.zodToJsonSchema)(outputSchema)) : 'any';
// Convert arguments to Python SDK format with value and type
const parameters = {};
const schemaObject = (0, zod_to_json_schema_1.zodToJsonSchema)(parametersSchema);
const properties = schemaObject.properties || {};
for (const [key, value] of Object.entries(args)) {
const propSchema = properties[key] || {};
parameters[key] = {
value: typeof value === 'object' ? JSON.stringify(value) : String(value),
type: propSchema.type || typeof value
};
}
// Determine response expectation based on mode and expectsResponse
let responseExpectation;
if (expectsResponse === false || (expectsResponse === undefined && mode === 'function')) {
responseExpectation = types_1.ResponseExpectation.NONE;
}
else if (expectsResponse === true) {
responseExpectation = types_1.ResponseExpectation.REQUIRED;
}
else {
responseExpectation = types_1.ResponseExpectation.AUTO;
}
return {
session_id: this._sessionId,
response_expectation: responseExpectation,
cache_response: cacheResponse || false,
tool_call: {
function_name: functionName,
parameters,
return_type: returnType,
docstring: description
}
};
}
async executeMockRequest(payload) {
const baseUrl = process.env.VERIS_ENDPOINT_URL || process.env.VERIS_MOCK_ENDPOINT_URL;
if (!baseUrl) {
throw new Error('VERIS_ENDPOINT_URL environment variable is not set');
}
const endpoint = `${baseUrl.replace(/\/$/, '')}/api/v2/tool_mock`;
const timeout = parseFloat(process.env.VERIS_MOCK_TIMEOUT || '90000');
try {
const response = await axios_1.default.post(endpoint, payload, { timeout });
let mockResult = response.data;
console.log(`Mock response: ${JSON.stringify(mockResult)}`);
if (typeof mockResult === 'string') {
try {
mockResult = JSON.parse(mockResult);
}
catch (error) {
// Keep as string if not valid JSON
}
}
return mockResult;
}
catch (error) {
console.error('Mock request failed:', error);
throw error;
}
}
createMockWrapper(originalFunc, { name, description, parametersSchema, outputSchema, mode = 'tool', expectsResponse, cacheResponse }) {
return async (args) => {
// Check if we have a session ID - if not, execute original function
// Session ID presence determines whether mocking is enabled
if (!this._sessionId) {
return originalFunc(args);
}
// Handle spy mode - execute original function and log
if (mode === 'spy') {
console.log(`Spying on function: ${name}`);
// TODO: Add logging to backend
const result = await originalFunc(args);
// TODO: Log response
return result;
}
// Mock mode is enabled when session ID is present
console.log(`Mocking function: ${name} (session: ${this._sessionId})`);
const payload = this.createMockPayload(name, description, args, parametersSchema, outputSchema, mode, expectsResponse, cacheResponse);
return this.executeMockRequest(payload);
};
}
mockFunction(func, params) {
return this.createMockWrapper(func, params);
}
// Decorator support
mock(options = { mode: 'tool' }) {
return (_target, propertyKey, descriptor) => {
const originalMethod = descriptor.value;
descriptor.value = async function (...args) {
// Check if we have a session ID - if not, execute original function
// Session ID presence determines whether mocking is enabled
if (!exports.veris._sessionId) {
return originalMethod.apply(this, args);
}
// Handle spy mode
if (options.mode === 'spy') {
console.log(`Spying on function: ${propertyKey}`);
const result = await originalMethod.apply(this, args);
return result;
}
// Mock mode is enabled when session ID is present
console.log(`Mocking function: ${propertyKey} (session: ${exports.veris._sessionId})`);
// Convert parameters to the expected format if parametersSchema is provided
let parameters = args[0] || {};
if (options.parametersSchema) {
const schemaObject = (0, zod_to_json_schema_1.zodToJsonSchema)(options.parametersSchema);
const properties = schemaObject.properties || {};
const formattedParams = {};
for (const [key, value] of Object.entries(parameters)) {
const propSchema = properties[key] || {};
formattedParams[key] = {
value: typeof value === 'object' ? JSON.stringify(value) : String(value),
type: propSchema.type || typeof value
};
}
parameters = formattedParams;
}
// Generate return_type from outputSchema if provided
const returnType = options.outputSchema
? JSON.stringify((0, zod_to_json_schema_1.zodToJsonSchema)(options.outputSchema))
: 'any';
// Determine response expectation
let responseExpectation;
if (options.expectsResponse === false || (options.expectsResponse === undefined && options.mode === 'function')) {
responseExpectation = types_1.ResponseExpectation.NONE;
}
else if (options.expectsResponse === true) {
responseExpectation = types_1.ResponseExpectation.REQUIRED;
}
else {
responseExpectation = types_1.ResponseExpectation.AUTO;
}
// Create payload with proper format
const payload = {
session_id: exports.veris._sessionId,
response_expectation: responseExpectation,
cache_response: options.cacheResponse || false,
tool_call: {
function_name: propertyKey,
parameters,
return_type: returnType,
docstring: options.description || ''
}
};
return exports.veris.executeMockRequest(payload);
};
return descriptor;
};
}
}
exports.ToolMock = ToolMock;
exports.veris = new ToolMock();
//# sourceMappingURL=toolMock.js.map