@xiaoso/dsh-tool-plus 0.1.0-beta.3 → 0.1.0-beta.4

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 (155) hide show
  1. package/lib/abort-D1_Z5Ut5.mjs +51 -0
  2. package/lib/abort-dIkZBV7Q.mjs +51 -0
  3. package/lib/amazon-bedrock-B0nxT06F.mjs +917 -0
  4. package/lib/amazon-bedrock-WQhvjHYu.mjs +917 -0
  5. package/lib/anthropic-CJCauvYz.mjs +3115 -0
  6. package/lib/anthropic-CZghe_9U.mjs +3115 -0
  7. package/lib/anthropic-sCMH7JID.mjs +262 -0
  8. package/lib/anthropic-tTntD8BD.mjs +262 -0
  9. package/lib/api-key-login-BzqNdM2y.mjs +157 -0
  10. package/lib/api-key-login-CWVwvHT1.mjs +157 -0
  11. package/lib/aws-credentials-CXryMobh.mjs +867 -0
  12. package/lib/aws-credentials-ChG79ey-.mjs +867 -0
  13. package/lib/azure-openai-responses-Cgmc-rbL.mjs +274 -0
  14. package/lib/azure-openai-responses-DuukbD0F.mjs +274 -0
  15. package/lib/bun-shim.mjs +81 -6
  16. package/lib/bundled-references-Cavaffah.mjs +55 -0
  17. package/lib/bundled-references-sLN0YdXU.mjs +55 -0
  18. package/lib/callback-server-CQ5Jo8F-.mjs +398 -0
  19. package/lib/callback-server-DDSrZ6l_.mjs +398 -0
  20. package/lib/client.js +1 -1
  21. package/lib/cursor-B3zg7EHj.mjs +273 -0
  22. package/lib/cursor-B6TUEmgP.mjs +135 -0
  23. package/lib/cursor-D8gvtTL3.mjs +135 -0
  24. package/lib/cursor-DkSX2h3H.mjs +5441 -0
  25. package/lib/cursor-aJrXeYCb.mjs +273 -0
  26. package/lib/cursor-mJQwUKXK.mjs +5441 -0
  27. package/lib/device-code-DBo3B5nh.mjs +51 -0
  28. package/lib/device-code-DIb0FU-H.mjs +51 -0
  29. package/lib/devin-BHZZyMhO.mjs +95 -0
  30. package/lib/devin-BK7DHeca.mjs +114 -0
  31. package/lib/devin-CfMp3cXS.mjs +95 -0
  32. package/lib/devin-D9zR5B_R.mjs +542 -0
  33. package/lib/devin-Q1yem3lp.mjs +114 -0
  34. package/lib/devin-vNZTNUON.mjs +542 -0
  35. package/lib/error-Dd8DIqs-.mjs +1449 -0
  36. package/lib/error-yCSG0mGC.mjs +1449 -0
  37. package/lib/event-stream-BbFZJy-z.mjs +151 -0
  38. package/lib/event-stream-loUa0s1T.mjs +151 -0
  39. package/lib/fs-promises-shim-Bx0fpxuk.mjs +57 -0
  40. package/lib/github-copilot-B1yiyVRh.mjs +104 -0
  41. package/lib/github-copilot-BWT3eAOF.mjs +208 -0
  42. package/lib/github-copilot-CYkjeTi3.mjs +208 -0
  43. package/lib/github-copilot-jscUZ8Hf.mjs +104 -0
  44. package/lib/gitlab-duo-CM7Ref1H.mjs +155 -0
  45. package/lib/gitlab-duo-gubO4FNw.mjs +155 -0
  46. package/lib/gitlab-duo-workflow-BGAF6JDw.mjs +91 -0
  47. package/lib/gitlab-duo-workflow-D78tdn8E.mjs +91 -0
  48. package/lib/google-BS4T25Pn.mjs +30 -0
  49. package/lib/google-TFe-7-of.mjs +30 -0
  50. package/lib/google-antigravity-DGmwC2KV.mjs +198 -0
  51. package/lib/google-antigravity-DNYhgTpA.mjs +198 -0
  52. package/lib/google-auth-B6gjsZvg.mjs +232 -0
  53. package/lib/google-auth-De7_s3eo.mjs +232 -0
  54. package/lib/google-gemini-cli-CWu8HvXW.mjs +211 -0
  55. package/lib/google-gemini-cli-Cb97bzQc.mjs +850 -0
  56. package/lib/google-gemini-cli-Cqds_Q5T.mjs +850 -0
  57. package/lib/google-gemini-cli-Dsztq0N5.mjs +211 -0
  58. package/lib/google-oauth-shared-CuEHaDDj.mjs +147 -0
  59. package/lib/google-oauth-shared-yqlyqPPC.mjs +147 -0
  60. package/lib/google-shared-CgKmmdO3.mjs +760 -0
  61. package/lib/google-shared-Dr-VG-ap.mjs +760 -0
  62. package/lib/google-vertex-BDN2tLaD.mjs +99 -0
  63. package/lib/google-vertex-DopVOQOG.mjs +99 -0
  64. package/lib/identity-Da1GPU9a.mjs +219 -0
  65. package/lib/identity-xRP7_eSR.mjs +219 -0
  66. package/lib/idle-iterator-Baoyn3Hp.mjs +366 -0
  67. package/lib/idle-iterator-DUjKQEGT.mjs +366 -0
  68. package/lib/index.mjs +1731 -1178
  69. package/lib/kimi--wUOWER5.mjs +236 -0
  70. package/lib/kimi-Dh0pv3WZ.mjs +236 -0
  71. package/lib/markit-BL3cH47U.mjs +1417 -0
  72. package/lib/markit-BNiNY6SE.mjs +1417 -0
  73. package/lib/minimax-code-DCbuA6Yk.mjs +53 -0
  74. package/lib/minimax-code-Uq8Qu9LW.mjs +53 -0
  75. package/lib/models-D_XnT6ay.mjs +104660 -0
  76. package/lib/models-SGASygJ3.mjs +104660 -0
  77. package/lib/ollama-DPzBmq89.mjs +589 -0
  78. package/lib/ollama-DoBz5SFm.mjs +589 -0
  79. package/lib/openai-codex-Bi-4S4PX.mjs +255 -0
  80. package/lib/openai-codex-Ch8CkT3p.mjs +255 -0
  81. package/lib/openai-codex-responses-CvxL_FMF.mjs +3144 -0
  82. package/lib/openai-codex-responses-pejZgdZo.mjs +3144 -0
  83. package/lib/openai-completions-CF8IyNtP.mjs +1360 -0
  84. package/lib/openai-completions-DIf361kF.mjs +1360 -0
  85. package/lib/openai-reasoning-fallback-Nj6yB2rY.mjs +286 -0
  86. package/lib/openai-reasoning-fallback-OdJREP1o.mjs +286 -0
  87. package/lib/openai-responses-BqXJInHX.mjs +867 -0
  88. package/lib/openai-responses-Db_a-U4-.mjs +867 -0
  89. package/lib/opencode-DhMolSoB.mjs +38 -0
  90. package/lib/opencode-Rq_Q2vAO.mjs +38 -0
  91. package/lib/perplexity-C4iLVMUj.mjs +194 -0
  92. package/lib/perplexity-Uu7Jzg5b.mjs +194 -0
  93. package/lib/proxy-DDqrmjjC.mjs +190 -0
  94. package/lib/proxy-pM_NIv-H.mjs +190 -0
  95. package/lib/request-debug-HJMoJncL.mjs +183 -0
  96. package/lib/sanitize-text-CfcXzw5X.mjs +33 -0
  97. package/lib/scrapers-BkFfcPHj.mjs +9198 -0
  98. package/lib/scrapers-CVptboMs.mjs +9198 -0
  99. package/lib/scrapers-nhQAvc8d.mjs +9198 -0
  100. package/lib/shell-snapshot-fn-env.sh +67 -43
  101. package/lib/src-BgpusnsB.mjs +5076 -0
  102. package/lib/src-lDmkSRbm.mjs +5006 -0
  103. package/lib/stream-BlldLkVq.mjs +10236 -0
  104. package/lib/stream-CRtexYLe.mjs +10236 -0
  105. package/lib/stream-markup-healing-DMsxBx1L.mjs +491 -0
  106. package/lib/stream-markup-healing-KMkiAA00.mjs +491 -0
  107. package/lib/turndown-DN7ByzEI.mjs +667 -0
  108. package/lib/types/config/settings.d.ts +9 -1
  109. package/lib/types/config/truncate.d.ts +9 -5
  110. package/lib/types/tools/bash/background.d.ts +1 -1
  111. package/lib/types/tools/bash/bash-executor.d.ts +4 -0
  112. package/lib/types/tools/bash/bash-interceptor.d.ts +10 -8
  113. package/lib/types/tools/bash/cd-workdir.d.ts +35 -0
  114. package/lib/types/tools/bash/non-interactive-env.d.ts +2 -0
  115. package/lib/types/tools/bash/render.d.ts +4 -3
  116. package/lib/types/tools/bash/sanitize-text.d.ts +5 -0
  117. package/lib/types/tools/bash/shell-snapshot.d.ts +4 -1
  118. package/lib/types/tools/bash/shell-tokenize.d.ts +60 -0
  119. package/lib/types/tools/bash/streaming-output.d.ts +12 -212
  120. package/lib/types/tools/bash/which.d.ts +20 -0
  121. package/lib/types/tools/bash/windows-shell.d.ts +31 -0
  122. package/lib/types/tools/edit/adapter/index.d.ts +25 -3
  123. package/lib/types/tools/edit/adapter/tools/auto-generated-guard.d.ts +7 -17
  124. package/lib/types/tools/glob/adapter/index.d.ts +27 -1
  125. package/lib/types/tools/grep/adapter/index.d.ts +29 -1
  126. package/lib/types/tools/omp/edit/dispatch.d.ts +43 -0
  127. package/lib/types/tools/omp/edit/hashline/noop-loop-guard.d.ts +3 -1
  128. package/lib/types/tools/omp/tools/auto-generated-guard.d.ts +20 -0
  129. package/lib/types/tools/omp/tools/write.d.ts +4 -4
  130. package/lib/types/tools/shared/auto-generated-guard.dsh.d.ts +16 -4
  131. package/lib/types/tools/shared/bun-shim.d.ts +4 -0
  132. package/lib/types/tools/shared/fs-promises-shim.d.ts +3 -1
  133. package/lib/types/tools/shared/omp-prompt.d.ts +13 -7
  134. package/lib/types/tools/shared/session-state.d.ts +9 -3
  135. package/lib/utils-Bw139LTz.mjs +8119 -0
  136. package/lib/utils-CZw4tVZQ.mjs +12315 -0
  137. package/lib/utils-CiGN7OHR.mjs +12315 -0
  138. package/lib/utils-Cp76gCyk.mjs +8119 -0
  139. package/lib/utils-D0GRDgAr.mjs +12315 -0
  140. package/lib/utils-D2YknRk4.mjs +51 -0
  141. package/lib/utils-DzXZDfYc.mjs +51 -0
  142. package/lib/vision-guard-01qSwFpf.mjs +92 -0
  143. package/lib/vision-guard-DzZGaOga.mjs +92 -0
  144. package/lib/wafer-CgtPHerf.mjs +17 -0
  145. package/lib/wafer-cBtrn6q9.mjs +17 -0
  146. package/lib/xai-oauth-Buk8XVvM.mjs +446 -0
  147. package/lib/xai-oauth-CMal8l1O.mjs +446 -0
  148. package/lib/xiaomi-CZgwvX2G.mjs +157 -0
  149. package/lib/xiaomi-D2qT5cAC.mjs +157 -0
  150. package/lib/zai-7DWMkEqM.mjs +203 -0
  151. package/lib/zai-C59YnomG.mjs +203 -0
  152. package/lib/zip-Cg9ANN_U.mjs +1316 -0
  153. package/lib/zip-D36ZKsP8.mjs +1316 -0
  154. package/package.json +1 -1
  155. package/presets/package.json +1 -1
