@vorim/sdk 1.0.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/integrations/crewai.cjs +141 -0
- package/dist/integrations/crewai.cjs.map +1 -0
- package/dist/integrations/crewai.d.cts +174 -0
- package/dist/integrations/crewai.d.ts +174 -0
- package/dist/integrations/crewai.js +111 -0
- package/dist/integrations/crewai.js.map +1 -0
- package/dist/integrations/langchain.cjs +197 -0
- package/dist/integrations/langchain.cjs.map +1 -0
- package/dist/integrations/langchain.d.cts +145 -0
- package/dist/integrations/langchain.d.ts +145 -0
- package/dist/integrations/langchain.js +169 -0
- package/dist/integrations/langchain.js.map +1 -0
- package/dist/integrations/llamaindex.cjs +162 -0
- package/dist/integrations/llamaindex.cjs.map +1 -0
- package/dist/integrations/llamaindex.d.cts +131 -0
- package/dist/integrations/llamaindex.d.ts +131 -0
- package/dist/integrations/llamaindex.js +134 -0
- package/dist/integrations/llamaindex.js.map +1 -0
- package/dist/integrations/openai.cjs +208 -0
- package/dist/integrations/openai.cjs.map +1 -0
- package/dist/integrations/openai.d.cts +189 -0
- package/dist/integrations/openai.d.ts +189 -0
- package/dist/integrations/openai.js +181 -0
- package/dist/integrations/openai.js.map +1 -0
- package/package.json +51 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/langchain.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — LangChain / LangGraph JS Integration\n// Provides tool wrapping with permission checks + audit trail,\n// a callback handler for observability, and a factory for creating\n// Vorim-secured LangGraph ReAct agents.\n//\n// Peer dependencies:\n// @langchain/core >=0.3.0\n// @langchain/langgraph >=0.2.0\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\n\n// ─── Re-declared LangChain types (peer dependency — not bundled) ──────────\n// These mirror the actual types from @langchain/core so consumers don't\n// need to import them separately for basic usage.\n\n/** Minimal subset of @langchain/core Serialized */\ninterface Serialized {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimLangChainConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id to associate with this LangChain agent. */\n agentId: string;\n /** Map tool names → Vorim permission scopes. Unmapped tools default to 'agent:execute'. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default permission scope for tools not in permissionMap. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (fire-and-forget). @default true */\n asyncAudit?: boolean;\n}\n\n// ─── Tool Wrapper ─────────────────────────────────────────────────────────\n\n/**\n * Wraps a LangChain `StructuredTool` (or `DynamicStructuredTool`) with\n * Vorim permission checks before execution and audit event emission after.\n *\n * Works with any tool that has `name`, `description`, `schema`, and `_call`.\n *\n * @example\n * ```ts\n * import { DynamicStructuredTool } from \"@langchain/core/tools\";\n * import { wrapTool } from \"@vorim/sdk/integrations/langchain\";\n *\n * const guarded = wrapTool(myTool, {\n * vorim, agentId: \"agid_acme_a1b2c3d4\",\n * permissionMap: { search_docs: \"agent:read\" },\n * });\n * ```\n */\nexport function wrapTool<T extends LangChainTool>(\n tool: T,\n config: VorimLangChainConfig,\n): T {\n const { vorim, agentId, permissionMap = {}, defaultPermission = 'agent:execute', asyncAudit = true } = config;\n\n const originalCall = tool._call.bind(tool);\n\n // Override _call to inject permission check + audit\n (tool as any)._call = async function vorimGuardedCall(\n arg: unknown,\n runManager?: unknown,\n parentConfig?: unknown,\n ): Promise<unknown> {\n const scope = permissionMap[tool.name] ?? defaultPermission;\n\n // 1. Permission check\n const { allowed, reason } = await vorim.check(agentId, scope);\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: tool.name,\n resource: truncate(JSON.stringify(arg), 500),\n permission: scope,\n result: 'denied',\n metadata: { reason, framework: 'langchain' },\n };\n emitAudit(vorim, event, asyncAudit);\n throw new Error(`Vorim: permission denied for \"${tool.name}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`);\n }\n\n // 2. Execute the original tool\n const start = Date.now();\n let result: unknown;\n try {\n result = await originalCall(arg, runManager, parentConfig);\n } catch (err) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: tool.name,\n resource: truncate(JSON.stringify(arg), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n metadata: { error: err instanceof Error ? err.message : String(err), framework: 'langchain' },\n };\n emitAudit(vorim, event, asyncAudit);\n throw err;\n }\n\n // 3. Audit success\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: tool.name,\n resource: truncate(JSON.stringify(arg), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n metadata: { framework: 'langchain' },\n };\n emitAudit(vorim, event, asyncAudit);\n\n return result;\n };\n\n return tool;\n}\n\n/**\n * Wraps an array of LangChain tools with Vorim permission + audit.\n */\nexport function wrapTools<T extends LangChainTool>(\n tools: T[],\n config: VorimLangChainConfig,\n): T[] {\n return tools.map(t => wrapTool(t, config));\n}\n\n// ─── Callback Handler ─────────────────────────────────────────────────────\n\n/**\n * LangChain callback handler that emits Vorim audit events for every\n * tool invocation. This is a **non-intrusive** observability layer —\n * it does not block or modify tool execution.\n *\n * Attach it to any LangChain invoke/stream call:\n * ```ts\n * const handler = new VorimCallbackHandler(vorim, \"agid_acme_a1b2c3d4\");\n * await agent.invoke({ messages }, { callbacks: [handler] });\n * ```\n */\nexport class VorimCallbackHandler {\n name = 'VorimCallbackHandler';\n private vorim: VorimSDK;\n private agentId: string;\n private runMap = new Map<string, { tool: string; input: string; startTime: number }>();\n\n // Flags to satisfy BaseCallbackHandler interface\n ignoreLLM = true;\n ignoreChain = true;\n ignoreAgent = true;\n ignoreRetriever = true;\n ignoreCustomEvent = true;\n lc_serializable = false;\n\n get lc_id(): string[] { return ['vorim', 'callbacks', 'VorimCallbackHandler']; }\n get lc_namespace(): string[] { return ['vorim', 'callbacks']; }\n\n constructor(vorim: VorimSDK, agentId: string) {\n this.vorim = vorim;\n this.agentId = agentId;\n }\n\n async handleToolStart(\n tool: Serialized,\n input: string,\n runId: string,\n _parentRunId?: string,\n _tags?: string[],\n _metadata?: Record<string, unknown>,\n runName?: string,\n ): Promise<void> {\n const toolName = runName ?? tool.id?.[tool.id.length - 1] ?? 'unknown';\n this.runMap.set(runId, { tool: toolName, input, startTime: Date.now() });\n }\n\n async handleToolEnd(\n _output: unknown,\n runId: string,\n ): Promise<void> {\n const run = this.runMap.get(runId);\n if (!run) return;\n this.runMap.delete(runId);\n\n await this.vorim.emit({\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: run.tool,\n resource: truncate(run.input, 500),\n result: 'success',\n latency_ms: Date.now() - run.startTime,\n metadata: { framework: 'langchain' },\n }).catch(() => {}); // never throw from callback\n }\n\n async handleToolError(\n err: Error,\n runId: string,\n ): Promise<void> {\n const run = this.runMap.get(runId);\n if (!run) return;\n this.runMap.delete(runId);\n\n await this.vorim.emit({\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: run.tool,\n resource: truncate(run.input, 500),\n result: 'error',\n latency_ms: Date.now() - run.startTime,\n error_code: err.name,\n metadata: { error: err.message, framework: 'langchain' },\n }).catch(() => {});\n }\n\n // Required by BaseCallbackHandler — no-op for events we don't need\n copy(): VorimCallbackHandler {\n return new VorimCallbackHandler(this.vorim, this.agentId);\n }\n\n toJSON() {\n return { lc: 1, type: 'not_implemented', id: this.lc_id };\n }\n\n toJSONNotImplemented() {\n return this.toJSON();\n }\n}\n\n// ─── Agent Factory ────────────────────────────────────────────────────────\n\nexport interface CreateVorimAgentConfig extends VorimLangChainConfig {\n /** Display name for the agent when registering with Vorim. */\n name: string;\n /** Agent capabilities (e.g. [\"web_search\", \"code_execution\"]). */\n capabilities: string[];\n /** Initial permission scopes to grant. */\n scopes: PermissionScope[];\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Registers a new agent with Vorim and returns wrapped tools + callback handler\n * ready to use with `createReactAgent` or any LangChain agent.\n *\n * @example\n * ```ts\n * import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n * import { ChatOpenAI } from \"@langchain/openai\";\n * import { createVorimAgent } from \"@vorim/sdk/integrations/langchain\";\n *\n * const { agentId, tools, callbackHandler } = await createVorimAgent({\n * vorim,\n * name: \"research-agent\",\n * capabilities: [\"web_search\"],\n * scopes: [\"agent:read\", \"agent:execute\"],\n * tools: [searchTool, analysisTool],\n * });\n *\n * const agent = createReactAgent({\n * llm: new ChatOpenAI({ model: \"gpt-4o\" }),\n * tools,\n * });\n *\n * const result = await agent.invoke(\n * { messages: [{ role: \"user\", content: \"Research AI trends\" }] },\n * { callbacks: [callbackHandler] },\n * );\n * ```\n */\nexport async function createVorimAgent<T extends LangChainTool>(config: CreateVorimAgentConfig & { tools: T[] }) {\n const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;\n\n // Register agent with Vorim\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const agentConfig: VorimLangChainConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };\n\n // Wrap tools with permission checks\n const tools = wrapTools(rawTools, agentConfig);\n\n // Create callback handler for audit trail\n const callbackHandler = new VorimCallbackHandler(vorim, agentId);\n\n return {\n /** The Vorim agent_id. */\n agentId,\n /** The full agent registration result. */\n registration,\n /** Tools wrapped with Vorim permission checks + audit. */\n tools,\n /** Callback handler for audit trail observability. */\n callbackHandler,\n /** The private key (store securely — shown once). */\n privateKey: registration.private_key,\n };\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────\n\n/** Minimal interface matching any LangChain StructuredTool / DynamicStructuredTool. */\ninterface LangChainTool {\n name: string;\n description: string;\n schema: unknown;\n _call(arg: any, runManager?: any, parentConfig?: any): Promise<any>;\n}\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, async: boolean): void {\n if (async) {\n vorim.emit(event).catch(() => {});\n } else {\n vorim.emit(event).catch(() => {});\n }\n}\n"],"mappings":";AA4DO,SAAS,SACd,MACA,QACG;AACH,QAAM,EAAE,OAAO,SAAS,gBAAgB,CAAC,GAAG,oBAAoB,iBAAiB,aAAa,KAAK,IAAI;AAEvG,QAAM,eAAe,KAAK,MAAM,KAAK,IAAI;AAGzC,EAAC,KAAa,QAAQ,eAAe,iBACnC,KACA,YACA,cACkB;AAClB,UAAM,QAAQ,cAAc,KAAK,IAAI,KAAK;AAG1C,UAAM,EAAE,SAAS,OAAO,IAAI,MAAM,MAAM,MAAM,SAAS,KAAK;AAE5D,QAAI,CAAC,SAAS;AACZ,YAAMA,SAAyB;AAAA,QAC7B,UAAU;AAAA,QACV,YAAY;AAAA,QACZ,QAAQ,KAAK;AAAA,QACb,UAAU,SAAS,KAAK,UAAU,GAAG,GAAG,GAAG;AAAA,QAC3C,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,UAAU,EAAE,QAAQ,WAAW,YAAY;AAAA,MAC7C;AACA,gBAAU,OAAOA,QAAO,UAAU;AAClC,YAAM,IAAI,MAAM,iCAAiC,KAAK,IAAI,mBAAc,KAAK,IAAI,SAAS,KAAK,MAAM,KAAK,EAAE,EAAE;AAAA,IAChH;AAGA,UAAM,QAAQ,KAAK,IAAI;AACvB,QAAI;AACJ,QAAI;AACF,eAAS,MAAM,aAAa,KAAK,YAAY,YAAY;AAAA,IAC3D,SAAS,KAAK;AACZ,YAAMA,SAAyB;AAAA,QAC7B,UAAU;AAAA,QACV,YAAY;AAAA,QACZ,QAAQ,KAAK;AAAA,QACb,UAAU,SAAS,KAAK,UAAU,GAAG,GAAG,GAAG;AAAA,QAC3C,YAAY;AAAA,QACZ,QAAQ;AAAA,Q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AAsB,iBAA0C,QAAiD;AAC/G,QAAM,EAAE,OAAO,MAAM,cAAc,QAAQ,aAAa,OAAO,UAAU,eAAe,mBAAmB,WAAW,IAAI;AAG1H,QAAM,eAAe,MAAM,MAAM,SAAS;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,UAAU,aAAa,MAAM;AACnC,QAAM,cAAoC,EAAE,OAAO,SAAS,eAAe,mBAAmB,WAAW;AAGzG,QAAM,QAAQ,UAAU,UAAU,WAAW;AAG7C,QAAM,kBAAkB,IAAI,qBAAqB,OAAO,OAAO;AAE/D,SAAO;AAAA;AAAA,IAEL;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA,YAAY,aAAa;AAAA,EAC3B;AACF;AAYA,SAAS,SAAS,KAAa,KAAqB;AAClD,SAAO,IAAI,SAAS,MAAM,IAAI,MAAM,GAAG,GAAG,IAAI,WAAM;AACtD;AAEA,SAAS,UAAU,OAAiB,OAAwB,OAAsB;AAChF,MAAI,OAAO;AACT,UAAM,KAAK,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAClC,OAAO;AACL,UAAM,KAAK,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAClC;AACF;","names":["event"]}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/integrations/llamaindex.ts
|
|
21
|
+
var llamaindex_exports = {};
|
|
22
|
+
__export(llamaindex_exports, {
|
|
23
|
+
createVorimAgent: () => createVorimAgent,
|
|
24
|
+
emitLlamaIndexEvent: () => emitLlamaIndexEvent,
|
|
25
|
+
wrapTool: () => wrapTool,
|
|
26
|
+
wrapTools: () => wrapTools
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(llamaindex_exports);
|
|
29
|
+
function wrapTool(tool, config) {
|
|
30
|
+
const {
|
|
31
|
+
vorim,
|
|
32
|
+
agentId,
|
|
33
|
+
permissionMap = {},
|
|
34
|
+
defaultPermission = "agent:execute",
|
|
35
|
+
asyncAudit = true
|
|
36
|
+
} = config;
|
|
37
|
+
const originalCall = tool.call.bind(tool);
|
|
38
|
+
const toolName = tool.metadata.name;
|
|
39
|
+
const scope = permissionMap[toolName] ?? defaultPermission;
|
|
40
|
+
const wrapped = Object.create(Object.getPrototypeOf(tool), {
|
|
41
|
+
...Object.getOwnPropertyDescriptors(tool),
|
|
42
|
+
call: {
|
|
43
|
+
value: async function vorimGuardedCall(input) {
|
|
44
|
+
const { allowed, reason } = await vorim.check(agentId, scope);
|
|
45
|
+
if (!allowed) {
|
|
46
|
+
const event2 = {
|
|
47
|
+
agent_id: agentId,
|
|
48
|
+
event_type: "tool_call",
|
|
49
|
+
action: toolName,
|
|
50
|
+
resource: truncate(JSON.stringify(input), 500),
|
|
51
|
+
permission: scope,
|
|
52
|
+
result: "denied",
|
|
53
|
+
metadata: { reason, framework: "llamaindex" }
|
|
54
|
+
};
|
|
55
|
+
emitAudit(vorim, event2, asyncAudit);
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Vorim: permission denied for "${toolName}" \u2014 scope "${scope}"${reason ? `: ${reason}` : ""}`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
const start = Date.now();
|
|
61
|
+
let result;
|
|
62
|
+
try {
|
|
63
|
+
result = await originalCall(input);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
const event2 = {
|
|
66
|
+
agent_id: agentId,
|
|
67
|
+
event_type: "tool_call",
|
|
68
|
+
action: toolName,
|
|
69
|
+
resource: truncate(JSON.stringify(input), 500),
|
|
70
|
+
permission: scope,
|
|
71
|
+
result: "error",
|
|
72
|
+
latency_ms: Date.now() - start,
|
|
73
|
+
error_code: err instanceof Error ? err.name : "UNKNOWN",
|
|
74
|
+
metadata: {
|
|
75
|
+
error: err instanceof Error ? err.message : String(err),
|
|
76
|
+
framework: "llamaindex"
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
emitAudit(vorim, event2, asyncAudit);
|
|
80
|
+
throw err;
|
|
81
|
+
}
|
|
82
|
+
const event = {
|
|
83
|
+
agent_id: agentId,
|
|
84
|
+
event_type: "tool_call",
|
|
85
|
+
action: toolName,
|
|
86
|
+
resource: truncate(JSON.stringify(input), 500),
|
|
87
|
+
permission: scope,
|
|
88
|
+
result: "success",
|
|
89
|
+
latency_ms: Date.now() - start,
|
|
90
|
+
metadata: { framework: "llamaindex" }
|
|
91
|
+
};
|
|
92
|
+
emitAudit(vorim, event, asyncAudit);
|
|
93
|
+
return result;
|
|
94
|
+
},
|
|
95
|
+
writable: true,
|
|
96
|
+
configurable: true,
|
|
97
|
+
enumerable: true
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
return wrapped;
|
|
101
|
+
}
|
|
102
|
+
function wrapTools(tools, config) {
|
|
103
|
+
return tools.map((t) => wrapTool(t, config));
|
|
104
|
+
}
|
|
105
|
+
async function createVorimAgent(config) {
|
|
106
|
+
const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;
|
|
107
|
+
const registration = await vorim.register({
|
|
108
|
+
name,
|
|
109
|
+
description,
|
|
110
|
+
capabilities,
|
|
111
|
+
scopes
|
|
112
|
+
});
|
|
113
|
+
const agentId = registration.agent.agent_id;
|
|
114
|
+
const toolConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };
|
|
115
|
+
const tools = wrapTools(rawTools, toolConfig);
|
|
116
|
+
return {
|
|
117
|
+
/** The Vorim agent_id. */
|
|
118
|
+
agentId,
|
|
119
|
+
/** Full registration result. */
|
|
120
|
+
registration,
|
|
121
|
+
/** Tools wrapped with Vorim permission checks + audit. */
|
|
122
|
+
tools,
|
|
123
|
+
/** The private key (store securely — shown once). */
|
|
124
|
+
privateKey: registration.private_key
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
async function emitLlamaIndexEvent(vorim, agentId, event) {
|
|
128
|
+
await vorim.emit({
|
|
129
|
+
agent_id: agentId,
|
|
130
|
+
event_type: "api_request",
|
|
131
|
+
action: event.action,
|
|
132
|
+
resource: event.resource,
|
|
133
|
+
result: event.result,
|
|
134
|
+
latency_ms: event.latencyMs,
|
|
135
|
+
error_code: event.error ? "LLAMAINDEX_ERROR" : void 0,
|
|
136
|
+
metadata: {
|
|
137
|
+
framework: "llamaindex",
|
|
138
|
+
...event.error ? { error: event.error } : {},
|
|
139
|
+
...event.metadata
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function truncate(str, max) {
|
|
144
|
+
return str.length > max ? str.slice(0, max) + "\u2026" : str;
|
|
145
|
+
}
|
|
146
|
+
function emitAudit(vorim, event, async) {
|
|
147
|
+
if (async) {
|
|
148
|
+
vorim.emit(event).catch(() => {
|
|
149
|
+
});
|
|
150
|
+
} else {
|
|
151
|
+
vorim.emit(event).catch(() => {
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
156
|
+
0 && (module.exports = {
|
|
157
|
+
createVorimAgent,
|
|
158
|
+
emitLlamaIndexEvent,
|
|
159
|
+
wrapTool,
|
|
160
|
+
wrapTools
|
|
161
|
+
});
|
|
162
|
+
//# sourceMappingURL=llamaindex.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/llamaindex.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — LlamaIndex TS Integration\n// Wraps LlamaIndex tools with Vorim permission checks + audit trails.\n// Provides a tool wrapper and agent registration factory.\n//\n// Peer dependency: llamaindex >=0.4.0 (or @llamaindex/core)\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\n\n// ─── Re-declared LlamaIndex types (peer dependency — not bundled) ─────────\n// These mirror the actual interfaces from @llamaindex/core/llms and\n// @llamaindex/core/tools so consumers don't need to wrangle imports.\n\n/** Matches @llamaindex/core ToolMetadata */\ninterface ToolMetadata<P extends Record<string, unknown> = Record<string, unknown>> {\n name: string;\n description: string;\n parameters?: P;\n}\n\n/**\n * Matches @llamaindex/core BaseTool.\n * In LlamaIndex, `call` is optional on BaseTool but required on BaseToolWithCall.\n */\ninterface LlamaIndexTool<Input = any> {\n metadata: ToolMetadata;\n call: (input: Input) => any | Promise<any>;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimLlamaIndexConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id to associate. */\n agentId: string;\n /** Map tool names → Vorim permission scopes. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default permission scope for unmapped tools. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (fire-and-forget). @default true */\n asyncAudit?: boolean;\n}\n\n// ─── Tool Wrapper ─────────────────────────────────────────────────────────\n\n/**\n * Wraps a LlamaIndex tool (`BaseTool` / `BaseToolWithCall` / `FunctionTool`)\n * with Vorim permission checks before execution and audit event emission after.\n *\n * The wrapper implements the same `BaseTool` interface so it's a drop-in\n * replacement anywhere LlamaIndex expects a tool.\n *\n * @example\n * ```ts\n * import { FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { wrapTool } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(\n * async ({ query }: { query: string }) => `Results for: ${query}`,\n * { name: \"search\", description: \"Search documents\", parameters: { ... } }\n * );\n *\n * const guarded = wrapTool(searchTool, {\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * permissionMap: { search: \"agent:read\" },\n * });\n *\n * // Use with any LlamaIndex agent\n * const agent = new OpenAIAgent({ tools: [guarded] });\n * ```\n */\nexport function wrapTool<T extends LlamaIndexTool>(\n tool: T,\n config: VorimLlamaIndexConfig,\n): T {\n const {\n vorim, agentId,\n permissionMap = {},\n defaultPermission = 'agent:execute',\n asyncAudit = true,\n } = config;\n\n const originalCall = tool.call.bind(tool);\n const toolName = tool.metadata.name;\n const scope = permissionMap[toolName] ?? defaultPermission;\n\n // Create a new object that preserves the tool's prototype chain\n // and all properties, but overrides `call`\n const wrapped = Object.create(Object.getPrototypeOf(tool), {\n ...Object.getOwnPropertyDescriptors(tool),\n call: {\n value: async function vorimGuardedCall(input: any): Promise<any> {\n // 1. Permission check\n const { allowed, reason } = await vorim.check(agentId, scope);\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'denied',\n metadata: { reason, framework: 'llamaindex' },\n };\n emitAudit(vorim, event, asyncAudit);\n throw new Error(\n `Vorim: permission denied for \"${toolName}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`,\n );\n }\n\n // 2. Execute the original tool\n const start = Date.now();\n let result: any;\n try {\n result = await originalCall(input);\n } catch (err) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n metadata: {\n error: err instanceof Error ? err.message : String(err),\n framework: 'llamaindex',\n },\n };\n emitAudit(vorim, event, asyncAudit);\n throw err;\n }\n\n // 3. Audit success\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n metadata: { framework: 'llamaindex' },\n };\n emitAudit(vorim, event, asyncAudit);\n\n return result;\n },\n writable: true,\n configurable: true,\n enumerable: true,\n },\n }) as T;\n\n return wrapped;\n}\n\n/**\n * Wraps an array of LlamaIndex tools with Vorim permission + audit.\n */\nexport function wrapTools<T extends LlamaIndexTool>(\n tools: T[],\n config: VorimLlamaIndexConfig,\n): T[] {\n return tools.map(t => wrapTool(t, config));\n}\n\n// ─── Agent Factory ────────────────────────────────────────────────────────\n\nexport interface CreateVorimLlamaIndexAgentConfig extends VorimLlamaIndexConfig {\n /** Display name for the agent. */\n name: string;\n /** Agent capabilities. */\n capabilities: string[];\n /** Initial permission scopes. */\n scopes: PermissionScope[];\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Registers a new agent with Vorim and returns wrapped tools ready for\n * use with any LlamaIndex agent (OpenAIAgent, ReActAgent, etc.).\n *\n * @example\n * ```ts\n * import { OpenAIAgent, FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { createVorimAgent } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(...);\n * const writeTool = FunctionTool.from(...);\n *\n * const { agentId, tools } = await createVorimAgent({\n * vorim,\n * name: \"research-agent\",\n * capabilities: [\"search\", \"write\"],\n * scopes: [\"agent:read\", \"agent:write\", \"agent:execute\"],\n * tools: [searchTool, writeTool],\n * permissionMap: {\n * search: \"agent:read\",\n * write: \"agent:write\",\n * },\n * });\n *\n * // Create LlamaIndex agent with Vorim-wrapped tools\n * const agent = new OpenAIAgent({ tools });\n * const response = await agent.chat({ message: \"Research AI trends\" });\n * ```\n */\nexport async function createVorimAgent<T extends LlamaIndexTool>(\n config: CreateVorimLlamaIndexAgentConfig & { tools: T[] },\n) {\n const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;\n\n // Register agent with Vorim\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const toolConfig: VorimLlamaIndexConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };\n\n // Wrap tools with permission checks\n const tools = wrapTools(rawTools, toolConfig);\n\n return {\n /** The Vorim agent_id. */\n agentId,\n /** Full registration result. */\n registration,\n /** Tools wrapped with Vorim permission checks + audit. */\n tools,\n /** The private key (store securely — shown once). */\n privateKey: registration.private_key,\n };\n}\n\n// ─── Audit Helpers ────────────────────────────────────────────────────────\n\n/**\n * Emit a manual audit event for a LlamaIndex agent action that isn't\n * captured by the tool wrapper (e.g. RAG retrieval, chat responses).\n */\nexport async function emitLlamaIndexEvent(\n vorim: VorimSDK,\n agentId: string,\n event: {\n action: string;\n resource?: string;\n result: 'success' | 'denied' | 'error';\n latencyMs?: number;\n error?: string;\n metadata?: Record<string, unknown>;\n },\n): Promise<void> {\n await vorim.emit({\n agent_id: agentId,\n event_type: 'api_request',\n action: event.action,\n resource: event.resource,\n result: event.result,\n latency_ms: event.latencyMs,\n error_code: event.error ? 'LLAMAINDEX_ERROR' : undefined,\n metadata: {\n framework: 'llamaindex',\n ...(event.error ? { error: event.error } : {}),\n ...event.metadata,\n },\n });\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, async: boolean): void {\n if (async) {\n vorim.emit(event).catch(() => {});\n } else {\n vorim.emit(event).catch(() => {});\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8EO,SAAS,SACd,MACA,QACG;AACH,QAAM;AAAA,IACJ;AAAA,IAAO;AAAA,IACP,gBAAgB,CAAC;AAAA,IACjB,oBAAoB;AAAA,IACpB,aAAa;AAAA,EACf,IAAI;AAEJ,QAAM,eAAe,KAAK,KAAK,KAAK,IAAI;AACxC,QAAM,WAAW,KAAK,SAAS;AAC/B,QAAM,QAAQ,cAAc,QAAQ,KAAK;AAIzC,QAAM,UAAU,OAAO,OAAO,OAAO,eAAe,IAAI,GAAG;AAAA,IACzD,GAAG,OAAO,0BAA0B,IAAI;AAAA,IACxC,MAAM;AAAA,MACJ,OAAO,eAAe,iBAAiB,OAA0B;AAE/D,cAAM,EAAE,SAAS,OAAO,IAAI,MAAM,MAAM,MAAM,SAAS,KAAK;AAE5D,YAAI,CAAC,SAAS;AACZ,gBAAMA,SAAyB;AAAA,YAC7B,UAAU;AAAA,YACV,YAAY;AAAA,YACZ,QAAQ;AAAA,YACR,UAAU,SAAS,KAAK,UAAU,KAAK,GAAG,GAAG;AAAA,YAC7C,YAAY;AAAA,YACZ,QAAQ;AAAA,YACR,UAAU,EAAE,QAAQ,WAAW,aAAa;AAAA,UAC9C;AACA,oBAAU,OAAOA,QAAO,UAAU;AAClC,gBAAM,IAAI;AAAA,YACR,iCAAiC,QAAQ,mBAAc,KAAK,IAAI,SAAS,KAAK,MAAM,KAAK,EAAE;AAAA,UAC7F;AAAA,QACF;AAGA,cAAM,QAAQ,KAAK,IAAI;AACvB,YAAI;AACJ,YAAI;AACF,mBAAS,MAAM,aAAa,KAAK;AAAA,QACnC,SAAS,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U,UAAU;AAE5C,SAAO;AAAA;AAAA,IAEL;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA,YAAY,aAAa;AAAA,EAC3B;AACF;AAQA,eAAsB,oBACpB,OACA,SACA,OAQe;AACf,QAAM,MAAM,KAAK;AAAA,IACf,UAAU;AAAA,IACV,YAAY;AAAA,IACZ,QAAQ,MAAM;AAAA,IACd,UAAU,MAAM;AAAA,IAChB,QAAQ,MAAM;AAAA,IACd,YAAY,MAAM;AAAA,IAClB,YAAY,MAAM,QAAQ,qBAAqB;AAAA,IAC/C,UAAU;AAAA,MACR,WAAW;AAAA,MACX,GAAI,MAAM,QAAQ,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;AAAA,MAC5C,GAAG,MAAM;AAAA,IACX;AAAA,EACF,CAAC;AACH;AAIA,SAAS,SAAS,KAAa,KAAqB;AAClD,SAAO,IAAI,SAAS,MAAM,IAAI,MAAM,GAAG,GAAG,IAAI,WAAM;AACtD;AAEA,SAAS,UAAU,OAAiB,OAAwB,OAAsB;AAChF,MAAI,OAAO;AACT,UAAM,KAAK,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAClC,OAAO;AACL,UAAM,KAAK,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAClC;AACF;","names":["event"]}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { VorimSDK, PermissionScope, AgentRegistrationResult } from '../index.cjs';
|
|
2
|
+
|
|
3
|
+
/** Matches @llamaindex/core ToolMetadata */
|
|
4
|
+
interface ToolMetadata<P extends Record<string, unknown> = Record<string, unknown>> {
|
|
5
|
+
name: string;
|
|
6
|
+
description: string;
|
|
7
|
+
parameters?: P;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Matches @llamaindex/core BaseTool.
|
|
11
|
+
* In LlamaIndex, `call` is optional on BaseTool but required on BaseToolWithCall.
|
|
12
|
+
*/
|
|
13
|
+
interface LlamaIndexTool<Input = any> {
|
|
14
|
+
metadata: ToolMetadata;
|
|
15
|
+
call: (input: Input) => any | Promise<any>;
|
|
16
|
+
}
|
|
17
|
+
interface VorimLlamaIndexConfig {
|
|
18
|
+
/** Vorim SDK instance. */
|
|
19
|
+
vorim: VorimSDK;
|
|
20
|
+
/** The Vorim agent_id to associate. */
|
|
21
|
+
agentId: string;
|
|
22
|
+
/** Map tool names → Vorim permission scopes. */
|
|
23
|
+
permissionMap?: Record<string, PermissionScope>;
|
|
24
|
+
/** Default permission scope for unmapped tools. @default 'agent:execute' */
|
|
25
|
+
defaultPermission?: PermissionScope;
|
|
26
|
+
/** Whether to emit audit events asynchronously (fire-and-forget). @default true */
|
|
27
|
+
asyncAudit?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Wraps a LlamaIndex tool (`BaseTool` / `BaseToolWithCall` / `FunctionTool`)
|
|
31
|
+
* with Vorim permission checks before execution and audit event emission after.
|
|
32
|
+
*
|
|
33
|
+
* The wrapper implements the same `BaseTool` interface so it's a drop-in
|
|
34
|
+
* replacement anywhere LlamaIndex expects a tool.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* import { FunctionTool } from "llamaindex";
|
|
39
|
+
* import createVorim from "@vorim/sdk";
|
|
40
|
+
* import { wrapTool } from "@vorim/sdk/integrations/llamaindex";
|
|
41
|
+
*
|
|
42
|
+
* const vorim = createVorim({ apiKey: "agid_sk_live_..." });
|
|
43
|
+
*
|
|
44
|
+
* const searchTool = FunctionTool.from(
|
|
45
|
+
* async ({ query }: { query: string }) => `Results for: ${query}`,
|
|
46
|
+
* { name: "search", description: "Search documents", parameters: { ... } }
|
|
47
|
+
* );
|
|
48
|
+
*
|
|
49
|
+
* const guarded = wrapTool(searchTool, {
|
|
50
|
+
* vorim,
|
|
51
|
+
* agentId: "agid_acme_a1b2c3d4",
|
|
52
|
+
* permissionMap: { search: "agent:read" },
|
|
53
|
+
* });
|
|
54
|
+
*
|
|
55
|
+
* // Use with any LlamaIndex agent
|
|
56
|
+
* const agent = new OpenAIAgent({ tools: [guarded] });
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
declare function wrapTool<T extends LlamaIndexTool>(tool: T, config: VorimLlamaIndexConfig): T;
|
|
60
|
+
/**
|
|
61
|
+
* Wraps an array of LlamaIndex tools with Vorim permission + audit.
|
|
62
|
+
*/
|
|
63
|
+
declare function wrapTools<T extends LlamaIndexTool>(tools: T[], config: VorimLlamaIndexConfig): T[];
|
|
64
|
+
interface CreateVorimLlamaIndexAgentConfig extends VorimLlamaIndexConfig {
|
|
65
|
+
/** Display name for the agent. */
|
|
66
|
+
name: string;
|
|
67
|
+
/** Agent capabilities. */
|
|
68
|
+
capabilities: string[];
|
|
69
|
+
/** Initial permission scopes. */
|
|
70
|
+
scopes: PermissionScope[];
|
|
71
|
+
/** Optional description. */
|
|
72
|
+
description?: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Registers a new agent with Vorim and returns wrapped tools ready for
|
|
76
|
+
* use with any LlamaIndex agent (OpenAIAgent, ReActAgent, etc.).
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* import { OpenAIAgent, FunctionTool } from "llamaindex";
|
|
81
|
+
* import createVorim from "@vorim/sdk";
|
|
82
|
+
* import { createVorimAgent } from "@vorim/sdk/integrations/llamaindex";
|
|
83
|
+
*
|
|
84
|
+
* const vorim = createVorim({ apiKey: "agid_sk_live_..." });
|
|
85
|
+
*
|
|
86
|
+
* const searchTool = FunctionTool.from(...);
|
|
87
|
+
* const writeTool = FunctionTool.from(...);
|
|
88
|
+
*
|
|
89
|
+
* const { agentId, tools } = await createVorimAgent({
|
|
90
|
+
* vorim,
|
|
91
|
+
* name: "research-agent",
|
|
92
|
+
* capabilities: ["search", "write"],
|
|
93
|
+
* scopes: ["agent:read", "agent:write", "agent:execute"],
|
|
94
|
+
* tools: [searchTool, writeTool],
|
|
95
|
+
* permissionMap: {
|
|
96
|
+
* search: "agent:read",
|
|
97
|
+
* write: "agent:write",
|
|
98
|
+
* },
|
|
99
|
+
* });
|
|
100
|
+
*
|
|
101
|
+
* // Create LlamaIndex agent with Vorim-wrapped tools
|
|
102
|
+
* const agent = new OpenAIAgent({ tools });
|
|
103
|
+
* const response = await agent.chat({ message: "Research AI trends" });
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
declare function createVorimAgent<T extends LlamaIndexTool>(config: CreateVorimLlamaIndexAgentConfig & {
|
|
107
|
+
tools: T[];
|
|
108
|
+
}): Promise<{
|
|
109
|
+
/** The Vorim agent_id. */
|
|
110
|
+
agentId: string;
|
|
111
|
+
/** Full registration result. */
|
|
112
|
+
registration: AgentRegistrationResult;
|
|
113
|
+
/** Tools wrapped with Vorim permission checks + audit. */
|
|
114
|
+
tools: T[];
|
|
115
|
+
/** The private key (store securely — shown once). */
|
|
116
|
+
privateKey: string;
|
|
117
|
+
}>;
|
|
118
|
+
/**
|
|
119
|
+
* Emit a manual audit event for a LlamaIndex agent action that isn't
|
|
120
|
+
* captured by the tool wrapper (e.g. RAG retrieval, chat responses).
|
|
121
|
+
*/
|
|
122
|
+
declare function emitLlamaIndexEvent(vorim: VorimSDK, agentId: string, event: {
|
|
123
|
+
action: string;
|
|
124
|
+
resource?: string;
|
|
125
|
+
result: 'success' | 'denied' | 'error';
|
|
126
|
+
latencyMs?: number;
|
|
127
|
+
error?: string;
|
|
128
|
+
metadata?: Record<string, unknown>;
|
|
129
|
+
}): Promise<void>;
|
|
130
|
+
|
|
131
|
+
export { type CreateVorimLlamaIndexAgentConfig, type VorimLlamaIndexConfig, createVorimAgent, emitLlamaIndexEvent, wrapTool, wrapTools };
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { VorimSDK, PermissionScope, AgentRegistrationResult } from '../index.js';
|
|
2
|
+
|
|
3
|
+
/** Matches @llamaindex/core ToolMetadata */
|
|
4
|
+
interface ToolMetadata<P extends Record<string, unknown> = Record<string, unknown>> {
|
|
5
|
+
name: string;
|
|
6
|
+
description: string;
|
|
7
|
+
parameters?: P;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Matches @llamaindex/core BaseTool.
|
|
11
|
+
* In LlamaIndex, `call` is optional on BaseTool but required on BaseToolWithCall.
|
|
12
|
+
*/
|
|
13
|
+
interface LlamaIndexTool<Input = any> {
|
|
14
|
+
metadata: ToolMetadata;
|
|
15
|
+
call: (input: Input) => any | Promise<any>;
|
|
16
|
+
}
|
|
17
|
+
interface VorimLlamaIndexConfig {
|
|
18
|
+
/** Vorim SDK instance. */
|
|
19
|
+
vorim: VorimSDK;
|
|
20
|
+
/** The Vorim agent_id to associate. */
|
|
21
|
+
agentId: string;
|
|
22
|
+
/** Map tool names → Vorim permission scopes. */
|
|
23
|
+
permissionMap?: Record<string, PermissionScope>;
|
|
24
|
+
/** Default permission scope for unmapped tools. @default 'agent:execute' */
|
|
25
|
+
defaultPermission?: PermissionScope;
|
|
26
|
+
/** Whether to emit audit events asynchronously (fire-and-forget). @default true */
|
|
27
|
+
asyncAudit?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Wraps a LlamaIndex tool (`BaseTool` / `BaseToolWithCall` / `FunctionTool`)
|
|
31
|
+
* with Vorim permission checks before execution and audit event emission after.
|
|
32
|
+
*
|
|
33
|
+
* The wrapper implements the same `BaseTool` interface so it's a drop-in
|
|
34
|
+
* replacement anywhere LlamaIndex expects a tool.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* import { FunctionTool } from "llamaindex";
|
|
39
|
+
* import createVorim from "@vorim/sdk";
|
|
40
|
+
* import { wrapTool } from "@vorim/sdk/integrations/llamaindex";
|
|
41
|
+
*
|
|
42
|
+
* const vorim = createVorim({ apiKey: "agid_sk_live_..." });
|
|
43
|
+
*
|
|
44
|
+
* const searchTool = FunctionTool.from(
|
|
45
|
+
* async ({ query }: { query: string }) => `Results for: ${query}`,
|
|
46
|
+
* { name: "search", description: "Search documents", parameters: { ... } }
|
|
47
|
+
* );
|
|
48
|
+
*
|
|
49
|
+
* const guarded = wrapTool(searchTool, {
|
|
50
|
+
* vorim,
|
|
51
|
+
* agentId: "agid_acme_a1b2c3d4",
|
|
52
|
+
* permissionMap: { search: "agent:read" },
|
|
53
|
+
* });
|
|
54
|
+
*
|
|
55
|
+
* // Use with any LlamaIndex agent
|
|
56
|
+
* const agent = new OpenAIAgent({ tools: [guarded] });
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
declare function wrapTool<T extends LlamaIndexTool>(tool: T, config: VorimLlamaIndexConfig): T;
|
|
60
|
+
/**
|
|
61
|
+
* Wraps an array of LlamaIndex tools with Vorim permission + audit.
|
|
62
|
+
*/
|
|
63
|
+
declare function wrapTools<T extends LlamaIndexTool>(tools: T[], config: VorimLlamaIndexConfig): T[];
|
|
64
|
+
interface CreateVorimLlamaIndexAgentConfig extends VorimLlamaIndexConfig {
|
|
65
|
+
/** Display name for the agent. */
|
|
66
|
+
name: string;
|
|
67
|
+
/** Agent capabilities. */
|
|
68
|
+
capabilities: string[];
|
|
69
|
+
/** Initial permission scopes. */
|
|
70
|
+
scopes: PermissionScope[];
|
|
71
|
+
/** Optional description. */
|
|
72
|
+
description?: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Registers a new agent with Vorim and returns wrapped tools ready for
|
|
76
|
+
* use with any LlamaIndex agent (OpenAIAgent, ReActAgent, etc.).
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* import { OpenAIAgent, FunctionTool } from "llamaindex";
|
|
81
|
+
* import createVorim from "@vorim/sdk";
|
|
82
|
+
* import { createVorimAgent } from "@vorim/sdk/integrations/llamaindex";
|
|
83
|
+
*
|
|
84
|
+
* const vorim = createVorim({ apiKey: "agid_sk_live_..." });
|
|
85
|
+
*
|
|
86
|
+
* const searchTool = FunctionTool.from(...);
|
|
87
|
+
* const writeTool = FunctionTool.from(...);
|
|
88
|
+
*
|
|
89
|
+
* const { agentId, tools } = await createVorimAgent({
|
|
90
|
+
* vorim,
|
|
91
|
+
* name: "research-agent",
|
|
92
|
+
* capabilities: ["search", "write"],
|
|
93
|
+
* scopes: ["agent:read", "agent:write", "agent:execute"],
|
|
94
|
+
* tools: [searchTool, writeTool],
|
|
95
|
+
* permissionMap: {
|
|
96
|
+
* search: "agent:read",
|
|
97
|
+
* write: "agent:write",
|
|
98
|
+
* },
|
|
99
|
+
* });
|
|
100
|
+
*
|
|
101
|
+
* // Create LlamaIndex agent with Vorim-wrapped tools
|
|
102
|
+
* const agent = new OpenAIAgent({ tools });
|
|
103
|
+
* const response = await agent.chat({ message: "Research AI trends" });
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
declare function createVorimAgent<T extends LlamaIndexTool>(config: CreateVorimLlamaIndexAgentConfig & {
|
|
107
|
+
tools: T[];
|
|
108
|
+
}): Promise<{
|
|
109
|
+
/** The Vorim agent_id. */
|
|
110
|
+
agentId: string;
|
|
111
|
+
/** Full registration result. */
|
|
112
|
+
registration: AgentRegistrationResult;
|
|
113
|
+
/** Tools wrapped with Vorim permission checks + audit. */
|
|
114
|
+
tools: T[];
|
|
115
|
+
/** The private key (store securely — shown once). */
|
|
116
|
+
privateKey: string;
|
|
117
|
+
}>;
|
|
118
|
+
/**
|
|
119
|
+
* Emit a manual audit event for a LlamaIndex agent action that isn't
|
|
120
|
+
* captured by the tool wrapper (e.g. RAG retrieval, chat responses).
|
|
121
|
+
*/
|
|
122
|
+
declare function emitLlamaIndexEvent(vorim: VorimSDK, agentId: string, event: {
|
|
123
|
+
action: string;
|
|
124
|
+
resource?: string;
|
|
125
|
+
result: 'success' | 'denied' | 'error';
|
|
126
|
+
latencyMs?: number;
|
|
127
|
+
error?: string;
|
|
128
|
+
metadata?: Record<string, unknown>;
|
|
129
|
+
}): Promise<void>;
|
|
130
|
+
|
|
131
|
+
export { type CreateVorimLlamaIndexAgentConfig, type VorimLlamaIndexConfig, createVorimAgent, emitLlamaIndexEvent, wrapTool, wrapTools };
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// src/integrations/llamaindex.ts
|
|
2
|
+
function wrapTool(tool, config) {
|
|
3
|
+
const {
|
|
4
|
+
vorim,
|
|
5
|
+
agentId,
|
|
6
|
+
permissionMap = {},
|
|
7
|
+
defaultPermission = "agent:execute",
|
|
8
|
+
asyncAudit = true
|
|
9
|
+
} = config;
|
|
10
|
+
const originalCall = tool.call.bind(tool);
|
|
11
|
+
const toolName = tool.metadata.name;
|
|
12
|
+
const scope = permissionMap[toolName] ?? defaultPermission;
|
|
13
|
+
const wrapped = Object.create(Object.getPrototypeOf(tool), {
|
|
14
|
+
...Object.getOwnPropertyDescriptors(tool),
|
|
15
|
+
call: {
|
|
16
|
+
value: async function vorimGuardedCall(input) {
|
|
17
|
+
const { allowed, reason } = await vorim.check(agentId, scope);
|
|
18
|
+
if (!allowed) {
|
|
19
|
+
const event2 = {
|
|
20
|
+
agent_id: agentId,
|
|
21
|
+
event_type: "tool_call",
|
|
22
|
+
action: toolName,
|
|
23
|
+
resource: truncate(JSON.stringify(input), 500),
|
|
24
|
+
permission: scope,
|
|
25
|
+
result: "denied",
|
|
26
|
+
metadata: { reason, framework: "llamaindex" }
|
|
27
|
+
};
|
|
28
|
+
emitAudit(vorim, event2, asyncAudit);
|
|
29
|
+
throw new Error(
|
|
30
|
+
`Vorim: permission denied for "${toolName}" \u2014 scope "${scope}"${reason ? `: ${reason}` : ""}`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const start = Date.now();
|
|
34
|
+
let result;
|
|
35
|
+
try {
|
|
36
|
+
result = await originalCall(input);
|
|
37
|
+
} catch (err) {
|
|
38
|
+
const event2 = {
|
|
39
|
+
agent_id: agentId,
|
|
40
|
+
event_type: "tool_call",
|
|
41
|
+
action: toolName,
|
|
42
|
+
resource: truncate(JSON.stringify(input), 500),
|
|
43
|
+
permission: scope,
|
|
44
|
+
result: "error",
|
|
45
|
+
latency_ms: Date.now() - start,
|
|
46
|
+
error_code: err instanceof Error ? err.name : "UNKNOWN",
|
|
47
|
+
metadata: {
|
|
48
|
+
error: err instanceof Error ? err.message : String(err),
|
|
49
|
+
framework: "llamaindex"
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
emitAudit(vorim, event2, asyncAudit);
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
const event = {
|
|
56
|
+
agent_id: agentId,
|
|
57
|
+
event_type: "tool_call",
|
|
58
|
+
action: toolName,
|
|
59
|
+
resource: truncate(JSON.stringify(input), 500),
|
|
60
|
+
permission: scope,
|
|
61
|
+
result: "success",
|
|
62
|
+
latency_ms: Date.now() - start,
|
|
63
|
+
metadata: { framework: "llamaindex" }
|
|
64
|
+
};
|
|
65
|
+
emitAudit(vorim, event, asyncAudit);
|
|
66
|
+
return result;
|
|
67
|
+
},
|
|
68
|
+
writable: true,
|
|
69
|
+
configurable: true,
|
|
70
|
+
enumerable: true
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
return wrapped;
|
|
74
|
+
}
|
|
75
|
+
function wrapTools(tools, config) {
|
|
76
|
+
return tools.map((t) => wrapTool(t, config));
|
|
77
|
+
}
|
|
78
|
+
async function createVorimAgent(config) {
|
|
79
|
+
const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;
|
|
80
|
+
const registration = await vorim.register({
|
|
81
|
+
name,
|
|
82
|
+
description,
|
|
83
|
+
capabilities,
|
|
84
|
+
scopes
|
|
85
|
+
});
|
|
86
|
+
const agentId = registration.agent.agent_id;
|
|
87
|
+
const toolConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };
|
|
88
|
+
const tools = wrapTools(rawTools, toolConfig);
|
|
89
|
+
return {
|
|
90
|
+
/** The Vorim agent_id. */
|
|
91
|
+
agentId,
|
|
92
|
+
/** Full registration result. */
|
|
93
|
+
registration,
|
|
94
|
+
/** Tools wrapped with Vorim permission checks + audit. */
|
|
95
|
+
tools,
|
|
96
|
+
/** The private key (store securely — shown once). */
|
|
97
|
+
privateKey: registration.private_key
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
async function emitLlamaIndexEvent(vorim, agentId, event) {
|
|
101
|
+
await vorim.emit({
|
|
102
|
+
agent_id: agentId,
|
|
103
|
+
event_type: "api_request",
|
|
104
|
+
action: event.action,
|
|
105
|
+
resource: event.resource,
|
|
106
|
+
result: event.result,
|
|
107
|
+
latency_ms: event.latencyMs,
|
|
108
|
+
error_code: event.error ? "LLAMAINDEX_ERROR" : void 0,
|
|
109
|
+
metadata: {
|
|
110
|
+
framework: "llamaindex",
|
|
111
|
+
...event.error ? { error: event.error } : {},
|
|
112
|
+
...event.metadata
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
function truncate(str, max) {
|
|
117
|
+
return str.length > max ? str.slice(0, max) + "\u2026" : str;
|
|
118
|
+
}
|
|
119
|
+
function emitAudit(vorim, event, async) {
|
|
120
|
+
if (async) {
|
|
121
|
+
vorim.emit(event).catch(() => {
|
|
122
|
+
});
|
|
123
|
+
} else {
|
|
124
|
+
vorim.emit(event).catch(() => {
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export {
|
|
129
|
+
createVorimAgent,
|
|
130
|
+
emitLlamaIndexEvent,
|
|
131
|
+
wrapTool,
|
|
132
|
+
wrapTools
|
|
133
|
+
};
|
|
134
|
+
//# sourceMappingURL=llamaindex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/llamaindex.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — LlamaIndex TS Integration\n// Wraps LlamaIndex tools with Vorim permission checks + audit trails.\n// Provides a tool wrapper and agent registration factory.\n//\n// Peer dependency: llamaindex >=0.4.0 (or @llamaindex/core)\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\n\n// ─── Re-declared LlamaIndex types (peer dependency — not bundled) ─────────\n// These mirror the actual interfaces from @llamaindex/core/llms and\n// @llamaindex/core/tools so consumers don't need to wrangle imports.\n\n/** Matches @llamaindex/core ToolMetadata */\ninterface ToolMetadata<P extends Record<string, unknown> = Record<string, unknown>> {\n name: string;\n description: string;\n parameters?: P;\n}\n\n/**\n * Matches @llamaindex/core BaseTool.\n * In LlamaIndex, `call` is optional on BaseTool but required on BaseToolWithCall.\n */\ninterface LlamaIndexTool<Input = any> {\n metadata: ToolMetadata;\n call: (input: Input) => any | Promise<any>;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimLlamaIndexConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id to associate. */\n agentId: string;\n /** Map tool names → Vorim permission scopes. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default permission scope for unmapped tools. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (fire-and-forget). @default true */\n asyncAudit?: boolean;\n}\n\n// ─── Tool Wrapper ─────────────────────────────────────────────────────────\n\n/**\n * Wraps a LlamaIndex tool (`BaseTool` / `BaseToolWithCall` / `FunctionTool`)\n * with Vorim permission checks before execution and audit event emission after.\n *\n * The wrapper implements the same `BaseTool` interface so it's a drop-in\n * replacement anywhere LlamaIndex expects a tool.\n *\n * @example\n * ```ts\n * import { FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { wrapTool } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(\n * async ({ query }: { query: string }) => `Results for: ${query}`,\n * { name: \"search\", description: \"Search documents\", parameters: { ... } }\n * );\n *\n * const guarded = wrapTool(searchTool, {\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * permissionMap: { search: \"agent:read\" },\n * });\n *\n * // Use with any LlamaIndex agent\n * const agent = new OpenAIAgent({ tools: [guarded] });\n * ```\n */\nexport function wrapTool<T extends LlamaIndexTool>(\n tool: T,\n config: VorimLlamaIndexConfig,\n): T {\n const {\n vorim, agentId,\n permissionMap = {},\n defaultPermission = 'agent:execute',\n asyncAudit = true,\n } = config;\n\n const originalCall = tool.call.bind(tool);\n const toolName = tool.metadata.name;\n const scope = permissionMap[toolName] ?? defaultPermission;\n\n // Create a new object that preserves the tool's prototype chain\n // and all properties, but overrides `call`\n const wrapped = Object.create(Object.getPrototypeOf(tool), {\n ...Object.getOwnPropertyDescriptors(tool),\n call: {\n value: async function vorimGuardedCall(input: any): Promise<any> {\n // 1. Permission check\n const { allowed, reason } = await vorim.check(agentId, scope);\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'denied',\n metadata: { reason, framework: 'llamaindex' },\n };\n emitAudit(vorim, event, asyncAudit);\n throw new Error(\n `Vorim: permission denied for \"${toolName}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`,\n );\n }\n\n // 2. Execute the original tool\n const start = Date.now();\n let result: any;\n try {\n result = await originalCall(input);\n } catch (err) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n metadata: {\n error: err instanceof Error ? err.message : String(err),\n framework: 'llamaindex',\n },\n };\n emitAudit(vorim, event, asyncAudit);\n throw err;\n }\n\n // 3. Audit success\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n metadata: { framework: 'llamaindex' },\n };\n emitAudit(vorim, event, asyncAudit);\n\n return result;\n },\n writable: true,\n configurable: true,\n enumerable: true,\n },\n }) as T;\n\n return wrapped;\n}\n\n/**\n * Wraps an array of LlamaIndex tools with Vorim permission + audit.\n */\nexport function wrapTools<T extends LlamaIndexTool>(\n tools: T[],\n config: VorimLlamaIndexConfig,\n): T[] {\n return tools.map(t => wrapTool(t, config));\n}\n\n// ─── Agent Factory ────────────────────────────────────────────────────────\n\nexport interface CreateVorimLlamaIndexAgentConfig extends VorimLlamaIndexConfig {\n /** Display name for the agent. */\n name: string;\n /** Agent capabilities. */\n capabilities: string[];\n /** Initial permission scopes. */\n scopes: PermissionScope[];\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Registers a new agent with Vorim and returns wrapped tools ready for\n * use with any LlamaIndex agent (OpenAIAgent, ReActAgent, etc.).\n *\n * @example\n * ```ts\n * import { OpenAIAgent, FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { createVorimAgent } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(...);\n * const writeTool = FunctionTool.from(...);\n *\n * const { agentId, tools } = await createVorimAgent({\n * vorim,\n * name: \"research-agent\",\n * capabilities: [\"search\", \"write\"],\n * scopes: [\"agent:read\", \"agent:write\", \"agent:execute\"],\n * tools: [searchTool, writeTool],\n * permissionMap: {\n * search: \"agent:read\",\n * write: \"agent:write\",\n * },\n * });\n *\n * // Create LlamaIndex agent with Vorim-wrapped tools\n * const agent = new OpenAIAgent({ tools });\n * const response = await agent.chat({ message: \"Research AI trends\" });\n * ```\n */\nexport async function createVorimAgent<T extends LlamaIndexTool>(\n config: CreateVorimLlamaIndexAgentConfig & { tools: T[] },\n) {\n const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;\n\n // Register agent with Vorim\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const toolConfig: VorimLlamaIndexConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };\n\n // Wrap tools with permission checks\n const tools = wrapTools(rawTools, toolConfig);\n\n return {\n /** The Vorim agent_id. */\n agentId,\n /** Full registration result. */\n registration,\n /** Tools wrapped with Vorim permission checks + audit. */\n tools,\n /** The private key (store securely — shown once). */\n privateKey: registration.private_key,\n };\n}\n\n// ─── Audit Helpers ────────────────────────────────────────────────────────\n\n/**\n * Emit a manual audit event for a LlamaIndex agent action that isn't\n * captured by the tool wrapper (e.g. RAG retrieval, chat responses).\n */\nexport async function emitLlamaIndexEvent(\n vorim: VorimSDK,\n agentId: string,\n event: {\n action: string;\n resource?: string;\n result: 'success' | 'denied' | 'error';\n latencyMs?: number;\n error?: string;\n metadata?: Record<string, unknown>;\n },\n): Promise<void> {\n await vorim.emit({\n agent_id: agentId,\n event_type: 'api_request',\n action: event.action,\n resource: event.resource,\n result: event.result,\n latency_ms: event.latencyMs,\n error_code: event.error ? 'LLAMAINDEX_ERROR' : undefined,\n metadata: {\n framework: 'llamaindex',\n ...(event.error ? { error: event.error } : {}),\n ...event.metadata,\n },\n });\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, async: boolean): void {\n if (async) {\n vorim.emit(event).catch(() => {});\n } else {\n vorim.emit(event).catch(() => {});\n }\n}\n"],"mappings":";AA8EO,SAAS,SACd,MACA,QACG;AACH,QAAM;AAAA,IACJ;AAAA,IAAO;AAAA,IACP,gBAAgB,CAAC;AAAA,IACjB,oBAAoB;AAAA,IACpB,aAAa;AAAA,EACf,IAAI;AAEJ,QAAM,eAAe,KAAK,KAAK,KAAK,IAAI;AACxC,QAAM,WAAW,KAAK,SAAS;AAC/B,QAAM,QAAQ,cAAc,QA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