@superatomai/sdk-node 0.0.33 → 0.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1011,6 +1011,143 @@ If adaptation is not possible or would fundamentally change the component:
1011
1011
  4. **Preserve structure**: Keep the same number and type of components
1012
1012
 
1013
1013
  5. **Return complete JSON** with all adapted properties for all components`
1014
+ },
1015
+ "dash-comp-picker": {
1016
+ system: `You are a component selection expert that picks the best dashboard component and generates complete props based on user requests.
1017
+
1018
+ ## Your Task
1019
+
1020
+ Analyze the user's request and:
1021
+ 1. **Select the most appropriate component** from the available components list
1022
+ 2. **Determine the data source**: Database query OR External tool (ERP)
1023
+ 3. **Generate complete props** for the selected component including the data retrieval/modification method
1024
+
1025
+ ## Component Selection Rules
1026
+
1027
+ 1. **Match by Intent**: Understand what the user wants to display/achieve
1028
+ 2. **Match by Type**: Choose the component type that best fits the data visualization or action need
1029
+ 3. **Match by Description**: Use component descriptions and keywords to find the best fit
1030
+
1031
+ ## Data Source Decision
1032
+
1033
+ ### Use DATABASE when:
1034
+ - User asks about data that exists in the database schema (customers, orders, products, etc.)
1035
+ - Questions about internal business data (sales, inventory, users, transactions)
1036
+ - CRUD operations on database tables
1037
+
1038
+ ### Use EXTERNAL TOOL when:
1039
+ - User mentions specific external systems (ERP, CRM, email, calendar, etc.)
1040
+ - Data not available in database schema
1041
+ - Actions that require external integrations (send email, create calendar event, sync with ERP)
1042
+ - Tool description matches the user's request
1043
+
1044
+ ## Props Generation Rules
1045
+
1046
+ **CRITICAL**: Look at each component's "Props Structure" in the available components list. Generate ALL props that the component expects.
1047
+
1048
+ ### For Data Viewing Components (charts, tables, KPIs):
1049
+
1050
+ **Option A: Database Query** (when data is in database)
1051
+ \`\`\`json
1052
+ {
1053
+ "query": {
1054
+ "sql": "SELECT column1, column2 FROM table WHERE condition = $param LIMIT 32",
1055
+ "params": { "param": "value" }
1056
+ }
1057
+ }
1058
+ \`\`\`
1059
+
1060
+ **Option B: External Tool** (when data is from ERP/external system)
1061
+ \`\`\`json
1062
+ {
1063
+ "externalTool": {
1064
+ "toolId": "tool_id_from_list",
1065
+ "toolName": "Tool Display Name",
1066
+ "action": "get",
1067
+ "params": {
1068
+ "param1": "value1",
1069
+ "param2": "value2"
1070
+ }
1071
+ }
1072
+ }
1073
+ \`\`\`
1074
+
1075
+ ### For Data Modification Components (forms):
1076
+
1077
+ **Option A: Database Mutation**
1078
+ \`\`\`json
1079
+ {
1080
+ "query": {
1081
+ "sql": "INSERT INTO table (col1, col2) VALUES ($col1, $col2)",
1082
+ "params": {}
1083
+ },
1084
+ "fields": [
1085
+ { "name": "col1", "type": "text", "required": true },
1086
+ { "name": "col2", "type": "number", "required": false }
1087
+ ]
1088
+ }
1089
+ \`\`\`
1090
+
1091
+ **Option B: External Tool Mutation**
1092
+ \`\`\`json
1093
+ {
1094
+ "externalTool": {
1095
+ "toolId": "tool_id_from_list",
1096
+ "toolName": "Tool Display Name",
1097
+ "action": "create|update|delete",
1098
+ "params": {
1099
+ "param1": "value_or_placeholder"
1100
+ }
1101
+ },
1102
+ "fields": [
1103
+ { "name": "param1", "type": "text", "required": true }
1104
+ ]
1105
+ }
1106
+ \`\`\`
1107
+
1108
+ ### Database Query Rules
1109
+ {{DATABASE_RULES}}
1110
+
1111
+ ## Output Format
1112
+
1113
+ You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
1114
+
1115
+ {
1116
+ "componentId": "id_from_available_list",
1117
+ "componentName": "name_of_component",
1118
+ "componentType": "type_of_component",
1119
+ "dataSourceType": "database" | "external_tool",
1120
+ "operationType": "view" | "create" | "update" | "delete",
1121
+ "reasoning": "Why this component was selected and why this data source",
1122
+ "props": {
1123
+ // Generate ALL props based on the component's Props Structure
1124
+ // Include either "query" OR "externalTool" based on data source
1125
+ // Include all other required props (title, description, config, fields, etc.)
1126
+ }
1127
+ }
1128
+
1129
+ **CRITICAL:**
1130
+ - Return ONLY valid JSON (no markdown code blocks, no text before/after)
1131
+ - \`componentId\` MUST match an ID from the available components list
1132
+ - \`dataSourceType\` indicates whether data comes from database or external tool
1133
+ - \`operationType\` indicates the type of operation (view/create/update/delete)
1134
+ - Generate COMPLETE props based on the component's "Props Structure"
1135
+ - For queries, ALWAYS use \`$paramName\` placeholders and include \`params\` object
1136
+ - For external tools, \`toolId\` MUST match an ID from the available tools list
1137
+
1138
+ ---
1139
+
1140
+ ## CONTEXT (for this specific request)
1141
+
1142
+ ### Database Schema
1143
+ {{SCHEMA_DOC}}
1144
+
1145
+ ### Available External Tools
1146
+ {{AVAILABLE_TOOLS}}
1147
+
1148
+ ### Available Components
1149
+ {{AVAILABLE_COMPONENTS}}`,
1150
+ user: `{{USER_PROMPT}}`
1014
1151
  }
