@outputai/core 0.4.1-dev.622e67b.0 → 0.4.1-dev.7aa9a5f.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outputai/core",
3
- "version": "0.4.1-dev.622e67b.0",
3
+ "version": "0.4.1-dev.7aa9a5f.0",
4
4
  "description": "The core module of the output framework",
5
5
  "type": "module",
6
6
  "exports": {
@@ -33,6 +33,7 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@aws-sdk/client-s3": "3.1038.0",
36
+ "@aws-sdk/lib-storage": "3.1038.0",
36
37
  "@babel/generator": "7.29.1",
37
38
  "@babel/parser": "7.29.2",
38
39
  "@babel/traverse": "7.29.0",
@@ -42,6 +43,8 @@
42
43
  "@temporalio/common": "1.17.0",
43
44
  "@temporalio/worker": "1.17.0",
44
45
  "@temporalio/workflow": "1.17.0",
46
+ "decimal.js": "10.6.0",
47
+ "json-stream-stringify": "3.1.6",
45
48
  "redis": "5.12.1",
46
49
  "stacktrace-parser": "0.1.11",
47
50
  "undici": "8.1.0",
@@ -64,6 +67,7 @@
64
67
  "#logger": "./src/logger.js",
65
68
  "#utils": "./src/utils/index.js",
66
69
  "#tracing": "./src/tracing/internal_interface.js",
70
+ "#trace_attribute": "./src/tracing/trace_attribute.js",
67
71
  "#async_storage": "./src/async_storage.js",
68
72
  "#internal_activities": "./src/internal_activities/index.js"
69
73
  },
@@ -1,3 +1,6 @@
1
+ import type { Attribute } from '#trace_attribute';
2
+
3
+ export { Attribute } from '#trace_attribute';
1
4
  /**
2
5
  * Creates a new event.
3
6
  *
@@ -32,14 +35,6 @@ export declare function addEventError( args: { id: string; details: unknown } ):
32
35
  *
33
36
  * @param args
34
37
  * @param args.eventId - The id of the event to attach the attribute to.
35
- * @param args.name - The attribute name
36
- * @param args.value - The attribute value
37
- */
38
- export declare function addEventAttribute( args: { eventId: string; name: string, value: unknown } ): void;
39
-
40
- /**
41
- * Known attributes.
38
+ * @param args.attribute - The attribute to attach to the event.
42
39
  */
43
- export declare const Attribute: {
44
- COST: 'cost';
45
- };
40
+ export declare function addEventAttribute( args: { eventId: string; attribute: Attribute.Instance } ): void;
@@ -1,5 +1,7 @@
1
1
  import { addEventActionWithContext, EventAction } from '#tracing';
2
2
 
3
+ export { Attribute } from '#trace_attribute';
4
+
3
5
  /**
4
6
  * Creates a new event.
5
7
  *
@@ -42,12 +44,5 @@ export const addEventError = ( { id, details } ) => addEventActionWithContext( E
42
44
  * @param {unknown} args.value - The attribute value
43
45
  * @returns {void}
44
46
  */
45
- export const addEventAttribute = ( { eventId, name, value } ) =>
46
- addEventActionWithContext( EventAction.ADD_ATTR, { id: eventId, details: { name, value } } );
47
-
48
- /**
49
- * Known attributes
50
- */
51
- export const Attribute = {
52
- COST: 'cost'
53
- };
47
+ export const addEventAttribute = ( { eventId, attribute } ) =>
48
+ addEventActionWithContext( EventAction.ADD_ATTR, { id: eventId, details: attribute } );
package/src/consts.js CHANGED
@@ -33,6 +33,10 @@ export const BusEventType = {
33
33
  RUNTIME_ERROR: 'runtime_error'
34
34
  };
35
35
 
36
+ export const Signal = {
37
+ ADD_ATTRIBUTE: 'add_attribute'
38
+ };
39
+
36
40
  export const WorkflowSpecialOutput = {
37
41
  CONTINUED_AS_NEW: '<<continued_as_new>>'
38
42
  };
