@outputai/core 0.15.1-next.fd6bb62.0 → 0.16.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/dist/credentials/index.d.ts +1 -1
- package/dist/credentials/types.d.ts +4 -4
- package/dist/evals/aggregate.d.ts +2 -0
- package/dist/evals/aggregate.js +11 -0
- package/dist/evals/eval_workflow.d.ts +20 -0
- package/dist/evals/eval_workflow.js +98 -0
- package/dist/evals/index.d.ts +7 -0
- package/dist/evals/index.js +4 -0
- package/dist/evals/interpret.d.ts +3 -0
- package/dist/evals/interpret.js +40 -0
- package/dist/evals/schemas.d.ts +96 -0
- package/dist/evals/schemas.js +60 -0
- package/dist/evals/verdict.d.ts +27 -0
- package/dist/evals/verdict.js +109 -0
- package/dist/evals/verify.d.ts +42 -0
- package/dist/evals/verify.js +19 -0
- package/package.json +57 -15
- package/src/consts.d.ts +2 -0
- package/src/helpers/path.js +34 -0
- package/src/http/fetch/index.d.ts +3 -5
- package/src/http/index.d.ts +1 -0
- package/src/interface/index.d.ts +1 -0
- package/src/llm/agent.js +147 -0
- package/src/llm/ai_provider.js +131 -0
- package/src/llm/ai_sdk_options.js +126 -0
- package/src/llm/consts.js +6 -0
- package/src/llm/deprecated_provider_aliases.js +8 -0
- package/src/llm/generate.js +98 -0
- package/src/llm/index.d.ts +697 -0
- package/src/llm/index.js +6 -0
- package/src/llm/judge.js +48 -0
- package/src/llm/prompt/content.js +70 -0
- package/src/llm/prompt/interpolations.js +58 -0
- package/src/llm/prompt/loader.js +67 -0
- package/src/llm/prompt/markup/attributes.js +52 -0
- package/src/llm/prompt/markup/nodes.js +71 -0
- package/src/llm/prompt/markup/tokenizer.js +3 -0
- package/src/llm/prompt/markup/tokens.js +26 -0
- package/src/llm/prompt/validations.js +129 -0
- package/src/llm/utils/cost.js +267 -0
- package/src/llm/utils/error_handler.js +53 -0
- package/src/llm/utils/file.js +42 -0
- package/src/llm/utils/google_vertex_auth.js +31 -0
- package/src/llm/utils/image.js +37 -0
- package/src/llm/utils/legacy_cost_attribute.js +75 -0
- package/src/llm/utils/metering.js +139 -0
- package/src/llm/utils/models.js +15 -0
- package/src/llm/utils/models_pricing.js +96 -0
- package/src/llm/utils/models_pricing_snapshot.json +4711 -0
- package/src/llm/utils/skills.js +74 -0
- package/src/llm/utils/sources.js +73 -0
- package/src/llm/utils/stream.js +75 -0
- package/src/llm/utils/tools.js +62 -0
- package/src/llm/utils/usage.js +155 -0
- package/src/llm/utils/usage_tools.js +23 -0
- package/src/llm/utils/web_search.js +155 -0
- package/src/llm/utils/wrap.js +279 -0
- package/src/llm/validations.js +234 -0
- package/src/worker/bundler_options.js +1 -9
- package/src/worker/interceptors/activity.js +0 -1
- package/src/worker/interceptors/workflow.js +0 -1
- package/src/worker/loader/workflows.js +16 -2
- package/src/worker/webpack_loaders/workflow_rewriter/index.mjs +3 -7
- package/src/worker/webpack_loaders/workflow_rewriter/rewrite_activity_calls.js +27 -7
- package/src/worker/webpack_loaders/workflow_validator/npm_workflow_export_resolve.js +5 -6
- package/src/sdk/README.md +0 -47
- package/src/sdk/helpers/component_metadata.d.ts +0 -17
- package/src/sdk/helpers/component_metadata.js +0 -6
- package/src/sdk/helpers/index.d.ts +0 -12
- package/src/sdk/helpers/index.js +0 -3
- package/src/sdk/helpers/objects.d.ts +0 -56
- package/src/sdk/helpers/objects.js +0 -8
- package/src/sdk/helpers/path.d.ts +0 -11
- package/src/sdk/helpers/path.js +0 -32
- package/src/sdk/runtime/context.d.ts +0 -30
- package/src/sdk/runtime/context.js +0 -15
- package/src/sdk/runtime/events.d.ts +0 -13
- package/src/sdk/runtime/events.js +0 -5
- package/src/sdk/runtime/index.d.ts +0 -12
- package/src/sdk/runtime/index.js +0 -3
- package/src/sdk/runtime/tracing.d.ts +0 -48
- package/src/sdk/runtime/tracing.js +0 -11
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { extractSources } from './sources.js';
|
|
2
|
+
import { serializeImagesFromResponse } from './image.js';
|
|
3
|
+
import { addEventActionWithContext, EventAction } from '#tracing';
|
|
4
|
+
import { mapAiError } from './error_handler.js';
|
|
5
|
+
import { isPromise } from 'node:util/types';
|
|
6
|
+
import { FatalError } from '#errors';
|
|
7
|
+
import { Logger } from '#runtime_logger';
|
|
8
|
+
import { Metering } from './metering.js';
|
|
9
|
+
import { randomBytes } from 'node:crypto';
|
|
10
|
+
|
|
11
|
+
/** Creates a proxy of the AI SDK response and attach virtual getters to it based on an object map */
|
|
12
|
+
const createResponseProxy = ( { response, properties } ) => new Proxy( response, {
|
|
13
|
+
get( target, prop, receiver ) {
|
|
14
|
+
return Object.hasOwn( properties, prop ) ? properties[prop] : Reflect.get( target, prop, receiver );
|
|
15
|
+
}
|
|
16
|
+
} );
|
|
17
|
+
|
|
18
|
+
/** Generate a trace id, starts the tracing and return the id */
|
|
19
|
+
const startTrace = ( { name, prompt } ) => {
|
|
20
|
+
const traceId = `${name}-${Date.now()}-${randomBytes( 4 ).toString( 'hex' )}`;
|
|
21
|
+
addEventActionWithContext( EventAction.START, { kind: 'llm', id: traceId, name, details: { prompt } } );
|
|
22
|
+
return traceId;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Handle AI SDK errors: map them, add an error trace entry and return the new error */
|
|
26
|
+
const handleAiSdkError = ( { traceId, error: originalError } ) => {
|
|
27
|
+
const error = mapAiError( originalError );
|
|
28
|
+
addEventActionWithContext( EventAction.ERROR, { id: traceId, details: error } );
|
|
29
|
+
return error;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Handle a failure of our own response handling: wrap it, add an error trace entry and return it.
|
|
34
|
+
* Fatal on purpose - such a failure is deterministic, so a retry pays for the model call again and
|
|
35
|
+
* fails the same way.
|
|
36
|
+
*/
|
|
37
|
+
const handleResponseError = ( { traceId, error: cause } ) => {
|
|
38
|
+
const error = new FatalError( 'AI SDK response handling failed.', { cause } );
|
|
39
|
+
addEventActionWithContext( EventAction.ERROR, { id: traceId, details: error } );
|
|
40
|
+
return error;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** Invokes an async function, wrapped in a try/catch, return { result, error } */
|
|
44
|
+
const inlineTryAsync = async fn => {
|
|
45
|
+
try {
|
|
46
|
+
return { result: await fn(), error: null };
|
|
47
|
+
} catch ( error ) {
|
|
48
|
+
return { result: null, error };
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Runs a completing AI SDK text call (`generateText`, `generateTextWithStreaming`,
|
|
54
|
+
* `Agent.generate`, `Agent.generateWithStreaming`): starts the LLM trace, runs `fn`, ends the trace
|
|
55
|
+
* and returns the response proxied with `result` (`text`), `cost` and merged `sources`.
|
|
56
|
+
*
|
|
57
|
+
* `fn` receives `onStepEndHook` to wire into the SDK `onStepEnd`, so the usage of every completed
|
|
58
|
+
* step is collected as the call progresses and still lands when `fn` throws after the model ran.
|
|
59
|
+
* The response `fn` returns is billed directly, and its aggregate usage takes precedence over the
|
|
60
|
+
* collected steps. Trace output keeps raw `response.usage`; normalized usage and cost are trace
|
|
61
|
+
* attributes.
|
|
62
|
+
*
|
|
63
|
+
* Reading the billed response is guarded: a throw from `fn` is mapped as an SDK error, while a
|
|
64
|
+
* failure of our own handling becomes a `FatalError` recorded on the trace. The proxy is built
|
|
65
|
+
* before the trace ends, so a call that fails there never leaves an `end` entry next to an `error`.
|
|
66
|
+
*
|
|
67
|
+
* @param {object} args
|
|
68
|
+
* @param {string} args.name - Trace event name
|
|
69
|
+
* @param {object} args.prompt - Loaded prompt (`config.provider` / `config.model` used for cost)
|
|
70
|
+
* @param {Record<string, string>} [args.toolIdsByName] - Provider tool ids keyed by configured name
|
|
71
|
+
* @param {( wiring: { onStepEndHook: Function } ) => Promise<object>} args.fn - AI SDK call; wire
|
|
72
|
+
* `onStepEndHook` into the call `onStepEnd` and return the SDK response
|
|
73
|
+
* @returns {Promise<object>} Proxied SDK response
|
|
74
|
+
*/
|
|
75
|
+
export const wrapTextGeneration = async ( { name, prompt, toolIdsByName, fn } ) => {
|
|
76
|
+
const traceId = startTrace( { name, prompt } );
|
|
77
|
+
|
|
78
|
+
const metering = new Metering( { traceId, prompt, toolIdsByName } );
|
|
79
|
+
|
|
80
|
+
const onStepEndHook = metering.recordStep;
|
|
81
|
+
|
|
82
|
+
const { result: response, error } = await inlineTryAsync( () => fn( { onStepEndHook } ) );
|
|
83
|
+
|
|
84
|
+
await metering.bill( response );
|
|
85
|
+
|
|
86
|
+
if ( error ) {
|
|
87
|
+
throw handleAiSdkError( { traceId, error } );
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
const { text: result, finalStep, usage } = response;
|
|
92
|
+
const providerMetadata = finalStep?.providerMetadata;
|
|
93
|
+
const sources = extractSources( response );
|
|
94
|
+
|
|
95
|
+
// Create proxy first, as this could theoretically fail
|
|
96
|
+
const responseProxy = createResponseProxy( { response, properties: { cost: metering.attributes.cost, sources, result } } );
|
|
97
|
+
addEventActionWithContext( EventAction.END, { id: traceId, details: { result, usage, providerMetadata, sources } } );
|
|
98
|
+
|
|
99
|
+
return responseProxy;
|
|
100
|
+
} catch ( error ) {
|
|
101
|
+
throw handleResponseError( { traceId, error } );
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Runs `generateImage`: starts the LLM trace, meters the returned usage, ends the trace and returns
|
|
107
|
+
* the response proxied with `result` (the first `image`) and `cost`.
|
|
108
|
+
*
|
|
109
|
+
* Image calls expose no step lifecycle, so usage is read from the response. With no
|
|
110
|
+
* step loop and no output parsing, a throw from `fn` happens before any usage exists, so it is
|
|
111
|
+
* mapped and recorded without metering. Reading the billed response is guarded the same way
|
|
112
|
+
* `wrapTextGeneration` guards it: a failure there is a `FatalError` recorded after billing.
|
|
113
|
+
*
|
|
114
|
+
* @param {object} args
|
|
115
|
+
* @param {string} args.name - Trace event name
|
|
116
|
+
* @param {object} args.prompt - Loaded prompt (`config.provider` / `config.model` used for cost)
|
|
117
|
+
* @param {() => Promise<object>} args.fn - AI SDK call; must return the SDK response
|
|
118
|
+
* @returns {Promise<object>} Proxied SDK response
|
|
119
|
+
*/
|
|
120
|
+
export const wrapImageGeneration = async ( { name, prompt, fn } ) => {
|
|
121
|
+
const traceId = startTrace( { name, prompt } );
|
|
122
|
+
|
|
123
|
+
const metering = new Metering( { traceId, prompt } );
|
|
124
|
+
|
|
125
|
+
const { result: response, error } = await inlineTryAsync( fn );
|
|
126
|
+
|
|
127
|
+
if ( error ) {
|
|
128
|
+
throw handleAiSdkError( { traceId, error } );
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
await metering.bill( response );
|
|
132
|
+
|
|
133
|
+
try {
|
|
134
|
+
const { usage, image: result, providerMetadata } = response;
|
|
135
|
+
const serializeImages = serializeImagesFromResponse( response );
|
|
136
|
+
|
|
137
|
+
// Create proxy first, as this could theoretically fail
|
|
138
|
+
const responseProxy = createResponseProxy( { response, properties: { cost: metering.attributes.cost, result } } );
|
|
139
|
+
|
|
140
|
+
addEventActionWithContext( EventAction.END, { id: traceId, details: { result: serializeImages, usage, providerMetadata } } );
|
|
141
|
+
return responseProxy;
|
|
142
|
+
} catch ( error ) {
|
|
143
|
+
throw handleResponseError( { traceId, error } );
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/** Awaits a consumer callback, logging and swallowing its failures: the hooks are fire and forget */
|
|
148
|
+
const invokeCallback = async ( cb, args, cbName ) => {
|
|
149
|
+
if ( typeof cb === 'function' ) {
|
|
150
|
+
try {
|
|
151
|
+
await cb( ...args );
|
|
152
|
+
} catch ( e ) {
|
|
153
|
+
Logger.error( `Stream ${cbName}() callback failed`, { namespace: 'LLM', error: e?.message || String( e ) } );
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Starts an LLM trace around a live AI SDK stream (`streamText`, `Agent.stream`).
|
|
160
|
+
*
|
|
161
|
+
* `fn` receives `onEndHook(response, callback)` and `onErrorHook(event, callback)` to wire into the
|
|
162
|
+
* SDK `onEnd` / `onError`, plus `onStepEndHook` and `onAbortHook` for `onStepEnd` / `onAbort`. Both
|
|
163
|
+
* terminal hooks bill, end or record the trace, then invoke `callback`; a `callback` that is not a
|
|
164
|
+
* function is skipped, and callback failures are logged, never rethrown.
|
|
165
|
+
*
|
|
166
|
+
* Neither hook throws, because the SDK invokes them through `notify`, which swallows callback
|
|
167
|
+
* failures and discards their return: a failure while reading the response would vanish, so it is
|
|
168
|
+
* logged and recorded as a trace error here instead. An `onError`
|
|
169
|
+
* event carrying no `Error` is normalized to `Streaming failed.` with the original value as `cause`,
|
|
170
|
+
* so the trace always closes and the consumer callback always runs.
|
|
171
|
+
*
|
|
172
|
+
* Metering is fed by `onStepEndHook`, which collects step usage so the tokens survive the exits
|
|
173
|
+
* that report no response: `NoOutputGeneratedError` skips `onEnd`, and an abort fires neither
|
|
174
|
+
* terminal hook. `onAbortHook` bills that case, and the SDK awaits it before enqueueing the abort
|
|
175
|
+
* part, so billing from there always lands before the consumer observes the cancellation.
|
|
176
|
+
*
|
|
177
|
+
* A throw or rejected Promise from `fn` (stream creation / Agent setup) is mapped and recorded on
|
|
178
|
+
* the trace; a non-Promise return (the `streamText` stream) is returned as is, with a rejection of
|
|
179
|
+
* its `output` promise recorded without being swallowed from the consumer. An abort on
|
|
180
|
+
* `abortSignal` records its reason as a trace error, and the listener is removed when the stream
|
|
181
|
+
* ends, reports an error, or fails during setup. An abort the SDK raises on its own timeout leaves
|
|
182
|
+
* `abortSignal` untouched, so `onAbort` records that one instead.
|
|
183
|
+
*
|
|
184
|
+
* @param {object} args
|
|
185
|
+
* @param {string} args.name - Trace event name
|
|
186
|
+
* @param {object} args.prompt - Loaded prompt (`config.provider` / `config.model` used for cost)
|
|
187
|
+
* @param {Record<string, string>} [args.toolIdsByName] - Provider tool ids keyed by configured name
|
|
188
|
+
* @param {AbortSignal} [args.abortSignal] - Optional signal used to trace stream cancellation
|
|
189
|
+
* @param {( wiring: { onEndHook: Function, onErrorHook: Function, onStepEndHook: Function,
|
|
190
|
+
* onAbortHook: Function } ) => object | Promise<object>} args.fn - Wire the hooks into the call
|
|
191
|
+
* and return the SDK stream, or a Promise of that stream (`Agent.stream`)
|
|
192
|
+
* @returns {object | Promise<object>} Value returned by `fn`; a rejected Promise is remapped
|
|
193
|
+
*/
|
|
194
|
+
export const wrapStream = ( { name, prompt, toolIdsByName, abortSignal, fn } ) => {
|
|
195
|
+
const traceId = startTrace( { name, prompt } );
|
|
196
|
+
const metering = new Metering( { traceId, prompt, toolIdsByName } );
|
|
197
|
+
|
|
198
|
+
const handleAbort = () => {
|
|
199
|
+
const error = abortSignal?.reason instanceof Error ? abortSignal.reason : new Error( 'Streaming aborted.', { cause: abortSignal?.reason } );
|
|
200
|
+
handleAiSdkError( { traceId, error } );
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
if ( abortSignal ) {
|
|
204
|
+
if ( abortSignal.aborted ) {
|
|
205
|
+
handleAbort();
|
|
206
|
+
} else {
|
|
207
|
+
abortSignal.addEventListener( 'abort', handleAbort, { once: true } );
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const removeAbortListener = () => abortSignal?.removeEventListener( 'abort', handleAbort );
|
|
211
|
+
|
|
212
|
+
const onStepEndHook = metering.recordStep;
|
|
213
|
+
|
|
214
|
+
const onAbortHook = async () => {
|
|
215
|
+
removeAbortListener();
|
|
216
|
+
|
|
217
|
+
await metering.bill();
|
|
218
|
+
// abortion was caused by timeout and not signal
|
|
219
|
+
if ( !abortSignal?.aborted ) {
|
|
220
|
+
handleAiSdkError( { traceId, error: new Error( 'Streaming timed out.' ) } );
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const onEndHook = async ( response, callback ) => {
|
|
225
|
+
removeAbortListener();
|
|
226
|
+
|
|
227
|
+
await metering.bill( response );
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
const { text: result, finalStep, usage } = response;
|
|
231
|
+
const providerMetadata = finalStep?.providerMetadata;
|
|
232
|
+
const sources = extractSources( response );
|
|
233
|
+
|
|
234
|
+
const proxyResponse = createResponseProxy( { response, properties: { cost: metering.attributes.cost, sources, result } } );
|
|
235
|
+
addEventActionWithContext( EventAction.END, { id: traceId, details: { result, usage, providerMetadata, sources } } );
|
|
236
|
+
|
|
237
|
+
await invokeCallback( callback, [ proxyResponse ], 'onEnd' );
|
|
238
|
+
} catch ( error ) {
|
|
239
|
+
Logger.error( 'AI SDK response handling failed', { namespace: 'LLM', error: error?.message || String( error ) } );
|
|
240
|
+
handleResponseError( { traceId, error } );
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const onErrorHook = async ( event, callback ) => {
|
|
245
|
+
removeAbortListener();
|
|
246
|
+
await metering.bill();
|
|
247
|
+
|
|
248
|
+
const error = event?.error instanceof Error ? event.error : new Error( 'Streaming failed.', { cause: event?.error } );
|
|
249
|
+
const mappedError = handleAiSdkError( { traceId, error } );
|
|
250
|
+
await invokeCallback( callback, [ mappedError ], 'onError' );
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
const handleStreamError = error => {
|
|
254
|
+
removeAbortListener();
|
|
255
|
+
return handleAiSdkError( { traceId, error } );
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
const addStreamOutputErrorHandler = stream => {
|
|
259
|
+
stream.output?.catch( error => handleAiSdkError( { traceId, error } ) );
|
|
260
|
+
return stream;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
const createStream = () => {
|
|
264
|
+
try {
|
|
265
|
+
return fn( { onEndHook, onErrorHook, onStepEndHook, onAbortHook } );
|
|
266
|
+
} catch ( error ) {
|
|
267
|
+
throw handleStreamError( error );
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
const stream = createStream();
|
|
272
|
+
|
|
273
|
+
/** Streams can be a promise or not, for both cases add the handler to catch .output errors, and if it is a promise add a .catch handler to observe errors there as well */
|
|
274
|
+
return isPromise( stream ) ?
|
|
275
|
+
stream.then( addStreamOutputErrorHandler ).catch( e => {
|
|
276
|
+
throw handleStreamError( e );
|
|
277
|
+
} ) :
|
|
278
|
+
addStreamOutputErrorHandler( stream );
|
|
279
|
+
};
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { ValidationError } from '#errors';
|
|
4
|
+
import { Role } from './consts.js';
|
|
5
|
+
import { promptSchema } from './prompt/validations.js';
|
|
6
|
+
|
|
7
|
+
const rejectPromptOwnedCallArg = name => z.unknown().optional().refine(
|
|
8
|
+
value => value === undefined,
|
|
9
|
+
`${name} must be set in the prompt file, not as a call argument`
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
// Listed so .strict() callers get the prompt-file message instead of an unrecognized-key error.
|
|
13
|
+
// @TODO Do not drop this later.
|
|
14
|
+
const promptOwnedCallArgRejection = {
|
|
15
|
+
maxSteps: rejectPromptOwnedCallArg( 'maxSteps' ),
|
|
16
|
+
skills: rejectPromptOwnedCallArg( 'skills' )
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const functionSchema = z.custom( value => typeof value === 'function', 'Expected function' );
|
|
20
|
+
|
|
21
|
+
const variablesSchema = z.record( z.string(), z.unknown() );
|
|
22
|
+
|
|
23
|
+
const toolChoiceSchema = z.union( [
|
|
24
|
+
z.enum( [ 'auto', 'none', 'required' ] ),
|
|
25
|
+
z.object( {
|
|
26
|
+
type: z.literal( 'tool' ),
|
|
27
|
+
toolName: z.string().min( 1 )
|
|
28
|
+
} ).strict()
|
|
29
|
+
] );
|
|
30
|
+
|
|
31
|
+
const stopWhenSchema = z.union( [
|
|
32
|
+
functionSchema,
|
|
33
|
+
z.array( functionSchema ).min( 1 )
|
|
34
|
+
] );
|
|
35
|
+
|
|
36
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray( value );
|
|
37
|
+
|
|
38
|
+
const opaqueObjectSchema = z.custom( isObject, 'Expected object' );
|
|
39
|
+
|
|
40
|
+
const outputSchema = opaqueObjectSchema;
|
|
41
|
+
|
|
42
|
+
const toolsSchema = z.record( z.string().min( 1 ), opaqueObjectSchema );
|
|
43
|
+
|
|
44
|
+
const messageStoreSchema = z.custom(
|
|
45
|
+
value => value !== null &&
|
|
46
|
+
typeof value === 'object' &&
|
|
47
|
+
typeof value.getMessages === 'function' &&
|
|
48
|
+
typeof value.addMessages === 'function',
|
|
49
|
+
'Expected an object with getMessages and addMessages functions'
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
const modelMessageSchema = z.object( {
|
|
53
|
+
role: z.enum( [ ...Object.values( Role ), 'tool' ] ),
|
|
54
|
+
content: z.union( [ z.string(), z.array( z.unknown() ) ] )
|
|
55
|
+
} ).loose();
|
|
56
|
+
|
|
57
|
+
const promptFileSchema = z.string().min( 1 );
|
|
58
|
+
|
|
59
|
+
const promptInputSchema = z.unknown().transform( ( value, ctx ) => {
|
|
60
|
+
const result = ( isObject( value ) ? promptSchema : promptFileSchema ).safeParse( value );
|
|
61
|
+
if ( !result.success ) {
|
|
62
|
+
for ( const issue of result.error.issues ) {
|
|
63
|
+
ctx.addIssue( issue );
|
|
64
|
+
}
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
return result.data;
|
|
68
|
+
} );
|
|
69
|
+
|
|
70
|
+
const promptCallFields = {
|
|
71
|
+
prompt: promptInputSchema,
|
|
72
|
+
promptDir: z.string().min( 1 ).optional(),
|
|
73
|
+
variables: variablesSchema.optional()
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const textRuntimeCallFields = {
|
|
77
|
+
abortSignal: z.instanceof( AbortSignal ).optional(),
|
|
78
|
+
output: outputSchema.optional(),
|
|
79
|
+
stopWhen: stopWhenSchema.optional(),
|
|
80
|
+
toolChoice: toolChoiceSchema.optional(),
|
|
81
|
+
tools: toolsSchema.optional()
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const generateTextCallFields = {
|
|
85
|
+
...promptCallFields,
|
|
86
|
+
...promptOwnedCallArgRejection,
|
|
87
|
+
...textRuntimeCallFields
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const toPromptArgs = ( { prompt, maxSteps, skills, ...rest } ) => ( {
|
|
91
|
+
...( typeof prompt === 'string' ? { promptFile: prompt } : { promptObject: prompt } ),
|
|
92
|
+
...rest
|
|
93
|
+
} );
|
|
94
|
+
|
|
95
|
+
const rejectPromptObjectFileArgs = ( args, ctx ) => {
|
|
96
|
+
if ( !isObject( args.prompt ) ) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
for ( const field of [ 'promptDir', 'variables' ] ) {
|
|
101
|
+
if ( args[field] !== undefined ) {
|
|
102
|
+
ctx.addIssue( {
|
|
103
|
+
code: 'custom',
|
|
104
|
+
path: [ field ],
|
|
105
|
+
message: `${field} cannot be used when prompt is an object`
|
|
106
|
+
} );
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const generateTextArgsSchema = z.object( generateTextCallFields )
|
|
112
|
+
.strict()
|
|
113
|
+
.superRefine( rejectPromptObjectFileArgs )
|
|
114
|
+
.transform( toPromptArgs );
|
|
115
|
+
|
|
116
|
+
const generateTextWithStreamingArgsSchema = z.object( {
|
|
117
|
+
...generateTextCallFields,
|
|
118
|
+
onChunk: functionSchema.optional()
|
|
119
|
+
} ).strict().superRefine( rejectPromptObjectFileArgs ).transform( toPromptArgs );
|
|
120
|
+
|
|
121
|
+
const streamTextArgsSchema = z.object( {
|
|
122
|
+
...generateTextCallFields,
|
|
123
|
+
onChunk: functionSchema.optional(),
|
|
124
|
+
onError: functionSchema.optional(),
|
|
125
|
+
onEnd: functionSchema.optional()
|
|
126
|
+
} ).strict().superRefine( rejectPromptObjectFileArgs ).transform( toPromptArgs );
|
|
127
|
+
|
|
128
|
+
const agentCallFields = {
|
|
129
|
+
...promptCallFields,
|
|
130
|
+
...promptOwnedCallArgRejection,
|
|
131
|
+
messageStore: messageStoreSchema.optional(),
|
|
132
|
+
output: outputSchema.optional(),
|
|
133
|
+
stopWhen: stopWhenSchema.optional(),
|
|
134
|
+
tools: toolsSchema.optional()
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const agentMethodCallFields = {
|
|
138
|
+
abortSignal: z.instanceof( AbortSignal ).optional(),
|
|
139
|
+
messages: z.array( modelMessageSchema ).default( [] ),
|
|
140
|
+
toolChoice: toolChoiceSchema.optional(),
|
|
141
|
+
...promptOwnedCallArgRejection
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const agentArgsSchema = z.object( agentCallFields )
|
|
145
|
+
.strict()
|
|
146
|
+
.superRefine( rejectPromptObjectFileArgs )
|
|
147
|
+
.transform( toPromptArgs );
|
|
148
|
+
|
|
149
|
+
const agentGenerateArgsSchema = z.object( agentMethodCallFields ).strict();
|
|
150
|
+
|
|
151
|
+
const agentGenerateWithStreamingArgsSchema = z.object( {
|
|
152
|
+
...agentMethodCallFields,
|
|
153
|
+
onChunk: functionSchema.optional()
|
|
154
|
+
} ).strict();
|
|
155
|
+
|
|
156
|
+
const agentStreamArgsSchema = z.object( {
|
|
157
|
+
...agentMethodCallFields,
|
|
158
|
+
onChunk: functionSchema.optional(),
|
|
159
|
+
onError: functionSchema.optional(),
|
|
160
|
+
onEnd: functionSchema.optional()
|
|
161
|
+
} ).strict();
|
|
162
|
+
|
|
163
|
+
const base64StringSchema = z.string()
|
|
164
|
+
.min( 1 )
|
|
165
|
+
.regex(
|
|
166
|
+
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}(?:==)?|[A-Za-z0-9+/]{3}=?)?$/,
|
|
167
|
+
'Image strings must be raw base64 data.'
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
const imageDataSchema = z.union( [
|
|
171
|
+
z.instanceof( Buffer ),
|
|
172
|
+
z.instanceof( Uint8Array ),
|
|
173
|
+
z.instanceof( ArrayBuffer ),
|
|
174
|
+
base64StringSchema
|
|
175
|
+
] );
|
|
176
|
+
|
|
177
|
+
const imageInputSchema = z.union( [
|
|
178
|
+
imageDataSchema,
|
|
179
|
+
z.object( {
|
|
180
|
+
data: imageDataSchema,
|
|
181
|
+
mediaType: z.string().min( 1 ).optional()
|
|
182
|
+
} ).strict()
|
|
183
|
+
] );
|
|
184
|
+
|
|
185
|
+
const generateImageCallFields = {
|
|
186
|
+
abortSignal: z.instanceof( AbortSignal ).optional(),
|
|
187
|
+
images: z.array( imageInputSchema ).min( 1 ).optional(),
|
|
188
|
+
mask: imageInputSchema.optional(),
|
|
189
|
+
...promptCallFields
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
const generateImageArgsSchema = z.object( generateImageCallFields ).strict().superRefine( ( args, ctx ) => {
|
|
193
|
+
rejectPromptObjectFileArgs( args, ctx );
|
|
194
|
+
|
|
195
|
+
if ( args.mask && !args.images ) {
|
|
196
|
+
ctx.addIssue( {
|
|
197
|
+
code: 'custom',
|
|
198
|
+
path: [ 'mask' ],
|
|
199
|
+
message: 'mask requires images.'
|
|
200
|
+
} );
|
|
201
|
+
}
|
|
202
|
+
} ).transform( toPromptArgs );
|
|
203
|
+
|
|
204
|
+
const parseSchema = ( schema, input, errorPrefix ) => {
|
|
205
|
+
const result = schema.safeParse( input );
|
|
206
|
+
if ( !result.success ) {
|
|
207
|
+
throw new ValidationError( `${errorPrefix}: ${z.prettifyError( result.error )}` );
|
|
208
|
+
}
|
|
209
|
+
return result.data;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
export const parseGenerateTextArgs = args =>
|
|
213
|
+
parseSchema( generateTextArgsSchema, args, 'Invalid generateText() arguments' );
|
|
214
|
+
|
|
215
|
+
export const parseGenerateTextWithStreamingArgs = args =>
|
|
216
|
+
parseSchema( generateTextWithStreamingArgsSchema, args, 'Invalid generateTextWithStreaming() arguments' );
|
|
217
|
+
|
|
218
|
+
export const parseStreamTextArgs = args =>
|
|
219
|
+
parseSchema( streamTextArgsSchema, args, 'Invalid streamText() arguments' );
|
|
220
|
+
|
|
221
|
+
export const parseGenerateImageArgs = args =>
|
|
222
|
+
parseSchema( generateImageArgsSchema, args, 'Invalid generateImage() arguments' );
|
|
223
|
+
|
|
224
|
+
export const parseAgentArgs = args =>
|
|
225
|
+
parseSchema( agentArgsSchema, args, 'Invalid Agent() arguments' );
|
|
226
|
+
|
|
227
|
+
export const parseAgentGenerateArgs = args =>
|
|
228
|
+
parseSchema( agentGenerateArgsSchema, args ?? {}, 'Invalid Agent.generate() arguments' );
|
|
229
|
+
|
|
230
|
+
export const parseAgentGenerateWithStreamingArgs = args =>
|
|
231
|
+
parseSchema( agentGenerateWithStreamingArgsSchema, args ?? {}, 'Invalid Agent.generateWithStreaming() arguments' );
|
|
232
|
+
|
|
233
|
+
export const parseAgentStreamArgs = args =>
|
|
234
|
+
parseSchema( agentStreamArgsSchema, args ?? {}, 'Invalid Agent.stream() arguments' );
|
|
@@ -37,16 +37,8 @@ const excludeUnlessPackageExposeWorkflows = resource => {
|
|
|
37
37
|
};
|
|
38
38
|
|
|
39
39
|
export const webpackConfigHook = config => {
|
|
40
|
-
// Prefer the "output-workflow-bundle" export condition when resolving packages.
|
|
41
|
-
// Packages that transitively depend on Node.js built-ins (which can't exist in the
|
|
42
|
-
// Temporal workflow bundle) can provide an alternative entry point under this condition
|
|
43
|
-
// that excludes the offending code paths. Packages without this condition fall through
|
|
44
|
-
// to the standard "import" / "module" / "default" conditions as normal.
|
|
45
40
|
config.resolve = config.resolve ?? {};
|
|
46
|
-
config.resolve.conditionNames = [
|
|
47
|
-
'output-workflow-bundle',
|
|
48
|
-
...( config.resolve.conditionNames ?? [ 'import', 'module', 'webpack', 'default' ] )
|
|
49
|
-
];
|
|
41
|
+
config.resolve.conditionNames = config.resolve.conditionNames ?? [ 'import', 'module', 'webpack', 'default' ];
|
|
50
42
|
|
|
51
43
|
config.module = config.module ?? { };
|
|
52
44
|
config.module.rules = config.module.rules ?? [];
|
|
@@ -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
|
-
|
|
23
|
-
|
|
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
|
};
|
|
@@ -15,8 +15,8 @@ const evaluatorsNameCache = new Map(); // path -> Map<exported, evaluatorName>
|
|
|
15
15
|
const sharedEvaluatorsNameCache = new Map(); // path -> Map<exported, evaluatorName> (shared)
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
|
-
* Webpack loader that
|
|
19
|
-
*
|
|
18
|
+
* Webpack loader that strips imported steps/evaluators by reading declared activity names,
|
|
19
|
+
* transforming function-body activity calls and replacing other references with the activity name.
|
|
20
20
|
* Preserves sourcemaps.
|
|
21
21
|
*
|
|
22
22
|
* @param {string|Buffer} source - Module source code.
|
|
@@ -40,11 +40,7 @@ export default function stepImportRewriterAstLoader( source, inputMap ) {
|
|
|
40
40
|
return callback( null, source, inputMap );
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
|
|
44
|
-
// No edits performed
|
|
45
|
-
if ( !rewrote ) {
|
|
46
|
-
return callback( null, source, inputMap );
|
|
47
|
-
}
|
|
43
|
+
rewriteActivityCalls( { ast, activityImports } );
|
|
48
44
|
|
|
49
45
|
const { code, map } = generate( ast, {
|
|
50
46
|
sourceMaps: true,
|
|
@@ -54,8 +54,6 @@ const createInvokeActivityCall = ( activityName, args ) =>
|
|
|
54
54
|
|
|
55
55
|
// Rewrite valid function-body activity calls; top-level call validation belongs to the validator loader.
|
|
56
56
|
const rewriteActivityCallsInFunctions = ( { ast, activityNames } ) => {
|
|
57
|
-
const state = { rewrote: false };
|
|
58
|
-
|
|
59
57
|
traverse( ast, {
|
|
60
58
|
CallExpression: path => {
|
|
61
59
|
if ( !path.getFunctionParent() || !isIdentifierCallee( path ) ) {
|
|
@@ -70,19 +68,41 @@ const rewriteActivityCallsInFunctions = ( { ast, activityNames } ) => {
|
|
|
70
68
|
|
|
71
69
|
assertGlobalThisIsSafe( path );
|
|
72
70
|
path.replaceWith( createInvokeActivityCall( activityName, path.node.arguments ) );
|
|
73
|
-
state.rewrote = true;
|
|
74
71
|
}
|
|
75
72
|
} );
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// Calls belong to the call rewrite (function bodies) or the validator loader (top level).
|
|
76
|
+
const isCallee = path => path.parentPath.isCallExpression( { callee: path.node } );
|
|
77
|
+
|
|
78
|
+
// The activity import is stripped from the bundle, so non-call references become the activity name.
|
|
79
|
+
const rewriteActivityReferences = ( { ast, activityNames } ) => {
|
|
80
|
+
traverse( ast, {
|
|
81
|
+
Identifier: path => {
|
|
82
|
+
const { name } = path.node;
|
|
83
|
+
const activityName = activityNames.get( name );
|
|
84
|
+
if ( !activityName || !path.isReferencedIdentifier() || isCallee( path ) || path.parentPath.isExportSpecifier() ) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if ( hasLiveLocalBinding( path, name ) ) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
76
90
|
|
|
77
|
-
|
|
91
|
+
if ( path.parentPath.isObjectProperty( { shorthand: true } ) ) {
|
|
92
|
+
path.parent.shorthand = false;
|
|
93
|
+
}
|
|
94
|
+
path.replaceWith( stringLiteral( activityName ) );
|
|
95
|
+
}
|
|
96
|
+
} );
|
|
78
97
|
};
|
|
79
98
|
|
|
80
|
-
// Entry point: resolve collected component imports into
|
|
99
|
+
// Entry point: resolve collected component imports into dispatcher calls and activity names.
|
|
81
100
|
export default function rewriteActivityCalls( { ast, activityImports } ) {
|
|
82
101
|
const activityNames = buildActivityNameMap( activityImports );
|
|
83
102
|
if ( activityNames.size === 0 ) {
|
|
84
|
-
return
|
|
103
|
+
return;
|
|
85
104
|
}
|
|
86
105
|
|
|
87
|
-
|
|
106
|
+
rewriteActivityCallsInFunctions( { ast, activityNames } );
|
|
107
|
+
rewriteActivityReferences( { ast, activityNames } );
|
|
88
108
|
};
|