llmz 0.6.0 → 0.6.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.
Files changed (110) hide show
  1. package/DOCS.md +1 -3
  2. package/dist/_baseForOwn-CFhWe_W6.js +48 -0
  3. package/dist/_baseForOwn-buOZDFbK.cjs +103 -0
  4. package/dist/_baseIteratee-CF4qP2a8.cjs +2377 -0
  5. package/dist/_baseIteratee-P_firB7b.js +2138 -0
  6. package/dist/_getPrototype-CG7Dxrrz.js +6 -0
  7. package/dist/_getPrototype-DQDlNVVM.cjs +10 -0
  8. package/dist/_overArg-C5Hy7oCi.cjs +196 -0
  9. package/dist/_overArg-CRYbj1NH.js +155 -0
  10. package/dist/citations.d.ts +11 -11
  11. package/dist/component-BwixNVH8.cjs +73 -0
  12. package/dist/component-DGG7d_Mz.js +44 -0
  13. package/dist/context.d.ts +8 -8
  14. package/dist/custom-client-BPmEoWKu.cjs +2618 -0
  15. package/dist/custom-client-NUoxrFQh.js +2547 -0
  16. package/dist/dual-modes-D_p-jedw.js +2750 -0
  17. package/dist/dual-modes-wAOAlaBS.cjs +2840 -0
  18. package/dist/errors-C962uJdS.cjs +220 -0
  19. package/dist/errors-Cg1G0Awu.js +161 -0
  20. package/dist/execute-BEaq3jkV.cjs +1003 -0
  21. package/dist/execute-DYvFRs54.js +1001 -0
  22. package/dist/exit-BGi0Kk0y.cjs +428 -0
  23. package/dist/exit-CDdxDBRT.js +417 -0
  24. package/dist/index.cjs +1786 -1489
  25. package/dist/index.d.ts +10 -9
  26. package/dist/index.js +1721 -1479
  27. package/dist/index.workerd.js +17534 -16875
  28. package/dist/isEmpty-BhJRCqIF.js +52 -0
  29. package/dist/isEmpty-LY533Wmh.cjs +57 -0
  30. package/dist/isPlainObject-CSxXVKCk.cjs +56 -0
  31. package/dist/isPlainObject-D39AzPO2.js +51 -0
  32. package/dist/jsx-BWvT6ukg.cjs +75 -0
  33. package/dist/jsx-CIgdGGVs.js +52 -0
  34. package/dist/jsx.d.ts +2 -2
  35. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  36. package/dist/prompts/chat-mode/user.md.d.ts +1 -1
  37. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  38. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  39. package/dist/quickjs-variant-BYhMBpwU.js +45 -0
  40. package/dist/quickjs-variant-CsIwTVFC.cjs +56 -0
  41. package/dist/quickjs-variant.workerd.d.ts +1 -1
  42. package/dist/result.d.ts +12 -12
  43. package/dist/rolldown-runtime-EAsCxrDo.js +14 -0
  44. package/dist/runtime/interpret-result.d.ts +1 -1
  45. package/dist/snapshots.d.ts +5 -5
  46. package/dist/stack-traces-BIE_5Xwf.js +21 -0
  47. package/dist/stack-traces-ntw_qhoy.cjs +26 -0
  48. package/dist/tool-CAo-BQHs.js +643 -0
  49. package/dist/tool-DdPZb0JW.cjs +654 -0
  50. package/dist/tool.d.ts +3 -3
  51. package/dist/truncator-B6aaJaN1.cjs +276 -0
  52. package/dist/truncator-DZqEqnpD.js +253 -0
  53. package/dist/typings-BwAz_TM9.cjs +784 -0
  54. package/dist/typings-CrBa7Tyy.js +743 -0
  55. package/dist/uniq-BYQ7GWwb.js +183 -0
  56. package/dist/uniq-G872RWmE.cjs +200 -0
  57. package/dist/utils-UBeAFeEI.js +950 -0
  58. package/dist/utils-ZpJm00ed.cjs +1075 -0
  59. package/dist/vm/errors.d.ts +2 -2
  60. package/dist/vm-BjkJqSQH.cjs +3438 -0
  61. package/dist/vm-C5vf1LH3.js +3436 -0
  62. package/package.json +7 -7
  63. package/dist/chunk-34GJUS6U.js +0 -3266
  64. package/dist/chunk-3UZKLXAD.cjs +0 -3249
  65. package/dist/chunk-4POZJQXN.js +0 -1530
  66. package/dist/chunk-5WBNTV42.cjs +0 -1530
  67. package/dist/chunk-5ZF6NTYI.cjs +0 -33
  68. package/dist/chunk-72ZWBNZV.js +0 -173
  69. package/dist/chunk-DDSJTR6Q.cjs +0 -257
  70. package/dist/chunk-GDJTKI7J.js +0 -792
  71. package/dist/chunk-GLXADNTR.js +0 -199
  72. package/dist/chunk-GOWPACSK.cjs +0 -199
  73. package/dist/chunk-HB2G32AK.js +0 -257
  74. package/dist/chunk-HC2QZTVT.cjs +0 -3266
  75. package/dist/chunk-HEAQAEFZ.cjs +0 -173
  76. package/dist/chunk-HMMM32RG.cjs +0 -792
  77. package/dist/chunk-I56MPOVG.cjs +0 -62
  78. package/dist/chunk-KIN7Y247.cjs +0 -32
  79. package/dist/chunk-KTDBAJBB.cjs +0 -1685
  80. package/dist/chunk-KWQTYXAT.js +0 -62
  81. package/dist/chunk-LOX7GOR6.js +0 -1685
  82. package/dist/chunk-PK72FAKD.cjs +0 -175
  83. package/dist/chunk-PZE6PIPG.cjs +0 -621
  84. package/dist/chunk-RGUG3UMF.cjs +0 -26
  85. package/dist/chunk-TDALRNGL.js +0 -621
  86. package/dist/chunk-UGHFNCPD.js +0 -26
  87. package/dist/chunk-WSVDMGMR.js +0 -175
  88. package/dist/chunk-XTEHT2TK.js +0 -33
  89. package/dist/chunk-YEAWWJSJ.js +0 -32
  90. package/dist/chunk-YRS7KRKP.js +0 -3249
  91. package/dist/component-2NYFY6CW.cjs +0 -14
  92. package/dist/component-ASNZHQUR.js +0 -14
  93. package/dist/dual-modes-S5TJ5JVJ.js +0 -10
  94. package/dist/dual-modes-TCMWBZIH.cjs +0 -10
  95. package/dist/execute-FF7D46TY.js +0 -1109
  96. package/dist/execute-IK6O4SU2.cjs +0 -1109
  97. package/dist/exit-MX56VN2C.cjs +0 -8
  98. package/dist/exit-UQ3EUX5D.js +0 -8
  99. package/dist/jsx-DDZ63UUF.js +0 -13
  100. package/dist/jsx-ULPWX5TW.cjs +0 -13
  101. package/dist/tool-KD7FL45V.js +0 -11
  102. package/dist/tool-VE2YHIY2.cjs +0 -11
  103. package/dist/truncator-73RCL52Y.js +0 -12
  104. package/dist/truncator-FZNLYSDL.cjs +0 -12
  105. package/dist/typings-E2RROCLT.js +0 -10
  106. package/dist/typings-LQOBZXSO.cjs +0 -10
  107. package/dist/utils-IATCUNKF.js +0 -43
  108. package/dist/utils-ITB4NEL7.cjs +0 -43
  109. package/dist/vm-6D3IIIU7.cjs +0 -12
  110. package/dist/vm-QO5FSGPN.js +0 -12
