langwatch 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +5 -2
  2. package/dist/add-LBBS4I3H.js +114 -0
  3. package/dist/add-LBBS4I3H.js.map +1 -0
  4. package/dist/add-RD3ZKFAT.mjs +114 -0
  5. package/dist/add-RD3ZKFAT.mjs.map +1 -0
  6. package/dist/chunk-2JU376G7.js +242 -0
  7. package/dist/chunk-2JU376G7.js.map +1 -0
  8. package/dist/chunk-2ODBGSBI.js +4 -0
  9. package/dist/{chunk-G3AUABT7.js.map → chunk-2ODBGSBI.js.map} +1 -1
  10. package/dist/chunk-3GKPQB4R.mjs +242 -0
  11. package/dist/chunk-3GKPQB4R.mjs.map +1 -0
  12. package/dist/chunk-4NRLVT2U.mjs +35 -0
  13. package/dist/chunk-4NRLVT2U.mjs.map +1 -0
  14. package/dist/{chunk-SVJ7SCGB.js → chunk-52GXX3MA.js} +33 -31
  15. package/dist/chunk-52GXX3MA.js.map +1 -0
  16. package/dist/chunk-5NC5ILKA.js +94 -0
  17. package/dist/chunk-5NC5ILKA.js.map +1 -0
  18. package/dist/chunk-AAROJADR.mjs +49 -0
  19. package/dist/chunk-AAROJADR.mjs.map +1 -0
  20. package/dist/chunk-DHJKJVY7.mjs +20 -0
  21. package/dist/chunk-DHJKJVY7.mjs.map +1 -0
  22. package/dist/{chunk-VJSOCNPA.js → chunk-DTEKFQ4U.js} +6 -28
  23. package/dist/chunk-DTEKFQ4U.js.map +1 -0
  24. package/dist/chunk-E7UE2MPD.mjs +93 -0
  25. package/dist/chunk-E7UE2MPD.mjs.map +1 -0
  26. package/dist/chunk-F6E4XQQU.js +20 -0
  27. package/dist/chunk-F6E4XQQU.js.map +1 -0
  28. package/dist/chunk-FJLK5CFL.js +37 -0
  29. package/dist/chunk-FJLK5CFL.js.map +1 -0
  30. package/dist/{chunk-Z5J5UI5E.mjs → chunk-GJSEBQXF.mjs} +139 -107
  31. package/dist/chunk-GJSEBQXF.mjs.map +1 -0
  32. package/dist/chunk-HA3LI5IK.js +35 -0
  33. package/dist/chunk-HA3LI5IK.js.map +1 -0
  34. package/dist/chunk-HJU67C7H.js +93 -0
  35. package/dist/chunk-HJU67C7H.js.map +1 -0
  36. package/dist/chunk-IGHXIIIK.js +49 -0
  37. package/dist/chunk-IGHXIIIK.js.map +1 -0
  38. package/dist/{chunk-PMBEK6YE.mjs → chunk-J7ICRUU4.mjs} +5 -3
  39. package/dist/{chunk-PMBEK6YE.mjs.map → chunk-J7ICRUU4.mjs.map} +1 -1
  40. package/dist/{chunk-HPC6Z7J4.js → chunk-PWZBLTHR.js} +3 -3
  41. package/dist/{chunk-HPC6Z7J4.js.map → chunk-PWZBLTHR.js.map} +1 -1
  42. package/dist/chunk-SMXXAVMB.js +100 -0
  43. package/dist/chunk-SMXXAVMB.js.map +1 -0
  44. package/dist/{chunk-CSC3CMIT.mjs → chunk-STV4ZVNA.mjs} +2 -2
  45. package/dist/chunk-T5AZMMVS.mjs +94 -0
  46. package/dist/chunk-T5AZMMVS.mjs.map +1 -0
  47. package/dist/{chunk-4BZATFKJ.mjs → chunk-UU33HCCZ.mjs} +4 -26
  48. package/dist/{chunk-4BZATFKJ.mjs.map → chunk-UU33HCCZ.mjs.map} +1 -1
  49. package/dist/{chunk-PTJ6AAI7.js → chunk-VGHLQXKB.js} +138 -106
  50. package/dist/chunk-VGHLQXKB.js.map +1 -0
  51. package/dist/chunk-W5ZEP3CI.mjs +100 -0
  52. package/dist/chunk-W5ZEP3CI.mjs.map +1 -0
  53. package/dist/chunk-Y666BJA5.mjs +4 -0
  54. package/dist/chunk-YN4436PK.mjs +37 -0
  55. package/dist/chunk-YN4436PK.mjs.map +1 -0
  56. package/dist/cli/index.d.mts +1 -0
  57. package/dist/cli/index.d.ts +1 -0
  58. package/dist/cli/index.js +106 -0
  59. package/dist/cli/index.js.map +1 -0
  60. package/dist/cli/index.mjs +106 -0
  61. package/dist/cli/index.mjs.map +1 -0
  62. package/dist/client-browser.js +15 -10
  63. package/dist/client-browser.js.map +1 -1
  64. package/dist/client-browser.mjs +9 -4
  65. package/dist/client-browser.mjs.map +1 -1
  66. package/dist/client-node.js +14 -9
  67. package/dist/client-node.js.map +1 -1
  68. package/dist/client-node.mjs +11 -6
  69. package/dist/client-node.mjs.map +1 -1
  70. package/dist/create-G5MTGOOH.js +70 -0
  71. package/dist/create-G5MTGOOH.js.map +1 -0
  72. package/dist/create-QUZYBMQB.mjs +70 -0
  73. package/dist/create-QUZYBMQB.mjs.map +1 -0
  74. package/dist/evaluation/index.js +5 -4
  75. package/dist/evaluation/index.js.map +1 -1
  76. package/dist/evaluation/index.mjs +4 -3
  77. package/dist/index.d.mts +21 -14
  78. package/dist/index.d.ts +21 -14
  79. package/dist/index.js +10 -7
  80. package/dist/index.js.map +1 -1
  81. package/dist/index.mjs +9 -6
  82. package/dist/init-H67RW22E.mjs +16 -0
  83. package/dist/init-H67RW22E.mjs.map +1 -0
  84. package/dist/init-XU2JFY6N.js +16 -0
  85. package/dist/init-XU2JFY6N.js.map +1 -0
  86. package/dist/list-7NPSX2E4.mjs +136 -0
  87. package/dist/list-7NPSX2E4.mjs.map +1 -0
  88. package/dist/list-ZXFLAF52.js +136 -0
  89. package/dist/list-ZXFLAF52.js.map +1 -0
  90. package/dist/login-76NQIHKR.js +110 -0
  91. package/dist/login-76NQIHKR.js.map +1 -0
  92. package/dist/login-EK4WVOI2.mjs +110 -0
  93. package/dist/login-EK4WVOI2.mjs.map +1 -0
  94. package/dist/observability/index.d.mts +3 -3
  95. package/dist/observability/index.d.ts +3 -3
  96. package/dist/observability/index.js +5 -4
  97. package/dist/observability/index.js.map +1 -1
  98. package/dist/observability/index.mjs +4 -3
  99. package/dist/observability/instrumentation/langchain/index.d.mts +2 -2
  100. package/dist/observability/instrumentation/langchain/index.d.ts +2 -2
  101. package/dist/observability/instrumentation/langchain/index.js +29 -27
  102. package/dist/observability/instrumentation/langchain/index.js.map +1 -1
  103. package/dist/observability/instrumentation/langchain/index.mjs +5 -3
  104. package/dist/observability/instrumentation/langchain/index.mjs.map +1 -1
  105. package/dist/prompt/index.d.mts +2 -2
  106. package/dist/prompt/index.d.ts +2 -2
  107. package/dist/prompt/index.js +8 -4
  108. package/dist/prompt/index.js.map +1 -1
  109. package/dist/prompt/index.mjs +10 -6
  110. package/dist/{prompt-BXJWdbQp.d.mts → prompt-D-jpMrLS.d.mts} +245 -0
  111. package/dist/{prompt-BXJWdbQp.d.ts → prompt-D-jpMrLS.d.ts} +245 -0
  112. package/dist/remove-SDJYEPAY.mjs +106 -0
  113. package/dist/remove-SDJYEPAY.mjs.map +1 -0
  114. package/dist/remove-XBNGIVMR.js +106 -0
  115. package/dist/remove-XBNGIVMR.js.map +1 -0
  116. package/dist/sync-EISKGPTL.js +403 -0
  117. package/dist/sync-EISKGPTL.js.map +1 -0
  118. package/dist/sync-ST2IWXSB.mjs +403 -0
  119. package/dist/sync-ST2IWXSB.mjs.map +1 -0
  120. package/dist/{trace-G2312klE.d.ts → trace-CqaKo0kZ.d.ts} +1 -1
  121. package/dist/{trace-D-bZOuqb.d.mts → trace-DtVc5GhF.d.mts} +1 -1
  122. package/package.json +23 -12
  123. package/dist/chunk-76KNOWLS.js +0 -39
  124. package/dist/chunk-76KNOWLS.js.map +0 -1
  125. package/dist/chunk-G3AUABT7.js +0 -4
  126. package/dist/chunk-OM7VY3XT.mjs +0 -4
  127. package/dist/chunk-PTJ6AAI7.js.map +0 -1
  128. package/dist/chunk-SVJ7SCGB.js.map +0 -1
  129. package/dist/chunk-VJSOCNPA.js.map +0 -1
  130. package/dist/chunk-X62YT4WB.mjs +0 -39
  131. package/dist/chunk-X62YT4WB.mjs.map +0 -1
  132. package/dist/chunk-Z5J5UI5E.mjs.map +0 -1
  133. /package/dist/{chunk-CSC3CMIT.mjs.map → chunk-STV4ZVNA.mjs.map} +0 -0
  134. /package/dist/{chunk-OM7VY3XT.mjs.map → chunk-Y666BJA5.mjs.map} +0 -0
