@superatomai/sdk-node 0.0.33 → 0.0.34

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.js CHANGED
@@ -1033,6 +1033,143 @@ If adaptation is not possible or would fundamentally change the component:
1033
1033
  4. **Preserve structure**: Keep the same number and type of components
1034
1034
 
1035
1035
  5. **Return complete JSON** with all adapted properties for all components`
1036
+ },
1037
+ "dash-comp-picker": {
1038
+ system: `You are a component selection expert that picks the best dashboard component and generates complete props based on user requests.
1039
+
1040
+ ## Your Task
1041
+
1042
+ Analyze the user's request and:
1043
+ 1. **Select the most appropriate component** from the available components list
1044
+ 2. **Determine the data source**: Database query OR External tool (ERP)
1045
+ 3. **Generate complete props** for the selected component including the data retrieval/modification method
1046
+
1047
+ ## Component Selection Rules
1048
+
1049
+ 1. **Match by Intent**: Understand what the user wants to display/achieve
1050
+ 2. **Match by Type**: Choose the component type that best fits the data visualization or action need
1051
+ 3. **Match by Description**: Use component descriptions and keywords to find the best fit
1052
+
1053
+ ## Data Source Decision
1054
+
1055
+ ### Use DATABASE when:
1056
+ - User asks about data that exists in the database schema (customers, orders, products, etc.)
1057
+ - Questions about internal business data (sales, inventory, users, transactions)
1058
+ - CRUD operations on database tables
1059
+
1060
+ ### Use EXTERNAL TOOL when:
1061
+ - User mentions specific external systems (ERP, CRM, email, calendar, etc.)
1062
+ - Data not available in database schema
1063
+ - Actions that require external integrations (send email, create calendar event, sync with ERP)
1064
+ - Tool description matches the user's request
1065
+
1066
+ ## Props Generation Rules
1067
+
1068
+ **CRITICAL**: Look at each component's "Props Structure" in the available components list. Generate ALL props that the component expects.
1069
+
1070
+ ### For Data Viewing Components (charts, tables, KPIs):
1071
+
1072
+ **Option A: Database Query** (when data is in database)
1073
+ \`\`\`json
1074
+ {
1075
+ "query": {
1076
+ "sql": "SELECT column1, column2 FROM table WHERE condition = $param LIMIT 32",
1077
+ "params": { "param": "value" }
1078
+ }
1079
+ }
1080
+ \`\`\`
1081
+
1082
+ **Option B: External Tool** (when data is from ERP/external system)
1083
+ \`\`\`json
1084
+ {
1085
+ "externalTool": {
1086
+ "toolId": "tool_id_from_list",
1087
+ "toolName": "Tool Display Name",
1088
+ "action": "get",
1089
+ "params": {
1090
+ "param1": "value1",
1091
+ "param2": "value2"
1092
+ }
1093
+ }
1094
+ }
1095
+ \`\`\`
1096
+
1097
+ ### For Data Modification Components (forms):
1098
+
1099
+ **Option A: Database Mutation**
1100
+ \`\`\`json
1101
+ {
1102
+ "query": {
1103
+ "sql": "INSERT INTO table (col1, col2) VALUES ($col1, $col2)",
1104
+ "params": {}
1105
+ },
1106
+ "fields": [
1107
+ { "name": "col1", "type": "text", "required": true },
1108
+ { "name": "col2", "type": "number", "required": false }
1109
+ ]
1110
+ }
1111
+ \`\`\`
1112
+
1113
+ **Option B: External Tool Mutation**
1114
+ \`\`\`json
1115
+ {
1116
+ "externalTool": {
1117
+ "toolId": "tool_id_from_list",
1118
+ "toolName": "Tool Display Name",
1119
+ "action": "create|update|delete",
1120
+ "params": {
1121
+ "param1": "value_or_placeholder"
1122
+ }
1123
+ },
1124
+ "fields": [
1125
+ { "name": "param1", "type": "text", "required": true }
1126
+ ]
1127
+ }
1128
+ \`\`\`
1129
+
1130
+ ### Database Query Rules
1131
+ {{DATABASE_RULES}}
1132
+
1133
+ ## Output Format
1134
+
1135
+ You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
1136
+
1137
+ {
1138
+ "componentId": "id_from_available_list",
1139
+ "componentName": "name_of_component",
1140
+ "componentType": "type_of_component",
1141
+ "dataSourceType": "database" | "external_tool",
1142
+ "operationType": "view" | "create" | "update" | "delete",
1143
+ "reasoning": "Why this component was selected and why this data source",
1144
+ "props": {
1145
+ // Generate ALL props based on the component's Props Structure
1146
+ // Include either "query" OR "externalTool" based on data source
1147
+ // Include all other required props (title, description, config, fields, etc.)
1148
+ }
1149
+ }
1150
+
1151
+ **CRITICAL:**
1152
+ - Return ONLY valid JSON (no markdown code blocks, no text before/after)
1153
+ - \`componentId\` MUST match an ID from the available components list
1154
+ - \`dataSourceType\` indicates whether data comes from database or external tool
1155
+ - \`operationType\` indicates the type of operation (view/create/update/delete)
1156
+ - Generate COMPLETE props based on the component's "Props Structure"
1157
+ - For queries, ALWAYS use \`$paramName\` placeholders and include \`params\` object
1158
+ - For external tools, \`toolId\` MUST match an ID from the available tools list
1159
+
1160
+ ---
1161
+
1162
+ ## CONTEXT (for this specific request)
1163
+
1164
+ ### Database Schema
1165
+ {{SCHEMA_DOC}}
1166
+
1167
+ ### Available External Tools
1168
+ {{AVAILABLE_TOOLS}}
1169
+
1170
+ ### Available Components
1171
+ {{AVAILABLE_COMPONENTS}}`,
1172
+ user: `{{USER_PROMPT}}`
1036
1173
  }
