@burdenoff/fe-libs 2026.1022.3 → 2026.1023.2

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,21 +1,22 @@
1
1
  import { assistantLlmTerminalCodeOf as e } from "./sandboxProxyError.js";
2
2
  import { isQuotaExhaustedError as t } from "./quota.js";
3
+ import { buildProgress as n, isReapedSandboxConnectionError as r, isRecoverable as i, mergeMessagesById as a, sanitize as o } from "./progress.js";
4
+ import { AssistantPromptDelivery as s, trackAssistantSandboxTurn as c } from "./promptDelivery.js";
3
5
  import "./gatewayClient.js";
4
- import { checkAssistantAiCredits as n, getAssistantMessages as r, getAssistantStreamAccess as i, reportAssistantAiTokenUsage as a, sendAssistantPromptAsync as o, stopReapedAssistantSandbox as s } from "./api.js";
5
- import { AssistantRuntimeManager as c } from "./runtime.js";
6
- import { buildProgress as l, isReapedSandboxConnectionError as u, isRecoverable as d, mergeMessagesById as f, sanitize as p } from "./progress.js";
7
- import { parseUiOffers as m } from "./uiActions/uiOffers.js";
8
- import { assistantUsageLedger as h, hasPendingUsageReports as g, reportUsageWithRetry as _, retryPendingUsageReports as v, usageSendRefusal as y } from "./usageReporting.js";
6
+ import { checkAssistantAiCredits as l, getAssistantMessages as u, getAssistantStreamAccess as d, reportAssistantAiTokenUsage as f, sendAssistantPromptAsync as p, stopReapedAssistantSandbox as m } from "./api.js";
7
+ import { AssistantRuntimeManager as h } from "./runtime.js";
8
+ import { parseUiOffers as g } from "./uiActions/uiOffers.js";
9
+ import { assistantUsageLedger as _, hasPendingUsageReports as v, reportUsageWithRetry as y, retryPendingUsageReports as b, usageSendRefusal as x } from "./usageReporting.js";
9
10
  //#region src/shared/assistant/createSandboxAssistantTransport.ts
