@riotprompt/riotprompt 0.0.8 → 0.0.10
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/.kodrdriv-test-cache.json +6 -0
- package/BUG-ANALYSIS.md +523 -0
- package/CODE-REVIEW-SUMMARY.md +330 -0
- package/FIXES-APPLIED.md +437 -0
- package/README.md +2 -2
- package/dist/builder.js +3 -0
- package/dist/builder.js.map +1 -1
- package/dist/chat.d.ts +1 -1
- package/dist/chat.js +2 -5
- package/dist/chat.js.map +1 -1
- package/dist/constants.js +1 -2
- package/dist/constants.js.map +1 -1
- package/dist/context-manager.d.ts +136 -0
- package/dist/context-manager.js +243 -0
- package/dist/context-manager.js.map +1 -0
- package/dist/conversation-logger.d.ts +285 -0
- package/dist/conversation-logger.js +491 -0
- package/dist/conversation-logger.js.map +1 -0
- package/dist/conversation.d.ts +277 -0
- package/dist/conversation.js +649 -0
- package/dist/conversation.js.map +1 -0
- package/dist/formatter.js.map +1 -1
- package/dist/items/section.js +3 -3
- package/dist/items/section.js.map +1 -1
- package/dist/iteration-strategy.d.ts +233 -0
- package/dist/iteration-strategy.js +520 -0
- package/dist/iteration-strategy.js.map +1 -0
- package/dist/loader.js +21 -3
- package/dist/loader.js.map +1 -1
- package/dist/message-builder.d.ts +156 -0
- package/dist/message-builder.js +256 -0
- package/dist/message-builder.js.map +1 -0
- package/dist/model-config.d.ts +115 -0
- package/dist/model-config.js +205 -0
- package/dist/model-config.js.map +1 -0
- package/dist/override.js +8 -1
- package/dist/override.js.map +1 -1
- package/dist/parser.js +3 -3
- package/dist/parser.js.map +1 -1
- package/dist/recipes.d.ts +42 -0
- package/dist/recipes.js +189 -4
- package/dist/recipes.js.map +1 -1
- package/dist/reflection.d.ts +250 -0
- package/dist/reflection.js +419 -0
- package/dist/reflection.js.map +1 -0
- package/dist/riotprompt.cjs +3854 -178
- package/dist/riotprompt.cjs.map +1 -1
- package/dist/riotprompt.d.ts +20 -2
- package/dist/riotprompt.js +10 -1
- package/dist/riotprompt.js.map +1 -1
- package/dist/token-budget.d.ts +177 -0
- package/dist/token-budget.js +401 -0
- package/dist/token-budget.js.map +1 -0
- package/dist/tools.d.ts +239 -0
- package/dist/tools.js +324 -0
- package/dist/tools.js.map +1 -0
- package/dist/util/general.js +1 -1
- package/dist/util/general.js.map +1 -1
- package/package.json +23 -20
package/dist/loader.js
CHANGED
|
@@ -10,6 +10,9 @@ import './parser.js';
|
|
|
10
10
|
import './override.js';
|
|
11
11
|
import './builder.js';
|
|
12
12
|
import './recipes.js';
|
|
13
|
+
import './conversation.js';
|
|
14
|
+
import 'tiktoken';
|
|
15
|
+
import './tools.js';
|
|
13
16
|
import { create as create$1 } from './util/storage.js';
|
|
14
17
|
|
|
15
18
|
const OptionsSchema = z.object({
|
|
@@ -60,7 +63,7 @@ const create = (loaderOptions)=>{
|
|
|
60
63
|
};
|
|
61
64
|
/**
|
|
62
65
|
* Loads context from the provided directories and returns instruction sections
|
|
63
|
-
*
|
|
66
|
+
*
|
|
64
67
|
* @param contextDirectories Directories containing context files
|
|
65
68
|
* @returns Array of instruction sections loaded from context directories
|
|
66
69
|
*/ const load = async (contextDirectories = [], options = {})=>{
|
|
@@ -112,8 +115,22 @@ const create = (loaderOptions)=>{
|
|
|
112
115
|
}
|
|
113
116
|
// Get all other files in the directory
|
|
114
117
|
const files = await storage.listFiles(contextDir);
|
|
115
|
-
const ignorePatternsRegex = ignorePatterns.map((pattern)=>
|
|
116
|
-
|
|
118
|
+
const ignorePatternsRegex = ignorePatterns.map((pattern)=>{
|
|
119
|
+
try {
|
|
120
|
+
return new RegExp(pattern, 'i');
|
|
121
|
+
} catch (error) {
|
|
122
|
+
logger.error(`Invalid ignore pattern: ${pattern}`, {
|
|
123
|
+
error
|
|
124
|
+
});
|
|
125
|
+
// Return a pattern that matches nothing
|
|
126
|
+
return /(?!)/; // Negative lookahead that always fails
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
const filteredFiles = files.filter((file)=>{
|
|
130
|
+
const fullPath = path__default.join(contextDir, file);
|
|
131
|
+
// Test against both filename and full path for flexibility
|
|
132
|
+
return !ignorePatternsRegex.some((regex)=>regex.test(file) || regex.test(fullPath));
|
|
133
|
+
});
|
|
117
134
|
for (const file of filteredFiles){
|
|
118
135
|
// Skip the context.md file as it's already processed
|
|
119
136
|
if (file === 'context.md') continue;
|
|
@@ -141,6 +158,7 @@ const create = (loaderOptions)=>{
|
|
|
141
158
|
...sectionOptions
|
|
142
159
|
});
|
|
143
160
|
// Add this file section to the main context section
|
|
161
|
+
// Type is correct - Section.add() accepts Section<T>
|
|
144
162
|
mainContextSection.add(fileSection, {
|
|
145
163
|
...sectionOptions
|
|
146
164
|
});
|
package/dist/loader.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.js","sources":["../src/loader.ts"],"sourcesContent":["import path from \"path\";\nimport { z } from \"zod\";\nimport { DEFAULT_IGNORE_PATTERNS } from \"./constants\";\nimport { ParametersSchema } from \"./items/parameters\";\nimport { SectionOptions, SectionOptionsSchema } from \"./items/section\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { Section, Weighted, createSection } from \"./riotprompt\";\nimport * as Storage from \"./util/storage\";\n\nconst OptionsSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n ignorePatterns: z.array(z.string()).optional().default(DEFAULT_IGNORE_PATTERNS),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type Options = z.infer<typeof OptionsSchema>;\n\nexport type OptionsParam = Partial<Options>;\n\nexport interface Instance {\n load: <T extends Weighted>(contextDirectories?: string[], options?: SectionOptions) => Promise<Section<T>[]>;\n}\n\n/**\n * Extracts the first header from Markdown text\n * @param markdownText The Markdown text to parse\n * @returns The first header found in the Markdown or null if none is found\n */\nexport function extractFirstHeader(markdownText: string): string | null {\n // Regular expression to match Markdown headers (# Header, ## Header, etc.)\n const headerRegex = /^(#{1,6})\\s+(.+?)(?:\\n|$)/m;\n const match = markdownText.match(headerRegex);\n\n if (match && match[2]) {\n return match[2].trim();\n }\n\n return null;\n}\n\n/**\n * Removes the first header from Markdown text\n * @param markdownText The Markdown text to process\n * @returns The Markdown text without the first header\n */\nexport function removeFirstHeader(markdownText: string): string {\n // Regular expression to match Markdown headers (# Header, ## Header, etc.)\n const headerRegex = /^(#{1,6})\\s+(.+?)(?:\\n|$)/m;\n const match = markdownText.match(headerRegex);\n\n if (match) {\n return markdownText.replace(headerRegex, '').trim();\n }\n\n return markdownText;\n}\n\nexport const create = (loaderOptions?: OptionsParam): Instance => {\n const options: Required<Options> = OptionsSchema.parse(loaderOptions || {}) as Required<Options>;\n const parameters = options.parameters;\n\n const logger = wrapLogger(options.logger, 'Loader');\n const ignorePatterns = options.ignorePatterns;\n\n const loadOptions = (sectionOptions: Partial<SectionOptions> = {}): SectionOptions => {\n const currentOptions = SectionOptionsSchema.parse(sectionOptions);\n return {\n ...currentOptions,\n parameters: {\n ...parameters,\n ...currentOptions.parameters\n }\n }\n }\n\n /**\n * Loads context from the provided directories and returns instruction sections\n * \n * @param contextDirectories Directories containing context files\n * @returns Array of instruction sections loaded from context directories\n */\n const load = async<T extends Weighted>(\n contextDirectories: string[] = [],\n options: Partial<SectionOptions> = {}\n ): Promise<Section<T>[]> => {\n const sectionOptions = loadOptions(options);\n\n logger.debug(`Loading context from ${contextDirectories}`);\n const contextSections: Section<T>[] = [];\n\n if (!contextDirectories || contextDirectories.length === 0) {\n logger.debug(`No context directories provided, returning empty context`);\n return contextSections;\n }\n\n const storage = Storage.create({ log: logger.debug });\n\n // Add context sections from each directory\n for (const contextDir of contextDirectories) {\n try {\n const dirName = path.basename(contextDir);\n logger.debug(`Processing context directory ${dirName}`);\n let mainContextSection: Section<T>;\n\n // First check if there's a context.md file\n const contextFile = path.join(contextDir, 'context.md');\n\n if (await storage.exists(contextFile)) {\n logger.debug(`Found context.md file in ${contextDir}`);\n const mainContextContent = await storage.readFile(contextFile, 'utf8');\n // Extract the first header from the Markdown content\n const firstHeader = extractFirstHeader(mainContextContent);\n\n // Use the header from context.md as the section title, or fallback to directory name\n const sectionTitle = firstHeader || dirName;\n mainContextSection = createSection<T>({ ...sectionOptions, title: sectionTitle });\n\n // Add content without the header\n if (firstHeader) {\n mainContextSection.add(removeFirstHeader(mainContextContent), { ...sectionOptions });\n } else {\n mainContextSection.add(mainContextContent, { ...sectionOptions });\n }\n } else {\n // If no context.md exists, use directory name as title\n mainContextSection = createSection<T>({ ...sectionOptions, title: dirName });\n }\n\n // Get all other files in the directory\n const files = await storage.listFiles(contextDir);\n const ignorePatternsRegex = ignorePatterns.map(pattern => new RegExp(pattern, 'i'));\n\n const filteredFiles = files.filter(file =>\n !ignorePatternsRegex.some(regex => regex.test(file))\n );\n\n for (const file of filteredFiles) {\n // Skip the context.md file as it's already processed\n if (file === 'context.md') continue;\n\n logger.debug(`Processing file ${file} in ${contextDir}`);\n const filePath = path.join(contextDir, file);\n if (await storage.isFile(filePath)) {\n const fileContent = await storage.readFile(filePath, 'utf8');\n let sectionName = file;\n let contentToAdd = fileContent;\n\n // Extract header if it exists\n if (file.endsWith('.md')) {\n const fileHeader = extractFirstHeader(fileContent);\n if (fileHeader) {\n sectionName = fileHeader;\n // Remove the header from the content\n contentToAdd = removeFirstHeader(fileContent);\n }\n }\n\n // Create a subsection with the extracted name\n const fileSection = createSection<T>({ ...sectionOptions, title: sectionName });\n fileSection.add(contentToAdd, { ...sectionOptions });\n\n // Add this file section to the main context section\n mainContextSection.add(fileSection as unknown as T, { ...sectionOptions });\n }\n }\n\n contextSections.push(mainContextSection);\n } catch (error) {\n logger.error(`Error processing context directory ${contextDir}: ${error}`);\n }\n }\n\n return contextSections;\n }\n\n\n return {\n load\n }\n}\n"],"names":["OptionsSchema","z","object","logger","any","optional","default","DEFAULT_LOGGER","ignorePatterns","array","string","DEFAULT_IGNORE_PATTERNS","parameters","ParametersSchema","extractFirstHeader","markdownText","headerRegex","match","trim","removeFirstHeader","replace","create","loaderOptions","options","parse","wrapLogger","loadOptions","sectionOptions","currentOptions","SectionOptionsSchema","load","contextDirectories","debug","contextSections","length","storage","Storage","log","contextDir","dirName","path","basename","mainContextSection","contextFile","join","exists","mainContextContent","readFile","firstHeader","sectionTitle","createSection","title","add","files","listFiles","ignorePatternsRegex","map","pattern","RegExp","filteredFiles","filter","file","some","regex","test","filePath","isFile","fileContent","sectionName","contentToAdd","endsWith","fileHeader","fileSection","push","error"],"mappings":";;;;;;;;;;;;;;AASA,MAAMA,aAAAA,GAAgBC,CAAAA,CAAEC,MAAM,CAAC;AAC3BC,IAAAA,MAAAA,EAAQF,EAAEG,GAAG,EAAA,CAAGC,QAAQ,EAAA,CAAGC,OAAO,CAACC,cAAAA,CAAAA;IACnCC,cAAAA,EAAgBP,CAAAA,CAAEQ,KAAK,CAACR,CAAAA,CAAES,MAAM,EAAA,CAAA,CAAIL,QAAQ,EAAA,CAAGC,OAAO,CAACK,uBAAAA,CAAAA;AACvDC,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBR,QAAQ,EAAA,CAAGC,OAAO,CAAC,EAAC;AACrD,CAAA,CAAA;AAUA;;;;IAKO,SAASQ,kBAAAA,CAAmBC,YAAoB,EAAA;;AAEnD,IAAA,MAAMC,WAAAA,GAAc,4BAAA;IACpB,MAAMC,KAAAA,GAAQF,YAAAA,CAAaE,KAAK,CAACD,WAAAA,CAAAA;AAEjC,IAAA,IAAIC,KAAAA,IAASA,KAAK,CAAC,CAAA,CAAE,EAAE;AACnB,QAAA,OAAOA,KAAK,CAAC,CAAA,CAAE,CAACC,IAAI,EAAA;AACxB,IAAA;IAEA,OAAO,IAAA;AACX;AAEA;;;;IAKO,SAASC,iBAAAA,CAAkBJ,YAAoB,EAAA;;AAElD,IAAA,MAAMC,WAAAA,GAAc,4BAAA;IACpB,MAAMC,KAAAA,GAAQF,YAAAA,CAAaE,KAAK,CAACD,WAAAA,CAAAA;AAEjC,IAAA,IAAIC,KAAAA,EAAO;AACP,QA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kBgD,WAAAA,CAAAA;AACrC,4BAAA;AACJ,wBAAA;;AAGA,wBAAA,MAAMK,cAActB,QAAAA,CAAiB;AAAE,4BAAA,GAAGvB,cAAc;4BAAEwB,KAAAA,EAAOiB;AAAY,yBAAA,CAAA;wBAC7EI,WAAAA,CAAYpB,GAAG,CAACiB,YAAAA,EAAc;AAAE,4BAAA,GAAG1C;AAAe,yBAAA,CAAA;;wBAGlDe,kBAAAA,CAAmBU,GAAG,CAACoB,WAAAA,EAA6B;AAAE,4BAAA,GAAG7C;AAAe,yBAAA,CAAA;AAC5E,oBAAA;AACJ,gBAAA;AAEAM,gBAAAA,eAAAA,CAAgBwC,IAAI,CAAC/B,kBAAAA,CAAAA;AACzB,YAAA,CAAA,CAAE,OAAOgC,KAAAA,EAAO;gBACZvE,MAAAA,CAAOuE,KAAK,CAAC,CAAC,mCAAmC,EAAEpC,UAAAA,CAAW,EAAE,EAAEoC,KAAAA,CAAAA,CAAO,CAAA;AAC7E,YAAA;AACJ,QAAA;QAEA,OAAOzC,eAAAA;AACX,IAAA,CAAA;IAGA,OAAO;AACHH,QAAAA;AACJ,KAAA;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"loader.js","sources":["../src/loader.ts"],"sourcesContent":["import path from \"path\";\nimport { z } from \"zod\";\nimport { DEFAULT_IGNORE_PATTERNS } from \"./constants\";\nimport { ParametersSchema } from \"./items/parameters\";\nimport { SectionOptions, SectionOptionsSchema } from \"./items/section\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { Section, Weighted, createSection } from \"./riotprompt\";\nimport * as Storage from \"./util/storage\";\n\nconst OptionsSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n ignorePatterns: z.array(z.string()).optional().default(DEFAULT_IGNORE_PATTERNS),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type Options = z.infer<typeof OptionsSchema>;\n\nexport type OptionsParam = Partial<Options>;\n\nexport interface Instance {\n load: <T extends Weighted>(contextDirectories?: string[], options?: SectionOptions) => Promise<Section<T>[]>;\n}\n\n/**\n * Extracts the first header from Markdown text\n * @param markdownText The Markdown text to parse\n * @returns The first header found in the Markdown or null if none is found\n */\nexport function extractFirstHeader(markdownText: string): string | null {\n // Regular expression to match Markdown headers (# Header, ## Header, etc.)\n const headerRegex = /^(#{1,6})\\s+(.+?)(?:\\n|$)/m;\n const match = markdownText.match(headerRegex);\n\n if (match && match[2]) {\n return match[2].trim();\n }\n\n return null;\n}\n\n/**\n * Removes the first header from Markdown text\n * @param markdownText The Markdown text to process\n * @returns The Markdown text without the first header\n */\nexport function removeFirstHeader(markdownText: string): string {\n // Regular expression to match Markdown headers (# Header, ## Header, etc.)\n const headerRegex = /^(#{1,6})\\s+(.+?)(?:\\n|$)/m;\n const match = markdownText.match(headerRegex);\n\n if (match) {\n return markdownText.replace(headerRegex, '').trim();\n }\n\n return markdownText;\n}\n\nexport const create = (loaderOptions?: OptionsParam): Instance => {\n const options: Required<Options> = OptionsSchema.parse(loaderOptions || {}) as Required<Options>;\n const parameters = options.parameters;\n\n const logger = wrapLogger(options.logger, 'Loader');\n const ignorePatterns = options.ignorePatterns;\n\n const loadOptions = (sectionOptions: Partial<SectionOptions> = {}): SectionOptions => {\n const currentOptions = SectionOptionsSchema.parse(sectionOptions);\n return {\n ...currentOptions,\n parameters: {\n ...parameters,\n ...currentOptions.parameters\n }\n }\n }\n\n /**\n * Loads context from the provided directories and returns instruction sections\n *\n * @param contextDirectories Directories containing context files\n * @returns Array of instruction sections loaded from context directories\n */\n const load = async<T extends Weighted>(\n contextDirectories: string[] = [],\n options: Partial<SectionOptions> = {}\n ): Promise<Section<T>[]> => {\n const sectionOptions = loadOptions(options);\n\n logger.debug(`Loading context from ${contextDirectories}`);\n const contextSections: Section<T>[] = [];\n\n if (!contextDirectories || contextDirectories.length === 0) {\n logger.debug(`No context directories provided, returning empty context`);\n return contextSections;\n }\n\n const storage = Storage.create({ log: logger.debug });\n\n // Add context sections from each directory\n for (const contextDir of contextDirectories) {\n try {\n const dirName = path.basename(contextDir);\n logger.debug(`Processing context directory ${dirName}`);\n let mainContextSection: Section<T>;\n\n // First check if there's a context.md file\n const contextFile = path.join(contextDir, 'context.md');\n\n if (await storage.exists(contextFile)) {\n logger.debug(`Found context.md file in ${contextDir}`);\n const mainContextContent = await storage.readFile(contextFile, 'utf8');\n // Extract the first header from the Markdown content\n const firstHeader = extractFirstHeader(mainContextContent);\n\n // Use the header from context.md as the section title, or fallback to directory name\n const sectionTitle = firstHeader || dirName;\n mainContextSection = createSection<T>({ ...sectionOptions, title: sectionTitle });\n\n // Add content without the header\n if (firstHeader) {\n mainContextSection.add(removeFirstHeader(mainContextContent), { ...sectionOptions });\n } else {\n mainContextSection.add(mainContextContent, { ...sectionOptions });\n }\n } else {\n // If no context.md exists, use directory name as title\n mainContextSection = createSection<T>({ ...sectionOptions, title: dirName });\n }\n\n // Get all other files in the directory\n const files = await storage.listFiles(contextDir);\n const ignorePatternsRegex = ignorePatterns.map(pattern => {\n try {\n return new RegExp(pattern, 'i');\n } catch (error) {\n logger.error(`Invalid ignore pattern: ${pattern}`, { error });\n // Return a pattern that matches nothing\n return /(?!)/; // Negative lookahead that always fails\n }\n });\n\n const filteredFiles = files.filter(file => {\n const fullPath = path.join(contextDir, file);\n // Test against both filename and full path for flexibility\n return !ignorePatternsRegex.some(regex => regex.test(file) || regex.test(fullPath));\n });\n\n for (const file of filteredFiles) {\n // Skip the context.md file as it's already processed\n if (file === 'context.md') continue;\n\n logger.debug(`Processing file ${file} in ${contextDir}`);\n const filePath = path.join(contextDir, file);\n if (await storage.isFile(filePath)) {\n const fileContent = await storage.readFile(filePath, 'utf8');\n let sectionName = file;\n let contentToAdd = fileContent;\n\n // Extract header if it exists\n if (file.endsWith('.md')) {\n const fileHeader = extractFirstHeader(fileContent);\n if (fileHeader) {\n sectionName = fileHeader;\n // Remove the header from the content\n contentToAdd = removeFirstHeader(fileContent);\n }\n }\n\n // Create a subsection with the extracted name\n const fileSection = createSection<T>({ ...sectionOptions, title: sectionName });\n fileSection.add(contentToAdd, { ...sectionOptions });\n\n // Add this file section to the main context section\n // Type is correct - Section.add() accepts Section<T>\n mainContextSection.add(fileSection, { ...sectionOptions });\n }\n }\n\n contextSections.push(mainContextSection);\n } catch (error) {\n logger.error(`Error processing context directory ${contextDir}: ${error}`);\n }\n }\n\n return contextSections;\n }\n\n\n return {\n load\n }\n}\n"],"names":["OptionsSchema","z","object","logger","any","optional","default","DEFAULT_LOGGER","ignorePatterns","array","string","DEFAULT_IGNORE_PATTERNS","parameters","ParametersSchema","extractFirstHeader","markdownText","headerRegex","match","trim","removeFirstHeader","replace","create","loaderOptions","options","parse","wrapLogger","loadOptions","sectionOptions","currentOptions","SectionOptionsSchema","load","contextDirectories","debug","contextSections","length","storage","Storage","log","contextDir","dirName","path","basename","mainContextSection","contextFile","join","exists","mainContextContent","readFile","firstHeader","sectionTitle","createSection","title","add","files","listFiles","ignorePatternsRegex","map","pattern","RegExp","error","filteredFiles","filter","file","fullPath","some","regex","test","filePath","isFile","fileContent","sectionName","contentToAdd","endsWith","fileHeader","fileSection","push"],"mappings":";;;;;;;;;;;;;;;;;AASA,MAAMA,aAAAA,GAAgBC,CAAAA,CAAEC,MAAM,CAAC;AAC3BC,IAAAA,MAAAA,EAAQF,EAAEG,GAAG,EAAA,CAAGC,QAAQ,EAAA,CAAGC,OAAO,CAACC,cAAAA,CAAAA;IACnCC,cAAAA,EAAgBP,CAAAA,CAAEQ,KAAK,CAACR,CAAAA,CAAES,MAAM,EAAA,CAAA,CAAIL,QAAQ,EAAA,CAAGC,OAAO,CAACK,uBAAAA,CAAAA;AACvDC,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBR,QAAQ,EAAA,CAAGC,OAAO,CAAC,EAAC;AACrD,CAAA,CAAA;AAUA;;;;IAKO,SAASQ,kBAAAA,CAAmBC,YAAoB,EAAA;;AAEnD,IAAA,MAAMC,WAAAA,GAAc,4BAAA;IACpB,MAAMC,KAAAA,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gBAAAA,eAAAA,CAAgB0C,IAAI,CAACjC,kBAAAA,CAAAA;AACzB,YAAA,CAAA,CAAE,OAAOiB,KAAAA,EAAO;gBACZxD,MAAAA,CAAOwD,KAAK,CAAC,CAAC,mCAAmC,EAAErB,UAAAA,CAAW,EAAE,EAAEqB,KAAAA,CAAAA,CAAO,CAAA;AAC7E,YAAA;AACJ,QAAA;QAEA,OAAO1B,eAAAA;AACX,IAAA,CAAA;IAGA,OAAO;AACHH,QAAAA;AACJ,KAAA;AACJ;;;;"}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { Model } from './chat';
|
|
2
|
+
import { Context } from './items/context';
|
|
3
|
+
import { Instruction } from './items/instruction';
|
|
4
|
+
import { Section } from './items/section';
|
|
5
|
+
import { ConversationMessage, ToolCall } from './conversation';
|
|
6
|
+
import * as Formatter from "./formatter";
|
|
7
|
+
/**
|
|
8
|
+
* Semantic message role
|
|
9
|
+
*/
|
|
10
|
+
export type SemanticRole = 'system' | 'user' | 'assistant' | 'tool' | 'developer';
|
|
11
|
+
/**
|
|
12
|
+
* Message metadata
|
|
13
|
+
*/
|
|
14
|
+
export interface MessageMetadata {
|
|
15
|
+
priority?: 'high' | 'medium' | 'low';
|
|
16
|
+
timestamp?: Date;
|
|
17
|
+
source?: string;
|
|
18
|
+
[key: string]: any;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* MessageBuilder provides semantic, type-safe message construction.
|
|
22
|
+
*
|
|
23
|
+
* Features:
|
|
24
|
+
* - Semantic message types (system, user, assistant, tool)
|
|
25
|
+
* - Model-specific role handling (system vs developer)
|
|
26
|
+
* - Structured content composition
|
|
27
|
+
* - Metadata attachment
|
|
28
|
+
* - Format-aware building
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* const message = MessageBuilder.system()
|
|
33
|
+
* .withContent('You are a helpful assistant')
|
|
34
|
+
* .withInstructions(instructionSection)
|
|
35
|
+
* .buildForModel('gpt-4o');
|
|
36
|
+
*
|
|
37
|
+
* const toolMessage = MessageBuilder.tool('call_123')
|
|
38
|
+
* .withResult(result)
|
|
39
|
+
* .withMetadata({ duration: 45 })
|
|
40
|
+
* .build();
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export declare class MessageBuilder {
|
|
44
|
+
private semanticRole;
|
|
45
|
+
private contentParts;
|
|
46
|
+
private metadata;
|
|
47
|
+
private formatter?;
|
|
48
|
+
private toolCallId?;
|
|
49
|
+
private toolCalls?;
|
|
50
|
+
private logger;
|
|
51
|
+
private constructor();
|
|
52
|
+
/**
|
|
53
|
+
* Create system message builder
|
|
54
|
+
*/
|
|
55
|
+
static system(logger?: any): MessageBuilder;
|
|
56
|
+
/**
|
|
57
|
+
* Create user message builder
|
|
58
|
+
*/
|
|
59
|
+
static user(logger?: any): MessageBuilder;
|
|
60
|
+
/**
|
|
61
|
+
* Create assistant message builder
|
|
62
|
+
*/
|
|
63
|
+
static assistant(logger?: any): MessageBuilder;
|
|
64
|
+
/**
|
|
65
|
+
* Create tool message builder
|
|
66
|
+
*/
|
|
67
|
+
static tool(callId: string, logger?: any): MessageBuilder;
|
|
68
|
+
/**
|
|
69
|
+
* Create developer message builder (for o1 models)
|
|
70
|
+
*/
|
|
71
|
+
static developer(logger?: any): MessageBuilder;
|
|
72
|
+
/**
|
|
73
|
+
* Add content to message
|
|
74
|
+
*/
|
|
75
|
+
withContent(content: string | Section<any>): this;
|
|
76
|
+
/**
|
|
77
|
+
* Add persona section (typically for system messages)
|
|
78
|
+
*/
|
|
79
|
+
withPersona(persona: Section<Instruction>): this;
|
|
80
|
+
/**
|
|
81
|
+
* Add instructions section
|
|
82
|
+
*/
|
|
83
|
+
withInstructions(instructions: Section<Instruction> | string[]): this;
|
|
84
|
+
/**
|
|
85
|
+
* Add context section
|
|
86
|
+
*/
|
|
87
|
+
withContext(context: Section<Context> | Array<{
|
|
88
|
+
content: string;
|
|
89
|
+
title?: string;
|
|
90
|
+
}>): this;
|
|
91
|
+
/**
|
|
92
|
+
* Set tool call ID (for tool messages)
|
|
93
|
+
*/
|
|
94
|
+
withCallId(id: string): this;
|
|
95
|
+
/**
|
|
96
|
+
* Set tool result (for tool messages)
|
|
97
|
+
*/
|
|
98
|
+
withResult(result: any): this;
|
|
99
|
+
/**
|
|
100
|
+
* Add tool calls (for assistant messages)
|
|
101
|
+
*/
|
|
102
|
+
withToolCalls(calls: ToolCall[]): this;
|
|
103
|
+
/**
|
|
104
|
+
* Add metadata
|
|
105
|
+
*/
|
|
106
|
+
withMetadata(metadata: Record<string, any>): this;
|
|
107
|
+
/**
|
|
108
|
+
* Add timestamp to metadata
|
|
109
|
+
*/
|
|
110
|
+
withTimestamp(): this;
|
|
111
|
+
/**
|
|
112
|
+
* Set priority in metadata
|
|
113
|
+
*/
|
|
114
|
+
withPriority(priority: 'high' | 'medium' | 'low'): this;
|
|
115
|
+
/**
|
|
116
|
+
* Set formatter for section rendering
|
|
117
|
+
*/
|
|
118
|
+
withFormatter(formatter: Formatter.Instance): this;
|
|
119
|
+
/**
|
|
120
|
+
* Build message with semantic role
|
|
121
|
+
*/
|
|
122
|
+
build(): ConversationMessage;
|
|
123
|
+
/**
|
|
124
|
+
* Build message with model-specific role
|
|
125
|
+
*/
|
|
126
|
+
buildForModel(model: Model): ConversationMessage;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Message template functions for common patterns
|
|
130
|
+
*/
|
|
131
|
+
export declare const MessageTemplates: {
|
|
132
|
+
/**
|
|
133
|
+
* System message for agentic tasks
|
|
134
|
+
*/
|
|
135
|
+
agenticSystem: (persona?: string, instructions?: string[]) => MessageBuilder;
|
|
136
|
+
/**
|
|
137
|
+
* User query with optional context
|
|
138
|
+
*/
|
|
139
|
+
userQuery: (query: string, context?: Array<{
|
|
140
|
+
content: string;
|
|
141
|
+
title?: string;
|
|
142
|
+
}>) => MessageBuilder;
|
|
143
|
+
/**
|
|
144
|
+
* Tool result with metadata
|
|
145
|
+
*/
|
|
146
|
+
toolResult: (callId: string, result: any, metadata?: Record<string, any>) => MessageBuilder;
|
|
147
|
+
/**
|
|
148
|
+
* Tool success result
|
|
149
|
+
*/
|
|
150
|
+
toolSuccess: (callId: string, result: any, duration?: number) => MessageBuilder;
|
|
151
|
+
/**
|
|
152
|
+
* Tool failure result
|
|
153
|
+
*/
|
|
154
|
+
toolFailure: (callId: string, error: Error) => MessageBuilder;
|
|
155
|
+
};
|
|
156
|
+
export default MessageBuilder;
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { wrapLogger, DEFAULT_LOGGER } from './logger.js';
|
|
2
|
+
import { create } from './formatter.js';
|
|
3
|
+
import { getPersonaRole } from './model-config.js';
|
|
4
|
+
|
|
5
|
+
function _define_property(obj, key, value) {
|
|
6
|
+
if (key in obj) {
|
|
7
|
+
Object.defineProperty(obj, key, {
|
|
8
|
+
value: value,
|
|
9
|
+
enumerable: true,
|
|
10
|
+
configurable: true,
|
|
11
|
+
writable: true
|
|
12
|
+
});
|
|
13
|
+
} else {
|
|
14
|
+
obj[key] = value;
|
|
15
|
+
}
|
|
16
|
+
return obj;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* MessageBuilder provides semantic, type-safe message construction.
|
|
20
|
+
*
|
|
21
|
+
* Features:
|
|
22
|
+
* - Semantic message types (system, user, assistant, tool)
|
|
23
|
+
* - Model-specific role handling (system vs developer)
|
|
24
|
+
* - Structured content composition
|
|
25
|
+
* - Metadata attachment
|
|
26
|
+
* - Format-aware building
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* const message = MessageBuilder.system()
|
|
31
|
+
* .withContent('You are a helpful assistant')
|
|
32
|
+
* .withInstructions(instructionSection)
|
|
33
|
+
* .buildForModel('gpt-4o');
|
|
34
|
+
*
|
|
35
|
+
* const toolMessage = MessageBuilder.tool('call_123')
|
|
36
|
+
* .withResult(result)
|
|
37
|
+
* .withMetadata({ duration: 45 })
|
|
38
|
+
* .build();
|
|
39
|
+
* ```
|
|
40
|
+
*/ class MessageBuilder {
|
|
41
|
+
/**
|
|
42
|
+
* Create system message builder
|
|
43
|
+
*/ static system(logger) {
|
|
44
|
+
return new MessageBuilder('system', logger);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Create user message builder
|
|
48
|
+
*/ static user(logger) {
|
|
49
|
+
return new MessageBuilder('user', logger);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Create assistant message builder
|
|
53
|
+
*/ static assistant(logger) {
|
|
54
|
+
return new MessageBuilder('assistant', logger);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Create tool message builder
|
|
58
|
+
*/ static tool(callId, logger) {
|
|
59
|
+
const builder = new MessageBuilder('tool', logger);
|
|
60
|
+
builder.toolCallId = callId;
|
|
61
|
+
return builder;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Create developer message builder (for o1 models)
|
|
65
|
+
*/ static developer(logger) {
|
|
66
|
+
return new MessageBuilder('developer', logger);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Add content to message
|
|
70
|
+
*/ withContent(content) {
|
|
71
|
+
if (typeof content === 'string') {
|
|
72
|
+
this.contentParts.push(content);
|
|
73
|
+
} else {
|
|
74
|
+
// Format section
|
|
75
|
+
const formatter$1 = this.formatter || create();
|
|
76
|
+
this.contentParts.push(formatter$1.format(content));
|
|
77
|
+
}
|
|
78
|
+
return this;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Add persona section (typically for system messages)
|
|
82
|
+
*/ withPersona(persona) {
|
|
83
|
+
const formatter$1 = this.formatter || create();
|
|
84
|
+
this.contentParts.push(formatter$1.format(persona));
|
|
85
|
+
return this;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Add instructions section
|
|
89
|
+
*/ withInstructions(instructions) {
|
|
90
|
+
if (Array.isArray(instructions)) {
|
|
91
|
+
this.contentParts.push(instructions.join('\n'));
|
|
92
|
+
} else {
|
|
93
|
+
const formatter$1 = this.formatter || create();
|
|
94
|
+
this.contentParts.push(formatter$1.format(instructions));
|
|
95
|
+
}
|
|
96
|
+
return this;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Add context section
|
|
100
|
+
*/ withContext(context) {
|
|
101
|
+
if (Array.isArray(context)) {
|
|
102
|
+
const contextStr = context.map((c)=>c.title ? `## ${c.title}\n\n${c.content}` : c.content).join('\n\n');
|
|
103
|
+
this.contentParts.push(contextStr);
|
|
104
|
+
} else {
|
|
105
|
+
const formatter$1 = this.formatter || create();
|
|
106
|
+
this.contentParts.push(formatter$1.format(context));
|
|
107
|
+
}
|
|
108
|
+
return this;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Set tool call ID (for tool messages)
|
|
112
|
+
*/ withCallId(id) {
|
|
113
|
+
this.toolCallId = id;
|
|
114
|
+
return this;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Set tool result (for tool messages)
|
|
118
|
+
*/ withResult(result) {
|
|
119
|
+
const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
|
|
120
|
+
this.contentParts.push(resultStr);
|
|
121
|
+
return this;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Add tool calls (for assistant messages)
|
|
125
|
+
*/ withToolCalls(calls) {
|
|
126
|
+
this.toolCalls = calls;
|
|
127
|
+
return this;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Add metadata
|
|
131
|
+
*/ withMetadata(metadata) {
|
|
132
|
+
this.metadata = {
|
|
133
|
+
...this.metadata,
|
|
134
|
+
...metadata
|
|
135
|
+
};
|
|
136
|
+
return this;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Add timestamp to metadata
|
|
140
|
+
*/ withTimestamp() {
|
|
141
|
+
this.metadata.timestamp = new Date();
|
|
142
|
+
return this;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Set priority in metadata
|
|
146
|
+
*/ withPriority(priority) {
|
|
147
|
+
this.metadata.priority = priority;
|
|
148
|
+
return this;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Set formatter for section rendering
|
|
152
|
+
*/ withFormatter(formatter) {
|
|
153
|
+
this.formatter = formatter;
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Build message with semantic role
|
|
158
|
+
*/ build() {
|
|
159
|
+
const content = this.contentParts.join('\n\n');
|
|
160
|
+
const message = {
|
|
161
|
+
role: this.semanticRole,
|
|
162
|
+
content: content || null
|
|
163
|
+
};
|
|
164
|
+
// Add tool-specific fields
|
|
165
|
+
if (this.semanticRole === 'tool' && this.toolCallId) {
|
|
166
|
+
message.tool_call_id = this.toolCallId;
|
|
167
|
+
}
|
|
168
|
+
if (this.toolCalls) {
|
|
169
|
+
message.tool_calls = this.toolCalls;
|
|
170
|
+
}
|
|
171
|
+
return message;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Build message with model-specific role
|
|
175
|
+
*/ buildForModel(model) {
|
|
176
|
+
const message = this.build();
|
|
177
|
+
// Handle model-specific role requirements
|
|
178
|
+
if (this.semanticRole === 'system') {
|
|
179
|
+
// Use model registry to determine correct role
|
|
180
|
+
const personaRole = getPersonaRole(model);
|
|
181
|
+
if (personaRole === 'developer') {
|
|
182
|
+
message.role = 'developer';
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return message;
|
|
186
|
+
}
|
|
187
|
+
constructor(role, logger){
|
|
188
|
+
_define_property(this, "semanticRole", void 0);
|
|
189
|
+
_define_property(this, "contentParts", void 0);
|
|
190
|
+
_define_property(this, "metadata", void 0);
|
|
191
|
+
_define_property(this, "formatter", void 0);
|
|
192
|
+
_define_property(this, "toolCallId", void 0);
|
|
193
|
+
_define_property(this, "toolCalls", void 0);
|
|
194
|
+
_define_property(this, "logger", void 0);
|
|
195
|
+
this.semanticRole = role;
|
|
196
|
+
this.contentParts = [];
|
|
197
|
+
this.metadata = {};
|
|
198
|
+
this.logger = wrapLogger(logger || DEFAULT_LOGGER, 'MessageBuilder');
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Message template functions for common patterns
|
|
203
|
+
*/ const MessageTemplates = {
|
|
204
|
+
/**
|
|
205
|
+
* System message for agentic tasks
|
|
206
|
+
*/ agenticSystem: (persona, instructions)=>{
|
|
207
|
+
const builder = MessageBuilder.system();
|
|
208
|
+
if (persona) {
|
|
209
|
+
builder.withContent(persona);
|
|
210
|
+
}
|
|
211
|
+
if (instructions) {
|
|
212
|
+
builder.withInstructions(instructions);
|
|
213
|
+
}
|
|
214
|
+
return builder;
|
|
215
|
+
},
|
|
216
|
+
/**
|
|
217
|
+
* User query with optional context
|
|
218
|
+
*/ userQuery: (query, context)=>{
|
|
219
|
+
const builder = MessageBuilder.user().withContent(query);
|
|
220
|
+
if (context) {
|
|
221
|
+
builder.withContext(context);
|
|
222
|
+
}
|
|
223
|
+
return builder;
|
|
224
|
+
},
|
|
225
|
+
/**
|
|
226
|
+
* Tool result with metadata
|
|
227
|
+
*/ toolResult: (callId, result, metadata)=>{
|
|
228
|
+
const builder = MessageBuilder.tool(callId).withResult(result).withTimestamp();
|
|
229
|
+
if (metadata) {
|
|
230
|
+
builder.withMetadata(metadata);
|
|
231
|
+
}
|
|
232
|
+
return builder;
|
|
233
|
+
},
|
|
234
|
+
/**
|
|
235
|
+
* Tool success result
|
|
236
|
+
*/ toolSuccess: (callId, result, duration)=>{
|
|
237
|
+
return MessageBuilder.tool(callId).withResult(result).withMetadata({
|
|
238
|
+
success: true,
|
|
239
|
+
duration
|
|
240
|
+
}).withTimestamp();
|
|
241
|
+
},
|
|
242
|
+
/**
|
|
243
|
+
* Tool failure result
|
|
244
|
+
*/ toolFailure: (callId, error)=>{
|
|
245
|
+
return MessageBuilder.tool(callId).withResult({
|
|
246
|
+
error: error.message,
|
|
247
|
+
stack: error.stack
|
|
248
|
+
}).withMetadata({
|
|
249
|
+
success: false,
|
|
250
|
+
errorName: error.name
|
|
251
|
+
}).withTimestamp();
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
export { MessageBuilder, MessageTemplates, MessageBuilder as default };
|
|
256
|
+
//# sourceMappingURL=message-builder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"message-builder.js","sources":["../src/message-builder.ts"],"sourcesContent":["import { Model } from \"./chat\";\nimport { Context } from \"./items/context\";\nimport { Instruction } from \"./items/instruction\";\nimport { Section } from \"./items/section\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport type { ConversationMessage, ToolCall } from \"./conversation\";\nimport * as Formatter from \"./formatter\";\nimport { getPersonaRole as getPersonaRoleFromRegistry } from \"./model-config\";\n\n// ===== TYPE DEFINITIONS =====\n\n/**\n * Semantic message role\n */\nexport type SemanticRole = 'system' | 'user' | 'assistant' | 'tool' | 'developer';\n\n/**\n * Message metadata\n */\nexport interface MessageMetadata {\n priority?: 'high' | 'medium' | 'low';\n timestamp?: Date;\n source?: string;\n [key: string]: any;\n}\n\n/**\n * MessageBuilder provides semantic, type-safe message construction.\n *\n * Features:\n * - Semantic message types (system, user, assistant, tool)\n * - Model-specific role handling (system vs developer)\n * - Structured content composition\n * - Metadata attachment\n * - Format-aware building\n *\n * @example\n * ```typescript\n * const message = MessageBuilder.system()\n * .withContent('You are a helpful assistant')\n * .withInstructions(instructionSection)\n * .buildForModel('gpt-4o');\n *\n * const toolMessage = MessageBuilder.tool('call_123')\n * .withResult(result)\n * .withMetadata({ duration: 45 })\n * .build();\n * ```\n */\nexport class MessageBuilder {\n private semanticRole: SemanticRole;\n private contentParts: string[];\n private metadata: MessageMetadata;\n private formatter?: Formatter.Instance;\n private toolCallId?: string;\n private toolCalls?: ToolCall[];\n private logger: any;\n\n private constructor(role: SemanticRole, logger?: any) {\n this.semanticRole = role;\n this.contentParts = [];\n this.metadata = {};\n this.logger = wrapLogger(logger || DEFAULT_LOGGER, 'MessageBuilder');\n }\n\n /**\n * Create system message builder\n */\n static system(logger?: any): MessageBuilder {\n return new MessageBuilder('system', logger);\n }\n\n /**\n * Create user message builder\n */\n static user(logger?: any): MessageBuilder {\n return new MessageBuilder('user', logger);\n }\n\n /**\n * Create assistant message builder\n */\n static assistant(logger?: any): MessageBuilder {\n return new MessageBuilder('assistant', logger);\n }\n\n /**\n * Create tool message builder\n */\n static tool(callId: string, logger?: any): MessageBuilder {\n const builder = new MessageBuilder('tool', logger);\n builder.toolCallId = callId;\n return builder;\n }\n\n /**\n * Create developer message builder (for o1 models)\n */\n static developer(logger?: any): MessageBuilder {\n return new MessageBuilder('developer', logger);\n }\n\n /**\n * Add content to message\n */\n withContent(content: string | Section<any>): this {\n if (typeof content === 'string') {\n this.contentParts.push(content);\n } else {\n // Format section\n const formatter = this.formatter || Formatter.create();\n this.contentParts.push(formatter.format(content));\n }\n return this;\n }\n\n /**\n * Add persona section (typically for system messages)\n */\n withPersona(persona: Section<Instruction>): this {\n const formatter = this.formatter || Formatter.create();\n this.contentParts.push(formatter.format(persona));\n return this;\n }\n\n /**\n * Add instructions section\n */\n withInstructions(instructions: Section<Instruction> | string[]): this {\n if (Array.isArray(instructions)) {\n this.contentParts.push(instructions.join('\\n'));\n } else {\n const formatter = this.formatter || Formatter.create();\n this.contentParts.push(formatter.format(instructions));\n }\n return this;\n }\n\n /**\n * Add context section\n */\n withContext(context: Section<Context> | Array<{ content: string; title?: string }>): this {\n if (Array.isArray(context)) {\n const contextStr = context.map(c =>\n c.title ? `## ${c.title}\\n\\n${c.content}` : c.content\n ).join('\\n\\n');\n this.contentParts.push(contextStr);\n } else {\n const formatter = this.formatter || Formatter.create();\n this.contentParts.push(formatter.format(context));\n }\n return this;\n }\n\n /**\n * Set tool call ID (for tool messages)\n */\n withCallId(id: string): this {\n this.toolCallId = id;\n return this;\n }\n\n /**\n * Set tool result (for tool messages)\n */\n withResult(result: any): this {\n const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);\n this.contentParts.push(resultStr);\n return this;\n }\n\n /**\n * Add tool calls (for assistant messages)\n */\n withToolCalls(calls: ToolCall[]): this {\n this.toolCalls = calls;\n return this;\n }\n\n /**\n * Add metadata\n */\n withMetadata(metadata: Record<string, any>): this {\n this.metadata = { ...this.metadata, ...metadata };\n return this;\n }\n\n /**\n * Add timestamp to metadata\n */\n withTimestamp(): this {\n this.metadata.timestamp = new Date();\n return this;\n }\n\n /**\n * Set priority in metadata\n */\n withPriority(priority: 'high' | 'medium' | 'low'): this {\n this.metadata.priority = priority;\n return this;\n }\n\n /**\n * Set formatter for section rendering\n */\n withFormatter(formatter: Formatter.Instance): this {\n this.formatter = formatter;\n return this;\n }\n\n /**\n * Build message with semantic role\n */\n build(): ConversationMessage {\n const content = this.contentParts.join('\\n\\n');\n\n const message: ConversationMessage = {\n role: this.semanticRole as any,\n content: content || null,\n };\n\n // Add tool-specific fields\n if (this.semanticRole === 'tool' && this.toolCallId) {\n message.tool_call_id = this.toolCallId;\n }\n\n if (this.toolCalls) {\n message.tool_calls = this.toolCalls;\n }\n\n return message;\n }\n\n /**\n * Build message with model-specific role\n */\n buildForModel(model: Model): ConversationMessage {\n const message = this.build();\n\n // Handle model-specific role requirements\n if (this.semanticRole === 'system') {\n // Use model registry to determine correct role\n const personaRole = getPersonaRoleFromRegistry(model);\n if (personaRole === 'developer') {\n message.role = 'developer' as any;\n }\n }\n\n return message;\n }\n}\n\n/**\n * Message template functions for common patterns\n */\nexport const MessageTemplates = {\n /**\n * System message for agentic tasks\n */\n agenticSystem: (persona?: string, instructions?: string[]) => {\n const builder = MessageBuilder.system();\n\n if (persona) {\n builder.withContent(persona);\n }\n\n if (instructions) {\n builder.withInstructions(instructions);\n }\n\n return builder;\n },\n\n /**\n * User query with optional context\n */\n userQuery: (query: string, context?: Array<{ content: string; title?: string }>) => {\n const builder = MessageBuilder.user().withContent(query);\n\n if (context) {\n builder.withContext(context);\n }\n\n return builder;\n },\n\n /**\n * Tool result with metadata\n */\n toolResult: (callId: string, result: any, metadata?: Record<string, any>) => {\n const builder = MessageBuilder.tool(callId)\n .withResult(result)\n .withTimestamp();\n\n if (metadata) {\n builder.withMetadata(metadata);\n }\n\n return builder;\n },\n\n /**\n * Tool success result\n */\n toolSuccess: (callId: string, result: any, duration?: number) => {\n return MessageBuilder.tool(callId)\n .withResult(result)\n .withMetadata({ success: true, duration })\n .withTimestamp();\n },\n\n /**\n * Tool failure result\n */\n toolFailure: (callId: string, error: Error) => {\n return MessageBuilder.tool(callId)\n .withResult({ error: error.message, stack: error.stack })\n .withMetadata({ success: false, errorName: error.name })\n .withTimestamp();\n },\n};\n\nexport default MessageBuilder;\n\n"],"names":["MessageBuilder","system","logger","user","assistant","tool","callId","builder","toolCallId","developer","withContent","content","contentParts","push","formatter","Formatter","format","withPersona","persona","withInstructions","instructions","Array","isArray","join","withContext","context","contextStr","map","c","title","withCallId","id","withResult","result","resultStr","JSON","stringify","withToolCalls","calls","toolCalls","withMetadata","metadata","withTimestamp","timestamp","Date","withPriority","priority","withFormatter","build","message","role","semanticRole","tool_call_id","tool_calls","buildForModel","model","personaRole","getPersonaRoleFromRegistry","wrapLogger","DEFAULT_LOGGER","MessageTemplates","agenticSystem","userQuery","query","toolResult","toolSuccess","duration","success","toolFailure","error","stack","errorName","name"],"mappings":";;;;;;;;;;;;;;;;;AA0BA;;;;;;;;;;;;;;;;;;;;;;AAsBC,IACM,MAAMA,cAAAA,CAAAA;AAgBT;;QAGA,OAAOC,MAAAA,CAAOC,MAAY,EAAkB;QACxC,OAAO,IAAIF,eAAe,QAAA,EAAUE,MAAAA,CAAAA;AACxC,IAAA;AAEA;;QAGA,OAAOC,IAAAA,CAAKD,MAAY,EAAkB;QACtC,OAAO,IAAIF,eAAe,MAAA,EAAQE,MAAAA,CAAAA;AACtC,IAAA;AAEA;;QAGA,OAAOE,SAAAA,CAAUF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