@agents24/client 0.2.20 → 0.2.22

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.
@@ -1,4 +1,4 @@
1
- import { createSseParser, parseObservationControl, Agents24ProtocolError, parseRuntimeSsePayload, parseThreadSummarySsePayload } from './chunk-ML3G4LFY.js';
1
+ import { parseProtocolJson, parseAssistantPreview, parseRuntimeSsePayload, Agents24ProtocolError, createSseParser, parseObservationControl, parseThreadSummarySsePayload } from './chunk-ZFNGZOYN.js';
2
2
 
3
3
  // src/upload-timing.ts
4
4
  async function timedAttachmentUpload(requestId, telemetry, operation) {
@@ -235,88 +235,6 @@ function errorKindForStatus(status) {
235
235
  return "server";
236
236
  }
237
237
 
238
- // src/reconnect.ts
239
- function shouldReconnect(error) {
240
- return error instanceof Agents24ClientError && error.kind === "network" && error.retryable;
241
- }
242
- async function reconnectRuntimeStream({
243
- initial,
244
- attach,
245
- signal,
246
- maxReconnectAttempts,
247
- operation,
248
- emit = async () => void 0,
249
- refreshSession
250
- }) {
251
- let state;
252
- let attempt = 0;
253
- const onProgress = (next) => {
254
- if (!state) {
255
- void emit({
256
- type: "stream.connected",
257
- operation,
258
- ...next.runId ? { runId: next.runId } : {},
259
- ...next.cursor === null ? {} : { cursor: next.cursor },
260
- attempt
261
- });
262
- }
263
- const messageId = next.messageId || state?.messageId;
264
- state = {
265
- ...state,
266
- ...next,
267
- runId: next.runId ?? state?.runId ?? null,
268
- threadId: next.threadId ?? state?.threadId ?? null,
269
- ...messageId ? { messageId } : {}
270
- };
271
- return state;
272
- };
273
- while (true) {
274
- try {
275
- const result = state?.runId ? await attach(state.runId, state.cursor ?? void 0, onProgress) : await initial(onProgress);
276
- state = onProgress(result);
277
- } catch (error) {
278
- if (signal?.aborted || !shouldReconnect(error) || attempt >= maxReconnectAttempts) throw error;
279
- attempt += 1;
280
- await emit({
281
- type: "stream.reconnecting",
282
- operation,
283
- ...state?.runId ? { runId: state.runId } : {},
284
- ...state?.cursor == null ? {} : { cursor: state.cursor },
285
- attempt,
286
- reason: "network"
287
- });
288
- continue;
289
- }
290
- if (state.leaseExpired && !signal?.aborted) continue;
291
- if (!state.detached || signal?.aborted) {
292
- if (state.messageStatus) return state;
293
- await emit({
294
- type: "stream.completed",
295
- operation,
296
- ...state.runId ? { runId: state.runId } : {},
297
- ...state.cursor === null ? {} : { cursor: state.cursor },
298
- attempt
299
- });
300
- return state;
301
- }
302
- await emit({
303
- type: "stream.detached",
304
- operation,
305
- ...state.runId ? { runId: state.runId } : {},
306
- ...state.cursor === null ? {} : { cursor: state.cursor },
307
- attempt,
308
- reason: state.detachReason ?? "server_detach"
309
- });
310
- if (attempt >= maxReconnectAttempts || state.detachReason === "revoked" || state.detachReason === "policy_changed") {
311
- return state;
312
- }
313
- if (state.detachReason === "token_expired" && refreshSession) {
314
- await refreshSession();
315
- }
316
- attempt += 1;
317
- }
318
- }
319
-
320
238
  // src/capabilities.ts
321
239
  function globals() {
322
240
  return globalThis;
@@ -689,78 +607,6 @@ async function dpopTokenRequest(input) {
689
607
  });
690
608
  }
691
609
 