@@ -0,0 +1,242 @@
1
+ import {
2
+ localPromptConfigSchema
3
+ } from "./chunk-4NRLVT2U.mjs";
4
+ import {
5
+ PromptConverter
6
+ } from "./chunk-W5ZEP3CI.mjs";
7
+
8
+ // src/cli/utils/fileManager.ts
9
+ import * as fs from "fs";
10
+ import * as path from "path";
11
+ import * as yaml from "js-yaml";
12
+ import chalk from "chalk";
13
+ var FileManager = class {
14
+ static getPromptsConfigPath() {
15
+ return path.join(process.cwd(), this.PROMPTS_CONFIG_FILE);
16
+ }
17
+ static getPromptsLockPath() {
18
+ return path.join(process.cwd(), this.PROMPTS_LOCK_FILE);
19
+ }
20
+ static getPromptsDir() {
21
+ return path.join(process.cwd(), this.PROMPTS_DIR);
22
+ }
23
+ static getMaterializedDir() {
24
+ return path.join(this.getPromptsDir(), this.MATERIALIZED_DIR);
25
+ }
26
+ static ensureDirectories() {
27
+ const promptsDir = this.getPromptsDir();
28
+ const materializedDir = this.getMaterializedDir();
29
+ if (!fs.existsSync(promptsDir)) {
30
+ fs.mkdirSync(promptsDir, { recursive: true });
31
+ }
32
+ if (!fs.existsSync(materializedDir)) {
33
+ fs.mkdirSync(materializedDir, { recursive: true });
34
+ }
35
+ }
36
+ static loadPromptsConfig() {
37
+ const configPath = this.getPromptsConfigPath();
38
+ if (!fs.existsSync(configPath)) {
39
+ return { prompts: {} };
40
+ }
41
+ try {
42
+ const content = fs.readFileSync(configPath, "utf-8");
43
+ return JSON.parse(content);
44
+ } catch (error) {
45
+ throw new Error(`Failed to parse prompts.json: ${error instanceof Error ? error.message : "Unknown error"}`);
46
+ }
47
+ }
48
+ static savePromptsConfig(config) {
49
+ const configPath = this.getPromptsConfigPath();
50
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
51
+ }
52
+ static initializePromptsConfig() {
53
+ const configPath = this.getPromptsConfigPath();
54
+ const existed = fs.existsSync(configPath);
55
+ if (!existed) {
56
+ const emptyConfig = { prompts: {} };
57
+ this.savePromptsConfig(emptyConfig);
58
+ return { created: true, path: configPath };
59
+ }
60
+ return { created: false, path: configPath };
61
+ }
62
+ static loadPromptsLock() {
63
+ const lockPath = this.getPromptsLockPath();
64
+ if (!fs.existsSync(lockPath)) {
65
+ return {
66
+ lockfileVersion: 1,
67
+ prompts: {}
68
+ };
69
+ }
70
+ try {
71
+ const content = fs.readFileSync(lockPath, "utf-8");
72
+ return JSON.parse(content);
73
+ } catch (error) {
74
+ throw new Error(`Failed to parse prompts-lock.json: ${error instanceof Error ? error.message : "Unknown error"}`);
75
+ }
76
+ }
77
+ static savePromptsLock(lock) {
78
+ const lockPath = this.getPromptsLockPath();
79
+ fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + "\n");
80
+ }
81
+ static initializePromptsLock() {
82
+ const lockPath = this.getPromptsLockPath();
83
+ const existed = fs.existsSync(lockPath);
84
+ if (!existed) {
85
+ const emptyLock = {
86
+ lockfileVersion: 1,
87
+ prompts: {}
88
+ };
89
+ this.savePromptsLock(emptyLock);
90
+ return { created: true, path: lockPath };
91
+ }
92
+ return { created: false, path: lockPath };
93
+ }
94
+ static loadLocalPrompt(filePath) {
95
+ const fullPath = path.resolve(filePath);
96
+ if (!fs.existsSync(fullPath)) {
97
+ throw new Error(`Local prompt file not found: ${filePath}`);
98
+ }
99
+ try {
100
+ const content = fs.readFileSync(fullPath, "utf-8");
101
+ const rawData = yaml.load(content);
102
+ const result = localPromptConfigSchema.safeParse(rawData);
103
+ if (!result.success) {
104
+ const prettyError = result.error.issues.map((issue) => `\u2716 ${issue.message}${issue.path.length > 0 ? `
105
+ \u2192 at ${issue.path.join(".")}` : ""}`).join("\n");
106
+ throw new Error(
107
+ `Invalid prompt configuration in ${chalk.yellow(filePath)}:
108
+ ${prettyError}`
109
+ );
110
+ }
111
+ return result.data;
112
+ } catch (error) {
113
+ if (error instanceof Error && error.message.includes("Invalid prompt configuration")) {
114
+ throw error;
115
+ }
116
+ throw new Error(`Failed to parse local prompt file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
117
+ }
118
+ }
119
+ static saveMaterializedPrompt(name, prompt) {
120
+ const materializedDir = this.getMaterializedDir();
121
+ const parts = name.split("/");
122
+ const fileName = `${parts[parts.length - 1]}.prompt.yaml`;
123
+ if (parts.length > 1) {
124
+ const subDir = path.join(materializedDir, ...parts.slice(0, -1));
125
+ if (!fs.existsSync(subDir)) {
126
+ fs.mkdirSync(subDir, { recursive: true });
127
+ }
128
+ }
129
+ const filePath = path.join(materializedDir, ...parts.slice(0, -1), fileName);
130
+ const yamlContent = PromptConverter.fromMaterializedToYaml(prompt);
131
+ const yamlString = yaml.dump(yamlContent, {
132
+ lineWidth: -1,
133
+ noRefs: true,
134
+ sortKeys: false
135
+ });
136
+ fs.writeFileSync(filePath, yamlString);
137
+ return filePath;
138
+ }
139
+ static getLocalPromptFiles() {
140
+ const promptsDir = this.getPromptsDir();
141
+ const materializedDir = this.getMaterializedDir();
142
+ if (!fs.existsSync(promptsDir)) {
143
+ return [];
144
+ }
145
+ const files = [];
146
+ const walkDir = (dir, relativePath = "") => {
147
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
148
+ for (const entry of entries) {
149
+ const fullPath = path.join(dir, entry.name);
150
+ const relativeFilePath = path.join(relativePath, entry.name);
151
+ if (entry.isDirectory()) {
152
+ if (fullPath === materializedDir) {
153
+ continue;
154
+ }
155
+ walkDir(fullPath, relativeFilePath);
156
+ } else if (entry.isFile() && entry.name.endsWith(".prompt.yaml")) {
157
+ files.push(path.join(promptsDir, relativeFilePath));
158
+ }
159
+ }
160
+ };
161
+ walkDir(promptsDir);
162
+ return files;
163
+ }
164
+ static promptNameFromPath(filePath) {
165
+ const promptsDir = this.getPromptsDir();
166
+ const relativePath = path.relative(promptsDir, filePath);
167
+ return relativePath.replace(/\.prompt\.yaml$/, "");
168
+ }
169
+ static cleanupOrphanedMaterializedFiles(currentDependencies) {
170
+ const materializedDir = this.getMaterializedDir();
171
+ if (!fs.existsSync(materializedDir)) {
172
+ return [];
173
+ }
174
+ const cleaned = [];
175
+ const cleanupDir = (dir, relativePath = "") => {
176
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
177
+ for (const entry of entries) {
178
+ const fullPath = path.join(dir, entry.name);
179
+ const relativeFilePath = path.join(relativePath, entry.name);
180
+ if (entry.isDirectory()) {
181
+ cleanupDir(fullPath, relativeFilePath);
182
+ try {
183
+ const dirEntries = fs.readdirSync(fullPath);
184
+ if (dirEntries.length === 0) {
185
+ fs.rmdirSync(fullPath);
186
+ }
187
+ } catch (e) {
188
+ }
189
+ } else if (entry.isFile() && entry.name.endsWith(".prompt.yaml")) {
190
+ const promptName = relativeFilePath.replace(/\.prompt\.yaml$/, "");
191
+ if (!currentDependencies.has(promptName)) {
192
+ fs.unlinkSync(fullPath);
193
+ cleaned.push(promptName);
194
+ }
195
+ }
196
+ }
197
+ };
198
+ cleanupDir(materializedDir);
199
+ return cleaned;
200
+ }
201
+ static updateLockEntry(lock, name, prompt, materializedPath) {
202
+ const relativePath = path.relative(process.cwd(), materializedPath);
203
+ lock.prompts[name] = {
204
+ version: prompt.version,
205
+ versionId: prompt.versionId,
206
+ materialized: relativePath
207
+ };
208
+ }
209
+ static removeFromLock(lock, names) {
210
+ for (const name of names) {
211
+ delete lock.prompts[name];
212
+ }
213
+ }
214
+ static addToGitignore(entry) {
215
+ const gitignorePath = path.join(process.cwd(), ".gitignore");
216
+ if (!fs.existsSync(gitignorePath)) {
217
+ fs.writeFileSync(gitignorePath, `${entry}
218
+ `);
219
+ return { added: true, existed: false };
220
+ }
221
+ const content = fs.readFileSync(gitignorePath, "utf-8");
222
+ const lines = content.split("\n").map((line) => line.trim());
223
+ if (lines.includes(entry)) {
224
+ return { added: false, existed: true };
225
+ }
226
+ const newContent = content.endsWith("\n") ? `${content}${entry}
227
+ ` : `${content}
228
+ ${entry}
229
+ `;
230
+ fs.writeFileSync(gitignorePath, newContent);
231
+ return { added: true, existed: false };
232
+ }
233
+ };
234
+ FileManager.PROMPTS_CONFIG_FILE = "prompts.json";
235
+ FileManager.PROMPTS_LOCK_FILE = "prompts-lock.json";
236
+ FileManager.PROMPTS_DIR = "prompts";
237
+ FileManager.MATERIALIZED_DIR = ".materialized";
238
+
239
+ export {
240
+ FileManager
241
+ };
242
+ //# sourceMappingURL=chunk-3GKPQB4R.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/utils/fileManager.ts"],"sourcesContent":["import * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as yaml from \"js-yaml\";\nimport chalk from \"chalk\";\nimport { z } from \"zod\";\nimport type { PromptsConfig, LocalPromptConfig, MaterializedPrompt, PromptsLock, PromptsLockEntry } from \"../types\";\nimport { localPromptConfigSchema } from \"../types\";\nimport { PromptConverter } from \"../../prompt/converter\";\n\nexport class FileManager {\n private static readonly PROMPTS_CONFIG_FILE = \"prompts.json\";\n private static readonly PROMPTS_LOCK_FILE = \"prompts-lock.json\";\n private static readonly PROMPTS_DIR = \"prompts\";\n private static readonly MATERIALIZED_DIR = \".materialized\";\n\n static getPromptsConfigPath(): string {\n return path.join(process.cwd(), this.PROMPTS_CONFIG_FILE);\n }\n\n static getPromptsLockPath(): string {\n return path.join(process.cwd(), this.PROMPTS_LOCK_FILE);\n }\n\n static getPromptsDir(): string {\n return path.join(process.cwd(), this.PROMPTS_DIR);\n }\n\n static getMaterializedDir(): string {\n return path.join(this.getPromptsDir(), this.MATERIALIZED_DIR);\n }\n\n static ensureDirectories(): void {\n const promptsDir = this.getPromptsDir();\n const materializedDir = this.getMaterializedDir();\n\n if (!fs.existsSync(promptsDir)) {\n fs.mkdirSync(promptsDir, { recursive: true });\n }\n\n if (!fs.existsSync(materializedDir)) {\n fs.mkdirSync(materializedDir, { recursive: true });\n }\n }\n\n static loadPromptsConfig(): PromptsConfig {\n const configPath = this.getPromptsConfigPath();\n\n if (!fs.existsSync(configPath)) {\n return { prompts: {} };\n }\n\n try {\n const content = fs.readFileSync(configPath, \"utf-8\");\n return JSON.parse(content) as PromptsConfig;\n } catch (error) {\n throw new Error(`Failed to parse prompts.json: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n }\n }\n\n static savePromptsConfig(config: PromptsConfig): void {\n const configPath = this.getPromptsConfigPath();\n fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + \"\\n\");\n }\n\n static initializePromptsConfig(): { created: boolean; path: string } {\n const configPath = this.getPromptsConfigPath();\n const existed = fs.existsSync(configPath);\n\n if (!existed) {\n const emptyConfig: PromptsConfig = { prompts: {} };\n this.savePromptsConfig(emptyConfig);\n return { created: true, path: configPath };\n }\n\n return { created: false, path: configPath };\n }\n\n static loadPromptsLock(): PromptsLock {\n const lockPath = this.getPromptsLockPath();\n\n if (!fs.existsSync(lockPath)) {\n return {\n lockfileVersion: 1,\n prompts: {}\n };\n }\n\n try {\n const content = fs.readFileSync(lockPath, \"utf-8\");\n return JSON.parse(content) as PromptsLock;\n } catch (error) {\n throw new Error(`Failed to parse prompts-lock.json: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n }\n }\n\n static savePromptsLock(lock: PromptsLock): void {\n const lockPath = this.getPromptsLockPath();\n fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + \"\\n\");\n }\n\n static initializePromptsLock(): { created: boolean; path: string } {\n const lockPath = this.getPromptsLockPath();\n const existed = fs.existsSync(lockPath);\n\n if (!existed) {\n const emptyLock: PromptsLock = {\n lockfileVersion: 1,\n prompts: {}\n };\n this.savePromptsLock(emptyLock);\n return { created: true, path: lockPath };\n }\n\n return { created: false, path: lockPath };\n }\n\n static loadLocalPrompt(filePath: string): LocalPromptConfig {\n const fullPath = path.resolve(filePath);\n\n if (!fs.existsSync(fullPath)) {\n throw new Error(`Local prompt file not found: ${filePath}`);\n }\n\n try {\n const content = fs.readFileSync(fullPath, \"utf-8\");\n const rawData = yaml.load(content);\n\n // Validate with zod and provide nice error messages\n const result = localPromptConfigSchema.safeParse(rawData);\n\n if (!result.success) {\n // Format zod errors nicely (manually since z.prettifyError might not be available)\n const prettyError = result.error.issues\n .map(issue => `✖ ${issue.message}${issue.path.length > 0 ? `\\n → at ${issue.path.join('.')}` : ''}`)\n .join('\\n');\n\n throw new Error(\n `Invalid prompt configuration in ${chalk.yellow(filePath)}:\\n${prettyError}`\n );\n }\n\n return result.data;\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Invalid prompt configuration\")) {\n throw error; // Re-throw zod validation errors as-is\n }\n throw new Error(`Failed to parse local prompt file ${filePath}: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n }\n }\n\n static saveMaterializedPrompt(name: string, prompt: MaterializedPrompt): string {\n const materializedDir = this.getMaterializedDir();\n const parts = name.split(\"/\");\n const fileName = `${parts[parts.length - 1]}.prompt.yaml`;\n\n // Create nested directories if needed\n if (parts.length > 1) {\n const subDir = path.join(materializedDir, ...parts.slice(0, -1));\n if (!fs.existsSync(subDir)) {\n fs.mkdirSync(subDir, { recursive: true });\n }\n }\n\n const filePath = path.join(materializedDir, ...parts.slice(0, -1), fileName);\n\n // Convert to YAML format using the converter\n const yamlContent = PromptConverter.fromMaterializedToYaml(prompt);\n\n const yamlString = yaml.dump(yamlContent, {\n lineWidth: -1,\n noRefs: true,\n sortKeys: false\n });\n\n fs.writeFileSync(filePath, yamlString);\n return filePath;\n }\n\n static getLocalPromptFiles(): string[] {\n const promptsDir = this.getPromptsDir();\n const materializedDir = this.getMaterializedDir();\n\n if (!fs.existsSync(promptsDir)) {\n return [];\n }\n\n const files: string[] = [];\n\n const walkDir = (dir: string, relativePath = \"\"): void => {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativeFilePath = path.join(relativePath, entry.name);\n\n if (entry.isDirectory()) {\n // Skip the .materialized directory\n if (fullPath === materializedDir) {\n continue;\n }\n walkDir(fullPath, relativeFilePath);\n } else if (entry.isFile() && entry.name.endsWith(\".prompt.yaml\")) {\n files.push(path.join(promptsDir, relativeFilePath));\n }\n }\n };\n\n walkDir(promptsDir);\n return files;\n }\n\n static promptNameFromPath(filePath: string): string {\n const promptsDir = this.getPromptsDir();\n const relativePath = path.relative(promptsDir, filePath);\n return relativePath.replace(/\\.prompt\\.yaml$/, \"\");\n }\n\n static cleanupOrphanedMaterializedFiles(currentDependencies: Set<string>): string[] {\n const materializedDir = this.getMaterializedDir();\n\n if (!fs.existsSync(materializedDir)) {\n return [];\n }\n\n const cleaned: string[] = [];\n\n const cleanupDir = (dir: string, relativePath = \"\"): void => {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativeFilePath = path.join(relativePath, entry.name);\n\n if (entry.isDirectory()) {\n cleanupDir(fullPath, relativeFilePath);\n\n // Remove empty directories\n try {\n const dirEntries = fs.readdirSync(fullPath);\n if (dirEntries.length === 0) {\n fs.rmdirSync(fullPath);\n }\n } catch {\n // Directory not empty or other error, ignore\n }\n } else if (entry.isFile() && entry.name.endsWith(\".prompt.yaml\")) {\n // Extract prompt name from materialized file path\n const promptName = relativeFilePath.replace(/\\.prompt\\.yaml$/, \"\");\n\n if (!currentDependencies.has(promptName)) {\n fs.unlinkSync(fullPath);\n cleaned.push(promptName);\n }\n }\n }\n };\n\n cleanupDir(materializedDir);\n return cleaned;\n }\n\n static updateLockEntry(lock: PromptsLock, name: string, prompt: MaterializedPrompt, materializedPath: string): void {\n const relativePath = path.relative(process.cwd(), materializedPath);\n\n lock.prompts[name] = {\n version: prompt.version,\n versionId: prompt.versionId,\n materialized: relativePath,\n };\n }\n\n static removeFromLock(lock: PromptsLock, names: string[]): void {\n for (const name of names) {\n delete lock.prompts[name];\n }\n }\n\n static addToGitignore(entry: string): { added: boolean; existed: boolean } {\n const gitignorePath = path.join(process.cwd(), \".gitignore\");\n\n // Check if .gitignore exists\n if (!fs.existsSync(gitignorePath)) {\n // Create new .gitignore with the entry\n fs.writeFileSync(gitignorePath, `${entry}\\n`);\n return { added: true, existed: false };\n }\n\n // Read existing .gitignore\n const content = fs.readFileSync(gitignorePath, \"utf-8\");\n const lines = content.split(\"\\n\").map(line => line.trim());\n\n // Check if entry already exists\n if (lines.includes(entry)) {\n return { added: false, existed: true };\n }\n\n // Add entry to .gitignore\n const newContent = content.endsWith(\"\\n\") ? `${content}${entry}\\n` : `${content}\\n${entry}\\n`;\n fs.writeFileSync(gitignorePath, newContent);\n\n return { added: true, existed: false };\n }\n}"],"mappings":";;;;;;;;AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,UAAU;AACtB,OAAO,WAAW;AAMX,IAAM,cAAN,MAAkB;AAAA,EAMvB,OAAO,uBAA+B;AACpC,WAAY,UAAK,QAAQ,IAAI,GAAG,KAAK,mBAAmB;AAAA,EAC1D;AAAA,EAEA,OAAO,qBAA6B;AAClC,WAAY,UAAK,QAAQ,IAAI,GAAG,KAAK,iBAAiB;AAAA,EACxD;AAAA,EAEA,OAAO,gBAAwB;AAC7B,WAAY,UAAK,QAAQ,IAAI,GAAG,KAAK,WAAW;AAAA,EAClD;AAAA,EAEA,OAAO,qBAA6B;AAClC,WAAY,UAAK,KAAK,cAAc,GAAG,KAAK,gBAAgB;AAAA,EAC9D;AAAA,EAEA,OAAO,oBAA0B;AAC/B,UAAM,aAAa,KAAK,cAAc;AACtC,UAAM,kBAAkB,KAAK,mBAAmB;AAEhD,QAAI,CAAI,cAAW,UAAU,GAAG;AAC9B,MAAG,aAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAAA,IAC9C;AAEA,QAAI,CAAI,cAAW,eAAe,GAAG;AACnC,MAAG,aAAU,iBAAiB,EAAE,WAAW,KAAK,CAAC;AAAA,IACnD;AAAA,EACF;AAAA,EAEA,OAAO,oBAAmC;AACxC,UAAM,aAAa,KAAK,qBAAqB;AAE7C,QAAI,CAAI,cAAW,UAAU,GAAG;AAC9B,aAAO,EAAE,SAAS,CAAC,EAAE;AAAA,IACvB;AAEA,QAAI;AACF,YAAM,UAAa,gB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OAAuB;AAC9D,eAAW,QAAQ,OAAO;AACxB,aAAO,KAAK,QAAQ,IAAI;AAAA,IAC1B;AAAA,EACF;AAAA,EAEA,OAAO,eAAe,OAAqD;AACzE,UAAM,gBAAqB,UAAK,QAAQ,IAAI,GAAG,YAAY;AAG3D,QAAI,CAAI,cAAW,aAAa,GAAG;AAEjC,MAAG,iBAAc,eAAe,GAAG,KAAK;AAAA,CAAI;AAC5C,aAAO,EAAE,OAAO,MAAM,SAAS,MAAM;AAAA,IACvC;AAGA,UAAM,UAAa,gBAAa,eAAe,OAAO;AACtD,UAAM,QAAQ,QAAQ,MAAM,IAAI,EAAE,IAAI,UAAQ,KAAK,KAAK,CAAC;AAGzD,QAAI,MAAM,SAAS,KAAK,GAAG;AACzB,aAAO,EAAE,OAAO,OAAO,SAAS,KAAK;AAAA,IACvC;AAGA,UAAM,aAAa,QAAQ,SAAS,IAAI,IAAI,GAAG,OAAO,GAAG,KAAK;AAAA,IAAO,GAAG,OAAO;AAAA,EAAK,KAAK;AAAA;AACzF,IAAG,iBAAc,eAAe,UAAU;AAE1C,WAAO,EAAE,OAAO,MAAM,SAAS,MAAM;AAAA,EACvC;AACF;AArSa,YACa,sBAAsB;AADnC,YAEa,oBAAoB;AAFjC,YAGa,cAAc;AAH3B,YAIa,mBAAmB;","names":[]}
@@ -0,0 +1,35 @@
1
+ // src/cli/types.ts
2
+ import { z } from "zod";
3
+ var localPromptConfigSchema = z.object({
4
+ model: z.string().min(1, "Model is required"),
5
+ modelParameters: z.object({
6
+ temperature: z.number().optional(),
7
+ max_tokens: z.number().optional()
8
+ }).loose().optional(),
9
+ messages: z.array(
10
+ z.object({
11
+ role: z.enum(["system", "user", "assistant"]),
12
+ content: z.string().min(1, "Message content cannot be empty")
13
+ }).loose()
14
+ ).min(1, "At least one message is required")
15
+ }).loose();
16
+ var parsePromptSpec = (spec) => {
17
+ const atIndex = spec.lastIndexOf("@");
18
+ if (atIndex === -1) {
19
+ return { name: spec, version: "latest" };
20
+ }
21
+ const name = spec.slice(0, atIndex);
22
+ const version = spec.slice(atIndex + 1);
23
+ if (!name || !version) {
24
+ throw new Error(
25
+ `Invalid prompt specification: ${spec}. Use format 'name@version' or just 'name'`
26
+ );
27
+ }
28
+ return { name, version };
29
+ };
30
+
31
+ export {
32
+ localPromptConfigSchema,
33
+ parsePromptSpec
34
+ };
35
+ //# sourceMappingURL=chunk-4NRLVT2U.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/types.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport type PromptDependency =\n | string\n | {\n version?: string;\n file?: string;\n };\n\nexport type PromptsConfig = {\n prompts: Record<string, PromptDependency>;\n};\n\n// Zod schema for local prompt config with permissive validation\nexport const localPromptConfigSchema = z\n .object({\n model: z.string().min(1, \"Model is required\"),\n modelParameters: z\n .object({\n temperature: z.number().optional(),\n max_tokens: z.number().optional(),\n })\n .loose()\n .optional(),\n messages: z\n .array(\n z\n .object({\n role: z.enum([\"system\", \"user\", \"assistant\"]),\n content: z.string().min(1, \"Message content cannot be empty\"),\n })\n .loose(),\n )\n .min(1, \"At least one message is required\"),\n })\n .loose();\n\nexport type LocalPromptConfig = z.infer<typeof localPromptConfigSchema>;\n\nexport type MaterializedPrompt = {\n id: string;\n name: string;\n version: number;\n versionId: string;\n model: string;\n messages: Array<{\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }>;\n prompt: string;\n updatedAt: string;\n versionCreatedAt: string;\n};\n\nexport type SyncResult = {\n fetched: Array<{ name: string; version: number; versionSpec: string }>;\n pushed: Array<{ name: string; version: number }>;\n unchanged: string[];\n cleaned: string[];\n errors: Array<{ name: string; error: string }>;\n};\n\nexport type PromptsLockEntry = {\n version: number;\n versionId: string;\n materialized: string;\n};\n\nexport type PromptsLock = {\n lockfileVersion: number;\n prompts: Record<string, PromptsLockEntry>;\n};\n\n// Parse npm-style version specifications like \"foo@latest\" or \"bar@5\"\nexport const parsePromptSpec = (\n spec: string,\n): { name: string; version: string } => {\n const atIndex = spec.lastIndexOf(\"@\");\n if (atIndex === -1) {\n return { name: spec, version: \"latest\" };\n }\n\n const name = spec.slice(0, atIndex);\n const version = spec.slice(atIndex + 1);\n\n if (!name || !version) {\n throw new Error(\n `Invalid prompt specification: ${spec}. Use format 'name@version' or just 'name'`,\n );\n }\n\n return { name, version };\n};\n"],"mappings":";AAAA,SAAS,SAAS;AAcX,IAAM,0BAA0B,EACpC,OAAO;AAAA,EACN,OAAO,EAAE,OAAO,EAAE,IAAI,GAAG,mBAAmB;AAAA,EAC5C,iBAAiB,EACd,OAAO;AAAA,IACN,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,IACjC,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAClC,CAAC,EACA,MAAM,EACN,SAAS;AAAA,EACZ,UAAU,EACP;AAAA,IACC,EACG,OAAO;AAAA,MACN,MAAM,EAAE,KAAK,CAAC,UAAU,QAAQ,WAAW,CAAC;AAAA,MAC5C,SAAS,EAAE,OAAO,EAAE,IAAI,GAAG,iCAAiC;AAAA,IAC9D,CAAC,EACA,MAAM;AAAA,EACX,EACC,IAAI,GAAG,kCAAkC;AAC9C,CAAC,EACA,MAAM;AAuCF,IAAM,kBAAkB,CAC7B,SACsC;AACtC,QAAM,UAAU,KAAK,YAAY,GAAG;AACpC,MAAI,YAAY,IAAI;AAClB,WAAO,EAAE,MAAM,MAAM,SAAS,SAAS;AAAA,EACzC;AAEA,QAAM,OAAO,KAAK,MAAM,GAAG,OAAO;AAClC,QAAM,UAAU,KAAK,MAAM,UAAU,CAAC;AAEtC,MAAI,CAAC,QAAQ,CAAC,SAAS;AACrB,UAAM,IAAI;AAAA,MACR,iCAAiC,IAAI;AAAA,IACvC;AAAA,EACF;AAEA,SAAO,EAAE,MAAM,QAAQ;AACzB;","names":[]}
@@ -16,9 +16,11 @@
16
16
 
