@agents24/node 0.5.12 → 0.5.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bff.js CHANGED
@@ -213,6 +213,41 @@ function reportFailureResponse(callback, request, operation, response) {
213
213
  return response;
214
214
  }
215
215
 
216
+ // src/bff-sse.ts
217
+ function sseHeaders(headers) {
218
+ const result = new Headers(headers);
219
+ result.set("Cache-Control", "no-cache, no-transform");
220
+ result.set("Content-Type", "text/event-stream; charset=utf-8");
221
+ result.set("X-Accel-Buffering", "no");
222
+ return result;
223
+ }
224
+ function sseResponse(execute, headers, failurePayload, onFailure) {
225
+ const stream = new TransformStream();
226
+ const writer = stream.writable.getWriter();
227
+ const encoder = new TextEncoder();
228
+ const write = (value) => writer.write(encoder.encode(`data: ${JSON.stringify(value)}
229
+
230
+ `));
231
+ void execute(write).catch(async (error) => {
232
+ onFailure?.(error);
233
+ if (failurePayload) {
234
+ await write(failurePayload(error)).catch(() => void 0);
235
+ return;
236
+ }
237
+ const event = {
238
+ version: "run-stream.v3",
239
+ seq: Number.MAX_SAFE_INTEGER,
240
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
241
+ event: "run.failed",
242
+ run_id: "bff-stream-error",
243
+ stage: "run",
244
+ payload: { error: "The Agent stream failed." }
245
+ };
246
+ await write(event).catch(() => void 0);
247
+ }).finally(() => writer.close().catch(() => void 0));
248
+ return new Response(stream.readable, { headers: sseHeaders(headers) });
249
+ }
250
+
216
251
  // src/bff-values.ts
217
252
  function normalized(value, field) {
218
253
  const result = String(value || "").trim();
@@ -353,39 +388,49 @@ function routeId(path, pattern, field) {
353
388
  throw new BffInputError(400, "INVALID_PATH", `${field} is invalid.`);
354
389
  }
355
390
  }
356
- function sseHeaders(headers) {
357
- const result = new Headers(headers);
358
- result.set("Cache-Control", "no-cache, no-transform");
359
- result.set("Content-Type", "text/event-stream; charset=utf-8");
360
- result.set("X-Accel-Buffering", "no");
361
- return result;
391
+ function messageBody(body) {
392
+ const mode = body.mode === "steer" ? "steer" : body.mode === "queue" ? "queue" : null;
393
+ if (!mode) throw new BffInputError(400, "INVALID_MODE", "Message mode must be queue or steer.");
394
+ const input = stringValue(body.input) ?? "";
395
+ const attachmentIds = stringList(body.attachmentIds);
396
+ if (!input && attachmentIds.length === 0) throw new BffInputError(400, "INPUT_REQUIRED", "A message or attachment is required.");
397
+ if (input.length > MAX_INPUT_LENGTH) throw new BffInputError(413, "INPUT_TOO_LARGE", "The message is too large.");
398
+ if (attachmentIds.length > MAX_ATTACHMENTS) throw new BffInputError(400, "TOO_MANY_ATTACHMENTS", "Too many attachments.");
399
+ if (mode === "steer" && attachmentIds.length) throw new BffInputError(400, "STEER_TEXT_ONLY", "Steering supports text only.");
400
+ const requestedModelId = stringValue(body.requestedModelId) || void 0;
401
+ return {
402
+ mode,
403
+ input,
404
+ attachmentIds,
405
+ ...requestedModelId ? { requestedModelId } : {},
406
+ toolInputs: objectValue(body.toolInputs),
407
+ metadata: objectValue(body.metadata)
408
+ };
362
409
  }
363
- function sseResponse(execute, headers, failurePayload, onFailure) {
364
- const stream = new TransformStream();
365
- const writer = stream.writable.getWriter();
366
- const encoder = new TextEncoder();
367
- const write = (value) => writer.write(encoder.encode(`data: ${JSON.stringify(value)}
368
-
369
- `));
370
- void execute(write).catch(async (error) => {
371
- onFailure?.(error);
372
- if (failurePayload) {
373
- await write(failurePayload(error)).catch(() => void 0);
374
- return;
375
- }
376
- const message = "The Agent stream failed.";
377
- const event = {
378
- version: "run-stream.v3",
379
- seq: Number.MAX_SAFE_INTEGER,
380
- ts: (/* @__PURE__ */ new Date()).toISOString(),
381
- event: "run.failed",
382
- run_id: "bff-stream-error",
383
- stage: "run",
384
- payload: { error: message }
385
- };
386
- await write(event).catch(() => void 0);
387
- }).finally(() => writer.close().catch(() => void 0));
388
- return new Response(stream.readable, { headers: sseHeaders(headers) });
410
+ function messageRevision(value) {
411
+ const revision = Number(value);
412
+ if (!Number.isInteger(revision) || revision < 1) throw new BffInputError(400, "INVALID_REVISION", "Message revision is invalid.");
413
+ return revision;
414
+ }
415
+ function computerFileQuery(url, requirePath) {
416
+ const path = url.searchParams.get("path") || void 0;
417
+ if (requirePath && !path) throw new BffInputError(400, "INVALID_PATH", "path is required.");
418
+ if (path && path.length > 1024) throw new BffInputError(400, "INVALID_PATH", "path is too long.");
419
+ const rawCursor = url.searchParams.get("cursor");
420
+ const rawLimit = url.searchParams.get("limit");
421
+ const cursor = rawCursor === null ? void 0 : Number(rawCursor);
422
+ const limit = rawLimit === null ? void 0 : Number(rawLimit);
423
+ if (cursor !== void 0 && (!Number.isInteger(cursor) || cursor < 0)) {
424
+ throw new BffInputError(400, "INVALID_PAGINATION", "cursor is invalid.");
425
+ }
426
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > 200)) {
427
+ throw new BffInputError(400, "INVALID_PAGINATION", "limit is invalid.");
428
+ }
429
+ return {
430
+ ...path ? { path } : {},
431
+ ...cursor !== void 0 ? { cursor } : {},
432
+ ...limit !== void 0 ? { limit } : {}
433
+ };
389
434
  }
