@agents24/node 0.5.31 → 0.5.32

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.
Files changed (56) hide show
  1. package/compatibility.json +5 -5
  2. package/dist/artifacts.cjs +12 -0
  3. package/dist/artifacts.cjs.map +1 -1
  4. package/dist/artifacts.d.cts +13 -1
  5. package/dist/artifacts.d.ts +13 -1
  6. package/dist/artifacts.js +12 -1
  7. package/dist/artifacts.js.map +1 -1
  8. package/dist/bff.cjs +185 -131
  9. package/dist/bff.cjs.map +1 -1
  10. package/dist/bff.d.cts +13 -7
  11. package/dist/bff.d.ts +13 -7
  12. package/dist/bff.js +185 -132
  13. package/dist/bff.js.map +1 -1
  14. package/dist/{client-vFBe6Sfx.d.cts → client-BhE-CjMz.d.cts} +65 -16
  15. package/dist/{client-vFBe6Sfx.d.ts → client-BhE-CjMz.d.ts} +65 -16
  16. package/dist/index.cjs +45 -4
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +3 -3
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +46 -5
  21. package/dist/index.js.map +1 -1
  22. package/dist/server.cjs.map +1 -1
  23. package/dist/server.js.map +1 -1
  24. package/dist/types/artifacts.d.ts +12 -0
  25. package/dist/types/artifacts.d.ts.map +1 -1
  26. package/dist/types/bff-agent-resolution.d.ts +3 -0
  27. package/dist/types/bff-agent-resolution.d.ts.map +1 -1
  28. package/dist/types/bff-bootstrap.d.ts +17 -0
  29. package/dist/types/bff-bootstrap.d.ts.map +1 -0
  30. package/dist/types/bff-conversation-submission.d.ts +16 -0
  31. package/dist/types/bff-conversation-submission.d.ts.map +1 -0
  32. package/dist/types/bff-errors.d.ts +1 -1
  33. package/dist/types/bff-errors.d.ts.map +1 -1
  34. package/dist/types/bff-multi-agent.d.ts +11 -0
  35. package/dist/types/bff-multi-agent.d.ts.map +1 -0
  36. package/dist/types/bff-request.d.ts +3 -1
  37. package/dist/types/bff-request.d.ts.map +1 -1
  38. package/dist/types/bff-resolver.d.ts +9 -0
  39. package/dist/types/bff-resolver.d.ts.map +1 -0
  40. package/dist/types/bff-single-agent.d.ts +5 -0
  41. package/dist/types/bff-single-agent.d.ts.map +1 -0
  42. package/dist/types/bff.d.ts +2 -4
  43. package/dist/types/bff.d.ts.map +1 -1
  44. package/dist/types/embed-types.d.ts +1 -0
  45. package/dist/types/embed-types.d.ts.map +1 -1
  46. package/dist/types/embed.d.ts +2 -2
  47. package/dist/types/embed.d.ts.map +1 -1
  48. package/dist/types/generated/embed.d.ts +8 -0
  49. package/dist/types/generated/embed.d.ts.map +1 -0
  50. package/dist/types/generated/manifest.d.ts +1 -1
  51. package/dist/types/generated/manifest.d.ts.map +1 -1
  52. package/dist/types/streams.d.ts +1 -1
  53. package/dist/types/streams.d.ts.map +1 -1
  54. package/dist/types/types.d.ts +41 -0
  55. package/dist/types/types.d.ts.map +1 -1
  56. 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
- return async (principal) => {
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,40 @@ function computerFileQuery(url, requirePath) {
229
235
  };
230
236
  }
231
237
 
