@gravity-rail/sdk 3.2.0 → 6.0.0
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/README.md +20 -3
- package/dist/account-CSJJbLIj.d.cts +459 -0
- package/dist/account-CSJJbLIj.d.ts +459 -0
- package/dist/{path-ChuuGGLG.d.ts → agent_standing_job-CqKpMoHO.d.cts} +1099 -153
- package/dist/{path-CXnjBalr.d.cts → agent_standing_job-yehTe972.d.ts} +1099 -153
- package/dist/{chat-interaction-Cc9hQNyx.d.ts → chat-interaction-BtUtVszg.d.ts} +14107 -9967
- package/dist/{chat-interaction-CoHsIqyX.d.cts → chat-interaction-CAfwlYvv.d.cts} +14107 -9967
- package/dist/{chunk-MAPAZORN.js → chunk-L4XC6KDG.js} +1940 -605
- package/dist/chunk-L4XC6KDG.js.map +1 -0
- package/dist/{chunk-D5VNVTUQ.js → chunk-P2MSMMMJ.js} +120 -2
- package/dist/chunk-P2MSMMMJ.js.map +1 -0
- package/dist/{chunk-RLFS7O2L.js → chunk-P2X5TOYY.js} +211 -83
- package/dist/chunk-P2X5TOYY.js.map +1 -0
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts +3 -2
- package/dist/helpers.d.ts +3 -2
- package/dist/helpers.js +1 -1
- package/dist/index.cjs +2309 -1146
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +87 -249
- package/dist/index.d.ts +87 -249
- package/dist/index.js +171 -458
- package/dist/index.js.map +1 -1
- package/dist/internal.cjs +2333 -710
- package/dist/internal.cjs.map +1 -1
- package/dist/internal.d.cts +2486 -285
- package/dist/internal.d.ts +2486 -285
- package/dist/internal.js +158 -31
- package/dist/internal.js.map +1 -1
- package/dist/{member-import-BWyl88Qx.d.ts → member-import-C5nnoGvW.d.ts} +1 -1
- package/dist/{member-import-9h52_4KO.d.cts → member-import-DhaNVT7s.d.cts} +1 -1
- package/dist/realtime.cjs +250 -3
- package/dist/realtime.cjs.map +1 -1
- package/dist/realtime.d.cts +87 -4
- package/dist/realtime.d.ts +87 -4
- package/dist/realtime.js +245 -3
- package/dist/realtime.js.map +1 -1
- package/dist/schemas.cjs +156 -23
- package/dist/schemas.cjs.map +1 -1
- package/dist/schemas.d.cts +623 -72
- package/dist/schemas.d.ts +623 -72
- package/dist/schemas.js +74 -25
- package/dist/schemas.js.map +1 -1
- package/dist/{tasks-B7tIHQcS.d.cts → tasks-A12E_RLa.d.cts} +2275 -2043
- package/dist/{tasks-B7tIHQcS.d.ts → tasks-DrmyOlRh.d.ts} +2275 -2043
- package/dist/{types-BXaWYGHj.d.cts → types-Bv6GtLZ2.d.cts} +25 -2
- package/dist/{types-BXaWYGHj.d.ts → types-Bv6GtLZ2.d.ts} +25 -2
- package/package.json +5 -5
- package/dist/chunk-D5VNVTUQ.js.map +0 -1
- package/dist/chunk-MAPAZORN.js.map +0 -1
- package/dist/chunk-RLFS7O2L.js.map +0 -1
|
@@ -55,21 +55,20 @@ function parseOrgAuthChallenge(wwwAuthenticate) {
|
|
|
55
55
|
if (!wwwAuthenticate.includes('realm="org"')) return null;
|
|
56
56
|
const orgUuidMatch = wwwAuthenticate.match(/org_uuid="([^"]+)"/);
|
|
57
57
|
const authUrlMatch = wwwAuthenticate.match(/auth_url="([^"]+)"/);
|
|
58
|
+
const acrValues = wwwAuthenticate.match(/acr_values="([^"]*)"/)?.[1]?.trim().split(/\s+/).filter(Boolean);
|
|
58
59
|
if (!orgUuidMatch?.[1] || !authUrlMatch?.[1]) {
|
|
59
60
|
console.warn("Invalid org auth challenge header: missing required fields");
|
|
60
61
|
return null;
|
|
61
62
|
}
|
|
62
63
|
return {
|
|
63
64
|
orgUuid: orgUuidMatch[1],
|
|
64
|
-
authUrl: authUrlMatch[1]
|
|
65
|
+
authUrl: authUrlMatch[1],
|
|
66
|
+
...acrValues?.length ? { acrValues } : {}
|
|
65
67
|
};
|
|
66
68
|
}
|
|
67
|
-
function orgAuthHeaderName(token) {
|
|
68
|
-
return token.startsWith("gr_sess_") ? "X-Org-Session" : "X-Org-Token";
|
|
69
|
-
}
|
|
70
69
|
function setOrgAuthHeader(headers, token) {
|
|
71
70
|
if (!token) return;
|
|
72
|
-
headers.set(
|
|
71
|
+
headers.set("X-Org-Session", token);
|
|
73
72
|
}
|
|
74
73
|
var BaseApiClient = class {
|
|
75
74
|
baseUrl;
|
|
@@ -80,13 +79,13 @@ var BaseApiClient = class {
|
|
|
80
79
|
enhancedAuthInProgress = null;
|
|
81
80
|
orgAuthHandler;
|
|
82
81
|
orgAuthInProgress = null;
|
|
82
|
+
orgSessionRevision = 0;
|
|
83
|
+
orgSessionRejectionHandler;
|
|
83
84
|
orgSession;
|
|
84
85
|
/**
|
|
85
|
-
*
|
|
86
|
-
* a
|
|
87
|
-
*
|
|
88
|
-
* `!this.orgSession` would prevent re-auth across orgs and surface as a silent
|
|
89
|
-
* 401 in multi-org CLI workflows.
|
|
86
|
+
* Optional issuer context supplied with an opaque credential. A handler
|
|
87
|
+
* cannot complete a challenge with a session explicitly bound to another org.
|
|
88
|
+
* The server remains responsible for validating the credential itself.
|
|
90
89
|
*/
|
|
91
90
|
orgSessionOrgUuid;
|
|
92
91
|
constructor(apiKey, baseUrl, customFetch) {
|
|
@@ -121,24 +120,25 @@ var BaseApiClient = class {
|
|
|
121
120
|
}
|
|
122
121
|
/**
|
|
123
122
|
* Set the opaque org session credential a bearer client sends as `X-Org-Session`.
|
|
124
|
-
*
|
|
125
|
-
*
|
|
123
|
+
* Only opaque `gr_sess_` credentials are supported. A legacy org token
|
|
124
|
+
* raises an error; sign in to the organization again to obtain a session.
|
|
125
|
+
* Pass `undefined` to clear the session.
|
|
126
126
|
*
|
|
127
|
-
* `orgUuid` is the org that issued the credential
|
|
128
|
-
* handler
|
|
129
|
-
*
|
|
130
|
-
*
|
|
127
|
+
* `orgUuid` is the org that issued the credential. When supplied by an
|
|
128
|
+
* org-auth handler, it must match the challenge the handler completes.
|
|
129
|
+
* Callers without that context may omit it. Any rejected credential can
|
|
130
|
+
* trigger one reauthentication attempt, including for the same org.
|
|
131
131
|
*/
|
|
132
132
|
setOrgSession(session, orgUuid) {
|
|
133
|
+
if (session !== void 0 && !/^gr_sess_[A-Za-z0-9_-]+$/.test(session)) {
|
|
134
|
+
throw new Error(
|
|
135
|
+
"Unsupported organization session. Sign in again to obtain an opaque gr_sess_ credential."
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
this.orgSessionRejectionHandler = void 0;
|
|
133
139
|
this.orgSession = session;
|
|
134
140
|
this.orgSessionOrgUuid = session ? orgUuid : void 0;
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* @deprecated Legacy compatibility for stateless orgToken JWE credentials.
|
|
138
|
-
* Prefer setOrgSession() for opaque org browser sessions.
|
|
139
|
-
*/
|
|
140
|
-
setOrgToken(token, orgUuid) {
|
|
141
|
-
this.setOrgSession(token, orgUuid);
|
|
141
|
+
this.orgSessionRevision += 1;
|
|
142
142
|
}
|
|
143
143
|
/**
|
|
144
144
|
* The `credentials` a request carries: none for a bearer client (the fetch
|
|
@@ -149,33 +149,113 @@ var BaseApiClient = class {
|
|
|
149
149
|
}
|
|
150
150
|
/**
|
|
151
151
|
* Run the org-auth handler once for concurrent challenges. A bearer client's
|
|
152
|
-
* handler
|
|
152
|
+
* handler returns a candidate; a same-origin session's
|
|
153
153
|
* handler leaves an httpOnly org-session cookie on the page's origin instead,
|
|
154
154
|
* which the retry presents. A bearer client whose handler issued nothing has
|
|
155
155
|
* nothing to retry with.
|
|
156
156
|
*/
|
|
157
|
-
async answerOrgAuthChallenge(
|
|
157
|
+
async answerOrgAuthChallenge(info, presented, requestRevision) {
|
|
158
158
|
const handler = this.orgAuthHandler;
|
|
159
|
-
if (!handler)
|
|
160
|
-
if (
|
|
161
|
-
this.orgAuthInProgress
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
159
|
+
if (!handler) throw new ApiError("Organization authentication handler is unavailable", 401);
|
|
160
|
+
if (this.orgAuthInProgress) {
|
|
161
|
+
if (this.orgAuthInProgress.orgUuid !== info.orgUuid || this.orgAuthInProgress.requestRevision !== requestRevision) {
|
|
162
|
+
throw new ApiError(
|
|
163
|
+
"Organization authentication context changed. Retry the request.",
|
|
164
|
+
401
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
return this.orgAuthInProgress.promise;
|
|
168
168
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
this.orgSessionOrgUuid = orgAuthInfo.orgUuid;
|
|
172
|
-
return;
|
|
169
|
+
if (this.orgSessionRevision !== requestRevision) {
|
|
170
|
+
throw new ApiError("Organization authentication context changed. Retry the request.", 401);
|
|
173
171
|
}
|
|
174
|
-
|
|
175
|
-
|
|
172
|
+
this.clearOrgSessionIfCurrent(presented);
|
|
173
|
+
const attemptRevision = this.orgSessionRevision;
|
|
174
|
+
const promise = Promise.resolve().then(() => handler(info)).then((candidate) => {
|
|
175
|
+
if (this.orgSessionRevision !== attemptRevision) {
|
|
176
|
+
throw new ApiError(
|
|
177
|
+
"Organization authentication context changed. Retry the request.",
|
|
178
|
+
401
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
if (candidate === void 0) {
|
|
182
|
+
if (this.apiKey) {
|
|
183
|
+
throw new ApiError(
|
|
184
|
+
"Organization authentication must return a session candidate",
|
|
185
|
+
401
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
return "cookie";
|
|
189
|
+
}
|
|
190
|
+
if (!candidate || typeof candidate.session !== "string" || candidate.source !== "cache" && candidate.source !== "new") {
|
|
191
|
+
throw new ApiError(
|
|
192
|
+
"Organization authentication returned an invalid session candidate",
|
|
193
|
+
401
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
if (candidate.orgUuid !== info.orgUuid) {
|
|
197
|
+
throw new ApiError(
|
|
198
|
+
"Organization authentication issued a session for another organization",
|
|
199
|
+
401
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
if (candidate.source === "cache" && info.sessionRejected) {
|
|
203
|
+
throw new ApiError(
|
|
204
|
+
"Organization authentication requires a newly issued session after rejection",
|
|
205
|
+
401
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
this.setOrgSession(candidate.session, candidate.orgUuid);
|
|
209
|
+
let rejected = false;
|
|
210
|
+
this.orgSessionRejectionHandler = () => {
|
|
211
|
+
if (rejected) return;
|
|
212
|
+
rejected = true;
|
|
213
|
+
candidate.onRejected?.();
|
|
214
|
+
};
|
|
215
|
+
return candidate.source;
|
|
216
|
+
}).finally(() => {
|
|
217
|
+
if (this.orgAuthInProgress?.promise === promise) this.orgAuthInProgress = null;
|
|
218
|
+
});
|
|
219
|
+
this.orgAuthInProgress = { orgUuid: info.orgUuid, requestRevision, promise };
|
|
220
|
+
return promise;
|
|
221
|
+
}
|
|
222
|
+
assertOrgAuthContext(orgUuid) {
|
|
223
|
+
if (this.orgSession && this.orgSessionOrgUuid !== orgUuid || this.apiKey && !this.orgSession) {
|
|
224
|
+
throw new ApiError("Organization authentication context changed. Retry the request.", 401);
|
|
176
225
|
}
|
|
177
226
|
}
|
|
178
|
-
|
|
227
|
+
notifyOrgSessionRejected(presented, callback) {
|
|
228
|
+
try {
|
|
229
|
+
callback?.();
|
|
230
|
+
} catch {
|
|
231
|
+
this.clearOrgSessionIfCurrent(presented);
|
|
232
|
+
throw new ApiError("Could not discard rejected organization session", 401);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
hasNewerOrgSession(presented, orgUuid) {
|
|
236
|
+
return Boolean(
|
|
237
|
+
presented && this.orgSession && this.orgSession !== presented && this.orgSessionOrgUuid === orgUuid
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
clearOrgSessionIfCurrent(expected) {
|
|
241
|
+
if (this.orgSession !== expected || this.orgSession === void 0) return;
|
|
242
|
+
this.setOrgSession(void 0);
|
|
243
|
+
}
|
|
244
|
+
async fetch(endpoint, options, orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1, enhancedAuthRetry = false) {
|
|
245
|
+
return this.fetchApiVersion(
|
|
246
|
+
"v2",
|
|
247
|
+
endpoint,
|
|
248
|
+
options,
|
|
249
|
+
orgAuthRetriesRemaining,
|
|
250
|
+
enhancedAuthRetry
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* `fetch` against a named API version: `/api/{version}/{endpoint}`, with the
|
|
255
|
+
* same credentials, step-up retry, org-auth challenge handling and
|
|
256
|
+
* org-session rejection bookkeeping. `fetch` is this method bound to `v2`.
|
|
257
|
+
*/
|
|
258
|
+
async fetchApiVersion(version, endpoint, options, orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1, enhancedAuthRetry = false) {
|
|
179
259
|
try {
|
|
180
260
|
const headers = new Headers({
|
|
181
261
|
// Don't set Content-Type for FormData — the browser must set it
|
|
@@ -187,7 +267,11 @@ var BaseApiClient = class {
|
|
|
187
267
|
headers.set("Authorization", `Bearer ${this.apiKey}`);
|
|
188
268
|
}
|
|
189
269
|
setOrgAuthHeader(headers, this.orgSession);
|
|
190
|
-
const
|
|
270
|
+
const presentedOrgSession = headers.get("X-Org-Session");
|
|
271
|
+
const requestOrgRevision = this.orgSessionRevision;
|
|
272
|
+
const presentedOrgUuid = this.orgSessionOrgUuid;
|
|
273
|
+
const rejectionHandler = this.orgSessionRejectionHandler;
|
|
274
|
+
const fullUrl = `${this.baseUrl}/api/${version}/${endpoint}`;
|
|
191
275
|
const response = await this.fetchFunction(fullUrl, {
|
|
192
276
|
...options,
|
|
193
277
|
...this.credentialsInit(),
|
|
@@ -195,7 +279,7 @@ var BaseApiClient = class {
|
|
|
195
279
|
headers
|
|
196
280
|
});
|
|
197
281
|
if (!response.ok) {
|
|
198
|
-
if (response.status === 401 && requiresStepUpAuth(response.headers.get("WWW-Authenticate")) && this.enhancedAuthHandler) {
|
|
282
|
+
if (response.status === 401 && !enhancedAuthRetry && requiresStepUpAuth(response.headers.get("WWW-Authenticate")) && this.enhancedAuthHandler) {
|
|
199
283
|
if (this.enhancedAuthInProgress) {
|
|
200
284
|
await this.enhancedAuthInProgress;
|
|
201
285
|
} else {
|
|
@@ -207,33 +291,53 @@ var BaseApiClient = class {
|
|
|
207
291
|
this.enhancedAuthInProgress = null;
|
|
208
292
|
}
|
|
209
293
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
294
|
+
return await this.fetchApiVersion(
|
|
295
|
+
version,
|
|
296
|
+
endpoint,
|
|
297
|
+
options,
|
|
298
|
+
orgAuthRetriesRemaining,
|
|
299
|
+
true
|
|
300
|
+
);
|
|
217
301
|
}
|
|
218
302
|
if (response.status === 401) {
|
|
219
303
|
const orgAuthInfo = parseOrgAuthChallenge(response.headers.get("WWW-Authenticate"));
|
|
220
|
-
if (orgAuthInfo &&
|
|
221
|
-
|
|
222
|
-
|
|
304
|
+
if (orgAuthInfo && presentedOrgSession) {
|
|
305
|
+
orgAuthInfo.sessionRejected = true;
|
|
306
|
+
if (presentedOrgUuid === orgAuthInfo.orgUuid) {
|
|
307
|
+
this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);
|
|
308
|
+
}
|
|
223
309
|
}
|
|
224
|
-
if (orgAuthInfo &&
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
310
|
+
if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {
|
|
311
|
+
let nextOrgRetries = orgAuthRetriesRemaining - 1;
|
|
312
|
+
if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {
|
|
313
|
+
const completion = await this.answerOrgAuthChallenge(
|
|
314
|
+
orgAuthInfo,
|
|
315
|
+
presentedOrgSession,
|
|
316
|
+
requestOrgRevision
|
|
317
|
+
);
|
|
318
|
+
if (completion !== "cache") nextOrgRetries = 0;
|
|
319
|
+
}
|
|
320
|
+
this.assertOrgAuthContext(orgAuthInfo.orgUuid);
|
|
321
|
+
return await this.fetchApiVersion(
|
|
322
|
+
version,
|
|
323
|
+
endpoint,
|
|
324
|
+
options,
|
|
325
|
+
nextOrgRetries,
|
|
326
|
+
enhancedAuthRetry
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
if (orgAuthInfo) {
|
|
330
|
+
this.clearOrgSessionIfCurrent(presentedOrgSession);
|
|
331
|
+
if (orgAuthInfo.acrValues?.includes("urn:gravity:mfa")) {
|
|
332
|
+
throw new ApiError(
|
|
333
|
+
"Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.",
|
|
334
|
+
401
|
|
335
|
+
);
|
|
232
336
|
}
|
|
233
337
|
}
|
|
234
338
|
}
|
|
235
339
|
const errorData = await response.json().catch(() => ({}));
|
|
236
|
-
if (response.status === 401 && endpoint === "account") {
|
|
340
|
+
if (response.status === 401 && version === "v2" && endpoint === "account") {
|
|
237
341
|
throw new Error("unauthorized");
|
|
238
342
|
}
|
|
239
343
|
if (Array.isArray(errorData.detail)) {
|
|
@@ -290,7 +394,7 @@ ${formattedErrors}`, response.status);
|
|
|
290
394
|
throw error;
|
|
291
395
|
}
|
|
292
396
|
}
|
|
293
|
-
async fetchRaw(endpoint, options, allowedErrorStatuses = [],
|
|
397
|
+
async fetchRaw(endpoint, options, allowedErrorStatuses = [], orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1, enhancedAuthRetry = false) {
|
|
294
398
|
try {
|
|
295
399
|
const headers = new Headers({
|
|
296
400
|
...options?.headers || {}
|
|
@@ -302,6 +406,10 @@ ${formattedErrors}`, response.status);
|
|
|
302
406
|
headers.set("Authorization", `Bearer ${this.apiKey}`);
|
|
303
407
|
}
|
|
304
408
|
setOrgAuthHeader(headers, this.orgSession);
|
|
409
|
+
const presentedOrgSession = headers.get("X-Org-Session");
|
|
410
|
+
const requestOrgRevision = this.orgSessionRevision;
|
|
411
|
+
const presentedOrgUuid = this.orgSessionOrgUuid;
|
|
412
|
+
const rejectionHandler = this.orgSessionRejectionHandler;
|
|
305
413
|
const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {
|
|
306
414
|
...options,
|
|
307
415
|
...this.credentialsInit(),
|
|
@@ -309,7 +417,7 @@ ${formattedErrors}`, response.status);
|
|
|
309
417
|
headers
|
|
310
418
|
});
|
|
311
419
|
if (!response.ok) {
|
|
312
|
-
if (response.status === 401 && requiresStepUpAuth(response.headers.get("WWW-Authenticate")) && this.enhancedAuthHandler) {
|
|
420
|
+
if (response.status === 401 && !enhancedAuthRetry && requiresStepUpAuth(response.headers.get("WWW-Authenticate")) && this.enhancedAuthHandler) {
|
|
313
421
|
if (this.enhancedAuthInProgress) {
|
|
314
422
|
await this.enhancedAuthInProgress;
|
|
315
423
|
} else {
|
|
@@ -321,28 +429,48 @@ ${formattedErrors}`, response.status);
|
|
|
321
429
|
this.enhancedAuthInProgress = null;
|
|
322
430
|
}
|
|
323
431
|
}
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
432
|
+
return await this.fetchRaw(
|
|
433
|
+
endpoint,
|
|
434
|
+
options,
|
|
435
|
+
allowedErrorStatuses,
|
|
436
|
+
orgAuthRetriesRemaining,
|
|
437
|
+
true
|
|
438
|
+
);
|
|
331
439
|
}
|
|
332
440
|
if (response.status === 401) {
|
|
333
441
|
const orgAuthInfo = parseOrgAuthChallenge(response.headers.get("WWW-Authenticate"));
|
|
334
|
-
if (orgAuthInfo &&
|
|
335
|
-
|
|
336
|
-
|
|
442
|
+
if (orgAuthInfo && presentedOrgSession) {
|
|
443
|
+
orgAuthInfo.sessionRejected = true;
|
|
444
|
+
if (presentedOrgUuid === orgAuthInfo.orgUuid) {
|
|
445
|
+
this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);
|
|
446
|
+
}
|
|
337
447
|
}
|
|
338
|
-
if (orgAuthInfo &&
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
448
|
+
if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {
|
|
449
|
+
let nextOrgRetries = orgAuthRetriesRemaining - 1;
|
|
450
|
+
if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {
|
|
451
|
+
const completion = await this.answerOrgAuthChallenge(
|
|
452
|
+
orgAuthInfo,
|
|
453
|
+
presentedOrgSession,
|
|
454
|
+
requestOrgRevision
|
|
455
|
+
);
|
|
456
|
+
if (completion !== "cache") nextOrgRetries = 0;
|
|
457
|
+
}
|
|
458
|
+
this.assertOrgAuthContext(orgAuthInfo.orgUuid);
|
|
459
|
+
return await this.fetchRaw(
|
|
460
|
+
endpoint,
|
|
461
|
+
options,
|
|
462
|
+
allowedErrorStatuses,
|
|
463
|
+
nextOrgRetries,
|
|
464
|
+
enhancedAuthRetry
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
if (orgAuthInfo) {
|
|
468
|
+
this.clearOrgSessionIfCurrent(presentedOrgSession);
|
|
469
|
+
if (!allowedErrorStatuses.includes(401) && orgAuthInfo.acrValues?.includes("urn:gravity:mfa")) {
|
|
470
|
+
throw new ApiError(
|
|
471
|
+
"Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.",
|
|
472
|
+
401
|
|
473
|
+
);
|
|
346
474
|
}
|
|
347
475
|
}
|
|
348
476
|
}
|
|
@@ -449,4 +577,4 @@ export {
|
|
|
449
577
|
BaseApiClient,
|
|
450
578
|
ChatInteractionController
|
|
451
579
|
};
|
|
452
|
-
//# sourceMappingURL=chunk-
|
|
580
|
+
//# sourceMappingURL=chunk-P2X5TOYY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/api/base.ts","../src/helpers/chat-interaction.ts"],"sourcesContent":["// Utility function to read a specific cookie value\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const trimmedCookie = cookie.trim();\n const eqIndex = trimmedCookie.indexOf('=');\n if (eqIndex === -1) continue;\n\n const cookieName = trimmedCookie.substring(0, eqIndex);\n const cookieValue = trimmedCookie.substring(eqIndex + 1);\n\n if (cookieName === name) {\n return cookieValue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Structured validation error returned by the backend's workflow-expression\n * validator (CEL / Jinja schema checks). See WorkflowValidationErrorResponse\n * in workflowValidationTypes.ts for the public-facing shape.\n */\nexport interface ApiValidationError {\n field: string;\n kind: 'cel_syntax' | 'cel_schema' | 'jinja_syntax' | 'jinja_schema';\n message: string;\n offendingPath: string | null;\n location: {\n start: number;\n end: number;\n line: number;\n column: number;\n length: number;\n } | null;\n suggestion: string | null;\n}\n\nfunction isApiValidationError(value: unknown): value is ApiValidationError {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.field === 'string' && typeof v.kind === 'string' && typeof v.message === 'string'\n );\n}\n\n/** Browser-console sink for API failures. A fixed event name only — never the\n * error object, its ``name``, or response-derived ``message``/``errorData``. */\nfunction logApiClientError(_error: unknown): void {\n console.warn('API request failed');\n}\n\nexport class ApiError extends Error {\n statusCode: number;\n /** Legacy string-array errors — kept for non-validation callers. */\n errors?: string[];\n /**\n * Structured workflow-expression validation errors (CEL/Jinja).\n * Populated when the backend returns a WorkflowValidationErrorResponse.\n */\n validationErrors?: ApiValidationError[];\n /**\n * The raw structured `detail` object when the backend returned one (a body\n * with `error: true` or a `code`). Declared here rather than bolted on with\n * `as any` at the throw site so consumers can narrow it with a type guard —\n * see `isMemberContactConflict` in `types/member-types`.\n */\n errorData?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n errors?: string[],\n validationErrors?: ApiValidationError[]\n ) {\n super(message);\n this.name = 'ApiError';\n this.statusCode = statusCode;\n this.errors = errors;\n this.validationErrors = validationErrors;\n }\n}\n\n/**\n * Handler for enhanced authentication requirement (RFC 9470 Step-Up Authentication).\n * Called when a 401 response includes WWW-Authenticate header with\n * error=\"insufficient_user_authentication\".\n * Should return a promise that resolves with the new auth token after re-auth.\n */\nexport type EnhancedAuthHandler = () => Promise<string>;\n\n/**\n * Info parsed from WWW-Authenticate header for org auth requirement.\n */\nexport interface OrgAuthInfo {\n orgUuid: string;\n authUrl: string;\n /** Requested authentication contexts. The server must verify the new evidence. */\n acrValues?: string[];\n /** The SDK sent an org credential on the request that produced this challenge. */\n sessionRejected?: boolean;\n}\n\n/**\n * Handler for organization authentication requirement.\n * Called when a 401 response includes WWW-Authenticate header with realm=\"org\".\n * The handler should redirect the user to the auth URL for consent/SSO.\n * Bearer handlers return a candidate; cookie handlers may resolve without a value.\n * `sessionRejected` describes the credential sent on that request, without\n * exposing it. A rejected cached candidate requires fresh authentication.\n */\nexport interface OrgAuthSessionCandidate {\n session: string;\n orgUuid: string;\n /** Local provenance only; the server still validates the credential. */\n source: 'cache' | 'new';\n /** Cleanup for this exact candidate when its own org rejects it. */\n onRejected?: () => void;\n}\n\nexport type OrgAuthHandler = (info: OrgAuthInfo) => Promise<OrgAuthSessionCandidate | void>;\ntype OrgAuthCompletion = OrgAuthSessionCandidate['source'] | 'cookie';\n\n/**\n * Check if a WWW-Authenticate header indicates step-up authentication is required.\n * Per RFC 9470, this is indicated by error=\"insufficient_user_authentication\".\n */\nfunction requiresStepUpAuth(wwwAuthenticate: string | null): boolean {\n if (!wwwAuthenticate) return false;\n return wwwAuthenticate.includes('error=\"insufficient_user_authentication\"');\n}\n\n/**\n * Parse org auth info from WWW-Authenticate header.\n * Returns null if this is not an org auth challenge.\n * Expected format: Bearer realm=\"org\", org_uuid=\"...\", auth_url=\"...\"\n * (the challenge names no cookie: a browser's org session is an httpOnly\n * cookie on its own host, and a bearer client sends `X-Org-Session`).\n *\n * Exported so non-SDK fetch paths (e.g. the app's same-origin file-content\n * proxy fetches) can detect the same challenge and trigger the shared org\n * step-up flow.\n */\nexport function parseOrgAuthChallenge(wwwAuthenticate: string | null): OrgAuthInfo | null {\n if (!wwwAuthenticate) return null;\n if (!wwwAuthenticate.includes('realm=\"org\"')) return null;\n\n // Parse the key-value pairs from the header\n const orgUuidMatch = wwwAuthenticate.match(/org_uuid=\"([^\"]+)\"/);\n const authUrlMatch = wwwAuthenticate.match(/auth_url=\"([^\"]+)\"/);\n const acrValues = wwwAuthenticate\n .match(/acr_values=\"([^\"]*)\"/)?.[1]\n ?.trim()\n .split(/\\s+/)\n .filter(Boolean);\n\n if (!orgUuidMatch?.[1] || !authUrlMatch?.[1]) {\n // Don't log the raw header value — it embeds org_uuid + auth_url.\n console.warn('Invalid org auth challenge header: missing required fields');\n return null;\n }\n\n return {\n orgUuid: orgUuidMatch[1],\n authUrl: authUrlMatch[1],\n ...(acrValues?.length ? { acrValues } : {}),\n };\n}\n\n/**\n * The API versions a client can address. `/api/v2` is every existing method's\n * base; `/api/v3` serves the Chat resource\n * (`docs/decisions/api/2026-11-09-1-api-v3-begins-with-the-chat-resource.md`).\n */\ntype ApiVersion = 'v2' | 'v3';\n\nfunction setOrgAuthHeader(headers: Headers, token: string | undefined): void {\n if (!token) return;\n headers.set('X-Org-Session', token);\n}\n\n/**\n * Transport and credential for every request the client makes.\n *\n * - **Bearer** (`apiKey` set): `Authorization: Bearer <apiKey>` on every\n * request, no cookies. This is how non-browser consumers (the CLI, servers,\n * API keys) and bearer-holding browser runtimes (widget iframes) call the API.\n * - **Same-origin session** (no `apiKey`): no `Authorization` header and\n * `credentials: 'same-origin'`. The browser presents the host's httpOnly\n * session cookie, and only to the origin the page is on; the client never\n * reads a cookie to build a credential. A browser app points `baseUrl` at its\n * own origin, which serves `/api/v2` and `/api/v3` (Gravity Rail's edge on\n * full-account hosts, the frontend's proxy on Site hosts).\n *\n * The org-auth challenge (`WWW-Authenticate: Bearer realm=\"org\"`) is answered by\n * `setOrgAuthHandler`. A bearer client's handler hands back the org session with\n * a candidate result, which is sent as `X-Org-Session`; in same-origin session\n * mode the org session is an httpOnly cookie on the page's origin, so the\n * request is retried once after the handler and the browser presents it.\n * A bearer request that starts without an org credential may first try a\n * cached candidate, then make one fresh-auth attempt if the server rejects\n * it. A request that starts with an org credential has only the fresh attempt.\n */\nexport class BaseApiClient {\n protected baseUrl: string;\n protected apiKey: string | undefined;\n protected isCrossDomain: boolean;\n protected fetchFunction: typeof fetch;\n private enhancedAuthHandler?: EnhancedAuthHandler;\n private enhancedAuthInProgress: Promise<string> | null = null;\n private orgAuthHandler?: OrgAuthHandler;\n private orgAuthInProgress: {\n orgUuid: string;\n requestRevision: number;\n promise: Promise<OrgAuthCompletion>;\n } | null = null;\n private orgSessionRevision = 0;\n private orgSessionRejectionHandler?: () => void;\n private orgSession?: string;\n /**\n * Optional issuer context supplied with an opaque credential. A handler\n * cannot complete a challenge with a session explicitly bound to another org.\n * The server remains responsible for validating the credential itself.\n */\n private orgSessionOrgUuid?: string;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n // console.log('[BaseApiClient] constructor - baseUrl:', baseUrl);\n // Bind fetch to its proper context (window in browser, global in Node)\n this.fetchFunction =\n customFetch || (typeof window !== 'undefined' ? fetch.bind(window) : fetch);\n\n // Determine if we're making cross-domain requests by comparing current origin to API origin\n const apiUrlParsed = new URL(baseUrl);\n const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';\n this.isCrossDomain = currentOrigin !== '' && currentOrigin !== apiUrlParsed.origin;\n // console.log('[BaseApiClient] isCrossDomain:', this.isCrossDomain, 'currentOrigin:', currentOrigin, 'apiOrigin:', apiUrlParsed.origin);\n }\n\n /**\n * Set the handler for enhanced authentication requirements (RFC 9470 Step-Up Auth).\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with error=\"insufficient_user_authentication\".\n */\n setEnhancedAuthHandler(handler: EnhancedAuthHandler | undefined) {\n this.enhancedAuthHandler = handler;\n }\n\n /**\n * Set the handler for organization authentication requirements.\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with realm=\"org\". The handler should redirect the user to complete org auth.\n */\n setOrgAuthHandler(handler: OrgAuthHandler | undefined) {\n this.orgAuthHandler = handler;\n }\n\n /**\n * Update the API key (used after successful re-authentication).\n */\n updateApiKey(newApiKey: string) {\n this.apiKey = newApiKey;\n }\n\n /**\n * Set the opaque org session credential a bearer client sends as `X-Org-Session`.\n * Only opaque `gr_sess_` credentials are supported. A legacy org token\n * raises an error; sign in to the organization again to obtain a session.\n * Pass `undefined` to clear the session.\n *\n * `orgUuid` is the org that issued the credential. When supplied by an\n * org-auth handler, it must match the challenge the handler completes.\n * Callers without that context may omit it. Any rejected credential can\n * trigger one reauthentication attempt, including for the same org.\n */\n setOrgSession(session: string | undefined, orgUuid?: string) {\n if (session !== undefined && !/^gr_sess_[A-Za-z0-9_-]+$/.test(session)) {\n throw new Error(\n 'Unsupported organization session. Sign in again to obtain an opaque gr_sess_ credential.'\n );\n }\n this.orgSessionRejectionHandler = undefined;\n this.orgSession = session;\n this.orgSessionOrgUuid = session ? orgUuid : undefined;\n this.orgSessionRevision += 1;\n }\n\n /**\n * The `credentials` a request carries: none for a bearer client (the fetch\n * default), the page's own-origin cookies for a same-origin session.\n */\n private credentialsInit(): Pick<RequestInit, 'credentials'> {\n return this.apiKey ? {} : { credentials: 'same-origin' };\n }\n\n /**\n * Run the org-auth handler once for concurrent challenges. A bearer client's\n * handler returns a candidate; a same-origin session's\n * handler leaves an httpOnly org-session cookie on the page's origin instead,\n * which the retry presents. A bearer client whose handler issued nothing has\n * nothing to retry with.\n */\n private async answerOrgAuthChallenge(\n info: OrgAuthInfo,\n presented: string | null,\n requestRevision: number\n ): Promise<OrgAuthCompletion> {\n const handler = this.orgAuthHandler;\n if (!handler) throw new ApiError('Organization authentication handler is unavailable', 401);\n if (this.orgAuthInProgress) {\n if (\n this.orgAuthInProgress.orgUuid !== info.orgUuid ||\n this.orgAuthInProgress.requestRevision !== requestRevision\n ) {\n throw new ApiError(\n 'Organization authentication context changed. Retry the request.',\n 401\n );\n }\n return this.orgAuthInProgress.promise;\n }\n if (this.orgSessionRevision !== requestRevision) {\n throw new ApiError('Organization authentication context changed. Retry the request.', 401);\n }\n this.clearOrgSessionIfCurrent(presented);\n const attemptRevision = this.orgSessionRevision;\n const promise: Promise<OrgAuthCompletion> = Promise.resolve()\n .then(() => handler(info))\n .then((candidate): OrgAuthCompletion => {\n if (this.orgSessionRevision !== attemptRevision) {\n throw new ApiError(\n 'Organization authentication context changed. Retry the request.',\n 401\n );\n }\n if (candidate === undefined) {\n if (this.apiKey) {\n throw new ApiError(\n 'Organization authentication must return a session candidate',\n 401\n );\n }\n return 'cookie';\n }\n if (\n !candidate ||\n typeof candidate.session !== 'string' ||\n (candidate.source !== 'cache' && candidate.source !== 'new')\n ) {\n throw new ApiError(\n 'Organization authentication returned an invalid session candidate',\n 401\n );\n }\n if (candidate.orgUuid !== info.orgUuid) {\n throw new ApiError(\n 'Organization authentication issued a session for another organization',\n 401\n );\n }\n if (candidate.source === 'cache' && info.sessionRejected) {\n throw new ApiError(\n 'Organization authentication requires a newly issued session after rejection',\n 401\n );\n }\n this.setOrgSession(candidate.session, candidate.orgUuid);\n let rejected = false;\n this.orgSessionRejectionHandler = () => {\n if (rejected) return;\n rejected = true;\n candidate.onRejected?.();\n };\n return candidate.source;\n })\n .finally(() => {\n if (this.orgAuthInProgress?.promise === promise) this.orgAuthInProgress = null;\n });\n this.orgAuthInProgress = { orgUuid: info.orgUuid, requestRevision, promise };\n return promise;\n }\n\n private assertOrgAuthContext(orgUuid: string): void {\n if (\n (this.orgSession && this.orgSessionOrgUuid !== orgUuid) ||\n (this.apiKey && !this.orgSession)\n ) {\n throw new ApiError('Organization authentication context changed. Retry the request.', 401);\n }\n }\n\n private notifyOrgSessionRejected(\n presented: string | null,\n callback: (() => void) | undefined\n ): void {\n try {\n callback?.();\n } catch {\n this.clearOrgSessionIfCurrent(presented);\n throw new ApiError('Could not discard rejected organization session', 401);\n }\n }\n\n private hasNewerOrgSession(presented: string | null, orgUuid: string): boolean {\n // A concurrent login may have replaced the rejected credential. Retry\n // that replacement only with an explicit matching org binding; the\n // server still validates it, and this consumes the existing retry budget.\n return Boolean(\n presented &&\n this.orgSession &&\n this.orgSession !== presented &&\n this.orgSessionOrgUuid === orgUuid\n );\n }\n\n private clearOrgSessionIfCurrent(expected: string | null | undefined): void {\n if (this.orgSession !== expected || this.orgSession === undefined) return;\n this.setOrgSession(undefined);\n }\n\n protected async fetch<T>(\n endpoint: string,\n options?: RequestInit,\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<T> {\n return this.fetchApiVersion<T>(\n 'v2',\n endpoint,\n options,\n orgAuthRetriesRemaining,\n enhancedAuthRetry\n );\n }\n\n /**\n * `fetch` against a named API version: `/api/{version}/{endpoint}`, with the\n * same credentials, step-up retry, org-auth challenge handling and\n * org-session rejection bookkeeping. `fetch` is this method bound to `v2`.\n */\n protected async fetchApiVersion<T>(\n version: ApiVersion,\n endpoint: string,\n options?: RequestInit,\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<T> {\n try {\n const headers = new Headers({\n // Don't set Content-Type for FormData — the browser must set it\n // with the multipart boundary automatically.\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n const presentedOrgSession = headers.get('X-Org-Session');\n const requestOrgRevision = this.orgSessionRevision;\n const presentedOrgUuid = this.orgSessionOrgUuid;\n const rejectionHandler = this.orgSessionRejectionHandler;\n\n // console.warn(\"Calling with apiKey:\", this.apiKey)\n const fullUrl = `${this.baseUrl}/api/${version}/${endpoint}`;\n // console.log('[BaseApiClient] fetch - URL:', fullUrl, 'baseUrl:', this.baseUrl, 'endpoint:', endpoint);\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n !enhancedAuthRetry &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n if (this.apiKey) this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n return await this.fetchApiVersion<T>(\n version,\n endpoint,\n options,\n orgAuthRetriesRemaining,\n true\n );\n }\n\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (orgAuthInfo && presentedOrgSession) {\n orgAuthInfo.sessionRejected = true;\n if (presentedOrgUuid === orgAuthInfo.orgUuid) {\n this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);\n }\n }\n if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {\n let nextOrgRetries = orgAuthRetriesRemaining - 1;\n if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {\n const completion = await this.answerOrgAuthChallenge(\n orgAuthInfo,\n presentedOrgSession,\n requestOrgRevision\n );\n if (completion !== 'cache') nextOrgRetries = 0;\n }\n this.assertOrgAuthContext(orgAuthInfo.orgUuid);\n return await this.fetchApiVersion<T>(\n version,\n endpoint,\n options,\n nextOrgRetries,\n enhancedAuthRetry\n );\n }\n if (orgAuthInfo) {\n this.clearOrgSessionIfCurrent(presentedOrgSession);\n if (orgAuthInfo.acrValues?.includes('urn:gravity:mfa')) {\n throw new ApiError(\n 'Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.',\n 401\n );\n }\n }\n }\n\n const errorData = await response.json().catch(() => ({}));\n\n // Handle unauthorized errors for account endpoint\n if (response.status === 401 && version === 'v2' && endpoint === 'account') {\n throw new Error('unauthorized');\n }\n\n // Handle structured validation errors (Pydantic array format)\n if (Array.isArray(errorData.detail)) {\n const formattedErrors = errorData.detail\n .map((error: any) => {\n const location = error.loc.join(' > ');\n return `${location}: ${error.msg}`;\n })\n .join('\\n');\n throw new ApiError(`Validation Error:\\n${formattedErrors}`, response.status);\n }\n\n // Handle validation errors with errors array (new format)\n if (errorData.errors && Array.isArray(errorData.errors)) {\n // Structured workflow-expression validation errors — objects with\n // { field, kind, message, offendingPath, location }. Build a\n // readable message and preserve the structured payload.\n if (errorData.errors.length > 0 && isApiValidationError(errorData.errors[0])) {\n const validationErrors: ApiValidationError[] =\n errorData.errors.filter(isApiValidationError);\n const [first] = validationErrors;\n if (first) {\n const extra =\n validationErrors.length > 1\n ? ` (+${validationErrors.length - 1} more)`\n : '';\n const readable = `${first.field}: ${first.message}${extra}`;\n throw new ApiError(\n readable,\n response.status,\n validationErrors.map((e) => `${e.field}: ${e.message}`),\n validationErrors\n );\n }\n }\n\n // Legacy string-array errors.\n const stringErrors: string[] = errorData.errors.filter(\n (e: unknown): e is string => typeof e === 'string'\n );\n const details = stringErrors.join('; ');\n const message = errorData.detail\n ? `${errorData.detail}: ${details}`\n : `Validation failed: ${details}`;\n throw new ApiError(message, response.status, stringErrors);\n }\n\n // Handle structured errors (with error: true or with code property).\n //\n // TWO body shapes reach here and both carry structure:\n //\n // * `detail` IS the structured object — the member/account contact\n // conflicts build their whole payload as `HTTPException.detail`.\n // * `detail` is PROSE and the machine-readable fields sit beside it\n // at the top level. That is what the domain exception handlers\n // emit: `conflict_handler` writes `{detail, code, ...payload}`, so\n // a Journey v2 refusal arrives as\n // `{detail: \"...\", code: \"journey_v2_invalid_topology\", issues: [...]}`.\n //\n // `detail || errorData` picked the prose string for the second shape,\n // which is not an object, so the branch fell through and `code` and\n // `issues` were dropped on the floor — leaving a client unable to\n // tell a definition conflict from a structural refusal, or to point\n // at the resources a validator rejected. Prefer an OBJECT detail and\n // otherwise read the body itself; the message is unchanged in both\n // cases (prose still wins when there is prose).\n const detail = errorData.detail;\n const structuredError = detail && typeof detail === 'object' ? detail : errorData;\n if (\n structuredError &&\n typeof structuredError === 'object' &&\n (structuredError.error === true || structuredError.code)\n ) {\n const message =\n (typeof detail === 'string' && detail) ||\n structuredError.message ||\n structuredError.code ||\n 'Unknown error';\n const error = new ApiError(message, response.status);\n // Attach the full error data for frontend handling\n error.errorData = structuredError;\n throw error;\n }\n\n // Handle simple error messages\n const errorMessage =\n typeof errorData.detail === 'string'\n ? errorData.detail\n : errorData.message || response.statusText;\n const simpleError = new ApiError(errorMessage, response.status);\n // A prose `detail` STRING alongside a top-level `code` is the shape\n // the backend's domain-validation handler produces: it merges an\n // exception's `payload` into the body and keeps `detail`\n // authoritative. That misses the structured branch above, because\n // `errorData.detail || errorData` resolves to the string. Carry the\n // body through so a caller can still branch on the token — the\n // alternative is parsing `detail`, which is deliberately\n // human-facing prose and not a stable contract.\n if (typeof errorData.code === 'string') {\n simpleError.errorData = errorData;\n }\n throw simpleError;\n }\n\n // Handle 204 No Content - no JSON body to parse\n if (response.status === 204) {\n return undefined as any;\n }\n\n return response.json();\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n\n protected async fetchRaw(\n endpoint: string,\n options?: RequestInit,\n allowedErrorStatuses: number[] = [],\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<Response> {\n try {\n const headers = new Headers({\n ...((options?.headers as Record<string, string>) || {}),\n });\n // Without this, fetch labels a string body text/plain and FastAPI\n // rejects a JSON body parameter with 422 \"Validation failed\" (every\n // live-view browser storage save, until 2026-10-27).\n if (typeof options?.body === 'string' && !headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n const presentedOrgSession = headers.get('X-Org-Session');\n const requestOrgRevision = this.orgSessionRevision;\n const presentedOrgUuid = this.orgSessionOrgUuid;\n const rejectionHandler = this.orgSessionRejectionHandler;\n\n const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n !enhancedAuthRetry &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n if (this.apiKey) this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n return await this.fetchRaw(\n endpoint,\n options,\n allowedErrorStatuses,\n orgAuthRetriesRemaining,\n true\n );\n }\n\n // Mirror of the org-auth branch in fetch() above; see comments there.\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (orgAuthInfo && presentedOrgSession) {\n orgAuthInfo.sessionRejected = true;\n if (presentedOrgUuid === orgAuthInfo.orgUuid) {\n this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);\n }\n }\n if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {\n let nextOrgRetries = orgAuthRetriesRemaining - 1;\n if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {\n const completion = await this.answerOrgAuthChallenge(\n orgAuthInfo,\n presentedOrgSession,\n requestOrgRevision\n );\n if (completion !== 'cache') nextOrgRetries = 0;\n }\n this.assertOrgAuthContext(orgAuthInfo.orgUuid);\n return await this.fetchRaw(\n endpoint,\n options,\n allowedErrorStatuses,\n nextOrgRetries,\n enhancedAuthRetry\n );\n }\n if (orgAuthInfo) {\n this.clearOrgSessionIfCurrent(presentedOrgSession);\n if (\n !allowedErrorStatuses.includes(401) &&\n orgAuthInfo.acrValues?.includes('urn:gravity:mfa')\n ) {\n throw new ApiError(\n 'Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.',\n 401\n );\n }\n }\n }\n\n if (allowedErrorStatuses.includes(response.status)) {\n return response;\n }\n\n const errorText = await response.text().catch(() => '');\n throw new ApiError(errorText || response.statusText, response.status);\n }\n\n return response;\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n\n /**\n * Fetch from root path (not prefixed with /api/v2/)\n * Used for OAuth and other non-API endpoints\n */\n protected async fetchRoot<T>(path: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const fullUrl = `${this.baseUrl}/${path}`;\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null as T;\n }\n const errorData = await response.json().catch(() => ({}));\n const errorMessage = errorData.detail || errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json();\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n}\n","import type { ChatsApi } from '../api/chats';\nimport type { InteractionMode, InteractionSessionResponse } from '../types/chat-types';\n\ntype InteractionApi = Pick<\n ChatsApi,\n 'createChatInteractionSession' | 'transitionChatInteractionSession'\n>;\n\n/** One client's mode history in one Chat. Create a separate controller per device/session. */\nexport class ChatInteractionController {\n private current: InteractionSessionResponse | undefined;\n private pending: { mode: InteractionMode; requestId: string } | undefined;\n private tail: Promise<unknown> = Promise.resolve();\n private readonly clientSessionId = crypto.randomUUID();\n\n constructor(\n private readonly api: InteractionApi,\n private readonly workspaceId: string,\n private readonly chatId: number\n ) {}\n\n /** Serialize switches and reuse request IDs when a response is lost. */\n ensure(mode: InteractionMode): Promise<InteractionSessionResponse> {\n const operation = this.tail.then(async () => {\n // Resolve an uncertain earlier write before selecting the next mode.\n if (this.pending) await this.applyPending();\n if (this.current?.mode !== mode) {\n this.pending = { mode, requestId: crypto.randomUUID() };\n await this.applyPending();\n }\n if (!this.current) throw new Error('Interaction session unavailable');\n return this.current;\n });\n this.tail = operation.catch(() => undefined);\n return operation;\n }\n\n private async applyPending(): Promise<void> {\n const pending = this.pending;\n if (!pending) return;\n this.current = this.current\n ? await this.api.transitionChatInteractionSession(\n this.workspaceId,\n this.chatId,\n this.current.id,\n pending\n )\n : await this.api.createChatInteractionSession(this.workspaceId, this.chatId, {\n ...pending,\n clientSessionId: this.clientSessionId,\n });\n this.pending = undefined;\n }\n}\n"],"mappings":";AACO,SAAS,eAAe,MAAkC;AAC9D,MAAI,OAAO,aAAa,YAAa,QAAO;AAE5C,QAAM,UAAU,SAAS,OAAO,MAAM,GAAG;AACzC,aAAW,UAAU,SAAS;AAC3B,UAAM,gBAAgB,OAAO,KAAK;AAClC,UAAM,UAAU,cAAc,QAAQ,GAAG;AACzC,QAAI,YAAY,GAAI;AAEpB,UAAM,aAAa,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