@tryvira/sdk 0.1.58 → 0.1.60

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.
@@ -33,6 +33,8 @@ export interface HostModelRequest extends HostSessionIdentity {
33
33
  mappingId: string;
34
34
  eventId: string;
35
35
  }[];
36
+ profile?: Record<string, unknown>;
37
+ revisionId?: string;
36
38
  }
37
39
  export interface HostToolProposal extends HostSessionIdentity {
38
40
  requestId: string;
@@ -42,6 +44,16 @@ export interface HostToolProposal extends HostSessionIdentity {
42
44
  traceId?: string;
43
45
  turnId?: string;
44
46
  }
47
+ /** Server-issued mapping between a host/framework tool name and the canonical
48
+ * Vira policy identity. Host names and aliases are never treated as policy
49
+ * IDs unless this immutable contract is present in the runtime context. */
50
+ export interface HostToolBinding {
51
+ toolId: string;
52
+ hostActionName: string;
53
+ aliases: readonly string[];
54
+ schemaDigest: string;
55
+ }
56
+ export declare function resolveHostToolBinding(bindings: readonly HostToolBinding[] | undefined, hostToolName: string): HostToolBinding | null;
45
57
  export interface HostToolResult extends HostToolProposal {
46
58
  ok: boolean;
47
59
  result?: unknown;
@@ -79,6 +91,14 @@ export interface HostLifecycleConfig {
79
91
  authorizeAction?: (proposal: HostToolProposal) => Promise<HostActionAuthorization> | HostActionAuthorization;
80
92
  projectionMaxBytes?: number;
81
93
  timeoutMs?: number;
94
+ /** Maximum time a granted tool may hold the session lock when the host never
95
+ * emits execute.after. This releases governance state; it cannot interrupt a
96
+ * host callback that the framework does not expose a cancellation signal for. */
97
+ toolSessionTimeoutMs?: number;
98
+ /** Maximum serialized size of a tool result admitted to observation telemetry. */
99
+ toolObservationMaxBytes?: number;
100
+ /** Additional customer-approved field names to redact case-insensitively. */
101
+ toolObservationRedactKeys?: readonly string[];
82
102
  }
83
103
  export interface GovernedToolExecution<T = unknown> {
84
104
  proposal: HostToolProposal;
@@ -90,28 +110,51 @@ export interface GovernedToolResult<T = unknown> {
90
110
  result?: T;
91
111
  observation?: unknown;
92
112
  }
113
+ export interface HostObservationResult {
114
+ status: 'observed' | 'failed' | 'skipped' | 'off';
115
+ response?: unknown;
116
+ errorCode?: string;
117
+ /** The tool may already have produced a real side effect; this is telemetry
118
+ * state only and must never be interpreted as an execution retry signal. */
119
+ executionCommitted?: true;
120
+ }
93
121
  export interface HostConnectionIdentity {
94
122
  aiSystemId: string;
95
123
  connectionId: string;
96
124
  }
97
125
  export interface HostProjectionResult {
98
- status: 'applied' | 'abstain' | 'off' | 'unavailable';
126
+ status: 'applied' | 'task_run' | 'abstain' | 'off' | 'unavailable';
99
127
  response?: ViraResponse<unknown> | null;
100
128
  projection?: string;
101
129
  projectionDigest?: string;
102
130
  taskKey?: string;
103
131
  behaviorPoint?: string;
132
+ taskRunId?: string;
133
+ taskRunStateVersion?: number;
134
+ selectedTaskKeys?: readonly string[];
104
135
  reasonCode?: string;
105
136
  }
137
+ export declare function redactToolObservation(value: unknown, options?: {
138
+ maxBytes?: number;
139
+ redactKeys?: readonly string[];
140
+ }): {
141
+ value: unknown;
142
+ redacted: boolean;
143
+ truncated: boolean;
144
+ };
106
145
  export declare function createViraHostRuntime(client: ViraClient, config: HostLifecycleConfig): Readonly<{
107
146
  mode: HostLifecycleMode;
108
147
  capabilities: HostCapabilities;
109
- connectOnce: () => Promise<unknown>;
148
+ connectOnce: (options?: {
149
+ force?: boolean;
150
+ }) => Promise<unknown>;
151
+ reconnect: () => Promise<unknown>;
110
152
  getConnectionIdentity: () => HostConnectionIdentity | null;
111
153
  beforeModel: (request: HostModelRequest) => Promise<HostProjectionResult>;
112
154
  beforeTool: (proposal: HostToolProposal) => Promise<HostActionAuthorization>;
113
- afterTool: (result: HostToolResult) => Promise<unknown>;
155
+ afterTool: (result: HostToolResult) => Promise<HostObservationResult>;
114
156
  executeTool: <T>(input: GovernedToolExecution<T>) => Promise<GovernedToolResult<T>>;
157
+ cancelTool: (identity: HostSessionIdentity, callId?: string) => boolean;
115
158
  endSession: (identity: HostSessionIdentity) => void;
116
159
  getProjection: (identity: HostSessionIdentity) => HostProjectionResult | undefined;
117
160
  supportsPostModelVerification: boolean;
package/dist/index.js CHANGED
@@ -201,13 +201,31 @@ var ViraClient = class {
201
201
  if (!systemResult) return null;
202
202
  const systemId = String(systemResult.body.system.id ?? "");
203
203
  required(systemId, "SDK_SYSTEM_ID_MISSING");
204
- const connectionResult = await this.connectAdapter(systemId, {
205
- adapterType: input.adapterType,
206
- adapterVersion: input.adapterVersion,
207
- capabilities: input.capabilities,
208
- config: input.config,
209
- idempotencyKey: input.idempotencyKey
210
- });
204
+ let connectionResult;
205
+ try {
206
+ connectionResult = await this.connectAdapter(systemId, {
207
+ adapterType: input.adapterType,
208
+ adapterVersion: input.adapterVersion,
209
+ capabilities: input.capabilities,
210
+ config: input.config,
211
+ idempotencyKey: input.idempotencyKey
212
+ });
213
+ } catch (error) {
214
+ if (!(input.reuseExistingConnectionOnConflict !== false && error instanceof ViraApiError && error.status === 409)) throw error;
215
+ const listed = await this.listSystemConnections(systemId);
216
+ const connections = Array.isArray(listed?.body?.connections) ? listed.body.connections : [];
217
+ const requested = new Set((input.capabilities ?? []).map(String));
218
+ const reused = connections.find((connection) => String(connection.adapterType ?? "") === input.adapterType && requested.size <= new Set(Array.isArray(connection.capabilities) ? connection.capabilities.map(String) : []).size && [...requested].every((capability) => (Array.isArray(connection.capabilities) ? connection.capabilities.map(String) : []).includes(capability)));
219
+ if (!reused) throw error;
220
+ const verified = await this.getConnection(String(reused.id ?? ""));
221
+ const verifiedConnection = verified?.body?.connection && typeof verified.body.connection === "object" ? verified.body.connection : null;
222
+ if (!verifiedConnection || String(verifiedConnection.adapterType ?? "") !== input.adapterType) throw error;
223
+ const verifiedCapabilities = Array.isArray(verifiedConnection.capabilities) ? verifiedConnection.capabilities.map(String) : [];
224
+ if (![...requested].every((capability) => verifiedCapabilities.includes(capability))) throw error;
225
+ const fromVersion = String(verifiedConnection.adapterVersion ?? "");
226
+ const transition = fromVersion === input.adapterVersion ? "UNCHANGED" : "REUSE_COMPATIBLE";
227
+ connectionResult = { status: 200, requestId: verified?.requestId ?? listed?.requestId ?? error.requestId, body: { connection: verifiedConnection, handshake: { adapterType: input.adapterType, accepted: verifiedCapabilities, rejected: [], configValid: true, reusedExistingConnection: true, adapterVersionTransition: { from: fromVersion, to: input.adapterVersion, mode: transition } } } };
228
+ }
211
229
  if (!connectionResult) return null;
212
230
  const connectedId = String(connectionResult.body.connection?.id ?? "").trim();
213
231
  if (connectedId) this.boundConnectionId = connectedId;
@@ -222,9 +240,19 @@ var ViraClient = class {
222
240
  };
223
241
  }
224
242
  observe(event, options = {}) {
225
- return this.request(buildObservationRequest(event), {
226
- idempotencyKey: options.idempotencyKey ?? event.eventId
227
- });
243
+ buildObservationRequest(event);
244
+ return (async () => {
245
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : void 0;
246
+ const source = event.attributes && typeof event.attributes === "object" ? String(event.attributes.source ?? "") : "";
247
+ const safeEvent = source === "opencode.context" && payload && typeof payload.text === "string" ? { ...event, payload: { ...payload, text: void 0, textDigest: (await contentIdempotencyKey("observation:text", payload.text)).split(":").pop(), minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } } : event;
248
+ const response = await this.request(buildObservationRequest(safeEvent), {
249
+ idempotencyKey: options.idempotencyKey ?? event.eventId
250
+ });
251
+ if (event.eventType === "conversation.output") {
252
+ await this.request(buildObservationRequest({ ...safeEvent, eventType: "model.response", eventId: `${event.eventId}:model.response`, payload: { ...safeEvent.payload ?? {}, status: "completed" } }), { idempotencyKey: `${options.idempotencyKey ?? event.eventId}:model.response` });
253
+ }
254
+ return response;
255
+ })();
228
256
  }
229
257
  trace(event, options = {}) {
230
258
  return this.observe({ ...event, eventType: "model.response" }, options);
@@ -469,9 +497,12 @@ var ViraClient = class {
469
497
  const body = semantic.body;
470
498
  const receipt = body.receipt && typeof body.receipt === "object" ? body.receipt : {};
471
499
  if (receipt.outcome !== "select" || typeof receipt.taskKey !== "string")
472
- return { semantic, runtime: null };
500
+ return { semantic, runtime: null, taskKeys: [], capsules: [], multiTask: false };
473
501
  const capsules = Array.isArray(body.capsules) ? body.capsules : [];
474
- const firstCapsule = capsules[0] && typeof capsules[0] === "object" ? capsules[0] : {};
502
+ const candidateValues = Array.isArray(body.intentCandidates) ? body.intentCandidates : Array.isArray(body.selectedTaskKeys) ? body.selectedTaskKeys : [];
503
+ const taskKeys = [...new Set(candidateValues.map((value) => typeof value === "string" ? value.trim() : value && typeof value === "object" ? String(value.taskKey ?? value.semanticTaskKey ?? "").trim() : "").filter(Boolean))];
504
+ if (!taskKeys.length) taskKeys.push(receipt.taskKey.trim());
505
+ const firstCapsule = capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) && typeof capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) === "object" ? capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) : capsules[0] && typeof capsules[0] === "object" ? capsules[0] : {};
475
506
  const behaviorPoint = typeof firstCapsule.behaviorKey === "string" && firstCapsule.behaviorKey.trim() ? firstCapsule.behaviorKey : receipt.taskKey;
476
507
  const runtime = input.executionBoundary ? await this.resolveBoundary({
477
508
  executionBoundary: input.executionBoundary,
@@ -479,16 +510,17 @@ var ViraClient = class {
479
510
  taskKey: receipt.taskKey,
480
511
  behaviorPoint,
481
512
  capsule: firstCapsule,
513
+ ...input.revisionId ? { revisionId: input.revisionId } : {},
482
514
  ...input.requestId ? { requestId: input.requestId } : {},
483
515
  ...input.sessionId ? { conversationId: input.sessionId } : {},
484
516
  ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {}
485
517
  },
486
518
  idempotencyKey: input.idempotencyKey ? `sdk:runtime:${input.idempotencyKey}` : void 0
487
519
  }) : await this.resolveRuntime({
488
- semanticContext: { taskKey: receipt.taskKey, behaviorPoint, capsule: firstCapsule, ...input.requestId ? { requestId: input.requestId } : {}, ...input.sessionId ? { conversationId: input.sessionId } : {}, ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {} },
520
+ semanticContext: { taskKey: receipt.taskKey, behaviorPoint, capsule: firstCapsule, ...input.revisionId ? { revisionId: input.revisionId } : {}, ...input.requestId ? { requestId: input.requestId } : {}, ...input.sessionId ? { conversationId: input.sessionId } : {}, ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {} },
489
521
  idempotencyKey: input.idempotencyKey ? `sdk:runtime:${input.idempotencyKey}` : void 0
490
522
  });
491
- return { semantic, runtime };
523
+ return { semantic, runtime, taskKeys, capsules, multiTask: taskKeys.length > 1 };
492
524
  }
493
525
  async authorizeHostAction(input) {
494
526
  required(input.scope.organizationId, "SDK_ACTION_ORGANIZATION_REQUIRED");
@@ -698,7 +730,7 @@ var ViraClient = class {
698
730
  if (!Number.isInteger(expectedVersion) || expectedVersion < 0) throw new Error("SDK_TASKRUN_STATE_VERSION_REQUIRED");
699
731
  return this.request({ method: "POST", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/continue`, body: { expectedVersion, ...options.cursor ? { cursor: options.cursor } : {} } }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:continue:${taskRunId}:${expectedVersion}` });
700
732
  }
701
- cancelTaskRun(taskRunId, expectedVersion, options = {}) {
733
+ cancelTaskRun(taskRunId, expectedVersion = 0, options = {}) {
702
734
  required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
703
735
  if (!Number.isInteger(expectedVersion) || expectedVersion < 0) throw new Error("SDK_TASKRUN_STATE_VERSION_REQUIRED");
704
736
  return this.request({ method: "POST", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/cancel`, body: { expectedVersion } }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:cancel:${taskRunId}:${expectedVersion}` });
@@ -799,6 +831,12 @@ var ViraClient = class {
799
831
  { idempotencyKey: options.idempotencyKey }
800
832
  );
801
833
  }
834
+ submitTeachConversationEvidence(evidence, options = {}) {
835
+ required(evidence.conversationId, "SDK_TEACH_CONVERSATION_ID_REQUIRED");
836
+ required(evidence.message, "SDK_TEACH_CONVERSATION_MESSAGE_REQUIRED");
837
+ if (evidence.consent !== true) throw new Error("SDK_TEACH_CONVERSATION_CONSENT_REQUIRED");
838
+ return this.request({ method: "POST", path: "/v1/teach/conversations", body: { ...evidence, privacy: evidence.privacy ?? "CONSENTED_TENANT" } }, { idempotencyKey: options.idempotencyKey });
839
+ }
802
840
  listConversationArchive(input = {}) {
803
841
  return this.request({ method: "GET", path: "/v1/teach/conversations", query: { ...input.limit === void 0 ? {} : { limit: String(input.limit) }, ...input.cursor ? { cursor: input.cursor } : {} } });
804
842
  }
@@ -1148,10 +1186,11 @@ function buildObservationRequest(event) {
1148
1186
  throw new Error("SDK_OBSERVATION_SCOPE_REQUIRED");
1149
1187
  if (!event?.eventId || !event.eventType || !event.aiSystemId || !event.connectionId)
1150
1188
  throw new Error("SDK_OBSERVATION_FIELD_REQUIRED");
1189
+ const safeEvent = event;
1151
1190
  return Object.freeze({
1152
1191
  method: "POST",
1153
1192
  path: "/v1/observations",
1154
- body: Object.freeze({ ...event })
1193
+ body: Object.freeze({ ...safeEvent })
1155
1194
  });
1156
1195
  }
1157
1196
 
@@ -1241,6 +1280,12 @@ function createFrameworkAdapters(client) {
1241
1280
 
1242
1281
  // ../../sdks/host-lifecycle.ts
1243
1282
  import { createHash } from "node:crypto";
1283
+ function resolveHostToolBinding(bindings, hostToolName) {
1284
+ const name = hostToolName.trim();
1285
+ if (!name) return null;
1286
+ if (!bindings?.length) return null;
1287
+ return bindings.find((binding) => binding.hostActionName === name || binding.aliases.includes(name)) ?? null;
1288
+ }
1244
1289
  var nonEmpty = (value, code) => {
1245
1290
  if (typeof value !== "string" || !value.trim()) throw new Error(code);
1246
1291
  return value.trim();
@@ -1255,6 +1300,41 @@ var lifecycleTimeout = (value) => {
1255
1300
  if (!Number.isFinite(parsed) || parsed < 250) throw new Error("SDK_HOST_TIMEOUT_INVALID");
1256
1301
  return Math.min(Math.floor(parsed), 12e4);
1257
1302
  };
1303
+ var toolSessionTimeout = (value, fallback) => {
1304
+ const parsed = Number(value ?? fallback);
1305
+ if (!Number.isFinite(parsed) || parsed < 250) throw new Error("SDK_HOST_TOOL_SESSION_TIMEOUT_INVALID");
1306
+ return Math.min(Math.floor(parsed), 6e5);
1307
+ };
1308
+ var observationMaxBytes = (value) => {
1309
+ const parsed = Number(value ?? 16384);
1310
+ if (!Number.isFinite(parsed) || parsed < 512) throw new Error("SDK_HOST_OBSERVATION_BUDGET_INVALID");
1311
+ return Math.min(Math.floor(parsed), 256e3);
1312
+ };
1313
+ var sensitiveKey = /(?:authorization|cookie|set-cookie|password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|client[_-]?secret|refresh[_-]?token|id[_-]?token|session[_-]?token|ssn|social[_-]?security|credit[_-]?card|card[_-]?number|cvv|cvc|bank[_-]?account|iban|routing[_-]?number|date[_-]?of[_-]?birth|birth[_-]?date|email|phone|mobile|address|postal|zip)/i;
1314
+ var sensitiveValue = /(?:bearer\s+[a-z0-9._~+/=-]{8,}|(?:sk|pk|vira|evren|ghp|github_pat|xox[baprs])-[_a-z0-9-]{8,}|(?:eyj[a-z0-9_-]{10,}\.){2}[a-z0-9_-]{10,}|\b(?:\d[ -]*?){13,19}\b|\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b|\+?\d[\d ()-]{7,}\d)/i;
1315
+ var redactMarker = "[REDACTED]";
1316
+ var redactToolValue = (value, redactKeys, depth = 0) => {
1317
+ if (depth > 8) return "[TRUNCATED_DEPTH]";
1318
+ if (typeof value === "string") return sensitiveValue.test(value) ? redactMarker : value.length > 4096 ? `${value.slice(0, 4096)}\u2026[TRUNCATED]` : value;
1319
+ if (value === null || typeof value === "number" || typeof value === "boolean") return value;
1320
+ if (Array.isArray(value)) return value.slice(0, 100).map((item) => redactToolValue(item, redactKeys, depth + 1));
1321
+ if (value && typeof value === "object") {
1322
+ const output = {};
1323
+ for (const [key, child] of Object.entries(value).slice(0, 200)) {
1324
+ output[key] = sensitiveKey.test(key) || redactKeys.some((candidate) => candidate.trim() && candidate.toLowerCase() === key.toLowerCase()) ? redactMarker : redactToolValue(child, redactKeys, depth + 1);
1325
+ }
1326
+ return output;
1327
+ }
1328
+ return String(value);
1329
+ };
1330
+ function redactToolObservation(value, options = {}) {
1331
+ const budget = observationMaxBytes(options.maxBytes);
1332
+ const keys = options.redactKeys ?? [];
1333
+ const sanitized = redactToolValue(value, keys);
1334
+ const serialized = JSON.stringify(sanitized);
1335
+ if (Buffer.byteLength(serialized, "utf8") <= budget) return { value: sanitized, redacted: serialized.includes(redactMarker), truncated: serialized.includes("[TRUNCATED_") };
1336
+ return { value: { summary: "[REDACTED_TOOL_RESULT]", bytes: Buffer.byteLength(serialized, "utf8"), budget }, redacted: true, truncated: true };
1337
+ }
1258
1338
  var withTimeout = async (operation, timeoutMs, code) => {
1259
1339
  let timer;
1260
1340
  try {
@@ -1283,34 +1363,67 @@ function createViraHostRuntime(client, config) {
1283
1363
  if (!capabilities || typeof capabilities !== "object") throw new Error("SDK_HOST_CAPABILITIES_REQUIRED");
1284
1364
  const maxBytes = bounded(config.projectionMaxBytes, 8e3);
1285
1365
  const timeoutMs = lifecycleTimeout(config.timeoutMs);
1366
+ const toolSessionTimeoutMs = toolSessionTimeout(config.toolSessionTimeoutMs, timeoutMs);
1367
+ const toolObservationMaxBytes = observationMaxBytes(config.toolObservationMaxBytes);
1368
+ const toolObservationRedactKeys = config.toolObservationRedactKeys ?? [];
1286
1369
  if (mode === "enforce" && (!capabilities.canInterceptToolBefore || !capabilities.canPreventSideEffect)) throw new Error("SDK_HOST_ENFORCE_CAPABILITY_REQUIRED");
1287
1370
  if (mode === "enforce" && typeof config.authorizeAction !== "function") throw new Error("SDK_HOST_ACTION_AUTHORIZER_REQUIRED");
1288
1371
  let connected = null;
1289
1372
  let connectionIdentity = null;
1290
1373
  const projections = /* @__PURE__ */ new Map();
1291
- const activeToolSessions = /* @__PURE__ */ new Set();
1292
- const connectOnce = async () => {
1374
+ const activeToolSessions = /* @__PURE__ */ new Map();
1375
+ const connectOnce = async (options = {}) => {
1293
1376
  if (mode === "off" || !config.connect) return null;
1294
- if (!connected) connected = withTimeout(client.connectOnce(config.connect), timeoutMs, "SDK_HOST_CONNECT_TIMEOUT").then((result) => {
1295
- const body = bodyOf(result);
1296
- const system = body.system && typeof body.system === "object" ? body.system : {};
1297
- const connection = body.connection && typeof body.connection === "object" ? body.connection : {};
1298
- const aiSystemId = typeof system.id === "string" ? system.id.trim() : "";
1299
- const connectionId = typeof connection.id === "string" ? connection.id.trim() : "";
1300
- if (!aiSystemId || !connectionId) throw new Error("SDK_HOST_CONNECT_IDENTITY_MISSING");
1301
- connectionIdentity = { aiSystemId, connectionId };
1302
- return result;
1303
- });
1377
+ if (options.force) {
1378
+ connected = null;
1379
+ connectionIdentity = null;
1380
+ }
1381
+ if (!connected) {
1382
+ const attempt = withTimeout(client.connectOnce(config.connect), timeoutMs, "SDK_HOST_CONNECT_TIMEOUT").then((result) => {
1383
+ const body = bodyOf(result);
1384
+ const system = body.system && typeof body.system === "object" ? body.system : {};
1385
+ const connection = body.connection && typeof body.connection === "object" ? body.connection : {};
1386
+ const aiSystemId = typeof system.id === "string" ? system.id.trim() : "";
1387
+ const connectionId = typeof connection.id === "string" ? connection.id.trim() : "";
1388
+ if (!aiSystemId || !connectionId) throw new Error("SDK_HOST_CONNECT_IDENTITY_MISSING");
1389
+ connectionIdentity = { aiSystemId, connectionId };
1390
+ return result;
1391
+ });
1392
+ let cachedAttempt;
1393
+ cachedAttempt = attempt.catch((error) => {
1394
+ if (connected === cachedAttempt) connected = null;
1395
+ connectionIdentity = null;
1396
+ throw error;
1397
+ });
1398
+ connected = cachedAttempt;
1399
+ }
1304
1400
  return connected;
1305
1401
  };
1402
+ const reconnect = async () => connectOnce({ force: true });
1306
1403
  const sessionKey = (request) => `${request.organizationId}:${request.projectId}:${request.environmentId}:${request.conversationId}`;
1307
1404
  const beforeModel = async (request) => {
1308
1405
  nonEmpty(request.input, "SDK_HOST_MODEL_INPUT_REQUIRED");
1309
1406
  if (mode === "off") return { status: "off" };
1310
1407
  if (!capabilities.canInjectContext) return { status: "unavailable", reasonCode: "HOST_CONTEXT_INJECTION_UNSUPPORTED" };
1408
+ if (capabilities.canObserveModel) {
1409
+ void client.observe({ eventId: `${request.conversationId}:conversation.input:${request.requestId}`, eventType: "conversation.input", aiSystemId: request.aiSystemId, connectionId: request.connectionId, organizationId: request.organizationId, projectId: request.projectId, environmentId: request.environmentId, conversationId: request.conversationId, requestId: request.requestId, traceId: request.traceId, payload: { inputDigest: digest(request.input), minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } }, { idempotencyKey: `sdk:conversation.input:${request.conversationId}:${request.requestId}` }).catch(() => void 0);
1410
+ void client.observe({ eventId: `${request.conversationId}:model.request:${request.requestId}`, eventType: "model.request", aiSystemId: request.aiSystemId, connectionId: request.connectionId, organizationId: request.organizationId, projectId: request.projectId, environmentId: request.environmentId, conversationId: request.conversationId, requestId: request.requestId, traceId: request.traceId, payload: { inputDigest: digest(request.input), minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } }, { idempotencyKey: `sdk:model.request:${request.conversationId}:${request.requestId}` }).catch(() => void 0);
1411
+ }
1311
1412
  await connectOnce();
1312
- const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId, signalAttestationRefs: request.signalAttestationRefs }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
1413
+ const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, profile: request.profile, revisionId: request.revisionId, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId, signalAttestationRefs: request.signalAttestationRefs }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
1313
1414
  if (!semantic) return { status: "unavailable", reasonCode: "VIRA_SEMANTIC_UNAVAILABLE" };
1415
+ if (semantic.multiTask === true && semantic.taskKeys?.length > 1 && typeof client.startTaskRunFromPrompt === "function") {
1416
+ try {
1417
+ const admitted = await withTimeout(client.startTaskRunFromPrompt({ input: request.input, taskRunId: `host-task-run-${request.requestId}`, requestId: request.requestId, conversationId: request.conversationId, traceRootRef: request.traceId }), timeoutMs, "SDK_HOST_TASKRUN_ADMISSION_TIMEOUT");
1418
+ const admittedBody = bodyOf(admitted);
1419
+ const taskRun = admittedBody.taskRun && typeof admittedBody.taskRun === "object" ? admittedBody.taskRun : {};
1420
+ const taskRunId = typeof taskRun.taskRunId === "string" ? taskRun.taskRunId : `host-task-run-${request.requestId}`;
1421
+ const taskRunStateVersion = Number(taskRun.stateVersion);
1422
+ return { status: "task_run", response: admitted, taskRunId, ...Number.isInteger(taskRunStateVersion) && taskRunStateVersion >= 0 ? { taskRunStateVersion } : {}, selectedTaskKeys: semantic.taskKeys };
1423
+ } catch (error) {
1424
+ return { status: "unavailable", selectedTaskKeys: semantic.taskKeys, reasonCode: error instanceof Error ? error.message : "SDK_HOST_TASKRUN_ADMISSION_FAILED" };
1425
+ }
1426
+ }
1314
1427
  const semanticBody = bodyOf(semantic.semantic);
1315
1428
  const receipt = semanticBody.receipt && typeof semanticBody.receipt === "object" ? semanticBody.receipt : {};
1316
1429
  if (receipt.outcome !== "select" || typeof receipt.taskKey !== "string" || !semantic.runtime) {
@@ -1332,38 +1445,76 @@ function createViraHostRuntime(client, config) {
1332
1445
  nonEmpty(proposal.toolName, "SDK_HOST_TOOL_NAME_REQUIRED");
1333
1446
  if (mode !== "enforce") return { decision: "ABSTAIN", reasonCode: mode === "off" ? "HOST_MODE_OFF" : "OBSERVE_ONLY" };
1334
1447
  const toolSessionKey = `${proposal.organizationId}:${proposal.projectId}:${proposal.environmentId}:${proposal.conversationId}:${proposal.sessionId ?? proposal.conversationId}`;
1335
- if (activeToolSessions.has(toolSessionKey)) return { decision: "BLOCK", reasonCode: "SDK_HOST_TOOL_IN_FLIGHT" };
1336
- activeToolSessions.add(toolSessionKey);
1448
+ const current = activeToolSessions.get(toolSessionKey);
1449
+ if (current && current.expiresAt > Date.now()) return { decision: "BLOCK", reasonCode: "SDK_HOST_TOOL_IN_FLIGHT" };
1450
+ if (current) {
1451
+ clearTimeout(current.timer);
1452
+ activeToolSessions.delete(toolSessionKey);
1453
+ }
1454
+ const expiresAt = Date.now() + toolSessionTimeoutMs;
1455
+ const timer = setTimeout(() => {
1456
+ const held = activeToolSessions.get(toolSessionKey);
1457
+ if (held?.callId === proposal.callId) activeToolSessions.delete(toolSessionKey);
1458
+ }, toolSessionTimeoutMs);
1459
+ timer.unref?.();
1460
+ activeToolSessions.set(toolSessionKey, { callId: proposal.callId, expiresAt, timer });
1337
1461
  let decision;
1338
1462
  try {
1339
1463
  const authorized = await withTimeout(Promise.resolve(config.authorizeAction(proposal)), timeoutMs, "SDK_HOST_ACTION_AUTHORIZATION_TIMEOUT");
1340
1464
  const authorizedBody = bodyOf(authorized);
1341
1465
  decision = typeof authorizedBody.decision === "string" ? authorizedBody : authorized;
1342
1466
  } catch {
1343
- activeToolSessions.delete(toolSessionKey);
1467
+ const held = activeToolSessions.get(toolSessionKey);
1468
+ if (held?.callId === proposal.callId) {
1469
+ clearTimeout(held.timer);
1470
+ activeToolSessions.delete(toolSessionKey);
1471
+ }
1344
1472
  return { decision: "ERROR", reasonCode: "VIRA_ACTION_AUTHORIZATION_TIMEOUT" };
1345
1473
  }
1346
1474
  if (!decision || !["ALLOW", "BLOCK", "ESCALATE", "ABSTAIN", "ERROR"].includes(decision.decision)) {
1347
- activeToolSessions.delete(toolSessionKey);
1475
+ const held = activeToolSessions.get(toolSessionKey);
1476
+ if (held?.callId === proposal.callId) {
1477
+ clearTimeout(held.timer);
1478
+ activeToolSessions.delete(toolSessionKey);
1479
+ }
1348
1480
  throw new Error("SDK_HOST_ACTION_DECISION_INVALID");
1349
1481
  }
1350
- if (decision.decision !== "ALLOW") activeToolSessions.delete(toolSessionKey);
1482
+ if (decision.decision !== "ALLOW") {
1483
+ const held = activeToolSessions.get(toolSessionKey);
1484
+ if (held?.callId === proposal.callId) {
1485
+ clearTimeout(held.timer);
1486
+ activeToolSessions.delete(toolSessionKey);
1487
+ }
1488
+ }
1351
1489
  if (decision.decision === "ALLOW" && !isAllow(decision)) {
1352
- activeToolSessions.delete(toolSessionKey);
1490
+ const held = activeToolSessions.get(toolSessionKey);
1491
+ if (held?.callId === proposal.callId) {
1492
+ clearTimeout(held.timer);
1493
+ activeToolSessions.delete(toolSessionKey);
1494
+ }
1353
1495
  throw new Error("SDK_HOST_ALLOW_RECEIPT_INVALID");
1354
1496
  }
1355
1497
  return decision;
1356
1498
  };
1357
1499
  const afterTool = async (result) => {
1358
1500
  nonEmpty(result.callId, "SDK_HOST_TOOL_CALL_ID_REQUIRED");
1359
- if (mode === "off" || !capabilities.canInspectToolAfter) return { status: "off" };
1501
+ if (mode === "off") return { status: "off" };
1502
+ if (!capabilities.canInspectToolAfter) return { status: "skipped", executionCommitted: true };
1360
1503
  const toolSessionKey = `${result.organizationId}:${result.projectId}:${result.environmentId}:${result.conversationId}:${result.sessionId ?? result.conversationId}`;
1361
- const observedResult = result.ok ? result.result : { errorCode: result.errorCode ?? "HOST_TOOL_FAILED" };
1504
+ const minimized = result.ok ? redactToolObservation(result.result, { maxBytes: toolObservationMaxBytes, redactKeys: toolObservationRedactKeys }) : { value: { errorCode: result.errorCode ?? "HOST_TOOL_FAILED" }, redacted: false, truncated: false };
1505
+ const observedResult = minimized.value;
1362
1506
  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", ...result.authorityReceiptDigest ? { authorityReceiptDigest: result.authorityReceiptDigest } : {}, ...result.decisionDigest ? { decisionDigest: result.decisionDigest } : {}, requestId: result.requestId, conversationId: result.conversationId, ...result.sessionId ? { sessionId: result.sessionId } : {}, ...result.turnId ? { turnId: result.turnId } : {} };
1363
1507
  try {
1364
- return await 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");
1508
+ const response = await 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, minimization: { redacted: minimized.redacted, truncated: minimized.truncated, budgetBytes: toolObservationMaxBytes } }, resultDigest: evidence.resultDigest }), timeoutMs, "SDK_HOST_OBSERVE_TIMEOUT");
1509
+ return { status: "observed", response, executionCommitted: true };
1510
+ } catch (error) {
1511
+ return { status: "failed", errorCode: error instanceof Error ? error.message : "SDK_HOST_OBSERVE_FAILED", executionCommitted: true };
1365
1512
  } finally {
1366
- activeToolSessions.delete(toolSessionKey);
1513
+ const held = activeToolSessions.get(toolSessionKey);
1514
+ if (held?.callId === result.callId) {
1515
+ clearTimeout(held.timer);
1516
+ activeToolSessions.delete(toolSessionKey);
1517
+ }
1367
1518
  }
1368
1519
  };
1369
1520
  const executeTool = async (input) => {
@@ -1383,11 +1534,19 @@ function createViraHostRuntime(client, config) {
1383
1534
  throw Object.assign(error instanceof Error ? error : new Error(errorCode), { decision, observation });
1384
1535
  }
1385
1536
  };
1537
+ const cancelTool = (identity, callId) => {
1538
+ const key = `${identity.organizationId}:${identity.projectId}:${identity.environmentId}:${identity.conversationId}:${identity.sessionId ?? identity.conversationId}`;
1539
+ const held = activeToolSessions.get(key);
1540
+ if (!held || callId && held.callId !== callId) return false;
1541
+ clearTimeout(held.timer);
1542
+ activeToolSessions.delete(key);
1543
+ return true;
1544
+ };
1386
1545
  const endSession = (identity) => {
1387
1546
  projections.delete(sessionKey({ ...identity, requestId: "session-end", input: "" }));
1388
- activeToolSessions.delete(`${identity.organizationId}:${identity.projectId}:${identity.environmentId}:${identity.conversationId}:${identity.sessionId ?? identity.conversationId}`);
1547
+ cancelTool(identity);
1389
1548
  };
1390
- return Object.freeze({ mode, capabilities, connectOnce, getConnectionIdentity: () => connectionIdentity, beforeModel, beforeTool, afterTool, executeTool, endSession, getProjection: (identity) => projections.get(sessionKey({ ...identity, requestId: "projection", input: "" })), supportsPostModelVerification: capabilities.canInterceptResponseBeforeDisplay });
1549
+ return Object.freeze({ mode, capabilities, connectOnce, reconnect, getConnectionIdentity: () => connectionIdentity, beforeModel, beforeTool, afterTool, executeTool, cancelTool, endSession, getProjection: (identity) => projections.get(sessionKey({ ...identity, requestId: "projection", input: "" })), supportsPostModelVerification: capabilities.canInterceptResponseBeforeDisplay });
1391
1550
  }
1392
1551
  export {
1393
1552
  ViraApiError,
@@ -1410,5 +1569,7 @@ export {
1410
1569
  createVercelAIHooks,
1411
1570
  createViraHostRuntime,
1412
1571
  createViraMiddleware,
1413
- resolveFrameworkBoundary
1572
+ redactToolObservation,
1573
+ resolveFrameworkBoundary,
1574
+ resolveHostToolBinding
1414
1575
  };
@@ -235,6 +235,7 @@ export declare class ViraClient {
235
235
  capabilities?: readonly string[];
236
236
  config?: unknown;
237
237
  idempotencyKey?: string;
238
+ reuseExistingConnectionOnConflict?: boolean;
238
239
  }): Promise<ViraResponse<ConnectOnceResult> | null>;
239
240
  observe(event: ClientObservation, options?: {
240
241
  idempotencyKey?: string;
@@ -369,6 +370,7 @@ export declare class ViraClient {
369
370
  sessionId?: string;
370
371
  timeoutMs?: number;
371
372
  requestId?: string;
373
+ revisionId?: string;
372
374
  executionBoundary?: Record<string, unknown>;
373
375
  signalAttestationRefs?: readonly {
374
376
  stableKey: string;
@@ -379,6 +381,9 @@ export declare class ViraClient {
379
381
  }): Promise<{
380
382
  semantic: ViraResponse<ClientBody>;
381
383
  runtime: ViraResponse<RuntimeResolution> | null;
384
+ taskKeys: string[];
385
+ capsules: ClientBody[];
386
+ multiTask: boolean;
382
387
  } | null>;
383
388
  authorizeHostAction(input: {
384
389
  executionId: string;
@@ -488,7 +493,7 @@ export declare class ViraClient {
488
493
  cursor?: string;
489
494
  idempotencyKey?: string;
490
495
  }): Promise<ViraResponse<ClientBody> | null>;
491
- cancelTaskRun(taskRunId: string, expectedVersion: number, options?: {
496
+ cancelTaskRun(taskRunId: string, expectedVersion?: number | undefined, options?: {
492
497
  idempotencyKey?: string;
493
498
  }): Promise<ViraResponse<ClientBody> | null>;
494
499
  retryTaskRun(taskRunId: string, expectedVersion: number, options?: {
@@ -538,6 +543,9 @@ export declare class ViraClient {
538
543
  submitTeachEvidence(evidence: ClientBody, options?: {
539
544
  idempotencyKey?: string;
540
545
  }): Promise<ViraResponse<ClientBody> | null>;
546
+ submitTeachConversationEvidence(evidence: ClientBody, options?: {
547
+ idempotencyKey?: string;
548
+ }): Promise<ViraResponse<ClientBody> | null>;
541
549
  listConversationArchive(input?: {
542
550
  limit?: number;
543
551
  cursor?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryvira/sdk",
3
- "version": "0.1.58",
3
+ "version": "0.1.60",
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"},