@agents24/node 0.5.30 → 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 (59) 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 +188 -130
  9. package/dist/bff.cjs.map +1 -1
  10. package/dist/bff.d.cts +16 -6
  11. package/dist/bff.d.ts +16 -6
  12. package/dist/bff.js +188 -131
  13. package/dist/bff.js.map +1 -1
  14. package/dist/{client-BIn7miCx.d.cts → client-BhE-CjMz.d.cts} +119 -15
  15. package/dist/{client-BIn7miCx.d.ts → client-BhE-CjMz.d.ts} +119 -15
  16. package/dist/index.cjs +55 -8
  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 +56 -9
  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/agents.d.ts.map +1 -1
  25. package/dist/types/artifacts.d.ts +12 -0
  26. package/dist/types/artifacts.d.ts.map +1 -1
  27. package/dist/types/bff-agent-resolution.d.ts +19 -0
  28. package/dist/types/bff-agent-resolution.d.ts.map +1 -1
  29. package/dist/types/bff-bootstrap.d.ts +17 -0
  30. package/dist/types/bff-bootstrap.d.ts.map +1 -0
  31. package/dist/types/bff-conversation-submission.d.ts +16 -0
  32. package/dist/types/bff-conversation-submission.d.ts.map +1 -0
  33. package/dist/types/bff-errors.d.ts +1 -1
  34. package/dist/types/bff-errors.d.ts.map +1 -1
  35. package/dist/types/bff-multi-agent.d.ts +11 -0
  36. package/dist/types/bff-multi-agent.d.ts.map +1 -0
  37. package/dist/types/bff-request.d.ts +3 -1
  38. package/dist/types/bff-request.d.ts.map +1 -1
  39. package/dist/types/bff-resolver.d.ts +9 -0
  40. package/dist/types/bff-resolver.d.ts.map +1 -0
  41. package/dist/types/bff-single-agent.d.ts +5 -0
  42. package/dist/types/bff-single-agent.d.ts.map +1 -0
  43. package/dist/types/bff.d.ts +2 -4
  44. package/dist/types/bff.d.ts.map +1 -1
  45. package/dist/types/embed-types.d.ts +13 -0
  46. package/dist/types/embed-types.d.ts.map +1 -1
  47. package/dist/types/embed.d.ts +2 -2
  48. package/dist/types/embed.d.ts.map +1 -1
  49. package/dist/types/generated/embed.d.ts +8 -0
  50. package/dist/types/generated/embed.d.ts.map +1 -0
  51. package/dist/types/generated/ingestion-types.d.ts +20 -0
  52. package/dist/types/generated/ingestion-types.d.ts.map +1 -1
  53. package/dist/types/generated/manifest.d.ts +1 -1
  54. package/dist/types/generated/manifest.d.ts.map +1 -1
  55. package/dist/types/streams.d.ts +1 -1
  56. package/dist/types/streams.d.ts.map +1 -1
  57. package/dist/types/types.d.ts +64 -1
  58. package/dist/types/types.d.ts.map +1 -1
  59. 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 } : {}
@@ -650,11 +676,13 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
650
676
  mode: "queue",
651
677
  input,
652
678
  attachmentIds,
679
+ ...resolution.customerTenant === void 0 ? {} : { customerTenant: resolution.customerTenant },
653
680
  ...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {},
654
681
  ...resolution.knowledgeNamespaces === void 0 ? {} : { knowledgeNamespaces: resolution.knowledgeNamespaces },
655
682
  toolInputs: objectValue(body.toolInputs),
656
683
  ...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) }
657
684
  }, { idempotencyKey }) : await embed.startAgentRun(agentId, {
685
+ ...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
658
686
  ...identity,
659
687
  integration_id: integrationId,
660
688
  ...resolution.chatScope === void 0 ? {} : { chat_scope: resolution.chatScope },
@@ -685,7 +713,7 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
685
713
  cursor: 0
686
714
  }, (event) => {
687
715
  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 });