@@ -0,0 +1,24 @@
1
+ import { Attribute } from '#trace_attribute';
2
+ import Decimal from 'decimal.js';
3
+
4
+ export const aggregateAttributes = attributes => ( {
5
+ cost: {
6
+ total: attributes
7
+ .filter( a => [ Attribute.HTTPRequestCost.TYPE, Attribute.LLMUsage.TYPE ].includes( a.type ) )
8
+ .reduce( ( sum, a ) => sum.add( a.total ), Decimal( 0 ) ).toNumber()
9
+ },
10
+ tokens: {
11
+ total: attributes
12
+ .filter( a => Attribute.LLMUsage.TYPE === a.type )
13
+ .reduce( ( sum, a ) => sum.add( a.tokensUsed ), Decimal( 0 ) ).toNumber(),
14
+ ...Object.entries( attributes
15
+ .filter( a => Attribute.LLMUsage.TYPE === a.type )
16
+ .flatMap( a => a.usage )
17
+ .reduce( ( obj, a ) => Object.assign( obj, { [a.type]: ( obj[a.type] ?? Decimal( 0 ) ).add( a.amount ) } ), {} ) )
18
+ .reduce( ( obj, [ k, v ] ) => Object.assign( obj, { [k]: v.toNumber() } ), {} ) // convert all values to number
19
+
20
+ },
21
+ httpRequests: {
22
+ total: attributes.filter( a => Attribute.HTTPRequestCount.TYPE === a.type ).length
23
+ }
24
+ } );
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { Attribute } from '#trace_attribute';
3
+ import { aggregateAttributes } from './aggregations.js';
4
+
5
+ describe( 'aggregateAttributes', () => {
6
+ it( 'returns zeroed aggregations when there are no attributes', () => {
7
+ expect( aggregateAttributes( [] ) ).toEqual( {
8
+ cost: { total: 0 },
9
+ tokens: { total: 0 },
10
+ httpRequests: { total: 0 }
11
+ } );
12
+ } );
13
+
14
+ it( 'aggregates costs, token usage, and HTTP request count by attribute type', () => {
15
+ const attributes = [
16
+ {
17
+ type: Attribute.HTTPRequestCount.TYPE,
18
+ url: 'https://api.example.test/a',
19
+ requestId: 'req-1'
20
+ },
21
+ {
22
+ type: Attribute.HTTPRequestCount.TYPE,
23
+ url: 'https://api.example.test/b',
24
+ requestId: 'req-2'
25
+ },
26
+ {
27
+ type: Attribute.HTTPRequestCost.TYPE,
28
+ url: 'https://api.example.test/a',
29
+ requestId: 'req-1',
30
+ total: 0.2
31
+ },
32
+ {
33
+ type: Attribute.LLMUsage.TYPE,
34
+ modelId: 'gpt-4o',
35
+ total: 0.3,
36
+ tokensUsed: 120,
37
+ usage: [
38
+ { type: 'input', ppm: 1, amount: 100, total: 0.1 },
39
+ { type: 'output', ppm: 2, amount: 20, total: 0.2 }
40
+ ]
41
+ },
42
+ {
43
+ type: Attribute.LLMUsage.TYPE,
44
+ modelId: 'gpt-4o-mini',
45
+ total: 0.05,
46
+ tokensUsed: 30,
47
+ usage: [
48
+ { type: 'input', ppm: 1, amount: 25, total: 0.025 },
49
+ { type: 'reasoning', ppm: 5, amount: 5, total: 0.025 }
50
+ ]
51
+ },
52
+ {
53
+ type: 'unrelated',
54
+ total: 100,
55
+ tokensUsed: 100
56
+ }
57
+ ];
58
+
59
+ expect( aggregateAttributes( attributes ) ).toEqual( {
60
+ cost: { total: 0.55 },
61
+ tokens: {
62
+ total: 150,
63
+ input: 125,
64
+ output: 20,
65
+ reasoning: 5
66
+ },
67
+ httpRequests: { total: 2 }
68
+ } );
69
+ } );
70
+
71
+ it( 'uses LLMUsage.tokensUsed for total tokens instead of summing usage amounts', () => {
72
+ const attributes = [
73
+ {
74
+ type: Attribute.LLMUsage.TYPE,
75
+ modelId: 'provider-model',
76
+ total: 0.1,
77
+ tokensUsed: 42,
78
+ usage: [
79
+ { type: 'input', ppm: 1, amount: 10, total: 0.01 },
80
+ { type: 'output', ppm: 1, amount: 5, total: 0.005 }
81
+ ]
82
+ }
83
+ ];
84
+
85
+ expect( aggregateAttributes( attributes ).tokens ).toEqual( {
86
+ total: 42,
87
+ input: 10,
88
+ output: 5
89
+ } );
90
+ } );
91
+ } );
@@ -1,11 +1,13 @@
1
1
  // THIS RUNS IN THE TEMPORAL'S SANDBOX ENVIRONMENT