1037
1174
  };
1038
1175
  }
@@ -2058,6 +2195,19 @@ var KbNodesRequestMessageSchema = import_zod3.z.object({
2058
2195
  type: import_zod3.z.literal("KB_NODES"),
2059
2196
  payload: KbNodesRequestPayloadSchema
2060
2197
  });
2198
+ var DashCompRequestPayloadSchema = import_zod3.z.object({
2199
+ prompt: import_zod3.z.string(),
2200
+ SA_RUNTIME: import_zod3.z.object({
2201
+ threadId: import_zod3.z.string().optional(),
2202
+ uiBlockId: import_zod3.z.string().optional()
2203
+ }).optional()
2204
+ });
2205
+ var DashCompRequestMessageSchema = import_zod3.z.object({
2206
+ id: import_zod3.z.string(),
2207
+ from: MessageParticipantSchema,
2208
+ type: import_zod3.z.literal("DASH_COMP_REQ"),
2209
+ payload: DashCompRequestPayloadSchema
2210
+ });
2061
2211
 
2062
2212
  // src/index.ts
2063
2213
  init_logger();
@@ -5605,7 +5755,7 @@ var AnthropicLLM = class extends BaseLLM {
5605
5755
  super(config);
5606
5756
  }
5607
5757
  getDefaultModel() {
5608
- return "anthropic/claude-haiku-4-5-20251001";
5758
+ return "anthropic/claude-sonnet-4-5-20250929";
5609
5759
  }
