@rimori/react-client 0.1.0 → 0.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.
Files changed (115) hide show
  1. package/README.md +142 -1
  2. package/dist/{react-client/src/components → components}/ContextMenu.js +1 -2
  3. package/dist/components/Spinner.d.ts +0 -7
  4. package/dist/components/Spinner.js +1 -4
  5. package/dist/components/ai/Assistant.js +1 -1
  6. package/dist/components/ai/Avatar.d.ts +2 -3
  7. package/dist/components/ai/Avatar.js +6 -4
  8. package/dist/components/ai/EmbeddedAssistent/AudioInputField.js +1 -1
  9. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +1 -1
  10. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.js +2 -2
  11. package/dist/components/audio/Playbutton.js +13 -9
  12. package/dist/hooks/I18nHooks.d.ts +1 -1
  13. package/dist/{react-client/src/plugin → hooks}/ThemeSetter.d.ts +1 -1
  14. package/dist/hooks/ThemeSetter.js +31 -0
  15. package/dist/hooks/UseChatHook.d.ts +2 -2
  16. package/dist/index.d.ts +9 -0
  17. package/dist/index.js +9 -0
  18. package/dist/{react-client/plugin → plugin}/ThemeSetter.d.ts +1 -1
  19. package/dist/plugin/ThemeSetter.js +31 -0
  20. package/dist/providers/PluginProvider.d.ts +2 -1
  21. package/dist/providers/PluginProvider.js +10 -7
  22. package/dist/{react-client/src/utils → utils}/FullscreenUtils.js +2 -2
  23. package/package.json +4 -7
  24. package/src/components/ContextMenu.tsx +2 -2
  25. package/src/components/ai/Avatar.tsx +9 -4
  26. package/src/components/ai/EmbeddedAssistent/AudioInputField.tsx +1 -1
  27. package/src/components/audio/Playbutton.tsx +28 -1
  28. package/src/hooks/ThemeSetter.ts +40 -0
  29. package/src/index.ts +10 -0
  30. package/src/providers/PluginProvider.tsx +12 -8
  31. package/tsconfig.json +6 -12
  32. package/dist/components/components/ContextMenu.d.ts +0 -10
  33. package/dist/components/components/ContextMenu.js +0 -135
  34. package/dist/react-client/plugin/ThemeSetter.js +0 -19
  35. package/dist/react-client/src/components/MarkdownEditor.d.ts +0 -8
  36. package/dist/react-client/src/components/MarkdownEditor.js +0 -48
  37. package/dist/react-client/src/components/Spinner.d.ts +0 -8
  38. package/dist/react-client/src/components/Spinner.js +0 -4
  39. package/dist/react-client/src/components/ai/Assistant.d.ts +0 -9
  40. package/dist/react-client/src/components/ai/Assistant.js +0 -58
  41. package/dist/react-client/src/components/ai/Avatar.d.ts +0 -14
  42. package/dist/react-client/src/components/ai/Avatar.js +0 -59
  43. package/dist/react-client/src/components/ai/EmbeddedAssistent/AudioInputField.d.ts +0 -7
  44. package/dist/react-client/src/components/ai/EmbeddedAssistent/AudioInputField.js +0 -37
  45. package/dist/react-client/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.d.ts +0 -8
  46. package/dist/react-client/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +0 -79
  47. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +0 -19
  48. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/MessageSender.js +0 -91
  49. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/Player.d.ts +0 -27
  50. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/Player.js +0 -185
  51. package/dist/react-client/src/components/ai/utils.d.ts +0 -6
  52. package/dist/react-client/src/components/ai/utils.js +0 -13
  53. package/dist/react-client/src/components/audio/Playbutton.d.ts +0 -15
  54. package/dist/react-client/src/components/audio/Playbutton.js +0 -82
  55. package/dist/react-client/src/components/components/ContextMenu.d.ts +0 -10
  56. package/dist/react-client/src/components/components/ContextMenu.js +0 -135
  57. package/dist/react-client/src/hooks/I18nHooks.d.ts +0 -11
  58. package/dist/react-client/src/hooks/I18nHooks.js +0 -25
  59. package/dist/react-client/src/hooks/UseChatHook.d.ts +0 -10
  60. package/dist/react-client/src/hooks/UseChatHook.js +0 -29
  61. package/dist/react-client/src/plugin/ThemeSetter.js +0 -19
  62. package/dist/react-client/src/providers/PluginProvider.d.ts +0 -12
  63. package/dist/react-client/src/providers/PluginProvider.js +0 -142
  64. package/dist/react-client/src/utils/PluginUtils.d.ts +0 -2
  65. package/dist/react-client/src/utils/PluginUtils.js +0 -23
  66. package/dist/rimori-client/src/cli/types/DatabaseTypes.d.ts +0 -103
  67. package/dist/rimori-client/src/cli/types/DatabaseTypes.js +0 -2
  68. package/dist/rimori-client/src/controller/AIController.d.ts +0 -15
  69. package/dist/rimori-client/src/controller/AIController.js +0 -255
  70. package/dist/rimori-client/src/controller/AccomplishmentController.d.ts +0 -38
  71. package/dist/rimori-client/src/controller/AccomplishmentController.js +0 -112
  72. package/dist/rimori-client/src/controller/AudioController.d.ts +0 -37
  73. package/dist/rimori-client/src/controller/AudioController.js +0 -68
  74. package/dist/rimori-client/src/controller/ExerciseController.d.ts +0 -54
  75. package/dist/rimori-client/src/controller/ExerciseController.js +0 -74
  76. package/dist/rimori-client/src/controller/ObjectController.d.ts +0 -42
  77. package/dist/rimori-client/src/controller/ObjectController.js +0 -76
  78. package/dist/rimori-client/src/controller/SettingsController.d.ts +0 -79
  79. package/dist/rimori-client/src/controller/SettingsController.js +0 -118
  80. package/dist/rimori-client/src/controller/SharedContentController.d.ts +0 -106
  81. package/dist/rimori-client/src/controller/SharedContentController.js +0 -285
  82. package/dist/rimori-client/src/controller/TranslationController.d.ts +0 -38
  83. package/dist/rimori-client/src/controller/TranslationController.js +0 -106
  84. package/dist/rimori-client/src/controller/VoiceController.d.ts +0 -9
  85. package/dist/rimori-client/src/controller/VoiceController.js +0 -37
  86. package/dist/rimori-client/src/fromRimori/EventBus.d.ts +0 -101
  87. package/dist/rimori-client/src/fromRimori/EventBus.js +0 -263
  88. package/dist/rimori-client/src/fromRimori/PluginTypes.d.ts +0 -174
  89. package/dist/rimori-client/src/fromRimori/PluginTypes.js +0 -1
  90. package/dist/rimori-client/src/index.d.ts +0 -11
  91. package/dist/rimori-client/src/index.js +0 -10
  92. package/dist/rimori-client/src/plugin/CommunicationHandler.d.ts +0 -48
  93. package/dist/rimori-client/src/plugin/CommunicationHandler.js +0 -234
  94. package/dist/rimori-client/src/plugin/Logger.d.ts +0 -73
  95. package/dist/rimori-client/src/plugin/Logger.js +0 -308
  96. package/dist/rimori-client/src/plugin/RimoriClient.d.ts +0 -258
  97. package/dist/rimori-client/src/plugin/RimoriClient.js +0 -375
  98. package/dist/rimori-client/src/plugin/StandaloneClient.d.ts +0 -17
  99. package/dist/rimori-client/src/plugin/StandaloneClient.js +0 -115
  100. package/dist/rimori-client/src/utils/difficultyConverter.d.ts +0 -4
  101. package/dist/rimori-client/src/utils/difficultyConverter.js +0 -10
  102. package/dist/rimori-client/src/utils/endpoint.d.ts +0 -2
  103. package/dist/rimori-client/src/utils/endpoint.js +0 -2
  104. package/dist/utils/PluginUtils.d.ts +0 -2
  105. package/dist/utils/PluginUtils.js +0 -23
  106. package/index.ts +0 -6
  107. package/src/components/MarkdownEditor.tsx +0 -144
  108. package/src/components/Spinner.tsx +0 -29
  109. package/src/plugin/ThemeSetter.ts +0 -23
  110. package/src/utils/FullscreenUtils.ts +0 -22
  111. /package/dist/{react-client/src/components → components}/ContextMenu.d.ts +0 -0
  112. /package/dist/{react-client/src/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts → components/ai/EmbeddedAssistent/VoiceRecorder.d.ts} +0 -0
  113. /package/dist/{react-client/src/components/ai/EmbeddedAssistent/VoiceRecoder.js → components/ai/EmbeddedAssistent/VoiceRecorder.js} +0 -0
  114. /package/dist/{react-client/src/utils → utils}/FullscreenUtils.d.ts +0 -0
  115. /package/src/components/ai/EmbeddedAssistent/{VoiceRecoder.tsx → VoiceRecorder.tsx} +0 -0