238
+ // src/bff-conversation-submission.ts
239
+ async function submitConversationStream(input) {
240
+ const { request, body, resolution } = input;
241
+ const value = messageBody({ ...body, mode: "queue" });
242
+ const upstream = await input.options.client.embed.openConversationSubmission(stringValue(body.threadId), {
243
+ ...input.identity,
244
+ integration_id: input.integrationId,
245
+ runtime_target: input.runtimeTarget,
246
+ agent_ids: input.agents.map((agent) => agent.agentId),
247
+ agent_versions: Object.fromEntries(input.agents.filter((agent) => agent.agentVersionId).map((agent) => [agent.agentId, agent.agentVersionId])),
248
+ input: value.input,
249
+ attachment_ids: value.attachmentIds,
250
+ client_submission_id: value.clientSubmissionId,
251
+ ...input.requestedAgentId ? { requested_agent_id: input.requestedAgentId } : {},
252
+ ...value.requestedModelId ? { requested_model_id: value.requestedModelId } : {},
253
+ ...resolution.chatScope === void 0 ? {} : { chat_scope: resolution.chatScope },
254
+ ...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
255
+ ...resolution.trustedContext === void 0 ? {} : { trusted_context: resolution.trustedContext },
256
+ ...resolution.knowledgeNamespaces === void 0 ? {} : { knowledge_namespaces: resolution.knowledgeNamespaces },
257
+ tool_inputs: value.toolInputs,
258
+ metadata: objectValue(body.metadata)
259
+ }, {
260
+ signal: request.signal,
261
+ idempotencyKey: request.headers.get("idempotency-key") || void 0,
262
+ streamFeatures: new URL(request.url).searchParams.get("stream_features") || ""
263
+ });
264
+ const headers = new Headers({ "Cache-Control": "no-store", "X-Accel-Buffering": "no" });
265
+ for (const name of ["content-type", "x-run-id", "x-thread-id"]) {
266
+ const value2 = upstream.headers.get(name);
267
+ if (value2) headers.set(name, value2);
268
+ }
269
+ return mergeHeaders(new Response(upstream.body, { status: upstream.status, headers }), resolution.responseHeaders);
270
+ }
271
+
232
272
  // src/bff-delegations.ts
