openkbs 0.0.52 → 0.0.55

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.
Files changed (28) hide show
  1. package/README.md +1496 -192
  2. package/package.json +2 -1
  3. package/src/actions.js +407 -13
  4. package/src/index.js +38 -2
  5. package/src/utils.js +1 -1
  6. package/templates/.openkbs/knowledge/examples/ai-copywriter-agent/app/instructions.txt +44 -9
  7. package/templates/.openkbs/knowledge/examples/ai-copywriter-agent/src/Events/actions.js +43 -42
  8. package/templates/.openkbs/knowledge/examples/ai-copywriter-agent/src/Events/handler.js +14 -8
  9. package/templates/.openkbs/knowledge/examples/ai-copywriter-agent/src/Frontend/contentRender.js +95 -12
  10. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/README.md +64 -0
  11. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/app/instructions.txt +160 -0
  12. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/app/settings.json +7 -0
  13. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/src/Events/actions.js +258 -0
  14. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/src/Events/onRequest.js +13 -0
  15. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/src/Events/onRequest.json +3 -0
  16. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/src/Events/onResponse.js +13 -0
  17. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/src/Events/onResponse.json +3 -0
  18. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/src/Frontend/contentRender.js +170 -0
  19. package/templates/.openkbs/knowledge/examples/ai-marketing-agent/src/Frontend/contentRender.json +3 -0
  20. package/templates/.openkbs/knowledge/metadata.json +1 -1
  21. package/templates/CLAUDE.md +593 -222
  22. package/templates/app/instructions.txt +13 -1
  23. package/templates/app/settings.json +5 -6
  24. package/templates/src/Events/actions.js +43 -9
  25. package/templates/src/Events/handler.js +24 -25
  26. package/templates/webpack.contentRender.config.js +8 -2
  27. package/version.json +3 -3
  28. package/MODIFY.md +0 -132
