@rimori/client 1.1.10 → 1.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 (151) hide show
  1. package/README.md +128 -45
  2. package/dist/cli/scripts/init/dev-registration.d.ts +35 -0
  3. package/dist/cli/scripts/init/dev-registration.js +175 -0
  4. package/dist/cli/scripts/init/env-setup.d.ts +9 -0
  5. package/dist/cli/scripts/init/env-setup.js +43 -0
  6. package/dist/cli/scripts/init/file-operations.d.ts +4 -0
  7. package/dist/cli/scripts/init/file-operations.js +51 -0
  8. package/dist/cli/scripts/init/html-cleaner.d.ts +4 -0
  9. package/dist/cli/scripts/init/html-cleaner.js +38 -0
  10. package/dist/cli/scripts/init/main.d.ts +2 -0
  11. package/dist/cli/scripts/init/main.js +159 -0
  12. package/dist/cli/scripts/init/package-setup.d.ts +32 -0
  13. package/dist/cli/scripts/init/package-setup.js +75 -0
  14. package/dist/cli/scripts/init/router-transformer.d.ts +6 -0
  15. package/dist/cli/scripts/init/router-transformer.js +254 -0
  16. package/dist/cli/scripts/init/tailwind-config.d.ts +4 -0
  17. package/dist/cli/scripts/init/tailwind-config.js +56 -0
  18. package/dist/cli/scripts/init/vite-config.d.ts +20 -0
  19. package/dist/cli/scripts/init/vite-config.js +54 -0
  20. package/dist/cli/scripts/release/release-config-upload.d.ts +7 -0
  21. package/dist/cli/scripts/release/release-config-upload.js +116 -0
  22. package/dist/cli/scripts/release/release-db-update.d.ts +6 -0
  23. package/dist/cli/scripts/release/release-db-update.js +100 -0
  24. package/dist/cli/scripts/release/release-file-upload.d.ts +6 -0
  25. package/dist/cli/scripts/release/release-file-upload.js +136 -0
  26. package/dist/cli/scripts/release/release.d.ts +23 -0
  27. package/dist/cli/scripts/release/release.js +70 -0
  28. package/dist/cli/types/DatabaseTypes.d.ts +103 -0
  29. package/dist/cli/types/DatabaseTypes.js +2 -0
  30. package/dist/components/ai/Assistant.js +4 -4
  31. package/dist/components/ai/Avatar.d.ts +3 -2
  32. package/dist/components/ai/Avatar.js +10 -5
  33. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +1 -1
  34. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts +1 -0
  35. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.js +12 -6
  36. package/dist/components/ai/utils.js +0 -1
  37. package/dist/components/audio/Playbutton.js +3 -3
  38. package/dist/{core → components}/components/ContextMenu.js +2 -2
  39. package/dist/components.d.ts +5 -5
  40. package/dist/components.js +5 -5
  41. package/dist/core/controller/AIController.d.ts +15 -0
  42. package/dist/core/controller/AIController.js +120 -0
  43. package/dist/{controller → core/controller}/ObjectController.d.ts +8 -0
  44. package/dist/{controller → core/controller}/SettingsController.d.ts +12 -4
  45. package/dist/{controller → core/controller}/SettingsController.js +0 -25
  46. package/dist/{controller → core/controller}/SharedContentController.d.ts +1 -1
  47. package/dist/{controller → core/controller}/SharedContentController.js +4 -4
  48. package/dist/core/core.d.ts +13 -0
  49. package/dist/core/core.js +8 -0
  50. package/dist/{plugin/fromRimori → fromRimori}/EventBus.d.ts +3 -3
  51. package/dist/{plugin/fromRimori → fromRimori}/EventBus.js +25 -8
  52. package/dist/fromRimori/PluginTypes.d.ts +171 -0
  53. package/dist/hooks/UseChatHook.d.ts +2 -1
  54. package/dist/hooks/UseChatHook.js +3 -3
  55. package/dist/index.d.ts +5 -3
  56. package/dist/index.js +4 -3
  57. package/dist/plugin/AccomplishmentHandler.d.ts +1 -1
  58. package/dist/plugin/AccomplishmentHandler.js +1 -1
  59. package/dist/plugin/PluginController.d.ts +16 -3
  60. package/dist/plugin/PluginController.js +24 -18
  61. package/dist/plugin/RimoriClient.d.ts +16 -11
  62. package/dist/plugin/RimoriClient.js +35 -25
  63. package/dist/plugin/StandaloneClient.js +11 -8
  64. package/dist/plugin/ThemeSetter.d.ts +1 -0
  65. package/dist/plugin/ThemeSetter.js +9 -6
  66. package/dist/providers/PluginProvider.d.ts +3 -0
  67. package/dist/providers/PluginProvider.js +4 -4
  68. package/dist/utils/Language.d.ts +2 -1
  69. package/dist/utils/Language.js +4 -2
  70. package/dist/utils/difficultyConverter.js +1 -1
  71. package/dist/utils/endpoint.d.ts +2 -0
  72. package/dist/utils/endpoint.js +2 -0
  73. package/dist/worker/WorkerSetup.js +3 -1
  74. package/example/docs/devdocs.md +231 -0
  75. package/example/docs/overview.md +29 -0
  76. package/example/docs/userdocs.md +123 -0
  77. package/example/rimori.config.ts +89 -0
  78. package/example/worker/vite.config.ts +23 -0
  79. package/example/worker/worker.ts +11 -0
  80. package/package.json +15 -9
  81. package/src/cli/scripts/init/dev-registration.ts +193 -0
  82. package/src/cli/scripts/init/env-setup.ts +44 -0
  83. package/src/cli/scripts/init/file-operations.ts +58 -0
  84. package/src/cli/scripts/init/html-cleaner.ts +48 -0
  85. package/src/cli/scripts/init/main.ts +171 -0
  86. package/src/cli/scripts/init/package-setup.ts +117 -0
  87. package/src/cli/scripts/init/router-transformer.ts +329 -0
  88. package/src/cli/scripts/init/tailwind-config.ts +75 -0
  89. package/src/cli/scripts/init/vite-config.ts +73 -0
  90. package/src/cli/scripts/release/release-config-upload.ts +114 -0
  91. package/src/cli/scripts/release/release-db-update.ts +97 -0
  92. package/src/cli/scripts/release/release-file-upload.ts +138 -0
  93. package/src/cli/scripts/release/release.ts +69 -0
  94. package/src/cli/types/DatabaseTypes.ts +117 -0
  95. package/src/components/ai/Assistant.tsx +4 -4
  96. package/src/components/ai/Avatar.tsx +24 -7
  97. package/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.tsx +1 -1
  98. package/src/components/ai/EmbeddedAssistent/VoiceRecoder.tsx +16 -8
  99. package/src/components/ai/utils.ts +0 -2
  100. package/src/components/audio/Playbutton.tsx +3 -3
  101. package/src/{core → components}/components/ContextMenu.tsx +3 -3
  102. package/src/components.ts +6 -6
  103. package/src/core/controller/AIController.ts +122 -0
  104. package/src/core/controller/ObjectController.ts +115 -0
  105. package/src/{controller → core/controller}/SettingsController.ts +13 -29
  106. package/src/{controller → core/controller}/SharedContentController.ts +5 -5
  107. package/src/core/core.ts +15 -0
  108. package/src/{plugin/fromRimori → fromRimori}/EventBus.ts +28 -10
  109. package/src/fromRimori/PluginTypes.ts +203 -0
  110. package/src/hooks/UseChatHook.ts +5 -4
  111. package/src/index.ts +5 -3
  112. package/src/plugin/AccomplishmentHandler.ts +1 -1
  113. package/src/plugin/PluginController.ts +35 -23
  114. package/src/plugin/RimoriClient.ts +42 -35
  115. package/src/plugin/StandaloneClient.ts +11 -8
  116. package/src/plugin/ThemeSetter.ts +12 -8
  117. package/src/providers/PluginProvider.tsx +7 -4
  118. package/src/utils/Language.ts +4 -2
  119. package/src/utils/difficultyConverter.ts +3 -3
  120. package/src/utils/endpoint.ts +2 -0
  121. package/src/worker/WorkerSetup.ts +4 -2
  122. package/dist/components/PluginController.d.ts +0 -21
  123. package/dist/components/PluginController.js +0 -116
  124. package/dist/controller/AIController.d.ts +0 -23
  125. package/dist/controller/AIController.js +0 -93
  126. package/dist/controller/SidePluginController.d.ts +0 -3
  127. package/dist/controller/SidePluginController.js +0 -31
  128. package/dist/core.d.ts +0 -7
  129. package/dist/core.js +0 -7
  130. package/dist/plugin/ContextMenu.d.ts +0 -17
  131. package/dist/plugin/ContextMenu.js +0 -45
  132. package/dist/plugin/fromRimori/PluginTypes.d.ts +0 -48
  133. package/dist/plugin/fromRimori/SupabaseHandler.d.ts +0 -13
  134. package/dist/plugin/fromRimori/SupabaseHandler.js +0 -55
  135. package/dist/providers/PluginController.d.ts +0 -21
  136. package/dist/providers/PluginController.js +0 -116
  137. package/dist/types/Actions.d.ts +0 -4
  138. package/dist/types/Actions.js +0 -1
  139. package/src/controller/AIController.ts +0 -112
  140. package/src/controller/ObjectController.ts +0 -107
  141. package/src/controller/SidePluginController.ts +0 -25
  142. package/src/core.ts +0 -8
  143. package/src/plugin/fromRimori/PluginTypes.ts +0 -64
  144. package/src/types/Actions.ts +0 -6
  145. /package/dist/{core → components}/components/ContextMenu.d.ts +0 -0
  146. /package/dist/{controller → core/controller}/ObjectController.js +0 -0
  147. /package/dist/{controller → core/controller}/VoiceController.d.ts +0 -0
  148. /package/dist/{controller → core/controller}/VoiceController.js +0 -0
  149. /package/dist/{plugin/fromRimori → fromRimori}/PluginTypes.js +0 -0
  150. /package/src/{controller → core/controller}/VoiceController.ts +0 -0
  151. /package/src/{plugin/fromRimori → fromRimori}/readme.md +0 -0
