pika-shared 1.0.2 → 1.2.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.
@@ -0,0 +1,49 @@
1
+ import { InstructionAssistanceConfig, TagsChatAppOverridableFeature, AgentInstructionChatAppOverridableFeature, TagDefinition, TagDefinitionWidget } from '../types/chatbot/chatbot-types.mjs';
2
+ import '@aws-sdk/client-bedrock-agent-runtime';
3
+
4
+ /**
5
+ * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!
6
+ *
7
+ * The functions in this utility are used both by the front end svelte kit web client in the browser
8
+ * and in the backend lambda converse functions. So, that means it needs to be able
9
+ * to run in a browser. Do not add additional imports beyond anodine types.
10
+ *
11
+ * To be super clear: this is just logic to generate instruction assistance content given
12
+ * the right inputs. It does not collect up those inputs, it is given them.
13
+ *
14
+ */
15
+
16
+ /**
17
+ * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!
18
+ *
19
+ * See header at top of file for important notes.
20
+ *
21
+ * Generate instruction assistance content based on enabled features
22
+ *
23
+ * @param instructionAssistanceConfig - The instruction assistance configuration from SSM
24
+ * @param tags - The tags configuration from the chat app
25
+ * @param agentInstructionFeature - The agent instruction feature configuration from the chat app
26
+ * @returns The instruction assistance content
27
+ */
28
+ declare function generateInstructionAssistanceContent(instructionAssistanceConfig: InstructionAssistanceConfig | undefined, tags: TagsChatAppOverridableFeature | undefined, agentInstructionFeature: AgentInstructionChatAppOverridableFeature | undefined, tagDefinitions: TagDefinition<TagDefinitionWidget>[]): InstructionAssistanceConfig;
29
+ /**
30
+ * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!
31
+ *
32
+ * See header at top of file for important notes.
33
+ *
34
+ * Apply instruction assistance to the base prompt using placeholder replacement
35
+ */
36
+ declare function applyInstructionAssistance(basePrompt: string, instructionContent: InstructionAssistanceConfig): string;
37
+ /**
38
+ * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!
39
+ *
40
+ * See header at top of file for important notes.
41
+ *
42
+ * Get the instruction assistance configuration from raw SSM parameters
43
+ *
44
+ * @param params - The raw SSM parameters
45
+ * @returns The instruction assistance configuration
46
+ */
47
+ declare function getInstructionsAssistanceConfigFromRawSsmParams(params: Record<string, string>): InstructionAssistanceConfig;
48
+
49
+ export { applyInstructionAssistance, generateInstructionAssistanceContent, getInstructionsAssistanceConfigFromRawSsmParams };
@@ -0,0 +1,49 @@
1
+ import { InstructionAssistanceConfig, TagsChatAppOverridableFeature, AgentInstructionChatAppOverridableFeature, TagDefinition, TagDefinitionWidget } from '../types/chatbot/chatbot-types.js';
2
+ import '@aws-sdk/client-bedrock-agent-runtime';
3
+
4
+ /**
5
+ * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!
6
+ *
7
+ * The functions in this utility are used both by the front end svelte kit web client in the browser
8
+ * and in the backend lambda converse functions. So, that means it needs to be able
9
+ * to run in a browser. Do not add additional imports beyond anodine types.
10
+ *
11
+ * To be super clear: this is just logic to generate instruction assistance content given
12
+ * the right inputs. It does not collect up those inputs, it is given them.
13
+ *
14
+ */
15
+
16
+ /**
17
+ * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!
18
+ *
19
+ * See header at top of file for important notes.
20
+ *
21
+ * Generate instruction assistance content based on enabled features
22
+ *
23
+ * @param instructionAssistanceConfig - The instruction assistance configuration from SSM
24
+ * @param tags - The tags configuration from the chat app
25
+ * @param agentInstructionFeature - The agent instruction feature configuration from the chat app
26
+ * @returns The instruction assistance content
27
+ */
28
+ declare function generateInstructionAssistanceContent(instructionAssistanceConfig: InstructionAssistanceConfig | undefined, tags: TagsChatAppOverridableFeature | undefined, agentInstructionFeature: AgentInstructionChatAppOverridableFeature | undefined, tagDefinitions: TagDefinition<TagDefinitionWidget>[]): InstructionAssistanceConfig;
29
+ /**
30
+ * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!
31
+ *
32
+ * See header at top of file for important notes.
33
+ *
34
+ * Apply instruction assistance to the base prompt using placeholder replacement
35
+ */
36
+ declare function applyInstructionAssistance(basePrompt: string, instructionContent: InstructionAssistanceConfig): string;
37
+ /**
38
+ * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!
39
+ *
40
+ * See header at top of file for important notes.
41
+ *
42
+ * Get the instruction assistance configuration from raw SSM parameters
43
+ *
44
+ * @param params - The raw SSM parameters
45
+ * @returns The instruction assistance configuration
46
+ */
47
+ declare function getInstructionsAssistanceConfigFromRawSsmParams(params: Record<string, string>): InstructionAssistanceConfig;
48
+
49
+ export { applyInstructionAssistance, generateInstructionAssistanceContent, getInstructionsAssistanceConfigFromRawSsmParams };
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+
3
+ // src/util/instruction-assistance-utils.ts
4
+ function generateInstructionAssistanceContent(instructionAssistanceConfig, tags, agentInstructionFeature, tagDefinitions) {
5
+ console.log("Generating instruction assistance content:", {
6
+ enabled: agentInstructionFeature?.enabled,
7
+ includeOutputFormattingRequirements: agentInstructionFeature?.includeOutputFormattingRequirements,
8
+ includeInstructionsForTags: agentInstructionFeature?.includeInstructionsForTags,
9
+ completeExampleEnabled: agentInstructionFeature?.completeExampleInstructionEnabled,
10
+ jsonOnlyEnabled: agentInstructionFeature?.jsonOnlyImperativeInstructionEnabled
11
+ });
12
+ let outputFormattingRequirements = "";
13
+ let tagInstructions = "";
14
+ let completeExampleInstructionLine = "";
15
+ let jsonOnlyImperativeInstructionLine = "";
16
+ if (!agentInstructionFeature?.enabled) {
17
+ return {
18
+ outputFormattingRequirements,
19
+ tagInstructions,
20
+ completeExampleInstructionLine,
21
+ jsonOnlyImperativeInstructionLine
22
+ };
23
+ }
24
+ if (agentInstructionFeature.includeOutputFormattingRequirements) {
25
+ outputFormattingRequirements = instructionAssistanceConfig?.outputFormattingRequirements || `**Output Formatting Requirements:**
26
+ - **Output Response Enclosure**: All response output MUST be completely enclosed within <answer></answer> tags, including supported custom tags.
27
+ - **Output Content Format:** All responses MUST be in Markdown with supported custom tags.`;
28
+ }
29
+ if (agentInstructionFeature.includeInstructionsForTags && tags && tags.tagsEnabled?.length > 0) {
30
+ console.log("Fetching tag definitions for instruction generation:", tags.tagsEnabled);
31
+ if (tagDefinitions.length > 0) {
32
+ const tagDictionary = tagDefinitions.filter((tagDef) => tagDef.canBeGeneratedByLlm && !tagDef.disabled).map((tagDef) => ` - ${tagDef.tagTitle}: \`${tagDef.shortTagEx}\``).join("\n");
33
+ let tagInstructionsContent = "";
34
+ if (tagDictionary) {
35
+ tagInstructionsContent += `- **Custom Tags Supported:**
36
+ ${tagDictionary}
37
+ `;
38
+ }
39
+ for (const tagDef of tagDefinitions) {
40
+ if (tagDef.canBeGeneratedByLlm && !tagDef.disabled && tagDef.llmInstructionsMd) {
41
+ const tagType = `${tagDef.scope}.${tagDef.tag}`;
42
+ tagInstructionsContent += `- **${tagDef.tagTitle}:**
43
+ <tag-instructions type="${tagType}">
44
+ ${tagDef.llmInstructionsMd}
45
+ </tag-instructions>
46
+ `;
47
+ }
48
+ }
49
+ if (tagInstructionsContent) {
50
+ tagInstructions = tagInstructionsContent;
51
+ }
52
+ }
53
+ }
54
+ if (agentInstructionFeature.completeExampleInstructionEnabled) {
55
+ completeExampleInstructionLine = agentInstructionFeature.completeExampleInstructionLine || instructionAssistanceConfig?.completeExampleInstructionLine || "- **Complete Example Output:**\n `<answer>##Example markdown\nNormal text and an <image>http://some.url</image> and some **bold text**\n<chart>(...)</chart></answer>`";
56
+ }
57
+ if (agentInstructionFeature.jsonOnlyImperativeInstructionEnabled) {
58
+ jsonOnlyImperativeInstructionLine = agentInstructionFeature.jsonOnlyImperativeInstructionLine || instructionAssistanceConfig?.jsonOnlyImperativeInstructionLine || "BE ABSOLUTELY CERTAIN ANY JSON INCLUDED IS 100% VALID (especially for charts). Invalid JSON will break the user experience.";
59
+ }
60
+ console.log("Generated instruction assistance content:", {
61
+ hasOutputFormatting: !!outputFormattingRequirements,
62
+ hasTagInstructions: !!tagInstructions,
63
+ hasCompleteExample: !!completeExampleInstructionLine,
64
+ hasJsonValidation: !!jsonOnlyImperativeInstructionLine
65
+ });
66
+ return {
67
+ outputFormattingRequirements,
68
+ tagInstructions,
69
+ completeExampleInstructionLine,
70
+ jsonOnlyImperativeInstructionLine
71
+ };
72
+ }
73
+ function applyInstructionAssistance(basePrompt, instructionContent) {
74
+ let enhancedPrompt = basePrompt;
75
+ if (enhancedPrompt.includes("{{prompt-assistance}}")) {
76
+ console.log("Found {{prompt-assistance}} placeholder");
77
+ const allContent = [
78
+ instructionContent.outputFormattingRequirements,
79
+ instructionContent.tagInstructions,
80
+ instructionContent.completeExampleInstructionLine,
81
+ instructionContent.jsonOnlyImperativeInstructionLine
82
+ ].filter((content) => content && content.trim().length > 0).join("\n\n");
83
+ enhancedPrompt = enhancedPrompt.replace("{{prompt-assistance}}", allContent);
84
+ } else {
85
+ const placeholders = [
86
+ { placeholder: "{{output-formatting-requirements}}", content: instructionContent.outputFormattingRequirements },
87
+ { placeholder: "{{tag-instructions}}", content: instructionContent.tagInstructions },
88
+ { placeholder: "{{complete-example-instruction-line}}", content: instructionContent.completeExampleInstructionLine },
89
+ { placeholder: "{{json-only-imperative-instruction-line}}", content: instructionContent.jsonOnlyImperativeInstructionLine }
90
+ ];
91
+ let hasAnyPlaceholder = false;
92
+ for (const { placeholder, content } of placeholders) {
93
+ if (enhancedPrompt.includes(placeholder) && content) {
94
+ console.log(`Found ${placeholder} placeholder`);
95
+ hasAnyPlaceholder = true;
96
+ enhancedPrompt = enhancedPrompt.replace(placeholder, content);
97
+ }
98
+ }
99
+ if (!hasAnyPlaceholder) {
100
+ console.log("No placeholders found, appending to end of prompt");
101
+ const allContent = [
102
+ instructionContent.outputFormattingRequirements,
103
+ instructionContent.tagInstructions,
104
+ instructionContent.completeExampleInstructionLine,
105
+ instructionContent.jsonOnlyImperativeInstructionLine
106
+ ].filter((content) => content && content.trim().length > 0);
107
+ if (allContent.length > 0) {
108
+ enhancedPrompt = enhancedPrompt + "\n\n" + allContent.join("\n\n");
109
+ }
110
+ }
111
+ }
112
+ return enhancedPrompt;
113
+ }
114
+ function getInstructionsAssistanceConfigFromRawSsmParams(params) {
115
+ const expectedKeys = ["output-formatting-requirements", "default-complete-example-line", "default-json-validation-line"];
116
+ const missingKeys = expectedKeys.filter((key) => !params[key]);
117
+ if (missingKeys.length > 0) {
118
+ throw new Error(
119
+ `Missing required instruction assistance parameters: ${Object.keys(params).filter((key) => !expectedKeys.includes(key)).join(", ")}`
120
+ );
121
+ }
122
+ return {
123
+ outputFormattingRequirements: params["output-formatting-requirements"],
124
+ completeExampleInstructionLine: params["default-complete-example-line"],
125
+ jsonOnlyImperativeInstructionLine: params["default-json-validation-line"]
126
+ };
127
+ }
128
+
129
+ exports.applyInstructionAssistance = applyInstructionAssistance;
130
+ exports.generateInstructionAssistanceContent = generateInstructionAssistanceContent;
131
+ exports.getInstructionsAssistanceConfigFromRawSsmParams = getInstructionsAssistanceConfigFromRawSsmParams;
132
+ //# sourceMappingURL=instruction-assistance-utils.js.map
133
+ //# sourceMappingURL=instruction-assistance-utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/instruction-assistance-utils.ts"],"names":[],"mappings":";;;AAgCO,SAAS,oCACZ,CAAA,2BAAA,EACA,IACA,EAAA,uBAAA,EACA,cAC2B,EAAA;AAC3B,EAAA,OAAA,CAAQ,IAAI,4CAA8C,EAAA;AAAA,IACtD,SAAS,uBAAyB,EAAA,OAAA;AAAA,IAClC,qCAAqC,uBAAyB,EAAA,mCAAA;AAAA,IAC9D,4BAA4B,uBAAyB,EAAA,0BAAA;AAAA,IACrD,wBAAwB,uBAAyB,EAAA,iCAAA;AAAA,IACjD,iBAAiB,uBAAyB,EAAA;AAAA,GAC7C,CAAA;AAED,EAAA,IAAI,4BAA+B,GAAA,EAAA;AACnC,EAAA,IAAI,eAAkB,GAAA,EAAA;AACtB,EAAA,IAAI,8BAAiC,GAAA,EAAA;AACrC,EAAA,IAAI,iCAAoC,GAAA,EAAA;AAExC,EAAI,IAAA,CAAC,yBAAyB,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AAA,GAAiB,cAAiB,GAAA,MAAA,GAAS,UAAW,CAAA,IAAA,CAAK,MAAM,CAAA;AAAA;AACrE;AACJ;AAGJ,EAAO,OAAA,cAAA;AACX;AAYO,SAAS,gDAAgD,MAA6D,EAAA;AACzH,EAAA,MAAM,YAAe,GAAA,CAAC,gCAAkC,EAAA,+BAAA,EAAiC,8BAA8B,CAAA;AACvH,EAAM,MAAA,WAAA,GAAc,aAAa,MAAO,CAAA,CAAC,QAAQ,CAAC,MAAA,CAAO,GAAG,CAAC,CAAA;AAC7D,EAAI,IAAA,WAAA,CAAY,SAAS,CAAG,EAAA;AACxB,IAAA,MAAM,IAAI,KAAA;AAAA,MACN,uDAAuD,MAAO,CAAA,IAAA,CAAK,MAAM,CAAA,CACpE,OAAO,CAAC,GAAA,KAAQ,CAAC,YAAA,CAAa,SAAS,GAAG,CAAC,CAC3C,CAAA,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,KACnB;AAAA;AAGJ,EAAO,OAAA;AAAA,IACH,4BAAA,EAA8B,OAAO,gCAAgC,CAAA;AAAA,IACrE,8BAAA,EAAgC,OAAO,+BAA+B,CAAA;AAAA,IACtE,iCAAA,EAAmC,OAAO,8BAA8B;AAAA,GAC5E;AACJ","file":"instruction-assistance-utils.js","sourcesContent":["/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * The functions in this utility are used both by the front end svelte kit web client in the browser\n * and in the backend lambda converse functions. So, that means it needs to be able\n * to run in a browser. Do not add additional imports beyond anodine types.\n *\n * To be super clear: this is just logic to generate instruction assistance content given\n * the right inputs. It does not collect up those inputs, it is given them.\n *\n */\n\nimport type {\n AgentInstructionChatAppOverridableFeature,\n InstructionAssistanceConfig,\n TagDefinition,\n TagDefinitionWidget,\n TagsChatAppOverridableFeature\n} from '../types/chatbot/chatbot-types';\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Generate instruction assistance content based on enabled features\n *\n * @param instructionAssistanceConfig - The instruction assistance configuration from SSM\n * @param tags - The tags configuration from the chat app\n * @param agentInstructionFeature - The agent instruction feature configuration from the chat app\n * @returns The instruction assistance content\n */\nexport function generateInstructionAssistanceContent(\n instructionAssistanceConfig: InstructionAssistanceConfig | undefined,\n tags: TagsChatAppOverridableFeature | undefined,\n agentInstructionFeature: AgentInstructionChatAppOverridableFeature | undefined,\n tagDefinitions: TagDefinition<TagDefinitionWidget>[]\n): InstructionAssistanceConfig {\n console.log('Generating instruction assistance content:', {\n enabled: agentInstructionFeature?.enabled,\n includeOutputFormattingRequirements: agentInstructionFeature?.includeOutputFormattingRequirements,\n includeInstructionsForTags: agentInstructionFeature?.includeInstructionsForTags,\n completeExampleEnabled: agentInstructionFeature?.completeExampleInstructionEnabled,\n jsonOnlyEnabled: agentInstructionFeature?.jsonOnlyImperativeInstructionEnabled\n });\n\n let outputFormattingRequirements = '';\n let tagInstructions = '';\n let completeExampleInstructionLine = '';\n let jsonOnlyImperativeInstructionLine = '';\n\n if (!agentInstructionFeature?.enabled) {\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n }\n\n // Generate output formatting requirements\n if (agentInstructionFeature.includeOutputFormattingRequirements) {\n outputFormattingRequirements =\n instructionAssistanceConfig?.outputFormattingRequirements ||\n `**Output Formatting Requirements:**\n- **Output Response Enclosure**: All response output MUST be completely enclosed within <answer></answer> tags, including supported custom tags.\n- **Output Content Format:** All responses MUST be in Markdown with supported custom tags.`;\n }\n\n // Generate tag instructions\n if (agentInstructionFeature.includeInstructionsForTags && tags && tags.tagsEnabled?.length > 0) {\n console.log('Fetching tag definitions for instruction generation:', tags.tagsEnabled);\n\n if (tagDefinitions.length > 0) {\n // First create a dictionary listing all supported tags\n const tagDictionary = tagDefinitions\n .filter((tagDef) => tagDef.canBeGeneratedByLlm && !tagDef.disabled)\n .map((tagDef) => ` - ${tagDef.tagTitle}: \\`${tagDef.shortTagEx}\\``)\n .join('\\n');\n\n let tagInstructionsContent = '';\n if (tagDictionary) {\n tagInstructionsContent += `- **Custom Tags Supported:**\\n${tagDictionary}\\n`;\n }\n\n // Then add detailed instructions for each tag\n for (const tagDef of tagDefinitions) {\n if (tagDef.canBeGeneratedByLlm && !tagDef.disabled && tagDef.llmInstructionsMd) {\n const tagType = `${tagDef.scope}.${tagDef.tag}`;\n tagInstructionsContent += `- **${tagDef.tagTitle}:**\\n <tag-instructions type=\"${tagType}\">\\n${tagDef.llmInstructionsMd}\\n </tag-instructions>\\n`;\n }\n }\n\n if (tagInstructionsContent) {\n tagInstructions = tagInstructionsContent;\n }\n }\n }\n\n // Generate complete example instruction line\n if (agentInstructionFeature.completeExampleInstructionEnabled) {\n completeExampleInstructionLine =\n agentInstructionFeature.completeExampleInstructionLine ||\n instructionAssistanceConfig?.completeExampleInstructionLine ||\n '- **Complete Example Output:**\\n `<answer>##Example markdown\\nNormal text and an <image>http://some.url</image> and some **bold text**\\n<chart>(...)</chart></answer>`';\n }\n\n // Generate JSON validation instruction line\n if (agentInstructionFeature.jsonOnlyImperativeInstructionEnabled) {\n jsonOnlyImperativeInstructionLine =\n agentInstructionFeature.jsonOnlyImperativeInstructionLine ||\n instructionAssistanceConfig?.jsonOnlyImperativeInstructionLine ||\n 'BE ABSOLUTELY CERTAIN ANY JSON INCLUDED IS 100% VALID (especially for charts). Invalid JSON will break the user experience.';\n }\n\n console.log('Generated instruction assistance content:', {\n hasOutputFormatting: !!outputFormattingRequirements,\n hasTagInstructions: !!tagInstructions,\n hasCompleteExample: !!completeExampleInstructionLine,\n hasJsonValidation: !!jsonOnlyImperativeInstructionLine\n });\n\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Apply instruction assistance to the base prompt using placeholder replacement\n */\nexport function applyInstructionAssistance(basePrompt: string, instructionContent: InstructionAssistanceConfig): string {\n let enhancedPrompt = basePrompt;\n\n // Check for primary placeholder first\n if (enhancedPrompt.includes('{{prompt-assistance}}')) {\n console.log('Found {{prompt-assistance}} placeholder');\n\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ]\n .filter((content) => content && content.trim().length > 0)\n .join('\\n\\n');\n\n enhancedPrompt = enhancedPrompt.replace('{{prompt-assistance}}', allContent);\n } else {\n // Look for fine-grained placeholders\n const placeholders = [\n { placeholder: '{{output-formatting-requirements}}', content: instructionContent.outputFormattingRequirements },\n { placeholder: '{{tag-instructions}}', content: instructionContent.tagInstructions },\n { placeholder: '{{complete-example-instruction-line}}', content: instructionContent.completeExampleInstructionLine },\n { placeholder: '{{json-only-imperative-instruction-line}}', content: instructionContent.jsonOnlyImperativeInstructionLine }\n ];\n\n let hasAnyPlaceholder = false;\n for (const { placeholder, content } of placeholders) {\n if (enhancedPrompt.includes(placeholder) && content) {\n console.log(`Found ${placeholder} placeholder`);\n hasAnyPlaceholder = true;\n enhancedPrompt = enhancedPrompt.replace(placeholder, content);\n }\n }\n\n // If no placeholders found, append to end\n if (!hasAnyPlaceholder) {\n console.log('No placeholders found, appending to end of prompt');\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ].filter((content) => content && content.trim().length > 0);\n\n if (allContent.length > 0) {\n enhancedPrompt = enhancedPrompt + '\\n\\n' + allContent.join('\\n\\n');\n }\n }\n }\n\n return enhancedPrompt;\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Get the instruction assistance configuration from raw SSM parameters\n *\n * @param params - The raw SSM parameters\n * @returns The instruction assistance configuration\n */\nexport function getInstructionsAssistanceConfigFromRawSsmParams(params: Record<string, string>): InstructionAssistanceConfig {\n const expectedKeys = ['output-formatting-requirements', 'default-complete-example-line', 'default-json-validation-line'];\n const missingKeys = expectedKeys.filter((key) => !params[key]);\n if (missingKeys.length > 0) {\n throw new Error(\n `Missing required instruction assistance parameters: ${Object.keys(params)\n .filter((key) => !expectedKeys.includes(key))\n .join(', ')}`\n );\n }\n\n return {\n outputFormattingRequirements: params['output-formatting-requirements'],\n completeExampleInstructionLine: params['default-complete-example-line'],\n jsonOnlyImperativeInstructionLine: params['default-json-validation-line']\n };\n}\n"]}
@@ -0,0 +1,129 @@
1
+ // src/util/instruction-assistance-utils.ts
2
+ function generateInstructionAssistanceContent(instructionAssistanceConfig, tags, agentInstructionFeature, tagDefinitions) {
3
+ console.log("Generating instruction assistance content:", {
4
+ enabled: agentInstructionFeature?.enabled,
5
+ includeOutputFormattingRequirements: agentInstructionFeature?.includeOutputFormattingRequirements,
6
+ includeInstructionsForTags: agentInstructionFeature?.includeInstructionsForTags,
7
+ completeExampleEnabled: agentInstructionFeature?.completeExampleInstructionEnabled,
8
+ jsonOnlyEnabled: agentInstructionFeature?.jsonOnlyImperativeInstructionEnabled
9
+ });
10
+ let outputFormattingRequirements = "";
11
+ let tagInstructions = "";
12
+ let completeExampleInstructionLine = "";
13
+ let jsonOnlyImperativeInstructionLine = "";
14
+ if (!agentInstructionFeature?.enabled) {
15
+ return {
16
+ outputFormattingRequirements,
17
+ tagInstructions,
18
+ completeExampleInstructionLine,
19
+ jsonOnlyImperativeInstructionLine
20
+ };
21
+ }
22
+ if (agentInstructionFeature.includeOutputFormattingRequirements) {
23
+ outputFormattingRequirements = instructionAssistanceConfig?.outputFormattingRequirements || `**Output Formatting Requirements:**
24
+ - **Output Response Enclosure**: All response output MUST be completely enclosed within <answer></answer> tags, including supported custom tags.
25
+ - **Output Content Format:** All responses MUST be in Markdown with supported custom tags.`;
26
+ }
27
+ if (agentInstructionFeature.includeInstructionsForTags && tags && tags.tagsEnabled?.length > 0) {
28
+ console.log("Fetching tag definitions for instruction generation:", tags.tagsEnabled);
29
+ if (tagDefinitions.length > 0) {
30
+ const tagDictionary = tagDefinitions.filter((tagDef) => tagDef.canBeGeneratedByLlm && !tagDef.disabled).map((tagDef) => ` - ${tagDef.tagTitle}: \`${tagDef.shortTagEx}\``).join("\n");
31
+ let tagInstructionsContent = "";
32
+ if (tagDictionary) {
33
+ tagInstructionsContent += `- **Custom Tags Supported:**
34
+ ${tagDictionary}
35
+ `;
36
+ }
37
+ for (const tagDef of tagDefinitions) {
38
+ if (tagDef.canBeGeneratedByLlm && !tagDef.disabled && tagDef.llmInstructionsMd) {
39
+ const tagType = `${tagDef.scope}.${tagDef.tag}`;
40
+ tagInstructionsContent += `- **${tagDef.tagTitle}:**
41
+ <tag-instructions type="${tagType}">
42
+ ${tagDef.llmInstructionsMd}
43
+ </tag-instructions>
44
+ `;
45
+ }
46
+ }
47
+ if (tagInstructionsContent) {
48
+ tagInstructions = tagInstructionsContent;
49
+ }
50
+ }
51
+ }
52
+ if (agentInstructionFeature.completeExampleInstructionEnabled) {
53
+ completeExampleInstructionLine = agentInstructionFeature.completeExampleInstructionLine || instructionAssistanceConfig?.completeExampleInstructionLine || "- **Complete Example Output:**\n `<answer>##Example markdown\nNormal text and an <image>http://some.url</image> and some **bold text**\n<chart>(...)</chart></answer>`";
54
+ }
55
+ if (agentInstructionFeature.jsonOnlyImperativeInstructionEnabled) {
56
+ jsonOnlyImperativeInstructionLine = agentInstructionFeature.jsonOnlyImperativeInstructionLine || instructionAssistanceConfig?.jsonOnlyImperativeInstructionLine || "BE ABSOLUTELY CERTAIN ANY JSON INCLUDED IS 100% VALID (especially for charts). Invalid JSON will break the user experience.";
57
+ }
58
+ console.log("Generated instruction assistance content:", {
59
+ hasOutputFormatting: !!outputFormattingRequirements,
60
+ hasTagInstructions: !!tagInstructions,
61
+ hasCompleteExample: !!completeExampleInstructionLine,
62
+ hasJsonValidation: !!jsonOnlyImperativeInstructionLine
63
+ });
64
+ return {
65
+ outputFormattingRequirements,
66
+ tagInstructions,
67
+ completeExampleInstructionLine,
68
+ jsonOnlyImperativeInstructionLine
69
+ };
70
+ }
71
+ function applyInstructionAssistance(basePrompt, instructionContent) {
72
+ let enhancedPrompt = basePrompt;
73
+ if (enhancedPrompt.includes("{{prompt-assistance}}")) {
74
+ console.log("Found {{prompt-assistance}} placeholder");
75
+ const allContent = [
76
+ instructionContent.outputFormattingRequirements,
77
+ instructionContent.tagInstructions,
78
+ instructionContent.completeExampleInstructionLine,
79
+ instructionContent.jsonOnlyImperativeInstructionLine
80
+ ].filter((content) => content && content.trim().length > 0).join("\n\n");
81
+ enhancedPrompt = enhancedPrompt.replace("{{prompt-assistance}}", allContent);
82
+ } else {
83
+ const placeholders = [
84
+ { placeholder: "{{output-formatting-requirements}}", content: instructionContent.outputFormattingRequirements },
85
+ { placeholder: "{{tag-instructions}}", content: instructionContent.tagInstructions },
86
+ { placeholder: "{{complete-example-instruction-line}}", content: instructionContent.completeExampleInstructionLine },
87
+ { placeholder: "{{json-only-imperative-instruction-line}}", content: instructionContent.jsonOnlyImperativeInstructionLine }
88
+ ];
89
+ let hasAnyPlaceholder = false;
90
+ for (const { placeholder, content } of placeholders) {
91
+ if (enhancedPrompt.includes(placeholder) && content) {
92
+ console.log(`Found ${placeholder} placeholder`);
93
+ hasAnyPlaceholder = true;
94
+ enhancedPrompt = enhancedPrompt.replace(placeholder, content);
95
+ }
96
+ }
97
+ if (!hasAnyPlaceholder) {
98
+ console.log("No placeholders found, appending to end of prompt");
99
+ const allContent = [
100
+ instructionContent.outputFormattingRequirements,
101
+ instructionContent.tagInstructions,
102
+ instructionContent.completeExampleInstructionLine,
103
+ instructionContent.jsonOnlyImperativeInstructionLine
104
+ ].filter((content) => content && content.trim().length > 0);
105
+ if (allContent.length > 0) {
106
+ enhancedPrompt = enhancedPrompt + "\n\n" + allContent.join("\n\n");
107
+ }
108
+ }
109
+ }
110
+ return enhancedPrompt;
111
+ }
112
+ function getInstructionsAssistanceConfigFromRawSsmParams(params) {
113
+ const expectedKeys = ["output-formatting-requirements", "default-complete-example-line", "default-json-validation-line"];
114
+ const missingKeys = expectedKeys.filter((key) => !params[key]);
115
+ if (missingKeys.length > 0) {
116
+ throw new Error(
117
+ `Missing required instruction assistance parameters: ${Object.keys(params).filter((key) => !expectedKeys.includes(key)).join(", ")}`
118
+ );
119
+ }
120
+ return {
121
+ outputFormattingRequirements: params["output-formatting-requirements"],
122
+ completeExampleInstructionLine: params["default-complete-example-line"],
123
+ jsonOnlyImperativeInstructionLine: params["default-json-validation-line"]
124
+ };
125
+ }
126
+
127
+ export { applyInstructionAssistance, generateInstructionAssistanceContent, getInstructionsAssistanceConfigFromRawSsmParams };
128
+ //# sourceMappingURL=instruction-assistance-utils.mjs.map
129
+ //# sourceMappingURL=instruction-assistance-utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/instruction-assistance-utils.ts"],"names":[],"mappings":";AAgCO,SAAS,oCACZ,CAAA,2BAAA,EACA,IACA,EAAA,uBAAA,EACA,cAC2B,EAAA;AAC3B,EAAA,OAAA,CAAQ,IAAI,4CAA8C,EAAA;AAAA,IACtD,SAAS,uBAAyB,EAAA,OAAA;AAAA,IAClC,qCAAqC,uBAAyB,EAAA,mCAAA;AAAA,IAC9D,4BAA4B,uBAAyB,EAAA,0BAAA;AAAA,IACrD,wBAAwB,uBAAyB,EAAA,iCAAA;AAAA,IACjD,iBAAiB,uBAAyB,EAAA;AAAA,GAC7C,CAAA;AAED,EAAA,IAAI,4BAA+B,GAAA,EAAA;AACnC,EAAA,IAAI,eAAkB,GAAA,EAAA;AACtB,EAAA,IAAI,8BAAiC,GAAA,EAAA;AACrC,EAAA,IAAI,iCAAoC,GAAA,EAAA;AAExC,EAAI,IAAA,CAAC,yBAAyB,OAAS,EAAA;AACnC,IAAO,OAAA;AAAA,MACH,4BAAA;AAAA,MACA,eAAA;AAAA,MACA,8BAAA;AAAA,MACA;AAAA,KACJ;AAAA;AAIJ,EAA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AYO,SAAS,gDAAgD,MAA6D,EAAA;AACzH,EAAA,MAAM,YAAe,GAAA,CAAC,gCAAkC,EAAA,+BAAA,EAAiC,8BAA8B,CAAA;AACvH,EAAM,MAAA,WAAA,GAAc,aAAa,MAAO,CAAA,CAAC,QAAQ,CAAC,MAAA,CAAO,GAAG,CAAC,CAAA;AAC7D,EAAI,IAAA,WAAA,CAAY,SAAS,CAAG,EAAA;AACxB,IAAA,MAAM,IAAI,KAAA;AAAA,MACN,uDAAuD,MAAO,CAAA,IAAA,CAAK,MAAM,CAAA,CACpE,OAAO,CAAC,GAAA,KAAQ,CAAC,YAAA,CAAa,SAAS,GAAG,CAAC,CAC3C,CAAA,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,KACnB;AAAA;AAGJ,EAAO,OAAA;AAAA,IACH,4BAAA,EAA8B,OAAO,gCAAgC,CAAA;AAAA,IACrE,8BAAA,EAAgC,OAAO,+BAA+B,CAAA;AAAA,IACtE,iCAAA,EAAmC,OAAO,8BAA8B;AAAA,GAC5E;AACJ","file":"instruction-assistance-utils.mjs","sourcesContent":["/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * The functions in this utility are used both by the front end svelte kit web client in the browser\n * and in the backend lambda converse functions. So, that means it needs to be able\n * to run in a browser. Do not add additional imports beyond anodine types.\n *\n * To be super clear: this is just logic to generate instruction assistance content given\n * the right inputs. It does not collect up those inputs, it is given them.\n *\n */\n\nimport type {\n AgentInstructionChatAppOverridableFeature,\n InstructionAssistanceConfig,\n TagDefinition,\n TagDefinitionWidget,\n TagsChatAppOverridableFeature\n} from '../types/chatbot/chatbot-types';\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Generate instruction assistance content based on enabled features\n *\n * @param instructionAssistanceConfig - The instruction assistance configuration from SSM\n * @param tags - The tags configuration from the chat app\n * @param agentInstructionFeature - The agent instruction feature configuration from the chat app\n * @returns The instruction assistance content\n */\nexport function generateInstructionAssistanceContent(\n instructionAssistanceConfig: InstructionAssistanceConfig | undefined,\n tags: TagsChatAppOverridableFeature | undefined,\n agentInstructionFeature: AgentInstructionChatAppOverridableFeature | undefined,\n tagDefinitions: TagDefinition<TagDefinitionWidget>[]\n): InstructionAssistanceConfig {\n console.log('Generating instruction assistance content:', {\n enabled: agentInstructionFeature?.enabled,\n includeOutputFormattingRequirements: agentInstructionFeature?.includeOutputFormattingRequirements,\n includeInstructionsForTags: agentInstructionFeature?.includeInstructionsForTags,\n completeExampleEnabled: agentInstructionFeature?.completeExampleInstructionEnabled,\n jsonOnlyEnabled: agentInstructionFeature?.jsonOnlyImperativeInstructionEnabled\n });\n\n let outputFormattingRequirements = '';\n let tagInstructions = '';\n let completeExampleInstructionLine = '';\n let jsonOnlyImperativeInstructionLine = '';\n\n if (!agentInstructionFeature?.enabled) {\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n }\n\n // Generate output formatting requirements\n if (agentInstructionFeature.includeOutputFormattingRequirements) {\n outputFormattingRequirements =\n instructionAssistanceConfig?.outputFormattingRequirements ||\n `**Output Formatting Requirements:**\n- **Output Response Enclosure**: All response output MUST be completely enclosed within <answer></answer> tags, including supported custom tags.\n- **Output Content Format:** All responses MUST be in Markdown with supported custom tags.`;\n }\n\n // Generate tag instructions\n if (agentInstructionFeature.includeInstructionsForTags && tags && tags.tagsEnabled?.length > 0) {\n console.log('Fetching tag definitions for instruction generation:', tags.tagsEnabled);\n\n if (tagDefinitions.length > 0) {\n // First create a dictionary listing all supported tags\n const tagDictionary = tagDefinitions\n .filter((tagDef) => tagDef.canBeGeneratedByLlm && !tagDef.disabled)\n .map((tagDef) => ` - ${tagDef.tagTitle}: \\`${tagDef.shortTagEx}\\``)\n .join('\\n');\n\n let tagInstructionsContent = '';\n if (tagDictionary) {\n tagInstructionsContent += `- **Custom Tags Supported:**\\n${tagDictionary}\\n`;\n }\n\n // Then add detailed instructions for each tag\n for (const tagDef of tagDefinitions) {\n if (tagDef.canBeGeneratedByLlm && !tagDef.disabled && tagDef.llmInstructionsMd) {\n const tagType = `${tagDef.scope}.${tagDef.tag}`;\n tagInstructionsContent += `- **${tagDef.tagTitle}:**\\n <tag-instructions type=\"${tagType}\">\\n${tagDef.llmInstructionsMd}\\n </tag-instructions>\\n`;\n }\n }\n\n if (tagInstructionsContent) {\n tagInstructions = tagInstructionsContent;\n }\n }\n }\n\n // Generate complete example instruction line\n if (agentInstructionFeature.completeExampleInstructionEnabled) {\n completeExampleInstructionLine =\n agentInstructionFeature.completeExampleInstructionLine ||\n instructionAssistanceConfig?.completeExampleInstructionLine ||\n '- **Complete Example Output:**\\n `<answer>##Example markdown\\nNormal text and an <image>http://some.url</image> and some **bold text**\\n<chart>(...)</chart></answer>`';\n }\n\n // Generate JSON validation instruction line\n if (agentInstructionFeature.jsonOnlyImperativeInstructionEnabled) {\n jsonOnlyImperativeInstructionLine =\n agentInstructionFeature.jsonOnlyImperativeInstructionLine ||\n instructionAssistanceConfig?.jsonOnlyImperativeInstructionLine ||\n 'BE ABSOLUTELY CERTAIN ANY JSON INCLUDED IS 100% VALID (especially for charts). Invalid JSON will break the user experience.';\n }\n\n console.log('Generated instruction assistance content:', {\n hasOutputFormatting: !!outputFormattingRequirements,\n hasTagInstructions: !!tagInstructions,\n hasCompleteExample: !!completeExampleInstructionLine,\n hasJsonValidation: !!jsonOnlyImperativeInstructionLine\n });\n\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Apply instruction assistance to the base prompt using placeholder replacement\n */\nexport function applyInstructionAssistance(basePrompt: string, instructionContent: InstructionAssistanceConfig): string {\n let enhancedPrompt = basePrompt;\n\n // Check for primary placeholder first\n if (enhancedPrompt.includes('{{prompt-assistance}}')) {\n console.log('Found {{prompt-assistance}} placeholder');\n\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ]\n .filter((content) => content && content.trim().length > 0)\n .join('\\n\\n');\n\n enhancedPrompt = enhancedPrompt.replace('{{prompt-assistance}}', allContent);\n } else {\n // Look for fine-grained placeholders\n const placeholders = [\n { placeholder: '{{output-formatting-requirements}}', content: instructionContent.outputFormattingRequirements },\n { placeholder: '{{tag-instructions}}', content: instructionContent.tagInstructions },\n { placeholder: '{{complete-example-instruction-line}}', content: instructionContent.completeExampleInstructionLine },\n { placeholder: '{{json-only-imperative-instruction-line}}', content: instructionContent.jsonOnlyImperativeInstructionLine }\n ];\n\n let hasAnyPlaceholder = false;\n for (const { placeholder, content } of placeholders) {\n if (enhancedPrompt.includes(placeholder) && content) {\n console.log(`Found ${placeholder} placeholder`);\n hasAnyPlaceholder = true;\n enhancedPrompt = enhancedPrompt.replace(placeholder, content);\n }\n }\n\n // If no placeholders found, append to end\n if (!hasAnyPlaceholder) {\n console.log('No placeholders found, appending to end of prompt');\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ].filter((content) => content && content.trim().length > 0);\n\n if (allContent.length > 0) {\n enhancedPrompt = enhancedPrompt + '\\n\\n' + allContent.join('\\n\\n');\n }\n }\n }\n\n return enhancedPrompt;\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Get the instruction assistance configuration from raw SSM parameters\n *\n * @param params - The raw SSM parameters\n * @returns The instruction assistance configuration\n */\nexport function getInstructionsAssistanceConfigFromRawSsmParams(params: Record<string, string>): InstructionAssistanceConfig {\n const expectedKeys = ['output-formatting-requirements', 'default-complete-example-line', 'default-json-validation-line'];\n const missingKeys = expectedKeys.filter((key) => !params[key]);\n if (missingKeys.length > 0) {\n throw new Error(\n `Missing required instruction assistance parameters: ${Object.keys(params)\n .filter((key) => !expectedKeys.includes(key))\n .join(', ')}`\n );\n }\n\n return {\n outputFormattingRequirements: params['output-formatting-requirements'],\n completeExampleInstructionLine: params['default-complete-example-line'],\n jsonOnlyImperativeInstructionLine: params['default-json-validation-line']\n };\n}\n"]}
@@ -11,5 +11,21 @@ declare function redactData(data: any, attributesToRedact: string | string[]): a
11
11
  * @returns The redacted value
