@vertesia/build-tools 1.3.0 → 1.4.0-dev.20260614.160504Z

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 (220) hide show
  1. package/README.md +3 -3
  2. package/lib/bin/build.d.ts +35 -0
  3. package/lib/bin/build.d.ts.map +1 -0
  4. package/lib/bin/build.js +79 -0
  5. package/lib/bin/build.js.map +1 -0
  6. package/lib/bin/config.d.ts +24 -0
  7. package/lib/bin/config.d.ts.map +1 -0
  8. package/lib/bin/config.js +91 -0
  9. package/lib/bin/config.js.map +1 -0
  10. package/lib/core/compilers/widget.d.ts +27 -0
  11. package/lib/core/compilers/widget.d.ts.map +1 -0
  12. package/lib/core/compilers/widget.js +37 -0
  13. package/lib/core/compilers/widget.js.map +1 -0
  14. package/lib/{types → core}/parsers/frontmatter.d.ts +1 -1
  15. package/lib/core/parsers/frontmatter.d.ts.map +1 -0
  16. package/lib/{esm → core}/parsers/frontmatter.js +1 -1
  17. package/lib/core/parsers/frontmatter.js.map +1 -0
  18. package/lib/core/transformers/index.d.ts +10 -0
  19. package/lib/core/transformers/index.d.ts.map +1 -0
  20. package/lib/core/transformers/index.js +10 -0
  21. package/lib/core/transformers/index.js.map +1 -0
  22. package/lib/{types/presets → core/transformers}/prompt.d.ts +7 -21
  23. package/lib/core/transformers/prompt.d.ts.map +1 -0
  24. package/lib/{esm/presets → core/transformers}/prompt.js +17 -14
  25. package/lib/core/transformers/prompt.js.map +1 -0
  26. package/lib/core/transformers/raw.d.ts.map +1 -0
  27. package/lib/{esm/presets → core/transformers}/raw.js +2 -2
  28. package/lib/core/transformers/raw.js.map +1 -0
  29. package/lib/core/transformers/skill-collection.d.ts.map +1 -0
  30. package/lib/{esm/presets → core/transformers}/skill-collection.js +5 -12
  31. package/lib/core/transformers/skill-collection.js.map +1 -0
  32. package/lib/core/transformers/skill.d.ts +111 -0
  33. package/lib/core/transformers/skill.d.ts.map +1 -0
  34. package/lib/{esm/presets → core/transformers}/skill.js +70 -51
  35. package/lib/core/transformers/skill.js.map +1 -0
  36. package/lib/core/transformers/template-collection.d.ts.map +1 -0
  37. package/lib/{esm/presets → core/transformers}/template-collection.js +5 -12
  38. package/lib/core/transformers/template-collection.js.map +1 -0
  39. package/lib/{types/presets → core/transformers}/template.d.ts +7 -22
  40. package/lib/core/transformers/template.d.ts.map +1 -0
  41. package/lib/{esm/presets → core/transformers}/template.js +16 -11
  42. package/lib/core/transformers/template.js.map +1 -0
  43. package/lib/{types → core}/types.d.ts +5 -61
  44. package/lib/core/types.d.ts.map +1 -0
  45. package/lib/core/types.js +6 -0
  46. package/lib/{cjs → core}/types.js.map +1 -1
  47. package/lib/core/utils/asset-copy.d.ts.map +1 -0
  48. package/lib/core/utils/asset-copy.js.map +1 -0
  49. package/lib/core/utils/asset-discovery.d.ts.map +1 -0
  50. package/lib/{esm → core}/utils/asset-discovery.js +4 -4
  51. package/lib/core/utils/asset-discovery.js.map +1 -0
  52. package/lib/core/utils/template-asset-discovery.d.ts.map +1 -0
  53. package/lib/{esm → core}/utils/template-asset-discovery.js +3 -7
  54. package/lib/core/utils/template-asset-discovery.js.map +1 -0
  55. package/lib/import-transform/builtins.d.ts +21 -0
  56. package/lib/import-transform/builtins.d.ts.map +1 -0
  57. package/lib/import-transform/builtins.js +50 -0
  58. package/lib/import-transform/builtins.js.map +1 -0
  59. package/lib/import-transform/chunk-emitter.d.ts +24 -0
  60. package/lib/import-transform/chunk-emitter.d.ts.map +1 -0
  61. package/lib/import-transform/chunk-emitter.js +35 -0
  62. package/lib/import-transform/chunk-emitter.js.map +1 -0
  63. package/lib/import-transform/detector.d.ts +24 -0
  64. package/lib/import-transform/detector.d.ts.map +1 -0
  65. package/lib/import-transform/detector.js +34 -0
  66. package/lib/import-transform/detector.js.map +1 -0
  67. package/lib/import-transform/index.d.ts +47 -0
  68. package/lib/import-transform/index.d.ts.map +1 -0
  69. package/lib/import-transform/index.js +115 -0
  70. package/lib/import-transform/index.js.map +1 -0
  71. package/lib/import-transform/patterns.d.ts +25 -0
  72. package/lib/import-transform/patterns.d.ts.map +1 -0
  73. package/lib/import-transform/patterns.js +27 -0
  74. package/lib/import-transform/patterns.js.map +1 -0
  75. package/lib/import-transform/resolver.d.ts +23 -0
  76. package/lib/import-transform/resolver.d.ts.map +1 -0
  77. package/lib/import-transform/resolver.js +30 -0
  78. package/lib/import-transform/resolver.js.map +1 -0
  79. package/lib/import-transform/rewriter.d.ts +21 -0
  80. package/lib/import-transform/rewriter.d.ts.map +1 -0
  81. package/lib/import-transform/rewriter.js +30 -0
  82. package/lib/import-transform/rewriter.js.map +1 -0
  83. package/lib/import-transform/scanner.d.ts +17 -0
  84. package/lib/import-transform/scanner.d.ts.map +1 -0
  85. package/lib/import-transform/scanner.js +46 -0
  86. package/lib/import-transform/scanner.js.map +1 -0
  87. package/lib/index.d.ts +39 -0
  88. package/lib/index.d.ts.map +1 -0
  89. package/lib/index.js +43 -0
  90. package/lib/index.js.map +1 -0
  91. package/lib/vite/api-server.d.ts +54 -0
  92. package/lib/vite/api-server.d.ts.map +1 -0
  93. package/lib/vite/api-server.js +94 -0
  94. package/lib/vite/api-server.js.map +1 -0
  95. package/lib/vite/dev-server.d.ts +42 -0
  96. package/lib/vite/dev-server.d.ts.map +1 -0
  97. package/lib/vite/dev-server.js +111 -0
  98. package/lib/vite/dev-server.js.map +1 -0
  99. package/lib/vite/index.d.ts +15 -0
  100. package/lib/vite/index.d.ts.map +1 -0
  101. package/lib/vite/index.js +15 -0
  102. package/lib/vite/index.js.map +1 -0
  103. package/package.json +38 -28
  104. package/src/bin/build.ts +83 -0
  105. package/src/bin/config.ts +113 -0
  106. package/src/core/compilers/widget.ts +69 -0
  107. package/src/{parsers → core/parsers}/frontmatter.ts +2 -2
  108. package/src/core/transformers/index.ts +27 -0
  109. package/src/{presets → core/transformers}/prompt.ts +35 -32
  110. package/src/{presets → core/transformers}/raw.ts +2 -2
  111. package/src/{presets → core/transformers}/skill-collection.ts +5 -12
  112. package/src/{presets → core/transformers}/skill.ts +119 -99
  113. package/src/{presets → core/transformers}/template-collection.ts +76 -83
  114. package/src/{presets → core/transformers}/template.ts +121 -116
  115. package/src/core/types.ts +71 -0
  116. package/src/{utils → core/utils}/asset-copy.ts +3 -2
  117. package/src/{utils → core/utils}/asset-discovery.ts +5 -5
  118. package/src/{utils → core/utils}/template-asset-discovery.ts +70 -77
  119. package/src/import-transform/builtins.ts +56 -0
  120. package/src/import-transform/chunk-emitter.ts +60 -0
  121. package/src/import-transform/detector.ts +56 -0
  122. package/src/import-transform/index.ts +171 -0
  123. package/src/import-transform/patterns.ts +34 -0
  124. package/src/import-transform/resolver.ts +57 -0
  125. package/src/import-transform/rewriter.ts +48 -0
  126. package/src/import-transform/scanner.ts +55 -0
  127. package/src/index.ts +67 -42
  128. package/src/vite/api-server.ts +142 -0
  129. package/src/vite/dev-server.ts +128 -0
  130. package/src/vite/index.ts +15 -0
  131. package/lib/build-tools.js +0 -2054
  132. package/lib/build-tools.js.map +0 -1
  133. package/lib/cjs/index.js +0 -43
  134. package/lib/cjs/index.js.map +0 -1
  135. package/lib/cjs/package.json +0 -3
  136. package/lib/cjs/parsers/frontmatter.js +0 -25
  137. package/lib/cjs/parsers/frontmatter.js.map +0 -1
  138. package/lib/cjs/plugin.js +0 -150
  139. package/lib/cjs/plugin.js.map +0 -1
  140. package/lib/cjs/presets/index.js +0 -25
  141. package/lib/cjs/presets/index.js.map +0 -1
  142. package/lib/cjs/presets/prompt.js +0 -185
  143. package/lib/cjs/presets/prompt.js.map +0 -1
  144. package/lib/cjs/presets/raw.js +0 -25
  145. package/lib/cjs/presets/raw.js.map +0 -1
  146. package/lib/cjs/presets/skill-collection.js +0 -83
  147. package/lib/cjs/presets/skill-collection.js.map +0 -1
  148. package/lib/cjs/presets/skill.js +0 -272
  149. package/lib/cjs/presets/skill.js.map +0 -1
  150. package/lib/cjs/presets/template-collection.js +0 -80
  151. package/lib/cjs/presets/template-collection.js.map +0 -1
  152. package/lib/cjs/presets/template.js +0 -105
  153. package/lib/cjs/presets/template.js.map +0 -1
  154. package/lib/cjs/types.js +0 -6
  155. package/lib/cjs/utils/asset-copy.js +0 -61
  156. package/lib/cjs/utils/asset-copy.js.map +0 -1
  157. package/lib/cjs/utils/asset-discovery.js +0 -100
  158. package/lib/cjs/utils/asset-discovery.js.map +0 -1
  159. package/lib/cjs/utils/template-asset-discovery.js +0 -63
  160. package/lib/cjs/utils/template-asset-discovery.js.map +0 -1
  161. package/lib/cjs/utils/widget-compiler.js +0 -115
  162. package/lib/cjs/utils/widget-compiler.js.map +0 -1
  163. package/lib/cjs/vite.js +0 -45
  164. package/lib/cjs/vite.js.map +0 -1
  165. package/lib/esm/index.js +0 -26
  166. package/lib/esm/index.js.map +0 -1
  167. package/lib/esm/parsers/frontmatter.js.map +0 -1
  168. package/lib/esm/plugin.js +0 -144
  169. package/lib/esm/plugin.js.map +0 -1
  170. package/lib/esm/presets/index.js +0 -10
  171. package/lib/esm/presets/index.js.map +0 -1
  172. package/lib/esm/presets/prompt.js.map +0 -1
  173. package/lib/esm/presets/raw.js.map +0 -1
  174. package/lib/esm/presets/skill-collection.js.map +0 -1
  175. package/lib/esm/presets/skill.js.map +0 -1
  176. package/lib/esm/presets/template-collection.js.map +0 -1
  177. package/lib/esm/presets/template.js.map +0 -1
  178. package/lib/esm/types.js +0 -5
  179. package/lib/esm/types.js.map +0 -1
  180. package/lib/esm/utils/asset-copy.js.map +0 -1
  181. package/lib/esm/utils/asset-discovery.js.map +0 -1
  182. package/lib/esm/utils/template-asset-discovery.js.map +0 -1
  183. package/lib/esm/utils/widget-compiler.js +0 -76
  184. package/lib/esm/utils/widget-compiler.js.map +0 -1
  185. package/lib/esm/vite.js +0 -42
  186. package/lib/esm/vite.js.map +0 -1
  187. package/lib/types/index.d.ts +0 -24
  188. package/lib/types/index.d.ts.map +0 -1
  189. package/lib/types/parsers/frontmatter.d.ts.map +0 -1
  190. package/lib/types/plugin.d.ts +0 -10
  191. package/lib/types/plugin.d.ts.map +0 -1
  192. package/lib/types/presets/index.d.ts +0 -10
  193. package/lib/types/presets/index.d.ts.map +0 -1
  194. package/lib/types/presets/prompt.d.ts.map +0 -1
  195. package/lib/types/presets/raw.d.ts.map +0 -1
  196. package/lib/types/presets/skill-collection.d.ts.map +0 -1
  197. package/lib/types/presets/skill.d.ts +0 -361
  198. package/lib/types/presets/skill.d.ts.map +0 -1
  199. package/lib/types/presets/template-collection.d.ts.map +0 -1
  200. package/lib/types/presets/template.d.ts.map +0 -1
  201. package/lib/types/types.d.ts.map +0 -1
  202. package/lib/types/utils/asset-copy.d.ts.map +0 -1
  203. package/lib/types/utils/asset-discovery.d.ts.map +0 -1
  204. package/lib/types/utils/template-asset-discovery.d.ts.map +0 -1
  205. package/lib/types/utils/widget-compiler.d.ts +0 -15
  206. package/lib/types/utils/widget-compiler.d.ts.map +0 -1
  207. package/lib/types/vite.d.ts +0 -32
  208. package/lib/types/vite.d.ts.map +0 -1
  209. package/src/plugin.ts +0 -166
  210. package/src/presets/index.ts +0 -10
  211. package/src/types.ts +0 -140
  212. package/src/utils/widget-compiler.ts +0 -98
  213. package/src/vite.ts +0 -45
  214. /package/lib/{types/presets → core/transformers}/raw.d.ts +0 -0
  215. /package/lib/{types/presets → core/transformers}/skill-collection.d.ts +0 -0
  216. /package/lib/{types/presets → core/transformers}/template-collection.d.ts +0 -0
  217. /package/lib/{types → core}/utils/asset-copy.d.ts +0 -0
  218. /package/lib/{esm → core}/utils/asset-copy.js +0 -0
  219. /package/lib/{types → core}/utils/asset-discovery.d.ts +0 -0
  220. /package/lib/{types → core}/utils/template-asset-discovery.d.ts +0 -0