716
+ }, { signal, onControl: control, leaseSeconds: 60, streamFeatures: url.searchParams.get("stream_features") || "", onPreview: (frame) => write(frame) });
689
717
  }, {
690
718
  "X-Run-ID": admittedRunId,
691
719
  ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
@@ -973,11 +1001,13 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
973
1001
  if (error instanceof BffInputError) {
974
1002
  return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", publicError(error.status, error.code, error.message)), resolution.responseHeaders);
975
1003
  }
976
- return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", errorResponse(error)), resolution.responseHeaders);
1004
+ return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error)), resolution.responseHeaders);
977
1005
  }
978
1006
  };
979
1007
  }
980
- function createResolvedAgents24BffHandler(options) {
1008
+
1009
+ // src/bff-multi-agent.ts
1010
+ function createResolvedAgents24BffHandler(options, sharedIdentity) {
981
1011
  const runtimeTarget = options.runtimeTarget || "published";
982
1012
  const basePath = normalizeBasePath(options.basePath);
983
1013
  const integrationId = normalized(options.integrationId, "integrationId");
@@ -991,7 +1021,7 @@ function createResolvedAgents24BffHandler(options) {
991
1021
  if (runtimeTarget === "draft" && agents.some((agent) => agent.agentVersionId)) {
992
1022
  throw new Error("agentVersionId cannot be used with draft runtimeTarget.");
993
1023
  }
994
- const resolveCustomerIdentity = createCustomerIdentityResolver(
1024
+ const resolveCustomerIdentity = sharedIdentity || createCustomerIdentityResolver(
995
1025
  options.client.embed,
996
1026
  integrationId,
997
1027
  stringValue(options.integrationName)
@@ -1030,11 +1060,12 @@ function createResolvedAgents24BffHandler(options) {
1030
1060
  resolution = await options.resolvePrincipal(request);
1031
1061
  resolution.principal.subject = normalized(resolution.principal.subject, "subject");
1032
1062
  if (resolution.principal.issuer !== void 0) resolution.principal.issuer = normalized(resolution.principal.issuer, "issuer");
1033
- } catch {
1034
- return publicError(401, "PRINCIPAL_REQUIRED", "A valid application session is required.");
1063
+ } catch (error) {
1064
+ return resolverErrorResponse(error);
1035
1065
  }
1036
1066
  try {
1037
1067
  const externalUserId = await resolveCustomerIdentity(resolution.principal);
1068
+ await options.onPrincipalResolved?.(request, resolution, externalUserId);
1038
1069
  const identity = {
1039
1070
  external_user_id: externalUserId,
1040
1071
  ...resolution.principal.externalSessionId ? { external_session_id: resolution.principal.externalSessionId } : {}
@@ -1064,7 +1095,7 @@ function createResolvedAgents24BffHandler(options) {
1064
1095
  headers: request.headers,
1065
1096
  body,
1066
1097
  signal: request.signal
1067
- }));
1098
+ }), resolution);
1068
1099
  };
1069
1100
  const resolveRunAgent = async (runId) => {
1070
1101
  const result = await options.client.embed.resolveConversationRun(runId, {
@@ -1087,75 +1118,29 @@ function createResolvedAgents24BffHandler(options) {
1087
1118
  });
1088
1119
  return (await requestedAgent(detail.runtime_selection?.agent_id)).agentId;
1089
1120
  };
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
1121
  if (request.method === "POST" && path === "/chat/stream") {
1133
1122
  const body = await requestJson(request);
1134
1123
  const threadId = stringValue(body.threadId);
1135
- const storedAgent = threadId ? await resolveThreadAgent(threadId) : void 0;
1136
- 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);
1137
1136
  const input = stringValue(body.input);
1138
1137
  const attachmentIds = stringList(body.attachmentIds);
1139
1138
  if (!input && attachmentIds.length === 0) throw new BffInputError(400, "INPUT_REQUIRED", "A message or attachment is required.");
1140
1139
  if (input && input.length > MAX_INPUT_LENGTH) throw new BffInputError(413, "INPUT_TOO_LARGE", "The message is too large.");
1141
1140
  if (attachmentIds.length > MAX_ATTACHMENTS) throw new BffInputError(400, "TOO_MANY_ATTACHMENTS", `At most ${MAX_ATTACHMENTS} attachments are allowed.`);
1142
- const admission = threadId ? await options.client.embed.submitAgentThreadMessage(selected.agentId, threadId, {
1143
- externalUserId,
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
- ...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {},
1155
- ...resolution.knowledgeNamespaces === void 0 ? {} : { knowledgeNamespaces: resolution.knowledgeNamespaces },
1156
- toolInputs: objectValue(body.toolInputs),
1157
- ...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) }
1158
- }, { 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 },
1143
+ ...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
1159
1144
  ...identity,
1160
1145
  ...selected.agentVersionId ? { agent_version_id: selected.agentVersionId } : {},
1161
1146
  runtime_target: runtimeTarget,
@@ -1170,7 +1155,7 @@ function createResolvedAgents24BffHandler(options) {
1170
1155
  tool_inputs: objectValue(body.toolInputs),
1171
1156
  ...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) },