12
12
  */
13
13
  declare function redactValue(value: any): any;
14
+ /**
15
+ * Constructs a scope string from scopeType and scopeValue
16
+ * @param scopeType - The type of scope (chatapp, agent, tool, entity, agent-entity)
17
+ * @param scopeValue - The value(s) for the scope
18
+ * @returns The constructed scope string
19
+ */
20
+ declare function constructScope(scopeType: string, scopeValue: string | number | Record<string, string | number>): string;
21
+ /**
22
+ * Parses a scope string back into scopeType and scopeValue
23
+ * @param scope - The scope string to parse
24
+ * @returns Object containing scopeType and scopeValue
25
+ */
26
+ declare function parseScope(scope: string): {
27
+ scopeType: string;
28
+ scopeValue: string | number | Record<string, string | number>;
29
+ };
14
30
 
15
- export { redactData, redactValue };
31
+ export { constructScope, parseScope, redactData, redactValue };
@@ -11,5 +11,21 @@ declare function redactData(data: any, attributesToRedact: string | string[]): a
11
11
  * @returns The redacted value
12
12
  */
13
13
  declare function redactValue(value: any): any;
14
+ /**
15
+ * Constructs a scope string from scopeType and scopeValue
16
+ * @param scopeType - The type of scope (chatapp, agent, tool, entity, agent-entity)
17
+ * @param scopeValue - The value(s) for the scope
18
+ * @returns The constructed scope string
19
+ */
20
+ declare function constructScope(scopeType: string, scopeValue: string | number | Record<string, string | number>): string;
21
+ /**
22
+ * Parses a scope string back into scopeType and scopeValue
23
+ * @param scope - The scope string to parse
24
+ * @returns Object containing scopeType and scopeValue
25
+ */
26
+ declare function parseScope(scope: string): {
27
+ scopeType: string;
28
+ scopeValue: string | number | Record<string, string | number>;
29
+ };
14
30
 