@@ -1,11 +0,0 @@
1
- import { TOptions } from '@rimori/client';
2
- type TranslatorFn = (key: string, options?: TOptions) => string;
3
- /**
4
- * Custom useTranslation hook that provides a translation function and indicates readiness
5
- * @returns An object containing the translation function (`t`) and a boolean (`ready`) indicating if the translator is initialized.
6
- */
7
- export declare function useTranslation(): {
8
- t: TranslatorFn;
9
- ready: boolean;
10
- };
11
- export {};
@@ -1,25 +0,0 @@
1
- import { useEffect, useState } from 'react';
2
- import { useRimori } from '../providers/PluginProvider';
3
- /**
4
- * Custom useTranslation hook that provides a translation function and indicates readiness
5
- * @returns An object containing the translation function (`t`) and a boolean (`ready`) indicating if the translator is initialized.
6
- */
7
- export function useTranslation() {
8
- const { plugin } = useRimori();
9
- const [translatorInstance, setTranslatorInstance] = useState(null);
10
- useEffect(() => {
11
- void plugin.getTranslator().then(setTranslatorInstance);
12
- }, [plugin]);
13
- const safeT = (key, options) => {
14
- // return zero-width space if translator is not initialized to keep text space occupied
15
- if (!translatorInstance)
16
- return '\u200B'; // zero-width space
17
- const result = translatorInstance.t(key, options);
18
- if (!result) {
19
- console.error(`Translation key not found: ${key}`);
20
- return '\u200B'; // zero-width space
21
- }
22
- return result;
23
- };
24
- return { t: safeT, ready: translatorInstance !== null };
25
- }
@@ -1,10 +0,0 @@
1
- import React from 'react';
2
- import { Tool } from '@rimori/client';
3
- import { Message } from '@rimori/client';
4
- export declare function useChat(tools?: Tool[]): {
5
- messages: Message[];
6
- append: (appendMessages: Message[]) => void;
7
- isLoading: boolean;
8
- setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
9
- lastMessage: Message | undefined;
10
- };
@@ -1,29 +0,0 @@
1
- import React from 'react';
2
- import { useRimori } from '../providers/PluginProvider';
3
- export function useChat(tools) {
4
- const [messages, setMessages] = React.useState([]);
5
- const [isLoading, setIsLoading] = React.useState(false);
6
- const { ai } = useRimori();
7
- const append = (appendMessages) => {
8
- const allMessages = [...messages, ...appendMessages];
9
- setMessages(allMessages);
10
- ai.getSteamedText(allMessages, (id, message, finished, toolInvocations) => {
11
- const lastMessage = messages[messages.length - 1];
12
- setIsLoading(!finished);
13
- if ((lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.id) === id) {
14
- lastMessage.content = message;
15
- setMessages([...messages, lastMessage]);
16
- }
17
- else {
18
- setMessages([...allMessages, { id, role: 'assistant', content: message, toolCalls: toolInvocations }]);
19
- }
20
- }, tools);
21
- };
22
- return {
23
- messages,
24
- append,
25
- isLoading,
26
- setMessages,
27
- lastMessage: messages[messages.length - 1],
28
- };
29
- }
@@ -1,19 +0,0 @@
1
- export function setTheme(theme) {
2
- document.documentElement.classList.add('dark:text-gray-200');
3
- if (isDarkTheme(theme)) {
4
- document.documentElement.setAttribute('data-theme', 'dark');
5
- document.documentElement.classList.add('dark', 'dark:bg-gray-950');
6
- document.documentElement.style.background = 'hsl(var(--background))';
7
- }
8
- }
9
- export function isDarkTheme(theme) {
10
- // If no theme provided, try to get from URL as fallback (for standalone mode)
11
- if (!theme) {
12
- const urlParams = new URLSearchParams(window.location.search);
13
- theme = urlParams.get('theme');
14
- }
15
- if (!theme || theme === 'system') {
16
- return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
17
- }
18
- return theme === 'dark';
19
- }
@@ -1,12 +0,0 @@
1
- import React, { ReactNode } from 'react';
2
- import { RimoriClient } from '@rimori/client';
3
- interface PluginProviderProps {
4
- children: ReactNode;
5
- pluginId: string;
6
- settings?: {
7
- disableContextMenu?: boolean;
8
- };
9
- }
10
- export declare const PluginProvider: React.FC<PluginProviderProps>;
11
- export declare const useRimori: () => RimoriClient;
12
- export {};
@@ -1,142 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
11
- import { createContext, useContext, useEffect, useState } from 'react';
12
- import { EventBusHandler, RimoriClient, StandaloneClient } from '@rimori/client';
13
- import ContextMenu from '../components/ContextMenu';
14
- const PluginContext = createContext(null);
15
- export const PluginProvider = ({ children, pluginId, settings }) => {
16
- const [plugin, setPlugin] = useState(null);
17
- const [standaloneClient, setStandaloneClient] = useState(false);
18
- const [applicationMode, setApplicationMode] = useState(null);
19
- const [theme, setTheme] = useState(null);
20
- const isSidebar = applicationMode === 'sidebar';
21
- const isSettings = applicationMode === 'settings';
22
- useEffect(() => {
23
- initEventBus(pluginId);
24
- // Check if we're in an iframe context - if not, we're standalone
25
- const standaloneDetected = window === window.parent;
26
- if (standaloneDetected && !standaloneClient) {
27
- StandaloneClient.getInstance().then((client) => {
28
- client.needsLogin().then((needLogin) => setStandaloneClient(needLogin ? client : true));
29
- });
30
- }
31
- if ((!standaloneDetected && !plugin) || (standaloneDetected && standaloneClient === true)) {
32
- RimoriClient.getInstance(pluginId).then((client) => {
33
- setPlugin(client);
34
- // Get applicationMode and theme from MessageChannel query params
35
- if (!standaloneDetected) {
36
- const mode = client.getQueryParam('applicationMode');
37
- const themeParam = client.getQueryParam('rm_theme');
38
- setApplicationMode(mode);
39
- setTheme(themeParam);
40
- }
41
- });
42
- }
43
- }, [pluginId, standaloneClient]);
44
- //route change
45
- useEffect(() => {
46
- if (!plugin)
47
- return;
48
- //sidebar pages should not report url changes
49
- if (isSidebar)
50
- return;
51
- let lastHash = window.location.hash;
52
- const emitUrlChange = (url) => plugin.event.emit('session.triggerUrlChange', { url });
53
- const interval = setInterval(() => {
54
- if (lastHash === window.location.hash)
55
- return;
56
- lastHash = window.location.hash;
57
- // console.log('url changed:', lastHash);
58
- emitUrlChange(lastHash);
59
- }, 1000);
60
- emitUrlChange(lastHash);
61
- return () => clearInterval(interval);
62
- }, [plugin]);
63
- if (standaloneClient instanceof StandaloneClient) {
64
- return (_jsx(StandaloneAuth, { onLogin: (email, password) => __awaiter(void 0, void 0, void 0, function* () {
65
- if (yield standaloneClient.login(email, password))
66
- setStandaloneClient(true);
67
- }) }));
68
- }
69
- if (!plugin) {
70
- return '';
71
- }
72
- return (_jsxs(PluginContext.Provider, { value: plugin, children: [!(settings === null || settings === void 0 ? void 0 : settings.disableContextMenu) && !isSidebar && !isSettings && _jsx(ContextMenu, { client: plugin }), children] }));
73
- };
74
- export const useRimori = () => {
75
- const context = useContext(PluginContext);
76
- if (context === null) {
77
- throw new Error('useRimori must be used within an PluginProvider');
78
- }
79
- return context;
80
- };
81
- function getUrlParam(name) {
82
- // First try to get from URL hash query params (for compatibility)
83
- const hashParts = window.location.hash.split('?');
84
- if (hashParts.length > 1) {
85
- const hashParams = new URLSearchParams(hashParts[1]);
86
- const hashValue = hashParams.get(name);
87
- if (hashValue)
88
- return hashValue;
89
- }
90
- // Fallback to regular URL search params
91
- const url = new URL(window.location.href);
92
- return url.searchParams.get(name);
93
- }
94
- function initEventBus(pluginId) {
95
- // For now, use URL fallback for EventBus naming - this will be updated once MessageChannel is ready
96
- const isSidebar = getUrlParam('applicationMode') === 'sidebar';
97
- EventBusHandler.getInstance('Plugin EventBus ' + pluginId + ' ' + (isSidebar ? 'sidebar' : 'main'));
98
- }
99
- function StandaloneAuth({ onLogin }) {
100
- const [user, setUser] = useState('');
101
- const [password, setPassword] = useState('');
102
- return (_jsx("div", { style: {
103
- position: 'fixed',
104
- inset: 0,
105
- display: 'flex',
106
- alignItems: 'center',
107
- justifyContent: 'center',
108
- backgroundColor: 'rgba(0, 0, 0, 0.5)',
109
- }, children: _jsxs("div", { style: {
110
- backgroundColor: '#343534',
111
- padding: '1rem',
112
- borderRadius: '0.5rem',
113
- width: '500px',
114
- flexDirection: 'column',
115
- display: 'flex',
116
- alignItems: 'center',
117
- justifyContent: 'center',
118
- }, children: [_jsx("p", { style: { fontSize: '2rem', fontWeight: 'bold', marginBottom: '1rem', textAlign: 'center' }, children: "Rimori Login" }), _jsx("p", { style: { marginBottom: '1rem', textAlign: 'center' }, children: "Please login with your Rimori developer account for this plugin to be able to access the Rimori platform the same it will operate in the Rimori platform." }), _jsx("input", { style: {
119
- marginBottom: '1rem',
120
- width: '100%',
121
- padding: '0.5rem',
122
- borderRadius: '0.5rem',
123
- border: 'none',
124
- backgroundColor: '#444444',
125
- }, type: "email", placeholder: "Email", onChange: (e) => setUser(e.target.value) }), _jsx("input", { style: {
126
- marginBottom: '1rem',
127
- width: '100%',
128
- padding: '0.5rem',
129
- borderRadius: '0.5rem',
130
- border: 'none',
131
- backgroundColor: '#444444',
132
- }, type: "password", placeholder: "Password", onChange: (e) => setPassword(e.target.value) }), _jsx("button", { style: {
133
- marginBottom: '1rem',
134
- width: '100%',
135
- padding: '0.5rem',
136
- borderRadius: '0.5rem',
137
- border: 'none',
138
- backgroundColor: '#928358',
139
- }, onClick: () => {
140
- onLogin(user, password);
141
- }, children: "Login" })] }) }));
142
- }
@@ -1,2 +0,0 @@
1
- export declare function isFullscreen(): boolean;
2
- export declare function triggerFullscreen(onStateChange: (isFullscreen: boolean) => void, selector?: string): void;
@@ -1,23 +0,0 @@
1
- export function isFullscreen() {
2
- return !!document.fullscreenElement;
3
- }
4
- export function triggerFullscreen(onStateChange, selector) {
5
- document.addEventListener('fullscreenchange', () => {
6
- onStateChange(isFullscreen());
7
- });
8
- try {
9
- const ref = document.querySelector(selector || '#root');
10
- if (!isFullscreen()) {
11
- // @ts-ignore
12
- ref.requestFullscreen() || ref.webkitRequestFullscreen();
13
- }
14
- else {
15
- // @ts-ignore
16
- document.exitFullscreen() || document.webkitExitFullscreen();
17
- }
18
- }
19
- catch (error) {
20
- console.error('Failed to enter fullscreen', error.message);
21
- }
22
- onStateChange(isFullscreen());
23
- }
@@ -1,103 +0,0 @@
1
- /**
2
- * Supported database column data types for table schema definitions.
3
- */
4
- type DbColumnType = 'decimal' | 'integer' | 'text' | 'boolean' | 'json' | 'timestamp' | 'uuid';
5
- /**
6
- * Foreign key relationship configuration with cascade delete support.
7
- * Defines a relationship where the source record is deleted when the destination record is deleted.
8
- */
9
- interface ForeignKeyRelation {
10
- /** The target table that this column references */
11
- references_table: string;
12
- /** The target column in the referenced table (defaults to 'id') */
13
- references_column?: string;
14
- /** Whether to cascade delete when the referenced record is deleted */
15
- on_delete_cascade: boolean;
16
- }
17
- /**
18
- * Database column definition with support for types, constraints, and relationships.
19
- */
20
- export interface DbColumnDefinition {
21
- /** The data type of the column */
22
- type: DbColumnType;
23
- /** Human-readable description of the column's purpose */
24
- description: string;
25
- /** Whether the column can contain null values */
26
- nullable?: boolean;
27
- /** Whether the column has a unique constraint */
28
- unique?: boolean;
29
- /** Default value for the column. can also use sql functions like now(), auth.uid() or gen_random_uuid() */
30
- default_value?: string | number | boolean;
31
- /** Array of allowed values for enumerated columns */
32
- /** Foreign key relationship configuration */
33
- foreign_key?: ForeignKeyRelation;
34
- /** The name of the column before it was renamed. */
35
- old_name?: string;
36
- /** Whether the column is deprecated. The column gets renamed to column_name_old. To fully remove the column, first set deprecated to true and then after a release, remove the column from the table definition. */
37
- deprecated?: boolean;
38
- /** Whether the column is a primary key */
39
- /** Restrictions for the column. If the column is restricted, the permission is further restricted. E.g. if the column is restricted to user, then the user can only read the column if they have the right permission.
40
- * Example: Denying users to update the column, but allowing the moderator to update the column.
41
- */
42
- restrict?: {
43
- /** Restrictions for the user */
44
- user: Partial<Omit<DbPermissionDefinition, 'delete'>>;
45
- /** Restrictions for the moderator */
46
- moderator?: Partial<Omit<DbPermissionDefinition, 'delete'>>;
47
- };
48
- }
49
- /**
50
- * Base table structure that all database tables inherit.
51
- * Includes standard audit fields for tracking creation and ownership.
52
- */
53
- interface BaseTableStructure {
54
- /** Unique identifier for the record */
55
- id: DbColumnDefinition;
56
- /** Timestamp when the record was created */
57
- created_at: DbColumnDefinition;
58
- /** ID of the user who created the record */
59
- created_by: DbColumnDefinition;
60
- }
61
- /**
62
- * Complete database table schema definition.
63
- * Defines the structure, constraints, and relationships for a database table.
64
- */
65
- export interface DbTableDefinition {
66
- /** Name of the database table */
67
- table_name: string;
68
- /** Description of the table's purpose and usage */
69
- description: string;
70
- /** Permissions for the table */
71
- permissions: {
72
- user: DbPermissionDefinition;
73
- moderator?: DbPermissionDefinition;
74
- };
75
- /** Column definitions for the table */
76
- columns: {
77
- [column_name: string]: DbColumnDefinition;
78
- };
79
- }
80
- /**
81
- * Permission definition for a database table.
82
- * NONE means the action is not allowed.
83
- * OWN means only do the action on your own records.
84
- * ALL means do the action on all records.
85
- *
86
- * Defines the permissions for a database table.
87
- */
88
- export type DbPermission = 'NONE' | 'OWN' | 'ALL';
89
- /**
90
- * Permission definition for a database table.
91
- * Defines the permissions for a database table.
92
- */
93
- export interface DbPermissionDefinition {
94
- read: DbPermission;
95
- insert: DbPermission;
96
- update: DbPermission;
97
- delete: DbPermission;
98
- }
99
- /**
100
- * Full table definition that includes automatically generated fields.
101
- */
102
- export type FullTable<T extends Record<string, DbColumnDefinition>> = T & BaseTableStructure;
103
- export {};
@@ -1,2 +0,0 @@
1
- // Database table structure definitions
2
- export {};
@@ -1,15 +0,0 @@
1
- import { Tool } from '../fromRimori/PluginTypes';
2
- export interface ToolInvocation {
3
- toolCallId: string;
4
- toolName: string;
5
- args: Record<string, string>;
6
- }
7
- export interface Message {
8
- id?: string;
9
- role: 'user' | 'assistant' | 'system';
10
- content: string;
11
- toolCalls?: ToolInvocation[];
12
- }
13
- export declare function generateText(backendUrl: string, messages: Message[], tools: Tool[], token: string): Promise<any>;
14
- export type OnLLMResponse = (id: string, response: string, finished: boolean, toolInvocations?: ToolInvocation[]) => void;
15
- export declare function streamChatGPT(backendUrl: string, messages: Message[], tools: Tool[], onResponse: OnLLMResponse, token: string): Promise<void>;
@@ -1,255 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- var __rest = (this && this.__rest) || function (s, e) {
11
- var t = {};
12
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
- t[p] = s[p];
14
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
- t[p[i]] = s[p[i]];
18
- }
19
- return t;
20
- };
21
- export function generateText(backendUrl, messages, tools, token) {
22
- return __awaiter(this, void 0, void 0, function* () {
23
- const response = yield fetch(`${backendUrl}/ai/llm`, {
24
- method: 'POST',
25
- body: JSON.stringify({ messages, tools }),
26
- headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
27
- });
28
- return yield response.json();
29
- });
30
- }
31
- export function streamChatGPT(backendUrl, messages, tools, onResponse, token) {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- const messageId = Math.random().toString(36).substring(3);
34
- const currentMessages = [...messages];
35
- console.log('Starting streamChatGPT with:', {
36
- messageId,
37
- messageCount: messages.length,
38
- toolCount: tools.length,
39
- backendUrl,
40
- });
41
- while (true) {
42
- const messagesForApi = currentMessages.map((_a) => {
43
- var { id } = _a, rest = __rest(_a, ["id"]);
44
- return rest;
45
- });
46
- try {
47
- const response = yield fetch(`${backendUrl}/ai/llm`, {
48
- method: 'POST',
49
- body: JSON.stringify({ messages: messagesForApi, tools, stream: true }),
50
- headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
51
- });
52
- if (!response.ok) {
53
- throw new Error(`HTTP error! status: ${response.status}`);
54
- }
55
- if (!response.body) {
56
- console.error('No response body.');
57
- return;
58
- }
59
- const reader = response.body.getReader();
60
- const decoder = new TextDecoder('utf-8');
61
- let content = '';
62
- let done = false;
63
- const toolInvocations = [];
64
- let currentTextId = '';
65
- let isToolCallMode = false;
66
- let buffer = ''; // Buffer for incomplete chunks
67
- while (!done) {
68
- const { value, done: readerDone } = yield reader.read();
69
- if (value) {
70
- const chunk = decoder.decode(value, { stream: true });
71
- buffer += chunk;
72
- // Split by lines, but handle incomplete lines
73
- const lines = buffer.split('\n');
74
- // Keep the last line in buffer if it's incomplete
75
- if (lines.length > 1) {
76
- buffer = lines.pop() || '';
77
- }
78
- for (const line of lines) {
79
- if (line.trim() === '')
80
- continue;
81
- // Handle the new streaming format
82
- if (line.startsWith('data: ')) {
83
- const dataStr = line.substring(6); // Remove 'data: ' prefix
84
- // Handle [DONE] marker
85
- if (dataStr === '[DONE]') {
86
- done = true;
87
- break;
88
- }
89
- try {
90
- const data = JSON.parse(dataStr);
91
- // Log the first message to understand the format
92
- if (!content && !isToolCallMode) {
93
- // console.log('First stream message received:', data);
94
- }
95
- switch (data.type) {
96
- case 'start':
97
- // Stream started, no action needed
98
- // console.log('Stream started');
99
- break;
100
- case 'start-step':
101
- // Step started, no action needed
102
- // console.log('Step started');
103
- break;
104
- case 'reasoning-start':
105
- // Reasoning started, no action needed
106
- console.log('Reasoning started:', data.id);
107
- break;
108
- case 'reasoning-end':
109
- // Reasoning ended, no action needed
110
- console.log('Reasoning ended:', data.id);
111
- break;
112
- case 'text-start':
113
- // Text generation started, store the ID
114
- currentTextId = data.id;
115
- console.log('Text generation started:', data.id);
116
- break;
117
- case 'text-delta':
118
- // Text delta received, append to content
119
- if (data.delta) {
120
- content += data.delta;
121
- onResponse(messageId, content, false);
122
- }
123
- break;
124
- case 'text-end':
125
- // Text generation ended
126
- console.log('Text generation ended:', data.id);
127
- break;
128
- case 'finish-step':
129
- // Step finished, no action needed
130
- // console.log('Step finished');
131
- break;
132
- case 'finish':
133
- // Stream finished
134
- // console.log('Stream finished');
135
- done = true;
136
- break;
137
- // Additional message types that might be present in the AI library
138
- case 'tool-call':
139
- case 'tool-input-available': //for now input calls should be handled the same way as tool calls
140
- // Tool call initiated
141
- console.log('Tool call initiated:', data);
142
- isToolCallMode = true;
143
- if (data.toolCallId && data.toolName && (data.args || data.input)) {
144
- toolInvocations.push({
145
- toolCallId: data.toolCallId,
146
- toolName: data.toolName,
147
- args: data.args || data.input,
148
- });
149
- }
150
- break;
151
- case 'tool-input-delta': //for now input calls should be handled the same way as tool calls
152
- case 'tool-call-delta':
153
- // Tool call delta (for streaming tool calls)
154
- console.log('Tool call delta:', data);
155
- break;
156
- case 'tool-call-end':
157
- // Tool call completed
158
- console.log('Tool call completed:', data);
159
- break;
160
- case 'tool-result':
161
- // Tool execution result
162
- console.log('Tool result:', data);
163
- break;
164
- case 'error':
165
- // Error occurred
166
- console.error('Stream error:', data);
167
- break;
168
- case 'usage':
169
- // Usage information
170
- console.log('Usage info:', data);
171
- break;
172
- case 'model':
173
- // Model information
174
- console.log('Model info:', data);
175
- break;
176
- case 'stop':
177
- // Stop signal
178
- console.log('Stop signal received');
179
- done = true;
180
- break;
181
- default:
182
- // Unknown type, log for debugging
183
- console.log('Unknown stream type:', data.type, data);
184
- break;
185
- }
186
- }
187
- catch (error) {
188
- console.error('Error parsing stream data:', error, dataStr);
189
- }
190
- }
191
- }
192
- }
193
- if (readerDone) {
194
- done = true;
195
- }
196
- }
197
- // Check if we have content or if this was a tool call response
198
- if (content || toolInvocations.length > 0) {
199
- currentMessages.push({
200
- id: messageId,
201
- role: 'assistant',
202
- content: content,
203
- toolCalls: toolInvocations.length > 0 ? toolInvocations : undefined,
204
- });
205
- }
206
- // Handle tool call scenario if tools were provided
207
- if (tools.length > 0 && toolInvocations.length > 0) {
208
- console.log('Tool calls detected, executing tools...');
209
- const toolResults = [];
210
- for (const toolInvocation of toolInvocations) {
211
- const tool = tools.find((t) => t.name === toolInvocation.toolName);
212
- if (tool && tool.execute) {
213
- try {
214
- const result = yield tool.execute(toolInvocation.args);
215
- toolResults.push({
216
- id: Math.random().toString(36).substring(3),
217
- role: 'user',
218
- content: `Tool '${toolInvocation.toolName}' returned: ${JSON.stringify(result)}`,
219
- });
220
- }
221
- catch (error) {
222
- console.error(`Error executing tool ${toolInvocation.toolName}:`, error);
223
- toolResults.push({
224
- id: Math.random().toString(36).substring(3),
225
- role: 'user',
226
- content: `Tool '${toolInvocation.toolName}' failed with error: ${error}`,
227
- });
228
- }
229
- }
230
- }
231
- if (toolResults.length > 0) {
232
- currentMessages.push(...toolResults);
233
- // Continue the loop to handle the next response
234
- continue;
235
- }
236
- }
237
- // Since the new format doesn't seem to support tool calls in the same way,
238
- // we'll assume the stream is complete when we reach the end
239
- // If tools are provided and no content was generated, this might indicate a tool call
240
- if (tools.length > 0 && !content && !isToolCallMode) {
241
- // This might be a tool call scenario, but we need more information
242
- // For now, we'll just finish the stream
243
- console.log('No content generated, but tools provided - might be tool call scenario');
244
- }
245
- onResponse(messageId, content, true, toolInvocations);
246
- return;
247
- }
248
- catch (error) {
249
- console.error('Error in streamChatGPT:', error);
250
- onResponse(messageId, `Error: ${error instanceof Error ? error.message : String(error)}`, true, []);
251
- return;
252
- }
253
- }
254
- });
255
- }