@poe-platform/safe-bash 0.1.789 → 0.1.790

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 (207) hide show
  1. package/dist/image-ast/index.browser.js +147 -80
  2. package/dist/image-ast/index.js +147 -80
  3. package/dist/mp4-ast/mp4.d.ts +2 -0
  4. package/dist/pdf-ast/cos/parser.d.ts +1 -0
  5. package/dist/pdf-ast/cos/security.d.ts +2 -0
  6. package/dist/pdf-ast/cos/writer.d.ts +1 -0
  7. package/dist/pdf-ast/document.d.ts +3 -0
  8. package/dist/pdf-ast/edit/forms.d.ts +1 -0
  9. package/dist/pdf-ast/index.js +171 -82
  10. package/dist/safe-bash/chunks/{chunk-L5QQLNTO.js → chunk-22PI65AH.js} +2 -2
  11. package/dist/safe-bash/chunks/{chunk-KHJGUF2W.js → chunk-2TAGYMPK.js} +43 -42
  12. package/dist/safe-bash/chunks/{chunk-D4PHJK4T.js → chunk-2W4HTMEK.js} +52 -48
  13. package/dist/safe-bash/chunks/{chunk-FFZXP6ZC.js → chunk-3M7L7XU2.js} +2 -2
  14. package/dist/safe-bash/chunks/{chunk-XNODZRVD.js → chunk-3QAO6UYS.js} +2 -2
  15. package/dist/safe-bash/chunks/{chunk-YPETOVQU.js → chunk-3VKFK3NF.js} +2 -2
  16. package/dist/safe-bash/chunks/chunk-5OST7NOX.js +42 -0
  17. package/dist/safe-bash/chunks/{chunk-KEBSX2AX.js → chunk-6HLURHVU.js} +2 -2
  18. package/dist/safe-bash/chunks/chunk-DYEUZE6Z.js +19 -0
  19. package/dist/safe-bash/chunks/{chunk-T2TGCHKE.js → chunk-FM3WBSZT.js} +2 -2
  20. package/dist/safe-bash/chunks/chunk-GAYRKQM6.js +22 -0
  21. package/dist/safe-bash/chunks/{chunk-Q45QCA4J.js → chunk-I3KSESCR.js} +0 -7
  22. package/dist/safe-bash/chunks/{chunk-OSKDIBQS.js → chunk-JLIMK5TD.js} +1 -1
  23. package/dist/safe-bash/chunks/{chunk-2AYZCT5X.js → chunk-JQ2FAJJT.js} +27 -23
  24. package/dist/safe-bash/chunks/{chunk-QA3NVP43.js → chunk-JRE6Z3T7.js} +2 -2
  25. package/dist/safe-bash/chunks/{chunk-DC5EHLKS.js → chunk-NDIL6T7Y.js} +5 -5
  26. package/dist/safe-bash/chunks/{chunk-747G42FY.js → chunk-OPR4UAIT.js} +2 -2
  27. package/dist/safe-bash/chunks/chunk-OSMQCYSP.js +19 -0
  28. package/dist/safe-bash/chunks/chunk-OYB332PQ.js +17 -0
  29. package/dist/safe-bash/chunks/{chunk-X5ZCECM6.js → chunk-QTIH2AFE.js} +77 -69
  30. package/dist/safe-bash/chunks/{chunk-CTUHLNJM.js → chunk-SBESXWT2.js} +43 -44
  31. package/dist/safe-bash/chunks/{chunk-4FDQJUFW.js → chunk-SDEPGTOF.js} +1 -1
  32. package/dist/safe-bash/chunks/chunk-UZU5BIJI.js +32 -0
  33. package/dist/safe-bash/chunks/{chunk-BI6JV62X.js → chunk-VCCMROTL.js} +7 -10
  34. package/dist/safe-bash/chunks/chunk-W47GHRRF.js +13 -0
  35. package/dist/safe-bash/chunks/{chunk-NPMQWZUZ.js → chunk-WS7KZIUM.js} +2 -2
  36. package/dist/safe-bash/chunks/{chunk-3PZYHMGM.js → chunk-YYAERCWS.js} +7 -7
  37. package/dist/safe-bash/chunks/{chunk-5U7JECDB.js → chunk-ZPGVEUKF.js} +8 -7
  38. package/dist/safe-bash/chunks/{csvkit-K55OYAQC.js → csvkit-USUJG62I.js} +65 -11
  39. package/dist/safe-bash/chunks/{ffmpeg-BEFTQ6DZ.js → ffmpeg-KRGG5DLH.js} +21 -10
  40. package/dist/safe-bash/chunks/{gh-HQWOWLWE.js → gh-UCFDUZCX.js} +16 -8
  41. package/dist/safe-bash/chunks/{git-HO7WDPHZ.js → git-LPAF6KDG.js} +7 -9
  42. package/dist/safe-bash/chunks/{imagemagick-53BMHH6D.js → imagemagick-KGREKK4G.js} +38 -7
  43. package/dist/safe-bash/chunks/{implementation-QUTAAYMT.js → implementation-FXDRYS5A.js} +34 -8
  44. package/dist/safe-bash/chunks/{pdfimages-4OYI6FLG.js → pdfimages-UADCF4G4.js} +12 -8
  45. package/dist/safe-bash/chunks/{pdfinfo-I7U6TQPP.js → pdfinfo-O7UWPF4W.js} +38 -13
  46. package/dist/safe-bash/chunks/{pdftk-SUA6FMHI.js → pdftk-AERXIJTN.js} +13 -8
  47. package/dist/safe-bash/chunks/{pdftoppm-4C5DGEWX.js → pdftoppm-L466JQKI.js} +17 -10
  48. package/dist/safe-bash/chunks/{pdftotext-Y4WI225Y.js → pdftotext-SUSI4WXS.js} +19 -9
  49. package/dist/safe-bash/chunks/{qpdf-IORB4RV5.js → qpdf-YL24KVRH.js} +14 -8
  50. package/dist/safe-bash/chunks/{sips-WHAMJFEU.js → sips-QXEQZERX.js} +14 -7
  51. package/dist/safe-bash/chunks/{soffice-SYEK6WJS.js → soffice-TBITRML3.js} +16 -8
  52. package/dist/safe-bash/chunks/{wkhtmltopdf-ZIICWJLF.js → wkhtmltopdf-NJA2THRC.js} +27 -7
  53. package/dist/safe-bash/command-chunks/chunk-2C5BEBPY.js +1388 -0
  54. package/dist/safe-bash/command-chunks/{chunk-2VTMZTV3.js → chunk-2EXV2ZLV.js} +2 -2
  55. package/dist/safe-bash/command-chunks/{chunk-UJOO6DKY.js → chunk-6EASC5EC.js} +1 -1
  56. package/dist/safe-bash/command-chunks/{chunk-ZF3ZVGQC.js → chunk-7JRITHKW.js} +150 -80
  57. package/dist/safe-bash/{chunks/chunk-LD76P7AG.js → command-chunks/chunk-AKDMCNX4.js} +74 -39
  58. package/dist/safe-bash/command-chunks/{chunk-6F7QJMJ3.js → chunk-CBDVLMJB.js} +1 -1
  59. package/dist/safe-bash/command-chunks/chunk-H4LWTITX.js +169 -0
  60. package/dist/safe-bash/command-chunks/chunk-I2MQNBGR.js +145 -0
  61. package/dist/safe-bash/command-chunks/{chunk-5GRLAARV.js → chunk-IOXI5ZAJ.js} +1 -1
  62. package/dist/safe-bash/command-chunks/{chunk-XNHSCU6I.js → chunk-MDPIOQUD.js} +6 -6
  63. package/dist/safe-bash/command-chunks/chunk-QI4MGIN6.js +6 -0
  64. package/dist/safe-bash/command-chunks/chunk-QTYZAWSB.js +91 -0
  65. package/dist/safe-bash/command-chunks/chunk-SNK7K3XW.js +90 -0
  66. package/dist/safe-bash/command-chunks/chunk-T5OLGM43.js +314 -0
  67. package/dist/safe-bash/command-chunks/chunk-TB7IFMUZ.js +802 -0
  68. package/dist/safe-bash/command-chunks/{chunk-AT6ZSOE6.js → chunk-TPPBPIWL.js} +1 -1
  69. package/dist/safe-bash/command-chunks/chunk-VMK4XVKO.js +82 -0
  70. package/dist/safe-bash/command-chunks/chunk-VNSJKXDU.js +130 -0
  71. package/dist/safe-bash/command-chunks/chunk-YFNTMH6Z.js +6 -0
  72. package/dist/safe-bash/commands/csplit/index.browser.js +2 -2
  73. package/dist/safe-bash/commands/docx/index.browser.js +2 -2
  74. package/dist/safe-bash/commands/factor/index.browser.js +2 -2
  75. package/dist/safe-bash/commands/getopt/index.browser.js +2 -2
  76. package/dist/safe-bash/commands/hexdump/index.browser.js +2 -2
  77. package/dist/safe-bash/commands/iconv/index.browser.js +2 -2
  78. package/dist/safe-bash/commands/line-endings/index.browser.js +2 -2
  79. package/dist/safe-bash/commands/llm/command.d.ts +1 -4
  80. package/dist/safe-bash/commands/llm/command.js +1 -248
  81. package/dist/safe-bash/commands/llm/elevenlabs-stream.d.ts +1 -2
  82. package/dist/safe-bash/commands/llm/elevenlabs-stream.js +1 -117
  83. package/dist/safe-bash/commands/llm/elevenlabs.d.ts +1 -15
  84. package/dist/safe-bash/commands/llm/elevenlabs.js +1 -123
  85. package/dist/safe-bash/commands/llm/index.browser.js +20 -15
  86. package/dist/safe-bash/commands/llm/index.d.ts +1 -6
  87. package/dist/safe-bash/commands/llm/index.js +1 -4
  88. package/dist/safe-bash/commands/llm/mime.d.ts +1 -2
  89. package/dist/safe-bash/commands/llm/mime.js +1 -136
  90. package/dist/safe-bash/commands/llm/openai-http.d.ts +1 -8
  91. package/dist/safe-bash/commands/llm/openai-http.js +1 -143
  92. package/dist/safe-bash/commands/llm/openai-sse.d.ts +1 -3
  93. package/dist/safe-bash/commands/llm/openai-sse.js +1 -78
  94. package/dist/safe-bash/commands/llm/openai.d.ts +1 -14
  95. package/dist/safe-bash/commands/llm/openai.js +1 -288
  96. package/dist/safe-bash/commands/llm/providers/elevenlabs.d.ts +1 -1
  97. package/dist/safe-bash/commands/llm/providers/elevenlabs.js +1 -1
  98. package/dist/safe-bash/commands/llm/providers/index.browser.js +6 -6
  99. package/dist/safe-bash/commands/llm/providers/index.d.ts +1 -3
  100. package/dist/safe-bash/commands/llm/providers/index.js +1 -2
  101. package/dist/safe-bash/commands/llm/providers/openai.d.ts +1 -1
  102. package/dist/safe-bash/commands/llm/providers/openai.js +1 -1
  103. package/dist/safe-bash/commands/llm/providers/shared.d.ts +1 -23
  104. package/dist/safe-bash/commands/llm/providers/shared.js +1 -65
  105. package/dist/safe-bash/commands/llm/service.d.ts +1 -37
  106. package/dist/safe-bash/commands/llm/service.js +1 -151
  107. package/dist/safe-bash/commands/llm/types.d.ts +1 -52
  108. package/dist/safe-bash/commands/llm/types.js +1 -1
  109. package/dist/safe-bash/commands/mdq/index.browser.js +3 -3
  110. package/dist/safe-bash/commands/media/index.browser.js +1 -1
  111. package/dist/safe-bash/commands/network/index.browser.js +9 -9
  112. package/dist/safe-bash/commands/network/types.d.ts +2 -40
  113. package/dist/safe-bash/commands/node/index.browser.js +6 -8
  114. package/dist/safe-bash/commands/op/index.browser.js +3 -3
  115. package/dist/safe-bash/commands/op/index.js +12 -28
  116. package/dist/safe-bash/commands/pr/index.browser.js +2 -2
  117. package/dist/safe-bash/commands/python/index.browser.js +8 -8
  118. package/dist/safe-bash/commands/python/worker.browser.js +2 -2
  119. package/dist/safe-bash/commands/tsort/index.browser.js +2 -2
  120. package/dist/safe-bash/commands/xml/index.browser.js +2 -2
  121. package/dist/safe-bash/commands/yq/index.browser.js +3 -3
  122. package/dist/safe-bash/core.browser.js +9775 -10975
  123. package/dist/safe-bash/core.d.ts +0 -1
  124. package/dist/safe-bash/core.js +0 -1
  125. package/dist/safe-bash/jobs.browser.js +5 -4
  126. package/dist/safe-bash/optional-host.browser.js +61 -88
  127. package/dist/safe-bash/shell/runtime.js +34 -12
  128. package/dist/safe-bash/yq-browser/index.js +1 -1
  129. package/dist/safe-bash-command-ffmpeg/index.js +8130 -8011
  130. package/dist/safe-bash-command-git/git_rust.wasm +0 -0
  131. package/dist/safe-bash-command-git/wasm.generated.js +1 -1
  132. package/dist/safe-bash-command-imagemagick/index.js +2 -2
  133. package/dist/safe-bash-command-llm/LICENSE +21 -0
  134. package/dist/safe-bash-command-llm/command.d.ts +5 -0
  135. package/dist/safe-bash-command-llm/command.js +14 -0
  136. package/dist/safe-bash-command-llm/configuration.d.ts +18 -0
  137. package/dist/safe-bash-command-llm/elevenlabs-stream.d.ts +2 -0
  138. package/dist/safe-bash-command-llm/elevenlabs-stream.js +7 -0
  139. package/dist/safe-bash-command-llm/elevenlabs.d.ts +15 -0
  140. package/dist/safe-bash-command-llm/elevenlabs.js +10 -0
  141. package/dist/safe-bash-command-llm/index.d.ts +10 -0
  142. package/dist/safe-bash-command-llm/index.js +46 -0
  143. package/dist/safe-bash-command-llm/mime.d.ts +2 -0
  144. package/dist/safe-bash-command-llm/mime.js +9 -0
  145. package/dist/safe-bash-command-llm/model-options.d.ts +3 -0
  146. package/dist/safe-bash-command-llm/openai-http.d.ts +8 -0
  147. package/dist/safe-bash-command-llm/openai-http.js +17 -0
  148. package/dist/safe-bash-command-llm/openai-sse.d.ts +3 -0
  149. package/dist/safe-bash-command-llm/openai-sse.js +8 -0
  150. package/dist/safe-bash-command-llm/openai.d.ts +14 -0
  151. package/dist/safe-bash-command-llm/openai.js +12 -0
  152. package/dist/safe-bash-command-llm/providers/elevenlabs.d.ts +1 -0
  153. package/dist/safe-bash-command-llm/providers/elevenlabs.js +11 -0
  154. package/dist/safe-bash-command-llm/providers/index.d.ts +3 -0
  155. package/dist/safe-bash-command-llm/providers/index.js +24 -0
  156. package/dist/safe-bash-command-llm/providers/openai.d.ts +1 -0
  157. package/dist/safe-bash-command-llm/providers/openai.js +13 -0
  158. package/dist/safe-bash-command-llm/providers/shared.d.ts +23 -0
  159. package/dist/safe-bash-command-llm/providers/shared.js +13 -0
  160. package/dist/safe-bash-command-llm/schemas.d.ts +2 -0
  161. package/dist/safe-bash-command-llm/service.d.ts +42 -0
  162. package/dist/safe-bash-command-llm/service.js +9 -0
  163. package/dist/safe-bash-command-llm/templates.d.ts +27 -0
  164. package/dist/safe-bash-command-llm/types.d.ts +87 -0
  165. package/dist/safe-bash-command-llm/types.js +6 -0
  166. package/dist/safe-bash-command-mmdc/command.d.ts +4 -0
  167. package/dist/safe-bash-command-mmdc/index.d.ts +1 -1
  168. package/dist/safe-bash-command-mmdc/index.js +7084 -6687
  169. package/dist/safe-bash-command-mmdc/layout.d.ts +1 -0
  170. package/dist/safe-bash-command-mmdc/parser.d.ts +1 -0
  171. package/dist/safe-bash-command-mmdc/png.d.ts +3 -0
  172. package/dist/safe-bash-command-mmdc/raster.d.ts +1 -0
  173. package/dist/safe-bash-command-pandoc/command.js +3 -3
  174. package/dist/safe-bash-command-pandoc/index.js +3 -3
  175. package/dist/safe-bash-command-pdfimages/index.js +147 -80
  176. package/dist/safe-bash-command-pdfinfo/index.js +147 -80
  177. package/dist/safe-bash-command-pdftk/index.js +147 -80
  178. package/dist/safe-bash-command-pdftoppm/index.js +147 -80
  179. package/dist/safe-bash-command-pdftotext/index.js +147 -80
  180. package/dist/safe-bash-command-qpdf/index.js +174 -101
  181. package/dist/safe-bash-command-sips/index.js +2 -2
  182. package/dist/safe-bash-command-soffice/index.js +1 -1
  183. package/dist/safe-bash-command-ssconvert/index.js +147 -80
  184. package/dist/safe-bash-command-wkhtmltopdf/index.js +147 -80
  185. package/dist/safe-bash-contracts/default-executor.d.ts +5 -0
  186. package/dist/safe-bash-contracts/default-executor.js +37 -0
  187. package/dist/safe-bash-contracts/http.d.ts +41 -0
  188. package/dist/safe-bash-contracts/http.js +6 -0
  189. package/dist/safe-bash-io-engine/commands/search/requirements.js +3 -3
  190. package/dist/safe-bash-io-engine/commands/text-programs/shared.js +3 -3
  191. package/dist/safe-bash-io-engine/gnu-information.d.ts +1 -1
  192. package/dist/safe-bash-io-engine/gnu-information.js +1 -1
  193. package/dist/safe-bash-io-engine/internal.js +2 -2
  194. package/dist/safe-bash-query-engine/index.js +3 -3
  195. package/dist/safe-bash-query-engine/interpreter.js +2 -2
  196. package/dist/safe-bash-query-engine/query-core.js +3 -3
  197. package/package.json +2 -2
  198. package/dist/safe-bash/chunks/chunk-2G2T5MEM.js +0 -14
  199. package/dist/safe-bash/chunks/chunk-2MUJ7RLZ.js +0 -409
  200. package/dist/safe-bash/chunks/chunk-GJWUEOT6.js +0 -14
  201. package/dist/safe-bash/chunks/chunk-H7MMJS26.js +0 -37
  202. package/dist/safe-bash/chunks/chunk-LAPF2XE6.js +0 -14
  203. package/dist/safe-bash/chunks/chunk-S2LSZFZ6.js +0 -758
  204. package/dist/safe-bash/chunks/chunk-T3VDYWKZ.js +0 -21
  205. package/dist/safe-bash/chunks/chunk-VUVKC6HV.js +0 -81
  206. package/dist/safe-bash/chunks/chunk-VYW4Q6KF.js +0 -12
  207. package/dist/safe-bash/command-chunks/{chunk-BJ6DGYJA.js → chunk-KNI4GRXF.js} +3 -3
