@tryvira/sdk 0.1.75 → 0.1.94

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/index.js CHANGED
@@ -43,8 +43,8 @@ var contentIdempotencyKey = async (operation, request) => {
43
43
  if (!globalThis.crypto?.subtle) throw new Error("SDK_IDEMPOTENCY_CRYPTO_UNAVAILABLE");
44
44
  const bytes = new TextEncoder().encode(canonicalJson(request));
45
45
  const digest2 = await globalThis.crypto.subtle.digest("SHA-256", bytes);
46
- const hex = [...new Uint8Array(digest2)].map((value) => value.toString(16).padStart(2, "0")).join("");
47
- return `${operation}:${hex}`;
46
+ const hex2 = [...new Uint8Array(digest2)].map((value) => value.toString(16).padStart(2, "0")).join("");
47
+ return `${operation}:${hex2}`;
48
48
  };
49
49
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
50
50
  var retryAfterMs = (value, now = Date.now()) => {
@@ -113,6 +113,8 @@ var ViraClient = class {
113
113
  packs;
114
114
  baseUrl;
115
115
  apiKey;
116
+ accessTokenProvider;
117
+ operatorDelegationTokenProvider;
116
118
  fetcher;
117
119
  timeoutMs;
118
120
  retries;
@@ -122,6 +124,8 @@ var ViraClient = class {
122
124
  constructor(options) {
123
125
  this.baseUrl = normalizeBaseUrl(options.baseUrl, options.allowInsecureLocalhost === true);
124
126
  this.apiKey = options.apiKey;
127
+ this.accessTokenProvider = options.accessTokenProvider;
128
+ this.operatorDelegationTokenProvider = options.operatorDelegationTokenProvider;
125
129
  this.fetcher = options.fetcher ?? fetch;
126
130
  this.timeoutMs = Math.max(
127
131
  1e3,
@@ -129,27 +133,114 @@ var ViraClient = class {
129
133
  );
130
134
  this.retries = Math.max(0, Math.min(options.retries ?? 2, 5));
131
135
  this.failureMode = options.failureMode ?? "throw";
132
- this.defaultHeaders = options.defaultHeaders ?? {};
136
+ this.defaultHeaders = options.organizationUnitId ? { ...options.defaultHeaders, "x-vira-organization-unit-id": options.organizationUnitId } : options.defaultHeaders ?? {};
133
137
  this.boundConnectionId = options.connectionId;
134
138
  this.evaluations = {
135
139
  createPlan: (input, options2 = {}) => this.createEvaluationPlan(input, options2),
136
- get: (id) => this.getEvaluation(id),
137
- compare: (id) => this.getEvaluationComparison(id),
140
+ get: (id2) => this.getEvaluation(id2),
141
+ compare: (id2) => this.getEvaluationComparison(id2),
138
142
  reviewFinding: (evaluationId, findingId, input, options2 = {}) => this.reviewComparativeFinding(evaluationId, findingId, input, options2),
139
- proposeImprovement: (id, input, options2 = {}) => this.createImprovementProposal(id, input, options2)
143
+ proposeImprovement: (id2, input, options2 = {}) => this.createImprovementProposal(id2, input, options2)
140
144
  };
141
145
  this.teach = {
142
- review: (id, action = "request-review", options2 = {}) => this.reviewImprovementProposal(id, action, options2),
146
+ review: (id2, action = "request-review", options2 = {}) => this.reviewImprovementProposal(id2, action, options2),
143
147
  createCandidate: (input, options2 = {}) => this.createBehaviorRevisionCandidate(input, options2),
144
- evaluateCandidate: (id, input, options2 = {}) => this.evaluateBehaviorRevisionCandidate(id, input, options2)
148
+ evaluateCandidate: (id2, input, options2 = {}) => this.evaluateBehaviorRevisionCandidate(id2, input, options2)
145
149
  };
146
150
  this.packs = {
147
151
  createRevision: (input, options2 = {}) => this.createPackRevision(input, options2),
148
- getRevision: (id) => this.getPackRevision(id),
149
- diffRevision: (id) => this.getPackRevisionDiff(id),
150
- transitionRevision: (id, transition, options2 = {}) => this.transitionPackRevision(id, transition, options2)
152
+ getRevision: (id2) => this.getPackRevision(id2),
153
+ diffRevision: (id2) => this.getPackRevisionDiff(id2),
154
+ transitionRevision: (id2, transition, options2 = {}) => this.transitionPackRevision(id2, transition, options2)
151
155
  };
152
156
  }
157
+ listOrganizationUnits() {
158
+ return this.request({ method: "GET", path: "/v1/organization-units" });
159
+ }
160
+ listOrganizationBillingAdmins() {
161
+ return this.request({ method: "GET", path: "/v1/organization/billing-admins" });
162
+ }
163
+ setOrganizationBillingAdmin(actorId, status = "ACTIVE", options = {}) {
164
+ if (!actorId.trim()) throw new Error("SDK_ACTOR_ID_REQUIRED");
165
+ return this.request({ method: "POST", path: `/v1/organization/billing-admins/${encodeURIComponent(actorId)}`, body: { status } }, { idempotencyKey: options.idempotencyKey ?? `sdk:billing-admin:${globalThis.crypto.randomUUID()}`, enforcing: true });
166
+ }
167
+ getAICreditWallet() {
168
+ return this.request({ method: "GET", path: "/v1/billing/credits" });
169
+ }
170
+ listAICreditBudgets() {
171
+ return this.request({ method: "GET", path: "/v1/billing/credits/budgets" });
172
+ }
173
+ listAIUsageReceipts(input = {}) {
174
+ const query = {};
175
+ if (input.organizationUnitId) query.organizationUnitId = input.organizationUnitId;
176
+ if (input.limit !== void 0) {
177
+ if (!Number.isSafeInteger(input.limit)) throw new Error("SDK_AI_USAGE_LIMIT_INVALID");
178
+ query.limit = String(Math.min(500, Math.max(1, input.limit)));
179
+ }
180
+ return this.request({ method: "GET", path: "/v1/billing/ai-usage", ...Object.keys(query).length ? { query } : {} });
181
+ }
182
+ getAIUsageSummary(input = {}) {
183
+ return this.request({ method: "GET", path: "/v1/billing/ai-usage/summary", ...input.organizationUnitId ? { query: { organizationUnitId: input.organizationUnitId } } : {} });
184
+ }
185
+ reserveAICredits(input, options = {}) {
186
+ if (!Number.isSafeInteger(input.amountMicrocredits) || input.amountMicrocredits < 1) throw new Error("SDK_AI_CREDIT_AMOUNT_INVALID");
187
+ if (!input.idempotencyKey.trim()) throw new Error("SDK_IDEMPOTENCY_KEY_REQUIRED");
188
+ return this.request({ method: "POST", path: "/v1/billing/credits/reservations", body: input }, { idempotencyKey: options.idempotencyKey ?? input.idempotencyKey });
189
+ }
190
+ releaseAICreditReservation(reservationId, options = {}) {
191
+ if (!reservationId.trim()) throw new Error("SDK_AI_CREDIT_RESERVATION_ID_REQUIRED");
192
+ return this.request({ method: "POST", path: `/v1/billing/credits/reservations/${encodeURIComponent(reservationId)}/release`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:ai-credit-release:${reservationId}` });
193
+ }
194
+ listInbox(options = {}) {
195
+ const limit = options.limit === void 0 ? void 0 : Math.min(100, Math.max(1, Math.trunc(options.limit)));
196
+ if (options.limit !== void 0 && !Number.isFinite(options.limit)) throw new Error("SDK_NOTIFICATION_LIMIT_INVALID");
197
+ return this.request({ method: "GET", path: "/v1/notifications/inbox", query: { ...limit === void 0 ? {} : { limit: String(limit) }, ...options.cursor ? { cursor: options.cursor } : {}, ...options.search ? { search: options.search } : {} } });
198
+ }
199
+ markInboxRead(notificationId, options = {}) {
200
+ if (!notificationId.trim()) throw new Error("SDK_NOTIFICATION_ID_REQUIRED");
201
+ return this.request({ method: "POST", path: `/v1/notifications/${encodeURIComponent(notificationId)}/read`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:inbox-read:${notificationId}` });
202
+ }
203
+ listNotificationDestinations() {
204
+ return this.request({ method: "GET", path: "/v1/notification-destinations" });
205
+ }
206
+ createNotificationDestination(input, options) {
207
+ if (!input.label.trim()) throw new Error("SDK_NOTIFICATION_DESTINATION_LABEL_REQUIRED");
208
+ if (!input.endpoint.trim()) throw new Error("SDK_NOTIFICATION_DESTINATION_ENDPOINT_REQUIRED");
209
+ if (!options.idempotencyKey.trim()) throw new Error("SDK_IDEMPOTENCY_KEY_REQUIRED");
210
+ return this.request({ method: "POST", path: "/v1/notification-destinations", body: input }, options);
211
+ }
212
+ revokeNotificationDestination(destinationId, options = {}) {
213
+ if (!destinationId.trim()) throw new Error("SDK_NOTIFICATION_DESTINATION_ID_REQUIRED");
214
+ return this.request({ method: "POST", path: "/v1/notification-destinations/" + encodeURIComponent(destinationId) + "/revoke", body: {} }, { idempotencyKey: options.idempotencyKey ?? "sdk:notification-destination-revoke:" + destinationId });
215
+ }
216
+ createOrganizationUnit(input, options = {}) {
217
+ return this.request({ method: "POST", path: "/v1/organization-units", body: input }, options);
218
+ }
219
+ previewOrganizationUnitArchive(unitId) {
220
+ if (!unitId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_ID_REQUIRED");
221
+ return this.request({ method: "POST", path: `/v1/organization-units/${encodeURIComponent(unitId)}/archive-preview`, body: {} });
222
+ }
223
+ archiveOrganizationUnit(unitId, options) {
224
+ if (!unitId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_ID_REQUIRED");
225
+ if (options.confirm !== true) throw new Error("SDK_ORGANIZATION_UNIT_ARCHIVE_CONFIRMATION_REQUIRED");
226
+ return this.request({ method: "POST", path: `/v1/organization-units/${encodeURIComponent(unitId)}/archive`, body: { confirm: true } }, options);
227
+ }
228
+ listOrganizationUnitMembers(unitId) {
229
+ if (!unitId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_ID_REQUIRED");
230
+ return this.request({ method: "GET", path: `/v1/organization-units/${encodeURIComponent(unitId)}/members` });
231
+ }
232
+ setOrganizationUnitMember(unitId, actorId, input, options = {}) {
233
+ if (!unitId.trim() || !actorId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_MEMBER_REQUIRED");
234
+ return this.request({ method: "POST", path: `/v1/organization-units/${encodeURIComponent(unitId)}/members/${encodeURIComponent(actorId)}`, body: input }, { idempotencyKey: options.idempotencyKey ?? `sdk:unit-member:${globalThis.crypto.randomUUID()}`, enforcing: true });
235
+ }
236
+ listProjectOrganizationUnits(projectId) {
237
+ if (!projectId.trim()) throw new Error("SDK_PROJECT_ID_REQUIRED");
238
+ return this.request({ method: "GET", path: `/v1/projects/${encodeURIComponent(projectId)}/organization-units` });
239
+ }
240
+ bindProjectOrganizationUnit(projectId, unitId, input = {}, options = {}) {
241
+ if (!projectId.trim() || !unitId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_BINDING_REQUIRED");
242
+ return this.request({ method: "POST", path: `/v1/projects/${encodeURIComponent(projectId)}/organization-units/${encodeURIComponent(unitId)}`, body: input }, { idempotencyKey: options.idempotencyKey ?? `sdk:project-unit:${globalThis.crypto.randomUUID()}`, enforcing: true });
243
+ }
153
244
  async request(request, options = {}) {
154
245
  const url = new URL(this.baseUrl + request.path);
155
246
  for (const [key, value] of Object.entries(request.query ?? {}))
@@ -159,7 +250,18 @@ var ViraClient = class {
159
250
  ...this.defaultHeaders
160
251
  };
161
252
  if (request.body) headers["content-type"] = "application/json";
162
- if (this.apiKey) {
253
+ const operatorOperation = /^\/v1\/(?:billing\/legacy-pricing\/(?:inspect|propose|approve)|behavior-policy-bindings\/reconciliation\/(?:inspect|propose|approve|history|remediation-inspect|remediation-propose|remediation-approve|remediation-history)|signals\/subject-consent\/(?:inspect|grant|withdraw)|teach\/subject-evidence\/(?:admit|withdraw|history))$/.test(request.path);
254
+ if (operatorOperation) {
255
+ if (Object.keys(headers).some((key) => ["authorization", "x-vira-api-key", "x-vira-delegation", "x-vira-taskrun-delegation", "x-vira-optimizer-grant", "cookie"].includes(key.toLowerCase())))
256
+ throw new Error("SDK_OPERATOR_MIXED_AUTHORITY_FORBIDDEN");
257
+ const delegation = (await this.operatorDelegationTokenProvider?.())?.trim();
258
+ if (!delegation) throw new Error("SDK_OPERATOR_DELEGATION_REQUIRED");
259
+ headers["x-vira-delegation"] = delegation;
260
+ } else if (this.accessTokenProvider) {
261
+ const accessToken = (await this.accessTokenProvider())?.trim();
262
+ if (!accessToken) throw new Error("SDK_ACCESS_TOKEN_REQUIRED");
263
+ headers.authorization = `Bearer ${accessToken}`;
264
+ } else if (this.apiKey) {
163
265
  if (this.apiKey.startsWith("vira_live_")) headers["x-vira-api-key"] = this.apiKey;
164
266
  else {
165
267
  headers.authorization = `Bearer ${this.apiKey}`;
@@ -179,7 +281,8 @@ var ViraClient = class {
179
281
  method: request.method,
180
282
  headers,
181
283
  body: request.body ? JSON.stringify(request.body) : void 0,
182
- signal: controller.signal
284
+ signal: controller.signal,
285
+ ...operatorOperation ? { redirect: "error", credentials: "omit" } : {}
183
286
  });
184
287
  const raw = await response.text();
185
288
  let body = null;
@@ -228,6 +331,330 @@ var ViraClient = class {
228
331
  idempotencyKey: input.idempotencyKey
229
332
  });
230
333
  }
334
+ /** Advisory only. Does not approve, reserve or transfer an AI System. */
335
+ getAISystemOwnershipTransferReadiness(systemId) {
336
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
337
+ return this.request({
338
+ method: "GET",
339
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/ownership-transfer/readiness"
340
+ });
341
+ }
342
+ /** Recipient consents to a NEW empty AI System, never transfer of history. */
343
+ acceptAISystemClone(systemId, input) {
344
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
345
+ for (const k of ["expectedOwnerUnitId", "newName", "reason"])
346
+ required(input[k], "SDK_SYSTEM_CLONE_FIELD_REQUIRED");
347
+ return this.request({
348
+ method: "POST",
349
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/accept",
350
+ body: { ...input }
351
+ }, { enforcing: true });
352
+ }
353
+ /** Owner prepares blank successor; provider credentials and traffic remain put. */
354
+ prepareAISystemClone(systemId, input) {
355
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
356
+ for (const k of ["expectedOwnerUnitId", "targetUnitId", "acceptanceAuditId", "reason"])
357
+ required(input[k], "SDK_SYSTEM_CLONE_FIELD_REQUIRED");
358
+ return this.request({
359
+ method: "POST",
360
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/prepare",
361
+ body: { ...input }
362
+ }, { enforcing: true });
363
+ }
364
+ /** Advisory clone preflight; never changes provider routing or ownership. */
365
+ getAISystemCloneCutoverReadiness(systemId, input) {
366
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
367
+ required(input.newAiSystemId, "SDK_SYSTEM_CLONE_FIELD_REQUIRED");
368
+ required(input.preparationAuditId, "SDK_SYSTEM_CLONE_FIELD_REQUIRED");
369
+ return this.request({
370
+ method: "POST",
371
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/readiness",
372
+ body: { newAiSystemId: input.newAiSystemId, preparationAuditId: input.preparationAuditId }
373
+ });
374
+ }
375
+ /** Read target-unit STAGED route version; no access to credentials or traffic. */
376
+ getAISystemCutoverRouteStage(systemId) {
377
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
378
+ return this.request({
379
+ method: "GET",
380
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route"
381
+ });
382
+ }
383
+ /** Link a completed, currently approved F16 Strategy execution to this STAGED receipt. */
384
+ recordAISystemCutoverBehaviorEvidence(systemId, input) {
385
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
386
+ required(input.runtimeReceiptId, "SDK_SYSTEM_CUTOVER_RUNTIME_RECEIPT_REQUIRED");
387
+ required(input.strategyExecutionId, "SDK_SYSTEM_CUTOVER_STRATEGY_EXECUTION_REQUIRED");
388
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
389
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
390
+ return this.request({
391
+ method: "POST",
392
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/behavior",
393
+ body: {
394
+ expectedVersion: input.expectedVersion,
395
+ runtimeReceiptId: input.runtimeReceiptId,
396
+ strategyExecutionId: input.strategyExecutionId
397
+ }
398
+ }, { enforcing: true });
399
+ }
400
+ /** Explicit billable connectivity probe, not model behavior certification. */
401
+ enqueueAISystemCutoverProviderProbe(systemId, input) {
402
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
403
+ required(input.runtimeReceiptId, "SDK_SYSTEM_CUTOVER_RUNTIME_RECEIPT_REQUIRED");
404
+ required(input.reason, "SDK_SYSTEM_CUTOVER_FIELD_REQUIRED");
405
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
406
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
407
+ if (input.acknowledgeBillable !== true)
408
+ throw new Error("SDK_SYSTEM_CUTOVER_PROBE_BILLING_ACK_REQUIRED");
409
+ return this.request({
410
+ method: "POST",
411
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/probe",
412
+ body: {
413
+ expectedVersion: input.expectedVersion,
414
+ runtimeReceiptId: input.runtimeReceiptId,
415
+ reason: input.reason,
416
+ acknowledgeBillable: true
417
+ }
418
+ }, { enforcing: true });
419
+ }
420
+ /** Revoke exactly one STAGED route version; no live traffic is modified. */
421
+ withdrawAISystemCutoverRouteStage(systemId, input) {
422
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
423
+ required(input.reason, "SDK_SYSTEM_CUTOVER_FIELD_REQUIRED");
424
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
425
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
426
+ return this.request({
427
+ method: "POST",
428
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/withdraw",
429
+ body: { expectedVersion: input.expectedVersion, reason: input.reason }
430
+ }, { enforcing: true });
431
+ }
432
+ /** Inspect the committed route generation without exposing provider secrets. */
433
+ getAISystemLiveRoute(systemId) {
434
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
435
+ return this.request(
436
+ {
437
+ method: "GET",
438
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live"
439
+ },
440
+ { enforcing: false }
441
+ );
442
+ }
443
+ /** Independent target-department acceptance; never activates by itself. */
444
+ acceptAISystemLiveActivation(systemId, input) {
445
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
446
+ if (!input || !Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1 || !Number.isSafeInteger(input.expectedGeneration) || input.expectedGeneration < 0)
447
+ throw new Error("SDK_SYSTEM_CUTOVER_LIVE_VERSION_INVALID");
448
+ required(input.runtimeReceiptId, "SDK_RUNTIME_RECEIPT_ID_REQUIRED");
449
+ required(input.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
450
+ return this.request(
451
+ {
452
+ method: "POST",
453
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live/accept",
454
+ body: {
455
+ expectedVersion: input.expectedVersion,
456
+ expectedGeneration: input.expectedGeneration,
457
+ runtimeReceiptId: input.runtimeReceiptId,
458
+ reason: input.reason
459
+ }
460
+ },
461
+ { enforcing: true }
462
+ );
463
+ }
464
+ /** Organization owner commits with a separately issued target approval. */
465
+ activateAISystemLiveRoute(systemId, input) {
466
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
467
+ required(input?.targetUnitId, "SDK_SYSTEM_CUTOVER_TARGET_REQUIRED");
468
+ required(input?.activationConsentAuditId, "SDK_SYSTEM_CUTOVER_ACCEPTANCE_REQUIRED");
469
+ required(input?.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
470
+ return this.request({
471
+ method: "POST",
472
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live/activate",
473
+ body: {
474
+ targetUnitId: input.targetUnitId,
475
+ activationConsentAuditId: input.activationConsentAuditId,
476
+ reason: input.reason
477
+ }
478
+ }, { enforcing: true });
479
+ }
480
+ /** Independent approval to restore SOURCE for one exact ACTIVE generation. */
481
+ acceptAISystemLiveRollback(systemId, input) {
482
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
483
+ if (!input || !Number.isSafeInteger(input.expectedGeneration) || input.expectedGeneration < 1)
484
+ throw new Error("SDK_SYSTEM_CUTOVER_LIVE_VERSION_INVALID");
485
+ required(input.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
486
+ return this.request(
487
+ {
488
+ method: "POST",
489
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live/rollback/accept",
490
+ body: { expectedGeneration: input.expectedGeneration, reason: input.reason }
491
+ },
492
+ { enforcing: true }
493
+ );
494
+ }
495
+ /** Roll back exactly once, guarded by previous-generation and host fences. */
496
+ rollbackAISystemLiveRoute(systemId, input) {
497
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
498
+ required(input?.targetUnitId, "SDK_SYSTEM_CUTOVER_TARGET_REQUIRED");
499
+ required(input?.rollbackConsentAuditId, "SDK_SYSTEM_CUTOVER_ACCEPTANCE_REQUIRED");
500
+ required(input?.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
501
+ return this.request({
502
+ method: "POST",
503
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live/rollback",
504
+ body: {
505
+ targetUnitId: input.targetUnitId,
506
+ rollbackConsentAuditId: input.rollbackConsentAuditId,
507
+ reason: input.reason
508
+ }
509
+ }, { enforcing: true });
510
+ }
511
+ /**
512
+ * Reconcile an UNCERTAIN host model/tool call only with a server-verified
513
+ * completed effect receipt. No provider retry or AI Credit mutation.
514
+ */
515
+ reconcileAISystemHostInvocation(systemId, input) {
516
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
517
+ required(input?.invocationId, "SDK_F4_HOST_INVOCATION_REQUIRED");
518
+ required(input?.resultReceiptId, "SDK_F4_HOST_RESULT_RECEIPT_REQUIRED");
519
+ required(input?.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
520
+ return this.request(
521
+ {
522
+ method: "POST",
523
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/reconcile/host",
524
+ body: {
525
+ invocationId: input.invocationId,
526
+ resultReceiptId: input.resultReceiptId,
527
+ reason: input.reason
528
+ }
529
+ },
530
+ { enforcing: true }
531
+ );
532
+ }
533
+ /**
534
+ * Release only an uninvoked, failed F4 provider probe's RESERVED AI Credits.
535
+ * No unknown-outcome refund, duplicate model call, or automatic settlement.
536
+ */
537
+ releaseUninvokedAISystemProbeCredit(systemId, input) {
538
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
539
+ required(input?.probeJobId, "SDK_F4_PROBE_JOB_REQUIRED");
540
+ required(input?.reservationId, "SDK_F4_RESERVATION_REQUIRED");
541
+ required(input?.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
542
+ return this.request({
543
+ method: "POST",
544
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/reconcile/probe-release",
545
+ body: {
546
+ probeJobId: input.probeJobId,
547
+ reservationId: input.reservationId,
548
+ reason: input.reason
549
+ }
550
+ }, { enforcing: true });
551
+ }
552
+ /**
553
+ * Read-only bounded blocker identities for manual departmental reconciliation.
554
+ * This does not retry providers, release credits or approve ACTIVE routing.
555
+ */
556
+ inspectAISystemCutoverDrainCases(systemId, input) {
557
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
558
+ if (!input || !Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
559
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
560
+ return this.request({
561
+ method: "POST",
562
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/drain/cases",
563
+ body: { expectedVersion: input.expectedVersion }
564
+ }, { enforcing: false });
565
+ }
566
+ /**
567
+ * Operator-only readback of queued/in-flight F4 jobs, unresolved provider
568
+ * invocations and outstanding departmental credit holds across versions.
569
+ * Never authorizes ACTIVE traffic or triggers a model call.
570
+ */
571
+ inspectAISystemCutoverDrain(systemId, input) {
572
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
573
+ if (!input || !Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
574
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
575
+ return this.request({
576
+ method: "POST",
577
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/drain",
578
+ body: { expectedVersion: input.expectedVersion }
579
+ }, { enforcing: false });
580
+ }
581
+ /** Read proof of a runtime policy admission; not provider success or cutover. */
582
+ inspectAISystemCutoverAdmission(systemId, input) {
583
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
584
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
585
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
586
+ const receiptId = input.runtimeReceiptId;
587
+ if (receiptId !== void 0 && (typeof receiptId !== "string" || !receiptId.trim() || receiptId !== receiptId.trim() || receiptId.length > 500))
588
+ throw new Error("SDK_RUNTIME_RECEIPT_ID_REQUIRED");
589
+ return this.request({
590
+ method: "POST",
591
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/admission",
592
+ body: {
593
+ expectedVersion: input.expectedVersion,
594
+ ...receiptId === void 0 ? {} : { runtimeReceiptId: receiptId }
595
+ }
596
+ }, { enforcing: false });
597
+ }
598
+ /** Target admin consents only to a STAGED route, not traffic switching. */
599
+ acceptAISystemCutoverRoute(systemId, input) {
600
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
601
+ for (const k of ["successorAiSystemId", "successorConnectionId", "preparationAuditId", "reason"])
602
+ required(input[k], "SDK_SYSTEM_CUTOVER_FIELD_REQUIRED");
603
+ if (input.expectedVersion !== null && (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1))
604
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
605
+ return this.request({
606
+ method: "POST",
607
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/accept",
608
+ body: { ...input }
609
+ }, { enforcing: true });
610
+ }
611
+ /** Independent organization owner CAS-stages an inert route record. */
612
+ stageAISystemCutoverRoute(systemId, input) {
613
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
614
+ for (const k of [
615
+ "successorAiSystemId",
616
+ "successorConnectionId",
617
+ "preparationAuditId",
618
+ "routeAcceptanceAuditId",
619
+ "reason"
620
+ ])
621
+ required(input[k], "SDK_SYSTEM_CUTOVER_FIELD_REQUIRED");
622
+ if (input.expectedVersion !== null && (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1))
623
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
624
+ return this.request({
625
+ method: "POST",
626
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/stage",
627
+ body: { ...input }
628
+ }, { enforcing: true });
629
+ }
630
+ /** Target department admin signs a 10-minute, scope-locked acceptance. */
631
+ acceptAISystemOwnershipTransfer(systemId, input) {
632
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
633
+ required(input.expectedOwnerUnitId, "SDK_SYSTEM_TRANSFER_EXPECTED_OWNER_REQUIRED");
634
+ required(input.reason, "SDK_SYSTEM_TRANSFER_REASON_REQUIRED");
635
+ return this.request(
636
+ {
637
+ method: "POST",
638
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/ownership-transfer/accept",
639
+ body: { ...input }
640
+ },
641
+ { enforcing: true }
642
+ );
643
+ }
644
+ /** Existing organization owner finalizes an independently accepted transfer. */
645
+ commitAISystemOwnershipTransfer(systemId, input) {
646
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
647
+ for (const key of ["expectedOwnerUnitId", "targetUnitId", "acceptanceAuditId", "reason"])
648
+ required(input[key], "SDK_SYSTEM_TRANSFER_FIELD_REQUIRED");
649
+ return this.request(
650
+ {
651
+ method: "POST",
652
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/ownership-transfer/commit",
653
+ body: { ...input }
654
+ },
655
+ { enforcing: true }
656
+ );
657
+ }
231
658
  listAISystems(options = {}) {
232
659
  return this.request({ method: "GET", path: "/v1/ai-systems", query: listQuery(options) });
233
660
  }
@@ -306,7 +733,7 @@ var ViraClient = class {
306
733
  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 } } } };
307
734
  }
308
735
  if (!connectionResult) return null;
309
- const connectedId = String(connectionResult.body.connection?.id ?? "").trim();
736
+ const connectedId = String(connectionResult.body.connection.id ?? "").trim();
310
737
  if (connectedId) this.boundConnectionId = connectedId;
311
738
  return {
312
739
  status: connectionResult.status,
@@ -347,14 +774,147 @@ var ViraClient = class {
347
774
  required(eventId, "SDK_OBSERVATION_ID_REQUIRED");
348
775
  return this.request({ method: "GET", path: `/v1/observations/${encodeURIComponent(eventId)}` });
349
776
  }
777
+ /** Admin-only: supersede one admitted event with another in the same unit. */
778
+ async supersedeObservation(input, options = {}) {
779
+ required(input.tombstoneEventId, "SDK_OBSERVATION_TOMBSTONE_REQUIRED");
780
+ required(input.targetEventId, "SDK_OBSERVATION_TARGET_REQUIRED");
781
+ required(input.targetEventVersion, "SDK_OBSERVATION_VERSION_REQUIRED");
782
+ if (input.reason !== void 0) {
783
+ required(input.reason, "SDK_OBSERVATION_REASON_REQUIRED");
784
+ if (input.reason !== input.reason.trim() || input.reason.length > 512)
785
+ throw new Error("SDK_OBSERVATION_REASON_REQUIRED");
786
+ }
787
+ const body = { ...input, confirm: true };
788
+ return this.request({
789
+ method: "POST",
790
+ path: "/v1/observations/supersessions",
791
+ body
792
+ }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(
793
+ "sdk:observation:supersession",
794
+ body
795
+ ) });
796
+ }
797
+ /** Admin-only: create or replay a department-scoped historical backfill. */
798
+ async beginObservationBackfill(input, options = {}) {
799
+ required(input.id, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
800
+ required(input.windowStart, "SDK_OBSERVATION_BACKFILL_WINDOW_REQUIRED");
801
+ required(input.windowEnd, "SDK_OBSERVATION_BACKFILL_WINDOW_REQUIRED");
802
+ if (input.checkpointRequired !== void 0 && typeof input.checkpointRequired !== "boolean")
803
+ throw new Error("SDK_OBSERVATION_BACKFILL_CHECKPOINT_POLICY_INVALID");
804
+ if (input.reason !== void 0) {
805
+ required(input.reason, "SDK_OBSERVATION_REASON_REQUIRED");
806
+ if (input.reason !== input.reason.trim() || input.reason.length > 512)
807
+ throw new Error("SDK_OBSERVATION_REASON_REQUIRED");
808
+ }
809
+ const body = { ...input, confirm: true };
810
+ return this.request({
811
+ method: "POST",
812
+ path: "/v1/observations/backfills",
813
+ body
814
+ }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(
815
+ "sdk:observation:backfill:begin",
816
+ body
817
+ ) });
818
+ }
819
+ /** Admin-only: finalize processed events within the department backfill window. */
820
+ async completeObservationBackfill(id2, options = {}) {
821
+ required(id2, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
822
+ if (options.reason !== void 0) {
823
+ required(options.reason, "SDK_OBSERVATION_REASON_REQUIRED");
824
+ if (options.reason !== options.reason.trim() || options.reason.length > 512)
825
+ throw new Error("SDK_OBSERVATION_REASON_REQUIRED");
826
+ }
827
+ const body = { confirm: true, ...options.reason ? { reason: options.reason } : {} };
828
+ return this.request({
829
+ method: "POST",
830
+ path: `/v1/observations/backfills/${encodeURIComponent(id2)}/complete`,
831
+ body
832
+ }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(
833
+ `sdk:observation:backfill:complete:${id2}`,
834
+ body
835
+ ) });
836
+ }
837
+ /** Read-only advisory status; finalization rechecks under PostgreSQL locks. */
838
+ getObservationBackfillReadiness(id2) {
839
+ required(id2, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
840
+ return this.request({
841
+ method: "GET",
842
+ path: `/v1/observations/backfills/${encodeURIComponent(id2)}/readiness`
843
+ });
844
+ }
845
+ /** Read-only: scoped lineage and checkpoint summary, without raw cursor. */
846
+ getObservationBackfillHistory(id2) {
847
+ required(id2, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
848
+ return this.request({
849
+ method: "GET",
850
+ path: `/v1/observations/backfills/${encodeURIComponent(id2)}/history`
851
+ });
852
+ }
853
+ /** Admin-only: keep completed history and activate a reviewed successor. */
854
+ async reviseObservationBackfill(id2, input, options = {}) {
855
+ required(id2, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
856
+ required(input.successorId, "SDK_OBSERVATION_BACKFILL_SUCCESSOR_REQUIRED");
857
+ required(input.reason, "SDK_OBSERVATION_REASON_REQUIRED");
858
+ if (id2 === input.successorId || [id2, input.successorId, input.reason].some((value) => value !== value.trim() || value.length > 512))
859
+ throw new Error("SDK_OBSERVATION_BACKFILL_REVISION_INVALID");
860
+ const body = { confirm: true, successorId: input.successorId, reason: input.reason };
861
+ return this.request({
862
+ method: "POST",
863
+ path: `/v1/observations/backfills/${encodeURIComponent(id2)}/revise`,
864
+ body
865
+ }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(
866
+ `sdk:observation:backfill:revise:${id2}`,
867
+ body
868
+ ) });
869
+ }
870
+ /** Read-only. The SDK cannot manufacture a trusted runtime evidence receipt. */
871
+ listTrajectoryRuntimeEvidence(trajectoryKey) {
872
+ required(trajectoryKey, "SDK_OBSERVATION_TRAJECTORY_REQUIRED");
873
+ return this.request({
874
+ method: "GET",
875
+ path: `/v1/observations/trajectories/${encodeURIComponent(trajectoryKey)}/runtime-evidence`
876
+ });
877
+ }
350
878
  trace(event, options = {}) {
351
879
  return this.observe({ ...event, eventType: "model.response" }, options);
352
880
  }
353
881
  searchRuntimeTraces(query = {}) {
882
+ if (query.limit !== void 0 && (!Number.isInteger(query.limit) || query.limit < 1 || query.limit > 100)) throw new Error("SDK_RUNTIME_TRACE_LIMIT_INVALID");
354
883
  const params = new URLSearchParams();
355
884
  for (const [key, value] of Object.entries(query)) if (value !== void 0) params.set(key, String(value));
356
885
  return this.request({ method: "GET", path: `/v1/runtime/traces/search${params.size ? `?${params.toString()}` : ""}` });
357
886
  }
887
+ startOptimization(input, options = {}) {
888
+ const key = typeof input.idempotencyKey === "string" ? input.idempotencyKey.trim() : "";
889
+ if (!key) throw new Error("SDK_IDEMPOTENCY_KEY_REQUIRED");
890
+ if (!input.canonicalDigest || !input.policyDigest || !input.baseProjection && !input.strategyOptimization && !input.canonicalRevisionId) throw new Error("SDK_OPTIMIZATION_FIELDS_REQUIRED");
891
+ return this.request({ method: "POST", path: "/v1/optimization/execute", body: input }, { idempotencyKey: options.idempotencyKey ?? key, enforcing: true });
892
+ }
893
+ resumeOptimization(input, options = {}) {
894
+ return this.startOptimization({ ...input, resume: true }, options);
895
+ }
896
+ promoteOptimizationRun(runId, evaluationId, expectedVersion, options = {}) {
897
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
898
+ required(evaluationId, "SDK_OPTIMIZATION_EVALUATION_ID_REQUIRED");
899
+ if (expectedVersion !== null && (!Number.isSafeInteger(expectedVersion) || expectedVersion < 1)) throw new Error("SDK_OPTIMIZATION_POINTER_VERSION_INVALID");
900
+ return this.request({ method: "POST", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/promote`, body: { evaluationId, expectedVersion } }, { idempotencyKey: options.idempotencyKey ?? `sdk:optimization-promote:${runId}:${evaluationId}`, enforcing: true });
901
+ }
902
+ getOptimizationRun(runId) {
903
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
904
+ return this.request({ method: "GET", path: `/v1/optimization/runs/${encodeURIComponent(runId)}` });
905
+ }
906
+ reviewOptimizationRun(runId) {
907
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
908
+ return this.request({ method: "GET", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/review` });
909
+ }
910
+ reattachOptimizationRun(runId, options = {}) {
911
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
912
+ return this.request({ method: "POST", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/reattach`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:optimization-reattach:${runId}`, enforcing: true });
913
+ }
914
+ cancelOptimizationRun(runId, options = {}) {
915
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
916
+ return this.request({ method: "POST", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/cancel`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:optimization-cancel:${runId}`, enforcing: true });
917
+ }
358
918
  outcome(event, options = {}) {
359
919
  return this.observe({ ...event, eventType: "business.outcome" }, options);
360
920
  }
@@ -388,10 +948,12 @@ var ViraClient = class {
388
948
  );
389
949
  }
390
950
  discover(options = {}) {
951
+ if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new Error("SDK_DISCOVERY_LIMIT_INVALID");
952
+ const normalized = { ...options, ...options.limit !== void 0 ? { limit: Math.min(options.limit, 200) } : {} };
391
953
  return this.request({
392
954
  method: "GET",
393
955
  path: "/v1/discovery/candidates",
394
- query: { ...options.reviewState ? { reviewState: options.reviewState } : {}, ...listQuery(options) }
956
+ query: { ...options.reviewState ? { reviewState: options.reviewState } : {}, ...listQuery(normalized) }
395
957
  });
396
958
  }
397
959
  async reviewDiscoveryCandidate(kind, key, input, options = {}) {
@@ -399,7 +961,19 @@ var ViraClient = class {
399
961
  required(key, "SDK_DISCOVERY_CANDIDATE_KEY_REQUIRED");
400
962
  required(typeof input?.decision === "string" ? input.decision : "", "SDK_DISCOVERY_CANDIDATE_DECISION_REQUIRED");
401
963
  const path = `/v1/discovery/candidates/${encodeURIComponent(kind)}/${encodeURIComponent(key)}/review`;
402
- return this.request({ method: "POST", path, body: input }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:discovery-review:${kind}:${key}`, input) });
964
+ if (input.patch !== void 0 && input.payload !== void 0) throw new Error("SDK_DISCOVERY_REVIEW_PATCH_AMBIGUOUS");
965
+ const { payload, patch, ...rest } = input;
966
+ const reviewPatch = patch !== void 0 ? patch : payload;
967
+ if (reviewPatch !== void 0 && (!reviewPatch || typeof reviewPatch !== "object" || Array.isArray(reviewPatch))) throw new Error("SDK_DISCOVERY_REVIEW_PATCH_INVALID");
968
+ const body = { ...rest, ...reviewPatch === void 0 ? {} : { patch: reviewPatch } };
969
+ const invocationId = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`;
970
+ return this.request({ method: "POST", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:discovery-review:${kind}:${key}`, { invocationId, body }), enforcing: true });
971
+ }
972
+ /** Explicit canonical publication; API approval and scope checks still apply. */
973
+ publishDiscoveryCandidate(kind, key, input = {}, options = {}) {
974
+ required(kind, "SDK_DISCOVERY_CANDIDATE_KIND_REQUIRED");
975
+ required(key, "SDK_DISCOVERY_CANDIDATE_KEY_REQUIRED");
976
+ return this.request({ method: "POST", path: `/v1/discovery/candidates/${encodeURIComponent(kind)}/${encodeURIComponent(key)}/publish`, body: input }, { idempotencyKey: options.idempotencyKey ?? `sdk:discovery-publish:${globalThis.crypto.randomUUID()}`, enforcing: true });
403
977
  }
404
978
  async createSignalDiscoveryProposal(input, options = {}) {
405
979
  return this.request({ method: "POST", path: "/v1/signals/discovery-proposals", body: input }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey("sdk:signal-discovery-proposal", input) });
@@ -554,7 +1128,8 @@ var ViraClient = class {
554
1128
  method: "POST",
555
1129
  path: "/v1/runtime/execute",
556
1130
  body: buildRuntimeRequest(
557
- input
1131
+ input,
1132
+ { includeAIIdentity: true, allowStagedValidation: true }
558
1133
  )
559
1134
  },
560
1135
  { idempotencyKey: input.idempotencyKey, enforcing: true }
@@ -590,6 +1165,88 @@ var ViraClient = class {
590
1165
  idempotencyKey: input.idempotencyKey
591
1166
  });
592
1167
  }
1168
+ /** Inspect historical rate candidates using an authenticated delegated user session. */
1169
+ inspectLegacyPricing(reservationId) {
1170
+ this.validateLegacyPricingIdentity(reservationId);
1171
+ return this.request({ method: "POST", path: "/v1/billing/legacy-pricing/inspect", body: { reservationId } }, { enforcing: true });
1172
+ }
1173
+ /** Create a short-lived proposal. This never pins rates or debits credits. */
1174
+ proposeLegacyPricing(input) {
1175
+ const { reservationId, reviewDigest, evidenceReference } = input;
1176
+ this.validateLegacyPricingIdentity(reservationId, reviewDigest);
1177
+ if (typeof reviewDigest !== "string" || !/^[a-f0-9]{64}$/.test(reviewDigest)) throw Error("SDK_LEGACY_PRICING_DIGEST_INVALID");
1178
+ if (typeof evidenceReference !== "string" || !evidenceReference.trim() || evidenceReference !== evidenceReference.trim() || evidenceReference.length > 512) throw Error("SDK_LEGACY_PRICING_EVIDENCE_INVALID");
1179
+ return this.request({ method: "POST", path: "/v1/billing/legacy-pricing/propose", body: { reservationId, reviewDigest, evidenceReference } }, { enforcing: true });
1180
+ }
1181
+ /** Approve only from a different active actor/session; the server enforces independence. */
1182
+ approveLegacyPricing(input) {
1183
+ const { reservationId, reviewDigest, proposalId } = input;
1184
+ this.validateLegacyPricingIdentity(reservationId, reviewDigest);
1185
+ if (typeof reviewDigest !== "string" || !/^[a-f0-9]{64}$/.test(reviewDigest)) throw Error("SDK_LEGACY_PRICING_DIGEST_INVALID");
1186
+ if (typeof proposalId !== "string" || !proposalId.trim() || proposalId !== proposalId.trim() || proposalId.length > 256) throw Error("SDK_LEGACY_PRICING_PROPOSAL_INVALID");
1187
+ return this.request({ method: "POST", path: "/v1/billing/legacy-pricing/approve", body: { reservationId, reviewDigest, proposalId } }, { enforcing: true });
1188
+ }
1189
+ inspectLegacyPromotionReconciliation(input = {}) {
1190
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/inspect", body: input }, { enforcing: true });
1191
+ }
1192
+ proposeLegacyPromotionReconciliation(input) {
1193
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/propose", body: input }, { idempotencyKey: String(input.idempotencyKey ?? `sdk:legacy-promotion-proposal:${globalThis.crypto.randomUUID()}`), enforcing: true });
1194
+ }
1195
+ approveLegacyPromotionReconciliation(input) {
1196
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/approve", body: input }, { idempotencyKey: String(input.idempotencyKey ?? `sdk:legacy-promotion-approval:${globalThis.crypto.randomUUID()}`), enforcing: true });
1197
+ }
1198
+ historyLegacyPromotionReconciliation(input = {}) {
1199
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/history", body: input }, { enforcing: true });
1200
+ }
1201
+ inspectLegacyRecordRemediation(input = {}) {
1202
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/remediation-inspect", body: input }, { enforcing: true });
1203
+ }
1204
+ proposeLegacyRecordRemediation(input) {
1205
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/remediation-propose", body: input }, { idempotencyKey: String(input.idempotencyKey ?? `sdk:legacy-record-proposal:${globalThis.crypto.randomUUID()}`), enforcing: true });
1206
+ }
1207
+ approveLegacyRecordRemediation(input) {
1208
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/remediation-approve", body: input }, { idempotencyKey: String(input.idempotencyKey ?? `sdk:legacy-record-approval:${globalThis.crypto.randomUUID()}`), enforcing: true });
1209
+ }
1210
+ historyLegacyRecordRemediation(input = {}) {
1211
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/remediation-history", body: input }, { enforcing: true });
1212
+ }
1213
+ inspectSubjectSignalConsent(input) {
1214
+ return this.request({ method: "POST", path: "/v1/signals/subject-consent/inspect", body: input }, { enforcing: true });
1215
+ }
1216
+ grantSubjectSignalConsent(input) {
1217
+ return this.request({ method: "POST", path: "/v1/signals/subject-consent/grant", body: input }, { idempotencyKey: `sdk:subject-signal-consent:${input.eventId}:${input.mappingId}`, enforcing: true });
1218
+ }
1219
+ withdrawSubjectSignalConsent(input) {
1220
+ return this.request({ method: "POST", path: "/v1/signals/subject-consent/withdraw", body: input }, { idempotencyKey: `sdk:subject-signal-consent-withdraw:${input.consentId}`, enforcing: true });
1221
+ }
1222
+ admitSubjectTeachEvidence(input) {
1223
+ return this.request({ method: "POST", path: "/v1/teach/subject-evidence/admit", body: input }, { idempotencyKey: String(input.idempotencyKey ?? `sdk:subject-teach-admit:${globalThis.crypto.randomUUID()}`), enforcing: true });
1224
+ }
1225
+ withdrawSubjectTeachEvidence(input) {
1226
+ return this.request({ method: "POST", path: "/v1/teach/subject-evidence/withdraw", body: input }, { idempotencyKey: `sdk:subject-teach-withdraw:${input.evidenceId}`, enforcing: true });
1227
+ }
1228
+ historySubjectTeachEvidence(input = {}) {
1229
+ return this.request({ method: "POST", path: "/v1/teach/subject-evidence/history", body: input }, { enforcing: true });
1230
+ }
1231
+ validateLegacyPricingIdentity(reservationId, reviewDigest) {
1232
+ if (typeof reservationId !== "string" || !reservationId.trim() || reservationId !== reservationId.trim() || reservationId.length > 256) throw Error("SDK_LEGACY_PRICING_RESERVATION_INVALID");
1233
+ if (reviewDigest !== void 0 && (typeof reviewDigest !== "string" || !/^[a-f0-9]{64}$/.test(reviewDigest))) throw Error("SDK_LEGACY_PRICING_DIGEST_INVALID");
1234
+ }
1235
+ /** Provider account usage only; never a managed charge or TaskRun completion. */
1236
+ verifyExternalProviderUsage(input) {
1237
+ const { aiSystemId, connectionId, generationId, providerId } = input;
1238
+ for (const value of [aiSystemId, connectionId]) if (typeof value !== "string" || !value.trim() || value !== value.trim() || value.length > 200) throw new Error("SDK_BYOK_IDENTITY_INVALID");
1239
+ if (providerId !== "openai" && providerId !== "openrouter" && providerId !== "xai" && providerId !== "gemini") throw new Error("SDK_BYOK_PROVIDER_INVALID");
1240
+ if (typeof generationId !== "string" || !{ openai: /^resp_[A-Za-z0-9_-]{1,180}$/, openrouter: /^gen-[A-Za-z0-9_-]{1,180}$/, xai: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, gemini: /^(?:v1_|int_)[A-Za-z0-9_-]{1,180}$/ }[providerId].test(generationId)) throw new Error("SDK_BYOK_GENERATION_INVALID");
1241
+ return this.request({ method: "POST", path: "/v1/external-provider/usage/verify", body: { aiSystemId, connectionId, generationId, providerId } }, { enforcing: true });
1242
+ }
1243
+ /** Explicit first-party model transport. BYOK host observations remain non-chargeable. */
1244
+ executeManagedChat(input) {
1245
+ required(input.aiSystemId, "SDK_AI_SYSTEM_REQUIRED");
1246
+ required(input.connectionId, "SDK_CONNECTION_REQUIRED");
1247
+ required(input.operationId, "SDK_MANAGED_OPERATION_REQUIRED");
1248
+ return this.request({ method: "POST", path: "/v1/managed-model/chat/completions", body: { ...input, stream: false } }, { idempotencyKey: "managed-chat:" + input.operationId });
1249
+ }
593
1250
  /** Classify input only; use resolveRuntime for one BehaviorPoint or resolveTaskRun/startTaskRun for TaskRun routing and execution. */
594
1251
  resolveSemantic(input) {
595
1252
  required(input.input, "SDK_SEMANTIC_INPUT_REQUIRED");
@@ -657,9 +1314,19 @@ var ViraClient = class {
657
1314
  return this.request({
658
1315
  method: "POST",
659
1316
  path: "/v1/runtime/actions/authorize",
660
- body: { executionId: input.executionId, sessionId: input.sessionId, dataVersion: input.dataVersion, scope: input.scope, context: input.context, proposal: input.proposal, ...input.approval ? { approval: input.approval } : {} }
1317
+ body: { executionId: input.executionId, sessionId: input.sessionId, dataVersion: input.dataVersion, scope: input.scope, context: input.context, proposal: input.proposal, ...input.approval ? { approval: input.approval } : {}, ...input.signalAttestationRefs?.length ? { signalAttestationRefs: input.signalAttestationRefs } : {}, ...input.aiSystemId ? { aiSystemId: input.aiSystemId } : {} }
661
1318
  });
662
1319
  }
1320
+ /** Queue the approved SINGLE effect on the worker, never execute it locally. */
1321
+ async queueTaskRunHostDispatch(input) {
1322
+ for (const value of [input.taskRunId, input.childRunId, input.aiSystemId, input.sessionId, input.scope.organizationId, input.scope.projectId, input.scope.environmentId, input.scope.organizationUnitId, input.approvalId]) required(value, "SDK_SINGLE_HOST_DISPATCH_FIELD_REQUIRED");
1323
+ const executionId = String(input.context.execution_id ?? ""), dataVersion = String(input.context.data_version ?? "");
1324
+ required(executionId, "SDK_ACTION_EXECUTION_REQUIRED");
1325
+ required(dataVersion, "SDK_ACTION_DATA_VERSION_REQUIRED");
1326
+ const result = await this.request({ method: "POST", path: "/v1/runtime/actions/authorize", body: { executionId, dataVersion, sessionId: input.sessionId, aiSystemId: input.aiSystemId, scope: input.scope, context: input.context, proposal: input.proposal, approval: { approvalId: input.approvalId }, taskRunDispatch: { taskRunId: input.taskRunId, childRunId: input.childRunId } } }, { enforcing: true });
1327
+ if (!result || result.status !== 202 || result.body?.status !== "QUEUED" || result.body.clientExecutionAllowed !== false || !result.body.invocationId) throw Error("SDK_SINGLE_HOST_QUEUE_PROOF_REQUIRED");
1328
+ return result;
1329
+ }
663
1330
  async createHostActionApproval(input) {
664
1331
  required(input.sessionId, "SDK_ACTION_SESSION_REQUIRED");
665
1332
  required(input.dataVersion, "SDK_ACTION_DATA_VERSION_REQUIRED");
@@ -689,15 +1356,16 @@ var ViraClient = class {
689
1356
  path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}`
690
1357
  });
691
1358
  }
692
- createBehaviorStrategy(definition, id) {
1359
+ createBehaviorStrategy(definition, id2) {
693
1360
  if (!definition) throw new Error("SDK_STRATEGY_DEFINITION_REQUIRED");
694
1361
  return this.request({
695
1362
  method: "POST",
696
1363
  path: "/v1/behavior-strategies",
697
- body: { definition, ...id ? { id } : {} }
1364
+ body: { definition, ...id2 ? { id: id2 } : {} }
698
1365
  });
699
1366
  }
700
1367
  listSemanticTasks(options = {}) {
1368
+ if (options.limit !== void 0 && (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 200)) throw new Error("SDK_SEMANTIC_TASK_LIMIT_INVALID");
701
1369
  return this.request({ method: "GET", path: "/v1/semantic-tasks", query: listQuery(options) });
702
1370
  }
703
1371
  async deleteSemanticTask(taskId, options = {}) {
@@ -711,6 +1379,7 @@ var ViraClient = class {
711
1379
  return this.request({ method: "POST", path: "/v1/semantic-tasks", body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:semantic-task:${task.taskKey}`, body) });
712
1380
  }
713
1381
  listBehaviorPoints(options = {}) {
1382
+ if (options.limit !== void 0 && (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 200)) throw new Error("SDK_BEHAVIOR_POINT_LIMIT_INVALID");
714
1383
  return this.request({ method: "GET", path: "/v1/behavior-points", query: listQuery(options) });
715
1384
  }
716
1385
  async deleteBehaviorPoint(pointId, options = {}) {
@@ -776,9 +1445,15 @@ var ViraClient = class {
776
1445
  throw new Error("SDK_STRATEGY_CANDIDATES_REQUIRED");
777
1446
  if (!Number.isFinite(input.expiresAt))
778
1447
  throw new Error("SDK_EXPIRY_REQUIRED");
1448
+ if (input.cutoverRouteValidation !== void 0 && input.traceId !== void 0)
1449
+ throw new Error("SDK_F4_STRATEGY_TRACE_SERVER_OWNED");
779
1450
  const body = {
780
- ...buildRuntimeRequest(input),
1451
+ ...buildRuntimeRequest(
1452
+ input,
1453
+ { includeAIIdentity: true, allowStagedValidation: true }
1454
+ ),
781
1455
  artifactDigest: input.artifactDigest,
1456
+ ...input.releaseId ? { releaseId: input.releaseId } : {},
782
1457
  ...input.behaviorPoint ? { behaviorPoint: input.behaviorPoint } : {},
783
1458
  ...input.executionBoundary ? { executionBoundary: input.executionBoundary } : {},
784
1459
  ...input.traceId ? { traceId: input.traceId } : {},
@@ -797,6 +1472,39 @@ var ViraClient = class {
797
1472
  path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}`
798
1473
  });
799
1474
  }
1475
+ /** Uses the existing Strategy execution read-authorizer and unit-scoped
1476
+ * credentials. Never exposes an amount-based settlement method. */
1477
+ getAIUsageReconciliation(executionId) {
1478
+ required(executionId, "SDK_EXECUTION_ID_REQUIRED");
1479
+ return this.request({
1480
+ method: "GET",
1481
+ path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}/credit-reconciliation`
1482
+ });
1483
+ }
1484
+ getJob(jobId) {
1485
+ required(jobId, "SDK_JOB_ID_REQUIRED");
1486
+ return this.request({ method: "GET", path: `/v1/jobs/${encodeURIComponent(jobId)}` });
1487
+ }
1488
+ getConflictInspection(inspectionId) {
1489
+ required(inspectionId, "SDK_CONFLICT_INSPECTION_ID_REQUIRED");
1490
+ return this.request({ method: "GET", path: `/v1/conflicts/${encodeURIComponent(inspectionId)}` });
1491
+ }
1492
+ async inspectConflicts(input, options = {}) {
1493
+ if (!Array.isArray(input.proposed) || !Array.isArray(input.active) || !Array.isArray(input.controls)) throw new Error("SDK_CONFLICT_INSPECTION_ARRAYS_REQUIRED");
1494
+ const body = { ...input.id ? { id: required(input.id, "SDK_CONFLICT_INSPECTION_ID_REQUIRED") } : {}, proposed: input.proposed, active: input.active, controls: input.controls };
1495
+ return this.request({ method: "POST", path: "/v1/conflicts/inspect", body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey("sdk:conflicts:inspect", body) });
1496
+ }
1497
+ async resolveConflictInspection(inspectionId, status, options = {}) {
1498
+ required(inspectionId, "SDK_CONFLICT_INSPECTION_ID_REQUIRED");
1499
+ if (status !== "APPROVED" && status !== "REJECTED") throw new Error("SDK_CONFLICT_RESOLUTION_STATUS_INVALID");
1500
+ if (options.authorityDigest !== void 0 && !options.authorityDigest.trim()) throw new Error("SDK_CONFLICT_AUTHORITY_DIGEST_INVALID");
1501
+ const path = `/v1/conflicts/${encodeURIComponent(inspectionId)}/resolve`, body = { status, ...options.authorityDigest ? { authorityDigest: options.authorityDigest } : {} };
1502
+ return this.request({ method: "POST", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:conflicts:resolve:${inspectionId}`, body) });
1503
+ }
1504
+ listStrategyExecutions(options = {}) {
1505
+ if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1 || options.limit > 200)) throw new Error("SDK_STRATEGY_EXECUTION_LIMIT_INVALID");
1506
+ return this.request({ method: "GET", path: "/v1/runtime/strategy-executions", query: listQuery(options) });
1507
+ }
800
1508
  getStrategyExecutionTrace(executionId) {
801
1509
  required(executionId, "SDK_EXECUTION_ID_REQUIRED");
802
1510
  return this.request({
@@ -825,28 +1533,50 @@ var ViraClient = class {
825
1533
  body: {}
826
1534
  });
827
1535
  }
828
- resolveTaskRun(input) {
1536
+ listCompoundTaskPlans(options = {}) {
1537
+ if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1 || options.limit > 500)) throw new Error("SDK_COMPOUND_TASK_PLAN_LIMIT_INVALID");
1538
+ if (options.cursor !== void 0 && !options.cursor.trim()) throw new Error("SDK_COMPOUND_TASK_PLAN_CURSOR_INVALID");
1539
+ return this.request({ method: "GET", path: "/v1/compound-tasks/plans", query: { ...options.limit === void 0 ? {} : { limit: String(options.limit) }, ...options.cursor ? { cursor: options.cursor } : {} } });
1540
+ }
1541
+ saveCompoundTaskPlan(plan, options = {}) {
1542
+ const planId = typeof plan.planId === "string" ? plan.planId.trim() : "";
1543
+ const planDigest = typeof plan.planDigest === "string" ? plan.planDigest.trim() : "";
1544
+ if (!planId || !planDigest) throw new Error("SDK_COMPOUND_TASK_PLAN_FIELDS_REQUIRED");
1545
+ return this.request({ method: "POST", path: "/v1/compound-tasks/plans", body: { plan } }, { idempotencyKey: options.idempotencyKey ?? `sdk:compound-task-plan:${planId}:${planDigest}` });
1546
+ }
1547
+ getCompoundTaskPlan(planId) {
1548
+ required(planId, "SDK_COMPOUND_TASK_PLAN_ID_REQUIRED");
1549
+ return this.request({ method: "GET", path: `/v1/compound-tasks/plans/${encodeURIComponent(planId)}` });
1550
+ }
1551
+ async resolveTaskRun(input) {
829
1552
  required(input.input, "SDK_TASKRUN_INPUT_REQUIRED");
830
1553
  if (input.requestedMode) required(input.requestedMode, "SDK_TASKRUN_MODE_REQUIRED");
831
1554
  const connectionId = input.connectionId ?? this.boundConnectionId;
832
- return this.request({ method: "POST", path: "/v1/task-runs/resolve", body: { ...input, ...connectionId ? { connectionId } : {} } }, { idempotencyKey: `sdk:task-run:resolve:${input.input}` });
1555
+ const requestId = input.requestId ?? `sdk-task-route-${(await contentIdempotencyKey("sdk-task-route", input)).split(":").at(-1)}`;
1556
+ return this.request({ method: "POST", path: "/v1/task-runs/resolve", body: { ...input, requestId, ...connectionId ? { connectionId } : {} } }, { idempotencyKey: `sdk:task-run:resolve:${requestId}` });
833
1557
  }
834
1558
  startTaskRun(input, options = {}) {
835
1559
  for (const value of [input.taskRunId, input.requestId]) required(value, "SDK_TASKRUN_ADMISSION_FIELD_REQUIRED");
1560
+ required(input.aiSystemId, "SDK_TASKRUN_AI_SYSTEM_REQUIRED");
836
1561
  if (input.input === void 0 || input.input === null) throw new Error("SDK_TASKRUN_INPUT_REQUIRED");
837
1562
  const body = { ...input, ...input.ownerActorRef ? { ownerActorRef: input.ownerActorRef } : {}, ...input.requestedMode ? { requestedMode: input.requestedMode } : {}, ...!input.connectionId && this.boundConnectionId ? { connectionId: this.boundConnectionId } : {} };
838
1563
  return this.request({ method: "POST", path: "/v1/task-runs", body }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:start:${input.requestId}` });
839
1564
  }
840
1565
  startTaskRunFromPrompt(input, options = {}) {
1566
+ required(input.aiSystemId, "SDK_TASKRUN_AI_SYSTEM_REQUIRED");
841
1567
  if (input.input === void 0 || input.input === null) throw new Error("SDK_TASKRUN_INPUT_REQUIRED");
842
- const id = () => globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`;
843
- const requestId = input.requestId ?? `sdk-task-run-${id()}`;
844
- return this.startTaskRun({ taskRunId: input.taskRunId ?? `task-run-${id()}`, requestId, input: input.input, ...input.conversationId ? { conversationId: input.conversationId } : {}, ...input.episodeId ? { episodeId: input.episodeId } : {}, ...input.traceRootRef ? { traceRootRef: input.traceRootRef } : {}, ...input.budget ? { budget: input.budget } : {}, ...input.connectionId ? { connectionId: input.connectionId } : {}, ...input.hostCapabilities ? { hostCapabilities: [...input.hostCapabilities] } : {} }, options);
1568
+ const id2 = () => globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`;
1569
+ const requestId = input.requestId ?? `sdk-task-run-${id2()}`;
1570
+ return this.startTaskRun({ taskRunId: input.taskRunId ?? `task-run-${id2()}`, requestId, aiSystemId: input.aiSystemId, input: input.input, ...input.conversationId ? { conversationId: input.conversationId } : {}, ...input.episodeId ? { episodeId: input.episodeId } : {}, ...input.traceRootRef ? { traceRootRef: input.traceRootRef } : {}, ...input.budget ? { budget: input.budget } : {}, ...input.connectionId ? { connectionId: input.connectionId } : {}, ...input.hostCapabilities ? { hostCapabilities: [...input.hostCapabilities] } : {} }, options);
845
1571
  }
846
1572
  getTaskRun(taskRunId) {
847
1573
  required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
848
1574
  return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}` });
849
1575
  }
1576
+ getTaskRunEvidence(taskRunId) {
1577
+ required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1578
+ return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/evidence` });
1579
+ }
850
1580
  listTaskRunEvents(taskRunId) {
851
1581
  required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
852
1582
  return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/events` });
@@ -874,8 +1604,25 @@ var ViraClient = class {
874
1604
  });
875
1605
  }
876
1606
  listCapabilities(options = {}) {
877
- const query = options.surface ? `?surface=${encodeURIComponent(options.surface)}` : "";
878
- return this.request({ method: "GET", path: `/v1/capabilities${query}` });
1607
+ return this.request({ method: "GET", path: "/v1/capabilities", ...options.surface ? { query: { surface: options.surface } } : {} });
1608
+ }
1609
+ /** Read the scope actually admitted by the credential, never a caller claim.
1610
+ * Useful before attaching a host to a department-bound machine key. */
1611
+ async resolveCredentialScope(expected = {}, options = {}) {
1612
+ const response = await this.listCapabilities({ surface: "sdk" });
1613
+ const scope = response?.body?.scope;
1614
+ if (!scope || response?.body?.source !== "scoped-product-capability-catalog") throw Error("SDK_CREDENTIAL_SCOPE_UNAVAILABLE");
1615
+ for (const key of ["organizationId", "projectId", "environmentId", "organizationUnitId"]) {
1616
+ const value = scope[key];
1617
+ if ((key !== "organizationUnitId" || options.requireDepartment || value !== void 0) && (typeof value !== "string" || !value.trim() || value !== value.trim())) throw Error("SDK_CREDENTIAL_SCOPE_INVALID");
1618
+ if (expected[key] !== void 0 && expected[key] !== value) throw Error("SDK_CREDENTIAL_SCOPE_MISMATCH");
1619
+ }
1620
+ return {
1621
+ organizationId: scope.organizationId,
1622
+ projectId: scope.projectId,
1623
+ environmentId: scope.environmentId,
1624
+ ...scope.organizationUnitId ? { organizationUnitId: scope.organizationUnitId } : {}
1625
+ };
879
1626
  }
880
1627
  getBehaviorProgram(programId) {
881
1628
  required(programId, "SDK_PROGRAM_ID_REQUIRED");
@@ -894,6 +1641,119 @@ var ViraClient = class {
894
1641
  const path = `/v1/behavior-programs/${encodeURIComponent(programId)}/cascade`, body = { confirm: options.confirm === true, purgeRuntime: options.purgeRuntime === true };
895
1642
  return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:behavior-program-cascade:${programId}`, { path, body }) });
896
1643
  }
1644
+ /** Authenticated draft only. Never releases or activates a behavior policy. */
1645
+ createBehaviorPolicySource(source) {
1646
+ required(source.policyKey, "SDK_BEHAVIOR_POLICY_KEY_REQUIRED");
1647
+ if (source.sourceLevel === "organization_unit") required(source.sourceId, "SDK_BEHAVIOR_POLICY_UNIT_REQUIRED");
1648
+ if (!Number.isSafeInteger(source.revision) || source.revision < 1)
1649
+ throw new Error("SDK_BEHAVIOR_POLICY_REVISION_INVALID");
1650
+ if (!Array.isArray(source.modules) || !source.modules.length)
1651
+ throw new Error("SDK_BEHAVIOR_POLICY_MODULES_REQUIRED");
1652
+ return this.request({
1653
+ method: "POST",
1654
+ path: "/v1/behavior-policy-sources",
1655
+ body: source
1656
+ });
1657
+ }
1658
+ listBehaviorPolicySources(input) {
1659
+ required(input.policyKey, "SDK_BEHAVIOR_POLICY_KEY_REQUIRED");
1660
+ if (input.sourceLevel === "organization_unit") required(input.sourceId, "SDK_BEHAVIOR_POLICY_UNIT_REQUIRED");
1661
+ return this.request({
1662
+ method: "GET",
1663
+ path: "/v1/behavior-policy-sources",
1664
+ query: {
1665
+ sourceLevel: input.sourceLevel,
1666
+ policyKey: input.policyKey,
1667
+ ...input.sourceId ? { sourceId: input.sourceId } : {}
1668
+ }
1669
+ });
1670
+ }
1671
+ getBehaviorPolicySource(sourceRevisionId) {
1672
+ required(sourceRevisionId, "SDK_BEHAVIOR_POLICY_SOURCE_ID_REQUIRED");
1673
+ return this.request({
1674
+ method: "GET",
1675
+ path: "/v1/behavior-policy-sources/" + encodeURIComponent(sourceRevisionId)
1676
+ });
1677
+ }
1678
+ /** Conflict preview only. Returned canActivate=false is intentional. */
1679
+ previewBehaviorPolicyBinding(input) {
1680
+ required(input.sourceRevisionId, "SDK_BEHAVIOR_POLICY_SOURCE_ID_REQUIRED");
1681
+ required(input.sourceDigest, "SDK_BEHAVIOR_POLICY_SOURCE_DIGEST_REQUIRED");
1682
+ required(input.programId, "SDK_BEHAVIOR_POLICY_PROGRAM_ID_REQUIRED");
1683
+ return this.request({
1684
+ method: "POST",
1685
+ path: "/v1/behavior-policy-bindings/preview",
1686
+ body: input
1687
+ });
1688
+ }
1689
+ /** Preview's digest is a concurrency precondition, never approval. */
1690
+ getCurrentBehaviorPolicyBinding(policyKey, options = {}) {
1691
+ required(policyKey, "SDK_BEHAVIOR_POLICY_KEY_REQUIRED");
1692
+ return this.request({
1693
+ method: "GET",
1694
+ path: "/v1/behavior-policy-bindings/current",
1695
+ query: {
1696
+ policyKey,
1697
+ ...options.sourceLevel ? { sourceLevel: options.sourceLevel } : {},
1698
+ ...options.sourceId ? { sourceId: options.sourceId } : {}
1699
+ }
1700
+ });
1701
+ }
1702
+ /** One non-retryable, server-reviewed PostgreSQL transaction. */
1703
+ commitBehaviorPolicyBinding(input) {
1704
+ for (const key of [
1705
+ "sourceRevisionId",
1706
+ "sourceDigest",
1707
+ "programId",
1708
+ "programDigest",
1709
+ "expectedPolicySnapshotDigest",
1710
+ "reason"
1711
+ ])
1712
+ required(input[key], "SDK_POLICY_RELEASE_FIELD_REQUIRED");
1713
+ if (!["ACTIVATE", "REPLACE", "ROLLBACK"].includes(input.mode))
1714
+ throw new Error("SDK_POLICY_RELEASE_MODE_INVALID");
1715
+ if (input.mode !== "ACTIVATE")
1716
+ required(input.expectedCurrentBindingDigest, "SDK_POLICY_RELEASE_CURRENT_BINDING_REQUIRED");
1717
+ return this.request(
1718
+ {
1719
+ method: "POST",
1720
+ path: "/v1/behavior-policy-bindings/commit",
1721
+ body: { ...input }
1722
+ },
1723
+ { enforcing: true }
1724
+ );
1725
+ }
1726
+ /** Read-only full blast-radius simulation. Digest is a CAS precondition, not approval. */
1727
+ previewWideBehaviorPolicyImpact(input) {
1728
+ required(input.sourceRevisionId, "SDK_POLICY_IMPACT_SOURCE_REQUIRED");
1729
+ required(input.sourceDigest, "SDK_POLICY_IMPACT_DIGEST_REQUIRED");
1730
+ if (!["ACTIVATE", "REPLACE", "ROLLBACK"].includes(input.mode))
1731
+ throw new Error("SDK_POLICY_RELEASE_MODE_INVALID");
1732
+ if (input.mode !== "ACTIVATE")
1733
+ required(input.expectedCurrentBindingDigest, "SDK_POLICY_RELEASE_CURRENT_BINDING_REQUIRED");
1734
+ return this.request({
1735
+ method: "POST",
1736
+ path: "/v1/behavior-policy-bindings/impact",
1737
+ body: input
1738
+ });
1739
+ }
1740
+ /** Independent owner approval + server-revalidated impact under one transaction. */
1741
+ commitWideBehaviorPolicyBinding(input) {
1742
+ for (const key of ["sourceRevisionId", "sourceDigest", "expectedImpactDigest", "reason"])
1743
+ required(input[key], "SDK_POLICY_IMPACT_COMMIT_FIELD_REQUIRED");
1744
+ if (!["ACTIVATE", "REPLACE", "ROLLBACK"].includes(input.mode))
1745
+ throw new Error("SDK_POLICY_RELEASE_MODE_INVALID");
1746
+ if (input.mode !== "ACTIVATE")
1747
+ required(input.expectedCurrentBindingDigest, "SDK_POLICY_RELEASE_CURRENT_BINDING_REQUIRED");
1748
+ return this.request(
1749
+ {
1750
+ method: "POST",
1751
+ path: "/v1/behavior-policy-bindings/commit-wide",
1752
+ body: input
1753
+ },
1754
+ { enforcing: true }
1755
+ );
1756
+ }
897
1757
  createBehaviorProgram(program, options = {}) {
898
1758
  if (!program || typeof program !== "object")
899
1759
  throw new Error("SDK_PROGRAM_REQUIRED");
@@ -916,17 +1776,24 @@ var ViraClient = class {
916
1776
  }
917
1777
  resolveCapabilities(attestationId, request, options = {}) {
918
1778
  required(attestationId, "SDK_ATTESTATION_ID_REQUIRED");
1779
+ const nested = request.executionContext && typeof request.executionContext === "object" ? request.executionContext : {};
1780
+ const executionId = request.executionId ?? nested.executionId;
1781
+ required(executionId, "SDK_CAPABILITY_EXECUTION_ID_REQUIRED");
1782
+ const { executionContext: _legacyContext, ...directRequest } = request;
919
1783
  return this.request(
920
1784
  {
921
1785
  method: "POST",
922
1786
  path: "/v1/runtime/capabilities/resolve",
923
- body: { attestationId, request }
1787
+ body: { ...directRequest, executionId, attestationId }
924
1788
  },
925
1789
  { idempotencyKey: options.idempotencyKey, enforcing: true }
926
1790
  );
927
1791
  }
928
1792
  recordCapabilityTrace(decisionDigest, trace, options = {}) {
929
1793
  required(decisionDigest, "SDK_DECISION_DIGEST_REQUIRED");
1794
+ required(trace.id ?? trace.traceId, "SDK_CAPABILITY_TRACE_ID_REQUIRED");
1795
+ const ctx = trace.executionContext && typeof trace.executionContext === "object" ? trace.executionContext : {};
1796
+ required(trace.executionId ?? ctx.executionId, "SDK_CAPABILITY_TRACE_EXECUTION_REQUIRED");
930
1797
  return this.request(
931
1798
  {
932
1799
  method: "POST",
@@ -989,6 +1856,9 @@ var ViraClient = class {
989
1856
  required(analysisId, "SDK_TEACH_ANALYSIS_ID_REQUIRED");
990
1857
  return this.request({ method: "GET", path: `/v1/teach/analyses/${encodeURIComponent(analysisId)}` });
991
1858
  }
1859
+ listTeachAnalyses() {
1860
+ return this.request({ method: "GET", path: "/v1/teach/analyses" });
1861
+ }
992
1862
  createCrossConversationTeachAnalysis(input, options = {}) {
993
1863
  if (!Array.isArray(input.conversationRefs) || input.conversationRefs.length < 2) throw new Error("SDK_TEACH_CROSS_CONVERSATION_REFS_REQUIRED");
994
1864
  const body = { conversationRefs: input.conversationRefs };
@@ -1155,6 +2025,13 @@ var ViraClient = class {
1155
2025
  required(input?.reason, "SDK_MANUAL_RELEASE_REASON_REQUIRED");
1156
2026
  return this.request({ method: "POST", path: "/v1/releases/manual-program", body: { programId: input.programId, reason: input.reason } }, { idempotencyKey: options.idempotencyKey ?? `sdk:manual-release:${input.programId}` });
1157
2027
  }
2028
+ retireProgramPointer(pointerKey, input, options = {}) {
2029
+ required(pointerKey, "SDK_PROMOTION_POINTER_KEY_REQUIRED");
2030
+ if (input?.confirm !== true) throw new Error("SDK_PROMOTION_POINTER_RETIRE_CONFIRMATION_REQUIRED");
2031
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1) throw new Error("SDK_PROMOTION_POINTER_VERSION_INVALID");
2032
+ if (typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 500) throw new Error("SDK_PROMOTION_POINTER_RETIRE_REASON_INVALID");
2033
+ return this.request({ method: "POST", path: `/v1/promotions/program-pointers/${encodeURIComponent(pointerKey)}/retire`, body: { confirm: true, expectedVersion: input.expectedVersion, reason: input.reason.trim() } }, { idempotencyKey: options.idempotencyKey ?? `sdk:program-pointer-retire:${pointerKey}:${input.expectedVersion}` });
2034
+ }
1158
2035
  recordDeploymentComparison(deploymentId, comparison, options = {}) {
1159
2036
  required(deploymentId, "SDK_DEPLOYMENT_ID_REQUIRED");
1160
2037
  return this.request(
@@ -1217,8 +2094,21 @@ var ViraClient = class {
1217
2094
  body: {}
1218
2095
  });
1219
2096
  }
2097
+ listAISystemUnitGrants(aiSystemId) {
2098
+ if (!aiSystemId.trim()) throw new Error("SDK_AI_SYSTEM_ID_REQUIRED");
2099
+ return this.request({ method: "GET", path: `/v1/ai-systems/${encodeURIComponent(aiSystemId)}/unit-grants` });
2100
+ }
2101
+ grantAISystemUnitAccess(aiSystemId, input, options = {}) {
2102
+ if (!aiSystemId.trim() || !input.unitId.trim()) throw new Error("SDK_AI_SYSTEM_UNIT_GRANT_REQUIRED");
2103
+ if (!input.permissions.length) throw new Error("SDK_AI_SYSTEM_UNIT_PERMISSIONS_REQUIRED");
2104
+ return this.request({ method: "POST", path: `/v1/ai-systems/${encodeURIComponent(aiSystemId)}/unit-grants`, body: { unitId: input.unitId, permissions: [...input.permissions] } }, { idempotencyKey: options.idempotencyKey ?? `sdk:ai-system-unit-grant:${globalThis.crypto.randomUUID()}`, enforcing: true });
2105
+ }
2106
+ revokeAISystemUnitAccess(aiSystemId, unitId, options = {}) {
2107
+ if (!aiSystemId.trim() || !unitId.trim()) throw new Error("SDK_AI_SYSTEM_UNIT_GRANT_REQUIRED");
2108
+ return this.request({ method: "DELETE", path: `/v1/ai-systems/${encodeURIComponent(aiSystemId)}/unit-grants/${encodeURIComponent(unitId)}`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:ai-system-unit-revoke:${globalThis.crypto.randomUUID()}`, enforcing: true });
2109
+ }
1220
2110
  };
1221
- function buildRuntimeRequest(input) {
2111
+ function buildRuntimeRequest(input, options = {}) {
1222
2112
  const {
1223
2113
  organizationId,
1224
2114
  projectId,
@@ -1246,6 +2136,23 @@ function buildRuntimeRequest(input) {
1246
2136
  if (typeof value !== "string" || !value.trim())
1247
2137
  throw new Error("SDK_REQUEST_FIELD_REQUIRED");
1248
2138
  if (!Number.isFinite(expiresAt)) throw new Error("SDK_EXPIRY_REQUIRED");
2139
+ if (Object.prototype.hasOwnProperty.call(input, "stagedRoutePin") || Object.prototype.hasOwnProperty.call(input, "runtimeRoutePin"))
2140
+ throw new Error("SDK_RUNTIME_ROUTE_PIN_CALLER_FORBIDDEN");
2141
+ const validation = input.cutoverRouteValidation;
2142
+ if (validation !== void 0 && !options.allowStagedValidation)
2143
+ throw new Error("SDK_RUNTIME_STAGED_VALIDATION_UNSUPPORTED_ROUTE");
2144
+ const pair = input.aiSystemId !== void 0 || input.connectionId !== void 0;
2145
+ if (options.includeAIIdentity && pair && (typeof input.aiSystemId !== "string" || !input.aiSystemId.trim() || input.aiSystemId !== input.aiSystemId.trim() || typeof input.connectionId !== "string" || !input.connectionId.trim() || input.connectionId !== input.connectionId.trim()))
2146
+ throw new Error("SDK_RUNTIME_AI_IDENTITY_PAIR_REQUIRED");
2147
+ if (validation !== void 0) {
2148
+ if (!options.includeAIIdentity || !pair)
2149
+ throw new Error("SDK_RUNTIME_AI_IDENTITY_PAIR_REQUIRED");
2150
+ if (!validation || typeof validation !== "object" || Array.isArray(validation))
2151
+ throw new Error("SDK_RUNTIME_STAGED_VALIDATION_INVALID");
2152
+ const v = validation;
2153
+ if (Object.keys(v).length !== 3 || Object.keys(v).some((key) => !["mode", "sourceAiSystemId", "expectedVersion"].includes(key)) || v.mode !== "STAGED_VALIDATION" || typeof v.sourceAiSystemId !== "string" || !v.sourceAiSystemId.trim() || v.sourceAiSystemId !== v.sourceAiSystemId.trim() || !Number.isSafeInteger(v.expectedVersion) || Number(v.expectedVersion) < 1)
2154
+ throw new Error("SDK_RUNTIME_STAGED_VALIDATION_INVALID");
2155
+ }
1249
2156
  const boundary = {
1250
2157
  ...typeof decisionPlanId === "string" ? { decisionPlanId } : {},
1251
2158
  ...typeof calibrationId === "string" ? { calibrationId } : {},
@@ -1263,7 +2170,9 @@ function buildRuntimeRequest(input) {
1263
2170
  idempotencyKey,
1264
2171
  nonce,
1265
2172
  expiresAt,
1266
- ...boundary
2173
+ ...boundary,
2174
+ ...options.includeAIIdentity && pair ? { aiSystemId: input.aiSystemId, connectionId: input.connectionId } : {},
2175
+ ...validation !== void 0 ? { cutoverRouteValidation: validation } : {}
1267
2176
  });
1268
2177
  }
1269
2178
  function buildPublicContentRequest(input) {
@@ -1411,6 +2320,17 @@ function createFrameworkAdapters(client) {
1411
2320
 
1412
2321
  // ../../sdks/host-lifecycle.ts
1413
2322
  import { createHash } from "node:crypto";
2323
+
2324
+ // ../../contracts/external-host-commercial-v1.ts
2325
+ var externalHostCommercialEvidence = Object.freeze({
2326
+ schemaVersion: 1,
2327
+ chargeClass: "byok",
2328
+ authority: "HOST_REPORTED_UNVERIFIED",
2329
+ settlementStatus: "NOT_CHARGEABLE",
2330
+ managedCreditEligible: false
2331
+ });
2332
+
2333
+ // ../../sdks/host-lifecycle.ts
1414
2334
  function resolveHostToolBinding(bindings, hostToolName) {
1415
2335
  const name = hostToolName.trim();
1416
2336
  if (!name) return null;
@@ -1483,7 +2403,7 @@ var bodyOf = (response) => {
1483
2403
  }
1484
2404
  return response && typeof response === "object" && !Array.isArray(response) ? response : {};
1485
2405
  };
1486
- var isAllow = (decision) => decision.decision === "ALLOW" && Boolean(decision.authorityReceiptDigest && decision.decisionDigest);
2406
+ var isAllow = (decision) => decision.decision === "ALLOW" && /^[a-f0-9]{64}$/.test(decision.authorityReceiptDigest ?? "") && /^[a-f0-9]{64}$/.test(decision.decisionDigest ?? "");
1487
2407
  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);
1488
2408
  var digest = (value) => createHash("sha256").update(canonical(value), "utf8").digest("hex");
1489
2409
  function createViraHostRuntime(client, config) {
@@ -1539,13 +2459,13 @@ function createViraHostRuntime(client, config) {
1539
2459
  if (!capabilities.canInjectContext) return { status: "unavailable", reasonCode: "HOST_CONTEXT_INJECTION_UNSUPPORTED" };
1540
2460
  if (capabilities.canObserveModel) {
1541
2461
  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);
1542
- 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);
2462
+ 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), commercial: externalHostCommercialEvidence, minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } }, { idempotencyKey: `sdk:model.request:${request.conversationId}:${request.requestId}` }).catch(() => void 0);
1543
2463
  }
1544
2464
  await connectOnce();
1545
2465
  const profile = request.profile || {};
1546
2466
  const existingHierarchy = profile.scopeHierarchy && typeof profile.scopeHierarchy === "object" && !Array.isArray(profile.scopeHierarchy) ? profile.scopeHierarchy : {};
1547
2467
  const scopedProfile = request.workspaceId || request.userId ? { ...profile, scopeHierarchy: { ...existingHierarchy, ...request.workspaceId ? { workspaceId: request.workspaceId } : {}, ...request.userId ? { userId: request.userId } : {}, sessionId: request.sessionId ?? request.conversationId } } : request.profile;
1548
- const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, profile: scopedProfile, revisionId: request.revisionId, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId, signalAttestationRefs: request.signalAttestationRefs }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
2468
+ const semantic = await withTimeout(client.resolveSemanticRuntime({ input: request.input, aiSystemId: request.aiSystemId, profile: scopedProfile, revisionId: request.revisionId, sessionId: request.sessionId ?? request.conversationId, requestId: request.requestId, signalAttestationRefs: request.signalAttestationRefs }), timeoutMs, "SDK_HOST_RESOLVE_TIMEOUT");
1549
2469
  if (!semantic) return { status: "unavailable", reasonCode: "VIRA_SEMANTIC_UNAVAILABLE" };
1550
2470
  if (semantic.multiTask === true && semantic.taskKeys?.length > 1 && typeof client.startTaskRunFromPrompt === "function") {
1551
2471
  try {
@@ -1556,7 +2476,7 @@ function createViraHostRuntime(client, config) {
1556
2476
  ...capabilities.canPreventSideEffect ? ["external_action"] : [],
1557
2477
  ...capabilities.canInspectToolAfter ? ["tool_result"] : []
1558
2478
  ];
1559
- const admitted = await withTimeout(client.startTaskRunFromPrompt({ input: request.input, taskRunId: `host-task-run-${request.requestId}`, requestId: request.requestId, conversationId: request.conversationId, traceRootRef: request.traceId, ...request.connectionId ? { connectionId: request.connectionId } : {}, hostCapabilities }), timeoutMs, "SDK_HOST_TASKRUN_ADMISSION_TIMEOUT");
2479
+ const admitted = await withTimeout(client.startTaskRunFromPrompt({ aiSystemId: request.aiSystemId, input: request.input, taskRunId: `host-task-run-${request.requestId}`, requestId: request.requestId, conversationId: request.conversationId, traceRootRef: request.traceId, ...request.connectionId ? { connectionId: request.connectionId } : {}, hostCapabilities }), timeoutMs, "SDK_HOST_TASKRUN_ADMISSION_TIMEOUT");
1560
2480
  const admittedBody = bodyOf(admitted);
1561
2481
  const taskRun = admittedBody.taskRun && typeof admittedBody.taskRun === "object" ? admittedBody.taskRun : {};
1562
2482
  const taskRunId = typeof taskRun.taskRunId === "string" ? taskRun.taskRunId : `host-task-run-${request.requestId}`;
@@ -1690,7 +2610,317 @@ function createViraHostRuntime(client, config) {
1690
2610
  };
1691
2611
  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 });
1692
2612
  }
2613
+
2614
+ // ../../sdks/host-completion.ts
2615
+ import { createHash as createHash2, createHmac, timingSafeEqual } from "node:crypto";
2616
+ var obj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
2617
+ var id = (v) => typeof v === "string" && v.length > 0 && v.length <= 500 && v === v.trim();
2618
+ var hex = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
2619
+ var scopeKeys = ["organizationId", "projectId", "environmentId", "organizationUnitId"];
2620
+ var validScope = (v) => obj(v) && Object.keys(v).length === 4 && scopeKeys.every((k) => id(v[k]));
2621
+ var sameScope = (a, b) => validScope(a) && scopeKeys.every((k) => a[k] === b[k]);
2622
+ var MAX_BYTES = 256 * 1024;
2623
+ function assertJson(v) {
2624
+ let nodes = 0;
2625
+ const active = /* @__PURE__ */ new Set();
2626
+ const walk = (x, depth) => {
2627
+ if (++nodes > 2e4 || depth > 40) throw Error("HOST_COMPLETION_JSON_LIMIT");
2628
+ if (x === null || typeof x === "boolean" || typeof x === "string") return;
2629
+ if (typeof x === "number" && Number.isFinite(x) && (!Number.isInteger(x) || Number.isSafeInteger(x))) return;
2630
+ if (!x || typeof x !== "object" || active.has(x) || !Array.isArray(x) && Object.getPrototypeOf(x) !== Object.prototype && Object.getPrototypeOf(x) !== null) throw Error("HOST_COMPLETION_JSON_INVALID");
2631
+ active.add(x);
2632
+ for (const item of Array.isArray(x) ? x : Object.values(x)) walk(item, depth + 1);
2633
+ active.delete(x);
2634
+ };
2635
+ walk(v, 0);
2636
+ if (Buffer.byteLength(JSON.stringify(v), "utf8") > MAX_BYTES) throw Error("HOST_COMPLETION_JSON_LIMIT");
2637
+ }
2638
+ function canonicalHostCompletionJson(v) {
2639
+ assertJson(v);
2640
+ const encode = (x) => Array.isArray(x) ? "[" + x.map(encode).join(",") + "]" : x !== null && typeof x === "object" ? "{" + Object.keys(x).sort().map((k) => JSON.stringify(k) + ":" + encode(x[k])).join(",") + "}" : JSON.stringify(x);
2641
+ return encode(v);
2642
+ }
2643
+ var hostCompletionDigest = (v) => createHash2("sha256").update(canonicalHostCompletionJson(v)).digest("hex");
2644
+ var constantEqual = (a, b) => timingSafeEqual(createHash2("sha256").update(a).digest(), createHash2("sha256").update(b).digest());
2645
+ function signHostCompletion(request, requestDigest, outcome, key) {
2646
+ if (key.length < 32 || !hex(requestDigest) || requestDigest !== hostCompletionDigest(request) || !id(outcome.providerInvocationId)) throw Error("HOST_COMPLETION_SIGNING_INVALID");
2647
+ assertJson(outcome.result);
2648
+ const receipt = { schemaVersion: 1, status: "COMPLETED", invocationId: request.invocationId, requestDigest, providerInvocationId: outcome.providerInvocationId, resultDigest: hostCompletionDigest(outcome.result) };
2649
+ const completion = { receipt, signature: createHmac("sha256", key).update(canonicalHostCompletionJson(receipt)).digest("hex"), result: outcome.result };
2650
+ assertJson(completion);
2651
+ if (Buffer.byteLength(JSON.stringify(completion), "utf8") > 128 * 1024) throw Error("HOST_COMPLETION_RECEIPT_LIMIT");
2652
+ return completion;
2653
+ }
2654
+ function verifyStored(record, binding) {
2655
+ const { request, requestDigest, completion } = record;
2656
+ validateRequest(request, binding);
2657
+ if (requestDigest !== hostCompletionDigest(request)) throw Error("HOST_COMPLETION_STORE_CORRUPT");
2658
+ if (completion) {
2659
+ const expected = signHostCompletion(request, requestDigest, { providerInvocationId: completion.receipt.providerInvocationId, result: completion.result }, binding.receiptKey);
2660
+ if (!constantEqual(expected.signature, completion.signature) || hostCompletionDigest(expected) !== hostCompletionDigest(completion)) throw Error("HOST_COMPLETION_STORE_CORRUPT");
2661
+ }
2662
+ return record;
2663
+ }
2664
+ function validateRequest(value, b) {
2665
+ if (!obj(value) || value.schemaVersion !== 1 || !sameScope(value.scope, b.scope) || value.aiSystemId !== b.aiSystemId || value.toolKey !== b.toolKey || value.bindingDigest !== b.bindingDigest || !id(value.actorId) || !id(value.runtimeReceiptId) || !hex(value.authorizationDigest) || !hex(value.argumentsDigest)) throw Error("HOST_COMPLETION_REQUEST_BINDING_INVALID");
2666
+ const scope = [b.scope.organizationId, b.scope.projectId, b.scope.environmentId, b.scope.organizationUnitId];
2667
+ if (b.kind === "SINGLE") {
2668
+ if (!id(value.taskRunId) || !id(value.childRunId) || !id(value.connectionId) || value.connectionId !== b.connectionId || value.semanticTaskKey !== b.semanticTaskKey || !["planDigest", "authorityDigest", "artifactDigest", "policyDigest", "inputDigest"].every((k) => hex(value[k])) || value.invocationId !== "single-host:" + hostCompletionDigest([...scope, value.taskRunId, value.childRunId])) throw Error("HOST_COMPLETION_SINGLE_BINDING_INVALID");
2669
+ } else if (b.kind === "RECOVERY") {
2670
+ if (!id(value.operationId) || !id(value.stateId) || !id(value.trajectoryKey) || !id(value.violationReceiptId) || value.connectionId !== b.connectionId || value.planDigest !== b.recoveryPlanDigest || value.stepType !== b.recoveryStepType || value.operationKey !== b.toolKey || !hex(value.authorityDigest) || value.authorizationDigest !== value.authorityDigest || !Number.isSafeInteger(value.stepIndex) || Number(value.stepIndex) < 0 || !Number.isSafeInteger(value.attempt) || Number(value.attempt) < 1 || Number(value.attempt) > 8 || ["invoke_compensation_action", "cancel_pending", "require_approval", "escalate", "terminate_trajectory"].includes(String(value.stepType)) && value.attempt !== 1 || value.operationId !== "recovery-step:" + hostCompletionDigest([...scope, null, value.stateId, value.trajectoryKey, value.authorityDigest, value.planDigest, value.stepIndex, value.operationKey, value.attempt]) || value.invocationId !== "recovery-host:" + hostCompletionDigest([...scope, value.operationId, b.toolKey]) || value.stepType === "invoke_compensation_action" && !id(value.originalEffectReceiptId) || value.terminalFailureDigest !== void 0 && (value.stepType !== "escalate" || value.attempt !== 1 || !hex(value.terminalFailureDigest))) throw Error("HOST_COMPLETION_RECOVERY_BINDING_INVALID");
2671
+ } else if (!id(value.executionId) || !id(value.stepKey) || value.stepSequence !== void 0 && (!Number.isSafeInteger(value.stepSequence) || Number(value.stepSequence) < 0) || value.invocationId !== "strategy-host:" + hostCompletionDigest([...scope, value.executionId, value.stepKey, b.toolKey, ...value.stepSequence === void 0 ? [] : [value.stepSequence]])) throw Error("HOST_COMPLETION_STRATEGY_BINDING_INVALID");
2672
+ }
2673
+ function validateBinding(b) {
2674
+ if (!["SINGLE", "STRATEGY", "RECOVERY"].includes(b.kind) || !validScope(b.scope) || !id(b.aiSystemId) || !id(b.toolKey) || !hex(b.bindingDigest) || ![b.dispatchToken, b.readbackToken, b.receiptKey].every((x) => typeof x === "string" && x.length >= 32) || (/* @__PURE__ */ new Set([b.dispatchToken, b.readbackToken, b.receiptKey])).size !== 3 || b.kind === "SINGLE" && (!id(b.connectionId) || !id(b.semanticTaskKey)) || b.kind === "RECOVERY" && (!id(b.connectionId) || !hex(b.recoveryPlanDigest) || !["retry", "restore_checkpoint", "invoke_compensation_action", "cancel_pending", "require_approval", "escalate", "terminate_trajectory"].includes(b.recoveryStepType ?? ""))) throw Error("HOST_COMPLETION_CONFIG_INVALID");
2675
+ }
2676
+ function createHostCompletionBinding(input) {
2677
+ const url = (v) => {
2678
+ const u = new URL(v);
2679
+ if (u.protocol !== "https:" || u.username || u.password || u.hash || u.search) throw Error("HOST_COMPLETION_ENDPOINT_INVALID");
2680
+ return u.toString();
2681
+ };
2682
+ const target = url(input.endpoint), readback = url(input.receiptEndpoint);
2683
+ if (target === readback) throw Error("HOST_COMPLETION_ENDPOINT_INVALID");
2684
+ const { kind, scope, aiSystemId, toolKey, connectionId, semanticTaskKey, recoveryPlanDigest, recoveryStepType, dispatchToken, readbackToken, receiptKey, tokenEnv, receiptTokenEnv, receiptKeyEnv } = input;
2685
+ const prefix = kind === "SINGLE" ? "VIRA_SINGLE_HOST_SECRET_" : kind === "RECOVERY" ? "VIRA_RECOVERY_HOST_SECRET_" : "VIRA_STRATEGY_HOST_SECRET_";
2686
+ if (![tokenEnv, receiptTokenEnv, receiptKeyEnv].every((x) => x.startsWith(prefix) && /^[A-Z0-9_]+$/.test(x)) || (/* @__PURE__ */ new Set([tokenEnv, receiptTokenEnv, receiptKeyEnv])).size !== 3) throw Error("HOST_COMPLETION_SECRET_NAMES_INVALID");
2687
+ const secretRefs = { tokenEnv, receiptTokenEnv, receiptKeyEnv, receiptKeyDigest: hostCompletionDigest(receiptKey) };
2688
+ const material = kind === "SINGLE" ? { scope, aiSystemId, semanticTaskKey, toolKey, connectionId, target, receiptEndpoint: readback, ...secretRefs } : kind === "RECOVERY" ? { kind, scope, aiSystemId, toolKey, connectionId, recoveryPlanDigest, recoveryStepType, target, readback, ...secretRefs } : { scope, aiSystemId, toolKey, target, readback, ...secretRefs };
2689
+ const binding = { kind, scope, aiSystemId, toolKey, connectionId, semanticTaskKey, recoveryPlanDigest, recoveryStepType, dispatchToken, readbackToken, receiptKey, bindingDigest: hostCompletionDigest(material) };
2690
+ validateBinding(binding);
2691
+ return binding;
2692
+ }
2693
+ function createHostCompletionAuthority(input) {
2694
+ validateBinding(input.binding);
2695
+ const binding = { ...input.binding, scope: { ...input.binding.scope } };
2696
+ const { store, tool } = input;
2697
+ const seal = async (record, outcome) => {
2698
+ const signed = signHostCompletion(record.request, record.requestDigest, outcome, binding.receiptKey);
2699
+ const saved = verifyStored(await store.complete(record.request, record.requestDigest, signed), binding);
2700
+ if (!saved.completion || hostCompletionDigest(saved.completion) !== hostCompletionDigest(signed)) throw Error("HOST_COMPLETION_CONFLICT");
2701
+ return saved.completion;
2702
+ };
2703
+ const auth = (actual, secret) => typeof actual === "string" && constantEqual(actual, "Bearer " + secret);
2704
+ return {
2705
+ async dispatch(input2) {
2706
+ if (!auth(input2.authorization, binding.dispatchToken)) return { status: 401, body: { error: "HOST_COMPLETION_UNAUTHORIZED" } };
2707
+ assertJson(input2.body);
2708
+ const body = input2.body;
2709
+ if (!obj(body) || Object.keys(body).some((k) => !["request", "requestDigest", "arguments"].includes(k)) || !obj(body.arguments)) throw Error("HOST_COMPLETION_BODY_INVALID");
2710
+ const request = body.request;
2711
+ validateRequest(request, binding);
2712
+ if (input2.idempotencyKey !== request.invocationId || body.requestDigest !== hostCompletionDigest(request) || request.argumentsDigest !== hostCompletionDigest(body.arguments)) throw Error("HOST_COMPLETION_REQUEST_DIGEST_INVALID");
2713
+ if (input2.signal?.aborted) return { status: 409, body: { error: "HOST_COMPLETION_DISPATCH_CANCELLED" } };
2714
+ const claim = await store.claim(request, body.requestDigest);
2715
+ const record = verifyStored(claim.record, binding);
2716
+ if (record.requestDigest !== body.requestDigest) throw Error("HOST_COMPLETION_IDEMPOTENCY_CONFLICT");
2717
+ if (claim.claimed && !record.completion) {
2718
+ try {
2719
+ input2.signal?.throwIfAborted();
2720
+ const outcome = await tool.execute({ request: structuredClone(request), arguments: structuredClone(body.arguments), idempotencyKey: request.invocationId, ...input2.signal ? { signal: input2.signal } : {} });
2721
+ await seal(record, outcome);
2722
+ } catch {
2723
+ return { status: 202, body: { status: "PENDING", invocationId: request.invocationId } };
2724
+ }
2725
+ }
2726
+ return { status: 202, body: { status: "ACCEPTED", invocationId: request.invocationId } };
2727
+ },
2728
+ async readback(input2) {
2729
+ if (!auth(input2.authorization, binding.readbackToken)) return { status: 401, body: { error: "HOST_COMPLETION_UNAUTHORIZED" } };
2730
+ if (!id(input2.invocationId)) return { status: 400, body: { error: "HOST_COMPLETION_INVOCATION_INVALID" } };
2731
+ const record = await store.get(input2.invocationId, binding.bindingDigest);
2732
+ if (!record) return { status: 404, body: { error: "HOST_COMPLETION_NOT_FOUND" } };
2733
+ verifyStored(record, binding);
2734
+ if (record.request.invocationId !== input2.invocationId) throw Error("HOST_COMPLETION_STORE_CORRUPT");
2735
+ let completion = record.completion;
2736
+ if (!completion && tool.recover) {
2737
+ const outcome = await tool.recover({ request: structuredClone(record.request), idempotencyKey: record.request.invocationId });
2738
+ if (outcome) completion = await seal(record, outcome);
2739
+ }
2740
+ return completion ? { status: 200, body: completion } : { status: 202, body: { status: "PENDING" } };
2741
+ },
2742
+ capabilities(authorization) {
2743
+ return auth(authorization, binding.readbackToken) ? { status: 200, body: { schemaVersion: 1, kind: binding.kind, scope: binding.scope, aiSystemId: binding.aiSystemId, toolKey: binding.toolKey, bindingDigest: binding.bindingDigest, independentReadback: true, durableClaimRequired: true, providerRecovery: !!tool.recover } } : { status: 401, body: { error: "HOST_COMPLETION_UNAUTHORIZED" } };
2744
+ }
2745
+ };
2746
+ }
2747
+ function createHostCompletionHttpHandler(authority, paths = {}) {
2748
+ const dispatch = paths.dispatch ?? "/action", readback = paths.readback ?? "/receipt", capabilities = paths.capabilities ?? "/capabilities";
2749
+ if ((/* @__PURE__ */ new Set([dispatch, readback, capabilities])).size !== 3 || ![dispatch, readback, capabilities].every((p) => /^\/[a-zA-Z0-9/_-]+$/.test(p))) throw Error("HOST_COMPLETION_PATH_INVALID");
2750
+ return async (req, res) => {
2751
+ const send = (status, body) => {
2752
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff" });
2753
+ res.end(JSON.stringify(body));
2754
+ };
2755
+ try {
2756
+ const u = new URL(req.url ?? "/", "http://host.invalid");
2757
+ if (req.method === "GET" && u.pathname === readback && u.searchParams.getAll("invocationId").length === 1 && Array.from(u.searchParams.keys()).every((k) => k === "invocationId")) {
2758
+ const result = await authority.readback({ authorization: req.headers.authorization, invocationId: u.searchParams.get("invocationId") });
2759
+ return send(result.status, result.body);
2760
+ }
2761
+ if (req.method === "GET" && u.pathname === capabilities && !u.search) {
2762
+ const result = authority.capabilities(req.headers.authorization);
2763
+ return send(result.status, result.body);
2764
+ }
2765
+ if (req.method !== "POST" || u.pathname !== dispatch || u.search) return send(404, { error: "HOST_COMPLETION_ROUTE_NOT_FOUND" });
2766
+ if (!/^application\/json(?:;|$)/i.test(req.headers["content-type"] ?? "")) return send(415, { error: "HOST_COMPLETION_CONTENT_TYPE" });
2767
+ const chunks = [];
2768
+ let size = 0;
2769
+ for await (const chunk of req) {
2770
+ const bytes = Buffer.from(chunk);
2771
+ size += bytes.length;
2772
+ if (size > MAX_BYTES) {
2773
+ send(413, { error: "HOST_COMPLETION_BODY_LIMIT" });
2774
+ return;
2775
+ }
2776
+ chunks.push(bytes);
2777
+ }
2778
+ let body;
2779
+ try {
2780
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
2781
+ } catch {
2782
+ return send(400, { error: "HOST_COMPLETION_BODY_INVALID" });
2783
+ }
2784
+ const controller = new AbortController();
2785
+ const disconnected = () => {
2786
+ if (!res.writableEnded) controller.abort(Error("HOST_COMPLETION_CLIENT_DISCONNECTED"));
2787
+ };
2788
+ res.once("close", disconnected);
2789
+ if (res.destroyed) disconnected();
2790
+ try {
2791
+ const result = await authority.dispatch({ authorization: req.headers.authorization, idempotencyKey: req.headers["idempotency-key"], body, signal: controller.signal });
2792
+ if (!res.destroyed) return send(result.status, result.body);
2793
+ } finally {
2794
+ res.removeListener("close", disconnected);
2795
+ }
2796
+ } catch (error) {
2797
+ const code = error instanceof Error && /^HOST_COMPLETION_[A-Z_]+$/.test(error.message) ? error.message : "HOST_COMPLETION_UNAVAILABLE";
2798
+ return send(code.includes("CONFLICT") ? 409 : code.includes("INVALID") || code.includes("LIMIT") ? 400 : 503, { error: code });
2799
+ }
2800
+ };
2801
+ }
2802
+ async function checkHostCompletionCapabilities(input) {
2803
+ validateBinding(input.binding);
2804
+ const receipt = new URL(input.receiptEndpoint);
2805
+ if (receipt.protocol !== "https:" || receipt.username || receipt.password || receipt.hash || receipt.search) throw Error("HOST_COMPLETION_ENDPOINT_INVALID");
2806
+ const target = new URL("/capabilities", receipt);
2807
+ const response = await (input.fetcher ?? fetch)(target, { method: "GET", headers: { authorization: "Bearer " + input.binding.readbackToken, accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(1e4) });
2808
+ if (response.status !== 200) throw Error("HOST_COMPLETION_CAPABILITIES_UNAVAILABLE");
2809
+ const text = await response.text();
2810
+ if (Buffer.byteLength(text, "utf8") > 16384) throw Error("HOST_COMPLETION_CAPABILITIES_LIMIT");
2811
+ const value = JSON.parse(text), b = input.binding;
2812
+ if (!obj(value) || value.schemaVersion !== 1 || value.kind !== b.kind || !sameScope(value.scope, b.scope) || value.aiSystemId !== b.aiSystemId || value.toolKey !== b.toolKey || value.bindingDigest !== b.bindingDigest || value.independentReadback !== true || value.durableClaimRequired !== true || typeof value.providerRecovery !== "boolean") throw Error("HOST_COMPLETION_CAPABILITIES_BINDING_INVALID");
2813
+ return { verified: true, bindingDigest: b.bindingDigest, providerRecovery: value.providerRecovery };
2814
+ }
2815
+
2816
+ // ../../sdks/host-completion-postgres.ts
2817
+ var HOST_COMPLETION_POSTGRES_SCHEMA = `
2818
+ CREATE TABLE IF NOT EXISTS vira_host_completion_v1 (
2819
+ invocation_id text PRIMARY KEY,
2820
+ binding_digest text NOT NULL CHECK(binding_digest ~ '^[a-f0-9]{64}$'),
2821
+ request_digest text NOT NULL CHECK(request_digest ~ '^[a-f0-9]{64}$'),
2822
+ request_json text NOT NULL,
2823
+ completion_json text,
2824
+ completion_digest text CHECK(completion_digest ~ '^[a-f0-9]{64}$'),
2825
+ admitted_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
2826
+ completed_at timestamptz,
2827
+ CHECK ((completion_json IS NULL AND completion_digest IS NULL AND completed_at IS NULL)
2828
+ OR (completion_json IS NOT NULL AND completion_digest IS NOT NULL AND completed_at IS NOT NULL))
2829
+ );
2830
+ CREATE OR REPLACE FUNCTION vira_host_completion_v1_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
2831
+ BEGIN
2832
+ IF TG_OP='DELETE' THEN RAISE EXCEPTION 'HOST_COMPLETION_IMMUTABLE'; END IF;
2833
+ IF OLD.completion_json IS NOT NULL OR NEW.completion_json IS NULL
2834
+ OR NEW.invocation_id IS DISTINCT FROM OLD.invocation_id OR NEW.binding_digest IS DISTINCT FROM OLD.binding_digest
2835
+ OR NEW.request_digest IS DISTINCT FROM OLD.request_digest OR NEW.request_json IS DISTINCT FROM OLD.request_json
2836
+ OR NEW.admitted_at IS DISTINCT FROM OLD.admitted_at THEN RAISE EXCEPTION 'HOST_COMPLETION_IMMUTABLE'; END IF;
2837
+ RETURN NEW;
2838
+ END;
2839
+ $$;
2840
+ DROP TRIGGER IF EXISTS vira_host_completion_v1_immutable ON vira_host_completion_v1;
2841
+ CREATE TRIGGER vira_host_completion_v1_immutable BEFORE UPDATE OR DELETE ON vira_host_completion_v1
2842
+ FOR EACH ROW EXECUTE FUNCTION vira_host_completion_v1_immutable();
2843
+ `;
2844
+ var columns = "invocation_id,binding_digest,request_digest,request_json,completion_json,completion_digest";
2845
+ function decode(row) {
2846
+ const r = row;
2847
+ const request = JSON.parse(r.request_json);
2848
+ if (request.invocationId !== r.invocation_id || request.bindingDigest !== r.binding_digest || hostCompletionDigest(request) !== r.request_digest) throw Error("HOST_COMPLETION_STORE_CORRUPT");
2849
+ const completion = r.completion_json === null ? null : JSON.parse(r.completion_json);
2850
+ if (completion ? hostCompletionDigest(completion) !== r.completion_digest : r.completion_digest !== null) throw Error("HOST_COMPLETION_STORE_CORRUPT");
2851
+ return { request, requestDigest: r.request_digest, completion };
2852
+ }
2853
+ function createPostgresHostCompletionStore(db) {
2854
+ const get = async (invocationId, bindingDigest) => {
2855
+ const { rows } = await db.query("SELECT " + columns + " FROM vira_host_completion_v1 WHERE invocation_id=$1 AND binding_digest=$2", [invocationId, bindingDigest]);
2856
+ if (rows.length > 1) throw Error("HOST_COMPLETION_STORE_CORRUPT");
2857
+ return rows[0] ? decode(rows[0]) : null;
2858
+ };
2859
+ return {
2860
+ get,
2861
+ async claim(request, requestDigest) {
2862
+ if (hostCompletionDigest(request) !== requestDigest) throw Error("HOST_COMPLETION_REQUEST_DIGEST_INVALID");
2863
+ const { rows } = await db.query("INSERT INTO vira_host_completion_v1(invocation_id,binding_digest,request_digest,request_json) VALUES($1,$2,$3,$4) ON CONFLICT(invocation_id) DO NOTHING RETURNING " + columns, [request.invocationId, request.bindingDigest, requestDigest, JSON.stringify(request)]);
2864
+ if (rows.length > 1) throw Error("HOST_COMPLETION_STORE_CORRUPT");
2865
+ if (rows[0]) return { claimed: true, record: decode(rows[0]) };
2866
+ const record = await get(request.invocationId, request.bindingDigest);
2867
+ if (!record || record.requestDigest !== requestDigest) throw Error("HOST_COMPLETION_IDEMPOTENCY_CONFLICT");
2868
+ return { claimed: false, record };
2869
+ },
2870
+ async complete(request, requestDigest, completion) {
2871
+ if (hostCompletionDigest(request) !== requestDigest || completion.receipt.invocationId !== request.invocationId || completion.receipt.requestDigest !== requestDigest) throw Error("HOST_COMPLETION_REQUEST_DIGEST_INVALID");
2872
+ const digest2 = hostCompletionDigest(completion);
2873
+ const { rows } = await db.query("UPDATE vira_host_completion_v1 SET completion_json=$4,completion_digest=$5,completed_at=CURRENT_TIMESTAMP WHERE invocation_id=$1 AND binding_digest=$2 AND request_digest=$3 AND completion_json IS NULL RETURNING " + columns, [request.invocationId, request.bindingDigest, requestDigest, JSON.stringify(completion), digest2]);
2874
+ if (rows.length > 1) throw Error("HOST_COMPLETION_STORE_CORRUPT");
2875
+ const record = rows[0] ? decode(rows[0]) : await get(request.invocationId, request.bindingDigest);
2876
+ if (!record || record.requestDigest !== requestDigest || !record.completion || hostCompletionDigest(record.completion) !== digest2) throw Error("HOST_COMPLETION_CONFLICT");
2877
+ return record;
2878
+ }
2879
+ };
2880
+ }
2881
+
2882
+ // ../../sdks/host-completion-adapters.ts
2883
+ var object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
2884
+ function decodeHostEffectResult(value) {
2885
+ if (!object(value) || typeof value.providerInvocationId !== "string" || !value.providerInvocationId.trim() || !Object.hasOwn(value, "result")) throw Error("HOST_COMPLETION_PROVIDER_EVIDENCE_REQUIRED");
2886
+ return { providerInvocationId: value.providerInvocationId, result: value.result };
2887
+ }
2888
+ function createMcpHostCompletionTool(input) {
2889
+ const { client, toolKey } = input;
2890
+ const name = input.mcpToolName ?? toolKey;
2891
+ if (!toolKey.trim() || !name.trim() || typeof client.callTool !== "function") throw Error("HOST_COMPLETION_MCP_CONFIG_INVALID");
2892
+ return {
2893
+ async execute({ request, arguments: args, idempotencyKey, signal }) {
2894
+ if (request.toolKey !== toolKey || idempotencyKey !== request.invocationId) throw Error("HOST_COMPLETION_MCP_BINDING_INVALID");
2895
+ signal?.throwIfAborted();
2896
+ const response = await client.callTool({ name, arguments: { ...args }, _meta: { "vira/idempotencyKey": idempotencyKey, "vira/requestDigest": request.argumentsDigest } }, void 0, signal ? { signal } : void 0);
2897
+ if (!object(response) || response.isError === true) throw Error("HOST_COMPLETION_MCP_OUTCOME_UNKNOWN");
2898
+ if (input.decode) return input.decode(response, request);
2899
+ return decodeHostEffectResult(response.structuredContent);
2900
+ },
2901
+ ...input.recover ? { recover: async (value) => {
2902
+ if (value.request.toolKey !== toolKey || value.idempotencyKey !== value.request.invocationId) throw Error("HOST_COMPLETION_MCP_BINDING_INVALID");
2903
+ return input.recover(value);
2904
+ } } : {}
2905
+ };
2906
+ }
2907
+ function createOpenCodeHostCompletionTool(input) {
2908
+ if (!input.toolKey.trim() || typeof input.invoke !== "function") throw Error("HOST_COMPLETION_OPENCODE_CONFIG_INVALID");
2909
+ return {
2910
+ async execute({ request, arguments: args, idempotencyKey, signal }) {
2911
+ if (request.toolKey !== input.toolKey || idempotencyKey !== request.invocationId) throw Error("HOST_COMPLETION_OPENCODE_BINDING_INVALID");
2912
+ signal?.throwIfAborted();
2913
+ const outcome = await input.invoke(args, { idempotencyKey, request, ...signal ? { signal } : {} });
2914
+ return input.decode ? input.decode(outcome, request) : decodeHostEffectResult(outcome);
2915
+ },
2916
+ ...input.recover ? { recover: async (value) => {
2917
+ if (value.request.toolKey !== input.toolKey || value.idempotencyKey !== value.request.invocationId) throw Error("HOST_COMPLETION_OPENCODE_BINDING_INVALID");
2918
+ return input.recover(value);
2919
+ } } : {}
2920
+ };
2921
+ }
1693
2922
  export {
2923
+ HOST_COMPLETION_POSTGRES_SCHEMA,
1694
2924
  ViraApiError,
1695
2925
  ViraClient,
1696
2926
  buildAISystemRequest,
@@ -1698,21 +2928,32 @@ export {
1698
2928
  buildObservationRequest,
1699
2929
  buildPublicContentRequest,
1700
2930
  buildRuntimeRequest,
2931
+ canonicalHostCompletionJson,
2932
+ checkHostCompletionCapabilities,
1701
2933
  createFrameworkAdapters,
1702
2934
  createFrameworkLifecycleAdapter,
1703
2935
  createFrameworkObservationAdapter,
1704
2936
  createFrameworkRuntimeCore,
1705
2937
  createGenericHttpHooks,
1706
2938
  createGenericRuntimeHooks,
2939
+ createHostCompletionAuthority,
2940
+ createHostCompletionBinding,
2941
+ createHostCompletionHttpHandler,
1707
2942
  createLangGraphHooks,
1708
2943
  createMastraHooks,
2944
+ createMcpHostCompletionTool,
1709
2945
  createOpenAIAgentsHooks,
1710
2946
  createOpenAICompatibleHooks,
2947
+ createOpenCodeHostCompletionTool,
2948
+ createPostgresHostCompletionStore,
1711
2949
  createVercelAIHooks,
1712
2950
  createViraHostRuntime,
1713
2951
  createViraMiddleware,
2952
+ decodeHostEffectResult,
2953
+ hostCompletionDigest,
1714
2954
  redactToolObservation,
1715
2955
  resolveFrameworkBoundary,
1716
2956
  resolveHostToolBinding,
2957
+ signHostCompletion,
1717
2958
  viraHttpRequest
1718
2959
  };