@braintrust/temporal 0.1.0 → 0.1.1-rc.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Braintrust Data LLC
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -33,9 +33,14 @@ const client = new Client({
33
33
  plugins: [plugin],
34
34
  });
35
35
 
36
+ // ESM-safe resolution (recommended for ESM projects):
37
+ const workflowsUrl = new URL("./workflows", import.meta.url);
38
+ const workflowsPath = workflowsUrl.pathname;
39
+ // CommonJS resolution (existing/example usage):
40
+ // const workflowsPath = require.resolve("./workflows");
36
41
  const worker = await Worker.create({
37
42
  taskQueue: "my-queue",
38
- workflowsPath: require.resolve("./workflows"),
43
+ workflowsPath: workflowsPath,
39
44
  activities,
40
45
  plugins: [plugin],
41
46
  });
@@ -0,0 +1,31 @@
1
+ // src/utils.ts
2
+ var BRAINTRUST_SPAN_HEADER = "_braintrust-span";
3
+ var BRAINTRUST_WORKFLOW_SPAN_HEADER = "_braintrust-workflow-span";
4
+ var BRAINTRUST_WORKFLOW_SPAN_ID_HEADER = "_braintrust-workflow-span-id";
5
+ function serializeHeaderValue(value) {
6
+ return {
7
+ metadata: {
8
+ encoding: new TextEncoder().encode("json/plain")
9
+ },
10
+ data: new TextEncoder().encode(JSON.stringify(value))
11
+ };
12
+ }
13
+ function deserializeHeaderValue(payload) {
14
+ if (!payload?.data) {
15
+ return void 0;
16
+ }
17
+ try {
18
+ const decoded = new TextDecoder().decode(payload.data);
19
+ return JSON.parse(decoded);
20
+ } catch {
21
+ return void 0;
22
+ }
23
+ }
24
+
25
+ export {
26
+ BRAINTRUST_SPAN_HEADER,
27
+ BRAINTRUST_WORKFLOW_SPAN_HEADER,
28
+ BRAINTRUST_WORKFLOW_SPAN_ID_HEADER,
29
+ serializeHeaderValue,
30
+ deserializeHeaderValue
31
+ };
package/dist/index.js CHANGED
@@ -233,6 +233,7 @@ function createBraintrustActivityInterceptor(ctx) {
233
233
  }
234
234
 
235
235
  // src/plugin.ts