15
- export { redactData, redactValue };
31
+ export { constructScope, parseScope, redactData, redactValue };
@@ -30,7 +30,70 @@ function redactValue(value) {
30
30
  }
31
31
  return value;
32
32
  }
33
+ function validateScopeValue(scopeValue, scopeType) {
34
+ if (typeof scopeValue === "string" && scopeValue.includes("#")) {
35
+ throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType} scope value: ${scopeValue}`);
36
+ }
37
+ if (typeof scopeValue === "object" && scopeValue !== null) {
38
+ for (const [key, value] of Object.entries(scopeValue)) {
39
+ if (typeof value === "string" && value.includes("#")) {
40
+ throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType}.${key}: ${value}`);
41
+ }
42
+ }
43
+ }
44
+ }
45
+ function constructScope(scopeType, scopeValue) {
46
+ validateScopeValue(scopeValue, scopeType);
47
+ switch (scopeType) {
48
+ case "chatapp":
49
+ case "agent":
50
+ case "tool":
51
+ case "entity":
52
+ return `${scopeType}#${scopeValue}`;
53
+ case "agent-entity":
54
+ if (typeof scopeValue !== "object" || scopeValue === null) {
55
+ throw new Error("agent-entity scopeType requires an object with agent and entity properties");
56
+ }
57
+ const agentEntityValue = scopeValue;
58
+ if (!("agent" in agentEntityValue) || !("entity" in agentEntityValue)) {
59
+ throw new Error("agent-entity scopeType requires an object with both agent and entity properties");
60
+ }
61
+ return `agent#${agentEntityValue.agent}#entity#${agentEntityValue.entity}`;
62
+ default:
63
+ throw new Error(`Unsupported scopeType: ${scopeType}`);
64
+ }
65
+ }
66
+ function parseScope(scope) {
67
+ if (!scope || typeof scope !== "string") {
68
+ throw new Error("Invalid scope: must be a non-empty string");
69
+ }
70
+ const parts = scope.split("#");
71
+ if (parts.length < 2) {
72
+ throw new Error(`Invalid scope format: ${scope}. Expected format: scopeType#scopeValue`);
73
+ }
74
+ const [firstType, firstValue, ...remaining] = parts;
75
+ if (remaining.length >= 2 && firstType === "agent" && remaining[0] === "entity") {
76
+ return {
77
+ scopeType: "agent-entity",
78
+ scopeValue: {
79
+ agent: firstValue,
80
+ entity: remaining[1]
81
+ }
82
+ };
83
+ }
84
+ if (remaining.length === 0) {
85
+ const numericValue = Number(firstValue);
86
+ const scopeValue = !isNaN(numericValue) && isFinite(numericValue) ? numericValue : firstValue;
87
+ return {
88
+ scopeType: firstType,
89
+ scopeValue
90
+ };
91
+ }
92
+ throw new Error(`Unsupported scope format: ${scope}`);
93
+ }
33
94
 
