@outputai/core 0.15.1-next.ff9e1ab.0 → 0.16.1-next.25ff32e.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.
Files changed (109) hide show
  1. package/dist/credentials/index.d.ts +1 -1
  2. package/dist/credentials/types.d.ts +4 -4
  3. package/dist/evals/aggregate.d.ts +2 -0
  4. package/dist/evals/aggregate.js +11 -0
  5. package/dist/evals/eval_workflow.d.ts +20 -0
  6. package/dist/evals/eval_workflow.js +98 -0
  7. package/dist/evals/index.d.ts +7 -0
  8. package/dist/evals/index.js +4 -0
  9. package/dist/evals/interpret.d.ts +3 -0
  10. package/dist/evals/interpret.js +40 -0
  11. package/dist/evals/schemas.d.ts +96 -0
  12. package/dist/evals/schemas.js +60 -0
  13. package/dist/evals/verdict.d.ts +27 -0
  14. package/dist/evals/verdict.js +109 -0
  15. package/dist/evals/verify.d.ts +42 -0
  16. package/dist/evals/verify.js +19 -0
  17. package/package.json +64 -14
  18. package/src/consts.d.ts +2 -0
  19. package/src/consts.js +4 -3
  20. package/src/helpers/error_serializer.js +26 -5
  21. package/src/helpers/fetch.js +21 -9
  22. package/src/helpers/path.js +34 -0
  23. package/src/helpers/redact.js +2 -1
  24. package/src/hooks/index.js +1 -1
  25. package/src/http/config.js +10 -0
  26. package/src/http/cost.d.ts +20 -0
  27. package/src/http/cost.js +41 -0
  28. package/src/http/fetch/events.js +10 -0
  29. package/src/http/fetch/index.d.ts +24 -0
  30. package/src/http/fetch/index.js +78 -0
  31. package/src/http/fetch/logger.d.ts +10 -0
  32. package/src/http/fetch/logger.js +56 -0
  33. package/src/http/index.d.ts +28 -0
  34. package/src/http/index.js +9 -0
  35. package/src/http/ky/index.d.ts +25 -0
  36. package/src/http/ky/index.js +10 -0
  37. package/src/http/request_tag.js +30 -0
  38. package/src/interface/index.d.ts +1 -0
  39. package/src/interface/logger.js +4 -4
  40. package/src/llm/agent.js +147 -0
  41. package/src/llm/ai_provider.js +131 -0
  42. package/src/llm/ai_sdk_options.js +126 -0
  43. package/src/llm/consts.js +6 -0
  44. package/src/llm/deprecated_provider_aliases.js +8 -0
  45. package/src/llm/generate.js +98 -0
  46. package/src/llm/index.d.ts +697 -0
  47. package/src/llm/index.js +6 -0
  48. package/src/llm/judge.js +48 -0
  49. package/src/llm/prompt/content.js +70 -0
  50. package/src/llm/prompt/interpolations.js +58 -0
  51. package/src/llm/prompt/loader.js +67 -0
  52. package/src/llm/prompt/markup/attributes.js +52 -0
  53. package/src/llm/prompt/markup/nodes.js +71 -0
  54. package/src/llm/prompt/markup/tokenizer.js +3 -0
  55. package/src/llm/prompt/markup/tokens.js +26 -0
  56. package/src/llm/prompt/validations.js +129 -0
  57. package/src/llm/utils/cost.js +267 -0
  58. package/src/llm/utils/error_handler.js +53 -0
  59. package/src/llm/utils/file.js +42 -0
  60. package/src/llm/utils/google_vertex_auth.js +31 -0
  61. package/src/llm/utils/image.js +37 -0
  62. package/src/llm/utils/legacy_cost_attribute.js +75 -0
  63. package/src/llm/utils/metering.js +139 -0
  64. package/src/llm/utils/models.js +15 -0
  65. package/src/llm/utils/models_pricing.js +96 -0
  66. package/src/llm/utils/models_pricing_snapshot.json +4711 -0
  67. package/src/llm/utils/skills.js +74 -0
  68. package/src/llm/utils/sources.js +73 -0
  69. package/src/llm/utils/stream.js +75 -0
  70. package/src/llm/utils/tools.js +62 -0
  71. package/src/llm/utils/usage.js +155 -0
  72. package/src/llm/utils/usage_tools.js +23 -0
  73. package/src/llm/utils/web_search.js +155 -0
  74. package/src/llm/utils/wrap.js +279 -0
  75. package/src/llm/validations.js +234 -0
  76. package/src/tracing/trace_attribute.d.ts +0 -17
  77. package/src/tracing/trace_attribute.js +1 -29
  78. package/src/worker/bundler_options.js +1 -9
  79. package/src/worker/configs.js +63 -15
  80. package/src/worker/global_functions.js +11 -6
  81. package/src/worker/index.js +42 -55
  82. package/src/worker/interceptors/activity.js +0 -1
  83. package/src/worker/interceptors/workflow.js +0 -1
  84. package/src/worker/loader/workflows.js +16 -2
  85. package/src/worker/log_hooks.js +8 -0
  86. package/src/worker/shutdown.js +5 -11
  87. package/src/worker/telemetry.js +122 -2
  88. package/src/worker/temporal_logger.js +45 -12
  89. package/src/worker/webpack_loaders/workflow_rewriter/index.mjs +3 -7
  90. package/src/worker/webpack_loaders/workflow_rewriter/rewrite_activity_calls.js +27 -7
  91. package/src/worker/webpack_loaders/workflow_validator/npm_workflow_export_resolve.js +5 -6
  92. package/src/worker/worker_options.js +43 -0
  93. package/src/sdk/README.md +0 -47
  94. package/src/sdk/helpers/component_metadata.d.ts +0 -17
  95. package/src/sdk/helpers/component_metadata.js +0 -6
  96. package/src/sdk/helpers/index.d.ts +0 -12
  97. package/src/sdk/helpers/index.js +0 -3
  98. package/src/sdk/helpers/objects.d.ts +0 -56
  99. package/src/sdk/helpers/objects.js +0 -8
  100. package/src/sdk/helpers/path.d.ts +0 -11
  101. package/src/sdk/helpers/path.js +0 -32
  102. package/src/sdk/runtime/context.d.ts +0 -30
  103. package/src/sdk/runtime/context.js +0 -15
  104. package/src/sdk/runtime/events.d.ts +0 -13
  105. package/src/sdk/runtime/events.js +0 -5
  106. package/src/sdk/runtime/index.d.ts +0 -12
  107. package/src/sdk/runtime/index.js +0 -3
  108. package/src/sdk/runtime/tracing.d.ts +0 -48
  109. package/src/sdk/runtime/tracing.js +0 -11