@@ -0,0 +1,258 @@
1
+ // Memory helpers
2
+ const setMemoryValue = async (itemId, value, expirationInMinutes) => {
3
+ const body = {
4
+ value,
5
+ lastUpdated: new Date().toISOString()
6
+ };
7
+ if (expirationInMinutes) {
8
+ body.exp = new Date(Date.now() + expirationInMinutes * 60000).toISOString();
9
+ }
10
+ try {
11
+ await openkbs.updateItem({ itemType: 'memory', itemId, body });
12
+ } catch {
13
+ await openkbs.createItem({ itemType: 'memory', itemId, body });
14
+ }
15
+ };
16
+
17
+ // Upload generated image helper
18
+ const uploadGeneratedImage = async (base64Data, meta) => {
19
+ const fileName = `image-${Date.now()}-${Math.random().toString(36).substring(7)}.png`;
20
+ const uploadResult = await openkbs.uploadImage(base64Data, fileName, 'image/png');
21
+ return { type: 'CHAT_IMAGE', data: { imageUrl: uploadResult.url }, ...meta };
22
+ };
23
+
24
+ export const getActions = (meta) => [
25
+ // Memory Management
26
+ [/<setMemory>([\s\S]*?)<\/setMemory>/s, async (match) => {
27
+ try {
28
+ const data = JSON.parse(match[1].trim());
29
+ if (!data.itemId?.startsWith('memory_')) {
30
+ return { type: "MEMORY_ERROR", error: "itemId must start with 'memory_'", ...meta };
31
+ }
32
+ await setMemoryValue(data.itemId, data.value, data.expirationInMinutes);
33
+ return { type: "MEMORY_UPDATED", itemId: data.itemId, ...meta };
34
+ } catch (e) {
35
+ return { type: "MEMORY_ERROR", error: e.message, ...meta };
36
+ }
37
+ }],
38
+
39
+ [/<deleteItem>([\s\S]*?)<\/deleteItem>/s, async (match) => {
40
+ try {
41
+ const data = JSON.parse(match[1].trim());
42
+ await openkbs.deleteItem(data.itemId);
43
+ return { type: "ITEM_DELETED", itemId: data.itemId, ...meta };
44
+ } catch (e) {
45
+ return { type: "DELETE_ERROR", error: e.message, ...meta };
46
+ }
47
+ }],
48
+
49
+ // AI Image Generation
50
+ [/<createAIImage>([\s\S]*?)<\/createAIImage>/s, async (match) => {
51
+ try {
52
+ const data = JSON.parse(match[1].trim());
53
+ const model = data.model || "gemini-2.5-flash-image";
54
+ const params = { model, n: 1 };
55
+
56
+ if (data.imageUrls?.length > 0) params.imageUrls = data.imageUrls;
57
+
58
+ if (model === 'gpt-image-1') {
59
+ const validSizes = ["1024x1024", "1536x1024", "1024x1536", "auto"];
60
+ params.size = validSizes.includes(data.size) ? data.size : "1024x1024";
61
+ params.quality = "high";
62
+ } else if (model === 'gemini-2.5-flash-image') {
63
+ const validRatios = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];
64
+ params.aspect_ratio = validRatios.includes(data.aspect_ratio) ? data.aspect_ratio : "1:1";
65
+ }
66
+
67
+ const image = await openkbs.generateImage(data.prompt, params);
68
+ return await uploadGeneratedImage(image[0].b64_json, meta);
69
+ } catch (e) {
70
+ return { error: e.message || 'Image creation failed', ...meta };
71
+ }
72
+ }],
73
+
74
+ // AI Video Generation
75
+ [/<createAIVideo>([\s\S]*?)<\/createAIVideo>/s, async (match) => {
76
+ try {
77
+ const data = JSON.parse(match[1].trim());
78
+ const params = {
79
+ video_model: data.model || "sora-2",
80
+ seconds: [4, 8, 12].includes(data.seconds) ? data.seconds : 8
81
+ };
82
+
83
+ if (data.input_reference_url) {
84
+ params.input_reference_url = data.input_reference_url;
85
+ } else {
86
+ params.size = ['720x1280', '1280x720'].includes(data.size) ? data.size : '1280x720';
87
+ }
88
+
89
+ const videoData = await openkbs.generateVideo(data.prompt, params);
90
+
91
+ if (videoData?.[0]?.status === 'pending') {
92
+ return { type: 'VIDEO_PENDING', data: { videoId: videoData[0].video_id }, ...meta };
93
+ }
94
+ if (videoData?.[0]?.video_url) {
95
+ return { type: 'CHAT_VIDEO', data: { videoUrl: videoData[0].video_url }, ...meta };
96
+ }
97
+ return { error: 'Video generation failed', ...meta };
98
+ } catch (e) {
99
+ return { error: e.message, ...meta };
100
+ }
101
+ }],
102
+
103
+ [/<continueVideoPolling>([\s\S]*?)<\/continueVideoPolling>/s, async (match) => {
104
+ try {
105
+ const data = JSON.parse(match[1].trim());
106
+ const videoData = await openkbs.checkVideoStatus(data.videoId);
107
+
108
+ if (videoData?.[0]?.status === 'completed' && videoData[0].video_url) {
109
+ return { type: 'CHAT_VIDEO', data: { videoUrl: videoData[0].video_url }, ...meta };
110
+ } else if (videoData?.[0]?.status === 'pending') {
111
+ return { type: 'VIDEO_PENDING', data: { videoId: data.videoId }, ...meta };
112
+ }
113
+ return { error: 'Video generation failed', ...meta };
114
+ } catch (e) {
115
+ return { error: e.message, ...meta };
116
+ }
117
+ }],
118
+
119
+ // View Image (adds to LLM vision context)
120
+ [/<viewImage>([\s\S]*?)<\/viewImage>/s, async (match) => {
121
+ try {
122
+ const data = JSON.parse(match[1].trim());
123
+ return {
124
+ data: [
125
+ { type: "text", text: `Viewing: ${data.url}` },
126
+ { type: "image_url", image_url: { url: data.url } }
127
+ ],
128
+ ...meta
129
+ };
130
+ } catch (e) {
131
+ return { type: "VIEW_IMAGE_ERROR", error: e.message, ...meta };
132
+ }
133
+ }],
134
+
135
+ // Web scraping
136
+ [/<webpageToText>([\s\S]*?)<\/webpageToText>/s, async (match) => {
137
+ try {
138
+ const data = JSON.parse(match[1].trim());
139
+ let response = await openkbs.webpageToText(data.url);
140
+ if (response?.content?.length > 5000) {
141
+ response.content = response.content.substring(0, 5000);
142
+ }
143
+ return { data: response, ...meta };
144
+ } catch (e) {
145
+ return { error: e.message, ...meta };
146
+ }
147
+ }],
148
+
149
+ // Google Search
150
+ [/<googleSearch>([\s\S]*?)<\/googleSearch>/s, async (match) => {
151
+ try {
152
+ const data = JSON.parse(match[1].trim());
153
+ const response = await openkbs.googleSearch(data.query);
154
+ const results = response?.map(({ title, link, snippet, pagemap }) => ({
155
+ title, link, snippet, image: pagemap?.metatags?.[0]?.["og:image"]
156
+ }));
157
+ return { data: results, ...meta };
158
+ } catch (e) {
159
+ return { error: e.message, ...meta };
160
+ }
161
+ }],
162
+
163
+ // Google Image Search
164
+ [/<googleImageSearch>([\s\S]*?)<\/googleImageSearch>/s, async (match) => {
165
+ try {
166
+ const data = JSON.parse(match[1].trim());
167
+ const response = await openkbs.googleSearch(data.query, { searchType: 'image' });
168
+ const results = response?.map(({ title, link, pagemap }) => ({
169
+ title, link, image: pagemap?.cse_image?.[0]?.src || link
170
+ }))?.slice(0, data.limit || 10);
171
+ return { data: results, ...meta };
172
+ } catch (e) {
173
+ return { error: e.message, ...meta };
174
+ }
175
+ }],
176
+
177
+ // Send Email
178
+ [/<sendMail>([\s\S]*?)<\/sendMail>/s, async (match) => {
179
+ try {
180
+ const data = JSON.parse(match[1].trim());
181
+ await openkbs.sendMail(data.to, data.subject, data.body);
182
+ return { type: 'EMAIL_SENT', data: { to: data.to, subject: data.subject }, ...meta };
183
+ } catch (e) {
184
+ return { error: e.message, ...meta };
185
+ }
186
+ }],
187
+
188
+ // Schedule Task
189
+ [/<scheduleTask>([\s\S]*?)<\/scheduleTask>/s, async (match) => {
190
+ try {
191
+ const data = JSON.parse(match[1].trim());
192
+ let scheduledTime;
193
+
194
+ if (data.time) {
195
+ let isoTimeStr = data.time.replace(' ', 'T');
196
+ if (!isoTimeStr.includes('Z') && !isoTimeStr.includes('+')) isoTimeStr += 'Z';
197
+ scheduledTime = new Date(isoTimeStr).getTime();
198
+ } else if (data.delay) {
199
+ let delayMs = 0;
200
+ if (data.delay.endsWith('h')) delayMs = parseFloat(data.delay) * 3600000;
201
+ else if (data.delay.endsWith('d')) delayMs = parseFloat(data.delay) * 86400000;
202
+ else delayMs = parseFloat(data.delay) * 60000;
203
+ scheduledTime = Date.now() + delayMs;
204
+ } else {
205
+ scheduledTime = Date.now() + 3600000;
206
+ }
207
+
208
+ const response = await openkbs.kb({
209
+ action: 'createScheduledTask',
210
+ scheduledTime: Math.floor(scheduledTime / 60000) * 60000,
211
+ taskPayload: { message: `[SCHEDULED_TASK] ${data.message}`, createdAt: Date.now() },
212
+ description: data.message.substring(0, 50)
213
+ });
214
+
215
+ return { type: 'TASK_SCHEDULED', data: { scheduledTime: new Date(scheduledTime).toISOString(), taskId: response.taskId }, ...meta };
216
+ } catch (e) {
217
+ return { error: e.message, ...meta };
218
+ }
219
+ }],
220
+
221
+ // Get Scheduled Tasks
222
+ [/<getScheduledTasks\s*\/>/s, async () => {
223
+ try {
224
+ const response = await openkbs.kb({ action: 'getScheduledTasks' });
225
+ return { type: 'SCHEDULED_TASKS_LIST', data: response, ...meta };
226
+ } catch (e) {
227
+ return { error: e.message, ...meta };
228
+ }
229
+ }],
230
+
231
+ // Web Page Publishing
232
+ [/<publishWebPage>([\s\S]*?)<\/publishWebPage>/s, async (match) => {
233
+ try {
234
+ const htmlContent = match[1].trim();
235
+ const titleMatch = htmlContent.match(/<title>(.*?)<\/title>/i);
236
+ const title = titleMatch ? titleMatch[1] : 'Page';
237
+ const filename = `${title.toLowerCase().replace(/[^a-z0-9]+/g, '_')}_${Date.now()}.html`;
238
+
239
+ const presignedUrl = await openkbs.kb({
240
+ action: 'createPresignedURL',
241
+ namespace: 'files',
242
+ fileName: filename,
243
+ fileType: 'text/html',
244
+ presignedOperation: 'putObject'
245
+ });
246
+
247
+ const htmlBuffer = Buffer.from(htmlContent, 'utf8');
248
+ await axios.put(presignedUrl, htmlBuffer, {
249
+ headers: { 'Content-Type': 'text/html', 'Content-Length': htmlBuffer.length }
250
+ });
251
+
252
+ const publicUrl = `https://web.file.vpc1.us/files/${openkbs.kbId}/${filename}`;
253
+ return { type: 'WEB_PAGE_PUBLISHED', data: { url: publicUrl, title }, ...meta };
254
+ } catch (e) {
255
+ return { type: 'PUBLISH_ERROR', error: e.message, ...meta };
256
+ }
257
+ }]
258
+ ];
@@ -0,0 +1,13 @@
1
+ import {getActions} from './actions.js';
2
+
3
+ export const handler = async (event) => {
4
+ const actions = getActions({ _meta_actions: [] });
5
+
6
+ for (let [regex, action] of actions) {
7
+ const lastMessage = event.payload.messages[event.payload.messages.length - 1].content;
8
+ const match = lastMessage?.match(regex);
9
+ if (match) return await action(match);
10
+ }
11
+
12
+ return { type: 'CONTINUE' }
13
+ };
@@ -0,0 +1,13 @@
1
+ import {getActions} from './actions.js';
2
+
3
+ export const handler = async (event) => {
4
+ const actions = getActions({ _meta_actions: ["REQUEST_CHAT_MODEL"] });
5
+
6
+ for (let [regex, action] of actions) {
7
+ const lastMessage = event.payload.messages[event.payload.messages.length - 1].content;
8
+ const match = lastMessage?.match(regex);
9
+ if (match) return await action(match);
10
+ }
11
+
12
+ return { type: 'CONTINUE' }
13
+ };
@@ -0,0 +1,170 @@
1
+ import React, { useEffect } from 'react';
2
+ import { Box, Tooltip, Chip } from '@mui/material';
3
+ import SearchIcon from '@mui/icons-material/Search';
4
+ import ImageIcon from '@mui/icons-material/Image';
5
+ import VideoLibraryIcon from '@mui/icons-material/VideoLibrary';
6
+ import LanguageIcon from '@mui/icons-material/Language';
7
+ import EmailIcon from '@mui/icons-material/Email';
8
+ import ScheduleIcon from '@mui/icons-material/Schedule';
9
+ import MemoryIcon from '@mui/icons-material/Memory';
10
+ import PublishIcon from '@mui/icons-material/Publish';
11
+
12
+ // Command patterns to detect
13
+ const COMMAND_PATTERNS = [
14
+ /<createAIImage>[\s\S]*?<\/createAIImage>/,
15
+ /<createAIVideo>[\s\S]*?<\/createAIVideo>/,
16
+ /<continueVideoPolling>[\s\S]*?<\/continueVideoPolling>/,
17
+ /<googleSearch>[\s\S]*?<\/googleSearch>/,
18
+ /<googleImageSearch>[\s\S]*?<\/googleImageSearch>/,
19
+ /<viewImage>[\s\S]*?<\/viewImage>/,
20
+ /<webpageToText>[\s\S]*?<\/webpageToText>/,
21
+ /<sendMail>[\s\S]*?<\/sendMail>/,
22
+ /<scheduleTask>[\s\S]*?<\/scheduleTask>/,
23
+ /<getScheduledTasks\s*\/>/,
24
+ /<setMemory>[\s\S]*?<\/setMemory>/,
25
+ /<deleteItem>[\s\S]*?<\/deleteItem>/,
26
+ /<publishWebPage>[\s\S]*?<\/publishWebPage>/
27
+ ];
28
+
29
+ // Icon mapping for commands
30
+ const commandIcons = {
31
+ createAIImage: ImageIcon,
32
+ createAIVideo: VideoLibraryIcon,
33
+ continueVideoPolling: VideoLibraryIcon,
34
+ googleSearch: SearchIcon,
35
+ googleImageSearch: SearchIcon,
36
+ viewImage: ImageIcon,
37
+ webpageToText: LanguageIcon,
38
+ sendMail: EmailIcon,
39
+ scheduleTask: ScheduleIcon,
40
+ getScheduledTasks: ScheduleIcon,
41
+ setMemory: MemoryIcon,
42
+ deleteItem: MemoryIcon,
43
+ publishWebPage: PublishIcon
44
+ };
45
+
46
+ // Parse commands from content
47
+ const parseCommands = (content) => {
48
+ const commands = [];
49
+ const regex = /<(\w+)>([\s\S]*?)<\/\1>|<(\w+)\s*\/>/g;
50
+ let match;
51
+ while ((match = regex.exec(content)) !== null) {
52
+ const name = match[1] || match[3];
53
+ let data = match[2] || '';
54
+ try {
55
+ data = data.trim() ? JSON.parse(data.trim()) : {};
56
+ } catch (e) {
57
+ data = data.trim();
58
+ }
59
+ commands.push({ name, data });
60
+ }
61
+ return commands;
62
+ };
63
+
64
+ // Render command as icon with tooltip
65
+ const CommandIcon = ({ command }) => {
66
+ const Icon = commandIcons[command.name] || SearchIcon;
67
+ return (
68
+ <Tooltip
69
+ title={
70
+ <Box sx={{ p: 1 }}>
71
+ <Box sx={{ fontWeight: 'bold', color: '#4CAF50', mb: 0.5 }}>{command.name}</Box>
72
+ <pre style={{ margin: 0, fontSize: '10px', maxWidth: 300, overflow: 'auto' }}>
73
+ {typeof command.data === 'object' ? JSON.stringify(command.data, null, 2) : command.data}
74
+ </pre>
75
+ </Box>
76
+ }
77
+ arrow
78
+ >
79
+ <Box sx={{
80
+ display: 'inline-flex',
81
+ width: 32, height: 32,
82
+ borderRadius: '50%',
83
+ backgroundColor: 'rgba(76, 175, 80, 0.1)',
84
+ border: '2px solid rgba(76, 175, 80, 0.3)',
85
+ alignItems: 'center',
86
+ justifyContent: 'center',
87
+ mx: 0.5,
88
+ cursor: 'pointer',
89
+ '&:hover': { backgroundColor: 'rgba(76, 175, 80, 0.2)', transform: 'scale(1.1)' },
90
+ transition: 'all 0.2s'
91
+ }}>
92
+ <Icon sx={{ fontSize: 16, color: '#4CAF50' }} />
93
+ </Box>
94
+ </Tooltip>
95
+ );
96
+ };
97
+
98
+ // Image renderer
99
+ const ImageWithDownload = ({ imageUrl }) => (
100
+ <Box sx={{ position: 'relative', display: 'inline-block' }}>
101
+ <img
102
+ src={imageUrl}
103
+ alt="Generated"
104
+ style={{ maxWidth: '100%', borderRadius: 8 }}
105
+ />
106
+ </Box>
107
+ );
108
+
109
+ // do NOT useState() directly in this function, it is not a React component
110
+ const onRenderChatMessage = async (params) => {
111
+ let { content, role } = params.messages[params.msgIndex];
112
+ const { msgIndex, messages } = params;
113
+
114
+ let JSONData;
115
+ try {
116
+ JSONData = JSON.parse(content);
117
+ } catch (e) {}
118
+
119
+ // Hide CONTINUE type system messages
120
+ if (JSONData?.type === 'CONTINUE') {
121
+ return JSON.stringify({ type: 'HIDDEN_MESSAGE' });
122
+ }
123
+
124
+ // Handle CHAT_IMAGE type
125
+ if (JSONData?.type === 'CHAT_IMAGE' && JSONData?.data?.imageUrl) {
126
+ return <ImageWithDownload imageUrl={JSONData.data.imageUrl} />;
127
+ }
128
+
129
+ // Hide system response if previous message had a command
130
+ if (role === 'system' && JSONData &&
131
+ (JSONData._meta_type === 'EVENT_STARTED' || JSONData._meta_type === 'EVENT_FINISHED')) {
132
+ const hasSpecialRendering = JSONData.type === 'CHAT_IMAGE' || JSONData.type === 'CHAT_VIDEO';
133
+ if (!hasSpecialRendering && msgIndex > 0) {
134
+ const prevMessage = messages[msgIndex - 1];
135
+ const prevHasCommand = COMMAND_PATTERNS.some(p => p.test(prevMessage.content));
136
+ if (prevHasCommand) return JSON.stringify({ type: 'HIDDEN_MESSAGE' });
137
+ }
138
+ }
139
+
140
+ // Render commands as icons
141
+ const hasCommand = COMMAND_PATTERNS.some(p => p.test(content));
142
+ if (hasCommand) {
143
+ const commands = parseCommands(content);
144
+ return (
145
+ <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
146
+ {commands.map((cmd, i) => <CommandIcon key={i} command={cmd} />)}
147
+ </Box>
148
+ );
149
+ }
150
+
151
+ return null; // Use default rendering
152
+ };
153
+
154
+ const Header = ({ setRenderSettings }) => {
155
+ useEffect(() => {
156
+ setRenderSettings({
157
+ inputLabelsQuickSend: true,
158
+ disableBalanceView: false,
159
+ disableEmojiButton: true,
160
+ disableChatModelsSelect: false,
161
+ backgroundOpacity: 0.02
162
+ });
163
+ }, [setRenderSettings]);
164
+
165
+ return null;
166
+ };
167
+
168
+ const exports = { onRenderChatMessage, Header };
169
+ window.contentRender = exports;
170
+ export default exports;
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.0.16"
2
+ "version": "0.0.21"
3
3
  }