@vorim/sdk 1.0.1 → 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.
@@ -0,0 +1,208 @@
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/openai.ts
21
+ var openai_exports = {};
22
+ __export(openai_exports, {
23
+ VorimToolRegistry: () => VorimToolRegistry,
24
+ createVorimOpenAIAgent: () => createVorimOpenAIAgent,
25
+ runAgentLoop: () => runAgentLoop
26
+ });
27
+ module.exports = __toCommonJS(openai_exports);
28
+ var VorimToolRegistry = class {
29
+ vorim;
30
+ agentId;
31
+ defaultPermission;
32
+ asyncAudit;
33
+ tools = /* @__PURE__ */ new Map();
34
+ constructor(config) {
35
+ this.vorim = config.vorim;
36
+ this.agentId = config.agentId;
37
+ this.defaultPermission = config.defaultPermission ?? "agent:execute";
38
+ this.asyncAudit = config.asyncAudit ?? true;
39
+ }
40
+ /** Register a tool. */
41
+ add(definition) {
42
+ this.tools.set(definition.name, definition);
43
+ return this;
44
+ }
45
+ /** Register multiple tools. */
46
+ addAll(definitions) {
47
+ for (const def of definitions) this.add(def);
48
+ return this;
49
+ }
50
+ /** Convert registered tools to OpenAI's ChatCompletionTool format. */
51
+ toOpenAITools() {
52
+ return [...this.tools.values()].map((t) => ({
53
+ type: "function",
54
+ function: {
55
+ name: t.name,
56
+ description: t.description,
57
+ parameters: t.parameters,
58
+ ...t.strict != null ? { strict: t.strict } : {}
59
+ }
60
+ }));
61
+ }
62
+ /**
63
+ * Execute tool calls from an OpenAI chat completion response.
64
+ * Each call is checked against Vorim permissions and audited.
65
+ * Returns an array of tool messages ready to append to the conversation.
66
+ */
67
+ async executeToolCalls(toolCalls) {
68
+ const results = await Promise.all(
69
+ toolCalls.map((tc) => this.executeSingleCall(tc))
70
+ );
71
+ return results;
72
+ }
73
+ async executeSingleCall(toolCall) {
74
+ const { id, function: fn } = toolCall;
75
+ const definition = this.tools.get(fn.name);
76
+ if (!definition) {
77
+ return {
78
+ role: "tool",
79
+ tool_call_id: id,
80
+ content: JSON.stringify({ error: `Unknown tool: ${fn.name}` })
81
+ };
82
+ }
83
+ const scope = definition.permission ?? this.defaultPermission;
84
+ let args;
85
+ try {
86
+ args = JSON.parse(fn.arguments);
87
+ } catch {
88
+ return {
89
+ role: "tool",
90
+ tool_call_id: id,
91
+ content: JSON.stringify({ error: `Invalid JSON arguments for ${fn.name}` })
92
+ };
93
+ }
94
+ const { allowed, reason } = await this.vorim.check(this.agentId, scope);
95
+ if (!allowed) {
96
+ const event = {
97
+ agent_id: this.agentId,
98
+ event_type: "tool_call",
99
+ action: fn.name,
100
+ resource: truncate(fn.arguments, 500),
101
+ permission: scope,
102
+ result: "denied",
103
+ metadata: { reason, framework: "openai" }
104
+ };
105
+ this.emitAudit(event);
106
+ return {
107
+ role: "tool",
108
+ tool_call_id: id,
109
+ content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` \u2014 ${reason}` : ""}` })
110
+ };
111
+ }
112
+ const start = Date.now();
113
+ try {
114
+ const result = await definition.execute(args);
115
+ const content = typeof result === "string" ? result : JSON.stringify(result);
116
+ const event = {
117
+ agent_id: this.agentId,
118
+ event_type: "tool_call",
119
+ action: fn.name,
120
+ resource: truncate(fn.arguments, 500),
121
+ permission: scope,
122
+ result: "success",
123
+ latency_ms: Date.now() - start,
124
+ metadata: { framework: "openai" }
125
+ };
126
+ this.emitAudit(event);
127
+ return { role: "tool", tool_call_id: id, content };
128
+ } catch (err) {
129
+ const errMsg = err instanceof Error ? err.message : String(err);
130
+ const event = {
131
+ agent_id: this.agentId,
132
+ event_type: "tool_call",
133
+ action: fn.name,
134
+ resource: truncate(fn.arguments, 500),
135
+ permission: scope,
136
+ result: "error",
137
+ latency_ms: Date.now() - start,
138
+ error_code: err instanceof Error ? err.name : "UNKNOWN",
139
+ metadata: { error: errMsg, framework: "openai" }
140
+ };
141
+ this.emitAudit(event);
142
+ return {
143
+ role: "tool",
144
+ tool_call_id: id,
145
+ content: JSON.stringify({ error: errMsg })
146
+ };
147
+ }
148
+ }
149
+ emitAudit(event) {
150
+ if (this.asyncAudit) {
151
+ this.vorim.emit(event).catch(() => {
152
+ });
153
+ } else {
154
+ this.vorim.emit(event).catch(() => {
155
+ });
156
+ }
157
+ }
158
+ };
159
+ async function runAgentLoop(config) {
160
+ const { openai, model = "gpt-4o", systemPrompt, maxIterations = 10, registry, userMessage } = config;
161
+ const messages = [];
162
+ if (systemPrompt) messages.push({ role: "system", content: systemPrompt });
163
+ messages.push({ role: "user", content: userMessage });
164
+ const tools = registry.toOpenAITools();
165
+ for (let i = 0; i < maxIterations; i++) {
166
+ const response = await openai.chat.completions.create({
167
+ model,
168
+ messages,
169
+ ...tools.length > 0 ? { tools } : {}
170
+ });
171
+ const choice = response.choices[0];
172
+ messages.push(choice.message);
173
+ if (choice.finish_reason === "stop" || !choice.message.tool_calls?.length) {
174
+ return choice.message.content ?? "";
175
+ }
176
+ const toolMessages = await registry.executeToolCalls(choice.message.tool_calls);
177
+ messages.push(...toolMessages);
178
+ }
179
+ return messages[messages.length - 1]?.content ?? "";
180
+ }
181
+ async function createVorimOpenAIAgent(config) {
182
+ const { vorim, name, description, capabilities, scopes, tools } = config;
183
+ const registration = await vorim.register({
184
+ name,
185
+ description,
186
+ capabilities,
187
+ scopes
188
+ });
189
+ const agentId = registration.agent.agent_id;
190
+ const registry = new VorimToolRegistry({ vorim, agentId });
191
+ registry.addAll(tools);
192
+ return {
193
+ agentId,
194
+ registration,
195
+ registry,
196
+ privateKey: registration.private_key
197
+ };
198
+ }
199
+ function truncate(str, max) {
200
+ return str.length > max ? str.slice(0, max) + "\u2026" : str;
201
+ }
202
+ // Annotate the CommonJS export names for ESM import in node:
203
+ 0 && (module.exports = {
204
+ VorimToolRegistry,
205
+ createVorimOpenAIAgent,
206
+ runAgentLoop
207
+ });
208
+ //# sourceMappingURL=openai.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/openai.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — OpenAI Integration\n// Wraps OpenAI function calling with Vorim permission checks, audit trails,\n// and agent identity. Works with the OpenAI Node.js SDK (chat completions\n// with tool use).\n//\n// Peer dependency: openai >=4.0.0\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\n\n// ─── Re-declared OpenAI types (peer dependency — not bundled) ─────────────\n\ninterface ChatCompletionTool {\n type: 'function';\n function: {\n name: string;\n description?: string;\n parameters?: Record<string, unknown>;\n strict?: boolean;\n };\n}\n\ninterface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface ToolMessage {\n role: 'tool';\n tool_call_id: string;\n content: string;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {\n /** Tool name (must match the function name sent to OpenAI). */\n name: string;\n /** Description shown to the LLM. */\n description: string;\n /** JSON Schema for the tool's parameters. */\n parameters: Record<string, unknown>;\n /** The function to execute when the tool is called. */\n execute: (args: TArgs) => Promise<TResult>;\n /** Vorim permission scope required. @default 'agent:execute' */\n permission?: PermissionScope;\n /** Whether to use strict mode for OpenAI structured outputs. */\n strict?: boolean;\n}\n\nexport interface VorimOpenAIConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id. */\n agentId: string;\n /** Default permission scope for tools without an explicit one. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously. @default true */\n asyncAudit?: boolean;\n}\n\n// ─── Tool Registry ────────────────────────────────────────────────────────\n\n/**\n * Manages a set of tools with Vorim permission checks and audit logging.\n * Converts tools to OpenAI's `ChatCompletionTool` format and handles\n * execution of tool calls from the model's response.\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import createVorim from \"@vorim/sdk\";\n * import { VorimToolRegistry } from \"@vorim/sdk/integrations/openai\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n * const openai = new OpenAI();\n *\n * const registry = new VorimToolRegistry({\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * });\n *\n * registry.add({\n * name: \"search_docs\",\n * description: \"Search internal documents\",\n * parameters: {\n * type: \"object\",\n * properties: { query: { type: \"string\" } },\n * required: [\"query\"],\n * },\n * execute: async ({ query }) => searchDocs(query),\n * permission: \"agent:read\",\n * });\n *\n * // Use with OpenAI chat completions\n * const response = await openai.chat.completions.create({\n * model: \"gpt-4o\",\n * messages,\n * tools: registry.toOpenAITools(),\n * });\n *\n * // Execute tool calls from the response\n * const toolMessages = await registry.executeToolCalls(\n * response.choices[0].message.tool_calls ?? []\n * );\n * ```\n */\nexport class VorimToolRegistry {\n private vorim: VorimSDK;\n private agentId: string;\n private defaultPermission: PermissionScope;\n private asyncAudit: boolean;\n private tools = new Map<string, VorimToolDefinition>();\n\n constructor(config: VorimOpenAIConfig) {\n this.vorim = config.vorim;\n this.agentId = config.agentId;\n this.defaultPermission = config.defaultPermission ?? 'agent:execute';\n this.asyncAudit = config.asyncAudit ?? true;\n }\n\n /** Register a tool. */\n add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this {\n this.tools.set(definition.name, definition as VorimToolDefinition);\n return this;\n }\n\n /** Register multiple tools. */\n addAll(definitions: VorimToolDefinition[]): this {\n for (const def of definitions) this.add(def);\n return this;\n }\n\n /** Convert registered tools to OpenAI's ChatCompletionTool format. */\n toOpenAITools(): ChatCompletionTool[] {\n return [...this.tools.values()].map(t => ({\n type: 'function' as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n ...(t.strict != null ? { strict: t.strict } : {}),\n },\n }));\n }\n\n /**\n * Execute tool calls from an OpenAI chat completion response.\n * Each call is checked against Vorim permissions and audited.\n * Returns an array of tool messages ready to append to the conversation.\n */\n async executeToolCalls(toolCalls: ToolCall[]): Promise<ToolMessage[]> {\n const results = await Promise.all(\n toolCalls.map(tc => this.executeSingleCall(tc)),\n );\n return results;\n }\n\n private async executeSingleCall(toolCall: ToolCall): Promise<ToolMessage> {\n const { id, function: fn } = toolCall;\n const definition = this.tools.get(fn.name);\n\n if (!definition) {\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Unknown tool: ${fn.name}` }),\n };\n }\n\n const scope = definition.permission ?? this.defaultPermission;\n let args: unknown;\n try {\n args = JSON.parse(fn.arguments);\n } catch {\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Invalid JSON arguments for ${fn.name}` }),\n };\n }\n\n // 1. Permission check\n const { allowed, reason } = await this.vorim.check(this.agentId, scope);\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 500),\n permission: scope,\n result: 'denied',\n metadata: { reason, framework: 'openai' },\n };\n this.emitAudit(event);\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` — ${reason}` : ''}` }),\n };\n }\n\n // 2. Execute\n const start = Date.now();\n try {\n const result = await definition.execute(args as any);\n const content = typeof result === 'string' ? result : JSON.stringify(result);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n metadata: { framework: 'openai' },\n };\n this.emitAudit(event);\n\n return { role: 'tool', tool_call_id: id, content };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 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: errMsg, framework: 'openai' },\n };\n this.emitAudit(event);\n\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: errMsg }),\n };\n }\n }\n\n private emitAudit(event: AuditEventInput): void {\n if (this.asyncAudit) {\n this.vorim.emit(event).catch(() => {});\n } else {\n // Caller is already in an async context, but we don't await here\n // in async mode. For sync audit, the executeToolCalls caller\n // should await the full pipeline.\n this.vorim.emit(event).catch(() => {});\n }\n }\n}\n\n// ─── Agent Loop ───────────────────────────────────────────────────────────\n\nexport interface VorimAgentLoopConfig extends VorimOpenAIConfig {\n /** OpenAI client instance. */\n openai: OpenAIClient;\n /** Model to use. @default 'gpt-4o' */\n model?: string;\n /** System prompt for the agent. */\n systemPrompt?: string;\n /** Maximum iterations before stopping. @default 10 */\n maxIterations?: number;\n}\n\n/** Minimal OpenAI client interface (avoids importing the full SDK). */\ninterface OpenAIClient {\n chat: {\n completions: {\n create(params: any): Promise<any>;\n };\n };\n}\n\n/**\n * Runs a complete agent loop with OpenAI function calling, Vorim\n * permission enforcement, and audit logging.\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import createVorim from \"@vorim/sdk\";\n * import { runAgentLoop, VorimToolRegistry } from \"@vorim/sdk/integrations/openai\";\n *\n * const registry = new VorimToolRegistry({ vorim, agentId });\n * registry.add({ name: \"search\", ... });\n *\n * const response = await runAgentLoop({\n * vorim,\n * agentId,\n * openai: new OpenAI(),\n * model: \"gpt-4o\",\n * systemPrompt: \"You are a helpful assistant.\",\n * registry,\n * userMessage: \"Find docs about onboarding\",\n * });\n * ```\n */\nexport async function runAgentLoop(\n config: VorimAgentLoopConfig & {\n registry: VorimToolRegistry;\n userMessage: string;\n },\n): Promise<string> {\n const { openai, model = 'gpt-4o', systemPrompt, maxIterations = 10, registry, userMessage } = config;\n\n const messages: any[] = [];\n if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });\n messages.push({ role: 'user', content: userMessage });\n\n const tools = registry.toOpenAITools();\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await openai.chat.completions.create({\n model,\n messages,\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n const choice = response.choices[0];\n messages.push(choice.message);\n\n // If the model is done (no tool calls), return the response\n if (choice.finish_reason === 'stop' || !choice.message.tool_calls?.length) {\n return choice.message.content ?? '';\n }\n\n // Execute tool calls and add results to messages\n const toolMessages = await registry.executeToolCalls(choice.message.tool_calls);\n messages.push(...toolMessages);\n }\n\n return messages[messages.length - 1]?.content ?? '';\n}\n\n// ─── Agent Registration Helper ───────────────────────────────────────────\n\n/**\n * Registers a new agent with Vorim and returns a ready-to-use tool registry.\n *\n * @example\n * ```ts\n * const { agentId, registry } = await createVorimOpenAIAgent({\n * vorim,\n * name: \"support-agent\",\n * capabilities: [\"search\", \"email\"],\n * scopes: [\"agent:read\", \"agent:execute\", \"agent:communicate\"],\n * tools: [searchTool, emailTool],\n * });\n * ```\n */\nexport async function createVorimOpenAIAgent(config: {\n vorim: VorimSDK;\n name: string;\n description?: string;\n capabilities: string[];\n scopes: PermissionScope[];\n tools: VorimToolDefinition[];\n}) {\n const { vorim, name, description, capabilities, scopes, tools } = config;\n\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n\n const registry = new VorimToolRegistry({ vorim, agentId });\n registry.addAll(tools);\n\n return {\n agentId,\n registration,\n registry,\n privateKey: registration.private_key,\n };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiHO,IAAM,oBAAN,MAAwB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAQ,oBAAI,IAAiC;AAAA,EAErD,YAAY,QAA2B;AACrC,SAAK,QAAQ,OAAO;AACpB,SAAK,UAAU,OAAO;AACtB,SAAK,oBAAoB,OAAO,qBAAqB;AACrD,SAAK,aAAa,OAAO,cAAc;AAAA,EACzC;AAAA;AAAA,EAGA,IAAoB,YAAuD;AACzE,SAAK,MAAM,IAAI,WAAW,MAAM,UAAiC;AACjE,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,OAAO,aAA0C;AAC/C,eAAW,OAAO,YAAa,MAAK,IAAI,GAAG;AAC3C,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,gBAAsC;AACpC,WAAO,CAAC,GAAG,KAAK,MAAM,OAAO,CAAC,EAAE,IAAI,QAAM;AAAA,MACxC,MAAM;AAAA,MACN,UAAU;AAAA,QACR,MAAM,EAAE;AAAA,QACR,aAAa,EAAE;AAAA,QACf,YAAY,EAAE;AAAA,QACd,GAAI,EAAE,UAAU,OAAO,EAAE,QAAQ,EAAE,OAAO,IAAI,CAAC;AAAA,MACjD;AAAA,IACF,EAAE;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,iBAAiB,WAA+C;AACpE,UAAM,UAAU,MAAM,QAAQ;AAAA,MAC5B,UAAU,IAAI,QAAM,KAAK,kBAAkB,EAAE,CAAC;AAAA,IAChD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBAAkB,UAA0C;AACxE,UAAM,EAAE,IAAI,UAAU,GAAG,IAAI;A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AAQ,SAAS,YAAY,CAAC;AAEpD,QAAM,QAAQ,SAAS,cAAc;AAErC,WAAS,IAAI,GAAG,IAAI,eAAe,KAAK;AACtC,UAAM,WAAW,MAAM,OAAO,KAAK,YAAY,OAAO;AAAA,MACpD;AAAA,MACA;AAAA,MACA,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;AAAA,IACtC,CAAC;AAED,UAAM,SAAS,SAAS,QAAQ,CAAC;AACjC,aAAS,KAAK,OAAO,OAAO;AAG5B,QAAI,OAAO,kBAAkB,UAAU,CAAC,OAAO,QAAQ,YAAY,QAAQ;AACzE,aAAO,OAAO,QAAQ,WAAW;AAAA,IACnC;AAGA,UAAM,eAAe,MAAM,SAAS,iBAAiB,OAAO,QAAQ,UAAU;AAC9E,aAAS,KAAK,GAAG,YAAY;AAAA,EAC/B;AAEA,SAAO,SAAS,SAAS,SAAS,CAAC,GAAG,WAAW;AACnD;AAkBA,eAAsB,uBAAuB,QAO1C;AACD,QAAM,EAAE,OAAO,MAAM,aAAa,cAAc,QAAQ,MAAM,IAAI;AAElE,QAAM,eAAe,MAAM,MAAM,SAAS;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,UAAU,aAAa,MAAM;AAEnC,QAAM,WAAW,IAAI,kBAAkB,EAAE,OAAO,QAAQ,CAAC;AACzD,WAAS,OAAO,KAAK;AAErB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY,aAAa;AAAA,EAC3B;AACF;AAIA,SAAS,SAAS,KAAa,KAAqB;AAClD,SAAO,IAAI,SAAS,MAAM,IAAI,MAAM,GAAG,GAAG,IAAI,WAAM;AACtD;","names":[]}
@@ -0,0 +1,189 @@
1
+ import { VorimSDK, PermissionScope, AgentRegistrationResult } from '../index.cjs';
2
+
3
+ interface ChatCompletionTool {
4
+ type: 'function';
5
+ function: {
6
+ name: string;
7
+ description?: string;
8
+ parameters?: Record<string, unknown>;
9
+ strict?: boolean;
10
+ };
11
+ }
12
+ interface ToolCall {
13
+ id: string;
14
+ type: 'function';
15
+ function: {
16
+ name: string;
17
+ arguments: string;
18
+ };
19
+ }
20
+ interface ToolMessage {
21
+ role: 'tool';
22
+ tool_call_id: string;
23
+ content: string;
24
+ }
25
+ interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {
26
+ /** Tool name (must match the function name sent to OpenAI). */
27
+ name: string;
28
+ /** Description shown to the LLM. */
29
+ description: string;
30
+ /** JSON Schema for the tool's parameters. */
31
+ parameters: Record<string, unknown>;
32
+ /** The function to execute when the tool is called. */
33
+ execute: (args: TArgs) => Promise<TResult>;
34
+ /** Vorim permission scope required. @default 'agent:execute' */
35
+ permission?: PermissionScope;
36
+ /** Whether to use strict mode for OpenAI structured outputs. */
37
+ strict?: boolean;
38
+ }
39
+ interface VorimOpenAIConfig {
40
+ /** Vorim SDK instance. */
41
+ vorim: VorimSDK;
42
+ /** The Vorim agent_id. */
43
+ agentId: string;
44
+ /** Default permission scope for tools without an explicit one. @default 'agent:execute' */
45
+ defaultPermission?: PermissionScope;
46
+ /** Whether to emit audit events asynchronously. @default true */
47
+ asyncAudit?: boolean;
48
+ }
49
+ /**
50
+ * Manages a set of tools with Vorim permission checks and audit logging.
51
+ * Converts tools to OpenAI's `ChatCompletionTool` format and handles
52
+ * execution of tool calls from the model's response.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import OpenAI from "openai";
57
+ * import createVorim from "@vorim/sdk";
58
+ * import { VorimToolRegistry } from "@vorim/sdk/integrations/openai";
59
+ *
60
+ * const vorim = createVorim({ apiKey: "agid_sk_live_..." });
61
+ * const openai = new OpenAI();
62
+ *
63
+ * const registry = new VorimToolRegistry({
64
+ * vorim,
65
+ * agentId: "agid_acme_a1b2c3d4",
66
+ * });
67
+ *
68
+ * registry.add({
69
+ * name: "search_docs",
70
+ * description: "Search internal documents",
71
+ * parameters: {
72
+ * type: "object",
73
+ * properties: { query: { type: "string" } },
74
+ * required: ["query"],
75
+ * },
76
+ * execute: async ({ query }) => searchDocs(query),
77
+ * permission: "agent:read",
78
+ * });
79
+ *
80
+ * // Use with OpenAI chat completions
81
+ * const response = await openai.chat.completions.create({
82
+ * model: "gpt-4o",
83
+ * messages,
84
+ * tools: registry.toOpenAITools(),
85
+ * });
86
+ *
87
+ * // Execute tool calls from the response
88
+ * const toolMessages = await registry.executeToolCalls(
89
+ * response.choices[0].message.tool_calls ?? []
90
+ * );
91
+ * ```
92
+ */
93
+ declare class VorimToolRegistry {
94
+ private vorim;
95
+ private agentId;
96
+ private defaultPermission;
97
+ private asyncAudit;
98
+ private tools;
99
+ constructor(config: VorimOpenAIConfig);
100
+ /** Register a tool. */
101
+ add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this;
102
+ /** Register multiple tools. */
103
+ addAll(definitions: VorimToolDefinition[]): this;
104
+ /** Convert registered tools to OpenAI's ChatCompletionTool format. */
105
+ toOpenAITools(): ChatCompletionTool[];
106
+ /**
107
+ * Execute tool calls from an OpenAI chat completion response.
108
+ * Each call is checked against Vorim permissions and audited.
109
+ * Returns an array of tool messages ready to append to the conversation.
110
+ */
111
+ executeToolCalls(toolCalls: ToolCall[]): Promise<ToolMessage[]>;
112
+ private executeSingleCall;
113
+ private emitAudit;
114
+ }
115
+ interface VorimAgentLoopConfig extends VorimOpenAIConfig {
116
+ /** OpenAI client instance. */
117
+ openai: OpenAIClient;
118
+ /** Model to use. @default 'gpt-4o' */
119
+ model?: string;
120
+ /** System prompt for the agent. */
121
+ systemPrompt?: string;
122
+ /** Maximum iterations before stopping. @default 10 */
123
+ maxIterations?: number;
124
+ }
125
+ /** Minimal OpenAI client interface (avoids importing the full SDK). */
126
+ interface OpenAIClient {
127
+ chat: {
128
+ completions: {
129
+ create(params: any): Promise<any>;
130
+ };
131
+ };
132
+ }
133
+ /**
134
+ * Runs a complete agent loop with OpenAI function calling, Vorim
135
+ * permission enforcement, and audit logging.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * import OpenAI from "openai";
140
+ * import createVorim from "@vorim/sdk";
141
+ * import { runAgentLoop, VorimToolRegistry } from "@vorim/sdk/integrations/openai";
142
+ *
143
+ * const registry = new VorimToolRegistry({ vorim, agentId });
144
+ * registry.add({ name: "search", ... });
145
+ *
146
+ * const response = await runAgentLoop({
147
+ * vorim,
148
+ * agentId,
149
+ * openai: new OpenAI(),
150
+ * model: "gpt-4o",
151
+ * systemPrompt: "You are a helpful assistant.",
152
+ * registry,
153
+ * userMessage: "Find docs about onboarding",
154
+ * });
155
+ * ```
156
+ */
157
+ declare function runAgentLoop(config: VorimAgentLoopConfig & {
158
+ registry: VorimToolRegistry;
159
+ userMessage: string;
160
+ }): Promise<string>;
161
+ /**
162
+ * Registers a new agent with Vorim and returns a ready-to-use tool registry.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const { agentId, registry } = await createVorimOpenAIAgent({
167
+ * vorim,
168
+ * name: "support-agent",
169
+ * capabilities: ["search", "email"],
170
+ * scopes: ["agent:read", "agent:execute", "agent:communicate"],
171
+ * tools: [searchTool, emailTool],
172
+ * });
173
+ * ```
174
+ */
175
+ declare function createVorimOpenAIAgent(config: {
176
+ vorim: VorimSDK;
177
+ name: string;
178
+ description?: string;
179
+ capabilities: string[];
180
+ scopes: PermissionScope[];
181
+ tools: VorimToolDefinition[];
182
+ }): Promise<{
183
+ agentId: string;
184
+ registration: AgentRegistrationResult;
185
+ registry: VorimToolRegistry;
186
+ privateKey: string;
187
+ }>;
188
+
189
+ export { type VorimAgentLoopConfig, type VorimOpenAIConfig, type VorimToolDefinition, VorimToolRegistry, createVorimOpenAIAgent, runAgentLoop };
@@ -0,0 +1,189 @@
1
+ import { VorimSDK, PermissionScope, AgentRegistrationResult } from '../index.js';
2
+
3
+ interface ChatCompletionTool {
4
+ type: 'function';
5
+ function: {
6
+ name: string;
7
+ description?: string;
8
+ parameters?: Record<string, unknown>;
9
+ strict?: boolean;
10
+ };
11
+ }
12
+ interface ToolCall {
13
+ id: string;
14
+ type: 'function';
15
+ function: {
16
+ name: string;
17
+ arguments: string;
18
+ };
19
+ }
20
+ interface ToolMessage {
21
+ role: 'tool';
22
+ tool_call_id: string;
23
+ content: string;
24
+ }
25
+ interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {
26
+ /** Tool name (must match the function name sent to OpenAI). */
27
+ name: string;
28
+ /** Description shown to the LLM. */
29
+ description: string;
30
+ /** JSON Schema for the tool's parameters. */
31
+ parameters: Record<string, unknown>;
32
+ /** The function to execute when the tool is called. */
33
+ execute: (args: TArgs) => Promise<TResult>;
34
+ /** Vorim permission scope required. @default 'agent:execute' */
35
+ permission?: PermissionScope;
36
+ /** Whether to use strict mode for OpenAI structured outputs. */
37
+ strict?: boolean;
38
+ }
39
+ interface VorimOpenAIConfig {
40
+ /** Vorim SDK instance. */
41
+ vorim: VorimSDK;
42
+ /** The Vorim agent_id. */
43
+ agentId: string;
44
+ /** Default permission scope for tools without an explicit one. @default 'agent:execute' */
45
+ defaultPermission?: PermissionScope;
46
+ /** Whether to emit audit events asynchronously. @default true */
47
+ asyncAudit?: boolean;
48
+ }
49
+ /**
50
+ * Manages a set of tools with Vorim permission checks and audit logging.
51
+ * Converts tools to OpenAI's `ChatCompletionTool` format and handles
52
+ * execution of tool calls from the model's response.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import OpenAI from "openai";
57
+ * import createVorim from "@vorim/sdk";
58
+ * import { VorimToolRegistry } from "@vorim/sdk/integrations/openai";
59
+ *
60
+ * const vorim = createVorim({ apiKey: "agid_sk_live_..." });
61
+ * const openai = new OpenAI();
62
+ *
63
+ * const registry = new VorimToolRegistry({
64
+ * vorim,
65
+ * agentId: "agid_acme_a1b2c3d4",
66
+ * });
67
+ *
68
+ * registry.add({
69
+ * name: "search_docs",
70
+ * description: "Search internal documents",
71
+ * parameters: {
72
+ * type: "object",
73
+ * properties: { query: { type: "string" } },
74
+ * required: ["query"],
75
+ * },
76
+ * execute: async ({ query }) => searchDocs(query),
77
+ * permission: "agent:read",
78
+ * });
79
+ *
80
+ * // Use with OpenAI chat completions
81
+ * const response = await openai.chat.completions.create({
82
+ * model: "gpt-4o",
83
+ * messages,
84
+ * tools: registry.toOpenAITools(),
85
+ * });
86
+ *
87
+ * // Execute tool calls from the response
88
+ * const toolMessages = await registry.executeToolCalls(
89
+ * response.choices[0].message.tool_calls ?? []
90
+ * );
91
+ * ```
92
+ */
93
+ declare class VorimToolRegistry {
94
+ private vorim;
95
+ private agentId;
96
+ private defaultPermission;
97
+ private asyncAudit;
98
+ private tools;
99
+ constructor(config: VorimOpenAIConfig);
100
+ /** Register a tool. */
101
+ add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this;
102
+ /** Register multiple tools. */
103
+ addAll(definitions: VorimToolDefinition[]): this;
104
+ /** Convert registered tools to OpenAI's ChatCompletionTool format. */
105
+ toOpenAITools(): ChatCompletionTool[];
106
+ /**
107
+ * Execute tool calls from an OpenAI chat completion response.
108
+ * Each call is checked against Vorim permissions and audited.
109
+ * Returns an array of tool messages ready to append to the conversation.
110
+ */
111
+ executeToolCalls(toolCalls: ToolCall[]): Promise<ToolMessage[]>;
112
+ private executeSingleCall;
113
+ private emitAudit;
114
+ }
115
+ interface VorimAgentLoopConfig extends VorimOpenAIConfig {
116
+ /** OpenAI client instance. */
117
+ openai: OpenAIClient;
118
+ /** Model to use. @default 'gpt-4o' */
119
+ model?: string;
120
+ /** System prompt for the agent. */
121
+ systemPrompt?: string;
122
+ /** Maximum iterations before stopping. @default 10 */
123
+ maxIterations?: number;
124
+ }
125
+ /** Minimal OpenAI client interface (avoids importing the full SDK). */
126
+ interface OpenAIClient {
127
+ chat: {
128
+ completions: {
129
+ create(params: any): Promise<any>;
130
+ };
131
+ };
132
+ }
133
+ /**
134
+ * Runs a complete agent loop with OpenAI function calling, Vorim
135
+ * permission enforcement, and audit logging.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * import OpenAI from "openai";
140
+ * import createVorim from "@vorim/sdk";
141
+ * import { runAgentLoop, VorimToolRegistry } from "@vorim/sdk/integrations/openai";
142
+ *
143
+ * const registry = new VorimToolRegistry({ vorim, agentId });
144
+ * registry.add({ name: "search", ... });
145
+ *
146
+ * const response = await runAgentLoop({
147
+ * vorim,
148
+ * agentId,
149
+ * openai: new OpenAI(),
150
+ * model: "gpt-4o",
151
+ * systemPrompt: "You are a helpful assistant.",
152
+ * registry,
153
+ * userMessage: "Find docs about onboarding",
154
+ * });
155
+ * ```
156
+ */
157
+ declare function runAgentLoop(config: VorimAgentLoopConfig & {
158
+ registry: VorimToolRegistry;
159
+ userMessage: string;
160
+ }): Promise<string>;
161
+ /**
162
+ * Registers a new agent with Vorim and returns a ready-to-use tool registry.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const { agentId, registry } = await createVorimOpenAIAgent({
167
+ * vorim,
168
+ * name: "support-agent",
169
+ * capabilities: ["search", "email"],
170
+ * scopes: ["agent:read", "agent:execute", "agent:communicate"],
171
+ * tools: [searchTool, emailTool],
172
+ * });
173
+ * ```
174
+ */
175
+ declare function createVorimOpenAIAgent(config: {
176
+ vorim: VorimSDK;
177
+ name: string;
178
+ description?: string;
179
+ capabilities: string[];
180
+ scopes: PermissionScope[];
181
+ tools: VorimToolDefinition[];
182
+ }): Promise<{
183
+ agentId: string;
184
+ registration: AgentRegistrationResult;
185
+ registry: VorimToolRegistry;
186
+ privateKey: string;
187
+ }>;
188
+
189
+ export { type VorimAgentLoopConfig, type VorimOpenAIConfig, type VorimToolDefinition, VorimToolRegistry, createVorimOpenAIAgent, runAgentLoop };