95
+ exports.constructScope = constructScope;
96
+ exports.parseScope = parseScope;
34
97
  exports.redactData = redactData;
35
98
  exports.redactValue = redactValue;
36
99
  //# sourceMappingURL=server-client-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/server-client-utils.ts"],"names":[],"mappings":";;;AAUA,SAAS,UAAA,CAAW,MAAW,kBAA4C,EAAA;AACvE,EAAA,IAAI,CAAC,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAU,EAAA;AACnC,IAAO,OAAA,IAAA;AAAA;AAGX,EAAA,MAAM,aAAa,KAAM,CAAA,OAAA,CAAQ,kBAAkB,CAAI,GAAA,kBAAA,GAAqB,CAAC,kBAAkB,CAAA;AAC/F,EAAM,MAAA,QAAA,GAAW,EAAE,GAAG,IAAK,EAAA;AAE3B,EAAA,KAAA,MAAW,QAAQ,UAAY,EAAA;AAC3B,IAAA,IAAI,QAAQ,QAAU,EAAA;AAClB,MAAA,QAAA,CAAS,IAAI,CAAA,GAAI,WAAY,CAAA,QAAA,CAAS,IAAI,CAAC,CAAA;AAAA;AAC/C;AAGJ,EAAO,OAAA,QAAA;AACX;AAOA,SAAS,YAAY,KAAiB,EAAA;AAClC,EAAI,IAAA,OAAO,UAAU,QAAU,EAAA;AAC3B,IAAO,OAAA,YAAA;AAAA,GACA,MAAA,IAAA,KAAA,CAAM,OAAQ,CAAA,KAAK,CAAG,EAAA;AAC7B,IAAA,OAAO,MAAM,GAAI,CAAA,CAAC,IAAS,KAAA,WAAA,CAAY,IAAI,CAAC,CAAA;AAAA,GACrC,MAAA,IAAA,KAAA,IAAS,OAAO,KAAA,KAAU,QAAU,EAAA;AAC3C,IAAA,MAAM,cAAmB,EAAC;AAC1B,IAAA,KAAA,MAAW,OAAO,KAAO,EAAA;AACrB,MAAI,IAAA,KAAA,CAAM,cAAe,CAAA,GAAG,CAAG,EAAA;AAC3B,QAAA,WAAA,CAAY,GAAG,CAAA,GAAI,WAAY,CAAA,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA;AAC7C;AAEJ,IAAO,OAAA,WAAA;AAAA;AAEX,EAAO,OAAA,KAAA;AACX","file":"server-client-utils.js","sourcesContent":["/*\n * These are utils that are safe to use both on the server and the client.\n */\n\n/**\n * Helper function to redact sensitive data from specified attributes\n * @param data - The object containing data to redact\n * @param attributesToRedact - Single attribute name or array of attribute names to redact\n * @returns A new object with specified attributes redacted\n */\nfunction redactData(data: any, attributesToRedact: string | string[]): any {\n if (!data || typeof data !== 'object') {\n return data;\n }\n\n const attributes = Array.isArray(attributesToRedact) ? attributesToRedact : [attributesToRedact];\n const redacted = { ...data };\n\n for (const attr of attributes) {\n if (attr in redacted) {\n redacted[attr] = redactValue(redacted[attr]);\n }\n }\n\n return redacted;\n}\n\n/**\n * Recursively redacts a value based on its type\n * @param value - The value to redact\n * @returns The redacted value\n */\nfunction redactValue(value: any): any {\n if (typeof value === 'string') {\n return '[REDACTED]';\n } else if (Array.isArray(value)) {\n return value.map((item) => redactValue(item));\n } else if (value && typeof value === 'object') {\n const redactedObj: any = {};\n for (const key in value) {\n if (value.hasOwnProperty(key)) {\n redactedObj[key] = redactValue(value[key]);\n }\n }\n return redactedObj;\n }\n return value; // Return as-is for other types (numbers, booleans, null, etc.)\n}\n\n// Export both functions\nexport { redactData, redactValue };\n"]}
