@tryvira/opencode 0.1.83 → 0.1.85

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/tui.js ADDED
@@ -0,0 +1,2488 @@
1
+ // ../../sdks/js-client.ts
2
+ var listQuery = (options) => ({
3
+ ...options.limit === void 0 ? {} : { limit: String(options.limit) },
4
+ ...options.cursor ? { cursor: options.cursor } : {},
5
+ ...options.status ? { status: options.status } : {},
6
+ ...options.search ? { search: options.search } : {}
7
+ });
8
+ var ViraApiError = class extends Error {
9
+ status;
10
+ body;
11
+ requestId;
12
+ constructor(message, status, body, requestId) {
13
+ super(message);
14
+ this.name = "ViraApiError";
15
+ this.status = status;
16
+ this.body = body;
17
+ this.requestId = requestId;
18
+ }
19
+ };
20
+ var required = (value, code) => {
21
+ if (typeof value !== "string" || !value.trim()) throw new Error(code);
22
+ return value;
23
+ };
24
+ var normalizeBaseUrl = (value, allowInsecureLocalhost = false) => {
25
+ let url;
26
+ try {
27
+ url = new URL(required(value, "SDK_BASE_URL_REQUIRED"));
28
+ } catch {
29
+ throw new Error("SDK_BASE_URL_INVALID");
30
+ }
31
+ const hostname = url.hostname.toLowerCase();
32
+ const loopback = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
33
+ if (url.username || url.password || url.search || url.hash) throw new Error("SDK_BASE_URL_INVALID");
34
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback && allowInsecureLocalhost))
35
+ throw new Error("SDK_HTTPS_REQUIRED");
36
+ return value.replace(/\/$/, "");
37
+ };
38
+ var canonicalJson = (value) => JSON.stringify(
39
+ value,
40
+ (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([left], [right]) => left.localeCompare(right))) : item
41
+ );
42
+ var contentIdempotencyKey = async (operation, request) => {
43
+ if (!globalThis.crypto?.subtle) throw new Error("SDK_IDEMPOTENCY_CRYPTO_UNAVAILABLE");
44
+ const bytes = new TextEncoder().encode(canonicalJson(request));
45
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
46
+ const hex2 = [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
47
+ return `${operation}:${hex2}`;
48
+ };
49
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
50
+ var retryAfterMs = (value, now = Date.now()) => {
51
+ if (!value) return 0;
52
+ const seconds = Number(value);
53
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1e3, 12e4);
54
+ const date = Date.parse(value);
55
+ return Number.isFinite(date) && date > now ? Math.min(date - now, 12e4) : 0;
56
+ };
57
+ function notifyTransport(observer, method, status, error, started, attempt) {
58
+ if (!observer) return;
59
+ try {
60
+ const known = ["GET", "POST", "PUT", "PATCH", "DELETE"];
61
+ const outcome = status === 429 ? "http_429" : status !== void 0 ? status >= 200 && status < 600 ? "http_" + Math.floor(status / 100) + "xx" : "http_other" : error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name) ? "timeout" : "transport_error";
62
+ const event = Object.freeze({ method: known.includes(method) ? method : "OTHER", outcome, durationMs: Math.max(0, performance.now() - started), attempt: attempt + 1 });
63
+ void Promise.resolve(observer(event)).catch(() => {
64
+ });
65
+ } catch {
66
+ }
67
+ }
68
+ var ViraClient = class {
69
+ evaluations;
70
+ teach;
71
+ packs;
72
+ baseUrl;
73
+ apiKey;
74
+ apiCredentialProvider;
75
+ operatorDelegationTokenProvider;
76
+ fetcher;
77
+ transportObserver;
78
+ timeoutMs;
79
+ retries;
80
+ failureMode;
81
+ defaultHeaders;
82
+ boundConnectionId;
83
+ constructor(options) {
84
+ this.baseUrl = normalizeBaseUrl(options.baseUrl, options.allowInsecureLocalhost === true);
85
+ this.apiKey = options.apiKey;
86
+ this.apiCredentialProvider = options.apiCredentialProvider ?? options.accessTokenProvider;
87
+ this.operatorDelegationTokenProvider = options.operatorDelegationTokenProvider;
88
+ this.fetcher = options.fetcher ?? fetch;
89
+ this.transportObserver = options.transportObserver;
90
+ this.timeoutMs = Math.max(
91
+ 1e3,
92
+ Math.min(options.timeoutMs ?? 15e3, 12e4)
93
+ );
94
+ this.retries = Math.max(0, Math.min(options.retries ?? 2, 5));
95
+ this.failureMode = options.failureMode ?? "throw";
96
+ this.defaultHeaders = options.organizationUnitId ? { ...options.defaultHeaders, "x-vira-organization-unit-id": options.organizationUnitId } : options.defaultHeaders ?? {};
97
+ this.boundConnectionId = options.connectionId;
98
+ this.evaluations = {
99
+ createPlan: (input, options2 = {}) => this.createEvaluationPlan(input, options2),
100
+ get: (id) => this.getEvaluation(id),
101
+ compare: (id) => this.getEvaluationComparison(id),
102
+ reviewFinding: (evaluationId, findingId, input, options2 = {}) => this.reviewComparativeFinding(evaluationId, findingId, input, options2),
103
+ proposeImprovement: (id, input, options2 = {}) => this.createImprovementProposal(id, input, options2)
104
+ };
105
+ this.teach = {
106
+ review: (id, action = "request-review", options2 = {}) => this.reviewImprovementProposal(id, action, options2),
107
+ createCandidate: (input, options2 = {}) => this.createBehaviorRevisionCandidate(input, options2),
108
+ evaluateCandidate: (id, input, options2 = {}) => this.evaluateBehaviorRevisionCandidate(id, input, options2)
109
+ };
110
+ this.packs = {
111
+ createRevision: (input, options2 = {}) => this.createPackRevision(input, options2),
112
+ getRevision: (id) => this.getPackRevision(id),
113
+ diffRevision: (id) => this.getPackRevisionDiff(id),
114
+ transitionRevision: (id, transition, options2 = {}) => this.transitionPackRevision(id, transition, options2)
115
+ };
116
+ }
117
+ listOrganizationUnits() {
118
+ return this.request({ method: "GET", path: "/v1/organization-units" });
119
+ }
120
+ listOrganizationBillingAdmins() {
121
+ return this.request({ method: "GET", path: "/v1/organization/billing-admins" });
122
+ }
123
+ setOrganizationBillingAdmin(actorId, status = "ACTIVE", options = {}) {
124
+ if (!actorId.trim()) throw new Error("SDK_ACTOR_ID_REQUIRED");
125
+ 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 });
126
+ }
127
+ getAICreditWallet() {
128
+ return this.request({ method: "GET", path: "/v1/billing/credits" });
129
+ }
130
+ listAICreditBudgets() {
131
+ return this.request({ method: "GET", path: "/v1/billing/credits/budgets" });
132
+ }
133
+ listAIUsageReceipts(input = {}) {
134
+ const query = {};
135
+ if (input.organizationUnitId) query.organizationUnitId = input.organizationUnitId;
136
+ if (input.limit !== void 0) {
137
+ if (!Number.isSafeInteger(input.limit)) throw new Error("SDK_AI_USAGE_LIMIT_INVALID");
138
+ query.limit = String(Math.min(500, Math.max(1, input.limit)));
139
+ }
140
+ return this.request({ method: "GET", path: "/v1/billing/ai-usage", ...Object.keys(query).length ? { query } : {} });
141
+ }
142
+ getAIUsageSummary(input = {}) {
143
+ return this.request({ method: "GET", path: "/v1/billing/ai-usage/summary", ...input.organizationUnitId ? { query: { organizationUnitId: input.organizationUnitId } } : {} });
144
+ }
145
+ reserveAICredits(input, options = {}) {
146
+ if (!Number.isSafeInteger(input.amountMicrocredits) || input.amountMicrocredits < 1) throw new Error("SDK_AI_CREDIT_AMOUNT_INVALID");
147
+ if (!input.idempotencyKey.trim()) throw new Error("SDK_IDEMPOTENCY_KEY_REQUIRED");
148
+ return this.request({ method: "POST", path: "/v1/billing/credits/reservations", body: input }, { idempotencyKey: options.idempotencyKey ?? input.idempotencyKey });
149
+ }
150
+ releaseAICreditReservation(reservationId, options = {}) {
151
+ if (!reservationId.trim()) throw new Error("SDK_AI_CREDIT_RESERVATION_ID_REQUIRED");
152
+ return this.request({ method: "POST", path: `/v1/billing/credits/reservations/${encodeURIComponent(reservationId)}/release`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:ai-credit-release:${reservationId}` });
153
+ }
154
+ listInbox(options = {}) {
155
+ const limit = options.limit === void 0 ? void 0 : Math.min(100, Math.max(1, Math.trunc(options.limit)));
156
+ if (options.limit !== void 0 && !Number.isFinite(options.limit)) throw new Error("SDK_NOTIFICATION_LIMIT_INVALID");
157
+ 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 } : {} } });
158
+ }
159
+ readNotificationUpdates(options = {}) {
160
+ const count = options.count ?? 32;
161
+ if (!Number.isSafeInteger(count) || count < 1 || count > 100) throw new Error("SDK_NOTIFICATION_UPDATES_COUNT_INVALID");
162
+ return this.request({ method: "GET", path: "/v1/notifications/updates", query: { afterId: options.afterId ?? "latest", count: String(count) } });
163
+ }
164
+ markInboxRead(notificationId, options = {}) {
165
+ if (!notificationId.trim()) throw new Error("SDK_NOTIFICATION_ID_REQUIRED");
166
+ return this.request({ method: "POST", path: `/v1/notifications/${encodeURIComponent(notificationId)}/read`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:inbox-read:${notificationId}` });
167
+ }
168
+ listNotificationDestinations() {
169
+ return this.request({ method: "GET", path: "/v1/notification-destinations" });
170
+ }
171
+ createNotificationDestination(input, options) {
172
+ if (!input.label.trim()) throw new Error("SDK_NOTIFICATION_DESTINATION_LABEL_REQUIRED");
173
+ if (!input.endpoint.trim()) throw new Error("SDK_NOTIFICATION_DESTINATION_ENDPOINT_REQUIRED");
174
+ if (!options.idempotencyKey.trim()) throw new Error("SDK_IDEMPOTENCY_KEY_REQUIRED");
175
+ return this.request({ method: "POST", path: "/v1/notification-destinations", body: input }, options);
176
+ }
177
+ revokeNotificationDestination(destinationId, options = {}) {
178
+ if (!destinationId.trim()) throw new Error("SDK_NOTIFICATION_DESTINATION_ID_REQUIRED");
179
+ return this.request({ method: "POST", path: "/v1/notification-destinations/" + encodeURIComponent(destinationId) + "/revoke", body: {} }, { idempotencyKey: options.idempotencyKey ?? "sdk:notification-destination-revoke:" + destinationId });
180
+ }
181
+ createOrganizationUnit(input, options = {}) {
182
+ return this.request({ method: "POST", path: "/v1/organization-units", body: input }, options);
183
+ }
184
+ previewOrganizationUnitArchive(unitId) {
185
+ if (!unitId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_ID_REQUIRED");
186
+ return this.request({ method: "POST", path: `/v1/organization-units/${encodeURIComponent(unitId)}/archive-preview`, body: {} });
187
+ }
188
+ archiveOrganizationUnit(unitId, options) {
189
+ if (!unitId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_ID_REQUIRED");
190
+ if (options.confirm !== true) throw new Error("SDK_ORGANIZATION_UNIT_ARCHIVE_CONFIRMATION_REQUIRED");
191
+ return this.request({ method: "POST", path: `/v1/organization-units/${encodeURIComponent(unitId)}/archive`, body: { confirm: true } }, options);
192
+ }
193
+ listOrganizationUnitMembers(unitId) {
194
+ if (!unitId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_ID_REQUIRED");
195
+ return this.request({ method: "GET", path: `/v1/organization-units/${encodeURIComponent(unitId)}/members` });
196
+ }
197
+ setOrganizationUnitMember(unitId, actorId, input, options = {}) {
198
+ if (!unitId.trim() || !actorId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_MEMBER_REQUIRED");
199
+ 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 });
200
+ }
201
+ listProjectOrganizationUnits(projectId) {
202
+ if (!projectId.trim()) throw new Error("SDK_PROJECT_ID_REQUIRED");
203
+ return this.request({ method: "GET", path: `/v1/projects/${encodeURIComponent(projectId)}/organization-units` });
204
+ }
205
+ bindProjectOrganizationUnit(projectId, unitId, input = {}, options = {}) {
206
+ if (!projectId.trim() || !unitId.trim()) throw new Error("SDK_ORGANIZATION_UNIT_BINDING_REQUIRED");
207
+ 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 });
208
+ }
209
+ async request(request, options = {}) {
210
+ const url = new URL(this.baseUrl + request.path);
211
+ for (const [key, value] of Object.entries(request.query ?? {}))
212
+ url.searchParams.set(key, value);
213
+ const headers = {
214
+ accept: "application/json",
215
+ ...this.defaultHeaders
216
+ };
217
+ if (request.body) headers["content-type"] = "application/json";
218
+ 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);
219
+ if (operatorOperation) {
220
+ 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())))
221
+ throw new Error("SDK_OPERATOR_MIXED_AUTHORITY_FORBIDDEN");
222
+ const delegation = (await this.operatorDelegationTokenProvider?.())?.trim();
223
+ if (!delegation) throw new Error("SDK_OPERATOR_DELEGATION_REQUIRED");
224
+ headers["x-vira-delegation"] = delegation;
225
+ } else if (this.apiCredentialProvider) {
226
+ const credential = (await this.apiCredentialProvider())?.trim();
227
+ if (!credential) throw new Error("SDK_API_CREDENTIAL_REQUIRED");
228
+ if (/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(credential))
229
+ throw new Error("SDK_OAUTH_IDENTITY_TOKEN_UNSUPPORTED");
230
+ headers["x-vira-api-key"] = credential;
231
+ } else if (this.apiKey) {
232
+ if (this.apiKey.startsWith("vira_live_")) headers["x-vira-api-key"] = this.apiKey;
233
+ else {
234
+ headers.authorization = `Bearer ${this.apiKey}`;
235
+ headers["x-vira-api-key"] = this.apiKey;
236
+ }
237
+ }
238
+ if (options.idempotencyKey)
239
+ headers["idempotency-key"] = options.idempotencyKey;
240
+ const retryable = request.method === "GET" || Boolean(options.idempotencyKey);
241
+ const attempts = retryable ? this.retries + 1 : 1;
242
+ let lastError;
243
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
244
+ const controller = new AbortController();
245
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
246
+ const started = this.transportObserver ? performance.now() : 0;
247
+ let reported = false;
248
+ try {
249
+ const response = await this.fetcher(url, {
250
+ method: request.method,
251
+ headers,
252
+ body: request.body ? JSON.stringify(request.body) : void 0,
253
+ signal: controller.signal,
254
+ ...operatorOperation ? { redirect: "error", credentials: "omit" } : {}
255
+ });
256
+ const raw = await response.text();
257
+ notifyTransport(this.transportObserver, request.method, response.status, void 0, started, attempt);
258
+ reported = true;
259
+ let body = null;
260
+ try {
261
+ body = raw ? JSON.parse(raw) : null;
262
+ } catch {
263
+ body = raw;
264
+ }
265
+ const requestId = response.headers.get("x-request-id") ?? "";
266
+ if (!response.ok) {
267
+ const error = new ViraApiError(
268
+ `VIRA_API_${response.status}`,
269
+ response.status,
270
+ body,
271
+ requestId
272
+ );
273
+ if ((response.status >= 500 || response.status === 429) && attempt + 1 < attempts) {
274
+ const serverDelay = retryAfterMs(response.headers.get("retry-after"));
275
+ const jitter = Math.floor(Math.random() * 25);
276
+ await wait(Math.max(serverDelay, 25 * 2 ** attempt) + jitter);
277
+ continue;
278
+ }
279
+ if (this.failureMode === "open" && !options.enforcing && response.status >= 500)
280
+ return null;
281
+ throw error;
282
+ }
283
+ return { status: response.status, body, requestId };
284
+ } catch (error) {
285
+ if (!reported) notifyTransport(this.transportObserver, request.method, void 0, error, started, attempt);
286
+ lastError = error;
287
+ if (error instanceof ViraApiError) throw error;
288
+ if (attempt + 1 < attempts) {
289
+ await wait(25 * 2 ** attempt);
290
+ continue;
291
+ }
292
+ if (this.failureMode === "open" && !options.enforcing) return null;
293
+ throw error;
294
+ } finally {
295
+ clearTimeout(timer);
296
+ }
297
+ }
298
+ throw lastError;
299
+ }
300
+ connectSystem(input) {
301
+ const request = buildAISystemRequest(input);
302
+ return this.request(request, {
303
+ idempotencyKey: input.idempotencyKey
304
+ });
305
+ }
306
+ /** Advisory only. Does not approve, reserve or transfer an AI System. */
307
+ getAISystemOwnershipTransferReadiness(systemId) {
308
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
309
+ return this.request({
310
+ method: "GET",
311
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/ownership-transfer/readiness"
312
+ });
313
+ }
314
+ /** Recipient consents to a NEW empty AI System, never transfer of history. */
315
+ acceptAISystemClone(systemId, input) {
316
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
317
+ for (const k of ["expectedOwnerUnitId", "newName", "reason"])
318
+ required(input[k], "SDK_SYSTEM_CLONE_FIELD_REQUIRED");
319
+ return this.request({
320
+ method: "POST",
321
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/accept",
322
+ body: { ...input }
323
+ }, { enforcing: true });
324
+ }
325
+ /** Owner prepares blank successor; provider credentials and traffic remain put. */
326
+ prepareAISystemClone(systemId, input) {
327
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
328
+ for (const k of ["expectedOwnerUnitId", "targetUnitId", "acceptanceAuditId", "reason"])
329
+ required(input[k], "SDK_SYSTEM_CLONE_FIELD_REQUIRED");
330
+ return this.request({
331
+ method: "POST",
332
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/prepare",
333
+ body: { ...input }
334
+ }, { enforcing: true });
335
+ }
336
+ /** Advisory clone preflight; never changes provider routing or ownership. */
337
+ getAISystemCloneCutoverReadiness(systemId, input) {
338
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
339
+ required(input.newAiSystemId, "SDK_SYSTEM_CLONE_FIELD_REQUIRED");
340
+ required(input.preparationAuditId, "SDK_SYSTEM_CLONE_FIELD_REQUIRED");
341
+ return this.request({
342
+ method: "POST",
343
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/readiness",
344
+ body: { newAiSystemId: input.newAiSystemId, preparationAuditId: input.preparationAuditId }
345
+ });
346
+ }
347
+ /** Read target-unit STAGED route version; no access to credentials or traffic. */
348
+ getAISystemCutoverRouteStage(systemId) {
349
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
350
+ return this.request({
351
+ method: "GET",
352
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route"
353
+ });
354
+ }
355
+ /** Link a completed, currently approved F16 Strategy execution to this STAGED receipt. */
356
+ recordAISystemCutoverBehaviorEvidence(systemId, input) {
357
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
358
+ required(input.runtimeReceiptId, "SDK_SYSTEM_CUTOVER_RUNTIME_RECEIPT_REQUIRED");
359
+ required(input.strategyExecutionId, "SDK_SYSTEM_CUTOVER_STRATEGY_EXECUTION_REQUIRED");
360
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
361
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
362
+ return this.request({
363
+ method: "POST",
364
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/behavior",
365
+ body: {
366
+ expectedVersion: input.expectedVersion,
367
+ runtimeReceiptId: input.runtimeReceiptId,
368
+ strategyExecutionId: input.strategyExecutionId
369
+ }
370
+ }, { enforcing: true });
371
+ }
372
+ /** Explicit billable connectivity probe, not model behavior certification. */
373
+ enqueueAISystemCutoverProviderProbe(systemId, input) {
374
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
375
+ required(input.runtimeReceiptId, "SDK_SYSTEM_CUTOVER_RUNTIME_RECEIPT_REQUIRED");
376
+ required(input.reason, "SDK_SYSTEM_CUTOVER_FIELD_REQUIRED");
377
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
378
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
379
+ if (input.acknowledgeBillable !== true)
380
+ throw new Error("SDK_SYSTEM_CUTOVER_PROBE_BILLING_ACK_REQUIRED");
381
+ return this.request({
382
+ method: "POST",
383
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/probe",
384
+ body: {
385
+ expectedVersion: input.expectedVersion,
386
+ runtimeReceiptId: input.runtimeReceiptId,
387
+ reason: input.reason,
388
+ acknowledgeBillable: true
389
+ }
390
+ }, { enforcing: true });
391
+ }
392
+ /** Revoke exactly one STAGED route version; no live traffic is modified. */
393
+ withdrawAISystemCutoverRouteStage(systemId, input) {
394
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
395
+ required(input.reason, "SDK_SYSTEM_CUTOVER_FIELD_REQUIRED");
396
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
397
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
398
+ return this.request({
399
+ method: "POST",
400
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/withdraw",
401
+ body: { expectedVersion: input.expectedVersion, reason: input.reason }
402
+ }, { enforcing: true });
403
+ }
404
+ /** Inspect the committed route generation without exposing provider secrets. */
405
+ getAISystemLiveRoute(systemId) {
406
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
407
+ return this.request(
408
+ {
409
+ method: "GET",
410
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live"
411
+ },
412
+ { enforcing: false }
413
+ );
414
+ }
415
+ /** Independent target-department acceptance; never activates by itself. */
416
+ acceptAISystemLiveActivation(systemId, input) {
417
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
418
+ if (!input || !Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1 || !Number.isSafeInteger(input.expectedGeneration) || input.expectedGeneration < 0)
419
+ throw new Error("SDK_SYSTEM_CUTOVER_LIVE_VERSION_INVALID");
420
+ required(input.runtimeReceiptId, "SDK_RUNTIME_RECEIPT_ID_REQUIRED");
421
+ required(input.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
422
+ return this.request(
423
+ {
424
+ method: "POST",
425
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live/accept",
426
+ body: {
427
+ expectedVersion: input.expectedVersion,
428
+ expectedGeneration: input.expectedGeneration,
429
+ runtimeReceiptId: input.runtimeReceiptId,
430
+ reason: input.reason
431
+ }
432
+ },
433
+ { enforcing: true }
434
+ );
435
+ }
436
+ /** Organization owner commits with a separately issued target approval. */
437
+ activateAISystemLiveRoute(systemId, input) {
438
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
439
+ required(input?.targetUnitId, "SDK_SYSTEM_CUTOVER_TARGET_REQUIRED");
440
+ required(input?.activationConsentAuditId, "SDK_SYSTEM_CUTOVER_ACCEPTANCE_REQUIRED");
441
+ required(input?.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
442
+ return this.request({
443
+ method: "POST",
444
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live/activate",
445
+ body: {
446
+ targetUnitId: input.targetUnitId,
447
+ activationConsentAuditId: input.activationConsentAuditId,
448
+ reason: input.reason
449
+ }
450
+ }, { enforcing: true });
451
+ }
452
+ /** Independent approval to restore SOURCE for one exact ACTIVE generation. */
453
+ acceptAISystemLiveRollback(systemId, input) {
454
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
455
+ if (!input || !Number.isSafeInteger(input.expectedGeneration) || input.expectedGeneration < 1)
456
+ throw new Error("SDK_SYSTEM_CUTOVER_LIVE_VERSION_INVALID");
457
+ required(input.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
458
+ return this.request(
459
+ {
460
+ method: "POST",
461
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live/rollback/accept",
462
+ body: { expectedGeneration: input.expectedGeneration, reason: input.reason }
463
+ },
464
+ { enforcing: true }
465
+ );
466
+ }
467
+ /** Roll back exactly once, guarded by previous-generation and host fences. */
468
+ rollbackAISystemLiveRoute(systemId, input) {
469
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
470
+ required(input?.targetUnitId, "SDK_SYSTEM_CUTOVER_TARGET_REQUIRED");
471
+ required(input?.rollbackConsentAuditId, "SDK_SYSTEM_CUTOVER_ACCEPTANCE_REQUIRED");
472
+ required(input?.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
473
+ return this.request({
474
+ method: "POST",
475
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/live/rollback",
476
+ body: {
477
+ targetUnitId: input.targetUnitId,
478
+ rollbackConsentAuditId: input.rollbackConsentAuditId,
479
+ reason: input.reason
480
+ }
481
+ }, { enforcing: true });
482
+ }
483
+ /**
484
+ * Reconcile an UNCERTAIN host model/tool call only with a server-verified
485
+ * completed effect receipt. No provider retry or AI Credit mutation.
486
+ */
487
+ reconcileAISystemHostInvocation(systemId, input) {
488
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
489
+ required(input?.invocationId, "SDK_F4_HOST_INVOCATION_REQUIRED");
490
+ required(input?.resultReceiptId, "SDK_F4_HOST_RESULT_RECEIPT_REQUIRED");
491
+ required(input?.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
492
+ return this.request(
493
+ {
494
+ method: "POST",
495
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/reconcile/host",
496
+ body: {
497
+ invocationId: input.invocationId,
498
+ resultReceiptId: input.resultReceiptId,
499
+ reason: input.reason
500
+ }
501
+ },
502
+ { enforcing: true }
503
+ );
504
+ }
505
+ /**
506
+ * Release only an uninvoked, failed F4 provider probe's RESERVED AI Credits.
507
+ * No unknown-outcome refund, duplicate model call, or automatic settlement.
508
+ */
509
+ releaseUninvokedAISystemProbeCredit(systemId, input) {
510
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
511
+ required(input?.probeJobId, "SDK_F4_PROBE_JOB_REQUIRED");
512
+ required(input?.reservationId, "SDK_F4_RESERVATION_REQUIRED");
513
+ required(input?.reason, "SDK_SYSTEM_CUTOVER_REASON_REQUIRED");
514
+ return this.request({
515
+ method: "POST",
516
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/reconcile/probe-release",
517
+ body: {
518
+ probeJobId: input.probeJobId,
519
+ reservationId: input.reservationId,
520
+ reason: input.reason
521
+ }
522
+ }, { enforcing: true });
523
+ }
524
+ /**
525
+ * Read-only bounded blocker identities for manual departmental reconciliation.
526
+ * This does not retry providers, release credits or approve ACTIVE routing.
527
+ */
528
+ inspectAISystemCutoverDrainCases(systemId, input) {
529
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
530
+ if (!input || !Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
531
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
532
+ return this.request({
533
+ method: "POST",
534
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/drain/cases",
535
+ body: { expectedVersion: input.expectedVersion }
536
+ }, { enforcing: false });
537
+ }
538
+ /**
539
+ * Operator-only readback of queued/in-flight F4 jobs, unresolved provider
540
+ * invocations and outstanding departmental credit holds across versions.
541
+ * Never authorizes ACTIVE traffic or triggers a model call.
542
+ */
543
+ inspectAISystemCutoverDrain(systemId, input) {
544
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
545
+ if (!input || !Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
546
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
547
+ return this.request({
548
+ method: "POST",
549
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/drain",
550
+ body: { expectedVersion: input.expectedVersion }
551
+ }, { enforcing: false });
552
+ }
553
+ /** Read proof of a runtime policy admission; not provider success or cutover. */
554
+ inspectAISystemCutoverAdmission(systemId, input) {
555
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
556
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)
557
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
558
+ const receiptId = input.runtimeReceiptId;
559
+ if (receiptId !== void 0 && (typeof receiptId !== "string" || !receiptId.trim() || receiptId !== receiptId.trim() || receiptId.length > 500))
560
+ throw new Error("SDK_RUNTIME_RECEIPT_ID_REQUIRED");
561
+ return this.request({
562
+ method: "POST",
563
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/admission",
564
+ body: {
565
+ expectedVersion: input.expectedVersion,
566
+ ...receiptId === void 0 ? {} : { runtimeReceiptId: receiptId }
567
+ }
568
+ }, { enforcing: false });
569
+ }
570
+ /** Target admin consents only to a STAGED route, not traffic switching. */
571
+ acceptAISystemCutoverRoute(systemId, input) {
572
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
573
+ for (const k of ["successorAiSystemId", "successorConnectionId", "preparationAuditId", "reason"])
574
+ required(input[k], "SDK_SYSTEM_CUTOVER_FIELD_REQUIRED");
575
+ if (input.expectedVersion !== null && (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1))
576
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
577
+ return this.request({
578
+ method: "POST",
579
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/accept",
580
+ body: { ...input }
581
+ }, { enforcing: true });
582
+ }
583
+ /** Independent organization owner CAS-stages an inert route record. */
584
+ stageAISystemCutoverRoute(systemId, input) {
585
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
586
+ for (const k of [
587
+ "successorAiSystemId",
588
+ "successorConnectionId",
589
+ "preparationAuditId",
590
+ "routeAcceptanceAuditId",
591
+ "reason"
592
+ ])
593
+ required(input[k], "SDK_SYSTEM_CUTOVER_FIELD_REQUIRED");
594
+ if (input.expectedVersion !== null && (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1))
595
+ throw new Error("SDK_SYSTEM_CUTOVER_EXPECTED_VERSION_INVALID");
596
+ return this.request({
597
+ method: "POST",
598
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/clone-cutover/route/stage",
599
+ body: { ...input }
600
+ }, { enforcing: true });
601
+ }
602
+ /** Target department admin signs a 10-minute, scope-locked acceptance. */
603
+ acceptAISystemOwnershipTransfer(systemId, input) {
604
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
605
+ required(input.expectedOwnerUnitId, "SDK_SYSTEM_TRANSFER_EXPECTED_OWNER_REQUIRED");
606
+ required(input.reason, "SDK_SYSTEM_TRANSFER_REASON_REQUIRED");
607
+ return this.request(
608
+ {
609
+ method: "POST",
610
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/ownership-transfer/accept",
611
+ body: { ...input }
612
+ },
613
+ { enforcing: true }
614
+ );
615
+ }
616
+ /** Existing organization owner finalizes an independently accepted transfer. */
617
+ commitAISystemOwnershipTransfer(systemId, input) {
618
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
619
+ for (const key of ["expectedOwnerUnitId", "targetUnitId", "acceptanceAuditId", "reason"])
620
+ required(input[key], "SDK_SYSTEM_TRANSFER_FIELD_REQUIRED");
621
+ return this.request(
622
+ {
623
+ method: "POST",
624
+ path: "/v1/ai-systems/" + encodeURIComponent(systemId) + "/ownership-transfer/commit",
625
+ body: { ...input }
626
+ },
627
+ { enforcing: true }
628
+ );
629
+ }
630
+ listAISystems(options = {}) {
631
+ return this.request({ method: "GET", path: "/v1/ai-systems", query: listQuery(options) });
632
+ }
633
+ async deleteAISystem(systemId, options = {}) {
634
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
635
+ const path = `/v1/ai-systems/${encodeURIComponent(systemId)}`, body = { confirm: options.confirm === true };
636
+ return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:ai-system:${systemId}`, { path, body }) });
637
+ }
638
+ async deleteAISystemCascade(systemId, options = {}) {
639
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
640
+ const path = `/v1/ai-systems/${encodeURIComponent(systemId)}/cleanup`, body = { confirm: options.confirm === true, deleteObservations: options.deleteObservations === true };
641
+ return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:ai-system-cascade:${systemId}`, { path, body }) });
642
+ }
643
+ getAISystem(systemId) {
644
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
645
+ return this.request({ method: "GET", path: `/v1/ai-systems/${encodeURIComponent(systemId)}` });
646
+ }
647
+ connectAdapter(systemId, input) {
648
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
649
+ const body = {
650
+ ...input,
651
+ capabilities: [...input.capabilities ?? []]
652
+ };
653
+ delete body.idempotencyKey;
654
+ return this.request(
655
+ {
656
+ method: "POST",
657
+ path: `/v1/ai-systems/${encodeURIComponent(systemId)}/connections`,
658
+ body
659
+ },
660
+ { idempotencyKey: input.idempotencyKey }
661
+ );
662
+ }
663
+ async connectOnce(input) {
664
+ let systemResult;
665
+ try {
666
+ systemResult = await this.connectSystem(input);
667
+ } catch (error) {
668
+ if (!(input.reuseExistingConnectionOnConflict !== false && error instanceof ViraApiError && error.status === 409)) throw error;
669
+ const listed = await this.listAISystems();
670
+ if (!listed) throw error;
671
+ const systems = Array.isArray(listed?.body?.systems) ? listed.body.systems : [];
672
+ const reused = systems.find(
673
+ (system) => String(system.name ?? "") === input.name && String(system.systemType ?? "") === input.systemType && String(system.organizationId ?? "") === input.organizationId && String(system.projectId ?? "") === input.projectId && String(system.environmentId ?? "") === input.environmentId
674
+ );
675
+ if (!reused) throw error;
676
+ systemResult = { status: listed.status, requestId: listed.requestId, body: { system: reused } };
677
+ }
678
+ if (!systemResult) return null;
679
+ const systemId = String(systemResult.body.system.id ?? "");
680
+ required(systemId, "SDK_SYSTEM_ID_MISSING");
681
+ let connectionResult;
682
+ try {
683
+ connectionResult = await this.connectAdapter(systemId, {
684
+ id: input.id,
685
+ adapterType: input.adapterType,
686
+ adapterVersion: input.adapterVersion,
687
+ capabilities: input.capabilities,
688
+ config: input.config,
689
+ idempotencyKey: input.idempotencyKey
690
+ });
691
+ } catch (error) {
692
+ if (!(input.reuseExistingConnectionOnConflict !== false && error instanceof ViraApiError && error.status === 409)) throw error;
693
+ const listed = await this.listSystemConnections(systemId);
694
+ const connections = Array.isArray(listed?.body?.connections) ? listed.body.connections : [];
695
+ const requested = new Set((input.capabilities ?? []).map(String));
696
+ const reused = connections.find((connection) => String(connection.adapterType ?? "") === input.adapterType && requested.size <= new Set(Array.isArray(connection.capabilities) ? connection.capabilities.map(String) : []).size && [...requested].every((capability) => (Array.isArray(connection.capabilities) ? connection.capabilities.map(String) : []).includes(capability)));
697
+ if (!reused) throw error;
698
+ const verified = await this.getConnection(String(reused.id ?? ""));
699
+ const verifiedConnection = verified?.body?.connection && typeof verified.body.connection === "object" ? verified.body.connection : null;
700
+ if (!verifiedConnection || String(verifiedConnection.adapterType ?? "") !== input.adapterType) throw error;
701
+ const verifiedCapabilities = Array.isArray(verifiedConnection.capabilities) ? verifiedConnection.capabilities.map(String) : [];
702
+ if (![...requested].every((capability) => verifiedCapabilities.includes(capability))) throw error;
703
+ const fromVersion = String(verifiedConnection.adapterVersion ?? "");
704
+ const transition = fromVersion === input.adapterVersion ? "UNCHANGED" : "REUSE_COMPATIBLE";
705
+ 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 } } } };
706
+ }
707
+ if (!connectionResult) return null;
708
+ const connectedId = String(connectionResult.body.connection.id ?? "").trim();
709
+ if (connectedId) this.boundConnectionId = connectedId;
710
+ return {
711
+ status: connectionResult.status,
712
+ requestId: connectionResult.requestId,
713
+ body: {
714
+ system: systemResult.body.system,
715
+ connection: connectionResult.body.connection,
716
+ handshake: connectionResult.body.handshake
717
+ }
718
+ };
719
+ }
720
+ /** Canonical verb-noun name; connectOnce remains for source compatibility. */
721
+ connectAiSystem(input) {
722
+ return this.connectOnce(input);
723
+ }
724
+ observe(event, options = {}) {
725
+ buildObservationRequest(event);
726
+ return (async () => {
727
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : void 0;
728
+ const source = event.attributes && typeof event.attributes === "object" ? String(event.attributes.source ?? "") : "";
729
+ const safeEvent = source === "opencode.context" && payload && typeof payload.text === "string" ? { ...event, payload: { ...payload, text: void 0, textDigest: (await contentIdempotencyKey("observation:text", payload.text)).split(":").pop(), minimization: { rawTextSent: false, digestAlgorithm: "sha256" } } } : event;
730
+ const response = await this.request(buildObservationRequest(safeEvent), {
731
+ idempotencyKey: options.idempotencyKey ?? event.eventId
732
+ });
733
+ if (event.eventType === "conversation.output") {
734
+ await this.request(buildObservationRequest({ ...safeEvent, eventType: "model.response", eventId: `${event.eventId}:model.response`, payload: { ...safeEvent.payload ?? {}, status: "completed" } }), { idempotencyKey: `${options.idempotencyKey ?? event.eventId}:model.response` });
735
+ }
736
+ return response;
737
+ })();
738
+ }
739
+ /** Explicit opt-in upload through the existing scoped observation authority.
740
+ * Do not call automatically from a transport observer (recursive reporting).
741
+ * May be subject to observation quotas and negotiated latency capability.
742
+ */
743
+ reportTransportLatency(input, options = {}) {
744
+ if (!Number.isFinite(input.durationMs) || input.durationMs < 0 || input.durationMs > 36e5) throw Error("SDK_TRANSPORT_LATENCY_INVALID");
745
+ return this.observe({
746
+ organizationId: input.organizationId,
747
+ projectId: input.projectId,
748
+ environmentId: input.environmentId,
749
+ ...input.organizationUnitId ? { organizationUnitId: input.organizationUnitId } : {},
750
+ eventId: input.eventId,
751
+ eventType: "latency",
752
+ aiSystemId: input.aiSystemId,
753
+ connectionId: input.connectionId,
754
+ payload: { latencyMs: input.durationMs }
755
+ }, options);
756
+ }
757
+ listObservations(input = {}) {
758
+ const query = new URLSearchParams();
759
+ if (input.limit !== void 0) query.set("limit", String(input.limit));
760
+ if (input.cursor) query.set("cursor", input.cursor);
761
+ return this.request({ method: "GET", path: `/v1/observations${query.size ? `?${query.toString()}` : ""}` });
762
+ }
763
+ getObservation(eventId) {
764
+ required(eventId, "SDK_OBSERVATION_ID_REQUIRED");
765
+ return this.request({ method: "GET", path: `/v1/observations/${encodeURIComponent(eventId)}` });
766
+ }
767
+ /** Admin-only: supersede one admitted event with another in the same unit. */
768
+ async supersedeObservation(input, options = {}) {
769
+ required(input.tombstoneEventId, "SDK_OBSERVATION_TOMBSTONE_REQUIRED");
770
+ required(input.targetEventId, "SDK_OBSERVATION_TARGET_REQUIRED");
771
+ required(input.targetEventVersion, "SDK_OBSERVATION_VERSION_REQUIRED");
772
+ if (input.reason !== void 0) {
773
+ required(input.reason, "SDK_OBSERVATION_REASON_REQUIRED");
774
+ if (input.reason !== input.reason.trim() || input.reason.length > 512)
775
+ throw new Error("SDK_OBSERVATION_REASON_REQUIRED");
776
+ }
777
+ const body = { ...input, confirm: true };
778
+ return this.request({
779
+ method: "POST",
780
+ path: "/v1/observations/supersessions",
781
+ body
782
+ }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(
783
+ "sdk:observation:supersession",
784
+ body
785
+ ) });
786
+ }
787
+ /** Admin-only: create or replay a department-scoped historical backfill. */
788
+ async beginObservationBackfill(input, options = {}) {
789
+ required(input.id, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
790
+ required(input.windowStart, "SDK_OBSERVATION_BACKFILL_WINDOW_REQUIRED");
791
+ required(input.windowEnd, "SDK_OBSERVATION_BACKFILL_WINDOW_REQUIRED");
792
+ if (input.checkpointRequired !== void 0 && typeof input.checkpointRequired !== "boolean")
793
+ throw new Error("SDK_OBSERVATION_BACKFILL_CHECKPOINT_POLICY_INVALID");
794
+ if (input.reason !== void 0) {
795
+ required(input.reason, "SDK_OBSERVATION_REASON_REQUIRED");
796
+ if (input.reason !== input.reason.trim() || input.reason.length > 512)
797
+ throw new Error("SDK_OBSERVATION_REASON_REQUIRED");
798
+ }
799
+ const body = { ...input, confirm: true };
800
+ return this.request({
801
+ method: "POST",
802
+ path: "/v1/observations/backfills",
803
+ body
804
+ }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(
805
+ "sdk:observation:backfill:begin",
806
+ body
807
+ ) });
808
+ }
809
+ /** Admin-only: finalize processed events within the department backfill window. */
810
+ async completeObservationBackfill(id, options = {}) {
811
+ required(id, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
812
+ if (options.reason !== void 0) {
813
+ required(options.reason, "SDK_OBSERVATION_REASON_REQUIRED");
814
+ if (options.reason !== options.reason.trim() || options.reason.length > 512)
815
+ throw new Error("SDK_OBSERVATION_REASON_REQUIRED");
816
+ }
817
+ const body = { confirm: true, ...options.reason ? { reason: options.reason } : {} };
818
+ return this.request({
819
+ method: "POST",
820
+ path: `/v1/observations/backfills/${encodeURIComponent(id)}/complete`,
821
+ body
822
+ }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(
823
+ `sdk:observation:backfill:complete:${id}`,
824
+ body
825
+ ) });
826
+ }
827
+ /** Read-only advisory status; finalization rechecks under PostgreSQL locks. */
828
+ getObservationBackfillReadiness(id) {
829
+ required(id, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
830
+ return this.request({
831
+ method: "GET",
832
+ path: `/v1/observations/backfills/${encodeURIComponent(id)}/readiness`
833
+ });
834
+ }
835
+ /** Read-only: scoped lineage and checkpoint summary, without raw cursor. */
836
+ getObservationBackfillHistory(id) {
837
+ required(id, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
838
+ return this.request({
839
+ method: "GET",
840
+ path: `/v1/observations/backfills/${encodeURIComponent(id)}/history`
841
+ });
842
+ }
843
+ /** Admin-only: keep completed history and activate a reviewed successor. */
844
+ async reviseObservationBackfill(id, input, options = {}) {
845
+ required(id, "SDK_OBSERVATION_BACKFILL_ID_REQUIRED");
846
+ required(input.successorId, "SDK_OBSERVATION_BACKFILL_SUCCESSOR_REQUIRED");
847
+ required(input.reason, "SDK_OBSERVATION_REASON_REQUIRED");
848
+ if (id === input.successorId || [id, input.successorId, input.reason].some((value) => value !== value.trim() || value.length > 512))
849
+ throw new Error("SDK_OBSERVATION_BACKFILL_REVISION_INVALID");
850
+ const body = { confirm: true, successorId: input.successorId, reason: input.reason };
851
+ return this.request({
852
+ method: "POST",
853
+ path: `/v1/observations/backfills/${encodeURIComponent(id)}/revise`,
854
+ body
855
+ }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(
856
+ `sdk:observation:backfill:revise:${id}`,
857
+ body
858
+ ) });
859
+ }
860
+ /** Read-only. The SDK cannot manufacture a trusted runtime evidence receipt. */
861
+ listTrajectoryRuntimeEvidence(trajectoryKey) {
862
+ required(trajectoryKey, "SDK_OBSERVATION_TRAJECTORY_REQUIRED");
863
+ return this.request({
864
+ method: "GET",
865
+ path: `/v1/observations/trajectories/${encodeURIComponent(trajectoryKey)}/runtime-evidence`
866
+ });
867
+ }
868
+ trace(event, options = {}) {
869
+ return this.observe({ ...event, eventType: "model.response" }, options);
870
+ }
871
+ searchRuntimeTraces(query = {}) {
872
+ if (query.limit !== void 0 && (!Number.isInteger(query.limit) || query.limit < 1 || query.limit > 100)) throw new Error("SDK_RUNTIME_TRACE_LIMIT_INVALID");
873
+ const params = new URLSearchParams();
874
+ for (const [key, value] of Object.entries(query)) if (value !== void 0) params.set(key, String(value));
875
+ return this.request({ method: "GET", path: `/v1/runtime/traces/search${params.size ? `?${params.toString()}` : ""}` });
876
+ }
877
+ listOptimizationTargets(input) {
878
+ for (const value of [input.aiSystemId, input.connectionId]) required(value, "SDK_OPTIMIZATION_TARGET_REQUIRED");
879
+ return this.request({ method: "POST", path: "/v1/optimization/target-options", body: input }, { enforcing: true });
880
+ }
881
+ previewOptimizationTarget(input) {
882
+ for (const value of [input.aiSystemId, input.connectionId, input.canonicalRevisionId, input.sourceReleaseId]) required(value, "SDK_OPTIMIZATION_TARGET_REQUIRED");
883
+ return this.request({ method: "POST", path: "/v1/optimization/target-preview", body: input }, { enforcing: true });
884
+ }
885
+ startOptimization(input, options = {}) {
886
+ const key = typeof input.idempotencyKey === "string" ? input.idempotencyKey.trim() : "";
887
+ if (!key) throw new Error("SDK_IDEMPOTENCY_KEY_REQUIRED");
888
+ if (!input.canonicalDigest || !input.policyDigest || !input.baseProjection && !input.strategyOptimization && !input.canonicalRevisionId) throw new Error("SDK_OPTIMIZATION_FIELDS_REQUIRED");
889
+ return this.request({ method: "POST", path: "/v1/optimization/execute", body: input }, { idempotencyKey: options.idempotencyKey ?? key, enforcing: true });
890
+ }
891
+ resumeOptimization(input, options = {}) {
892
+ return this.startOptimization({ ...input, resume: true }, options);
893
+ }
894
+ promoteOptimizationRun(runId, evaluationId, expectedVersion, options = {}) {
895
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
896
+ required(evaluationId, "SDK_OPTIMIZATION_EVALUATION_ID_REQUIRED");
897
+ if (expectedVersion !== null && (!Number.isSafeInteger(expectedVersion) || expectedVersion < 1)) throw new Error("SDK_OPTIMIZATION_POINTER_VERSION_INVALID");
898
+ 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 });
899
+ }
900
+ getOptimizationRun(runId) {
901
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
902
+ return this.request({ method: "GET", path: `/v1/optimization/runs/${encodeURIComponent(runId)}` });
903
+ }
904
+ reviewOptimizationRun(runId) {
905
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
906
+ return this.request({ method: "GET", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/review` });
907
+ }
908
+ reattachOptimizationRun(runId, options = {}) {
909
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
910
+ return this.request({ method: "POST", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/reattach`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:optimization-reattach:${runId}`, enforcing: true });
911
+ }
912
+ cancelOptimizationRun(runId, options = {}) {
913
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
914
+ return this.request({ method: "POST", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/cancel`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:optimization-cancel:${runId}`, enforcing: true });
915
+ }
916
+ outcome(event, options = {}) {
917
+ return this.observe({ ...event, eventType: "business.outcome" }, options);
918
+ }
919
+ feedback(event, options = {}) {
920
+ return this.observe({ ...event, eventType: "feedback.user" }, options);
921
+ }
922
+ recordBusinessOutcome(event, options = {}) {
923
+ return this.outcome(event, options);
924
+ }
925
+ recordUserFeedback(event, options = {}) {
926
+ return this.feedback(event, options);
927
+ }
928
+ observeBatch(events, options = {}) {
929
+ if (!Array.isArray(events) || events.length < 1 || events.length > 100)
930
+ throw new Error("SDK_OBSERVATION_BATCH_INVALID");
931
+ if (events.some((event) => !event.organizationId?.trim() || !event.projectId?.trim() || !event.environmentId?.trim()))
932
+ throw new Error("SDK_OBSERVATION_SCOPE_REQUIRED");
933
+ return this.request(
934
+ {
935
+ method: "POST",
936
+ path: "/v1/observations/batch",
937
+ body: { events: [...events] }
938
+ },
939
+ { idempotencyKey: options.idempotencyKey }
940
+ );
941
+ }
942
+ observeSdk(delivery, options = {}) {
943
+ return this.request(
944
+ { method: "POST", path: "/v1/observations/sdk", body: delivery },
945
+ { idempotencyKey: options.idempotencyKey }
946
+ );
947
+ }
948
+ discover(options = {}) {
949
+ if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new Error("SDK_DISCOVERY_LIMIT_INVALID");
950
+ const normalized = { ...options, ...options.limit !== void 0 ? { limit: Math.min(options.limit, 200) } : {} };
951
+ return this.request({
952
+ method: "GET",
953
+ path: "/v1/discovery/candidates",
954
+ query: { ...options.reviewState ? { reviewState: options.reviewState } : {}, ...listQuery(normalized) }
955
+ });
956
+ }
957
+ async reviewDiscoveryCandidate(kind, key, input, options = {}) {
958
+ required(kind, "SDK_DISCOVERY_CANDIDATE_KIND_REQUIRED");
959
+ required(key, "SDK_DISCOVERY_CANDIDATE_KEY_REQUIRED");
960
+ required(typeof input?.decision === "string" ? input.decision : "", "SDK_DISCOVERY_CANDIDATE_DECISION_REQUIRED");
961
+ const path = `/v1/discovery/candidates/${encodeURIComponent(kind)}/${encodeURIComponent(key)}/review`;
962
+ if (input.patch !== void 0 && input.payload !== void 0) throw new Error("SDK_DISCOVERY_REVIEW_PATCH_AMBIGUOUS");
963
+ const { payload, patch, ...rest } = input;
964
+ const reviewPatch = patch !== void 0 ? patch : payload;
965
+ if (reviewPatch !== void 0 && (!reviewPatch || typeof reviewPatch !== "object" || Array.isArray(reviewPatch))) throw new Error("SDK_DISCOVERY_REVIEW_PATCH_INVALID");
966
+ const body = { ...rest, ...reviewPatch === void 0 ? {} : { patch: reviewPatch } };
967
+ const invocationId = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`;
968
+ return this.request({ method: "POST", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:discovery-review:${kind}:${key}`, { invocationId, body }), enforcing: true });
969
+ }
970
+ /** Explicit canonical publication; API approval and scope checks still apply. */
971
+ publishDiscoveryCandidate(kind, key, input = {}, options = {}) {
972
+ required(kind, "SDK_DISCOVERY_CANDIDATE_KIND_REQUIRED");
973
+ required(key, "SDK_DISCOVERY_CANDIDATE_KEY_REQUIRED");
974
+ 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 });
975
+ }
976
+ async createSignalDiscoveryProposal(input, options = {}) {
977
+ return this.request({ method: "POST", path: "/v1/signals/discovery-proposals", body: input }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey("sdk:signal-discovery-proposal", input) });
978
+ }
979
+ async reviewSignalDiscoveryProposal(proposalId, decision, options = {}) {
980
+ required(proposalId, "SDK_SIGNAL_PROPOSAL_ID_REQUIRED");
981
+ const path = `/v1/signals/discovery-proposals/${encodeURIComponent(proposalId)}/review`, body = { decision };
982
+ return this.request({ method: "POST", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`signal-review:${proposalId}`, body) });
983
+ }
984
+ async materializeSignalDiscovery(proposalId, input = {}, options = {}) {
985
+ required(proposalId, "SDK_SIGNAL_PROPOSAL_ID_REQUIRED");
986
+ const path = `/v1/signals/discovery-proposals/${encodeURIComponent(proposalId)}/materialize`;
987
+ return this.request({ method: "POST", path, body: input }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`signal-materialize:${proposalId}`, input) });
988
+ }
989
+ async createSignalMapping(input, options = {}) {
990
+ return this.request({ method: "POST", path: "/v1/signals/mappings", body: input }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey("sdk:signal-mapping", input) });
991
+ }
992
+ getSignalMapping(mappingId) {
993
+ required(mappingId, "SDK_SIGNAL_MAPPING_ID_REQUIRED");
994
+ return this.request({ method: "GET", path: `/v1/signals/mappings/${encodeURIComponent(mappingId)}` });
995
+ }
996
+ async reviewSignalMapping(mappingId, input = {}, options = {}) {
997
+ required(mappingId, "SDK_SIGNAL_MAPPING_ID_REQUIRED");
998
+ const path = `/v1/signals/mappings/${encodeURIComponent(mappingId)}/review`;
999
+ return this.request({ method: "POST", path, body: input }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`signal-mapping-review:${mappingId}`, input) });
1000
+ }
1001
+ connectionHealth(connectionId) {
1002
+ required(connectionId, "SDK_CONNECTION_ID_REQUIRED");
1003
+ return this.request({
1004
+ method: "GET",
1005
+ path: `/v1/connections/${encodeURIComponent(connectionId)}/health`
1006
+ });
1007
+ }
1008
+ getConnection(connectionId) {
1009
+ required(connectionId, "SDK_CONNECTION_ID_REQUIRED");
1010
+ return this.request({
1011
+ method: "GET",
1012
+ path: `/v1/connections/${encodeURIComponent(connectionId)}`
1013
+ });
1014
+ }
1015
+ listSystemConnections(systemId, options = {}) {
1016
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
1017
+ return this.request({
1018
+ method: "GET",
1019
+ path: `/v1/ai-systems/${encodeURIComponent(systemId)}/connections`,
1020
+ query: listQuery(options)
1021
+ });
1022
+ }
1023
+ inventory(systemId) {
1024
+ required(systemId, "SDK_SYSTEM_ID_REQUIRED");
1025
+ return this.request({
1026
+ method: "GET",
1027
+ path: `/v1/ai-systems/${encodeURIComponent(systemId)}/inventory`
1028
+ });
1029
+ }
1030
+ listPacks(options = {}) {
1031
+ return this.request({
1032
+ method: "GET",
1033
+ path: "/v1/packs",
1034
+ query: listQuery(options)
1035
+ });
1036
+ }
1037
+ getPack(packId) {
1038
+ required(packId, "SDK_PACK_ID_REQUIRED");
1039
+ return this.request({ method: "GET", path: `/v1/packs/${encodeURIComponent(packId)}` });
1040
+ }
1041
+ async deletePack(packId, options = {}) {
1042
+ required(packId, "SDK_PACK_ID_REQUIRED");
1043
+ const path = `/v1/packs/${encodeURIComponent(packId)}`;
1044
+ const body = { confirm: options.confirm === true };
1045
+ return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:pack:${packId}`, { path, body }) });
1046
+ }
1047
+ async importPack(input) {
1048
+ if (!input?.manifest && !input?.archiveBase64)
1049
+ throw new Error("SDK_PACK_MANIFEST_OR_ARCHIVE_REQUIRED");
1050
+ if (input.archiveBase64 && !input.fileName)
1051
+ throw new Error("SDK_PACK_FILE_NAME_REQUIRED");
1052
+ const body = {
1053
+ ...input.manifest ? { manifest: input.manifest } : {},
1054
+ objects: input.objects ?? {},
1055
+ ...input.archiveBase64 ? { archiveBase64: input.archiveBase64, fileName: input.fileName } : {}
1056
+ };
1057
+ return this.request(
1058
+ {
1059
+ method: "POST",
1060
+ path: "/v1/packs/import",
1061
+ body
1062
+ },
1063
+ { idempotencyKey: input.idempotencyKey ?? await contentIdempotencyKey("sdk:pack:import", body) }
1064
+ );
1065
+ }
1066
+ async installPack(packId, variables = {}) {
1067
+ required(packId, "SDK_PACK_ID_REQUIRED");
1068
+ const path = `/v1/packs/${encodeURIComponent(packId)}/install`;
1069
+ const body = { variables };
1070
+ return this.request(
1071
+ { method: "POST", path, body },
1072
+ { idempotencyKey: await contentIdempotencyKey(`sdk:pack:install:${packId}`, body) }
1073
+ );
1074
+ }
1075
+ async revokeSignalMapping(mappingId, expectedMappingDigest) {
1076
+ required(mappingId, "SDK_SIGNAL_MAPPING_ID_REQUIRED");
1077
+ if (!/^[a-f0-9]{64}$/.test(expectedMappingDigest)) throw Error("SDK_SIGNAL_MAPPING_DIGEST_INVALID");
1078
+ const body = { expectedMappingDigest };
1079
+ return this.request({ method: "POST", path: `/v1/signals/mappings/${encodeURIComponent(mappingId)}/revoke`, body }, { idempotencyKey: await contentIdempotencyKey(`sdk:signal-mapping:revoke:${mappingId}`, body), enforcing: true });
1080
+ }
1081
+ getPackSignalReadiness(packId) {
1082
+ required(packId, "SDK_PACK_ID_REQUIRED");
1083
+ return this.request({ method: "GET", path: `/v1/packs/${encodeURIComponent(packId)}/doctor` });
1084
+ }
1085
+ async bindPackSignalMappings(packId, input) {
1086
+ required(packId, "SDK_PACK_ID_REQUIRED");
1087
+ required(input.aiSystemId, "SDK_AI_SYSTEM_REQUIRED");
1088
+ required(input.connectionId, "SDK_CONNECTION_REQUIRED");
1089
+ const body = { aiSystemId: input.aiSystemId, connectionId: input.connectionId, approve: input.approve === true };
1090
+ return this.request({ method: "POST", path: `/v1/packs/${encodeURIComponent(packId)}/signal-mappings`, body }, { idempotencyKey: await contentIdempotencyKey(`sdk:pack:signal-mappings:${packId}`, body) });
1091
+ }
1092
+ async diagnosePack(packId, input = {}) {
1093
+ required(packId, "SDK_PACK_ID_REQUIRED");
1094
+ const body = { runtimeBindings: [...input.runtimeBindings ?? []], knownVerifiers: [...input.knownVerifiers ?? []] };
1095
+ return this.request({ method: "POST", path: `/v1/packs/${encodeURIComponent(packId)}/doctor`, body }, { idempotencyKey: await contentIdempotencyKey(`sdk:pack:doctor:${packId}`, body) });
1096
+ }
1097
+ async evaluatePack(packId, input) {
1098
+ required(packId, "SDK_PACK_ID_REQUIRED");
1099
+ required(input?.evaluationId, "SDK_EVALUATION_ID_REQUIRED");
1100
+ const path = `/v1/packs/${encodeURIComponent(packId)}/evaluate`;
1101
+ const body = { evaluationId: input.evaluationId };
1102
+ return this.request({ method: "POST", path, body }, { idempotencyKey: await contentIdempotencyKey(`sdk:pack:evaluate:${packId}`, body) });
1103
+ }
1104
+ async approvePack(packId, options = {}) {
1105
+ required(packId, "SDK_PACK_ID_REQUIRED");
1106
+ const body = options.manualApproval ? { manualApproval: true, reason: required(options.reason ?? "", "SDK_MANUAL_PACK_APPROVAL_REASON_REQUIRED") } : {};
1107
+ return this.request(
1108
+ {
1109
+ method: "POST",
1110
+ path: `/v1/packs/${encodeURIComponent(packId)}/approve`,
1111
+ body
1112
+ },
1113
+ { idempotencyKey: await contentIdempotencyKey(`sdk:pack:approve:${packId}`, body) }
1114
+ );
1115
+ }
1116
+ async releasePack(packId) {
1117
+ required(packId, "SDK_PACK_ID_REQUIRED");
1118
+ return this.request(
1119
+ {
1120
+ method: "POST",
1121
+ path: `/v1/packs/${encodeURIComponent(packId)}/release`,
1122
+ body: {}
1123
+ },
1124
+ { idempotencyKey: await contentIdempotencyKey(`sdk:pack:release:${packId}`, {}) }
1125
+ );
1126
+ }
1127
+ async previewPackUpgrade(packId, incoming) {
1128
+ required(packId, "SDK_PACK_ID_REQUIRED");
1129
+ if (!incoming || typeof incoming !== "object")
1130
+ throw new Error("SDK_PACK_UPGRADE_INPUT_REQUIRED");
1131
+ return this.request(
1132
+ {
1133
+ method: "POST",
1134
+ path: `/v1/packs/${encodeURIComponent(packId)}/upgrade-preview`,
1135
+ body: { incoming }
1136
+ },
1137
+ { idempotencyKey: await contentIdempotencyKey(`sdk:pack:upgrade-preview:${packId}`, { incoming }) }
1138
+ );
1139
+ }
1140
+ executeRuntime(input) {
1141
+ return this.request(
1142
+ {
1143
+ method: "POST",
1144
+ path: "/v1/runtime/execute",
1145
+ body: buildRuntimeRequest(
1146
+ input,
1147
+ { includeAIIdentity: true, allowStagedValidation: true }
1148
+ )
1149
+ },
1150
+ { idempotencyKey: input.idempotencyKey, enforcing: true }
1151
+ );
1152
+ }
1153
+ resolveRuntime(input) {
1154
+ if (!input.behaviorPoint && !input.executionBoundary && !input.semanticContext)
1155
+ throw new Error("SDK_RUNTIME_ROUTE_REQUIRED");
1156
+ const idempotencyKey = input.idempotencyKey ?? `sdk:resolve:${globalThis.crypto.randomUUID()}`;
1157
+ if (!idempotencyKey.trim() || idempotencyKey !== idempotencyKey.trim())
1158
+ throw new Error("SDK_IDEMPOTENCY_KEY_INVALID");
1159
+ return this.request(
1160
+ {
1161
+ method: "POST",
1162
+ path: "/v1/runtime/resolve",
1163
+ body: {
1164
+ ...input.aiSystemId ? { aiSystemId: input.aiSystemId } : {},
1165
+ ...input.provider !== void 0 ? { provider: input.provider } : {},
1166
+ ...input.model !== void 0 ? { model: input.model } : {},
1167
+ ...input.protocol !== void 0 ? { protocol: input.protocol } : {},
1168
+ ...input.behaviorPoint ? { behaviorPoint: input.behaviorPoint } : {},
1169
+ ...input.executionBoundary ? { executionBoundary: input.executionBoundary } : {},
1170
+ ...input.semanticContext ? { semanticContext: input.semanticContext } : {},
1171
+ ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {}
1172
+ }
1173
+ },
1174
+ {
1175
+ // One key per logical invocation: transport retries reuse this value,
1176
+ // while a later call for the same BehaviorPoint is billed separately.
1177
+ idempotencyKey,
1178
+ enforcing: true
1179
+ }
1180
+ );
1181
+ }
1182
+ /** Resolve a runtime route from a governed execution boundary and semantic context. */
1183
+ resolveBoundary(input) {
1184
+ if (!input.executionBoundary || typeof input.executionBoundary !== "object")
1185
+ throw new Error("SDK_EXECUTION_BOUNDARY_REQUIRED");
1186
+ return this.resolveRuntime({
1187
+ aiSystemId: input.aiSystemId,
1188
+ provider: input.provider,
1189
+ model: input.model,
1190
+ protocol: input.protocol,
1191
+ executionBoundary: input.executionBoundary,
1192
+ ...input.semanticContext ? { semanticContext: input.semanticContext } : {},
1193
+ idempotencyKey: input.idempotencyKey
1194
+ });
1195
+ }
1196
+ /** Inspect historical rate candidates using an authenticated delegated user session. */
1197
+ inspectLegacyPricing(reservationId) {
1198
+ this.validateLegacyPricingIdentity(reservationId);
1199
+ return this.request({ method: "POST", path: "/v1/billing/legacy-pricing/inspect", body: { reservationId } }, { enforcing: true });
1200
+ }
1201
+ /** Create a short-lived proposal. This never pins rates or debits credits. */
1202
+ proposeLegacyPricing(input) {
1203
+ const { reservationId, reviewDigest, evidenceReference } = input;
1204
+ this.validateLegacyPricingIdentity(reservationId, reviewDigest);
1205
+ if (typeof reviewDigest !== "string" || !/^[a-f0-9]{64}$/.test(reviewDigest)) throw Error("SDK_LEGACY_PRICING_DIGEST_INVALID");
1206
+ if (typeof evidenceReference !== "string" || !evidenceReference.trim() || evidenceReference !== evidenceReference.trim() || evidenceReference.length > 512) throw Error("SDK_LEGACY_PRICING_EVIDENCE_INVALID");
1207
+ return this.request({ method: "POST", path: "/v1/billing/legacy-pricing/propose", body: { reservationId, reviewDigest, evidenceReference } }, { enforcing: true });
1208
+ }
1209
+ /** Approve only from a different active actor/session; the server enforces independence. */
1210
+ approveLegacyPricing(input) {
1211
+ const { reservationId, reviewDigest, proposalId } = input;
1212
+ this.validateLegacyPricingIdentity(reservationId, reviewDigest);
1213
+ if (typeof reviewDigest !== "string" || !/^[a-f0-9]{64}$/.test(reviewDigest)) throw Error("SDK_LEGACY_PRICING_DIGEST_INVALID");
1214
+ if (typeof proposalId !== "string" || !proposalId.trim() || proposalId !== proposalId.trim() || proposalId.length > 256) throw Error("SDK_LEGACY_PRICING_PROPOSAL_INVALID");
1215
+ return this.request({ method: "POST", path: "/v1/billing/legacy-pricing/approve", body: { reservationId, reviewDigest, proposalId } }, { enforcing: true });
1216
+ }
1217
+ inspectLegacyPromotionReconciliation(input = {}) {
1218
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/inspect", body: input }, { enforcing: true });
1219
+ }
1220
+ proposeLegacyPromotionReconciliation(input) {
1221
+ 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 });
1222
+ }
1223
+ approveLegacyPromotionReconciliation(input) {
1224
+ 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 });
1225
+ }
1226
+ historyLegacyPromotionReconciliation(input = {}) {
1227
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/history", body: input }, { enforcing: true });
1228
+ }
1229
+ inspectLegacyRecordRemediation(input = {}) {
1230
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/remediation-inspect", body: input }, { enforcing: true });
1231
+ }
1232
+ proposeLegacyRecordRemediation(input) {
1233
+ 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 });
1234
+ }
1235
+ approveLegacyRecordRemediation(input) {
1236
+ 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 });
1237
+ }
1238
+ historyLegacyRecordRemediation(input = {}) {
1239
+ return this.request({ method: "POST", path: "/v1/behavior-policy-bindings/reconciliation/remediation-history", body: input }, { enforcing: true });
1240
+ }
1241
+ inspectSubjectSignalConsent(input) {
1242
+ return this.request({ method: "POST", path: "/v1/signals/subject-consent/inspect", body: input }, { enforcing: true });
1243
+ }
1244
+ grantSubjectSignalConsent(input) {
1245
+ return this.request({ method: "POST", path: "/v1/signals/subject-consent/grant", body: input }, { idempotencyKey: `sdk:subject-signal-consent:${input.eventId}:${input.mappingId}`, enforcing: true });
1246
+ }
1247
+ withdrawSubjectSignalConsent(input) {
1248
+ return this.request({ method: "POST", path: "/v1/signals/subject-consent/withdraw", body: input }, { idempotencyKey: `sdk:subject-signal-consent-withdraw:${input.consentId}`, enforcing: true });
1249
+ }
1250
+ admitSubjectTeachEvidence(input) {
1251
+ 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 });
1252
+ }
1253
+ withdrawSubjectTeachEvidence(input) {
1254
+ return this.request({ method: "POST", path: "/v1/teach/subject-evidence/withdraw", body: input }, { idempotencyKey: `sdk:subject-teach-withdraw:${input.evidenceId}`, enforcing: true });
1255
+ }
1256
+ historySubjectTeachEvidence(input = {}) {
1257
+ return this.request({ method: "POST", path: "/v1/teach/subject-evidence/history", body: input }, { enforcing: true });
1258
+ }
1259
+ validateLegacyPricingIdentity(reservationId, reviewDigest) {
1260
+ if (typeof reservationId !== "string" || !reservationId.trim() || reservationId !== reservationId.trim() || reservationId.length > 256) throw Error("SDK_LEGACY_PRICING_RESERVATION_INVALID");
1261
+ if (reviewDigest !== void 0 && (typeof reviewDigest !== "string" || !/^[a-f0-9]{64}$/.test(reviewDigest))) throw Error("SDK_LEGACY_PRICING_DIGEST_INVALID");
1262
+ }
1263
+ /** Provider account usage only; never a managed charge or TaskRun completion. */
1264
+ verifyExternalProviderUsage(input) {
1265
+ const { aiSystemId, connectionId, generationId, providerId } = input;
1266
+ 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");
1267
+ if (providerId !== "openai" && providerId !== "openrouter" && providerId !== "xai" && providerId !== "gemini") throw new Error("SDK_BYOK_PROVIDER_INVALID");
1268
+ 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");
1269
+ return this.request({ method: "POST", path: "/v1/external-provider/usage/verify", body: { aiSystemId, connectionId, generationId, providerId } }, { enforcing: true });
1270
+ }
1271
+ /** Explicit first-party model transport. BYOK host observations remain non-chargeable. */
1272
+ executeManagedChat(input) {
1273
+ required(input.aiSystemId, "SDK_AI_SYSTEM_REQUIRED");
1274
+ required(input.connectionId, "SDK_CONNECTION_REQUIRED");
1275
+ required(input.operationId, "SDK_MANAGED_OPERATION_REQUIRED");
1276
+ return this.request({ method: "POST", path: "/v1/managed-model/chat/completions", body: { ...input, stream: false } }, { idempotencyKey: "managed-chat:" + input.operationId });
1277
+ }
1278
+ /** Classify input only; use resolveRuntime for one BehaviorPoint or resolveTaskRun/startTaskRun for TaskRun routing and execution. */
1279
+ resolveSemantic(input) {
1280
+ required(input.input, "SDK_SEMANTIC_INPUT_REQUIRED");
1281
+ const { idempotencyKey, requestId, ...body } = input;
1282
+ const resolvedRequestId = requestId ?? `sdk-semantic-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
1283
+ return this.request(
1284
+ {
1285
+ method: "POST",
1286
+ path: "/v1/semantic/resolve",
1287
+ body: { ...body, requestId: resolvedRequestId }
1288
+ },
1289
+ { idempotencyKey: idempotencyKey ?? `sdk:semantic:${resolvedRequestId}` }
1290
+ );
1291
+ }
1292
+ async resolveSemanticRuntime(input) {
1293
+ let semantic = await this.resolveSemantic(input);
1294
+ if (!semantic) return null;
1295
+ let body = semantic.body;
1296
+ if (body.replayed === true && !Array.isArray(body.capsules)) {
1297
+ const replayRequestId = `${input.requestId ?? "sdk-semantic"}:rehydrate:${Date.now()}`;
1298
+ const refreshed = await this.resolveSemantic({
1299
+ ...input,
1300
+ requestId: replayRequestId,
1301
+ idempotencyKey: `sdk:semantic:rehydrate:${replayRequestId}`
1302
+ });
1303
+ if (refreshed) {
1304
+ semantic = refreshed;
1305
+ body = refreshed.body;
1306
+ }
1307
+ }
1308
+ const receipt = body.receipt && typeof body.receipt === "object" ? body.receipt : {};
1309
+ if (receipt.outcome !== "select" || typeof receipt.taskKey !== "string")
1310
+ return { semantic, runtime: null, taskKeys: [], capsules: [], multiTask: false };
1311
+ const capsules = Array.isArray(body.capsules) ? body.capsules : [];
1312
+ const candidateValues = Array.isArray(body.intentCandidates) ? body.intentCandidates : Array.isArray(body.selectedTaskKeys) ? body.selectedTaskKeys : [];
1313
+ const taskKeys = [...new Set(candidateValues.map((value) => typeof value === "string" ? value.trim() : value && typeof value === "object" ? String(value.taskKey ?? value.semanticTaskKey ?? "").trim() : "").filter(Boolean))];
1314
+ if (!taskKeys.length) taskKeys.push(receipt.taskKey.trim());
1315
+ const firstCapsule = capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) && typeof capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) === "object" ? capsules.find((value) => value && typeof value === "object" && String(value.behaviorKey ?? "").trim() === receipt.taskKey) : capsules[0] && typeof capsules[0] === "object" ? capsules[0] : {};
1316
+ const behaviorPoint = typeof firstCapsule.behaviorKey === "string" && firstCapsule.behaviorKey.trim() ? firstCapsule.behaviorKey : receipt.taskKey;
1317
+ const runtime = input.executionBoundary ? await this.resolveBoundary({
1318
+ aiSystemId: input.aiSystemId,
1319
+ provider: input.provider,
1320
+ model: input.model,
1321
+ protocol: input.protocol,
1322
+ executionBoundary: input.executionBoundary,
1323
+ semanticContext: {
1324
+ taskKey: receipt.taskKey,
1325
+ behaviorPoint,
1326
+ capsule: firstCapsule,
1327
+ ...input.revisionId ? { revisionId: input.revisionId } : {},
1328
+ ...input.requestId ? { requestId: input.requestId } : {},
1329
+ ...input.sessionId ? { conversationId: input.sessionId } : {},
1330
+ ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {}
1331
+ },
1332
+ idempotencyKey: input.idempotencyKey ? `sdk:runtime:${input.idempotencyKey}` : void 0
1333
+ }) : await this.resolveRuntime({
1334
+ aiSystemId: input.aiSystemId,
1335
+ provider: input.provider,
1336
+ model: input.model,
1337
+ protocol: input.protocol,
1338
+ semanticContext: { taskKey: receipt.taskKey, behaviorPoint, capsule: firstCapsule, ...input.revisionId ? { revisionId: input.revisionId } : {}, ...input.requestId ? { requestId: input.requestId } : {}, ...input.sessionId ? { conversationId: input.sessionId } : {}, ...input.signalAttestationRefs ? { signalAttestationRefs: input.signalAttestationRefs } : {} },
1339
+ idempotencyKey: input.idempotencyKey ? `sdk:runtime:${input.idempotencyKey}` : void 0
1340
+ });
1341
+ return { semantic, runtime, taskKeys, capsules, multiTask: taskKeys.length > 1 };
1342
+ }
1343
+ async authorizeHostAction(input) {
1344
+ required(input.scope.organizationId, "SDK_ACTION_ORGANIZATION_REQUIRED");
1345
+ required(input.scope.projectId, "SDK_ACTION_PROJECT_REQUIRED");
1346
+ required(input.scope.environmentId, "SDK_ACTION_ENVIRONMENT_REQUIRED");
1347
+ required(input.executionId, "SDK_ACTION_EXECUTION_REQUIRED");
1348
+ required(input.sessionId, "SDK_ACTION_SESSION_REQUIRED");
1349
+ required(input.dataVersion, "SDK_ACTION_DATA_VERSION_REQUIRED");
1350
+ return this.request({
1351
+ method: "POST",
1352
+ path: "/v1/runtime/actions/authorize",
1353
+ 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 } : {}, ...input.connectionId ? { connectionId: input.connectionId } : {} }
1354
+ });
1355
+ }
1356
+ /** Queue the approved SINGLE effect on the worker, never execute it locally. */
1357
+ async queueTaskRunHostDispatch(input) {
1358
+ 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");
1359
+ const executionId = String(input.context.execution_id ?? ""), dataVersion = String(input.context.data_version ?? "");
1360
+ required(executionId, "SDK_ACTION_EXECUTION_REQUIRED");
1361
+ required(dataVersion, "SDK_ACTION_DATA_VERSION_REQUIRED");
1362
+ 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 });
1363
+ if (!result || result.status !== 202 || result.body?.status !== "QUEUED" || result.body.clientExecutionAllowed !== false || !result.body.invocationId) throw Error("SDK_SINGLE_HOST_QUEUE_PROOF_REQUIRED");
1364
+ return result;
1365
+ }
1366
+ async createHostActionApproval(input) {
1367
+ required(input.sessionId, "SDK_ACTION_SESSION_REQUIRED");
1368
+ required(input.dataVersion, "SDK_ACTION_DATA_VERSION_REQUIRED");
1369
+ required(input.confirmation.proposalId, "SDK_ACTION_CONFIRMATION_PROPOSAL_REQUIRED");
1370
+ required(input.confirmation.toolName, "SDK_ACTION_CONFIRMATION_TOOL_REQUIRED");
1371
+ required(input.confirmation.argumentsDigest, "SDK_ACTION_CONFIRMATION_ARGUMENTS_REQUIRED");
1372
+ required(input.confirmation.requestContextDigest, "SDK_ACTION_CONFIRMATION_CONTEXT_REQUIRED");
1373
+ required(input.confirmation.acknowledgedAt, "SDK_ACTION_CONFIRMATION_TIME_REQUIRED");
1374
+ return this.request({ method: "POST", path: "/v1/runtime/actions/approvals", body: { sessionId: input.sessionId, dataVersion: input.dataVersion, proposal: input.proposal, confirmation: input.confirmation, ...input.ttlSeconds !== void 0 ? { ttlSeconds: input.ttlSeconds } : {} } });
1375
+ }
1376
+ listBehaviorStrategies(options = {}) {
1377
+ return this.request({
1378
+ method: "GET",
1379
+ path: "/v1/behavior-strategies",
1380
+ query: listQuery(options)
1381
+ });
1382
+ }
1383
+ async deleteBehaviorStrategy(strategyId, options = {}) {
1384
+ required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1385
+ const path = `/v1/behavior-strategies/${encodeURIComponent(strategyId)}`, body = { confirm: options.confirm === true };
1386
+ return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:strategy:${strategyId}`, { path, body }) });
1387
+ }
1388
+ getBehaviorStrategy(strategyId) {
1389
+ required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1390
+ return this.request({
1391
+ method: "GET",
1392
+ path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}`
1393
+ });
1394
+ }
1395
+ createBehaviorStrategy(definition, id) {
1396
+ if (!definition) throw new Error("SDK_STRATEGY_DEFINITION_REQUIRED");
1397
+ return this.request({
1398
+ method: "POST",
1399
+ path: "/v1/behavior-strategies",
1400
+ body: { definition, ...id ? { id } : {} }
1401
+ });
1402
+ }
1403
+ listSemanticTasks(options = {}) {
1404
+ if (options.limit !== void 0 && (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 200)) throw new Error("SDK_SEMANTIC_TASK_LIMIT_INVALID");
1405
+ return this.request({ method: "GET", path: "/v1/semantic-tasks", query: listQuery(options) });
1406
+ }
1407
+ async deleteSemanticTask(taskId, options = {}) {
1408
+ required(taskId, "SDK_SEMANTIC_TASK_ID_REQUIRED");
1409
+ const path = `/v1/semantic-tasks/${encodeURIComponent(taskId)}`, body = { confirm: options.confirm === true };
1410
+ return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:semantic-task:${taskId}`, { path, body }) });
1411
+ }
1412
+ async createSemanticTask(task, options = {}) {
1413
+ required(task?.taskKey, "SDK_SEMANTIC_TASK_KEY_REQUIRED");
1414
+ const body = { ...task, ...options.id ? { id: options.id } : {} };
1415
+ return this.request({ method: "POST", path: "/v1/semantic-tasks", body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:semantic-task:${task.taskKey}`, body) });
1416
+ }
1417
+ listBehaviorPoints(options = {}) {
1418
+ if (options.limit !== void 0 && (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 200)) throw new Error("SDK_BEHAVIOR_POINT_LIMIT_INVALID");
1419
+ return this.request({ method: "GET", path: "/v1/behavior-points", query: listQuery(options) });
1420
+ }
1421
+ async deleteBehaviorPoint(pointId, options = {}) {
1422
+ required(pointId, "SDK_BEHAVIOR_POINT_ID_REQUIRED");
1423
+ const path = `/v1/behavior-points/${encodeURIComponent(pointId)}`, body = { confirm: options.confirm === true };
1424
+ return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:behavior-point:${pointId}`, { path, body }) });
1425
+ }
1426
+ async createBehaviorPoint(point, options = {}) {
1427
+ required(point?.key, "SDK_BEHAVIOR_POINT_KEY_REQUIRED");
1428
+ if (!point.taskId && !point.taskIds?.length) throw new Error("SDK_BEHAVIOR_POINT_TASK_REQUIRED");
1429
+ const body = { ...point, ...options.id ? { id: options.id } : {} };
1430
+ return this.request({ method: "POST", path: "/v1/behavior-points", body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:behavior-point:${point.key}`, body) });
1431
+ }
1432
+ createBehaviorStrategyVariant(strategyId, variant, options = {}) {
1433
+ required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1434
+ if (!variant || typeof variant !== "object")
1435
+ throw new Error("SDK_STRATEGY_VARIANT_REQUIRED");
1436
+ return this.request(
1437
+ {
1438
+ method: "POST",
1439
+ path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}/variants`,
1440
+ body: variant
1441
+ },
1442
+ { idempotencyKey: options.idempotencyKey }
1443
+ );
1444
+ }
1445
+ /** Create a separate immutable draft revision against a specific observed parent.
1446
+ * This never activates or releases the draft. */
1447
+ reviseBehaviorStrategy(strategyId, definition, parent, options = {}) {
1448
+ required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1449
+ if (!definition || typeof definition !== "object" || Array.isArray(definition))
1450
+ throw new Error("SDK_STRATEGY_VARIANT_REQUIRED");
1451
+ if (!parent || typeof parent.variantId !== "string" || !parent.variantId.trim() || parent.variantId.trim() !== parent.variantId || parent.variantId.length > 512 || typeof parent.artifactDigest !== "string" || !/^[a-f0-9]{64}$/.test(parent.artifactDigest) || typeof parent.definitionDigest !== "string" || !/^[a-f0-9]{64}$/.test(parent.definitionDigest))
1452
+ throw new Error("SDK_STRATEGY_PARENT_INVALID");
1453
+ return this.createBehaviorStrategyVariant(strategyId, {
1454
+ definition,
1455
+ studioBoundAuthoring: true,
1456
+ expectedParentVariantId: parent.variantId,
1457
+ expectedParentArtifactDigest: parent.artifactDigest,
1458
+ expectedParentDefinitionDigest: parent.definitionDigest
1459
+ }, options);
1460
+ }
1461
+ validateBehaviorStrategy(strategyId, options = {}) {
1462
+ required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1463
+ if (options.variantId !== void 0 && (typeof options.variantId !== "string" || !options.variantId.trim() || options.variantId.trim() !== options.variantId || options.variantId.length > 512))
1464
+ throw new Error("SDK_STRATEGY_VARIANT_ID_INVALID");
1465
+ return this.request({
1466
+ method: "POST",
1467
+ path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}/validate`,
1468
+ body: options.variantId === void 0 ? {} : { variantId: options.variantId }
1469
+ });
1470
+ }
1471
+ activateBehaviorStrategy(strategyId) {
1472
+ required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1473
+ return this.request({ method: "POST", path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}/activate`, body: {} });
1474
+ }
1475
+ simulateBehaviorStrategy(strategyId, initialState = {}, options = {}) {
1476
+ required(strategyId, "SDK_STRATEGY_ID_REQUIRED");
1477
+ if (options.variantId !== void 0 && (typeof options.variantId !== "string" || !options.variantId.trim() || options.variantId.trim() !== options.variantId || options.variantId.length > 512))
1478
+ throw new Error("SDK_STRATEGY_VARIANT_ID_INVALID");
1479
+ return this.request({
1480
+ method: "POST",
1481
+ path: `/v1/behavior-strategies/${encodeURIComponent(strategyId)}/simulate`,
1482
+ body: { initialState, ...options.variantId === void 0 ? {} : { variantId: options.variantId } }
1483
+ });
1484
+ }
1485
+ startStrategyExecution(input) {
1486
+ required(input.artifactDigest, "SDK_ARTIFACT_DIGEST_REQUIRED");
1487
+ for (const value of [
1488
+ input.organizationId,
1489
+ input.projectId,
1490
+ input.environmentId,
1491
+ input.revisionId,
1492
+ input.idempotencyKey,
1493
+ input.nonce,
1494
+ input.decisionPlanId,
1495
+ input.policy
1496
+ ])
1497
+ required(value, "SDK_STRATEGY_START_FIELD_REQUIRED");
1498
+ if (input.behaviorPoint !== void 0)
1499
+ required(input.behaviorPoint, "SDK_BEHAVIOR_POINT_REQUIRED");
1500
+ if (!Array.isArray(input.candidates) || input.candidates.length === 0)
1501
+ throw new Error("SDK_STRATEGY_CANDIDATES_REQUIRED");
1502
+ if (!Number.isFinite(input.expiresAt))
1503
+ throw new Error("SDK_EXPIRY_REQUIRED");
1504
+ if (input.cutoverRouteValidation !== void 0 && input.traceId !== void 0)
1505
+ throw new Error("SDK_F4_STRATEGY_TRACE_SERVER_OWNED");
1506
+ const body = {
1507
+ ...buildRuntimeRequest(
1508
+ input,
1509
+ { includeAIIdentity: true, allowStagedValidation: true }
1510
+ ),
1511
+ artifactDigest: input.artifactDigest,
1512
+ ...input.releaseId ? { releaseId: input.releaseId } : {},
1513
+ ...input.behaviorPoint ? { behaviorPoint: input.behaviorPoint } : {},
1514
+ ...input.executionBoundary ? { executionBoundary: input.executionBoundary } : {},
1515
+ ...input.traceId ? { traceId: input.traceId } : {},
1516
+ ...input.executionId ? { executionId: input.executionId } : {},
1517
+ ...input.state ? { state: input.state } : {}
1518
+ };
1519
+ return this.request(
1520
+ { method: "POST", path: "/v1/runtime/strategy-executions", body },
1521
+ { idempotencyKey: input.idempotencyKey }
1522
+ );
1523
+ }
1524
+ getStrategyExecution(executionId) {
1525
+ required(executionId, "SDK_EXECUTION_ID_REQUIRED");
1526
+ return this.request({
1527
+ method: "GET",
1528
+ path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}`
1529
+ });
1530
+ }
1531
+ /** Uses the existing Strategy execution read-authorizer and unit-scoped
1532
+ * credentials. Never exposes an amount-based settlement method. */
1533
+ getAIUsageReconciliation(executionId) {
1534
+ required(executionId, "SDK_EXECUTION_ID_REQUIRED");
1535
+ return this.request({
1536
+ method: "GET",
1537
+ path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}/credit-reconciliation`
1538
+ });
1539
+ }
1540
+ getJob(jobId) {
1541
+ required(jobId, "SDK_JOB_ID_REQUIRED");
1542
+ return this.request({ method: "GET", path: `/v1/jobs/${encodeURIComponent(jobId)}` });
1543
+ }
1544
+ getConflictInspection(inspectionId) {
1545
+ required(inspectionId, "SDK_CONFLICT_INSPECTION_ID_REQUIRED");
1546
+ return this.request({ method: "GET", path: `/v1/conflicts/${encodeURIComponent(inspectionId)}` });
1547
+ }
1548
+ async inspectConflicts(input, options = {}) {
1549
+ if (!Array.isArray(input.proposed) || !Array.isArray(input.active) || !Array.isArray(input.controls)) throw new Error("SDK_CONFLICT_INSPECTION_ARRAYS_REQUIRED");
1550
+ const body = { ...input.id ? { id: required(input.id, "SDK_CONFLICT_INSPECTION_ID_REQUIRED") } : {}, proposed: input.proposed, active: input.active, controls: input.controls };
1551
+ return this.request({ method: "POST", path: "/v1/conflicts/inspect", body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey("sdk:conflicts:inspect", body) });
1552
+ }
1553
+ async resolveConflictInspection(inspectionId, status, options = {}) {
1554
+ required(inspectionId, "SDK_CONFLICT_INSPECTION_ID_REQUIRED");
1555
+ if (status !== "APPROVED" && status !== "REJECTED") throw new Error("SDK_CONFLICT_RESOLUTION_STATUS_INVALID");
1556
+ if (options.authorityDigest !== void 0 && !options.authorityDigest.trim()) throw new Error("SDK_CONFLICT_AUTHORITY_DIGEST_INVALID");
1557
+ const path = `/v1/conflicts/${encodeURIComponent(inspectionId)}/resolve`, body = { status, ...options.authorityDigest ? { authorityDigest: options.authorityDigest } : {} };
1558
+ return this.request({ method: "POST", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:conflicts:resolve:${inspectionId}`, body) });
1559
+ }
1560
+ listStrategyExecutions(options = {}) {
1561
+ if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1 || options.limit > 200)) throw new Error("SDK_STRATEGY_EXECUTION_LIMIT_INVALID");
1562
+ return this.request({ method: "GET", path: "/v1/runtime/strategy-executions", query: listQuery(options) });
1563
+ }
1564
+ getStrategyExecutionTrace(executionId) {
1565
+ required(executionId, "SDK_EXECUTION_ID_REQUIRED");
1566
+ return this.request({
1567
+ method: "GET",
1568
+ path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}/trace`
1569
+ });
1570
+ }
1571
+ continueStrategyExecution(executionId, continuation) {
1572
+ required(executionId, "SDK_EXECUTION_ID_REQUIRED");
1573
+ const input = typeof continuation === "string" ? { authorityDigest: continuation } : continuation ?? {};
1574
+ if (input.expectedSequence !== void 0 && (!Number.isSafeInteger(input.expectedSequence) || input.expectedSequence < 0)) throw Error("SDK_STRATEGY_SEQUENCE_INVALID");
1575
+ return this.request({
1576
+ method: "POST",
1577
+ path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}/continue`,
1578
+ body: {
1579
+ ...input.authorityDigest ? { authorityDigest: input.authorityDigest } : {},
1580
+ ...input.expectedSequence !== void 0 ? { expectedSequence: input.expectedSequence } : {},
1581
+ ...input.state ? { state: input.state } : {},
1582
+ ...input.references ? { references: input.references } : {}
1583
+ }
1584
+ });
1585
+ }
1586
+ cancelStrategyExecution(executionId, options = {}) {
1587
+ required(executionId, "SDK_EXECUTION_ID_REQUIRED");
1588
+ if (options.expectedSequence !== void 0 && (!Number.isSafeInteger(options.expectedSequence) || options.expectedSequence < 0)) throw Error("SDK_STRATEGY_SEQUENCE_INVALID");
1589
+ return this.request({
1590
+ method: "POST",
1591
+ path: `/v1/runtime/strategy-executions/${encodeURIComponent(executionId)}/cancel`,
1592
+ body: { ...options.authorityDigest !== void 0 ? { authorityDigest: options.authorityDigest } : {}, ...options.expectedSequence !== void 0 ? { expectedSequence: options.expectedSequence } : {} }
1593
+ });
1594
+ }
1595
+ listCompoundTaskPlans(options = {}) {
1596
+ if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1 || options.limit > 500)) throw new Error("SDK_COMPOUND_TASK_PLAN_LIMIT_INVALID");
1597
+ if (options.cursor !== void 0 && !options.cursor.trim()) throw new Error("SDK_COMPOUND_TASK_PLAN_CURSOR_INVALID");
1598
+ return this.request({ method: "GET", path: "/v1/compound-tasks/plans", query: { ...options.limit === void 0 ? {} : { limit: String(options.limit) }, ...options.cursor ? { cursor: options.cursor } : {} } });
1599
+ }
1600
+ saveCompoundTaskPlan(plan, options = {}) {
1601
+ const planId = typeof plan.planId === "string" ? plan.planId.trim() : "";
1602
+ const planDigest = typeof plan.planDigest === "string" ? plan.planDigest.trim() : "";
1603
+ if (!planId || !planDigest) throw new Error("SDK_COMPOUND_TASK_PLAN_FIELDS_REQUIRED");
1604
+ return this.request({ method: "POST", path: "/v1/compound-tasks/plans", body: { plan } }, { idempotencyKey: options.idempotencyKey ?? `sdk:compound-task-plan:${planId}:${planDigest}` });
1605
+ }
1606
+ getCompoundTaskPlan(planId) {
1607
+ required(planId, "SDK_COMPOUND_TASK_PLAN_ID_REQUIRED");
1608
+ return this.request({ method: "GET", path: `/v1/compound-tasks/plans/${encodeURIComponent(planId)}` });
1609
+ }
1610
+ async resolveTaskRun(input) {
1611
+ required(input.input, "SDK_TASKRUN_INPUT_REQUIRED");
1612
+ if (input.requestedMode) required(input.requestedMode, "SDK_TASKRUN_MODE_REQUIRED");
1613
+ const connectionId = input.connectionId ?? this.boundConnectionId;
1614
+ const requestId = input.requestId ?? `sdk-task-route-${(await contentIdempotencyKey("sdk-task-route", input)).split(":").at(-1)}`;
1615
+ return this.request({ method: "POST", path: "/v1/task-runs/resolve", body: { ...input, requestId, ...connectionId ? { connectionId } : {} } }, { idempotencyKey: `sdk:task-run:resolve:${requestId}` });
1616
+ }
1617
+ startTaskRun(input, options = {}) {
1618
+ for (const value of [input.taskRunId, input.requestId]) required(value, "SDK_TASKRUN_ADMISSION_FIELD_REQUIRED");
1619
+ required(input.aiSystemId, "SDK_TASKRUN_AI_SYSTEM_REQUIRED");
1620
+ if (input.input === void 0 || input.input === null) throw new Error("SDK_TASKRUN_INPUT_REQUIRED");
1621
+ const body = { ...input, ...input.ownerActorRef ? { ownerActorRef: input.ownerActorRef } : {}, ...input.requestedMode ? { requestedMode: input.requestedMode } : {}, ...!input.connectionId && this.boundConnectionId ? { connectionId: this.boundConnectionId } : {} };
1622
+ return this.request({ method: "POST", path: "/v1/task-runs", body }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:start:${input.requestId}` });
1623
+ }
1624
+ startTaskRunFromPrompt(input, options = {}) {
1625
+ required(input.aiSystemId, "SDK_TASKRUN_AI_SYSTEM_REQUIRED");
1626
+ if (input.input === void 0 || input.input === null) throw new Error("SDK_TASKRUN_INPUT_REQUIRED");
1627
+ const id = () => globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`;
1628
+ const requestId = input.requestId ?? `sdk-task-run-${id()}`;
1629
+ return this.startTaskRun({ taskRunId: input.taskRunId ?? `task-run-${id()}`, 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);
1630
+ }
1631
+ /** Read authorized history; partial without a cursor is not complete. */
1632
+ listTaskRuns(options = {}) {
1633
+ const limit = options.limit === void 0 ? 50 : options.limit;
1634
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error("SDK_TASKRUN_HISTORY_LIMIT_INVALID");
1635
+ const cursor = options.cursor;
1636
+ if (cursor !== void 0 && (typeof cursor !== "string" || !cursor.length || cursor.length > 256 || cursor !== cursor.trim())) throw new Error("SDK_TASKRUN_HISTORY_CURSOR_INVALID");
1637
+ const { aiSystemId, conversationId } = options;
1638
+ const scoped = aiSystemId !== void 0 || conversationId !== void 0;
1639
+ if (scoped && [aiSystemId, conversationId].some((value) => typeof value !== "string" || !value.length || value.length > 256 || value !== value.trim())) throw Error("SDK_TASKRUN_HISTORY_SESSION_SELECTION_INVALID");
1640
+ return this.request({ method: "GET", path: "/v1/task-runs", query: { limit: String(limit), ...cursor !== void 0 ? { cursor } : {}, ...scoped ? { aiSystemId, conversationId } : {} } });
1641
+ }
1642
+ getTaskRun(taskRunId) {
1643
+ required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1644
+ return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}` });
1645
+ }
1646
+ getTaskRunEvidence(taskRunId, options = {}) {
1647
+ required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1648
+ return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/evidence`, ...options.includeResult === true ? { query: { includeResult: "true" } } : {} });
1649
+ }
1650
+ listTaskRunEvents(taskRunId) {
1651
+ required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1652
+ return this.request({ method: "GET", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/events` });
1653
+ }
1654
+ continueTaskRun(taskRunId, expectedVersion, options = {}) {
1655
+ required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1656
+ if (!Number.isInteger(expectedVersion) || expectedVersion < 0) throw new Error("SDK_TASKRUN_STATE_VERSION_REQUIRED");
1657
+ return this.request({ method: "POST", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/continue`, body: { expectedVersion, ...options.cursor ? { cursor: options.cursor } : {} } }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:continue:${taskRunId}:${expectedVersion}` });
1658
+ }
1659
+ cancelTaskRun(taskRunId, expectedVersion = 0, options = {}) {
1660
+ required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1661
+ if (!Number.isInteger(expectedVersion) || expectedVersion < 0) throw new Error("SDK_TASKRUN_STATE_VERSION_REQUIRED");
1662
+ return this.request({ method: "POST", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/cancel`, body: { expectedVersion } }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:cancel:${taskRunId}:${expectedVersion}` });
1663
+ }
1664
+ retryTaskRun(taskRunId, expectedVersion, options = {}) {
1665
+ required(taskRunId, "SDK_TASKRUN_ID_REQUIRED");
1666
+ if (!Number.isInteger(expectedVersion) || expectedVersion < 0) throw new Error("SDK_TASKRUN_STATE_VERSION_REQUIRED");
1667
+ return this.request({ method: "POST", path: `/v1/task-runs/${encodeURIComponent(taskRunId)}/retry`, body: { expectedVersion } }, { idempotencyKey: options.idempotencyKey ?? `sdk:task-run:retry:${taskRunId}:${expectedVersion}` });
1668
+ }
1669
+ listBehaviorPrograms(options = {}) {
1670
+ return this.request({
1671
+ method: "GET",
1672
+ path: "/v1/behavior-programs",
1673
+ query: listQuery(options)
1674
+ });
1675
+ }
1676
+ listCapabilities(options = {}) {
1677
+ return this.request({ method: "GET", path: "/v1/capabilities", ...options.surface ? { query: { surface: options.surface } } : {} });
1678
+ }
1679
+ /** Read the scope actually admitted by the credential, never a caller claim.
1680
+ * Useful before attaching a host to a department-bound machine key. */
1681
+ async resolveCredentialScope(expected = {}, options = {}) {
1682
+ const response = await this.listCapabilities({ surface: "sdk" });
1683
+ const scope = response?.body?.scope;
1684
+ if (!scope || response?.body?.source !== "scoped-product-capability-catalog") throw Error("SDK_CREDENTIAL_SCOPE_UNAVAILABLE");
1685
+ for (const key of ["organizationId", "projectId", "environmentId", "organizationUnitId"]) {
1686
+ const value = scope[key];
1687
+ if ((key !== "organizationUnitId" || options.requireDepartment || value !== void 0) && (typeof value !== "string" || !value.trim() || value !== value.trim())) throw Error("SDK_CREDENTIAL_SCOPE_INVALID");
1688
+ if (expected[key] !== void 0 && expected[key] !== value) throw Error("SDK_CREDENTIAL_SCOPE_MISMATCH");
1689
+ }
1690
+ return {
1691
+ organizationId: scope.organizationId,
1692
+ projectId: scope.projectId,
1693
+ environmentId: scope.environmentId,
1694
+ ...scope.organizationUnitId ? { organizationUnitId: scope.organizationUnitId } : {}
1695
+ };
1696
+ }
1697
+ getBehaviorProgram(programId) {
1698
+ required(programId, "SDK_PROGRAM_ID_REQUIRED");
1699
+ return this.request({
1700
+ method: "GET",
1701
+ path: `/v1/behavior-programs/${encodeURIComponent(programId)}`
1702
+ });
1703
+ }
1704
+ async deleteBehaviorProgram(programId, options = {}) {
1705
+ required(programId, "SDK_PROGRAM_ID_REQUIRED");
1706
+ const path = `/v1/behavior-programs/${encodeURIComponent(programId)}`, body = { confirm: options.confirm === true };
1707
+ return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:behavior-program:${programId}`, { path, body }) });
1708
+ }
1709
+ async deleteBehaviorProgramCascade(programId, options = {}) {
1710
+ required(programId, "SDK_PROGRAM_ID_REQUIRED");
1711
+ const path = `/v1/behavior-programs/${encodeURIComponent(programId)}/cascade`, body = { confirm: options.confirm === true, purgeRuntime: options.purgeRuntime === true };
1712
+ return this.request({ method: "DELETE", path, body }, { idempotencyKey: options.idempotencyKey ?? await contentIdempotencyKey(`sdk:delete:behavior-program-cascade:${programId}`, { path, body }) });
1713
+ }
1714
+ /** Authenticated draft only. Never releases or activates a behavior policy. */
1715
+ createBehaviorPolicySource(source) {
1716
+ required(source.policyKey, "SDK_BEHAVIOR_POLICY_KEY_REQUIRED");
1717
+ if (source.sourceLevel === "organization_unit") required(source.sourceId, "SDK_BEHAVIOR_POLICY_UNIT_REQUIRED");
1718
+ if (!Number.isSafeInteger(source.revision) || source.revision < 1)
1719
+ throw new Error("SDK_BEHAVIOR_POLICY_REVISION_INVALID");
1720
+ if (!Array.isArray(source.modules) || !source.modules.length)
1721
+ throw new Error("SDK_BEHAVIOR_POLICY_MODULES_REQUIRED");
1722
+ return this.request({
1723
+ method: "POST",
1724
+ path: "/v1/behavior-policy-sources",
1725
+ body: source
1726
+ });
1727
+ }
1728
+ listBehaviorPolicySources(input) {
1729
+ required(input.policyKey, "SDK_BEHAVIOR_POLICY_KEY_REQUIRED");
1730
+ if (input.sourceLevel === "organization_unit") required(input.sourceId, "SDK_BEHAVIOR_POLICY_UNIT_REQUIRED");
1731
+ return this.request({
1732
+ method: "GET",
1733
+ path: "/v1/behavior-policy-sources",
1734
+ query: {
1735
+ sourceLevel: input.sourceLevel,
1736
+ policyKey: input.policyKey,
1737
+ ...input.sourceId ? { sourceId: input.sourceId } : {}
1738
+ }
1739
+ });
1740
+ }
1741
+ getBehaviorPolicySource(sourceRevisionId) {
1742
+ required(sourceRevisionId, "SDK_BEHAVIOR_POLICY_SOURCE_ID_REQUIRED");
1743
+ return this.request({
1744
+ method: "GET",
1745
+ path: "/v1/behavior-policy-sources/" + encodeURIComponent(sourceRevisionId)
1746
+ });
1747
+ }
1748
+ /** Conflict preview only. Returned canActivate=false is intentional. */
1749
+ previewBehaviorPolicyBinding(input) {
1750
+ required(input.sourceRevisionId, "SDK_BEHAVIOR_POLICY_SOURCE_ID_REQUIRED");
1751
+ required(input.sourceDigest, "SDK_BEHAVIOR_POLICY_SOURCE_DIGEST_REQUIRED");
1752
+ required(input.programId, "SDK_BEHAVIOR_POLICY_PROGRAM_ID_REQUIRED");
1753
+ return this.request({
1754
+ method: "POST",
1755
+ path: "/v1/behavior-policy-bindings/preview",
1756
+ body: input
1757
+ });
1758
+ }
1759
+ /** Preview's digest is a concurrency precondition, never approval. */
1760
+ getCurrentBehaviorPolicyBinding(policyKey, options = {}) {
1761
+ required(policyKey, "SDK_BEHAVIOR_POLICY_KEY_REQUIRED");
1762
+ return this.request({
1763
+ method: "GET",
1764
+ path: "/v1/behavior-policy-bindings/current",
1765
+ query: {
1766
+ policyKey,
1767
+ ...options.sourceLevel ? { sourceLevel: options.sourceLevel } : {},
1768
+ ...options.sourceId ? { sourceId: options.sourceId } : {}
1769
+ }
1770
+ });
1771
+ }
1772
+ /** One non-retryable, server-reviewed PostgreSQL transaction. */
1773
+ commitBehaviorPolicyBinding(input) {
1774
+ for (const key of [
1775
+ "sourceRevisionId",
1776
+ "sourceDigest",
1777
+ "programId",
1778
+ "programDigest",
1779
+ "expectedPolicySnapshotDigest",
1780
+ "reason"
1781
+ ])
1782
+ required(input[key], "SDK_POLICY_RELEASE_FIELD_REQUIRED");
1783
+ if (!["ACTIVATE", "REPLACE", "ROLLBACK"].includes(input.mode))
1784
+ throw new Error("SDK_POLICY_RELEASE_MODE_INVALID");
1785
+ if (input.mode !== "ACTIVATE")
1786
+ required(input.expectedCurrentBindingDigest, "SDK_POLICY_RELEASE_CURRENT_BINDING_REQUIRED");
1787
+ return this.request(
1788
+ {
1789
+ method: "POST",
1790
+ path: "/v1/behavior-policy-bindings/commit",
1791
+ body: { ...input }
1792
+ },
1793
+ { enforcing: true }
1794
+ );
1795
+ }
1796
+ /** Read-only full blast-radius simulation. Digest is a CAS precondition, not approval. */
1797
+ previewWideBehaviorPolicyImpact(input) {
1798
+ required(input.sourceRevisionId, "SDK_POLICY_IMPACT_SOURCE_REQUIRED");
1799
+ required(input.sourceDigest, "SDK_POLICY_IMPACT_DIGEST_REQUIRED");
1800
+ if (!["ACTIVATE", "REPLACE", "ROLLBACK"].includes(input.mode))
1801
+ throw new Error("SDK_POLICY_RELEASE_MODE_INVALID");
1802
+ if (input.mode !== "ACTIVATE")
1803
+ required(input.expectedCurrentBindingDigest, "SDK_POLICY_RELEASE_CURRENT_BINDING_REQUIRED");
1804
+ return this.request({
1805
+ method: "POST",
1806
+ path: "/v1/behavior-policy-bindings/impact",
1807
+ body: input
1808
+ });
1809
+ }
1810
+ /** Independent owner approval + server-revalidated impact under one transaction. */
1811
+ commitWideBehaviorPolicyBinding(input) {
1812
+ for (const key of ["sourceRevisionId", "sourceDigest", "expectedImpactDigest", "reason"])
1813
+ required(input[key], "SDK_POLICY_IMPACT_COMMIT_FIELD_REQUIRED");
1814
+ if (!["ACTIVATE", "REPLACE", "ROLLBACK"].includes(input.mode))
1815
+ throw new Error("SDK_POLICY_RELEASE_MODE_INVALID");
1816
+ if (input.mode !== "ACTIVATE")
1817
+ required(input.expectedCurrentBindingDigest, "SDK_POLICY_RELEASE_CURRENT_BINDING_REQUIRED");
1818
+ return this.request(
1819
+ {
1820
+ method: "POST",
1821
+ path: "/v1/behavior-policy-bindings/commit-wide",
1822
+ body: input
1823
+ },
1824
+ { enforcing: true }
1825
+ );
1826
+ }
1827
+ createBehaviorProgram(program, options = {}) {
1828
+ if (!program || typeof program !== "object")
1829
+ throw new Error("SDK_PROGRAM_REQUIRED");
1830
+ return this.request(
1831
+ { method: "POST", path: "/v1/behavior-programs", body: program },
1832
+ {
1833
+ idempotencyKey: options.idempotencyKey ?? `sdk:program:${String(program.id ?? "")}`
1834
+ }
1835
+ );
1836
+ }
1837
+ attestCapabilities(attestation, options = {}) {
1838
+ return this.request(
1839
+ {
1840
+ method: "POST",
1841
+ path: "/v1/runtime/capabilities/attest",
1842
+ body: attestation
1843
+ },
1844
+ { idempotencyKey: options.idempotencyKey }
1845
+ );
1846
+ }
1847
+ resolveCapabilities(attestationId, request, options = {}) {
1848
+ required(attestationId, "SDK_ATTESTATION_ID_REQUIRED");
1849
+ const nested = request.executionContext && typeof request.executionContext === "object" ? request.executionContext : {};
1850
+ const executionId = request.executionId ?? nested.executionId;
1851
+ required(executionId, "SDK_CAPABILITY_EXECUTION_ID_REQUIRED");
1852
+ const { executionContext: _legacyContext, ...directRequest } = request;
1853
+ return this.request(
1854
+ {
1855
+ method: "POST",
1856
+ path: "/v1/runtime/capabilities/resolve",
1857
+ body: { ...directRequest, executionId, attestationId }
1858
+ },
1859
+ { idempotencyKey: options.idempotencyKey, enforcing: true }
1860
+ );
1861
+ }
1862
+ recordCapabilityTrace(decisionDigest, trace, options = {}) {
1863
+ required(decisionDigest, "SDK_DECISION_DIGEST_REQUIRED");
1864
+ required(trace.id ?? trace.traceId, "SDK_CAPABILITY_TRACE_ID_REQUIRED");
1865
+ const ctx = trace.executionContext && typeof trace.executionContext === "object" ? trace.executionContext : {};
1866
+ required(trace.executionId ?? ctx.executionId, "SDK_CAPABILITY_TRACE_EXECUTION_REQUIRED");
1867
+ return this.request(
1868
+ {
1869
+ method: "POST",
1870
+ path: "/v1/runtime/capabilities/traces",
1871
+ body: { decisionDigest, trace }
1872
+ },
1873
+ { idempotencyKey: options.idempotencyKey }
1874
+ );
1875
+ }
1876
+ resolveModelServing(request, options = {}) {
1877
+ return this.request(
1878
+ { method: "POST", path: "/v1/model-serving/resolve", body: request },
1879
+ { idempotencyKey: options.idempotencyKey, enforcing: true }
1880
+ );
1881
+ }
1882
+ recordModelServingTrace(trace, selection, options = {}) {
1883
+ return this.request(
1884
+ {
1885
+ method: "POST",
1886
+ path: "/v1/model-serving/traces",
1887
+ body: { trace, selection }
1888
+ },
1889
+ { idempotencyKey: options.idempotencyKey }
1890
+ );
1891
+ }
1892
+ submitTeachEvidence(evidence, options = {}) {
1893
+ return this.request(
1894
+ { method: "POST", path: "/v1/teach/evidence", body: evidence },
1895
+ { idempotencyKey: options.idempotencyKey }
1896
+ );
1897
+ }
1898
+ submitTeachConversationEvidence(evidence, options = {}) {
1899
+ required(evidence.conversationId, "SDK_TEACH_CONVERSATION_ID_REQUIRED");
1900
+ required(evidence.message, "SDK_TEACH_CONVERSATION_MESSAGE_REQUIRED");
1901
+ if (evidence.consent !== true) throw new Error("SDK_TEACH_CONVERSATION_CONSENT_REQUIRED");
1902
+ return this.request({ method: "POST", path: "/v1/teach/conversations", body: { ...evidence, privacy: evidence.privacy ?? "CONSENTED_TENANT" } }, { idempotencyKey: options.idempotencyKey });
1903
+ }
1904
+ listConversationArchive(input = {}) {
1905
+ return this.request({ method: "GET", path: "/v1/teach/conversations", query: { ...input.limit === void 0 ? {} : { limit: String(input.limit) }, ...input.cursor ? { cursor: input.cursor } : {} } });
1906
+ }
1907
+ importConversationArchive(conversations, options = {}) {
1908
+ if (!Array.isArray(conversations) || !conversations.length) throw new Error("SDK_CONVERSATION_IMPORT_REQUIRED");
1909
+ return this.request({ method: "POST", path: "/v1/teach/conversations/import", body: { conversations: [...conversations] } }, { idempotencyKey: options.idempotencyKey });
1910
+ }
1911
+ revokeConversation(evidenceId, reason, options = {}) {
1912
+ required(evidenceId, "SDK_CONVERSATION_ID_REQUIRED");
1913
+ required(reason, "SDK_CONVERSATION_REVOCATION_REASON_REQUIRED");
1914
+ return this.request({ method: "POST", path: `/v1/teach/conversations/${encodeURIComponent(evidenceId)}/revoke`, body: { reason } }, { idempotencyKey: options.idempotencyKey });
1915
+ }
1916
+ createTeachAnalysis(evidenceIds, options = {}) {
1917
+ if (!Array.isArray(evidenceIds) || evidenceIds.length < 1) throw new Error("SDK_TEACH_ANALYSIS_EVIDENCE_REQUIRED");
1918
+ const body = { evidenceIds: [...evidenceIds] };
1919
+ if (options.analysisId) body.analysisId = options.analysisId;
1920
+ if (options.controlPointId) body.controlPointId = options.controlPointId;
1921
+ if (options.summary) body.summary = options.summary;
1922
+ const requestKey = JSON.stringify([evidenceIds, options.analysisId ?? "", options.controlPointId ?? "", options.summary ?? ""]);
1923
+ return this.request({ method: "POST", path: "/v1/teach/analyses", body }, { idempotencyKey: options.idempotencyKey ?? `sdk:teach:analysis:${requestKey}` });
1924
+ }
1925
+ getTeachAnalysis(analysisId) {
1926
+ required(analysisId, "SDK_TEACH_ANALYSIS_ID_REQUIRED");
1927
+ return this.request({ method: "GET", path: `/v1/teach/analyses/${encodeURIComponent(analysisId)}` });
1928
+ }
1929
+ listTeachAnalyses() {
1930
+ return this.request({ method: "GET", path: "/v1/teach/analyses" });
1931
+ }
1932
+ createCrossConversationTeachAnalysis(input, options = {}) {
1933
+ if (!Array.isArray(input.conversationRefs) || input.conversationRefs.length < 2) throw new Error("SDK_TEACH_CROSS_CONVERSATION_REFS_REQUIRED");
1934
+ const body = { conversationRefs: input.conversationRefs };
1935
+ if (input.analysisId) body.analysisId = input.analysisId;
1936
+ if (input.controlPointId) body.controlPointId = input.controlPointId;
1937
+ if (input.objective) body.objective = input.objective;
1938
+ return this.request({ method: "POST", path: "/v1/teach/cross-conversation-analyses", body }, { idempotencyKey: options.idempotencyKey ?? `sdk:teach:cross-conversation:${JSON.stringify(body)}` });
1939
+ }
1940
+ createTeachProposal(input, options = {}) {
1941
+ return this.request({ method: "POST", path: "/v1/teach/proposals", body: input }, { idempotencyKey: options.idempotencyKey });
1942
+ }
1943
+ getTeachRunBehaviorSet(teachRunId) {
1944
+ required(teachRunId, "SDK_TEACH_RUN_ID_REQUIRED");
1945
+ return this.request({ method: "GET", path: `/v1/teach/runs/${encodeURIComponent(teachRunId)}/behavior-set` });
1946
+ }
1947
+ listTeachRuns(input = {}) {
1948
+ return this.request({ method: "GET", path: "/v1/teach/runs", query: { ...input.limit === void 0 ? {} : { limit: String(input.limit) }, ...input.cursor ? { cursor: input.cursor } : {}, ...input.status ? { status: input.status } : {} } });
1949
+ }
1950
+ getTeachRunRecommendation(teachRunId) {
1951
+ required(teachRunId, "SDK_TEACH_RUN_ID_REQUIRED");
1952
+ return this.request({ method: "GET", path: `/v1/teach/runs/${encodeURIComponent(teachRunId)}/recommendation` });
1953
+ }
1954
+ acceptTeachRecommendation(teachRunId, actorId, options = {}) {
1955
+ required(teachRunId, "SDK_TEACH_RUN_ID_REQUIRED");
1956
+ required(actorId, "SDK_TEACH_RECOMMENDATION_ACTOR_REQUIRED");
1957
+ return this.request({ method: "POST", path: `/v1/teach/runs/${encodeURIComponent(teachRunId)}/recommendation/accept`, body: { actorId } }, { idempotencyKey: options.idempotencyKey ?? `sdk:teach:recommendation:accept:${teachRunId}` });
1958
+ }
1959
+ rejectTeachRecommendation(teachRunId, reason, options = {}) {
1960
+ required(teachRunId, "SDK_TEACH_RUN_ID_REQUIRED");
1961
+ required(reason, "SDK_TEACH_RECOMMENDATION_REASON_REQUIRED");
1962
+ return this.request({ method: "POST", path: `/v1/teach/runs/${encodeURIComponent(teachRunId)}/recommendation/reject`, body: { reason } }, { idempotencyKey: options.idempotencyKey ?? `sdk:teach:recommendation:reject:${teachRunId}` });
1963
+ }
1964
+ editTeachRecommendation(teachRunId, input, options = {}) {
1965
+ required(teachRunId, "SDK_TEACH_RUN_ID_REQUIRED");
1966
+ required(input?.revisionId, "SDK_TEACH_RECOMMENDATION_REVISION_ID_REQUIRED");
1967
+ required(input?.reason, "SDK_TEACH_RECOMMENDATION_REASON_REQUIRED");
1968
+ return this.request({ method: "POST", path: `/v1/teach/runs/${encodeURIComponent(teachRunId)}/recommendation/edit`, body: input }, { idempotencyKey: options.idempotencyKey ?? `sdk:teach:recommendation:edit:${input.revisionId}` });
1969
+ }
1970
+ transitionTeachProposal(proposalId, transition, input = {}, options = {}) {
1971
+ required(proposalId, "SDK_TEACH_PROPOSAL_ID_REQUIRED");
1972
+ return this.request({ method: "POST", path: `/v1/teach/proposals/${encodeURIComponent(proposalId)}/${transition}`, body: input }, { idempotencyKey: options.idempotencyKey ?? `sdk:teach:${transition}:${proposalId}` });
1973
+ }
1974
+ requestTeachProposalChanges(proposalId, feedback, options = {}) {
1975
+ required(proposalId, "SDK_TEACH_PROPOSAL_ID_REQUIRED");
1976
+ required(feedback, "SDK_TEACH_REQUEST_CHANGES_FEEDBACK_REQUIRED");
1977
+ return this.request({ method: "POST", path: `/v1/teach/proposals/${encodeURIComponent(proposalId)}/request-changes`, body: { feedback } }, { idempotencyKey: options.idempotencyKey ?? `sdk:teach:request-changes:${proposalId}:${feedback}` });
1978
+ }
1979
+ /** Start a standalone or comparative evaluation; use evaluatePack for Pack lifecycle evaluation. */
1980
+ startEvaluation(input, options = {}) {
1981
+ return this.request(
1982
+ { method: "POST", path: "/v1/evaluations", body: input },
1983
+ { idempotencyKey: options.idempotencyKey }
1984
+ );
1985
+ }
1986
+ /** Request a server-executed OFF/current-ON/candidate-ON comparison.
1987
+ * The server owns arm execution and receipts; callers cannot submit outputs.
1988
+ */
1989
+ startComparativeEvaluation(input, options = {}) {
1990
+ if (!input.comparisonPlan || typeof input.comparisonPlan !== "object")
1991
+ throw new Error("SDK_COMPARISON_PLAN_REQUIRED");
1992
+ return this.startEvaluation(input, options);
1993
+ }
1994
+ evaluateQuality(input, options = {}) {
1995
+ return this.request(
1996
+ { method: "POST", path: "/v1/quality/evaluate", body: input },
1997
+ { idempotencyKey: options.idempotencyKey }
1998
+ );
1999
+ }
2000
+ getEvaluation(evaluationId) {
2001
+ required(evaluationId, "SDK_EVALUATION_ID_REQUIRED");
2002
+ return this.request({
2003
+ method: "GET",
2004
+ path: `/v1/evaluations/${encodeURIComponent(evaluationId)}`
2005
+ });
2006
+ }
2007
+ listEvaluations(input = {}) {
2008
+ return this.request({ method: "GET", path: "/v1/evaluations", query: { ...input.limit === void 0 ? {} : { limit: String(input.limit) }, ...input.cursor ? { cursor: input.cursor } : {}, ...input.status ? { status: input.status } : {} } });
2009
+ }
2010
+ getEvaluationComparison(evaluationId) {
2011
+ required(evaluationId, "SDK_EVALUATION_ID_REQUIRED");
2012
+ return this.request({
2013
+ method: "GET",
2014
+ path: `/v1/evaluations/${encodeURIComponent(evaluationId)}/comparison`
2015
+ });
2016
+ }
2017
+ reviewComparativeFinding(evaluationId, findingId, input, options = {}) {
2018
+ required(evaluationId, "SDK_EVALUATION_ID_REQUIRED");
2019
+ required(findingId, "SDK_COMPARATIVE_FINDING_ID_REQUIRED");
2020
+ if (!["ACCEPT", "REJECT", "EDIT", "MORE_EVIDENCE"].includes(input?.decision)) throw new Error("SDK_COMPARATIVE_FINDING_DECISION_INVALID");
2021
+ return this.request({ method: "POST", path: `/v1/evaluations/${encodeURIComponent(evaluationId)}/comparison/findings/${encodeURIComponent(findingId)}/review`, body: { ...input } }, { idempotencyKey: options.idempotencyKey ?? `sdk:comparison:finding:${evaluationId}:${findingId}` });
2022
+ }
2023
+ createEvaluationPlan(input, options = {}) {
2024
+ return this.request({ method: "POST", path: "/v1/evaluation-plans", body: input }, { idempotencyKey: options.idempotencyKey });
2025
+ }
2026
+ getEvaluationPlan(planId) {
2027
+ required(planId, "SDK_EVALUATION_PLAN_ID_REQUIRED");
2028
+ return this.request({ method: "GET", path: `/v1/evaluation-plans/${encodeURIComponent(planId)}` });
2029
+ }
2030
+ sealEvaluationPlan(planId, options = {}) {
2031
+ required(planId, "SDK_EVALUATION_PLAN_ID_REQUIRED");
2032
+ return this.request({ method: "POST", path: `/v1/evaluation-plans/${encodeURIComponent(planId)}/seal`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:evaluation-plan:seal:${planId}` });
2033
+ }
2034
+ createImprovementProposal(evaluationId, input, options = {}) {
2035
+ required(evaluationId, "SDK_EVALUATION_ID_REQUIRED");
2036
+ return this.request({ method: "POST", path: `/v1/evaluations/${encodeURIComponent(evaluationId)}/improvement-proposal`, body: input }, { idempotencyKey: options.idempotencyKey });
2037
+ }
2038
+ getImprovementProposal(proposalId) {
2039
+ required(proposalId, "SDK_IMPROVEMENT_PROPOSAL_ID_REQUIRED");
2040
+ return this.request({ method: "GET", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}` });
2041
+ }
2042
+ reviewImprovementProposal(proposalId, action = "request-review", options = {}) {
2043
+ required(proposalId, "SDK_IMPROVEMENT_PROPOSAL_ID_REQUIRED");
2044
+ return this.request({ method: "POST", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}`, body: { action } }, { idempotencyKey: options.idempotencyKey ?? `sdk:improvement-proposal:${action}:${proposalId}` });
2045
+ }
2046
+ editImprovementProposalAsNew(proposalId, input, options = {}) {
2047
+ required(proposalId, "SDK_IMPROVEMENT_PROPOSAL_ID_REQUIRED");
2048
+ required(input?.id, "SDK_IMPROVEMENT_EDIT_ID_REQUIRED");
2049
+ required(input?.reason, "SDK_IMPROVEMENT_EDIT_REASON_REQUIRED");
2050
+ return this.request({ method: "POST", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}`, body: { ...input, action: "edit" } }, { idempotencyKey: options.idempotencyKey ?? `sdk:improvement-proposal:edit:${input.id}` });
2051
+ }
2052
+ createBehaviorRevisionCandidate(input, options = {}) {
2053
+ return this.request({ method: "POST", path: "/v1/behavior-revision-candidates", body: input }, { idempotencyKey: options.idempotencyKey });
2054
+ }
2055
+ evaluateBehaviorRevisionCandidate(candidateId, input, options = {}) {
2056
+ required(candidateId, "SDK_BEHAVIOR_CANDIDATE_ID_REQUIRED");
2057
+ if (!Array.isArray(input.dataset) || input.dataset.length === 0) throw new Error("SDK_CANDIDATE_EVALUATION_DATASET_REQUIRED");
2058
+ return this.request({ method: "POST", path: `/v1/behavior-revision-candidates/${encodeURIComponent(candidateId)}/evaluate`, body: input }, { idempotencyKey: options.idempotencyKey ?? `sdk:behavior-candidate:evaluate:${candidateId}` });
2059
+ }
2060
+ transitionBehaviorRevisionCandidate(candidateId, transition, input = {}, options = {}) {
2061
+ required(candidateId, "SDK_BEHAVIOR_CANDIDATE_ID_REQUIRED");
2062
+ return this.request({ method: "POST", path: `/v1/behavior-revision-candidates/${encodeURIComponent(candidateId)}/${transition}`, body: input }, { idempotencyKey: options.idempotencyKey ?? `sdk:behavior-candidate:${transition}:${candidateId}` });
2063
+ }
2064
+ createPackRevision(input, options = {}) {
2065
+ return this.request({ method: "POST", path: "/v1/pack-revisions", body: input }, { idempotencyKey: options.idempotencyKey });
2066
+ }
2067
+ getPackRevision(revisionId) {
2068
+ required(revisionId, "SDK_PACK_REVISION_ID_REQUIRED");
2069
+ return this.request({ method: "GET", path: `/v1/pack-revisions/${encodeURIComponent(revisionId)}` });
2070
+ }
2071
+ getPackRevisionDiff(revisionId) {
2072
+ required(revisionId, "SDK_PACK_REVISION_ID_REQUIRED");
2073
+ return this.request({ method: "GET", path: `/v1/pack-revisions/${encodeURIComponent(revisionId)}/diff` });
2074
+ }
2075
+ transitionPackRevision(revisionId, transition, options = {}) {
2076
+ required(revisionId, "SDK_PACK_REVISION_ID_REQUIRED");
2077
+ return this.request({ method: "POST", path: `/v1/pack-revisions/${encodeURIComponent(revisionId)}/${transition}`, body: {} }, { idempotencyKey: options.idempotencyKey ?? `sdk:pack-revision:${transition}:${revisionId}` });
2078
+ }
2079
+ materializePackRevision(revisionId, input, options = {}) {
2080
+ required(revisionId, "SDK_PACK_REVISION_ID_REQUIRED");
2081
+ return this.request({ method: "POST", path: `/v1/pack-revisions/${encodeURIComponent(revisionId)}/materialize`, body: input }, { idempotencyKey: options.idempotencyKey ?? `sdk:pack-revision:materialize:${revisionId}` });
2082
+ }
2083
+ createRelease(input, options = {}) {
2084
+ return this.request(
2085
+ { method: "POST", path: "/v1/releases", body: input },
2086
+ { idempotencyKey: options.idempotencyKey }
2087
+ );
2088
+ }
2089
+ createManualRelease(input, options = {}) {
2090
+ if (!input || typeof input !== "object" || !input.manualApproval) throw new Error("SDK_MANUAL_RELEASE_APPROVAL_REQUIRED");
2091
+ return this.createRelease(input, { idempotencyKey: options.idempotencyKey });
2092
+ }
2093
+ releaseProgramManually(input, options = {}) {
2094
+ required(input?.programId, "SDK_MANUAL_RELEASE_PROGRAM_REQUIRED");
2095
+ required(input?.reason, "SDK_MANUAL_RELEASE_REASON_REQUIRED");
2096
+ 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}` });
2097
+ }
2098
+ retireProgramPointer(pointerKey, input, options = {}) {
2099
+ required(pointerKey, "SDK_PROMOTION_POINTER_KEY_REQUIRED");
2100
+ if (input?.confirm !== true) throw new Error("SDK_PROMOTION_POINTER_RETIRE_CONFIRMATION_REQUIRED");
2101
+ if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1) throw new Error("SDK_PROMOTION_POINTER_VERSION_INVALID");
2102
+ if (typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 500) throw new Error("SDK_PROMOTION_POINTER_RETIRE_REASON_INVALID");
2103
+ 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}` });
2104
+ }
2105
+ recordDeploymentComparison(deploymentId, comparison, options = {}) {
2106
+ required(deploymentId, "SDK_DEPLOYMENT_ID_REQUIRED");
2107
+ return this.request(
2108
+ {
2109
+ method: "POST",
2110
+ path: `/v1/deployments/${encodeURIComponent(deploymentId)}/comparisons`,
2111
+ body: comparison
2112
+ },
2113
+ { idempotencyKey: options.idempotencyKey }
2114
+ );
2115
+ }
2116
+ recordDeploymentHealth(deploymentId, health, options = {}) {
2117
+ required(deploymentId, "SDK_DEPLOYMENT_ID_REQUIRED");
2118
+ return this.request(
2119
+ {
2120
+ method: "POST",
2121
+ path: `/v1/deployments/${encodeURIComponent(deploymentId)}/authoritative-health`,
2122
+ body: health
2123
+ },
2124
+ { idempotencyKey: options.idempotencyKey }
2125
+ );
2126
+ }
2127
+ async compileBehaviorCapsule(input) {
2128
+ required(input.programId, "SDK_PROGRAM_ID_REQUIRED");
2129
+ required(input.input, "SDK_RUNTIME_INPUT_REQUIRED");
2130
+ const body = { ...input };
2131
+ return this.request(
2132
+ {
2133
+ method: "POST",
2134
+ path: "/v1/runtime/behavior-capsule",
2135
+ body
2136
+ },
2137
+ {
2138
+ idempotencyKey: input.idempotencyKey ?? await contentIdempotencyKey(`sdk:capsule:${input.programId}`, body),
2139
+ enforcing: true
2140
+ }
2141
+ );
2142
+ }
2143
+ async serveBehaviorProjection(input) {
2144
+ required(input.input, "SDK_RUNTIME_INPUT_REQUIRED");
2145
+ required(input.provider, "SDK_PROVIDER_REQUIRED");
2146
+ const body = { ...input };
2147
+ return this.request(
2148
+ {
2149
+ method: "POST",
2150
+ path: "/v1/runtime/behavior-projection",
2151
+ body
2152
+ },
2153
+ {
2154
+ idempotencyKey: input.idempotencyKey ?? await contentIdempotencyKey(`sdk:projection:${input.programId ?? "active"}`, body),
2155
+ enforcing: true
2156
+ }
2157
+ );
2158
+ }
2159
+ async testConnection(connectionId) {
2160
+ required(connectionId, "SDK_CONNECTION_ID_REQUIRED");
2161
+ return this.request({
2162
+ method: "POST",
2163
+ path: `/v1/connections/${encodeURIComponent(connectionId)}/test`,
2164
+ body: {}
2165
+ });
2166
+ }
2167
+ listAISystemUnitGrants(aiSystemId) {
2168
+ if (!aiSystemId.trim()) throw new Error("SDK_AI_SYSTEM_ID_REQUIRED");
2169
+ return this.request({ method: "GET", path: `/v1/ai-systems/${encodeURIComponent(aiSystemId)}/unit-grants` });
2170
+ }
2171
+ grantAISystemUnitAccess(aiSystemId, input, options = {}) {
2172
+ if (!aiSystemId.trim() || !input.unitId.trim()) throw new Error("SDK_AI_SYSTEM_UNIT_GRANT_REQUIRED");
2173
+ if (!input.permissions.length) throw new Error("SDK_AI_SYSTEM_UNIT_PERMISSIONS_REQUIRED");
2174
+ 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 });
2175
+ }
2176
+ revokeAISystemUnitAccess(aiSystemId, unitId, options = {}) {
2177
+ if (!aiSystemId.trim() || !unitId.trim()) throw new Error("SDK_AI_SYSTEM_UNIT_GRANT_REQUIRED");
2178
+ 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 });
2179
+ }
2180
+ listVerifiedHostInvocationResults(systemId, input = {}) {
2181
+ required(systemId, "SDK_AI_SYSTEM_ID_REQUIRED");
2182
+ return this.request({ method: "POST", path: `/v1/ai-systems/${encodeURIComponent(systemId)}/clone-cutover/route/reconcile/host-candidates`, body: input }, { enforcing: true });
2183
+ }
2184
+ freezeDepartmentOptimizationDataset(input) {
2185
+ return this.request({ method: "POST", path: "/v1/optimization/dataset-freeze", body: input }, { enforcing: true });
2186
+ }
2187
+ listDepartmentOptimizationDatasets(input) {
2188
+ return this.request({ method: "POST", path: "/v1/optimization/dataset-options", body: input }, { enforcing: true });
2189
+ }
2190
+ prepareFrozenOptimizationRun(input, options = {}) {
2191
+ return this.request({ method: "POST", path: "/v1/optimization/prepare-frozen", body: input }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2192
+ }
2193
+ executeFrozenOptimizationRun(input, options = {}) {
2194
+ return this.request({ method: "POST", path: "/v1/optimization/execute-frozen", body: input }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2195
+ }
2196
+ proposeNativePolicyScenarios(input) {
2197
+ return this.request({ method: "POST", path: "/v1/evaluations/policy-scenarios", body: input }, { enforcing: true });
2198
+ }
2199
+ previewNativePolicyScenarios(input) {
2200
+ return this.request({ method: "POST", path: "/v1/evaluations/policy-preview", body: input }, { enforcing: true });
2201
+ }
2202
+ admitNativeEvaluationTeachFeedback(evaluationId, input, options = {}) {
2203
+ required(evaluationId, "SDK_EVALUATION_ID_REQUIRED");
2204
+ return this.request({ method: "POST", path: `/v1/evaluations/${encodeURIComponent(evaluationId)}/teach-feedback`, body: input }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2205
+ }
2206
+ previewNativeTeachDraftRevision(proposalId, input) {
2207
+ required(proposalId, "SDK_PROPOSAL_ID_REQUIRED");
2208
+ return this.request({ method: "POST", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}/native-draft-preview`, body: input }, { enforcing: true });
2209
+ }
2210
+ applyNativeTeachDraftRevision(proposalId, input, options = {}) {
2211
+ required(proposalId, "SDK_PROPOSAL_ID_REQUIRED");
2212
+ return this.request({ method: "POST", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}/native-draft-apply`, body: input }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2213
+ }
2214
+ compareNativeTeachRevision(input) {
2215
+ return this.request({ method: "POST", path: "/v1/evaluations/native-revision-comparison", body: input }, { enforcing: true });
2216
+ }
2217
+ getNativeTeachRevisionHistory(proposalId) {
2218
+ required(proposalId, "SDK_PROPOSAL_ID_REQUIRED");
2219
+ return this.request({ method: "GET", path: `/v1/behavior-improvement-proposals/${encodeURIComponent(proposalId)}/native-draft-history` });
2220
+ }
2221
+ getNativeRevisionComparisonSource(candidatePackId) {
2222
+ required(candidatePackId, "SDK_CANDIDATE_PACK_ID_REQUIRED");
2223
+ return this.request({ method: "GET", path: `/v1/evaluations/native-revision-source/${encodeURIComponent(candidatePackId)}` });
2224
+ }
2225
+ listStrategyConnectionOptions(input) {
2226
+ required(input.aiSystemId, "SDK_AI_SYSTEM_ID_REQUIRED");
2227
+ return this.request({ method: "GET", path: "/v1/task-runs/strategy-connections/options", query: { aiSystemId: input.aiSystemId } });
2228
+ }
2229
+ listOptimizationReviewOptions(input) {
2230
+ return this.request({ method: "POST", path: "/v1/optimization/review-options", body: input }, { enforcing: true });
2231
+ }
2232
+ listOptimizerEvaluationHistory(runId) {
2233
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
2234
+ return this.request({ method: "GET", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/evaluation-history` });
2235
+ }
2236
+ previewOptimizerStrategyPromotion(runId, input, options = {}) {
2237
+ required(runId, "SDK_OPTIMIZATION_RUN_ID_REQUIRED");
2238
+ return this.request({ method: "POST", path: `/v1/optimization/runs/${encodeURIComponent(runId)}/promote-preview`, body: input }, { idempotencyKey: options.idempotencyKey, enforcing: true });
2239
+ }
2240
+ };
2241
+ function buildRuntimeRequest(input, options = {}) {
2242
+ const {
2243
+ organizationId,
2244
+ projectId,
2245
+ environmentId,
2246
+ revisionId,
2247
+ idempotencyKey,
2248
+ nonce,
2249
+ expiresAt,
2250
+ decisionPlanId,
2251
+ calibrationId,
2252
+ candidates,
2253
+ allowedIds,
2254
+ policy,
2255
+ postModelJudge,
2256
+ shadow
2257
+ } = input;
2258
+ for (const value of [
2259
+ organizationId,
2260
+ projectId,
2261
+ environmentId,
2262
+ revisionId,
2263
+ idempotencyKey,
2264
+ nonce
2265
+ ])
2266
+ if (typeof value !== "string" || !value.trim())
2267
+ throw new Error("SDK_REQUEST_FIELD_REQUIRED");
2268
+ if (!Number.isFinite(expiresAt)) throw new Error("SDK_EXPIRY_REQUIRED");
2269
+ if (Object.prototype.hasOwnProperty.call(input, "stagedRoutePin") || Object.prototype.hasOwnProperty.call(input, "runtimeRoutePin"))
2270
+ throw new Error("SDK_RUNTIME_ROUTE_PIN_CALLER_FORBIDDEN");
2271
+ const validation = input.cutoverRouteValidation;
2272
+ if (validation !== void 0 && !options.allowStagedValidation)
2273
+ throw new Error("SDK_RUNTIME_STAGED_VALIDATION_UNSUPPORTED_ROUTE");
2274
+ const pair = input.aiSystemId !== void 0 || input.connectionId !== void 0;
2275
+ 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()))
2276
+ throw new Error("SDK_RUNTIME_AI_IDENTITY_PAIR_REQUIRED");
2277
+ if (validation !== void 0) {
2278
+ if (!options.includeAIIdentity || !pair)
2279
+ throw new Error("SDK_RUNTIME_AI_IDENTITY_PAIR_REQUIRED");
2280
+ if (!validation || typeof validation !== "object" || Array.isArray(validation))
2281
+ throw new Error("SDK_RUNTIME_STAGED_VALIDATION_INVALID");
2282
+ const v = validation;
2283
+ 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)
2284
+ throw new Error("SDK_RUNTIME_STAGED_VALIDATION_INVALID");
2285
+ }
2286
+ const boundary = {
2287
+ ...typeof decisionPlanId === "string" ? { decisionPlanId } : {},
2288
+ ...typeof calibrationId === "string" ? { calibrationId } : {},
2289
+ ...Array.isArray(candidates) ? { candidates } : {},
2290
+ ...Array.isArray(allowedIds) ? { allowedIds } : {},
2291
+ ...typeof policy === "string" ? { policy } : {},
2292
+ ...postModelJudge !== void 0 ? { postModelJudge } : {},
2293
+ ...shadow !== void 0 ? { shadow } : {}
2294
+ };
2295
+ return Object.freeze({
2296
+ organizationId,
2297
+ projectId,
2298
+ environmentId,
2299
+ revisionId,
2300
+ idempotencyKey,
2301
+ nonce,
2302
+ expiresAt,
2303
+ ...boundary,
2304
+ ...options.includeAIIdentity && pair ? { aiSystemId: input.aiSystemId, connectionId: input.connectionId } : {},
2305
+ ...validation !== void 0 ? { cutoverRouteValidation: validation } : {}
2306
+ });
2307
+ }
2308
+ function buildAISystemRequest(input) {
2309
+ const { name, systemType, organizationId, projectId, environmentId } = input;
2310
+ for (const value of [
2311
+ name,
2312
+ systemType,
2313
+ organizationId,
2314
+ projectId,
2315
+ environmentId
2316
+ ])
2317
+ if (typeof value !== "string" || !value.trim())
2318
+ throw new Error("SDK_AI_SYSTEM_FIELD_REQUIRED");
2319
+ return Object.freeze({
2320
+ method: "POST",
2321
+ path: "/v1/ai-systems",
2322
+ body: Object.freeze({
2323
+ name,
2324
+ systemType,
2325
+ organizationId,
2326
+ projectId,
2327
+ environmentId
2328
+ })
2329
+ });
2330
+ }
2331
+ function buildObservationRequest(event) {
2332
+ if (!event?.organizationId?.trim() || !event?.projectId?.trim() || !event?.environmentId?.trim())
2333
+ throw new Error("SDK_OBSERVATION_SCOPE_REQUIRED");
2334
+ if (!event?.eventId || !event.eventType || !event.aiSystemId || !event.connectionId)
2335
+ throw new Error("SDK_OBSERVATION_FIELD_REQUIRED");
2336
+ const safeEvent = event;
2337
+ return Object.freeze({
2338
+ method: "POST",
2339
+ path: "/v1/observations",
2340
+ body: Object.freeze({ ...safeEvent })
2341
+ });
2342
+ }
2343
+
2344
+ // ../../sdks/host-taskrun-handoff.ts
2345
+ import { createHash } from "node:crypto";
2346
+ var record = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
2347
+ var nonempty = (v) => typeof v === "string" && v.length > 0 && v === v.trim();
2348
+ var hex = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v) && v !== "0".repeat(64);
2349
+ var statuses = ["PLANNED", "ADMITTED", "RUNNING", "WAITING_USER", "WAITING_HOST", "WAITING_APPROVAL", "PARTIAL", "COMPLETED", "FAILED", "BLOCKED", "CANCELLED"];
2350
+ function readHostTaskRunState(response, expected, admission = false) {
2351
+ const envelope = record(response), body = record(envelope.body), run = record(body.taskRun);
2352
+ if (envelope.status !== (admission ? 201 : 200) || admission && body.proposalOnly !== false || run.taskRunId !== expected.taskRunId || run.aiSystemId !== expected.aiSystemId || run.conversationId !== expected.conversationId || ["organizationId", "projectId", "environmentId", "organizationUnitId"].some((key) => run[key] !== expected[key]) || !nonempty(run.requestId) || expected.requestId !== void 0 && run.requestId !== expected.requestId || !Number.isSafeInteger(run.stateVersion) || Number(run.stateVersion) < (expected.minimumVersion ?? 0) || !hex(run.planDigest) || !hex(run.authorityDigest) || expected.planDigest !== void 0 && run.planDigest !== expected.planDigest || expected.authorityDigest !== void 0 && run.authorityDigest !== expected.authorityDigest || !["COMPOUND", "HYBRID"].includes(String(run.mode)) || expected.mode !== void 0 && run.mode !== expected.mode || !statuses.includes(run.status)) throw Error("HOST_TASKRUN_HANDOFF_EVIDENCE_INVALID");
2353
+ if (expected.status !== void 0 && run.stateVersion === expected.minimumVersion && run.status !== expected.status) throw Error("HOST_TASKRUN_HANDOFF_EVIDENCE_INVALID");
2354
+ const tasks = run.selectedTaskKeys;
2355
+ if (!Array.isArray(tasks) || tasks.length < 2 || tasks.some((t) => !nonempty(t)) || new Set(tasks).size !== tasks.length || expected.selectedTaskKeys !== void 0 && (tasks.length !== expected.selectedTaskKeys.length || expected.selectedTaskKeys.some((t) => !tasks.includes(t)))) throw Error("HOST_TASKRUN_HANDOFF_TASK_SET_MISMATCH");
2356
+ if (admission && run.status !== "ADMITTED") throw Error("HOST_TASKRUN_NOT_ADMITTED");
2357
+ const checkpoint = record(run.checkpoint), checkpointExecutionDigest = checkpoint.executionDigest;
2358
+ if (checkpointExecutionDigest !== void 0 && !hex(checkpointExecutionDigest)) throw Error("HOST_TASKRUN_HANDOFF_EVIDENCE_INVALID");
2359
+ if (!admission && run.stateVersion === expected.minimumVersion && Object.hasOwn(expected, "checkpointExecutionDigest") && checkpointExecutionDigest !== expected.checkpointExecutionDigest) throw Error("HOST_TASKRUN_HANDOFF_EVIDENCE_INVALID");
2360
+ return { taskRunId: expected.taskRunId, requestId: run.requestId, stateVersion: Number(run.stateVersion), mode: run.mode, status: run.status, planDigest: run.planDigest, authorityDigest: run.authorityDigest, selectedTaskKeys: tasks, checkpointExecutionDigest };
2361
+ }
2362
+ function hostTaskRunTerminal(status) {
2363
+ return ["COMPLETED", "FAILED", "BLOCKED", "CANCELLED", "PARTIAL"].includes(status);
2364
+ }
2365
+ function readHostTaskRunTerminalEvidence(response, run) {
2366
+ const envelope = record(response), evidence = record(record(envelope.body).evidence);
2367
+ if (!hostTaskRunTerminal(run.status) || envelope.status !== 200 || evidence.source !== "postgres-taskrun-strategy-release-credit-evidence" || evidence.taskRunId !== run.taskRunId || evidence.organizationUnitId !== run.organizationUnitId || evidence.aiSystemId !== run.aiSystemId || evidence.mode !== run.mode || evidence.status !== run.status || evidence.stateVersion !== run.stateVersion || evidence.planDigest !== run.planDigest || evidence.authorityDigest !== run.authorityDigest || evidence.checkpointExecutionDigest !== (run.checkpointExecutionDigest ?? null) || run.status === "COMPLETED" && !hex(run.checkpointExecutionDigest)) throw Error("HOST_TASKRUN_TERMINAL_EVIDENCE_INVALID");
2368
+ return Object.freeze({ taskRunId: run.taskRunId, stateVersion: run.stateVersion, mode: run.mode, status: run.status, planDigest: run.planDigest, authorityDigest: run.authorityDigest, checkpointExecutionDigest: run.checkpointExecutionDigest ?? null, outputAvailable: false, clientExecutionAllowed: false });
2369
+ }
2370
+ function readHostTaskRunResult(response, run) {
2371
+ const terminal = readHostTaskRunTerminalEvidence(response, run), result = record(record(record(response).body).result);
2372
+ const fail = () => {
2373
+ throw Error("HOST_TASKRUN_RESULT_INVALID");
2374
+ };
2375
+ if (terminal.status !== "COMPLETED" || result.status !== "COMPLETED" || result.clientExecutionAllowed !== false || ["taskRunId", "requestId", "organizationId", "projectId", "environmentId", "organizationUnitId", "aiSystemId", "conversationId", "mode", "stateVersion", "planDigest", "authorityDigest", "checkpointExecutionDigest"].some((key) => result[key] !== run[key]) || !hex(result.resultDigest) || !Array.isArray(result.outputs) || !result.outputs.length) fail();
2376
+ const hash = (value) => createHash("sha256").update(JSON.stringify(value, (_, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)).digest("hex");
2377
+ const { resultDigest, ...body } = result;
2378
+ if (hash(body) !== resultDigest) fail();
2379
+ const evidence = record(record(record(response).body).evidence);
2380
+ if (!Array.isArray(evidence.children) || evidence.children.length !== result.outputs.length) throw Error("HOST_TASKRUN_RESULT_INVALID");
2381
+ const nodes = /* @__PURE__ */ new Set(), ids = /* @__PURE__ */ new Set();
2382
+ const outputs = result.outputs.map((value) => {
2383
+ const child = record(value);
2384
+ if (!nonempty(child.nodeKey) || !nonempty(child.semanticTaskKey) || !nonempty(child.receiptId) || nodes.has(child.nodeKey) || ids.has(child.receiptId) || !hex(child.outputDigest) || !Object.hasOwn(child, "output") || child.output === void 0 || child.output === null || hash(child.output) !== child.outputDigest) throw Error("HOST_TASKRUN_RESULT_INVALID");
2385
+ const matching = evidence.children.map(record).filter((item) => item.nodeKey === child.nodeKey);
2386
+ if (matching.length !== 1 || matching[0].semanticTaskKey !== child.semanticTaskKey || matching[0].receiptId !== child.receiptId || matching[0].status !== "COMPLETED" || matching[0].scopeEvidenceStatus !== "VERIFIED" || matching[0].outputDigest !== child.outputDigest) throw Error("HOST_TASKRUN_RESULT_INVALID");
2387
+ nodes.add(child.nodeKey);
2388
+ ids.add(child.receiptId);
2389
+ return { nodeKey: child.nodeKey, semanticTaskKey: child.semanticTaskKey, receiptId: child.receiptId, outputDigest: child.outputDigest, output: structuredClone(child.output) };
2390
+ });
2391
+ if (run.mode === "COMPOUND" ? outputs.length !== 1 || outputs[0].nodeKey !== "compound-plan" : outputs.length !== run.selectedTaskKeys.length || new Set(outputs.map((child) => child.semanticTaskKey)).size !== outputs.length || outputs.some((child) => !run.selectedTaskKeys.includes(child.semanticTaskKey))) fail();
2392
+ return Object.freeze({ ...terminal, outputAvailable: true, resultDigest, outputs });
2393
+ }
2394
+
2395
+ // src/tui-result.ts
2396
+ var isHostResultId = (value) => typeof value === "string" && /^host-task-run-host-turn:[a-f0-9]{64}$/.test(value);
2397
+ async function readTuiTaskRunResult(client, identity, id, active) {
2398
+ if (!isHostResultId(id) || Object.values(identity).some((value) => typeof value !== "string" || !value.trim() || value.trim() !== value) || identity.sessionId !== identity.conversationId || !active()) throw Error("OPENCODE_TUI_RESULT_SCOPE_REQUIRED");
2399
+ const state = readHostTaskRunState(await client.getTaskRun(id), { ...identity, taskRunId: id, requestId: id.slice("host-task-run-".length) });
2400
+ if (!active()) throw Error("OPENCODE_TUI_RESULT_SESSION_CHANGED");
2401
+ if (state.status !== "COMPLETED") return { status: state.status, outputAvailable: false };
2402
+ const run = { ...identity, ...state };
2403
+ const result = readHostTaskRunResult(await client.getTaskRunEvidence(id, { includeResult: true }), run);
2404
+ if (!active()) throw Error("OPENCODE_TUI_RESULT_SESSION_CHANGED");
2405
+ const current = readHostTaskRunState(await client.getTaskRun(id), { ...run, minimumVersion: run.stateVersion });
2406
+ if (!active() || current.stateVersion !== run.stateVersion || current.status !== run.status || current.checkpointExecutionDigest !== run.checkpointExecutionDigest) throw Error("OPENCODE_TUI_RESULT_STATE_CHANGED");
2407
+ return result;
2408
+ }
2409
+ function formatTuiResult(outputs) {
2410
+ return outputs.map((child) => typeof child.output === "string" ? child.output : JSON.stringify(child.output, null, 2)).join("\n\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "");
2411
+ }
2412
+
2413
+ // src/tui-result-selection.ts
2414
+ var record2 = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
2415
+ var valid = (v) => typeof v === "string" && v.length > 0 && v.length <= 256 && v === v.trim();
2416
+ async function selectSessionTaskRun(client, identity, active) {
2417
+ if (!valid(identity.aiSystemId) || !valid(identity.sessionId) || identity.sessionId !== identity.conversationId || !active()) return;
2418
+ const response = record2(await client.listTaskRuns({ limit: 100, aiSystemId: identity.aiSystemId, conversationId: identity.conversationId }));
2419
+ if (!active()) return;
2420
+ const body = record2(response.body), selection = record2(body.sessionSelection);
2421
+ if (response.status !== 200 || body.partial !== false || body.nextCursor !== void 0 || selection.aiSystemId !== identity.aiSystemId || selection.conversationId !== identity.conversationId || !Array.isArray(body.taskRuns) || body.taskRuns.length > 100) return;
2422
+ const ids = /* @__PURE__ */ new Set();
2423
+ let selected;
2424
+ for (const item of body.taskRuns) {
2425
+ const row = record2(item);
2426
+ if (!valid(row.taskRunId) || row.aiSystemId !== identity.aiSystemId || ids.has(row.taskRunId)) return;
2427
+ ids.add(row.taskRunId);
2428
+ if (!/^host-task-run-host-turn:[a-f0-9]{64}$/.test(row.taskRunId)) continue;
2429
+ if (row.mode !== "COMPOUND" && row.mode !== "HYBRID") return;
2430
+ if (selected !== void 0) return;
2431
+ selected = row.taskRunId;
2432
+ }
2433
+ return selected;
2434
+ }
2435
+
2436
+ // src/tui-entry.ts
2437
+ var val = (value) => typeof value === "string" ? value.trim() : "";
2438
+ var tui_entry_default = { id: "vira.cli", setup(context) {
2439
+ let busy = false, disposed = false;
2440
+ const get = (key, env) => val(context.options?.[key]) || val(process.env[env]);
2441
+ const run = async (argument) => {
2442
+ if (busy || disposed) return;
2443
+ busy = true;
2444
+ try {
2445
+ const session = context.ui.router.current();
2446
+ if (session.type !== "session" || !session.sessionID) throw Error("SESSION_REQUIRED");
2447
+ const sessionID = session.sessionID, active = () => {
2448
+ const current = context.ui.router.current();
2449
+ return !disposed && current.type === "session" && current.sessionID === sessionID;
2450
+ };
2451
+ const identity = { organizationId: get("organizationId", "VIRA_ORGANIZATION_ID"), projectId: get("projectId", "VIRA_PROJECT_ID"), environmentId: get("environmentId", "VIRA_ENVIRONMENT_ID"), organizationUnitId: get("organizationUnitId", "VIRA_ORGANIZATION_UNIT_ID"), aiSystemId: get("aiSystemId", "VIRA_AI_SYSTEM_ID"), conversationId: sessionID, sessionId: sessionID };
2452
+ const baseUrl = get("apiUrl", "VIRA_CONTROL_URL") || val(process.env.VIRA_API_URL), apiKey = get("apiKey", "VIRA_API_KEY");
2453
+ if (!baseUrl || !apiKey || Object.values(identity).some((value) => !value)) throw Error("CONFIGURATION_REQUIRED");
2454
+ const client = new ViraClient({ baseUrl, apiKey, organizationUnitId: identity.organizationUnitId, retries: 0, timeoutMs: 15e3 });
2455
+ let id = val(argument);
2456
+ if (!id) {
2457
+ try {
2458
+ id = await selectSessionTaskRun(client, identity, active) ?? "";
2459
+ } catch {
2460
+ }
2461
+ if (!active()) return;
2462
+ if (!id) id = val(await context.ui.dialog.prompt({ title: "Vira TaskRun result \xB7 choose exact reference", placeholder: "host-task-run-host-turn:\u2026" }));
2463
+ }
2464
+ if (!id || !active()) return;
2465
+ if (!isHostResultId(id)) throw Error("INVALID_REFERENCE");
2466
+ const result = await readTuiTaskRunResult(client, identity, id, active);
2467
+ if (!active()) return;
2468
+ if (!result.outputAvailable) {
2469
+ await context.ui.dialog.alert({ title: "Vira TaskRun status", message: result.status + " \xB7 No verified completed result yet." });
2470
+ return;
2471
+ }
2472
+ const message = formatTuiResult(result.outputs);
2473
+ const chars = Array.from(message), pageSize = 6e3, pages = Math.max(1, Math.ceil(chars.length / pageSize));
2474
+ for (let i = 0; i < pages && active(); i++) await context.ui.dialog.alert({ title: "Vira verified result \xB7 " + (i + 1) + "/" + pages, message: chars.slice(i * pageSize, (i + 1) * pageSize).join("") || "(empty output)" });
2475
+ } catch {
2476
+ if (!disposed) await context.ui.dialog.alert({ title: "Vira result unavailable", message: "Open the original session and check the TaskRun reference, department, AI System and owner credential. No model or action was executed." });
2477
+ } finally {
2478
+ busy = false;
2479
+ }
2480
+ };
2481
+ context.keymap.layer(() => ({ mode: "global", commands: [{ id: "vira.result", title: "Read verified Vira TaskRun result", group: "Vira", palette: true, slash: { name: "vira-result", arguments: true }, run }] }));
2482
+ return () => {
2483
+ disposed = true;
2484
+ };
2485
+ } };
2486
+ export {
2487
+ tui_entry_default as default
2488
+ };