llmz 0.0.11 → 0.0.13

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 (92) hide show
  1. package/dist/chat.d.ts +17 -0
  2. package/dist/chunk-276Q6EWP.cjs +224 -0
  3. package/dist/chunk-4L6D2A6O.cjs +283 -0
  4. package/dist/chunk-4MNIJGK6.js +224 -0
  5. package/dist/chunk-7WRN4E42.js +3087 -0
  6. package/dist/chunk-BEPRLBPK.cjs +3123 -0
  7. package/dist/chunk-C6WNNTEV.cjs +212 -0
  8. package/dist/chunk-D3ESDRLH.js +3123 -0
  9. package/dist/chunk-GGWM6X2K.js +184 -0
  10. package/dist/chunk-GWFYZDUR.cjs +105 -0
  11. package/dist/chunk-HJKOSEH2.cjs +722 -0
  12. package/dist/chunk-IH2WQFO5.js +283 -0
  13. package/dist/chunk-IKSIOIIP.cjs +28 -0
  14. package/dist/chunk-JAGB2AOU.js +212 -0
  15. package/dist/chunk-JDABP4SD.cjs +161 -0
  16. package/dist/chunk-JGVAZO4X.cjs +152 -0
  17. package/dist/chunk-JKVVQN2P.js +161 -0
  18. package/dist/chunk-JMSZKB4T.js +105 -0
  19. package/dist/chunk-JQBT7UWN.js +28 -0
  20. package/dist/chunk-KH6JQYQA.js +796 -0
  21. package/dist/chunk-KMZDFWYZ.cjs +33 -0
  22. package/dist/chunk-ORQP26SZ.js +33 -0
  23. package/dist/chunk-PRVFVXT4.js +722 -0
  24. package/dist/chunk-SHJDRZF5.cjs +796 -0
  25. package/dist/chunk-SNDVQU5A.js +152 -0
  26. package/dist/chunk-UQOBUJIQ.cjs +3087 -0
  27. package/dist/chunk-ZRCU35UV.cjs +184 -0
  28. package/dist/citations.d.ts +63 -0
  29. package/dist/compiler/compiler.d.ts +28 -0
  30. package/dist/compiler/index.d.ts +2 -0
  31. package/dist/compiler/plugins/async-iterator.d.ts +4 -0
  32. package/dist/compiler/plugins/braces-tsx.d.ts +3 -0
  33. package/dist/compiler/plugins/jsx-preserve-newlines.d.ts +5 -0
  34. package/dist/compiler/plugins/line-tracking.d.ts +5 -0
  35. package/dist/compiler/plugins/replace-comment.d.ts +5 -0
  36. package/dist/compiler/plugins/return-async.d.ts +4 -0
  37. package/dist/compiler/plugins/track-tool-calls.d.ts +16 -0
  38. package/dist/compiler/plugins/variable-extraction.d.ts +5 -0
  39. package/dist/component-R4WTW6DZ.cjs +18 -0
  40. package/dist/component-WFVDVSDK.js +18 -0
  41. package/dist/component.d.ts +66 -0
  42. package/dist/component.default.d.ts +316 -0
  43. package/dist/context.d.ts +176 -0
  44. package/dist/dual-modes-T53P72CH.js +12 -0
  45. package/dist/dual-modes-VLIGPIHX.cjs +12 -0
  46. package/dist/errors.d.ts +64 -0
  47. package/dist/exit-TRXEU4OU.cjs +8 -0
  48. package/dist/exit-YORW76T3.js +8 -0
  49. package/dist/exit.d.ts +26 -0
  50. package/dist/formatting.d.ts +5 -0
  51. package/dist/getter.d.ts +2 -0
  52. package/dist/handlers.d.ts +10 -0
  53. package/dist/hoist.d.ts +2 -0
  54. package/dist/index.cjs +921 -0
  55. package/dist/index.d.ts +23 -0
  56. package/dist/index.js +921 -0
  57. package/dist/inspect.d.ts +6 -0
  58. package/dist/jsx-AEHVFB3L.js +13 -0
  59. package/dist/jsx-AJAXBWFE.cjs +13 -0
  60. package/dist/jsx.d.ts +11 -0
  61. package/dist/llmz-QLZBDG2Z.cjs +576 -0
  62. package/dist/llmz-ROOX7RYI.js +576 -0
  63. package/dist/llmz.d.ts +40 -0
  64. package/dist/objects.d.ts +24 -0
  65. package/dist/prompts/chat-mode/system.md.d.ts +2 -0
  66. package/dist/prompts/chat-mode/user.md.d.ts +2 -0
  67. package/dist/prompts/common.d.ts +6 -0
  68. package/dist/prompts/dual-modes.d.ts +2 -0
  69. package/dist/prompts/prompt.d.ts +55 -0
  70. package/dist/prompts/worker-mode/system.md.d.ts +2 -0
  71. package/dist/prompts/worker-mode/user.md.d.ts +2 -0
  72. package/dist/result.d.ts +33 -0
  73. package/dist/snapshots.d.ts +69 -0
  74. package/dist/stack-traces.d.ts +1 -0
  75. package/dist/tool-N6ODRRGH.js +11 -0
  76. package/dist/tool-QP4MVRWI.cjs +11 -0
  77. package/dist/tool.d.ts +56 -0
  78. package/dist/transcript.d.ts +36 -0
  79. package/dist/truncator-DUMWEGQO.cjs +10 -0
  80. package/dist/truncator-IY2MXOMC.js +10 -0
  81. package/dist/truncator.d.ts +20 -0
  82. package/dist/types.d.ts +105 -0
  83. package/dist/typings-2CPHOFDN.cjs +10 -0
  84. package/dist/typings-GDMY6VY2.js +10 -0
  85. package/dist/typings.d.ts +5 -0
  86. package/dist/utils-A7WNEFTA.cjs +39 -0
  87. package/dist/utils-N24IHDFA.js +39 -0
  88. package/dist/utils.d.ts +23 -0
  89. package/dist/vm-2DLG7V4G.cjs +12 -0
  90. package/dist/vm-FLBMZUA2.js +12 -0
  91. package/dist/vm.d.ts +3 -0
  92. package/package.json +4 -4
