@tryvira/sdk 0.1.46 → 0.1.47
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/dist/host-lifecycle.d.ts +93 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +123 -4
- package/dist/js-client.d.ts +10 -0
- package/package.json +2 -2
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { ViraClient, ViraResponse } from './js-client.ts';
|
|
2
|
+
export type HostLifecycleMode = 'off' | 'observe' | 'enforce';
|
|
3
|
+
export type HostActionDecision = 'ALLOW' | 'BLOCK' | 'ESCALATE' | 'ABSTAIN' | 'ERROR';
|
|
4
|
+
export interface HostCapabilities {
|
|
5
|
+
canObserveModel: boolean;
|
|
6
|
+
canInjectContext: boolean;
|
|
7
|
+
canInterceptToolBefore: boolean;
|
|
8
|
+
canInspectToolAfter: boolean;
|
|
9
|
+
canPreventSideEffect: boolean;
|
|
10
|
+
canInterceptResponseBeforeDisplay: boolean;
|
|
11
|
+
coversMcp?: boolean;
|
|
12
|
+
supportsSessionFork?: boolean;
|
|
13
|
+
}
|
|
14
|
+
export interface HostSessionIdentity {
|
|
15
|
+
hostName: string;
|
|
16
|
+
hostVersion: string;
|
|
17
|
+
aiSystemId: string;
|
|
18
|
+
connectionId: string;
|
|
19
|
+
organizationId: string;
|
|
20
|
+
projectId: string;
|
|
21
|
+
environmentId: string;
|
|
22
|
+
conversationId: string;
|
|
23
|
+
sessionId?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface HostModelRequest extends HostSessionIdentity {
|
|
26
|
+
requestId: string;
|
|
27
|
+
input: string;
|
|
28
|
+
traceId?: string;
|
|
29
|
+
turnId?: string;
|
|
30
|
+
sequence?: number;
|
|
31
|
+
}
|
|
32
|
+
export interface HostToolProposal extends HostSessionIdentity {
|
|
33
|
+
requestId: string;
|
|
34
|
+
callId: string;
|
|
35
|
+
toolName: string;
|
|
36
|
+
args: Record<string, unknown>;
|
|
37
|
+
traceId?: string;
|
|
38
|
+
turnId?: string;
|
|
39
|
+
}
|
|
40
|
+
export interface HostToolResult extends HostToolProposal {
|
|
41
|
+
ok: boolean;
|
|
42
|
+
result?: unknown;
|
|
43
|
+
errorCode?: string;
|
|
44
|
+
resultDigest?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface HostToolEvidence {
|
|
47
|
+
abi: 'vira.host-tool-evidence.v1';
|
|
48
|
+
eventId: string;
|
|
49
|
+
callId: string;
|
|
50
|
+
toolName: string;
|
|
51
|
+
argumentsDigest: string;
|
|
52
|
+
resultDigest: string;
|
|
53
|
+
outcome: 'success' | 'failure';
|
|
54
|
+
requestId: string;
|
|
55
|
+
conversationId: string;
|
|
56
|
+
sessionId?: string;
|
|
57
|
+
turnId?: string;
|
|
58
|
+
}
|
|
59
|
+
export interface HostActionAuthorization {
|
|
60
|
+
decision: HostActionDecision;
|
|
61
|
+
authorityReceiptDigest?: string;
|
|
62
|
+
decisionDigest?: string;
|
|
63
|
+
reasonCode?: string;
|
|
64
|
+
expiresAt?: string;
|
|
65
|
+
}
|
|
66
|
+
export interface HostLifecycleConfig {
|
|
67
|
+
mode?: HostLifecycleMode;
|
|
68
|
+
capabilities: HostCapabilities;
|
|
69
|
+
connect?: Parameters<ViraClient['connectOnce']>[0];
|
|
70
|
+
authorizeAction?: (proposal: HostToolProposal) => Promise<HostActionAuthorization> | HostActionAuthorization;
|
|
71
|
+
projectionMaxBytes?: number;
|
|
72
|
+
timeoutMs?: number;
|
|
73
|
+
}
|
|
74
|
+
export interface HostProjectionResult {
|
|
75
|
+
status: 'applied' | 'abstain' | 'off' | 'unavailable';
|
|
76
|
+
response?: ViraResponse<unknown> | null;
|
|
77
|
+
projection?: string;
|
|
78
|
+
projectionDigest?: string;
|
|
79
|
+
taskKey?: string;
|
|
80
|
+
behaviorPoint?: string;
|
|
81
|
+
reasonCode?: string;
|
|
82
|
+
}
|
|
83
|
+
export declare function createViraHostRuntime(client: ViraClient, config: HostLifecycleConfig): Readonly<{
|
|
84
|
+
mode: HostLifecycleMode;
|
|
85
|
+
capabilities: HostCapabilities;
|
|
86
|
+
connectOnce: () => Promise<unknown>;
|
|
87
|
+
beforeModel: (request: HostModelRequest) => Promise<HostProjectionResult>;
|
|
88
|
+
beforeTool: (proposal: HostToolProposal) => Promise<HostActionAuthorization>;
|
|
89
|
+
afterTool: (result: HostToolResult) => Promise<unknown>;
|
|
90
|
+
endSession: (identity: HostSessionIdentity) => void;
|
|
91
|
+
getProjection: (identity: HostSessionIdentity) => HostProjectionResult | undefined;
|
|
92
|
+
supportsPostModelVerification: boolean;
|
|
93
|
+
}>;
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -36,8 +36,8 @@ var canonicalJson = (value) => JSON.stringify(
|
|
|
36
36
|
var contentIdempotencyKey = async (operation, request) => {
|
|
37
37
|
if (!globalThis.crypto?.subtle) throw new Error("SDK_IDEMPOTENCY_CRYPTO_UNAVAILABLE");
|
|
38
38
|
const bytes = new TextEncoder().encode(canonicalJson(request));
|
|
39
|
-
const
|
|
40
|
-
const hex = [...new Uint8Array(
|
|
39
|
+
const digest2 = await globalThis.crypto.subtle.digest("SHA-256", bytes);
|
|
40
|
+
const hex = [...new Uint8Array(digest2)].map((value) => value.toString(16).padStart(2, "0")).join("");
|
|
41
41
|
return `${operation}:${hex}`;
|
|
42
42
|
};
|
|
43
43
|
var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -94,8 +94,11 @@ var ViraClient = class {
|
|
|
94
94
|
};
|
|
95
95
|
if (request.body) headers["content-type"] = "application/json";
|
|
96
96
|
if (this.apiKey) {
|
|
97
|
-
|
|
98
|
-
|
|
97
|
+
if (this.apiKey.startsWith("vira_live_")) headers["x-vira-api-key"] = this.apiKey;
|
|
98
|
+
else {
|
|
99
|
+
headers.authorization = `Bearer ${this.apiKey}`;
|
|
100
|
+
headers["x-vira-api-key"] = this.apiKey;
|
|
101
|
+
}
|
|
99
102
|
}
|
|
100
103
|
if (options.idempotencyKey)
|
|
101
104
|
headers["idempotency-key"] = options.idempotencyKey;
|
|
@@ -478,6 +481,17 @@ var ViraClient = class {
|
|
|
478
481
|
});
|
|
479
482
|
return { semantic, runtime };
|
|
480
483
|
}
|
|
484
|
+
async authorizeHostAction(input) {
|
|
485
|
+
required(input.scope.organizationId, "SDK_ACTION_ORGANIZATION_REQUIRED");
|
|
486
|
+
required(input.scope.projectId, "SDK_ACTION_PROJECT_REQUIRED");
|
|
487
|
+
required(input.scope.environmentId, "SDK_ACTION_ENVIRONMENT_REQUIRED");
|
|
488
|
+
required(input.executionId, "SDK_ACTION_EXECUTION_REQUIRED");
|
|
489
|
+
return this.request({
|
|
490
|
+
method: "POST",
|
|
491
|
+
path: "/v1/runtime/actions/authorize",
|
|
492
|
+
body: { executionId: input.executionId, scope: input.scope, context: input.context, proposal: input.proposal }
|
|
493
|
+
});
|
|
494
|
+
}
|
|
481
495
|
listBehaviorStrategies() {
|
|
482
496
|
return this.request({
|
|
483
497
|
method: "GET",
|
|
@@ -1186,6 +1200,110 @@ function createFrameworkLifecycleAdapter(client, framework, options = {}) {
|
|
|
1186
1200
|
function createFrameworkAdapters(client) {
|
|
1187
1201
|
return Object.freeze(Object.fromEntries(["openai-agents", "vercel-ai", "langchain", "langgraph", "otel", "mcp"].map((name) => [name, createFrameworkObservationAdapter(client, name)])));
|
|
1188
1202
|
}
|
|
1203
|
+
|
|
1204
|
+
// ../../sdks/host-lifecycle.ts
|
|
1205
|
+
import { createHash } from "node:crypto";
|
|
1206
|
+
var nonEmpty = (value, code) => {
|
|
1207
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(code);
|
|
1208
|
+
return value.trim();
|
|
1209
|
+
};
|
|
1210
|
+
var bounded = (value, fallback) => {
|
|
1211
|
+
const parsed = Number(value ?? fallback);
|
|
1212
|
+
if (!Number.isFinite(parsed) || parsed < 256) throw new Error("SDK_HOST_PROJECTION_BUDGET_INVALID");
|
|
1213
|
+
return Math.min(Math.floor(parsed), 64e3);
|
|
1214
|
+
};
|
|
1215
|
+
var lifecycleTimeout = (value) => {
|
|
1216
|
+
const parsed = Number(value ?? 15e3);
|
|
1217
|
+
if (!Number.isFinite(parsed) || parsed < 250) throw new Error("SDK_HOST_TIMEOUT_INVALID");
|
|
1218
|
+
return Math.min(Math.floor(parsed), 12e4);
|
|
1219
|
+
};
|
|
1220
|
+
var withTimeout = async (operation, timeoutMs, code) => {
|
|
1221
|
+
let timer;
|
|
1222
|
+
try {
|
|
1223
|
+
return await Promise.race([operation, new Promise((_, reject) => {
|
|
1224
|
+
timer = setTimeout(() => reject(new Error(code)), timeoutMs);
|
|
1225
|
+
})]);
|
|
1226
|
+
} finally {
|
|
1227
|
+
if (timer) clearTimeout(timer);
|
|
1228
|
+
}
|
|
1229
|
+
};
|
|
1230
|
+
var bodyOf = (response) => {
|
|
1231
|
+
if (response && typeof response === "object" && "body" in response) {
|
|
1232
|
+
const body = response.body;
|
|
1233
|
+
return body && typeof body === "object" && !Array.isArray(body) ? body : {};
|
|
1234
|
+
}
|
|
1235
|
+
return response && typeof response === "object" && !Array.isArray(response) ? response : {};
|
|
1236
|
+
};
|
|
1237
|
+
var isAllow = (decision) => decision.decision === "ALLOW" && Boolean(decision.authorityReceiptDigest && decision.decisionDigest);
|
|
1238
|
+
var canonical = (value) => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` : value && typeof value === "object" ? `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => `${JSON.stringify(key)}:${canonical(child)}`).join(",")}}` : JSON.stringify(value);
|
|
1239
|
+
var digest = (value) => createHash("sha256").update(canonical(value), "utf8").digest("hex");
|
|
1240
|
+
function createViraHostRuntime(client, config) {
|
|
1241
|
+
if (!client) throw new Error("SDK_HOST_CLIENT_REQUIRED");
|
|
1242
|
+
const mode = config.mode ?? "off";
|
|
1243
|
+
if (!["off", "observe", "enforce"].includes(mode)) throw new Error("SDK_HOST_MODE_INVALID");
|
|
1244
|
+
const capabilities = config.capabilities;
|
|
1245
|
+
if (!capabilities || typeof capabilities !== "object") throw new Error("SDK_HOST_CAPABILITIES_REQUIRED");
|
|
1246
|
+
const maxBytes = bounded(config.projectionMaxBytes, 8e3);
|
|
1247
|
+
const timeoutMs = lifecycleTimeout(config.timeoutMs);
|
|
1248
|
+
if (mode === "enforce" && (!capabilities.canInterceptToolBefore || !capabilities.canPreventSideEffect)) throw new Error("SDK_HOST_ENFORCE_CAPABILITY_REQUIRED");
|
|
1249
|
+
if (mode === "enforce" && typeof config.authorizeAction !== "function") throw new Error("SDK_HOST_ACTION_AUTHORIZER_REQUIRED");
|
|
1250
|
+
let connected = null;
|
|
1251
|
+
const projections = /* @__PURE__ */ new Map();
|
|
1252
|
+
const connectOnce = async () => {
|
|
1253
|
+
if (mode === "off" || !config.connect) return null;
|
|
1254
|
+
if (!connected) connected = withTimeout(client.connectOnce(config.connect), timeoutMs, "SDK_HOST_CONNECT_TIMEOUT");
|
|
1255
|
+
return connected;
|
|
1256
|
+
};
|
|
1257
|
+
const sessionKey = (request) => `${request.organizationId}:${request.projectId}:${request.environmentId}:${request.conversationId}`;
|
|
1258
|
+
const beforeModel = async (request) => {
|
|
1259
|
+
nonEmpty(request.input, "SDK_HOST_MODEL_INPUT_REQUIRED");
|
|
1260
|
+
if (mode === "off") return { status: "off" };
|
|
1261
|
+
if (!capabilities.canInjectContext) return { status: "unavailable", reasonCode: "HOST_CONTEXT_INJECTION_UNSUPPORTED" };
|
|
1262
|
+
await connectOnce();
|
|
1263
|
+
const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
|
|
1264
|
+
if (!semantic) return { status: "unavailable", reasonCode: "VIRA_SEMANTIC_UNAVAILABLE" };
|
|
1265
|
+
const semanticBody = bodyOf(semantic.semantic);
|
|
1266
|
+
const receipt = semanticBody.receipt && typeof semanticBody.receipt === "object" ? semanticBody.receipt : {};
|
|
1267
|
+
if (receipt.outcome !== "select" || typeof receipt.taskKey !== "string" || !semantic.runtime) {
|
|
1268
|
+
const result2 = { status: "abstain", taskKey: typeof receipt.taskKey === "string" ? receipt.taskKey : void 0, reasonCode: String(receipt.abstainReason ?? receipt.clarifyReason ?? "NO_BEHAVIOR_MATCH") };
|
|
1269
|
+
projections.set(sessionKey(request), result2);
|
|
1270
|
+
return result2;
|
|
1271
|
+
}
|
|
1272
|
+
const runtimeBody = bodyOf(semantic.runtime);
|
|
1273
|
+
const projection = runtimeBody.behaviorProjection && typeof runtimeBody.behaviorProjection === "object" ? runtimeBody.behaviorProjection : {};
|
|
1274
|
+
const rendered = typeof projection.rendered === "string" ? projection.rendered : "";
|
|
1275
|
+
if (!rendered.trim()) return { status: "abstain", taskKey: String(receipt.taskKey), reasonCode: "EMPTY_BEHAVIOR_PROJECTION" };
|
|
1276
|
+
if (Buffer.byteLength(rendered, "utf8") > maxBytes) return { status: "unavailable", taskKey: String(receipt.taskKey), reasonCode: "BEHAVIOR_PROJECTION_BUDGET_EXCEEDED" };
|
|
1277
|
+
const result = { status: "applied", response: semantic.runtime, projection: rendered, projectionDigest: typeof projection.projectionDigest === "string" ? projection.projectionDigest : void 0, taskKey: String(receipt.taskKey), behaviorPoint: typeof runtimeBody.behaviorPoint === "string" ? runtimeBody.behaviorPoint : void 0 };
|
|
1278
|
+
projections.set(sessionKey(request), result);
|
|
1279
|
+
return result;
|
|
1280
|
+
};
|
|
1281
|
+
const beforeTool = async (proposal) => {
|
|
1282
|
+
nonEmpty(proposal.callId, "SDK_HOST_TOOL_CALL_ID_REQUIRED");
|
|
1283
|
+
nonEmpty(proposal.toolName, "SDK_HOST_TOOL_NAME_REQUIRED");
|
|
1284
|
+
if (mode !== "enforce") return { decision: "ABSTAIN", reasonCode: mode === "off" ? "HOST_MODE_OFF" : "OBSERVE_ONLY" };
|
|
1285
|
+
let decision;
|
|
1286
|
+
try {
|
|
1287
|
+
decision = await withTimeout(Promise.resolve(config.authorizeAction(proposal)), timeoutMs, "SDK_HOST_ACTION_AUTHORIZATION_TIMEOUT");
|
|
1288
|
+
} catch {
|
|
1289
|
+
return { decision: "ERROR", reasonCode: "VIRA_ACTION_AUTHORIZATION_TIMEOUT" };
|
|
1290
|
+
}
|
|
1291
|
+
if (!decision || !["ALLOW", "BLOCK", "ESCALATE", "ABSTAIN", "ERROR"].includes(decision.decision)) throw new Error("SDK_HOST_ACTION_DECISION_INVALID");
|
|
1292
|
+
if (decision.decision === "ALLOW" && !isAllow(decision)) throw new Error("SDK_HOST_ALLOW_RECEIPT_INVALID");
|
|
1293
|
+
return decision;
|
|
1294
|
+
};
|
|
1295
|
+
const afterTool = async (result) => {
|
|
1296
|
+
nonEmpty(result.callId, "SDK_HOST_TOOL_CALL_ID_REQUIRED");
|
|
1297
|
+
if (mode === "off" || !capabilities.canInspectToolAfter) return { status: "off" };
|
|
1298
|
+
const observedResult = result.ok ? result.result : { errorCode: result.errorCode ?? "HOST_TOOL_FAILED" };
|
|
1299
|
+
const evidence = { abi: "vira.host-tool-evidence.v1", eventId: result.callId, callId: result.callId, toolName: result.toolName, argumentsDigest: digest(result.args), resultDigest: result.resultDigest ?? digest(observedResult), outcome: result.ok ? "success" : "failure", requestId: result.requestId, conversationId: result.conversationId, ...result.sessionId ? { sessionId: result.sessionId } : {}, ...result.turnId ? { turnId: result.turnId } : {} };
|
|
1300
|
+
return withTimeout(client.observe({ eventId: result.callId, eventType: result.ok ? "tool.result" : "tool.failed", aiSystemId: result.aiSystemId, connectionId: result.connectionId, organizationId: result.organizationId, projectId: result.projectId, environmentId: result.environmentId, conversationId: result.conversationId, requestId: result.requestId, traceId: result.traceId, payload: { result: observedResult, evidence }, resultDigest: evidence.resultDigest }), timeoutMs, "SDK_HOST_OBSERVE_TIMEOUT");
|
|
1301
|
+
};
|
|
1302
|
+
const endSession = (identity) => {
|
|
1303
|
+
projections.delete(sessionKey({ ...identity, requestId: "session-end", input: "" }));
|
|
1304
|
+
};
|
|
1305
|
+
return Object.freeze({ mode, capabilities, connectOnce, beforeModel, beforeTool, afterTool, endSession, getProjection: (identity) => projections.get(sessionKey({ ...identity, requestId: "projection", input: "" })), supportsPostModelVerification: capabilities.canInterceptResponseBeforeDisplay });
|
|
1306
|
+
}
|
|
1189
1307
|
export {
|
|
1190
1308
|
ViraApiError,
|
|
1191
1309
|
ViraClient,
|
|
@@ -1204,6 +1322,7 @@ export {
|
|
|
1204
1322
|
createOpenAIAgentsHooks,
|
|
1205
1323
|
createOpenAICompatibleHooks,
|
|
1206
1324
|
createVercelAIHooks,
|
|
1325
|
+
createViraHostRuntime,
|
|
1207
1326
|
createViraMiddleware,
|
|
1208
1327
|
resolveFrameworkBoundary
|
|
1209
1328
|
};
|
package/dist/js-client.d.ts
CHANGED
|
@@ -366,6 +366,16 @@ export declare class ViraClient {
|
|
|
366
366
|
semantic: ViraResponse<ClientBody>;
|
|
367
367
|
runtime: ViraResponse<RuntimeResolution> | null;
|
|
368
368
|
} | null>;
|
|
369
|
+
authorizeHostAction(input: {
|
|
370
|
+
executionId: string;
|
|
371
|
+
scope: {
|
|
372
|
+
organizationId: string;
|
|
373
|
+
projectId: string;
|
|
374
|
+
environmentId: string;
|
|
375
|
+
};
|
|
376
|
+
context: Record<string, unknown>;
|
|
377
|
+
proposal: Record<string, unknown>;
|
|
378
|
+
}): Promise<ViraResponse<ClientBody> | null>;
|
|
369
379
|
listBehaviorStrategies(): Promise<ViraResponse<ClientBody> | null>;
|
|
370
380
|
deleteBehaviorStrategy(strategyId: string, options?: {
|
|
371
381
|
confirm?: boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tryvira/sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.47",
|
|
4
4
|
"description": "Typed Vira SDK for connect-once, observation and governed runtime execution.",
|
|
5
5
|
"keywords": ["vira", "ai-governance", "ai-runtime", "semantic-routing"],
|
|
6
6
|
"engines": {"node": ">=20"},
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"main": "./dist/index.js",
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"exports": {".": {"types": "./dist/index.d.ts", "import": "./dist/index.js"}},
|
|
14
|
-
"files": ["dist/index.js", "dist/index.d.ts", "dist/js-client.d.ts", "dist/framework-adapters.d.ts", "README.md"],
|
|
14
|
+
"files": ["dist/index.js", "dist/index.d.ts", "dist/js-client.d.ts", "dist/framework-adapters.d.ts", "dist/host-lifecycle.d.ts", "README.md"],
|
|
15
15
|
"publishConfig": {"access": "public"},
|
|
16
16
|
"scripts": {"build": "node ../../scripts/build-publishable-packages.mjs sdk", "pack:check": "npm run build && npm pack --dry-run && npm run public:surface:smoke", "public:surface:smoke": "node ../../scripts/public-surface-contract-acceptance.mjs --sdk-package", "prepublishOnly": "npm run pack:check && npm run public:surface:smoke", "publish:public": "npm run pack:check && npm run public:surface:smoke && npm publish --access public"},
|
|
17
17
|
"license": "MIT"
|