llmz 0.0.10 → 0.0.12

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 +3 -3
package/dist/index.js ADDED
@@ -0,0 +1,921 @@
1
+ import {
2
+ DefaultExit,
3
+ ErrorExecutionResult,
4
+ ExecutionResult,
5
+ ListenExit,
6
+ PartialExecutionResult,
7
+ Snapshot,
8
+ SuccessExecutionResult,
9
+ ThinkExit,
10
+ getValue
11
+ } from "./chunk-PRVFVXT4.js";
12
+ import "./chunk-KH6JQYQA.js";
13
+ import {
14
+ Tool
15
+ } from "./chunk-JAGB2AOU.js";
16
+ import {
17
+ formatTypings,
18
+ getTypings
19
+ } from "./chunk-IH2WQFO5.js";
20
+ import {
21
+ CodeFormattingError,
22
+ LoopExceededError,
23
+ SnapshotSignal,
24
+ ThinkSignal
25
+ } from "./chunk-JKVVQN2P.js";
26
+ import "./chunk-JQBT7UWN.js";
27
+ import {
28
+ Exit
29
+ } from "./chunk-JMSZKB4T.js";
30
+ import {
31
+ Component,
32
+ assertValidComponent,
33
+ isAnyComponent,
34
+ isComponent,
35
+ renderToTsx
36
+ } from "./chunk-GGWM6X2K.js";
37
+ import "./chunk-ORQP26SZ.js";
38
+ import "./chunk-SNDVQU5A.js";
39
+ import {
40
+ escapeString,
41
+ getMultilineComment,
42
+ isValidIdentifier
43
+ } from "./chunk-4MNIJGK6.js";
44
+ import {
45
+ cloneDeep_default,
46
+ upperFirst_default
47
+ } from "./chunk-7WRN4E42.js";
48
+
49
+ // src/objects.ts
50
+ import { z } from "@bpinternal/zui";
51
+
52
+ // src/hoist.ts
53
+ import { CodeGenerator } from "@babel/generator";
54
+ import { parse } from "@babel/parser";
55
+ import Traverse from "@babel/traverse";
56
+ import * as t from "@babel/types";
57
+ var traverse = Traverse;
58
+ function getTypingsWithoutComments(type) {
59
+ const typeClone = cloneDeep_default(type);
60
+ removeBabelComments(typeClone);
61
+ return new CodeGenerator(typeClone, { comments: false }).generate().code;
62
+ }
63
+ function removeBabelComments(node) {
64
+ node.leadingComments = null;
65
+ node.trailingComments = null;
66
+ node.innerComments = null;
67
+ Object.keys(node).forEach((key) => {
68
+ const val = node[key];
69
+ if (Array.isArray(val)) {
70
+ val.forEach((child) => child && typeof child === "object" && removeBabelComments(child));
71
+ } else if (val && typeof val === "object" && val.type) {
72
+ removeBabelComments(val);
73
+ }
74
+ });
75
+ }
76
+ function extractAndHoistTypes(ast) {
77
+ const typeMap = /* @__PURE__ */ new Map();
78
+ const typeCounts = /* @__PURE__ */ new Map();
79
+ const hoistedTypes = [];
80
+ function addTypeToMap(typeNode) {
81
+ const typeString = getTypingsWithoutComments(typeNode.typeAnnotation);
82
+ if (!typeMap.has(typeString)) {
83
+ typeMap.set(typeString, typeNode);
84
+ }
85
+ }
86
+ function generateUniqueTypeName(baseName) {
87
+ let typeName = baseName;
88
+ let counter = 1;
89
+ while ([...typeMap.values()].some((typeNode) => typeNode.id.name === typeName)) {
90
+ typeName = `${baseName}${counter++}`;
91
+ }
92
+ return typeName;
93
+ }
94
+ function createTypeAlias(name, type) {
95
+ return t.tsTypeAliasDeclaration(t.identifier(name), null, type);
96
+ }
97
+ function getTypePaths(path) {
98
+ var _a, _b, _c;
99
+ let currPath = path;
100
+ const parts = /* @__PURE__ */ new Set();
101
+ while (currPath) {
102
+ const { node, parentPath } = currPath;
103
+ if (t.isIdentifier(node) && node.name) {
104
+ parts.add(node.name);
105
+ }
106
+ if (t.isTSMethodSignature(node) && currPath.key === "parameters") {
107
+ parts.add("Input");
108
+ }
109
+ if (currPath.key === "returnType") {
110
+ parts.add("Output");
111
+ const methodName = "id" in parentPath.node && "name" in parentPath.node.id && ((_b = (_a = parentPath == null ? void 0 : parentPath.node) == null ? void 0 : _a.id) == null ? void 0 : _b.name);
112
+ if (methodName) {
113
+ parts.add(methodName);
114
+ }
115
+ }
116
+ if (((_c = node == null ? void 0 : node.key) == null ? void 0 : _c.type) === "Identifier") {
117
+ parts.add(node.key.name);
118
+ }
119
+ if (t.isTSParameterProperty(node) || t.isTSFunctionType(node)) {
120
+ parts.add("Input");
121
+ }
122
+ if (t.isTSFunctionType(node)) {
123
+ parts.add("Output");
124
+ }
125
+ currPath = parentPath;
126
+ }
127
+ return parts.size ? Array.from(parts).reverse().map(upperFirst_default) : ["UnnamedType"];
128
+ }
129
+ function generateTypeName(path) {
130
+ return getTypePaths(path).join("");
131
+ }
132
+ function findNestedTypes(path) {
133
+ const node = path.node;
134
+ if (t.isTSTypeLiteral(node)) {
135
+ const typeString = getTypingsWithoutComments(node);
136
+ typeCounts.set(typeString, (typeCounts.get(typeString) || 0) + 1);
137
+ if (typeMap.has(typeString) && (typeCounts.get(typeString) || 0) > 1) {
138
+ path.replaceWith(t.tsTypeReference(typeMap.get(typeString).id));
139
+ } else if (!typeMap.has(typeString) && (typeCounts.get(typeString) || 0) > 1) {
140
+ const typeName = generateUniqueTypeName(generateTypeName(path));
141
+ const typeAlias = createTypeAlias(typeName, node);
142
+ addTypeToMap(typeAlias);
143
+ path.replaceWith(t.tsTypeReference(t.identifier(typeName)));
144
+ }
145
+ const members = path.get("members");
146
+ const memberPaths = Array.isArray(members) ? members : [members];
147
+ memberPaths.forEach((memberPath) => {
148
+ findNestedTypes(memberPath);
149
+ });
150
+ }
151
+ if (t.isTSPropertySignature(node) && path.get("typeAnnotation")) {
152
+ const annPath = path.get("typeAnnotation.typeAnnotation");
153
+ if (annPath == null ? void 0 : annPath.node) {
154
+ findNestedTypes(annPath);
155
+ }
156
+ }
157
+ if (t.isTSArrayType(node)) {
158
+ findNestedTypes(path.get("elementType"));
159
+ }
160
+ if (t.isTSUnionType(node) || t.isTSIntersectionType(node)) {
161
+ ;
162
+ path.get("types").forEach((p) => findNestedTypes(p));
163
+ }
164
+ if (t.isTSTypeReference(node) && node.typeParameters) {
165
+ ;
166
+ path.get("typeParameters.params").forEach((param) => findNestedTypes(param));
167
+ }
168
+ if (t.isTSFunctionType(node)) {
169
+ const returnPath = path.get("typeAnnotation");
170
+ if (returnPath == null ? void 0 : returnPath.node)
171
+ findNestedTypes(returnPath);
172
+ const params = path.get("parameters");
173
+ params.forEach((paramPath) => {
174
+ const ta = paramPath.get("typeAnnotation.typeAnnotation");
175
+ if (ta == null ? void 0 : ta.node)
176
+ findNestedTypes(ta);
177
+ });
178
+ }
179
+ if (t.isTSMethodSignature(node)) {
180
+ const returnPath = path.get("typeAnnotation");
181
+ if (returnPath == null ? void 0 : returnPath.node) {
182
+ findNestedTypes(returnPath);
183
+ }
184
+ const params = path.get("parameters");
185
+ params.forEach((paramPath) => {
186
+ const ta = paramPath.get("typeAnnotation.typeAnnotation");
187
+ if (ta == null ? void 0 : ta.node)
188
+ findNestedTypes(ta);
189
+ });
190
+ }
191
+ if (t.isTSDeclareFunction(node)) {
192
+ const params = path.get("params");
193
+ params.forEach((p) => {
194
+ const ta = p.get("typeAnnotation.typeAnnotation");
195
+ if (ta == null ? void 0 : ta.node)
196
+ findNestedTypes(ta);
197
+ });
198
+ const returnType = path.get("returnType.typeAnnotation");
199
+ if (returnType == null ? void 0 : returnType.node)
200
+ findNestedTypes(returnType);
201
+ }
202
+ }
203
+ traverse(ast, {
204
+ TSTypeAliasDeclaration(path) {
205
+ const typeString = getTypingsWithoutComments(path.node.typeAnnotation);
206
+ typeCounts.set(typeString, (typeCounts.get(typeString) || 0) + 1);
207
+ if (typeMap.has(typeString) && (typeCounts.get(typeString) || 0) > 1) {
208
+ const existing = typeMap.get(typeString);
209
+ path.replaceWith(
210
+ t.tsTypeAliasDeclaration(path.node.id, null, t.tsTypeReference(t.identifier(existing.id.name)))
211
+ );
212
+ } else {
213
+ addTypeToMap(path.node);
214
+ }
215
+ },
216
+ TSPropertySignature(path) {
217
+ const annPath = path.get("typeAnnotation.typeAnnotation");
218
+ if (annPath == null ? void 0 : annPath.node)
219
+ findNestedTypes(annPath);
220
+ },
221
+ TSFunctionType(path) {
222
+ const returnPath = path.get("typeAnnotation");
223
+ if (returnPath.node)
224
+ findNestedTypes(returnPath);
225
+ const params = path.get("parameters");
226
+ params.forEach((param) => {
227
+ const ta = param.get("typeAnnotation.typeAnnotation");
228
+ if (ta == null ? void 0 : ta.node)
229
+ findNestedTypes(ta);
230
+ });
231
+ },
232
+ TSMethodSignature(path) {
233
+ const returnPath = path.get("typeAnnotation.typeAnnotation");
234
+ if (returnPath == null ? void 0 : returnPath.node) {
235
+ findNestedTypes(returnPath);
236
+ }
237
+ const params = path.get("parameters");
238
+ params.forEach((param) => {
239
+ const ta = param.get("typeAnnotation.typeAnnotation");
240
+ if (ta == null ? void 0 : ta.node)
241
+ findNestedTypes(ta);
242
+ });
243
+ },
244
+ TSDeclareFunction(path) {
245
+ const params = path.get("params");
246
+ params.forEach((p) => {
247
+ const ta = p.get("typeAnnotation.typeAnnotation");
248
+ if (ta == null ? void 0 : ta.node)
249
+ findNestedTypes(ta);
250
+ });
251
+ const returnPath = path.get("returnType.typeAnnotation");
252
+ if (returnPath == null ? void 0 : returnPath.node)
253
+ findNestedTypes(returnPath);
254
+ }
255
+ });
256
+ typeMap.forEach((typeNode, typeString) => {
257
+ if ((typeCounts.get(typeString) || 0) > 1) {
258
+ if (!hoistedTypes.some((ht) => {
259
+ return getTypingsWithoutComments(ht.typeAnnotation) === getTypingsWithoutComments(typeNode.typeAnnotation);
260
+ })) {
261
+ hoistedTypes.push(typeNode);
262
+ }
263
+ }
264
+ });
265
+ ast.program.body = [
266
+ ...hoistedTypes,
267
+ ...ast.program.body.filter(
268
+ (node) => !hoistedTypes.some((ht) => t.isTSTypeAliasDeclaration(node) && node.id.name === ht.id.name)
269
+ )
270
+ ];
271
+ return ast;
272
+ }
273
+ async function hoistTypings(code, formatOptions) {
274
+ formatOptions ??= {};
275
+ formatOptions.throwOnError ??= true;
276
+ for (let i = 1; i <= 5; i++) {
277
+ try {
278
+ const initialCode = code;
279
+ const ast = parse(code, {
280
+ sourceType: "module",
281
+ plugins: ["typescript"]
282
+ });
283
+ const transformedAst = extractAndHoistTypes(ast);
284
+ code = new CodeGenerator(transformedAst, {
285
+ // quotes: 'single',
286
+ compact: false
287
+ }).generate().code;
288
+ if (initialCode === code) {
289
+ break;
290
+ }
291
+ } catch (err) {
292
+ console.error(err);
293
+ if (formatOptions.throwOnError) {
294
+ throw new CodeFormattingError(err instanceof Error ? err.message : String(err ?? "Unknown Error"), code);
295
+ }
296
+ break;
297
+ }
298
+ }
299
+ return formatTypings(code, formatOptions);
300
+ }
301
+
302
+ // src/objects.ts
303
+ var LARGE_OBJECT_LINES_OF_CODE = 10;
304
+ var ObjectInstance = class {
305
+ name;
306
+ description;
307
+ properties;
308
+ tools;
309
+ metadata;
310
+ constructor(props) {
311
+ var _a;
312
+ if (!isValidIdentifier(props.name)) {
313
+ throw new Error(
314
+ `Invalid name for tool ${props.name}. A tool name must start with a letter and contain only letters, numbers, and underscores. It must be 1-50 characters long.`
315
+ );
316
+ }
317
+ if (props.description !== void 0 && typeof props.description !== "string") {
318
+ throw new Error(
319
+ `Invalid description for tool ${props.name}. Expected a string, but got type "${typeof props.description}"`
320
+ );
321
+ }
322
+ if (props.metadata !== void 0 && typeof props.metadata !== "object") {
323
+ throw new Error(
324
+ `Invalid metadata for tool ${props.name}. Expected an object, but got type "${typeof props.metadata}"`
325
+ );
326
+ }
327
+ if (props.properties !== void 0 && !Array.isArray(props.properties)) {
328
+ throw new Error(
329
+ `Invalid properties for tool ${props.name}. Expected an array, but got type "${typeof props.properties}"`
330
+ );
331
+ }
332
+ if (props.tools !== void 0 && !Array.isArray(props.tools)) {
333
+ throw new Error(`Invalid tools for tool ${props.name}. Expected an array, but got type "${typeof props.tools}"`);
334
+ }
335
+ if ((_a = props.properties) == null ? void 0 : _a.length) {
336
+ if (props.properties.length > 100) {
337
+ throw new Error(
338
+ `Too many properties for tool ${props.name}. Expected at most 100 properties, but got ${props.properties.length}`
339
+ );
340
+ }
341
+ for (const prop of props.properties) {
342
+ if (props.properties.filter((p) => p.name === prop.name).length > 1) {
343
+ throw new Error(`Duplicate property name "${prop.name}" in tool ${props.name}`);
344
+ }
345
+ if (!isValidIdentifier(prop.name)) {
346
+ throw new Error(
347
+ `Invalid name for property ${prop.name}. A property name must start with a letter and contain only letters, numbers, and underscores. It must be 1-50 characters long.`
348
+ );
349
+ }
350
+ if (prop.description !== void 0 && typeof prop.description !== "string") {
351
+ throw new Error(
352
+ `Invalid description for property ${prop.name}. Expected a string, but got type "${typeof prop.description}"`
353
+ );
354
+ }
355
+ if (props.description && props.description.length >= 5e3) {
356
+ throw new Error(
357
+ `Description for property ${prop.name} is too long. Expected at most 5000 characters, but got ${props.description.length}`
358
+ );
359
+ }
360
+ if (typeof prop.writable !== "boolean") {
361
+ prop.writable = false;
362
+ }
363
+ }
364
+ }
365
+ this.name = props.name;
366
+ this.description = props.description;
367
+ this.metadata = props.metadata ?? {};
368
+ this.properties = props.properties;
369
+ this.tools = Tool.withUniqueNames(props.tools ?? []);
370
+ }
371
+ async getTypings() {
372
+ return getObjectTypings(this).withProperties().withTools().build();
373
+ }
374
+ };
375
+ function getObjectTypings(obj) {
376
+ let includeProperties = false;
377
+ let includeTools = false;
378
+ let hoisting = false;
379
+ const typings = [];
380
+ const addProperties = async () => {
381
+ var _a;
382
+ if (includeProperties && ((_a = obj.properties) == null ? void 0 : _a.length)) {
383
+ typings.push("");
384
+ typings.push("// ---------------- //");
385
+ typings.push("// Properties //");
386
+ typings.push("// ---------------- //");
387
+ typings.push("");
388
+ for (const prop of obj.properties ?? []) {
389
+ const description = prop.description ?? "";
390
+ if (description == null ? void 0 : description.trim().length) {
391
+ typings.push(getMultilineComment(description));
392
+ }
393
+ let type = "unknown";
394
+ if (prop.type) {
395
+ type = await getTypings(prop.type, {});
396
+ } else if (prop.value !== void 0) {
397
+ type = typeof prop.value;
398
+ }
399
+ type = prop.writable ? `Writable<${type}>` : `Readonly<${type}>`;
400
+ const value = embedPropertyValue(prop);
401
+ typings.push(`const ${prop.name}: ${type} = ${value}`);
402
+ }
403
+ }
404
+ };
405
+ const addTools = async () => {
406
+ var _a;
407
+ if (includeTools && ((_a = obj.tools) == null ? void 0 : _a.length)) {
408
+ typings.push("");
409
+ typings.push("// ---------------- //");
410
+ typings.push("// Tools //");
411
+ typings.push("// ---------------- //");
412
+ typings.push("");
413
+ for (const tool of obj.tools) {
414
+ const fnType = z.function(tool.zInput, tool.zOutput).title(tool.name).describe(tool.description ?? "");
415
+ let temp = await getTypings(fnType, {
416
+ declaration: true
417
+ });
418
+ temp = temp.replace("declare function ", "function ");
419
+ typings.push(temp);
420
+ }
421
+ }
422
+ };
423
+ const finalize = async () => {
424
+ var _a;
425
+ let closingBracket = "";
426
+ if (typings.length >= LARGE_OBJECT_LINES_OF_CODE) {
427
+ closingBracket = ` // end namespace "${obj.name}"`;
428
+ }
429
+ let body = typings.join("\n");
430
+ if (hoisting) {
431
+ body = await hoistTypings(body, { throwOnError: false });
432
+ }
433
+ typings.push("}" + closingBracket);
434
+ let header = "";
435
+ if ((_a = obj.description) == null ? void 0 : _a.trim().length) {
436
+ header = getMultilineComment(obj.description);
437
+ }
438
+ return formatTypings(
439
+ `${header}
440
+ export namespace ${obj.name} {
441
+ ${body}
442
+ } ${closingBracket}`.trim(),
443
+ { throwOnError: false }
444
+ );
445
+ };
446
+ const api = {
447
+ withProperties: () => {
448
+ includeProperties = true;
449
+ return api;
450
+ },
451
+ withTools: () => {
452
+ includeTools = true;
453
+ return api;
454
+ },
455
+ withHoisting: () => {
456
+ hoisting = true;
457
+ return api;
458
+ },
459
+ async build() {
460
+ await addProperties();
461
+ await addTools();
462
+ return finalize();
463
+ }
464
+ };
465
+ return api;
466
+ }
467
+ function embedPropertyValue(property) {
468
+ if (typeof property.value === "string") {
469
+ return escapeString(property.value);
470
+ }
471
+ if (Number.isNaN(property.value)) {
472
+ return "NaN";
473
+ }
474
+ if (typeof property.value === "number" && Number.isInteger(property.value)) {
475
+ return property.value.toString();
476
+ }
477
+ if (typeof property.value === "boolean") {
478
+ return property.value.toString();
479
+ }
480
+ if (Array.isArray(property.value) || typeof property.value === "object") {
481
+ return JSON.stringify(property.value);
482
+ }
483
+ if (property.value instanceof Date) {
484
+ return `new Date('${property.value.toISOString()}')`;
485
+ }
486
+ if (property.value instanceof RegExp) {
487
+ return `new RegExp(${escapeString(property.value.source)}, ${escapeString(property.value.flags)})`;
488
+ }
489
+ if (property.value === null) {
490
+ return "null";
491
+ }
492
+ if (property.value === void 0) {
493
+ return "undefined";
494
+ }
495
+ if (typeof property.value === "function") {
496
+ return "function() {}";
497
+ }
498
+ if (typeof property.value === "symbol") {
499
+ return "Symbol()";
500
+ }
501
+ if (typeof property.value === "bigint") {
502
+ return `${property.value}n`;
503
+ }
504
+ if (property.value instanceof Error) {
505
+ return `Error(${escapeString(property.value.message)})`;
506
+ }
507
+ if (property.value instanceof Map) {
508
+ return `new Map(${JSON.stringify(Array.from(property.value.entries()))})`;
509
+ }
510
+ if (property.value instanceof Set) {
511
+ return `new Set(${JSON.stringify(Array.from(property.value.values()))})`;
512
+ }
513
+ return "unknown";
514
+ }
515
+
516
+ // src/citations.ts
517
+ var RARE_SYMBOLS = {
518
+ ARROW_UP: "\u2191",
519
+ CIRCLE_BULLET: "\u30FB",
520
+ STAR_BULLET_FULL: "\u2605",
521
+ STAR_BULLET_EMPTY: "\u2606",
522
+ ARROW_BULLET: "\u2192",
523
+ SQUARE_BULLET: "\u25A0",
524
+ TRIANGLE_BULLET: "\u25BA",
525
+ OPENING_TAG: "\u3010",
526
+ CLOSING_TAG: "\u3011",
527
+ SS: "\xA7",
528
+ CROSS: "\u2020"
529
+ };
530
+ var CitationsManager = class {
531
+ _citations = /* @__PURE__ */ new Map();
532
+ _nextId = 0;
533
+ /**
534
+ * Registers a new source and returns the created Citation.
535
+ * @param source An object representing the source of the citation.
536
+ * @returns The created Citation.
537
+ */
538
+ registerSource(source) {
539
+ const id = this._nextId++;
540
+ const tag = `${RARE_SYMBOLS.OPENING_TAG}${id}${RARE_SYMBOLS.CLOSING_TAG}`;
541
+ const citation = {
542
+ id,
543
+ source,
544
+ tag
545
+ };
546
+ this._citations.set(id, citation);
547
+ return citation;
548
+ }
549
+ /**
550
+ * Extracts citations from the provided content and cleans the content of citation tags.
551
+ * Non-found citations are replaced with a special "Not Found" citation.
552
+ * @param content The string content containing citation tags.
553
+ * @returns An object containing the cleaned content and an array of found citations.
554
+ */
555
+ extractCitations(content, replace) {
556
+ const citations = [];
557
+ const notFoundCitation = {
558
+ id: -1,
559
+ source: "Not Found",
560
+ tag: ""
561
+ };
562
+ const regex = new RegExp(`${RARE_SYMBOLS.OPENING_TAG}([\\d|\\w|\\s|,]{0,})${RARE_SYMBOLS.CLOSING_TAG}`, "ig");
563
+ let match;
564
+ const offsets = [];
565
+ while ((match = regex.exec(content)) !== null) {
566
+ const offset = match.index;
567
+ const length = match[0].length;
568
+ offsets.push({ start: offset, length });
569
+ const multi = (match[1] ?? "").split(/\D/g).map((s) => s.trim()).filter(Boolean).map((s) => parseInt(s, 10)).filter((s) => !isNaN(s) && s >= 0);
570
+ for (const citationId of multi) {
571
+ const citation = this._citations.get(citationId);
572
+ if (citation) {
573
+ citations.push({ ...citation, offset });
574
+ } else {
575
+ citations.push({ ...notFoundCitation, offset });
576
+ }
577
+ }
578
+ }
579
+ const entries = offsets.map((o) => ({
580
+ start: o.start,
581
+ length: o.length,
582
+ citations: citations.filter((x) => x.offset === o.start && x.id !== -1)
583
+ })).sort((a, b) => a.start - b.start);
584
+ let result = "";
585
+ let cursor = 0;
586
+ for (const { start, length, citations: citations2 } of entries) {
587
+ result += content.slice(cursor, start);
588
+ const replacement = citations2.map((citation) => replace ? replace(citation) : "").join("");
589
+ result += replacement;
590
+ cursor = start + length;
591
+ }
592
+ result += content.slice(cursor);
593
+ return { cleaned: result, citations };
594
+ }
595
+ /**
596
+ * Strips citation tags from the provided content.
597
+ * @param content The string content containing citation tags.
598
+ * @returns The cleaned content without citation tags.
599
+ */
600
+ static stripCitationTags(content) {
601
+ const regex = new RegExp(`${RARE_SYMBOLS.OPENING_TAG}([\\d|\\w|\\s|,]{0,})${RARE_SYMBOLS.CLOSING_TAG}?`, "g");
602
+ return content.replace(regex, "");
603
+ }
604
+ /**
605
+ * Removes citations from a deeply nested plain object and returns a new object with citations removed.
606
+ * @param obj The plain object to process.
607
+ * @returns A tuple containing the new object and an array of extracted citations with paths.
608
+ */
609
+ removeCitationsFromObject(obj) {
610
+ const result = [];
611
+ const processObject = (current, path) => {
612
+ if (typeof current === "string") {
613
+ const extraction = this.extractCitations(current);
614
+ if (extraction.citations.length > 0) {
615
+ result.push(...extraction.citations.map((citation) => ({ path, citation })));
616
+ }
617
+ return extraction.cleaned;
618
+ } else if (typeof current === "object" && current !== null) {
619
+ const newObject = Array.isArray(current) ? [] : {};
620
+ for (const key of Object.keys(current)) {
621
+ newObject[key] = processObject(current[key], `${path}.${key}`);
622
+ }
623
+ return newObject;
624
+ }
625
+ return current;
626
+ };
627
+ const newObj = processObject(obj, "root");
628
+ return [newObj, result];
629
+ }
630
+ /**
631
+ * Re-adds citations to the cleaned content based on their offsets.
632
+ * @param cleaned The cleaned string without citation tags.
633
+ * @param citations The array of citations with offsets.
634
+ * @returns The string with citation tags re-added.
635
+ */
636
+ reAddCitations(cleaned, citations) {
637
+ let content = cleaned;
638
+ citations.sort((a, b) => (a.offset ?? 0) - (b.offset ?? 0));
639
+ const adjustment = 0;
640
+ for (const citation of citations) {
641
+ if (citation.offset != null) {
642
+ const position = citation.offset + adjustment;
643
+ content = content.slice(0, position) + citation.tag + content.slice(position);
644
+ }
645
+ }
646
+ return content;
647
+ }
648
+ };
649
+
650
+ // src/component.default.ts
651
+ import { z as z2 } from "@bpinternal/zui";
652
+ var Button = new Component({
653
+ type: "leaf",
654
+ description: "A button component that can perform actions when clicked",
655
+ name: "Button",
656
+ aliases: ["btn"],
657
+ examples: [
658
+ {
659
+ name: "Say action",
660
+ description: "A button that triggers a say action",
661
+ code: `<Message>
662
+ <Button action="say" label="Hello" />
663
+ </Message>`
664
+ },
665
+ {
666
+ name: "Postback action",
667
+ description: "A button that sends a postback value",
668
+ code: `<Message>
669
+ <Button action="postback" label="Buy" value="buy_product" />
670
+ </Message>`
671
+ }
672
+ ],
673
+ leaf: {
674
+ props: z2.object({
675
+ action: z2.enum(["say", "url", "postback"]).default("say").describe('The action to perform when the button is clicked. Can be "say", "url", or "postback"'),
676
+ label: z2.string().describe("The text displayed on the button"),
677
+ value: z2.string().optional().describe('The postback value to send when the button is clicked. Required if action is "postback"'),
678
+ url: z2.string().optional().describe('The URL to open when the button is clicked. Required if action is "url"')
679
+ })
680
+ }
681
+ });
682
+ var Image = new Component({
683
+ type: "leaf",
684
+ name: "Image",
685
+ description: "Displays an image from a URL.",
686
+ aliases: [],
687
+ examples: [
688
+ {
689
+ name: "Basic image",
690
+ description: "A simple image with alt text",
691
+ code: `<Message>
692
+ <Image url="https://example.com/photo.jpg" alt="Example image" />
693
+ </Message>`
694
+ }
695
+ ],
696
+ leaf: {
697
+ props: z2.object({
698
+ url: z2.string().describe("The URL of the image (must be valid)"),
699
+ alt: z2.string().optional().describe("Alternative text describing the image")
700
+ })
701
+ }
702
+ });
703
+ var File = new Component({
704
+ type: "leaf",
705
+ name: "File",
706
+ description: "Sends a downloadable file to the user.",
707
+ aliases: [],
708
+ examples: [
709
+ {
710
+ name: "PDF download",
711
+ description: "Send a PDF file with a name",
712
+ code: `<Message>
713
+ <File url="https://example.com/report.pdf" name="Report.pdf" />
714
+ </Message>`
715
+ }
716
+ ],
717
+ leaf: {
718
+ props: z2.object({
719
+ url: z2.string().describe("The URL of the file (must be valid)"),
720
+ name: z2.string().optional().describe("The display name of the file")
721
+ })
722
+ }
723
+ });
724
+ var Video = new Component({
725
+ type: "leaf",
726
+ name: "Video",
727
+ description: "Embeds a video from a URL.",
728
+ aliases: [],
729
+ examples: [
730
+ {
731
+ name: "Intro video",
732
+ description: "A video with a title",
733
+ code: `<Message>
734
+ <Video url="https://example.com/intro.mp4" title="Welcome" />
735
+ </Message>`
736
+ }
737
+ ],
738
+ leaf: {
739
+ props: z2.object({
740
+ url: z2.string().describe("The URL of the video (must be valid)"),
741
+ title: z2.string().optional().describe("Title for the video")
742
+ })
743
+ }
744
+ });
745
+ var Audio = new Component({
746
+ type: "leaf",
747
+ name: "Audio",
748
+ description: "Plays an audio clip from a URL.",
749
+ aliases: [],
750
+ examples: [
751
+ {
752
+ name: "Sample audio",
753
+ description: "Play a short audio clip with a title",
754
+ code: `<Message>
755
+ <Audio url="https://example.com/audio.mp3" title="Sample" />
756
+ </Message>`
757
+ }
758
+ ],
759
+ leaf: {
760
+ props: z2.object({
761
+ url: z2.string().describe("The URL of the audio clip (must be valid)"),
762
+ title: z2.string().optional().describe("Title for the audio clip")
763
+ })
764
+ }
765
+ });
766
+ var Card = new Component({
767
+ type: "container",
768
+ name: "Card",
769
+ description: "A visual card component that can include an image and buttons.",
770
+ aliases: [],
771
+ examples: [
772
+ {
773
+ name: "Product card",
774
+ description: "A card with an image and two buttons",
775
+ code: `<Message>
776
+ <Card title="Product Name" subtitle="Limited offer">
777
+ <Image url="https://example.com/product.jpg" alt="Product image" />
778
+ <Button action="postback" label="Buy" value="buy_product" />
779
+ <Button action="postback" label="Wishlist" value="wishlist" />
780
+ </Card>
781
+ </Message>`
782
+ }
783
+ ],
784
+ container: {
785
+ props: z2.object({
786
+ title: z2.string().min(1).max(250).describe("Title text (1\u2013250 characters)"),
787
+ subtitle: z2.string().optional().describe("Optional subtitle for the card")
788
+ }),
789
+ children: [
790
+ {
791
+ description: "Image (optional, max 1)",
792
+ component: Image.definition
793
+ },
794
+ {
795
+ description: "Button (optional, up to 5)",
796
+ component: Button.definition
797
+ }
798
+ ]
799
+ }
800
+ });
801
+ var Carousel = new Component({
802
+ type: "container",
803
+ name: "Carousel",
804
+ description: "A virtual container for displaying 1 to 10 Card components as a carousel.",
805
+ aliases: [],
806
+ examples: [
807
+ {
808
+ name: "Product carousel",
809
+ description: "A carousel with multiple cards",
810
+ code: `<Message>
811
+ <Carousel>
812
+ <Card title="Item 1" subtitle="First product">
813
+ <Image url="https://example.com/item1.jpg" alt="Item 1" />
814
+ <Button action="postback" label="Buy" value="buy_1" />
815
+ </Card>
816
+ <Card title="Item 2" subtitle="Second product">
817
+ <Image url="https://example.com/item2.jpg" alt="Item 2" />
818
+ <Button action="postback" label="Buy" value="buy_2" />
819
+ </Card>
820
+ </Carousel>
821
+ </Message>`
822
+ }
823
+ ],
824
+ container: {
825
+ props: z2.object({}),
826
+ children: [
827
+ {
828
+ description: "Card component (required, 1\u201310 allowed)",
829
+ component: Card.definition
830
+ }
831
+ ]
832
+ }
833
+ });
834
+ var Text = new Component({
835
+ type: "default",
836
+ name: "Message",
837
+ aliases: ["Text", "Markdown"],
838
+ description: "Markdown-formatted text that appears directly inside components like <Message>.",
839
+ examples: [
840
+ {
841
+ name: "Basic Markdown",
842
+ description: "Simple markdown content inside a message",
843
+ code: `<Message>
844
+ **Hello**, welcome to our service!
845
+ </Message>`
846
+ }
847
+ ],
848
+ default: {
849
+ props: z2.object({}),
850
+ children: []
851
+ }
852
+ });
853
+ var DefaultComponents = {
854
+ Button,
855
+ Image,
856
+ File,
857
+ Video,
858
+ Audio,
859
+ Card,
860
+ Carousel,
861
+ Text
862
+ };
863
+
864
+ // src/chat.ts
865
+ var Chat = class {
866
+ handler;
867
+ transcript;
868
+ components;
869
+ constructor(props) {
870
+ this.handler = props.handler;
871
+ this.components = props.components;
872
+ this.transcript = props.transcript || [];
873
+ }
874
+ onExecutionDone(_result) {
875
+ }
876
+ };
877
+
878
+ // src/index.ts
879
+ var execute = async (props) => {
880
+ const { executeContext } = await import("./llmz-ROOX7RYI.js");
881
+ return executeContext(props);
882
+ };
883
+ var init = async () => {
884
+ await import("./llmz-ROOX7RYI.js");
885
+ await import("./component-WFVDVSDK.js");
886
+ await import("./tool-N6ODRRGH.js");
887
+ await import("./exit-YORW76T3.js");
888
+ await import("./jsx-AEHVFB3L.js");
889
+ await import("./vm-FLBMZUA2.js");
890
+ await import("./utils-N24IHDFA.js");
891
+ await import("./truncator-IY2MXOMC.js");
892
+ await import("./typings-GDMY6VY2.js");
893
+ await import("./dual-modes-T53P72CH.js");
894
+ };
895
+ export {
896
+ Chat,
897
+ CitationsManager,
898
+ Component,
899
+ DefaultComponents,
900
+ DefaultExit,
901
+ ErrorExecutionResult,
902
+ ExecutionResult,
903
+ Exit,
904
+ ListenExit,
905
+ LoopExceededError,
906
+ ObjectInstance,
907
+ PartialExecutionResult,
908
+ Snapshot,
909
+ SnapshotSignal,
910
+ SuccessExecutionResult,
911
+ ThinkExit,
912
+ ThinkSignal,
913
+ Tool,
914
+ assertValidComponent,
915
+ execute,
916
+ getValue,
917
+ init,
918
+ isAnyComponent,
919
+ isComponent,
920
+ renderToTsx
921
+ };