2
2
  import { proxyActivities, inWorkflowContext, executeChild, workflowInfo, uuid4, ParentClosePolicy, continueAsNew } from '@temporalio/workflow';
3
+ import { defineSignal, setHandler } from '@temporalio/workflow';
3
4
  import { validateWorkflow } from './validations/static.js';
4
5
  import { validateWithSchema } from './validations/runtime.js';
5
- import { SHARED_STEP_PREFIX, ACTIVITY_GET_TRACE_DESTINATIONS, METADATA_ACCESS_SYMBOL } from '#consts';
6
+ import { SHARED_STEP_PREFIX, ACTIVITY_GET_TRACE_DESTINATIONS, METADATA_ACCESS_SYMBOL, Signal } from '#consts';
6
7
  import { deepMerge, setMetadata, toUrlSafeBase64 } from '#utils';
7
8
  import { FatalError, ValidationError } from '#errors';
8
9
  import { Context } from './workflow_context.js';
10
+ import { aggregateAttributes } from './aggregations.js';
9
11
 
10
12
  const defaultOptions = {
11
13
  activityOptions: {
@@ -22,6 +24,9 @@ const defaultOptions = {
22
24
  disableTrace: false
23
25
  };
24
26
 
27
+ export const extractErrorDetail = ( e, key ) =>
28
+ e ? ( e.details?.find?.( d => d[key] )?.[key] ?? extractErrorDetail( e.cause, key ) ) : null;
29
+
25
30
  export function workflow( { name, description, inputSchema, outputSchema, fn, options = {}, aliases = [] } ) {
26
31
  validateWorkflow( { name, description, inputSchema, outputSchema, fn, options, aliases } );
27
32
 
@@ -69,7 +74,9 @@ export function workflow( { name, description, inputSchema, outputSchema, fn, op
69
74
 
70
75
  // Run the internal activity to retrieve the workflow trace destinations (only for root workflows, not nested)
71
76
  const traceDestinations = isRoot ? ( await steps[ACTIVITY_GET_TRACE_DESTINATIONS]( executionContext ) ) : null;
72
- const traceObject = { trace: { destinations: traceDestinations } };
77
+
78
+ const attributes = [];
79
+ setHandler( defineSignal( Signal.ADD_ATTRIBUTE ), e => attributes.push( e ) );
73
80
 
74
81
  try {
75
82
  // validation comes after setting memo to have that info already set for interceptor even if validations fail
@@ -91,17 +98,25 @@ export function workflow( { name, description, inputSchema, outputSchema, fn, op
91
98
  * @param {import('@temporalio/workflow').ActivityOptions} extra.options
92
99
  * @returns {Promise<unknown>}
93
100
  */
94
- startWorkflow: async ( childName, input, extra = {} ) =>
95
- executeChild( childName, {
96
- args: input ? [ input ] : [],
97
- workflowId: `${workflowId}-${toUrlSafeBase64( uuid4() )}`,
98
- parentClosePolicy: ParentClosePolicy[extra?.detached ? 'ABANDON' : 'TERMINATE'],
99
- memo: {
100
- executionContext,
101
- parentId: workflowId,
102
- ...( extra?.options?.activityOptions && { activityOptions: deepMerge( activityOptions, extra.options.activityOptions ) } )
103
- }
104
- } )
101
+ startWorkflow: async ( childName, input, extra = {} ) => {
102
+ try {
103
+ const result = await executeChild( childName, {
104
+ args: input ? [ input ] : [],
105
+ workflowId: `${workflowId}-${toUrlSafeBase64( uuid4() )}`,
106
+ parentClosePolicy: ParentClosePolicy[extra?.detached ? 'ABANDON' : 'TERMINATE'],
107
+ memo: {
108
+ executionContext,
109
+ parentId: workflowId,
110
+ ...( extra?.options?.activityOptions && { activityOptions: deepMerge( activityOptions, extra.options.activityOptions ) } )
111
+ }
112
+ } );
113
+ attributes.push( ...( result.attributes ?? [] ) );
114
+ return result.output;
115
+ } catch ( error ) {
116
+ attributes.push( ...( extractErrorDetail( error, 'attributes' ) ?? [] ) );
117
+ throw error;
118
+ }
119
+ }
105
120
  };
106
121
 
107
122
  const output = await fn.call( dispatchers, input, context );
@@ -110,14 +125,17 @@ export function workflow( { name, description, inputSchema, outputSchema, fn, op
110
125
 
111
126
  if ( isRoot ) {
112
127
  // Append the trace info to the result of the workflow
113
- return { output, ...traceObject };
128
+ return { output, trace: { destinations: traceDestinations }, attributes, aggregations: aggregateAttributes( attributes ) };
114
129
  }
115
130
 
116
- return output;
131
+ return { output, attributes };
117
132
  } catch ( e ) {
118
- // Append the trace info as metadata of the error, so it can be read by the interceptor.
133
+ // Append the extra info as metadata of the error, so it can be read by the interceptor.
134
+ e[METADATA_ACCESS_SYMBOL] = { ...( e[METADATA_ACCESS_SYMBOL] ?? {} ), attributes };
135
+ // if it is roo also add trace/aggregations
119
136
  if ( isRoot ) {
120
- e[METADATA_ACCESS_SYMBOL] = { ...( e[METADATA_ACCESS_SYMBOL] ?? {} ), ...traceObject };
137
+ e[METADATA_ACCESS_SYMBOL].trace = { destinations: traceDestinations };
138
+ e[METADATA_ACCESS_SYMBOL].aggregations = aggregateAttributes( attributes );
121
139
  }
122
140
  throw e;
123
141
  }
@@ -1,7 +1,10 @@
1
+ import { Signal } from '#consts';
1
2
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
3
  import { z } from 'zod';
3
4
 
4
5
  const inWorkflowContextMock = vi.hoisted( () => vi.fn( () => true ) );
6
+ const defineSignalMock = vi.hoisted( () => vi.fn( name => name ) );
7
+ const setHandlerMock = vi.hoisted( () => vi.fn() );
5
8
  const traceDestinationsStepMock = vi.fn().mockResolvedValue( { local: '/tmp/trace' } );
6
9
  const executeChildMock = vi.fn().mockResolvedValue( undefined );
7
10
  const continueAsNewMock = vi.fn().mockResolvedValue( undefined );
@@ -41,7 +44,16 @@ vi.mock( '@temporalio/workflow', () => ( {
41
44
  workflowInfo: workflowInfoMock,
42
45
  uuid4: () => '550e8400e29b41d4a716446655440000',
43
46
  ParentClosePolicy: { TERMINATE: 'TERMINATE', ABANDON: 'ABANDON' },
44
- continueAsNew: continueAsNewMock
47
+ ChildWorkflowFailure: class ChildWorkflowFailure extends Error {
48
+ constructor( message, cause ) {
49
+ super( message );
50
+ this.name = 'ChildWorkflowFailure';
51
+ this.cause = cause;
52
+ }
53
+ },
54
+ continueAsNew: continueAsNewMock,
55
+ defineSignal: ( ...args ) => defineSignalMock( ...args ),
56
+ setHandler: ( ...args ) => setHandlerMock( ...args )
45
57
  } ) );
46
58
 
47
59
  vi.mock( '#consts', async importOriginal => {
@@ -53,10 +65,17 @@ vi.mock( '#consts', async importOriginal => {
53
65
  };
54
66
  } );
55
67
 
68
+ const emptyAggregations = {
69
+ cost: { total: 0 },
70
+ tokens: { total: 0 },
71
+ httpRequests: { total: 0 }
72
+ };
73
+
56
74
  describe( 'workflow()', () => {
57
75
  beforeEach( () => {
58
76
  vi.clearAllMocks();
59
77
  inWorkflowContextMock.mockReturnValue( true );
78
+ defineSignalMock.mockImplementation( name => name );
60
79
  workflowInfoMock.mockReturnValue( { ...workflowInfoReturn } );
61
80
  workflowInfoReturn.memo = {};
62
81
  proxyActivitiesMock.mockImplementation( () => {
@@ -217,7 +236,7 @@ describe( 'workflow()', () => {
217
236
  } );
218
237
 
219
238
  describe( 'root workflow (in workflow context)', () => {
220
- it( 'calls getTraceDestinations, returns { output, trace } and assigns executionContext to memo', async () => {
239
+ it( 'calls getTraceDestinations, returns root trace data and assigns executionContext to memo', async () => {
221
240
  const { workflow } = await import( './workflow.js' );
222
241
 
223
242
  const wf = workflow( {
@@ -232,7 +251,9 @@ describe( 'workflow()', () => {
232
251
  expect( traceDestinationsStepMock ).toHaveBeenCalledTimes( 1 );
233
252
  expect( result ).toEqual( {
234
253
  output: { v: 42 },
235
- trace: { destinations: { local: '/tmp/trace' } }
254
+ trace: { destinations: { local: '/tmp/trace' } },
255
+ attributes: [],
256
+ aggregations: emptyAggregations
236
257
  } );
237
258
  const memo = workflowInfoMock().memo;
238
259
  expect( memo.executionContext ).toEqual( {
@@ -243,6 +264,68 @@ describe( 'workflow()', () => {
243
264
  } );
244
265
  } );
245
266
 
267
+ it( 'collects attribute signals and returns aggregated attributes', async () => {
268
+ const { workflow } = await import( './workflow.js' );
269
+ const { Attribute } = await import( '#trace_attribute' );
270
+ const handlers = { addAttribute: () => {} };
271
+ setHandlerMock.mockImplementation( ( signalName, handler ) => {
272
+ if ( signalName === Signal.ADD_ATTRIBUTE ) {
273
+ handlers.addAttribute = handler;
274
+ }
275
+ } );
276
+
277
+ const httpRequest = {
278
+ type: Attribute.HTTPRequestCount.TYPE,
279
+ url: 'https://api.example.test/items',
280
+ requestId: 'req-1'
281
+ };
282
+ const httpCost = {
283
+ type: Attribute.HTTPRequestCost.TYPE,
284
+ url: 'https://api.example.test/items',
285
+ requestId: 'req-1',
286
+ total: 2.5
287
+ };
288
+ const llmUsage = {
289
+ type: Attribute.LLMUsage.TYPE,
290
+ modelId: 'gpt-4o',
291
+ total: 0.25,
292
+ usage: [
293
+ { type: 'input', ppm: 5, amount: 20_000, total: 0.1 },
294
+ { type: 'output', ppm: 30, amount: 5_000, total: 0.15 }
295
+ ],
296
+ tokensUsed: 25_000
297
+ };
298
+
299
+ const wf = workflow( {
300
+ name: 'attr_wf',
301
+ description: 'Attributes',
302
+ inputSchema: z.object( {} ),
303
+ outputSchema: z.object( { ok: z.boolean() } ),
304
+ fn: async () => {
305
+ handlers.addAttribute( httpRequest );
306
+ handlers.addAttribute( httpCost );
307
+ handlers.addAttribute( llmUsage );
308
+ return { ok: true };
309
+ }
310
+ } );
311
+
312
+ const result = await wf( {} );
313
+ expect( result ).toEqual( {
314
+ output: { ok: true },
315
+ trace: { destinations: { local: '/tmp/trace' } },
316
+ attributes: [ httpRequest, httpCost, llmUsage ],
317
+ aggregations: {
318
+ cost: { total: 2.75 },
319
+ tokens: {
320
+ total: 25_000,
321
+ input: 20_000,
322
+ output: 5_000
323
+ },
324
+ httpRequests: { total: 1 }
325
+ }
326
+ } );
327
+ } );
328
+
246
329
  it( 'sets executionContext.disableTrace when options.disableTrace is true', async () => {
247
330
  const { workflow } = await import( './workflow.js' );
248
331
 
@@ -261,7 +344,7 @@ describe( 'workflow()', () => {
261
344
  } );
262
345
 
263
346
  describe( 'child workflow (memo.executionContext already set)', () => {
264
- it( 'does not call getTraceDestinations and returns plain output', async () => {
347
+ it( 'does not call getTraceDestinations and returns an internal output envelope', async () => {
265
348
  workflowInfoMock.mockReturnValue( {
266
349
  ...workflowInfoReturn,
267
350
  memo: { executionContext: { workflowId: 'parent-1', workflowName: 'parent_wf' } }
@@ -278,7 +361,7 @@ describe( 'workflow()', () => {
278
361
 
279
362
  const result = await wf( {} );
280
363
  expect( traceDestinationsStepMock ).not.toHaveBeenCalled();
281
- expect( result ).toEqual( { x: 'child' } );
364
+ expect( result ).toEqual( { output: { x: 'child' }, attributes: [] } );
282
365
  } );
283
366
  } );
284
367
 
@@ -381,6 +464,7 @@ describe( 'workflow()', () => {
381
464
  it( 'calls executeChild with correct args and TERMINATE when not detached', async () => {
382
465
  const { workflow } = await import( './workflow.js' );
383
466
  const { ParentClosePolicy } = await import( '@temporalio/workflow' );
467
+ executeChildMock.mockResolvedValueOnce( { output: {}, attributes: [] } );
384
468
 
385
469
  const wf = workflow( {
386
470
  name: 'parent_wf',
@@ -408,6 +492,7 @@ describe( 'workflow()', () => {
408
492
  it( 'uses ABANDON when extra.detached is true', async () => {
409
493
  const { workflow } = await import( './workflow.js' );
410
494
  const { ParentClosePolicy } = await import( '@temporalio/workflow' );
495
+ executeChildMock.mockResolvedValueOnce( { output: {}, attributes: [] } );
411
496
 
412
497
  const wf = workflow( {
413
498
  name: 'detach_wf',
@@ -428,6 +513,7 @@ describe( 'workflow()', () => {
428
513
 
429
514
  it( 'passes empty args when input is null/omitted', async () => {
430
515
  const { workflow } = await import( './workflow.js' );
516
+ executeChildMock.mockResolvedValueOnce( { output: {}, attributes: [] } );
431
517
 
432
518
  const wf = workflow( {
433
519
  name: 'no_input_wf',
@@ -445,11 +531,96 @@ describe( 'workflow()', () => {
445
531
  args: []
446
532
  } ) );
447
533
  } );
534
+
535
+ it( 'returns child output and merges child attributes into the root result', async () => {
536
+ const { workflow } = await import( './workflow.js' );
537
+ const { Attribute } = await import( '#trace_attribute' );
538
+ const childAttribute = {
539
+ type: Attribute.LLMUsage.TYPE,
540
+ modelId: 'gpt-4o',
541
+ total: 0.4,
542
+ tokensUsed: 20,
543
+ usage: [
544
+ { type: 'input', ppm: 10, amount: 20, total: 0.4 }
545
+ ]
546
+ };
547
+ executeChildMock.mockResolvedValueOnce( {
548
+ output: { child: 'ok' },
549
+ attributes: [ childAttribute ]
550
+ } );
551
+
552
+ const wf = workflow( {
553
+ name: 'merge_child_wf',
554
+ description: 'Merge child attributes',
555
+ inputSchema: z.object( {} ),
556
+ outputSchema: z.object( { child: z.string() } ),
557
+ async fn() {
558
+ return this.startWorkflow( 'child_wf', { id: 1 } );
559
+ }
560
+ } );
561
+
562
+ const result = await wf( {} );
563
+ expect( result ).toEqual( {
564
+ output: { child: 'ok' },
565
+ trace: { destinations: { local: '/tmp/trace' } },
566
+ attributes: [ childAttribute ],
567
+ aggregations: {
568
+ cost: { total: 0.4 },
569
+ tokens: {
570
+ total: 20,
571
+ input: 20
572
+ },
573
+ httpRequests: { total: 0 }
574
+ }
575
+ } );
576
+ } );
577
+
578
+ it( 'merges child error attributes before rethrowing to root metadata', async () => {
579
+ const { workflow } = await import( './workflow.js' );
580
+ const { ChildWorkflowFailure } = await import( '@temporalio/workflow' );
581
+ const { METADATA_ACCESS_SYMBOL } = await import( '#consts' );
582
+ const { Attribute } = await import( '#trace_attribute' );
583
+ const childAttribute = {
584
+ type: Attribute.HTTPRequestCost.TYPE,
585
+ url: 'https://api.example.test',
586
+ requestId: 'req-child',
587
+ total: 2
588
+ };
589
+ const childError = new ChildWorkflowFailure( 'child failed', {
590
+ message: 'Child workflow execution failed',
591
+ details: [ { attributes: [ childAttribute ] } ]
592
+ } );
593
+ executeChildMock.mockRejectedValueOnce( childError );
594
+
595
+ const wf = workflow( {
596
+ name: 'child_error_wf',
597
+ description: 'Child error attributes',
598
+ inputSchema: z.object( {} ),
599
+ outputSchema: z.object( {} ),
600
+ async fn() {
601
+ await this.startWorkflow( 'child_wf', { id: 1 } );
602
+ return {};
603
+ }
604
+ } );
605
+
606
+ await expect( wf( {} ) ).rejects.toThrow( 'child failed' );
607
+ expect( childError[METADATA_ACCESS_SYMBOL] ).toEqual( {
608
+ attributes: [ childAttribute ],
609
+ trace: { destinations: { local: '/tmp/trace' } },
610
+ aggregations: {
611
+ cost: { total: 2 },
612
+ tokens: { total: 0 },
613
+ httpRequests: { total: 0 }
614
+ }
615
+ } );
616
+ } );
448
617
  } );
449
618
 
450
619
  describe( 'error handling (root workflow)', () => {
451
- it( 'rethrows error from fn and rejects with same message', async () => {
620
+ it( 'rethrows error from fn with trace attributes and aggregation metadata', async () => {
452
621
  const { workflow } = await import( './workflow.js' );
622
+ const { METADATA_ACCESS_SYMBOL } = await import( '#consts' );
623
+ const error = new Error( 'workflow failed' );
453
624
 
454
625
  const wf = workflow( {
455
626
  name: 'err_wf',
@@ -457,11 +628,16 @@ describe( 'workflow()', () => {
457
628
  inputSchema: z.object( {} ),
458
629
  outputSchema: z.object( {} ),
459
630
  fn: async () => {
460
- throw new Error( 'workflow failed' );
631
+ throw error;
461
632
  }
462
633
  } );
463
634
 
464
635
  await expect( wf( {} ) ).rejects.toThrow( 'workflow failed' );
636
+ expect( error[METADATA_ACCESS_SYMBOL] ).toEqual( {
637
+ trace: { destinations: { local: '/tmp/trace' } },
638
+ attributes: [],
639
+ aggregations: emptyAggregations
640
+ } );
465
641
  } );
466
642
  } );
467
643
  } );
@@ -1,9 +1,11 @@
1
- import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
1
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, createWriteStream } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'url';
4
4
  import buildTraceTree from '../../tools/build_trace_tree.js';
5
- import { safeFormatJSON } from '../../tools/utils.js';
6
5
  import { EOL } from 'node:os';
6
+ import { JsonStreamStringify } from 'json-stream-stringify';
7
+
8
+ import { pipeline } from 'stream/promises';
7
9
 
8
10
  const __dirname = dirname( fileURLToPath( import.meta.url ) );
9
11
 
@@ -109,7 +111,7 @@ export const init = () => {
109
111
  * @param {object} args.executionContext - Execution info: workflowId, workflowName, startTime
110
112
  * @returns {void}
111
113
  */
112
- export const exec = ( { entry, executionContext } ) => {
114
+ export const exec = async ( { entry, executionContext } ) => {
113
115
  const { workflowId, workflowName, startTime } = executionContext;
114
116
  const tempFilePath = createTempFilePath( executionContext );
115
117
  addEntry( entry, tempFilePath );
@@ -126,7 +128,11 @@ export const exec = ( { entry, executionContext } ) => {
126
128
  const path = join( dir, buildTraceFilename( { startTime, workflowId } ) );
127
129
 
128
130
  mkdirSync( dir, { recursive: true } );
129
- writeFileSync( path, safeFormatJSON( content ) + EOL, 'utf-8' );
131
+
132
+ await pipeline(
133
+ new JsonStreamStringify( content ),
134
+ createWriteStream( path )
135
+ );
130
136
  };
131
137
 
132
138
  /**