233
273
  function delegationRoute(path) {
234
274
  return /^\/threads\/([^/]+)\/delegations(?:\/(events|[^/]+)(?:\/(history|actions))?)?$/.exec(path);
@@ -269,47 +309,6 @@ async function dispatchDelegations(request, path, embed, agentId, scope) {
269
309
  throw new BffInputError(404, "NOT_FOUND", "The requested task route does not exist.");
270
310
  }
271
311
 
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
312
  // src/errors.ts
314
313
  var Agents24SDKError = class extends Error {
315
314
  kind;
@@ -348,7 +347,7 @@ var Agents24SDKError = class extends Error {
348
347
  };
349
348
 
350
349
  // src/bff-errors.ts
351
- function publicError(status, code, message, retryable = false, violations) {
350
+ function publicError(status, code, message, retryable = false, violations, retryAfterMs = null) {
352
351
  const category = status === 401 ? "authentication" : status === 403 ? "authorization" : status === 404 ? "not_found" : status === 409 ? "conflict" : status === 429 ? "rate_limit" : status >= 500 ? "internal" : "validation";
353
352
  return Response.json({
354
353
  schema_version: "agents24.failure.v1",
@@ -358,7 +357,7 @@ function publicError(status, code, message, retryable = false, violations) {
358
357
  message,
359
358
  request_id: crypto.randomUUID(),
360
359
  retryable,
361
- retry_after_ms: null,
360
+ retry_after_ms: retryAfterMs,
362
361
  details: {}
363
362
  }, {
364
363
  status,
@@ -554,7 +553,33 @@ function sseResponse(execute, headers, failurePayload, onFailure, requestSignal,
554
553
  return new Response(stream, { headers: sseHeaders(headers) });
555
554
  }
556
555
 
557
- // src/bff.ts
556
+ // src/bff-resolver.ts
557
+ var AgentBffResolverError = class extends Error {
558
+ constructor(kind, retryAfterMs) {
559
+ super("Application identity could not be resolved.");
560
+ this.kind = kind;
561
+ this.retryAfterMs = retryAfterMs;
562
+ }
563
+ kind;
564
+ retryAfterMs;
565
+ };
566
+ function resolverErrorResponse(error) {
567
+ if (!(error instanceof AgentBffResolverError)) return errorResponse(error);
568
+ const definition = {
569
+ unauthenticated: [401, "PRINCIPAL_REQUIRED", "A valid application session is required."],
570
+ denied: [403, "PRINCIPAL_DENIED", "Access to this application is denied."],
571
+ unavailable: [503, "PRINCIPAL_UNAVAILABLE", "Application identity is temporarily unavailable."]
572
+ };
573
+ const [status, code, message] = definition[error.kind];
574
+ const delay = Number.isFinite(error.retryAfterMs) && error.retryAfterMs >= 0 ? Math.min(error.retryAfterMs, 6e4) : null;
575
+ const response = publicError(status, code, message, status >= 500, void 0, delay);
576
+ if (Number.isFinite(error.retryAfterMs) && error.retryAfterMs >= 0) {
577
+ return new Response(response.body, { status, headers: { ...Object.fromEntries(response.headers), "Retry-After": String(Math.ceil(delay / 1e3)) } });
578
+ }
579
+ return response;
580
+ }
581
+
582
+ // src/bff-single-agent.ts
558
583
  function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity) {
559
584
  const agentId = normalized(options.agentId, "agentId");
560
585
  const agentVersionId = stringValue(options.agentVersionId);
@@ -574,7 +599,7 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
574
599
  const streamFailure = (request, operation) => (error) => {
575
600
  reportFailureResponse(options.onDiagnostic, request, operation, errorResponse(error));
576
601
  };
577
- return async (request) => {
602
+ return async (request, trustedResolution) => {
578
603
  const url = new URL(request.url);
579
604
  if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {
580
605
  return publicError(404, "NOT_FOUND", "The requested BFF route does not exist.");
@@ -585,18 +610,19 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
585
610
  const path = url.pathname.slice(basePath.length) || "/";
586
611
  let resolution;
587
612
  try {
588
- resolution = await options.resolvePrincipal(request);
613
+ resolution = trustedResolution || await options.resolvePrincipal(request);
589
614
  resolution.principal.subject = normalized(resolution.principal.subject, "subject");
590
615
  if (resolution.principal.issuer !== void 0) {
591
616
  resolution.principal.issuer = normalized(resolution.principal.issuer, "issuer");
592
617
  }
593
- } catch {
594
- return publicError(401, "PRINCIPAL_REQUIRED", "A valid application session is required.");
618
+ } catch (error) {
619
+ return resolverErrorResponse(error);
595
620
  }
596
621
  const principal = resolution.principal;
597
622
  const idempotencyKey = stringValue(request.headers.get("idempotency-key"));
598
623
  try {
599
624
  const customerPrincipalRef = await resolveCustomerIdentity(principal);
625
+ await options.onPrincipalResolved?.(request, resolution, customerPrincipalRef);
600
626
  const identity = {
601
627
  external_user_id: customerPrincipalRef,
602
628
  ...principal.externalSessionId ? { external_session_id: principal.externalSessionId } : {}
@@ -687,7 +713,7 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
687
713
  cursor: 0
688
714
  }, (event) => {
689
715
  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 });
716
+ }, { signal, onControl: control, leaseSeconds: 60, streamFeatures: url.searchParams.get("stream_features") || "", onPreview: (frame) => write(frame) });
691
717
  }, {
692
718
  "X-Run-ID": admittedRunId,
693
719
  ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
@@ -975,11 +1001,13 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
975
1001
  if (error instanceof BffInputError) {
976
1002
  return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", publicError(error.status, error.code, error.message)), resolution.responseHeaders);
977
1003
  }
978
- return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", errorResponse(error)), resolution.responseHeaders);
1004
+ return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error)), resolution.responseHeaders);
979
1005
  }
980
1006
  };
981
1007
  }
982
- function createResolvedAgents24BffHandler(options) {
1008
+
1009
+ // src/bff-multi-agent.ts
1010
+ function createResolvedAgents24BffHandler(options, sharedIdentity) {
983
1011
  const runtimeTarget = options.runtimeTarget || "published";
984
1012
  const basePath = normalizeBasePath(options.basePath);
985
1013
  const integrationId = normalized(options.integrationId, "integrationId");
@@ -993,7 +1021,7 @@ function createResolvedAgents24BffHandler(options) {
993
1021
  if (runtimeTarget === "draft" && agents.some((agent) => agent.agentVersionId)) {
994
1022
  throw new Error("agentVersionId cannot be used with draft runtimeTarget.");
995
1023
  }
996
- const resolveCustomerIdentity = createCustomerIdentityResolver(
1024
+ const resolveCustomerIdentity = sharedIdentity || createCustomerIdentityResolver(
997
1025
  options.client.embed,
998
1026
  integrationId,
999
1027
  stringValue(options.integrationName)
@@ -1032,11 +1060,12 @@ function createResolvedAgents24BffHandler(options) {
1032
1060
  resolution = await options.resolvePrincipal(request);
1033
1061
  resolution.principal.subject = normalized(resolution.principal.subject, "subject");
1034
1062
  if (resolution.principal.issuer !== void 0) resolution.principal.issuer = normalized(resolution.principal.issuer, "issuer");
1035
- } catch {
1036
- return publicError(401, "PRINCIPAL_REQUIRED", "A valid application session is required.");
1063
+ } catch (error) {
1064
+ return resolverErrorResponse(error);
1037
1065
  }
1038
1066
  try {
1039
1067
  const externalUserId = await resolveCustomerIdentity(resolution.principal);
1068
+ await options.onPrincipalResolved?.(request, resolution, externalUserId);
1040
1069
  const identity = {
1041
1070
  external_user_id: externalUserId,
1042
1071
  ...resolution.principal.externalSessionId ? { external_session_id: resolution.principal.externalSessionId } : {}
@@ -1066,7 +1095,7 @@ function createResolvedAgents24BffHandler(options) {
1066
1095
  headers: request.headers,
1067
1096
  body,
1068
1097
  signal: request.signal
1069
- }));
1098
+ }), resolution);
1070
1099
  };
1071
1100
  const resolveRunAgent = async (runId) => {
1072
1101
  const result = await options.client.embed.resolveConversationRun(runId, {
@@ -1089,76 +1118,28 @@ function createResolvedAgents24BffHandler(options) {
1089
1118
  });
1090
1119
  return (await requestedAgent(detail.runtime_selection?.agent_id)).agentId;
1091
1120
  };
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
1121
  if (request.method === "POST" && path === "/chat/stream") {
1135
1122
  const body = await requestJson(request);
1136
1123
  const threadId = stringValue(body.threadId);
1137
- const storedAgent = threadId ? await resolveThreadAgent(threadId) : void 0;
1138
- const selected = await requestedAgent(body.requestedAgentId || storedAgent);
1124
+ if (threadId) return submitConversationStream({
1125
+ options,
1126
+ request,
1127
+ body,
1128
+ resolution,
1129
+ agents,
1130
+ identity,
1131
+ integrationId,
1132
+ runtimeTarget,
1133
+ requestedAgentId: body.requestedAgentId ? (await requestedAgent(body.requestedAgentId)).agentId : void 0
1134
+ });
1135
+ const selected = await requestedAgent(body.requestedAgentId);
1139
1136
  const input = stringValue(body.input);
1140
1137
  const attachmentIds = stringList(body.attachmentIds);
1141
1138
  if (!input && attachmentIds.length === 0) throw new BffInputError(400, "INPUT_REQUIRED", "A message or attachment is required.");
1142
1139
  if (input && input.length > MAX_INPUT_LENGTH) throw new BffInputError(413, "INPUT_TOO_LARGE", "The message is too large.");
1143
1140
  if (attachmentIds.length > MAX_ATTACHMENTS) throw new BffInputError(400, "TOO_MANY_ATTACHMENTS", `At most ${MAX_ATTACHMENTS} attachments are allowed.`);
1144
- const admission = threadId ? await options.client.embed.submitAgentThreadMessage(selected.agentId, threadId, {
1145
- externalUserId,
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, {
1141
+ const admission = await options.client.embed.startAgentRun(selected.agentId, {
1142
+ ...resolution.trustedContext === void 0 ? {} : { trusted_context: resolution.trustedContext },
1162
1143
  ...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
1163
1144
  ...identity,
1164
1145
  ...selected.agentVersionId ? { agent_version_id: selected.agentVersionId } : {},
@@ -1174,7 +1155,7 @@ function createResolvedAgents24BffHandler(options) {
1174
1155
  tool_inputs: objectValue(body.toolInputs),
1175
1156
  ...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) },
1176
1157
  client: objectValue(body.client)
1177
- }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")) });
1158
+ }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")), streamFeatures: url.searchParams.get("stream_features") || "" });
1178
1159
  const admittedRunId = admission.run_id;
1179
1160
  if (!admittedRunId) return mergeHeaders(json(admission, void 0, 202), resolution.responseHeaders);
1180
1161
  return mergeHeaders(sseResponse(async (write, signal, control) => {
@@ -1188,7 +1169,7 @@ function createResolvedAgents24BffHandler(options) {
1188
1169
  cursor: 0
1189
1170
  }, (event) => {
1190
1171
  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 });
1172
+ }, { signal, onControl: control, leaseSeconds: 60, streamFeatures: url.searchParams.get("stream_features") || "", onPreview: (frame) => write(frame) });
1192
1173
  }, {
1193
1174
  "X-Run-ID": admittedRunId,
1194
1175
  ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
@@ -1359,31 +1340,104 @@ function createResolvedAgents24BffHandler(options) {
1359
1340
  return mergeHeaders(publicError(404, "NOT_FOUND", "The requested BFF route does not exist."), resolution.responseHeaders);
1360
1341
  } catch (error) {
1361
1342
  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", errorResponse(error)), resolution.responseHeaders);
1343
+ return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error)), resolution.responseHeaders);
1344
+ }
1345
+ };
1346
+ }
1347
+
1348
+ // src/bff-agent-resolution.ts
1349
+ function clean(value) {
1350
+ const result = typeof value === "string" ? value.trim() : "";
1351
+ return result || void 0;
1352
+ }
1353
+ function required(value, field) {
1354
+ const result = clean(value);
1355
+ if (!result || /[\r\n\0]/.test(result)) throw new Error(`${field} is required.`);
1356
+ return result;
1357
+ }
1358
+ function prepareAgents24BffAgentResolution(options) {
1359
+ if (!options.agents.length || options.agents.length > 50) {
1360
+ throw new Error("agents must contain between one and 50 Agents.");
1361
+ }
1362
+ const configured = options.agents.map((item) => {
1363
+ const agentId = clean(item.agentId);
1364
+ const agentAlias = clean(item.agentAlias);
1365
+ if (Boolean(agentId) === Boolean(agentAlias)) {
1366
+ throw new Error("Each Agent requires exactly one of agentId or agentAlias.");
1363
1367
  }
1368
+ return { agentId, agentAlias, agentVersionId: clean(item.agentVersionId) };
1369
+ });
1370
+ return async () => {
1371
+ const agents = await Promise.all(configured.map(async (item) => {
1372
+ if (item.agentAlias) {
1373
+ const resolution = await options.client.embed.resolveAgentAlias(item.agentAlias);
1374
+ return {
1375
+ agentId: required(resolution.agent_id, "agentId"),
1376
+ agentAlias: required(item.agentAlias, "agentAlias"),
1377
+ agentVersionId: item.agentVersionId
1378
+ };
1379
+ }
1380
+ return { agentId: required(item.agentId, "agentId"), agentVersionId: item.agentVersionId };
1381
+ }));
1382
+ if (new Set(agents.map((item) => item.agentId)).size !== agents.length) {
1383
+ throw new Error("Configured Agent selectors must resolve to unique Agents.");
1384
+ }
1385
+ return agents;
1364
1386
  };
1365
1387
  }
1388
+
1389
+ // src/bff-bootstrap.ts
1390
+ function principalIdentity(principal, options) {
1391
+ const profile = Object.fromEntries(Object.entries({ display_name: principal.displayName, email: principal.email, avatar_url: principal.avatarUrl }).filter(([, value]) => value !== void 0));
1392
+ return {
1393
+ integration_id: options.integrationId,
1394
+ subject: normalized(principal.subject, "subject"),
1395
+ ...options.integrationName ? { integration_name: options.integrationName } : {},
1396
+ ...principal.issuer ? { issuer: normalized(principal.issuer, "issuer") } : {},
1397
+ ...Object.keys(profile).length ? { profile } : {}
1398
+ };
1399
+ }
1400
+ async function runtimeBootstrap(options, request, identityResolver) {
1401
+ const resolution = await options.resolvePrincipal(request);
1402
+ const result = await options.client.embed.bootstrapRuntime({
1403
+ identity: principalIdentity(resolution.principal, options),
1404
+ agents: options.agents.map((agent) => ({
1405
+ ..."agentId" in agent && agent.agentId ? { agent_id: agent.agentId } : { agent_alias: agent.agentAlias },
1406
+ ...agent.agentVersionId ? { agent_version_id: agent.agentVersionId } : {}
1407
+ })),
1408
+ runtime_target: options.runtimeTarget || "published",
1409
+ selected_agent: new URL(request.url).searchParams.get("agent_id") || void 0
1410
+ });
1411
+ identityResolver.remember(resolution.principal, result.customer_principal_ref);
1412
+ await options.onPrincipalResolved?.(request, resolution, result.customer_principal_ref);
1413
+ return { response: mergeHeaders(json(result.bootstrap), resolution.responseHeaders), result };
1414
+ }
1415
+
1416
+ // src/bff.ts
1366
1417
  function createAgents24BffHandler(options) {
1367
1418
  const resolveAgents = prepareAgents24BffAgentResolution(options);
1419
+ const identity = createCustomerIdentityResolver(options.client.embed, options.integrationId, options.integrationName);
1420
+ const basePath = normalizeBasePath(options.basePath);
1368
1421
  let resolvedHandler;
1369
- const resolve = async () => {
1370
- const agents = await resolveAgents();
1371
- return createResolvedAgents24BffHandler({ ...options, agents });
1372
- };
1373
1422
  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();
1423
+ if (!browserRequestIsSameOrigin(request)) return publicError(403, "BFF_ORIGIN_DENIED", "The BFF accepts same-origin browser requests only.");
1378
1424
  try {
1379
- return (await resolvedHandler)(request);
1425
+ if (request.method === "GET" && new URL(request.url).pathname === `${basePath}/bootstrap`) {
1426
+ const { response, result } = await runtimeBootstrap(options, request, identity);
1427
+ const agents = result.resolved_agents.map((row) => ({ agentId: row.agent_id, agentAlias: row.agent_alias, agentVersionId: row.agent_version_id || void 0 }));
1428
+ resolvedHandler = Promise.resolve(createResolvedAgents24BffHandler({ ...options, agents }, identity));
1429
+ return response;
1430
+ }
1431
+ resolvedHandler ||= resolveAgents().then((agents) => createResolvedAgents24BffHandler({ ...options, agents }, identity));
1432
+ return await (await resolvedHandler)(request);
1380
1433
  } catch (error) {
1381
1434
  resolvedHandler = void 0;
1382
- return reportFailureResponse(options.onDiagnostic, request, "agent.resolve", errorResponse(error));
1435
+ return reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error));
1383
1436
  }
1384
1437
  };
1385
1438
  }
1386
1439
 
1440
+ exports.AgentBffResolverError = AgentBffResolverError;
1387
1441
  exports.createAgents24BffHandler = createAgents24BffHandler;
1388
1442
  //# sourceMappingURL=bff.cjs.map
1389
1443
  //# sourceMappingURL=bff.cjs.map