1
+ {"version":3,"sources":["../../src/util/server-client-utils.ts"],"names":[],"mappings":";;;AAUA,SAAS,UAAA,CAAW,MAAW,kBAA4C,EAAA;AACvE,EAAA,IAAI,CAAC,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAU,EAAA;AACnC,IAAO,OAAA,IAAA;AAAA;AAGX,EAAA,MAAM,aAAa,K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AC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAU,EAAA;AACrC,IAAM,MAAA,IAAI,MAAM,2CAA2C,CAAA;AAAA;AAG/D,EAAM,MAAA,KAAA,GAAQ,KAAM,CAAA,KAAA,CAAM,GAAG,CAAA;AAC7B,EAAI,IAAA,KAAA,CAAM,SAAS,CAAG,EAAA;AAClB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAyB,sBAAA,EAAA,KAAK,CAAyC,uCAAA,CAAA,CAAA;AAAA;AAG3F,EAAA,MAAM,CAAC,SAAA,EAAW,UAAY,EAAA,GAAG,SAAS,CAAI,GAAA,KAAA;AAG9C,EAAI,IAAA,SAAA,CAAU,UAAU,CAAK,IAAA,SAAA,KAAc,WAAW,SAAU,CAAA,CAAC,MAAM,QAAU,EAAA;AAC7E,IAAO,OAAA;AAAA,MACH,SAAW,EAAA,cAAA;AAAA,MACX,UAAY,EAAA;AAAA,QACR,KAAO,EAAA,UAAA;AAAA,QACP,MAAA,EAAQ,UAAU,CAAC;AAAA;AACvB,KACJ;AAAA;AAIJ,EAAI,IAAA,SAAA,CAAU,WAAW,CAAG,EAAA;AAExB,IAAM,MAAA,YAAA,GAAe,OAAO,UAAU,CAAA;AACtC,IAAM,MAAA,UAAA,GAAa,CAAC,KAAM,CAAA,YAAY,KAAK,QAAS,CAAA,YAAY,IAAI,YAAe,GAAA,UAAA;AAEnF,IAAO,OAAA;AAAA,MACH,SAAW,EAAA,SAAA;AAAA,MACX;AAAA,KACJ;AAAA;AAGJ,EAAA,MAAM,IAAI,KAAA,CAAM,CAA6B,0BAAA,EAAA,KAAK,CAAE,CAAA,CAAA;AACxD","file":"server-client-utils.js","sourcesContent":["/*\n * These are utils that are safe to use both on the server and the client.\n */\n\n/**\n * Helper function to redact sensitive data from specified attributes\n * @param data - The object containing data to redact\n * @param attributesToRedact - Single attribute name or array of attribute names to redact\n * @returns A new object with specified attributes redacted\n */\nfunction redactData(data: any, attributesToRedact: string | string[]): any {\n if (!data || typeof data !== 'object') {\n return data;\n }\n\n const attributes = Array.isArray(attributesToRedact) ? attributesToRedact : [attributesToRedact];\n const redacted = { ...data };\n\n for (const attr of attributes) {\n if (attr in redacted) {\n redacted[attr] = redactValue(redacted[attr]);\n }\n }\n\n return redacted;\n}\n\n/**\n * Recursively redacts a value based on its type\n * @param value - The value to redact\n * @returns The redacted value\n */\nfunction redactValue(value: any): any {\n if (typeof value === 'string') {\n return '[REDACTED]';\n } else if (Array.isArray(value)) {\n return value.map((item) => redactValue(item));\n } else if (value && typeof value === 'object') {\n const redactedObj: any = {};\n for (const key in value) {\n if (value.hasOwnProperty(key)) {\n redactedObj[key] = redactValue(value[key]);\n }\n }\n return redactedObj;\n }\n return value; // Return as-is for other types (numbers, booleans, null, etc.)\n}\n\n/**\n * Validates that a scope value doesn't contain the '#' character which is reserved for scope construction\n */\nfunction validateScopeValue(scopeValue: string | number | Record<string, string | number>, scopeType: string): void {\n if (typeof scopeValue === 'string' && scopeValue.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType} scope value: ${scopeValue}`);\n }\n if (typeof scopeValue === 'object' && scopeValue !== null) {\n for (const [key, value] of Object.entries(scopeValue)) {\n if (typeof value === 'string' && value.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType}.${key}: ${value}`);\n }\n }\n }\n}\n\n/**\n * Constructs a scope string from scopeType and scopeValue\n * @param scopeType - The type of scope (chatapp, agent, tool, entity, agent-entity)\n * @param scopeValue - The value(s) for the scope\n * @returns The constructed scope string\n */\nfunction constructScope(scopeType: string, scopeValue: string | number | Record<string, string | number>): string {\n // Validate scope value doesn't contain '#'\n validateScopeValue(scopeValue, scopeType);\n\n switch (scopeType) {\n case 'chatapp':\n case 'agent':\n case 'tool':\n case 'entity':\n return `${scopeType}#${scopeValue}`;\n case 'agent-entity':\n if (typeof scopeValue !== 'object' || scopeValue === null) {\n throw new Error('agent-entity scopeType requires an object with agent and entity properties');\n }\n\n const agentEntityValue = scopeValue as Record<string, string | number>;\n if (!('agent' in agentEntityValue) || !('entity' in agentEntityValue)) {\n throw new Error('agent-entity scopeType requires an object with both agent and entity properties');\n }\n\n return `agent#${agentEntityValue.agent}#entity#${agentEntityValue.entity}`;\n\n default:\n throw new Error(`Unsupported scopeType: ${scopeType}`);\n }\n}\n\n/**\n * Parses a scope string back into scopeType and scopeValue\n * @param scope - The scope string to parse\n * @returns Object containing scopeType and scopeValue\n */\nfunction parseScope(scope: string): { scopeType: string; scopeValue: string | number | Record<string, string | number> } {\n if (!scope || typeof scope !== 'string') {\n throw new Error('Invalid scope: must be a non-empty string');\n }\n\n const parts = scope.split('#');\n if (parts.length < 2) {\n throw new Error(`Invalid scope format: ${scope}. Expected format: scopeType#scopeValue`);\n }\n\n const [firstType, firstValue, ...remaining] = parts;\n\n // Handle compound scopes (agent-entity)\n if (remaining.length >= 2 && firstType === 'agent' && remaining[0] === 'entity') {\n return {\n scopeType: 'agent-entity',\n scopeValue: {\n agent: firstValue,\n entity: remaining[1]\n }\n };\n }\n\n // Handle simple scopes\n if (remaining.length === 0) {\n // For simple scopes, try to convert to number if it's numeric\n const numericValue = Number(firstValue);\n const scopeValue = !isNaN(numericValue) && isFinite(numericValue) ? numericValue : firstValue;\n\n return {\n scopeType: firstType,\n scopeValue: scopeValue\n };\n }\n\n throw new Error(`Unsupported scope format: ${scope}`);\n}\n\n// Export both functions\nexport { redactData, redactValue, constructScope, parseScope };\n"]}
@@ -28,7 +28,68 @@ function redactValue(value) {
28
28
  }