10
- var b = 42e4, x = 400, S = 2e3, C = 5e3;
11
- function w() {
11
+ var S = 42e4, C = 400, w = 2e3, T = 5e3;
12
+ function E() {
12
13
  return typeof window > "u" ? {} : {
13
14
  currentUrl: window.location.href,
14
15
  currentPage: window.location.pathname.split("/").filter(Boolean).slice(0, 3).join("/") || "home",
15
16
  viewportSize: `${window.innerWidth}x${window.innerHeight}`
16
17
  };
17
18
  }
18
- function T(e, t) {
19
+ function D(e, t) {
19
20
  let n = /* @__PURE__ */ new Set();
20
21
  for (let e of t) e.info?.role === "user" && typeof e.info.id == "string" && n.add(e.info.id);
21
22
  let r = /* @__PURE__ */ new Set();
@@ -25,115 +26,128 @@ function T(e, t) {
25
26
  }
26
27
  return e.filter((e) => r.has(`${e.turnId} ${e.assistantMessageId}`));
27
28
  }
28
- function E(E, D) {
29
- let O = E.mode ?? "assistant", k = E.streamBudgetMs ?? b, A = { accumulateNarration: E.accumulateNarration === !0 }, j = E.ttlSeconds ?? 3600, M = E.isProdRuntime ?? (() => !1), N = E.enableCredits ?? !1, P = h("transport", E.product), F = (e) => async (t) => {
30
- t.messageId && await a(t.workspaceId, t.sessionId, t.messageId, t.model, t.tokens, e);
31
- }, I = new c({
32
- product: E.product,
33
- mode: O,
34
- ttlSeconds: j,
35
- isProd: M,
36
- getWorkspaceId: D.getWorkspaceId,
37
- getAuthContext: D.getAuthContext
38
- }), L = () => E.gatherPageContext ? { ...E.gatherPageContext() } : w();
39
- async function R(t, n, a, c) {
29
+ function O(O, k) {
30
+ let A = O.mode ?? "assistant", j = O.streamBudgetMs ?? S, M = { accumulateNarration: O.accumulateNarration === !0 }, N = O.ttlSeconds ?? 3600, P = O.isProdRuntime ?? (() => !1), F = O.enableCredits ?? !1, I = _("transport", O.product), L = (e) => async (t) => {
31
+ t.messageId && await f(t.workspaceId, t.sessionId, t.messageId, t.model, t.tokens, e);
32
+ }, R = new h({
33
+ product: O.product,
34
+ mode: A,
35
+ ttlSeconds: N,
36
+ isProd: P,
37
+ getWorkspaceId: k.getWorkspaceId,
38
+ getAuthContext: k.getAuthContext
39
+ }), z = () => O.gatherPageContext ? { ...O.gatherPageContext() } : E();
40
+ async function B(t, l, f, h) {
41
+ let _ = new s(), v = !1, b = () => {}, x = () => v || t.signal.aborted;
40
42
  try {
41
- let { sandboxId: e, sessionId: s } = await I.ensureRuntime();
42
- I.startKeepWarm();
43
- let c = Date.now();
44
- await o(e, n, s, t.prompt, O, L(), a, t.parts?.length ? { parts: t.parts } : void 0);
45
- let u = null, d = null, h = await i(e, n, s, O, a).catch(() => null);
43
+ if (x()) throw Error("Cancelled");
44
+ let { sandboxId: e, sessionId: r } = await R.ensureRuntime();
45
+ b = c(e, () => {
46
+ v = !0;
47
+ }), R.startKeepWarm();
48
+ let i = Date.now();
49
+ if (await _.dispatch({
50
+ prompt: t.prompt,
51
+ isAbandoned: x,
52
+ readMessages: (t) => u(e, l, r, A, f, { sinceMs: t }),
53
+ send: () => p(e, l, r, t.prompt, A, z(), f, t.parts?.length ? { parts: t.parts } : void 0)
54
+ }), x()) throw Error("Cancelled");
55
+ let s = null, m = null, h = await d(e, l, r, A, f).catch(() => null);
46
56
  if (h && typeof EventSource < "u") try {
47
- d = new EventSource(h.url);
57
+ m = new EventSource(h.url);
48
58
  let e = () => {
49
- if (u) {
50
- let e = u;
51
- u = null, e();
59
+ if (s) {
60
+ let e = s;
61
+ s = null, e();
52
62
  }
53
63
  };
54
- d.onmessage = e, d.addEventListener("message.part.updated", e), d.addEventListener("message.updated", e), d.onerror = () => {
55
- d?.close(), d = null;
64
+ m.onmessage = e, m.addEventListener("message.part.updated", e), m.addEventListener("message.updated", e), m.onerror = () => {
65
+ m?.close(), m = null;
56
66
  };
57
67
  } catch {
58
- d?.close(), d = null;
68
+ m?.close(), m = null;
59
69
  }
60
- let g = (e) => new Promise((n) => {
70
+ let S = (e) => new Promise((n) => {
61
71
  if (t.signal.aborted) return n();
62
72
  let r = setTimeout(() => {
63
- u = null, n();
73
+ s = null, n();
64
74
  }, e);
65
- u = () => {
75
+ s = () => {
66
76
  clearTimeout(r), n();
67
77
  };
68
- }), v = E.onUiOffers, y = null, b = v ? (e, t) => {
69
- y = m(e, t);
70
- } : void 0, w = () => {
71
- let e = y;
72
- return y = null, e;
73
- }, D = c + k, j = [], M = l([], c, A), R = c;
78
+ }), E = O.onUiOffers, k = null, N = E ? (e, t) => {
79
+ k = g(e, t);
80
+ } : void 0, P = () => {
81
+ let e = k;
82
+ return k = null, e;
83
+ }, B = i + j, V = [], H = n([], i, M), U = i;
74
84
  try {
75
- for (; Date.now() < D;) {
76
- if (t.signal.aborted) throw Error("Cancelled");
77
- let i = await r(e, n, s, O, a, {
78
- sinceMs: R,
85
+ for (; Date.now() < B;) {
86
+ if (x()) throw Error("Cancelled");
87
+ let s = await u(e, l, r, A, f, {
88
+ sinceMs: U,
79
89
  surfaceTurnTerminal: !0,
80
- surfaceUiOffers: b
90
+ surfaceUiOffers: N
81
91
  });
82
- j = f(j, i);
83
- let o = w();
84
- v && o && v(T(o.offers, j), o.serverNow);
85
- for (let e of i) {
92
+ V = a(V, s);
93
+ let c = P();
94
+ E && c && E(D(c.offers, V), c.serverNow);
95
+ for (let e of s) {
86
96
  let t = e.info?.time?.created;
87
- typeof t == "number" && t > R && (R = t);
97
+ typeof t == "number" && t > U && (U = t);
88
98
  }
89
- if (M = l(j, c, A), t.onProgress(p(M.content)), M.done) break;
90
- let u = Date.now() - c < C ? x : S;
91
- await (d ? g(u) : new Promise((e) => setTimeout(e, u)));
99
+ if (H = n(V, i, M), t.onProgress(o(H.content)), H.done) break;
100
+ let d = Date.now() - i < T ? C : w;
101
+ await (m ? S(d) : new Promise((e) => setTimeout(e, d)));
92
102
  }
93
103
  } finally {
94
- d?.close();
104
+ m?.close();
95
105
  }
96
- if (!M.done) throw Error("The assistant timed out while responding. Please try again.");
97
- let z = await r(e, n, s, O, a, { limit: 50 }).catch(() => j), B = l(f(j, z), c, A);
98
- if (N) {
99
- let e = z.filter((e) => e.info?.role === "assistant").sort((e, t) => (t.info?.time?.created ?? 0) - (e.info?.time?.created ?? 0))[0], t = e?.info?.tokens, r = e?.info?.providerID && e?.info?.modelID ? `${e.info.providerID}/${e.info.modelID}` : void 0;
100
- e?.info?.id && t && (await _({
101
- workspaceId: n,
102
- sessionId: s,
106
+ if (!H.done) throw Error("The assistant timed out while responding. Please try again.");
107
+ let W = await u(e, l, r, A, f, { limit: 50 }).catch(() => V), G = n(a(V, W), i, M);
108
+ if (F) {
109
+ let e = W.filter((e) => e.info?.role === "assistant").sort((e, t) => (t.info?.time?.created ?? 0) - (e.info?.time?.created ?? 0))[0], t = e?.info?.tokens, n = e?.info?.providerID && e?.info?.modelID ? `${e.info.providerID}/${e.info.modelID}` : void 0;
110
+ e?.info?.id && t && (await y({
111
+ workspaceId: l,
112
+ sessionId: r,
103
113
  messageId: e.info.id,
104
- model: r,
114
+ model: n,
105
115
  tokens: t
106
- }, F(a), { ledger: P })).ok && E.onCreditsUpdated?.();
116
+ }, L(f), { ledger: I })).ok && O.onCreditsUpdated?.();
107
117
  }
108
- return { text: p(B.content) };
109
- } catch (r) {
110
- if (c === 1 && d(r)) {
111
- let i = u(r), o = e(r) === "ASSISTANT_SESSION_REVOKED", c = i || o;
112
- if (c) {
113
- let e = I.getSandboxId();
114
- e && await s(e, n, a, { ownerScoped: o }).catch(() => void 0);
118
+ return { text: o(G.content) };
119
+ } catch (n) {
120
+ if (x()) throw Error("Cancelled", { cause: n });
121
+ if (h === 1 && _.canFailover() && i(n)) {
122
+ b();
123
+ let i = r(n), a = e(n) === "ASSISTANT_SESSION_REVOKED", o = i || a;
124
+ if (o) {
125
+ let e = R.getSandboxId();
126
+ e && await m(e, l, f, { ownerScoped: a }).catch(() => void 0);
115
127
  }
116
- return I.reset({ quarantineCurrentSandbox: c }), R(t, n, a, 2);
128
+ return R.reset({ quarantineCurrentSandbox: o }), B(t, l, f, 2);
117
129
  }
118
- throw r;
130
+ throw n;
131
+ } finally {
132
+ b();
119
133
  }
120
134
  }
121
135
  return {
122
136
  sendPrompt: async (e) => {
123
- let r = D.getWorkspaceId();
124
- if (!r) throw Error("The assistant needs an active workspace. Open a workspace and try again.");
125
- let i = D.getAuthContext();
126
- if (N && g(P, r)) {
127
- let e = await v(P, r, F(i));
128
- if (!e.ok) throw y(e.kind);
137
+ let n = k.getWorkspaceId();
138
+ if (!n) throw Error("The assistant needs an active workspace. Open a workspace and try again.");
139
+ let r = k.getAuthContext();
140
+ if (F && v(I, n)) {
141
+ let e = await b(I, n, L(r));
142
+ if (!e.ok) throw x(e.kind);
129
143
  }
130
- return N && n(r, i).catch((e) => {
131
- t(e) && E.onQuotaExhausted?.(e);
132
- }), R(e, r, i, 1);
144
+ return F && l(n, r).catch((e) => {
145
+ t(e) && O.onQuotaExhausted?.(e);
146
+ }), B(e, n, r, 1);
133
147
  },
134
- prewarm: (e) => I.prewarm(e),
135
- suspend: () => I.stopKeepWarm()
148
+ prewarm: (e) => R.prewarm(e),
149
+ suspend: () => R.stopKeepWarm()
136
150
  };
137
151
  }
138
152
  //#endregion
139
- export { E as createSandboxAssistantTransport, T as offersOfThisTurn };
153
+ export { O as createSandboxAssistantTransport, D as offersOfThisTurn };
@@ -1,6 +1,6 @@
1
- import { isAssistantModeId as e } from "../modeIds.js";
2
- import { MAX_REQUEST_BODY_BYTES as t } from "../gatewayLimits.js";
3
- import { sanitize as n } from "../progress.js";
1
+ import { sanitize as e } from "../progress.js";
2
+ import { isAssistantModeId as t } from "../modeIds.js";
3
+ import { MAX_REQUEST_BODY_BYTES as n } from "../gatewayLimits.js";
4
4
  import { ASSISTANT_HISTORY_SAVE_MUTATION as r, ASSISTANT_HISTORY_SAVE_OPERATION as i, buildHistorySaveVariables as a } from "./historyOperations.js";
5
5
  import { historyTimestampToIso as o } from "./historyTimestamps.js";
6
6
  import "./historyTypes.js";
@@ -251,13 +251,13 @@ function X(e, t) {
251
251
  })
252
252
  });
253
253
  }
254
- var Z = t - u;
255
- function le(e, t) {
256
- let r = e.map((e) => {
257
- let r = k(n(e.content)), i = I(e.timestamp) ? e.timestamp : null, a = H(t.kind, i, z(K(e.metadata)).kept), o = {
254
+ var Z = n - u;
255
+ function le(t, n) {
256
+ let r = t.map((t) => {
257
+ let r = k(e(t.content)), i = I(t.timestamp) ? t.timestamp : null, a = H(n.kind, i, z(K(t.metadata)).kept), o = {
258
258
  input: {
259
- clientMessageId: e.id,
260
- role: U[e.role],
259
+ clientMessageId: t.id,
260
+ role: U[t.role],
261
261
  content: r,
262
262
  ...i ? { clientCreatedAt: i } : {},
263
263
  ...Object.keys(a).length > 0 ? { metadata: a } : {}
@@ -267,17 +267,17 @@ function le(e, t) {
267
267
  return x(r) <= 98304 ? o : Y(o, q(r, l - x(y)) + y, !0);
268
268
  }), i = J(y);
269
269
  for (let e = 0; e < 3; e += 1) {
270
- let e = X(t, r.map((e) => e.input)) - Z;
270
+ let e = X(n, r.map((e) => e.input)) - Z;
271
271
  if (e <= 0) break;
272
- let n = -1, a = -1;
273
- r.forEach((e, t) => {
272
+ let t = -1, a = -1;
273
+ r.forEach((e, n) => {
274
274
  let r = J(e.input.content);
275
- r > a && (n = t, a = r);
275
+ r > a && (t = n, a = r);
276
276
  });
277
- let o = r[n];
277
+ let o = r[t];
278
278
  if (!o) break;
279
279
  let s = Math.max(0, a - e - i - 64), c = ce(o.source, s) + y;
280
- r = r.map((e, t) => t === n ? Y(e, c, !0) : e);
280
+ r = r.map((e, n) => n === t ? Y(e, c, !0) : e);
281
281
  }
282
282
  return r.map((e) => e.input);
283
283
  }
@@ -401,9 +401,9 @@ function be(e) {
401
401
  ...typeof o == "string" ? { at: o } : {}
402
402
  };
403
403
  }
404
- function xe(t) {
405
- let { kept: n } = z(t), r = {};
406
- if (n.voice === !0 && (r.voice = !0, typeof n.voiceSessionId == "string" && n.voiceSessionId.length > 0 && (r.voiceSessionId = n.voiceSessionId)), typeof n.lang == "string" && n.lang.length > 0 && (r.lang = n.lang), e(n.mode) && (r.mode = n.mode), typeof n.sandboxId == "string" && (r.sandboxId = n.sandboxId), typeof n.sessionId == "string" && (r.sessionId = n.sessionId), Array.isArray(n.attachments)) {
404
+ function xe(e) {
405
+ let { kept: n } = z(e), r = {};
406
+ if (n.voice === !0 && (r.voice = !0, typeof n.voiceSessionId == "string" && n.voiceSessionId.length > 0 && (r.voiceSessionId = n.voiceSessionId)), typeof n.lang == "string" && n.lang.length > 0 && (r.lang = n.lang), t(n.mode) && (r.mode = n.mode), typeof n.sandboxId == "string" && (r.sandboxId = n.sandboxId), typeof n.sessionId == "string" && (r.sessionId = n.sessionId), Array.isArray(n.attachments)) {
407
407
  let e = n.attachments.map(pe).filter((e) => e !== null);
408
408
  e.length > 0 && (r.attachments = e);
409
409
  }
@@ -418,16 +418,16 @@ function xe(t) {
418
418
  }
419
419
  return r;
420
420
  }
421
- function Se(e) {
422
- let t = xe(e.metadata);
421
+ function Se(t) {
422
+ let n = xe(t.metadata);
423
423
  return {
424
- id: e.clientMessageId ?? `legacy:${e.id}`,
425
- role: de[e.role],
426
- content: n(e.content),
427
- timestamp: o(e.clientCreatedAt) ?? o(e.createdAt) ?? e.createdAt,
428
- ...Object.keys(t).length > 0 ? { metadata: t } : {},
424
+ id: t.clientMessageId ?? `legacy:${t.id}`,
425
+ role: de[t.role],
426
+ content: e(t.content),
427
+ timestamp: o(t.clientCreatedAt) ?? o(t.createdAt) ?? t.createdAt,
428
+ ...Object.keys(n).length > 0 ? { metadata: n } : {},
429
429
  historyState: "saved",
430
- ...typeof e.seq == "number" ? { historySeq: e.seq } : {}
430
+ ...typeof t.seq == "number" ? { historySeq: t.seq } : {}
431
431
  };
432
432
  }
433
433
  //#endregion
@@ -346,3 +346,4 @@ export * from './avatar/live/AvatarFace';
346
346
  export * from './avatar/live/liveAvatarStatus';
347
347
  export * from './avatar/live/createLiveAvatarSeam';
348
348
  export * from './avatar/live/avatarVoice';
349
+ export * from './promptDelivery';
@@ -71,6 +71,8 @@ export declare function sanitize(response: string): string;
71
71
  * a prompt whose first attempt actually reached the model.
72
72
  */
73
73
  export declare function isReapedSandboxConnectionError(error: unknown): boolean;
74
+ /** Only known sandbox-service refusals that return before forwarding a request. */
75
+ export declare function isPreForwardSandboxRefusal(status: number | undefined, errorBody: unknown): boolean;
74
76
  /**
75
77
  * Whether an error is worth one retry from a clean runtime (union of fleet fragments).
76
78
  *
@@ -76,13 +76,21 @@ function f(e) {
76
76
  let t = e instanceof Error ? e.message.toLowerCase() : String(e).toLowerCase();
77
77
  return t.includes("unable to connect") && t.includes("able to access the url");
78
78
  }
79
- function p(t) {
79
+ var p = [
80
+ "sandbox is not running",
81
+ "proxy credentials not ready",
82
+ "service url not available"
83
+ ];
84
+ function m(e, t) {
85
+ return e === 503 && typeof t == "string" && p.some((e) => t.toLowerCase().includes(e));
86
+ }
87
+ function h(t) {
80
88
  let n = e(t);
81
89
  if (n !== null) return n;
82
90
  let r = t instanceof Error ? t.message.toLowerCase() : String(t).toLowerCase();
83
91
  return r.includes("rate limit exceeded") || r.includes("unauthorized") || r.includes("k8s api error 401") ? !1 : f(t) ? !0 : [
84
92
  "sandbox not found",
85
- "sandbox is not running",
93
+ ...p,
86
94
  "sandbox service not available yet",
87
95
  "sandbox failed",
88
96
  "sandbox startup timed out",
@@ -96,7 +104,7 @@ function p(t) {
96
104
  "proxy error: 503"
97
105
  ].some((e) => r.includes(e));
98
106
  }
99
- function m(e, n) {
107
+ function g(e, n) {
100
108
  let r = /* @__PURE__ */ new Map();
101
109
  for (let t of e) {
102
110
  let e = t.info?.id;
@@ -108,7 +116,7 @@ function m(e, n) {
108
116
  }
109
117
  return Array.from(r.values()).sort((e, n) => t(e) - t(n));
110
118
  }
111
- function h(e) {
119
+ function _(e) {
112
120
  let r = [];
113
121
  for (let i of e) {
114
122
  let e = i.info?.role;
@@ -123,4 +131,4 @@ function h(e) {
123
131
  return r;
124
132
  }
125
133
  //#endregion
126
- export { u as buildProgress, o as getAssistantMedia, n as getAssistantText, t as getRawMessageCreatedAt, l as getToolProgress, f as isReapedSandboxConnectionError, p as isRecoverable, h as mapSessionToHistory, m as mergeMessagesById, d as sanitize };
134
+ export { u as buildProgress, o as getAssistantMedia, n as getAssistantText, t as getRawMessageCreatedAt, l as getToolProgress, m as isPreForwardSandboxRefusal, f as isReapedSandboxConnectionError, h as isRecoverable, _ as mapSessionToHistory, g as mergeMessagesById, d as sanitize };
@@ -0,0 +1,24 @@
1
+ import { AssistantRawMessage } from './types';
2
+ export type AssistantPromptDeliveryState = 'not-sent' | 'sending' | 'admitted' | 'indeterminate';
3
+ /** A real proxy response, preserved without changing its existing error/code. */
4
+ export declare function withAssistantProxyResponse(error: Error, status: number | undefined, body: unknown): Error;
5
+ export declare const assistantPromptReconcileClock: {
6
+ now: () => number;
7
+ sleep: (ms: number) => Promise<void>;
8
+ };
9
+ /** One user turn. Only a definite refusal can make another dispatch eligible. */
10
+ export declare class AssistantPromptDelivery {
11
+ private delivery;
12
+ get state(): AssistantPromptDeliveryState;
13
+ canFailover(): boolean;
14
+ dispatch(options: {
15
+ prompt: string;
16
+ send: () => Promise<unknown>;
17
+ readMessages: (sinceMs: number) => Promise<AssistantRawMessage[]>;
18
+ isAbandoned: () => boolean;
19
+ }): Promise<void>;
20
+ }
21
+ /** Register only for the lifetime of the attempt; no prompt text is stored. */
22
+ export declare function trackAssistantSandboxTurn(sandboxId: string, abandon: () => void): () => void;
23
+ /** Synchronous abandonment must precede any app-initiated sandbox stop. */
24
+ export declare function abandonAssistantSandboxTurns(sandboxId: string): void;
@@ -0,0 +1,80 @@
1
+ import { isPreForwardSandboxRefusal as e } from "./progress.js";
2
+ //#region src/shared/assistant/promptDelivery.ts
3
+ function t(e, t, n) {
4
+ return Object.assign(e, { assistantProxyResponse: {
5
+ status: t,
6
+ errorBody: typeof n == "object" && n && "error" in n && typeof n.error == "string" && n.error.length > 0 ? n.error : void 0
7
+ } });
8
+ }
9
+ function n(e) {
10
+ if (!e || typeof e != "object" || !("assistantProxyResponse" in e)) return null;
11
+ let t = e.assistantProxyResponse;
12
+ return !t || typeof t != "object" ? null : {
13
+ status: "status" in t && typeof t.status == "number" ? t.status : void 0,
14
+ errorBody: "errorBody" in t && typeof t.errorBody == "string" ? t.errorBody : void 0
15
+ };
16
+ }
17
+ var r = {
18
+ now: () => Date.now(),
19
+ sleep: (e) => new Promise((t) => setTimeout(t, e))
20
+ }, i = class {
21
+ delivery = "not-sent";
22
+ get state() {
23
+ return this.delivery;
24
+ }
25
+ canFailover() {
26
+ return this.delivery === "not-sent";
27
+ }
28
+ async dispatch(t) {
29
+ if (t.isAbandoned()) throw Error("Cancelled");
30
+ if (!this.canFailover()) throw Error("The assistant turn may already have been delivered.");
31
+ let i = r.now();
32
+ this.delivery = "sending";
33
+ try {
34
+ await t.send(), this.delivery = "admitted";
35
+ return;
36
+ } catch (a) {
37
+ let o = n(a);
38
+ if (a instanceof Error && "assistantPromptNotDispatched" in a && a.assistantPromptNotDispatched === !0 || e(o?.status, o?.errorBody) || o?.errorBody && o.status !== void 0 && o.status >= 400 && o.status < 500) throw this.delivery = "not-sent", a;
39
+ if (this.delivery = "indeterminate", o?.status !== void 0 && ![
40
+ 502,
41
+ 503,
42
+ 504
43
+ ].includes(o.status)) throw a;
44
+ let s = r.now() + 1e4;
45
+ for (; r.now() < s;) {
46
+ if (t.isAbandoned()) throw Error("Cancelled", { cause: a });
47
+ let e, n = s - r.now();
48
+ try {
49
+ let r = await Promise.race([t.readMessages(i), new Promise((t) => {
50
+ e = setTimeout(() => t([]), n);
51
+ })]);
52
+ if (t.isAbandoned()) throw Error("Cancelled", { cause: a });
53
+ if (r.some((e) => e.info?.role === "user" && typeof e.info.time?.created == "number" && e.info.time.created > i && (e.parts ?? []).filter((e) => e.type === "text").map((e) => e.text ?? "").join("") === t.prompt)) {
54
+ this.delivery = "admitted";
55
+ return;
56
+ }
57
+ } catch {} finally {
58
+ e !== void 0 && clearTimeout(e);
59
+ }
60
+ if (t.isAbandoned()) throw Error("Cancelled", { cause: a });
61
+ let o = Math.min(250, s - r.now());
62
+ o > 0 && await r.sleep(o);
63
+ }
64
+ throw a;
65
+ }
66
+ }
67
+ }, a = /* @__PURE__ */ new Map();
68
+ function o(e, t) {
69
+ let n = a.get(e) ?? /* @__PURE__ */ new Set();
70
+ n.add(t), a.set(e, n);
71
+ let r = !0;
72
+ return () => {
73
+ r && (r = !1, n.delete(t), n.size === 0 && a.delete(e));
74
+ };
75
+ }
76
+ function s(e) {
77
+ for (let t of a.get(e) ?? []) t();
78
+ }
79
+ //#endregion
80
+ export { i as AssistantPromptDelivery, s as abandonAssistantSandboxTurns, r as assistantPromptReconcileClock, o as trackAssistantSandboxTurn, t as withAssistantProxyResponse };