@outputai/core 0.15.1-next.bb9bb8d.0 → 0.15.1-next.de5fa8c.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 (101) 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/helpers/fetch.js +21 -9
  20. package/src/helpers/path.js +34 -0
  21. package/src/helpers/redact.js +2 -1
  22. package/src/http/config.js +10 -0
  23. package/src/http/cost.d.ts +20 -0
  24. package/src/http/cost.js +41 -0
  25. package/src/http/fetch/events.js +10 -0
  26. package/src/http/fetch/index.d.ts +24 -0
  27. package/src/http/fetch/index.js +78 -0
  28. package/src/http/fetch/logger.d.ts +10 -0
  29. package/src/http/fetch/logger.js +56 -0
  30. package/src/http/index.d.ts +28 -0
  31. package/src/http/index.js +9 -0
  32. package/src/http/ky/index.d.ts +25 -0
  33. package/src/http/ky/index.js +10 -0
  34. package/src/http/request_tag.js +30 -0
  35. package/src/interface/index.d.ts +1 -0
  36. package/src/llm/agent.js +147 -0
  37. package/src/llm/ai_provider.js +131 -0
  38. package/src/llm/ai_sdk_options.js +126 -0
  39. package/src/llm/consts.js +6 -0
  40. package/src/llm/deprecated_provider_aliases.js +8 -0
  41. package/src/llm/generate.js +98 -0
  42. package/src/llm/index.d.ts +697 -0
  43. package/src/llm/index.js +6 -0
  44. package/src/llm/judge.js +48 -0
  45. package/src/llm/prompt/content.js +70 -0
  46. package/src/llm/prompt/interpolations.js +58 -0
  47. package/src/llm/prompt/loader.js +67 -0
  48. package/src/llm/prompt/markup/attributes.js +52 -0
  49. package/src/llm/prompt/markup/nodes.js +71 -0
  50. package/src/llm/prompt/markup/tokenizer.js +3 -0
  51. package/src/llm/prompt/markup/tokens.js +26 -0
  52. package/src/llm/prompt/validations.js +129 -0
  53. package/src/llm/utils/cost.js +267 -0
  54. package/src/llm/utils/error_handler.js +53 -0
  55. package/src/llm/utils/file.js +42 -0
  56. package/src/llm/utils/google_vertex_auth.js +31 -0
  57. package/src/llm/utils/image.js +37 -0
  58. package/src/llm/utils/legacy_cost_attribute.js +75 -0
  59. package/src/llm/utils/metering.js +139 -0
  60. package/src/llm/utils/models.js +15 -0
  61. package/src/llm/utils/models_pricing.js +96 -0
  62. package/src/llm/utils/models_pricing_snapshot.json +4711 -0
  63. package/src/llm/utils/skills.js +74 -0
  64. package/src/llm/utils/sources.js +73 -0
  65. package/src/llm/utils/stream.js +75 -0
  66. package/src/llm/utils/tools.js +62 -0
  67. package/src/llm/utils/usage.js +155 -0
  68. package/src/llm/utils/usage_tools.js +23 -0
  69. package/src/llm/utils/web_search.js +155 -0
  70. package/src/llm/utils/wrap.js +279 -0
  71. package/src/llm/validations.js +234 -0
  72. package/src/tracing/trace_attribute.d.ts +0 -17
  73. package/src/tracing/trace_attribute.js +1 -29
  74. package/src/worker/bundler_options.js +1 -9
  75. package/src/worker/configs.js +23 -4
  76. package/src/worker/index.js +16 -47
  77. package/src/worker/interceptors/activity.js +0 -1
  78. package/src/worker/interceptors/workflow.js +0 -1
  79. package/src/worker/loader/workflows.js +16 -2
  80. package/src/worker/telemetry.js +122 -2
  81. package/src/worker/webpack_loaders/workflow_rewriter/index.mjs +3 -7
  82. package/src/worker/webpack_loaders/workflow_rewriter/rewrite_activity_calls.js +27 -7
  83. package/src/worker/webpack_loaders/workflow_validator/npm_workflow_export_resolve.js +5 -6
  84. package/src/worker/worker_options.js +43 -0
  85. package/src/sdk/README.md +0 -47
  86. package/src/sdk/helpers/component_metadata.d.ts +0 -17
  87. package/src/sdk/helpers/component_metadata.js +0 -6
  88. package/src/sdk/helpers/index.d.ts +0 -12
  89. package/src/sdk/helpers/index.js +0 -3
  90. package/src/sdk/helpers/objects.d.ts +0 -56
  91. package/src/sdk/helpers/objects.js +0 -8
  92. package/src/sdk/helpers/path.d.ts +0 -11
  93. package/src/sdk/helpers/path.js +0 -32
  94. package/src/sdk/runtime/context.d.ts +0 -30
  95. package/src/sdk/runtime/context.js +0 -15
  96. package/src/sdk/runtime/events.d.ts +0 -13
  97. package/src/sdk/runtime/events.js +0 -5
  98. package/src/sdk/runtime/index.d.ts +0 -12
  99. package/src/sdk/runtime/index.js +0 -3
  100. package/src/sdk/runtime/tracing.d.ts +0 -48
  101. package/src/sdk/runtime/tracing.js +0 -11