17
17
 
18
18
 
19
+ var _chunkDTEKFQ4Ujs = require('./chunk-DTEKFQ4U.js');
19
20
 
20
21
 
21
- var _chunkVJSOCNPAjs = require('./chunk-VJSOCNPA.js');
22
+
23
+ var _chunkFJLK5CFLjs = require('./chunk-FJLK5CFL.js');
22
24
 
23
25
  // src/observability/trace.ts
24
26
 
@@ -68,7 +70,7 @@ function recordEvaluation(details, attributes) {
68
70
  var _a2;
69
71
  try {
70
72
  span.setType(details.isGuardrail ? "guardrail" : "evaluation");
71
- span.addEvent(_chunkVJSOCNPAjs.ATTR_LANGWATCH_EVALUATION_CUSTOM, {
73
+ span.addEvent(_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_EVALUATION_CUSTOM, {
72
74
  json_encoded_event: JSON.stringify({
73
75
  evaluation_id: (_a2 = details.evaluationId) != null ? _a2 : `eval_${_xksuid.generate.call(void 0, )}`,
74
76
  name: details.name,
@@ -180,10 +182,10 @@ var LangWatchSpanImpl = class {
180
182
  if (body.role === void 0) {
181
183
  body.role = "system";
182
184
  }
183
- this.span.addEvent(_chunkVJSOCNPAjs.LOG_EVNT_GEN_AI_SYSTEM_MESSAGE, _chunkVJSOCNPAjs.__spreadProps.call(void 0, _chunkVJSOCNPAjs.__spreadValues.call(void 0, {}, attributes), {
185
+ this.span.addEvent(_chunkDTEKFQ4Ujs.LOG_EVNT_GEN_AI_SYSTEM_MESSAGE, _chunkFJLK5CFLjs.__spreadProps.call(void 0, _chunkFJLK5CFLjs.__spreadValues.call(void 0, {}, attributes), {
184
186
  [_incubating2.default.ATTR_GEN_AI_SYSTEM]: system,
185
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
186
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
187
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
188
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
187
189
  }));
188
190
  return this;
189
191
  }
@@ -191,10 +193,10 @@ var LangWatchSpanImpl = class {
191
193
  if (body.role === void 0) {
192
194
  body.role = "user";
193
195
  }
194
- this.span.addEvent(_chunkVJSOCNPAjs.LOG_EVNT_GEN_AI_USER_MESSAGE, _chunkVJSOCNPAjs.__spreadProps.call(void 0, _chunkVJSOCNPAjs.__spreadValues.call(void 0, {}, attributes), {
196
+ this.span.addEvent(_chunkDTEKFQ4Ujs.LOG_EVNT_GEN_AI_USER_MESSAGE, _chunkFJLK5CFLjs.__spreadProps.call(void 0, _chunkFJLK5CFLjs.__spreadValues.call(void 0, {}, attributes), {
195
197
  [_incubating2.default.ATTR_GEN_AI_SYSTEM]: system,
196
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
197
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
198
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
199
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
198
200
  }));
199
201
  return this;
200
202
  }
@@ -202,10 +204,10 @@ var LangWatchSpanImpl = class {
202
204
  if (body.role === void 0) {
203
205
  body.role = "assistant";
204
206
  }
205
- this.span.addEvent(_chunkVJSOCNPAjs.LOG_EVNT_GEN_AI_ASSISTANT_MESSAGE, _chunkVJSOCNPAjs.__spreadProps.call(void 0, _chunkVJSOCNPAjs.__spreadValues.call(void 0, {}, attributes), {
207
+ this.span.addEvent(_chunkDTEKFQ4Ujs.LOG_EVNT_GEN_AI_ASSISTANT_MESSAGE, _chunkFJLK5CFLjs.__spreadProps.call(void 0, _chunkFJLK5CFLjs.__spreadValues.call(void 0, {}, attributes), {
206
208
  [_incubating2.default.ATTR_GEN_AI_SYSTEM]: system,
207
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
208
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
209
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
210
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
209
211
  }));
210
212
  return this;
211
213
  }
@@ -213,10 +215,10 @@ var LangWatchSpanImpl = class {
213
215
  if (body.role === void 0) {
214
216
  body.role = "tool";
215
217
  }
216
- this.span.addEvent(_chunkVJSOCNPAjs.LOG_EVNT_GEN_AI_TOOL_MESSAGE, _chunkVJSOCNPAjs.__spreadProps.call(void 0, _chunkVJSOCNPAjs.__spreadValues.call(void 0, {}, attributes), {
218
+ this.span.addEvent(_chunkDTEKFQ4Ujs.LOG_EVNT_GEN_AI_TOOL_MESSAGE, _chunkFJLK5CFLjs.__spreadProps.call(void 0, _chunkFJLK5CFLjs.__spreadValues.call(void 0, {}, attributes), {
217
219
  [_incubating2.default.ATTR_GEN_AI_SYSTEM]: system,
218
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
219
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
220
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
221
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
220
222
  }));
221
223
  return this;
222
224
  }
@@ -224,15 +226,15 @@ var LangWatchSpanImpl = class {
224
226
  if (body.message && body.message.role === void 0) {
225
227
  body.message.role = "assistant";
226
228
  }
227
- this.span.addEvent(_chunkVJSOCNPAjs.LOG_EVNT_GEN_AI_CHOICE, _chunkVJSOCNPAjs.__spreadProps.call(void 0, _chunkVJSOCNPAjs.__spreadValues.call(void 0, {}, attributes), {
229
+ this.span.addEvent(_chunkDTEKFQ4Ujs.LOG_EVNT_GEN_AI_CHOICE, _chunkFJLK5CFLjs.__spreadProps.call(void 0, _chunkFJLK5CFLjs.__spreadValues.call(void 0, {}, attributes), {
228
230
  [_incubating2.default.ATTR_GEN_AI_SYSTEM]: system,
229
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
230
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
231
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),
232
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true
231
233
  }));
232
234
  return this;
233
235
  }
234
236
  setType(type) {
235
- this.span.setAttribute(_chunkVJSOCNPAjs.ATTR_LANGWATCH_SPAN_TYPE, type);
237
+ this.span.setAttribute(_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_SPAN_TYPE, type);
236
238
  return this;
237
239
  }
238
240
  setRequestModel(model) {
@@ -245,7 +247,7 @@ var LangWatchSpanImpl = class {
245
247
  }
246
248
  setRAGContexts(ragContexts) {
247
249
  this.span.setAttribute(
248
- _chunkVJSOCNPAjs.ATTR_LANGWATCH_RAG_CONTEXTS,
250
+ _chunkDTEKFQ4Ujs.ATTR_LANGWATCH_RAG_CONTEXTS,
249
251
  JSON.stringify({
250
252
  type: "json",
251
253
  value: ragContexts
@@ -255,7 +257,7 @@ var LangWatchSpanImpl = class {
255
257
  }
256
258
  setRAGContext(ragContext) {
257
259
  this.span.setAttribute(
258
- _chunkVJSOCNPAjs.ATTR_LANGWATCH_RAG_CONTEXTS,
260
+ _chunkDTEKFQ4Ujs.ATTR_LANGWATCH_RAG_CONTEXTS,
259
261
  JSON.stringify({
260
262
  type: "json",
261
263
  value: [ragContext]
@@ -265,7 +267,7 @@ var LangWatchSpanImpl = class {
265
267
  }
266
268
  setMetrics(metrics) {
267
269
  this.span.setAttribute(
268
- _chunkVJSOCNPAjs.ATTR_LANGWATCH_METRICS,
270
+ _chunkDTEKFQ4Ujs.ATTR_LANGWATCH_METRICS,
269
271
  JSON.stringify({
270
272
  type: "json",
271
273
  value: metrics
@@ -275,16 +277,16 @@ var LangWatchSpanImpl = class {
275
277
  }
276
278
  setSelectedPrompt(prompt) {
277
279
  this.span.setAttributes({
278
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_PROMPT_SELECTED_ID]: prompt.id,
279
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_PROMPT_ID]: prompt.id,
280
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_PROMPT_VERSION_ID]: prompt.versionId,
281
- [_chunkVJSOCNPAjs.ATTR_LANGWATCH_PROMPT_VERSION_NUMBER]: prompt.version
280
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_PROMPT_SELECTED_ID]: prompt.id,
281
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_PROMPT_ID]: prompt.id,
282
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_PROMPT_VERSION_ID]: prompt.versionId,
283
+ [_chunkDTEKFQ4Ujs.ATTR_LANGWATCH_PROMPT_VERSION_NUMBER]: prompt.version
282
284
  });
283
285
  return this;
284
286
  }
285
287
  setInput(input) {
286
288
  this.span.setAttribute(
287
- _chunkVJSOCNPAjs.ATTR_LANGWATCH_INPUT,
289
+ _chunkDTEKFQ4Ujs.ATTR_LANGWATCH_INPUT,
288
290
  JSON.stringify({
289
291
  type: "json",
290
292
  value: input
@@ -294,7 +296,7 @@ var LangWatchSpanImpl = class {
294
296
  }
295
297
  setInputString(input) {
296
298
  this.span.setAttribute(
297
- _chunkVJSOCNPAjs.ATTR_LANGWATCH_INPUT,
299
+ _chunkDTEKFQ4Ujs.ATTR_LANGWATCH_INPUT,
298
300
  JSON.stringify({
299
301
  type: "text",
300
302
  value: input
@@ -304,7 +306,7 @@ var LangWatchSpanImpl = class {
304
306
  }
305
307
  setOutput(output) {
306
308
  this.span.setAttribute(
307
- _chunkVJSOCNPAjs.ATTR_LANGWATCH_OUTPUT,
309
+ _chunkDTEKFQ4Ujs.ATTR_LANGWATCH_OUTPUT,
308
310
  JSON.stringify({
309
311
  type: "json",
310
312
  value: output
@@ -314,7 +316,7 @@ var LangWatchSpanImpl = class {
314
316
  }
315
317
  setOutputString(output) {
316
318
  this.span.setAttribute(
317
- _chunkVJSOCNPAjs.ATTR_LANGWATCH_OUTPUT,
319
+ _chunkDTEKFQ4Ujs.ATTR_LANGWATCH_OUTPUT,
318
320
  JSON.stringify({
319
321
  type: "text",
320
322
  value: output
@@ -324,7 +326,7 @@ var LangWatchSpanImpl = class {
324
326
  }
325
327
  setOutputEvaluation(guardrail, output) {
326
328
  this.span.setAttribute(
327
- _chunkVJSOCNPAjs.ATTR_LANGWATCH_OUTPUT,
329
+ _chunkDTEKFQ4Ujs.ATTR_LANGWATCH_OUTPUT,
328
330
  JSON.stringify({
329
331
  type: guardrail ? "guardrail_result" : "evaluation_result",
330
332
  value: output
@@ -421,4 +423,4 @@ function getLangWatchTracer(name, version) {
421
423
 
422
424
 
423
425
  exports.getLangWatchTracer = getLangWatchTracer; exports.tracer = tracer; exports.recordEvaluation = recordEvaluation; exports.spanTypes = spanTypes; exports.createLangWatchSpan = createLangWatchSpan;
424
- //# sourceMappingURL=chunk-SVJ7SCGB.js.map
426
+ //# sourceMappingURL=chunk-52GXX3MA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/langwatch/langwatch/typescript-sdk/dist/chunk-52GXX3MA.js","../src/observability/trace.ts","../src/observability/span.ts","../src/evaluation/record-evaluation.ts","../src/evaluation/tracer.ts"],"names":["_a"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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;AACO,IAAA;AACT,EAAA;AACF;AAc+D;AAC5B,EAAA;AACnC;AFnYyF;AACA;AC/KL;AAClC,EAAA;AAID,EAAA;AAChB,IAAA;AACb,MAAA;AACY,QAAA;AAQjB,UAAA;AAE8D,YAAA;AAC7C,YAAA;AACR,cAAA;AACR,gBAAA;AACF,cAAA;AACF,YAAA;AAG2B,YAAA;AAMoB,YAAA;AACrB,cAAA;AACgC,cAAA;AAC1D,YAAA;AAEwB,YAAA;AACL,YAAA;AAOP,YAAA;AACd,UAAA;AACO,UAAA;AACT,QAAA;AAEkB,QAAA;AAGmB,UAAA;AACI,YAAA;AACN,YAAA;AACjC,UAAA;AACF,QAAA;AAEuB,QAAA;AAK8C,UAAA;AAEA,YAAA;AAC7C,YAAA;AACuD,cAAA;AAC3E,YAAA;AAC2B,YAAA;AAER,YAAA;AACyB,YAAA;AACA,YAAA;AAEE,YAAA;AAEX,cAAA;AACa,gBAAA;AACxC,gBAAA;AAC+B,kBAAA;AAChB,gBAAA;AACK,kBAAA;AACC,oBAAA;AACiC,oBAAA;AACvD,kBAAA;AAC8B,kBAAA;AACrB,kBAAA;AACV,gBAAA;AACgB,kBAAA;AAClB,gBAAA;AACF,cAAA;AAE2B,cAAA;AACwB,gBAAA;AACjB,cAAA;AACQ,gBAAA;AACnC,cAAA;AAC0B,gBAAA;AACjC,cAAA;AACD,YAAA;AACH,UAAA;AACF,QAAA;AAES,QAAA;AACkC,UAAA;AACiB,UAAA;AAC5D,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AAEgC,EAAA;AAClC;ADyIyF;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/langwatch/langwatch/typescript-sdk/dist/chunk-52GXX3MA.js","sourcesContent":[null,"import {\n trace as otelTrace,\n Tracer,\n Span,\n SpanOptions,\n Context,\n SpanStatusCode,\n} from \"@opentelemetry/api\";\nimport { LangWatchSpan, createLangWatchSpan } from \"./span\";\n\n/**\n * LangWatch OpenTelemetry Tracing Extensions\n *\n * This module provides wrappers and helpers for OpenTelemetry Tracer and Span objects,\n * adding ergonomic methods for LLM/GenAI observability and structured tracing.\n *\n * @module trace\n */\nexport interface LangWatchTracer extends Tracer {\n /**\n * Starts a new {@link LangWatchSpan}. Start the span without setting it on context.\n *\n * This method does NOT modify the current Context.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @returns LangWatchSpan The newly created span\n *\n * @example\n * const span = tracer.startSpan('op');\n * span.setAttribute('key', 'value');\n * span.end();\n */\n startSpan(\n name: string,\n options?: SpanOptions,\n context?: Context,\n ): LangWatchSpan;\n\n /**\n * Starts a new {@link LangWatchSpan} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n *\n * @example\n * const result = tracer.startActiveSpan('op', span => {\n * try {\n * // do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n *\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: LangWatchSpan) => unknown>(\n name: string,\n fn: F,\n ): ReturnType<F>;\n startActiveSpan<F extends (span: LangWatchSpan) => unknown>(\n name: string,\n options: SpanOptions,\n fn: F,\n ): ReturnType<F>;\n startActiveSpan<F extends (span: LangWatchSpan) => unknown>(\n name: string,\n options: SpanOptions,\n context: Context,\n fn: F,\n ): ReturnType<F>;\n\n /**\n * Starts a new {@link LangWatchSpan}, runs the provided async function, and automatically handles\n * error recording, status setting, and span ending. This is a safer and more ergonomic alternative\n * to manually using try/catch/finally blocks with startActiveSpan.\n *\n * Overloads:\n * - withActiveSpan(name, fn)\n * - withActiveSpan(name, options, fn)\n * - withActiveSpan(name, options, context, fn)\n *\n * @param name The name of the span\n * @param options Optional SpanOptions for span creation\n * @param context Optional Context to use to extract parent\n * @param fn The async function to execute within the span context. Receives the span as its first argument.\n * @returns The return value of the provided function\n *\n * @example\n * await tracer.withActiveSpan('my-operation', async (span) => {\n * // ... your code ...\n * });\n *\n * await tracer.withActiveSpan('my-operation', { attributes: { foo: 'bar' } }, async (span) => {\n * // ... your code ...\n * });\n *\n * await tracer.withActiveSpan('my-operation', { attributes: { foo: 'bar' } }, myContext, async (span) => {\n * // ... your code ...\n * });\n */\n withActiveSpan<T>(\n name: string,\n fn: (span: LangWatchSpan) => Promise<T> | T\n ): Promise<T>;\n withActiveSpan<T>(\n name: string,\n options: SpanOptions,\n fn: (span: LangWatchSpan) => Promise<T> | T\n ): Promise<T>;\n withActiveSpan<T>(\n name: string,\n options: SpanOptions,\n context: Context,\n fn: (span: LangWatchSpan) => Promise<T> | T\n ): Promise<T>;\n}\n\n/**\n * Extension of OpenTelemetry's Tracer with LangWatch-specific helpers.\n *\n * This interface provides methods for starting spans and active spans that return LangWatchSpan objects,\n * which include ergonomic helpers for LLM/GenAI tracing.\n *\n * @example\n * import { getLangWatchTracer } from 'langwatch';\n * const tracer = getLangWatchTracer('my-service');\n * const span = tracer.startSpan('llm-call');\n * span.setType('llm').setInput('Prompt').setOutput('Completion');\n * span.end();\n *\n * tracer.startActiveSpan('llm-call', (span) => {\n * span.setType('llm');\n * // ...\n * span.end();\n * });\n */\nexport function getLangWatchTracer(name: string, version?: string): LangWatchTracer {\n const tracer = otelTrace.getTracer(name, version);\n\n // Create a proxy for the tracer that intercepts the calls to startActiveSpan and\n // startSpan, and wraps the span object with our custom LangWatchSpan.\n const handler: ProxyHandler<LangWatchTracer> = {\n get(target, prop, _receiver) {\n switch (prop) {\n case \"startActiveSpan\": {\n const startActiveSpan: StartActiveSpanOverloads = (\n ...args: [\n string,\n SpanOptions?,\n Context?,\n ((span: Span) => unknown)?,\n ]\n ) => {\n // Find the span callback function (usually the last argument!)\n const fnIndex = args.findIndex((arg) => typeof arg === \"function\");\n if (fnIndex === -1) {\n throw new Error(\n \"startActiveSpan requires a function as the last argument\",\n );\n }\n\n // A type assertion is safe here due to the check above, but still sad 😥\n const userFn = args[fnIndex] as (\n span: Span,\n ...rest: unknown[]\n ) => unknown;\n\n // Replace the function with one that wraps the span first\n const spanWrapFunc = (...fnArgs: unknown[]) => {\n const [span, ...rest] = fnArgs;\n return userFn(createLangWatchSpan(span as Span), ...rest);\n };\n\n const newArgs = [...args];\n newArgs[fnIndex] = spanWrapFunc;\n\n // TypeScript can't infer the overload, but this is safe\n return (\n target.startActiveSpan as unknown as (\n ...args: unknown[]\n ) => unknown\n )(...newArgs);\n };\n return startActiveSpan;\n }\n\n case \"startSpan\": {\n return function (\n ...args: Parameters<Tracer[\"startSpan\"]>\n ): ReturnType<Tracer[\"startSpan\"]> {\n const span = target.startSpan(...args);\n return createLangWatchSpan(span);\n };\n }\n\n case \"withActiveSpan\": {\n /**\n * Implementation of withActiveSpan: supports all overloads like startActiveSpan.\n * Uses startActiveSpan to ensure context propagation for nested spans.\n */\n return async function withActiveSpan(...args: any[]): Promise<any> {\n // Find the function argument (should be the last argument)\n const fnIndex = args.findIndex((arg) => typeof arg === \"function\");\n if (fnIndex === -1) {\n throw new Error(\"withActiveSpan requires a function as the last argument\");\n }\n const userFn = args[fnIndex] as (span: LangWatchSpan) => Promise<any> | any;\n // The preceding arguments are: name, options?, context?\n const name = args[0];\n const options = args.length > 2 ? args[1] : undefined;\n const context = args.length > 3 ? args[2] : undefined;\n\n return await new Promise((resolve, reject) => {\n // Use startActiveSpan to ensure context propagation\n const cb = async (span: Span) => {\n const wrappedSpan = createLangWatchSpan(span);\n try {\n resolve(await userFn(wrappedSpan));\n } catch (err: any) {\n wrappedSpan.setStatus({\n code: SpanStatusCode.ERROR,\n message: err && err.message ? err.message : String(err),\n });\n wrappedSpan.recordException(err);\n reject(err);\n } finally {\n wrappedSpan.end();\n }\n };\n // Call the correct overload of startActiveSpan\n if (context !== undefined) {\n target.startActiveSpan(name, options, context, cb);\n } else if (options !== undefined) {\n target.startActiveSpan(name, options, cb);\n } else {\n target.startActiveSpan(name, cb);\n }\n });\n };\n }\n\n default: {\n const value = target[prop as keyof Tracer];\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n }\n },\n };\n\n return new Proxy(tracer, handler) as LangWatchTracer;\n}\n\n/**\n * Helper type for the function overloads of startActiveSpan.\n *\n * This matches OpenTelemetry's Tracer interface and is used internally for type safety.\n */\ntype StartActiveSpanOverloads = {\n <F extends (span: Span) => unknown>(name: string, fn: F): ReturnType<F>;\n <F extends (span: Span) => unknown>(\n name: string,\n options: SpanOptions,\n fn: F,\n ): ReturnType<F>;\n <F extends (span: Span) => unknown>(\n name: string,\n options: SpanOptions,\n context: Context,\n fn: F,\n ): ReturnType<F>;\n};\n","import {\n Attributes,\n AttributeValue,\n Span,\n SpanContext,\n SpanStatus,\n Link,\n Exception\n} from \"@opentelemetry/api\";\nimport semconv from \"@opentelemetry/semantic-conventions/incubating\";\nimport * as intSemconv from \"./semconv\";\nimport {\n RecordedEvaluationDetails,\n recordEvaluation,\n} from \"../evaluation/record-evaluation\";\nimport { EvaluationResultModel } from \"../evaluation/types\";\nimport { Prompt } from \"../prompt/prompt\";\n\n/**\n * Supported types of spans for LangWatch observability. These types categorize the nature of the span for downstream analysis and visualization.\n *\n * @example\n * import { spanTypes, SpanType } from './span';\n * const myType: SpanType = 'llm';\n */\nexport const spanTypes = [\n \"span\",\n \"llm\",\n \"chain\",\n \"tool\",\n \"agent\",\n \"guardrail\",\n \"evaluation\",\n \"rag\",\n \"prompt\",\n \"workflow\",\n \"component\",\n \"module\",\n \"server\",\n \"client\",\n \"producer\",\n \"consumer\",\n \"task\",\n \"unknown\",\n] as const;\n\nexport type SpanType = (typeof spanTypes)[number];\n\n/**\n * Context for a RAG (Retrieval-Augmented Generation) span.\n *\n * This structure is used to record which document and chunk were retrieved and used as context for a generation.\n *\n * @property document_id - Unique identifier for the source document.\n * @property chunk_id - Unique identifier for the chunk within the document.\n * @property content - The actual content of the chunk provided to the model.\n *\n * @example\n * const ragContext: LangWatchSpanRAGContext = {\n * document_id: 'doc-123',\n * chunk_id: 'chunk-456',\n * content: 'Relevant passage from the document.'\n * };\n */\nexport interface LangWatchSpanRAGContext {\n document_id: string;\n chunk_id: string;\n content: string;\n}\n\n/**\n * Metrics for a LangWatch span.\n *\n * @property promptTokens - The number of prompt tokens used.\n * @property completionTokens - The number of completion tokens used.\n * @property cost - The cost of the span.\n */\nexport interface LangWatchSpanMetrics {\n /** The number of prompt tokens used */\n promptTokens?: number;\n /** The number of completion tokens used */\n completionTokens?: number;\n /** The cost of the span */\n cost?: number;\n}\n\n/**\n * Body for a system message event in a GenAI span.\n *\n * Used to log system/instruction messages sent to the model.\n *\n * @property content - The message content.\n * @property role - The role of the message, typically 'system' or 'instruction'.\n *\n * @example\n * span.addGenAISystemMessageEvent({ content: 'You are a helpful assistant.' });\n */\nexport interface LangWatchSpanGenAISystemMessageEventBody {\n /** Content of the system message */\n content?: string;\n /** Role of the message (system or instruction) */\n role?: \"system\" | \"instruction\";\n}\n\n/**\n * Body for a user message event in a GenAI span.\n *\n * Used to log user/customer messages sent to the model.\n *\n * @property content - The message content.\n * @property role - The role of the message, typically 'user' or 'customer'.\n *\n * @example\n * span.addGenAIUserMessageEvent({ content: 'What is the weather today?' });\n */\nexport interface LangWatchSpanGenAIUserMessageEventBody {\n /** Content of the user message */\n content?: string;\n /** Role of the message (user or customer) */\n role?: \"user\" | \"customer\";\n}\n\n/**\n * Body for an assistant message event in a GenAI span.\n *\n * Used to log assistant/bot responses, including tool calls.\n *\n * @property content - The message content.\n * @property role - The role of the message, typically 'assistant' or 'bot'.\n * @property tool_calls - Array of tool call objects, if the assistant invoked tools/functions.\n *\n * @example\n * span.addGenAIAssistantMessageEvent({ content: 'The weather is sunny.', role: 'assistant' });\n */\nexport interface LangWatchSpanGenAIAssistantMessageEventBody {\n /** Content of the assistant message */\n content?: string;\n /** Role of the message (assistant or bot) */\n role?: \"assistant\" | \"bot\";\n /** Tool calls made by the assistant */\n tool_calls?: {\n function: {\n /** Name of the function called */\n name: string;\n /** Arguments passed to the function */\n arguments?: string;\n };\n /** Tool call identifier */\n id: string;\n /** Type of tool call */\n type: \"function\";\n }[];\n}\n\n/**\n * Body for a tool message event in a GenAI span.\n *\n * Used to log messages from tools/functions invoked by the assistant.\n *\n * @property content - The message content.\n * @property id - Unique identifier for the tool call.\n * @property role - The role, typically 'tool' or 'function'.\n *\n * @example\n * span.addGenAIToolMessageEvent({ content: 'Result from tool', id: 'tool-1', role: 'tool' });\n */\nexport interface LangWatchSpanGenAIToolMessageEventBody {\n /** Content of the tool message */\n content?: string;\n /** Tool call identifier */\n id: string;\n /** Role of the message (tool or function) */\n role?: \"tool\" | \"function\";\n}\n\n/**\n * Body for a choice event in a GenAI span.\n *\n * Used to log the model's output choices, including finish reason and message content.\n *\n * @property finish_reason - Why the generation finished (e.g., 'stop', 'length').\n * @property index - Index of the choice (for multi-choice outputs).\n * @property message - The message content and tool calls for this choice.\n *\n * @example\n * span.addGenAIChoiceEvent({ finish_reason: 'stop', index: 0, message: { content: 'Hello!' } });\n */\nexport interface LangWatchSpanGenAIChoiceEventBody {\n /** Reason the generation finished */\n finish_reason: intSemconv.VAL_GEN_AI_FINISH_REASONS | (string & {});\n /** Index of the choice */\n index: number;\n /** Message content for the choice */\n message?: {\n /** Content of the message */\n content?: string;\n /** Role of the message (assistant or bot) */\n role?: \"assistant\" | \"bot\";\n /** Tool calls made by the assistant */\n tool_calls?: {\n function: {\n /** Name of the function called */\n name: string;\n /** Arguments passed to the function */\n arguments?: string;\n };\n /** Tool call identifier */\n id: string;\n /** Type of tool call */\n type: \"function\";\n }[];\n };\n}\n\n/**\n * Extension of OpenTelemetry's Span with LangWatch-specific helpers for LLM, RAG, and GenAI tracing.\n *\n * This interface provides ergonomic methods for recording structured LLM/GenAI data, such as inputs, outputs, RAG contexts, and message events.\n *\n * All methods return `this` for chaining.\n *\n * @example\n * const span = createLangWatchSpan(otelSpan);\n * span\n * .setType('llm')\n * .setInput({ prompt: 'Hello' })\n * .setOutput('Hi!')\n * .addGenAIUserMessageEvent({ content: 'Hello' })\n * .addGenAIAssistantMessageEvent({ content: 'Hi!' });\n */\nexport interface LangWatchSpan extends Span {\n /**\n * Record the evaluation result for the span.\n *\n * @param details - The evaluation details\n * @param attributes - Additional attributes to add to the evaluation span.\n * @returns this\n */\n recordEvaluation(\n details: RecordedEvaluationDetails,\n attributes?: Attributes,\n ): this;\n\n /**\n * Add a GenAI system message event to the span.\n *\n * This logs a system/instruction message sent to the model.\n *\n * @param body - The event body (content and role)\n * @param system - The GenAI system (optional, e.g., 'openai', 'anthropic')\n * @param attributes - Additional OpenTelemetry attributes (optional)\n * @returns this\n */\n addGenAISystemMessageEvent(\n body: LangWatchSpanGenAISystemMessageEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this;\n /**\n * Add a GenAI user message event to the span.\n *\n * This logs a user/customer message sent to the model.\n *\n * @param body - The event body (content and role)\n * @param system - The GenAI system (optional)\n * @param attributes - Additional OpenTelemetry attributes (optional)\n * @returns this\n */\n addGenAIUserMessageEvent(\n body: LangWatchSpanGenAIUserMessageEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this;\n /**\n * Add a GenAI assistant message event to the span.\n *\n * This logs an assistant/bot response, including tool calls if present.\n *\n * @param body - The event body (content, role, tool_calls)\n * @param system - The GenAI system (optional)\n * @param attributes - Additional OpenTelemetry attributes (optional)\n * @returns this\n */\n addGenAIAssistantMessageEvent(\n body: LangWatchSpanGenAIAssistantMessageEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this;\n /**\n * Add a GenAI tool message event to the span.\n *\n * This logs a message from a tool/function invoked by the assistant.\n *\n * @param body - The event body (content, id, role)\n * @param system - The GenAI system (optional)\n * @param attributes - Additional OpenTelemetry attributes (optional)\n * @returns this\n */\n addGenAIToolMessageEvent(\n body: LangWatchSpanGenAIToolMessageEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this;\n /**\n * Add a GenAI choice event to the span.\n *\n * This logs a model output choice, including finish reason and message content.\n *\n * @param body - The event body (finish_reason, index, message)\n * @param system - The GenAI system (optional)\n * @param attributes - Additional OpenTelemetry attributes (optional)\n * @returns this\n */\n addGenAIChoiceEvent(\n body: LangWatchSpanGenAIChoiceEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this;\n\n /**\n * Set the type of the span (e.g., 'llm', 'rag', 'tool', etc).\n *\n * This is used for downstream filtering and analytics.\n *\n * @param type - The span type (see SpanType)\n * @returns this\n */\n setType(type: SpanType): this;\n\n /**\n * Set the request model name for the span.\n *\n * This is typically the model name sent in the API request (e.g., 'gpt-4', 'claude-3').\n *\n * @param model - The request model name\n * @returns this\n */\n setRequestModel(model: string): this;\n /**\n * Set the response model name for the span.\n *\n * This is the model name returned in the API response, if different from the request.\n *\n * @param model - The response model name\n * @returns this\n */\n setResponseModel(model: string): this;\n\n /**\n * Set multiple RAG contexts for the span.\n *\n * Use this to record all retrieved documents/chunks used as context for a generation.\n *\n * @param ragContexts - Array of RAG context objects\n * @returns this\n */\n setRAGContexts(ragContexts: LangWatchSpanRAGContext[]): this;\n /**\n * Set a single RAG context for the span.\n *\n * Use this if only one context was retrieved.\n *\n * @param ragContext - The RAG context object\n * @returns this\n */\n setRAGContext(ragContext: LangWatchSpanRAGContext): this;\n\n /**\n * Set the metrics for the span.\n *\n * @param metrics - The metrics object\n * @returns this\n */\n setMetrics(metrics: LangWatchSpanMetrics): this;\n\n /**\n * Set the selected prompt for the span. This will attach this prompt to the trace. If\n * this is set on multiple spans, the last one will be used.\n *\n * @param prompt - The prompt object\n * @returns this\n */\n setSelectedPrompt(prompt: Prompt): this;\n\n /**\n * Record the input to the span as a JSON-serializable value.\n *\n * The input is stringified and stored as a span attribute for later analysis.\n *\n * @param input - The input value (any type, will be JSON.stringified)\n * @returns this\n */\n setInput(input: unknown): this;\n /**\n * Record the input to the span as a plain string.\n *\n * Use this for raw text prompts or queries.\n *\n * @param input - The input string\n * @returns this\n */\n setInputString(input: string): this;\n /**\n * Record the output from the span as a JSON-serializable value.\n *\n * The output is stringified and stored as a span attribute for later analysis.\n *\n * @param output - The output value (any type, will be JSON.stringified)\n * @returns this\n */\n setOutput(output: unknown): this;\n /**\n * Record the output from the span as a plain string.\n *\n * Use this for raw text completions or responses.\n *\n * @param output - The output string\n * @returns this\n */\n setOutputString(output: string): this;\n\n /**\n * Set the evaluation output for the span.\n *\n * @param guardrail - Whether the evaluation is a guardrail\n * @param output - The evaluation result\n * @returns this\n */\n setOutputEvaluation(guardrail: boolean, output: EvaluationResultModel): this;\n}\n\n/**\n * LangWatchSpan class that wraps an OpenTelemetry Span with LangWatch-specific helpers.\n *\n * This class provides a clean, type-safe wrapper around OpenTelemetry spans with\n * additional methods for LLM, RAG, and GenAI tracing. All methods support fluent API chaining.\n *\n * @example\n * import { createLangWatchSpan } from './span';\n * const otelSpan = tracer.startSpan('llm-call');\n * const span = createLangWatchSpan(otelSpan);\n * span.setType('llm').setInput('Prompt').setOutput('Completion');\n */\nclass LangWatchSpanImpl implements LangWatchSpan {\n constructor(private span: Span) {}\n\n // OpenTelemetry Span methods with fluent API support\n setAttribute(key: string, value: AttributeValue): this {\n this.span.setAttribute(key, value);\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n this.span.setAttributes(attributes);\n return this;\n }\n\n addEvent(name: string, attributes?: Attributes): this {\n this.span.addEvent(name, attributes);\n return this;\n }\n\n recordException(exception: Exception): this {\n this.span.recordException(exception);\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n this.span.setStatus(status);\n return this;\n }\n\n updateName(name: string): this {\n this.span.updateName(name);\n return this;\n }\n\n // Pass through other Span methods without chaining\n end(endTime?: number): void {\n this.span.end(endTime);\n }\n\n isRecording(): boolean {\n return this.span.isRecording();\n }\n\n spanContext(): SpanContext {\n return this.span.spanContext();\n }\n\n addLink(link: Link): this {\n this.span.addLink(link);\n return this;\n }\n\n addLinks(links: Link[]): this {\n this.span.addLinks(links);\n return this;\n }\n\n // LangWatch-specific methods\n recordEvaluation(\n details: RecordedEvaluationDetails,\n attributes?: Attributes,\n ): this {\n recordEvaluation(details, attributes);\n return this;\n }\n\n addGenAISystemMessageEvent(\n body: LangWatchSpanGenAISystemMessageEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this {\n if (body.role === void 0) {\n body.role = \"system\";\n }\n\n this.span.addEvent(intSemconv.LOG_EVNT_GEN_AI_SYSTEM_MESSAGE, {\n ...attributes,\n [semconv.ATTR_GEN_AI_SYSTEM]: system,\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true,\n });\n return this;\n }\n\n addGenAIUserMessageEvent(\n body: LangWatchSpanGenAIUserMessageEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this {\n if (body.role === void 0) {\n body.role = \"user\";\n }\n\n this.span.addEvent(intSemconv.LOG_EVNT_GEN_AI_USER_MESSAGE, {\n ...attributes,\n [semconv.ATTR_GEN_AI_SYSTEM]: system,\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true,\n });\n return this;\n }\n\n addGenAIAssistantMessageEvent(\n body: LangWatchSpanGenAIAssistantMessageEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this {\n if (body.role === void 0) {\n body.role = \"assistant\";\n }\n\n this.span.addEvent(intSemconv.LOG_EVNT_GEN_AI_ASSISTANT_MESSAGE, {\n ...attributes,\n [semconv.ATTR_GEN_AI_SYSTEM]: system,\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true,\n });\n return this;\n }\n\n addGenAIToolMessageEvent(\n body: LangWatchSpanGenAIToolMessageEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this {\n if (body.role === void 0) {\n body.role = \"tool\";\n }\n\n this.span.addEvent(intSemconv.LOG_EVNT_GEN_AI_TOOL_MESSAGE, {\n ...attributes,\n [semconv.ATTR_GEN_AI_SYSTEM]: system,\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true,\n });\n return this;\n }\n\n addGenAIChoiceEvent(\n body: LangWatchSpanGenAIChoiceEventBody,\n system?: intSemconv.VAL_GEN_AI_SYSTEMS | (string & {}),\n attributes?: Record<string, AttributeValue>,\n ): this {\n if (body.message && body.message.role === void 0) {\n body.message.role = \"assistant\";\n }\n\n this.span.addEvent(intSemconv.LOG_EVNT_GEN_AI_CHOICE, {\n ...attributes,\n [semconv.ATTR_GEN_AI_SYSTEM]: system,\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_BODY]: JSON.stringify(body),\n [intSemconv.ATTR_LANGWATCH_GEN_AI_LOG_EVENT_IMPOSTER]: true,\n });\n return this;\n }\n\n setType(type: SpanType): this {\n this.span.setAttribute(intSemconv.ATTR_LANGWATCH_SPAN_TYPE, type);\n return this;\n }\n\n setRequestModel(model: string): this {\n this.span.setAttribute(semconv.ATTR_GEN_AI_REQUEST_MODEL, model);\n return this;\n }\n\n setResponseModel(model: string): this {\n this.span.setAttribute(semconv.ATTR_GEN_AI_RESPONSE_MODEL, model);\n return this;\n }\n\n setRAGContexts(ragContexts: LangWatchSpanRAGContext[]): this {\n this.span.setAttribute(\n intSemconv.ATTR_LANGWATCH_RAG_CONTEXTS,\n JSON.stringify({\n type: \"json\",\n value: ragContexts,\n }),\n );\n return this;\n }\n\n setRAGContext(ragContext: LangWatchSpanRAGContext): this {\n this.span.setAttribute(\n intSemconv.ATTR_LANGWATCH_RAG_CONTEXTS,\n JSON.stringify({\n type: \"json\",\n value: [ragContext],\n }),\n );\n return this;\n }\n\n setMetrics(metrics: LangWatchSpanMetrics): this {\n this.span.setAttribute(\n intSemconv.ATTR_LANGWATCH_METRICS,\n JSON.stringify({\n type: \"json\",\n value: metrics,\n }),\n );\n return this;\n }\n\n setSelectedPrompt(prompt: Prompt): this {\n this.span.setAttributes({\n [intSemconv.ATTR_LANGWATCH_PROMPT_SELECTED_ID]: prompt.id,\n [intSemconv.ATTR_LANGWATCH_PROMPT_ID]: prompt.id,\n [intSemconv.ATTR_LANGWATCH_PROMPT_VERSION_ID]: prompt.versionId,\n [intSemconv.ATTR_LANGWATCH_PROMPT_VERSION_NUMBER]: prompt.version,\n });\n return this;\n }\n\n setInput(input: unknown): this {\n this.span.setAttribute(\n intSemconv.ATTR_LANGWATCH_INPUT,\n JSON.stringify({\n type: \"json\",\n value: input,\n }),\n );\n return this;\n }\n\n setInputString(input: string): this {\n this.span.setAttribute(\n intSemconv.ATTR_LANGWATCH_INPUT,\n JSON.stringify({\n type: \"text\",\n value: input,\n }),\n );\n return this;\n }\n\n setOutput(output: unknown): this {\n this.span.setAttribute(\n intSemconv.ATTR_LANGWATCH_OUTPUT,\n JSON.stringify({\n type: \"json\",\n value: output,\n }),\n );\n return this;\n }\n\n setOutputString(output: string): this {\n this.span.setAttribute(\n intSemconv.ATTR_LANGWATCH_OUTPUT,\n JSON.stringify({\n type: \"text\",\n value: output,\n }),\n );\n return this;\n }\n\n setOutputEvaluation(guardrail: boolean, output: EvaluationResultModel): this {\n this.span.setAttribute(\n intSemconv.ATTR_LANGWATCH_OUTPUT,\n JSON.stringify({\n type: guardrail ? \"guardrail_result\" : \"evaluation_result\",\n value: output,\n }),\n );\n return this;\n }\n}\n\n/**\n * Creates a LangWatchSpan wrapper around an OpenTelemetry Span.\n *\n * @param span - The OpenTelemetry Span to wrap\n * @returns A LangWatchSpan with additional methods for LLM/GenAI observability\n *\n * @example\n * import { createLangWatchSpan } from './span';\n * const otelSpan = tracer.startSpan('llm-call');\n * const span = createLangWatchSpan(otelSpan);\n * span.setType('llm').setInput('Prompt').setOutput('Completion');\n */\nexport function createLangWatchSpan(span: Span): LangWatchSpan {\n return new LangWatchSpanImpl(span);\n}\n","import { EvaluationRESTResult } from \"../internal/generated/types/evaluations\";\nimport * as intSemconv from \"../observability/semconv\";\nimport { Attributes, SpanStatusCode } from \"@opentelemetry/api\";\nimport { generate } from \"xksuid\";\nimport { tracer } from \"./tracer\";\n\nexport interface RecordedEvaluationDetails {\n evaluationId?: string;\n name: string;\n type?: string;\n isGuardrail?: boolean;\n status?: \"processed\" | \"skipped\" | \"error\";\n passed?: boolean;\n score?: number;\n label?: string;\n details?: string;\n cost?: number | { currency: string; amount: number };\n error?: Error;\n timestamps?: {\n startedAtUnixMs: number;\n finishedAtUnixMs: number;\n };\n}\n\nexport function recordEvaluation(\n details: RecordedEvaluationDetails,\n attributes?: Attributes,\n) {\n let result: EvaluationRESTResult;\n const status = details.status || \"processed\";\n\n if (status === \"skipped\") {\n result = {\n status: \"skipped\",\n details: details.details,\n };\n } else if (status === \"error\") {\n result = {\n status: \"error\",\n error_type: details.error?.name || \"Unknown\",\n details: details.details || details.error?.message || \"Unknown error\",\n };\n } else {\n result = {\n status: \"processed\",\n passed: details.passed,\n score: details.score,\n label: details.label,\n details: details.details,\n };\n if (details.cost) {\n (result as any).cost =\n typeof details.cost === \"number\"\n ? { currency: \"USD\", amount: details.cost }\n : details.cost;\n }\n }\n\n tracer.startActiveSpan(\"record evaluation\", (span) => {\n try {\n span.setType(details.isGuardrail ? \"guardrail\" : \"evaluation\");\n span.addEvent(intSemconv.ATTR_LANGWATCH_EVALUATION_CUSTOM, {\n json_encoded_event: JSON.stringify({\n evaluation_id: details.evaluationId ?? `eval_${generate()}`,\n name: details.name,\n type: details.type,\n is_guardrail: details.isGuardrail,\n status: result.status,\n passed: details.passed,\n score: details.score,\n label: details.label,\n details: details.details,\n cost: details.cost,\n error: details.error,\n timestamps: details.timestamps,\n }),\n });\n\n span.setOutput(result);\n\n if (attributes) {\n span.setAttributes(attributes);\n }\n if (details.cost) {\n span.setMetrics({\n cost:\n typeof details.cost === \"number\"\n ? details.cost\n : details.cost.amount,\n });\n }\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message });\n } finally {\n span.end();\n }\n\n return;\n });\n}\n","import { getLangWatchTracer } from \"../observability/trace\";\n\nexport const tracer = getLangWatchTracer(\"langwatch.evaluation\");\n"]}