@@ -1,2054 +0,0 @@
1
- import { copyFileSync, mkdirSync, readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
2
- import path from 'node:path';
3
- import { rollup } from 'rollup';
4
- import { z } from 'zod';
5
- import matter from 'gray-matter';
6
- import path$1 from 'path';
7
-
8
- /**
9
- * Utilities for copying asset files during build
10
- */
11
- /**
12
- * Ensure a directory exists, creating it recursively if needed
13
- */
14
- function ensureDirectory(dirPath) {
15
- try {
16
- mkdirSync(dirPath, { recursive: true });
17
- }
18
- catch (error) {
19
- // Ignore if directory already exists
20
- if (error.code !== 'EEXIST') {
21
- throw error;
22
- }
23
- }
24
- }
25
- /**
26
- * Copy an asset file to its destination
27
- *
28
- * @param asset - Asset file information
29
- * @param assetsRoot - Root directory for assets
30
- */
31
- function copyAssetFile(asset, assetsRoot) {
32
- const destPath = path.join(assetsRoot, asset.destPath);
33
- const destDir = path.dirname(destPath);
34
- // Ensure destination directory exists
35
- ensureDirectory(destDir);
36
- // Copy file
37
- try {
38
- copyFileSync(asset.sourcePath, destPath);
39
- }
40
- catch (error) {
41
- throw new Error(`Failed to copy asset from ${asset.sourcePath} to ${destPath}: ${error instanceof Error ? error.message : String(error)}`);
42
- }
43
- }
44
- /**
45
- * Copy multiple asset files
46
- *
47
- * @param assets - Array of asset files to copy
48
- * @param assetsRoot - Root directory for assets
49
- * @returns Number of files copied
50
- */
51
- function copyAssets(assets, assetsRoot) {
52
- let copied = 0;
53
- for (const asset of assets) {
54
- copyAssetFile(asset, assetsRoot);
55
- copied++;
56
- }
57
- return copied;
58
- }
59
-
60
- /**
61
- * Widget compilation utility using Rollup
62
- */
63
- /**
64
- * Default external dependencies for widgets
65
- */
66
- const DEFAULT_EXTERNALS = [
67
- 'react',
68
- 'react-dom',
69
- 'react/jsx-runtime',
70
- 'react/jsx-dev-runtime',
71
- 'react-dom/client'
72
- ];
73
- /**
74
- * Compile widgets using Rollup
75
- *
76
- * @param widgets - Array of widget metadata to compile
77
- * @param outputDir - Directory to write compiled widgets
78
- * @param config - Widget compilation configuration
79
- * @returns Number of widgets compiled
80
- */
81
- async function compileWidgets(widgets, outputDir, config = {}) {
82
- if (widgets.length === 0) {
83
- return 0;
84
- }
85
- const { external = DEFAULT_EXTERNALS, tsconfig = './tsconfig.json', typescript: typescriptOptions = {}, minify = false } = config;
86
- // Build each widget separately to get individual bundles
87
- const buildPromises = widgets.map(async (widget) => {
88
- // Dynamically import plugins - use any to bypass TypeScript module resolution issues
89
- const typescript = (await import('@rollup/plugin-typescript')).default;
90
- const nodeResolve = (await import('@rollup/plugin-node-resolve')).default;
91
- const commonjs = (await import('@rollup/plugin-commonjs')).default;
92
- const plugins = [
93
- typescript({
94
- tsconfig,
95
- declaration: false,
96
- sourceMap: true,
97
- ...typescriptOptions
98
- }),
99
- nodeResolve({
100
- browser: true,
101
- preferBuiltins: false,
102
- extensions: ['.tsx', '.ts', '.jsx', '.js']
103
- }),
104
- commonjs()
105
- ];
106
- // Add minification if requested
107
- if (minify) {
108
- const { terser } = await import('rollup-plugin-terser');
109
- plugins.push(terser({
110
- compress: {
111
- drop_console: false
112
- }
113
- }));
114
- }
115
- const rollupConfig = {
116
- input: widget.path,
117
- output: {
118
- file: path.join(outputDir, `${widget.name}.js`),
119
- format: 'es',
120
- sourcemap: true,
121
- inlineDynamicImports: true
122
- },
123
- external,
124
- plugins
125
- };
126
- const bundle = await rollup(rollupConfig);
127
- await bundle.write(rollupConfig.output);
128
- await bundle.close();
129
- });
130
- await Promise.all(buildPromises);
131
- return widgets.length;
132
- }
133
-
134
- /**
135
- * Core Rollup plugin implementation for transforming imports
136
- */
137
- /**
138
- * Creates a Rollup plugin that transforms imports based on configured rules
139
- */
140
- function vertesiaImportPlugin(config) {
141
- const { transformers, assetsDir = './dist', widgetConfig } = config;
142
- if (!transformers || transformers.length === 0) {
143
- throw new Error('vertesiaImportPlugin: At least one transformer must be configured');
144
- }
145
- // Track assets to copy and widgets to compile
146
- const assetsToProcess = [];
147
- const widgetsToCompile = [];
148
- const shouldCopyAssets = assetsDir !== false;
149
- const shouldCompileWidgets = widgetConfig !== undefined && assetsDir !== false;
150
- return {
151
- name: 'vertesia-import-plugin',
152
- /**
153
- * Resolve import IDs to handle pattern-based imports
154
- */
155
- resolveId(source, importer) {
156
- // Check if any transformer pattern matches
157
- for (const transformer of transformers) {
158
- if (transformer.pattern.test(source)) {
159
- // Handle relative imports
160
- if (source.startsWith('.') && importer) {
161
- const cleanSource = source.replace(transformer.pattern, '');
162
- // Strip query parameters from importer to get the file path
163
- const cleanImporter = importer.indexOf('?') >= 0
164
- ? importer.substring(0, importer.indexOf('?'))
165
- : importer;
166
- // Always use dirname to get the directory containing the importer
167
- const baseDir = path.dirname(cleanImporter);
168
- const resolved = path.resolve(baseDir, cleanSource);
169
- // Return with the pattern suffix to identify it in load
170
- const suffix = source.match(transformer.pattern)?.[0] || '';
171
- return resolved + suffix;
172
- }
173
- return source;
174
- }
175
- }
176
- return null; // Let other plugins handle it
177
- },
178
- /**
179
- * Load and transform the file content
180
- */
181
- async load(id) {
182
- // Find matching transformer
183
- let matchedTransformer;
184
- let cleanId = id;
185
- for (const transformer of transformers) {
186
- if (transformer.pattern.test(id)) {
187
- matchedTransformer = transformer;
188
- // Remove query parameters to get actual file path
189
- // For example: '/path/file.md?skill' -> '/path/file.md'
190
- // '/path/file.html?raw' -> '/path/file.html'
191
- const queryIndex = id.indexOf('?');
192
- cleanId = queryIndex >= 0 ? id.substring(0, queryIndex) : id;
193
- break;
194
- }
195
- }
196
- if (!matchedTransformer) {
197
- return null; // Not for us
198
- }
199
- try {
200
- // Read file content (skip for virtual transforms)
201
- const content = matchedTransformer.virtual
202
- ? ''
203
- : readFileSync(cleanId, 'utf-8');
204
- // Transform the content
205
- const result = await matchedTransformer.transform(content, cleanId);
206
- // Collect assets if any
207
- if (result.assets && shouldCopyAssets) {
208
- assetsToProcess.push(...result.assets);
209
- }
210
- // Collect widgets if any
211
- if (result.widgets && shouldCompileWidgets) {
212
- widgetsToCompile.push(...result.widgets);
213
- }
214
- // Validate if schema provided
215
- if (matchedTransformer.schema) {
216
- const validation = matchedTransformer.schema.safeParse(result.data);
217
- if (!validation.success) {
218
- const errors = validation.error.errors
219
- .map((err) => ` - ${err.path.join('.')}: ${err.message}`)
220
- .join('\n');
221
- throw new Error(`Validation failed for ${id}:\n${errors}`);
222
- }
223
- }
224
- // Generate code
225
- const imports = result.imports ? result.imports.join('\n') + '\n\n' : '';
226
- if (result.code) {
227
- // Custom code provided - prepend imports
228
- return imports + result.code;
229
- }
230
- else {
231
- // Default: export data (escape if string, otherwise stringify as JSON)
232
- const dataJson = JSON.stringify(result.data, null, 2);
233
- return `${imports}export default ${dataJson};`;
234
- }
235
- }
236
- catch (error) {
237
- const message = error instanceof Error ? error.message : String(error);
238
- this.error(`Failed to transform ${id}: ${message}`);
239
- }
240
- },
241
- /**
242
- * Copy assets and compile widgets after all modules are loaded
243
- */
244
- async buildEnd() {
245
- // Copy script assets
246
- if (shouldCopyAssets && assetsToProcess.length > 0) {
247
- try {
248
- const copied = copyAssets(assetsToProcess, assetsDir);
249
- console.log(`Copied ${copied} asset file(s) to ${assetsDir}`);
250
- }
251
- catch (error) {
252
- const message = error instanceof Error ? error.message : String(error);
253
- this.warn(`Failed to copy assets: ${message}`);
254
- }
255
- }
256
- // Compile widgets
257
- if (shouldCompileWidgets && widgetsToCompile.length > 0) {
258
- try {
259
- const widgetsDir = config.widgetsDir || 'widgets';
260
- const outputDir = path.join(assetsDir, widgetsDir);
261
- console.log(`Compiling ${widgetsToCompile.length} widget(s)...`);
262
- const compiled = await compileWidgets(widgetsToCompile, outputDir, widgetConfig);
263
- console.log(`Compiled ${compiled} widget(s) to ${outputDir}`);
264
- }
265
- catch (error) {
266
- const message = error instanceof Error ? error.message : String(error);
267
- this.error(`Failed to compile widgets: ${message}`);
268
- }
269
- }
270
- }
271
- };
272
- }
273
-
274
- /**
275
- * Frontmatter parser utility using gray-matter
276
- */
277
- /**
278
- * Parse YAML frontmatter from markdown content
279
- *
280
- * @param content - Raw markdown content with optional frontmatter
281
- * @returns Parsed frontmatter and content
282
- */
283
- function parseFrontmatter(content) {
284
- const result = matter(content);
285
- return {
286
- frontmatter: result.data,
287
- content: result.content,
288
- original: content
289
- };
290
- }
291
-
292
- /**
293
- * Utilities for discovering asset files (scripts, widgets) in skill directories
294
- */
295
- /**
296
- * Check if a file exists and is a regular file
297
- */
298
- function isFile(filePath) {
299
- try {
300
- return statSync(filePath).isFile();
301
- }
302
- catch {
303
- return false;
304
- }
305
- }
306
- /**
307
- * Get all files in a directory (non-recursive)
308
- */
309
- function getFilesInDirectory(dirPath) {
310
- try {
311
- return readdirSync(dirPath).filter(file => {
312
- const fullPath = path.join(dirPath, file);
313
- return isFile(fullPath);
314
- });
315
- }
316
- catch {
317
- return [];
318
- }
319
- }
320
- /**
321
- * Check if a file is a script file (.js or .py)
322
- */
323
- function isScriptFile(fileName) {
324
- return /\.(js|py)$/.test(fileName);
325
- }
326
- /**
327
- * Check if a file is a widget file (.tsx)
328
- */
329
- function isWidgetFile(fileName) {
330
- return /\.tsx$/.test(fileName);
331
- }
332
- /**
333
- * Extract widget name from .tsx file (remove extension)
334
- */
335
- function getWidgetName(fileName) {
336
- return fileName.replace(/\.tsx$/, '');
337
- }
338
- /**
339
- * Discover assets (scripts and widgets) in a skill directory
340
- *
341
- * @param skillFilePath - Absolute path to the skill.md file
342
- * @param options - Asset discovery options
343
- * @returns Discovered assets and metadata
344
- */
345
- function discoverSkillAssets(skillFilePath, options = {}) {
346
- const skillDir = path.dirname(skillFilePath);
347
- const files = getFilesInDirectory(skillDir);
348
- const scripts = [];
349
- const widgets = [];
350
- const widgetMetadata = [];
351
- const assetFiles = [];
352
- const scriptsDir = options.scriptsDir || 'scripts';
353
- for (const file of files) {
354
- const fullPath = path.join(skillDir, file);
355
- if (isScriptFile(file)) {
356
- // Script file (.js or .py)
357
- scripts.push(file);
358
- assetFiles.push({
359
- sourcePath: fullPath,
360
- destPath: path.join(scriptsDir, file),
361
- type: 'script'
362
- });
363
- }
364
- else if (isWidgetFile(file)) {
365
- // Widget file (.tsx)
366
- const widgetName = getWidgetName(file);
367
- widgets.push(widgetName);
368
- widgetMetadata.push({
369
- name: widgetName,
370
- path: fullPath
371
- });
372
- // Note: We don't add widget .tsx files to assetFiles
373
- // Widgets are compiled by the plugin if widgetConfig is provided
374
- }
375
- }
376
- return {
377
- scripts,
378
- widgets,
379
- widgetMetadata,
380
- assetFiles
381
- };
382
- }
383
-
384
- /**
385
- * Skill transformer preset for markdown files with frontmatter
386
- */
387
- /**
388
- * Context triggers for auto-injection of skills (for frontmatter validation)
389
- */
390
- const SkillContextTriggersFrontmatterSchema = z.object({
391
- keywords: z.array(z.string()).optional(),
392
- tool_names: z.array(z.string()).optional(),
393
- data_patterns: z.array(z.string()).optional()
394
- }).strict();
395
- /**
396
- * Context triggers for auto-injection of skills (for output validation)
397
- */
398
- const SkillContextTriggersSchema = z.object({
399
- keywords: z.array(z.string()).optional(),
400
- tool_names: z.array(z.string()).optional(),
401
- data_patterns: z.array(z.string()).optional()
402
- }).optional();
403
- /**
404
- * Execution configuration for skills that need code execution (for frontmatter validation)
405
- */
406
- const SkillExecutionFrontmatterSchema = z.object({
407
- language: z.string(),
408
- packages: z.array(z.string()).optional(),
409
- system_packages: z.array(z.string()).optional(),
410
- template: z.string().optional()
411
- }).strict();
412
- /**
413
- * Execution configuration for skills that need code execution (for output validation)
414
- */
415
- const SkillExecutionSchema = z.object({
416
- language: z.string(),
417
- packages: z.array(z.string()).optional(),
418
- system_packages: z.array(z.string()).optional(),
419
- template: z.string().optional()
420
- }).optional();
421
- /**
422
- * Zod schema for skill frontmatter validation
423
- * This validates the YAML frontmatter before transformation
424
- * Supports both flat and nested structures
425
- */
426
- const SkillFrontmatterSchema = z.object({
427
- // Required fields
428
- name: z.string().min(1, 'Skill name is required'),
429
- description: z.string().min(1, 'Skill description is required'),
430
- // Optional fields
431
- title: z.string().optional(),
432
- content_type: z.enum(['md', 'jst']).optional(),
433
- // Flat structure fields (legacy)
434
- keywords: z.array(z.string()).optional(),
435
- tools: z.array(z.string()).optional(),
436
- data_patterns: z.array(z.string()).optional(),
437
- language: z.string().optional(),
438
- packages: z.array(z.string()).optional(),
439
- system_packages: z.array(z.string()).optional(),
440
- // Nested structure fields
441
- context_triggers: SkillContextTriggersFrontmatterSchema.optional(),
442
- execution: SkillExecutionFrontmatterSchema.optional(),
443
- related_tools: z.array(z.string()).optional(),
444
- input_schema: z.object({
445
- type: z.literal('object'),
446
- properties: z.record(z.any()).optional(),
447
- required: z.array(z.string()).optional()
448
- }).optional(),
449
- // Asset fields (auto-discovered but can be overridden)
450
- scripts: z.array(z.string()).optional(),
451
- widgets: z.array(z.string()).optional()
452
- }).strict();
453
- /**
454
- * MUST be kept in sync with @vertesia/tools-sdk SkillDefinition
455
- * Zod schema for skill definition
456
- * This validates the structure of skill objects generated from markdown
457
- * Matches the SkillDefinition interface from @vertesia/tools-sdk
458
- *
459
- * Note: The isEnabled property is not included in this schema because Zod cannot
460
- * properly validate function signatures. It will be type-checked by TypeScript instead.
461
- */
462
- const SkillDefinitionSchema = z.object({
463
- name: z.string().min(1, 'Skill name is required'),
464
- title: z.string().optional(),
465
- description: z.string().min(1, 'Skill description is required'),
466
- instructions: z.string(),
467
- content_type: z.enum(['md', 'jst']),
468
- input_schema: z.object({
469
- type: z.literal('object'),
470
- properties: z.record(z.any()).optional(),
471
- required: z.array(z.string()).optional()
472
- }).optional(),
473
- context_triggers: SkillContextTriggersSchema,
474
- execution: SkillExecutionSchema,
475
- related_tools: z.array(z.string()).optional(),
476
- scripts: z.array(z.string()).optional(),
477
- widgets: z.array(z.string()).optional()
478
- }).passthrough();
479
- /**
480
- * Schema for validating properties exported from properties.ts
481
- * This is a partial schema - allows any subset of SkillDefinition fields
482
- *
483
- * Note: Function properties like isEnabled cannot be validated by Zod for their signatures.
484
- * Zod will only check that they are functions, not their specific parameter/return types.
485
- * Use TypeScript for proper type checking of function signatures.
486
- */
487
- const SkillPropertiesSchema = SkillDefinitionSchema.partial().passthrough();
488
- /**
489
- * Build a SkillDefinition from frontmatter and markdown content.
490
- * This mirrors the logic in @vertesia/tools-sdk parseSkillFile function.
491
- *
492
- * Supports two frontmatter structures:
493
- *
494
- * 1. Flat structure (matches parseSkillFile in tools-sdk):
495
- * keywords: [...]
496
- * tools: [...]
497
- * language: python
498
- * packages: [...]
499
- *
500
- * 2. Nested structure (for more explicit YAML):
501
- * context_triggers:
502
- * keywords: [...]
503
- * tool_names: [...]
504
- * execution:
505
- * language: python
506
- * packages: [...]
507
- * related_tools: [...]
508
- *
509
- * @param frontmatter - Parsed frontmatter object
510
- * @param instructions - Markdown content (body of the file)
511
- * @param contentType - Content type ('md' or 'jst')
512
- * @param widgets - Discovered widget names
513
- * @param scripts - Discovered script names
514
- * @returns Skill definition object
515
- */
516
- function buildSkillDefinition(frontmatter, instructions, contentType, widgets, scripts) {
517
- const skill = {
518
- name: frontmatter.name,
519
- title: frontmatter.title,
520
- description: frontmatter.description,
521
- instructions,
522
- content_type: contentType,
523
- widgets: widgets.length > 0 ? widgets : undefined,
524
- scripts: scripts.length > 0 ? scripts : undefined,
525
- };
526
- // Build context triggers - support both flat and nested structure
527
- // Nested: context_triggers: { keywords: [...], tool_names: [...] }
528
- // Flat: keywords: [...], tools: [...]
529
- const contextTriggers = frontmatter.context_triggers;
530
- const hasNestedTriggers = contextTriggers && typeof contextTriggers === 'object';
531
- const hasFlatTriggers = frontmatter.keywords || frontmatter.tools || frontmatter.data_patterns;
532
- if (hasNestedTriggers || hasFlatTriggers) {
533
- skill.context_triggers = {
534
- keywords: hasNestedTriggers ? contextTriggers.keywords : frontmatter.keywords,
535
- tool_names: hasNestedTriggers ? contextTriggers.tool_names : frontmatter.tools,
536
- data_patterns: hasNestedTriggers ? contextTriggers.data_patterns : frontmatter.data_patterns,
537
- };
538
- }
539
- // Build execution config - support both flat and nested structure
540
- const execution = frontmatter.execution;
541
- const hasNestedExecution = execution && typeof execution === 'object';
542
- const hasFlatExecution = frontmatter.language;
543
- if (hasNestedExecution || hasFlatExecution) {
544
- skill.execution = {
545
- language: hasNestedExecution ? execution.language : frontmatter.language,
546
- packages: hasNestedExecution ? execution.packages : frontmatter.packages,
547
- system_packages: hasNestedExecution ? execution.system_packages : frontmatter.system_packages,
548
- };
549
- // Extract code template from instructions if present
550
- const codeBlockMatch = instructions.match(/```(?:python|javascript|typescript|js|ts|py)\n([\s\S]*?)```/);
551
- if (codeBlockMatch) {
552
- skill.execution.template = codeBlockMatch[1].trim();
553
- }
554
- }
555
- // Related tools - support both direct field and from tools field
556
- if (frontmatter.related_tools) {
557
- skill.related_tools = frontmatter.related_tools;
558
- }
559
- else if (frontmatter.tools && !hasNestedTriggers) {
560
- // If tools is not part of context_triggers, use it as related_tools
561
- skill.related_tools = frontmatter.tools;
562
- }
563
- // Input schema from frontmatter
564
- if (frontmatter.input_schema) {
565
- skill.input_schema = frontmatter.input_schema;
566
- }
567
- return skill;
568
- }
569
- /**
570
- * Skill transformer preset
571
- * Transforms markdown files with ?skill suffix OR SKILL.md files into skill definition objects
572
- *
573
- * Matches:
574
- * - Files with ?skill suffix: ./my-skill.md?skill
575
- * - SKILL.md files: ./my-skill/SKILL.md
576
- *
577
- * Runtime Properties:
578
- * - Supports properties.ts file in skill directory for runtime properties (functions, overrides)
579
- * - Properties from properties.ts override those from frontmatter
580
- * - See README.md for detailed usage examples
581
- *
582
- * @example
583
- * ```typescript
584
- * import skill1 from './my-skill.md?skill';
585
- * import skill2 from './my-skill/SKILL.md';
586
- * // Both are SkillDefinition objects
587
- * ```
588
- */
589
- const skillTransformer = {
590
- pattern: /(\.md\?skill$|\/SKILL\.md$)/,
591
- schema: SkillDefinitionSchema,
592
- transform: (content, filePath) => {
593
- const { frontmatter, content: markdown } = parseFrontmatter(content);
594
- // Validate frontmatter first to catch unknown properties
595
- const frontmatterValidation = SkillFrontmatterSchema.safeParse(frontmatter);
596
- if (!frontmatterValidation.success) {
597
- const errors = frontmatterValidation.error.errors
598
- .map((err) => {
599
- const pathStr = err.path.length > 0 ? err.path.join('.') : 'frontmatter';
600
- return ` - ${pathStr}: ${err.message}`;
601
- })
602
- .join('\n');
603
- throw new Error(`Invalid frontmatter in ${filePath}:\n${errors}`);
604
- }
605
- // Determine content type from frontmatter or file extension
606
- const content_type = frontmatter.content_type || 'md';
607
- // Discover assets (scripts and widgets) in the skill directory
608
- const assets = discoverSkillAssets(filePath);
609
- // Build skill definition using the same logic as parseSkillFile in tools-sdk
610
- const skillData = buildSkillDefinition(frontmatter, markdown, content_type, assets.widgets, assets.scripts);
611
- // Check if properties.ts exists in the skill directory
612
- const skillDir = path.dirname(filePath);
613
- const propertiesPath = path.join(skillDir, 'properties.ts');
614
- const hasProperties = existsSync(propertiesPath);
615
- // If properties.ts exists, generate custom code with import and merge
616
- // Rollup will handle transpiling properties.ts to properties.js
617
- if (hasProperties) {
618
- const skillDataJson = JSON.stringify(skillData, null, 2);
619
- const code = `import properties from './properties.js';
620
-
621
- // Runtime validation for function properties
622
- if ('isEnabled' in properties && typeof properties.isEnabled !== 'function') {
623
- throw new Error('properties.isEnabled must be a function, got ' + typeof properties.isEnabled);
624
- }
625
-
626
- const skill = ${skillDataJson};
627
-
628
- export default { ...skill, ...properties };
629
- `;
630
- return {
631
- data: skillData,
632
- assets: assets.assetFiles,
633
- widgets: assets.widgetMetadata,
634
- code
635
- };
636
- }
637
- return {
638
- data: skillData,
639
- assets: assets.assetFiles,
640
- widgets: assets.widgetMetadata
641
- };
642
- }
643
- };
644
-
645
- /**
646
- * Skill collection transformer for directory-based skill imports
647
- * Scans a directory for subdirectories containing SKILL.md files
648
- */
649
- /**
650
- * Skill collection transformer preset
651
- * Transforms directory imports with ?skills suffix into an array of skill imports
652
- *
653
- * Matches:
654
- * - ./all?skills (recommended - generates all.js in the directory)
655
- * - ./_skills?skills (generates _skills.js in the directory)
656
- * - Any path ending with a filename and ?skills
657
- *
658
- * NOTE: A filename before ?skills is REQUIRED to avoid naming conflicts.
659
- * The filename becomes the output module name.
660
- *
661
- * @example
662
- * ```typescript
663
- * import skills from './all?skills';
664
- * // Scans current directory for subdirectories with SKILL.md
665
- * // Generates all.js containing array of all skills
666
- * ```
667
- */
668
- const skillCollectionTransformer = {
669
- pattern: /\/[^/?]+\?skills$/,
670
- virtual: true, // Indicates this doesn't transform a real file
671
- transform: (_content, filePath) => {
672
- // Remove ?skills suffix and the filename to get directory path
673
- // Example: /path/code/all?skills -> /path/code/all -> /path/code/
674
- const pathWithoutQuery = filePath.replace(/\?skills$/, '');
675
- const dirPath = path.dirname(pathWithoutQuery);
676
- if (!existsSync(dirPath)) {
677
- throw new Error(`Directory not found: ${dirPath}`);
678
- }
679
- if (!statSync(dirPath).isDirectory()) {
680
- throw new Error(`Not a directory: ${dirPath}`);
681
- }
682
- // Scan for subdirectories containing SKILL.md
683
- const entries = readdirSync(dirPath);
684
- const imports = [];
685
- const names = [];
686
- for (const entry of entries) {
687
- const entryPath = path.join(dirPath, entry);
688
- try {
689
- if (statSync(entryPath).isDirectory()) {
690
- const skillFile = path.join(entryPath, 'SKILL.md');
691
- if (existsSync(skillFile)) {
692
- // Generate unique identifier from directory name
693
- const identifier = `Skill_${entry.replace(/[^a-zA-Z0-9_]/g, '_')}`;
694
- imports.push(`import ${identifier} from './${entry}/SKILL.md';`);
695
- names.push(identifier);
696
- }
697
- }
698
- }
699
- catch (err) {
700
- // Skip entries that can't be read
701
- continue;
702
- }
703
- }
704
- if (names.length === 0) {
705
- console.warn(`No SKILL.md files found in subdirectories of ${dirPath}`);
706
- }
707
- // Generate code that imports all skills and exports as array
708
- const code = [
709
- ...imports,
710
- '',
711
- `export default [${names.join(', ')}];`
712
- ].join('\n');
713
- return {
714
- data: null, // Not used when custom code is provided
715
- code
716
- };
717
- }
718
- };
719
-
720
- /**
721
- * Utilities for discovering asset files in template directories
722
- */
723
- /**
724
- * Files to exclude from template asset discovery
725
- * (source files and the template definition itself)
726
- */
727
- const EXCLUDED_PATTERNS = [
728
- /^TEMPLATE\.md$/,
729
- /\.ts$/,
730
- /\.js$/,
731
- ];
732
- function isExcluded(fileName) {
733
- return EXCLUDED_PATTERNS.some(p => p.test(fileName));
734
- }
735
- /**
736
- * Discover asset files in a template directory.
737
- * All files except TEMPLATE.md, *.ts, and *.js are considered assets.
738
- *
739
- * @param templateFilePath - Absolute path to the TEMPLATE.md file
740
- * @param templatePath - The template path segment (e.g., "examples/report")
741
- * @returns Discovered assets and metadata
742
- */
743
- function discoverTemplateAssets(templateFilePath, templatePath) {
744
- const templateDir = path.dirname(templateFilePath);
745
- const fileNames = [];
746
- const assetFiles = [];
747
- let files;
748
- try {
749
- files = readdirSync(templateDir).filter(file => {
750
- try {
751
- return statSync(path.join(templateDir, file)).isFile();
752
- }
753
- catch {
754
- return false;
755
- }
756
- });
757
- }
758
- catch {
759
- files = [];
760
- }
761
- for (const file of files) {
762
- if (isExcluded(file)) {
763
- continue;
764
- }
765
- fileNames.push(file);
766
- assetFiles.push({
767
- sourcePath: path.join(templateDir, file),
768
- destPath: path.join('templates', templatePath, file),
769
- type: 'template',
770
- });
771
- }
772
- return { fileNames, assetFiles };
773
- }
774
-
775
- /**
776
- * Template transformer preset for markdown files with frontmatter
777
- */
778
- /**
779
- * Zod schema for template frontmatter validation.
780
- * Only includes fields authored by the user.
781
- * The name and id are inferred from the directory structure.
782
- */
783
- const TemplateFrontmatterSchema = z.object({
784
- title: z.string().optional(),
785
- description: z.string().min(1, 'Template description is required'),
786
- tags: z.array(z.string()).optional(),
787
- type: z.enum(['presentation', 'document']),
788
- }).strict();
789
- /**
790
- * MUST be kept in sync with @vertesia/tools-sdk RenderingTemplateDefinition
791
- * Zod schema for template definition
792
- */
793
- const RenderingTemplateDefinitionSchema = z.object({
794
- id: z.string().min(1, 'Template id is required'),
795
- name: z.string().min(1, 'Template name is required'),
796
- title: z.string().optional(),
797
- description: z.string().min(1, 'Template description is required'),
798
- instructions: z.string(),
799
- tags: z.array(z.string()).optional(),
800
- type: z.enum(['presentation', 'document']),
801
- assets: z.array(z.string()),
802
- }).passthrough();
803
- /**
804
- * Derive the template path segments from the file path.
805
- *
806
- * Example: .../templates/examples/report/TEMPLATE.md
807
- * → category: "examples", name: "report", relative: "examples/report"
808
- */
809
- function deriveTemplatePathInfo(filePath) {
810
- const templateDir = path.dirname(filePath);
811
- const templateName = path.basename(templateDir);
812
- const collectionDir = path.dirname(templateDir);
813
- const category = path.basename(collectionDir);
814
- return { category, templateName, relative: `${category}/${templateName}` };
815
- }
816
- /**
817
- * Template transformer preset
818
- * Transforms markdown files with ?template suffix OR TEMPLATE.md files into template definition objects
819
- *
820
- * Matches:
821
- * - Files with ?template suffix: ./my-template.md?template
822
- * - TEMPLATE.md files: ./my-template/TEMPLATE.md
823
- *
824
- * @example
825
- * ```typescript
826
- * import template1 from './my-template.md?template';
827
- * import template2 from './my-template/TEMPLATE.md';
828
- * // Both are RenderingTemplateDefinition objects
829
- * ```
830
- */
831
- const templateTransformer = {
832
- pattern: /(\.md\?template$|\/TEMPLATE\.md$)/,
833
- schema: RenderingTemplateDefinitionSchema,
834
- transform: (content, filePath) => {
835
- const { frontmatter, content: markdown } = parseFrontmatter(content);
836
- // Validate frontmatter
837
- const frontmatterValidation = TemplateFrontmatterSchema.safeParse(frontmatter);
838
- if (!frontmatterValidation.success) {
839
- const errors = frontmatterValidation.error.errors
840
- .map((err) => {
841
- const pathStr = err.path.length > 0 ? err.path.join('.') : 'frontmatter';
842
- return ` - ${pathStr}: ${err.message}`;
843
- })
844
- .join('\n');
845
- throw new Error(`Invalid frontmatter in ${filePath}:\n${errors}`);
846
- }
847
- // Derive template path from directory structure
848
- const { category, templateName, relative: templatePath } = deriveTemplatePathInfo(filePath);
849
- // Discover asset files in the template directory
850
- const assets = discoverTemplateAssets(filePath, templatePath);
851
- // Build template definition
852
- // Assets use absolute paths for direct server-side resolution
853
- const templateData = {
854
- id: `${category}:${templateName}`,
855
- name: templateName,
856
- title: frontmatter.title,
857
- description: frontmatter.description,
858
- instructions: markdown,
859
- tags: frontmatter.tags,
860
- type: frontmatter.type,
861
- assets: assets.fileNames.map(f => `/templates/${templatePath}/${f}`),
862
- };
863
- return {
864
- data: templateData,
865
- assets: assets.assetFiles,
866
- };
867
- }
868
- };
869
-
870
- /**
871
- * Template collection transformer for directory-based template imports
872
- * Scans a directory for subdirectories containing TEMPLATE.md files
873
- */
874
- /**
875
- * Template collection transformer preset
876
- * Transforms directory imports with ?templates suffix into an array of template imports
877
- *
878
- * Matches:
879
- * - ./all?templates (recommended - generates all.js in the directory)
880
- * - Any path ending with a filename and ?templates
881
- *
882
- * NOTE: A filename before ?templates is REQUIRED to avoid naming conflicts.
883
- * The filename becomes the output module name.
884
- *
885
- * @example
886
- * ```typescript
887
- * import templates from './all?templates';
888
- * // Scans current directory for subdirectories with TEMPLATE.md
889
- * // Generates all.js containing array of all templates
890
- * ```
891
- */
892
- const templateCollectionTransformer = {
893
- pattern: /\/[^/?]+\?templates$/,
894
- virtual: true,
895
- transform: (_content, filePath) => {
896
- // Remove ?templates suffix and the filename to get directory path
897
- const pathWithoutQuery = filePath.replace(/\?templates$/, '');
898
- const dirPath = path.dirname(pathWithoutQuery);
899
- if (!existsSync(dirPath)) {
900
- throw new Error(`Directory not found: ${dirPath}`);
901
- }
902
- if (!statSync(dirPath).isDirectory()) {
903
- throw new Error(`Not a directory: ${dirPath}`);
904
- }
905
- // Scan for subdirectories containing TEMPLATE.md
906
- const entries = readdirSync(dirPath);
907
- const imports = [];
908
- const names = [];
909
- for (const entry of entries) {
910
- const entryPath = path.join(dirPath, entry);
911
- try {
912
- if (statSync(entryPath).isDirectory()) {
913
- const templateFile = path.join(entryPath, 'TEMPLATE.md');
914
- if (existsSync(templateFile)) {
915
- const identifier = `Template_${entry.replace(/[^a-zA-Z0-9_]/g, '_')}`;
916
- imports.push(`import ${identifier} from './${entry}/TEMPLATE.md';`);
917
- names.push(identifier);
918
- }
919
- }
920
- }
921
- catch (_err) {
922
- // Skip entries that can't be read
923
- continue;
924
- }
925
- }
926
- if (names.length === 0) {
927
- console.warn(`No TEMPLATE.md files found in subdirectories of ${dirPath}`);
928
- }
929
- // Generate code that imports all templates and exports as array
930
- const code = [
931
- ...imports,
932
- '',
933
- `export default [${names.join(', ')}];`
934
- ].join('\n');
935
- return {
936
- data: null,
937
- code
938
- };
939
- }
940
- };
941
-
942
- /**
943
- * Raw transformer preset for importing file content as strings
944
- */
945
- /**
946
- * Raw transformer preset
947
- * Transforms any file with ?raw suffix into a string export
948
- *
949
- * @example
950
- * ```typescript
951
- * import template from './template.html?raw';
952
- * // template is a string containing the file content
953
- * ```
954
- */
955
- const rawTransformer = {
956
- pattern: /\?raw$/,
957
- transform: (content) => {
958
- return {
959
- data: content
960
- };
961
- }
962
- };
963
-
964
- /**
965
- * @module access-control
966
- * @description
967
- * Access control interfaces
968
- */
969
- var Permission;
970
- (function (Permission) {
971
- Permission["int_read"] = "interaction:read";
972
- Permission["int_write"] = "interaction:write";
973
- Permission["int_delete"] = "interaction:delete";
974
- Permission["int_execute"] = "interaction:execute";
975
- Permission["run_read"] = "run:read";
976
- Permission["run_write"] = "run:write";
977
- Permission["env_admin"] = "environment:admin";
978
- Permission["project_admin"] = "project:admin";
979
- Permission["project_integration_read"] = "project:integration_read";
980
- Permission["project_settings_write"] = "project:settings_write";
981
- Permission["api_key_create"] = "api_key:create";
982
- Permission["api_key_read"] = "api_key:read";
983
- Permission["api_key_update"] = "api_key:update";
984
- Permission["api_key_delete"] = "api_key:delete";
985
- Permission["account_read"] = "account:read";
986
- Permission["account_write"] = "account:write";
987
- Permission["account_admin"] = "account:admin";
988
- Permission["manage_billing"] = "account:billing";
989
- /** View cost and usage analytics */
990
- Permission["billing_read"] = "billing:read";
991
- Permission["account_member"] = "account:member";
992
- Permission["content_read"] = "content:read";
993
- Permission["content_write"] = "content:write";
994
- Permission["content_delete"] = "content:delete";
995
- Permission["content_admin"] = "content:admin";
996
- Permission["content_superadmin"] = "content:superadmin";
997
- Permission["workflow_run"] = "workflow:run";
998
- Permission["workflow_admin"] = "workflow:admin";
999
- Permission["workflow_superadmin"] = "workflow:superadmin";
1000
- Permission["iam_impersonate"] = "iam:impersonate";
1001
- /** whether the user has access to Sutdio App. */
1002
- Permission["studio_access"] = "studio:access";
1003
- })(Permission || (Permission = {}));
1004
- var AccessControlResourceType;
1005
- (function (AccessControlResourceType) {
1006
- AccessControlResourceType["project"] = "project";
1007
- AccessControlResourceType["environment"] = "environment";
1008
- AccessControlResourceType["account"] = "account";
1009
- AccessControlResourceType["interaction"] = "interaction";
1010
- AccessControlResourceType["app"] = "application";
1011
- /** Dynamic resource matching by content properties at query time. */
1012
- AccessControlResourceType["content_set"] = "content_set";
1013
- })(AccessControlResourceType || (AccessControlResourceType = {}));
1014
- var AccessControlPrincipalType;
1015
- (function (AccessControlPrincipalType) {
1016
- AccessControlPrincipalType["user"] = "user";
1017
- AccessControlPrincipalType["group"] = "group";
1018
- AccessControlPrincipalType["apikey"] = "apikey";
1019
- /** Dynamic principal matching by user/group properties at token time. */
1020
- AccessControlPrincipalType["principal_set"] = "principal_set";
1021
- })(AccessControlPrincipalType || (AccessControlPrincipalType = {}));
1022
- // ============================================================================
1023
- // BLP Security Levels
1024
- // ============================================================================
1025
- /**
1026
- * Default sensitivity/clearance levels for the Bell-LaPadula security model.
1027
- * The numeric value is the index in the array (0 = lowest, 4 = highest).
1028
- * Projects can override these labels via project settings.
1029
- */
1030
- var SecurityLevel;
1031
- (function (SecurityLevel) {
1032
- SecurityLevel[SecurityLevel["public"] = 0] = "public";
1033
- SecurityLevel[SecurityLevel["internal"] = 1] = "internal";
1034
- SecurityLevel[SecurityLevel["confidential"] = 2] = "confidential";
1035
- SecurityLevel[SecurityLevel["restricted"] = 3] = "restricted";
1036
- SecurityLevel[SecurityLevel["secret"] = 4] = "secret";
1037
- })(SecurityLevel || (SecurityLevel = {}));
1038
-
1039
- var ApiKeyTypes;
1040
- (function (ApiKeyTypes) {
1041
- ApiKeyTypes["secret"] = "sk";
1042
- })(ApiKeyTypes || (ApiKeyTypes = {}));
1043
- var PrincipalType;
1044
- (function (PrincipalType) {
1045
- PrincipalType["User"] = "user";
1046
- PrincipalType["Group"] = "group";
1047
- PrincipalType["ApiKey"] = "apikey";
1048
- PrincipalType["ServiceAccount"] = "service_account";
1049
- PrincipalType["Agent"] = "agent";
1050
- PrincipalType["Schedule"] = "schedule";
1051
- })(PrincipalType || (PrincipalType = {}));
1052
-
1053
- var InteractionStatus;
1054
- (function (InteractionStatus) {
1055
- InteractionStatus["draft"] = "draft";
1056
- InteractionStatus["published"] = "published";
1057
- InteractionStatus["archived"] = "archived";
1058
- InteractionStatus["code"] = "code";
1059
- InteractionStatus["unknown"] = "unknown";
1060
- })(InteractionStatus || (InteractionStatus = {}));
1061
- var ExecutionRunStatus;
1062
- (function (ExecutionRunStatus) {
1063
- ExecutionRunStatus["created"] = "created";
1064
- ExecutionRunStatus["processing"] = "processing";
1065
- ExecutionRunStatus["completed"] = "completed";
1066
- ExecutionRunStatus["failed"] = "failed";
1067
- })(ExecutionRunStatus || (ExecutionRunStatus = {}));
1068
- var RunDataStorageLevel;
1069
- (function (RunDataStorageLevel) {
1070
- RunDataStorageLevel["STANDARD"] = "STANDARD";
1071
- RunDataStorageLevel["RESTRICTED"] = "RESTRICTED";
1072
- RunDataStorageLevel["DEBUG"] = "DEBUG";
1073
- })(RunDataStorageLevel || (RunDataStorageLevel = {}));
1074
- var RunDataStorageDescription;
1075
- (function (RunDataStorageDescription) {
1076
- RunDataStorageDescription["STANDARD"] = "Run data is stored for both the model inputs and output.";
1077
- RunDataStorageDescription["RESTRICTED"] = "No run data is stored for the model inputs \u2014 only the model output.";
1078
- RunDataStorageDescription["DEBUG"] = "Run data is stored for the model inputs and output, schema, and final prompt.";
1079
- })(RunDataStorageDescription || (RunDataStorageDescription = {}));
1080
- ({
1081
- [RunDataStorageLevel.STANDARD]: RunDataStorageDescription.STANDARD,
1082
- [RunDataStorageLevel.RESTRICTED]: RunDataStorageDescription.RESTRICTED,
1083
- [RunDataStorageLevel.DEBUG]: RunDataStorageDescription.DEBUG,
1084
- });
1085
- /**
1086
- * Defines the scope for agent search operations.
1087
- */
1088
- var AgentSearchScope;
1089
- (function (AgentSearchScope) {
1090
- /**
1091
- * Search is scoped to a specific collection.
1092
- */
1093
- AgentSearchScope["Collection"] = "collection";
1094
- })(AgentSearchScope || (AgentSearchScope = {}));
1095
- // ================= end async execution payloads ====================
1096
- var RunSourceTypes;
1097
- (function (RunSourceTypes) {
1098
- RunSourceTypes["api"] = "api";
1099
- RunSourceTypes["cli"] = "cli";
1100
- RunSourceTypes["ui"] = "ui";
1101
- RunSourceTypes["webhook"] = "webhook";
1102
- RunSourceTypes["test"] = "test-data";
1103
- RunSourceTypes["system"] = "system";
1104
- RunSourceTypes["schedule"] = "schedule";
1105
- })(RunSourceTypes || (RunSourceTypes = {}));
1106
- var ConfigModes;
1107
- (function (ConfigModes) {
1108
- ConfigModes["RUN_AND_INTERACTION_CONFIG"] = "RUN_AND_INTERACTION_CONFIG";
1109
- ConfigModes["RUN_CONFIG_ONLY"] = "RUN_CONFIG_ONLY";
1110
- ConfigModes["INTERACTION_CONFIG_ONLY"] = "INTERACTION_CONFIG_ONLY";
1111
- })(ConfigModes || (ConfigModes = {}));
1112
- var ConfigModesDescription;
1113
- (function (ConfigModesDescription) {
1114
- ConfigModesDescription["RUN_AND_INTERACTION_CONFIG"] = "This run configuration is used. Undefined options are filled with interaction configuration.";
1115
- ConfigModesDescription["RUN_CONFIG_ONLY"] = "Only this run configuration is used. Undefined options remain undefined.";
1116
- ConfigModesDescription["INTERACTION_CONFIG_ONLY"] = "Only interaction configuration is used.";
1117
- })(ConfigModesDescription || (ConfigModesDescription = {}));
1118
- ({
1119
- [ConfigModes.RUN_AND_INTERACTION_CONFIG]: ConfigModesDescription.RUN_AND_INTERACTION_CONFIG,
1120
- [ConfigModes.RUN_CONFIG_ONLY]: ConfigModesDescription.RUN_CONFIG_ONLY,
1121
- [ConfigModes.INTERACTION_CONFIG_ONLY]: ConfigModesDescription.INTERACTION_CONFIG_ONLY,
1122
- });
1123
- /**
1124
- * Source of the resolved model configuration
1125
- */
1126
- var ModelSource;
1127
- (function (ModelSource) {
1128
- /** Model was explicitly provided in the execution config */
1129
- ModelSource["config"] = "config";
1130
- /** Model comes from the interaction definition */
1131
- ModelSource["interaction"] = "interaction";
1132
- /** Model comes from environment's default_model */
1133
- ModelSource["environmentDefault"] = "environmentDefault";
1134
- /** Model comes from project system interaction defaults */
1135
- ModelSource["projectSystemDefault"] = "projectSystemDefault";
1136
- /** Model comes from project base defaults */
1137
- ModelSource["projectBaseDefault"] = "projectBaseDefault";
1138
- /** Model comes from project modality-specific defaults */
1139
- ModelSource["projectModalityDefault"] = "projectModalityDefault";
1140
- /** Model comes from legacy project defaults */
1141
- ModelSource["projectLegacyDefault"] = "projectLegacyDefault";
1142
- })(ModelSource || (ModelSource = {}));
1143
-
1144
- /**
1145
- * Data Platform Types
1146
- *
1147
- * Types for managing versioned analytical data stores with DuckDB + GCS storage.
1148
- * Supports AI-manageable schemas and multi-table atomic operations.
1149
- */
1150
- // ============================================================================
1151
- // Column Types
1152
- // ============================================================================
1153
- /**
1154
- * Supported column data types for DuckDB tables.
1155
- */
1156
- var DataColumnType;
1157
- (function (DataColumnType) {
1158
- DataColumnType["STRING"] = "STRING";
1159
- DataColumnType["INTEGER"] = "INTEGER";
1160
- DataColumnType["BIGINT"] = "BIGINT";
1161
- DataColumnType["FLOAT"] = "FLOAT";
1162
- DataColumnType["DOUBLE"] = "DOUBLE";
1163
- DataColumnType["DECIMAL"] = "DECIMAL";
1164
- DataColumnType["BOOLEAN"] = "BOOLEAN";
1165
- DataColumnType["DATE"] = "DATE";
1166
- DataColumnType["TIMESTAMP"] = "TIMESTAMP";
1167
- DataColumnType["JSON"] = "JSON";
1168
- })(DataColumnType || (DataColumnType = {}));
1169
- /**
1170
- * Semantic types that provide AI agents with context about column meaning.
1171
- */
1172
- var SemanticColumnType;
1173
- (function (SemanticColumnType) {
1174
- SemanticColumnType["EMAIL"] = "email";
1175
- SemanticColumnType["PHONE"] = "phone";
1176
- SemanticColumnType["URL"] = "url";
1177
- SemanticColumnType["CURRENCY"] = "currency";
1178
- SemanticColumnType["PERCENTAGE"] = "percentage";
1179
- SemanticColumnType["PERSON_NAME"] = "person_name";
1180
- SemanticColumnType["ADDRESS"] = "address";
1181
- SemanticColumnType["COUNTRY"] = "country";
1182
- SemanticColumnType["DATE_ISO"] = "date_iso";
1183
- SemanticColumnType["IDENTIFIER"] = "identifier";
1184
- })(SemanticColumnType || (SemanticColumnType = {}));
1185
- /**
1186
- * Mapping from DataColumnType to DuckDB SQL types.
1187
- */
1188
- ({
1189
- [DataColumnType.STRING]: 'VARCHAR',
1190
- [DataColumnType.INTEGER]: 'INTEGER',
1191
- [DataColumnType.BIGINT]: 'BIGINT',
1192
- [DataColumnType.FLOAT]: 'FLOAT',
1193
- [DataColumnType.DOUBLE]: 'DOUBLE',
1194
- [DataColumnType.DECIMAL]: 'DECIMAL(18,4)',
1195
- [DataColumnType.BOOLEAN]: 'BOOLEAN',
1196
- [DataColumnType.DATE]: 'DATE',
1197
- [DataColumnType.TIMESTAMP]: 'TIMESTAMP',
1198
- [DataColumnType.JSON]: 'JSON',
1199
- });
1200
- // ============================================================================
1201
- // Data Store Types
1202
- // ============================================================================
1203
- /**
1204
- * Data store lifecycle status.
1205
- */
1206
- var DataStoreStatus;
1207
- (function (DataStoreStatus) {
1208
- /** Store is being created */
1209
- DataStoreStatus["CREATING"] = "creating";
1210
- /** Store is active and usable */
1211
- DataStoreStatus["ACTIVE"] = "active";
1212
- /** Store encountered an error */
1213
- DataStoreStatus["ERROR"] = "error";
1214
- /** Store has been archived (soft deleted) */
1215
- DataStoreStatus["ARCHIVED"] = "archived";
1216
- })(DataStoreStatus || (DataStoreStatus = {}));
1217
- // ============================================================================
1218
- // Import Types
1219
- // ============================================================================
1220
- /**
1221
- * Import job status.
1222
- */
1223
- var ImportStatus;
1224
- (function (ImportStatus) {
1225
- /** Job is queued */
1226
- ImportStatus["PENDING"] = "pending";
1227
- /** Job is running */
1228
- ImportStatus["PROCESSING"] = "processing";
1229
- /** Job completed successfully */
1230
- ImportStatus["COMPLETED"] = "completed";
1231
- /** Job failed */
1232
- ImportStatus["FAILED"] = "failed";
1233
- /** Job was rolled back */
1234
- ImportStatus["ROLLED_BACK"] = "rolled_back";
1235
- })(ImportStatus || (ImportStatus = {}));
1236
- // ============================================================================
1237
- // Dashboard Types
1238
- // ============================================================================
1239
- /**
1240
- * Dashboard lifecycle status.
1241
- */
1242
- var DashboardStatus;
1243
- (function (DashboardStatus) {
1244
- /** Dashboard is active and usable */
1245
- DashboardStatus["ACTIVE"] = "active";
1246
- /** Dashboard has been archived (soft deleted) */
1247
- DashboardStatus["ARCHIVED"] = "archived";
1248
- })(DashboardStatus || (DashboardStatus = {}));
1249
-
1250
- // ============== Provider details ===============
1251
- var Providers;
1252
- (function (Providers) {
1253
- Providers["openai"] = "openai";
1254
- Providers["openai_compatible"] = "openai_compatible";
1255
- Providers["azure_openai"] = "azure_openai";
1256
- Providers["azure_foundry"] = "azure_foundry";
1257
- Providers["huggingface_ie"] = "huggingface_ie";
1258
- Providers["replicate"] = "replicate";
1259
- Providers["bedrock"] = "bedrock";
1260
- Providers["vertexai"] = "vertexai";
1261
- Providers["togetherai"] = "togetherai";
1262
- Providers["mistralai"] = "mistralai";
1263
- Providers["groq"] = "groq";
1264
- Providers["watsonx"] = "watsonx";
1265
- Providers["xai"] = "xai";
1266
- Providers["anthropic"] = "anthropic";
1267
- })(Providers || (Providers = {}));
1268
- ({
1269
- openai: {
1270
- id: Providers.openai},
1271
- azure_openai: {
1272
- id: Providers.azure_openai},
1273
- azure_foundry: {
1274
- id: Providers.azure_foundry},
1275
- huggingface_ie: {
1276
- id: Providers.huggingface_ie},
1277
- replicate: {
1278
- id: Providers.replicate},
1279
- bedrock: {
1280
- id: Providers.bedrock},
1281
- vertexai: {
1282
- id: Providers.vertexai},
1283
- togetherai: {
1284
- id: Providers.togetherai},
1285
- mistralai: {
1286
- id: Providers.mistralai},
1287
- groq: {
1288
- id: Providers.groq},
1289
- watsonx: {
1290
- id: Providers.watsonx},
1291
- xai: {
1292
- id: Providers.xai},
1293
- openai_compatible: {
1294
- id: Providers.openai_compatible},
1295
- anthropic: {
1296
- id: Providers.anthropic},
1297
- });
1298
- //Common names to share between different models
1299
- var SharedOptions;
1300
- (function (SharedOptions) {
1301
- //Text
1302
- SharedOptions["max_tokens"] = "max_tokens";
1303
- SharedOptions["temperature"] = "temperature";
1304
- SharedOptions["top_p"] = "top_p";
1305
- SharedOptions["top_k"] = "top_k";
1306
- SharedOptions["presence_penalty"] = "presence_penalty";
1307
- SharedOptions["frequency_penalty"] = "frequency_penalty";
1308
- SharedOptions["stop_sequence"] = "stop_sequence";
1309
- SharedOptions["effort"] = "effort";
1310
- //Image
1311
- SharedOptions["seed"] = "seed";
1312
- SharedOptions["number_of_images"] = "number_of_images";
1313
- })(SharedOptions || (SharedOptions = {}));
1314
- var OptionType;
1315
- (function (OptionType) {
1316
- OptionType["numeric"] = "numeric";
1317
- OptionType["enum"] = "enum";
1318
- OptionType["boolean"] = "boolean";
1319
- OptionType["string_list"] = "string_list";
1320
- })(OptionType || (OptionType = {}));
1321
- // ============== Prompts ===============
1322
- var PromptRole;
1323
- (function (PromptRole) {
1324
- PromptRole["safety"] = "safety";
1325
- PromptRole["system"] = "system";
1326
- PromptRole["user"] = "user";
1327
- PromptRole["assistant"] = "assistant";
1328
- PromptRole["negative"] = "negative";
1329
- PromptRole["mask"] = "mask";
1330
- /**
1331
- * Used to send the response of a tool
1332
- */
1333
- PromptRole["tool"] = "tool";
1334
- })(PromptRole || (PromptRole = {}));
1335
- /**
1336
- * @deprecated This is deprecated. Use CompletionResult.type information instead.
1337
- */
1338
- var Modalities;
1339
- (function (Modalities) {
1340
- Modalities["text"] = "text";
1341
- Modalities["image"] = "image";
1342
- })(Modalities || (Modalities = {}));
1343
- var AIModelStatus;
1344
- (function (AIModelStatus) {
1345
- AIModelStatus["Available"] = "available";
1346
- AIModelStatus["Pending"] = "pending";
1347
- AIModelStatus["Stopped"] = "stopped";
1348
- AIModelStatus["Unavailable"] = "unavailable";
1349
- AIModelStatus["Unknown"] = "unknown";
1350
- AIModelStatus["Legacy"] = "legacy";
1351
- })(AIModelStatus || (AIModelStatus = {}));
1352
- var ModelType;
1353
- (function (ModelType) {
1354
- ModelType["Classifier"] = "classifier";
1355
- ModelType["Regressor"] = "regressor";
1356
- ModelType["Clustering"] = "clustering";
1357
- ModelType["AnomalyDetection"] = "anomaly-detection";
1358
- ModelType["TimeSeries"] = "time-series";
1359
- ModelType["Text"] = "text";
1360
- ModelType["Image"] = "image";
1361
- ModelType["Audio"] = "audio";
1362
- ModelType["Video"] = "video";
1363
- ModelType["Embedding"] = "embedding";
1364
- ModelType["Chat"] = "chat";
1365
- ModelType["Code"] = "code";
1366
- ModelType["NLP"] = "nlp";
1367
- ModelType["MultiModal"] = "multi-modal";
1368
- ModelType["Test"] = "test";
1369
- ModelType["Other"] = "other";
1370
- ModelType["Unknown"] = "unknown";
1371
- })(ModelType || (ModelType = {}));
1372
- var TrainingJobStatus;
1373
- (function (TrainingJobStatus) {
1374
- TrainingJobStatus["running"] = "running";
1375
- TrainingJobStatus["succeeded"] = "succeeded";
1376
- TrainingJobStatus["failed"] = "failed";
1377
- TrainingJobStatus["cancelled"] = "cancelled";
1378
- })(TrainingJobStatus || (TrainingJobStatus = {}));
1379
-
1380
- ({
1381
- options: [
1382
- {
1383
- name: SharedOptions.max_tokens, type: OptionType.numeric, min: 1,
1384
- integer: true, step: 200, description: "The maximum number of tokens to generate"
1385
- },
1386
- {
1387
- name: SharedOptions.temperature, type: OptionType.numeric, min: 0.0, default: 0.7,
1388
- integer: false, step: 0.1, description: "A higher temperature biases toward less likely tokens, making the model more creative"
1389
- },
1390
- {
1391
- name: SharedOptions.top_p, type: OptionType.numeric, min: 0, max: 1,
1392
- integer: false, step: 0.1, description: "Limits token sampling to the cumulative probability of the top p tokens"
1393
- },
1394
- {
1395
- name: SharedOptions.top_k, type: OptionType.numeric, min: 1,
1396
- integer: true, step: 1, description: "Limits token sampling to the top k tokens"
1397
- },
1398
- {
1399
- name: SharedOptions.presence_penalty, type: OptionType.numeric, min: -2, max: 2.0,
1400
- integer: false, step: 0.1, description: "Penalise tokens if they appear at least once in the text"
1401
- },
1402
- {
1403
- name: SharedOptions.frequency_penalty, type: OptionType.numeric, min: -2, max: 2.0,
1404
- integer: false, step: 0.1, description: "Penalise tokens based on their frequency in the text"
1405
- },
1406
- { name: SharedOptions.stop_sequence, type: OptionType.string_list, value: [], description: "The generation will halt if one of the stop sequences is output" },
1407
- ]
1408
- });
1409
-
1410
- var ImagenTaskType;
1411
- (function (ImagenTaskType) {
1412
- ImagenTaskType["TEXT_IMAGE"] = "TEXT_IMAGE";
1413
- ImagenTaskType["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL";
1414
- ImagenTaskType["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION";
1415
- ImagenTaskType["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP";
1416
- ImagenTaskType["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT";
1417
- ImagenTaskType["CUSTOMIZATION_SUBJECT"] = "CUSTOMIZATION_SUBJECT";
1418
- ImagenTaskType["CUSTOMIZATION_STYLE"] = "CUSTOMIZATION_STYLE";
1419
- ImagenTaskType["CUSTOMIZATION_CONTROLLED"] = "CUSTOMIZATION_CONTROLLED";
1420
- ImagenTaskType["CUSTOMIZATION_INSTRUCT"] = "CUSTOMIZATION_INSTRUCT";
1421
- })(ImagenTaskType || (ImagenTaskType = {}));
1422
- var ImagenMaskMode;
1423
- (function (ImagenMaskMode) {
1424
- ImagenMaskMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED";
1425
- ImagenMaskMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND";
1426
- ImagenMaskMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND";
1427
- ImagenMaskMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC";
1428
- })(ImagenMaskMode || (ImagenMaskMode = {}));
1429
- var ThinkingLevel;
1430
- (function (ThinkingLevel) {
1431
- ThinkingLevel["HIGH"] = "HIGH";
1432
- ThinkingLevel["MEDIUM"] = "MEDIUM";
1433
- ThinkingLevel["LOW"] = "LOW";
1434
- ThinkingLevel["MINIMAL"] = "MINIMAL";
1435
- ThinkingLevel["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED";
1436
- })(ThinkingLevel || (ThinkingLevel = {}));
1437
-
1438
- // Virtual providers from studio
1439
- var CustomProviders;
1440
- (function (CustomProviders) {
1441
- CustomProviders["virtual_lb"] = "virtual_lb";
1442
- CustomProviders["virtual_mediator"] = "virtual_mediator";
1443
- CustomProviders["test"] = "test";
1444
- })(CustomProviders || (CustomProviders = {}));
1445
- ({
1446
- ...Providers,
1447
- ...CustomProviders
1448
- });
1449
- ({
1450
- virtual_lb: {
1451
- id: CustomProviders.virtual_lb},
1452
- virtual_mediator: {
1453
- id: CustomProviders.virtual_mediator},
1454
- test: {
1455
- id: CustomProviders.test},
1456
- });
1457
-
1458
- var SupportedIntegrations;
1459
- (function (SupportedIntegrations) {
1460
- SupportedIntegrations["gladia"] = "gladia";
1461
- SupportedIntegrations["github"] = "github";
1462
- SupportedIntegrations["aws"] = "aws";
1463
- SupportedIntegrations["magic_pdf"] = "magic_pdf";
1464
- SupportedIntegrations["serper"] = "serper";
1465
- SupportedIntegrations["exa"] = "exa";
1466
- SupportedIntegrations["linkup"] = "linkup";
1467
- SupportedIntegrations["resend"] = "resend";
1468
- SupportedIntegrations["ask_user_webhook"] = "ask_user_webhook";
1469
- })(SupportedIntegrations || (SupportedIntegrations = {}));
1470
-
1471
- var MeterNames;
1472
- (function (MeterNames) {
1473
- MeterNames["analyzed_pages"] = "analyzed_pages";
1474
- MeterNames["extracted_tables"] = "extracted_tables";
1475
- MeterNames["analyzed_images"] = "analyzed_images";
1476
- MeterNames["input_token_used"] = "input_token_used";
1477
- MeterNames["output_token_used"] = "output_token_used";
1478
- MeterNames["task_run"] = "task_run";
1479
- })(MeterNames || (MeterNames = {}));
1480
-
1481
- var ProjectRoles;
1482
- (function (ProjectRoles) {
1483
- ProjectRoles["owner"] = "owner";
1484
- ProjectRoles["admin"] = "admin";
1485
- ProjectRoles["manager"] = "manager";
1486
- ProjectRoles["developer"] = "developer";
1487
- ProjectRoles["application"] = "application";
1488
- ProjectRoles["consumer"] = "consumer";
1489
- ProjectRoles["executor"] = "executor";
1490
- ProjectRoles["reader"] = "reader";
1491
- ProjectRoles["billing"] = "billing";
1492
- ProjectRoles["member"] = "member";
1493
- ProjectRoles["app_member"] = "app_member";
1494
- ProjectRoles["content_superadmin"] = "content_superadmin";
1495
- })(ProjectRoles || (ProjectRoles = {}));
1496
- var ResourceVisibility;
1497
- (function (ResourceVisibility) {
1498
- ResourceVisibility["public"] = "public";
1499
- ResourceVisibility["account"] = "account";
1500
- ResourceVisibility["project"] = "project";
1501
- })(ResourceVisibility || (ResourceVisibility = {}));
1502
- /**
1503
- * System interaction category enum.
1504
- * Categories group one or more system interactions for default model assignment.
1505
- */
1506
- var SystemInteractionCategory;
1507
- (function (SystemInteractionCategory) {
1508
- SystemInteractionCategory["content_type"] = "content_type";
1509
- SystemInteractionCategory["intake"] = "intake";
1510
- SystemInteractionCategory["analysis"] = "analysis";
1511
- SystemInteractionCategory["non_applicable"] = "non_applicable";
1512
- })(SystemInteractionCategory || (SystemInteractionCategory = {}));
1513
- /**
1514
- * Map system interaction endpoints to categories.
1515
- */
1516
- ({
1517
- "ExtractInformation": SystemInteractionCategory.intake,
1518
- "SelectDocumentType": SystemInteractionCategory.intake,
1519
- "GenerateMetadataModel": SystemInteractionCategory.content_type,
1520
- "ChunkDocument": SystemInteractionCategory.intake,
1521
- "IdentifyTextSections": SystemInteractionCategory.intake,
1522
- "AnalyzeDocument": SystemInteractionCategory.analysis,
1523
- "ReduceTextSections": SystemInteractionCategory.analysis,
1524
- "GenericAgent": SystemInteractionCategory.non_applicable,
1525
- "AdhocTaskAgent": SystemInteractionCategory.non_applicable,
1526
- "Mediator": SystemInteractionCategory.non_applicable,
1527
- "AnalyzeConversation": SystemInteractionCategory.analysis,
1528
- "GetAgentConversationTopic": SystemInteractionCategory.analysis,
1529
- });
1530
- // export interface ProjectConfigurationEmbeddings {
1531
- // environment: string;
1532
- // max_tokens: number;
1533
- // dimensions: number;
1534
- // model?: string;
1535
- // }
1536
- var SupportedEmbeddingTypes;
1537
- (function (SupportedEmbeddingTypes) {
1538
- SupportedEmbeddingTypes["text"] = "text";
1539
- SupportedEmbeddingTypes["image"] = "image";
1540
- SupportedEmbeddingTypes["properties"] = "properties";
1541
- })(SupportedEmbeddingTypes || (SupportedEmbeddingTypes = {}));
1542
- var FullTextType;
1543
- (function (FullTextType) {
1544
- FullTextType["full_text"] = "full_text";
1545
- })(FullTextType || (FullTextType = {}));
1546
- ({
1547
- ...SupportedEmbeddingTypes,
1548
- ...FullTextType
1549
- });
1550
-
1551
- var PromptStatus;
1552
- (function (PromptStatus) {
1553
- PromptStatus["draft"] = "draft";
1554
- PromptStatus["published"] = "published";
1555
- PromptStatus["archived"] = "archived";
1556
- })(PromptStatus || (PromptStatus = {}));
1557
- var PromptSegmentDefType;
1558
- (function (PromptSegmentDefType) {
1559
- PromptSegmentDefType["chat"] = "chat";
1560
- PromptSegmentDefType["template"] = "template";
1561
- })(PromptSegmentDefType || (PromptSegmentDefType = {}));
1562
- var TemplateType;
1563
- (function (TemplateType) {
1564
- TemplateType["jst"] = "jst";
1565
- TemplateType["handlebars"] = "handlebars";
1566
- TemplateType["text"] = "text";
1567
- })(TemplateType || (TemplateType = {}));
1568
-
1569
- var ResolvableRefType;
1570
- (function (ResolvableRefType) {
1571
- ResolvableRefType["project"] = "Project";
1572
- ResolvableRefType["projects"] = "Projects";
1573
- ResolvableRefType["environment"] = "Environment";
1574
- ResolvableRefType["user"] = "User";
1575
- ResolvableRefType["account"] = "Account";
1576
- ResolvableRefType["interaction"] = "Interaction";
1577
- ResolvableRefType["userGroup"] = "UserGroup";
1578
- })(ResolvableRefType || (ResolvableRefType = {}));
1579
-
1580
- var CollectionStatus;
1581
- (function (CollectionStatus) {
1582
- CollectionStatus["active"] = "active";
1583
- CollectionStatus["archived"] = "archived";
1584
- })(CollectionStatus || (CollectionStatus = {}));
1585
-
1586
- var ContentObjectApiHeaders;
1587
- (function (ContentObjectApiHeaders) {
1588
- ContentObjectApiHeaders["COLLECTION_ID"] = "x-collection-id";
1589
- ContentObjectApiHeaders["PROCESSING_PRIORITY"] = "x-processing-priority";
1590
- ContentObjectApiHeaders["CREATE_REVISION"] = "x-create-revision";
1591
- ContentObjectApiHeaders["REVISION_LABEL"] = "x-revision-label";
1592
- /** When set to 'true', prevents this update from triggering workflow rules */
1593
- ContentObjectApiHeaders["SUPPRESS_WORKFLOWS"] = "x-suppress-workflows";
1594
- })(ContentObjectApiHeaders || (ContentObjectApiHeaders = {}));
1595
- /**
1596
- * Headers for Data Store API calls.
1597
- * Used for Cloud Run session affinity to route requests to the same instance.
1598
- */
1599
- var DataStoreApiHeaders;
1600
- (function (DataStoreApiHeaders) {
1601
- /** Data store ID for session affinity - routes requests for same store to same instance */
1602
- DataStoreApiHeaders["DATA_STORE_ID"] = "x-data-store-id";
1603
- })(DataStoreApiHeaders || (DataStoreApiHeaders = {}));
1604
- var ContentObjectStatus;
1605
- (function (ContentObjectStatus) {
1606
- ContentObjectStatus["created"] = "created";
1607
- ContentObjectStatus["processing"] = "processing";
1608
- ContentObjectStatus["ready"] = "ready";
1609
- ContentObjectStatus["completed"] = "completed";
1610
- ContentObjectStatus["failed"] = "failed";
1611
- ContentObjectStatus["archived"] = "archived";
1612
- })(ContentObjectStatus || (ContentObjectStatus = {}));
1613
- var ContentNature;
1614
- (function (ContentNature) {
1615
- ContentNature["Video"] = "video";
1616
- ContentNature["Image"] = "image";
1617
- ContentNature["Audio"] = "audio";
1618
- ContentNature["Document"] = "document";
1619
- ContentNature["Code"] = "code";
1620
- ContentNature["Other"] = "other";
1621
- })(ContentNature || (ContentNature = {}));
1622
- var WorkflowRuleInputType;
1623
- (function (WorkflowRuleInputType) {
1624
- WorkflowRuleInputType["single"] = "single";
1625
- WorkflowRuleInputType["multiple"] = "multiple";
1626
- WorkflowRuleInputType["none"] = "none";
1627
- })(WorkflowRuleInputType || (WorkflowRuleInputType = {}));
1628
- var ImageRenditionFormat;
1629
- (function (ImageRenditionFormat) {
1630
- ImageRenditionFormat["jpeg"] = "jpeg";
1631
- ImageRenditionFormat["png"] = "png";
1632
- ImageRenditionFormat["webp"] = "webp";
1633
- })(ImageRenditionFormat || (ImageRenditionFormat = {}));
1634
- var MarkdownRenditionFormat;
1635
- (function (MarkdownRenditionFormat) {
1636
- MarkdownRenditionFormat["docx"] = "docx";
1637
- MarkdownRenditionFormat["pdf"] = "pdf";
1638
- })(MarkdownRenditionFormat || (MarkdownRenditionFormat = {}));
1639
- /**
1640
- * Matrix of supported content type → format conversions.
1641
- * This is the authoritative source of truth for what renditions can be generated.
1642
- *
1643
- * Key patterns:
1644
- * - Exact MIME types (e.g., 'application/pdf')
1645
- * - Wildcard patterns (e.g., 'image/*', 'video/*')
1646
- */
1647
- ({
1648
- // Image formats can generate: jpeg, png, webp
1649
- 'image/*': [ImageRenditionFormat.jpeg, ImageRenditionFormat.png, ImageRenditionFormat.webp],
1650
- // Video formats can generate: jpeg, png (thumbnails)
1651
- 'video/*': [ImageRenditionFormat.jpeg, ImageRenditionFormat.png],
1652
- // PDF can generate: jpeg, png, webp (page images)
1653
- 'application/pdf': [ImageRenditionFormat.jpeg, ImageRenditionFormat.png, ImageRenditionFormat.webp],
1654
- // Markdown can generate: pdf, docx (NOT jpeg/png)
1655
- 'text/markdown': [MarkdownRenditionFormat.pdf, MarkdownRenditionFormat.docx],
1656
- // Any text/* can generate: docx (editable export)
1657
- 'text/*': [MarkdownRenditionFormat.docx],
1658
- // Office documents can generate: pdf
1659
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': [MarkdownRenditionFormat.pdf],
1660
- 'application/msword': [MarkdownRenditionFormat.pdf],
1661
- 'application/vnd.openxmlformats-officedocument.presentationml.presentation': [MarkdownRenditionFormat.pdf],
1662
- 'application/vnd.ms-powerpoint': [MarkdownRenditionFormat.pdf],
1663
- });
1664
- var ContentObjectProcessingPriority;
1665
- (function (ContentObjectProcessingPriority) {
1666
- ContentObjectProcessingPriority["normal"] = "normal";
1667
- ContentObjectProcessingPriority["low"] = "low";
1668
- })(ContentObjectProcessingPriority || (ContentObjectProcessingPriority = {}));
1669
-
1670
- var ContentEventName;
1671
- (function (ContentEventName) {
1672
- ContentEventName["create"] = "create";
1673
- ContentEventName["change_type"] = "change_type";
1674
- ContentEventName["update"] = "update";
1675
- ContentEventName["revision_created"] = "revision_created";
1676
- ContentEventName["delete"] = "delete";
1677
- ContentEventName["workflow_finished"] = "workflow_finished";
1678
- ContentEventName["workflow_execution_request"] = "workflow_execution_request";
1679
- ContentEventName["api_request"] = "api_request";
1680
- })(ContentEventName || (ContentEventName = {}));
1681
- // Task status enum for processed history
1682
- var TaskStatus;
1683
- (function (TaskStatus) {
1684
- TaskStatus["SCHEDULED"] = "scheduled";
1685
- TaskStatus["RUNNING"] = "running";
1686
- TaskStatus["COMPLETED"] = "completed";
1687
- TaskStatus["FAILED"] = "failed";
1688
- TaskStatus["CANCELED"] = "canceled";
1689
- TaskStatus["TIMED_OUT"] = "timed_out";
1690
- TaskStatus["TERMINATED"] = "terminated";
1691
- TaskStatus["SENT"] = "sent";
1692
- TaskStatus["RECEIVED"] = "received";
1693
- })(TaskStatus || (TaskStatus = {}));
1694
- // Task type enum
1695
- var TaskType;
1696
- (function (TaskType) {
1697
- TaskType["ACTIVITY"] = "activity";
1698
- TaskType["CHILD_WORKFLOW"] = "childWorkflow";
1699
- TaskType["SIGNAL"] = "signal";
1700
- TaskType["TIMER"] = "timer";
1701
- })(TaskType || (TaskType = {}));
1702
- var WorkflowExecutionStatus;
1703
- (function (WorkflowExecutionStatus) {
1704
- WorkflowExecutionStatus[WorkflowExecutionStatus["UNKNOWN"] = 0] = "UNKNOWN";
1705
- WorkflowExecutionStatus[WorkflowExecutionStatus["RUNNING"] = 1] = "RUNNING";
1706
- WorkflowExecutionStatus[WorkflowExecutionStatus["COMPLETED"] = 2] = "COMPLETED";
1707
- WorkflowExecutionStatus[WorkflowExecutionStatus["FAILED"] = 3] = "FAILED";
1708
- WorkflowExecutionStatus[WorkflowExecutionStatus["CANCELED"] = 4] = "CANCELED";
1709
- WorkflowExecutionStatus[WorkflowExecutionStatus["TERMINATED"] = 5] = "TERMINATED";
1710
- WorkflowExecutionStatus[WorkflowExecutionStatus["CONTINUED_AS_NEW"] = 6] = "CONTINUED_AS_NEW";
1711
- WorkflowExecutionStatus[WorkflowExecutionStatus["TIMED_OUT"] = 7] = "TIMED_OUT";
1712
- })(WorkflowExecutionStatus || (WorkflowExecutionStatus = {}));
1713
- var AgentMessageType;
1714
- (function (AgentMessageType) {
1715
- AgentMessageType[AgentMessageType["SYSTEM"] = 0] = "SYSTEM";
1716
- AgentMessageType[AgentMessageType["THOUGHT"] = 1] = "THOUGHT";
1717
- AgentMessageType[AgentMessageType["PLAN"] = 2] = "PLAN";
1718
- AgentMessageType[AgentMessageType["UPDATE"] = 3] = "UPDATE";
1719
- AgentMessageType[AgentMessageType["COMPLETE"] = 4] = "COMPLETE";
1720
- AgentMessageType[AgentMessageType["WARNING"] = 5] = "WARNING";
1721
- AgentMessageType[AgentMessageType["ERROR"] = 6] = "ERROR";
1722
- AgentMessageType[AgentMessageType["ANSWER"] = 7] = "ANSWER";
1723
- AgentMessageType[AgentMessageType["QUESTION"] = 8] = "QUESTION";
1724
- AgentMessageType[AgentMessageType["REQUEST_INPUT"] = 9] = "REQUEST_INPUT";
1725
- AgentMessageType[AgentMessageType["IDLE"] = 10] = "IDLE";
1726
- AgentMessageType[AgentMessageType["TERMINATED"] = 11] = "TERMINATED";
1727
- AgentMessageType[AgentMessageType["STREAMING_CHUNK"] = 12] = "STREAMING_CHUNK";
1728
- AgentMessageType[AgentMessageType["BATCH_PROGRESS"] = 13] = "BATCH_PROGRESS";
1729
- AgentMessageType[AgentMessageType["RESTARTING"] = 14] = "RESTARTING";
1730
- })(AgentMessageType || (AgentMessageType = {}));
1731
- // ============================================
1732
- // CONVERTERS
1733
- // ============================================
1734
- /**
1735
- * Map old string enum values to AgentMessageType
1736
- */
1737
- ({
1738
- 'system': AgentMessageType.SYSTEM,
1739
- 'thought': AgentMessageType.THOUGHT,
1740
- 'plan': AgentMessageType.PLAN,
1741
- 'update': AgentMessageType.UPDATE,
1742
- 'complete': AgentMessageType.COMPLETE,
1743
- 'warning': AgentMessageType.WARNING,
1744
- 'error': AgentMessageType.ERROR,
1745
- 'answer': AgentMessageType.ANSWER,
1746
- 'question': AgentMessageType.QUESTION,
1747
- 'request_input': AgentMessageType.REQUEST_INPUT,
1748
- 'idle': AgentMessageType.IDLE,
1749
- 'terminated': AgentMessageType.TERMINATED,
1750
- 'streaming_chunk': AgentMessageType.STREAMING_CHUNK,
1751
- 'batch_progress': AgentMessageType.BATCH_PROGRESS,
1752
- });
1753
- /**
1754
- * Map integer values to AgentMessageType (primary format)
1755
- */
1756
- ({
1757
- 0: AgentMessageType.SYSTEM,
1758
- 1: AgentMessageType.THOUGHT,
1759
- 2: AgentMessageType.PLAN,
1760
- 3: AgentMessageType.UPDATE,
1761
- 4: AgentMessageType.COMPLETE,
1762
- 5: AgentMessageType.WARNING,
1763
- 6: AgentMessageType.ERROR,
1764
- 7: AgentMessageType.ANSWER,
1765
- 8: AgentMessageType.QUESTION,
1766
- 9: AgentMessageType.REQUEST_INPUT,
1767
- 10: AgentMessageType.IDLE,
1768
- 11: AgentMessageType.TERMINATED,
1769
- 12: AgentMessageType.STREAMING_CHUNK,
1770
- 13: AgentMessageType.BATCH_PROGRESS,
1771
- });
1772
- /**
1773
- * Status of a file being processed for conversation use.
1774
- */
1775
- var FileProcessingStatus;
1776
- (function (FileProcessingStatus) {
1777
- /** File is being uploaded to artifact storage */
1778
- FileProcessingStatus["UPLOADING"] = "uploading";
1779
- /** File uploaded, text extraction in progress */
1780
- FileProcessingStatus["PROCESSING"] = "processing";
1781
- /** File is ready for use in conversation */
1782
- FileProcessingStatus["READY"] = "ready";
1783
- /** File processing failed */
1784
- FileProcessingStatus["ERROR"] = "error";
1785
- })(FileProcessingStatus || (FileProcessingStatus = {}));
1786
-
1787
- var TrainingSessionStatus;
1788
- (function (TrainingSessionStatus) {
1789
- TrainingSessionStatus["created"] = "created";
1790
- TrainingSessionStatus["building"] = "building";
1791
- TrainingSessionStatus["prepared"] = "prepared";
1792
- TrainingSessionStatus["processing"] = "processing";
1793
- TrainingSessionStatus["completed"] = "completed";
1794
- TrainingSessionStatus["cancelled"] = "cancelled";
1795
- TrainingSessionStatus["failed"] = "failed";
1796
- })(TrainingSessionStatus || (TrainingSessionStatus = {}));
1797
-
1798
- var TransientTokenType;
1799
- (function (TransientTokenType) {
1800
- TransientTokenType["userInvite"] = "user-invite";
1801
- TransientTokenType["migration"] = "migration";
1802
- })(TransientTokenType || (TransientTokenType = {}));
1803
-
1804
- var Datacenters;
1805
- (function (Datacenters) {
1806
- Datacenters["aws"] = "aws";
1807
- Datacenters["gcp"] = "gcp";
1808
- Datacenters["azure"] = "azure";
1809
- })(Datacenters || (Datacenters = {}));
1810
- var BillingMethod;
1811
- (function (BillingMethod) {
1812
- BillingMethod["stripe"] = "stripe";
1813
- BillingMethod["invoice"] = "invoice";
1814
- })(BillingMethod || (BillingMethod = {}));
1815
- var AccountType;
1816
- (function (AccountType) {
1817
- AccountType["vertesia"] = "vertesia";
1818
- AccountType["partner"] = "partner";
1819
- AccountType["free"] = "free";
1820
- AccountType["customer"] = "customer";
1821
- AccountType["prospect"] = "prospect";
1822
- AccountType["unknown"] = "unknown";
1823
- })(AccountType || (AccountType = {}));
1824
-
1825
- var ApiVersions;
1826
- (function (ApiVersions) {
1827
- ApiVersions[ApiVersions["COMPLETION_RESULT_V1"] = 20250925] = "COMPLETION_RESULT_V1";
1828
- ApiVersions[ApiVersions["DOWNLOAD_URL_NO_MIME_TYPE_V1"] = 20260210] = "DOWNLOAD_URL_NO_MIME_TYPE_V1";
1829
- ApiVersions[ApiVersions["MEDIA_BLOB_STORAGE_V1"] = 20260319] = "MEDIA_BLOB_STORAGE_V1";
1830
- })(ApiVersions || (ApiVersions = {}));
1831
-
1832
- /**
1833
- * Agent Observability Telemetry Types
1834
- *
1835
- * These types define the event-based model for agent observability.
1836
- */
1837
- // ============================================================================
1838
- // Enums
1839
- // ============================================================================
1840
- /**
1841
- * Types of telemetry events
1842
- */
1843
- var AgentEventType;
1844
- (function (AgentEventType) {
1845
- AgentEventType["AgentRunStarted"] = "agent_run_started";
1846
- AgentEventType["AgentRunCompleted"] = "agent_run_completed";
1847
- AgentEventType["LlmCall"] = "llm_call";
1848
- AgentEventType["ToolCall"] = "tool_call";
1849
- })(AgentEventType || (AgentEventType = {}));
1850
- /**
1851
- * Types of LLM calls in a conversation
1852
- */
1853
- var LlmCallType;
1854
- (function (LlmCallType) {
1855
- /** Initial conversation start */
1856
- LlmCallType["Start"] = "start";
1857
- /** Resuming with tool results */
1858
- LlmCallType["ResumeTools"] = "resume_tools";
1859
- /** Resuming with user message */
1860
- LlmCallType["ResumeUser"] = "resume_user";
1861
- /** Checkpoint resume (after conversation summarization) */
1862
- LlmCallType["Checkpoint"] = "checkpoint";
1863
- /** Nested interaction call from within tools */
1864
- LlmCallType["NestedInteraction"] = "nested_interaction";
1865
- })(LlmCallType || (LlmCallType = {}));
1866
- /**
1867
- * Types of tools that can be called
1868
- */
1869
- var TelemetryToolType;
1870
- (function (TelemetryToolType) {
1871
- /** Built-in tools (e.g., plan, search) */
1872
- TelemetryToolType["Builtin"] = "builtin";
1873
- /** Interaction-based tools */
1874
- TelemetryToolType["Interaction"] = "interaction";
1875
- /** Remote/MCP tools */
1876
- TelemetryToolType["Remote"] = "remote";
1877
- /** Skill tools */
1878
- TelemetryToolType["Skill"] = "skill";
1879
- })(TelemetryToolType || (TelemetryToolType = {}));
1880
-
1881
- /**
1882
- * Prompt transformer preset for template files with frontmatter
1883
- * Supports .jst, .hbs, and plain text files
1884
- */
1885
- /**
1886
- * Zod schema for prompt frontmatter validation
1887
- */
1888
- const PromptFrontmatterSchema = z.object({
1889
- // Required fields
1890
- role: z.nativeEnum(PromptRole, {
1891
- errorMap: () => ({ message: 'Role must be one of: safety, system, user, assistant, negative' })
1892
- }),
1893
- // Optional fields
1894
- content_type: z.nativeEnum(TemplateType).optional(),
1895
- schema: z.string().optional(),
1896
- name: z.string().optional(),
1897
- externalId: z.string().optional(),
1898
- }).strict();
1899
- /**
1900
- * MUST be kept in sync with @vertesia/common InCodePrompt
1901
- * Zod schema for prompt definition
1902
- */
1903
- const PromptDefinitionSchema = z.object({
1904
- role: z.nativeEnum(PromptRole),
1905
- content: z.string(),
1906
- content_type: z.nativeEnum(TemplateType),
1907
- schema: z.any().optional(),
1908
- name: z.string().optional(),
1909
- externalId: z.string().optional(),
1910
- });
1911
- /**
1912
- * Normalize schema path for import
1913
- * - Adds './' prefix if not a relative path
1914
- * - Replaces .ts with .js
1915
- * - Adds .js if no extension
1916
- *
1917
- * @param schemaPath - Original schema path from frontmatter
1918
- * @returns Normalized path for ES module import
1919
- */
1920
- function normalizeSchemaPath(schemaPath) {
1921
- let normalized = schemaPath.trim();
1922
- // Add './' prefix if not already a relative path
1923
- if (!normalized.startsWith('.')) {
1924
- normalized = './' + normalized;
1925
- }
1926
- // Get the extension
1927
- const ext = path$1.extname(normalized);
1928
- if (ext === '.ts') {
1929
- // Replace .ts with .js
1930
- normalized = normalized.slice(0, -3) + '.js';
1931
- }
1932
- else if (!ext) {
1933
- // No extension, add .js
1934
- normalized = normalized + '.js';
1935
- }
1936
- // If extension is already .js or something else, leave as is
1937
- return normalized;
1938
- }
1939
- /**
1940
- * Infer content type from file extension
1941
- *
1942
- * @param filePath - Path to the prompt file
1943
- * @returns Inferred content type
1944
- */
1945
- function inferContentType(filePath) {
1946
- const ext = path$1.extname(filePath).toLowerCase();
1947
- switch (ext) {
1948
- case '.jst':
1949
- return TemplateType.jst;
1950
- case '.hbs':
1951
- return TemplateType.handlebars;
1952
- default:
1953
- return TemplateType.text;
1954
- }
1955
- }
1956
- /**
1957
- * Build a PromptDefinition from frontmatter and content
1958
- *
1959
- * @param frontmatter - Parsed frontmatter object
1960
- * @param content - Prompt content (body of the file)
1961
- * @param filePath - Path to the prompt file (for content type inference)
1962
- * @returns Prompt definition object and optional imports
1963
- */
1964
- function buildPromptDefinition(frontmatter, content, filePath) {
1965
- // Determine content type from frontmatter or file extension
1966
- const content_type = frontmatter.content_type || inferContentType(filePath);
1967
- const prompt = {
1968
- role: frontmatter.role,
1969
- content,
1970
- content_type,
1971
- };
1972
- // Add optional fields
1973
- if (frontmatter.name) {
1974
- prompt.name = frontmatter.name;
1975
- }
1976
- if (frontmatter.externalId) {
1977
- prompt.externalId = frontmatter.externalId;
1978
- }
1979
- // Handle schema import if specified
1980
- let imports;
1981
- let schemaImportName;
1982
- if (frontmatter.schema) {
1983
- const normalizedPath = normalizeSchemaPath(frontmatter.schema);
1984
- schemaImportName = '__promptSchema';
1985
- imports = [`import ${schemaImportName} from '${normalizedPath}';`];
1986
- }
1987
- return { prompt, imports, schemaImportName };
1988
- }
1989
- /**
1990
- * Prompt transformer preset
1991
- * Transforms template files with ?prompt suffix into prompt definition objects
1992
- *
1993
- * Supported file types:
1994
- * - .jst (JavaScript template literals) → content_type: 'jst'
1995
- * - .hbs (Handlebars templates) → content_type: 'handlebars'
1996
- * - .txt or other → content_type: 'text'
1997
- *
1998
- * @example
1999
- * ```typescript
2000
- * import PROMPT from './prompt.hbs?prompt';
2001
- * // PROMPT is an InCodePrompt object
2002
- * ```
2003
- */
2004
- const promptTransformer = {
2005
- pattern: /\?prompt$/,
2006
- schema: PromptDefinitionSchema,
2007
- transform: (content, filePath) => {
2008
- const { frontmatter, content: promptContent } = parseFrontmatter(content);
2009
- // Validate frontmatter
2010
- const frontmatterValidation = PromptFrontmatterSchema.safeParse(frontmatter);
2011
- if (!frontmatterValidation.success) {
2012
- const errors = frontmatterValidation.error.errors
2013
- .map((err) => {
2014
- const path = err.path.length > 0 ? err.path.join('.') : 'frontmatter';
2015
- return ` - ${path}: ${err.message}`;
2016
- })
2017
- .join('\n');
2018
- throw new Error(`Invalid frontmatter in ${filePath}:\n${errors}`);
2019
- }
2020
- // Build prompt definition
2021
- const { prompt, imports, schemaImportName } = buildPromptDefinition(frontmatter, promptContent, filePath);
2022
- // If schema is specified, generate custom code with schema reference
2023
- if (schemaImportName) {
2024
- // Build the code manually to avoid JSON.stringify issues with schema reference
2025
- const lines = [
2026
- 'export default {',
2027
- ` role: "${prompt.role}",`,
2028
- ` content: ${JSON.stringify(prompt.content)},`,
2029
- ` content_type: "${prompt.content_type}",`,
2030
- ` schema: ${schemaImportName}`,
2031
- ];
2032
- if (prompt.name) {
2033
- lines.splice(4, 0, ` name: ${JSON.stringify(prompt.name)},`);
2034
- }
2035
- if (prompt.externalId) {
2036
- lines.splice(4, 0, ` externalId: ${JSON.stringify(prompt.externalId)},`);
2037
- }
2038
- lines.push('};');
2039
- const code = lines.join('\n');
2040
- return {
2041
- data: prompt,
2042
- imports,
2043
- code,
2044
- };
2045
- }
2046
- // Standard case without schema
2047
- return {
2048
- data: prompt,
2049
- };
2050
- }
2051
- };
2052
-
2053
- export { PromptDefinitionSchema, PromptRole, RenderingTemplateDefinitionSchema, SkillDefinitionSchema, SkillPropertiesSchema, TemplateType, parseFrontmatter, promptTransformer, rawTransformer, skillCollectionTransformer, skillTransformer, templateCollectionTransformer, templateTransformer, vertesiaImportPlugin };
2054
- //# sourceMappingURL=build-tools.js.map