@@ -0,0 +1,48 @@
1
+ import { Output } from 'ai';
2
+ import { z } from 'zod';
3
+ import { EvaluationBooleanResult, EvaluationNumberResult, EvaluationStringResult, EvaluationVerdictResult } from '#interface/evaluation_result';
4
+ import { generateText } from './generate.js';
5
+
6
+ const CONFIDENCE = 0.9;
7
+
8
+ const verdictSchema = z.object( { verdict: z.enum( [ 'pass', 'partial', 'fail' ] ), reasoning: z.string() } );
9
+ const scoreSchema = z.object( { score: z.number(), reasoning: z.string() } );
10
+ const booleanSchema = z.object( { result: z.boolean(), reasoning: z.string() } );
11
+ const labelSchema = z.object( { label: z.string(), reasoning: z.string() } );
12
+
13
+ const judge = async ( { prompt, variables, schema } ) => {
14
+ const { output } = await generateText( { prompt, variables, output: Output.object( { schema } ) } );
15
+ return output;
16
+ };
17
+
18
+ /**
19
+ * Ask an LLM judge for a pass, partial, or fail verdict.
20
+ */
21
+ export const judgeVerdict = async ( { prompt, variables, schema = verdictSchema } ) => {
22
+ const { verdict, reasoning } = await judge( { prompt, variables, schema } );
23
+ return new EvaluationVerdictResult( { value: verdict, confidence: CONFIDENCE, reasoning } );
24
+ };
25
+
26
+ /**
27
+ * Ask an LLM judge for a numeric score.
28
+ */
29
+ export const judgeScore = async ( { prompt, variables, schema = scoreSchema } ) => {
30
+ const { score, reasoning } = await judge( { prompt, variables, schema } );
31
+ return new EvaluationNumberResult( { value: score, confidence: CONFIDENCE, reasoning } );
32
+ };
33
+
34
+ /**
35
+ * Ask an LLM judge for a true or false answer.
36
+ */
37
+ export const judgeBoolean = async ( { prompt, variables, schema = booleanSchema } ) => {
38
+ const { result, reasoning } = await judge( { prompt, variables, schema } );
39
+ return new EvaluationBooleanResult( { value: result, confidence: CONFIDENCE, reasoning } );
40
+ };
41
+
42
+ /**
43
+ * Ask an LLM judge for a label.
44
+ */
45
+ export const judgeLabel = async ( { prompt, variables, schema = labelSchema } ) => {
46
+ const { label, reasoning } = await judge( { prompt, variables, schema } );
47
+ return new EvaluationStringResult( { value: label, confidence: CONFIDENCE, reasoning } );
48
+ };
@@ -0,0 +1,70 @@
1
+ import { Role } from '../consts.js';
2
+ import { decode } from './interpolations.js';
3
+ import { FatalError } from '#errors';
4
+ import { parseMarkup } from './markup/nodes.js';
5
+
6
+ /** Merge two objects 2-level deep. */
7
+ const mergeOptions = ( base = {}, extra = {} ) => {
8
+ const merged = { ...base };
9
+ for ( const [ namespace, options ] of Object.entries( extra ) ) {
10
+ merged[namespace] = { ...merged[namespace], ...options };
11
+ }
12
+ return merged;
13
+ };
14
+
15
+ /** Gets the options attribute from the message attributes */
16
+ const extractOptions = attributes => {
17
+ const { options, ...unsupportedAttributes } = attributes;
18
+ if ( Object.keys( unsupportedAttributes ).length > 0 ) {
19
+ throw new FatalError( 'Message has unsupported attributes. The only supported attribute is "options".' );
20
+ }
21
+ if ( options === true ) {
22
+ throw new FatalError( 'Message "options" attribute must have a value.' );
23
+ }
24
+ const rawOptions = options?.trim();
25
+ return rawOptions ? rawOptions.split( /\s+/ ) : null;
26
+ };
27
+
28
+ /** Merge down messageOptions selected from a list */
29
+ const resolveProviderOptions = ( options, messageOptions ) =>
30
+ options.reduce( ( result, option ) => {
31
+ if ( !messageOptions[option] ) {
32
+ throw new FatalError( `Message "options" attribute references unknown option "${option}" in \`config.messageOptions\`.` );
33
+ }
34
+ return mergeOptions( result, messageOptions[option] );
35
+ }, {} );
36
+
37
+ const promptRoleSet = new Set( [ Role.SYSTEM, Role.USER, Role.ASSISTANT ] );
38
+
39
+ /**
40
+ * Extract messages or instructions from prompt content. A leading role tag yields
41
+ * messages and null instructions; otherwise instructions are the decoded body.
42
+ */
43
+ export const parseContent = ( content, messageOptions ) => {
44
+ const nodes = parseMarkup( content );
45
+
46
+ if ( nodes.length === 0 ) {
47
+ return { messages: [], instructions: decode( content.trim() ) };
48
+ }
49
+
50
+ const invalidRole = nodes.find( node => !promptRoleSet.has( node.tagName ) );
51
+ if ( invalidRole ) {
52
+ throw new FatalError( `Message has invalid role "${invalidRole.tagName}".` );
53
+ }
54
+
55
+ return {
56
+ messages: nodes.map( node => {
57
+ const options = extractOptions( node.attributes );
58
+ if ( options && Object.keys( messageOptions ?? {} ).length === 0 ) {
59
+ throw new FatalError( 'Message has "options" attribute but `config.messageOptions` is empty.' );
60
+ }
61
+ const providerOptions = options ? resolveProviderOptions( options, messageOptions ) : null;
62
+ return {
63
+ role: node.tagName.toLowerCase(),
64
+ content: decode( node.content.trim() ),
65
+ ...( providerOptions && { providerOptions } )
66
+ };
67
+ } ),
68
+ instructions: null
69
+ };
70
+ };
@@ -0,0 +1,58 @@
1
+ import { isPlainObject } from '#helpers/object';
2
+ import { encodeXML, decodeXML } from 'entities';
3
+
4
+ export const interpolationFilterToken = '__var_safe';
5
+
6
+ /**
7
+ * XML-escapes a value.
8
+ * @param {unknown} value - Any value to escape
9
+ * @returns {string} Escaped value or '' if original value was null/undefined
10
+ */
11
+ export const encode = value => [ null, undefined ].includes( value ) ? '' : encodeXML( String( value ) );
12
+
13
+ /**
14
+ * Matches {% raw %}...{% endraw %} or {{ ... }} tags
15
+ */
16
+ const VAR_OR_RAW = /(\{%\s*raw\s*%\}[\s\S]*?\{%\s*endraw\s*%\})|\{\{\s*([\s\S]+?)\s*\}\}/g;
17
+
18
+ /**
19
+ * Appends `| __var_safe` filter to every `{{ ... }}` expression.
20
+ *
21
+ * The filter XML-escape the interpolated content so it cannot be parsed as new message blocks.
22
+ *
23
+ * Without this, a variable whose value contains `<system>` or `</user>` would inject extra
24
+ * message blocks.
25
+ *
26
+ * Raw regions `{% raw %} ... {% endraw %}` are emitted verbatim by Liquid and preserved
27
+ * unchanged.
28
+ *
29
+ * Note: The `g` flag advances past any matched raw regions, so `{{ ... }}` inside them are
30
+ * preserved as well.
31
+ *
32
+ * @param {string} raw - Raw template string
33
+ * @returns {string} Template with `| __var_safe` appended to each interpolation
34
+ */
35
+ export const pipeInterpolations = raw =>
36
+ raw.replace( VAR_OR_RAW, ( _, rawRegion, expressionContent ) =>
37
+ rawRegion === undefined ? `{{ ${expressionContent.trim()} | ${interpolationFilterToken} }}` : rawRegion
38
+ );
39
+
40
+ /**
41
+ * Recursive decode a XML-encoded value.
42
+ * @param {unknown} value - Value to decode
43
+ * @returns {unknown} Decoded value
44
+ */
45
+ export const decode = value => {
46
+ if ( typeof value === 'string' ) {
47
+ return decodeXML( value );
48
+ }
49
+ if ( Array.isArray( value ) ) {
50
+ return value.map( decode );
51
+ }
52
+ if ( isPlainObject( value ) ) {
53
+ return Object.fromEntries(
54
+ Object.entries( value ).map( ( [ key, item ] ) => [ key, decode( item ) ] )
55
+ );
56
+ }
57
+ return value;
58
+ };
@@ -0,0 +1,67 @@
1
+ import { Context, Liquid } from 'liquidjs';
2
+ import { parsePromptSchema } from './validations.js';
3
+ import { FatalError } from '#errors';
4
+ import { pipeInterpolations, interpolationFilterToken, encode, decode } from './interpolations.js';
5
+ import { resolveInvocationDir } from '#helpers/path';
6
+ import { searchAndReadFile } from '../utils/file.js';
7
+ import matter from 'gray-matter';
8
+ import { parseContent } from './content.js';
9
+
10
+ const liquid = new Liquid( {
11
+ strictFilters: true,
12
+ strictVariables: true,
13
+ lenientIf: true
14
+ } );
15
+
16
+ liquid.registerFilter( interpolationFilterToken, encode );
17
+
18
+ const splitPromptContent = text => {
19
+ const dummyEngine = () => ( {} ); // dummy engine to allow for split only
20
+ const file = matter( text, { engines: { yaml: dummyEngine } } );
21
+ return { rawFrontmatter: file.matter, rawContent: file.content };
22
+ };
23
+
24
+ const renderContent = ( rawContent, context ) => liquid.parseAndRenderSync( pipeInterpolations( rawContent ), context ).trim();
25
+
26
+ const renderFrontmatter = ( rawFrontmatter, context ) => liquid.parseAndRenderSync( pipeInterpolations( rawFrontmatter ), context );
27
+
28
+ const parseFrontmatter = yml => decode( matter( `---\n${yml}\n---\n` ).data );
29
+
30
+ /**
31
+ * Load a prompt file and render it with variables.
32
+ *
33
+ * @param {string} name - Name of the prompt file (without .prompt extension)
34
+ * @param {Record<string, unknown>} [variables] - Variables to interpolate
35
+ * @param {string} [dir] - Directory to search for the prompt file (defaults to stack-resolved invocation dir)
36
+ * @returns {Prompt} Loaded and rendered prompt object.
37
+ */
38
+ export const loadPrompt = ( name, variables = {}, dir = resolveInvocationDir() ) => {
39
+ // Small closure to encapsulate errors with "name"
40
+ const tryStep = ( fn, msg ) => {
41
+ try {
42
+ return fn();
43
+ } catch ( e ) {
44
+ throw new FatalError( [ `${msg} on prompt "${name}"`, e.message ].join( ': ' ), { cause: e } );
45
+ }
46
+ };
47
+
48
+ const file = searchAndReadFile( dir, `${name}.prompt` );
49
+ if ( !file ) {
50
+ throw new FatalError( `Prompt file "${name}" not found.` );
51
+ }
52
+
53
+ const { rawFrontmatter, rawContent } = tryStep( () => splitPromptContent( file.content ), 'Error parsing frontmatter' );
54
+ const context = new Context( variables, liquid.options, { sync: true } );
55
+ const renderedFrontmatter = tryStep( () => renderFrontmatter( rawFrontmatter, context ), 'Error rendering frontmatter' );
56
+ const content = tryStep( () => renderContent( rawContent, context ), 'Error rendering content' );
57
+
58
+ if ( !content ) {
59
+ throw new FatalError( `Prompt "${name}" has no content.` );
60
+ }
61
+
62
+ const config = tryStep( () => parseFrontmatter( renderedFrontmatter ), 'Error converting frontmatter yaml to js' );
63
+
64
+ const { messages, instructions } = tryStep( () => parseContent( content, config.messageOptions ), 'Error parsing content' );
65
+
66
+ return parsePromptSchema( { name, config, messages, instructions, fileDir: file.dir, variables } );
67
+ };
@@ -0,0 +1,52 @@
1
+ import { ValidationError } from '#errors';
2
+
3
+ const attributeSeparator = /(?<![=\s])\s+(?!\s*=)(?=(?:[^"']|"[^"]*"|'[^']*')*$)/;
4
+
5
+ export const extractAttributes = rawAttributes => {
6
+ if ( !rawAttributes?.trim() ) {
7
+ return {};
8
+ }
9
+ const pairs = rawAttributes.trim().split( attributeSeparator );
10
+ const attributeKeyRule = /^[A-Za-z][\w-]*$/;
11
+
12
+ return Object.fromEntries(
13
+ pairs.map( p => {
14
+ const splitIndex = p.indexOf( '=' );
15
+ if ( splitIndex === -1 ) {
16
+ const key = p.toLowerCase();
17
+ if ( !attributeKeyRule.test( key ) ) {
18
+ throw new ValidationError( `Invalid attribute name "${key}".` );
19
+ }
20
+ return [ key, true ];
21
+ }
22
+
23
+ const key = p.slice( 0, splitIndex ).trim().toLowerCase();
24
+ if ( !key ) {
25
+ throw new ValidationError( `Invalid attribute "${p}": name is missing.` );
26
+ }
27
+ if ( !attributeKeyRule.test( key ) ) {
28
+ throw new ValidationError( `Invalid attribute name "${key}".` );
29
+ }
30
+ const value = p.slice( splitIndex + 1 ).trim();
31
+ const openingQuote = value[0];
32
+ const isQuoted = openingQuote === '\'' || openingQuote === '"';
33
+
34
+ if ( !isQuoted ) {
35
+ const invalidCharacter = value.match( /['"<>=]/ )?.[0];
36
+ if ( invalidCharacter ) {
37
+ throw new ValidationError( `Invalid attribute "${key}": unquoted value contains invalid character \`${invalidCharacter}\`.` );
38
+ }
39
+ return [ key, value ];
40
+ } else {
41
+ if ( value.at( -1 ) !== openingQuote ) {
42
+ throw new ValidationError( `Invalid attribute "${key}": quoted value is missing its closing quote (${openingQuote}).` );
43
+ }
44
+ const unquoted = value.slice( 1, -1 );
45
+ if ( unquoted.includes( openingQuote ) ) {
46
+ throw new ValidationError( `Invalid attribute "${key}": quoted value contains an unexpected quote (${openingQuote}).` );
47
+ }
48
+ return [ key, unquoted ];
49
+ }
50
+ } )
51
+ );
52
+ };
@@ -0,0 +1,71 @@
1
+ import { isOpeningTag, isClosingTag, isEmptyText, isSelfClosingTag, isComment, extractTag } from './tokens.js' ;
2
+ import { tokenize } from './tokenizer.js';
3
+ import { ValidationError } from '#errors';
4
+
5
+ class Node {
6
+ constructor( tagName, attributes, content = '' ) {
7
+ this.tagName = tagName;
8
+ this.attributes = attributes;
9
+ this.content = content;
10
+ }
11
+ }
12
+
13
+ export const parseMarkup = content => {
14
+ const tokens = tokenize( content );
15
+ if ( !tokens ) {
16
+ return [];
17
+ }
18
+
19
+ const state = {
20
+ currentNode: null
21
+ };
22
+
23
+ const nodes = [];
24
+
25
+ // If the first ever valid text isnt a markup or comment, don't try to parse and return no nodes
26
+ const firstContentToken = tokens.find( token => !isComment( token ) && !isEmptyText( token ) );
27
+ if ( firstContentToken && !isOpeningTag( firstContentToken ) && !isClosingTag( firstContentToken ) && !isSelfClosingTag( firstContentToken ) ) {
28
+ return [];
29
+ }
30
+
31
+ for ( const token of tokens ) {
32
+ if ( isOpeningTag( token ) ) {
33
+ const { tagName, attributes } = extractTag( token );
34
+ if ( !state.currentNode ) {
35
+ state.currentNode = new Node( tagName, attributes );
36
+ } else {
37
+ if ( tagName === state.currentNode.tagName ) {
38
+ throw new ValidationError(
39
+ `Invalid child tag: <${tagName}> cannot appear inside another <${tagName}>. Escape it as "&lt;${tagName}&gt;".`
40
+ );
41
+ }
42
+ state.currentNode.content += token;
43
+ }
44
+ } else if ( isClosingTag( token ) ) {
45
+ if ( !state.currentNode ) {
46
+ throw new ValidationError( `Invalid root tag: closing tag "${token}" has no matching opening tag.` );
47
+ }
48
+ if ( extractTag( token ).tagName === state.currentNode.tagName ) {
49
+ nodes.push( state.currentNode );
50
+ state.currentNode = null;
51
+ } else {
52
+ state.currentNode.content += token;
53
+ }
54
+ } else {
55
+ if ( state.currentNode ) {
56
+ state.currentNode.content += token;
57
+ } else {
58
+ if ( isSelfClosingTag( token ) ) {
59
+ throw new ValidationError( `Invalid root tag: self-closing tag "${token}" is not allowed.` );
60
+ } else if ( !isComment( token ) && !isEmptyText( token ) ) {
61
+ throw new ValidationError( 'Invalid root text: text is not allowed outside message tags.' );
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ if ( state.currentNode ) {
68
+ throw new ValidationError( `Invalid tag: <${state.currentNode.tagName}> is missing its closing tag.` );
69
+ }
70
+ return nodes;
71
+ };
@@ -0,0 +1,3 @@
1
+ const tokenizer = /<!--[\s\S]*?-->|<\/\s*[A-Za-z][\w-]*\s*>|<[A-Za-z][\w-]*(?:"[^"]*"|'[^']*'|[^'"<>])*>|<[A-Za-z][\w-]*[^<>]*>|[^<]+|</g;
2
+
3
+ export const tokenize = value => value.match( tokenizer );
@@ -0,0 +1,26 @@
1
+ import { ValidationError } from '#errors';
2
+ import { extractAttributes } from './attributes.js';
3
+
4
+ export const extractTag = v => {
5
+ const capture = v.match( /^<\/?\s*([\w-]+)(?:\s+(.+?))?\s*>$/ );
6
+ if ( !capture ) {
7
+ throw new ValidationError( `Could not parse tag "${v}".` );
8
+ }
9
+ const [ name, rawAttributes ] = capture.slice( 1, 3 );
10
+ if ( !name ) {
11
+ throw new ValidationError( `Could not parse tag "${v}".` );
12
+ }
13
+ return {
14
+ tagName: name.toLowerCase(),
15
+ attributes: rawAttributes ? extractAttributes( rawAttributes ) : {}
16
+ };
17
+ };
18
+
19
+ const hasClosing = v => /\/\s*>$/.test( v );
20
+ const hasOpening = v => /^<[A-Za-z][\w-]*(?=\s|\/?>)[^<]*>$/.test( v );
21
+
22
+ export const isOpeningTag = v => hasOpening( v ) && !hasClosing( v );
23
+ export const isComment = v => v.startsWith( '<!--' ) && v.endsWith( '-->' ) && v.length >= 7 && !v.slice( 4, -3 ).includes( '-->' );
24
+ export const isSelfClosingTag = v => hasOpening( v ) && hasClosing( v );
25
+ export const isEmptyText = v => /^\s*$/.test( v );
26
+ export const isClosingTag = v => /^<\/\s*[A-Za-z]+[\w-]*\s*>$/.test( v );
@@ -0,0 +1,129 @@
1
+ import { z } from 'zod';
2
+ import { ValidationError } from '#errors';
3
+ import { Logger } from '#runtime_logger';
4
+ import { deprecatedProviderAliases } from '../deprecated_provider_aliases.js';
5
+ import { Role } from '../consts.js';
6
+
7
+ const log = Logger.createLogger( 'LLM' );
8
+
9
+ const handleDeprecatedKeys = prompt => {
10
+ const { config: { maxTokens, maxOutputTokens, provider } } = prompt;
11
+
12
+ // @TODO: maxTokens was replaced by maxOutputTokens in v0.12, it can be removed down the road
13
+ if ( Number.isFinite( maxTokens ) ) {
14
+ if ( Number.isFinite( maxOutputTokens ) ) {
15
+ log.warn( 'Prompt has both "maxOutputTokens" and deprecated "maxTokens" keys set, "maxTokens" value will be ignored.' );
16
+ } else {
17
+ log.warn( 'Prompt has deprecated key "maxTokens". Its value was set to "maxOutputTokens".' );
18
+ prompt.config.maxOutputTokens = maxTokens;
19
+ }
20
+ }
21
+
22
+ // @TODO: this handle aliases removal in v0.11, it can be removed down the road
23
+ if ( Object.hasOwn( deprecatedProviderAliases, provider ) ) {
24
+ const canonical = deprecatedProviderAliases[provider];
25
+ log.warn( `Prompt uses deprecated provider alias "${provider}". Use "${canonical}" instead.` );
26
+ prompt.config.provider = canonical;
27
+ }
28
+
29
+ return prompt;
30
+ };
31
+
32
+ const objectMapSchema = z.record(
33
+ z.string(),
34
+ z.record(
35
+ z.string(),
36
+ z.unknown()
37
+ )
38
+ );
39
+
40
+ const promptConfigSchema = z.object( {
41
+ aspectRatio: z.string().regex( /^\d+:\d+$/ ).optional(),
42
+ frequencyPenalty: z.number().optional(),
43
+ maxImagesPerCall: z.number().int().positive().optional(),
44
+ maxOutputTokens: z.number().int().positive().optional(),
45
+ maxSteps: z.number().int().positive().default( 10 ),
46
+ maxTokens: z.number().int().positive().optional(),
47
+ // A provider-namespaced options object, e.g. { anthropic: { cacheControl: { type: 'ephemeral' } } }
48
+ messageOptions: z.record( z.string(), objectMapSchema ).optional(),
49
+ model: z.string().min( 1 ),
50
+ n: z.number().int().positive().optional(),
51
+ presencePenalty: z.number().optional(),
52
+ provider: z.string().min( 1 ),
53
+ providerOptions: z.object( {
54
+ thinking: z.object( {
55
+ type: z.enum( [ 'enabled', 'disabled' ] ),
56
+ budgetTokens: z.number().optional()
57
+ } ).loose().optional()
58
+ } ).loose().optional(),
59
+ seed: z.number().int().optional(),
60
+ size: z.string().regex( /^\d+x\d+$/ ).optional(),
61
+ skills: z.preprocess( v => Array.isArray( v ) ? v : [].concat( v ?? [] ), z.array( z.string().min( 1 ) ) ),
62
+ stopSequences: z.array( z.string() ).optional(),
63
+ temperature: z.number().nonnegative().optional(),
64
+ topK: z.number().nonnegative().optional(),
65
+ topP: z.number().nonnegative().optional(),
66
+ tools: objectMapSchema.optional()
67
+ } ).strict();
68
+
69
+ export const promptSchema = z.object( {
70
+ name: z.string(),
71
+ config: promptConfigSchema,
72
+ messages: z.array(
73
+ z.object( {
74
+ role: z.enum( Object.values( Role ) ),
75
+ content: z.string(),
76
+ providerOptions: objectMapSchema.optional()
77
+ } ).strict()
78
+ ),
79
+ instructions: z.string().trim().min( 1 ).nullable().default( null ),
80
+ fileDir: z.string(),
81
+ variables: z.record( z.string(), z.unknown() ).default( {} )
82
+ } ).strict().superRefine( ( prompt, ctx ) => {
83
+ const hasMessages = prompt.messages.length > 0;
84
+ const hasInstructions = !!prompt.instructions;
85
+ const addIssue = message => ctx.addIssue( { code: 'custom', path: [ 'messages', 'instructions' ], message } );
86
+
87
+ if ( !hasMessages && !hasInstructions ) {
88
+ addIssue( 'Prompt must include either message blocks or plain instructions.' );
89
+ } else if ( hasMessages && hasInstructions ) {
90
+ addIssue( 'Prompt cannot include both message blocks and plain instructions.' );
91
+ }
92
+ } ).transform( handleDeprecatedKeys );
93
+
94
+ const promptConfigKeys = new Set( Object.keys( promptConfigSchema.shape ) );
95
+
96
+ /** Converts a string to camel case */
97
+ const toCamelCase = value => value.replace( /_([a-z])/g, ( _, letter ) => letter.toUpperCase() );
98
+
99
+ /** Appends camelCase suggestions to unrecognized top-level config keys written in snake_case. */
100
+ const appendCamelCaseSuggestions = error => {
101
+ for ( const issue of error.issues ) {
102
+ if ( issue.code !== 'unrecognized_keys' || issue.path.length !== 1 || issue.path[0] !== 'config' ) {
103
+ continue;
104
+ }
105
+
106
+ const suggestions = issue.keys
107
+ .filter( key => key.includes( '_' ) )
108
+ .map( key => ( { key, camel: toCamelCase( key ) } ) )
109
+ .filter( ( { key, camel } ) => camel !== key && promptConfigKeys.has( camel ) )
110
+ .map( ( { key, camel } ) => `"${key}" is not valid; use "${camel}"` );
111
+
112
+ if ( suggestions.length > 0 ) {
113
+ issue.message = `${issue.message}. ${suggestions.join( '. ' )}`;
114
+ }
115
+ }
116
+ };
117
+
118
+ export const parsePromptSchema = prompt => {
119
+ const result = promptSchema.safeParse( prompt );
120
+ if ( !result.success ) {
121
+ appendCamelCaseSuggestions( result.error );
122
+
123
+ throw new ValidationError(
124
+ `Invalid prompt file ${prompt.name}: ${z.prettifyError( result.error )}`,
125
+ { cause: result.error }
126
+ );
127
+ }
128
+ return result.data;
129
+ };