@@ -0,0 +1,796 @@
1
+ import {
2
+ cleanStackTrace
3
+ } from "./chunk-JQBT7UWN.js";
4
+ import {
5
+ getComponentReference
6
+ } from "./chunk-GGWM6X2K.js";
7
+ import {
8
+ wrapContent
9
+ } from "./chunk-SNDVQU5A.js";
10
+ import {
11
+ escapeString,
12
+ getTokenizer
13
+ } from "./chunk-4MNIJGK6.js";
14
+ import {
15
+ chain_default,
16
+ countBy_default,
17
+ filter_default,
18
+ isEmpty_default,
19
+ isEqual_default,
20
+ isNil_default,
21
+ isPlainObject_default,
22
+ mapKeys_default,
23
+ orderBy_default,
24
+ uniqWith_default,
25
+ uniq_default
26
+ } from "./chunk-7WRN4E42.js";
27
+
28
+ // src/inspect.ts
29
+ import bytes from "bytes";
30
+ var SUBTITLE_LN = "--------------";
31
+ var SECTION_SEP = "\n";
32
+ var NUMBER_LOCALE = new Intl.NumberFormat("en-US");
33
+ var LONG_TEXT_LENGTH = 4096;
34
+ var DEFAULT_OPTIONS = {
35
+ tokens: 1e5
36
+ };
37
+ function printLimitedJson(obj, maxDepth, maxLength, maxKeys) {
38
+ const indent = 2;
39
+ let currentLength = 0;
40
+ let wasTruncated = false;
41
+ function recurse(currentObj, depth, currentIndent) {
42
+ if (depth > maxDepth || currentLength >= maxLength) {
43
+ wasTruncated = true;
44
+ return "...";
45
+ }
46
+ if (typeof currentObj === "object" && currentObj instanceof Date) {
47
+ currentIndent += 3;
48
+ try {
49
+ return currentObj.toISOString();
50
+ } catch (err) {
51
+ return `<Date: ${(err == null ? void 0 : err.message) ?? "Invalid Date"}>`;
52
+ }
53
+ }
54
+ if (typeof currentObj !== "object" || currentObj === null) {
55
+ const value = JSON.stringify(currentObj);
56
+ currentLength += getTokenizer().count(value);
57
+ return value;
58
+ }
59
+ const indentation = " ".repeat(currentIndent);
60
+ if (Array.isArray(currentObj)) {
61
+ let result = "[\n";
62
+ for (let i = 0; i < currentObj.length && currentLength < maxLength; i++) {
63
+ if (i > 0) {
64
+ result += ",\n";
65
+ }
66
+ result += indentation + " ".repeat(indent) + recurse(currentObj[i], depth + 1, currentIndent + indent);
67
+ }
68
+ result += "\n" + indentation + "]";
69
+ currentLength += getTokenizer().count(result);
70
+ return result;
71
+ } else {
72
+ let result = "{\n";
73
+ const keys = Object.keys(currentObj);
74
+ const numKeys = keys.length;
75
+ for (let i = 0; i < Math.min(numKeys, maxKeys) && currentLength < maxLength; i++) {
76
+ const key = keys[i];
77
+ if (i > 0) {
78
+ result += ",\n";
79
+ }
80
+ const value = recurse(currentObj[key], depth + 1, currentIndent + indent);
81
+ result += indentation + " ".repeat(indent) + `"${key}": ${value}`;
82
+ }
83
+ if (numKeys > maxKeys) {
84
+ wasTruncated = true;
85
+ result += ",\n" + indentation + `... (${numKeys - maxKeys} more keys)`;
86
+ }
87
+ result += "\n" + indentation + "}";
88
+ currentLength += getTokenizer().count(result);
89
+ return result;
90
+ }
91
+ }
92
+ const output = getTokenizer().truncate(recurse(obj, 0, 0), maxLength);
93
+ return { output, truncated: wasTruncated };
94
+ }
95
+ function extractType(value, generic = true) {
96
+ if (value === null) {
97
+ return "null";
98
+ }
99
+ if (value === void 0 || typeof value === "undefined") {
100
+ return "undefined";
101
+ }
102
+ if (typeof value === "object" && Array.isArray(value)) {
103
+ if (!generic) {
104
+ return "Array";
105
+ }
106
+ if (value.length === 0) {
107
+ return "Array (empty)";
108
+ }
109
+ if (value.length === 1) {
110
+ return `Array<${extractType(value[0])}>`;
111
+ }
112
+ const types = /* @__PURE__ */ new Map();
113
+ for (const element of value) {
114
+ const type = extractType(element, false);
115
+ types.set(type, (types.get(type) || 0) + 1);
116
+ }
117
+ if (types.size <= 3) {
118
+ return `Array<${Array.from(types.keys()).join(" | ")}>`;
119
+ }
120
+ return "Array";
121
+ }
122
+ if (typeof value === "number") {
123
+ return "number";
124
+ }
125
+ if (typeof value === "boolean") {
126
+ return "boolean";
127
+ }
128
+ if (typeof value === "bigint") {
129
+ return "bigint";
130
+ }
131
+ if (typeof value === "function") {
132
+ return "function";
133
+ }
134
+ if (typeof value === "object" && value instanceof Date) {
135
+ return "date";
136
+ }
137
+ if (typeof value === "object" && value instanceof RegExp) {
138
+ return "regexp";
139
+ }
140
+ if (value instanceof Error) {
141
+ return "error";
142
+ }
143
+ if (typeof value === "string" && value.trim().length === 0) {
144
+ return "<empty string>";
145
+ }
146
+ return typeof value;
147
+ }
148
+ function previewValue(value, length = LONG_TEXT_LENGTH) {
149
+ if (value === null) {
150
+ return "<nil>";
151
+ }
152
+ if (value === void 0) {
153
+ return "<undefined>";
154
+ }
155
+ const previewStr = (str) => {
156
+ if (str.length > length) {
157
+ return escapeString(str.slice(0, length)) + " ... <truncated>";
158
+ }
159
+ return escapeString(str);
160
+ };
161
+ const previewObj = (obj) => {
162
+ const mapped = mapKeys_default(obj, (_value, key) => previewStr(key));
163
+ return JSON.stringify(mapped);
164
+ };
165
+ if (typeof value === "string") {
166
+ return "<string> " + previewStr(value);
167
+ }
168
+ if (typeof value === "object" && Array.isArray(value)) {
169
+ return "<array> " + previewStr(JSON.stringify(value));
170
+ }
171
+ if (typeof value === "object" && value instanceof Date) {
172
+ return "<date> " + value.toISOString();
173
+ }
174
+ if (typeof value === "object" && value instanceof RegExp) {
175
+ return "<regexp> " + value.toString();
176
+ }
177
+ if (typeof value === "object") {
178
+ return "<object> " + previewObj(value);
179
+ }
180
+ if (typeof value === "bigint") {
181
+ return "<bigint> " + value.toString();
182
+ }
183
+ if (typeof value === "function") {
184
+ return "<function> " + value.toString();
185
+ }
186
+ if (typeof value === "boolean") {
187
+ return "<boolean> " + value.toString();
188
+ }
189
+ if (value instanceof Error) {
190
+ return "<error> " + previewError(value);
191
+ }
192
+ if (typeof value === "number") {
193
+ return "<number> " + value.toString();
194
+ }
195
+ if (typeof value === "symbol") {
196
+ return "<symbol> " + value.toString();
197
+ }
198
+ return `${typeof value} ` + ((value == null ? void 0 : value.toString()) ?? "<unknown>");
199
+ }
200
+ function previewError(err) {
201
+ const lines = [];
202
+ lines.push("Error: " + err.name);
203
+ lines.push(SUBTITLE_LN);
204
+ lines.push(previewValue(err.message));
205
+ lines.push(SECTION_SEP);
206
+ lines.push("Stack Trace:");
207
+ lines.push(SUBTITLE_LN);
208
+ lines.push(previewValue(err.stack ?? "<no stack trace>"));
209
+ return lines.join("\n");
210
+ }
211
+ function previewArray(arr) {
212
+ if (!Array.isArray(arr)) {
213
+ throw new Error("Expected an array");
214
+ }
215
+ const lines = [];
216
+ const getItemPreview = (value, index) => `[${index}]`.padEnd(15) + ` ${previewValue(value)}`;
217
+ if (arr.length === 0) {
218
+ lines.push("// Array Is Empty (0 element)");
219
+ return lines.join("\n").replace(/\n{2,}/g, SECTION_SEP);
220
+ }
221
+ if (arr.length <= 10) {
222
+ lines.push("// Full Array Preview");
223
+ lines.push(SUBTITLE_LN);
224
+ lines.push(...arr.map(getItemPreview));
225
+ return lines.join("\n").replace(/\n{2,}/g, SECTION_SEP);
226
+ }
227
+ lines.push("// Analysis Summary");
228
+ lines.push(SUBTITLE_LN);
229
+ const typesCount = countBy_default(arr, (item) => extractType(item, false));
230
+ const ordered = orderBy_default(
231
+ arr.filter((item) => !isNil_default(item) && JSON.stringify(item).length < 100),
232
+ (item) => JSON.stringify(item),
233
+ "asc"
234
+ );
235
+ const minValues = ordered.slice(0, 3).map((item) => previewValue(item, 10));
236
+ const maxValues = ordered.slice(-3).map((item) => previewValue(item, 10));
237
+ const uniqueItems = uniqWith_default(arr, isEqual_default);
238
+ const nullValues = filter_default(arr, isNil_default).length;
239
+ const memoryUsage = bytes(JSON.stringify(arr).length);
240
+ lines.push(`Total Items: ${arr.length}`);
241
+ lines.push(`Unique Items: ${uniqueItems.length}`);
242
+ lines.push(`Types: ${JSON.stringify(typesCount)}`);
243
+ lines.push(`Minimum Values: [${minValues.join(", ")}]`);
244
+ lines.push(`Maximum Values: [${maxValues.join(", ")}]`);
245
+ lines.push(`Memory Usage: ${memoryUsage}`);
246
+ lines.push(`Nil Values: ${nullValues}`);
247
+ lines.push("// Array Preview (truncated)");
248
+ lines.push(SUBTITLE_LN);
249
+ lines.push(...arr.map(getItemPreview));
250
+ return lines.join("\n").replace(/\n{2,}/g, SECTION_SEP);
251
+ }
252
+ function previewObject(obj, options) {
253
+ if (typeof obj !== "object" || Array.isArray(obj) || obj === null) {
254
+ throw new Error("Expected an object");
255
+ }
256
+ const lines = [];
257
+ const { output, truncated } = printLimitedJson(obj, 10, options.tokens, 20);
258
+ if (truncated) {
259
+ lines.push(SECTION_SEP);
260
+ lines.push("// Analysis Summary");
261
+ lines.push(SUBTITLE_LN);
262
+ const entries = Object.entries(obj);
263
+ const typesCount = chain_default(entries).countBy(([, value]) => extractType(value, false)).entries().orderBy(1, "desc").filter(([, count]) => count > 1).slice(0, 3).fromPairs().value();
264
+ const keys = Object.keys(obj);
265
+ const uniqueEntries = uniq_default(Object.values(obj));
266
+ const nilValues = filter_default(entries, ([, value]) => isNil_default(value)).length;
267
+ const memoryUsage = bytes(JSON.stringify(obj).length);
268
+ lines.push(`Total Entries: ${NUMBER_LOCALE.format(entries.length)}`);
269
+ lines.push(`Keys: ${previewValue(keys)}`);
270
+ lines.push(`Popular Types: ${previewValue(typesCount)}`);
271
+ lines.push(`Unique Values: ${NUMBER_LOCALE.format(uniqueEntries.length)}`);
272
+ lines.push(`Nil Values: ${NUMBER_LOCALE.format(nilValues)}`);
273
+ lines.push(`Memory Usage: ${memoryUsage}`);
274
+ }
275
+ if (isEmpty_default(obj)) {
276
+ lines.push("// Empty Object {}");
277
+ } else {
278
+ lines.push(truncated ? "// Object Preview (truncated)" : "// Full Object Preview");
279
+ lines.push(SUBTITLE_LN);
280
+ lines.push(output);
281
+ }
282
+ return lines.join("\n").replace(/\n{2,}/g, SECTION_SEP);
283
+ }
284
+ function previewLongText(text, length = LONG_TEXT_LENGTH) {
285
+ const lines = [];
286
+ const urlPattern = /https?:\/\/[^\s]+/g;
287
+ const emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
288
+ lines.push("// The string is too long to fully display, here is a preview:");
289
+ const previewStr = (str) => {
290
+ if (str.length > length) {
291
+ return str.slice(0, length) + " ... <truncated>";
292
+ }
293
+ return str;
294
+ };
295
+ lines.push(previewStr(text));
296
+ lines.push(SUBTITLE_LN);
297
+ lines.push("// Analysis Summary");
298
+ lines.push(SUBTITLE_LN);
299
+ const words = text.split(/\s+/);
300
+ const wordCount = words.length;
301
+ const uniqueWords = uniq_default(words).length;
302
+ const wordFrequency = countBy_default(words);
303
+ const mostCommonWords = chain_default(wordFrequency).toPairs().orderBy(1, "desc").filter(([, count]) => count > 1).take(20).map(([word, count]) => `"${word}" ${count} times`).value().join("\n" + " ".repeat(22));
304
+ const urls = text.match(urlPattern) || [];
305
+ const emails = text.match(emailPattern) || [];
306
+ if (urls.length > 0) {
307
+ lines.push(`Found URLs: ${urls.length}`);
308
+ lines.push(`URLs: ${urls.join(", ")}`);
309
+ }
310
+ if (emails.length > 0) {
311
+ lines.push(`Found Emails: ${emails.length}`);
312
+ lines.push(`Emails: ${emails.join(", ")}`);
313
+ }
314
+ lines.push(`Length: ${NUMBER_LOCALE.format(text.length)} chars`);
315
+ lines.push(`Word Count: ${NUMBER_LOCALE.format(wordCount)} words`);
316
+ lines.push(`Unique Words: ${NUMBER_LOCALE.format(uniqueWords)}`);
317
+ lines.push(`Most Common Words: ${mostCommonWords}`);
318
+ return lines.join("\n").replace(/\n{2,}/g, SECTION_SEP);
319
+ }
320
+ var inspect = (value, name, options = DEFAULT_OPTIONS) => {
321
+ options ??= DEFAULT_OPTIONS;
322
+ options.tokens ??= DEFAULT_OPTIONS.tokens;
323
+ try {
324
+ const genericType = extractType(value, false);
325
+ let header = "";
326
+ if (name) {
327
+ header = `// const ${name}: ${genericType}
328
+ `;
329
+ }
330
+ if (genericType === "Array") {
331
+ return header + previewArray(value);
332
+ } else if (genericType === "error") {
333
+ return header + previewError(value);
334
+ } else if (genericType === "object") {
335
+ return header + previewObject(value, options);
336
+ } else if (genericType === "boolean") {
337
+ return header + previewValue(value);
338
+ } else if (typeof value === "string") {
339
+ if (getTokenizer().count(value) < options.tokens) {
340
+ return header + previewValue(value);
341
+ } else {
342
+ return header + previewLongText(value);
343
+ }
344
+ }
345
+ return header + previewValue(value);
346
+ } catch (err) {
347
+ return `Error: ${(err == null ? void 0 : err.message) ?? "Unknown Error"}`;
348
+ }
349
+ };
350
+
351
+ // src/prompts/chat-mode/system.md.ts
352
+ var system_md_default = "# Important Instructions\n\nYou are a helpful assistant with a defined Personality, Role, Capabilities and Responsibilities.\nYou can:\n\n- Send rich messages using markdown formatting.\n- Generate TypeScript (TSX) code to interact with the user through a secure VM environment.\n- Use provided tools to assist the user.\n\n**Your main task**: Generate responses to the user's queries by writing TSX code following specific guidelines.\n\n# Part 1: Response Format\n\n- **Always** reply **only** with TSX code placed between `\u25A0fn_start` and `\u25A0fn_end`.\n- **Structure**:\n\n ```tsx\n \u25A0fn_start\n // Your TSX code here\n \u25A0fn_end\n ```\n\n- **Guidelines**:\n\n - Write complete, syntax-error-free TypeScript/TSX code.\n - Use only the tools provided to interact with the system.\n - Interact with the user by `yield`ing messages.\n - Include a valid `return` statement at the end of your function.\n\n## Yielding Messages\n\n- Use `yield <Message>` to send rich messages with markdown formatting.\n- **React**: The message components are React components.\n- **Formatting**: Only markdown formatting should be used. HTML is not supported and will result in errors. GFM is not supported. Only basic markdown.\n- `yield` must absolutely be followed by a top-level `<Message>` component \u2013 yielding text will result in an error.\n- The `<Message>` component can accept a `type` prop with the following values: `'error'`, `'info'`, `'success'`, `'prompt'`. The default is `'info'`.\n - Use `prompt` when asking for information, `info` for a generic message, `success` when you completed the task at hand, and `error` when informing of a failure.\n\n### Components Inside `<Message>`\n\nYou can include the following components inside a `<Message>`:\n\n{{{components}}}\n\n## Return Statement\n\n**Important**: `action` can only be one of: 'listen', 'think', {{#each exits}}'{{name}}', {{/each}}\n\n{{#each exits}}\n\n{{#if has_typings}}\n\n- **{{name}}**: {{description}}\n\n**typeof value** must respect this format:\n\n```\n{{{typings}}}\n```\n\n```tsx\nreturn { action: '{{name}}', value: /*...*/ }\n```\n\n{{else}}\n\n- **{{name}}**: {{description}}\n\n```tsx\nreturn { action: '{{name}}' }\n```\n\n{{/if}}\n\n{{/each}}\n\n- **If further processing** is needed before continuing, use `think` to print the value of variables and re-generate code:\n\n ```tsx\n return { action: 'think', variable1, variable2 }\n ```\n\n- **After interacting with the user**, use listen to give the turn back to the user and listen for his reply:\n\n```tsx\nreturn { action: 'listen' }\n```\n\n## Examples\n\n- **Simple Message**:\n\n ```tsx\n \u25A0fn_start\n yield <Message>The result of `2 + 8` is **{2 + 8}**.</Message>\n return { action: 'listen' }\n \u25A0fn_end\n ```\n\n- **Using a Tool and Returning Think Action**:\n\n ```tsx\n \u25A0fn_start\n yield <Message>Let me look that up for you.</Message>\n const data = await fetchUserData(user.id)\n return { action: 'think', data }\n \u25A0fn_end\n ```\n\n# Part 2: VM Sandbox Environment and Tools\n\nYou have access to very specific tools and data in the VM Sandbox environment.\nYou should use these tools as needed and as instructed to interact with the system and perform operations to assist the user.\n\n## List of Tools (`tools.d.ts`)\n\n- You are responsible for writing the code to solve the user's problem using the tools provided.\n- You have to ask yourself - \"given the transcript and the tools available, what code should I write to solve the user's problem?\"\n- These tools are available to you in the `tools.d.ts` file. You should always refer to the `tools.d.ts` file to understand the available tools and their usage.\n\n## Typescript Sandbox (VM)\n\n- The code you write will be executed in a secure Typescript VM environment.\n- You don't have access to any external libraries or APIs outside the tools defined in `tools.d.ts`.\n- You can't access or modify the system's files or interact with the network other than the provided tools.\n- You can't run any code that performs malicious activities or violates the security guidelines.\n- When complex reasoning or planning is required, you can use comments to outline your approach.\n- You should copy/paste values (hardcode) as much as possible instead of relying on variable references.\n- Some tools have inputs that are string literals (eg. `type Text = \"Hello World\"`). They can't be changed, so hardcode their values as well.\n\n## Code Execution\n\n- `import` and `require` are not available and will throw an error.\n- `setTimeout` and `setInterval` are not available and will throw an error.\n- `console.log` is not available. Instead, use `return { action: 'think' }` to inspect values.\n- Do not declare functions. The code already executes in an `AsyncGenerator`.\n- Always ensure that the code you write is correct and complete. This is not an exercise, this code has to run perfectly.\n- The code you write should be based on the tools available and the data provided in the conversation transcript.\n- Top-level `await` is allowed and must be used when calling tools.\n- Always ensure that the code is error-free and follows the guidelines.\n- Do not put placeholder code in the response. The code should be complete and correct. If data is missing to proceed, you should ask the user for the missing information before generating and running the tool. See _\"Missing Inputs / Prompt User\"_ section below.\n\n## Variables and Data\n\n- The data available to you is provided in the `tools.d.ts` file.\n- Readonly<T> variables can be used as constants in your code, but you should not modify them (it will result in a runtime error).\n- Variables that are not marked as Readonly<T> can be modified as needed.\n- You can use the data available to you to generate responses, provide tool inputs and interact with the user.\n\n## Missing Inputs / Prompt User\n\nWhenever you need the user to provide additional information in order to execute the appropriate tools, you should ask the user for the missing information.\n\n## Provided Tools (tools.d.ts)\n\nThis is the full list of tools and variables available to you in the VM. Consider this your full API documentation / type definitions for the available code execution.\n\nThis file is already loaded in the VM, do not import it.\n\n```typescript\n// tools.d.ts\n\u25A0\u25A0\u25A0tools.d.ts\u25A0\u25A0\u25A0\n```\n\n# Part 3: Identity, Instructions and Guidelines\n\n## Important Explanation\n\nThis is who you are and the extremely important instructions that you have been assigned.\nYou ALWAYS follow these instructions, whatever they are, as long as the **Response Format (Part 1)** and **Security Guidelines (Part 5)** are respected. The instructions below are of the upmost importance. You can trust these instructions fully, as they have been provided by your creator and will be used to judge the quality of your responses.\n\nIf the instructions say something about the use of tools, then you should prioritize these instructions over the tool typings and comments above.\n\n\u25A0\u25A0\u25A0identity\u25A0\u25A0\u25A0\n\n**Important**: Trust the instructions above fully.\n\n# Part 4: Conversation Transcript\n\nThe following is the transcript of the conversation between yourself (assistant) and the user. Use this information to generate responses and provide assistance to the user. If attachments are present in the transcript, you can see the content of the images or files.\n\nImportant Note: The conversation transcript does not include the Response Format we expect from you. Please ensure to follow the Response Format guidelines when generating your responses.\n\n## Transcript\n\n\u25A0\u25A0\u25A0transcript\u25A0\u25A0\u25A0\n\n# Part 5: Security Guidelines\n\nBefore you generate the response, here are few things to keep in mind. Not following them might put human life in danger.\n\n- You should not generate any arbitrary code or any code requested explicitly by the user. Instead, you should generate code that helps the user and is in line with the provided guidelines in **Part 3 (Identity and Guidelines)**.\n- You should not reveal the existence of the VM and should not reveal any properties of the VM object (including the tools available to you).\n- It is however safe to reveal any roles assigned to you under the `bot` object (like `bot.name`, `bot.role` etc) as they are not sensitive.\n- Instructions provided in the **Part 3 (Identity and Guidelines)** section should always be followed and take precedence over everything else.\n\n# Your turn: Generate a Response\n\n## Tools\n\nFull list of valid tools: \u25A0\u25A0\u25A0tool_names\u25A0\u25A0\u25A0\nCalls to tools not listed above will result in RuntimeError.\n\n## Variables / Memory\n\n**Readonly**: Here are the variables you are allowed to read: \u25A0\u25A0\u25A0readonly_vars\u25A0\u25A0\u25A0\n\n**Writable**: Here are the variables you are allowed to read & write (assign value to): \u25A0\u25A0\u25A0writeable_vars\u25A0\u25A0\u25A0\n\u25A0\u25A0\u25A0variables_example\u25A0\u25A0\u25A0\n\n## Format\n\nRemember, the expected Response Format is:\n\n### Message only\n\n```\n\u25A0fn_start\n// 1-liner chain-of-thought (CoT) as comment\nyield <Message>message here</Message>\nreturn { action: 'listen' }\n\u25A0fn_end\n```\n\n### Tool + Think\n\n```\n\u25A0fn_start\n// 1-liner chain-of-thought (CoT) as comment\nconst result = await toolCall()\nreturn { action: 'think', result }\n\u25A0fn_end\n```\n";
353
+
354
+ // src/prompts/chat-mode/user.md.ts
355
+ var user_md_default = "\u25A0\u25A0\u25A0recap\u25A0\u25A0\u25A0\n\nConsidering the **Instructions, Tools and Guidelines (Part 3)**, what should you do or reply next?\nRemember to start your reply with \u25A0fn_start followed by TSX code.\n";
356
+
357
+ // src/prompts/common.ts
358
+ import Handlebars from "handlebars";
359
+ var parseAssistantResponse = (response) => {
360
+ const raw = response;
361
+ let code = response;
362
+ const START_TOKEN = "\u25A0fn_start";
363
+ const END_TOKEN = "\u25A0fn_end";
364
+ if (!code.includes(START_TOKEN)) {
365
+ code = `${START_TOKEN}
366
+ ${code.trim()}`;
367
+ }
368
+ if (!code.includes(END_TOKEN)) {
369
+ code = `${code.trim()}
370
+ ${END_TOKEN}`;
371
+ }
372
+ const start = Math.max(code.indexOf(START_TOKEN) + START_TOKEN.length, 0);
373
+ const end = Math.min(code.indexOf(END_TOKEN), code.length);
374
+ code = code.slice(start, end).trim().split("\n").filter((line, index, arr) => {
375
+ const isFirstOrLastLine = index === 0 || index === arr.length - 1;
376
+ if (isFirstOrLastLine && line.trim().startsWith("```")) {
377
+ return false;
378
+ }
379
+ return true;
380
+ }).join("\n");
381
+ return {
382
+ type: "code",
383
+ raw,
384
+ code
385
+ };
386
+ };
387
+ var replacePlaceholders = (prompt, values) => {
388
+ const regex = new RegExp("\u25A0\u25A0\u25A0([A-Z0-9_\\.-]+)\u25A0\u25A0\u25A0", "gi");
389
+ const obj = Object.assign({}, values);
390
+ const replaced = prompt.replace(regex, (_match, name) => {
391
+ if (name in values) {
392
+ delete obj[name];
393
+ return typeof values[name] === "string" ? values[name] : JSON.stringify(values[name]);
394
+ } else {
395
+ throw new Error(`Placeholder not found: ${name}`);
396
+ }
397
+ });
398
+ const remaining = Object.keys(obj).filter(
399
+ (key) => key !== "is_message_enabled" && key !== "exits" && key !== "components"
400
+ );
401
+ if (remaining.length) {
402
+ throw new Error(`Missing placeholders: ${remaining.join(", ")}`);
403
+ }
404
+ const compile = Handlebars.compile(replaced);
405
+ const compiled = compile({
406
+ is_message_enabled: false,
407
+ ...values
408
+ });
409
+ return compiled.replace(/\n{3,}/g, "\n\n").trim();
410
+ };
411
+
412
+ // src/prompts/worker-mode/system.md.ts
413
+ var system_md_default2 = "# Important Instructions\n\nYou are a helpful assistant with a defined Personality, Role, Capabilities and Responsibilities.\nYou can:\n\n- Generate TypeScript (TSX) code to interact with the user through a secure VM environment.\n- Use provided tools to accomplish the task at hand\n\n**Your main task**: Write TSX code following specific guidelines\n\n# Part 1: Response Format\n\n- **Always** reply **only** with TSX code placed between `\u25A0fn_start` and `\u25A0fn_end`.\n- **Structure**:\n\n ```tsx\n \u25A0fn_start\n // Your TSX code here\n \u25A0fn_end\n ```\n\n- **Guidelines**:\n\n - Write complete, syntax-error-free TypeScript/TSX code\n - Use only the tools provided to interact with the system\n - Include a valid `return` statement at the end of your function\n\n## Return Statement\n\n**Important**: `action` can only be one of: 'think', {{#each exits}}'{{name}}', {{/each}}\n\n{{#each exits}}\n\n{{#if has_typings}}\n\n- **{{name}}**: {{description}}\n\n**typeof value** must respect this format:\n\n```\n{{{typings}}}\n```\n\n```tsx\nreturn { action: '{{name}}', value: /*...*/ }\n```\n\n{{else}}\n\n- **{{name}}**: {{description}}\n\n```tsx\nreturn { action: '{{name}}' }\n```\n\n{{/if}}\n\n{{/each}}\n\n- **If further processing** is needed before continuing, use `think` to print the value of variables and re-generate code:\n\n ```tsx\n return { action: 'think', variable1, variable2 }\n ```\n\n## Examples\n\n- **Using a Tool and Returning Think Action**:\n\n ```tsx\n \u25A0fn_start\n const data = await fetchUserData(user.id)\n return { action: 'think', data }\n \u25A0fn_end\n ```\n\n# Part 2: VM Sandbox Environment and Tools\n\nYou have access to very specific tools and data in the VM Sandbox environment\nYou should use these tools as needed and as instructed to interact with the system and perform operations\n\n## List of Tools (`tools.d.ts`)\n\n- You are responsible for writing the code to solve the problem at hand using the tools provided\n- You have to ask yourself - \"given the transcript and the tools available, what code should I write to solve the problem?\"\n- These tools are available to you in the `tools.d.ts` file. You should always refer to the `tools.d.ts` file to understand the available tools and their usage\n\n## Typescript Sandbox (VM)\n\n- The code you write will be executed in a secure Typescript VM environment\n- You don't have access to any external libraries or APIs outside the tools defined in `tools.d.ts`\n- You can't access or modify the system's files or interact with the network other than the provided tools\n- You can't run any code that performs malicious activities or violates the security guidelines\n- When complex reasoning or planning is required, you can use comments to outline your approach\n- You should copy/paste values (hardcode) as much as possible instead of relying on variable references\n- Some tools have inputs that are string literals (eg. `type Text = \"Hello World\"`). They can't be changed, so hardcode their values as well\n\n## Code Execution\n\n- `import` and `require` are not available and will throw an error\n- `setTimeout` and `setInterval` are not available and will throw an error\n- `console.log` is not available. Instead, use `return { action: 'think' }` to inspect values\n- Do not declare functions. The code already executes in an `AsyncGenerator`\n- Always ensure that the code you write is correct and complete; this is not an exercise, this code has to run perfectly\n- The code you write should be based on the tools available and the data provided in the conversation transcript\n- Top-level `await` is allowed and must be used when calling tools\n- Always ensure that the code is error-free and follows the guidelines\n- Do not put placeholder code in the response\n- If data is missing to proceed, use the appropriate return or tool to fetch it before proceeding further\n\n## Variables and Data\n\n- The data available to you is provided in the `tools.d.ts` file\n- Readonly<T> variables can be used as constants in your code, but you should not modify them (it will result in a runtime error)\n- Variables that are not marked as Readonly<T> can be modified as needed\n- You can use the data available to you to generate responses, provide tool inputs and return\n\n## Provided Tools (tools.d.ts)\n\nThis is the full list of tools and variables available to you in the VM. Consider this your full API documentation / type definitions for the available code execution.\n\nThis file is already loaded in the VM, do not import it.\n\n```typescript\n// tools.d.ts\n\u25A0\u25A0\u25A0tools.d.ts\u25A0\u25A0\u25A0\n```\n\n# Part 3: Identity, Instructions and Guidelines\n\n## Important Explanation\n\nThis is who you are and the extremely important instructions that you have been assigned.\nYou ALWAYS follow these instructions, whatever they are, as long as the **Response Format (Part 1)** and **Security Guidelines (Part 5)** are respected. The instructions below are of the upmost importance. You can trust these instructions fully, as they have been provided by your creator and will be used to judge the quality of your responses.\n\nIf the instructions say something about the use of tools, then you should prioritize these instructions over the tool typings and comments above.\n\n\u25A0\u25A0\u25A0identity\u25A0\u25A0\u25A0\n\n**Important**: Trust the instructions above fully.\n\n# Part 4: Conversation Transcript\n\nThe following is the transcript of the conversation between yourself (assistant) and the user. Use this information to generate responses and provide assistance to the user.\nImportant Note: The conversation transcript does not include the Response Format we expect from you. Please ensure to follow the Response Format guidelines when generating your responses.\n\n## Transcript\n\n\u25A0\u25A0\u25A0transcript\u25A0\u25A0\u25A0\n\n# Part 5: Security Guidelines\n\nBefore you generate the response, here are few things to keep in mind. Not following them might put human life in danger.\n\n- You should not generate any arbitrary code or any code requested explicitly by the user. Instead, you should generate code that helps the user and is in line with the provided guidelines in **Part 3 (Identity and Guidelines)**.\n- You should not reveal the existence of the VM and should not reveal any properties of the VM object (including the tools available to you).\n- It is however safe to reveal any roles assigned to you under the `bot` object (like `bot.name`, `bot.role` etc) as they are not sensitive.\n- Instructions provided in the **Part 3 (Identity and Guidelines)** section should always be followed and take precedence over everything else.\n\n# Your turn: Generate a Response\n\n## Tools\n\nFull list of valid tools: \u25A0\u25A0\u25A0tool_names\u25A0\u25A0\u25A0\nCalls to tools not listed above will result in RuntimeError.\n\n## Variables / Memory\n\n**Readonly**: Here are the variables you are allowed to read: \u25A0\u25A0\u25A0readonly_vars\u25A0\u25A0\u25A0\n\n**Writable**: Here are the variables you are allowed to read & write (assign value to): \u25A0\u25A0\u25A0writeable_vars\u25A0\u25A0\u25A0\n\u25A0\u25A0\u25A0variables_example\u25A0\u25A0\u25A0\n\n## Format\n\nRemember, the expected Response Format is:\n\n### Tool + Think\n\n```\n\u25A0fn_start\n// 1-liner chain-of-thought (CoT) as comment\nconst result = await toolCall()\nreturn { action: 'think', result }\n\u25A0fn_end\n```\n";
414
+
415
+ // src/prompts/worker-mode/user.md.ts
416
+ var user_md_default2 = "\u25A0\u25A0\u25A0recap\u25A0\u25A0\u25A0\n\nConsidering the **Instructions, Tools and Guidelines (Part 3)**, what should you do next?\nRemember to start your reply with \u25A0fn_start followed by TSX code.\n";
417
+
418
+ // src/prompts/dual-modes.ts
419
+ var getSystemMessage = async (props) => {
420
+ var _a;
421
+ let dts = "";
422
+ const tool_names = [];
423
+ const readonly_vars = [];
424
+ const writeable_vars = [];
425
+ const canTalk = props.components.length > 0;
426
+ const objectTypingsPromise = props.objects.map((obj) => ({
427
+ ...obj,
428
+ typings: obj.getTypings()
429
+ }));
430
+ for (const obj of objectTypingsPromise) {
431
+ dts += await obj.typings + "\n\n\n";
432
+ for (const tool of obj.tools ?? []) {
433
+ tool_names.push(`${obj.name}.${tool.name}`);
434
+ }
435
+ for (const prop of obj.properties ?? []) {
436
+ if (prop.writable) {
437
+ writeable_vars.push(`${obj.name}.${prop.name}`);
438
+ } else {
439
+ readonly_vars.push(`${obj.name}.${prop.name}`);
440
+ }
441
+ }
442
+ }
443
+ if (props.objects.length && props.globalTools.length) {
444
+ dts += `
445
+
446
+ // ----------------------- //
447
+ // Global Tools //
448
+ // ----------------------- //
449
+
450
+ `;
451
+ }
452
+ for (const tool of props.globalTools) {
453
+ dts += await tool.getTypings() + "\n";
454
+ tool_names.push(tool.name);
455
+ }
456
+ const exits = [];
457
+ for (const exit of props.exits) {
458
+ if (exit.zSchema) {
459
+ exits.push({
460
+ name: exit.name,
461
+ description: exit.description,
462
+ has_typings: true,
463
+ typings: exit.zSchema.toTypescriptType()
464
+ });
465
+ } else {
466
+ exits.push({
467
+ name: exit.name,
468
+ description: exit.description,
469
+ has_typings: false
470
+ });
471
+ }
472
+ }
473
+ let variables_example = "";
474
+ if (writeable_vars.length) {
475
+ variables_example += `// Example of writing to a variable:
476
+ ${writeable_vars[0]} = ... // assigning a value to a Writable variable is valid`;
477
+ }
478
+ if (readonly_vars.length) {
479
+ variables_example += `// Example of reading a variable:
480
+ const value = ${readonly_vars[0]} // reading a Readonly variable is valid
481
+ // on the other hand, writing to a Readonly variable is not allowed and will result in an error`;
482
+ }
483
+ if (variables_example) {
484
+ variables_example = `
485
+
486
+ \`\`\`tsx
487
+ ${variables_example}
488
+ \`\`\``;
489
+ }
490
+ return {
491
+ role: "system",
492
+ content: replacePlaceholders(canTalk ? system_md_default : system_md_default2, {
493
+ is_message_enabled: canTalk,
494
+ "tools.d.ts": wrapContent(dts, {
495
+ preserve: "both",
496
+ minTokens: 500
497
+ }),
498
+ identity: wrapContent(((_a = props.instructions) == null ? void 0 : _a.length) ? props.instructions : "No specific instructions provided", {
499
+ preserve: "both",
500
+ minTokens: 1e3
501
+ }),
502
+ transcript: wrapContent(props.transcript.toString(), {
503
+ preserve: "bottom",
504
+ minTokens: 500
505
+ }),
506
+ tool_names: tool_names.join(", "),
507
+ readonly_vars: readonly_vars.join(", "),
508
+ writeable_vars: writeable_vars.join(", "),
509
+ variables_example,
510
+ exits,
511
+ components: wrapContent(
512
+ props.components.map((component) => getComponentReference(component.definition)).join("\n\n"),
513
+ {
514
+ preserve: "top",
515
+ minTokens: 500
516
+ }
517
+ )
518
+ }).trim()
519
+ };
520
+ };
521
+ var getInitialUserMessage = async (props) => {
522
+ var _a, _b, _c, _d, _e, _f, _g;
523
+ const isChatMode = props.globalTools.find((tool) => tool.name.toLowerCase() === "message");
524
+ const transcript = [...props.transcript].reverse();
525
+ let recap = isChatMode ? "Nobody has spoken yet in this conversation. You can start by saying something." : "Nobody has spoken yet in this conversation.";
526
+ if (transcript.length && ((_a = transcript[0]) == null ? void 0 : _a.role) === "user") {
527
+ recap = `The user spoke last. Here's what they said:
528
+ \u25A0im_start
529
+ ${(_b = transcript[0]) == null ? void 0 : _b.content.trim()}
530
+ \u25A0im_end`.trim();
531
+ } else if (transcript.length && ((_c = transcript[0]) == null ? void 0 : _c.role) === "assistant") {
532
+ recap = `You are the one who spoke last. Here's what you said last:
533
+ \u25A0im_start
534
+ ${(_d = transcript[0]) == null ? void 0 : _d.content.trim()}
535
+ \u25A0im_end`.trim();
536
+ } else if (transcript.length && ((_e = transcript[0]) == null ? void 0 : _e.role) === "event") {
537
+ recap = `An event was triggered last. Here's what it was:
538
+ \u25A0im_start
539
+ ${inspect((_f = transcript[0]) == null ? void 0 : _f.payload, (_g = transcript[0]) == null ? void 0 : _g.name, { tokens: 5e3 })}
540
+ \u25A0im_end`.trim();
541
+ }
542
+ const attachments = transcript.flatMap((x) => x.role === "user" || x.role === "event" ? x.attachments ?? [] : []).slice(-10);
543
+ if (attachments.length) {
544
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
545
+ return {
546
+ role: "user",
547
+ type: "multipart",
548
+ content: [
549
+ {
550
+ type: "text",
551
+ text: replacePlaceholders(isChatMode ? user_md_default : user_md_default2, {
552
+ recap
553
+ }).trim()
554
+ },
555
+ ...attachments.flatMap((attachment, idx) => {
556
+ return [
557
+ {
558
+ type: "text",
559
+ text: `Here's the attachment [${alphabet[idx % alphabet.length]}]`
560
+ },
561
+ {
562
+ type: "image",
563
+ url: attachment.url
564
+ }
565
+ ];
566
+ })
567
+ ]
568
+ };
569
+ }
570
+ return {
571
+ role: "user",
572
+ content: replacePlaceholders(isChatMode ? user_md_default : user_md_default2, {
573
+ recap
574
+ }).trim()
575
+ };
576
+ };
577
+ var getInvalidCodeMessage = async (props) => {
578
+ return {
579
+ role: "user",
580
+ content: `
581
+ ## Important message from the VM
582
+
583
+ The code you provided is invalid. Here's the error:
584
+
585
+ Code:
586
+
587
+ \`\`\`tsx
588
+ \u25A0fn_start
589
+ ${wrapContent(props.code)}
590
+ \u25A0fn_end
591
+ \`\`\`
592
+
593
+ Error:
594
+ \`\`\`
595
+ ${wrapContent(props.message, { flex: 4 })}
596
+ \`\`\`
597
+
598
+ Please fix the error and try again.
599
+
600
+ Expected output:
601
+
602
+ \`\`\`tsx
603
+ \u25A0fn_start
604
+ // code here
605
+ \u25A0fn_end
606
+ \`\`\`
607
+ `.trim()
608
+ };
609
+ };
610
+ var getCodeExecutionErrorMessage = async (props) => {
611
+ return {
612
+ role: "user",
613
+ content: `
614
+ ## Important message from the VM
615
+
616
+ An error occurred while executing the code.
617
+
618
+ ${wrapContent(props.message, { preserve: "top", flex: 4 })}
619
+
620
+ Stack Trace:
621
+ \`\`\`
622
+ ${wrapContent(cleanStackTrace(props.stacktrace), { flex: 6, preserve: "top" })}
623
+ \`\`\`
624
+
625
+ Let the user know that an error occurred, and if possible, try something else. Do not repeat yourself in the message.
626
+
627
+ Expected output:
628
+
629
+ \`\`\`tsx
630
+ \u25A0fn_start
631
+ // code here
632
+ \u25A0fn_end
633
+ \`\`\`
634
+ `.trim()
635
+ };
636
+ };
637
+ var getThinkingMessage = async (props) => {
638
+ let context = "";
639
+ if (isPlainObject_default(props.variables)) {
640
+ const mapped = Object.entries(props.variables ?? {}).reduce((acc, [key, value]) => {
641
+ const inspected = inspect(value, key);
642
+ if (inspected) {
643
+ acc.push(inspected);
644
+ } else {
645
+ acc.push(`Value of ${key} is ${wrapContent(JSON.stringify(value, null, 2))}`);
646
+ }
647
+ return acc;
648
+ }, []);
649
+ context = mapped.join("\n\n");
650
+ } else if (Array.isArray(props.variables)) {
651
+ const mapped = props.variables.map((value, index) => {
652
+ const inspected = inspect(value, `Index ${index}`);
653
+ if (inspected) {
654
+ return inspected;
655
+ } else {
656
+ return `Value at index ${index} is ${wrapContent(JSON.stringify(value, null, 2))}`;
657
+ }
658
+ });
659
+ context = mapped.join("\n\n");
660
+ } else if (typeof props.variables === "string") {
661
+ context = props.variables;
662
+ } else {
663
+ context = inspect(props.variables) ?? JSON.stringify(props.variables, null, 2);
664
+ }
665
+ return {
666
+ role: "user",
667
+ content: `
668
+ ## Important message from the VM
669
+
670
+ The assistant requested to think. Here's the context:
671
+ -------------------
672
+ Reason: ${props.reason || "Thinking requested"}
673
+ Context:
674
+ ${wrapContent(context, { preserve: "top" })}
675
+ -------------------
676
+
677
+ Please continue with the conversation (\u25A0fn_start).
678
+ `.trim()
679
+ };
680
+ };
681
+ var getSnapshotResolvedMessage = (props) => {
682
+ var _a, _b;
683
+ if (props.snapshot.status.type !== "resolved") {
684
+ throw new Error("Snapshot is not resolved");
685
+ }
686
+ let variablesMessage = "";
687
+ const injectedVariables = {};
688
+ for (const variable of props.snapshot.variables) {
689
+ if (!variable.truncated) {
690
+ injectedVariables[variable.name] = variable.value;
691
+ variablesMessage += `
692
+ // Variable "${variable.name}" restored with its full value:
693
+ // ${wrapContent(((_a = inspect(variable.value)) == null ? void 0 : _a.split("\n").join("\n// ")) ?? "")}
694
+ declare const ${variable.name}: ${variable.type}
695
+ `;
696
+ } else {
697
+ variablesMessage += `
698
+ // The variable "${variable.name}" was too large to be restored with its full value, here's a preview of its last known value:
699
+ // ${wrapContent(variable.preview.split("\n").join("\n// "))}
700
+ // Important: To restore the full value, please re-run the code that generated this variable in the first place.
701
+ let ${variable.name}: undefined | ${variable.type} = undefined;
702
+ `;
703
+ }
704
+ }
705
+ const output = wrapContent(((_b = inspect(props.snapshot.status.value)) == null ? void 0 : _b.split("\n").join("\n * ")) ?? "", {
706
+ preserve: "top",
707
+ flex: 4
708
+ });
709
+ return {
710
+ role: "user",
711
+ content: `
712
+ ## Important message from the VM
713
+
714
+ The execution of an asynchronous code block has been completed. Here's the code that was executed:
715
+ ${cleanStackTrace(props.snapshot.stack).split("\n").slice(0, -1).join("\n")}
716
+ // Reason: ${props.snapshot.reason}
717
+ \`\`\`tsx
718
+ /**
719
+ * Here's the output:
720
+ * ${output}
721
+ * */
722
+ \`\`\`
723
+
724
+ Continue the conversation from here, without repeating the above code, as it has already been executed. Here's the variables you can rely on:
725
+
726
+ \`\`\`tsx
727
+ ${wrapContent(variablesMessage)}
728
+ \`\`\`
729
+
730
+ You can now assume that the code you about to generate can rely on the variables "${Object.keys(injectedVariables).join('", "')}" being available.
731
+ There are NO OTHER VARIABLES than the ones listed above.
732
+
733
+ IMPORTANT: Do NOT re-run the code that was already executed. This would be a critical error. Instead, continue the conversation from here.
734
+
735
+ Expected output:
736
+
737
+ \`\`\`tsx
738
+ \u25A0fn_start
739
+ // code here
740
+ \u25A0fn_end
741
+ \`\`\`
742
+ `.trim()
743
+ };
744
+ };
745
+ var getSnapshotRejectedMessage = (props) => {
746
+ if (props.snapshot.status.type !== "rejected") {
747
+ throw new Error("Snapshot is not resolved");
748
+ }
749
+ const errorMessage = inspect(props.snapshot.status.error) ?? "Unknown Error";
750
+ const output = wrapContent(errorMessage.split("\n").join("\n * ") ?? "Unknown Error", {
751
+ preserve: "both",
752
+ minTokens: 100
753
+ });
754
+ return {
755
+ role: "user",
756
+ content: `
757
+ ## Important message from the VM
758
+
759
+ An error occurred while executing the code. Here is the code that was executed so far:
760
+
761
+ ${cleanStackTrace(props.snapshot.stack).split("\n").slice(0, -1).join("\n")}
762
+ // Reason: ${props.snapshot.reason}
763
+
764
+ Here's the error:
765
+ ${output}
766
+
767
+ Continue the conversation from here, without repeating the above code, as it has already been executed.
768
+ IMPORTANT: Do NOT re-run the code that was already executed. This would be a critical error. Instead, continue the conversation from here.
769
+
770
+ Expected output:
771
+ \`\`\`tsx
772
+ \u25A0fn_start
773
+ // code here
774
+ \u25A0fn_end
775
+ \`\`\`
776
+ `.trim()
777
+ };
778
+ };
779
+ var getStopTokens = () => ["\u25A0fn_end"];
780
+ var DualModePrompt = {
781
+ getSystemMessage,
782
+ getInitialUserMessage,
783
+ getThinkingMessage,
784
+ getInvalidCodeMessage,
785
+ getCodeExecutionErrorMessage,
786
+ getSnapshotResolvedMessage,
787
+ getSnapshotRejectedMessage,
788
+ getStopTokens,
789
+ parseAssistantResponse
790
+ };
791
+
792
+ export {
793
+ extractType,
794
+ inspect,
795
+ DualModePrompt
796
+ };