@@ -1,16 +1,32 @@
1
1
  import * as z from 'zod';
2
2
  import { isStringboolTrue } from '#helpers/string';
3
+ import { createChildLogger } from '#logger';
3
4
  import { workerTunerEnvSchema } from './configs_tuner_schema.js';
4
5
 
6
+ const log = createChildLogger( 'Worker' );
7
+
5
8
  class InvalidEnvVarsErrors extends Error { }
6
9
 
7
10
  const coalesceEmptyString = v => v === '' ? undefined : v;
8
11
 
9
- const durationSchema = z.preprocess(
12
+ const durationUnitsMs = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 };
13
+
14
+ // Plain integer ms, or `<n>(ms|s|m|h|d)` where n may be decimal
15
+ const durationPattern = /^(?:(?<plainMs>\d+)|(?<amount>\d+(?:\.\d+)?)\s?(?<unit>ms|s|m|h|d))$/i;
16
+
17
+ /**
18
+ * Converts a duration matching `durationPattern` into milliseconds.
19
+ * @param {string} value
20
+ * @returns {number}
21
+ */
22
+ const convertDurationToMs = value => {
23
+ const { plainMs, amount, unit } = value.match( durationPattern ).groups;
24
+ return plainMs === undefined ? Math.round( Number( amount ) * durationUnitsMs[unit.toLowerCase()] ) : Number( plainMs );
25
+ };
26
+
27
+ const durationMsSchema = z.preprocess(
10
28
  coalesceEmptyString,
11
- z.string()
12
- .regex( /^\d+$|^\d+(\.\d+)?\s?(ms|s|m|h|d)$/i )
13
- .optional()
29
+ z.string().regex( durationPattern ).transform( convertDurationToMs ).optional()
14
30
  );
15
31
 
16
32
  const envVarSchema = z.object( {
@@ -22,13 +38,31 @@ const envVarSchema = z.object( {
22
38
  // Worker concurrency — tune these via env vars to adjust for your workload.
23
39
  // Each step (API, LLM, etc.) call is one activity. Lower this to reduce memory pressure.
24
40
  TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 40 ) ),
25
- // Workflows are lightweight state machines — this can be high.
26
- TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 200 ) ),
27
- // LRU cache for sticky workflow execution. Lower values free memory faster after surges.
28
- TEMPORAL_MAX_CACHED_WORKFLOWS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 1000 ) ),
41
+ /*
42
+ Workflow tasks that may run at once. These are short state transitions, so this is rarely the
43
+ throughput limit - activity concurrency above is. Left unset so @temporalio/worker applies its
44
+ own default of 40; the startup 'Worker sizing' log reports it as workflowTaskSlots.
45
+ https://typescript.temporal.io/api/interfaces/worker.WorkerOptions#maxconcurrentworkflowtaskexecutions
46
+ */
47
+ TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_EXECUTIONS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().optional() ),
48
+ /*
49
+ LRU cache for sticky workflow execution, holding each workflow's state until it completes or is
50
+ evicted. Left unset so @temporalio/worker sizes it from the isolate's heap limit, which a flat
51
+ value here cannot track. That formula assumes roughly 600 cached workflows per GB, so set this
52
+ where payloads are heavier - the startup 'Worker sizing' log reports what it resolved to.
53
+ https://typescript.temporal.io/api/interfaces/worker.WorkerOptions#maxcachedworkflows
54
+ */
55
+ TEMPORAL_MAX_CACHED_WORKFLOWS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().optional() ),
29
56
  // How aggressively the worker pulls tasks from Temporal.
30
57
  TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_POLLS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 5 ) ),
31
58
  TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_POLLS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 5 ) ),
59
+ /*
60
+ Threads running workflow sandboxes. Each is a V8 isolate and NODE_OPTIONS heap caps apply per
61
+ isolate, so this multiplies the heap the process can commit - the startup 'Worker sizing'
62
+ log reports the total. Left unset so @temporalio/worker picks: 1 with reuseV8Context, 2 without.
63
+ https://typescript.temporal.io/api/interfaces/worker.WorkerOptions#workflowthreadpoolsize
64
+ */
65
+ TEMPORAL_WORKFLOW_THREAD_POOL_SIZE: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().optional() ),
32
66
  // JSON-encoded Temporal Worker tuner options.