@@ -0,0 +1,366 @@
1
+ import { installBunShim as __installBunShim } from "./bun-shim.mjs";
2
+ __installBunShim();
3
+ import { P as $env } from "./src-lDmkSRbm.mjs";
4
+ import { n as StreamTimeoutError, v as AbortError } from "./error-yCSG0mGC.mjs";
5
+ //#region node_modules/.pnpm/@oh-my-pi+pi-ai@17.3.5/node_modules/@oh-my-pi/pi-ai/src/utils/idle-iterator.ts
6
+ const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 3e5;
7
+ const DEFAULT_STREAM_FIRST_EVENT_TIMEOUT_MS = 3e5;
8
+ /** Re-mint persistent race promises every N iterations (see hoisted-racer comment). */
9
+ const RACER_REMINT_INTERVAL = 1024;
10
+ function normalizeIdleTimeoutMs(value, fallback) {
11
+ if (value === void 0) return fallback;
12
+ const parsed = Number(value);
13
+ if (!Number.isFinite(parsed)) return fallback;
14
+ if (parsed <= 0) return void 0;
15
+ return Math.trunc(parsed);
16
+ }
17
+ /**
18
+ * Returns the idle timeout used for provider streaming transports.
19
+ *
20
+ * `PI_OPENAI_STREAM_IDLE_TIMEOUT_MS` is accepted as a backward-compatible alias.
21
+ * Set `PI_STREAM_IDLE_TIMEOUT_MS=0` to disable the watchdog.
22
+ *
23
+ * Providers that legitimately stream much slower than the global default can pass
24
+ * `fallbackMs` to widen the floor used when neither env var nor caller option is set.
25
+ * Caller options still take precedence; env overrides still trump the fallback.
26
+ */
27
+ function getStreamIdleTimeoutMs(fallbackMs = DEFAULT_STREAM_IDLE_TIMEOUT_MS) {
28
+ return normalizeIdleTimeoutMs($env.PI_STREAM_IDLE_TIMEOUT_MS ?? $env.PI_OPENAI_STREAM_IDLE_TIMEOUT_MS, fallbackMs);
29
+ }
30
+ /**
31
+ * Returns the idle timeout used for OpenAI-family streaming transports.
32
+ *
33
+ * `PI_OPENAI_STREAM_IDLE_TIMEOUT_MS` takes precedence over the generic
34
+ * `PI_STREAM_IDLE_TIMEOUT_MS` because some deployments tune OpenAI-compatible
35
+ * backends separately from Anthropic/Gemini-style transports.
36
+ *
37
+ * Set `PI_OPENAI_STREAM_IDLE_TIMEOUT_MS=0` to disable the watchdog.
38
+ */
39
+ function getOpenAIStreamIdleTimeoutMs(fallbackMs = DEFAULT_STREAM_IDLE_TIMEOUT_MS) {
40
+ return normalizeIdleTimeoutMs($env.PI_OPENAI_STREAM_IDLE_TIMEOUT_MS ?? $env.PI_STREAM_IDLE_TIMEOUT_MS, fallbackMs);
41
+ }
42
+ /**
43
+ * Returns the timeout used while waiting for the first stream event.
44
+ * The first token can legitimately take longer than later inter-event gaps,
45
+ * so the default never undershoots the steady-state idle timeout.
46
+ *
47
+ * Set `PI_STREAM_FIRST_EVENT_TIMEOUT_MS=0` to disable the watchdog.
48
+ *
49
+ * Providers whose first response can legitimately take longer (heavy reasoning,
50
+ * slow cold-start proxies) can pass `fallbackMs` to widen the floor used when
51
+ * neither env var nor caller option is set. Caller options still take precedence;
52
+ * env overrides still trump the fallback.
53
+ */
54
+ function getStreamFirstEventTimeoutMs(idleTimeoutMs, fallbackMs = DEFAULT_STREAM_FIRST_EVENT_TIMEOUT_MS) {
55
+ const fallback = idleTimeoutMs === void 0 ? fallbackMs : Math.max(fallbackMs, idleTimeoutMs);
56
+ return normalizeIdleTimeoutMs($env.PI_STREAM_FIRST_EVENT_TIMEOUT_MS, fallback);
57
+ }
58
+ /**
59
+ * Returns the first-event timeout used for OpenAI-family streaming transports.
60
+ *
61
+ * Precedence: explicit `PI_OPENAI_STREAM_FIRST_EVENT_TIMEOUT_MS` (including a
62
+ * `"0"` disable) wins outright. Otherwise the resolved idle (caller-supplied
63
+ * `idleTimeoutMs` — which itself already encompasses per-call
64
+ * `streamIdleTimeoutMs` or `PI_OPENAI_STREAM_IDLE_TIMEOUT_MS` resolved
65
+ * upstream) floors the first-event budget so slow OpenAI-compatible servers
66
+ * are not undercut by a shorter `PI_STREAM_FIRST_EVENT_TIMEOUT_MS` or the
67
+ * global default during prompt processing. A zero per-provider fallback
68
+ * disables the first-event watchdog unless an environment override is set.
69
+ *
70
+ * Returns `0` when an explicit env knob or per-provider fallback disables the
71
+ * watchdog, preserving the sentinel through iterator timeout resolution.
72
+ */
73
+ function getOpenAIStreamFirstEventTimeoutMs(idleTimeoutMs, fallbackMs = DEFAULT_STREAM_FIRST_EVENT_TIMEOUT_MS) {
74
+ const openAIFirstEventRaw = $env.PI_OPENAI_STREAM_FIRST_EVENT_TIMEOUT_MS;
75
+ if (openAIFirstEventRaw !== void 0) return normalizeIdleTimeoutMs(openAIFirstEventRaw, fallbackMs) ?? 0;
76
+ const base = normalizeIdleTimeoutMs($env.PI_STREAM_FIRST_EVENT_TIMEOUT_MS, fallbackMs);
77
+ if (base === void 0 || base <= 0) return 0;
78
+ if (idleTimeoutMs === void 0 || idleTimeoutMs <= 0) return base;
79
+ return Math.max(base, idleTimeoutMs);
80
+ }
81
+ /**
82
+ * Arms a clearable pre-response (time-to-first-byte) abort guard for a streaming
83
+ * fetch, combined with the caller's signal.
84
+ *
85
+ * `AbortSignal.timeout(ms)` is an *absolute* wall-clock deadline: once handed to
86
+ * `fetch` it keeps governing the request after the response headers arrive, so
87
+ * it aborts an actively-streaming body the moment it fires — not just a stalled
88
+ * pre-response request (issue #2422 regression: large `write` tool-call streams
89
+ * died at the budget with `TimeoutError: The operation timed out.` despite
90
+ * deltas actively flowing). This arms a `clearTimeout`-able timer instead;
91
+ * callers MUST `clear()` as soon as the guarded transport attempt settles so
92
+ * the body stream is left to the iterator-level idle watchdog.
93
+ *
94
+ * Retrying callers MUST arm a fresh guard for each transport attempt and keep
95
+ * the retry loop's base signal reserved for caller cancellation. Reusing the
96
+ * guard as the loop signal makes its timeout indistinguishable from cancellation.
97
+ *
98
+ * Returns the caller signal unchanged (and a no-op `clear`) when no positive
99
+ * timeout is configured.
100
+ */
101
+ function armPreResponseTimeout(callerSignal, timeoutMs) {
102
+ if (timeoutMs === void 0 || timeoutMs <= 0) return {
103
+ signal: callerSignal,
104
+ clear: () => {}
105
+ };
106
+ const controller = new AbortController();
107
+ const timer = setTimeout(() => {
108
+ controller.abort(new DOMException("The operation timed out.", "TimeoutError"));
109
+ }, timeoutMs);
110
+ timer.unref?.();
111
+ return {
112
+ signal: callerSignal ? AbortSignal.any([callerSignal, controller.signal]) : controller.signal,
113
+ clear: () => clearTimeout(timer)
114
+ };
115
+ }
116
+ /**
117
+ * Yields items from an async iterable while enforcing a maximum idle gap between items.
118
+ *
119
+ * The first item may use a shorter timeout so stuck requests can be aborted and retried
120
+ * before any user-visible content has streamed.
121
+ */
122
+ async function* iterateWithIdleTimeout(iterable, options) {
123
+ const firstItemTimeoutMs = options.firstItemTimeoutMs ?? options.idleTimeoutMs;
124
+ let firstItemDeadlineMs = firstItemTimeoutMs !== void 0 && firstItemTimeoutMs > 0 ? Date.now() + firstItemTimeoutMs : void 0;
125
+ const abortSignal = options.abortSignal;
126
+ const iterator = iterable[Symbol.asyncIterator]();
127
+ let iteratorClosed = false;
128
+ const closeIterator = () => {
129
+ if (iteratorClosed) return;
130
+ iteratorClosed = true;
131
+ const returnPromise = iterator.return?.();
132
+ if (returnPromise) returnPromise.catch(() => {});
133
+ };
134
+ if (abortSignal?.aborted) {
135
+ closeIterator();
136
+ throw abortReason(abortSignal);
137
+ }
138
+ const withRacy = (promise) => promise.then((result) => ({
139
+ kind: "next",
140
+ result
141
+ }), (error) => ({
142
+ kind: "error",
143
+ error
144
+ }));
145
+ let awaitingFirstItem = true;
146
+ const markFirstItemReceived = () => {
147
+ awaitingFirstItem = false;
148
+ };
149
+ const isProgressItem = (item) => {
150
+ if (!options.isProgressItem) return true;
151
+ try {
152
+ return options.isProgressItem(item);
153
+ } catch {
154
+ return true;
155
+ }
156
+ };
157
+ let lastProgressAt = Date.now();
158
+ const hasPendingLocalWork = () => {
159
+ if (!options.hasPendingLocalWork) return false;
160
+ try {
161
+ return options.hasPendingLocalWork();
162
+ } catch {
163
+ return false;
164
+ }
165
+ };
166
+ const extendDeadlineForLocalWork = () => {
167
+ if (awaitingFirstItem) {
168
+ if (firstItemDeadlineMs !== void 0 && firstItemTimeoutMs !== void 0) firstItemDeadlineMs = Date.now() + firstItemTimeoutMs;
169
+ } else lastProgressAt = Date.now();
170
+ };
171
+ const noTimeoutEnforced = (firstItemTimeoutMs === void 0 || firstItemTimeoutMs <= 0) && (options.idleTimeoutMs === void 0 || options.idleTimeoutMs <= 0);
172
+ let abortPromise;
173
+ let abortListener;
174
+ let resolveAbort;
175
+ if (abortSignal) {
176
+ const { promise, resolve } = Promise.withResolvers();
177
+ resolveAbort = resolve;
178
+ abortListener = () => resolveAbort?.({ kind: "abort" });
179
+ abortSignal.addEventListener("abort", abortListener, { once: true });
180
+ abortPromise = promise;
181
+ }
182
+ let timeoutPromise;
183
+ let resolveTimeout;
184
+ let timeoutFired = false;
185
+ let timer;
186
+ let timerFireAtMs = Infinity;
187
+ const currentDeadlineMs = () => {
188
+ if (awaitingFirstItem) return firstItemDeadlineMs;
189
+ if (options.idleTimeoutMs !== void 0 && options.idleTimeoutMs > 0) return lastProgressAt + options.idleTimeoutMs;
190
+ };
191
+ const onTimerFire = () => {
192
+ timer = void 0;
193
+ timerFireAtMs = Infinity;
194
+ const deadlineMs = currentDeadlineMs();
195
+ if (deadlineMs === void 0) return;
196
+ const remainingMs = deadlineMs - Date.now();
197
+ if (remainingMs > 0) {
198
+ timerFireAtMs = deadlineMs;
199
+ timer = setTimeout(onTimerFire, remainingMs);
200
+ return;
201
+ }
202
+ timeoutFired = true;
203
+ resolveTimeout?.({ kind: "timeout" });
204
+ };
205
+ const armTimer = (deadlineMs) => {
206
+ if (timeoutPromise === void 0 || timeoutFired) {
207
+ const { promise, resolve } = Promise.withResolvers();
208
+ timeoutPromise = promise;
209
+ resolveTimeout = resolve;
210
+ timeoutFired = false;
211
+ }
212
+ if (timer !== void 0) {
213
+ if (timerFireAtMs <= deadlineMs) return;
214
+ clearTimeout(timer);
215
+ }
216
+ timerFireAtMs = deadlineMs;
217
+ timer = setTimeout(onTimerFire, Math.max(0, deadlineMs - Date.now()));
218
+ };
219
+ let pendingNext;
220
+ try {
221
+ let raceCount = 0;
222
+ while (true) {
223
+ if (++raceCount % RACER_REMINT_INTERVAL === 0) {
224
+ if (abortPromise !== void 0 && !abortSignal.aborted) {
225
+ const { promise, resolve } = Promise.withResolvers();
226
+ resolveAbort = resolve;
227
+ abortPromise = promise;
228
+ }
229
+ if (timeoutPromise !== void 0 && !timeoutFired) {
230
+ const { promise, resolve } = Promise.withResolvers();
231
+ resolveTimeout = resolve;
232
+ timeoutPromise = promise;
233
+ }
234
+ }
235
+ let activeTimeoutMs;
236
+ if (awaitingFirstItem) {
237
+ if (firstItemDeadlineMs !== void 0) {
238
+ activeTimeoutMs = firstItemDeadlineMs - Date.now();
239
+ if (activeTimeoutMs <= 0) {
240
+ if (!hasPendingLocalWork()) {
241
+ options.onFirstItemTimeout?.();
242
+ closeIterator();
243
+ throw new StreamTimeoutError(options.firstItemErrorMessage ?? options.errorMessage);
244
+ }
245
+ extendDeadlineForLocalWork();
246
+ activeTimeoutMs = firstItemDeadlineMs - Date.now();
247
+ }
248
+ }
249
+ } else if (options.idleTimeoutMs !== void 0 && options.idleTimeoutMs > 0) {
250
+ activeTimeoutMs = options.idleTimeoutMs - (Date.now() - lastProgressAt);
251
+ if (activeTimeoutMs <= 0) {
252
+ if (!hasPendingLocalWork()) {
253
+ options.onIdle?.();
254
+ closeIterator();
255
+ throw new StreamTimeoutError(options.errorMessage);
256
+ }
257
+ extendDeadlineForLocalWork();
258
+ activeTimeoutMs = options.idleTimeoutMs;
259
+ }
260
+ }
261
+ pendingNext ??= withRacy(iterator.next());
262
+ const racers = [pendingNext];
263
+ if (!noTimeoutEnforced && activeTimeoutMs !== void 0 && activeTimeoutMs > 0) {
264
+ armTimer(Date.now() + activeTimeoutMs);
265
+ racers.push(timeoutPromise);
266
+ }
267
+ if (abortPromise) racers.push(abortPromise);
268
+ let continuing = false;
269
+ try {
270
+ const outcome = await Promise.race(racers);
271
+ if (outcome.kind === "next" || outcome.kind === "error") pendingNext = void 0;
272
+ if (outcome.kind === "abort") {
273
+ closeIterator();
274
+ throw abortReason(abortSignal);
275
+ }
276
+ if (outcome.kind === "timeout") {
277
+ if (hasPendingLocalWork()) {
278
+ extendDeadlineForLocalWork();
279
+ continuing = true;
280
+ continue;
281
+ }
282
+ if (!awaitingFirstItem) options.onIdle?.();
283
+ else options.onFirstItemTimeout?.();
284
+ closeIterator();
285
+ throw new StreamTimeoutError(!awaitingFirstItem ? options.errorMessage : options.firstItemErrorMessage ?? options.errorMessage);
286
+ }
287
+ if (outcome.kind === "error") throw outcome.error;
288
+ if (outcome.result.done) {
289
+ markFirstItemReceived();
290
+ return;
291
+ }
292
+ const item = outcome.result.value;
293
+ if (isProgressItem(item)) {
294
+ markFirstItemReceived();
295
+ lastProgressAt = Date.now();
296
+ }
297
+ yield item;
298
+ continuing = true;
299
+ } finally {
300
+ if (!continuing) closeIterator();
301
+ }
302
+ }
303
+ } finally {
304
+ if (timer !== void 0) clearTimeout(timer);
305
+ resolveTimeout?.({ kind: "timeout" });
306
+ if (abortListener && abortSignal) abortSignal.removeEventListener("abort", abortListener);
307
+ resolveAbort?.({ kind: "abort" });
308
+ }
309
+ }
310
+ /**
311
+ * Yields items from an async iterable until the consumer marks the stream
312
+ * logically finished AND the source stays silent past a short grace window.
313
+ *
314
+ * Misbehaving OpenAI-compatible servers deliver the terminal chunk but never
315
+ * send `[DONE]` nor close the connection; without this guard the consumer
316
+ * hangs on `iterator.next()` until the idle watchdog converts an
317
+ * already-successful turn into a timeout error. Grace expiry is a clean end
318
+ * of iteration, never an error.
319
+ */
320
+ async function* iterateWithTerminalGrace(iterable, options) {
321
+ const iterator = iterable[Symbol.asyncIterator]();
322
+ try {
323
+ while (true) {
324
+ const finishedAtMs = options.finishedAtMs();
325
+ if (finishedAtMs === void 0) {
326
+ const result = await iterator.next();
327
+ if (result.done) return;
328
+ yield result.value;
329
+ continue;
330
+ }
331
+ const remainingMs = finishedAtMs + options.graceMs - Date.now();
332
+ if (remainingMs <= 0) {
333
+ options.onGraceEnd?.();
334
+ return;
335
+ }
336
+ const nextPromise = iterator.next();
337
+ let timer;
338
+ const timeoutPromise = new Promise((resolve) => {
339
+ timer = setTimeout(() => resolve("timeout"), remainingMs);
340
+ });
341
+ try {
342
+ const outcome = await Promise.race([nextPromise, timeoutPromise]);
343
+ if (outcome === "timeout") {
344
+ nextPromise.catch(() => {});
345
+ options.onGraceEnd?.();
346
+ return;
347
+ }
348
+ if (outcome.done) return;
349
+ yield outcome.value;
350
+ } finally {
351
+ if (timer !== void 0) clearTimeout(timer);
352
+ }
353
+ }
354
+ } finally {
355
+ const returnPromise = iterator.return?.();
356
+ if (returnPromise) Promise.resolve(returnPromise).catch(() => {});
357
+ }
358
+ }
359
+ function abortReason(signal) {
360
+ const reason = signal.reason;
361
+ if (reason instanceof Error) return reason;
362
+ if (typeof reason === "string") return new AbortError(reason);
363
+ return new AbortError();
364
+ }
365
+ //#endregion
366
+ export { getStreamIdleTimeoutMs as a, getStreamFirstEventTimeoutMs as i, getOpenAIStreamFirstEventTimeoutMs as n, iterateWithIdleTimeout as o, getOpenAIStreamIdleTimeoutMs as r, iterateWithTerminalGrace as s, armPreResponseTimeout as t };