@tryvira/sdk 0.1.46 → 0.1.48

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,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
@@ -1,2 +1,3 @@
1
1
  export * from "./js-client.js";
2
2
  export * from "./framework-adapters.js";
3
+ export * from "./host-lifecycle.js";
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 digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
40
- const hex = [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
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
- headers.authorization = `Bearer ${this.apiKey}`;
98
- headers["x-vira-api-key"] = this.apiKey;
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;
@@ -469,15 +472,28 @@ var ViraClient = class {
469
472
  semanticContext: {
470
473
  taskKey: receipt.taskKey,
471
474
  behaviorPoint,
472
- capsule: firstCapsule
475
+ capsule: firstCapsule,
476
+ ...input.requestId ? { requestId: input.requestId } : {},
477
+ ...input.sessionId ? { conversationId: input.sessionId } : {}
473
478
  },
474
479
  idempotencyKey: input.idempotencyKey ? `sdk:runtime:${input.idempotencyKey}` : void 0
475
480
  }) : await this.resolveRuntime({
476
- semanticContext: { taskKey: receipt.taskKey, behaviorPoint, capsule: firstCapsule },
481
+ semanticContext: { taskKey: receipt.taskKey, behaviorPoint, capsule: firstCapsule, ...input.requestId ? { requestId: input.requestId } : {}, ...input.sessionId ? { conversationId: input.sessionId } : {} },
477
482
  idempotencyKey: input.idempotencyKey ? `sdk:runtime:${input.idempotencyKey}` : void 0
478
483
  });
479
484
  return { semantic, runtime };
480
485
  }