236
+ var WORKFLOW_INTERCEPTORS_SPEC = "@braintrust/temporal/workflow-interceptors";
236
237
  var BraintrustTemporalPlugin = class {
237
238
  get name() {
238
239
  return "braintrust";
@@ -246,11 +247,14 @@ var BraintrustTemporalPlugin = class {
246
247
  const braintrustInterceptor = createBraintrustClientInterceptor();
247
248
  let workflow;
248
249
  if (Array.isArray(existing)) {
249
- workflow = [...existing, braintrustInterceptor];
250
+ workflow = [
251
+ ...existing,
252
+ braintrustInterceptor
253
+ ];
250
254
  } else if (existing) {
251
255
  workflow = {
252
256
  ...existing,
253
- ...braintrustInterceptor
257
+ calls: [...existing.calls ?? [], () => braintrustInterceptor]
254
258
  };
255
259
  } else {
256
260
  workflow = [braintrustInterceptor];
@@ -273,22 +277,27 @@ var BraintrustTemporalPlugin = class {
273
277
  const existingWorkflowModules = options.interceptors?.workflowModules ?? [];
274
278
  const existingSinks = options.sinks ?? {};
275
279
  const braintrustSinks = createBraintrustSinks();
276
- const workflowInterceptorsPath = require.resolve("@braintrust/temporal/workflow-interceptors");
277
- return {
280
+ const workflowModules = [
281
+ ...existingWorkflowModules,
282
+ WORKFLOW_INTERCEPTORS_SPEC
283
+ ];
284
+ const activityFactories = [
285
+ ...existingActivityInterceptors,
286
+ createBraintrustActivityInterceptor
287
+ ];
288
+ const result = {
278
289
  ...options,
279
290
  interceptors: {
280
291
  ...options.interceptors,
281
- activity: [
282
- ...existingActivityInterceptors,
283
- createBraintrustActivityInterceptor
284
- ],
285
- workflowModules: [...existingWorkflowModules, workflowInterceptorsPath]
292
+ activity: activityFactories,
293
+ workflowModules
286
294
  },
287
295
  sinks: {
288
296
  ...existingSinks,
289
297
  ...braintrustSinks
290
298
  }
291
299
  };
300
+ return result;
292
301
  }
293
302
  };
294
303
  function createBraintrustTemporalPlugin() {
package/dist/index.mjs CHANGED
@@ -1,9 +1,8 @@
1
1
  import {
2
2
  BRAINTRUST_SPAN_HEADER,
3
3
  BRAINTRUST_WORKFLOW_SPAN_ID_HEADER,
4
- __require,
5
4
  deserializeHeaderValue
6
- } from "./chunk-KT66NY2E.mjs";
5
+ } from "./chunk-NKP2TK53.mjs";
7
6
 
8
7
  // src/interceptors.ts
9
8
  import { defaultPayloadConverter } from "@temporalio/common";
@@ -188,6 +187,7 @@ function createBraintrustActivityInterceptor(ctx) {
188
187
  }
189
188
 
190
189
  // src/plugin.ts
190
+ var WORKFLOW_INTERCEPTORS_SPEC = "@braintrust/temporal/workflow-interceptors";
191
191
  var BraintrustTemporalPlugin = class {
192
192
  get name() {
193
193
  return "braintrust";
@@ -201,11 +201,14 @@ var BraintrustTemporalPlugin = class {
201
201
  const braintrustInterceptor = createBraintrustClientInterceptor();
202
202
  let workflow;
203
203
  if (Array.isArray(existing)) {
204
- workflow = [...existing, braintrustInterceptor];
204
+ workflow = [
205
+ ...existing,
206
+ braintrustInterceptor
207
+ ];
205
208
  } else if (existing) {
206
209
  workflow = {
207
210
  ...existing,
208
- ...braintrustInterceptor
211
+ calls: [...existing.calls ?? [], () => braintrustInterceptor]
209
212
  };
210
213
  } else {
211
214
  workflow = [braintrustInterceptor];
@@ -228,24 +231,27 @@ var BraintrustTemporalPlugin = class {
228
231
  const existingWorkflowModules = options.interceptors?.workflowModules ?? [];
229
232
  const existingSinks = options.sinks ?? {};
230
233
  const braintrustSinks = createBraintrustSinks();
231
- const workflowInterceptorsPath = __require.resolve(
232
- "@braintrust/temporal/workflow-interceptors"
233
- );
234
- return {
234
+ const workflowModules = [
235
+ ...existingWorkflowModules,
236
+ WORKFLOW_INTERCEPTORS_SPEC
237
+ ];
238
+ const activityFactories = [
239
+ ...existingActivityInterceptors,
240
+ createBraintrustActivityInterceptor
241
+ ];
242
+ const result = {
235
243
  ...options,
236
244
  interceptors: {
237
245
  ...options.interceptors,
238
- activity: [
239
- ...existingActivityInterceptors,
240
- createBraintrustActivityInterceptor
241
- ],
242
- workflowModules: [...existingWorkflowModules, workflowInterceptorsPath]
246
+ activity: activityFactories,
247
+ workflowModules
243
248
  },
244
249
  sinks: {
245
250
  ...existingSinks,
246
251
  ...braintrustSinks
247
252
  }
248
253
  };
254
+ return result;
249
255
  }
250
256
  };
251
257
  function createBraintrustTemporalPlugin() {
@@ -4,7 +4,7 @@ import {
4
4
  BRAINTRUST_WORKFLOW_SPAN_ID_HEADER,
5
5
  deserializeHeaderValue,
6
6
  serializeHeaderValue
7
- } from "./chunk-KT66NY2E.mjs";
7
+ } from "./chunk-NKP2TK53.mjs";
8
8
 
9
9
  // src/workflow-interceptors.ts
10
10
  import {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@braintrust/temporal",
3
- "version": "0.1.0",
3
+ "version": "0.1.1-rc.0",
4
4
  "description": "SDK for integrating Braintrust with Temporal",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -20,12 +20,6 @@
20
20
  "require": "./dist/workflow-interceptors.js"
21
21
  }
22
22
  },
23
- "scripts": {
24
- "build": "tsup",
25
- "watch": "tsup --watch",
26
- "clean": "rm -r dist/*",
27
- "test": "vitest run"
28
- },
29
23
  "author": "Braintrust Data Inc.",
30
24
  "license": "MIT",
31
25
  "devDependencies": {
@@ -35,10 +29,10 @@
35
29
  "@temporalio/worker": "^1.14.1",
36
30
  "@temporalio/workflow": "^1.14.1",
37
31
  "@types/node": "^22.15.21",
38
- "braintrust": "workspace:*",
39
32
  "tsup": "^8.5.0",
40
33
  "typescript": "5.5.4",
41
- "vitest": "^2.1.9"
34
+ "vitest": "^2.1.9",
35
+ "braintrust": "2.2.0"
42
36
  },
43
37
  "peerDependencies": {
44
38
  "@temporalio/activity": ">=1.11.0",
@@ -67,5 +61,11 @@
67
61
  "@temporalio/workflow": {
68
62
  "optional": false
69
63
  }
64
+ },
65
+ "scripts": {
66
+ "build": "tsup",
67
+ "watch": "tsup --watch",
68
+ "clean": "rm -r dist/*",
69
+ "test": "vitest run"
70
70
  }
71
- }
71
+ }
package/src/index.ts CHANGED
@@ -24,10 +24,12 @@
24
24
  * plugins: [braintrustPlugin],
25
25
  * });
26
26
  *
27
+ * const workflowsUrl = new URL("./workflows", import.meta.url);
28
+ * const workflowsPath = workflowsUrl.pathname;
27
29
  * // Create worker with the plugin
28
30
  * const worker = await Worker.create({
29
31
  * taskQueue: "my-queue",
30
- * workflowsPath: require.resolve("./workflows"),
32
+ * workflowsPath: workflowsPath,
31
33
  * activities,
32
34
  * plugins: [braintrustPlugin],
33
35
  * });
package/src/plugin.ts CHANGED
@@ -1,4 +1,10 @@
1
- import type { ClientPlugin, ClientOptions } from "@temporalio/client";
1
+ import type {
2
+ ClientPlugin,
3
+ ClientOptions,
4
+ WorkflowClientInterceptor,
5
+ WorkflowClientInterceptors,
6
+ WorkflowClientCallsInterceptorFactory,
7
+ } from "@temporalio/client";
2
8
  import type { WorkerPlugin, WorkerOptions } from "@temporalio/worker";
3
9
  import {
4
10
  createBraintrustClientInterceptor,
@@ -6,6 +12,9 @@ import {
6
12
  } from "./interceptors";
7
13
  import { createBraintrustSinks } from "./sinks";
8
14
 
15
+ // Add the workflow interceptor package specifier so the Temporal bundler can include it
16
+ const WORKFLOW_INTERCEPTORS_SPEC = "@braintrust/temporal/workflow-interceptors";
17
+
9
18
  /**
10
19
  * A Braintrust plugin for Temporal that automatically instruments
11
20
  * workflows and activities with tracing spans.
@@ -53,17 +62,24 @@ export class BraintrustTemporalPlugin implements ClientPlugin, WorkerPlugin {
53
62
  const existing = options.interceptors?.workflow;
54
63
  const braintrustInterceptor = createBraintrustClientInterceptor();
55
64
 
56
- // workflow can be an array or an object with named interceptors
57
- let workflow: typeof existing;
65
+ let workflow:
66
+ | WorkflowClientInterceptors
67
+ | WorkflowClientInterceptor[]
68
+ | undefined;
69
+
58
70
  if (Array.isArray(existing)) {
59
- workflow = [...existing, braintrustInterceptor];
71
+ workflow = [
72
+ ...(existing as WorkflowClientInterceptor[]),
73
+ braintrustInterceptor,
74
+ ];
60
75
  } else if (existing) {
61
- // It's a WorkflowClientInterceptors object, merge our interceptor
76
+ // It's a WorkflowClientInterceptors object, merge our interceptor into the calls array
62
77
  workflow = {
63
78
  ...existing,
64
- ...braintrustInterceptor,
79
+ calls: [...(existing.calls ?? []), () => braintrustInterceptor],
65
80
  };
66
81
  } else {
82
+ // keep in new array form
67
83
  workflow = [braintrustInterceptor];
68
84
  }
69
85
 
@@ -73,7 +89,7 @@ export class BraintrustTemporalPlugin implements ClientPlugin, WorkerPlugin {
73
89
  ...options.interceptors,
74
90
  workflow,
75
91
  },
76
- };
92
+ } as Omit<ClientOptions, "plugins">;
77
93
  }
78
94
 
79
95
  /**
@@ -88,27 +104,30 @@ export class BraintrustTemporalPlugin implements ClientPlugin, WorkerPlugin {
88
104
 
89
105
  const braintrustSinks = createBraintrustSinks();
90
106
 
91
- // Resolve the workflow interceptors module path
92
- // This needs to be resolved at runtime to get the actual file path
93
- const workflowInterceptorsPath = require.resolve(
94
- "@braintrust/temporal/workflow-interceptors",
95
- );
107
+ const workflowModules = [
108
+ ...existingWorkflowModules,
109
+ WORKFLOW_INTERCEPTORS_SPEC,
110
+ ];
96
111
 
97
- return {
112
+ const activityFactories = [
113
+ ...existingActivityInterceptors,
114
+ createBraintrustActivityInterceptor,
115
+ ];
116
+
117
+ const result: WorkerOptions = {
98
118
  ...options,
99
119
  interceptors: {
100
120
  ...options.interceptors,
101
- activity: [
102
- ...existingActivityInterceptors,
103
- createBraintrustActivityInterceptor,
104
- ],
105
- workflowModules: [...existingWorkflowModules, workflowInterceptorsPath],
121
+ activity: activityFactories,
122
+ workflowModules,
106
123
  },
107
124
  sinks: {
108
125
  ...existingSinks,
109
126
  ...braintrustSinks,
110
127
  },
111
128
  };
129
+
130
+ return result;
112
131
  }
113
132
  }
114
133
 
@@ -1,2 +0,0 @@
1
- # Braintrust API key for tracing
2
- BRAINTRUST_API_KEY=your-api-key-here
@@ -1,4 +0,0 @@
1
- server: temporal server start-dev
2
- worker1: pnpm run worker
3
- worker2: pnpm run worker
4
- worker3: pnpm run worker
@@ -1,183 +0,0 @@
1
- # Temporal + Braintrust Tracing Example
2
-
3
- This example demonstrates how to integrate Braintrust tracing with Temporal workflows and activities.
4
-
5
- ## Prerequisites
6
-
7
- - [mise](https://mise.jdx.dev/) (recommended) - automatically installs all dependencies
8
- - OR manually install:
9
- - Node.js 20+
10
- - `pnpm`
11
- - Temporal CLI (`temporal`)
12
- - Optional: [`overmind`](https://github.com/DarthSim/overmind) (only if you want to use the included `Procfile`)
13
-
14
- ### Option 1: Using mise (recommended)
15
-
16
- [mise](https://mise.jdx.dev/) will automatically install and manage all required tools (Node.js, Temporal CLI, overmind, and dependencies):
17
-
18
- **Install mise:**
19
-
20
- ```bash
21
- # macOS/Linux
22
- curl https://mise.run | sh
23
-
24
- # Or using Homebrew
25
- brew install mise
26
- ```
27
-
28
- **Setup and run:**
29
-
30
- ```bash
31
- # Copy and configure environment
32
- cp .env.example .env
33
- # Edit .env with your BRAINTRUST_API_KEY
34
-
35
- # mise will automatically install tools and dependencies
36
- mise run server # Start temporal server and workers
37
-
38
- # In another terminal:
39
- mise run workflow # Run the workflow client
40
- ```
41
-
42
- **Available mise tasks:**
43
-
44
- ```bash
45
- mise run install # Install dependencies
46
- mise run server # Run temporal server and workers
47
- mise run workflow # Run workflow client
48
- mise run stop # Stop temporal server and workers
49
- mise run kill # Force kill all processes
50
- ```
51
-
52
- ### Option 2: Manual installation
53
-
54
- #### Installing Temporal CLI
55
-
56
- The Temporal CLI is required to run the local Temporal server:
57
-
58
- **macOS:**
59
-
60
- ```bash
61
- brew install temporal
62
- ```
63
-
64
- **Linux:**
65
-
66
- ```bash
67
- # Using Homebrew
68
- brew install temporal
69
-
70
- # Or using curl
71
- curl -sSf https://temporal.download/cli.sh | sh
72
- ```
73
-
74
- **Windows:**
75
-
76
- ```powershell
77
- # Using Scoop
78
- scoop install temporal
79
-
80
- # Or download from releases
81
- # https://github.com/temporalio/cli/releases
82
- ```
83
-
84
- Verify the installation:
85
-
86
- ```bash
87
- temporal --version
88
- ```
89
-
90
- #### Installing overmind (optional)
91
-
92
- Overmind is a process manager that makes it easy to run multiple services together. If you want to use `overmind start` to run everything at once, install it for your platform:
93
-
94
- **macOS:**
95
-
96
- ```bash
97
- brew install overmind
98
- ```
99
-
100
- **Linux:**
101
-
102
- ```bash
103
- brew install overmind
104
-
105
- # Or download from releases
106
- # https://github.com/DarthSim/overmind/releases
107
- ```
108
-
109
- **Windows:**
110
- Overmind is not officially supported on Windows. Use the manual approach below instead.
111
-
112
- ## Setup
113
-
114
- ```bash
115
- # Copy and configure environment
116
- cp .env.example .env
117
- # Edit .env with your BRAINTRUST_API_KEY
118
-
119
- # Install dependencies
120
- pnpm install
121
- ```
122
-
123
- ## Running the Example
124
-
125
- ### Option 1: Using overmind
126
-
127
- Start the temporal server and workers together:
128
-
129
- ```bash
130
- overmind start
131
- ```
132
-
133
- Then in another terminal, run the workflow:
134
-
135
- ```bash
136
- pnpm run client
137
- ```
138
-
139
- ### Option 2: Manual
140
-
141
- 1. Start the Temporal server:
142
-
143
- ```bash
144
- temporal server start-dev
145
- ```
146
-
147
- 2. Start the worker:
148
-
149
- ```bash
150
- pnpm run worker
151
- ```
152
-
153
- 3. Run the client:
154
-
155
- ```bash
156
- pnpm run client
157
-
158
- # Or with a signal:
159
- pnpm run client -- --signal
160
- ```
161
-
162
- ## What Gets Traced
163
-
164
- - **Client span**: Wraps the workflow execution call
165
- - **Workflow span**: Created via sinks when the workflow starts
166
- - **Activity spans**: Created for each activity execution with parent linking
167
-
168
- The trace hierarchy looks like:
169
-
170
- ```
171
- Client span ("example.temporal.workflow")
172
- └── Workflow span ("temporal.workflow.simpleWorkflow")
173
- └── Activity span ("temporal.activity.addTen")
174
- └── Activity span ("temporal.activity.multiplyByTwo")
175
- └── Activity span ("temporal.activity.subtractFive")
176
- ```
177
-
178
- ## How It Works
179
-
180
- 1. **Client interceptor**: Captures the current Braintrust span context and adds it to workflow headers
181
- 2. **Workflow interceptor**: Extracts parent context from headers and creates a workflow span via sinks
182
- 3. **Sinks**: Allow the workflow isolate to call into Node.js to create spans (with `callDuringReplay: false`)
183
- 4. **Activity interceptor**: Creates spans for each activity, using the workflow span as parent
@@ -1,40 +0,0 @@
1
- # Mise will automatically read and use .tool-versions files as well as this file.
2
- [settings]
3
- experimental=true
4
-
5
- [env]
6
- # See env.example to configure API keys.
7
- _.file = ".env"
8
-
9
- [tools]
10
- node = "20"
11
- temporal = "latest"
12
- overmind = "latest"
13
-
14
- [hooks]
15
- postinstall = "mise run install"
16
-
17
- [tasks.install]
18
- description = "Install dependencies"
19
- run = "pnpm install --ignore-workspace"
20
-
21
- [tasks.server]
22
- description = "Run temporal server and workers"
23
- run = "overmind s"
24
-
25
- [tasks.workflow]
26
- description = "Run workflow client"
27
- run = "pnpm exec ts-node src/client.ts"
28
-
29
- [tasks.stop]
30
- description = "Stop temporal server and workers"
31
- run = "overmind quit || true"
32
-
33
- [tasks.kill]
34
- description = "Force kill temporal server and workers"
35
- run = """
36
- pkill -f 'examples/temporal.*ts-node' 2>/dev/null || true
37
- pkill -f 'overmind.*temporal' 2>/dev/null || true
38
- rm -f .overmind.sock
39
- echo 'Server killed'
40
- """
@@ -1,26 +0,0 @@
1
- {
2
- "name": "temporal-example",
3
- "version": "1.0.0",
4
- "private": true,
5
- "scripts": {
6
- "build": "tsc",
7
- "worker": "pnpm exec ts-node src/worker.ts",
8
- "client": "pnpm exec ts-node src/client.ts"
9
- },
10
- "dependencies": {
11
- "@braintrust/temporal": "^0.1.0",
12
- "@temporalio/activity": "^1.11.0",
13
- "@temporalio/client": "^1.11.0",
14
- "@temporalio/common": "^1.11.0",
15
- "@temporalio/worker": "^1.11.0",
16
- "@temporalio/workflow": "^1.11.0",
17
- "braintrust": "^2.0.0",
18
- "uuid": "^9.0.0"
19
- },
20
- "devDependencies": {
21
- "@types/node": "^20.0.0",
22
- "@types/uuid": "^9.0.0",
23
- "ts-node": "^10.9.0",
24
- "typescript": "^5.0.0"
25
- }
26
- }
@@ -1,42 +0,0 @@
1
- import * as braintrust from "braintrust";
2
-
3
- export interface TaskInput {
4
- value: number;
5
- }
6
-
7
- export async function addTen(input: TaskInput): Promise<number> {
8
- console.log(`Adding 10 to ${input.value}`);
9
-
10
- // Test child span within activity
11
- const result = await braintrust.traced(
12
- async (span) => {
13
- span.log({
14
- input: { value: input.value, operation: "add", operand: 10 },
15
- });
16
- await new Promise((resolve) => setTimeout(resolve, 500));
17
- const sum = input.value + 10;
18
- span.log({ output: sum });
19
- return sum;
20
- },
21
- { name: "compute.addition" },
22
- );
23
-
24
- console.log(`Result: ${input.value} + 10 = ${result}`);
25
- return result;
26
- }
27
-
28
- export async function multiplyByTwo(input: TaskInput): Promise<number> {
29
- console.log(`Multiplying ${input.value} by 2`);
30
- await new Promise((resolve) => setTimeout(resolve, 300));
31
- const result = input.value * 2;
32
- console.log(`Result: ${input.value} * 2 = ${result}`);
33
- return result;
34
- }
35
-
36
- export async function subtractFive(input: TaskInput): Promise<number> {
37
- console.log(`Subtracting 5 from ${input.value}`);
38
- await new Promise((resolve) => setTimeout(resolve, 300));
39
- const result = input.value - 5;
40
- console.log(`Result: ${input.value} - 5 = ${result}`);
41
- return result;
42
- }
@@ -1,53 +0,0 @@
1
- import { Client, Connection } from "@temporalio/client";
2
- import { v4 as uuid } from "uuid";
3
- import * as braintrust from "braintrust";
4
- import { BraintrustTemporalPlugin } from "@braintrust/temporal";
5
- import { simpleWorkflow } from "./workflows";
6
- import type { TaskInput } from "./activities";
7
-
8
- const TASK_QUEUE = "braintrust-example-task-queue";
9
-
10
- async function main() {
11
- braintrust.initLogger({ projectName: "temporal-example" });
12
-
13
- const connection = await Connection.connect({
14
- address: "localhost:7233",
15
- });
16
-
17
- const client = new Client({
18
- connection,
19
- namespace: "default",
20
- plugins: [new BraintrustTemporalPlugin()],
21
- });
22
-
23
- const inputData: TaskInput = { value: 5 };
24
- const workflowId = `simple-workflow-${uuid().slice(0, 8)}`;
25
-
26
- console.log(`Starting workflow with value: ${inputData.value}`);
27
- console.log(`Workflow ID: ${workflowId}`);
28
-
29
- // Wrap in a Braintrust span
30
- await braintrust.traced(
31
- async (span) => {
32
- const handle = await client.workflow.start(simpleWorkflow, {
33
- args: [inputData],
34
- taskQueue: TASK_QUEUE,
35
- workflowId,
36
- });
37
-
38
- const result = await handle.result();
39
- span.log({ output: result });
40
- console.log(`\nResult: ${result}`);
41
- console.log(`\nView trace: ${span.link()}`);
42
- return result;
43
- },
44
- { name: "temporal.client.simpleWorkflow" },
45
- );
46
-
47
- await braintrust.flush();
48
- }
49
-
50
- main().catch((err) => {
51
- console.error(err);
52
- process.exit(1);
53
- });
@@ -1,31 +0,0 @@
1
- import { Worker, NativeConnection } from "@temporalio/worker";
2
- import * as braintrust from "braintrust";
3
- import { BraintrustTemporalPlugin } from "@braintrust/temporal";
4
- import * as activities from "./activities";
5
-
6
- const TASK_QUEUE = "braintrust-example-task-queue";
7
-
8
- async function main() {
9
- braintrust.initLogger({ projectName: "temporal-example" });
10
-
11
- const connection = await NativeConnection.connect({
12
- address: "localhost:7233",
13
- });
14
-
15
- const worker = await Worker.create({
16
- connection,
17
- namespace: "default",
18
- taskQueue: TASK_QUEUE,
19
- workflowsPath: require.resolve("./workflows"),
20
- activities,
21
- plugins: [new BraintrustTemporalPlugin()],
22
- });
23
-
24
- console.log(`Worker started on task queue: ${TASK_QUEUE}`);
25
- await worker.run();
26
- }
27
-
28
- main().catch((err) => {
29
- console.error(err);
30
- process.exit(1);
31
- });
@@ -1,47 +0,0 @@
1
- import {
2
- proxyActivities,
3
- sleep,
4
- workflowInfo,
5
- defineSignal,
6
- setHandler,
7
- log,
8
- } from "@temporalio/workflow";
9
- import type * as activities from "./activities";
10
-
11
- const { addTen, multiplyByTwo, subtractFive } = proxyActivities<
12
- typeof activities
13
- >({
14
- startToCloseTimeout: "10 seconds",
15
- });
16
-
17
- export const addSignalValue = defineSignal<[number]>("addSignalValue");
18
-
19
- export interface TaskInput {
20
- value: number;
21
- }
22
-
23
- export async function simpleWorkflow(input: TaskInput): Promise<string> {
24
- log.info(`Starting workflow with value: ${input.value}`);
25
-
26
- let signalValue = 0;
27
- setHandler(addSignalValue, (value: number) => {
28
- log.info(`Received signal with value: ${value}`);
29
- signalValue += value;
30
- });
31
-
32
- // Step 1: Add 10
33
- const step1 = await addTen({ value: input.value });
34
- log.info(`After step 1: ${step1}`);
35
-
36
- // Step 2: Multiply by 2
37
- const step2 = await multiplyByTwo({ value: step1 });
38
- log.info(`After step 2: ${step2}`);
39
-
40
- // Step 3: Subtract 5
41
- const step3 = await subtractFive({ value: step2 });
42
- log.info(`After step 3: ${step3}`);
43
-
44
- const finalResult = `Complete: ${input.value} -> +10=${step1} -> *2=${step2} -> -5=${step3} + signal(${signalValue}) = ${step3 + signalValue}`;
45
- log.info(finalResult);
46
- return finalResult;
47
- }
@@ -1,15 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2021",
4
- "module": "commonjs",
5
- "lib": ["ES2021"],
6
- "strict": true,
7
- "esModuleInterop": true,
8
- "skipLibCheck": true,
9
- "forceConsistentCasingInFileNames": true,
10
- "outDir": "./dist",
11
- "rootDir": "./src",
12
- "declaration": true
13
- },
14
- "include": ["src/**/*"]
15
- }
@@ -1,243 +0,0 @@
1
- import { expect, test, describe } from "vitest";
2
- import {
3
- serializeHeaderValue,
4
- deserializeHeaderValue,
5
- BRAINTRUST_SPAN_HEADER,
6
- BRAINTRUST_WORKFLOW_SPAN_HEADER,
7
- BRAINTRUST_WORKFLOW_SPAN_ID_HEADER,
8
- } from "./utils";
9
- import { SpanComponentsV3, SpanObjectTypeV3 } from "braintrust/util";
10
- import {
11
- BraintrustTemporalPlugin,
12
- createBraintrustTemporalPlugin,
13
- } from "./plugin";
14
-
15
- describe("temporal header utilities", () => {
16
- test("serializeHeaderValue encodes string correctly", () => {
17
- const value = "test-span-id";
18
- const payload = serializeHeaderValue(value);
19
-
20
- expect(payload.metadata?.encoding).toBeDefined();
21
- expect(payload.data).toBeDefined();
22
- expect(new TextDecoder().decode(payload.metadata?.encoding)).toBe(
23
- "json/plain",
24
- );
25
- expect(new TextDecoder().decode(payload.data)).toBe('"test-span-id"');
26
- });
27
-
28
- test("deserializeHeaderValue decodes payload correctly", () => {
29
- const original = "test-value-123";
30
- const payload = serializeHeaderValue(original);
31
- const decoded = deserializeHeaderValue(payload);
32
-
33
- expect(decoded).toBe(original);
34
- });
35
-
36
- test("deserializeHeaderValue handles undefined payload", () => {
37
- expect(deserializeHeaderValue(undefined)).toBeUndefined();
38
- });
39
-
40
- test("deserializeHeaderValue handles payload without data", () => {
41
- expect(deserializeHeaderValue({ metadata: {} })).toBeUndefined();
42
- });
43
-
44
- test("deserializeHeaderValue handles invalid JSON", () => {
45
- const payload = {
46
- data: new TextEncoder().encode("not valid json"),
47
- };
48
- expect(deserializeHeaderValue(payload)).toBeUndefined();
49
- });
50
-
51
- test("round-trip serialization preserves complex strings", () => {
52
- const testCases = [
53
- "simple",
54
- "with spaces",
55
- "with/slashes",
56
- "unicode-日本語",
57
- "emoji-👋",
58
- "",
59
- ];
60
-
61
- for (const value of testCases) {
62
- const payload = serializeHeaderValue(value);
63
- const decoded = deserializeHeaderValue(payload);
64
- expect(decoded).toBe(value);
65
- }
66
- });
67
-
68
- test("header constants are defined", () => {
69
- expect(BRAINTRUST_SPAN_HEADER).toBe("_braintrust-span");
70
- expect(BRAINTRUST_WORKFLOW_SPAN_HEADER).toBe("_braintrust-workflow-span");
71
- expect(BRAINTRUST_WORKFLOW_SPAN_ID_HEADER).toBe(
72
- "_braintrust-workflow-span-id",
73
- );
74
- });
75
- });
76
-
77
- describe("SpanComponentsV3 cross-worker reconstruction", () => {
78
- test("can parse and reconstruct span components with new span_id", () => {
79
- const clientComponents = new SpanComponentsV3({
80
- object_type: SpanObjectTypeV3.PROJECT_LOGS,
81
- object_id: "project-123",
82
- row_id: "row-456",
83
- span_id: "client-span-id",
84
- root_span_id: "root-span-id",
85
- });
86
-
87
- const clientContext = clientComponents.toStr();
88
- const workflowSpanId = "workflow-span-id";
89
-
90
- const parsed = SpanComponentsV3.fromStr(clientContext);
91
- const data = parsed.data;
92
-
93
- expect(data.row_id).toBe("row-456");
94
- expect(data.root_span_id).toBe("root-span-id");
95
- expect(data.span_id).toBe("client-span-id");
96
-
97
- if (data.row_id && data.root_span_id) {
98
- const workflowComponents = new SpanComponentsV3({
99
- object_type: data.object_type,
100
- object_id: data.object_id,
101
- propagated_event: data.propagated_event,
102
- row_id: data.row_id,
103
- root_span_id: data.root_span_id,
104
- span_id: workflowSpanId,
105
- });
106
-
107
- const reconstructed = SpanComponentsV3.fromStr(
108
- workflowComponents.toStr(),
109
- );
110
- expect(reconstructed.data.span_id).toBe(workflowSpanId);
111
- expect(reconstructed.data.row_id).toBe("row-456");
112
- expect(reconstructed.data.root_span_id).toBe("root-span-id");
113
- expect(reconstructed.data.object_id).toBe("project-123");
114
- }
115
- });
116
-
117
- test("preserves object_type when reconstructing", () => {
118
- const objectTypes = [
119
- SpanObjectTypeV3.PROJECT_LOGS,
120
- SpanObjectTypeV3.EXPERIMENT,
121
- SpanObjectTypeV3.PLAYGROUND_LOGS,
122
- ];
123
-
124
- for (const objectType of objectTypes) {
125
- const original = new SpanComponentsV3({
126
- object_type: objectType,
127
- object_id: "test-id",
128
- row_id: "row-id",
129
- span_id: "original-span-id",
130
- root_span_id: "root-span-id",
131
- });
132
-
133
- const parsed = SpanComponentsV3.fromStr(original.toStr());
134
-
135
- const reconstructed = new SpanComponentsV3({
136
- object_type: parsed.data.object_type,
137
- object_id: parsed.data.object_id,
138
- propagated_event: parsed.data.propagated_event,
139
- row_id: parsed.data.row_id!,
140
- root_span_id: parsed.data.root_span_id!,
141
- span_id: "new-span-id",
142
- });
143
-
144
- expect(reconstructed.data.object_type).toBe(objectType);
145
- }
146
- });
147
-
148
- test("handles span components without row_id fields", () => {
149
- const componentsWithoutRowId = new SpanComponentsV3({
150
- object_type: SpanObjectTypeV3.PROJECT_LOGS,
151
- object_id: "test-id",
152
- });
153
-
154
- const parsed = SpanComponentsV3.fromStr(componentsWithoutRowId.toStr());
155
-
156
- expect(parsed.data.row_id).toBeUndefined();
157
- expect(parsed.data.span_id).toBeUndefined();
158
- expect(parsed.data.root_span_id).toBeUndefined();
159
- });
160
-
161
- test("preserves propagated_event when reconstructing", () => {
162
- const propagatedEvent = { key: "value", nested: { inner: 123 } };
163
-
164
- const original = new SpanComponentsV3({
165
- object_type: SpanObjectTypeV3.PROJECT_LOGS,
166
- object_id: "test-id",
167
- propagated_event: propagatedEvent,
168
- row_id: "row-id",
169
- span_id: "original-span-id",
170
- root_span_id: "root-span-id",
171
- });
172
-
173
- const parsed = SpanComponentsV3.fromStr(original.toStr());
174
-
175
- const reconstructed = new SpanComponentsV3({
176
- object_type: parsed.data.object_type,
177
- object_id: parsed.data.object_id,
178
- propagated_event: parsed.data.propagated_event,
179
- row_id: parsed.data.row_id!,
180
- root_span_id: parsed.data.root_span_id!,
181
- span_id: "new-span-id",
182
- });
183
-
184
- expect(reconstructed.data.propagated_event).toEqual(propagatedEvent);
185
- });
186
- });
187
-
188
- describe("BraintrustTemporalPlugin", () => {
189
- test("createBraintrustTemporalPlugin returns a plugin instance", () => {
190
- const plugin = createBraintrustTemporalPlugin();
191
- expect(plugin).toBeInstanceOf(BraintrustTemporalPlugin);
192
- expect(plugin.name).toBe("braintrust");
193
- });
194
-
195
- test("plugin has configureClient method", () => {
196
- const plugin = createBraintrustTemporalPlugin();
197
- expect(typeof plugin.configureClient).toBe("function");
198
- });
199
-
200
- test("plugin has configureWorker method", () => {
201
- const plugin = createBraintrustTemporalPlugin();
202
- expect(typeof plugin.configureWorker).toBe("function");
203
- });
204
-
205
- test("configureClient adds workflow interceptor", () => {
206
- const plugin = createBraintrustTemporalPlugin();
207
- const options = {};
208
- const configured = plugin.configureClient(options);
209
-
210
- expect(configured.interceptors).toBeDefined();
211
- expect(configured.interceptors?.workflow).toBeDefined();
212
- expect(Array.isArray(configured.interceptors?.workflow)).toBe(true);
213
- expect(configured.interceptors?.workflow?.length).toBe(1);
214
- });
215
-
216
- test("configureClient preserves existing interceptors", () => {
217
- const plugin = createBraintrustTemporalPlugin();
218
- const existingInterceptor = { start: async (i: unknown, n: unknown) => n };
219
- const options = {
220
- interceptors: {
221
- workflow: [existingInterceptor],
222
- },
223
- };
224
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
225
- const configured = plugin.configureClient(options as any);
226
-
227
- expect(configured.interceptors?.workflow?.length).toBe(2);
228
- });
229
-
230
- test("configureWorker adds activity interceptor and sinks", () => {
231
- const plugin = createBraintrustTemporalPlugin();
232
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
233
- const options = {} as any;
234
- const configured = plugin.configureWorker(options);
235
-
236
- expect(configured.interceptors).toBeDefined();
237
- expect(configured.interceptors?.activity).toBeDefined();
238
- expect(Array.isArray(configured.interceptors?.activity)).toBe(true);
239
- expect(configured.interceptors?.activity?.length).toBe(1);
240
- expect(configured.sinks).toBeDefined();
241
- expect(configured.sinks?.braintrust).toBeDefined();
242
- });
243
- });