1015
1152
  };
1016
1153
  }
@@ -2014,6 +2151,19 @@ var KbNodesRequestMessageSchema = z3.object({
2014
2151
  type: z3.literal("KB_NODES"),
2015
2152
  payload: KbNodesRequestPayloadSchema
2016
2153
  });
2154
+ var DashCompRequestPayloadSchema = z3.object({
2155
+ prompt: z3.string(),
2156
+ SA_RUNTIME: z3.object({
2157
+ threadId: z3.string().optional(),
2158
+ uiBlockId: z3.string().optional()
2159
+ }).optional()
2160
+ });
2161
+ var DashCompRequestMessageSchema = z3.object({
2162
+ id: z3.string(),
2163
+ from: MessageParticipantSchema,
2164
+ type: z3.literal("DASH_COMP_REQ"),
2165
+ payload: DashCompRequestPayloadSchema
2166
+ });
2017
2167
 
2018
2168
  // src/index.ts
2019
2169
  init_logger();
@@ -3926,19 +4076,44 @@ var LLM = class {
3926
4076
  }
3927
4077
  const firstBrace = jsonText.indexOf("{");
3928
4078
  const firstBracket = jsonText.indexOf("[");
3929
- const lastBrace = jsonText.lastIndexOf("}");
3930
- const lastBracket = jsonText.lastIndexOf("]");
3931
4079
  let startIdx = -1;