33
67
  TEMPORAL_WORKER_TUNER: workerTunerEnvSchema,
34
68
  // Activity configs
@@ -36,13 +70,18 @@ const envVarSchema = z.object( {
36
70
  OUTPUT_ACTIVITY_HEARTBEAT_INTERVAL_MS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 2 * 60 * 1000 ) ), // 2min
37
71
  // Whether to send activity heartbeats (enabled by default)
38
72
  OUTPUT_ACTIVITY_HEARTBEAT_ENABLED: z.transform( v => v === undefined ? true : isStringboolTrue( v ) ),
39
- // Set temporal worker shutdown force time. Defaults budget a shutdown against the 30s most
40
- // platforms allow before SIGKILL: force time + OUTPUT_HOOK_FLUSH_TIMEOUT_MS + 5s of margin.
41
- TEMPORAL_SHUTDOWN_FORCE_TIME: durationSchema.default( '20s' ),
73
+ // Set temporal worker shutdown force time. Worst case shutdown is force time + OUTPUT_HOOK_FLUSH_TIMEOUT_MS,
74
+ // which must fit the window the platform allows before SIGKILL (30s by default on Render and Kubernetes).
75
+ TEMPORAL_SHUTDOWN_FORCE_TIME: durationMsSchema.default( 20_000 ), // 20s
42
76
  // Set temporal worker shutdown grace time, when in-flight activities are asked to cancel
43
- TEMPORAL_SHUTDOWN_GRACE_TIME: durationSchema.default( '15s' ),
77
+ TEMPORAL_SHUTDOWN_GRACE_TIME: durationMsSchema.default( 15_000 ), // 15s
44
78
  // How long the worker awaits pending hook callbacks once the drain is over, before exiting anyway