@@ -0,0 +1,276 @@
1
+ const require__baseForOwn = require("./_baseForOwn-buOZDFbK.cjs");
2
+ const require_utils = require("./utils-ZpJm00ed.cjs");
3
+ //#region src/truncator.ts
4
+ var truncator_exports = /* @__PURE__ */ require__baseForOwn.__exportAll({
5
+ stripTruncationTags: () => stripTruncationTags,
6
+ truncateWrappedContent: () => truncateWrappedContent,
7
+ wrapContent: () => wrapContent
8
+ });
9
+ const DEFAULT_REMOVE_CHUNK = 250;
10
+ const WRAP_OPEN_TAG_1 = "【TRUNCATE";
11
+ const WRAP_OPEN_TAG_2 = "】";
12
+ const WRAP_CLOSE_TAG = "【/TRUNCATE】";
13
+ const REGEXP = `(${WRAP_OPEN_TAG_1}(?:\\s+[\\w:]+)*\\s*${WRAP_OPEN_TAG_2})([\\s\\S]*?)(${WRAP_CLOSE_TAG})`;
14
+ const DEFAULT_TRUNCATE_OPTIONS = {
15
+ preserve: "top",
16
+ flex: 1,
17
+ minTokens: 0
18
+ };
19
+ /**
20
+ * Wraps content with truncation tags to mark it as truncatable when using `truncateWrappedContent`.
21
+ *
22
+ * This function encases the provided content within special truncation tags that contain metadata
23
+ * about how the content should be truncated. The wrapped content becomes eligible for intelligent
24
+ * truncation while preserving non-wrapped content intact.
25
+ *
26
+ * @param content - The string content to wrap with truncation tags
27
+ * @param options - Optional truncation configuration
28
+ * @param options.preserve - Which part of the content to preserve when truncating:
29
+ * - 'top': Keep the beginning, remove from the end (default)
30
+ * - 'bottom': Keep the end, remove from the beginning
31
+ * - 'both': Keep both ends, remove from the middle
32
+ * @param options.flex - Priority factor for truncation (default: 1). Higher values make this
33
+ * content more likely to be truncated. A flex of 2 means this content can shrink twice as
34
+ * much as content with flex of 1.
35
+ * @param options.minTokens - Minimum number of tokens to preserve (default: 0). Content will
36
+ * never be truncated below this threshold.
37
+ *
38
+ * @returns The content wrapped with truncation tags and embedded metadata
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // Basic usage - content will be truncated from the end if needed
43
+ * const wrapped = wrapContent("This is some long content that might need truncation")
44
+ *
45
+ * // Preserve the end of the content
46
+ * const bottomPreserved = wrapContent("Error log: ... important error details", {
47
+ * preserve: 'bottom'
48
+ * })
49
+ *
50
+ * // High priority for truncation with minimum preservation
51
+ * const flexible = wrapContent("Optional context information", {
52
+ * flex: 3,
53
+ * minTokens: 50
54
+ * })
55
+ * ```
56
+ */
57
+ function wrapContent(content, options) {
58
+ const preserve = (options === null || options === void 0 ? void 0 : options.preserve) ?? DEFAULT_TRUNCATE_OPTIONS.preserve;
59
+ const flex = (options === null || options === void 0 ? void 0 : options.flex) ?? DEFAULT_TRUNCATE_OPTIONS.flex;
60
+ const minTokens = (options === null || options === void 0 ? void 0 : options.minTokens) ?? DEFAULT_TRUNCATE_OPTIONS.minTokens;
61
+ return `${WRAP_OPEN_TAG_1} preserve:${preserve} flex:${flex} min:${minTokens} ${WRAP_OPEN_TAG_2}${content}${WRAP_CLOSE_TAG}`;
62
+ }
63
+ /**
64
+ * Intelligently truncates message content to fit within a token limit while preserving important parts.
65
+ *
66
+ * This function processes an array of messages and reduces their total token count to fit within the
67
+ * specified limit. It only truncates content that has been wrapped with `wrapContent()`, leaving
68
+ * unwrapped content completely intact. The truncation algorithm prioritizes content based on flex
69
+ * values and respects preservation preferences and minimum token requirements.
70
+ *
71
+ * ## How it works:
72
+ * 1. **Parsing**: Scans each message for wrapped content sections and unwrapped sections
73
+ * 2. **Token counting**: Calculates tokens for each section using the configured tokenizer
74
+ * 3. **Prioritization**: Identifies the largest truncatable sections based on flex values
75
+ * 4. **Intelligent truncation**: Removes content according to preservation preferences
76
+ * 5. **Reconstruction**: Rebuilds messages with truncated content and removes wrapper tags
77
+ *
78
+ * ## Truncation strategy:
79
+ * - **Priority**: Higher flex values = higher truncation priority
80
+ * - **Minimum tokens**: Content is never truncated below its `minTokens` threshold
81
+ * - **Preservation modes**:
82
+ * - `'top'`: Removes from the end, keeps the beginning
83
+ * - `'bottom'`: Removes from the beginning, keeps the end
84
+ * - `'both'`: Removes from the middle, keeps both ends
85
+ *
86
+ * @template T - Type extending MessageLike (must have a content property)
87
+ * @param options - Configuration object
88
+ * @param options.messages - Array of messages to truncate
89
+ * @param options.tokenLimit - Maximum total tokens allowed across all messages
90
+ * @param options.throwOnFailure - Whether to throw an error if truncation fails (default: true).
91
+ * If false, returns the best effort result even if over the token limit.
92
+ *
93
+ * @returns Array of messages with content truncated to fit the token limit
94
+ *
95
+ * @throws Error if unable to truncate enough content to meet the token limit (when throwOnFailure is true)
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const messages = [
100
+ * {
101
+ * role: 'system',
102
+ * content: 'You are a helpful assistant. ' + wrapContent('Here is some background info...', { flex: 2 })
103
+ * },
104
+ * {
105
+ * role: 'user',
106
+ * content: 'Please help me with: ' + wrapContent('detailed context and examples', { preserve: 'both' })
107
+ * }
108
+ * ]
109
+ *
110
+ * // Truncate to fit within 1000 tokens
111
+ * const truncated = truncateWrappedContent({
112
+ * messages,
113
+ * tokenLimit: 1000,
114
+ * throwOnFailure: false
115
+ * })
116
+ *
117
+ * // The system message background info will be truncated first (higher flex),
118
+ * // and user context will be truncated from the middle if needed (preserve: 'both')
119
+ * ```
120
+ */
121
+ function truncateWrappedContent({ messages, tokenLimit, throwOnFailure = true }) {
122
+ const tokenizer = require_utils.getTokenizer();
123
+ /**
124
+ * Before { content: 'content', tokens: 10, truncatable: false }
125
+ * <WRAPPER>content</WRAPPER> { content: 'content', tokens: 10, truncatable: true }
126
+ * After { content: 'content', tokens: 10, truncatable: false }
127
+ */
128
+ const parts = [];
129
+ for (const msg of messages) {
130
+ const current = [];
131
+ const content = typeof msg.content === "string" ? msg.content : "";
132
+ let match;
133
+ const parser = new _MessageContentParser();
134
+ while ((match = parser.parse(content)) !== null) {
135
+ const { attributes, nonTruncatableContent, wrappedContent } = match;
136
+ if (nonTruncatableContent) current.push({
137
+ content: nonTruncatableContent,
138
+ tokens: tokenizer.count(nonTruncatableContent),
139
+ truncatable: false
140
+ });
141
+ current.push({
142
+ content: wrappedContent,
143
+ tokens: tokenizer.count(wrappedContent),
144
+ truncatable: true,
145
+ attributes: {
146
+ preserve: attributes.preserve,
147
+ flex: Number(attributes.flex) || DEFAULT_TRUNCATE_OPTIONS.flex,
148
+ minTokens: Number(attributes.min) || DEFAULT_TRUNCATE_OPTIONS.minTokens
149
+ }
150
+ });
151
+ }
152
+ const remainingContent = parser.getRemainingContent(content);
153
+ if (remainingContent) current.push({
154
+ content: remainingContent,
155
+ tokens: tokenizer.count(remainingContent),
156
+ truncatable: false
157
+ });
158
+ parts.push(current);
159
+ }
160
+ let currentCount = _countTotalTokens(parts);
161
+ while (currentCount > tokenLimit) {
162
+ var _biggest$attributes, _biggest$attributes3;
163
+ const { biggest, secondBiggest } = _getTwoBiggestTruncables(parts);
164
+ if (!biggest || !biggest.truncatable || biggest.tokens <= 0) {
165
+ if (throwOnFailure) throw new Error(`Cannot truncate further, current count: ${currentCount}`);
166
+ else break;
167
+ }
168
+ const delta = Math.max(biggest.tokens - ((secondBiggest === null || secondBiggest === void 0 ? void 0 : secondBiggest.tokens) ?? 0), DEFAULT_REMOVE_CHUNK);
169
+ const room = Math.min(delta, biggest.tokens);
170
+ let toRemove = Math.min(room, currentCount - tokenLimit);
171
+ if (toRemove <= 0) {
172
+ if (throwOnFailure) throw new Error(`Cannot truncate further, current count: ${currentCount}`);
173
+ else break;
174
+ }
175
+ if (biggest.tokens - toRemove < (((_biggest$attributes = biggest.attributes) === null || _biggest$attributes === void 0 ? void 0 : _biggest$attributes.minTokens) ?? 0)) {
176
+ var _biggest$attributes2;
177
+ toRemove = biggest.tokens - (((_biggest$attributes2 = biggest.attributes) === null || _biggest$attributes2 === void 0 ? void 0 : _biggest$attributes2.minTokens) ?? 0);
178
+ }
179
+ const preserve = ((_biggest$attributes3 = biggest.attributes) === null || _biggest$attributes3 === void 0 ? void 0 : _biggest$attributes3.preserve) ?? DEFAULT_TRUNCATE_OPTIONS.preserve;
180
+ const split = tokenizer.splitAndSlice(biggest.content);
181
+ if (preserve === "bottom") biggest.content = split.slice(toRemove).join("");
182
+ else if (preserve === "top") biggest.content = split.slice(0, -toRemove).join("");
183
+ else {
184
+ const anchor = Math.ceil(split.length / 2);
185
+ const radius = Math.ceil(toRemove / 2);
186
+ const left = anchor - radius;
187
+ const right = anchor + radius;
188
+ biggest.content = split.slice(0, left).join("") + split.slice(right).join("");
189
+ }
190
+ biggest.tokens -= toRemove;
191
+ currentCount -= toRemove;
192
+ }
193
+ return messages.map((msg, i) => {
194
+ const p = parts[i];
195
+ return {
196
+ ...msg,
197
+ content: typeof msg.content === "string" ? _renderRemainingWrappers(p.map((part) => part.content).join("")) : msg.content
198
+ };
199
+ });
200
+ }
201
+ var _MessageContentParser = class {
202
+ _regex;
203
+ _lastIndex = 0;
204
+ constructor() {
205
+ this._regex = _createRegex();
206
+ }
207
+ parse(content) {
208
+ const match = this._regex.exec(content);
209
+ if (!match) return null;
210
+ const attributes = match[1].split(/\s+/).slice(1).filter((x) => x !== WRAP_OPEN_TAG_2).map((x) => x.split(":")).reduce((acc, [key, value]) => ({
211
+ ...acc,
212
+ [key]: value
213
+ }), {});
214
+ let nonTruncatableContent = void 0;
215
+ if (match.index > this._lastIndex) nonTruncatableContent = content.slice(this._lastIndex, match.index);
216
+ const wrappedContent = match[2];
217
+ this._lastIndex = this._regex.lastIndex;
218
+ return {
219
+ attributes,
220
+ nonTruncatableContent,
221
+ wrappedContent
222
+ };
223
+ }
224
+ getRemainingContent(content) {
225
+ if (this._lastIndex < content.length) return content.slice(this._lastIndex);
226
+ return null;
227
+ }
228
+ };
229
+ const _createRegex = () => new RegExp(REGEXP, "g");
230
+ const _renderRemainingWrappers = (content) => content.replace(_createRegex(), "$2");
231
+ /** Removes truncation wrapper tags from content, leaving the wrapped content intact. */
232
+ const stripTruncationTags = (content) => _renderRemainingWrappers(content);
233
+ const _countTotalTokens = (parts) => parts.reduce((acc, x) => acc + x.reduce((acc, y) => acc + y.tokens, 0), 0);
234
+ const _getTwoBiggestTruncables = (parts) => {
235
+ let biggest = null;
236
+ let secondBiggest = null;
237
+ for (const part of parts.flat()) if (part.truncatable) {
238
+ var _part$attributes, _part$attributes2;
239
+ if (part.tokens <= (((_part$attributes = part.attributes) === null || _part$attributes === void 0 ? void 0 : _part$attributes.minTokens) ?? 0)) continue;
240
+ const flex = ((_part$attributes2 = part.attributes) === null || _part$attributes2 === void 0 ? void 0 : _part$attributes2.flex) ?? DEFAULT_TRUNCATE_OPTIONS.flex;
241
+ const tokens = part.tokens * flex;
242
+ if (!biggest || tokens > biggest.tokens) {
243
+ secondBiggest = biggest;
244
+ biggest = part;
245
+ } else if (!secondBiggest || tokens > secondBiggest.tokens) secondBiggest = part;
246
+ }
247
+ return {
248
+ biggest,
249
+ secondBiggest
250
+ };
251
+ };
252
+ //#endregion
253
+ Object.defineProperty(exports, "stripTruncationTags", {
254
+ enumerable: true,
255
+ get: function() {
256
+ return stripTruncationTags;
257
+ }
258
+ });
259
+ Object.defineProperty(exports, "truncateWrappedContent", {
260
+ enumerable: true,
261
+ get: function() {
262
+ return truncateWrappedContent;
263
+ }
264
+ });
265
+ Object.defineProperty(exports, "truncator_exports", {
266
+ enumerable: true,
267
+ get: function() {
268
+ return truncator_exports;
269
+ }
270
+ });
271
+ Object.defineProperty(exports, "wrapContent", {
272
+ enumerable: true,
273
+ get: function() {
274
+ return wrapContent;
275
+ }
276
+ });
@@ -0,0 +1,253 @@
1
+ import { n as __exportAll } from "./rolldown-runtime-EAsCxrDo.js";
2
+ import { o as getTokenizer } from "./utils-UBeAFeEI.js";
3
+ //#region src/truncator.ts
4
+ var truncator_exports = /* @__PURE__ */ __exportAll({
5
+ stripTruncationTags: () => stripTruncationTags,
6
+ truncateWrappedContent: () => truncateWrappedContent,
7
+ wrapContent: () => wrapContent
8
+ });
9
+ const DEFAULT_REMOVE_CHUNK = 250;
10
+ const WRAP_OPEN_TAG_1 = "【TRUNCATE";
11
+ const WRAP_OPEN_TAG_2 = "】";
12
+ const WRAP_CLOSE_TAG = "【/TRUNCATE】";
13
+ const REGEXP = `(${WRAP_OPEN_TAG_1}(?:\\s+[\\w:]+)*\\s*${WRAP_OPEN_TAG_2})([\\s\\S]*?)(${WRAP_CLOSE_TAG})`;
14
+ const DEFAULT_TRUNCATE_OPTIONS = {
15
+ preserve: "top",
16
+ flex: 1,
17
+ minTokens: 0
18
+ };
19
+ /**
20
+ * Wraps content with truncation tags to mark it as truncatable when using `truncateWrappedContent`.
21
+ *
22
+ * This function encases the provided content within special truncation tags that contain metadata
23
+ * about how the content should be truncated. The wrapped content becomes eligible for intelligent
24
+ * truncation while preserving non-wrapped content intact.
25
+ *
26
+ * @param content - The string content to wrap with truncation tags
27
+ * @param options - Optional truncation configuration
28
+ * @param options.preserve - Which part of the content to preserve when truncating:
29
+ * - 'top': Keep the beginning, remove from the end (default)
30
+ * - 'bottom': Keep the end, remove from the beginning
31
+ * - 'both': Keep both ends, remove from the middle
32
+ * @param options.flex - Priority factor for truncation (default: 1). Higher values make this
33
+ * content more likely to be truncated. A flex of 2 means this content can shrink twice as
34
+ * much as content with flex of 1.
35
+ * @param options.minTokens - Minimum number of tokens to preserve (default: 0). Content will
36
+ * never be truncated below this threshold.
37
+ *
38
+ * @returns The content wrapped with truncation tags and embedded metadata
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // Basic usage - content will be truncated from the end if needed
43
+ * const wrapped = wrapContent("This is some long content that might need truncation")
44
+ *
45
+ * // Preserve the end of the content
46
+ * const bottomPreserved = wrapContent("Error log: ... important error details", {
47
+ * preserve: 'bottom'
48
+ * })
49
+ *
50
+ * // High priority for truncation with minimum preservation
51
+ * const flexible = wrapContent("Optional context information", {
52
+ * flex: 3,
53
+ * minTokens: 50
54
+ * })
55
+ * ```
56
+ */
57
+ function wrapContent(content, options) {
58
+ const preserve = (options === null || options === void 0 ? void 0 : options.preserve) ?? DEFAULT_TRUNCATE_OPTIONS.preserve;
59
+ const flex = (options === null || options === void 0 ? void 0 : options.flex) ?? DEFAULT_TRUNCATE_OPTIONS.flex;
60
+ const minTokens = (options === null || options === void 0 ? void 0 : options.minTokens) ?? DEFAULT_TRUNCATE_OPTIONS.minTokens;
61
+ return `${WRAP_OPEN_TAG_1} preserve:${preserve} flex:${flex} min:${minTokens} ${WRAP_OPEN_TAG_2}${content}${WRAP_CLOSE_TAG}`;
62
+ }
63
+ /**
64
+ * Intelligently truncates message content to fit within a token limit while preserving important parts.
65
+ *
66
+ * This function processes an array of messages and reduces their total token count to fit within the
67
+ * specified limit. It only truncates content that has been wrapped with `wrapContent()`, leaving
68
+ * unwrapped content completely intact. The truncation algorithm prioritizes content based on flex
69
+ * values and respects preservation preferences and minimum token requirements.
70
+ *
71
+ * ## How it works:
72
+ * 1. **Parsing**: Scans each message for wrapped content sections and unwrapped sections
73
+ * 2. **Token counting**: Calculates tokens for each section using the configured tokenizer
74
+ * 3. **Prioritization**: Identifies the largest truncatable sections based on flex values
75
+ * 4. **Intelligent truncation**: Removes content according to preservation preferences
76
+ * 5. **Reconstruction**: Rebuilds messages with truncated content and removes wrapper tags
77
+ *
78
+ * ## Truncation strategy:
79
+ * - **Priority**: Higher flex values = higher truncation priority
80
+ * - **Minimum tokens**: Content is never truncated below its `minTokens` threshold
81
+ * - **Preservation modes**:
82
+ * - `'top'`: Removes from the end, keeps the beginning
83
+ * - `'bottom'`: Removes from the beginning, keeps the end
84
+ * - `'both'`: Removes from the middle, keeps both ends
85
+ *
86
+ * @template T - Type extending MessageLike (must have a content property)
87
+ * @param options - Configuration object
88
+ * @param options.messages - Array of messages to truncate
89
+ * @param options.tokenLimit - Maximum total tokens allowed across all messages
90
+ * @param options.throwOnFailure - Whether to throw an error if truncation fails (default: true).
91
+ * If false, returns the best effort result even if over the token limit.
92
+ *
93
+ * @returns Array of messages with content truncated to fit the token limit
94
+ *
95
+ * @throws Error if unable to truncate enough content to meet the token limit (when throwOnFailure is true)
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const messages = [
100
+ * {
101
+ * role: 'system',
102
+ * content: 'You are a helpful assistant. ' + wrapContent('Here is some background info...', { flex: 2 })
103
+ * },
104
+ * {
105
+ * role: 'user',
106
+ * content: 'Please help me with: ' + wrapContent('detailed context and examples', { preserve: 'both' })
107
+ * }
108
+ * ]
109
+ *
110
+ * // Truncate to fit within 1000 tokens
111
+ * const truncated = truncateWrappedContent({
112
+ * messages,
113
+ * tokenLimit: 1000,
114
+ * throwOnFailure: false
115
+ * })
116
+ *
117
+ * // The system message background info will be truncated first (higher flex),
118
+ * // and user context will be truncated from the middle if needed (preserve: 'both')
119
+ * ```
120
+ */
121
+ function truncateWrappedContent({ messages, tokenLimit, throwOnFailure = true }) {
122
+ const tokenizer = getTokenizer();
123
+ /**
124
+ * Before { content: 'content', tokens: 10, truncatable: false }
125
+ * <WRAPPER>content</WRAPPER> { content: 'content', tokens: 10, truncatable: true }
126
+ * After { content: 'content', tokens: 10, truncatable: false }
127
+ */
128
+ const parts = [];
129
+ for (const msg of messages) {
130
+ const current = [];
131
+ const content = typeof msg.content === "string" ? msg.content : "";
132
+ let match;
133
+ const parser = new _MessageContentParser();
134
+ while ((match = parser.parse(content)) !== null) {
135
+ const { attributes, nonTruncatableContent, wrappedContent } = match;
136
+ if (nonTruncatableContent) current.push({
137
+ content: nonTruncatableContent,
138
+ tokens: tokenizer.count(nonTruncatableContent),
139
+ truncatable: false
140
+ });
141
+ current.push({
142
+ content: wrappedContent,
143
+ tokens: tokenizer.count(wrappedContent),
144
+ truncatable: true,
145
+ attributes: {
146
+ preserve: attributes.preserve,
147
+ flex: Number(attributes.flex) || DEFAULT_TRUNCATE_OPTIONS.flex,
148
+ minTokens: Number(attributes.min) || DEFAULT_TRUNCATE_OPTIONS.minTokens
149
+ }
150
+ });
151
+ }
152
+ const remainingContent = parser.getRemainingContent(content);
153
+ if (remainingContent) current.push({
154
+ content: remainingContent,
155
+ tokens: tokenizer.count(remainingContent),
156
+ truncatable: false
157
+ });
158
+ parts.push(current);
159
+ }
160
+ let currentCount = _countTotalTokens(parts);
161
+ while (currentCount > tokenLimit) {
162
+ var _biggest$attributes, _biggest$attributes3;
163
+ const { biggest, secondBiggest } = _getTwoBiggestTruncables(parts);
164
+ if (!biggest || !biggest.truncatable || biggest.tokens <= 0) {
165
+ if (throwOnFailure) throw new Error(`Cannot truncate further, current count: ${currentCount}`);
166
+ else break;
167
+ }
168
+ const delta = Math.max(biggest.tokens - ((secondBiggest === null || secondBiggest === void 0 ? void 0 : secondBiggest.tokens) ?? 0), DEFAULT_REMOVE_CHUNK);
169
+ const room = Math.min(delta, biggest.tokens);
170
+ let toRemove = Math.min(room, currentCount - tokenLimit);
171
+ if (toRemove <= 0) {
172
+ if (throwOnFailure) throw new Error(`Cannot truncate further, current count: ${currentCount}`);
173
+ else break;
174
+ }
175
+ if (biggest.tokens - toRemove < (((_biggest$attributes = biggest.attributes) === null || _biggest$attributes === void 0 ? void 0 : _biggest$attributes.minTokens) ?? 0)) {
176
+ var _biggest$attributes2;
177
+ toRemove = biggest.tokens - (((_biggest$attributes2 = biggest.attributes) === null || _biggest$attributes2 === void 0 ? void 0 : _biggest$attributes2.minTokens) ?? 0);
178
+ }
179
+ const preserve = ((_biggest$attributes3 = biggest.attributes) === null || _biggest$attributes3 === void 0 ? void 0 : _biggest$attributes3.preserve) ?? DEFAULT_TRUNCATE_OPTIONS.preserve;
180
+ const split = tokenizer.splitAndSlice(biggest.content);
181
+ if (preserve === "bottom") biggest.content = split.slice(toRemove).join("");
182
+ else if (preserve === "top") biggest.content = split.slice(0, -toRemove).join("");
183
+ else {
184
+ const anchor = Math.ceil(split.length / 2);
185
+ const radius = Math.ceil(toRemove / 2);
186
+ const left = anchor - radius;
187
+ const right = anchor + radius;
188
+ biggest.content = split.slice(0, left).join("") + split.slice(right).join("");
189
+ }
190
+ biggest.tokens -= toRemove;
191
+ currentCount -= toRemove;
192
+ }
193
+ return messages.map((msg, i) => {
194
+ const p = parts[i];
195
+ return {
196
+ ...msg,
197
+ content: typeof msg.content === "string" ? _renderRemainingWrappers(p.map((part) => part.content).join("")) : msg.content
198
+ };
199
+ });
200
+ }
201
+ var _MessageContentParser = class {
202
+ _regex;
203
+ _lastIndex = 0;
204
+ constructor() {
205
+ this._regex = _createRegex();
206
+ }
207
+ parse(content) {
208
+ const match = this._regex.exec(content);
209
+ if (!match) return null;
210
+ const attributes = match[1].split(/\s+/).slice(1).filter((x) => x !== WRAP_OPEN_TAG_2).map((x) => x.split(":")).reduce((acc, [key, value]) => ({
211
+ ...acc,
212
+ [key]: value
213
+ }), {});
214
+ let nonTruncatableContent = void 0;
215
+ if (match.index > this._lastIndex) nonTruncatableContent = content.slice(this._lastIndex, match.index);
216
+ const wrappedContent = match[2];
217
+ this._lastIndex = this._regex.lastIndex;
218
+ return {
219
+ attributes,
220
+ nonTruncatableContent,
221
+ wrappedContent
222
+ };
223
+ }
224
+ getRemainingContent(content) {
225
+ if (this._lastIndex < content.length) return content.slice(this._lastIndex);
226
+ return null;
227
+ }
228
+ };
229
+ const _createRegex = () => new RegExp(REGEXP, "g");
230
+ const _renderRemainingWrappers = (content) => content.replace(_createRegex(), "$2");
231
+ /** Removes truncation wrapper tags from content, leaving the wrapped content intact. */
232
+ const stripTruncationTags = (content) => _renderRemainingWrappers(content);
233
+ const _countTotalTokens = (parts) => parts.reduce((acc, x) => acc + x.reduce((acc, y) => acc + y.tokens, 0), 0);
234
+ const _getTwoBiggestTruncables = (parts) => {
235
+ let biggest = null;
236
+ let secondBiggest = null;
237
+ for (const part of parts.flat()) if (part.truncatable) {
238
+ var _part$attributes, _part$attributes2;
239
+ if (part.tokens <= (((_part$attributes = part.attributes) === null || _part$attributes === void 0 ? void 0 : _part$attributes.minTokens) ?? 0)) continue;
240
+ const flex = ((_part$attributes2 = part.attributes) === null || _part$attributes2 === void 0 ? void 0 : _part$attributes2.flex) ?? DEFAULT_TRUNCATE_OPTIONS.flex;
241
+ const tokens = part.tokens * flex;
242
+ if (!biggest || tokens > biggest.tokens) {
243
+ secondBiggest = biggest;
244
+ biggest = part;
245
+ } else if (!secondBiggest || tokens > secondBiggest.tokens) secondBiggest = part;
246
+ }
247
+ return {
248
+ biggest,
249
+ secondBiggest
250
+ };
251
+ };
252
+ //#endregion
253
+ export { wrapContent as i, truncateWrappedContent as n, truncator_exports as r, stripTruncationTags as t };