390
435
  function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity) {
391
436
  const agentId = normalized(options.agentId, "agentId");
@@ -443,7 +488,8 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
443
488
  }));
444
489
  } else if (request.method === "POST" && path === "/chat/stream") {
445
490
  const body = await requestJson(request);
446
- const input = stringValue(body.input);
491
+ const input = stringValue(body.input) ?? "";
492
+ const threadId = stringValue(body.threadId);
447
493
  const attachmentIds = stringList(body.attachmentIds);
448
494
  if (!input && attachmentIds.length === 0) throw new BffInputError(400, "INPUT_REQUIRED", "A message or attachment is required.");
449
495
  if (input && input.length > MAX_INPUT_LENGTH) {
@@ -452,32 +498,47 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
452
498
  if (attachmentIds.length > MAX_ATTACHMENTS) {
453
499
  throw new BffInputError(400, "TOO_MANY_ATTACHMENTS", `At most ${MAX_ATTACHMENTS} attachments are allowed.`);
454
500
  }
455
- const admission = await embed.startAgentRun(agentId, {
501
+ const admission = threadId ? await embed.submitAgentThreadMessage(agentId, threadId, {
502
+ externalUserId: customerPrincipalRef,
503
+ ...principal.externalSessionId ? { externalSessionId: principal.externalSessionId } : {},
504
+ integrationId,
505
+ runtimeTarget,
506
+ mode: "queue",
507
+ input,
508
+ attachmentIds,
509
+ ...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {},
510
+ toolInputs: objectValue(body.toolInputs),
511
+ metadata: objectValue(body.metadata)
512
+ }, { idempotencyKey }) : await embed.startAgentRun(agentId, {
456
513
  ...identity,
457
514
  integration_id: integrationId,
458
515
  ...agentVersionId ? { agent_version_id: agentVersionId } : {},
459
516
  runtime_target: runtimeTarget,
460
517
  ...input ? { input } : {},
461
518
  attachment_ids: attachmentIds,
462
- ...stringValue(body.threadId) ? { thread_id: stringValue(body.threadId) } : {},
463
519
  ...stringValue(body.requestedModelId) ? { requested_model_id: stringValue(body.requestedModelId) } : {},
464
520
  tool_inputs: objectValue(body.toolInputs),
465
521
  metadata: objectValue(body.metadata),
466
522
  client: objectValue(body.client)
467
523
  }, { idempotencyKey });
468
- response = sseResponse(async (write) => {
469
- await embed.attachAgentRun(agentId, admission.run_id, {
470
- ...identity,
471
- integration_id: integrationId,
472
- runtime_target: runtimeTarget,
473
- metadata: objectValue(body.metadata),
474
- client: objectValue(body.client),
475
- cursor: 0
476
- }, (event) => write(event), { signal: request.signal });
477
- }, {
478
- "X-Run-ID": admission.run_id,
479
- ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
480
- }, void 0, streamFailure(request, "chat.stream"));
524
+ const admittedRunId = admission.run_id;
525
+ if (!admittedRunId) {
526
+ response = json(admission, void 0, 202);
527
+ } else {
528
+ response = sseResponse(async (write) => {
529
+ await embed.attachAgentRun(agentId, admittedRunId, {
530
+ ...identity,
531
+ integration_id: integrationId,
532
+ runtime_target: runtimeTarget,
533
+ metadata: objectValue(body.metadata),
534
+ client: objectValue(body.client),
535
+ cursor: 0
536
+ }, (event) => write(event), { signal: request.signal });
537
+ }, {
538
+ "X-Run-ID": admittedRunId,
539
+ ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
540
+ }, void 0, streamFailure(request, "chat.stream"));
541
+ }
481
542
  } else if (request.method === "POST" && /^\/runs\/[^/]+\/attach$/.test(path)) {
482
543
  const runId = routeId(path, /^\/runs\/([^/]+)\/attach$/, "runId");
483
544
  const body = await requestJson(request);
@@ -558,6 +619,80 @@ function createAgents24BffHandlerWithResolver(options, resolveCustomerIdentity)
558
619
  cursor,
559
620
  reason: "stream_failed"
560
621
  }), streamFailure(request, "threads.events"));
622
+ } else if (/^\/threads\/[^/]+\/messages$/.test(path) && request.method === "GET") {
623
+ const threadId = routeId(path, /^\/threads\/([^/]+)\/messages$/, "threadId");
624
+ const before = url.searchParams.has("before") ? messageRevision(url.searchParams.get("before")) : void 0;
625
+ const limit = url.searchParams.has("limit") ? messageRevision(url.searchParams.get("limit")) : void 0;
626
+ if (limit !== void 0 && limit > 100) throw new BffInputError(400, "INVALID_PAGINATION", "limit is too large.");
627
+ response = json(await embed.listAgentThreadMessages(agentId, threadId, { ...threadIdentity, integrationId, before, limit }));
628
+ } else if (/^\/threads\/[^/]+\/messages$/.test(path) && request.method === "POST") {
629
+ const threadId = routeId(path, /^\/threads\/([^/]+)\/messages$/, "threadId");
630
+ const body = await requestJson(request);
631
+ response = json(await embed.submitAgentThreadMessage(
632
+ agentId,
633
+ threadId,
634
+ { ...threadIdentity, integrationId, ...messageBody(body) },
635
+ { idempotencyKey }
636
+ ));
637
+ } else if (/^\/threads\/[^/]+\/messages\/[^/]+$/.test(path) && request.method === "PATCH") {
638
+ const threadId = routeId(path, /^\/threads\/([^/]+)\/messages\//, "threadId");
639
+ const messageId = routeId(path, /\/messages\/([^/]+)$/, "messageId");
640
+ const body = await requestJson(request);
641
+ const input = stringValue(body.input) ?? "";
642
+ const attachmentIds = stringList(body.attachmentIds);
643
+ if (!input && !attachmentIds.length) throw new BffInputError(400, "INPUT_REQUIRED", "A message or attachment is required.");
644
+ const mode = body.mode === void 0 ? void 0 : stringValue(body.mode);
645
+ if (mode !== void 0 && mode !== "steer") throw new BffInputError(400, "INVALID_MODE", "Message mode must be steer.");
646
+ if (mode === "steer" && attachmentIds.length) throw new BffInputError(400, "STEER_TEXT_ONLY", "Steering supports text only.");
647
+ if (input.length > MAX_INPUT_LENGTH || attachmentIds.length > MAX_ATTACHMENTS) throw new BffInputError(400, "INVALID_MESSAGE", "Message limits exceeded.");
648
+ response = json(await embed.editAgentThreadMessage(
649
+ agentId,
650
+ threadId,
651
+ messageId,
652
+ {
653
+ ...threadIdentity,
654
+ integrationId,
655
+ revision: messageRevision(body.revision),
656
+ input,
657
+ attachmentIds,
658
+ ...mode ? { mode } : {},
659
+ ...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {}
660
+ }
661
+ ));
662
+ } else if (/^\/threads\/[^/]+\/messages\/[^/]+$/.test(path) && request.method === "DELETE") {
663
+ const threadId = routeId(path, /^\/threads\/([^/]+)\/messages\//, "threadId");
664
+ const messageId = routeId(path, /\/messages\/([^/]+)$/, "messageId");
665
+ response = json(await embed.removeAgentThreadMessage(
666
+ agentId,
667
+ threadId,
668
+ messageId,
669
+ { ...threadIdentity, integrationId, revision: messageRevision(url.searchParams.get("revision")) }
670
+ ));
671
+ } else if (/^\/threads\/[^/]+\/queue\/resume$/.test(path) && request.method === "POST") {
672
+ const threadId = routeId(path, /^\/threads\/([^/]+)\/queue\/resume$/, "threadId");
673
+ response = json(await embed.resumeAgentThreadQueue(agentId, threadId, { ...threadIdentity, integrationId }));
674
+ } else if (/^\/threads\/[^/]+\/computer(?:\/files|\/file|\/content-access)?$/.test(path) && (request.method === "GET" || request.method === "POST" && path.endsWith("/content-access"))) {
675
+ const threadId = routeId(path, /^\/threads\/([^/]+)\/computer/, "threadId");
676
+ const scope = { ...threadIdentity, integrationId, runtimeTarget };
677
+ if (path.endsWith("/content-access")) {
678
+ response = json(await embed.createAgentComputerContentAccess(agentId, threadId, {
679
+ ...scope,
680
+ path: computerFileQuery(url, true).path,
681
+ download: url.searchParams.get("download") === "true"
682
+ }));
683
+ } else if (path.endsWith("/files")) {
684
+ response = json(await embed.listAgentComputerFiles(agentId, threadId, {
685
+ ...scope,
686
+ ...computerFileQuery(url, false)
687
+ }));
688
+ } else if (path.endsWith("/file")) {
689
+ response = json(await embed.readAgentComputerFile(agentId, threadId, {
690
+ ...scope,
691
+ path: computerFileQuery(url, true).path
692
+ }));
693
+ } else {
694
+ response = json(await embed.getAgentComputer(agentId, threadId, scope));
695
+ }
561
696
  } else if (/^\/threads\/[^/]+$/.test(path) && request.method === "GET") {
562
697
  const threadId = routeId(path, /^\/threads\/([^/]+)$/, "threadId");
563
698
  const rawBefore = url.searchParams.get("before_turn_index");
@@ -750,6 +885,16 @@ function createResolvedAgents24BffHandler(options) {
750
885
  });
751
886
  return requestedAgent(result.agent_id).agentId;
752
887
  };
888
+ const resolveThreadAgent = async (threadId) => {
889
+ const detail = await options.client.embed.getConversationThread(threadId, {
890
+ agentIds: agents.map((agent) => agent.agentId),
891
+ externalUserId,
892
+ ...resolution.principal.externalSessionId ? { externalSessionId: resolution.principal.externalSessionId } : {},
893
+ integrationId,
894
+ runtimeTarget
895
+ });
896
+ return requestedAgent(detail.runtime_selection?.agent_id).agentId;
897
+ };
753
898
  if (request.method === "GET" && path === "/bootstrap") {
754
899
  const candidates = await Promise.all(agents.map(async (agent) => {
755
900
  const [raw, policy] = await Promise.all([
@@ -796,25 +941,38 @@ function createResolvedAgents24BffHandler(options) {
796
941
  const body = await requestJson(request);
797
942
  const selected = requestedAgent(body.requestedAgentId);
798
943
  const input = stringValue(body.input);
944
+ const threadId = stringValue(body.threadId);
799
945
  const attachmentIds = stringList(body.attachmentIds);
800
946
  if (!input && attachmentIds.length === 0) throw new BffInputError(400, "INPUT_REQUIRED", "A message or attachment is required.");
801
947
  if (input && input.length > MAX_INPUT_LENGTH) throw new BffInputError(413, "INPUT_TOO_LARGE", "The message is too large.");
802
948
  if (attachmentIds.length > MAX_ATTACHMENTS) throw new BffInputError(400, "TOO_MANY_ATTACHMENTS", `At most ${MAX_ATTACHMENTS} attachments are allowed.`);
803
- const admission = await options.client.embed.startAgentRun(selected.agentId, {
949
+ const admission = threadId ? await options.client.embed.submitAgentThreadMessage(selected.agentId, threadId, {
950
+ externalUserId,
951
+ ...resolution.principal.externalSessionId ? { externalSessionId: resolution.principal.externalSessionId } : {},
952
+ integrationId,
953
+ runtimeTarget,
954
+ mode: "queue",
955
+ input: input ?? "",
956
+ attachmentIds,
957
+ ...stringValue(body.requestedModelId) ? { requestedModelId: stringValue(body.requestedModelId) } : {},
958
+ toolInputs: objectValue(body.toolInputs),
959
+ metadata: objectValue(body.metadata)
960
+ }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")) }) : await options.client.embed.startAgentRun(selected.agentId, {
804
961
  ...identity,
805
962
  ...selected.agentVersionId ? { agent_version_id: selected.agentVersionId } : {},
806
963
  runtime_target: runtimeTarget,
807
964
  integration_id: integrationId,
808
965
  ...input ? { input } : {},
809
966
  attachment_ids: attachmentIds,
810
- ...stringValue(body.threadId) ? { thread_id: stringValue(body.threadId) } : {},
811
967
  ...stringValue(body.requestedModelId) ? { requested_model_id: stringValue(body.requestedModelId) } : {},
812
968
  tool_inputs: objectValue(body.toolInputs),
813
969
  metadata: objectValue(body.metadata),
814
970
  client: objectValue(body.client)
815
971
  }, { idempotencyKey: stringValue(request.headers.get("idempotency-key")) });
972
+ const admittedRunId = admission.run_id;
973
+ if (!admittedRunId) return mergeHeaders(json(admission, void 0, 202), resolution.responseHeaders);
816
974
  return mergeHeaders(sseResponse(async (write) => {
817
- await options.client.embed.attachAgentRun(selected.agentId, admission.run_id, {
975
+ await options.client.embed.attachAgentRun(selected.agentId, admittedRunId, {
818
976
  ...identity,
819
977
  runtime_target: runtimeTarget,
820
978
  integration_id: integrationId,
@@ -823,7 +981,7 @@ function createResolvedAgents24BffHandler(options) {
823
981
  cursor: 0
824
982
  }, (event) => write(event), { signal: request.signal });
825
983
  }, {
826
- "X-Run-ID": admission.run_id,
984
+ "X-Run-ID": admittedRunId,
827
985
  ...admission.thread_id ? { "X-Thread-ID": admission.thread_id } : {}
828
986
  }, void 0, (error) => reportFailureResponse(options.onDiagnostic, request, "chat.stream", errorResponse(error))), resolution.responseHeaders);
829
987
  }
@@ -866,6 +1024,40 @@ function createResolvedAgents24BffHandler(options) {
866
1024
  reason: "stream_failed"
867
1025
  }), (error) => reportFailureResponse(options.onDiagnostic, request, "threads.events", errorResponse(error))), resolution.responseHeaders);
868
1026
  }
1027
+ if (/^\/threads\/[^/]+\/(?:messages(?:\/[^/]+)?|queue\/resume)$/.test(path) && ["GET", "POST", "PATCH", "DELETE"].includes(request.method)) {
1028
+ const threadId = routeId(path, /^\/threads\/([^/]+)\//, "threadId");
1029
+ return dispatchToAgent(await resolveThreadAgent(threadId));
1030
+ }
1031
+ if (/^\/threads\/[^/]+\/computer(?:\/files|\/file|\/content-access)?$/.test(path) && (request.method === "GET" || request.method === "POST" && path.endsWith("/content-access"))) {
1032
+ const threadId = routeId(path, /^\/threads\/([^/]+)\/computer/, "threadId");
1033
+ const scope = {
1034
+ agentIds: agents.map((agent) => agent.agentId),
1035
+ externalUserId,
1036
+ ...resolution.principal.externalSessionId ? { externalSessionId: resolution.principal.externalSessionId } : {},
1037
+ integrationId,
1038
+ runtimeTarget
1039
+ };
1040
+ if (path.endsWith("/content-access")) {
1041
+ return mergeHeaders(json(await options.client.embed.createConversationComputerContentAccess(threadId, {
1042
+ ...scope,
1043
+ path: computerFileQuery(url, true).path,
1044
+ download: url.searchParams.get("download") === "true"
1045
+ })), resolution.responseHeaders);
1046
+ }
1047
+ if (path.endsWith("/files")) {
1048
+ return mergeHeaders(json(await options.client.embed.listConversationComputerFiles(threadId, {
1049
+ ...scope,
1050
+ ...computerFileQuery(url, false)
1051
+ })), resolution.responseHeaders);
1052
+ }
1053
+ if (path.endsWith("/file")) {
1054
+ return mergeHeaders(json(await options.client.embed.readConversationComputerFile(threadId, {
1055
+ ...scope,
1056
+ path: computerFileQuery(url, true).path
1057
+ })), resolution.responseHeaders);
1058
+ }
1059
+ return mergeHeaders(json(await options.client.embed.getConversationComputer(threadId, scope)), resolution.responseHeaders);
1060
+ }
869
1061
  if (/^\/threads\/[^/]+$/.test(path) && request.method === "GET") {
870
1062
  const threadId = routeId(path, /^\/threads\/([^/]+)$/, "threadId");
871
1063
  const rawBefore = url.searchParams.get("before_turn_index");