@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.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Agents24 } from './client-BIn7miCx.cjs';
1
+ import { A as Agents24 } from './client-BhE-CjMz.cjs';
2
2
  import '@agents24/client/protocol';
3
3
  import '@agents24/client';
4
4
 
@@ -12,6 +12,11 @@ interface AgentBffPrincipal {
12
12
  }
13
13
  interface AgentBffPrincipalResolution {
14
14
  principal: AgentBffPrincipal;
15
+ customerTenant?: {
16
+ issuer: string;
17
+ subject: string;
18
+ };
19
+ trustedContext?: Record<string, unknown>;
15
20
  chatScope?: string;
16
21
  knowledgeNamespaces?: Record<string, string>;
17
22
  responseHeaders?: HeadersInit;
@@ -45,14 +50,19 @@ interface Agents24BffHandlerOptions {
45
50
  basePath?: string;
46
51
  resolvePrincipal(request: Request): Promise<AgentBffPrincipalResolution> | AgentBffPrincipalResolution;
47
52
  revokePrincipal?(request: Request, principal: AgentBffPrincipal): Promise<HeadersInit | void> | HeadersInit | void;
53
+ onPrincipalResolved?(request: Request, resolution: AgentBffPrincipalResolution, principalRef: string): Promise<void> | void;
48
54
  onDiagnostic?(diagnostic: Agents24BffDiagnostic): Promise<void> | void;
49
55
  }
50
56
  type Agents24BffHandler = (request: Request) => Promise<Response>;
51
57
 
52
- /**
53
- * Creates an Agent-neutral BFF from permanent UUID or human-readable alias selectors.
54
- * Aliases resolve once for the lifetime of this server process; UUID routes remain canonical.
55
- */
58
+ type AgentBffResolverErrorKind = "unauthenticated" | "denied" | "unavailable";
59
+ /** Explicit authentication outcome from the application's trusted resolver. */
60
+ declare class AgentBffResolverError extends Error {
61
+ readonly kind: AgentBffResolverErrorKind;
62
+ readonly retryAfterMs?: number | undefined;
63
+ constructor(kind: AgentBffResolverErrorKind, retryAfterMs?: number | undefined);
64
+ }
65
+
56
66
  declare function createAgents24BffHandler(options: Agents24BffHandlerOptions): Agents24BffHandler;
57
67
 
58
- export { type AgentBffPrincipal, type AgentBffPrincipalResolution, type Agents24BffAgent, type Agents24BffDiagnostic, type Agents24BffHandler, type Agents24BffHandlerOptions, createAgents24BffHandler };
68
+ export { type AgentBffPrincipal, type AgentBffPrincipalResolution, AgentBffResolverError, type AgentBffResolverErrorKind, type Agents24BffAgent, type Agents24BffDiagnostic, type Agents24BffHandler, type Agents24BffHandlerOptions, createAgents24BffHandler };
package/dist/bff.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Agents24 } from './client-BIn7miCx.js';
1
+ import { A as Agents24 } from './client-BhE-CjMz.js';
2
2
  import '@agents24/client/protocol';
3
3
  import '@agents24/client';
4
4
 
@@ -12,6 +12,11 @@ interface AgentBffPrincipal {
12
12
  }
