llmz 0.0.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 (96) hide show
  1. package/README.md +41 -0
  2. package/dist/chunk-3CGLDS5T.cjs +3059 -0
  3. package/dist/chunk-3T465BEW.js +96 -0
  4. package/dist/chunk-6QDFMQHA.js +98 -0
  5. package/dist/chunk-7FIPXMZR.js +33 -0
  6. package/dist/chunk-7S3UY52U.js +3059 -0
  7. package/dist/chunk-A7BDFLAE.cjs +30 -0
  8. package/dist/chunk-BKGPO722.cjs +3079 -0
  9. package/dist/chunk-BOLDQGES.cjs +33 -0
  10. package/dist/chunk-C2TSWGYC.cjs +91 -0
  11. package/dist/chunk-DFZ6GX5C.js +220 -0
  12. package/dist/chunk-DILHJIMP.js +180 -0
  13. package/dist/chunk-E2B5DRIC.cjs +419 -0
  14. package/dist/chunk-E5W3P7EO.cjs +96 -0
  15. package/dist/chunk-ENFB45AI.cjs +220 -0
  16. package/dist/chunk-MSTBEKOQ.js +28 -0
  17. package/dist/chunk-PQN6HW7A.cjs +28 -0
  18. package/dist/chunk-Q4DEJGXD.js +344 -0
  19. package/dist/chunk-QPSUMPLP.js +419 -0
  20. package/dist/chunk-QZGFCB4T.cjs +344 -0
  21. package/dist/chunk-R2N2UUKC.cjs +98 -0
  22. package/dist/chunk-RB2L33ZR.js +3079 -0
  23. package/dist/chunk-RJHDQL4C.js +161 -0
  24. package/dist/chunk-UG2GCPHF.js +91 -0
  25. package/dist/chunk-UVSOAH2H.js +152 -0
  26. package/dist/chunk-VP6WWAE2.cjs +152 -0
  27. package/dist/chunk-YPOOKE3A.cjs +180 -0
  28. package/dist/chunk-YSQDPG26.js +30 -0
  29. package/dist/chunk-YUDUY7XW.cjs +284 -0
  30. package/dist/chunk-ZSRC3TN4.js +284 -0
  31. package/dist/chunk-ZUAFUOUR.cjs +161 -0
  32. package/dist/compiler/compiler.d.ts +28 -0
  33. package/dist/compiler/index.d.ts +2 -0
  34. package/dist/compiler/plugins/async-iterator.d.ts +4 -0
  35. package/dist/compiler/plugins/braces-tsx.d.ts +3 -0
  36. package/dist/compiler/plugins/jsx-preserve-newlines.d.ts +5 -0
  37. package/dist/compiler/plugins/line-tracking.d.ts +5 -0
  38. package/dist/compiler/plugins/replace-comment.d.ts +5 -0
  39. package/dist/compiler/plugins/return-async.d.ts +4 -0
  40. package/dist/compiler/plugins/track-tool-calls.d.ts +16 -0
  41. package/dist/compiler/plugins/variable-extraction.d.ts +5 -0
  42. package/dist/component-DWBRHLEN.cjs +9 -0
  43. package/dist/component-R3ZAVXUC.js +9 -0
  44. package/dist/component.d.ts +51 -0
  45. package/dist/component.default.d.ts +10 -0
  46. package/dist/context.d.ts +167 -0
  47. package/dist/dual-modes-2VDEOJ5D.js +13 -0
  48. package/dist/dual-modes-3MH5N6RY.cjs +13 -0
  49. package/dist/errors.d.ts +64 -0
  50. package/dist/exit-GYMXZZ4I.js +9 -0
  51. package/dist/exit-PQHMJEOG.cjs +9 -0
  52. package/dist/exit.d.ts +20 -0
  53. package/dist/formatting.d.ts +5 -0
  54. package/dist/getter.d.ts +2 -0
  55. package/dist/handlers.d.ts +10 -0
  56. package/dist/hoist.d.ts +2 -0
  57. package/dist/index.cjs +811 -0
  58. package/dist/index.d.ts +18 -0
  59. package/dist/index.js +811 -0
  60. package/dist/inspect.d.ts +6 -0
  61. package/dist/jsx-CJ2RBODH.js +14 -0
  62. package/dist/jsx-PPLE5YTB.cjs +14 -0
  63. package/dist/jsx.d.ts +11 -0
  64. package/dist/llmz-EGTGPSTX.cjs +1049 -0
  65. package/dist/llmz-WY74UVE3.js +1049 -0
  66. package/dist/llmz.d.ts +41 -0
  67. package/dist/objects.d.ts +24 -0
  68. package/dist/openai.d.ts +8 -0
  69. package/dist/prompts/chat-mode/system.md.d.ts +2 -0
  70. package/dist/prompts/chat-mode/user.md.d.ts +2 -0
  71. package/dist/prompts/common.d.ts +6 -0
  72. package/dist/prompts/dual-modes.d.ts +2 -0
  73. package/dist/prompts/prompt.d.ts +50 -0
  74. package/dist/prompts/worker-mode/system.md.d.ts +2 -0
  75. package/dist/prompts/worker-mode/user.md.d.ts +2 -0
  76. package/dist/snapshots.d.ts +61 -0
  77. package/dist/stack-traces.d.ts +1 -0
  78. package/dist/tool-AY47ML65.cjs +12 -0
  79. package/dist/tool-WVIPESKN.js +12 -0
  80. package/dist/tool.d.ts +30 -0
  81. package/dist/transcript.d.ts +9 -0
  82. package/dist/truncator-MTONQESU.js +11 -0
  83. package/dist/truncator-ZKPOW2I3.cjs +11 -0
  84. package/dist/truncator.d.ts +21 -0
  85. package/dist/types.d.ts +131 -0
  86. package/dist/typings-HTYLRNIC.js +11 -0
  87. package/dist/typings-QRJGGNUM.cjs +11 -0
  88. package/dist/typings.d.ts +5 -0
  89. package/dist/utils-TS23YJPE.js +38 -0
  90. package/dist/utils-UR4IMUHC.cjs +38 -0
  91. package/dist/utils.d.ts +21 -0
  92. package/dist/vm-4JFSZAMR.cjs +13 -0
  93. package/dist/vm-SMMA664M.js +13 -0
  94. package/dist/vm.d.ts +3 -0
  95. package/package.json +85 -0
  96. package/patches/source-map-js@1.2.1.patch +16 -0