5610
5760
  getDefaultApiKey() {
5611
5761
  return process.env.ANTHROPIC_API_KEY;
@@ -8983,6 +9133,219 @@ function sendResponse8(id, res, sendMessage, clientId) {
8983
9133
  sendMessage(response);
8984
9134
  }
8985
9135
 
9136
+ // src/handlers/dash-comp-request.ts
9137
+ init_logger();
9138
+ init_prompt_loader();
9139
+ async function pickComponentWithLLM(prompt, components, anthropicApiKey, groqApiKey, geminiApiKey, openaiApiKey, llmProviders, _collections, tools) {
9140
+ const errors = [];
9141
+ let availableComponentsText = "No components available";
9142
+ if (components && components.length > 0) {
9143
+ availableComponentsText = components.map((comp, idx) => {
9144
+ const keywords = comp.keywords ? comp.keywords.join(", ") : "";
9145
+ const propsPreview = comp.props ? JSON.stringify(comp.props, null, 2) : "No props";
9146
+ return `${idx + 1}. ID: ${comp.id}
9147
+ Name: ${comp.name}
9148
+ Type: ${comp.type}
9149
+ Description: ${comp.description || "No description"}
9150
+ Keywords: ${keywords}
9151
+ Props Structure: ${propsPreview}`;
9152
+ }).join("\n\n");
9153
+ }
9154
+ let availableToolsText = "No external tools available.";
9155
+ if (tools && tools.length > 0) {
9156
+ availableToolsText = tools.map((tool, idx) => {
9157
+ const paramsStr = Object.entries(tool.params || {}).map(([key, type]) => `${key}: ${type}`).join(", ");
9158
+ return `${idx + 1}. ID: ${tool.id}
9159
+ Name: ${tool.name}
9160
+ Description: ${tool.description}
9161
+ Parameters: { ${paramsStr} }`;
9162
+ }).join("\n\n");
9163
+ }
9164
+ try {
9165
+ const schemaDoc = schema.generateSchemaDocumentation();
9166
+ const databaseRules = await promptLoader.loadDatabaseRules();
9167
+ const prompts = await promptLoader.loadPrompts("dash-comp-picker", {
9168
+ USER_PROMPT: prompt,
9169
+ AVAILABLE_COMPONENTS: availableComponentsText,
9170
+ SCHEMA_DOC: schemaDoc || "No database schema available",
9171
+ DATABASE_RULES: databaseRules,
9172
+ AVAILABLE_TOOLS: availableToolsText
9173
+ });
9174
+ logger.debug("[DASH_COMP_REQ] Loaded dash-comp-picker prompts with schema and tools");
9175
+ const providers = llmProviders || ["anthropic", "gemini", "openai", "groq"];
9176
+ let apiKey;
9177
+ let model = "anthropic/claude-sonnet-4-5-20250929";
9178
+ for (const provider of providers) {
9179
+ if (provider === "anthropic" && anthropicApiKey) {
9180
+ apiKey = anthropicApiKey;
9181
+ model = "anthropic/claude-sonnet-4-5-20250929";
9182
+ break;
9183
+ } else if (provider === "openai" && openaiApiKey) {
9184
+ apiKey = openaiApiKey;
9185
+ model = "openai/gpt-4o-mini";
9186
+ break;
9187
+ } else if (provider === "gemini" && geminiApiKey) {
9188
+ apiKey = geminiApiKey;
9189
+ model = "google/gemini-2.0-flash-001";
9190
+ break;
9191
+ } else if (provider === "groq" && groqApiKey) {
9192
+ apiKey = groqApiKey;
9193
+ model = "groq/llama-3.3-70b-versatile";
9194
+ break;
9195
+ }
9196
+ }
9197
+ if (!apiKey) {
9198
+ errors.push("No API key available for any LLM provider");
9199
+ return { success: false, errors };
9200
+ }
9201
+ logger.info(`[DASH_COMP_REQ] Using model: ${model}`);
9202
+ const result = await LLM.stream(
9203
+ {
9204
+ sys: prompts.system,
9205
+ user: prompts.user
9206
+ },
9207
+ {
9208
+ model,
9209
+ maxTokens: 3e3,
9210
+ temperature: 0.2,
9211
+ apiKey
9212
+ },
9213
+ true
9214
+ // Parse as JSON
9215
+ );
9216
+ logger.debug("[DASH_COMP_REQ] LLM response received");
9217
+ logger.file("[DASH_COMP_REQ] LLM response:", JSON.stringify(result, null, 2));
9218
+ if (!result.componentId || !result.props) {
9219
+ errors.push("Invalid LLM response: missing componentId or props");
9220
+ return { success: false, errors };
9221
+ }
9222
+ const originalComponent = components.find((c) => c.id === result.componentId);
9223
+ if (!originalComponent) {
9224
+ errors.push(`Component ${result.componentId} not found in available components`);
9225
+ return { success: false, errors };
9226
+ }
9227
+ const finalComponent = {
9228
+ ...originalComponent,
9229
+ props: {
9230
+ ...originalComponent.props,
9231
+ ...result.props
9232
+ }
9233
+ };
9234
+ logger.info(`[DASH_COMP_REQ] Successfully picked component: ${finalComponent.name} (${finalComponent.type})`);
9235
+ if (result.props.query) {
9236
+ logger.info(`[DASH_COMP_REQ] Data source: Database query`);
9237
+ }
9238
+ if (result.props.externalTool) {
9239
+ logger.info(`[DASH_COMP_REQ] Data source: External tool - ${result.props.externalTool.toolName}`);
9240
+ }
9241
+ return {
9242
+ success: true,
9243
+ data: {
9244
+ component: finalComponent,
9245
+ reasoning: result.reasoning || "Component selected based on user prompt",
9246
+ dataSource: result.props.query ? "database" : result.props.externalTool ? "external_tool" : "none"
9247
+ },
9248
+ errors: []
9249
+ };
9250
+ } catch (error) {
9251
+ const errorMsg = error instanceof Error ? error.message : String(error);
9252
+ logger.error(`[DASH_COMP_REQ] Error picking component: ${errorMsg}`);
9253
+ errors.push(errorMsg);
9254
+ return { success: false, errors };
9255
+ }
9256
+ }
9257
+ var processDashCompRequest = async (data, components, _sendMessage, anthropicApiKey, groqApiKey, geminiApiKey, openaiApiKey, llmProviders, collections, tools) => {
9258
+ const errors = [];
9259
+ logger.debug("[DASH_COMP_REQ] Parsing incoming message data");
9260
+ const parseResult = DashCompRequestMessageSchema.safeParse(data);
9261
+ if (!parseResult.success) {
9262
+ const zodError = parseResult.error;
9263
+ zodError.errors.forEach((err) => {
9264
+ errors.push(`${err.path.join(".")}: ${err.message}`);
9265
+ });
9266
+ return { success: false, errors };
9267
+ }
9268
+ const dashCompRequest = parseResult.data;
9269
+ const { id, payload } = dashCompRequest;
9270
+ const prompt = payload.prompt;
9271
+ const wsId = dashCompRequest.from.id || "unknown";
9272
+ if (!prompt) {
9273
+ errors.push("Prompt is required");
9274
+ }
9275
+ if (errors.length > 0) {
9276
+ return { success: false, errors, id, wsId };
9277
+ }
9278
+ logger.info(`[DASH_COMP_REQ] Processing request for prompt: "${prompt.substring(0, 50)}..."`);
9279
+ logger.info(`[DASH_COMP_REQ] Available: ${components?.length || 0} components, ${tools?.length || 0} tools`);
9280
+ if (!components || components.length === 0) {
9281
+ logger.warn("[DASH_COMP_REQ] No components available");
9282
+ return {
9283
+ success: false,
9284
+ errors: ["No components available. Please ensure components are loaded."],
9285
+ id,
9286
+ wsId
9287
+ };
9288
+ }
9289
+ const llmResponse = await pickComponentWithLLM(
9290
+ prompt,
9291
+ components,
9292
+ anthropicApiKey,
9293
+ groqApiKey,
9294
+ geminiApiKey,
9295
+ openaiApiKey,
9296
+ llmProviders,
9297
+ collections,
9298
+ tools
9299
+ );
9300
+ return {
9301
+ success: llmResponse.success,
9302
+ data: llmResponse.data,
9303
+ errors: llmResponse.errors,
9304
+ id,
9305
+ wsId
9306
+ };
9307
+ };
9308
+ async function handleDashCompRequest(data, components, sendMessage, anthropicApiKey, groqApiKey, geminiApiKey, openaiApiKey, llmProviders, collections, tools) {
9309
+ const response = await processDashCompRequest(
9310
+ data,
9311
+ components,
9312
+ sendMessage,
9313
+ anthropicApiKey,
9314
+ groqApiKey,
9315
+ geminiApiKey,
9316
+ openaiApiKey,
9317
+ llmProviders,
9318
+ collections,
9319
+ tools
9320
+ );
9321
+ sendDashCompResponse(
9322
+ response.id || data.id,
9323
+ {
9324
+ success: response.success,
9325
+ errors: response.errors,
9326
+ data: response.data
9327
+ },
9328
+ sendMessage,
9329
+ response.wsId || data.from?.id
9330
+ );
9331
+ }
9332
+ function sendDashCompResponse(id, res, sendMessage, clientId) {
9333
+ const response = {
9334
+ id,
9335
+ type: "DASH_COMP_RES",
9336
+ from: { type: "data-agent" },
9337
+ to: {
9338
+ type: "runtime",
9339
+ id: clientId
9340
+ },
9341
+ payload: {
9342
+ ...res
9343
+ }
9344
+ };
9345
+ sendMessage(response);
9346
+ logger.info(`[DASH_COMP_REQ] Response sent to client ${clientId}`);
9347
+ }
9348
+
8986
9349
  // src/auth/user-manager.ts
8987
9350
  var import_fs4 = __toESM(require("fs"));
8988
9351
  var import_path3 = __toESM(require("path"));
@@ -10038,6 +10401,11 @@ var SuperatomSDK = class {
10038
10401
  logger.error("Failed to handle KB nodes request:", error);
10039
10402
  });
10040
10403
  break;
10404
+ case "DASH_COMP_REQ":
10405
+ handleDashCompRequest(parsed, this.components, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.geminiApiKey, this.openaiApiKey, this.llmProviders, this.collections, this.tools).catch((error) => {
10406
+ logger.error("Failed to handle dash comp request:", error);
10407
+ });
10408
+ break;
10041
10409
  default:
10042
10410
  const handler = this.messageTypeHandlers.get(message.type);
10043
10411
  if (handler) {