692
- // src/multipart.ts
693
- function isBlobLike(value) {
694
- return typeof value.arrayBuffer === "function";
695
- }
696
- async function toBytes(value) {
697
- if (value instanceof Uint8Array) return value;
698
- if (value instanceof ArrayBuffer) return new Uint8Array(value);
699
- if (isBlobLike(value)) return new Uint8Array(await value.arrayBuffer());
700
- throw new Agents24ClientError("Upload data must be bytes, an ArrayBuffer, or a compatible blob-like value.", {
701
- kind: "validation",
702
- code: "INVALID_UPLOAD_DATA"
703
- });
704
- }
705
- function safeToken2(value, field) {
706
- if (!value || /[\r\n\0]/.test(value)) {
707
- throw new Agents24ClientError(`${field} contains invalid characters.`, {
708
- kind: "validation",
709
- code: "INVALID_MULTIPART_METADATA"
710
- });
711
- }
712
- return value.replace(/["\\]/g, "_");
713
- }
714
- function concat(chunks) {
715
- const length = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
716
- const output = new Uint8Array(length);
717
- let offset = 0;
718
- for (const chunk of chunks) {
719
- output.set(chunk, offset);
720
- offset += chunk.byteLength;
721
- }
722
- return output;
723
- }
724
- async function encodePart(part, boundary, encoder) {
725
- const field = safeToken2(part.field, "Multipart field");
726
- if (typeof part.value === "string") {
727
- return [encoder.encode(`--${boundary}\r
728
- Content-Disposition: form-data; name="${field}"\r
729
- \r
730
- ${part.value}\r
731
- `)];
732
- }
733
- const upload = part.value;
734
- const filename = safeToken2(upload.name, "Upload filename");
735
- const mediaType = safeToken2(normalizeAttachmentMimeType(upload.mediaType, upload.name), "Upload media type");
736
- return [
737
- encoder.encode(
738
- `--${boundary}\r
739
- Content-Disposition: form-data; name="${field}"; filename="${filename}"\r
740
- Content-Type: ${mediaType}\r
741
- \r
742
- `
743
- ),
744
- await toBytes(upload.data),
745
- encoder.encode("\r\n")
746
- ];
747
- }
748
- function createByteMultipartEncoder(encoder) {
749
- return {
750
- async encode(parts) {
751
- const boundary = `agents24-${Array.from(secureRandomBytes(18), (value) => value.toString(16).padStart(2, "0")).join("")}`;
752
- const chunks = [];
753
- for (const part of parts) chunks.push(...await encodePart(part, boundary, encoder));
754
- chunks.push(encoder.encode(`--${boundary}--\r
755
- `));
756
- return {
757
- body: concat(chunks),
758
- contentType: `multipart/form-data; boundary=${boundary}`
759
- };
760
- }
761
- };
762
- }
763
-
764
610
  // src/stream.ts
765
611
  function detachReason(event) {
766
612
  if (event.event !== "run.detached") return void 0;
@@ -857,57 +703,83 @@ async function consumeRuntimeStream(input) {
857
703
  let resolvedThreadId = input.response.headers.get("X-Thread-ID");
858
704
  let messageId;
859
705
  let detached = false;
706
+ let capacityWait;
860
707
  let streamComplete = false;
861
708
  let leaseExpired = false;
862
709
  let reason;
863
710
  input.onProgress?.({ runId, threadId: resolvedThreadId, cursor, detached: false });
864
- await consumeBody({
865
- response: input.response,
866
- ...input.signal ? { signal: input.signal } : {},
867
- decoder: input.decoder,
868
- onControl(control) {
869
- if (control.type === "lease_expired") leaseExpired = true;
870
- },
871
- async onPayload(payload) {
872
- let event;
873
- try {
874
- event = parseRuntimeSsePayload(payload, { ...input.validation, allowUnknownInternalEvents: false });
875
- } catch (error) {
876
- if (!(error instanceof Agents24ProtocolError) || error.category !== "unknown_event" || !input.validation?.allowUnknownInternalEvents) throw error;
877
- const internal = parseRuntimeSsePayload(payload, input.validation);
878
- if (cursor === null || internal.seq > cursor) {
879
- cursor = internal.seq;
880
- input.onProgress?.({ runId, threadId: resolvedThreadId, cursor, detached: false });
711
+ input.onPreview?.(null);
712
+ try {
713
+ await consumeBody({
714
+ response: input.response,
715
+ ...input.signal ? { signal: input.signal } : {},
716
+ decoder: input.decoder,
717
+ onControl(control) {
718
+ if (control.type === "lease_expired") leaseExpired = true;
719
+ },
720
+ async onPayload(payload) {
721
+ if (payload.includes('"assistant-preview.v1"')) {
722
+ const value = parseProtocolJson(payload);
723
+ if (value?.version === "assistant-preview.v1") {
724
+ const preview = parseAssistantPreview(value);
725
+ if (preview) {
726
+ input.onPreview?.(preview);
727
+ }
728
+ return;
729
+ }
881
730
  }
882
- return;
883
- }
884
- if (cursor !== null && event.seq <= cursor) return;
885
- cursor = event.seq;
886
- runId = event.run_id;
887
- resolvedThreadId = threadId(event) ?? resolvedThreadId;
888
- if (event.event === "run.accepted" && typeof event.payload.message_id === "string") {
889
- messageId = event.payload.message_id;
890
- }
891
- reason = detachReason(event);
892
- detached = reason !== void 0;
893
- if (event.event === "run.snapshot") {
894
- streamComplete = ["completed", "failed", "cancelled", "paused", "waiting", "interrupted"].includes(String(event.payload.status));
895
- } else if (event.event.startsWith("run.")) {
896
- streamComplete = ["run.completed", "run.failed", "run.cancelled", "run.paused", "run.waiting", "run.interrupted"].includes(event.event);
897
- } else if (["model.turn.started", "assistant.delta"].includes(event.event)) {
898
- streamComplete = false;
731
+ let event;
732
+ try {
733
+ event = parseRuntimeSsePayload(payload, { ...input.validation, allowUnknownInternalEvents: false });
734
+ } catch (error) {
735
+ if (!(error instanceof Agents24ProtocolError) || error.category !== "unknown_event" || !input.validation?.allowUnknownInternalEvents) throw error;
736
+ const internal = parseRuntimeSsePayload(payload, input.validation);
737
+ if (cursor === null || internal.seq > cursor) {
738
+ cursor = internal.seq;
739
+ input.onProgress?.({ runId, threadId: resolvedThreadId, cursor, detached: false });
740
+ }
741
+ return;
742
+ }
743
+ if (cursor !== null && event.seq <= cursor) return;
744
+ cursor = event.seq;
745
+ runId = event.run_id;
746
+ resolvedThreadId = threadId(event) ?? resolvedThreadId;
747
+ if (event.event === "run.accepted" && typeof event.payload.message_id === "string") {
748
+ messageId = event.payload.message_id;
749
+ }
750
+ reason = detachReason(event);
751
+ detached = reason !== void 0;
752
+ if (event.event === "run.snapshot") {
753
+ streamComplete = ["completed", "failed", "cancelled", "paused", "waiting", "interrupted"].includes(String(event.payload.status));
754
+ } else if (event.event.startsWith("run.")) {
755
+ streamComplete = ["run.completed", "run.failed", "run.cancelled", "run.paused", "run.waiting", "run.interrupted"].includes(event.event);
756
+ } else if (["model.turn.started", "assistant.delta"].includes(event.event)) {
757
+ streamComplete = false;
758
+ }
759
+ if (event.event === "run.waiting" || event.event === "run.snapshot" && event.payload.status === "waiting") {
760
+ capacityWait = void 0;
761
+ const value = event.payload.capacity_wait;
762
+ if (value && ["local_capacity", "provider_capacity", "provider_budget"].includes(value.reason || "") && typeof value.retry_at === "string" && Number.isFinite(Date.parse(value.retry_at)) && (value.deadline === null || typeof value.deadline === "string" && Number.isFinite(Date.parse(value.deadline)))) {
763
+ capacityWait = value;
764
+ }
765
+ } else if (event.event.startsWith("run.") || event.event === "model.turn.started" || event.event === "assistant.delta") {
766
+ capacityWait = void 0;
767
+ }
768
+ await input.onEvent(event);
769
+ input.onProgress?.({
770
+ runId,
771
+ threadId: resolvedThreadId,
772
+ cursor,
773
+ detached,
774
+ ...messageId ? { messageId } : {},
775
+ ...reason ? { detachReason: reason } : {},
776
+ ...capacityWait ? { capacityWait } : {}
777
+ });
899
778
  }
900
- await input.onEvent(event);
901
- input.onProgress?.({
902
- runId,
903
- threadId: resolvedThreadId,
904
- cursor,
905
- detached,
906
- ...messageId ? { messageId } : {},
907
- ...reason ? { detachReason: reason } : {}
908
- });
909
- }
910
- });
779
+ });
780
+ } finally {
781
+ input.onPreview?.(null);
782
+ }
911
783
  if (runId && !streamComplete && !leaseExpired && !detached && !input.signal?.aborted) {
912
784
  throw new Agents24ClientError("The runtime stream ended before a terminal or detach event.", {
913
785
  kind: "network",
@@ -922,7 +794,8 @@ async function consumeRuntimeStream(input) {
922
794
  detached,
923
795
  ...messageId ? { messageId } : {},
924
796
  ...reason ? { detachReason: reason } : {},
925
- leaseExpired
797
+ leaseExpired,
798
+ ...capacityWait ? { capacityWait } : {}
926
799
  };
927
800
  }
928
801
  async function consumeThreadSummaryStream(input) {
@@ -943,6 +816,204 @@ async function consumeThreadSummaryStream(input) {
943
816
  return cursor;
944
817
  }
945
818
 
946
- export { ATTACHMENT_EXTENSIONS, ATTACHMENT_MIME_ALIASES, ATTACHMENT_PROCESSING_PROFILES, ATTACHMENT_RUNTIME_LIMITS, Agents24ClientError, AuthenticatedHttp, SUPPORTED_ATTACHMENT_MIME_TYPES, absoluteUrl, appendQuery, attachmentFileAccept, canonicalHtu, consumeRuntimeStream, consumeThreadSummaryStream, createByteMultipartEncoder, defaultClock, defaultIds, dpopTokenRequest, encodePath, missingCapability, normalizeAttachmentMimeType, normalizeBaseUrl, reconnectRuntimeStream, resolveDecoderFactory, resolveEncoder, resolveFetch, responseError, responseJson, timedAttachmentUpload };
947
- //# sourceMappingURL=chunk-X4Q67CQE.js.map
948
- //# sourceMappingURL=chunk-X4Q67CQE.js.map
819
+ // src/reconnect.ts
820
+ function shouldReconnect(error) {
821
+ return error instanceof Agents24ClientError && error.kind === "network" && error.retryable;
822
+ }
823
+ function publicResult(state) {
824
+ const result = { ...state };
825
+ delete result.leaseExpired;
826
+ delete result.detachReason;
827
+ return result;
828
+ }
829
+ async function observeThreadSummaries(input) {
830
+ if (!input.signal?.aborted) {
831
+ try {
832
+ const response = await input.request(input.cursor);
833
+ await consumeThreadSummaryStream({
834
+ response,
835
+ decoder: input.decoder(),
836
+ onEvent: input.onEvent,
837
+ ...input.signal ? { signal: input.signal } : {},
838
+ ...input.onControl ? { onControl: input.onControl } : {},
839
+ ...input.cursor === void 0 ? {} : { afterCursor: input.cursor }
840
+ });
841
+ return;
842
+ } catch (error) {
843
+ if (input.signal?.aborted) return;
844
+ throw error;
845
+ }
846
+ }
847
+ }
848
+ async function reconnectRuntimeStream({
849
+ initial,
850
+ attach,
851
+ signal,
852
+ maxReconnectAttempts,
853
+ operation,
854
+ emit = async () => void 0,
855
+ refreshSession
856
+ }) {
857
+ let state;
858
+ let attempt = 0;
859
+ const onProgress = (next) => {
860
+ if (!state) {
861
+ void emit({
862
+ type: "stream.connected",
863
+ operation,
864
+ ...next.runId ? { runId: next.runId } : {},
865
+ ...next.cursor === null ? {} : { cursor: next.cursor },
866
+ attempt
867
+ });
868
+ }
869
+ const messageId = next.messageId || state?.messageId;
870
+ state = {
871
+ ...state,
872
+ ...next,
873
+ runId: next.runId ?? state?.runId ?? null,
874
+ threadId: next.threadId ?? state?.threadId ?? null,
875
+ ...messageId ? { messageId } : {}
876
+ };
877
+ if (state.capacityWait && !next.capacityWait) delete state.capacityWait;
878
+ return state;
879
+ };
880
+ while (true) {
881
+ try {
882
+ const result = state?.runId ? await attach(state.runId, state.cursor ?? void 0, onProgress) : await initial(onProgress);
883
+ state = onProgress(result);
884
+ } catch (error) {
885
+ if (signal?.aborted || !shouldReconnect(error) || attempt >= maxReconnectAttempts) throw error;
886
+ attempt += 1;
887
+ await emit({
888
+ type: "stream.reconnecting",
889
+ operation,
890
+ ...state?.runId ? { runId: state.runId } : {},
891
+ ...state?.cursor == null ? {} : { cursor: state.cursor },
892
+ attempt,
893
+ reason: "network"
894
+ });
895
+ continue;
896
+ }
897
+ if (state.capacityWait && state.runId && !signal?.aborted) {
898
+ await waitForCapacity(state.capacityWait.retry_at, signal);
899
+ if (signal?.aborted) return publicResult(state);
900
+ continue;
901
+ }
902
+ if (state.leaseExpired && !signal?.aborted) continue;
903
+ if (!state.detached || signal?.aborted) {
904
+ if (state.messageStatus) return publicResult(state);
905
+ await emit({
906
+ type: "stream.completed",
907
+ operation,
908
+ ...state.runId ? { runId: state.runId } : {},
909
+ ...state.cursor === null ? {} : { cursor: state.cursor },
910
+ attempt
911
+ });
912
+ return publicResult(state);
913
+ }
914
+ await emit({
915
+ type: "stream.detached",
916
+ operation,
917
+ ...state.runId ? { runId: state.runId } : {},
918
+ ...state.cursor === null ? {} : { cursor: state.cursor },
919
+ attempt,
920
+ reason: state.detachReason ?? "server_detach"
921
+ });
922
+ if (attempt >= maxReconnectAttempts || state.detachReason === "revoked" || state.detachReason === "policy_changed") {
923
+ return publicResult(state);
924
+ }
925
+ if (state.detachReason === "token_expired" && refreshSession) {
926
+ await refreshSession();
927
+ }
928
+ attempt += 1;
929
+ }
930
+ }
931
+ function waitForCapacity(retryAt, signal) {
932
+ if (signal?.aborted) return Promise.resolve();
933
+ return new Promise((resolve) => {
934
+ const finish = () => {
935
+ clearTimeout(timer);
936
+ signal?.removeEventListener("abort", finish);
937
+ resolve();
938
+ };
939
+ const timer = setTimeout(finish, Math.max(100, Math.min(6e4, Date.parse(retryAt) - Date.now())));
940
+ signal?.addEventListener("abort", finish, { once: true });
941
+ if (signal?.aborted) finish();
942
+ });
943
+ }
944
+
945
+ // src/multipart.ts
946
+ function isBlobLike(value) {
947
+ return typeof value.arrayBuffer === "function";
948
+ }
949
+ async function toBytes(value) {
950
+ if (value instanceof Uint8Array) return value;
951
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
952
+ if (isBlobLike(value)) return new Uint8Array(await value.arrayBuffer());
953
+ throw new Agents24ClientError("Upload data must be bytes, an ArrayBuffer, or a compatible blob-like value.", {
954
+ kind: "validation",
955
+ code: "INVALID_UPLOAD_DATA"
956
+ });
957
+ }
958
+ function safeToken2(value, field) {
959
+ if (!value || /[\r\n\0]/.test(value)) {
960
+ throw new Agents24ClientError(`${field} contains invalid characters.`, {
961
+ kind: "validation",
962
+ code: "INVALID_MULTIPART_METADATA"
963
+ });
964
+ }
965
+ return value.replace(/["\\]/g, "_");
966
+ }
967
+ function concat(chunks) {
968
+ const length = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
969
+ const output = new Uint8Array(length);
970
+ let offset = 0;
971
+ for (const chunk of chunks) {
972
+ output.set(chunk, offset);
973
+ offset += chunk.byteLength;
974
+ }
975
+ return output;
976
+ }
977
+ async function encodePart(part, boundary, encoder) {
978
+ const field = safeToken2(part.field, "Multipart field");
979
+ if (typeof part.value === "string") {
980
+ return [encoder.encode(`--${boundary}\r
981
+ Content-Disposition: form-data; name="${field}"\r
982
+ \r
983
+ ${part.value}\r
984
+ `)];
985
+ }
986
+ const upload = part.value;
987
+ const filename = safeToken2(upload.name, "Upload filename");
988
+ const mediaType = safeToken2(normalizeAttachmentMimeType(upload.mediaType, upload.name), "Upload media type");
989
+ return [
990
+ encoder.encode(
991
+ `--${boundary}\r
992
+ Content-Disposition: form-data; name="${field}"; filename="${filename}"\r
993
+ Content-Type: ${mediaType}\r
994
+ \r
995
+ `
996
+ ),
997
+ await toBytes(upload.data),
998
+ encoder.encode("\r\n")
999
+ ];
1000
+ }
1001
+ function createByteMultipartEncoder(encoder) {
1002
+ return {
1003
+ async encode(parts) {
1004
+ const boundary = `agents24-${Array.from(secureRandomBytes(18), (value) => value.toString(16).padStart(2, "0")).join("")}`;
1005
+ const chunks = [];
1006
+ for (const part of parts) chunks.push(...await encodePart(part, boundary, encoder));
1007
+ chunks.push(encoder.encode(`--${boundary}--\r
1008
+ `));
1009
+ return {
1010
+ body: concat(chunks),
1011
+ contentType: `multipart/form-data; boundary=${boundary}`
1012
+ };
1013
+ }
1014
+ };
1015
+ }
1016
+
1017
+ export { ATTACHMENT_EXTENSIONS, ATTACHMENT_MIME_ALIASES, ATTACHMENT_PROCESSING_PROFILES, ATTACHMENT_RUNTIME_LIMITS, Agents24ClientError, AuthenticatedHttp, SUPPORTED_ATTACHMENT_MIME_TYPES, absoluteUrl, appendQuery, attachmentFileAccept, canonicalHtu, consumeRuntimeStream, consumeThreadSummaryStream, createByteMultipartEncoder, defaultClock, defaultIds, dpopTokenRequest, encodePath, missingCapability, normalizeAttachmentMimeType, normalizeBaseUrl, observeThreadSummaries, reconnectRuntimeStream, resolveDecoderFactory, resolveEncoder, resolveFetch, responseError, responseJson, timedAttachmentUpload };
1018
+ //# sourceMappingURL=chunk-GOBSV2DI.js.map
1019
+ //# sourceMappingURL=chunk-GOBSV2DI.js.map