1172
1157
  client: objectValue(body.client)
1173
- }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")) });
1158
+ }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")), streamFeatures: url.searchParams.get("stream_features") || "" });
1174
1159
  const admittedRunId = admission.run_id;
1175
1160
  if (!admittedRunId) return mergeHeaders(json(admission, void 0, 202), resolution.responseHeaders);
1176
1161
  return mergeHeaders(sseResponse(async (write, signal, control) => {
@@ -1184,7 +1169,7 @@ function createResolvedAgents24BffHandler(options) {
1184
1169
  cursor: 0
1185
1170
  }, (event) => {
1186
1171
  if (event.event !== "assistant.completed" || new URL(request.url).searchParams.get("stream_features")?.split(",").includes("assistant-completion-v1")) return write(event);
1187
- }, { signal, onControl: control, leaseSeconds: 60 });
1172
+ }, { signal, onControl: control, leaseSeconds: 60, streamFeatures: url.searchParams.get("stream_features") || "", onPreview: (frame) => write(frame) });
1188
1173
  }, {
1189
1174
  "X-Run-ID": admittedRunId,
1190
1175
  ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
@@ -1355,31 +1340,104 @@ function createResolvedAgents24BffHandler(options) {
1355
1340
  return mergeHeaders(publicError(404, "NOT_FOUND", "The requested BFF route does not exist."), resolution.responseHeaders);
1356
1341
  } catch (error) {
1357
1342
  if (error instanceof BffInputError) return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", publicError(error.status, error.code, error.message)), resolution.responseHeaders);
1358
- 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.");
1359
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;
1360
1386
  };
1361
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
1362
1417
  function createAgents24BffHandler(options) {
1363
1418
  const resolveAgents = prepareAgents24BffAgentResolution(options);
1419
+ const identity = createCustomerIdentityResolver(options.client.embed, options.integrationId, options.integrationName);
1420
+ const basePath = normalizeBasePath(options.basePath);
1364
1421
  let resolvedHandler;
1365
- const resolve = async () => {
1366
- const agents = await resolveAgents();
1367
- return createResolvedAgents24BffHandler({ ...options, agents });
1368
- };
1369
1422
  return async (request) => {
1370
- if (!browserRequestIsSameOrigin(request)) {
1371
- return publicError(403, "BFF_ORIGIN_DENIED", "The BFF accepts same-origin browser requests only.");
1372
- }
1373
- resolvedHandler ||= resolve();
1423
+ if (!browserRequestIsSameOrigin(request)) return publicError(403, "BFF_ORIGIN_DENIED", "The BFF accepts same-origin browser requests only.");
1374
1424
  try {
1375
- 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);
1376
1433
  } catch (error) {
1377
1434
  resolvedHandler = void 0;
1378
- return reportFailureResponse(options.onDiagnostic, request, "agent.resolve", errorResponse(error));
1435
+ return reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error));
1379
1436
  }
1380
1437
  };
1381
1438
  }
1382
1439
 
1440
+ exports.AgentBffResolverError = AgentBffResolverError;
1383
1441
  exports.createAgents24BffHandler = createAgents24BffHandler;
1384
1442
  //# sourceMappingURL=bff.cjs.map
1385
1443
  //# sourceMappingURL=bff.cjs.map