@@ -0,0 +1,161 @@
1
+ import {
2
+ cleanStackTrace
3
+ } from "./chunk-MSTBEKOQ.js";
4
+
5
+ // src/errors.ts
6
+ var errorClasses = {};
7
+ function registerErrorClass(name, errorClass) {
8
+ errorClasses[name] = errorClass;
9
+ }
10
+ var tryParseMessage = (str) => {
11
+ try {
12
+ return JSON.parse(str);
13
+ } catch {
14
+ return str;
15
+ }
16
+ };
17
+ var Signals;
18
+ ((Signals2) => {
19
+ function isWrappedError(error) {
20
+ var _a, _b;
21
+ const isAlreadyWrapped = error.name === "Error" && ((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.startsWith("{")) && ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.endsWith("}"));
22
+ return isAlreadyWrapped;
23
+ }
24
+ Signals2.isWrappedError = isWrappedError;
25
+ function serializeError(error) {
26
+ if (isWrappedError(error)) {
27
+ const msg = tryParseMessage(error.message);
28
+ return JSON.stringify({
29
+ ...typeof msg === "object" ? msg : { message: msg },
30
+ properties: { ...error }
31
+ });
32
+ }
33
+ return JSON.stringify({
34
+ name: error.constructor.name,
35
+ message: error.message,
36
+ stack: cleanStackTrace(error.stack ?? ""),
37
+ properties: { ...error }
38
+ });
39
+ }
40
+ Signals2.serializeError = serializeError;
41
+ function maybeDeserializeError(error) {
42
+ const errorIsAlreadyDeserialized = error instanceof Error && error.name in errorClasses;
43
+ if (errorIsAlreadyDeserialized) {
44
+ return error;
45
+ }
46
+ const serializedError = error instanceof Error ? error.message : typeof error === "string" ? error : (error == null ? void 0 : error.toString()) ?? "";
47
+ try {
48
+ const parsed = JSON.parse(serializedError);
49
+ if (parsed && parsed.name && parsed.message) {
50
+ const { name, message, properties = {} } = parsed;
51
+ const ErrorClass = errorClasses[name] || Error;
52
+ const errorInstance = new ErrorClass(message);
53
+ errorInstance.message = message;
54
+ errorInstance.name = name;
55
+ errorInstance.stack = cleanStackTrace((error == null ? void 0 : error.stack) ?? "");
56
+ Object.assign(errorInstance, properties);
57
+ if (isWrappedError(errorInstance)) {
58
+ return maybeDeserializeError(errorInstance);
59
+ }
60
+ return errorInstance;
61
+ }
62
+ } catch {
63
+ }
64
+ return error;
65
+ }
66
+ Signals2.maybeDeserializeError = maybeDeserializeError;
67
+ })(Signals || (Signals = {}));
68
+ var VMSignal = class extends Error {
69
+ constructor(message) {
70
+ super(message);
71
+ this.message = message;
72
+ this.message = Signals.serializeError(this);
73
+ }
74
+ /**
75
+ * The code that was executed by the VM up to the point of the signal
76
+ */
77
+ truncatedCode = "";
78
+ /** The current tool call, if any */
79
+ toolCall;
80
+ /**
81
+ * Contains all the declared and executed variables during the VM execution
82
+ * See file plugins/variable-extraction.ts for more details
83
+ */
84
+ variables = {};
85
+ };
86
+ var SnapshotSignal = class extends VMSignal {
87
+ constructor(message) {
88
+ super(message);
89
+ this.message = Signals.serializeError(this);
90
+ }
91
+ };
92
+ var VMLoopSignal = class extends VMSignal {
93
+ constructor(message) {
94
+ super(message);
95
+ this.message = Signals.serializeError(this);
96
+ }
97
+ };
98
+ var ThinkSignal = class extends VMLoopSignal {
99
+ constructor(reason, context) {
100
+ super("Think signal received: " + reason);
101
+ this.reason = reason;
102
+ this.context = context;
103
+ this.message = Signals.serializeError(this);
104
+ }
105
+ toString() {
106
+ return Signals.serializeError(this);
107
+ }
108
+ };
109
+ var CodeExecutionError = class extends Error {
110
+ constructor(message, code, stacktrace) {
111
+ super(message);
112
+ this.code = code;
113
+ this.stacktrace = stacktrace;
114
+ this.message = Signals.serializeError(this);
115
+ }
116
+ };
117
+ var InvalidCodeError = class extends Error {
118
+ constructor(message, code) {
119
+ super(message);
120
+ this.code = code;
121
+ this.message = Signals.serializeError(this);
122
+ }
123
+ };
124
+ var LoopExceededError = class extends Error {
125
+ constructor() {
126
+ super("Loop exceeded error");
127
+ this.message = Signals.serializeError(this);
128
+ }
129
+ };
130
+ var CodeFormattingError = class extends Error {
131
+ constructor(message, code) {
132
+ super(message, {
133
+ cause: "Code formatting error"
134
+ });
135
+ this.code = code;
136
+ }
137
+ };
138
+ var AssignmentError = class extends Error {
139
+ constructor(message) {
140
+ super(message);
141
+ this.message = Signals.serializeError(this);
142
+ }
143
+ };
144
+ registerErrorClass("VMSignal", VMSignal);
145
+ registerErrorClass("SnapshotSignal", SnapshotSignal);
146
+ registerErrorClass("VMLoopSignal", VMLoopSignal);
147
+ registerErrorClass("ThinkSignal", ThinkSignal);
148
+ registerErrorClass("CodeExecutionError", CodeExecutionError);
149
+ registerErrorClass("AssignmentError", AssignmentError);
150
+
151
+ export {
152
+ Signals,
153
+ VMSignal,
154
+ SnapshotSignal,
155
+ ThinkSignal,
156
+ CodeExecutionError,
157
+ InvalidCodeError,
158
+ LoopExceededError,
159
+ CodeFormattingError,
160
+ AssignmentError
161
+ };
@@ -0,0 +1,91 @@
1
+ import {
2
+ extractType,
3
+ inspect
4
+ } from "./chunk-Q4DEJGXD.js";
5
+
6
+ // src/snapshots.ts
7
+ import { ulid } from "ulid";
8
+ var MAX_SNAPSHOT_SIZE_BYTES = 4e3;
9
+ var Snapshot = class _Snapshot {
10
+ id;
11
+ reason;
12
+ stack;
13
+ variables;
14
+ toolCall;
15
+ #status;
16
+ get status() {
17
+ return Object.freeze({ ...this.#status });
18
+ }
19
+ constructor(props) {
20
+ this.id = props.id;
21
+ this.stack = props.stack;
22
+ this.reason = props.reason;
23
+ this.variables = props.variables;
24
+ this.toolCall = props.toolCall;
25
+ this.#status = props.status;
26
+ }
27
+ static fromSignal(signal) {
28
+ const variables = Object.entries(signal.variables).map(([name, value]) => {
29
+ const type = extractType(value);
30
+ const bytes = JSON.stringify(value || "").length;
31
+ const truncated = bytes > MAX_SNAPSHOT_SIZE_BYTES;
32
+ return truncated ? { name, type, bytes, truncated: true, preview: inspect(value, name) ?? "N/A" } : { name, type, bytes, truncated: false, value };
33
+ });
34
+ return new _Snapshot({
35
+ id: "snapshot_" + ulid(),
36
+ reason: signal.message,
37
+ stack: signal.truncatedCode,
38
+ variables,
39
+ toolCall: signal.toolCall,
40
+ status: { type: "pending" }
41
+ });
42
+ }
43
+ toJSON() {
44
+ return {
45
+ id: this.id,
46
+ reason: this.reason,
47
+ stack: this.stack,
48
+ variables: this.variables,
49
+ toolCall: this.toolCall
50
+ };
51
+ }
52
+ static fromJSON(json) {
53
+ return new _Snapshot({
54
+ id: json.id,
55
+ reason: json.reason,
56
+ stack: json.stack,
57
+ variables: json.variables,
58
+ toolCall: json.toolCall,
59
+ status: json.status
60
+ });
61
+ }
62
+ clone() {
63
+ return new _Snapshot({
64
+ id: this.id,
65
+ reason: this.reason,
66
+ stack: this.stack,
67
+ variables: this.variables,
68
+ toolCall: this.toolCall,
69
+ status: this.#status
70
+ });
71
+ }
72
+ reset() {
73
+ this.#status = { type: "pending" };
74
+ }
75
+ resolve(value) {
76
+ if (this.#status.type !== "pending") {
77
+ throw new Error(`Cannot resolve snapshot because it is already settled: ${this.#status.type}`);
78
+ }
79
+ this.#status = { type: "resolved", value };
80
+ }
81
+ reject(error) {
82
+ if (this.#status.type !== "pending") {
83
+ throw new Error(`Cannot reject snapshot because it is already settled: ${this.#status.type}`);
84
+ }
85
+ this.#status = { type: "rejected", error };
86
+ }
87
+ };
88
+
89
+ export {
90
+ Snapshot
91
+ };
@@ -0,0 +1,152 @@
1
+ import {
2
+ getTokenizer
3
+ } from "./chunk-DFZ6GX5C.js";
4
+
5
+ // src/truncator.ts
6
+ var DEFAULT_REMOVE_CHUNK = 250;
7
+ var WRAP_OPEN_TAG_1 = "\u3010TRUNCATE";
8
+ var WRAP_OPEN_TAG_2 = "\u3011";
9
+ var WRAP_CLOSE_TAG = "\u3010/TRUNCATE\u3011";
10
+ var getRegex = () => new RegExp(`(${WRAP_OPEN_TAG_1}(?:\\s+[\\w:]+)*\\s*${WRAP_OPEN_TAG_2})([\\s\\S]*?)(${WRAP_CLOSE_TAG})`, "g");
11
+ var DEFAULT_TRUNCATE_OPTIONS = {
12
+ preserve: "top",
13
+ flex: 1,
14
+ minTokens: 0
15
+ };
16
+ function wrapContent(content, options) {
17
+ const preserve = (options == null ? void 0 : options.preserve) ?? DEFAULT_TRUNCATE_OPTIONS.preserve;
18
+ const flex = (options == null ? void 0 : options.flex) ?? DEFAULT_TRUNCATE_OPTIONS.flex;
19
+ const minTokens = (options == null ? void 0 : options.minTokens) ?? DEFAULT_TRUNCATE_OPTIONS.minTokens;
20
+ return `${WRAP_OPEN_TAG_1} preserve:${preserve} flex:${flex} min:${minTokens} ${WRAP_OPEN_TAG_2}${content}${WRAP_CLOSE_TAG}`;
21
+ }
22
+ function truncateWrappedContent({
23
+ messages,
24
+ tokenLimit,
25
+ throwOnFailure = true
26
+ }) {
27
+ var _a, _b, _c;
28
+ const tokenizer = getTokenizer();
29
+ const parts = [];
30
+ for (const msg of messages) {
31
+ const current = [];
32
+ const content = msg.content;
33
+ let match;
34
+ const regex = getRegex();
35
+ let lastIndex = 0;
36
+ while ((match = regex.exec(content)) !== null) {
37
+ const attributes = match[1].split(/\s+/).slice(1).filter((x) => x !== WRAP_OPEN_TAG_2).map((x) => x.split(":")).reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
38
+ if (match.index > lastIndex) {
39
+ const nonTruncatableContent = content.slice(lastIndex, match.index);
40
+ current.push({
41
+ content: nonTruncatableContent,
42
+ tokens: tokenizer.count(nonTruncatableContent),
43
+ truncatable: false
44
+ });
45
+ }
46
+ const wrappedContent = match[2];
47
+ current.push({
48
+ content: wrappedContent,
49
+ tokens: tokenizer.count(wrappedContent),
50
+ truncatable: true,
51
+ attributes: {
52
+ preserve: attributes.preserve,
53
+ flex: Number(attributes.flex) || DEFAULT_TRUNCATE_OPTIONS.flex,
54
+ minTokens: Number(attributes.min) || DEFAULT_TRUNCATE_OPTIONS.minTokens
55
+ }
56
+ });
57
+ lastIndex = regex.lastIndex;
58
+ }
59
+ if (lastIndex < content.length) {
60
+ const remainingContent = content.slice(lastIndex);
61
+ current.push({
62
+ content: remainingContent,
63
+ tokens: tokenizer.count(remainingContent),
64
+ truncatable: false
65
+ });
66
+ }
67
+ parts.push(current);
68
+ }
69
+ const getCount = () => parts.reduce((acc, x) => acc + x.reduce((acc2, y) => acc2 + y.tokens, 0), 0);
70
+ const getTwoBiggestTruncatables = () => {
71
+ var _a2, _b2;
72
+ let biggest = null;
73
+ let secondBiggest = null;
74
+ for (const part of parts.flat()) {
75
+ if (part.truncatable) {
76
+ const flex = ((_a2 = part.attributes) == null ? void 0 : _a2.flex) ?? DEFAULT_TRUNCATE_OPTIONS.flex;
77
+ const tokens = part.tokens * flex;
78
+ if (part.tokens <= (((_b2 = part.attributes) == null ? void 0 : _b2.minTokens) ?? 0)) {
79
+ continue;
80
+ }
81
+ if (!biggest || tokens > biggest.tokens) {
82
+ secondBiggest = biggest;
83
+ biggest = part;
84
+ } else if (!secondBiggest || tokens > secondBiggest.tokens) {
85
+ secondBiggest = part;
86
+ }
87
+ }
88
+ }
89
+ return { biggest, secondBiggest };
90
+ };
91
+ let currentCount = getCount();
92
+ while (currentCount > tokenLimit) {
93
+ const { biggest, secondBiggest } = getTwoBiggestTruncatables();
94
+ if (!biggest || !biggest.truncatable || biggest.tokens <= 0) {
95
+ if (throwOnFailure) {
96
+ throw new Error(`Cannot truncate further, current count: ${getCount()}`);
97
+ } else {
98
+ break;
99
+ }
100
+ }
101
+ const delta = Math.max(biggest.tokens - ((secondBiggest == null ? void 0 : secondBiggest.tokens) ?? 0), DEFAULT_REMOVE_CHUNK);
102
+ const room = Math.min(delta, biggest.tokens);
103
+ let toRemove = Math.min(room, currentCount - tokenLimit);
104
+ if (toRemove <= 0) {
105
+ if (throwOnFailure) {
106
+ throw new Error(`Cannot truncate further, current count: ${getCount()}`);
107
+ } else {
108
+ break;
109
+ }
110
+ }
111
+ if (biggest.tokens - toRemove < (((_a = biggest.attributes) == null ? void 0 : _a.minTokens) ?? 0)) {
112
+ toRemove = biggest.tokens - (((_b = biggest.attributes) == null ? void 0 : _b.minTokens) ?? 0);
113
+ }
114
+ const preserve = ((_c = biggest.attributes) == null ? void 0 : _c.preserve) ?? DEFAULT_TRUNCATE_OPTIONS.preserve;
115
+ const split = tokenizer.split(biggest.content);
116
+ if (preserve === "bottom") {
117
+ biggest.content = split.slice(toRemove).join("");
118
+ } else if (preserve === "top") {
119
+ biggest.content = split.slice(0, -toRemove).join("");
120
+ } else {
121
+ const anchor = Math.ceil(split.length / 2);
122
+ const radius = Math.ceil(toRemove / 2);
123
+ const left = anchor - radius;
124
+ const right = anchor + radius;
125
+ biggest.content = split.slice(0, left).join("") + split.slice(right).join("");
126
+ }
127
+ biggest.tokens -= toRemove;
128
+ currentCount -= toRemove;
129
+ }
130
+ const removeRedundantWrappers = (content) => {
131
+ return content.replace(getRegex(), "$2");
132
+ };
133
+ return messages.map((msg, i) => {
134
+ const p = parts[i];
135
+ return {
136
+ ...msg,
137
+ content: removeRedundantWrappers(
138
+ p.map((part) => {
139
+ if (part.truncatable) {
140
+ return part.content;
141
+ }
142
+ return part.content;
143
+ }).join("")
144
+ )
145
+ };
146
+ });
147
+ }
148
+
149
+ export {
150
+ wrapContent,
151
+ truncateWrappedContent
152
+ };
@@ -0,0 +1,152 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
+
3
+ var _chunkENFB45AIcjs = require('./chunk-ENFB45AI.cjs');
4
+
5
+ // src/truncator.ts
6
+ var DEFAULT_REMOVE_CHUNK = 250;
7
+ var WRAP_OPEN_TAG_1 = "\u3010TRUNCATE";
8
+ var WRAP_OPEN_TAG_2 = "\u3011";
9
+ var WRAP_CLOSE_TAG = "\u3010/TRUNCATE\u3011";
10
+ var getRegex = () => new RegExp(`(${WRAP_OPEN_TAG_1}(?:\\s+[\\w:]+)*\\s*${WRAP_OPEN_TAG_2})([\\s\\S]*?)(${WRAP_CLOSE_TAG})`, "g");
11
+ var DEFAULT_TRUNCATE_OPTIONS = {
12
+ preserve: "top",
13
+ flex: 1,
14
+ minTokens: 0
15
+ };
16
+ function wrapContent(content, options) {
17
+ const preserve = _nullishCoalesce((options == null ? void 0 : options.preserve), () => ( DEFAULT_TRUNCATE_OPTIONS.preserve));
18
+ const flex = _nullishCoalesce((options == null ? void 0 : options.flex), () => ( DEFAULT_TRUNCATE_OPTIONS.flex));
19
+ const minTokens = _nullishCoalesce((options == null ? void 0 : options.minTokens), () => ( DEFAULT_TRUNCATE_OPTIONS.minTokens));
20
+ return `${WRAP_OPEN_TAG_1} preserve:${preserve} flex:${flex} min:${minTokens} ${WRAP_OPEN_TAG_2}${content}${WRAP_CLOSE_TAG}`;
21
+ }
22
+ function truncateWrappedContent({
23
+ messages,
24
+ tokenLimit,
25
+ throwOnFailure = true
26
+ }) {
27
+ var _a, _b, _c;
28
+ const tokenizer = _chunkENFB45AIcjs.getTokenizer.call(void 0, );
29
+ const parts = [];
30
+ for (const msg of messages) {
31
+ const current = [];
32
+ const content = msg.content;
33
+ let match;
34
+ const regex = getRegex();
35
+ let lastIndex = 0;
36
+ while ((match = regex.exec(content)) !== null) {
37
+ const attributes = match[1].split(/\s+/).slice(1).filter((x) => x !== WRAP_OPEN_TAG_2).map((x) => x.split(":")).reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
38
+ if (match.index > lastIndex) {
39
+ const nonTruncatableContent = content.slice(lastIndex, match.index);
40
+ current.push({
41
+ content: nonTruncatableContent,
42
+ tokens: tokenizer.count(nonTruncatableContent),
43
+ truncatable: false
44
+ });
45
+ }
46
+ const wrappedContent = match[2];
47
+ current.push({
48
+ content: wrappedContent,
49
+ tokens: tokenizer.count(wrappedContent),
50
+ truncatable: true,
51
+ attributes: {
52
+ preserve: attributes.preserve,
53
+ flex: Number(attributes.flex) || DEFAULT_TRUNCATE_OPTIONS.flex,
54
+ minTokens: Number(attributes.min) || DEFAULT_TRUNCATE_OPTIONS.minTokens
55
+ }
56
+ });
57
+ lastIndex = regex.lastIndex;
58
+ }
59
+ if (lastIndex < content.length) {
60
+ const remainingContent = content.slice(lastIndex);
61
+ current.push({
62
+ content: remainingContent,
63
+ tokens: tokenizer.count(remainingContent),
64
+ truncatable: false
65
+ });
66
+ }
67
+ parts.push(current);
68
+ }
69
+ const getCount = () => parts.reduce((acc, x) => acc + x.reduce((acc2, y) => acc2 + y.tokens, 0), 0);
70
+ const getTwoBiggestTruncatables = () => {
71
+ var _a2, _b2;
72
+ let biggest = null;
73
+ let secondBiggest = null;
74
+ for (const part of parts.flat()) {
75
+ if (part.truncatable) {
76
+ const flex = _nullishCoalesce(((_a2 = part.attributes) == null ? void 0 : _a2.flex), () => ( DEFAULT_TRUNCATE_OPTIONS.flex));
77
+ const tokens = part.tokens * flex;
78
+ if (part.tokens <= (_nullishCoalesce(((_b2 = part.attributes) == null ? void 0 : _b2.minTokens), () => ( 0)))) {
79
+ continue;
80
+ }
81
+ if (!biggest || tokens > biggest.tokens) {
82
+ secondBiggest = biggest;
83
+ biggest = part;
84
+ } else if (!secondBiggest || tokens > secondBiggest.tokens) {
85
+ secondBiggest = part;
86
+ }
87
+ }
88
+ }
89
+ return { biggest, secondBiggest };
90
+ };
91
+ let currentCount = getCount();
92
+ while (currentCount > tokenLimit) {
93
+ const { biggest, secondBiggest } = getTwoBiggestTruncatables();
94
+ if (!biggest || !biggest.truncatable || biggest.tokens <= 0) {
95
+ if (throwOnFailure) {
96
+ throw new Error(`Cannot truncate further, current count: ${getCount()}`);
97
+ } else {
98
+ break;
99
+ }
100
+ }
101
+ const delta = Math.max(biggest.tokens - (_nullishCoalesce((secondBiggest == null ? void 0 : secondBiggest.tokens), () => ( 0))), DEFAULT_REMOVE_CHUNK);
102
+ const room = Math.min(delta, biggest.tokens);
103
+ let toRemove = Math.min(room, currentCount - tokenLimit);
104
+ if (toRemove <= 0) {
105
+ if (throwOnFailure) {
106
+ throw new Error(`Cannot truncate further, current count: ${getCount()}`);
107
+ } else {
108
+ break;
109
+ }
110
+ }
111
+ if (biggest.tokens - toRemove < (_nullishCoalesce(((_a = biggest.attributes) == null ? void 0 : _a.minTokens), () => ( 0)))) {
112
+ toRemove = biggest.tokens - (_nullishCoalesce(((_b = biggest.attributes) == null ? void 0 : _b.minTokens), () => ( 0)));
113
+ }
114
+ const preserve = _nullishCoalesce(((_c = biggest.attributes) == null ? void 0 : _c.preserve), () => ( DEFAULT_TRUNCATE_OPTIONS.preserve));
115
+ const split = tokenizer.split(biggest.content);
116
+ if (preserve === "bottom") {
117
+ biggest.content = split.slice(toRemove).join("");
118
+ } else if (preserve === "top") {
119
+ biggest.content = split.slice(0, -toRemove).join("");
120
+ } else {
121
+ const anchor = Math.ceil(split.length / 2);
122
+ const radius = Math.ceil(toRemove / 2);
123
+ const left = anchor - radius;
124
+ const right = anchor + radius;
125
+ biggest.content = split.slice(0, left).join("") + split.slice(right).join("");
126
+ }
127
+ biggest.tokens -= toRemove;
128
+ currentCount -= toRemove;
129
+ }
130
+ const removeRedundantWrappers = (content) => {
131
+ return content.replace(getRegex(), "$2");
132
+ };
133
+ return messages.map((msg, i) => {
134
+ const p = parts[i];
135
+ return {
136
+ ...msg,
137
+ content: removeRedundantWrappers(
138
+ p.map((part) => {
139
+ if (part.truncatable) {
140
+ return part.content;
141
+ }
142
+ return part.content;
143
+ }).join("")
144
+ )
145
+ };
146
+ });
147
+ }
148
+
149
+
150
+
151
+
152
+ exports.wrapContent = wrapContent; exports.truncateWrappedContent = truncateWrappedContent;