@@ -1,93 +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
- export function generateText(supabaseUrl, messages, tools, token) {
11
- return __awaiter(this, void 0, void 0, function* () {
12
- const response = yield fetch(`${supabaseUrl}/functions/v1/llm`, {
13
- method: 'POST',
14
- body: JSON.stringify({ messages, tools }),
15
- headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }
16
- });
17
- return yield response.json();
18
- });
19
- }
20
- export function streamChatGPT(supabaseUrl, messages, tools, onResponse, token) {
21
- return __awaiter(this, void 0, void 0, function* () {
22
- const messageId = Math.random().toString(36).substring(3);
23
- const response = yield fetch(`${supabaseUrl}/functions/v1/llm`, {
24
- method: 'POST',
25
- body: JSON.stringify({ messages, tools, stream: true }),
26
- headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }
27
- });
28
- if (!response.body) {
29
- console.error('No response body.');
30
- return;
31
- }
32
- const reader = response.body.getReader();
33
- const decoder = new TextDecoder('utf-8');
34
- let content = "";
35
- let done = false;
36
- let toolInvocations = [];
37
- while (!done) {
38
- const { value } = yield reader.read();
39
- if (value) {
40
- const chunk = decoder.decode(value, { stream: true });
41
- const lines = chunk.split('\n').filter(line => line.trim() !== '');
42
- for (const line of lines) {
43
- const data = line.substring(3, line.length - 1);
44
- const command = line.substring(0, 1);
45
- // console.log("data: ", { line, data, command });
46
- if (command === '0') {
47
- content += data;
48
- // console.log("AI response:", content);
49
- //content \n\n should be real line break when message is displayed
50
- //content \"\" should be real double quote when message is displayed
51
- onResponse(messageId, content.replace(/\\n/g, '\n').replace(/\\+"|"\\+/g, '"'), false);
52
- }
53
- else if (command === 'd') {
54
- // console.log("AI usage:", JSON.parse(line.substring(2)));
55
- done = true;
56
- break;
57
- }
58
- else if (command === '9') {
59
- // console.log("tool call:", JSON.parse(line.substring(2)));
60
- // console.log("tools", tools);
61
- const toolInvocation = JSON.parse(line.substring(2));
62
- toolInvocations.push(toolInvocation);
63
- // Find the tool and execute it if it has an execute function
64
- const tool = tools.find(t => t.name === toolInvocation.toolName);
65
- // console.log("tool", tool);
66
- if (tool && tool.execute) {
67
- try {
68
- const result = yield tool.execute(toolInvocation.args);
69
- const toolResult = { success: true, result: result };
70
- // Add the tool result as a message
71
- messages.push({
72
- id: Math.random().toString(36).substring(3),
73
- role: "function",
74
- content: JSON.stringify(toolResult),
75
- toolInvocations: [{
76
- args: toolInvocation.args,
77
- toolName: toolInvocation.toolName,
78
- }]
79
- });
80
- }
81
- catch (error) {
82
- console.error(`Error executing tool ${toolInvocation.toolName}:`, error);
83
- }
84
- }
85
- }
86
- }
87
- }
88
- // Wait for 5ms to avoid blocking the main thread
89
- yield new Promise(resolve => setTimeout(resolve, 5));
90
- }
91
- onResponse(messageId, content.replace(/\\n/g, '\n'), true, toolInvocations);
92
- });
93
- }
@@ -1,3 +0,0 @@
1
- import { SupabaseClient } from '@supabase/supabase-js';
2
- import { Plugin } from '../plugin/fromRimori/PluginTypes';
3
- export declare function getPlugins(supabase: SupabaseClient): Promise<Plugin[]>;
@@ -1,31 +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
- export function getPlugins(supabase) {
11
- return __awaiter(this, void 0, void 0, function* () {
12
- let { data, error } = yield supabase.from('plugins').select('*');
13
- if (error) {
14
- console.error(error);
15
- return [];
16
- }
17
- return (data || []).map((plugin) => ({
18
- id: plugin.id,
19
- title: plugin.title,
20
- description: plugin.description,
21
- icon_url: plugin.icon_url,
22
- endpoint: plugin.endpoint,
23
- context_menu_actions: plugin.context_menu_actions,
24
- plugin_pages: plugin.plugin_pages,
25
- sidebar_pages: plugin.sidebar_pages,
26
- settings_page: plugin.settings_page,
27
- version: plugin.version,
28
- external_hosted_url: plugin.external_hosted_url,
29
- }));
30
- });
31
- }
package/dist/core.d.ts DELETED
@@ -1,7 +0,0 @@
1
- export * from "./plugin/RimoriClient";
2
- export * from "./plugin/PluginController";
3
- export * from "./utils/difficultyConverter";
4
- export * from "./utils/PluginUtils";
5
- export * from "./worker/WorkerSetup";
6
- export * from "./utils/Language";
7
- export { SharedContent } from "./controller/SharedContentController";
package/dist/core.js DELETED
@@ -1,7 +0,0 @@
1
- // Core functionality exports
2
- export * from "./plugin/RimoriClient";
3
- export * from "./plugin/PluginController";
4
- export * from "./utils/difficultyConverter";
5
- export * from "./utils/PluginUtils";
6
- export * from "./worker/WorkerSetup";
7
- export * from "./utils/Language";
@@ -1,17 +0,0 @@
1
- import React from "react";
2
- interface Props {
3
- iframeRef: React.RefObject<HTMLIFrameElement | null>;
4
- }
5
- export interface ContextMenuInfo {
6
- x: number;
7
- y: number;
8
- text: string;
9
- open: boolean;
10
- }
11
- export interface ContextMenuAction {
12
- text: string;
13
- pluginId: string;
14
- actionKey: string;
15
- }
16
- declare const ContextMenu: ({ iframeRef }: Props) => import("react/jsx-runtime").JSX.Element | null;
17
- export default ContextMenu;
@@ -1,45 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { EventBus } from "@/lib/handler/EventBus";
3
- import { useState, useEffect } from "react";
4
- import { SupabaseClient } from "@/integrations/supabase/client";
5
- const ContextMenu = ({ iframeRef }) => {
6
- const [showMenu, setMenuVisibility] = useState(false);
7
- const [constextActions, setContextMenuActions] = useState([]);
8
- const [contextMenu, setContextMenu] = useState({ x: 0, y: 0, open: false, text: "" });
9
- useEffect(() => {
10
- SupabaseClient.getPlugins().then(plugins => {
11
- setContextMenuActions(plugins.flatMap(p => p.context_menu_actions));
12
- });
13
- }, []);
14
- useEffect(() => {
15
- // Hide the menu on click outside
16
- const handleClick = () => setMenuVisibility(false);
17
- document.addEventListener("click", handleClick);
18
- return () => document.removeEventListener("click", handleClick);
19
- }, []);
20
- useEffect(() => {
21
- EventBus.on("global.contextMenu.createActions", ({ data }) => {
22
- console.log("addContextMenuActions", data.actions);
23
- setContextMenuActions([...data.actions, ...constextActions]);
24
- });
25
- EventBus.on("global.contextMenu.trigger", ({ data }) => {
26
- if (!iframeRef.current)
27
- return;
28
- const { x, y, open, text } = data;
29
- const rect = iframeRef.current.getBoundingClientRect();
30
- setContextMenu({ x: x + rect.left, y: y + rect.top, open, text });
31
- setMenuVisibility(open);
32
- });
33
- }, []);
34
- if (!showMenu) {
35
- return null;
36
- }
37
- return (_jsx("div", { className: "fixed bg-gray-400 dark:bg-gray-700 shadow-lg border border-gray-400 rounded-md overflow-hidden dark:text-white", style: { top: contextMenu.y, left: contextMenu.x }, children: constextActions.map((action, index) => (_jsx(MenuEntryItem, { icon: action.icon, text: action.text, onClick: () => {
38
- setMenuVisibility(false);
39
- EventBus.emit("global.contextMenu", "global.sidebar.triggerAction", Object.assign(Object.assign({}, action), { text: contextMenu.text }));
40
- } }, index))) }));
41
- };
42
- function MenuEntryItem(props) {
43
- return _jsxs("button", { onClick: props.onClick, className: "px-4 py-2 text-left hover:bg-gray-500 dark:hover:bg-gray-600 w-full flex flex-row", children: [_jsx("span", { className: "flex-grow", children: props.icon }), _jsx("span", { className: "flex-grow", children: props.text })] });
44
- }
45
- export default ContextMenu;
@@ -1,48 +0,0 @@
1
- export interface Plugin {
2
- id: string;
3
- title: string;
4
- description: string;
5
- icon_url: string;
6
- version: string;
7
- endpoint: string;
8
- context_menu_actions: MenuEntry[];
9
- plugin_pages: PluginPage[];
10
- sidebar_pages: SidebarPage[];
11
- settings_page: string;
12
- worker?: {
13
- url: string;
14
- topics?: string[];
15
- };
16
- }
17
- export interface PluginPage {
18
- name: string;
19
- url: string;
20
- show: boolean;
21
- description: string;
22
- root: string;
23
- action?: (Record<string, string> & {
24
- key: string;
25
- });
26
- }
27
- export interface SidebarPage {
28
- name: string;
29
- url: string;
30
- iconUrl: string;
31
- description: string;
32
- actionKey: string;
33
- }
34
- export interface MenuEntry {
35
- text: string;
36
- pluginId: string;
37
- actionKey: string;
38
- icon?: React.ReactNode;
39
- }
40
- export type MainPanelAction = {
41
- pluginId: string;
42
- actionKey: string;
43
- } & Record<string, string>;
44
- export interface ContextMenuAction {
45
- text: string;
46
- pluginId: string;
47
- actionKey: string;
48
- }
@@ -1,13 +0,0 @@
1
- import { Plugin } from "@/types/PluginTypes";
2
- export declare class SupabaseHandler {
3
- getAccessData(plugin: Plugin): Promise<{
4
- token: any;
5
- pluginId: any;
6
- url: any;
7
- key: any;
8
- tablePrefix: any;
9
- expiration: Date;
10
- }>;
11
- getPluginAuthToken(): Promise<any>;
12
- static init(): void;
13
- }
@@ -1,55 +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 { EventBus } from "../handler/EventBus";
11
- import { getSupabase, SupabaseClient } from "@/integrations/supabase/client";
12
- export class SupabaseHandler {
13
- getAccessData(plugin) {
14
- return __awaiter(this, void 0, void 0, function* () {
15
- const env = window.APP_CONFIG;
16
- const token = yield this.getPluginAuthToken();
17
- return {
18
- token,
19
- pluginId: plugin.id,
20
- url: env.SUPABASE_URL,
21
- key: env.SUPABASE_ANON_KEY,
22
- tablePrefix: plugin.id,
23
- expiration: new Date(Date.now() + 1000 * 60 * 60 * 1.5), // 1.5 hours
24
- };
25
- });
26
- }
27
- getPluginAuthToken() {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- const supabase = getSupabase();
30
- const { data: { session } } = yield supabase.auth.getSession();
31
- if (!session) {
32
- throw new Error("User not logged in");
33
- }
34
- // Extract the full-access token for authorization with the Edge Function
35
- const { data, error } = yield supabase.functions.invoke("plugin-token");
36
- if (error) {
37
- console.error("Failed to get plugin token. ", error);
38
- throw new Error("Failed to get plugin token. " + error.message);
39
- }
40
- return data.token;
41
- });
42
- }
43
- static init() {
44
- const supabaseHandler = new SupabaseHandler();
45
- EventBus.respond("supabase", "global.supabase.requestAccess", (event) => __awaiter(this, void 0, void 0, function* () {
46
- const sender = event.sender.split(".")[0];
47
- const plugins = yield SupabaseClient.getPlugins();
48
- const plugin = plugins.find((p) => p.id === sender);
49
- if (!plugin) {
50
- throw new Error("Plugin not found");
51
- }
52
- return yield supabaseHandler.getAccessData(plugin);
53
- }));
54
- }
55
- }
@@ -1,21 +0,0 @@
1
- import { SupabaseClient } from '@supabase/supabase-js';
2
- import { RimoriClient } from "../plugin/RimoriClient";
3
- export declare class PluginController {
4
- private static client;
5
- private static instance;
6
- private communicationSecret;
7
- private supabase;
8
- private supabaseInfo;
9
- private pluginId;
10
- private constructor();
11
- static getInstance(sender: string): Promise<RimoriClient>;
12
- private getSecret;
13
- getClient(): Promise<{
14
- supabase: SupabaseClient;
15
- tablePrefix: string;
16
- pluginId: string;
17
- }>;
18
- getToken(): Promise<string>;
19
- getSupabaseUrl(): string;
20
- getGlobalEventTopic(preliminaryTopic: string): string;
21
- }
@@ -1,116 +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 { createClient } from '@supabase/supabase-js';
11
- import { EventBus } from '../plugin/fromRimori/EventBus';
12
- import { RimoriClient } from "../plugin/RimoriClient";
13
- import { setTheme } from '../plugin/ThemeSetter';
14
- export class PluginController {
15
- constructor(pluginId) {
16
- this.communicationSecret = null;
17
- this.supabase = null;
18
- this.supabaseInfo = null;
19
- this.pluginId = pluginId;
20
- this.getClient = this.getClient.bind(this);
21
- if (typeof WorkerGlobalScope === 'undefined') {
22
- setTheme();
23
- }
24
- window.addEventListener("message", (event) => {
25
- // console.log("client: message received", event);
26
- const { topic, sender, data, eventId } = event.data.event;
27
- // skip forwarding messages from own plugin
28
- if (sender === pluginId)
29
- return;
30
- EventBus.emit(sender, topic, data, eventId);
31
- });
32
- EventBus.on("*", (event) => {
33
- // skip messages which are not from the own plugin
34
- if (event.sender !== this.pluginId)
35
- return;
36
- if (event.topic.startsWith("self."))
37
- return;
38
- window.parent.postMessage({ event, secret: this.getSecret() }, "*");
39
- });
40
- }
41
- static getInstance(sender) {
42
- return __awaiter(this, void 0, void 0, function* () {
43
- if (!PluginController.instance) {
44
- PluginController.instance = new PluginController(sender);
45
- PluginController.client = yield RimoriClient.getInstance(PluginController.instance);
46
- }
47
- return PluginController.client;
48
- });
49
- }
50
- getSecret() {
51
- if (!this.communicationSecret) {
52
- const secret = new URLSearchParams(window.location.search).get("secret");
53
- if (!secret) {
54
- throw new Error("Communication secret not found in URL as query parameter");
55
- }
56
- this.communicationSecret = secret;
57
- }
58
- return this.communicationSecret;
59
- }
60
- getClient() {
61
- return __awaiter(this, void 0, void 0, function* () {
62
- if (this.supabase &&
63
- this.supabaseInfo &&
64
- this.supabaseInfo.expiration > new Date()) {
65
- return { supabase: this.supabase, tablePrefix: this.supabaseInfo.tablePrefix, pluginId: this.supabaseInfo.pluginId };
66
- }
67
- const { data } = yield EventBus.request(this.pluginId, "global.supabase.requestAccess");
68
- this.supabaseInfo = data;
69
- this.supabase = createClient(this.supabaseInfo.url, this.supabaseInfo.key, {
70
- accessToken: () => Promise.resolve(this.getToken())
71
- });
72
- return { supabase: this.supabase, tablePrefix: this.supabaseInfo.tablePrefix, pluginId: this.supabaseInfo.pluginId };
73
- });
74
- }
75
- getToken() {
76
- return __awaiter(this, void 0, void 0, function* () {
77
- if (this.supabaseInfo && this.supabaseInfo.expiration && this.supabaseInfo.expiration > new Date()) {
78
- return this.supabaseInfo.token;
79
- }
80
- const { data } = yield EventBus.request(this.pluginId, "global.supabase.requestAccess");
81
- if (!this.supabaseInfo) {
82
- throw new Error("Supabase info not found");
83
- }
84
- this.supabaseInfo.token = data.token;
85
- this.supabaseInfo.expiration = data.expiration;
86
- return this.supabaseInfo.token;
87
- });
88
- }
89
- getSupabaseUrl() {
90
- if (!this.supabaseInfo) {
91
- throw new Error("Supabase info not found");
92
- }
93
- return this.supabaseInfo.url;
94
- }
95
- getGlobalEventTopic(preliminaryTopic) {
96
- var _a, _b;
97
- if (preliminaryTopic.startsWith("global.")) {
98
- return preliminaryTopic;
99
- }
100
- if (preliminaryTopic.startsWith("self.")) {
101
- return preliminaryTopic;
102
- }
103
- const topicParts = preliminaryTopic.split(".");
104
- if (topicParts.length === 3) {
105
- if (!topicParts[0].startsWith("pl") && topicParts[0] !== "global") {
106
- throw new Error("The event topic must start with the plugin id or 'global'.");
107
- }
108
- return preliminaryTopic;
109
- }
110
- else if (topicParts.length > 3) {
111
- throw new Error(`The event topic must consist of 3 parts. <pluginId>.<topic area>.<action>. Received: ${preliminaryTopic}`);
112
- }
113
- const topicRoot = (_b = (_a = this.supabaseInfo) === null || _a === void 0 ? void 0 : _a.pluginId) !== null && _b !== void 0 ? _b : "global";
114
- return `${topicRoot}.${preliminaryTopic}`;
115
- }
116
- }
@@ -1,4 +0,0 @@
1
- export type MainPanelAction = {
2
- pluginId: string;
3
- actionKey: string;
4
- } & Record<string, string>;
@@ -1 +0,0 @@
1
- export {};
@@ -1,112 +0,0 @@
1
- export interface ToolInvocation {
2
- toolName: string;
3
- args: Record<string, string>;
4
- }
5
-
6
- export interface Tool {
7
- name: string;
8
- description: string;
9
- parameters: {
10
- name: string;
11
- description: string;
12
- type: "string" | "number" | "boolean";
13
- }[];
14
- execute?: <T = Record<string, string | boolean | number>>(args: T) => Promise<any> | void;
15
- }
16
-
17
- export interface Message {
18
- id: string;
19
- role: string;
20
- content: string;
21
- toolInvocations?: ToolInvocation[];
22
- }
23
-
24
- export async function generateText(supabaseUrl: string, messages: Message[], tools: Tool[], token: string) {
25
- const response = await fetch(`${supabaseUrl}/functions/v1/llm`, {
26
- method: 'POST',
27
- body: JSON.stringify({ messages, tools }),
28
- headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }
29
- });
30
-
31
- return await response.json();
32
- }
33
-
34
- export type OnLLMResponse = (id: string, response: string, finished: boolean, toolInvocations?: ToolInvocation[]) => void;
35
-
36
- export async function streamChatGPT(supabaseUrl: string, messages: Message[], tools: Tool[], onResponse: OnLLMResponse, token: string) {
37
- const messageId = Math.random().toString(36).substring(3);
38
- const response = await fetch(`${supabaseUrl}/functions/v1/llm`, {
39
- method: 'POST',
40
- body: JSON.stringify({ messages, tools, stream: true }),
41
- headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }
42
- });
43
-
44
- if (!response.body) {
45
- console.error('No response body.');
46
- return;
47
- }
48
-
49
- const reader = response.body.getReader();
50
- const decoder = new TextDecoder('utf-8');
51
-
52
- let content = "";
53
- let done = false;
54
- let toolInvocations: ToolInvocation[] = [];
55
- while (!done) {
56
- const { value } = await reader.read();
57
-
58
- if (value) {
59
- const chunk = decoder.decode(value, { stream: true });
60
- const lines = chunk.split('\n').filter(line => line.trim() !== '');
61
-
62
- for (const line of lines) {
63
- const data = line.substring(3, line.length - 1);
64
- const command = line.substring(0, 1);
65
- // console.log("data: ", { line, data, command });
66
-
67
- if (command === '0') {
68
- content += data;
69
- // console.log("AI response:", content);
70
-
71
- //content \n\n should be real line break when message is displayed
72
- //content \"\" should be real double quote when message is displayed
73
- onResponse(messageId, content.replace(/\\n/g, '\n').replace(/\\+"|"\\+/g, '"'), false);
74
- } else if (command === 'd') {
75
- // console.log("AI usage:", JSON.parse(line.substring(2)));
76
- done = true;
77
- break;
78
- } else if (command === '9') {
79
- // console.log("tool call:", JSON.parse(line.substring(2)));
80
- // console.log("tools", tools);
81
- const toolInvocation = JSON.parse(line.substring(2));
82
- toolInvocations.push(toolInvocation);
83
-
84
- // Find the tool and execute it if it has an execute function
85
- const tool = tools.find(t => t.name === toolInvocation.toolName);
86
- // console.log("tool", tool);
87
- if (tool && tool.execute) {
88
- try {
89
- const result = await tool.execute(toolInvocation.args);
90
- const toolResult = { success: true, result: result }
91
- // Add the tool result as a message
92
- messages.push({
93
- id: Math.random().toString(36).substring(3),
94
- role: "function",
95
- content: JSON.stringify(toolResult),
96
- toolInvocations: [{
97
- args: toolInvocation.args,
98
- toolName: toolInvocation.toolName,
99
- }]
100
- });
101
- } catch (error) {
102
- console.error(`Error executing tool ${toolInvocation.toolName}:`, error);
103
- }
104
- }
105
- }
106
- }
107
- }
108
- // Wait for 5ms to avoid blocking the main thread
109
- await new Promise(resolve => setTimeout(resolve, 5));
110
- }
111
- onResponse(messageId, content.replace(/\\n/g, '\n'), true, toolInvocations);
112
- }