45
- OUTPUT_HOOK_FLUSH_TIMEOUT_MS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 5 * 1000 ) ), // 5s
79
+ OUTPUT_HOOK_FLUSH_TIMEOUT_MS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 5_000 ) ), // 5s
80
+ // Verbosity of the Temporal SDK and Core logs. Takes Temporal levels, not Winston ones. Case-insensitive.
81
+ OUTPUT_TEMPORAL_LOG_LEVEL: z.preprocess(
82
+ v => coalesceEmptyString( v )?.toUpperCase(),
83
+ z.enum( [ 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR' ] ).default( 'INFO' )
84
+ ),
46
85
  // HTTP CONNECT proxy for Temporal gRPC connections (e.g. "proxy-host:8080").
47
86
  // Must be a bare host:port — no scheme (Temporal's native HTTP CONNECT
48
87
  // option is not a URL).
@@ -57,6 +96,13 @@ if ( error ) {
57
96
  throw new InvalidEnvVarsErrors( z.prettifyError( error ) );
58
97
  }
59
98
 
99
+ if ( envVars.TEMPORAL_SHUTDOWN_FORCE_TIME <= envVars.TEMPORAL_SHUTDOWN_GRACE_TIME ) {
100
+ log.warn( 'Temporal shutdown force time is not bigger than its grace time, so activities have no window to react to cancellation', {
101
+ shutdownForceTimeMs: envVars.TEMPORAL_SHUTDOWN_FORCE_TIME,
102
+ shutdownGraceTimeMs: envVars.TEMPORAL_SHUTDOWN_GRACE_TIME
103
+ } );
104
+ }
105
+
60
106
  export const address = envVars.TEMPORAL_ADDRESS;
61
107
  export const apiKey = envVars.TEMPORAL_API_KEY;
62
108
  export const maxConcurrentActivityTaskExecutions = envVars.TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS;
@@ -64,6 +110,7 @@ export const maxConcurrentWorkflowTaskExecutions = envVars.TEMPORAL_MAX_CONCURRE
64
110
  export const maxCachedWorkflows = envVars.TEMPORAL_MAX_CACHED_WORKFLOWS;
65
111
  export const maxConcurrentActivityTaskPolls = envVars.TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_POLLS;
66
112
  export const maxConcurrentWorkflowTaskPolls = envVars.TEMPORAL_MAX_CONCURRENT_WORKFLOW_TASK_POLLS;
113
+ export const workflowThreadPoolSize = envVars.TEMPORAL_WORKFLOW_THREAD_POOL_SIZE;
67
114
  export const workerTuner = envVars.TEMPORAL_WORKER_TUNER;
68
115
  export const namespace = envVars.TEMPORAL_NAMESPACE;
69
116
  export const taskQueue = envVars.OUTPUT_CATALOG_ID;
@@ -71,7 +118,8 @@ export const catalogId = envVars.OUTPUT_CATALOG_ID;
71
118
  export const workerTelemetryIntervalMs = envVars.OUTPUT_WORKER_TELEMETRY_INTERVAL_MS;
72
119
  export const activityHeartbeatIntervalMs = envVars.OUTPUT_ACTIVITY_HEARTBEAT_INTERVAL_MS;
73
120
  export const activityHeartbeatEnabled = envVars.OUTPUT_ACTIVITY_HEARTBEAT_ENABLED;
74
- export const shutdownForceTime = envVars.TEMPORAL_SHUTDOWN_FORCE_TIME;
75
- export const shutdownGraceTime = envVars.TEMPORAL_SHUTDOWN_GRACE_TIME;
121
+ export const shutdownForceTimeMs = envVars.TEMPORAL_SHUTDOWN_FORCE_TIME;
122
+ export const shutdownGraceTimeMs = envVars.TEMPORAL_SHUTDOWN_GRACE_TIME;
76
123
  export const hookFlushTimeoutMs = envVars.OUTPUT_HOOK_FLUSH_TIMEOUT_MS;
124
+ export const temporalLogLevel = envVars.OUTPUT_TEMPORAL_LOG_LEVEL;
77
125
  export const grpcProxy = envVars.TEMPORAL_GRPC_PROXY;
@@ -1,14 +1,19 @@
1
1
  import { mainEventBus } from '#bus';
2
- import { ACTIVITY_LOGGER_SYMBOL, BusEventType } from '#consts';
3
- import { activityInfo as activityInfoFn } from '@temporalio/activity';
2
+ import { WORKER_LOGGER_SYMBOL, BusEventType } from '#consts';
3
+ import { activityInfo as activityInfoFn, asyncLocalStorage } from '@temporalio/activity';
4
4
  import { assignImmutableProperty } from '#helpers/object';
5
5
 
6
6
  /**
7
7
  * Sets global functions on globalThis
8
8
  */
9
9
  export const bindGlobalFunctions = () => {
10
- /** Defines the activity logger function, accessible in activity context via logger interface */
11
- assignImmutableProperty( globalThis, ACTIVITY_LOGGER_SYMBOL, ( { level, message, metadata } ) =>
12
- mainEventBus.emit( BusEventType.ACTIVITY_LOG, { level, message, metadata, activityInfo: activityInfoFn() } )
13
- );
10
+ /** Defines the worker logger function, accessible from activity and worker (host) context via logger interface */
11
+ assignImmutableProperty( globalThis, WORKER_LOGGER_SYMBOL, ( { level, message, metadata } ) => {
12
+ const context = asyncLocalStorage.getStore();
13
+ if ( context ) { // means we are in an activity
14
+ mainEventBus.emit( BusEventType.ACTIVITY_LOG, { level, message, metadata, activityInfo: activityInfoFn() } );
15
+ } else { // means we are at the worker level, maybe a hook, but not inside the sandbox
16
+ mainEventBus.emit( BusEventType.WORKER_LOG, { level, message, metadata } );
17
+ }
18
+ } );
14
19
  };
@@ -1,5 +1,14 @@
1
1
  import { Worker, NativeConnection } from '@temporalio/worker';
2
- import * as configs from './configs.js';
2
+ import {
3
+ address,
4
+ apiKey,
5
+ namespace,
6
+ taskQueue,
7
+ grpcProxy,
8
+ hookFlushTimeoutMs,
9
+ shutdownForceTimeMs,
10
+ shutdownGraceTimeMs
11
+ } from './configs.js';
3
12
  import { loadActivities } from './loader/activities.js';
4
13
  import { loadWorkflows } from './loader/workflows.js';
5
14
  import { loadHooks } from './loader/hooks.js';
@@ -15,7 +24,7 @@ import { CatalogPublisher } from './catalog_workflow/catalog_publisher.js';
15
24
  import { mainEventBus } from '#bus';
16
25
  import { flushPendingHooks } from '#hooks/pending_hooks';
17
26
  import { BusEventType } from '#consts';
18
- import { setupTelemetry } from './telemetry.js';
27
+ import { setupTelemetry, logIsolateSizing } from './telemetry.js';
19
28
  import { TemporalConnectionMonitor } from './connection_monitor.js';
20
29
  import { bindGlobalFunctions } from './global_functions.js';
21
30
  import { setupClientConfig } from '#temporal/client';
@@ -24,28 +33,12 @@ import { setupTemporalLogger } from './temporal_logger.js';
24
33
  import { WorkerRunner } from './worker_runner.js';
25
34
  import { shutdownServices } from './shutdown.js';
26
35
  import { init as initCredentials } from '#credentials/init';
36
+ import { buildWorkerOptions } from './worker_options.js';
27
37
 
28
38
  import './log_hooks.js';
29
39
 
30
40
  const log = createChildLogger( 'Worker' );
31
41
 
32
- const {
33
- address,
34
- apiKey,
35
- namespace,
36
- taskQueue,
37
- grpcProxy,
38
- maxConcurrentWorkflowTaskExecutions,
39
- maxConcurrentActivityTaskExecutions,
40
- maxCachedWorkflows,
41
- maxConcurrentActivityTaskPolls,
42
- maxConcurrentWorkflowTaskPolls,
43
- shutdownForceTime,
44
- shutdownGraceTime,
45
- hookFlushTimeoutMs,
46
- workerTuner
47
- } = configs;
48
-
49
42
  const services = {
50
43
  connection: null,
51
44
  connectionMonitor: null,
@@ -68,6 +61,9 @@ const execute = async () => {
68
61
  log.info( 'Setting up Temporal Logger...' );
69
62
  run( setupTemporalLogger );
70
63
 
64
+ log.info( 'Binding globals...' );
65
+ run( bindGlobalFunctions );
66
+
71
67
  log.info( 'Loading config...', { callerDir } );
72
68
  await run( () => loadHooks( callerDir ) );
73
69
 
@@ -89,9 +85,6 @@ const execute = async () => {
89
85
  log.info( 'Computing catalog source code hash...' );
90
86
  const catalogHash = await run( () => hashSourceCode( callerDir ) );
91
87
 
92
- log.info( 'Binding globals...' );
93
- run( bindGlobalFunctions );
94
-
95
88
  log.info( 'Connecting Temporal...' );
96
89
  const proxy = grpcProxy ? { type: 'http-connect', targetHost: grpcProxy } : undefined;
97
90
  if ( proxy ) {
@@ -113,34 +106,19 @@ const execute = async () => {
113
106
  await run( () => services.catalogPublisher.run() );
114
107
 
115
108
  log.info( 'Creating Temporal worker...' );
116
- const worker = await run( () => {
117
- if ( workerTuner ) {
118
- log.info( 'Using worker tuner options', { ...workerTuner } );
119
- }
120
-
121
- return Worker.create( {
122
- connection,
123
- namespace,
124
- taskQueue,
125
- workflowsPath,
126
- activities,
127
- sinks,
128
- interceptors: initInterceptors( { activities, workflows } ),
129
- // tuner isn't compatible with concurrent task executions configs
130
- ...( workerTuner ? {
131
- tuner: workerTuner
132
- } : {
133
- maxConcurrentWorkflowTaskExecutions,
134
- maxConcurrentActivityTaskExecutions
135
- } ),
136
- maxCachedWorkflows,
137
- maxConcurrentActivityTaskPolls,
138
- maxConcurrentWorkflowTaskPolls,
139
- bundlerOptions: { webpackConfigHook },
140
- ...( shutdownForceTime !== undefined && { shutdownForceTime } ),
141
- ...( shutdownGraceTime !== undefined && { shutdownGraceTime } )
142
- } );
143
- } );
109
+ const worker = await run( () => Worker.create( {
110
+ connection,
111
+ namespace,
112
+ taskQueue,
113
+ workflowsPath,
114
+ activities,
115
+ sinks,
116
+ interceptors: initInterceptors( { activities, workflows } ),
117
+ bundlerOptions: { webpackConfigHook },
118
+ ...buildWorkerOptions()
119
+ } ) );
120
+
121
+ run( () => logIsolateSizing( { worker } ) );
144
122
 
145
123
  log.info( 'Setting up telemetry...' );
146
124
  run( () => setupTelemetry( { worker } ) );
@@ -165,21 +143,30 @@ const execute = async () => {
165
143
  execute()
166
144
  .catch( async error => abortController.abort( error ) )
167
145
  .finally( async () => {
168
- const shutdownFailures = await shutdownServices( services );
146
+ log.info( 'Shutting down', {
147
+ shutdownForceTimeMs,
148
+ shutdownGraceTimeMs,
149
+ hookFlushTimeoutMs
150
+ } );
151
+
152
+ const shutdownStartedAt = Date.now();
153
+ await shutdownServices( services );
169
154
 
170
155
  const hasError = signal.aborted && !( signal.reason instanceof KillSignError );
171
156
  if ( hasError ) {
172
157
  log.error( 'Worker error', { error: serializeError( signal.reason ) } );
173
- mainEventBus.emit( BusEventType.RUNTIME_ERROR, { error: signal.reason } );
158
+ mainEventBus.emit( BusEventType.WORKER_ERROR, { error: signal.reason } );
174
159
  }
175
160
 
176
161
  log.info( 'Flushing hook callbacks...' );
177
162
  await flushPendingHooks( hookFlushTimeoutMs );
178
163
 
179
- const workerFailedToStop = shutdownFailures.some( v => v.service === 'worker' );
180
- const exitCode = workerFailedToStop || hasError ? 1 : 0;
181
164
  setTimeout( () => {
182
- log.info( 'Bye', { exitCode } );
165
+ const exitCode = hasError ? 1 : 0;
166
+ log.info( 'Bye', {
167
+ exitCode,
168
+ shutdownDurationMs: Date.now() - shutdownStartedAt
169
+ } );
183
170
  process.exit( exitCode );
184
171
  } );
185
172
  } );
@@ -103,7 +103,6 @@ export class ActivityExecutionInterceptor {
103
103
  const nonRetryable = error instanceof FatalError || inheritsFromAnyNamedType( error, activityInfo.retryPolicy?.nonRetryableErrorTypes ?? [] );
104
104
  throw ApplicationFailure.fromError( unwrappedError, {
105
105
  nonRetryable,
106
- cause: unwrappedError,
107
106
  details: [ { error: serializeError( unwrappedError, { dropKeys: [ 'stack' ] } ) } ]
108
107
  } );
109
108
  } finally {
@@ -89,7 +89,6 @@ class WorkflowExecutionInterceptor {
89
89
  const unwrappedError = error instanceof TransparentFatalError ? error.cause : error;
90
90
  sinks.workflow.error( serializeError( unwrappedError ) );
91
91
  throw ApplicationFailure.fromError( unwrappedError, {
92
- cause: unwrappedError,
93
92
  nonRetryable: true,
94
93
  details: [ { error: serializeError( unwrappedError, { dropKeys: [ 'stack' ] } ) } ]
95
94
  } );
@@ -19,8 +19,22 @@ const createWorkflowsEntrypoint = workflows => {
19
19
  aliases.map( alias => ( { name: alias, path } ) )
20
20
  );
21
21
 
22
- const content = [ ...workflows, ...aliasExports, catalog ]
23
- .map( ( { name, path } ) => `export { default as ${name} } from '${path}';` ).join( EOL );
22
+ // A static re-export makes every cached workflow evaluate the whole catalog: Temporal's reusable VM
23
+ // keeps each module loaded during an activation in that workflow's own cache. A lazy export loads
24
+ // only the invoked workflow; eager mode keeps it in the same bundle. Workflow type resolution is by
25
+ // export name, and the metadata the framework reads is read in Node, never from the bundle.
26
+ const lazyExports = [ ...workflows, ...aliasExports ].map( ( { name, path } ) => `\
27
+ async function _${name}( ...args ) {
28
+ const { default: workflow } = await import( /* webpackMode: "eager" */ '${path}' );
29
+ if ( typeof workflow !== 'function' ) {
30
+ throw new TypeError( 'Workflow "${name}" must be exported as default.' );
31
+ }
32
+ return workflow( ...args );
33
+ }
34
+ export { _${name} as ${name} };` );
35
+
36
+ // The catalog stays static: it is the framework's own workflow, small, and always loaded.
37
+ const content = [ ...lazyExports, `export { default as ${catalog.name} } from '${catalog.path}';` ].join( EOL );
24
38
 
25
39
  return writeFileInTempDir( content, WORKFLOWS_INDEX_FILENAME );
26
40
  };
@@ -5,6 +5,7 @@ import { serializeError } from '#helpers/error_serializer';
5
5
 
6
6
  const activityLog = createChildLogger( 'Activity' );
7
7
  const workflowLog = createChildLogger( 'Workflow' );
8
+ const workerLog = createChildLogger( 'Worker' );
8
9
 
9
10
  /**
10
11
  * Intercepts internal bus events for activity and workflow lifecycle and log them
@@ -56,6 +57,13 @@ mainEventBus.on( BusEventType.ACTIVITY_LOG, ( { level, message, metadata, activi
56
57
  } )
57
58
  );
58
59
 
60
+ /*
61
+ ╔═══════════════╗
62
+ ║ Worker events ║
63
+ ╚═══════════════╝
64
+ */
65
+ mainEventBus.on( BusEventType.WORKER_LOG, ( { level, message, metadata } ) => workerLog[level]( message, metadata ) );
66
+
59
67
  /*
60
68
  ╔═════════════════╗
61
69
  ║ Workflow events ║
@@ -5,49 +5,43 @@ const log = createChildLogger( 'Worker Shutdown' );
5
5
 
6
6
  /**
7
7
  * Gracefully shuts every running service down, in order.
8
- * A service that fails to stop never interrupts the sequence, it is reported back instead.
9
- * @returns {Promise<Array<{ service: string, error: Error }>>} one entry per service that failed to stop
8
+ * A service that fails to stop never interrupts the sequence
10
9
  */
11
10
  export const shutdownServices = async ( { workerRunner, connectionMonitor, catalogPublisher, connection } ) => {
12
11
  const shutdownJobs = [
13
12
  {
14
- service: 'worker',
15
13
  label: 'Stopping Worker',
16
14
  isActive: () => workerRunner?.running,
17
15
  stop: () => workerRunner.stop()
18
16
  },
19
17
  {
20
- service: 'connection_monitor',
21
18
  label: 'Stopping Connection Monitor',
22
19
  isActive: () => connectionMonitor?.running,
23
20
  stop: () => connectionMonitor.stop()
24
21
  },
25
22
  {
26
- service: 'catalog_publisher',
27
23
  label: 'Interrupting Catalog Publisher',
28
24
  isActive: () => catalogPublisher?.running,
29
25
  stop: () => catalogPublisher.interrupt()
30
26
  },
31
27
  {
32
- service: 'connection',
33
28
  label: 'Closing Connection',
34
29
  isActive: () => connection,
35
30
  stop: () => connection.close()
36
31
  }
37
32
  ];
38
33
 
39
- const failures = [];
40
- for ( const { service, label, isActive, stop } of shutdownJobs ) {
34
+ for ( const { label, isActive, stop } of shutdownJobs ) {
41
35
  if ( isActive() ) {
36
+ const shutdownStartedAt = Date.now();
42
37
  log.info( `${label}...` );
43
38
  // a try covers a service that throws instead of rejecting, which a catch on the promise would miss
44
39
  try {
45
40
  await stop();
41
+ log.info( `${label} complete`, { shutdownDurationMs: Date.now() - shutdownStartedAt } );
46
42
  } catch ( error ) {
47
- failures.push( { service, error } );
48
- log.warn( `${label} error`, { error: serializeError( error ) } );
43
+ log.warn( `${label} failed`, { error: serializeError( error ), shutdownDurationMs: Date.now() - shutdownStartedAt } );
49
44
  }
50
45
  }
51
46
  }
52
- return failures;
53
47
  };
@@ -1,21 +1,141 @@
1
+ import { totalmem } from 'node:os';
2
+ import { getHeapStatistics } from 'node:v8';
1
3
  import { serializeError } from '#helpers/error_serializer';
2
4
  import { createChildLogger } from '#logger';
3
5
  import { workerTelemetryIntervalMs } from './configs.js';
4
6
 
5
7
  const log = createChildLogger( 'Telemetry' );
6
8
 
9
+ /**
10
+ * Resolve the memory limit to compare the worker against: the container's limit, or the
11
+ * machine's total memory when there is none.
12
+ *
13
+ * `process.constrainedMemory()` returns a sentinel near 2^64 rather than 0 when the process is
14
+ * unconstrained, so values at or above the machine's memory are treated as no limit.
15
+ *
16
+ * @returns {number} Bytes.
17
+ */
18
+ const resolveMemoryLimit = () => {
19
+ const constrainedMemory = process.constrainedMemory();
20
+ const machineMemory = totalmem();
21
+ return constrainedMemory > 0 && constrainedMemory < machineMemory ? constrainedMemory : machineMemory;
22
+ };
23
+
24
+ /**
25
+ * Log the worker's isolate and cache sizing. Warn when the projected
26
+ * heap exceeds the memory limit, or when workflow task slots exceed
27
+ * the cache.
28
+ *
29
+ * The worker runs one isolate on the main thread and one per workflow
30
+ * thread. A NODE_OPTIONS heap cap applies to each isolate, not to the
31
+ * process, so on a 4 GB container `--max-old-space-size-percentage=85`
32
+ * allows each isolate ~3.4 GB and two isolates can commit well over
33
+ * the container's memory.
34
+ *
35
+ * The cache and the task slots are sized independently:
36
+ * `@temporalio/worker` derives `maxCachedWorkflows` from the heap limit
37
+ * but fixes `workflowTaskSlots` at 40. On a small container the slots
38
+ * can exceed the cache, which causes tasks to evict each other's
39
+ * workflows and forces history replays.
40
+ *
41
+ * Logged fields are read from `worker.options`, so each is the resolved
42
+ * value rather than the requested one:
43
+ *
44
+ * - `workflowThreadPoolSize`: threads running workflow sandboxes.
45
+ * Defaults to 1 with `reuseV8Context`, 2 without. Ignored under
46
+ * `debugMode`.
47
+ * - `reuseV8Context`: whether workflows share one VM context per thread
48
+ * or each get a new one. Enabled by default. Upstream estimates
49
+ * roughly 600 cached workflows per GB with it and 250 without.
50
+ * - `isolateCount`: `1 + workflowThreadPoolSize`, the multiplier on the
51
+ * per-isolate heap cap. 1 under `debugMode`, which runs workflows in
52
+ * the main isolate and spawns no workflow threads.
53
+ * - `heapSizeLimit`: the main isolate's V8 heap ceiling, as resolved
54
+ * from NODE_OPTIONS.
55
+ * - `projectedCommittedHeap`: `isolateCount * heapSizeLimit`, the heap
56
+ * the process can commit if every isolate fills. Only the main
57
+ * thread's limit is readable, so this assumes the workflow threads
58
+ * have the same one.
59
+ * - `memoryLimit`: the limit the projection is compared against. The
60
+ * container's limit, or the machine's total memory when unconstrained.
61
+ * - `maxCachedWorkflows`: sticky cache size. Derived from
62
+ * `heapSizeLimit` when TEMPORAL_MAX_CACHED_WORKFLOWS is unset.
63
+ * - `workflowTaskSlots`: workflow tasks that may run at once, from the
64
+ * tuner. Undefined with a resource-based tuner, which sizes slots at
65
+ * runtime.
66
+ *
67
+ * @param {object} params Parameters.
68
+ * @param {import('@temporalio/worker').Worker} params.worker The created Temporal worker.
69
+ */
70
+ export const logIsolateSizing = ( { worker } ) => {
71
+ const { workflowThreadPoolSize, reuseV8Context, maxCachedWorkflows, tuner, debugMode } = worker.options;
72
+ // debugMode runs workflows in the main isolate and spawns no workflow threads.
73
+ const isolateCount = debugMode ? 1 : 1 + workflowThreadPoolSize;
74
+ const heapSizeLimit = getHeapStatistics().heap_size_limit;
75
+ const memoryLimit = resolveMemoryLimit();
76
+ const workflowTaskSlots = tuner?.workflowTaskSlotSupplier?.numSlots;
77
+ const projectedCommittedHeap = isolateCount * heapSizeLimit;
78
+
79
+ log.info( 'Worker sizing', {
80
+ workflowThreadPoolSize,
81
+ reuseV8Context,
82
+ isolateCount,
83
+ heapSizeLimit,
84
+ projectedCommittedHeap,
85
+ memoryLimit,
86
+ maxCachedWorkflows,
87
+ workflowTaskSlots
88
+ } );
89
+
90
+ if ( projectedCommittedHeap > memoryLimit ) {
91
+ log.warn( 'Worker isolates may commit more heap than the host allows', { isolateCount, heapSizeLimit, projectedCommittedHeap, memoryLimit } );
92
+ }
93
+
94
+ if ( workflowTaskSlots > maxCachedWorkflows ) {
95
+ log.warn( 'Worker runs more workflow tasks than it can cache, forcing replays', { workflowTaskSlots, maxCachedWorkflows } );
96
+ }
97
+ };
98
+
99
+ /**
100
+ * Start an interval that logs worker status and memory every
101
+ * OUTPUT_WORKER_TELEMETRY_INTERVAL_MS. Disabled when it is 0.
102
+ *
103
+ * Each record holds the Temporal worker's `status` and a `memory`
104
+ * block. The memory fields mix process-wide and main-isolate scopes:
105
+ *
106
+ * - `availableMemory`: memory the process can still allocate, within
107
+ * the container limit.
108
+ * - `memoryLimit`: the container's limit, or the machine's total memory
109
+ * when unconstrained.
110
+ * - `memoryUsage`: raw `process.memoryUsage()`. `rss` is process-wide;
111
+ * `heapTotal` and `heapUsed` cover only the main isolate.
112
+ * - `nonMainHeap`: `memoryUsage.rss - memoryUsage.heapUsed`, the
113
+ * resident memory outside the main isolate's live objects: workflow
114
+ * thread heaps, Rust core allocations, buffers, and heap pages V8 has
115
+ * committed but not filled. An upper bound on the workflow thread
116
+ * heap, not a measurement of it. Cached workflow memory is counted
117
+ * here, so it grows with the cache while `heapUsed` stays flat.
118
+ * - `heapSizeLimit`: the main isolate's V8 heap ceiling. Constant, but
119
+ * included in each sample so records are self-contained.
120
+ *
121
+ * @param {object} params Parameters.
122
+ * @param {import('@temporalio/worker').Worker} params.worker The created Temporal worker.
123
+ */
7
124
  export const setupTelemetry = ( { worker } ) => {
8
125
  if ( workerTelemetryIntervalMs <= 0 ) {
9
126
  return;
10
127
  }
11
128
  setInterval( () => {
12
129
  try {
130
+ const memoryUsage = process.memoryUsage();
13
131
  log.info( 'Worker', {
14
132
  status: worker.getStatus(),
15
133
  memory: {
16
134
  availableMemory: process.availableMemory(),
17
- constrainedMemory: process.constrainedMemory(),
18
- memoryUsage: process.memoryUsage()
135
+ memoryLimit: resolveMemoryLimit(),
136
+ memoryUsage,
137
+ nonMainHeap: memoryUsage.rss - memoryUsage.heapUsed,
138
+ heapSizeLimit: getHeapStatistics().heap_size_limit
19
139
  }
20
140
  } );
21
141
  } catch ( error ) {
@@ -1,32 +1,65 @@
1
- import { DefaultLogger, makeTelemetryFilterString, Runtime } from '@temporalio/worker';
1
+ import { DefaultLogger, GracefulShutdownPeriodExpiredError, Runtime } from '@temporalio/worker';
2
2
  import { createChildLogger } from '#logger';
3
+ import { serializeError } from '#helpers/error_serializer';
4
+ import { temporalLogLevel } from './configs.js';
3
5
 
4
6
  const log = createChildLogger( 'Temporal' );
5
7
  const OMITTED_MESSAGES = [ 'Activity failed', 'Workflow failed' ];
6
8
 
7
- const temporalLevelToInternalLevelMap = {
8
- TRACE: 'debug',
9
- DEBUG: 'debug',
10
- INFO: 'info',
11
- WARN: 'warn',
12
- ERROR: 'error'
9
+ /** Whether the entry reports the shutdown force time expiring, an expected outcome of a deploy that is logged as a warning, not an error */
10
+ const isForcedShutdownEntry = ( { meta } ) => meta?.error instanceof GracefulShutdownPeriodExpiredError;
11
+
12
+ /** Serializes Error values in the meta, otherwise they would be logged as an empty object */
13
+ const serializeMetaErrors = meta => meta && Object.fromEntries(
14
+ Object.entries( meta ).map( ( [ key, value ] ) => [ key, value instanceof Error ? serializeError( value ) : value ] )
15
+ );
16
+
17
+ const TemporalLogLevel = {
18
+ TRACE: 'TRACE',
19
+ DEBUG: 'DEBUG',
20
+ INFO: 'INFO',
21
+ WARN: 'WARN',
22
+ ERROR: 'ERROR'
13
23
  };
14
24
 
15
- export const setupTemporalLogger = () => {
16
- const level = process.env.OUTPUT_TEMPORAL_LOG_LEVEL?.toUpperCase() ?? 'INFO';
25
+ const temporalToInternalLogLevel = {
26
+ [TemporalLogLevel.TRACE]: 'debug',
27
+ [TemporalLogLevel.DEBUG]: 'debug',
28
+ [TemporalLogLevel.INFO]: 'info',
29
+ [TemporalLogLevel.WARN]: 'warn',
30
+ [TemporalLogLevel.ERROR]: 'error'
31
+ };
32
+
33
+ const temporalLogLevelsOrder = [
34
+ TemporalLogLevel.TRACE,
35
+ TemporalLogLevel.DEBUG,
36
+ TemporalLogLevel.INFO,
37
+ TemporalLogLevel.WARN,
38
+ TemporalLogLevel.ERROR
39
+ ];
17
40
 
41
+ const isLogLevelEnabled = ( configuredLevel, entryLevel ) =>
42
+ temporalLogLevelsOrder.indexOf( entryLevel ) >= temporalLogLevelsOrder.indexOf( configuredLevel );
43
+
44
+ export const setupTemporalLogger = () => {
18
45
  Runtime.install( {
19
- logger: new DefaultLogger( level, entry => {
46
+ logger: new DefaultLogger( temporalLogLevel, entry => {
20
47
  // Already reported by Output activity logs and traces.
21
48
  if ( OMITTED_MESSAGES.includes( entry.message ) ) {
22
49
  return;
23
50
  }
24
- log.log( temporalLevelToInternalLevelMap[entry.level], entry.message, entry.meta );
51
+ const forcedShutdown = isForcedShutdownEntry( entry );
52
+ if ( forcedShutdown && !isLogLevelEnabled( temporalLogLevel, TemporalLogLevel.WARN ) ) {
53
+ return;
54
+ }
55
+
56
+ const level = temporalToInternalLogLevel[forcedShutdown ? TemporalLogLevel.WARN : entry.level];
57
+ log.log( level, entry.message, serializeMetaErrors( entry.meta ) );
25
58
  } ),
26
59
  telemetryOptions: {
27
60
  logging: {
28
61
  forward: {},
29
- filter: makeTelemetryFilterString( { core: level, other: level } )
62
+ filter: { core: temporalLogLevel, other: temporalLogLevel }
30
63
  }
31
64
  }
32
65
  } );