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