486
+ async authorizeHostAction(input) {
487
+ required(input.scope.organizationId, "SDK_ACTION_ORGANIZATION_REQUIRED");
488
+ required(input.scope.projectId, "SDK_ACTION_PROJECT_REQUIRED");
489
+ required(input.scope.environmentId, "SDK_ACTION_ENVIRONMENT_REQUIRED");
490
+ required(input.executionId, "SDK_ACTION_EXECUTION_REQUIRED");
491
+ return this.request({
492
+ method: "POST",
493
+ path: "/v1/runtime/actions/authorize",
494
+ body: { executionId: input.executionId, scope: input.scope, context: input.context, proposal: input.proposal }
495
+ });
496
+ }
481
497
  listBehaviorStrategies() {
482
498
  return this.request({
483
499
  method: "GET",
@@ -1186,6 +1202,110 @@ function createFrameworkLifecycleAdapter(client, framework, options = {}) {
1186
1202
  function createFrameworkAdapters(client) {
1187
1203
  return Object.freeze(Object.fromEntries(["openai-agents", "vercel-ai", "langchain", "langgraph", "otel", "mcp"].map((name) => [name, createFrameworkObservationAdapter(client, name)])));
1188
1204
  }
1205
+
1206
+ // ../../sdks/host-lifecycle.ts
1207
+ import { createHash } from "node:crypto";
1208
+ var nonEmpty = (value, code) => {
1209
+ if (typeof value !== "string" || !value.trim()) throw new Error(code);
1210
+ return value.trim();
1211
+ };
1212
+ var bounded = (value, fallback) => {
1213
+ const parsed = Number(value ?? fallback);
1214
+ if (!Number.isFinite(parsed) || parsed < 256) throw new Error("SDK_HOST_PROJECTION_BUDGET_INVALID");
1215
+ return Math.min(Math.floor(parsed), 64e3);
1216
+ };
1217
+ var lifecycleTimeout = (value) => {
1218
+ const parsed = Number(value ?? 15e3);
1219
+ if (!Number.isFinite(parsed) || parsed < 250) throw new Error("SDK_HOST_TIMEOUT_INVALID");
1220
+ return Math.min(Math.floor(parsed), 12e4);
1221
+ };
1222
+ var withTimeout = async (operation, timeoutMs, code) => {
1223
+ let timer;
1224
+ try {
1225
+ return await Promise.race([operation, new Promise((_, reject) => {
1226
+ timer = setTimeout(() => reject(new Error(code)), timeoutMs);
1227
+ })]);
1228
+ } finally {
1229
+ if (timer) clearTimeout(timer);
1230
+ }
1231
+ };
1232
+ var bodyOf = (response) => {
1233
+ if (response && typeof response === "object" && "body" in response) {
1234
+ const body = response.body;
1235
+ return body && typeof body === "object" && !Array.isArray(body) ? body : {};
1236
+ }
1237
+ return response && typeof response === "object" && !Array.isArray(response) ? response : {};
1238
+ };
1239
+ var isAllow = (decision) => decision.decision === "ALLOW" && Boolean(decision.authorityReceiptDigest && decision.decisionDigest);
1240
+ 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);
1241
+ var digest = (value) => createHash("sha256").update(canonical(value), "utf8").digest("hex");
1242
+ function createViraHostRuntime(client, config) {
1243
+ if (!client) throw new Error("SDK_HOST_CLIENT_REQUIRED");
1244
+ const mode = config.mode ?? "off";
1245
+ if (!["off", "observe", "enforce"].includes(mode)) throw new Error("SDK_HOST_MODE_INVALID");
1246
+ const capabilities = config.capabilities;
1247
+ if (!capabilities || typeof capabilities !== "object") throw new Error("SDK_HOST_CAPABILITIES_REQUIRED");
1248
+ const maxBytes = bounded(config.projectionMaxBytes, 8e3);
1249
+ const timeoutMs = lifecycleTimeout(config.timeoutMs);
1250
+ if (mode === "enforce" && (!capabilities.canInterceptToolBefore || !capabilities.canPreventSideEffect)) throw new Error("SDK_HOST_ENFORCE_CAPABILITY_REQUIRED");
1251
+ if (mode === "enforce" && typeof config.authorizeAction !== "function") throw new Error("SDK_HOST_ACTION_AUTHORIZER_REQUIRED");
1252
+ let connected = null;
1253
+ const projections = /* @__PURE__ */ new Map();
1254
+ const connectOnce = async () => {
1255
+ if (mode === "off" || !config.connect) return null;
1256
+ if (!connected) connected = withTimeout(client.connectOnce(config.connect), timeoutMs, "SDK_HOST_CONNECT_TIMEOUT");
1257
+ return connected;
1258
+ };
1259
+ const sessionKey = (request) => `${request.organizationId}:${request.projectId}:${request.environmentId}:${request.conversationId}`;
1260
+ const beforeModel = async (request) => {
1261
+ nonEmpty(request.input, "SDK_HOST_MODEL_INPUT_REQUIRED");
1262
+ if (mode === "off") return { status: "off" };
1263
+ if (!capabilities.canInjectContext) return { status: "unavailable", reasonCode: "HOST_CONTEXT_INJECTION_UNSUPPORTED" };
1264
+ await connectOnce();
1265
+ const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
1266
+ if (!semantic) return { status: "unavailable", reasonCode: "VIRA_SEMANTIC_UNAVAILABLE" };
1267
+ const semanticBody = bodyOf(semantic.semantic);
1268
+ const receipt = semanticBody.receipt && typeof semanticBody.receipt === "object" ? semanticBody.receipt : {};
1269
+ if (receipt.outcome !== "select" || typeof receipt.taskKey !== "string" || !semantic.runtime) {
1270
+ const result2 = { status: "abstain", taskKey: typeof receipt.taskKey === "string" ? receipt.taskKey : void 0, reasonCode: String(receipt.abstainReason ?? receipt.clarifyReason ?? "NO_BEHAVIOR_MATCH") };
1271
+ projections.set(sessionKey(request), result2);
1272
+ return result2;
1273
+ }
1274
+ const runtimeBody = bodyOf(semantic.runtime);
1275
+ const projection = runtimeBody.behaviorProjection && typeof runtimeBody.behaviorProjection === "object" ? runtimeBody.behaviorProjection : {};
1276
+ const rendered = typeof projection.rendered === "string" ? projection.rendered : "";
1277
+ if (!rendered.trim()) return { status: "abstain", taskKey: String(receipt.taskKey), reasonCode: "EMPTY_BEHAVIOR_PROJECTION" };
1278
+ if (Buffer.byteLength(rendered, "utf8") > maxBytes) return { status: "unavailable", taskKey: String(receipt.taskKey), reasonCode: "BEHAVIOR_PROJECTION_BUDGET_EXCEEDED" };
1279
+ 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 };
1280
+ projections.set(sessionKey(request), result);
1281
+ return result;
1282
+ };
1283
+ const beforeTool = async (proposal) => {
1284
+ nonEmpty(proposal.callId, "SDK_HOST_TOOL_CALL_ID_REQUIRED");
1285
+ nonEmpty(proposal.toolName, "SDK_HOST_TOOL_NAME_REQUIRED");
1286
+ if (mode !== "enforce") return { decision: "ABSTAIN", reasonCode: mode === "off" ? "HOST_MODE_OFF" : "OBSERVE_ONLY" };
1287
+ let decision;
1288
+ try {
1289
+ decision = await withTimeout(Promise.resolve(config.authorizeAction(proposal)), timeoutMs, "SDK_HOST_ACTION_AUTHORIZATION_TIMEOUT");
1290
+ } catch {
1291
+ return { decision: "ERROR", reasonCode: "VIRA_ACTION_AUTHORIZATION_TIMEOUT" };
1292
+ }
1293
+ if (!decision || !["ALLOW", "BLOCK", "ESCALATE", "ABSTAIN", "ERROR"].includes(decision.decision)) throw new Error("SDK_HOST_ACTION_DECISION_INVALID");
1294
+ if (decision.decision === "ALLOW" && !isAllow(decision)) throw new Error("SDK_HOST_ALLOW_RECEIPT_INVALID");
1295
+ return decision;
1296
+ };
1297
+ const afterTool = async (result) => {
1298
+ nonEmpty(result.callId, "SDK_HOST_TOOL_CALL_ID_REQUIRED");
1299
+ if (mode === "off" || !capabilities.canInspectToolAfter) return { status: "off" };
1300
+ const observedResult = result.ok ? result.result : { errorCode: result.errorCode ?? "HOST_TOOL_FAILED" };
1301
+ 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 } : {} };
1302
+ 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");
1303
+ };
1304
+ const endSession = (identity) => {
1305
+ projections.delete(sessionKey({ ...identity, requestId: "session-end", input: "" }));
1306
+ };
1307
+ return Object.freeze({ mode, capabilities, connectOnce, beforeModel, beforeTool, afterTool, endSession, getProjection: (identity) => projections.get(sessionKey({ ...identity, requestId: "projection", input: "" })), supportsPostModelVerification: capabilities.canInterceptResponseBeforeDisplay });
1308
+ }
1189
1309
  export {
1190
1310
  ViraApiError,
1191
1311
  ViraClient,
@@ -1204,6 +1324,7 @@ export {
1204
1324
  createOpenAIAgentsHooks,
1205
1325
  createOpenAICompatibleHooks,
1206
1326
  createVercelAIHooks,
1327
+ createViraHostRuntime,
1207
1328
  createViraMiddleware,
1208
1329
  resolveFrameworkBoundary
1209
1330
  };
@@ -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.46",
3
+ "version": "0.1.48",
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"