@@ -0,0 +1,802 @@
1
+ import {
2
+ openAiChat
3
+ } from "./chunk-SNK7K3XW.js";
4
+ import {
5
+ credential,
6
+ jsonBody,
7
+ multipart,
8
+ providerLimits
9
+ } from "./chunk-QTYZAWSB.js";
10
+ import {
11
+ parseLlmNumericOption
12
+ } from "./chunk-VMK4XVKO.js";
13
+ import {
14
+ openAiBytes,
15
+ openAiError,
16
+ openAiJson,
17
+ openAiRecord,
18
+ openAiResponse
19
+ } from "./chunk-H4LWTITX.js";
20
+ import {
21
+ acceptsMimeType
22
+ } from "./chunk-AKDMCNX4.js";
23
+ import {
24
+ init_buffer
25
+ } from "./chunk-HX3SHTCE.js";
26
+
27
+ // packages/safe-bash-command-llm/dist/openai.js
28
+ init_buffer();
29
+
30
+ // packages/safe-bash-command-llm/dist/openai-chat-options.js
31
+ init_buffer();
32
+
33
+ // packages/safe-bash-command-llm/dist/token-integer.js
34
+ init_buffer();
35
+ var decimalZeroes = [
36
+ 48,
37
+ 1632,
38
+ 1776,
39
+ 1984,
40
+ 2406,
41
+ 2534,
42
+ 2662,
43
+ 2790,
44
+ 2918,
45
+ 3046,
46
+ 3174,
47
+ 3302,
48
+ 3430,
49
+ 3558,
50
+ 3664,
51
+ 3792,
52
+ 3872,
53
+ 4160,
54
+ 4240,
55
+ 6112,
56
+ 6160,
57
+ 6470,
58
+ 6608,
59
+ 6784,
60
+ 6800,
61
+ 6992,
62
+ 7088,
63
+ 7232,
64
+ 7248,
65
+ 42528,
66
+ 43216,
67
+ 43264,
68
+ 43472,
69
+ 43504,
70
+ 43600,
71
+ 44016,
72
+ 65296,
73
+ 66720,
74
+ 68912,
75
+ 69734,
76
+ 69872,
77
+ 69942,
78
+ 70096,
79
+ 70384,
80
+ 70736,
81
+ 70864,
82
+ 71248,
83
+ 71360,
84
+ 71472,
85
+ 71904,
86
+ 72016,
87
+ 72784,
88
+ 73040,
89
+ 73120,
90
+ 92768,
91
+ 93008,
92
+ 120782,
93
+ 120792,
94
+ 120802,
95
+ 120812,
96
+ 120822,
97
+ 123200,
98
+ 123632,
99
+ 125264,
100
+ 130032
101
+ ];
102
+ function digit(code) {
103
+ if (code === void 0)
104
+ return void 0;
105
+ if (code >= 48 && code <= 57)
106
+ return code - 48;
107
+ for (const zero of decimalZeroes)
108
+ if (code >= zero && code < zero + 10)
109
+ return code - zero;
110
+ return void 0;
111
+ }
112
+ function whitespace(code) {
113
+ return code >= 9 && code <= 13 || code === 32 || code === 133 || code === 160 || code === 5760 || code >= 8192 && code <= 8202 || code === 8232 || code === 8233 || code === 8239 || code === 8287 || code === 12288;
114
+ }
115
+ function tokenInteger(input) {
116
+ let start = 0, end = input.length;
117
+ while (start < end && whitespace(input.charCodeAt(start)))
118
+ start++;
119
+ while (end > start && whitespace(input.charCodeAt(end - 1)))
120
+ end--;
121
+ let normalized = "", previousDigit = false, digits = 0;
122
+ if (input[start] === "+" || input[start] === "-")
123
+ normalized = input[start++];
124
+ for (let index = start; index < end; ) {
125
+ const code = input.codePointAt(index);
126
+ const value = digit(code);
127
+ if (value !== void 0) {
128
+ normalized += String(value);
129
+ digits++;
130
+ previousDigit = true;
131
+ } else if (code === 95 && previousDigit && digit(input.codePointAt(index + 1)) !== void 0)
132
+ previousDigit = false;
133
+ else
134
+ return void 0;
135
+ index += code > 65535 ? 2 : 1;
136
+ }
137
+ return digits ? BigInt(normalized).toString() : void 0;
138
+ }
139
+
140
+ // packages/safe-bash-command-llm/dist/openai-chat-options.js
141
+ function biasInteger(value) {
142
+ if (typeof value === "boolean")
143
+ return Number(value);
144
+ if (typeof value === "number")
145
+ return Number.isFinite(value) ? Math.trunc(value) : void 0;
146
+ if (typeof value !== "string")
147
+ return void 0;
148
+ const integer = tokenInteger(value);
149
+ return integer === void 0 ? void 0 : Number(integer);
150
+ }
151
+ function dictionaryKeys(json) {
152
+ const keys = /* @__PURE__ */ new Set();
153
+ let depth = 0;
154
+ let expectingKey = false;
155
+ for (let index = 0; index < json.length; index++) {
156
+ const char = json[index];
157
+ if (char === '"') {
158
+ const start = index;
159
+ while (++index < json.length) {
160
+ if (json[index] === "\\")
161
+ index++;
162
+ else if (json[index] === '"')
163
+ break;
164
+ }
165
+ if (depth === 1 && expectingKey) {
166
+ keys.add(JSON.parse(json.slice(start, index + 1)));
167
+ expectingKey = false;
168
+ }
169
+ } else if (char === "{" || char === "[") {
170
+ depth++;
171
+ if (depth === 1)
172
+ expectingKey = true;
173
+ } else if (char === "}" || char === "]")
174
+ depth--;
175
+ else if (char === "," && depth === 1)
176
+ expectingKey = true;
177
+ }
178
+ return [...keys];
179
+ }
180
+ function logitBias(input) {
181
+ if (typeof input !== "string")
182
+ throw new TypeError("Invalid OpenAI logit_bias: expected a JSON dictionary");
183
+ let parsed;
184
+ try {
185
+ parsed = JSON.parse(input);
186
+ } catch {
187
+ throw new TypeError("Invalid OpenAI logit_bias: Invalid JSON in logit_bias string");
188
+ }
189
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
190
+ throw new TypeError("Invalid OpenAI logit_bias: expected a JSON dictionary");
191
+ const result = {};
192
+ for (const key of dictionaryKeys(input)) {
193
+ const value = parsed[key];
194
+ const token = tokenInteger(key);
195
+ const bias = biasInteger(value);
196
+ if (token === void 0 || bias === void 0 || !Number.isSafeInteger(bias) || bias < -100 || bias > 100)
197
+ throw new TypeError("Invalid OpenAI logit_bias: Invalid key-value pair in logit_bias dictionary");
198
+ Object.defineProperty(result, token, { value: bias, enumerable: true, configurable: true, writable: true });
199
+ }
200
+ return result;
201
+ }
202
+ function openAiChatOptions(options) {
203
+ const { json_object: jsonObject, logit_bias: bias, ...values } = options;
204
+ const result = { ...values };
205
+ if (bias !== void 0 && bias !== null)
206
+ result.logit_bias = logitBias(bias);
207
+ if (jsonObject !== void 0 && jsonObject !== null) {
208
+ const text = String(jsonObject).toLowerCase();
209
+ if (!["true", "false", "1", "0", "yes", "no", "on", "off", "y", "n", "t", "f"].includes(text))
210
+ throw new TypeError("Invalid OpenAI json_object: expected boolean");
211
+ if (["true", "1", "yes", "on", "y", "t"].includes(text)) {
212
+ if (Object.hasOwn(values, "response_format"))
213
+ throw new TypeError("OpenAI json_object conflicts with response_format");
214
+ result.response_format = { type: "json_object" };
215
+ }
216
+ }
217
+ return result;
218
+ }
219
+
220
+ // packages/safe-bash-command-llm/dist/chat-json.js
221
+ init_buffer();
222
+
223
+ // packages/safe-bash-command-llm/dist/json-string.js
224
+ init_buffer();
225
+
226
+ // packages/safe-bash-command-llm/dist/request-source.js
227
+ init_buffer();
228
+ function wait(start, signal) {
229
+ signal.throwIfAborted();
230
+ return new Promise((resolve, reject) => {
231
+ const abort = () => {
232
+ signal.removeEventListener("abort", abort);
233
+ reject(signal.reason);
234
+ };
235
+ signal.addEventListener("abort", abort, { once: true });
236
+ Promise.resolve().then(() => {
237
+ signal.throwIfAborted();
238
+ return start();
239
+ }).then((value) => {
240
+ signal.removeEventListener("abort", abort);
241
+ if (signal.aborted)
242
+ reject(signal.reason);
243
+ else
244
+ resolve(value);
245
+ }, (error) => {
246
+ signal.removeEventListener("abort", abort);
247
+ reject(signal.aborted ? signal.reason : error);
248
+ });
249
+ if (signal.aborted)
250
+ abort();
251
+ });
252
+ }
253
+ async function* sourceBytes(source, signal) {
254
+ signal.throwIfAborted();
255
+ const iterator = source[Symbol.asyncIterator]();
256
+ let ended = false, failed = false;
257
+ try {
258
+ while (true) {
259
+ const next = await wait(() => iterator.next(), signal);
260
+ if (next.done) {
261
+ ended = true;
262
+ return;
263
+ }
264
+ if (!(next.value instanceof Uint8Array))
265
+ throw new TypeError("LLM input must yield byte chunks");
266
+ yield next.value;
267
+ }
268
+ } catch (error) {
269
+ failed = true;
270
+ throw signal.aborted ? signal.reason : error;
271
+ } finally {
272
+ if (!ended) {
273
+ const returned = Promise.resolve().then(() => iterator.return?.());
274
+ if (signal.aborted)
275
+ void returned.catch(() => void 0);
276
+ else
277
+ await wait(() => returned, signal).catch((error) => {
278
+ if (!failed)
279
+ throw error;
280
+ });
281
+ }
282
+ }
283
+ }
284
+
285
+ // packages/safe-bash-command-llm/dist/json-string.js
286
+ async function* jsonString(source, signal) {
287
+ const encoder = new TextEncoder();
288
+ const decoder = new TextDecoder("utf-8", { fatal: true });
289
+ signal.throwIfAborted();
290
+ yield encoder.encode('"');
291
+ for await (const input of sourceBytes(source, signal)) {
292
+ signal.throwIfAborted();
293
+ for (let position = 0; position < input.byteLength; position += 2048) {
294
+ signal.throwIfAborted();
295
+ const text = decoder.decode(input.subarray(position, position + 2048), { stream: true });
296
+ if (text)
297
+ yield encoder.encode(JSON.stringify(text).slice(1, -1));
298
+ }
299
+ }
300
+ signal.throwIfAborted();
301
+ const final = decoder.decode();
302
+ if (final)
303
+ yield encoder.encode(JSON.stringify(final).slice(1, -1));
304
+ yield encoder.encode('"');
305
+ }
306
+
307
+ // packages/safe-bash-command-llm/dist/base64-stream.js
308
+ init_buffer();
309
+ async function* base64Stream(source, signal) {
310
+ let remainder = new Uint8Array(0);
311
+ for await (const input of sourceBytes(source, signal)) {
312
+ signal.throwIfAborted();
313
+ for (let position = 0; position < input.length; position += 8190) {
314
+ signal.throwIfAborted();
315
+ const next = input.subarray(position, position + 8190);
316
+ const bytes = new Uint8Array(remainder.length + next.length);
317
+ bytes.set(remainder);
318
+ bytes.set(next, remainder.length);
319
+ const length = bytes.length - bytes.length % 3;
320
+ if (length)
321
+ yield btoa(String.fromCharCode(...bytes.subarray(0, length)));
322
+ remainder = bytes.slice(length);
323
+ }
324
+ }
325
+ signal.throwIfAborted();
326
+ if (remainder.length)
327
+ yield btoa(String.fromCharCode(...remainder));
328
+ }
329
+
330
+ // packages/safe-bash-command-llm/dist/json-value.js
331
+ init_buffer();
332
+ function jsonValue(value, signal) {
333
+ const ancestors = /* @__PURE__ */ new Set();
334
+ const normalize = (input, key) => {
335
+ if (input && (typeof input === "object" || typeof input === "function")) {
336
+ const hook = input.toJSON;
337
+ if (typeof hook === "function")
338
+ input = hook.call(input, key);
339
+ if (input instanceof Number || input instanceof String || input instanceof Boolean)
340
+ return input.valueOf();
341
+ if (input && typeof input === "object" && Object.getPrototypeOf(input) === BigInt.prototype)
342
+ return BigInt.prototype.valueOf.call(input);
343
+ }
344
+ return input;
345
+ };
346
+ function validate(input, key = "") {
347
+ input = normalize(input, key);
348
+ signal.throwIfAborted();
349
+ if (typeof input === "bigint")
350
+ throw new TypeError("Do not know how to serialize a BigInt");
351
+ if (!input || typeof input !== "object")
352
+ return;
353
+ if (ancestors.has(input))
354
+ throw new TypeError("Converting circular structure to JSON");
355
+ ancestors.add(input);
356
+ try {
357
+ if (Array.isArray(input)) {
358
+ for (let i = 0; i < input.length; i++)
359
+ validate(input[i], String(i));
360
+ } else
361
+ for (const key2 in input)
362
+ if (Object.hasOwn(input, key2))
363
+ validate(input[key2], key2);
364
+ } finally {
365
+ ancestors.delete(input);
366
+ }
367
+ }
368
+ validate(value);
369
+ const encoder = new TextEncoder();
370
+ const ignored = (input) => input === void 0 || typeof input === "function" || typeof input === "symbol";
371
+ async function* string(input) {
372
+ yield encoder.encode('"');
373
+ for (let offset = 0; offset < input.length; ) {
374
+ signal.throwIfAborted();
375
+ let end = Math.min(offset + 1024, input.length);
376
+ const last = input.charCodeAt(end - 1);
377
+ if (end < input.length && last >= 55296 && last <= 56319 && input.charCodeAt(end) >= 56320 && input.charCodeAt(end) <= 57343)
378
+ end--;
379
+ yield encoder.encode(JSON.stringify(input.slice(offset, end)).slice(1, -1));
380
+ offset = end;
381
+ }
382
+ yield encoder.encode('"');
383
+ }
384
+ async function* encode(input) {
385
+ signal.throwIfAborted();
386
+ if (typeof input === "string") {
387
+ yield* string(input);
388
+ return;
389
+ }
390
+ if (!input || typeof input !== "object") {
391
+ yield encoder.encode(JSON.stringify(input) ?? "null");
392
+ return;
393
+ }
394
+ if (Array.isArray(input)) {
395
+ yield encoder.encode("[");
396
+ for (let i = 0; i < input.length; i++) {
397
+ if (i)
398
+ yield encoder.encode(",");
399
+ yield* encode(normalize(input[i], String(i)));
400
+ }
401
+ yield encoder.encode("]");
402
+ return;
403
+ }
404
+ yield encoder.encode("{");
405
+ let first = true;
406
+ for (const key in input)
407
+ if (Object.hasOwn(input, key)) {
408
+ const item = normalize(input[key], key);
409
+ if (ignored(item))
410
+ continue;
411
+ if (!first)
412
+ yield encoder.encode(",");
413
+ first = false;
414
+ yield* string(key);
415
+ yield encoder.encode(":");
416
+ yield* encode(item);
417
+ }
418
+ yield encoder.encode("}");
419
+ }
420
+ return encode(normalize(value, ""));
421
+ }
422
+
423
+ // packages/safe-bash-command-llm/dist/chat-json.js
424
+ function chatJson(request, limit) {
425
+ request.signal.throwIfAborted();
426
+ for (const field of ["model", "messages", "stream"])
427
+ if (Object.hasOwn(request.options, field))
428
+ throw new TypeError(`${field} is controlled by the provider`);
429
+ if (request.schema && Object.hasOwn(request.options, "response_format"))
430
+ throw new TypeError("schema conflicts with response_format");
431
+ for (const attachment of request.attachments)
432
+ if (!acceptsMimeType(["image/*"], attachment.mimeType))
433
+ throw new TypeError("Only image attachments are supported");
434
+ const controls = jsonValue({ ...request.options, ...request.schema ? { response_format: { type: "json_schema", json_schema: { name: "response", schema: request.schema } } } : {}, model: request.model }, request.signal);
435
+ const encoder = new TextEncoder();
436
+ async function* body() {
437
+ const text = (value) => encoder.encode(value);
438
+ let pending;
439
+ for await (const chunk of controls) {
440
+ if (pending)
441
+ yield pending;
442
+ pending = chunk;
443
+ }
444
+ yield text(',"messages":[');
445
+ let first = true;
446
+ for (const message of [...request.system === void 0 ? [] : [{ role: "system", content: request.system }], ...request.messages ?? []]) {
447
+ request.signal.throwIfAborted();
448
+ yield text((first ? "" : ",") + '{"role":' + JSON.stringify(message.role) + ',"content":');
449
+ first = false;
450
+ yield* jsonString(message.content.bytes, request.signal);
451
+ yield text("}");
452
+ }
453
+ yield text((first ? "" : ",") + '{"role":"user","content":');
454
+ if (request.attachments.length)
455
+ yield text('[{"type":"text","text":');
456
+ yield* jsonString(request.prompt.bytes, request.signal);
457
+ if (request.attachments.length) {
458
+ yield text("}");
459
+ for (const attachment of request.attachments) {
460
+ request.signal.throwIfAborted();
461
+ yield text(',{"type":"image_url","image_url":{"url":' + JSON.stringify(`data:${attachment.mimeType};base64,`).slice(0, -1));
462
+ for await (const part of base64Stream(attachment.source.bytes, request.signal))
463
+ yield text(part);
464
+ yield text('"}}');
465
+ }
466
+ yield text("]");
467
+ }
468
+ request.signal.throwIfAborted();
469
+ yield text('}],"stream":true}');
470
+ }
471
+ async function* limited() {
472
+ let size = 0;
473
+ for await (const chunk of body()) {
474
+ request.signal.throwIfAborted();
475
+ size += chunk.byteLength;
476
+ if (size > limit)
477
+ throw new RangeError("Provider request byte limit exceeded");
478
+ yield chunk;
479
+ }
480
+ }
481
+ return limited();
482
+ }
483
+
484
+ // packages/safe-bash-command-llm/dist/openai.js
485
+ var numericOptions = {
486
+ chat: /* @__PURE__ */ new Map([
487
+ ["temperature", ["number", 0, 2]],
488
+ ["top_p", ["number", 0, 1]],
489
+ ["frequency_penalty", ["number", -2, 2]],
490
+ ["presence_penalty", ["number", -2, 2]],
491
+ ["max_tokens", ["integer", 1, Number.MAX_SAFE_INTEGER]],
492
+ ["max_completion_tokens", ["integer", 1, Number.MAX_SAFE_INTEGER]],
493
+ ["n", ["integer", 1, Number.MAX_SAFE_INTEGER]],
494
+ ["seed", ["integer", Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]],
495
+ ["top_logprobs", ["integer", 0, 20]]
496
+ ]),
497
+ images: /* @__PURE__ */ new Map([
498
+ ["n", ["integer", 1, 10]],
499
+ ["output_compression", ["integer", 0, 100]],
500
+ ["partial_images", ["integer", 0, 3]]
501
+ ])
502
+ };
503
+ function jsonOptions(options, endpoint) {
504
+ return Object.fromEntries(Object.entries(options).map(([key, value]) => {
505
+ if ((endpoint === "chat" ? ["store", "parallel_tool_calls", "logprobs"] : ["stream"]).includes(key)) {
506
+ if (value !== "true" && value !== "false" && typeof value !== "boolean")
507
+ throw new Error(`Invalid OpenAI option ${key}: expected boolean`);
508
+ return [key, value === true || value === "true"];
509
+ }
510
+ const numeric = numericOptions[endpoint].get(key);
511
+ if (!numeric)
512
+ return [key, value];
513
+ const [type, minimum, maximum] = numeric;
514
+ const number = parseLlmNumericOption(value, type);
515
+ if (number === void 0 || !Number.isFinite(number) || type === "integer" && !Number.isSafeInteger(number)) {
516
+ throw new Error(`Invalid OpenAI option ${key}: expected a finite ${type === "integer" ? "safe integer" : "number"}`);
517
+ }
518
+ if (number < minimum || number > maximum)
519
+ throw new RangeError(`Invalid OpenAI option ${key}: expected ${minimum}..${maximum}`);
520
+ return [key, number];
521
+ }));
522
+ }
523
+ function base64(bytes) {
524
+ let binary = "";
525
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
526
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
527
+ }
528
+ return btoa(binary);
529
+ }
530
+ function imageSize(value) {
531
+ if (typeof value !== "string" || value.length === 0)
532
+ throw new Error("OpenAI image response has no b64_json");
533
+ if (value.length % 4 !== 0)
534
+ throw new Error("OpenAI image response contains non-canonical base64");
535
+ return value.length / 4 * 3 - (value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0);
536
+ }
537
+ function imageSlab(value) {
538
+ let decoded;
539
+ try {
540
+ decoded = atob(value);
541
+ } catch {
542
+ throw new Error("OpenAI image response contains invalid base64");
543
+ }
544
+ if (btoa(decoded) !== value)
545
+ throw new Error("OpenAI image response contains non-canonical base64");
546
+ return decoded;
547
+ }
548
+ function* imageBytes(value, signal) {
549
+ for (let offset = 0; offset < value.length; offset += 8192) {
550
+ signal.throwIfAborted();
551
+ const decoded = imageSlab(value.slice(offset, offset + 8192));
552
+ const bytes = new Uint8Array(decoded.length);
553
+ for (let index = 0; index < decoded.length; index++)
554
+ bytes[index] = decoded.charCodeAt(index);
555
+ yield bytes;
556
+ }
557
+ }
558
+ function waitForPoll(signal, interval) {
559
+ signal.throwIfAborted();
560
+ return new Promise((resolve, reject) => {
561
+ const abort = () => {
562
+ clearTimeout(timer);
563
+ signal.removeEventListener("abort", abort);
564
+ reject(signal.reason);
565
+ };
566
+ const timer = setTimeout(() => {
567
+ signal.removeEventListener("abort", abort);
568
+ resolve();
569
+ }, interval);
570
+ signal.addEventListener("abort", abort, { once: true });
571
+ if (signal.aborted)
572
+ abort();
573
+ });
574
+ }
575
+ function job(value, expectedId) {
576
+ if (value.error != null)
577
+ throw new Error(`OpenAI video failed: ${openAiError(value.error) ?? "unknown error"}`);
578
+ if (typeof value.id !== "string" || value.id.length === 0 || value.id === "." || value.id === ".." || expectedId !== void 0 && value.id !== expectedId) {
579
+ throw new Error("OpenAI video response has an invalid job id");
580
+ }
581
+ if (value.status !== "queued" && value.status !== "in_progress" && value.status !== "completed") {
582
+ throw new Error(`OpenAI video failed: ${typeof value.status === "string" ? value.status : "invalid status"}`);
583
+ }
584
+ return { id: value.id, status: value.status };
585
+ }
586
+ function createOpenAiProvider(options) {
587
+ const { transport, apiKey } = options;
588
+ const limits = providerLimits(options.limits);
589
+ if (typeof transport !== "function")
590
+ throw new TypeError("OpenAI requires an injected HTTP transport");
591
+ if (typeof apiKey !== "string" || !apiKey.trim() || apiKey.includes("\r") || apiKey.includes("\n"))
592
+ throw new TypeError("OpenAI requires a valid API key");
593
+ credential(apiKey);
594
+ const base = new URL(options.baseUrl ?? "https://api.openai.com/v1");
595
+ if (base.protocol !== "https:" && base.protocol !== "http:" || base.username || base.password || base.search || base.hash) {
596
+ throw new TypeError("OpenAI baseUrl must be an HTTP(S) URL without credentials, query or fragment");
597
+ }
598
+ const baseUrl = base.href.endsWith("/") ? base.href.slice(0, -1) : base.href;
599
+ const configured = options.models.map((model) => Object.freeze({
600
+ ...model,
601
+ inputSources: model.endpoint === "chat",
602
+ capabilities: Object.freeze(model.capabilities ?? (model.endpoint === "chat" ? ["messages"] : model.endpoint === "embeddings" ? ["embed"] : [])),
603
+ ...model.aliases === void 0 ? {} : { aliases: Object.freeze([...model.aliases]) },
604
+ ...model.attachmentTypes === void 0 ? {} : { attachmentTypes: Object.freeze([...model.attachmentTypes]) }
605
+ }));
606
+ const byId = /* @__PURE__ */ new Map();
607
+ for (const model of configured) {
608
+ if (!model.id || byId.has(model.id))
609
+ throw new TypeError(`OpenAI duplicate or empty model id: ${model.id}`);
610
+ if (!["chat", "images", "videos", "embeddings"].includes(model.endpoint))
611
+ throw new TypeError(`OpenAI invalid endpoint for model: ${model.id}`);
612
+ if (model.endpoint === "images" && !acceptsMimeType(["image/png", "image/jpeg", "image/webp"], model.outputType ?? ""))
613
+ throw new TypeError("Image models require outputType image/png, image/jpeg or image/webp");
614
+ if (model.endpoint === "videos" && !acceptsMimeType(["video/mp4"], model.outputType ?? ""))
615
+ throw new TypeError("Video models require outputType video/mp4");
616
+ if (model.endpoint === "chat" && model.outputType !== void 0 && !acceptsMimeType(["text/*"], model.outputType))
617
+ throw new TypeError("Chat models require a text outputType");
618
+ byId.set(model.id, model);
619
+ }
620
+ return {
621
+ name: "openai",
622
+ models: Object.freeze(configured),
623
+ async embed(request) {
624
+ request.signal.throwIfAborted();
625
+ const model = byId.get(request.model);
626
+ if (!model || model.endpoint !== "embeddings")
627
+ throw new Error(`Model ${request.model} does not support embeddings`);
628
+ const values = {};
629
+ for (const [key, value] of Object.entries(request.options)) {
630
+ if (key === "dimensions") {
631
+ const number = parseLlmNumericOption(value, "integer");
632
+ if (number === void 0 || !Number.isSafeInteger(number) || number < 1)
633
+ throw new TypeError("Invalid OpenAI dimensions: expected a positive integer");
634
+ values[key] = number;
635
+ } else if (key === "user" && typeof value === "string")
636
+ values[key] = value;
637
+ else
638
+ throw new TypeError(`Unsupported OpenAI embedding option: ${key}`);
639
+ }
640
+ for await (const response of openAiResponse(transport, {
641
+ url: `${baseUrl}/embeddings`,
642
+ method: "POST",
643
+ signal: request.signal,
644
+ ...jsonBody({ ...values, model: request.model, input: request.inputs }, limits.maxRequestBytes),
645
+ headers: [["authorization", `Bearer ${apiKey}`], ["content-type", "application/json"]]
646
+ }, limits.maxResponseBytes)) {
647
+ const body = await openAiJson(response, request.signal, limits.maxResponseBytes);
648
+ if (!Array.isArray(body.data) || body.data.length !== request.inputs.length)
649
+ throw new TypeError("Invalid OpenAI embedding response");
650
+ const vectors = new Array(request.inputs.length);
651
+ for (const item of body.data) {
652
+ if (!openAiRecord(item) || !Number.isSafeInteger(item.index) || item.index < 0 || item.index >= vectors.length || vectors[item.index] !== void 0 || !Array.isArray(item.embedding) || !item.embedding.length || item.embedding.some((value) => typeof value !== "number" || !Number.isFinite(value)))
653
+ throw new TypeError("Invalid OpenAI embedding response");
654
+ vectors[item.index] = item.embedding;
655
+ }
656
+ if (vectors.some((vector) => vector.length !== vectors[0]?.length))
657
+ throw new TypeError("Invalid OpenAI embedding dimensions");
658
+ return { model: request.model, vectors, ...openAiRecord(body.usage) ? { usage: body.usage } : {} };
659
+ }
660
+ throw new Error("OpenAI returned no embedding response");
661
+ },
662
+ async *completeSources(request) {
663
+ request.signal.throwIfAborted();
664
+ const model = byId.get(request.model);
665
+ if (!model || model.endpoint !== "chat")
666
+ throw new Error(`Model ${request.model} does not support streamed inputs`);
667
+ const body = chatJson({ ...request, options: openAiChatOptions(jsonOptions(request.options, "chat")) }, limits.maxRequestBytes);
668
+ let details;
669
+ for await (const response of openAiResponse(transport, {
670
+ url: `${baseUrl}/chat/completions`,
671
+ method: "POST",
672
+ signal: request.signal,
673
+ headers: [["authorization", `Bearer ${apiKey}`], ["content-type", "application/json"]],
674
+ body
675
+ }, limits.maxResponseBytes)) {
676
+ details = yield* openAiChat(response.body, request.signal, limits.maxEventBytes, limits.maxResponseBytes);
677
+ }
678
+ return details;
679
+ },
680
+ async *complete(request) {
681
+ request.signal.throwIfAborted();
682
+ const model = byId.get(request.model);
683
+ if (!model)
684
+ throw new Error(`Unknown model: ${request.model}`);
685
+ if (model.endpoint === "embeddings")
686
+ throw new TypeError("Embedding models require embed()");
687
+ if (model.endpoint !== "chat" && (request.messages?.length || request.schema !== void 0))
688
+ throw new TypeError("Messages and schemas require a chat model");
689
+ if (request.attachments.some((attachment) => !acceptsMimeType(["image/*"], attachment.mimeType))) {
690
+ throw new Error(`OpenAI ${model.endpoint} endpoint only supports image attachments`);
691
+ }
692
+ if (model.endpoint === "videos" && request.attachments.length > 1)
693
+ throw new Error("OpenAI videos accepts only one input_reference image");
694
+ if (request.attachments.reduce((size, file) => size + file.bytes.byteLength, 0) > limits.maxRequestBytes)
695
+ throw new RangeError("Provider request byte limit exceeded");
696
+ if (model.endpoint !== "chat" && request.system !== void 0)
697
+ throw new TypeError("System prompts are supported only by chat models");
698
+ if (request.schema !== void 0 && request.options.response_format !== void 0)
699
+ throw new TypeError("OpenAI option response_format conflicts with request schema");
700
+ const reserved = model.endpoint === "chat" ? ["model", "messages", "stream"] : model.endpoint === "images" ? ["model", "prompt", "image", "image[]"] : ["model", "prompt", "input_reference"];
701
+ for (const key of Object.keys(request.options)) {
702
+ if (reserved.includes(key))
703
+ throw new Error(`OpenAI option ${key} is controlled by the provider`);
704
+ }
705
+ const send = (path, method, body) => openAiResponse(transport, {
706
+ url: `${baseUrl}${path}`,
707
+ method,
708
+ signal: request.signal,
709
+ ...body,
710
+ headers: [["authorization", `Bearer ${apiKey}`], ...body?.headers ?? []]
711
+ }, limits.maxResponseBytes);
712
+ if (model.endpoint === "chat") {
713
+ const messages = [];
714
+ if (request.system !== void 0)
715
+ messages.push({ role: "system", content: request.system });
716
+ messages.push(...request.messages ?? []);
717
+ messages.push({ role: "user", content: request.attachments.length === 0 ? request.prompt : [
718
+ { type: "text", text: request.prompt },
719
+ ...request.attachments.map((attachment) => ({ type: "image_url", image_url: { url: `data:${attachment.mimeType};base64,${base64(attachment.bytes)}` } }))
720
+ ] });
721
+ let details;
722
+ for await (const response of send("/chat/completions", "POST", jsonBody({ ...openAiChatOptions(jsonOptions(request.options, "chat")), ...request.schema === void 0 ? {} : { response_format: { type: "json_schema", json_schema: { name: "response", schema: request.schema } } }, model: request.model, messages, stream: true }, limits.maxRequestBytes))) {
723
+ details = yield* openAiChat(response.body, request.signal, limits.maxEventBytes, limits.maxResponseBytes);
724
+ }
725
+ return details;
726
+ } else if (model.endpoint === "images") {
727
+ const editing = request.attachments.length > 0;
728
+ const outputFormat = model.outputType.split(";", 1)[0].trim().toLowerCase().slice("image/".length);
729
+ if (request.options.output_format !== void 0 && request.options.output_format !== outputFormat)
730
+ throw new TypeError("output_format conflicts with model outputType");
731
+ const values = { ...jsonOptions(request.options, "images"), output_format: outputFormat, model: request.model, prompt: request.prompt };
732
+ if (values.stream === true)
733
+ throw new TypeError("Image event streaming is not supported by this reference provider");
734
+ const body = editing ? multipart({ ...values, ...request.options }, request.attachments.map((file) => ({ ...file, field: "image[]" })), limits.maxRequestBytes) : jsonBody(values, limits.maxRequestBytes);
735
+ for await (const response of send(editing ? "/images/edits" : "/images/generations", "POST", body)) {
736
+ const value = await openAiJson(response, request.signal, limits.maxResponseBytes);
737
+ if (value.error != null)
738
+ throw new Error(`OpenAI: ${openAiError(value.error) ?? "image generation failed"}`);
739
+ if (!Array.isArray(value.data) || value.data.length === 0)
740
+ throw new Error("OpenAI image response has no images");
741
+ let size = 0;
742
+ const images = [];
743
+ for (const item of value.data) {
744
+ request.signal.throwIfAborted();
745
+ if (!openAiRecord(item))
746
+ throw new Error("OpenAI image response contains a malformed image");
747
+ size += imageSize(item.b64_json);
748
+ if (size > limits.maxResponseBytes)
749
+ throw new RangeError("Provider image byte limit exceeded");
750
+ images.push(item.b64_json);
751
+ }
752
+ for (const image of images) {
753
+ for (let offset = 0; offset < image.length; offset += 8192) {
754
+ request.signal.throwIfAborted();
755
+ const slab = image.slice(offset, offset + 8192);
756
+ if (offset + 8192 < image.length && slab.includes("="))
757
+ throw new Error("OpenAI image response contains non-canonical base64");
758
+ imageSlab(slab);
759
+ }
760
+ }
761
+ for (const image of images)
762
+ yield* imageBytes(image, request.signal);
763
+ }
764
+ } else {
765
+ let current;
766
+ for await (const response of send("/videos", "POST", multipart({ ...request.options, model: request.model, prompt: request.prompt }, request.attachments.map((file) => ({ ...file, field: "input_reference" })), limits.maxRequestBytes))) {
767
+ current = job(await openAiJson(response, request.signal, limits.maxResponseBytes));
768
+ }
769
+ if (!current)
770
+ throw new Error("OpenAI video creation returned no job");
771
+ const path = `/videos/${encodeURIComponent(current.id)}`;
772
+ let polls = 0;
773
+ while (current.status !== "completed") {
774
+ if (polls++ >= limits.maxPolls)
775
+ throw new RangeError("Provider video polling limit exceeded");
776
+ await waitForPoll(request.signal, limits.pollIntervalMs);
777
+ for await (const response of send(path, "GET"))
778
+ current = job(await openAiJson(response, request.signal, limits.maxResponseBytes), current.id);
779
+ }
780
+ for await (const response of send(`${path}/content`, "GET")) {
781
+ const contentType = response.headers.find(([name]) => name.toLowerCase() === "content-type")?.[1].split(";")[0]?.trim().toLowerCase();
782
+ if (contentType && contentType !== "application/octet-stream" && !contentType.startsWith("video/")) {
783
+ throw new Error(`OpenAI video download has unexpected content type: ${contentType}`);
784
+ }
785
+ let received = false;
786
+ for await (const chunk of openAiBytes(response.body, request.signal, limits.maxResponseBytes)) {
787
+ if (chunk.byteLength === 0)
788
+ continue;
789
+ received = true;
790
+ yield chunk;
791
+ }
792
+ if (!received)
793
+ throw new Error("OpenAI video download is empty");
794
+ }
795
+ }
796
+ }
797
+ };
798
+ }
799
+
800
+ export {
801
+ createOpenAiProvider
802
+ };