@sernixa/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Sernixa Team
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,186 @@
1
+ # @sernixa/sdk
2
+
3
+ TypeScript SDK for Sernixa — governed tool and agent execution with MCP
4
+ call-gate support.
5
+
6
+ ## What This Does
7
+
8
+ The SDK gates local JavaScript/TypeScript function execution through Sernixa's
9
+ approval oracle. Your code runs **only after** Sernixa returns an approved-style
10
+ decision (`approved`, `auto_approved`, or `executed`).
11
+
12
+ This is **not** a native MCP JSON-RPC server or transport. Sernixa exposes a
13
+ governed HTTP call gate for host/router-controlled MCP dispatch. Native MCP
14
+ transport is not shipped yet.
15
+
16
+ ## Install
17
+
18
+ > **Not yet published to npm.** Use the monorepo workspace package until the
19
+ > first npm release.
20
+
21
+ From the repository root:
22
+
23
+ ```bash
24
+ npm install
25
+ npm -w packages/sdk run build
26
+ ```
27
+
28
+ After npm publication (when available):
29
+
30
+ ```bash
31
+ npm install @sernixa/sdk
32
+ ```
33
+
34
+ ## Quick Start
35
+
36
+ ```ts
37
+ import { Client } from "@sernixa/sdk";
38
+
39
+ const client = new Client({
40
+ baseUrl: "http://localhost:8000",
41
+ apiKey: process.env.SERNIXA_API_KEY,
42
+ });
43
+
44
+ const readFile = client.intercept(
45
+ async (path: string) => `contents for ${path}`,
46
+ {
47
+ intentId: "mcp-read-file",
48
+ riskLevel: "LOW",
49
+ operationClass: "read",
50
+ dataSensitivity: "internal",
51
+ systemsTouched: ["workspace"],
52
+ }
53
+ );
54
+
55
+ const result = await readFile("/workspace/report.md");
56
+ ```
57
+
58
+ ## MCP Call Gate
59
+
60
+ Use `mcpCallGate()` to request approval for an MCP-style tool call through
61
+ Sernixa's governed HTTP call gate:
62
+
63
+ ```ts
64
+ const response = await client.mcpCallGate({
65
+ mcpToolsetId: "workspace-mcp",
66
+ toolName: "read_file",
67
+ intentId: "read-workspace-file",
68
+ arguments: { path: "/workspace/report.md" },
69
+ riskLevel: "LOW",
70
+ operationClass: "read",
71
+ dataSensitivity: "internal",
72
+ });
73
+
74
+ if (response.status === "accepted" || response.status === "auto_approved") {
75
+ // Dispatch the actual MCP tool call from the caller-owned host
76
+ }
77
+ ```
78
+
79
+ > **Important:** `dispatch_mode` is always `caller_owned_after_allowed`. Sernixa
80
+ > does not execute upstream MCP servers — it governs whether the call should
81
+ > proceed.
82
+
83
+ ## Gateway Wrapper
84
+
85
+ ```ts
86
+ import { SernixaGateway } from "@sernixa/sdk";
87
+
88
+ const gateway = new SernixaGateway({
89
+ apiKey: process.env.SERNIXA_API_KEY,
90
+ mcpProfile: "prod-tools",
91
+ enforceEbpf: true,
92
+ });
93
+
94
+ const result = await gateway.run(
95
+ () => agent.run({ input: "Summarize customer risk" }),
96
+ {
97
+ intentId: "agent-risk-summary",
98
+ riskLevel: "MEDIUM",
99
+ operationClass: "agent_run",
100
+ dataSensitivity: "internal",
101
+ }
102
+ );
103
+ ```
104
+
105
+ `enforceEbpf=true` does **not** start an eBPF collector. It checks `/ready` and
106
+ requires Flight Recorder runtime support outside `local_demo`.
107
+
108
+ ## Delegation
109
+
110
+ ```ts
111
+ import { Client } from "@sernixa/sdk";
112
+
113
+ const client = new Client();
114
+
115
+ const token = await client.createDelegationToken({
116
+ delegatorAgentId: "orchestrator",
117
+ delegateeAgentId: "worker",
118
+ scope: {
119
+ max_risk_level: "low",
120
+ allowed_operation_classes: ["read"],
121
+ },
122
+ });
123
+
124
+ const governed = client.interceptWithDelegation(
125
+ async () => "worker result",
126
+ {
127
+ intentId: "delegated-read",
128
+ riskLevel: "LOW",
129
+ operationClass: "read",
130
+ dataSensitivity: "internal",
131
+ systemsTouched: ["workspace"],
132
+ },
133
+ {
134
+ agentId: "worker",
135
+ delegationTokenId: token.token_id as string,
136
+ signingSecret: process.env.SERNIXA_REQUEST_SIGNING_SECRET!,
137
+ }
138
+ );
139
+
140
+ const result = await governed();
141
+ ```
142
+
143
+ ## Error Handling
144
+
145
+ ```ts
146
+ import {
147
+ SernixaBlockedError,
148
+ SernixaRejectedError,
149
+ SernixaTimeoutError,
150
+ SernixaSignatureError,
151
+ SernixaDelegationScopeError,
152
+ } from "@sernixa/sdk";
153
+
154
+ try {
155
+ await governed();
156
+ } catch (error) {
157
+ if (error instanceof SernixaBlockedError) {
158
+ console.error("Policy blocked:", error.reason);
159
+ } else if (error instanceof SernixaRejectedError) {
160
+ console.error("Reviewer rejected:", error.reason);
161
+ } else if (error instanceof SernixaDelegationScopeError) {
162
+ console.error("Delegation scope error:", error.reason);
163
+ } else if (error instanceof SernixaSignatureError) {
164
+ console.error("Signature error:", error.reason);
165
+ } else if (error instanceof SernixaTimeoutError) {
166
+ console.error("Approval pending:", error.approvalId);
167
+ }
168
+ }
169
+ ```
170
+
171
+ ## Environment Variables
172
+
173
+ | Variable | Default | Description |
174
+ | ---------------------------------- | -------------------- | -------------------------------------- |
175
+ | `SERNIXA_BASE_URL` | `http://localhost:8000` | Sernixa API base URL |
176
+ | `SERNIXA_API_KEY` | (empty) | Bearer token |
177
+ | `SERNIXA_POLL_INTERVAL_SECONDS` | `2` | Seconds between approval polls |
178
+ | `SERNIXA_POLL_TIMEOUT_SECONDS` | `600` | Max seconds to wait for approval |
179
+ | `SERNIXA_TIMEOUT_MS` | `10000` | Per-request HTTP timeout |
180
+ | `SERNIXA_MAX_RETRIES` | `2` | Retries for 429/5xx/network errors |
181
+ | `SERNIXA_CAPTURE_ARGUMENTS` | `false` | Submit function argument values |
182
+ | `SERNIXA_REQUEST_SIGNING_KEY_ID` | `local-request-key-v1` | Key ID for delegation signing |
183
+
184
+ ## License
185
+
186
+ MIT
@@ -0,0 +1,204 @@
1
+ export declare const VERSION = "0.1.0";
2
+ export type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' | 'low' | 'medium' | 'high' | 'critical';
3
+ export type DecisionStatus = 'pending' | 'pending_review' | 'approved' | 'auto_approved' | 'executed' | 'rejected' | 'blocked' | 'expired' | 'failed';
4
+ export type RuntimeMode = 'local_demo' | 'production_like' | string;
5
+ export type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;
6
+ export type ActionMetadata = Record<string, unknown>;
7
+ export type InterceptOptions = {
8
+ intentId: string;
9
+ riskLevel: RiskLevel;
10
+ operationClass: string;
11
+ dataSensitivity: string;
12
+ systemsTouched: string[];
13
+ metadata?: ActionMetadata;
14
+ actionId?: string;
15
+ };
16
+ export type ClientOptions = {
17
+ baseUrl?: string;
18
+ apiKey?: string;
19
+ pollIntervalSeconds?: number;
20
+ pollTimeoutSeconds?: number;
21
+ timeoutMs?: number;
22
+ maxRetries?: number;
23
+ fetch?: FetchLike;
24
+ };
25
+ export type GatewayOptions = ClientOptions & {
26
+ mcpProfile?: string;
27
+ enforceEbpf?: boolean;
28
+ client?: Client;
29
+ };
30
+ export type GatewayRunOptions = Partial<InterceptOptions> & {
31
+ mcpProfile?: string;
32
+ };
33
+ export type DelegationContext = {
34
+ agentId: string;
35
+ delegationTokenId: string;
36
+ signingSecret: string;
37
+ delegationChainId?: string;
38
+ runtimeId?: string;
39
+ runtimeIdentity?: string;
40
+ serviceIdentity?: string;
41
+ workloadIdentity?: string;
42
+ keyId?: string;
43
+ };
44
+ export type DelegationTokenRequest = {
45
+ delegatorAgentId: string;
46
+ delegateeAgentId: string;
47
+ scope: Record<string, unknown>;
48
+ parentTokenId?: string;
49
+ toolSubset?: string[];
50
+ rootHumanSessionId?: string;
51
+ expiresInSeconds?: number;
52
+ reason?: string;
53
+ };
54
+ export type McpCallGateRequest = {
55
+ mcpToolsetId: string;
56
+ toolName: string;
57
+ serverName?: string;
58
+ arguments?: Record<string, unknown>;
59
+ intentId: string;
60
+ actionId?: string;
61
+ agentId?: string;
62
+ riskLevel?: RiskLevel;
63
+ operationClass?: string;
64
+ dataSensitivity?: string;
65
+ resourceHints?: string[];
66
+ metadata?: Record<string, unknown>;
67
+ };
68
+ export type McpCallGateResponse = {
69
+ status: string;
70
+ action_id: string;
71
+ intent_id: string;
72
+ approval_id?: string;
73
+ reason: string;
74
+ dispatch_mode: string;
75
+ native_mcp_transport: boolean;
76
+ next_step: string;
77
+ };
78
+ export type ReadinessCheck = {
79
+ status?: string;
80
+ enabled?: boolean;
81
+ error?: string;
82
+ [key: string]: unknown;
83
+ };
84
+ export type ReadinessResponse = {
85
+ status: string;
86
+ runtime_mode?: string;
87
+ serving_mode?: string;
88
+ checks?: {
89
+ configuration?: {
90
+ status?: string;
91
+ snapshot?: Record<string, unknown>;
92
+ [key: string]: unknown;
93
+ };
94
+ flight_recorder?: ReadinessCheck;
95
+ mcp_gateway?: {
96
+ enabled: boolean;
97
+ published_profiles: number;
98
+ transport: string;
99
+ };
100
+ [key: string]: unknown;
101
+ };
102
+ [key: string]: unknown;
103
+ };
104
+ export declare const APPROVED_STATUSES: readonly ["approved", "auto_approved", "executed"];
105
+ export declare const TERMINAL_STATUSES: readonly ["approved", "auto_approved", "executed", "rejected", "blocked", "expired", "failed"];
106
+ export declare function isApprovedStatus(status: string | undefined | null): boolean;
107
+ export declare function isTerminalStatus(status: string | undefined | null): boolean;
108
+ export declare class SernixaError extends Error {
109
+ readonly statusCode?: number;
110
+ readonly approvalId?: string;
111
+ readonly reason?: string;
112
+ readonly evidence?: unknown;
113
+ constructor(message: string, options?: {
114
+ statusCode?: number;
115
+ approvalId?: string;
116
+ reason?: string;
117
+ evidence?: unknown;
118
+ cause?: unknown;
119
+ });
120
+ }
121
+ export declare class SernixaConfigurationError extends SernixaError {
122
+ }
123
+ export declare class SernixaValidationError extends SernixaError {
124
+ }
125
+ export declare class SernixaApiError extends SernixaError {
126
+ }
127
+ export declare class SernixaRateLimitError extends SernixaError {
128
+ }
129
+ export declare class SernixaBlockedError extends SernixaError {
130
+ }
131
+ export declare class SernixaRejectedError extends SernixaError {
132
+ }
133
+ export declare class SernixaExpiredError extends SernixaError {
134
+ }
135
+ export declare class SernixaTimeoutError extends SernixaError {
136
+ }
137
+ export declare class SernixaSignatureError extends SernixaError {
138
+ }
139
+ export declare class SernixaDelegationScopeError extends SernixaError {
140
+ }
141
+ export declare class SernixaReplayError extends SernixaError {
142
+ }
143
+ export declare function actionMetadata(options: {
144
+ riskLevel: RiskLevel;
145
+ operationClass: string;
146
+ dataSensitivity: string;
147
+ systemsTouched: string[];
148
+ [key: string]: unknown;
149
+ }): ActionMetadata;
150
+ export declare function safeSerialize(value: unknown, seen?: WeakSet<object>): unknown;
151
+ export declare function generateIdempotencyKey(intentId: string, fnName: string, args: unknown[], kwargs: Record<string, unknown>): string;
152
+ export declare function canonicalJson(value: unknown): string;
153
+ export declare function computeBodyHash(payload: {
154
+ intentId: string;
155
+ actionId: string;
156
+ metadata: Record<string, unknown>;
157
+ }): string;
158
+ export declare function signDelegatedRequest(payload: Record<string, unknown>, signingSecret: string): string;
159
+ export declare function buildDelegationSignaturePayload(options: {
160
+ intentId: string;
161
+ actionId: string;
162
+ metadata: Record<string, unknown>;
163
+ agentId: string;
164
+ runtimeId?: string;
165
+ runtimeIdentity?: string;
166
+ serviceIdentity?: string;
167
+ workloadIdentity?: string;
168
+ delegationTokenId: string;
169
+ delegationChainId?: string;
170
+ timestamp: number;
171
+ nonce: string;
172
+ bodyHash: string;
173
+ keyId: string;
174
+ algorithm?: string;
175
+ }): Record<string, unknown>;
176
+ export declare class Client {
177
+ readonly baseUrl: string;
178
+ readonly apiKey: string;
179
+ readonly pollIntervalSeconds: number;
180
+ readonly pollTimeoutSeconds: number;
181
+ readonly timeoutMs: number;
182
+ readonly maxRetries: number;
183
+ private readonly fetchImpl;
184
+ constructor(options?: ClientOptions);
185
+ intercept<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => TResult | Promise<TResult>, options: InterceptOptions): (...args: TArgs) => Promise<TResult>;
186
+ execute<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => TResult | Promise<TResult>, options: InterceptOptions, ...args: TArgs): Promise<TResult>;
187
+ readiness(): Promise<ReadinessResponse>;
188
+ createDelegationToken(request: DelegationTokenRequest): Promise<Record<string, unknown>>;
189
+ mcpCallGate(request: McpCallGateRequest): Promise<McpCallGateResponse>;
190
+ private buildActionPayload;
191
+ interceptWithDelegation<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => TResult | Promise<TResult>, options: InterceptOptions, delegation: DelegationContext): (...args: TArgs) => Promise<TResult>;
192
+ private submitAndWait;
193
+ private pollApproval;
194
+ private request;
195
+ }
196
+ export declare class SernixaGateway {
197
+ readonly client: Client;
198
+ readonly mcpProfile?: string;
199
+ readonly enforceEbpf: boolean;
200
+ constructor(options?: GatewayOptions);
201
+ run<TResult>(fn: () => TResult | Promise<TResult>, options?: GatewayRunOptions): Promise<TResult>;
202
+ }
203
+ export declare function validateRuntimeEvidence(readiness: Record<string, unknown>): void;
204
+ //# sourceMapp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S,IAAI,OAAO,CAAC,iBAAiB,CAAC;IAYvC,qBAAqB,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAwBxF,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAmD5E,OAAO,CAAC,kBAAkB;IAsF1B,uBAAuB,CAAC,KAAK,SAAS,OAAO,EAAE,EAAE,OAAO,EACtD,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,EAClD,OAAO,EAAE,gBAAgB,EACzB,UAAU,EAAE,iBAAiB,GAC5B,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC;YAQzB,aAAa;YAuCb,YAAY;YAmDZ,OAAO;CA2CtB;AAMD,qBAAa,cAAc;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAA;gBAEjB,OAAO,GAAE,cAAmB;IAMlC,GAAG,CAAC,OAAO,EACf,EAAE,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,EACpC,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,OAAO,CAAC;CAqBpB;AAMD,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAwBhF"}
package/dist/index.js ADDED
@@ -0,0 +1,680 @@
1
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
2
+ export const VERSION = '0.1.0';
3
+ // ---------------------------------------------------------------------------
4
+ // Constants
5
+ // ---------------------------------------------------------------------------
6
+ export const APPROVED_STATUSES = ['approved', 'auto_approved', 'executed'];
7
+ export const TERMINAL_STATUSES = [
8
+ 'approved',
9
+ 'auto_approved',
10
+ 'executed',
11
+ 'rejected',
12
+ 'blocked',
13
+ 'expired',
14
+ 'failed',
15
+ ];
16
+ const TRANSIENT_STATUS_CODES = new Set([429, 500, 502, 503, 504]);
17
+ const VALID_RISK_LEVELS = new Set(['low', 'medium', 'high', 'critical']);
18
+ const DELEGATED_REQUEST_SCHEMA_VERSION = 'sernixa.delegated_request.v1';
19
+ const DELEGATED_REQUEST_ALGORITHM = 'HMAC-SHA256';
20
+ // ---------------------------------------------------------------------------
21
+ // Status helpers
22
+ // ---------------------------------------------------------------------------
23
+ export function isApprovedStatus(status) {
24
+ return APPROVED_STATUSES.includes(status);
25
+ }
26
+ export function isTerminalStatus(status) {
27
+ return TERMINAL_STATUSES.includes(status);
28
+ }
29
+ // ---------------------------------------------------------------------------
30
+ // Error hierarchy
31
+ // ---------------------------------------------------------------------------
32
+ export class SernixaError extends Error {
33
+ statusCode;
34
+ approvalId;
35
+ reason;
36
+ evidence;
37
+ constructor(message, options = {}) {
38
+ super(message, { cause: options.cause });
39
+ this.name = new.target.name;
40
+ this.statusCode = options.statusCode;
41
+ this.approvalId = options.approvalId;
42
+ this.reason = options.reason;
43
+ this.evidence = options.evidence;
44
+ }
45
+ }
46
+ export class SernixaConfigurationError extends SernixaError {
47
+ }
48
+ export class SernixaValidationError extends SernixaError {
49
+ }
50
+ export class SernixaApiError extends SernixaError {
51
+ }
52
+ export class SernixaRateLimitError extends SernixaError {
53
+ }
54
+ export class SernixaBlockedError extends SernixaError {
55
+ }
56
+ export class SernixaRejectedError extends SernixaError {
57
+ }
58
+ export class SernixaExpiredError extends SernixaError {
59
+ }
60
+ export class SernixaTimeoutError extends SernixaError {
61
+ }
62
+ export class SernixaSignatureError extends SernixaError {
63
+ }
64
+ export class SernixaDelegationScopeError extends SernixaError {
65
+ }
66
+ export class SernixaReplayError extends SernixaError {
67
+ }
68
+ // ---------------------------------------------------------------------------
69
+ // Serialization / metadata helpers
70
+ // ---------------------------------------------------------------------------
71
+ export function actionMetadata(options) {
72
+ const { riskLevel, operationClass, dataSensitivity, systemsTouched, ...extra } = options;
73
+ return {
74
+ risk_level: riskLevel,
75
+ operation_class: operationClass,
76
+ data_sensitivity: dataSensitivity,
77
+ systems_touched: systemsTouched,
78
+ ...extra,
79
+ };
80
+ }
81
+ export function safeSerialize(value, seen = new WeakSet()) {
82
+ if (value === null ||
83
+ typeof value === 'string' ||
84
+ typeof value === 'number' ||
85
+ typeof value === 'boolean') {
86
+ return value;
87
+ }
88
+ if (typeof value === 'bigint') {
89
+ return value.toString();
90
+ }
91
+ if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol') {
92
+ return `<non-serializable: ${typeof value}>`;
93
+ }
94
+ if (Array.isArray(value)) {
95
+ return value.map((item) => safeSerialize(item, seen));
96
+ }
97
+ if (typeof value === 'object') {
98
+ if (seen.has(value)) {
99
+ return '<non-serializable: circular>';
100
+ }
101
+ seen.add(value);
102
+ if (value instanceof Date) {
103
+ return value.toISOString();
104
+ }
105
+ const output = {};
106
+ for (const [key, item] of Object.entries(value)) {
107
+ output[key] = safeSerialize(item, seen);
108
+ }
109
+ return output;
110
+ }
111
+ return String(value).slice(0, 200);
112
+ }
113
+ export function generateIdempotencyKey(intentId, fnName, args, kwargs) {
114
+ return createHash('sha256')
115
+ .update(JSON.stringify({
116
+ intent_id: intentId,
117
+ fn: fnName,
118
+ args: safeSerialize(args),
119
+ kwargs: safeSerialize(kwargs),
120
+ }))
121
+ .digest('hex');
122
+ }
123
+ // ---------------------------------------------------------------------------
124
+ // Delegation signing helpers
125
+ // ---------------------------------------------------------------------------
126
+ export function canonicalJson(value) {
127
+ return JSON.stringify(value, Object.keys(value).sort(), undefined)
128
+ .replace(/\s/g, '');
129
+ }
130
+ function canonicalJsonSorted(value) {
131
+ const sorted = {};
132
+ for (const key of Object.keys(value).sort()) {
133
+ sorted[key] = value[key];
134
+ }
135
+ return JSON.stringify(sorted);
136
+ }
137
+ export function computeBodyHash(payload) {
138
+ return createHash('sha256')
139
+ .update(canonicalJsonSorted({
140
+ intent_id: payload.intentId,
141
+ action_id: payload.actionId,
142
+ metadata: payload.metadata,
143
+ }))
144
+ .digest('hex');
145
+ }
146
+ export function signDelegatedRequest(payload, signingSecret) {
147
+ return createHmac('sha256', signingSecret)
148
+ .update(canonicalJsonSorted(payload))
149
+ .digest('hex');
150
+ }
151
+ export function buildDelegationSignaturePayload(options) {
152
+ return {
153
+ schema_version: DELEGATED_REQUEST_SCHEMA_VERSION,
154
+ intent_id: options.intentId,
155
+ action_id: options.actionId,
156
+ agent_id: options.agentId,
157
+ runtime_id: options.runtimeId ?? null,
158
+ runtime_identity: options.runtimeIdentity ?? null,
159
+ service_identity: options.serviceIdentity ?? null,
160
+ workload_identity: options.workloadIdentity ?? null,
161
+ delegation_token_id: options.delegationTokenId,
162
+ delegation_chain_id: options.delegationChainId ?? null,
163
+ timestamp: options.timestamp,
164
+ nonce: options.nonce,
165
+ operation_class: options.metadata.operation_class ?? null,
166
+ data_sensitivity: options.metadata.data_sensitivity ?? null,
167
+ body_hash: options.bodyHash,
168
+ key_id: options.keyId,
169
+ algorithm: options.algorithm ?? DELEGATED_REQUEST_ALGORITHM,
170
+ };
171
+ }
172
+ function validateActionOptions(options) {
173
+ if (!options.intentId.trim()) {
174
+ throw new SernixaValidationError('intentId must be a non-empty string.');
175
+ }
176
+ if (options.intentId.length > 128) {
177
+ throw new SernixaValidationError('intentId must be 128 characters or fewer.');
178
+ }
179
+ if (!VALID_RISK_LEVELS.has(String(options.riskLevel).toLowerCase())) {
180
+ throw new SernixaValidationError('riskLevel must be one of: low, medium, high, critical.');
181
+ }
182
+ if (!options.operationClass.trim()) {
183
+ throw new SernixaValidationError('operationClass must be a non-empty string.');
184
+ }
185
+ if (!options.dataSensitivity.trim()) {
186
+ throw new SernixaValidationError('dataSensitivity must be a non-empty string.');
187
+ }
188
+ if (!Array.isArray(options.systemsTouched) || options.systemsTouched.length === 0) {
189
+ throw new SernixaValidationError('systemsTouched must be a non-empty string array.');
190
+ }
191
+ if (!options.systemsTouched.every((item) => typeof item === 'string' && item.trim())) {
192
+ throw new SernixaValidationError('systemsTouched must contain only non-empty strings.');
193
+ }
194
+ JSON.stringify(safeMetadata(options.metadata ?? {}));
195
+ }
196
+ function safeMetadata(metadata) {
197
+ const output = {};
198
+ for (const [key, value] of Object.entries(metadata)) {
199
+ output[key] = safeSerialize(value);
200
+ }
201
+ return output;
202
+ }
203
+ function positiveNumber(value, name, allowZero) {
204
+ if (!Number.isFinite(value) || value < 0 || (!allowZero && value === 0)) {
205
+ throw new SernixaConfigurationError(`${name} must be ${allowZero ? 'zero or greater' : 'greater than zero'}.`);
206
+ }
207
+ return value;
208
+ }
209
+ function envNumber(name, fallback) {
210
+ const raw = process.env[name];
211
+ if (!raw) {
212
+ return fallback;
213
+ }
214
+ const parsed = Number(raw);
215
+ if (!Number.isFinite(parsed)) {
216
+ throw new SernixaConfigurationError(`${name} must be a number.`);
217
+ }
218
+ return parsed;
219
+ }
220
+ function envBool(name, fallback) {
221
+ const raw = process.env[name];
222
+ if (!raw) {
223
+ return fallback;
224
+ }
225
+ return ['1', 'true', 'yes', 'on'].includes(raw.toLowerCase());
226
+ }
227
+ async function responseJsonObject(response) {
228
+ let data;
229
+ try {
230
+ data = await response.json();
231
+ }
232
+ catch (error) {
233
+ throw new SernixaApiError('Sernixa API returned a non-JSON response.', {
234
+ statusCode: response.status,
235
+ cause: error,
236
+ });
237
+ }
238
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
239
+ throw new SernixaApiError('Sernixa API returned an unexpected JSON payload.', {
240
+ statusCode: response.status,
241
+ evidence: data,
242
+ });
243
+ }
244
+ return data;
245
+ }
246
+ async function responseText(response) {
247
+ try {
248
+ return (await response.text()).slice(0, 1000);
249
+ }
250
+ catch {
251
+ return '';
252
+ }
253
+ }
254
+ async function throwBlocked(response) {
255
+ const data = await responseJsonObject(response);
256
+ const detail = objectField(data, 'detail');
257
+ const status = stringField(detail, 'status') ?? '';
258
+ const reason = stringField(detail, 'reason') ?? stringField(data, 'reason') ?? 'blocked';
259
+ if (['invalid_signature', 'invalid_nonce'].includes(status)) {
260
+ throw new SernixaSignatureError(`Signature verification failed: ${reason}`, {
261
+ statusCode: response.status,
262
+ reason: status,
263
+ evidence: Object.keys(detail).length ? detail : data,
264
+ });
265
+ }
266
+ if (['replayed_nonce', 'stale_timestamp'].includes(status)) {
267
+ throw new SernixaReplayError(`Replay protection triggered: ${reason}`, {
268
+ statusCode: response.status,
269
+ reason: status,
270
+ evidence: Object.keys(detail).length ? detail : data,
271
+ });
272
+ }
273
+ if ([
274
+ 'out_of_scope',
275
+ 'mismatched_delegatee',
276
+ 'unknown_agent',
277
+ 'expired_token',
278
+ 'revoked_token',
279
+ 'invalid_chain',
280
+ ].includes(status)) {
281
+ throw new SernixaDelegationScopeError(`Action out of delegation scope: ${reason}`, {
282
+ statusCode: response.status,
283
+ reason: status,
284
+ evidence: Object.keys(detail).length ? detail : data,
285
+ });
286
+ }
287
+ throw new SernixaBlockedError(`Action blocked: ${reason}`, {
288
+ statusCode: response.status,
289
+ reason,
290
+ evidence: Object.keys(detail).length ? detail : data,
291
+ });
292
+ }
293
+ function objectField(value, key) {
294
+ const field = value[key];
295
+ return field && typeof field === 'object' && !Array.isArray(field)
296
+ ? field
297
+ : {};
298
+ }
299
+ function stringField(value, key) {
300
+ return typeof value[key] === 'string' ? value[key] : undefined;
301
+ }
302
+ function booleanField(value, key) {
303
+ return typeof value[key] === 'boolean' ? value[key] : undefined;
304
+ }
305
+ function isAbortError(error) {
306
+ return error instanceof Error && error.name === 'AbortError';
307
+ }
308
+ async function sleep(ms) {
309
+ if (ms <= 0) {
310
+ return;
311
+ }
312
+ await new Promise((resolve) => setTimeout(resolve, ms));
313
+ }
314
+ // ---------------------------------------------------------------------------
315
+ // Client
316
+ // ---------------------------------------------------------------------------
317
+ export class Client {
318
+ baseUrl;
319
+ apiKey;
320
+ pollIntervalSeconds;
321
+ pollTimeoutSeconds;
322
+ timeoutMs;
323
+ maxRetries;
324
+ fetchImpl;
325
+ constructor(options = {}) {
326
+ this.baseUrl = (options.baseUrl ?? process.env.SERNIXA_BASE_URL ?? 'http://localhost:8000').replace(/\/+$/, '');
327
+ if (!this.baseUrl.startsWith('http://') && !this.baseUrl.startsWith('https://')) {
328
+ throw new SernixaConfigurationError('SERNIXA_BASE_URL must start with http:// or https://.');
329
+ }
330
+ this.apiKey = options.apiKey ?? process.env.SERNIXA_API_KEY ?? '';
331
+ this.pollIntervalSeconds = positiveNumber(options.pollIntervalSeconds ?? envNumber('SERNIXA_POLL_INTERVAL_SECONDS', 2), 'pollIntervalSeconds', true);
332
+ this.pollTimeoutSeconds = positiveNumber(options.pollTimeoutSeconds ?? envNumber('SERNIXA_POLL_TIMEOUT_SECONDS', 600), 'pollTimeoutSeconds', true);
333
+ this.timeoutMs = positiveNumber(options.timeoutMs ?? envNumber('SERNIXA_TIMEOUT_MS', envNumber('SERNIXA_TIMEOUT_SECONDS', 10) * 1000), 'timeoutMs', false);
334
+ this.maxRetries = positiveNumber(options.maxRetries ?? envNumber('SERNIXA_MAX_RETRIES', 2), 'maxRetries', true);
335
+ this.fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
336
+ if (!this.fetchImpl) {
337
+ throw new SernixaConfigurationError('A fetch implementation is required in this Node runtime.');
338
+ }
339
+ }
340
+ intercept(fn, options) {
341
+ return async (...args) => {
342
+ const payload = this.buildActionPayload(fn, options, args);
343
+ await this.submitAndWait(payload);
344
+ return await fn(...args);
345
+ };
346
+ }
347
+ async execute(fn, options, ...args) {
348
+ return await this.intercept(fn, options)(...args);
349
+ }
350
+ async readiness() {
351
+ const response = await this.request('GET', '/ready');
352
+ const data = await responseJsonObject(response);
353
+ if (response.status >= 400 && !Object.hasOwn(data, 'checks')) {
354
+ throw new SernixaApiError('Sernixa readiness check failed.', {
355
+ statusCode: response.status,
356
+ evidence: data,
357
+ });
358
+ }
359
+ return data;
360
+ }
361
+ async createDelegationToken(request) {
362
+ const payload = {
363
+ delegator_agent_id: request.delegatorAgentId,
364
+ delegatee_agent_id: request.delegateeAgentId,
365
+ scope: request.scope,
366
+ parent_token_id: request.parentTokenId ?? null,
367
+ tool_subset: request.toolSubset ?? null,
368
+ root_human_session_id: request.rootHumanSessionId ?? null,
369
+ expires_in_seconds: request.expiresInSeconds ?? 3600,
370
+ reason: request.reason ?? null,
371
+ };
372
+ const response = await this.request('POST', '/api/delegations', {
373
+ body: JSON.stringify(payload),
374
+ });
375
+ if (response.status >= 400) {
376
+ throw new SernixaApiError('Failed to create delegation token.', {
377
+ statusCode: response.status,
378
+ evidence: await responseText(response),
379
+ });
380
+ }
381
+ return responseJsonObject(response);
382
+ }
383
+ async mcpCallGate(request) {
384
+ const payload = {
385
+ mcp_toolset_id: request.mcpToolsetId,
386
+ tool_name: request.toolName,
387
+ server_name: request.serverName ?? null,
388
+ arguments: request.arguments ?? {},
389
+ intent_id: request.intentId,
390
+ action_id: request.actionId ?? null,
391
+ agent_id: request.agentId ?? null,
392
+ risk_level: request.riskLevel ?? 'medium',
393
+ operation_class: request.operationClass ?? 'tool_call',
394
+ data_sensitivity: request.dataSensitivity ?? 'internal',
395
+ resource_hints: request.resourceHints ?? [],
396
+ metadata: request.metadata ?? {},
397
+ };
398
+ const response = await this.request('POST', '/api/mcp/tools/call', {
399
+ body: JSON.stringify(payload),
400
+ });
401
+ if (response.status === 401 || response.status === 403) {
402
+ await throwBlocked(response);
403
+ }
404
+ if (response.status >= 400) {
405
+ throw new SernixaApiError('MCP call gate request failed.', {
406
+ statusCode: response.status,
407
+ evidence: await responseText(response),
408
+ });
409
+ }
410
+ const data = await responseJsonObject(response);
411
+ // 202 means pending review — return it as-is with approval_id
412
+ return {
413
+ status: typeof data.status === 'string' ? data.status : 'accepted',
414
+ action_id: typeof data.action_id === 'string' ? data.action_id : '',
415
+ intent_id: typeof data.intent_id === 'string' ? data.intent_id : request.intentId,
416
+ approval_id: typeof data.approval_id === 'string' ? data.approval_id : undefined,
417
+ reason: typeof data.reason === 'string' ? data.reason : '',
418
+ dispatch_mode: typeof data.dispatch_mode === 'string'
419
+ ? data.dispatch_mode
420
+ : 'caller_owned_after_allowed',
421
+ native_mcp_transport: data.native_mcp_transport === true,
422
+ next_step: typeof data.next_step === 'string'
423
+ ? data.next_step
424
+ : 'Dispatch the MCP tool call from the caller-owned host only after this gate allows it.',
425
+ };
426
+ }
427
+ buildActionPayload(fn, options, args, delegation) {
428
+ validateActionOptions(options);
429
+ const captureArguments = envBool('SERNIXA_CAPTURE_ARGUMENTS', false);
430
+ const fnName = fn.name || 'anonymous';
431
+ const idempotencyKey = generateIdempotencyKey(options.intentId, fnName, captureArguments ? args : [`${args.length} positional argument(s)`], {});
432
+ const metadata = actionMetadata({
433
+ riskLevel: options.riskLevel,
434
+ operationClass: options.operationClass,
435
+ dataSensitivity: options.dataSensitivity,
436
+ systemsTouched: options.systemsTouched,
437
+ function: fnName,
438
+ arguments_captured: captureArguments,
439
+ args_count: args.length,
440
+ idempotency_key: idempotencyKey,
441
+ ...safeMetadata(options.metadata ?? {}),
442
+ });
443
+ if (captureArguments) {
444
+ metadata.args = safeSerialize(args);
445
+ }
446
+ const payload = {
447
+ intent_id: options.intentId,
448
+ action_id: options.actionId ?? fnName.replaceAll('_', '-'),
449
+ metadata,
450
+ };
451
+ // Delegation envelope
452
+ const ctx = delegation;
453
+ if (ctx) {
454
+ payload.agent_id = ctx.agentId;
455
+ payload.delegation_token_id = ctx.delegationTokenId;
456
+ payload.delegation_chain_id = ctx.delegationChainId ?? null;
457
+ payload.runtime_id = ctx.runtimeId ?? null;
458
+ payload.runtime_identity = ctx.runtimeIdentity ?? null;
459
+ payload.service_identity = ctx.serviceIdentity ?? null;
460
+ payload.workload_identity = ctx.workloadIdentity ?? null;
461
+ const timestamp = Math.floor(Date.now() / 1000);
462
+ const nonce = randomBytes(16).toString('hex');
463
+ const keyId = ctx.keyId ?? process.env.SERNIXA_REQUEST_SIGNING_KEY_ID ?? 'local-request-key-v1';
464
+ payload.timestamp = timestamp;
465
+ payload.nonce = nonce;
466
+ payload.key_id = keyId;
467
+ payload.algorithm = DELEGATED_REQUEST_ALGORITHM;
468
+ const bodyHash = computeBodyHash({
469
+ intentId: payload.intent_id,
470
+ actionId: payload.action_id,
471
+ metadata: payload.metadata,
472
+ });
473
+ payload.body_hash = bodyHash;
474
+ const sigPayload = buildDelegationSignaturePayload({
475
+ intentId: payload.intent_id,
476
+ actionId: payload.action_id,
477
+ metadata: payload.metadata,
478
+ agentId: ctx.agentId,
479
+ runtimeId: ctx.runtimeId,
480
+ runtimeIdentity: ctx.runtimeIdentity,
481
+ serviceIdentity: ctx.serviceIdentity,
482
+ workloadIdentity: ctx.workloadIdentity,
483
+ delegationTokenId: ctx.delegationTokenId,
484
+ delegationChainId: ctx.delegationChainId,
485
+ timestamp,
486
+ nonce,
487
+ bodyHash,
488
+ keyId,
489
+ });
490
+ payload.signature = signDelegatedRequest(sigPayload, ctx.signingSecret);
491
+ }
492
+ return payload;
493
+ }
494
+ interceptWithDelegation(fn, options, delegation) {
495
+ return async (...args) => {
496
+ const payload = this.buildActionPayload(fn, options, args, delegation);
497
+ await this.submitAndWait(payload);
498
+ return await fn(...args);
499
+ };
500
+ }
501
+ async submitAndWait(payload) {
502
+ const response = await this.request('POST', '/api/actions/execute', {
503
+ body: JSON.stringify(payload),
504
+ });
505
+ if (response.status === 202) {
506
+ const decision = await responseJsonObject(response);
507
+ const approvalId = stringField(decision, 'approval_id');
508
+ if (!approvalId) {
509
+ throw new SernixaApiError('Received pending_review response without approval_id.', {
510
+ statusCode: 202,
511
+ evidence: decision,
512
+ });
513
+ }
514
+ await this.pollApproval(approvalId);
515
+ return;
516
+ }
517
+ if (response.status === 401 || response.status === 403) {
518
+ await throwBlocked(response);
519
+ }
520
+ if (response.status >= 400) {
521
+ throw new SernixaApiError('Failed to submit Sernixa action.', {
522
+ statusCode: response.status,
523
+ evidence: await responseText(response),
524
+ });
525
+ }
526
+ const decision = await responseJsonObject(response);
527
+ const status = typeof decision.status === 'string' ? decision.status : 'accepted';
528
+ if (status === 'blocked') {
529
+ throw new SernixaBlockedError('Action blocked by Sernixa.', {
530
+ reason: stringField(decision, 'reason'),
531
+ evidence: decision,
532
+ });
533
+ }
534
+ }
535
+ async pollApproval(approvalId) {
536
+ const startedAt = Date.now();
537
+ while (Date.now() - startedAt <= this.pollTimeoutSeconds * 1000) {
538
+ await sleep(this.pollIntervalSeconds * 1000);
539
+ const response = await this.request('GET', `/api/approvals/${encodeURIComponent(approvalId)}`);
540
+ if (response.status >= 400) {
541
+ throw new SernixaApiError('Failed to poll Sernixa approval status.', {
542
+ statusCode: response.status,
543
+ approvalId,
544
+ evidence: await responseText(response),
545
+ });
546
+ }
547
+ const decision = await responseJsonObject(response);
548
+ const status = typeof decision.status === 'string' ? decision.status : undefined;
549
+ if (isApprovedStatus(status)) {
550
+ return;
551
+ }
552
+ if (status === 'rejected') {
553
+ throw new SernixaRejectedError('Action rejected by reviewer.', {
554
+ approvalId,
555
+ reason: stringField(decision, 'decision_reason') ?? stringField(decision, 'reason'),
556
+ evidence: decision,
557
+ });
558
+ }
559
+ if (status === 'blocked') {
560
+ throw new SernixaBlockedError('Action blocked during review.', {
561
+ approvalId,
562
+ reason: stringField(decision, 'decision_reason') ?? stringField(decision, 'reason'),
563
+ evidence: decision,
564
+ });
565
+ }
566
+ if (status === 'expired') {
567
+ throw new SernixaExpiredError('Action expired before approval.', {
568
+ approvalId,
569
+ evidence: decision,
570
+ });
571
+ }
572
+ if (status === 'failed') {
573
+ throw new SernixaError('Action failed after approval processing.', {
574
+ approvalId,
575
+ evidence: decision,
576
+ });
577
+ }
578
+ }
579
+ throw new SernixaTimeoutError(`Polling timed out after ${this.pollTimeoutSeconds} seconds.`, { approvalId });
580
+ }
581
+ async request(method, path, init = {}) {
582
+ let lastError;
583
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
584
+ const controller = new AbortController();
585
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
586
+ try {
587
+ const response = await this.fetchImpl(new URL(path, `${this.baseUrl}/`), {
588
+ ...init,
589
+ method,
590
+ headers: {
591
+ ...(this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),
592
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
593
+ ...init.headers,
594
+ },
595
+ signal: controller.signal,
596
+ });
597
+ clearTimeout(timeout);
598
+ if (!TRANSIENT_STATUS_CODES.has(response.status) || attempt >= this.maxRetries) {
599
+ if (response.status === 429 && attempt >= this.maxRetries) {
600
+ throw new SernixaRateLimitError('Sernixa API rate limit persisted after retries.', {
601
+ statusCode: 429,
602
+ evidence: await responseText(response),
603
+ });
604
+ }
605
+ return response;
606
+ }
607
+ }
608
+ catch (error) {
609
+ clearTimeout(timeout);
610
+ lastError = error;
611
+ if (error instanceof SernixaError) {
612
+ throw error;
613
+ }
614
+ if (attempt >= this.maxRetries) {
615
+ if (isAbortError(error)) {
616
+ throw new SernixaTimeoutError('Sernixa API request timed out.', { cause: error });
617
+ }
618
+ throw new SernixaApiError('Sernixa API request failed.', { cause: error });
619
+ }
620
+ }
621
+ await sleep(Math.min(2000, 250 * 2 ** attempt));
622
+ }
623
+ throw new SernixaApiError('Sernixa API request failed.', { cause: lastError });
624
+ }
625
+ }
626
+ // ---------------------------------------------------------------------------
627
+ // Gateway
628
+ // ---------------------------------------------------------------------------
629
+ export class SernixaGateway {
630
+ client;
631
+ mcpProfile;
632
+ enforceEbpf;
633
+ constructor(options = {}) {
634
+ this.client = options.client ?? new Client(options);
635
+ this.mcpProfile = options.mcpProfile;
636
+ this.enforceEbpf = options.enforceEbpf ?? false;
637
+ }
638
+ async run(fn, options = {}) {
639
+ if (this.enforceEbpf) {
640
+ validateRuntimeEvidence(await this.client.readiness());
641
+ }
642
+ const profile = options.mcpProfile ?? this.mcpProfile ?? 'default';
643
+ return await this.client.execute(fn, {
644
+ intentId: options.intentId ?? 'agent-run',
645
+ actionId: options.actionId ?? `gateway:${profile}`,
646
+ riskLevel: options.riskLevel ?? 'MEDIUM',
647
+ operationClass: options.operationClass ?? 'agent_run',
648
+ dataSensitivity: options.dataSensitivity ?? 'internal',
649
+ systemsTouched: options.systemsTouched ?? ['mcp'],
650
+ metadata: {
651
+ ...options.metadata,
652
+ sernixa_gateway: true,
653
+ mcp_profile: profile,
654
+ enforce_ebpf: this.enforceEbpf,
655
+ runtime_evidence_required: this.enforceEbpf ? 'flight_recorder' : 'not_required',
656
+ },
657
+ });
658
+ }
659
+ }
660
+ // ---------------------------------------------------------------------------
661
+ // Runtime evidence validation
662
+ // ---------------------------------------------------------------------------
663
+ export function validateRuntimeEvidence(readiness) {
664
+ const checks = objectField(readiness, 'checks');
665
+ const configuration = objectField(checks, 'configuration');
666
+ const snapshot = objectField(configuration, 'snapshot');
667
+ const flight = objectField(checks, 'flight_recorder');
668
+ const snapshotFlight = objectField(snapshot, 'flight_recorder');
669
+ const runtimeMode = stringField(readiness, 'runtime_mode') ?? stringField(snapshot, 'runtime_mode');
670
+ const enabled = booleanField(flight, 'enabled') === true || booleanField(snapshotFlight, 'enabled') === true;
671
+ if (enabled) {
672
+ return;
673
+ }
674
+ if (runtimeMode === 'local_demo') {
675
+ console.warn('enforceEbpf=true requested in local_demo without Flight Recorder runtime enabled; execution is not production proof.');
676
+ return;
677
+ }
678
+ throw new SernixaConfigurationError('enforceEbpf=true requires Flight Recorder runtime support. The Sernixa /ready response did not report an enabled flight_recorder check.', { evidence: readiness });
679
+ }
680
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAEjE,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA;AAwJ9B,8EAA8E;AAC9E,YAAY;AACZ,8EAA8E;AAE9E,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAA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,CAAC"}
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@sernixa/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Sernixa TypeScript SDK — governed tool and agent execution with MCP call-gate support",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "build": "tsc",
17
+ "typecheck": "tsc --noEmit",
18
+ "test": "npm run build && node --test test/*.test.mjs"
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "sideEffects": false,
26
+ "engines": {
27
+ "node": ">=18.0.0"
28
+ },
29
+ "license": "MIT",
30
+ "author": "Sernixa Team",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/abhishekdhull63/Sernixa.ai-Web.git",
34
+ "directory": "packages/sdk"
35
+ },
36
+ "keywords": [
37
+ "sernixa",
38
+ "mcp",
39
+ "governance",
40
+ "agent",
41
+ "ai-safety",
42
+ "sdk",
43
+ "tool-governance"
44
+ ]
45
+ }