3932
- let endIdx = -1;
4080
+ let openChar = "";
4081
+ let closeChar = "";
3933
4082
  if (firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket)) {
3934
4083
  startIdx = firstBrace;
3935
- endIdx = lastBrace;
4084
+ openChar = "{";
4085
+ closeChar = "}";
3936
4086
  } else if (firstBracket !== -1) {
3937
4087
  startIdx = firstBracket;
3938
- endIdx = lastBracket;
3939
- }
3940
- if (startIdx !== -1 && endIdx !== -1 && startIdx < endIdx) {
3941
- jsonText = jsonText.substring(startIdx, endIdx + 1);
4088
+ openChar = "[";
4089
+ closeChar = "]";
4090
+ }
4091
+ if (startIdx !== -1) {
4092
+ let depth = 0;
4093
+ let inString = false;
4094
+ let endIdx = -1;
4095
+ for (let i = startIdx; i < jsonText.length; i++) {
4096
+ const char = jsonText[i];
4097
+ const prevChar = i > 0 ? jsonText[i - 1] : "";
4098
+ if (char === '"' && prevChar !== "\\") {
4099
+ inString = !inString;
4100
+ continue;
4101
+ }
4102
+ if (!inString) {
4103
+ if (char === openChar) {
4104
+ depth++;
4105
+ } else if (char === closeChar) {
4106
+ depth--;
4107
+ if (depth === 0) {
4108
+ endIdx = i;
4109
+ break;
4110
+ }
4111
+ }
4112
+ }
4113
+ }
4114
+ if (endIdx !== -1) {
4115
+ jsonText = jsonText.substring(startIdx, endIdx + 1);
4116
+ }
3942
4117
  }