13
13
  interface AgentBffPrincipalResolution {
14
14
  principal: AgentBffPrincipal;
15
+ customerTenant?: {
16
+ issuer: string;
17
+ subject: string;
18
+ };
19
+ trustedContext?: Record<string, unknown>;
15
20
  chatScope?: string;
16
21
  knowledgeNamespaces?: Record<string, string>;
17
22
  responseHeaders?: HeadersInit;
@@ -45,14 +50,19 @@ interface Agents24BffHandlerOptions {
45
50
  basePath?: string;
46
51
  resolvePrincipal(request: Request): Promise<AgentBffPrincipalResolution> | AgentBffPrincipalResolution;
47
52
  revokePrincipal?(request: Request, principal: AgentBffPrincipal): Promise<HeadersInit | void> | HeadersInit | void;
53
+ onPrincipalResolved?(request: Request, resolution: AgentBffPrincipalResolution, principalRef: string): Promise<void> | void;
48
54
  onDiagnostic?(diagnostic: Agents24BffDiagnostic): Promise<void> | void;
49
55
  }
50
56
  type Agents24BffHandler = (request: Request) => Promise<Response>;
51
57
 
52
- /**
53
- * Creates an Agent-neutral BFF from permanent UUID or human-readable alias selectors.
54
- * Aliases resolve once for the lifetime of this server process; UUID routes remain canonical.
55
- */
58
+ type AgentBffResolverErrorKind = "unauthenticated" | "denied" | "unavailable";
59
+ /** Explicit authentication outcome from the application's trusted resolver. */
60
+ declare class AgentBffResolverError extends Error {
61
+ readonly kind: AgentBffResolverErrorKind;
62
+ readonly retryAfterMs?: number | undefined;
63
+ constructor(kind: AgentBffResolverErrorKind, retryAfterMs?: number | undefined);
64
+ }
65
+
56
66
  declare function createAgents24BffHandler(options: Agents24BffHandlerOptions): Agents24BffHandler;
57
67
 
58
- export { type AgentBffPrincipal, type AgentBffPrincipalResolution, type Agents24BffAgent, type Agents24BffDiagnostic, type Agents24BffHandler, type Agents24BffHandlerOptions, createAgents24BffHandler };
68
+ export { type AgentBffPrincipal, type AgentBffPrincipalResolution, AgentBffResolverError, type AgentBffResolverErrorKind, type Agents24BffAgent, type Agents24BffDiagnostic, type Agents24BffHandler, type Agents24BffHandlerOptions, createAgents24BffHandler };
package/dist/bff.js CHANGED
@@ -52,7 +52,7 @@ var CUSTOMER_IDENTITY_CACHE_TTL_MS = 6e4;
52
52
  var CUSTOMER_IDENTITY_CACHE_MAX_ENTRIES = 1024;
53
53
  function createCustomerIdentityResolver(embed, integrationId, integrationName) {
54
54
  const cache = /* @__PURE__ */ new Map();
55
- return async (principal) => {
55
+ const resolve = async (principal) => {
56
56
  const profile = {
57
57
  display_name: principal.displayName,
58
58
  email: principal.email,
@@ -87,6 +87,12 @@ function createCustomerIdentityResolver(embed, integrationId, integrationName) {
87
87
  });
88
88
  return value;
89
89
  };
90
+ return Object.assign(resolve, { remember(principal, reference) {
91
+ const profile = Object.fromEntries(Object.entries({ display_name: principal.displayName, email: principal.email, avatar_url: principal.avatarUrl }).filter(([, value]) => value !== void 0));
92
+ const key = JSON.stringify([integrationId, principal.issuer, principal.subject, profile]);
93
+ cache.set(key, { expiresAt: Date.now() + CUSTOMER_IDENTITY_CACHE_TTL_MS, value: Promise.resolve(normalized(reference, "customer_principal_ref")) });
94
+ while (cache.size > CUSTOMER_IDENTITY_CACHE_MAX_ENTRIES) cache.delete(cache.keys().next().value);
95
+ } });
90
96
  }
91
97
  function normalizeBasePath(value) {
92
98
  const path = String(value || "/api/agents24").trim().replace(/\/+$/, "");
@@ -227,6 +233,40 @@ function computerFileQuery(url, requirePath) {
227
233
  };
228
234
  }
229
235
 
236
+ // src/bff-conversation-submission.ts
237
+ async function submitConversationStream(input) {
238
+ const { request, body, resolution } = input;
239
+ const value = messageBody({ ...body, mode: "queue" });
240
+ const upstream = await input.options.client.embed.openConversationSubmission(stringValue(body.threadId), {
241
+ ...input.identity,
242
+ integration_id: input.integrationId,
243
+ runtime_target: input.runtimeTarget,
244
+ agent_ids: input.agents.map((agent) => agent.agentId),
245
+ agent_versions: Object.fromEntries(input.agents.filter((agent) => agent.agentVersionId).map((agent) => [agent.agentId, agent.agentVersionId])),
246
+ input: value.input,
247
+ attachment_ids: value.attachmentIds,
248
+ client_submission_id: value.clientSubmissionId,
249
+ ...input.requestedAgentId ? { requested_agent_id: input.requestedAgentId } : {},
250
+ ...value.requestedModelId ? { requested_model_id: value.requestedModelId } : {},
251
+ ...resolution.chatScope === void 0 ? {} : { chat_scope: resolution.chatScope },
252
+ ...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
253
+ ...resolution.trustedContext === void 0 ? {} : { trusted_context: resolution.trustedContext },
254
+ ...resolution.knowledgeNamespaces === void 0 ? {} : { knowledge_namespaces: resolution.knowledgeNamespaces },
255
+ tool_inputs: value.toolInputs,
256
+ metadata: objectValue(body.metadata)
257
+ }, {
258
+ signal: request.signal,
259
+ idempotencyKey: request.headers.get("idempotency-key") || void 0,
260
+ streamFeatures: new URL(request.url).searchParams.get("stream_features") || ""
261
+ });
262
+ const headers = new Headers({ "Cache-Control": "no-store", "X-Accel-Buffering": "no" });
263
+ for (const name of ["content-type", "x-run-id", "x-thread-id"]) {
264
+ const value2 = upstream.headers.get(name);
265
+ if (value2) headers.set(name, value2);
266
+ }
267
+ return mergeHeaders(new Response(upstream.body, { status: upstream.status, headers }), resolution.responseHeaders);
268
+ }
269
+
230
270
  // src/bff-delegations.ts
231
271
  function delegationRoute(path) {
232
272
  return /^\/threads\/([^/]+)\/delegations(?:\/(events|[^/]+)(?:\/(history|actions))?)?$/.exec(path);
@@ -267,47 +307,6 @@ async function dispatchDelegations(request, path, embed, agentId, scope) {
267
307
  throw new BffInputError(404, "NOT_FOUND", "The requested task route does not exist.");
268
308
  }
269
309
 
270
- // src/bff-agent-resolution.ts
271
- function clean(value) {
272
- const result = typeof value === "string" ? value.trim() : "";
273
- return result || void 0;
274
- }
275
- function required(value, field) {
276
- const result = clean(value);
277
- if (!result || /[\r\n\0]/.test(result)) throw new Error(`${field} is required.`);
278
- return result;
279
- }
280
- function prepareAgents24BffAgentResolution(options) {
281
- if (!options.agents.length || options.agents.length > 50) {
282
- throw new Error("agents must contain between one and 50 Agents.");
283
- }
284
- const configured = options.agents.map((item) => {
285
- const agentId = clean(item.agentId);
286
- const agentAlias = clean(item.agentAlias);
287
- if (Boolean(agentId) === Boolean(agentAlias)) {
288
- throw new Error("Each Agent requires exactly one of agentId or agentAlias.");
289
- }
290
- return { agentId, agentAlias, agentVersionId: clean(item.agentVersionId) };
291
- });
292
- return async () => {
293
- const agents = await Promise.all(configured.map(async (item) => {
294
- if (item.agentAlias) {
295
- const resolution = await options.client.embed.resolveAgentAlias(item.agentAlias);
296
- return {
297
- agentId: required(resolution.agent_id, "agentId"),
298
- agentAlias: required(item.agentAlias, "agentAlias"),
299
- agentVersionId: item.agentVersionId
300
- };
301
- }
302
- return { agentId: required(item.agentId, "agentId"), agentVersionId: item.agentVersionId };
303
- }));
304
- if (new Set(agents.map((item) => item.agentId)).size !== agents.length) {
305
- throw new Error("Configured Agent selectors must resolve to unique Agents.");
306
- }
307
- return agents;
308
- };
309
- }
310
-
311
310
  // src/errors.ts
312
311
  var Agents24SDKError = class extends Error {
313
312
  kind;
@@ -346,7 +345,7 @@ var Agents24SDKError = class extends Error {
346
345
  };
347
346
 
348
347
  // src/bff-errors.ts
349
- function publicError(status, code, message, retryable = false, violations) {
348
+ function publicError(status, code, message, retryable = false, violations, retryAfterMs = null) {
350
349
  const category = status === 401 ? "authentication" : status === 403 ? "authorization" : status === 404 ? "not_found" : status === 409 ? "conflict" : status === 429 ? "rate_limit" : status >= 500 ? "internal" : "validation";
351
350
  return Response.json({
352
351
  schema_version: "agents24.failure.v1",
@@ -356,7 +355,7 @@ function publicError(status, code, message, retryable = false, violations) {
356
355
  message,
357
356
  request_id: randomUUID(),
358
357
  retryable,
359
- retry_after_ms: null,
358
+ retry_after_ms: retryAfterMs,
360
359
  details: {}
361
360
  }, {
362
361
  status,
@@ -552,7 +551,33 @@ function sseResponse(execute, headers, failurePayload, onFailure, requestSignal,
552
551
  return new Response(stream, { headers: sseHeaders(headers) });
553
552
  }
554
553
 
555
- // src/bff.ts
554
+ // src/bff-resolver.ts
555
+ var AgentBffResolverError = class extends Error {
556
+ constructor(kind, retryAfterMs) {
557
+ super("Application identity could not be resolved.");
558
+ this.kind = kind;
559
+ this.retryAfterMs = retryAfterMs;
560
+ }
561
+ kind;
562
+ retryAfterMs;
563
+ };
564
+ function resolverErrorResponse(error) {
565
+ if (!(error instanceof AgentBffResolverError)) return errorResponse(error);
566
+ const definition = {
567
+ unauthenticated: [401, "PRINCIPAL_REQUIRED", "A valid application session is required."],
568
+ denied: [403, "PRINCIPAL_DENIED", "Access to this application is denied."],
569
+ unavailable: [503, "PRINCIPAL_UNAVAILABLE", "Application identity is temporarily unavailable."]
570
+ };
571
+ const [status, code, message] = definition[error.kind];
572
+ const delay = Number.isFinite(error.retryAfterMs) && error.retryAfterMs >= 0 ? Math.min(error.retryAfterMs, 6e4) : null;
573
+ const response = publicError(status, code, message, status >= 500, void 0, delay);
574
+ if (Number.isFinite(error.retryAfterMs) && error.retryAfterMs >= 0) {
575
+ return new Response(response.body, { status, headers: { ...Object.fromEntries(response.headers), "Retry-After": String(Math.ceil(delay / 1e3)) } });
576
+ }
577
+ return response;
578
+ }
579
+
580
+ // src/bff-single-agent.ts
556
581
  function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity) {
557
582
  const agentId = normalized(options.agentId, "agentId");
558
583
  const agentVersionId = stringValue(options.agentVersionId);
@@ -572,7 +597,7 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
572
597
  const streamFailure = (request, operation) => (error) => {
573
598
  reportFailureResponse(options.onDiagnostic, request, operation, errorResponse(error));
574
599
  };
575
- return async (request) => {
600
+ return async (request, trustedResolution) => {
576
601
  const url = new URL(request.url);
577
602
  if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {
578
603
  return publicError(404, "NOT_FOUND", "The requested BFF route does not exist.");
@@ -583,18 +608,19 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
583
608
  const path = url.pathname.slice(basePath.length) || "/";
584
609
  let resolution;
585
610
  try {
586
- resolution = await options.resolvePrincipal(request);
611
+ resolution = trustedResolution || await options.resolvePrincipal(request);
587
612
  resolution.principal.subject = normalized(resolution.principal.subject, "subject");
588
613
  if (resolution.principal.issuer !== void 0) {
589
614
  resolution.principal.issuer = normalized(resolution.principal.issuer, "issuer");
590
615
  }
591
- } catch {
592
- return publicError(401, "PRINCIPAL_REQUIRED", "A valid application session is required.");
616
+ } catch (error) {
617
+ return resolverErrorResponse(error);
593
618
  }
594
619
  const principal = resolution.principal;
595
620
  const idempotencyKey = stringValue(request.headers.get("idempotency-key"));
596
621
  try {
597
622
  const customerPrincipalRef = await resolveCustomerIdentity(principal);
623
+ await options.onPrincipalResolved?.(request, resolution, customerPrincipalRef);
598
624
  const identity = {
599
625
  external_user_id: customerPrincipalRef,
600
626
  ...principal.externalSessionId ? { external_session_id: principal.externalSessionId } : {}
@@ -648,11 +674,13 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
648
674
  mode: "queue",
649
675
  input,
650
676
  attachmentIds,
677
+ ...resolution.customerTenant === void 0 ? {} : { customerTenant: resolution.customerTenant },
651
678
  ...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {},
652
679
  ...resolution.knowledgeNamespaces === void 0 ? {} : { knowledgeNamespaces: resolution.knowledgeNamespaces },
653
680
  toolInputs: objectValue(body.toolInputs),
654
681
  ...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) }
655
682
  }, { idempotencyKey }) : await embed.startAgentRun(agentId, {
683
+ ...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
656
684
  ...identity,
657
685
  integration_id: integrationId,
658
686
  ...resolution.chatScope === void 0 ? {} : { chat_scope: resolution.chatScope },
@@ -683,7 +711,7 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
683
711
  cursor: 0
684
712
  }, (event) => {
685
713
  if (event.event !== "assistant.completed" || new URL(request.url).searchParams.get("stream_features")?.split(",").includes("assistant-completion-v1")) return write(event);
686
- }, { signal, onControl: control, leaseSeconds: 60 });
714
+ }, { signal, onControl: control, leaseSeconds: 60, streamFeatures: url.searchParams.get("stream_features") || "", onPreview: (frame) => write(frame) });
687
715
  }, {
688
716
  "X-Run-ID": admittedRunId,
689
717
  ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
@@ -971,11 +999,13 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
971
999
  if (error instanceof BffInputError) {
972
1000
  return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", publicError(error.status, error.code, error.message)), resolution.responseHeaders);
973
1001
  }
974
- return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", errorResponse(error)), resolution.responseHeaders);
1002
+ return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error)), resolution.responseHeaders);
975
1003
  }
976
1004
  };
977
1005
  }
978
- function createResolvedAgents24BffHandler(options) {
1006
+
1007
+ // src/bff-multi-agent.ts
1008
+ function createResolvedAgents24BffHandler(options, sharedIdentity) {
979
1009
  const runtimeTarget = options.runtimeTarget || "published";
980
1010
  const basePath = normalizeBasePath(options.basePath);
981
1011
  const integrationId = normalized(options.integrationId, "integrationId");
@@ -989,7 +1019,7 @@ function createResolvedAgents24BffHandler(options) {
989
1019
  if (runtimeTarget === "draft" && agents.some((agent) => agent.agentVersionId)) {
990
1020
  throw new Error("agentVersionId cannot be used with draft runtimeTarget.");
991
1021
  }
992
- const resolveCustomerIdentity = createCustomerIdentityResolver(
1022
+ const resolveCustomerIdentity = sharedIdentity || createCustomerIdentityResolver(
993
1023
  options.client.embed,
994
1024
  integrationId,
995
1025
  stringValue(options.integrationName)
@@ -1028,11 +1058,12 @@ function createResolvedAgents24BffHandler(options) {
1028
1058
  resolution = await options.resolvePrincipal(request);
1029
1059
  resolution.principal.subject = normalized(resolution.principal.subject, "subject");
1030
1060
  if (resolution.principal.issuer !== void 0) resolution.principal.issuer = normalized(resolution.principal.issuer, "issuer");
1031
- } catch {
1032
- return publicError(401, "PRINCIPAL_REQUIRED", "A valid application session is required.");
1061
+ } catch (error) {
1062
+ return resolverErrorResponse(error);
1033
1063
  }
1034
1064
  try {
1035
1065
  const externalUserId = await resolveCustomerIdentity(resolution.principal);
1066
+ await options.onPrincipalResolved?.(request, resolution, externalUserId);
1036
1067
  const identity = {
1037
1068
  external_user_id: externalUserId,
1038
1069
  ...resolution.principal.externalSessionId ? { external_session_id: resolution.principal.externalSessionId } : {}
@@ -1062,7 +1093,7 @@ function createResolvedAgents24BffHandler(options) {
1062
1093
  headers: request.headers,
1063
1094
  body,
1064
1095
  signal: request.signal
1065
- }));
1096
+ }), resolution);
1066
1097
  };
1067
1098
  const resolveRunAgent = async (runId) => {
1068
1099
  const result = await options.client.embed.resolveConversationRun(runId, {
@@ -1085,75 +1116,29 @@ function createResolvedAgents24BffHandler(options) {
1085
1116
  });
1086
1117
  return (await requestedAgent(detail.runtime_selection?.agent_id)).agentId;
1087
1118
  };
1088
- if (request.method === "GET" && path === "/bootstrap") {
1089
- const candidates = await Promise.all(agents.map(async (agent) => {
1090
- const [raw, policy] = await Promise.all([
1091
- options.client.embed.getRuntimeBootstrap(agent.agentId, agent.agentVersionId, runtimeTarget),
1092
- options.client.embed.getResourcePolicy(agent.agentId, {
1093
- external_user_id: externalUserId,
1094
- integration_id: integrationId,
1095
- ...agent.agentVersionId ? { agent_version_id: agent.agentVersionId } : {},
1096
- runtime_target: runtimeTarget
1097
- })
1098
- ]);
1099
- const alias = normalized(String(raw.agent_alias || ""), "agent_alias");
1100
- agent.agentAlias = alias;
1101
- agentBySelector.set(alias, agent);
1102
- for (const item of stringList(raw.agent_aliases)) agentBySelector.set(item, agent);
1103
- return { agent, raw, policy };
1104
- }));
1105
- const selected = await requestedAgent(url.searchParams.get("agent_id"));
1106
- const allowed = candidates.filter((candidate) => candidate.policy.agent_access_allowed !== false);
1107
- const selectedCandidate = allowed.find((candidate) => candidate.agent.agentId === selected.agentId) || allowed[0];
1108
- if (!selectedCandidate) throw new BffInputError(403, "RESOURCE_POLICY_ACCESS_DENIED", "No configured Agent is available.");
1109
- const document = bootstrapDocument(selectedCandidate.raw, selectedCandidate.agent.agentVersionId);
1110
- const features = objectValue(document.features);
1111
- features.models = selectedCandidate.policy.model_selection;
1112
- features.agents = {
1113
- selectable: allowed.length > 1,
1114
- default_id: normalized(String(allowed[0].raw.agent_alias || ""), "agent_alias"),
1115
- options: allowed.map((candidate) => ({
1116
- id: normalized(String(candidate.raw.agent_alias || ""), "agent_alias"),
1117
- label: normalized(String(candidate.raw.agent_name || ""), "agent_name")
1118
- }))
1119
- };
1120
- document.features = features;
1121
- document.capabilities = [
1122
- .../* @__PURE__ */ new Set([
1123
- ...document.capabilities || [],
1124
- ...allowed.length > 1 ? ["agents.select"] : [],
1125
- ...selectedCandidate.policy.model_selection.selectable ? ["models.select"] : []
1126
- ])
1127
- ];
1128
- return mergeHeaders(json(document), resolution.responseHeaders);
1129
- }
1130
1119
  if (request.method === "POST" && path === "/chat/stream") {
1131
1120
  const body = await requestJson(request);
1132
1121
  const threadId = stringValue(body.threadId);
1133
- const storedAgent = threadId ? await resolveThreadAgent(threadId) : void 0;
1134
- const selected = await requestedAgent(body.requestedAgentId || storedAgent);
1122
+ if (threadId) return submitConversationStream({
1123
+ options,
1124
+ request,
1125
+ body,
1126
+ resolution,
1127
+ agents,
1128
+ identity,
1129
+ integrationId,
1130
+ runtimeTarget,
1131
+ requestedAgentId: body.requestedAgentId ? (await requestedAgent(body.requestedAgentId)).agentId : void 0
1132
+ });
1133
+ const selected = await requestedAgent(body.requestedAgentId);
1135
1134
  const input = stringValue(body.input);
1136
1135
  const attachmentIds = stringList(body.attachmentIds);
1137
1136
  if (!input && attachmentIds.length === 0) throw new BffInputError(400, "INPUT_REQUIRED", "A message or attachment is required.");
1138
1137
  if (input && input.length > MAX_INPUT_LENGTH) throw new BffInputError(413, "INPUT_TOO_LARGE", "The message is too large.");
1139
1138
  if (attachmentIds.length > MAX_ATTACHMENTS) throw new BffInputError(400, "TOO_MANY_ATTACHMENTS", `At most ${MAX_ATTACHMENTS} attachments are allowed.`);
1140
- const admission = threadId ? await options.client.embed.submitAgentThreadMessage(selected.agentId, threadId, {
1141
- externalUserId,
1142
- ...resolution.principal.externalSessionId ? { externalSessionId: resolution.principal.externalSessionId } : {},
1143
- integrationId,
1144
- ...resolution.chatScope === void 0 ? {} : { chatScope: resolution.chatScope },
1145
- runtimeTarget,
1146
- clientSubmissionId: stringValue(body.clientSubmissionId),
1147
- ...body.relayClientId === null ? { relayClientId: null } : stringValue(body.relayClientId) ? { relayClientId: stringValue(body.relayClientId) } : {},
1148
- agentVersionId: selected.agentVersionId ?? null,
1149
- mode: "queue",
1150
- input: input ?? "",
1151
- attachmentIds,
1152
- ...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {},
1153
- ...resolution.knowledgeNamespaces === void 0 ? {} : { knowledgeNamespaces: resolution.knowledgeNamespaces },
1154
- toolInputs: objectValue(body.toolInputs),
1155
- ...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) }
1156
- }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")) }) : await options.client.embed.startAgentRun(selected.agentId, {
1139
+ const admission = await options.client.embed.startAgentRun(selected.agentId, {
1140
+ ...resolution.trustedContext === void 0 ? {} : { trusted_context: resolution.trustedContext },
1141
+ ...resolution.customerTenant === void 0 ? {} : { customer_tenant: resolution.customerTenant },
1157
1142
  ...identity,
1158
1143
  ...selected.agentVersionId ? { agent_version_id: selected.agentVersionId } : {},
1159
1144
  runtime_target: runtimeTarget,
@@ -1168,7 +1153,7 @@ function createResolvedAgents24BffHandler(options) {
1168
1153
  tool_inputs: objectValue(body.toolInputs),
1169
1154
  ...body.metadata === void 0 ? {} : { metadata: objectValue(body.metadata) },
1170
1155
  client: objectValue(body.client)
1171
- }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")) });
1156
+ }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")), streamFeatures: url.searchParams.get("stream_features") || "" });
1172
1157
  const admittedRunId = admission.run_id;
1173
1158
  if (!admittedRunId) return mergeHeaders(json(admission, void 0, 202), resolution.responseHeaders);
1174
1159
  return mergeHeaders(sseResponse(async (write, signal, control) => {
@@ -1182,7 +1167,7 @@ function createResolvedAgents24BffHandler(options) {
1182
1167
  cursor: 0
1183
1168
  }, (event) => {
1184
1169
  if (event.event !== "assistant.completed" || new URL(request.url).searchParams.get("stream_features")?.split(",").includes("assistant-completion-v1")) return write(event);
1185
- }, { signal, onControl: control, leaseSeconds: 60 });
1170
+ }, { signal, onControl: control, leaseSeconds: 60, streamFeatures: url.searchParams.get("stream_features") || "", onPreview: (frame) => write(frame) });
1186
1171
  }, {
1187
1172
  "X-Run-ID": admittedRunId,
1188
1173
  ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
@@ -1353,31 +1338,103 @@ function createResolvedAgents24BffHandler(options) {
1353
1338
  return mergeHeaders(publicError(404, "NOT_FOUND", "The requested BFF route does not exist."), resolution.responseHeaders);
1354
1339
  } catch (error) {
1355
1340
  if (error instanceof BffInputError) return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", publicError(error.status, error.code, error.message)), resolution.responseHeaders);
1356
- return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", errorResponse(error)), resolution.responseHeaders);
1341
+ return mergeHeaders(reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error)), resolution.responseHeaders);
1342
+ }
1343
+ };
1344
+ }
1345
+
1346
+ // src/bff-agent-resolution.ts
1347
+ function clean(value) {
1348
+ const result = typeof value === "string" ? value.trim() : "";
1349
+ return result || void 0;
1350
+ }
1351
+ function required(value, field) {
1352
+ const result = clean(value);
1353
+ if (!result || /[\r\n\0]/.test(result)) throw new Error(`${field} is required.`);
1354
+ return result;
1355
+ }
1356
+ function prepareAgents24BffAgentResolution(options) {
1357
+ if (!options.agents.length || options.agents.length > 50) {
1358
+ throw new Error("agents must contain between one and 50 Agents.");
1359
+ }
1360
+ const configured = options.agents.map((item) => {
1361
+ const agentId = clean(item.agentId);
1362
+ const agentAlias = clean(item.agentAlias);
1363
+ if (Boolean(agentId) === Boolean(agentAlias)) {
1364
+ throw new Error("Each Agent requires exactly one of agentId or agentAlias.");
1357
1365
  }
1366
+ return { agentId, agentAlias, agentVersionId: clean(item.agentVersionId) };
1367
+ });
1368
+ return async () => {
1369
+ const agents = await Promise.all(configured.map(async (item) => {
1370
+ if (item.agentAlias) {
1371
+ const resolution = await options.client.embed.resolveAgentAlias(item.agentAlias);
1372
+ return {
1373
+ agentId: required(resolution.agent_id, "agentId"),
1374
+ agentAlias: required(item.agentAlias, "agentAlias"),
1375
+ agentVersionId: item.agentVersionId
1376
+ };
1377
+ }
1378
+ return { agentId: required(item.agentId, "agentId"), agentVersionId: item.agentVersionId };
1379
+ }));
1380
+ if (new Set(agents.map((item) => item.agentId)).size !== agents.length) {
1381
+ throw new Error("Configured Agent selectors must resolve to unique Agents.");
1382
+ }
1383
+ return agents;
1358
1384
  };
1359
1385
  }
1386
+
1387
+ // src/bff-bootstrap.ts
1388
+ function principalIdentity(principal, options) {
1389
+ const profile = Object.fromEntries(Object.entries({ display_name: principal.displayName, email: principal.email, avatar_url: principal.avatarUrl }).filter(([, value]) => value !== void 0));
1390
+ return {
1391
+ integration_id: options.integrationId,
1392
+ subject: normalized(principal.subject, "subject"),
1393
+ ...options.integrationName ? { integration_name: options.integrationName } : {},
1394
+ ...principal.issuer ? { issuer: normalized(principal.issuer, "issuer") } : {},
1395
+ ...Object.keys(profile).length ? { profile } : {}
1396
+ };
1397
+ }
1398
+ async function runtimeBootstrap(options, request, identityResolver) {
1399
+ const resolution = await options.resolvePrincipal(request);
1400
+ const result = await options.client.embed.bootstrapRuntime({
1401
+ identity: principalIdentity(resolution.principal, options),
1402
+ agents: options.agents.map((agent) => ({
1403
+ ..."agentId" in agent && agent.agentId ? { agent_id: agent.agentId } : { agent_alias: agent.agentAlias },
1404
+ ...agent.agentVersionId ? { agent_version_id: agent.agentVersionId } : {}
1405
+ })),
1406
+ runtime_target: options.runtimeTarget || "published",
1407
+ selected_agent: new URL(request.url).searchParams.get("agent_id") || void 0
1408
+ });
1409
+ identityResolver.remember(resolution.principal, result.customer_principal_ref);
1410
+ await options.onPrincipalResolved?.(request, resolution, result.customer_principal_ref);
1411
+ return { response: mergeHeaders(json(result.bootstrap), resolution.responseHeaders), result };
1412
+ }
1413
+
1414
+ // src/bff.ts
1360
1415
  function createAgents24BffHandler(options) {
1361
1416
  const resolveAgents = prepareAgents24BffAgentResolution(options);
1417
+ const identity = createCustomerIdentityResolver(options.client.embed, options.integrationId, options.integrationName);
1418
+ const basePath = normalizeBasePath(options.basePath);
1362
1419
  let resolvedHandler;
1363
- const resolve = async () => {
1364
- const agents = await resolveAgents();
1365
- return createResolvedAgents24BffHandler({ ...options, agents });
1366
- };
1367
1420
  return async (request) => {
1368
- if (!browserRequestIsSameOrigin(request)) {
1369
- return publicError(403, "BFF_ORIGIN_DENIED", "The BFF accepts same-origin browser requests only.");
1370
- }
1371
- resolvedHandler ||= resolve();
1421
+ if (!browserRequestIsSameOrigin(request)) return publicError(403, "BFF_ORIGIN_DENIED", "The BFF accepts same-origin browser requests only.");
1372
1422
  try {
1373
- return (await resolvedHandler)(request);
1423
+ if (request.method === "GET" && new URL(request.url).pathname === `${basePath}/bootstrap`) {
1424
+ const { response, result } = await runtimeBootstrap(options, request, identity);
1425
+ const agents = result.resolved_agents.map((row) => ({ agentId: row.agent_id, agentAlias: row.agent_alias, agentVersionId: row.agent_version_id || void 0 }));
1426
+ resolvedHandler = Promise.resolve(createResolvedAgents24BffHandler({ ...options, agents }, identity));
1427
+ return response;
1428
+ }
1429
+ resolvedHandler ||= resolveAgents().then((agents) => createResolvedAgents24BffHandler({ ...options, agents }, identity));
1430
+ return await (await resolvedHandler)(request);
1374
1431
  } catch (error) {
1375
1432
  resolvedHandler = void 0;
1376
- return reportFailureResponse(options.onDiagnostic, request, "agent.resolve", errorResponse(error));
1433
+ return reportFailureResponse(options.onDiagnostic, request, "request", resolverErrorResponse(error));
1377
1434
  }
1378
1435
  };
1379
1436
  }
1380
1437
 
1381
- export { createAgents24BffHandler };
1438
+ export { AgentBffResolverError, createAgents24BffHandler };
1382
1439
  //# sourceMappingURL=bff.js.map
1383
1440
  //# sourceMappingURL=bff.js.map