@ramme-io/shared 2.0.1 → 2.0.3

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/src/ai/tools.ts DELETED
@@ -1,178 +0,0 @@
1
- /**
2
- * @file tools.ts
3
- * @package @ramme-io/shared
4
- * @description AI Tool Definitions & Schemas
5
- *
6
- * ARCHITECTURAL ROLE:
7
- * Defines the contract between the LLM and our UI components for Generative UI.
8
- * All tool schemas use Zod for runtime validation. This ensures type-safe tool
9
- * calling across any LLM provider (Anthropic, OpenAI, Ollama, etc.).
10
- */
11
-
12
- import { z } from 'zod';
13
-
14
- // ─────────────────────────────────────────────────────────────────────
15
- // Tool Parameter Schemas
16
- // ─────────────────────────────────────────────────────────────────────
17
-
18
- /**
19
- * Telemetry Graph Tool
20
- * Allows the LLM to render an interactive time-series chart of sensor data.
21
- */
22
- export const telemetryGraphParameters = z.object({
23
- deviceId: z.string().min(1, 'Device ID is required'),
24
- timeRange: z.enum(['1h', '24h', '7d'], {
25
- errorMap: () => ({ message: 'Time range must be 1h, 24h, or 7d' }),
26
- }),
27
- metrics: z
28
- .array(
29
- z.enum(['temperature', 'humidity', 'vwc', 'ec', 'ph', 'pressure', 'co2'])
30
- )
31
- .min(1, 'At least one metric is required')
32
- .max(4, 'Maximum 4 metrics per graph'),
33
- });
34
-
35
- export type TelemetryGraphParams = z.infer<typeof telemetryGraphParameters>;
36
-
37
- /**
38
- * Stock Chart Tool
39
- * Allows the LLM to render an interactive financial chart with price, volume, and technical indicators.
40
- */
41
- export const stockChartParameters = z.object({
42
- ticker: z.string().min(1).describe("The stock ticker symbol explicitly requested by the user. YOU MUST EXTRACT AND PROVIDE THIS (e.g., 'AAPL', 'MSFT')."),
43
- timeRange: z.enum(['1D', '1W', '1M', '1Y'], {
44
- errorMap: () => ({ message: 'Time range must be 1D, 1W, 1M, or 1Y' }),
45
- }).describe("The time range for the chart. Choose based on user request or default to '1M'."),
46
- metrics: z
47
- .array(z.enum(['price', 'volume', 'moving_average']))
48
- .min(1, 'At least one metric is required')
49
- .describe("Array of metrics to display. Always include 'price' and 'volume' unless user specifies otherwise."),
50
- });
51
-
52
- export type StockChartParams = z.infer<typeof stockChartParameters>;
53
-
54
- // ─────────────────────────────────────────────────────────────────────
55
- // Tool Definition Interface
56
- // ─────────────────────────────────────────────────────────────────────
57
-
58
- /**
59
- * Generic tool definition structure.
60
- * Each tool must have a unique name, description, and Zod parameter schema.
61
- */
62
- export interface ToolDefinition<T extends z.ZodSchema = z.ZodSchema> {
63
- name: string;
64
- description: string;
65
- parameters: T;
66
- }
67
-
68
- /**
69
- * Tool call object extracted from LLM streaming response.
70
- * This is what gets attached to the ChatMessage when a tool is invoked.
71
- */
72
- export interface ToolCall {
73
- name: string;
74
- arguments: Record<string, any>;
75
- id?: string; // Optional unique identifier for the tool call
76
- }
77
-
78
- // ─────────────────────────────────────────────────────────────────────
79
- // Tool Registry
80
- // ─────────────────────────────────────────────────────────────────────
81
-
82
- /**
83
- * Registry of all available AI tools.
84
- * Add new tools here to make them available to the LLM.
85
- */
86
- export const AI_TOOLS: Record<string, ToolDefinition> = {
87
- get_telemetry_graph: {
88
- name: 'get_telemetry_graph',
89
- description:
90
- 'Displays an interactive line chart of historical sensor telemetry data. Use this when the user asks to visualize trends, compare metrics over time, or analyze device performance. Supports temperature, humidity, VWC (volumetric water content), EC (electrical conductivity), pH, pressure, and CO2.',
91
- parameters: telemetryGraphParameters,
92
- },
93
- get_stock_chart: {
94
- name: 'get_stock_chart',
95
- description:
96
- 'Displays an interactive financial chart with price movements, volume, and technical indicators. Use this when the user asks to visualize stock performance, analyze price trends, or compare financial metrics over time. Supports daily (1D), weekly (1W), monthly (1M), and yearly (1Y) time ranges.',
97
- parameters: stockChartParameters,
98
- },
99
- };
100
-
101
- /**
102
- * Generates the system instruction fragment for tool calling.
103
- * This is appended to the system prompt when tools are enabled.
104
- * The LLM is instructed to output tool calls in a strict XML format.
105
- */
106
- export function generateToolSystemPrompt(tools: ToolDefinition[]): string {
107
- const toolDescriptions = tools
108
- .map((tool) => {
109
- // For the LLM, we describe the parameters in a readable format
110
- // rather than serializing the full Zod schema
111
- let paramsDesc = 'See tool description for parameter details';
112
-
113
- // If we need to provide schema info, we can parse it from the Zod object
114
- // For now, keeping it simple since the description already explains usage
115
- if (tool.name === 'get_telemetry_graph') {
116
- paramsDesc = `{
117
- "deviceId": "string (required)",
118
- "timeRange": "enum: '1h' | '24h' | '7d' (required)",
119
- "metrics": "array of enum: 'temperature' | 'humidity' | 'vwc' | 'ec' | 'ph' | 'pressure' | 'co2' (1-4 items required)"
120
- }`;
121
- }
122
-
123
- if (tool.name === 'get_stock_chart') {
124
- paramsDesc = `{
125
- "ticker": "string (required, e.g., 'AAPL', 'TSLA')",
126
- "timeRange": "enum: '1D' | '1W' | '1M' | '1Y' (required)",
127
- "metrics": "array of enum: 'price' | 'volume' | 'moving_average' (1+ items required)"
128
- }`;
129
- }
130
-
131
- return `<tool name="${tool.name}">
132
- <description>${tool.description}</description>
133
- <parameters>${paramsDesc}</parameters>
134
- </tool>`;
135
- })
136
- .join('\n\n');
137
-
138
- return `
139
- You have access to the following tools to enhance your responses with interactive UI components:
140
-
141
- ${toolDescriptions}
142
-
143
- When you need to use a tool, output it in this EXACT XML format:
144
- <tool_call>
145
- {
146
- "name": "tool_name",
147
- "arguments": {
148
- "param1": "value1",
149
- "param2": "value2"
150
- }
151
- }
152
- </tool_call>
153
-
154
- CRITICAL RULES:
155
- 1. Tool calls MUST be valid JSON wrapped in <tool_call></tool_call> XML tags.
156
- 2. Do NOT add any text before or after the tool_call tags on the same line.
157
- 3. You can include explanatory text before or after the tool call in separate paragraphs.
158
- 4. Only use tools when they directly serve the user's request.
159
- 5. Validate that all required parameters are present before calling a tool.
160
-
161
- Example usage:
162
- User: "Show me temperature trends for device ABC over the last 24 hours"
163
- You: "I'll visualize the temperature data for device ABC over the past day.
164
-
165
- <tool_call>
166
- {
167
- "name": "get_telemetry_graph",
168
- "arguments": {
169
- "deviceId": "ABC",
170
- "timeRange": "24h",
171
- "metrics": ["temperature"]
172
- }
173
- }
174
- </tool_call>
175
-
176
- The graph above shows the temperature fluctuations. Notice the spike around noon, which may indicate..."
177
- `.trim();
178
- }
@@ -1,35 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- export const BodewellDeviceID = z.enum([
4
- 'STK-V1-001', 'STK-V1-002', 'STK-V1-003',
5
- 'STK-PRO-001', 'STK-VIS-001'
6
- ]);
7
-
8
- // 1. The Telemetry Payload
9
- // Hardware may send partial packets or use stick_id alias.
10
- // Only device_id and soil_vwc are guaranteed per transmission.
11
- export const BodewellTelemetrySchema = z.object({
12
- device_id: BodewellDeviceID,
13
- stick_id: z.string().optional().describe("Firmware alias for device_id"),
14
- timestamp: z.number().optional().describe("Epoch timestamp from NTP"),
15
- air_temp: z.number().optional().describe("Celsius"),
16
- air_humid: z.number().optional().describe("Relative Humidity %"),
17
- humidity: z.number().optional().describe("Firmware alias for air_humid"),
18
- air_pressure: z.number().optional().describe("hPa"),
19
- pressure: z.number().optional().describe("Firmware alias for air_pressure"),
20
- light_lux: z.number().optional().describe("Lux level"),
21
- soil_temp_stemma: z.number().optional().describe("Celsius"),
22
- soil_vwc: z.number().describe("Volumetric Water Content / Raw Capacitance"),
23
- soil_moisture: z.number().optional().describe("Firmware alias for raw capacitance"),
24
- soil_moisture_raw: z.number().optional().describe("Unscaled capacitance (300-1100)"),
25
- }).passthrough();
26
-
27
- // 2. The Command Payload (Updated for your actual API route)
28
- export const BodewellCommandSchema = z.object({
29
- stick_id: BodewellDeviceID, // Note: Your API uses stick_id here, not device_id
30
- type: z.enum(['dry', 'wet']),
31
- value: z.number(),
32
- });
33
-
34
- export type BodewellTelemetry = z.infer<typeof BodewellTelemetrySchema>;
35
- export type BodewellCommand = z.infer<typeof BodewellCommandSchema>;
package/src/schema.ts DELETED
@@ -1,209 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- /**
4
- * @file schema.ts
5
- * @description The "Application Constitution".
6
- *
7
- * ARCHITECTURAL ROLE:
8
- * This file uses Zod to define the strict runtime validation rules for the
9
- * App Manifest. While `manifest-types.ts` handles compile-time TypeScript checks,
10
- * this file handles runtime validation, ensuring that any JSON loaded into the
11
- * engine (whether from a file, API, or user input) is structurally sound.
12
- *
13
- * LAYERS DEFINED:
14
- * 1. **SaaS Layer:** Data resources, fields, and tables.
15
- * 2. **Physical Layer:** IoT signals, sensors, and entities.
16
- * 3. **Logic Layer:** Workflows, triggers, and automated actions.
17
- * 4. **Presentation Layer:** Pages, sections, and UI blocks.
18
- */
19
-
20
- // ------------------------------------------------------------------
21
- // 1. DATA RESOURCE DEFINITIONS (SaaS Layer)
22
- // ------------------------------------------------------------------
23
-
24
- export const FieldSchema = z.object({
25
- key: z.string(),
26
- label: z.string(),
27
- type: z.enum(['text', 'number', 'currency', 'date', 'boolean', 'status', 'email', 'image', 'textarea']),
28
- required: z.boolean().optional(),
29
- description: z.string().optional(),
30
- defaultValue: z.any().optional(),
31
- });
32
- export type FieldDefinition = z.infer<typeof FieldSchema>;
33
-
34
- export const ResourceSchema = z.object({
35
- id: z.string(),
36
- name: z.string(),
37
- fields: z.array(FieldSchema),
38
- defaultView: z.enum(['table', 'grid', 'list']).optional(),
39
- features: z.object({
40
- searchable: z.boolean().optional(),
41
- creatable: z.boolean().optional(),
42
- editable: z.boolean().optional(),
43
- deletable: z.boolean().optional(),
44
- exportable: z.boolean().optional(),
45
- }).optional(),
46
- });
47
- export type ResourceDefinition = z.infer<typeof ResourceSchema>;
48
-
49
-
50
- // ------------------------------------------------------------------
51
- // 2. SIGNAL & IOT DEFINITIONS (Physical Layer)
52
- // ------------------------------------------------------------------
53
-
54
- export const SignalSchema = z.object({
55
- id: z.string().min(1, "Signal ID is required"),
56
- label: z.string(),
57
- description: z.string().optional(),
58
- kind: z.enum(['sensor', 'actuator', 'setpoint', 'metric', 'status', 'kpi']),
59
- source: z.enum(['mock', 'mqtt', 'http', 'derived', 'local']),
60
-
61
- // Connectivity
62
- topic: z.string().optional(),
63
- endpoint: z.string().optional(),
64
- jsonPath: z.string().optional(),
65
- refreshRate: z.number().optional().default(1000),
66
-
67
- // Values
68
- defaultValue: z.any().optional(),
69
- unit: z.string().optional(),
70
- min: z.number().optional(),
71
- max: z.number().optional(),
72
- });
73
- export type SignalDefinition = z.infer<typeof SignalSchema>;
74
-
75
- export const EntitySchema = z.object({
76
- id: z.string(),
77
- name: z.string(),
78
- description: z.string().optional(),
79
- type: z.string(),
80
- category: z.string().default('logical'),
81
- signals: z.array(z.string()),
82
- ui: z.object({
83
- icon: z.string().optional(),
84
- color: z.string().optional(),
85
- dashboardComponent: z.string().optional(),
86
- }).optional(),
87
- });
88
- export type EntityDefinition = z.infer<typeof EntitySchema>;
89
-
90
- // ------------------------------------------------------------------
91
- // 3. LOGIC & WORKFLOW DEFINITIONS (Logic Layer)
92
- // ------------------------------------------------------------------
93
-
94
- export const TriggerSchema = z.object({
95
- id: z.string(),
96
- type: z.enum(['signal_change', 'manual_action', 'schedule', 'webhook']),
97
- config: z.record(z.string(), z.any()),
98
- });
99
-
100
- export const ActionSchema = z.object({
101
- id: z.string(),
102
- type: z.enum([
103
- 'update_resource',
104
- 'send_notification',
105
- 'mqtt_publish',
106
- 'api_call',
107
- 'navigate',
108
- 'agent_task'
109
- ]),
110
- config: z.record(z.string(), z.any()),
111
- });
112
-
113
- export const WorkflowSchema = z.object({
114
- id: z.string(),
115
- name: z.string(),
116
- active: z.boolean().default(true),
117
- trigger: TriggerSchema,
118
- actions: z.array(ActionSchema),
119
- });
120
- export type WorkflowDefinition = z.infer<typeof WorkflowSchema>;
121
- export type ActionDefinition = z.infer<typeof ActionSchema>;
122
-
123
-
124
- // ------------------------------------------------------------------
125
- // 4. UI LAYOUT DEFINITIONS (Presentation Layer)
126
- // ------------------------------------------------------------------
127
-
128
- export const BlockSchema = z.object({
129
- id: z.string(),
130
- type: z.string(),
131
- props: z.record(z.string(), z.any()),
132
- layout: z.object({
133
- colSpan: z.number().optional(),
134
- rowSpan: z.number().optional(),
135
- }).optional(),
136
- });
137
- // Explicitly export the Block type
138
- export type Block = z.infer<typeof BlockSchema>;
139
-
140
- export const PageSectionSchema = z.object({
141
- id: z.string(),
142
- title: z.string().optional(),
143
- description: z.string().optional(),
144
- layout: z.object({
145
- columns: z.number().optional(),
146
- variant: z.enum(['grid', 'stack', 'split']).optional()
147
- }).optional(),
148
- blocks: z.array(BlockSchema),
149
- });
150
- // Explicitly export the PageSection type
151
- export type PageSection = z.infer<typeof PageSectionSchema>;
152
-
153
- export const PageSchema = z.object({
154
- id: z.string(),
155
- slug: z.string(),
156
- title: z.string(),
157
- description: z.string().optional(),
158
- icon: z.string().optional(),
159
- sections: z.array(PageSectionSchema),
160
- });
161
- export type PageDefinition = z.infer<typeof PageSchema>;
162
-
163
-
164
- // ------------------------------------------------------------------
165
- // 5. MASTER APP SPECIFICATION (Root)
166
- // ------------------------------------------------------------------
167
-
168
- export const AppSpecificationSchema = z.object({
169
- meta: z.object({
170
- name: z.string(),
171
- version: z.string(),
172
- description: z.string().optional(),
173
- author: z.string().optional(),
174
- createdAt: z.string().optional(),
175
- }),
176
-
177
- config: z.object({
178
- theme: z.enum(['light', 'dark', 'system', 'corporate', 'midnight', 'blueprint']).default('system'),
179
- mockMode: z.boolean().default(true),
180
- brokerUrl: z.string().optional(),
181
- }),
182
-
183
- modules: z.array(z.string()).optional(),
184
- resources: z.array(ResourceSchema).optional(),
185
-
186
- domain: z.object({
187
- signals: z.array(SignalSchema),
188
- entities: z.array(EntitySchema),
189
- workflows: z.array(WorkflowSchema).optional(),
190
- }),
191
-
192
- pages: z.array(PageSchema).optional(),
193
- });
194
-
195
- export type AppSpecification = z.infer<typeof AppSpecificationSchema>;
196
-
197
-
198
- // ------------------------------------------------------------------
199
- // 6. FLORA TELEMETRY (Legacy)
200
- // ------------------------------------------------------------------
201
-
202
- export const FloraTelemetrySchema = z.object({
203
- timestamp: z.number(),
204
- soilMoisture: z.number().min(0).max(100),
205
- ambientLight: z.number().min(0).max(100000),
206
- temperature: z.number().min(-40).max(125),
207
- });
208
-
209
- export type FloraTelemetry = z.infer<typeof FloraTelemetrySchema>;
package/tsconfig.json DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "ESNext",
5
- "moduleResolution": "bundler",
6
- "strict": true,
7
- "esModuleInterop": true,
8
- "declaration": true,
9
- "declarationMap": true,
10
- "sourceMap": true,
11
- "outDir": "./dist",
12
- "rootDir": "."
13
- },
14
- "include": ["index.ts", "src/**/*.ts"],
15
- "exclude": ["dist", "node_modules"]
16
- }