@agents24/node 0.5.31 → 0.5.33
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/compatibility.json +5 -5
- package/dist/artifacts.cjs +12 -0
- package/dist/artifacts.cjs.map +1 -1
- package/dist/artifacts.d.cts +13 -1
- package/dist/artifacts.d.ts +13 -1
- package/dist/artifacts.js +12 -1
- package/dist/artifacts.js.map +1 -1
- package/dist/bff.cjs +266 -139
- package/dist/bff.cjs.map +1 -1
- package/dist/bff.d.cts +15 -7
- package/dist/bff.d.ts +15 -7
- package/dist/bff.js +266 -140
- package/dist/bff.js.map +1 -1
- package/dist/{client-vFBe6Sfx.d.cts → client-IX8nsoyr.d.cts} +66 -16
- package/dist/{client-vFBe6Sfx.d.ts → client-IX8nsoyr.d.ts} +66 -16
- package/dist/index.cjs +46 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +47 -5
- package/dist/index.js.map +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.js.map +1 -1
- package/dist/types/artifacts.d.ts +12 -0
- package/dist/types/artifacts.d.ts.map +1 -1
- package/dist/types/bff-agent-resolution.d.ts +5 -0
- package/dist/types/bff-agent-resolution.d.ts.map +1 -1
- package/dist/types/bff-bootstrap.d.ts +17 -0
- package/dist/types/bff-bootstrap.d.ts.map +1 -0
- package/dist/types/bff-conversation-submission.d.ts +16 -0
- package/dist/types/bff-conversation-submission.d.ts.map +1 -0
- package/dist/types/bff-errors.d.ts +1 -1
- package/dist/types/bff-errors.d.ts.map +1 -1
- package/dist/types/bff-history.d.ts +17 -0
- package/dist/types/bff-history.d.ts.map +1 -0
- package/dist/types/bff-multi-agent.d.ts +12 -0
- package/dist/types/bff-multi-agent.d.ts.map +1 -0
- package/dist/types/bff-request.d.ts +3 -1
- package/dist/types/bff-request.d.ts.map +1 -1
- package/dist/types/bff-resolver.d.ts +9 -0
- package/dist/types/bff-resolver.d.ts.map +1 -0
- package/dist/types/bff-single-agent.d.ts +5 -0
- package/dist/types/bff-single-agent.d.ts.map +1 -0
- package/dist/types/bff.d.ts +2 -4
- package/dist/types/bff.d.ts.map +1 -1
- package/dist/types/embed-types.d.ts +2 -0
- package/dist/types/embed-types.d.ts.map +1 -1
- package/dist/types/embed.d.ts +2 -2
- package/dist/types/embed.d.ts.map +1 -1
- package/dist/types/generated/embed.d.ts +8 -0
- package/dist/types/generated/embed.d.ts.map +1 -0
- package/dist/types/generated/manifest.d.ts +1 -1
- package/dist/types/generated/manifest.d.ts.map +1 -1
- package/dist/types/streams.d.ts +1 -1
- package/dist/types/streams.d.ts.map +1 -1
- package/dist/types/types.d.ts +41 -0
- package/dist/types/types.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/bff.js
CHANGED
|
@@ -52,7 +52,7 @@ var CUSTOMER_IDENTITY_CACHE_TTL_MS = 6e4;
|
|
|
52
52
|
var CUSTOMER_IDENTITY_CACHE_MAX_ENTRIES = 1024;
|
|
53
53
|
function createCustomerIdentityResolver(embed, integrationId, integrationName) {
|
|
54
54
|
const cache = /* @__PURE__ */ new Map();
|
|
55
|
-
|
|
55
|
+
const resolve = async (principal) => {
|
|
56
56
|
const profile = {
|
|
57
57
|
display_name: principal.displayName,
|
|
58
58
|
email: principal.email,
|
|
@@ -87,6 +87,12 @@ function createCustomerIdentityResolver(embed, integrationId, integrationName) {
|
|
|
87
87
|
});
|
|
88
88
|
return value;
|
|
89
89
|
};
|
|
90
|
+
return Object.assign(resolve, { remember(principal, reference) {
|
|
91
|
+
const profile = Object.fromEntries(Object.entries({ display_name: principal.displayName, email: principal.email, avatar_url: principal.avatarUrl }).filter(([, value]) => value !== void 0));
|
|
92
|
+
const key = JSON.stringify([integrationId, principal.issuer, principal.subject, profile]);
|
|
93
|
+
cache.set(key, { expiresAt: Date.now() + CUSTOMER_IDENTITY_CACHE_TTL_MS, value: Promise.resolve(normalized(reference, "customer_principal_ref")) });
|
|
94
|
+
while (cache.size > CUSTOMER_IDENTITY_CACHE_MAX_ENTRIES) cache.delete(cache.keys().next().value);
|
|
95
|
+
} });
|
|
90
96
|
}
|
|
91
97
|
function normalizeBasePath(value) {
|
|
92
98
|
const path = String(value || "/api/agents24").trim().replace(/\/+$/, "");
|
|
@@ -227,6 +233,82 @@ function computerFileQuery(url, requirePath) {
|
|
|
227
233
|
};
|
|
228
234
|
}
|
|
229
235
|
|
|
236
|
+
// src/bff-history.ts
|
|
237
|
+
function historyProjection(value, historical) {
|
|
238
|
+
const row = objectValue(value);
|
|
239
|
+
if (Array.isArray(row.items)) return { ...row, items: row.items.map((item) => historyProjection(item, historical)) };
|
|
240
|
+
if (row.thread) return { ...row, thread: historyProjection(row.thread, historical) };
|
|
241
|
+
if (row.runtime_selection) return { ...row, read_only: historical.has(String(objectValue(row.runtime_selection).agent_id)) };
|
|
242
|
+
return value;
|
|
243
|
+
}
|
|
244
|
+
function assertWritableAgent(agent, historical) {
|
|
245
|
+
if (historical.has(agent)) throw new BffInputError(409, "THREAD_READ_ONLY", "This conversation is read-only. Start a new chat.");
|
|
246
|
+
}
|
|
247
|
+
async function guardHistoricalRequest(input) {
|
|
248
|
+
const { request, path, historical } = input;
|
|
249
|
+
if (!historical.size || request.method === "GET" || request.method === "HEAD" || request.method === "DELETE" && /^\/threads\/[^/]+$/.test(path) || request.method === "POST" && (/^\/attachments\/[^/]+\/content-access$/.test(path) || /^\/runs\/[^/]+\/attach$/.test(path) || /^\/threads\/[^/]+\/computer\/content-access$/.test(path))) return;
|
|
250
|
+
let threadId = path.match(/^\/threads\/([^/]+)/)?.[1];
|
|
251
|
+
if (path === "/chat/stream") threadId = stringValue((await requestJson(request.clone())).threadId);
|
|
252
|
+
if (path === "/attachments/upload") threadId = stringValue((await requestMultipart(request.clone())).get("thread_id"));
|
|
253
|
+
const scope = {
|
|
254
|
+
externalUserId: input.externalUserId,
|
|
255
|
+
integrationId: input.integrationId,
|
|
256
|
+
externalSessionId: input.resolution.principal.externalSessionId,
|
|
257
|
+
chatScope: input.resolution.chatScope,
|
|
258
|
+
runtimeTarget: input.runtimeTarget
|
|
259
|
+
};
|
|
260
|
+
if (threadId) {
|
|
261
|
+
const thread = await input.embed.getConversationThread(decodeURIComponent(threadId), { ...scope, agentIds: input.agentIds });
|
|
262
|
+
assertWritableAgent(String(thread.runtime_selection.agent_id), historical);
|
|
263
|
+
}
|
|
264
|
+
const runId = path.match(/^\/runs\/([^/]+)/)?.[1];
|
|
265
|
+
if (runId) {
|
|
266
|
+
const run = await input.embed.resolveConversationRun(decodeURIComponent(runId), {
|
|
267
|
+
agent_ids: input.agentIds,
|
|
268
|
+
external_user_id: scope.externalUserId,
|
|
269
|
+
integration_id: scope.integrationId,
|
|
270
|
+
external_session_id: scope.externalSessionId,
|
|
271
|
+
chat_scope: scope.chatScope,
|
|
272
|
+
runtime_target: scope.runtimeTarget
|
|
273
|
+
});
|
|
274
|
+
assertWritableAgent(run.agent_id, historical);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/bff-conversation-submission.ts
|
|
279
|
+
async function submitConversationStream(input) {
|
|
280
|
+
const { request, body, resolution } = input;
|
|
281
|
+
const value = messageBody({ ...body, mode: "queue" });
|
|
282
|
+
const upstream = await input.options.client.embed.openConversationSubmission(stringValue(body.threadId), {
|
|
283
|
+
...input.identity,
|
|
284
|
+
integration_id: input.integrationId,
|
|
285
|
+
runtime_target: input.runtimeTarget,
|
|
286
|
+
agent_ids: input.agents.map((agent) => agent.agentId),
|
|
287
|
+
agent_versions: Object.fromEntries(input.agents.filter((agent) => agent.agentVersionId).map((agent) => [agent.agentId, agent.agentVersionId])),
|
|
288
|
+
input: value.input,
|
|
289
|
+
attachment_ids: value.attachmentIds,
|
|
290
|
+
client_submission_id: value.clientSubmissionId,
|
|
291
|
+
...input.requestedAgentId ? { requested_agent_id: input.requestedAgentId } : {},
|
|
292
|
+
...value.requestedModelId ? { requested_model_id: value.requestedModelId } : {},
|
|
293
|
+
...resolution.chatScope === void 0 ? {} : { chat_scope: resolution.chatScope },
|
|
294
|
+
...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
|
|
295
|
+
...resolution.trustedContext === void 0 ? {} : { trusted_context: resolution.trustedContext },
|
|
296
|
+
...resolution.knowledgeNamespaces === void 0 ? {} : { knowledge_namespaces: resolution.knowledgeNamespaces },
|
|
297
|
+
tool_inputs: value.toolInputs,
|
|
298
|
+
metadata: objectValue(body.metadata)
|
|
299
|
+
}, {
|
|
300
|
+
signal: request.signal,
|
|
301
|
+
idempotencyKey: request.headers.get("idempotency-key") || void 0,
|
|
302
|
+
streamFeatures: new URL(request.url).searchParams.get("stream_features") || ""
|
|
303
|
+
});
|
|
304
|
+
const headers = new Headers({ "Cache-Control": "no-store", "X-Accel-Buffering": "no" });
|
|
305
|
+
for (const name of ["content-type", "x-run-id", "x-thread-id"]) {
|
|
306
|
+
const value2 = upstream.headers.get(name);
|
|
307
|
+
if (value2) headers.set(name, value2);
|
|
308
|
+
}
|
|
309
|
+
return mergeHeaders(new Response(upstream.body, { status: upstream.status, headers }), resolution.responseHeaders);
|
|
310
|
+
}
|
|
311
|
+
|
|
230
312
|
// src/bff-delegations.ts
|
|
231
313
|
function delegationRoute(path) {
|
|
232
314
|
return /^\/threads\/([^/]+)\/delegations(?:\/(events|[^/]+)(?:\/(history|actions))?)?$/.exec(path);
|
|
@@ -267,47 +349,6 @@ async function dispatchDelegations(request, path, embed, agentId, scope) {
|
|
|
267
349
|
throw new BffInputError(404, "NOT_FOUND", "The requested task route does not exist.");
|
|
268
350
|
}
|
|
269
351
|
|
|
270
|
-
// src/bff-agent-resolution.ts
|
|
271
|
-
function clean(value) {
|
|
272
|
-
const result = typeof value === "string" ? value.trim() : "";
|
|
273
|
-
return result || void 0;
|
|
274
|
-
}
|
|
275
|
-
function required(value, field) {
|
|
276
|
-
const result = clean(value);
|
|
277
|
-
if (!result || /[\r\n\0]/.test(result)) throw new Error(`${field} is required.`);
|
|
278
|
-
return result;
|
|
279
|
-
}
|
|
280
|
-
function prepareAgents24BffAgentResolution(options) {
|
|
281
|
-
if (!options.agents.length || options.agents.length > 50) {
|
|
282
|
-
throw new Error("agents must contain between one and 50 Agents.");
|
|
283
|
-
}
|
|
284
|
-
const configured = options.agents.map((item) => {
|
|
285
|
-
const agentId = clean(item.agentId);
|
|
286
|
-
const agentAlias = clean(item.agentAlias);
|
|
287
|
-
if (Boolean(agentId) === Boolean(agentAlias)) {
|
|
288
|
-
throw new Error("Each Agent requires exactly one of agentId or agentAlias.");
|
|
289
|
-
}
|
|
290
|
-
return { agentId, agentAlias, agentVersionId: clean(item.agentVersionId) };
|
|
291
|
-
});
|
|
292
|
-
return async () => {
|
|
293
|
-
const agents = await Promise.all(configured.map(async (item) => {
|
|
294
|
-
if (item.agentAlias) {
|
|
295
|
-
const resolution = await options.client.embed.resolveAgentAlias(item.agentAlias);
|
|
296
|
-
return {
|
|
297
|
-
agentId: required(resolution.agent_id, "agentId"),
|
|
298
|
-
agentAlias: required(item.agentAlias, "agentAlias"),
|
|
299
|
-
agentVersionId: item.agentVersionId
|
|
300
|
-
};
|
|
301
|
-
}
|
|
302
|
-
return { agentId: required(item.agentId, "agentId"), agentVersionId: item.agentVersionId };
|
|
303
|
-
}));
|
|
304
|
-
if (new Set(agents.map((item) => item.agentId)).size !== agents.length) {
|
|
305
|
-
throw new Error("Configured Agent selectors must resolve to unique Agents.");
|
|
306
|
-
}
|
|
307
|
-
return agents;
|
|
308
|
-
};
|
|
309
|
-
}
|
|
310
|
-
|
|
311
352
|
// src/errors.ts
|
|
312
353
|
var Agents24SDKError = class extends Error {
|
|
313
354
|
kind;
|
|
@@ -346,7 +387,7 @@ var Agents24SDKError = class extends Error {
|
|
|
346
387
|
};
|
|
347
388
|
|
|
348
389
|
// src/bff-errors.ts
|
|
349
|
-
function publicError(status, code, message, retryable = false, violations) {
|
|
390
|
+
function publicError(status, code, message, retryable = false, violations, retryAfterMs = null) {
|
|
350
391
|
const category = status === 401 ? "authentication" : status === 403 ? "authorization" : status === 404 ? "not_found" : status === 409 ? "conflict" : status === 429 ? "rate_limit" : status >= 500 ? "internal" : "validation";
|
|
351
392
|
return Response.json({
|
|
352
393
|
schema_version: "agents24.failure.v1",
|
|
@@ -356,7 +397,7 @@ function publicError(status, code, message, retryable = false, violations) {
|
|
|
356
397
|
message,
|
|
357
398
|
request_id: randomUUID(),
|
|
358
399
|
retryable,
|
|
359
|
-
retry_after_ms:
|
|
400
|
+
retry_after_ms: retryAfterMs,
|
|
360
401
|
details: {}
|
|
361
402
|
}, {
|
|
362
403
|
status,
|
|
@@ -552,7 +593,33 @@ function sseResponse(execute, headers, failurePayload, onFailure, requestSignal,
|
|
|
552
593
|
return new Response(stream, { headers: sseHeaders(headers) });
|
|
553
594
|
}
|
|
554
595
|
|
|
555
|
-
// src/bff.ts
|
|
596
|
+
// src/bff-resolver.ts
|
|
597
|
+
var AgentBffResolverError = class extends Error {
|
|
598
|
+
constructor(kind, retryAfterMs) {
|
|
599
|
+
super("Application identity could not be resolved.");
|
|
600
|
+
this.kind = kind;
|
|
601
|
+
this.retryAfterMs = retryAfterMs;
|
|
602
|
+
}
|
|
603
|
+
kind;
|
|
604
|
+
retryAfterMs;
|
|
605
|
+
};
|
|
606
|
+
function resolverErrorResponse(error) {
|
|
607
|
+
if (!(error instanceof AgentBffResolverError)) return errorResponse(error);
|
|
608
|
+
const definition = {
|
|
609
|
+
unauthenticated: [401, "PRINCIPAL_REQUIRED", "A valid application session is required."],
|
|
610
|
+
denied: [403, "PRINCIPAL_DENIED", "Access to this application is denied."],
|
|
611
|
+
unavailable: [503, "PRINCIPAL_UNAVAILABLE", "Application identity is temporarily unavailable."]
|
|
612
|
+
};
|
|
613
|
+
const [status, code, message] = definition[error.kind];
|
|
614
|
+
const delay = Number.isFinite(error.retryAfterMs) && error.retryAfterMs >= 0 ? Math.min(error.retryAfterMs, 6e4) : null;
|
|
615
|
+
const response = publicError(status, code, message, status >= 500, void 0, delay);
|
|
616
|
+
if (Number.isFinite(error.retryAfterMs) && error.retryAfterMs >= 0) {
|
|
617
|
+
return new Response(response.body, { status, headers: { ...Object.fromEntries(response.headers), "Retry-After": String(Math.ceil(delay / 1e3)) } });
|
|
618
|
+
}
|
|
619
|
+
return response;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// src/bff-single-agent.ts
|
|
556
623
|
function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity) {
|
|
557
624
|
const agentId = normalized(options.agentId, "agentId");
|
|
558
625
|
const agentVersionId = stringValue(options.agentVersionId);
|
|
@@ -572,7 +639,7 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
|
|
|
572
639
|
const streamFailure = (request, operation) => (error) => {
|
|
573
640
|
reportFailureResponse(options.onDiagnostic, request, operation, errorResponse(error));
|
|
574
641
|
};
|
|
575
|
-
return async (request) => {
|
|
642
|
+
return async (request, trustedResolution) => {
|
|
576
643
|
const url = new URL(request.url);
|
|
577
644
|
if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {
|
|
578
645
|
return publicError(404, "NOT_FOUND", "The requested BFF route does not exist.");
|
|
@@ -583,18 +650,19 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
|
|
|
583
650
|
const path = url.pathname.slice(basePath.length) || "/";
|
|
584
651
|
let resolution;
|
|
585
652
|
try {
|
|
586
|
-
resolution = await options.resolvePrincipal(request);
|
|
653
|
+
resolution = trustedResolution || await options.resolvePrincipal(request);
|
|
587
654
|
resolution.principal.subject = normalized(resolution.principal.subject, "subject");
|
|
588
655
|
if (resolution.principal.issuer !== void 0) {
|
|
589
656
|
resolution.principal.issuer = normalized(resolution.principal.issuer, "issuer");
|
|
590
657
|
}
|
|
591
|
-
} catch {
|
|
592
|
-
return
|
|
658
|
+
} catch (error) {
|
|
659
|
+
return resolverErrorResponse(error);
|
|
593
660
|
}
|
|
594
661
|
const principal = resolution.principal;
|
|
595
662
|
const idempotencyKey = stringValue(request.headers.get("idempotency-key"));
|
|
596
663
|
try {
|
|
597
664
|
const customerPrincipalRef = await resolveCustomerIdentity(principal);
|
|
665
|
+
await options.onPrincipalResolved?.(request, resolution, customerPrincipalRef);
|
|
598
666
|
const identity = {
|
|
599
667
|
external_user_id: customerPrincipalRef,
|
|
600
668
|
...principal.externalSessionId ? { external_session_id: principal.externalSessionId } : {}
|
|
@@ -649,12 +717,14 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
|
|
|
649
717
|
input,
|
|
650
718
|
attachmentIds,
|
|
651
719
|
...resolution.customerTenant === void 0 ? {} : { customerTenant: resolution.customerTenant },
|
|
720
|
+
...resolution.trustedContext === void 0 ? {} : { trustedContext: resolution.trustedContext },
|
|
652
721
|
...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {},
|
|
653
722
|
...resolution.knowledgeNamespaces === void 0 ? {} : { knowledgeNamespaces: resolution.knowledgeNamespaces },
|
|
654
723
|
toolInputs: objectValue(body.toolInputs),
|
|
655
724
|
...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) }
|
|
656
725
|
}, { idempotencyKey }) : await embed.startAgentRun(agentId, {
|
|
657
726
|
...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
|
|
727
|
+
...resolution.trustedContext === void 0 ? {} : { trusted_context: resolution.trustedContext },
|
|
658
728
|
...identity,
|
|
659
729
|
integration_id: integrationId,
|
|
660
730
|
...resolution.chatScope === void 0 ? {} : { chat_scope: resolution.chatScope },
|
|
@@ -685,7 +755,7 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
|
|
|
685
755
|
cursor: 0
|
|
686
756
|
}, (event) => {
|
|
687
757
|
if (event.event !== "assistant.completed" || new URL(request.url).searchParams.get("stream_features")?.split(",").includes("assistant-completion-v1")) return write(event);
|
|
688
|
-
}, { signal, onControl: control, leaseSeconds: 60 });
|
|
758
|
+
}, { signal, onControl: control, leaseSeconds: 60, streamFeatures: url.searchParams.get("stream_features") || "", onPreview: (frame) => write(frame) });
|
|
689
759
|
}, {
|
|
690
760
|
"X-Run-ID": admittedRunId,
|
|
691
761
|
...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
|
|
@@ -799,7 +869,7 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
|
|
|
799
869
|
response = json(await embed.submitAgentThreadMessage(
|
|
800
870
|
agentId,
|
|
801
871
|
threadId,
|
|
802
|
-
{ ...threadIdentity, integrationId, ...messageBody(body), ...resolution.knowledgeNamespaces === void 0 ? {} : { knowledgeNamespaces: resolution.knowledgeNamespaces }, agentVersionId: agentVersionId ?? null },
|
|
872
|
+
{ ...threadIdentity, integrationId, ...messageBody(body), ...resolution.trustedContext === void 0 ? {} : { trustedContext: resolution.trustedContext }, ...resolution.customerTenant === void 0 ? {} : { customerTenant: resolution.customerTenant }, ...resolution.knowledgeNamespaces === void 0 ? {} : { knowledgeNamespaces: resolution.knowledgeNamespaces }, agentVersionId: agentVersionId ?? null },
|
|
803
873
|
{ idempotencyKey }
|
|
804
874
|
));
|
|
805
875
|
} else if (/^\/threads\/[^/]+\/messages\/[^/]+$/.test(path) && request.method === "PATCH") {
|
|
@@ -973,11 +1043,14 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
|
|
|
973
1043
|
if (error instanceof BffInputError) {
|
|
974
1044
|
return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", publicError(error.status, error.code, error.message)), resolution.responseHeaders);
|
|
975
1045
|
}
|
|
976
|
-
return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request",
|
|
1046
|
+
return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error)), resolution.responseHeaders);
|
|
977
1047
|
}
|
|
978
1048
|
};
|
|
979
1049
|
}
|
|
980
|
-
|
|
1050
|
+
|
|
1051
|
+
// src/bff-multi-agent.ts
|
|
1052
|
+
function createResolvedAgents24BffHandler(options, sharedIdentity) {
|
|
1053
|
+
const historical = new Set(options.readOnlyAgentIds || []);
|
|
981
1054
|
const runtimeTarget = options.runtimeTarget || "published";
|
|
982
1055
|
const basePath = normalizeBasePath(options.basePath);
|
|
983
1056
|
const integrationId = normalized(options.integrationId, "integrationId");
|
|
@@ -991,7 +1064,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
991
1064
|
if (runtimeTarget === "draft" && agents.some((agent) => agent.agentVersionId)) {
|
|
992
1065
|
throw new Error("agentVersionId cannot be used with draft runtimeTarget.");
|
|
993
1066
|
}
|
|
994
|
-
const resolveCustomerIdentity = createCustomerIdentityResolver(
|
|
1067
|
+
const resolveCustomerIdentity = sharedIdentity || createCustomerIdentityResolver(
|
|
995
1068
|
options.client.embed,
|
|
996
1069
|
integrationId,
|
|
997
1070
|
stringValue(options.integrationName)
|
|
@@ -1030,11 +1103,13 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1030
1103
|
resolution = await options.resolvePrincipal(request);
|
|
1031
1104
|
resolution.principal.subject = normalized(resolution.principal.subject, "subject");
|
|
1032
1105
|
if (resolution.principal.issuer !== void 0) resolution.principal.issuer = normalized(resolution.principal.issuer, "issuer");
|
|
1033
|
-
} catch {
|
|
1034
|
-
return
|
|
1106
|
+
} catch (error) {
|
|
1107
|
+
return resolverErrorResponse(error);
|
|
1035
1108
|
}
|
|
1036
1109
|
try {
|
|
1037
1110
|
const externalUserId = await resolveCustomerIdentity(resolution.principal);
|
|
1111
|
+
await guardHistoricalRequest({ request, path, historical, agentIds: agents.map((row) => row.agentId), embed: options.client.embed, resolution, externalUserId, integrationId, runtimeTarget });
|
|
1112
|
+
await options.onPrincipalResolved?.(request, resolution, externalUserId);
|
|
1038
1113
|
const identity = {
|
|
1039
1114
|
external_user_id: externalUserId,
|
|
1040
1115
|
...resolution.principal.externalSessionId ? { external_session_id: resolution.principal.externalSessionId } : {}
|
|
@@ -1064,7 +1139,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1064
1139
|
headers: request.headers,
|
|
1065
1140
|
body,
|
|
1066
1141
|
signal: request.signal
|
|
1067
|
-
}));
|
|
1142
|
+
}), resolution);
|
|
1068
1143
|
};
|
|
1069
1144
|
const resolveRunAgent = async (runId) => {
|
|
1070
1145
|
const result = await options.client.embed.resolveConversationRun(runId, {
|
|
@@ -1087,76 +1162,30 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1087
1162
|
});
|
|
1088
1163
|
return (await requestedAgent(detail.runtime_selection?.agent_id)).agentId;
|
|
1089
1164
|
};
|
|
1090
|
-
if (request.method === "GET" && path === "/bootstrap") {
|
|
1091
|
-
const candidates = await Promise.all(agents.map(async (agent) => {
|
|
1092
|
-
const [raw, policy] = await Promise.all([
|
|
1093
|
-
options.client.embed.getRuntimeBootstrap(agent.agentId, agent.agentVersionId, runtimeTarget),
|
|
1094
|
-
options.client.embed.getResourcePolicy(agent.agentId, {
|
|
1095
|
-
external_user_id: externalUserId,
|
|
1096
|
-
integration_id: integrationId,
|
|
1097
|
-
...agent.agentVersionId ? { agent_version_id: agent.agentVersionId } : {},
|
|
1098
|
-
runtime_target: runtimeTarget
|
|
1099
|
-
})
|
|
1100
|
-
]);
|
|
1101
|
-
const alias = normalized(String(raw.agent_alias || ""), "agent_alias");
|
|
1102
|
-
agent.agentAlias = alias;
|
|
1103
|
-
agentBySelector.set(alias, agent);
|
|
1104
|
-
for (const item of stringList(raw.agent_aliases)) agentBySelector.set(item, agent);
|
|
1105
|
-
return { agent, raw, policy };
|
|
1106
|
-
}));
|
|
1107
|
-
const selected = await requestedAgent(url.searchParams.get("agent_id"));
|
|
1108
|
-
const allowed = candidates.filter((candidate) => candidate.policy.agent_access_allowed !== false);
|
|
1109
|
-
const selectedCandidate = allowed.find((candidate) => candidate.agent.agentId === selected.agentId) || allowed[0];
|
|
1110
|
-
if (!selectedCandidate) throw new BffInputError(403, "RESOURCE_POLICY_ACCESS_DENIED", "No configured Agent is available.");
|
|
1111
|
-
const document = bootstrapDocument(selectedCandidate.raw, selectedCandidate.agent.agentVersionId);
|
|
1112
|
-
const features = objectValue(document.features);
|
|
1113
|
-
features.models = selectedCandidate.policy.model_selection;
|
|
1114
|
-
features.agents = {
|
|
1115
|
-
selectable: allowed.length > 1,
|
|
1116
|
-
default_id: normalized(String(allowed[0].raw.agent_alias || ""), "agent_alias"),
|
|
1117
|
-
options: allowed.map((candidate) => ({
|
|
1118
|
-
id: normalized(String(candidate.raw.agent_alias || ""), "agent_alias"),
|
|
1119
|
-
label: normalized(String(candidate.raw.agent_name || ""), "agent_name")
|
|
1120
|
-
}))
|
|
1121
|
-
};
|
|
1122
|
-
document.features = features;
|
|
1123
|
-
document.capabilities = [
|
|
1124
|
-
.../* @__PURE__ */ new Set([
|
|
1125
|
-
...document.capabilities || [],
|
|
1126
|
-
...allowed.length > 1 ? ["agents.select"] : [],
|
|
1127
|
-
...selectedCandidate.policy.model_selection.selectable ? ["models.select"] : []
|
|
1128
|
-
])
|
|
1129
|
-
];
|
|
1130
|
-
return mergeHeaders(json(document), resolution.responseHeaders);
|
|
1131
|
-
}
|
|
1132
1165
|
if (request.method === "POST" && path === "/chat/stream") {
|
|
1133
1166
|
const body = await requestJson(request);
|
|
1134
1167
|
const threadId = stringValue(body.threadId);
|
|
1135
|
-
|
|
1136
|
-
|
|
1168
|
+
if (threadId && body.requestedAgentId) assertWritableAgent((await requestedAgent(body.requestedAgentId)).agentId, historical);
|
|
1169
|
+
if (threadId) return submitConversationStream({
|
|
1170
|
+
options,
|
|
1171
|
+
request,
|
|
1172
|
+
body,
|
|
1173
|
+
resolution,
|
|
1174
|
+
agents: agents.filter((agent) => !historical.has(agent.agentId)),
|
|
1175
|
+
identity,
|
|
1176
|
+
integrationId,
|
|
1177
|
+
runtimeTarget,
|
|
1178
|
+
requestedAgentId: body.requestedAgentId ? (await requestedAgent(body.requestedAgentId)).agentId : void 0
|
|
1179
|
+
});
|
|
1180
|
+
const selected = await requestedAgent(body.requestedAgentId);
|
|
1181
|
+
assertWritableAgent(selected.agentId, historical);
|
|
1137
1182
|
const input = stringValue(body.input);
|
|
1138
1183
|
const attachmentIds = stringList(body.attachmentIds);
|
|
1139
1184
|
if (!input && attachmentIds.length === 0) throw new BffInputError(400, "INPUT_REQUIRED", "A message or attachment is required.");
|
|
1140
1185
|
if (input && input.length > MAX_INPUT_LENGTH) throw new BffInputError(413, "INPUT_TOO_LARGE", "The message is too large.");
|
|
1141
1186
|
if (attachmentIds.length > MAX_ATTACHMENTS) throw new BffInputError(400, "TOO_MANY_ATTACHMENTS", `At most ${MAX_ATTACHMENTS} attachments are allowed.`);
|
|
1142
|
-
const admission =
|
|
1143
|
-
|
|
1144
|
-
...resolution.principal.externalSessionId ? { externalSessionId: resolution.principal.externalSessionId } : {},
|
|
1145
|
-
integrationId,
|
|
1146
|
-
...resolution.chatScope === void 0 ? {} : { chatScope: resolution.chatScope },
|
|
1147
|
-
runtimeTarget,
|
|
1148
|
-
clientSubmissionId: stringValue(body.clientSubmissionId),
|
|
1149
|
-
...body.relayClientId === null ? { relayClientId: null } : stringValue(body.relayClientId) ? { relayClientId: stringValue(body.relayClientId) } : {},
|
|
1150
|
-
agentVersionId: selected.agentVersionId ?? null,
|
|
1151
|
-
mode: "queue",
|
|
1152
|
-
input: input ?? "",
|
|
1153
|
-
attachmentIds,
|
|
1154
|
-
...resolution.customerTenant === void 0 ? {} : { customerTenant: resolution.customerTenant },
|
|
1155
|
-
...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {},
|
|
1156
|
-
...resolution.knowledgeNamespaces === void 0 ? {} : { knowledgeNamespaces: resolution.knowledgeNamespaces },
|
|
1157
|
-
toolInputs: objectValue(body.toolInputs),
|
|
1158
|
-
...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) }
|
|
1159
|
-
}, { idempotencyKey: stringValue(request.headers.get("idempotency-key")) }) : await options.client.embed.startAgentRun(selected.agentId, {
|
|
1187
|
+
const admission = await options.client.embed.startAgentRun(selected.agentId, {
|
|
1188
|
+
...resolution.trustedContext === void 0 ? {} : { trusted_context: resolution.trustedContext },
|
|
1160
1189
|
...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
|
|
1161
1190
|
...identity,
|
|
1162
1191
|
...selected.agentVersionId ? { agent_version_id: selected.agentVersionId } : {},
|
|
@@ -1172,7 +1201,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1172
1201
|
tool_inputs: objectValue(body.toolInputs),
|
|
1173
1202
|
...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) },
|
|
1174
1203
|
client: objectValue(body.client)
|
|
1175
|
-
}, { idempotencyKey: stringValue(request.headers.get("idempotency-key")) });
|
|
1204
|
+
}, { idempotencyKey: stringValue(request.headers.get("idempotency-key")), streamFeatures: url.searchParams.get("stream_features") || "" });
|
|
1176
1205
|
const admittedRunId = admission.run_id;
|
|
1177
1206
|
if (!admittedRunId) return mergeHeaders(json(admission, void 0, 202), resolution.responseHeaders);
|
|
1178
1207
|
return mergeHeaders(sseResponse(async (write, signal, control) => {
|
|
@@ -1186,7 +1215,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1186
1215
|
cursor: 0
|
|
1187
1216
|
}, (event) => {
|
|
1188
1217
|
if (event.event !== "assistant.completed" || new URL(request.url).searchParams.get("stream_features")?.split(",").includes("assistant-completion-v1")) return write(event);
|
|
1189
|
-
}, { signal, onControl: control, leaseSeconds: 60 });
|
|
1218
|
+
}, { signal, onControl: control, leaseSeconds: 60, streamFeatures: url.searchParams.get("stream_features") || "", onPreview: (frame) => write(frame) });
|
|
1190
1219
|
}, {
|
|
1191
1220
|
"X-Run-ID": admittedRunId,
|
|
1192
1221
|
...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
|
|
@@ -1198,7 +1227,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1198
1227
|
if (!Number.isInteger(skip) || skip < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) {
|
|
1199
1228
|
throw new BffInputError(400, "INVALID_PAGINATION", "skip must be non-negative and limit must be between 1 and 100.");
|
|
1200
1229
|
}
|
|
1201
|
-
return mergeHeaders(json(await options.client.embed.listAgentThreadsMulti({
|
|
1230
|
+
return mergeHeaders(json(historyProjection(await options.client.embed.listAgentThreadsMulti({
|
|
1202
1231
|
agent_ids: agents.map((agent) => agent.agentId),
|
|
1203
1232
|
external_user_id: externalUserId,
|
|
1204
1233
|
...resolution.principal.externalSessionId ? { external_session_id: resolution.principal.externalSessionId } : {},
|
|
@@ -1207,7 +1236,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1207
1236
|
...resolution.chatScope === void 0 ? {} : { chat_scope: resolution.chatScope },
|
|
1208
1237
|
skip,
|
|
1209
1238
|
limit
|
|
1210
|
-
})), resolution.responseHeaders);
|
|
1239
|
+
}), historical)), resolution.responseHeaders);
|
|
1211
1240
|
}
|
|
1212
1241
|
if (request.method === "GET" && path === "/threads/events") {
|
|
1213
1242
|
const rawCursor = url.searchParams.get("cursor");
|
|
@@ -1228,7 +1257,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1228
1257
|
onControl: control,
|
|
1229
1258
|
leaseSeconds: 60,
|
|
1230
1259
|
...url.searchParams.get("thread_id") ? { threadId: url.searchParams.get("thread_id") } : {}
|
|
1231
|
-
}, (event) => write(event));
|
|
1260
|
+
}, (event) => write(historyProjection(event, historical)));
|
|
1232
1261
|
}, void 0, () => ({
|
|
1233
1262
|
schema_version: "agents24.thread_summary_event.v1",
|
|
1234
1263
|
event: "snapshot_required",
|
|
@@ -1246,8 +1275,11 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1246
1275
|
if (/^\/threads\/[^/]+\/(?:messages(?:\/[^/]+)?|queue\/resume)$/.test(path) && ["GET", "POST", "PATCH", "DELETE"].includes(request.method)) {
|
|
1247
1276
|
const threadId = routeId(path, /^\/threads\/([^/]+)\//, "threadId");
|
|
1248
1277
|
const storedAgent = await resolveThreadAgent(threadId);
|
|
1278
|
+
if (request.method !== "GET") assertWritableAgent(storedAgent, historical);
|
|
1249
1279
|
const message = request.method === "PATCH" || request.method === "POST" && path.endsWith("/messages") ? await request.clone().json() : void 0;
|
|
1250
|
-
|
|
1280
|
+
const selected = (await requestedAgent(message?.requestedAgentId || storedAgent)).agentId;
|
|
1281
|
+
if (request.method !== "GET") assertWritableAgent(selected, historical);
|
|
1282
|
+
return dispatchToAgent(selected, message);
|
|
1251
1283
|
}
|
|
1252
1284
|
if (/^\/threads\/[^/]+\/computer(?:\/files|\/file|\/content-access)?$/.test(path) && (request.method === "GET" || request.method === "POST" && path.endsWith("/content-access"))) {
|
|
1253
1285
|
const threadId = routeId(path, /^\/threads\/([^/]+)\/computer/, "threadId");
|
|
@@ -1292,7 +1324,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1292
1324
|
if (detailLimit !== void 0 && (!Number.isInteger(detailLimit) || detailLimit < 1 || detailLimit > 100)) {
|
|
1293
1325
|
throw new BffInputError(400, "INVALID_PAGINATION", "limit must be between 1 and 100.");
|
|
1294
1326
|
}
|
|
1295
|
-
return mergeHeaders(json(await options.client.embed.getConversationThread(threadId, {
|
|
1327
|
+
return mergeHeaders(json(historyProjection(await options.client.embed.getConversationThread(threadId, {
|
|
1296
1328
|
agentIds: agents.map((agent) => agent.agentId),
|
|
1297
1329
|
externalUserId,
|
|
1298
1330
|
...resolution.principal.externalSessionId ? { externalSessionId: resolution.principal.externalSessionId } : {},
|
|
@@ -1301,12 +1333,13 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1301
1333
|
runtimeTarget,
|
|
1302
1334
|
beforeTurnIndex,
|
|
1303
1335
|
limit: detailLimit
|
|
1304
|
-
})), resolution.responseHeaders);
|
|
1336
|
+
}), historical)), resolution.responseHeaders);
|
|
1305
1337
|
}
|
|
1306
1338
|
if (/^\/threads\/[^/]+\/runtime-selection$/.test(path) && request.method === "PATCH") {
|
|
1307
1339
|
const threadId = routeId(path, /^\/threads\/([^/]+)\//, "threadId");
|
|
1308
1340
|
const body = await requestJson(request);
|
|
1309
1341
|
const selected = await requestedAgent(body.preferredAgentId);
|
|
1342
|
+
assertWritableAgent(selected.agentId, historical);
|
|
1310
1343
|
return mergeHeaders(json(await options.client.embed.setConversationRuntimeSelection(threadId, {
|
|
1311
1344
|
agent_ids: agents.map((agent) => agent.agentId),
|
|
1312
1345
|
preferred_agent_id: selected.agentId,
|
|
@@ -1331,6 +1364,7 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1331
1364
|
if (request.method === "POST" && path === "/attachments/upload") {
|
|
1332
1365
|
const form = await requestMultipart(request.clone());
|
|
1333
1366
|
const selected = await requestedAgent(form.get("requested_agent_id"));
|
|
1367
|
+
assertWritableAgent(selected.agentId, historical);
|
|
1334
1368
|
const policy = await options.client.embed.getResourcePolicy(selected.agentId, {
|
|
1335
1369
|
external_user_id: externalUserId,
|
|
1336
1370
|
integration_id: integrationId,
|
|
@@ -1341,7 +1375,22 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1341
1375
|
return dispatchToAgent(selected.agentId);
|
|
1342
1376
|
}
|
|
1343
1377
|
if (request.method === "POST" && /^\/attachments\/[^/]+\/content-access$/.test(path)) {
|
|
1344
|
-
|
|
1378
|
+
const body = await requestJson(request);
|
|
1379
|
+
if (body.disposition !== "inline" && body.disposition !== "attachment") throw new BffInputError(400, "INVALID_DISPOSITION", "Attachment disposition is invalid.");
|
|
1380
|
+
for (const [index, agent] of agents.entries()) {
|
|
1381
|
+
try {
|
|
1382
|
+
return mergeHeaders(json(await options.client.embed.createAttachmentContentAccess(agent.agentId, routeId(path, /^\/attachments\/([^/]+)\/content-access$/, "attachmentId"), {
|
|
1383
|
+
...identity,
|
|
1384
|
+
integration_id: integrationId,
|
|
1385
|
+
runtime_target: runtimeTarget,
|
|
1386
|
+
...resolution.chatScope === void 0 ? {} : { chat_scope: resolution.chatScope },
|
|
1387
|
+
disposition: body.disposition
|
|
1388
|
+
})), resolution.responseHeaders);
|
|
1389
|
+
} catch (error) {
|
|
1390
|
+
if (error.status !== 404 || index === agents.length - 1) throw error;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
throw new BffInputError(404, "NOT_FOUND", "Attachment not found.");
|
|
1345
1394
|
}
|
|
1346
1395
|
if (/^\/runs\/[^/]+\/(?:attach|cancel|feedback)$/.test(path) || /^\/runs\/[^/]+\/hitl\/[^/]+\/resume$/.test(path) || /^\/runs\/[^/]+\/mcp\/servers\/[^/]+\/auth\/start$/.test(path)) {
|
|
1347
1396
|
const runId = routeId(path, /^\/runs\/([^/]+)\//, "runId");
|
|
@@ -1357,31 +1406,108 @@ function createResolvedAgents24BffHandler(options) {
|
|
|
1357
1406
|
return mergeHeaders(publicError(404, "NOT_FOUND", "The requested BFF route does not exist."), resolution.responseHeaders);
|
|
1358
1407
|
} catch (error) {
|
|
1359
1408
|
if (error instanceof BffInputError) return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", publicError(error.status, error.code, error.message)), resolution.responseHeaders);
|
|
1360
|
-
return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request",
|
|
1409
|
+
return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error)), resolution.responseHeaders);
|
|
1361
1410
|
}
|
|
1362
1411
|
};
|
|
1363
1412
|
}
|
|
1413
|
+
|
|
1414
|
+
// src/bff-agent-resolution.ts
|
|
1415
|
+
function clean(value) {
|
|
1416
|
+
const result = typeof value === "string" ? value.trim() : "";
|
|
1417
|
+
return result || void 0;
|
|
1418
|
+
}
|
|
1419
|
+
function required(value, field) {
|
|
1420
|
+
const result = clean(value);
|
|
1421
|
+
if (!result || /[\r\n\0]/.test(result)) throw new Error(`${field} is required.`);
|
|
1422
|
+
return result;
|
|
1423
|
+
}
|
|
1424
|
+
function prepareAgents24BffAgentResolution(options) {
|
|
1425
|
+
if (!options.agents.length || options.agents.length > 50) {
|
|
1426
|
+
throw new Error("agents must contain between one and 50 Agents.");
|
|
1427
|
+
}
|
|
1428
|
+
const configured = options.agents.map((item) => {
|
|
1429
|
+
const agentId = clean(item.agentId);
|
|
1430
|
+
const agentAlias = clean(item.agentAlias);
|
|
1431
|
+
if (Boolean(agentId) === Boolean(agentAlias)) {
|
|
1432
|
+
throw new Error("Each Agent requires exactly one of agentId or agentAlias.");
|
|
1433
|
+
}
|
|
1434
|
+
return { agentId, agentAlias, agentVersionId: clean(item.agentVersionId) };
|
|
1435
|
+
});
|
|
1436
|
+
return async () => {
|
|
1437
|
+
const agents = await Promise.all(configured.map(async (item) => {
|
|
1438
|
+
if (item.agentAlias) {
|
|
1439
|
+
const resolution = await options.client.embed.resolveAgentAlias(item.agentAlias);
|
|
1440
|
+
return {
|
|
1441
|
+
agentId: required(resolution.agent_id, "agentId"),
|
|
1442
|
+
agentAlias: required(item.agentAlias, "agentAlias"),
|
|
1443
|
+
agentVersionId: item.agentVersionId
|
|
1444
|
+
};
|
|
1445
|
+
}
|
|
1446
|
+
return { agentId: required(item.agentId, "agentId"), agentVersionId: item.agentVersionId };
|
|
1447
|
+
}));
|
|
1448
|
+
if (new Set(agents.map((item) => item.agentId)).size !== agents.length) {
|
|
1449
|
+
throw new Error("Configured Agent selectors must resolve to unique Agents.");
|
|
1450
|
+
}
|
|
1451
|
+
return agents;
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
// src/bff-bootstrap.ts
|
|
1456
|
+
function principalIdentity(principal, options) {
|
|
1457
|
+
const profile = Object.fromEntries(Object.entries({ display_name: principal.displayName, email: principal.email, avatar_url: principal.avatarUrl }).filter(([, value]) => value !== void 0));
|
|
1458
|
+
return {
|
|
1459
|
+
integration_id: options.integrationId,
|
|
1460
|
+
subject: normalized(principal.subject, "subject"),
|
|
1461
|
+
...options.integrationName ? { integration_name: options.integrationName } : {},
|
|
1462
|
+
...principal.issuer ? { issuer: normalized(principal.issuer, "issuer") } : {},
|
|
1463
|
+
...Object.keys(profile).length ? { profile } : {}
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
async function runtimeBootstrap(options, request, identityResolver) {
|
|
1467
|
+
const resolution = await options.resolvePrincipal(request);
|
|
1468
|
+
const result = await options.client.embed.bootstrapRuntime({
|
|
1469
|
+
identity: principalIdentity(resolution.principal, options),
|
|
1470
|
+
agents: options.agents.map((agent) => ({
|
|
1471
|
+
..."agentId" in agent && agent.agentId ? { agent_id: agent.agentId } : { agent_alias: agent.agentAlias },
|
|
1472
|
+
...agent.agentVersionId ? { agent_version_id: agent.agentVersionId } : {}
|
|
1473
|
+
})),
|
|
1474
|
+
runtime_target: options.runtimeTarget || "published",
|
|
1475
|
+
selected_agent: new URL(request.url).searchParams.get("agent_id") || void 0
|
|
1476
|
+
});
|
|
1477
|
+
identityResolver.remember(resolution.principal, result.customer_principal_ref);
|
|
1478
|
+
await options.onPrincipalResolved?.(request, resolution, result.customer_principal_ref);
|
|
1479
|
+
return { response: mergeHeaders(json(result.bootstrap), resolution.responseHeaders), result };
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// src/bff.ts
|
|
1364
1483
|
function createAgents24BffHandler(options) {
|
|
1365
1484
|
const resolveAgents = prepareAgents24BffAgentResolution(options);
|
|
1366
|
-
|
|
1367
|
-
const
|
|
1368
|
-
const
|
|
1369
|
-
return createResolvedAgents24BffHandler({ ...options, agents });
|
|
1485
|
+
const resolveHistory = options.readOnlyAgents?.length ? prepareAgents24BffAgentResolution({ ...options, agents: options.readOnlyAgents }) : async () => [];
|
|
1486
|
+
const withHistory = async (agents) => {
|
|
1487
|
+
const history = await resolveHistory();
|
|
1488
|
+
return createResolvedAgents24BffHandler({ ...options, agents: [...agents, ...history], readOnlyAgentIds: history.map((row) => row.agentId) }, identity);
|
|
1370
1489
|
};
|
|
1490
|
+
const identity = createCustomerIdentityResolver(options.client.embed, options.integrationId, options.integrationName);
|
|
1491
|
+
const basePath = normalizeBasePath(options.basePath);
|
|
1492
|
+
let resolvedHandler;
|
|
1371
1493
|
return async (request) => {
|
|
1372
|
-
if (!browserRequestIsSameOrigin(request))
|
|
1373
|
-
return publicError(403, "BFF_ORIGIN_DENIED", "The BFF accepts same-origin browser requests only.");
|
|
1374
|
-
}
|
|
1375
|
-
resolvedHandler ||= resolve();
|
|
1494
|
+
if (!browserRequestIsSameOrigin(request)) return publicError(403, "BFF_ORIGIN_DENIED", "The BFF accepts same-origin browser requests only.");
|
|
1376
1495
|
try {
|
|
1377
|
-
|
|
1496
|
+
if (request.method === "GET" && new URL(request.url).pathname === `${basePath}/bootstrap`) {
|
|
1497
|
+
const { response, result } = await runtimeBootstrap(options, request, identity);
|
|
1498
|
+
const agents = result.resolved_agents.map((row) => ({ agentId: row.agent_id, agentAlias: row.agent_alias, agentVersionId: row.agent_version_id || void 0 }));
|
|
1499
|
+
resolvedHandler = Promise.resolve(await withHistory(agents));
|
|
1500
|
+
return response;
|
|
1501
|
+
}
|
|
1502
|
+
resolvedHandler ||= resolveAgents().then(withHistory);
|
|
1503
|
+
return await (await resolvedHandler)(request);
|
|
1378
1504
|
} catch (error) {
|
|
1379
1505
|
resolvedHandler = void 0;
|
|
1380
|
-
return reportFailureResponse(options.onDiagnostic, request, "
|
|
1506
|
+
return reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error));
|
|
1381
1507
|
}
|
|
1382
1508
|
};
|
|
1383
1509
|
}
|
|
1384
1510
|
|
|
1385
|
-
export { createAgents24BffHandler };
|
|
1511
|
+
export { AgentBffResolverError, createAgents24BffHandler };
|
|
1386
1512
|
//# sourceMappingURL=bff.js.map
|
|
1387
1513
|
//# sourceMappingURL=bff.js.map
|