3943
4118
  try {
3944
4119
  const repairedJson = jsonrepair(jsonText);
@@ -5561,7 +5736,7 @@ var AnthropicLLM = class extends BaseLLM {
5561
5736
  super(config);
5562
5737
  }
5563
5738
  getDefaultModel() {
5564
- return "anthropic/claude-haiku-4-5-20251001";
5739
+ return "anthropic/claude-sonnet-4-5-20250929";
5565
5740
  }
5566
5741
  getDefaultApiKey() {
5567
5742
  return process.env.ANTHROPIC_API_KEY;
@@ -8939,6 +9114,219 @@ function sendResponse8(id, res, sendMessage, clientId) {
8939
9114
  sendMessage(response);
8940
9115
  }
8941
9116
 
9117
+ // src/handlers/dash-comp-request.ts
9118
+ init_logger();
9119
+ init_prompt_loader();
9120
+ async function pickComponentWithLLM(prompt, components, anthropicApiKey, groqApiKey, geminiApiKey, openaiApiKey, llmProviders, _collections, tools) {
9121
+ const errors = [];
9122
+ let availableComponentsText = "No components available";
9123
+ if (components && components.length > 0) {
9124
+ availableComponentsText = components.map((comp, idx) => {
9125
+ const keywords = comp.keywords ? comp.keywords.join(", ") : "";
9126
+ const propsPreview = comp.props ? JSON.stringify(comp.props, null, 2) : "No props";
9127
+ return `${idx + 1}. ID: ${comp.id}
9128
+ Name: ${comp.name}
9129
+ Type: ${comp.type}
9130
+ Description: ${comp.description || "No description"}
9131
+ Keywords: ${keywords}
9132
+ Props Structure: ${propsPreview}`;
9133
+ }).join("\n\n");
9134
+ }
9135
+ let availableToolsText = "No external tools available.";
9136
+ if (tools && tools.length > 0) {
9137
+ availableToolsText = tools.map((tool, idx) => {
9138
+ const paramsStr = Object.entries(tool.params || {}).map(([key, type]) => `${key}: ${type}`).join(", ");
9139
+ return `${idx + 1}. ID: ${tool.id}
9140
+ Name: ${tool.name}
9141
+ Description: ${tool.description}
9142
+ Parameters: { ${paramsStr} }`;
9143
+ }).join("\n\n");
9144
+ }
9145
+ try {
9146
+ const schemaDoc = schema.generateSchemaDocumentation();
9147
+ const databaseRules = await promptLoader.loadDatabaseRules();
9148
+ const prompts = await promptLoader.loadPrompts("dash-comp-picker", {
9149
+ USER_PROMPT: prompt,
9150
+ AVAILABLE_COMPONENTS: availableComponentsText,
9151
+ SCHEMA_DOC: schemaDoc || "No database schema available",
9152
+ DATABASE_RULES: databaseRules,
9153
+ AVAILABLE_TOOLS: availableToolsText
9154
+ });
9155
+ logger.debug("[DASH_COMP_REQ] Loaded dash-comp-picker prompts with schema and tools");
9156
+ const providers = llmProviders || ["anthropic", "gemini", "openai", "groq"];
9157
+ let apiKey;
9158
+ let model = "anthropic/claude-sonnet-4-5-20250929";
9159
+ for (const provider of providers) {
9160
+ if (provider === "anthropic" && anthropicApiKey) {
9161
+ apiKey = anthropicApiKey;
9162
+ model = "anthropic/claude-sonnet-4-5-20250929";
9163
+ break;
9164
+ } else if (provider === "openai" && openaiApiKey) {
9165
+ apiKey = openaiApiKey;
9166
+ model = "openai/gpt-4o-mini";
9167
+ break;
9168
+ } else if (provider === "gemini" && geminiApiKey) {
9169
+ apiKey = geminiApiKey;
9170
+ model = "google/gemini-2.0-flash-001";
9171
+ break;
9172
+ } else if (provider === "groq" && groqApiKey) {
9173
+ apiKey = groqApiKey;
9174
+ model = "groq/llama-3.3-70b-versatile";
9175
+ break;
9176
+ }
9177
+ }
9178
+ if (!apiKey) {
9179
+ errors.push("No API key available for any LLM provider");
9180
+ return { success: false, errors };
9181
+ }
9182
+ logger.info(`[DASH_COMP_REQ] Using model: ${model}`);
9183
+ const result = await LLM.stream(
9184
+ {
9185
+ sys: prompts.system,
9186
+ user: prompts.user
9187
+ },
9188
+ {
9189
+ model,
9190
+ maxTokens: 3e3,
9191
+ temperature: 0.2,
9192
+ apiKey
9193
+ },
9194
+ true
9195
+ // Parse as JSON
9196
+ );
9197
+ logger.debug("[DASH_COMP_REQ] LLM response received");
9198
+ logger.file("[DASH_COMP_REQ] LLM response:", JSON.stringify(result, null, 2));
9199
+ if (!result.componentId || !result.props) {
9200
+ errors.push("Invalid LLM response: missing componentId or props");
9201
+ return { success: false, errors };
9202
+ }
9203
+ const originalComponent = components.find((c) => c.id === result.componentId);
9204
+ if (!originalComponent) {
9205
+ errors.push(`Component ${result.componentId} not found in available components`);
9206
+ return { success: false, errors };
9207
+ }
9208
+ const finalComponent = {
9209
+ ...originalComponent,
9210
+ props: {
9211
+ ...originalComponent.props,
9212
+ ...result.props
9213
+ }
9214
+ };
9215
+ logger.info(`[DASH_COMP_REQ] Successfully picked component: ${finalComponent.name} (${finalComponent.type})`);
9216
+ if (result.props.query) {
9217
+ logger.info(`[DASH_COMP_REQ] Data source: Database query`);
9218
+ }
9219
+ if (result.props.externalTool) {
9220
+ logger.info(`[DASH_COMP_REQ] Data source: External tool - ${result.props.externalTool.toolName}`);
9221
+ }
9222
+ return {
9223
+ success: true,
9224
+ data: {
9225
+ component: finalComponent,
9226
+ reasoning: result.reasoning || "Component selected based on user prompt",
9227
+ dataSource: result.props.query ? "database" : result.props.externalTool ? "external_tool" : "none"
9228
+ },
9229
+ errors: []
9230
+ };
9231
+ } catch (error) {
9232
+ const errorMsg = error instanceof Error ? error.message : String(error);
9233
+ logger.error(`[DASH_COMP_REQ] Error picking component: ${errorMsg}`);
9234
+ errors.push(errorMsg);
9235
+ return { success: false, errors };
9236
+ }
9237
+ }
9238
+ var processDashCompRequest = async (data, components, _sendMessage, anthropicApiKey, groqApiKey, geminiApiKey, openaiApiKey, llmProviders, collections, tools) => {
9239
+ const errors = [];
9240
+ logger.debug("[DASH_COMP_REQ] Parsing incoming message data");
9241
+ const parseResult = DashCompRequestMessageSchema.safeParse(data);
9242
+ if (!parseResult.success) {
9243
+ const zodError = parseResult.error;
9244
+ zodError.errors.forEach((err) => {
9245
+ errors.push(`${err.path.join(".")}: ${err.message}`);
9246
+ });
9247
+ return { success: false, errors };
9248
+ }
9249
+ const dashCompRequest = parseResult.data;
9250
+ const { id, payload } = dashCompRequest;
9251
+ const prompt = payload.prompt;
9252
+ const wsId = dashCompRequest.from.id || "unknown";
9253
+ if (!prompt) {
9254
+ errors.push("Prompt is required");
9255
+ }
9256
+ if (errors.length > 0) {
9257
+ return { success: false, errors, id, wsId };
9258
+ }
9259
+ logger.info(`[DASH_COMP_REQ] Processing request for prompt: "${prompt.substring(0, 50)}..."`);
9260
+ logger.info(`[DASH_COMP_REQ] Available: ${components?.length || 0} components, ${tools?.length || 0} tools`);
9261
+ if (!components || components.length === 0) {
9262
+ logger.warn("[DASH_COMP_REQ] No components available");
9263
+ return {
9264
+ success: false,
9265
+ errors: ["No components available. Please ensure components are loaded."],
9266
+ id,
9267
+ wsId
9268
+ };
9269
+ }
9270
+ const llmResponse = await pickComponentWithLLM(
9271
+ prompt,
9272
+ components,
9273
+ anthropicApiKey,
9274
+ groqApiKey,
9275
+ geminiApiKey,
9276
+ openaiApiKey,
9277
+ llmProviders,
9278
+ collections,
9279
+ tools
9280
+ );
9281
+ return {
9282
+ success: llmResponse.success,
9283
+ data: llmResponse.data,
9284
+ errors: llmResponse.errors,
9285
+ id,
9286
+ wsId
9287
+ };
9288
+ };
9289
+ async function handleDashCompRequest(data, components, sendMessage, anthropicApiKey, groqApiKey, geminiApiKey, openaiApiKey, llmProviders, collections, tools) {
9290
+ const response = await processDashCompRequest(
9291
+ data,
9292
+ components,
9293
+ sendMessage,
9294
+ anthropicApiKey,
9295
+ groqApiKey,
9296
+ geminiApiKey,
9297
+ openaiApiKey,
9298
+ llmProviders,
9299
+ collections,
9300
+ tools
9301
+ );
9302
+ sendDashCompResponse(
9303
+ response.id || data.id,
9304
+ {
9305
+ success: response.success,
9306
+ errors: response.errors,
9307
+ data: response.data
9308
+ },
9309
+ sendMessage,
9310
+ response.wsId || data.from?.id
9311
+ );
9312
+ }
9313
+ function sendDashCompResponse(id, res, sendMessage, clientId) {
9314
+ const response = {
9315
+ id,
9316
+ type: "DASH_COMP_RES",
9317
+ from: { type: "data-agent" },
9318
+ to: {
9319
+ type: "runtime",
9320
+ id: clientId
9321
+ },
9322
+ payload: {
9323
+ ...res
9324
+ }
9325
+ };
9326
+ sendMessage(response);
9327
+ logger.info(`[DASH_COMP_REQ] Response sent to client ${clientId}`);
9328
+ }
9329
+
8942
9330
  // src/auth/user-manager.ts
8943
9331
  init_logger();
8944
9332
  import fs5 from "fs";
@@ -9994,6 +10382,11 @@ var SuperatomSDK = class {
9994
10382
  logger.error("Failed to handle KB nodes request:", error);
9995
10383
  });
9996
10384
  break;
10385
+ case "DASH_COMP_REQ":
10386
+ handleDashCompRequest(parsed, this.components, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.geminiApiKey, this.openaiApiKey, this.llmProviders, this.collections, this.tools).catch((error) => {
10387
+ logger.error("Failed to handle dash comp request:", error);
10388
+ });
10389
+ break;
9997
10390
  default:
9998
10391
  const handler = this.messageTypeHandlers.get(message.type);
9999
10392
  if (handler) {