@palveron/sdk 1.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/CHANGELOG.md ADDED
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@palveron/sdk` will be documented in this file.
4
+
5
+ This project follows [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [1.0.0] — 2026-05-17
8
+
9
+ ### Added
10
+ - Initial public release of `@palveron/sdk` on npm
11
+ - `Palveron` client class with full API coverage
12
+ - Policy verification via `verify()` method with multi-modal attachments
13
+ (image, audio, video, document, code)
14
+ - `check()` convenience method for text-only verification
15
+ - `verifyWithFile()` convenience method (Node.js, auto MIME detection)
16
+ - `listPolicies()` and `health()` endpoints
17
+ - `diagnostics()` method for runtime introspection
18
+ - `RequestContext` for MCP / agentic context
19
+ (`mcpServer`, `toolName`, `chainDepth`, `sourceSystem`, `sessionId`)
20
+ - Typed error hierarchy: `PalveronError`, `PalveronAuthenticationError`,
21
+ `PalveronRateLimitError`, `PalveronValidationError`, `PalveronTimeoutError`,
22
+ `PalveronCircuitOpenError`
23
+ - `retryAfterMs` on rate limit errors
24
+ - Retry with exponential backoff + jitter
25
+ - Circuit breaker with configurable threshold and cooldown
26
+ - Custom headers support for proxy / auth scenarios
27
+ - Custom `baseUrl` for on-premise / self-hosted gateways
28
+ - TypeScript type definitions for every API surface
29
+ - Dual ESM + CommonJS output, source maps, declaration maps
30
+ - Zero runtime dependencies; works in Node.js 18+, Deno, Bun, Cloudflare
31
+ Workers, Vercel Edge
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Palveron
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,249 @@
1
+ <p align="center">
2
+ <h1 align="center">@palveron/sdk</h1>
3
+ <p align="center">Official TypeScript / JavaScript SDK for the Palveron AI Governance Gateway</p>
4
+ </p>
5
+
6
+ <p align="center">
7
+ <a href="https://www.npmjs.com/package/@palveron/sdk"><img src="https://img.shields.io/npm/v/@palveron/sdk.svg?style=flat-square&color=cb3837" alt="npm version"></a>
8
+ <a href="https://www.npmjs.com/package/@palveron/sdk"><img src="https://img.shields.io/npm/dm/@palveron/sdk.svg?style=flat-square" alt="npm downloads"></a>
9
+ <a href="https://github.com/palveron/sdk-typescript/actions"><img src="https://img.shields.io/github/actions/workflow/status/palveron/sdk-typescript/ci.yml?style=flat-square" alt="CI"></a>
10
+ <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-green.svg?style=flat-square" alt="License: MIT"></a>
11
+ <a href="https://docs.palveron.com"><img src="https://img.shields.io/badge/docs-palveron.com-5A67D8?style=flat-square" alt="Documentation"></a>
12
+ </p>
13
+
14
+ ---
15
+
16
+ Every AI interaction your application makes — governed, audited, and optionally anchored to the blockchain. In one line of code.
17
+
18
+ - **Zero dependencies** — uses native `fetch`; works in Node.js 18+, Deno, Bun, Cloudflare Workers, Vercel Edge
19
+ - **Multi-modal** — text, images, audio, documents, code
20
+ - **Enterprise-grade** — retry with exponential backoff, circuit breaker, typed errors
21
+ - **On-prem ready** — point to any Palveron Gateway endpoint
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install @palveron/sdk
27
+ # or
28
+ pnpm add @palveron/sdk
29
+ # or
30
+ yarn add @palveron/sdk
31
+ ```
32
+
33
+ ## Quick Start
34
+
35
+ ```typescript
36
+ import { Palveron } from '@palveron/sdk';
37
+
38
+ const palveron = new Palveron({ apiKey: process.env.PALVERON_API_KEY! });
39
+
40
+ // Verify any prompt before sending it to an LLM
41
+ const result = await palveron.verify({ prompt: userInput });
42
+
43
+ if (result.decision === 'BLOCKED') {
44
+ console.error(`Blocked: ${result.reason}`);
45
+ return;
46
+ }
47
+
48
+ // result.decision is 'ALLOWED' or 'MODIFIED'
49
+ // result.output contains the (possibly sanitized) text
50
+ // result.traceId links to the immutable audit trail
51
+ ```
52
+
53
+ ## Features
54
+
55
+ - **Policy Enforcement** — every prompt routed through your active guardrails before it reaches an LLM
56
+ - **Trace Verification** — every decision logged with an integrity hash for tamper detection
57
+ - **Agent Registration & Governance** — list and audit the agents covered by your account
58
+ - **Blockchain Attestation** — high-severity traces anchored to Flare for cryptographic audit trails
59
+ - **EU AI Act / DORA / GDPR** — compliance-ready audit fields out of the box
60
+
61
+ ## Configuration
62
+
63
+ ```typescript
64
+ const palveron = new Palveron({
65
+ apiKey: 'pv_live_xxx', // Required — project or agent API key
66
+ baseUrl: 'https://gateway.palveron.com', // Custom endpoint for on-prem
67
+ timeout: 30_000, // Request timeout in ms
68
+ maxRetries: 3, // Retry attempts on transient failures
69
+ retryBaseDelay: 500, // Base delay for exponential backoff (ms)
70
+ headers: { 'X-Tenant': 'acme' }, // Custom headers on every request
71
+ circuitBreakerThreshold: 5, // Failures before circuit opens
72
+ circuitBreakerCooldown: 30_000, // Cooldown before half-open retry (ms)
73
+ });
74
+ ```
75
+
76
+ ## API Reference
77
+
78
+ Full reference at **[docs.palveron.com/sdks](https://docs.palveron.com/sdks)**. Quick summary:
79
+
80
+ ### `verify(request)` — Core governance check
81
+
82
+ ```typescript
83
+ const result = await palveron.verify({
84
+ prompt: 'Transfer $50,000 to account DE89370400440532013000',
85
+ metadata: { userId: 'u_123', department: 'finance' },
86
+ attachments: [{
87
+ contentType: 'application/pdf',
88
+ data: base64EncodedPdf,
89
+ filename: 'contract.pdf',
90
+ }],
91
+ context: {
92
+ mcpServer: 'https://mcp.internal.corp',
93
+ toolName: 'bank_transfer',
94
+ chainDepth: 2,
95
+ sourceSystem: 'crewai',
96
+ sessionId: 'sess_abc',
97
+ },
98
+ });
99
+ ```
100
+
101
+ **Returns `VerifyResponse`:**
102
+
103
+ | Field | Type | Description |
104
+ |-------|------|-------------|
105
+ | `decision` | `'ALLOWED' \| 'BLOCKED' \| 'MODIFIED' \| 'ERROR'` | Governance decision |
106
+ | `output` | `string` | Sanitized output (PII redacted if MODIFIED) |
107
+ | `reason` | `string` | Human-readable explanation |
108
+ | `traceId` | `string` | Unique audit trail ID |
109
+ | `integrityHash` | `string` | SHA-256 hash for tamper detection |
110
+ | `shouldAnchor` | `boolean` | Whether trace will be anchored to Flare blockchain |
111
+ | `flareStatus` | `string` | `LOCAL_ONLY`, `PENDING`, `ANCHORED`, `SKIPPED`, `FAILED` |
112
+ | `flareTxHash` | `string \| null` | Blockchain transaction hash (after anchoring) |
113
+ | `contentType` | `string` | Detected content type |
114
+ | `findings` | `Finding[]` | Security findings (PII, secrets, policy violations) |
115
+ | `latencyMs` | `number` | Round-trip latency in milliseconds |
116
+
117
+ ### `check(prompt)` — Quick text-only verification
118
+
119
+ ```typescript
120
+ const { decision } = await palveron.check('Is this prompt safe?');
121
+ ```
122
+
123
+ ### `verifyWithFile(prompt, filePath)` — File attachment (Node.js only)
124
+
125
+ ```typescript
126
+ const result = await palveron.verifyWithFile(
127
+ 'Analyze this document for compliance',
128
+ './report.pdf'
129
+ );
130
+ ```
131
+
132
+ ### `listPolicies(env?)` — List active policies
133
+
134
+ ```typescript
135
+ const { policies } = await palveron.listPolicies('prod');
136
+ ```
137
+
138
+ ### `health()` — Gateway health check
139
+
140
+ ```typescript
141
+ const health = await palveron.health();
142
+ console.log(health.status); // 'healthy'
143
+ ```
144
+
145
+ ### `diagnostics()` — SDK diagnostics
146
+
147
+ ```typescript
148
+ const diag = palveron.diagnostics();
149
+ // { sdkVersion, baseUrl, timeout, maxRetries, circuitState }
150
+ ```
151
+
152
+ ## Examples
153
+
154
+ ### LLM gateway with governance
155
+
156
+ ```typescript
157
+ import { Palveron } from '@palveron/sdk';
158
+ import OpenAI from 'openai';
159
+
160
+ const palveron = new Palveron({ apiKey: process.env.PALVERON_API_KEY! });
161
+ const openai = new OpenAI();
162
+
163
+ async function askWithGovernance(userPrompt: string) {
164
+ const gate = await palveron.verify({ prompt: userPrompt });
165
+ if (gate.decision === 'BLOCKED') {
166
+ throw new Error(`Blocked by policy: ${gate.reason}`);
167
+ }
168
+ // `gate.output` is the (possibly sanitized) prompt — always use it
169
+ // instead of the raw input so downstream LLMs never see PII / secrets.
170
+ return openai.chat.completions.create({
171
+ model: 'gpt-4o',
172
+ messages: [{ role: 'user', content: gate.output }],
173
+ });
174
+ }
175
+ ```
176
+
177
+ ### Agentic / MCP audit context
178
+
179
+ ```typescript
180
+ const result = await palveron.verify({
181
+ prompt: 'Execute bank transfer',
182
+ context: {
183
+ mcpServer: 'https://banking-mcp.corp.internal',
184
+ toolName: 'transfer_funds',
185
+ chainDepth: 3,
186
+ sourceSystem: 'crewai',
187
+ sessionId: 'agent_session_42',
188
+ },
189
+ });
190
+ ```
191
+
192
+ ### On-premise / self-hosted gateway
193
+
194
+ ```typescript
195
+ const palveron = new Palveron({
196
+ apiKey: process.env.PALVERON_API_KEY!,
197
+ baseUrl: 'https://gateway.internal.acme.corp:8080',
198
+ timeout: 10_000,
199
+ maxRetries: 5,
200
+ });
201
+ ```
202
+
203
+ ## Error Handling
204
+
205
+ All errors extend `PalveronError` with structured metadata:
206
+
207
+ ```typescript
208
+ import { PalveronError, PalveronRateLimitError } from '@palveron/sdk';
209
+
210
+ try {
211
+ await palveron.verify({ prompt: input });
212
+ } catch (err) {
213
+ if (err instanceof PalveronRateLimitError) {
214
+ // err.retryAfterMs — wait this long before retrying
215
+ await sleep(err.retryAfterMs);
216
+ return retry();
217
+ }
218
+ if (err instanceof PalveronError) {
219
+ console.error(err.code, err.statusCode, err.requestId);
220
+ }
221
+ }
222
+ ```
223
+
224
+ | Error Class | Code | Retryable | When |
225
+ |-------------|------|:---------:|------|
226
+ | `PalveronAuthenticationError` | `AUTHENTICATION_FAILED` | No | Invalid or expired API key |
227
+ | `PalveronRateLimitError` | `RATE_LIMITED` | Yes | Quota exceeded (includes `retryAfterMs`) |
228
+ | `PalveronValidationError` | `VALIDATION_ERROR` | No | Malformed request (includes `field`) |
229
+ | `PalveronTimeoutError` | `TIMEOUT` | Yes | Gateway didn't respond in time |
230
+ | `PalveronCircuitOpenError` | `CIRCUIT_OPEN` | No | Too many consecutive failures |
231
+
232
+ ## Requirements
233
+
234
+ - Node.js **18 or newer** (uses native `fetch`)
235
+ - TypeScript **5.0 or newer** (recommended; SDK works in plain JavaScript too)
236
+ - Also runs in Deno, Bun, Cloudflare Workers, Vercel Edge
237
+
238
+ ## Links
239
+
240
+ - **Documentation** — [docs.palveron.com](https://docs.palveron.com)
241
+ - **SDK reference** — [docs.palveron.com/sdks](https://docs.palveron.com/sdks)
242
+ - **Dashboard** — [palveron.com](https://palveron.com)
243
+ - **Support** — [hello@palveron.com](mailto:hello@palveron.com)
244
+ - **GitHub** — [palveron/sdk-typescript](https://github.com/palveron/sdk-typescript)
245
+ - **Changelog** — [CHANGELOG.md](https://github.com/palveron/sdk-typescript/blob/main/CHANGELOG.md)
246
+
247
+ ## License
248
+
249
+ [MIT](./LICENSE) — Copyright © 2026 Palveron.
@@ -0,0 +1,225 @@
1
+ type Decision = 'ALLOWED' | 'BLOCKED' | 'MODIFIED' | 'ERROR';
2
+ type RiskLevel = 'minimal' | 'limited' | 'high' | 'unacceptable';
3
+ type Sensitivity = 'low' | 'medium' | 'high';
4
+ interface PalveronConfig {
5
+ /** API key (starts with pv_live_ or pv_test_) */
6
+ apiKey: string;
7
+ /** Gateway base URL (default: https://gateway.palveron.com) */
8
+ baseUrl?: string;
9
+ /** Request timeout in ms (default: 30000) */
10
+ timeout?: number;
11
+ /** Max retry attempts on transient failures (default: 3) */
12
+ maxRetries?: number;
13
+ /** Base delay for exponential backoff in ms (default: 500) */
14
+ retryBaseDelay?: number;
15
+ /** Custom logger (default: console) */
16
+ logger?: PalveronLogger;
17
+ /** Custom headers added to every request */
18
+ headers?: Record<string, string>;
19
+ /** Circuit breaker: max consecutive failures before opening (default: 5) */
20
+ circuitBreakerThreshold?: number;
21
+ /** Circuit breaker: cooldown in ms before half-open retry (default: 30000) */
22
+ circuitBreakerCooldown?: number;
23
+ }
24
+ interface PalveronLogger {
25
+ debug(message: string, meta?: Record<string, unknown>): void;
26
+ info(message: string, meta?: Record<string, unknown>): void;
27
+ warn(message: string, meta?: Record<string, unknown>): void;
28
+ error(message: string, meta?: Record<string, unknown>): void;
29
+ }
30
+ interface Attachment {
31
+ /** MIME type (e.g. "image/png", "audio/wav", "application/pdf") */
32
+ contentType: string;
33
+ /** Base64-encoded data */
34
+ data: string;
35
+ /** Optional filename */
36
+ filename?: string;
37
+ /** Optional per-attachment metadata (GPS, resolution, etc.) */
38
+ metadata?: Record<string, unknown>;
39
+ }
40
+ interface RequestContext {
41
+ /** MCP server URL if applicable */
42
+ mcpServer?: string;
43
+ /** MCP tool name */
44
+ toolName?: string;
45
+ /** Agent chain depth for recursive calls */
46
+ chainDepth?: number;
47
+ /** Source system identifier ("ros2", "unity", "cursor-ide", etc.) */
48
+ sourceSystem?: string;
49
+ /** Session ID for conversation tracking */
50
+ sessionId?: string;
51
+ }
52
+ interface VerifyRequest {
53
+ /** The prompt or input text to verify */
54
+ prompt: string;
55
+ /** Pre-extracted text from attachments (optional, server extracts if absent) */
56
+ extractedText?: string;
57
+ /** Arbitrary metadata passed through to the trace */
58
+ metadata?: Record<string, unknown>;
59
+ /** Multi-modal attachments (images, audio, documents, code) */
60
+ attachments?: Attachment[];
61
+ /** Agentic context (MCP, tool chains, source systems) */
62
+ context?: RequestContext;
63
+ }
64
+ interface Finding {
65
+ risk: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
66
+ category: string;
67
+ description: string;
68
+ confidence: number;
69
+ }
70
+ interface VerifyResponse {
71
+ /** Governance decision */
72
+ decision: Decision;
73
+ /** Modified/sanitized output (present when decision is MODIFIED) */
74
+ output: string;
75
+ /** Human-readable reason for the decision */
76
+ reason: string;
77
+ /** Unique trace ID for audit trail */
78
+ traceId: string;
79
+ /** SHA-256 integrity hash of the governance decision */
80
+ integrityHash: string;
81
+ /** Whether this trace will be anchored to Flare blockchain */
82
+ shouldAnchor: boolean;
83
+ /** Flare blockchain status */
84
+ flareStatus: string;
85
+ /** Flare transaction hash (populated after anchoring) */
86
+ flareTxHash: string | null;
87
+ /** Detected content type */
88
+ contentType: string;
89
+ /** Security findings (secrets, PII, policy violations) */
90
+ findings: Finding[];
91
+ /** Server-side latency in milliseconds */
92
+ latencyMs: number;
93
+ }
94
+ interface PolicyListResponse {
95
+ policies: Array<{
96
+ id: string;
97
+ name: string;
98
+ prompt: string;
99
+ environment: string;
100
+ contentTypes: string[];
101
+ createdAt: string;
102
+ updatedAt: string;
103
+ }>;
104
+ }
105
+ interface HealthResponse {
106
+ status: 'healthy' | 'degraded' | 'unhealthy';
107
+ version: string;
108
+ uptime: number;
109
+ checks: Record<string, {
110
+ status: string;
111
+ latencyMs: number;
112
+ }>;
113
+ }
114
+ declare class PalveronError extends Error {
115
+ readonly code: string;
116
+ readonly statusCode: number;
117
+ readonly requestId: string | null;
118
+ readonly retryable: boolean;
119
+ constructor(message: string, opts: {
120
+ code: string;
121
+ statusCode: number;
122
+ requestId?: string | null;
123
+ retryable?: boolean;
124
+ });
125
+ }
126
+ declare class PalveronAuthenticationError extends PalveronError {
127
+ constructor(message: string, requestId?: string | null);
128
+ }
129
+ declare class PalveronRateLimitError extends PalveronError {
130
+ readonly retryAfterMs: number;
131
+ constructor(message: string, retryAfterMs: number, requestId?: string | null);
132
+ }
133
+ declare class PalveronValidationError extends PalveronError {
134
+ readonly field: string | null;
135
+ constructor(message: string, field?: string, requestId?: string | null);
136
+ }
137
+ declare class PalveronCircuitOpenError extends PalveronError {
138
+ constructor();
139
+ }
140
+ declare class PalveronTimeoutError extends PalveronError {
141
+ constructor(timeoutMs: number, requestId?: string | null);
142
+ }
143
+ declare class Palveron {
144
+ private readonly config;
145
+ private readonly circuit;
146
+ constructor(config: PalveronConfig);
147
+ /**
148
+ * Send a governance verification request.
149
+ * This is the primary method — every LLM call should go through this.
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * const result = await palveron.verify({ prompt: 'User input here' });
154
+ * if (result.decision === 'BLOCKED') {
155
+ * throw new Error(result.reason);
156
+ * }
157
+ * ```
158
+ */
159
+ verify(request: VerifyRequest): Promise<VerifyResponse>;
160
+ /**
161
+ * Quick verification for text-only prompts.
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * const result = await palveron.check('Is this prompt safe?');
166
+ * console.log(result.decision); // 'ALLOWED'
167
+ * ```
168
+ */
169
+ check(prompt: string): Promise<VerifyResponse>;
170
+ /**
171
+ * Verify a prompt with a file attachment.
172
+ * Reads the file, Base64-encodes it, and sends it with the correct MIME type.
173
+ * Node.js only — use verify() with pre-encoded data in browsers.
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * const result = await palveron.verifyWithFile(
178
+ * 'Analyze this document',
179
+ * '/path/to/report.pdf'
180
+ * );
181
+ * ```
182
+ */
183
+ verifyWithFile(prompt: string, filePath: string): Promise<VerifyResponse>;
184
+ /**
185
+ * List all active policies for the project.
186
+ */
187
+ listPolicies(env?: string): Promise<PolicyListResponse>;
188
+ /**
189
+ * Check gateway health status.
190
+ */
191
+ health(): Promise<HealthResponse>;
192
+ /**
193
+ * Get SDK and connection diagnostics.
194
+ */
195
+ diagnostics(): {
196
+ sdkVersion: string;
197
+ baseUrl: string;
198
+ timeout: number;
199
+ maxRetries: number;
200
+ circuitState: string;
201
+ };
202
+ private request;
203
+ private backoffDelay;
204
+ private sleep;
205
+ private generateRequestId;
206
+ private inferMimeType;
207
+ }
208
+ /**
209
+ * Create a Palveron client instance.
210
+ *
211
+ * @example
212
+ * ```typescript
213
+ * import { createClient } from '@palveron/sdk';
214
+ *
215
+ * const palveron = createClient({
216
+ * apiKey: process.env.PALVERON_API_KEY!,
217
+ * baseUrl: 'https://gateway.acme.corp:8080', // on-prem
218
+ * });
219
+ *
220
+ * const result = await palveron.verify({ prompt: userInput });
221
+ * ```
222
+ */
223
+ declare function createClient(config: PalveronConfig): Palveron;
224
+
225
+ export { type Attachment, type Decision, type Finding, type HealthResponse, Palveron, PalveronAuthenticationError, PalveronCircuitOpenError, type PalveronConfig, PalveronError, type PalveronLogger, PalveronRateLimitError, PalveronTimeoutError, PalveronValidationError, type PolicyListResponse, type RequestContext, type RiskLevel, type Sensitivity, type VerifyRequest, type VerifyResponse, createClient, Palveron as default };