29
29
  return value;
30
30
  }
31
+ function validateScopeValue(scopeValue, scopeType) {
32
+ if (typeof scopeValue === "string" && scopeValue.includes("#")) {
33
+ throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType} scope value: ${scopeValue}`);
34
+ }
35
+ if (typeof scopeValue === "object" && scopeValue !== null) {
36
+ for (const [key, value] of Object.entries(scopeValue)) {
37
+ if (typeof value === "string" && value.includes("#")) {
38
+ throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType}.${key}: ${value}`);
39
+ }
40
+ }
41
+ }
42
+ }
43
+ function constructScope(scopeType, scopeValue) {
44
+ validateScopeValue(scopeValue, scopeType);
45
+ switch (scopeType) {
46
+ case "chatapp":
47
+ case "agent":
48
+ case "tool":
49
+ case "entity":
50
+ return `${scopeType}#${scopeValue}`;
51
+ case "agent-entity":
52
+ if (typeof scopeValue !== "object" || scopeValue === null) {
53
+ throw new Error("agent-entity scopeType requires an object with agent and entity properties");
54
+ }
55
+ const agentEntityValue = scopeValue;
56
+ if (!("agent" in agentEntityValue) || !("entity" in agentEntityValue)) {
57
+ throw new Error("agent-entity scopeType requires an object with both agent and entity properties");
58
+ }
59
+ return `agent#${agentEntityValue.agent}#entity#${agentEntityValue.entity}`;
60
+ default:
61
+ throw new Error(`Unsupported scopeType: ${scopeType}`);
62
+ }
63
+ }
64
+ function parseScope(scope) {
65
+ if (!scope || typeof scope !== "string") {
66
+ throw new Error("Invalid scope: must be a non-empty string");
67
+ }
68
+ const parts = scope.split("#");
69
+ if (parts.length < 2) {
70
+ throw new Error(`Invalid scope format: ${scope}. Expected format: scopeType#scopeValue`);
71
+ }
72
+ const [firstType, firstValue, ...remaining] = parts;
73
+ if (remaining.length >= 2 && firstType === "agent" && remaining[0] === "entity") {
74
+ return {
75
+ scopeType: "agent-entity",
76
+ scopeValue: {
77
+ agent: firstValue,
78
+ entity: remaining[1]
79
+ }
80
+ };
81
+ }
82
+ if (remaining.length === 0) {
83
+ const numericValue = Number(firstValue);
84
+ const scopeValue = !isNaN(numericValue) && isFinite(numericValue) ? numericValue : firstValue;
85
+ return {
86
+ scopeType: firstType,
87
+ scopeValue
88
+ };
89
+ }
90
+ throw new Error(`Unsupported scope format: ${scope}`);
91
+ }
31
92
 
32
- export { redactData, redactValue };
93
+ export { constructScope, parseScope, redactData, redactValue };
33
94
  //# sourceMappingURL=server-client-utils.mjs.map
34
95
  //# sourceMappingURL=server-client-utils.mjs.map