Luca448 commited on
Commit
831ae8e
·
1 Parent(s): e34f9f1

Feat: Add filesystem tools for Gemini AI allowing it to natively read, list and modify local user files with a Promise-based permission popup UI for safety

Browse files
Files changed (4) hide show
  1. index.html +2 -2
  2. src/ai/gemini.js +19 -3
  3. src/ai/tools/filesystem-tool.js +153 -0
  4. src/app.js +52 -0
index.html CHANGED
@@ -51,7 +51,7 @@
51
  </head>
52
  <body class="dark-theme in-chat-view">
53
 
54
- <div id="live-version-badge" style="position: fixed; top: 50px; left: 50%; transform: translateX(-50%); font-size: 10px; color: var(--text-secondary); opacity: 0.6; z-index: 99999; pointer-events: none; font-weight: 500; font-family: monospace; letter-spacing: 1px; background: rgba(0,0,0,0.2); padding: 2px 8px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.05);">BUILD 1.1.117</div>
55
 
56
  <!-- SVG Filters for Liquid Glass Refraction -->
57
  <svg width="0" height="0" style="position: absolute; pointer-events: none;">
@@ -70,7 +70,7 @@
70
  <div id="app"></div>
71
 
72
  <!-- Entry Script -->
73
- <script type="module" src="/src/app.js?v=1073"></script>
74
 
75
  <!-- Article View Modal -->
76
  <div id="article-view-modal" class="liquid-glass-heavy" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 10000; background: var(--bg-color); overflow-y: auto;">
 
51
  </head>
52
  <body class="dark-theme in-chat-view">
53
 
54
+ <div id="live-version-badge" style="position: fixed; top: 50px; left: 50%; transform: translateX(-50%); font-size: 10px; color: var(--text-secondary); opacity: 0.6; z-index: 99999; pointer-events: none; font-weight: 500; font-family: monospace; letter-spacing: 1px; background: rgba(0,0,0,0.2); padding: 2px 8px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.05);">BUILD 1.1.118</div>
55
 
56
  <!-- SVG Filters for Liquid Glass Refraction -->
57
  <svg width="0" height="0" style="position: absolute; pointer-events: none;">
 
70
  <div id="app"></div>
71
 
72
  <!-- Entry Script -->
73
+ <script type="module" src="/src/app.js?v=1074"></script>
74
 
75
  <!-- Article View Modal -->
76
  <div id="article-view-modal" class="liquid-glass-heavy" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 10000; background: var(--bg-color); overflow-y: auto;">
src/ai/gemini.js CHANGED
@@ -3,6 +3,7 @@ import { readPageToolDef, executeReadPage } from './tools/scrape-tool.js';
3
  import { shoppingToolDef, executeShoppingSearch } from './tools/shopping-tool.js';
4
  import { iservToolDeclaration, executeIServFetch } from './tools/iserv-tool.js';
5
  import { flashcardToolDef, executeFlashcards } from './tools/flashcard-tool.js';
 
6
  import { db } from '../db/database.js';
7
 
8
  export class GeminiClient {
@@ -69,6 +70,8 @@ export class GeminiClient {
69
  contents.push({ role: 'user', parts: finalParts });
70
 
71
  let customSysInst = systemInstruction || "";
 
 
72
  if (isDeepResearch) {
73
  customSysInst += "\n\nDu hast Zugriff auf Web-Suche (Tools: web_search, read_page), Shopping-Suche (Tool: shopping_search) UND IServ-Abruf (Tool: iserv_fetch).\nNUTZE DIE SHOPPING-SUCHE (shopping_search) ZWINGEND, wenn der Benutzer nach Produkten sucht (Kleidung, Technik, Deko etc.) oder Kaufempfehlungen möchte. WICHTIG: Die Shopping-Suche kümmert sich vollautomatisch um die grafische Darstellung (Karussell) für den Nutzer. Du darfst in deiner Text-Antwort KEINE eigenen Links, Markdown-Bilder (![]()) oder HTML-Code zu den Produkten ausgeben! Fasse stattdessen in deiner Antwort zusammen, warum du diese Art von Produkten gesucht hast, oder gib eine hilfreiche Kaufberatung/Zusammenfassung. ACHTUNG: Das visuelle Shopping-Karussell wird für den Nutzer immer OBERHALB deines Textes angezeigt. Beziehe dich also darauf (z.B. 'Wie du an den Modellen oben sehen kannst...'). Beende deinen Text NICHT mit einem Doppelpunkt, da unter deinem Text nichts mehr folgt.\nNUTZE DEN ISERV-ABRUF (iserv_fetch), wenn der Nutzer nach Hausaufgaben, Schulaufgaben oder IServ fragt!\nNUTZE DAS TOOL create_flashcards WENN DER NUTZER Karteikarten, Vokabeln oder Lernkarten erstellen möchte. Erstelle eine sinnvolle Menge an Karten.\nACHTUNG BEI ZAHLEN & FAKTEN: Achte bei der Extraktion von Zahlen auf ABSOLUTE Präzision.\nWICHTIGE REGEL ZUR RECHERCHE & BELEGEN: Bilde Hypothesen, aber verifiziere sie IMMER! Wenn dir Daten fehlen, rufe 'web_search' erneut auf.\nWENN DIR DATEN FEHLEN: Wenn du nach mehreren Suchen keine verlässlichen Fakten findest, MUSST du ehrlich sein. ERFINDE NIEMALS Ereignisse, Ergebnisse oder URLs!\nQUELLEN: Liste am Ende NUR DANN deine Quellen auf, wenn du TATSÄCHLICH echte URLs hast.";
74
  }
@@ -84,11 +87,14 @@ export class GeminiClient {
84
  };
85
  }
86
 
 
87
  if (isDeepResearch) {
88
- body.tools = [{
89
- functionDeclarations: [webSearchToolDef, readPageToolDef, shoppingToolDef, iservToolDeclaration, flashcardToolDef]
90
- }];
91
  }
 
 
 
 
92
 
93
  // Function loop
94
  let loopCount = 0;
@@ -143,6 +149,16 @@ export class GeminiClient {
143
  } else if (fnCall.name === "create_flashcards") {
144
  const result = await executeFlashcards(fnCall.args, onStatus);
145
  toolResponseStr = JSON.stringify(result);
 
 
 
 
 
 
 
 
 
 
146
  }
147
 
148
  // Append the tool response back to the model
 
3
  import { shoppingToolDef, executeShoppingSearch } from './tools/shopping-tool.js';
4
  import { iservToolDeclaration, executeIServFetch } from './tools/iserv-tool.js';
5
  import { flashcardToolDef, executeFlashcards } from './tools/flashcard-tool.js';
6
+ import { listLocalFilesToolDef, readLocalFileToolDef, writeLocalFileToolDef, deleteLocalFileToolDef, executeListLocalFiles, executeReadLocalFile, executeWriteLocalFile, executeDeleteLocalFile } from './tools/filesystem-tool.js';
7
  import { db } from '../db/database.js';
8
 
9
  export class GeminiClient {
 
70
  contents.push({ role: 'user', parts: finalParts });
71
 
72
  let customSysInst = systemInstruction || "";
73
+ customSysInst += "\n\nDu bist ein intelligenter lokaler Assistent. Du hast über Tools direkten Lese- und Schreibzugriff auf das Dateisystem (Ordner und Dokumente) des Nutzers. Nutze 'list_local_files', um zu sehen was der Nutzer gespeichert hat. Nutze 'read_local_file', um gezielt Inhalte zu lesen, und 'write_local_file', um Dokumente zu erstellen oder zu bearbeiten. Frage nicht um Erlaubnis, sondern führe die Tool-Aufrufe direkt aus (der Nutzer wird über ein Popup zustimmen).";
74
+
75
  if (isDeepResearch) {
76
  customSysInst += "\n\nDu hast Zugriff auf Web-Suche (Tools: web_search, read_page), Shopping-Suche (Tool: shopping_search) UND IServ-Abruf (Tool: iserv_fetch).\nNUTZE DIE SHOPPING-SUCHE (shopping_search) ZWINGEND, wenn der Benutzer nach Produkten sucht (Kleidung, Technik, Deko etc.) oder Kaufempfehlungen möchte. WICHTIG: Die Shopping-Suche kümmert sich vollautomatisch um die grafische Darstellung (Karussell) für den Nutzer. Du darfst in deiner Text-Antwort KEINE eigenen Links, Markdown-Bilder (![]()) oder HTML-Code zu den Produkten ausgeben! Fasse stattdessen in deiner Antwort zusammen, warum du diese Art von Produkten gesucht hast, oder gib eine hilfreiche Kaufberatung/Zusammenfassung. ACHTUNG: Das visuelle Shopping-Karussell wird für den Nutzer immer OBERHALB deines Textes angezeigt. Beziehe dich also darauf (z.B. 'Wie du an den Modellen oben sehen kannst...'). Beende deinen Text NICHT mit einem Doppelpunkt, da unter deinem Text nichts mehr folgt.\nNUTZE DEN ISERV-ABRUF (iserv_fetch), wenn der Nutzer nach Hausaufgaben, Schulaufgaben oder IServ fragt!\nNUTZE DAS TOOL create_flashcards WENN DER NUTZER Karteikarten, Vokabeln oder Lernkarten erstellen möchte. Erstelle eine sinnvolle Menge an Karten.\nACHTUNG BEI ZAHLEN & FAKTEN: Achte bei der Extraktion von Zahlen auf ABSOLUTE Präzision.\nWICHTIGE REGEL ZUR RECHERCHE & BELEGEN: Bilde Hypothesen, aber verifiziere sie IMMER! Wenn dir Daten fehlen, rufe 'web_search' erneut auf.\nWENN DIR DATEN FEHLEN: Wenn du nach mehreren Suchen keine verlässlichen Fakten findest, MUSST du ehrlich sein. ERFINDE NIEMALS Ereignisse, Ergebnisse oder URLs!\nQUELLEN: Liste am Ende NUR DANN deine Quellen auf, wenn du TATSÄCHLICH echte URLs hast.";
77
  }
 
87
  };
88
  }
89
 
90
+ let activeTools = [listLocalFilesToolDef, readLocalFileToolDef, writeLocalFileToolDef, deleteLocalFileToolDef];
91
  if (isDeepResearch) {
92
+ activeTools = activeTools.concat([webSearchToolDef, readPageToolDef, shoppingToolDef, iservToolDeclaration, flashcardToolDef]);
 
 
93
  }
94
+
95
+ body.tools = [{
96
+ functionDeclarations: activeTools
97
+ }];
98
 
99
  // Function loop
100
  let loopCount = 0;
 
149
  } else if (fnCall.name === "create_flashcards") {
150
  const result = await executeFlashcards(fnCall.args, onStatus);
151
  toolResponseStr = JSON.stringify(result);
152
+ } else if (fnCall.name === "list_local_files") {
153
+ toolResponseStr = await executeListLocalFiles(fnCall.args);
154
+ } else if (fnCall.name === "read_local_file") {
155
+ toolResponseStr = await executeReadLocalFile(fnCall.args);
156
+ } else if (fnCall.name === "write_local_file") {
157
+ toolResponseStr = await executeWriteLocalFile(fnCall.args);
158
+ } else if (fnCall.name === "delete_local_file") {
159
+ toolResponseStr = await executeDeleteLocalFile(fnCall.args);
160
+ } else {
161
+ toolResponseStr = JSON.stringify({ error: "Unknown tool call" });
162
  }
163
 
164
  // Append the tool response back to the model
src/ai/tools/filesystem-tool.js ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { fsService } from '../../services/file-system.js';
2
+
3
+ export const listLocalFilesToolDef = {
4
+ name: "list_local_files",
5
+ description: "Gibt eine Liste aller Ordner und Dateien im lokalen Dateisystem des Nutzers zurück. Nutze dies, um dir einen Überblick über die Dokumente des Nutzers zu verschaffen. Du siehst sofort alle Namen und Pfade, aber nicht den Dateiinhalt.",
6
+ parameters: {
7
+ type: "OBJECT",
8
+ properties: {
9
+ path: {
10
+ type: "STRING",
11
+ description: "Optional: Ein spezifischer Unterordner (z.B. 'Mathematik'). Lass es leer (''), um alle Dateien im Hauptordner anzuzeigen."
12
+ }
13
+ }
14
+ }
15
+ };
16
+
17
+ export const readLocalFileToolDef = {
18
+ name: "read_local_file",
19
+ description: "Liest den Textinhalt einer spezifischen lokalen Datei des Nutzers. Erfordert die Zustimmung des Nutzers. Nutze dies, um den Inhalt eines Dokuments zu analysieren.",
20
+ parameters: {
21
+ type: "OBJECT",
22
+ properties: {
23
+ path: {
24
+ type: "STRING",
25
+ description: "Der genaue Pfad der Datei (z.B. 'Mathematik/Zusammenfassung.md')."
26
+ }
27
+ },
28
+ required: ["path"]
29
+ }
30
+ };
31
+
32
+ export const writeLocalFileToolDef = {
33
+ name: "write_local_file",
34
+ description: "Erstellt eine neue lokale Datei oder überschreibt eine bestehende. Erfordert die Zustimmung des Nutzers. Nutze Markdown für Textdokumente.",
35
+ parameters: {
36
+ type: "OBJECT",
37
+ properties: {
38
+ path: {
39
+ type: "STRING",
40
+ description: "Der genaue Zielpfad (z.B. 'Biologie/Zellen.md')."
41
+ },
42
+ content: {
43
+ type: "STRING",
44
+ description: "Der komplette Inhalt, der in die Datei geschrieben werden soll."
45
+ }
46
+ },
47
+ required: ["path", "content"]
48
+ }
49
+ };
50
+
51
+ export const deleteLocalFileToolDef = {
52
+ name: "delete_local_file",
53
+ description: "Löscht eine lokale Datei oder einen Ordner. Erfordert die Zustimmung des Nutzers.",
54
+ parameters: {
55
+ type: "OBJECT",
56
+ properties: {
57
+ path: {
58
+ type: "STRING",
59
+ description: "Der Pfad der Datei oder des Ordners."
60
+ }
61
+ },
62
+ required: ["path"]
63
+ }
64
+ };
65
+
66
+ // --- Execution & Permission Helpers ---
67
+
68
+ function requestPermission(action, path) {
69
+ return new Promise((resolve) => {
70
+ // Generate a unique ID for this request
71
+ const requestId = 'req_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
72
+
73
+ // Create the event payload
74
+ const eventDetail = {
75
+ id: requestId,
76
+ action: action, // 'read', 'write', 'delete'
77
+ path: path,
78
+ resolve: resolve
79
+ };
80
+
81
+ // Dispatch to UI
82
+ const event = new CustomEvent('request-file-permission', { detail: eventDetail });
83
+ window.dispatchEvent(event);
84
+ });
85
+ }
86
+
87
+ export async function executeListLocalFiles(args) {
88
+ try {
89
+ const p = args.path || '';
90
+ const files = await fsService.readDir(p);
91
+ return JSON.stringify({ success: true, path: p || '/', items: files });
92
+ } catch (e) {
93
+ return JSON.stringify({ error: "Ordner konnte nicht gelesen werden: " + e.message });
94
+ }
95
+ }
96
+
97
+ export async function executeReadLocalFile(args) {
98
+ try {
99
+ const isAllowed = await requestPermission('read', args.path);
100
+ if (!isAllowed) {
101
+ return JSON.stringify({ error: "USER_DENIED: Der Nutzer hat das Lesen dieser Datei abgelehnt." });
102
+ }
103
+ const content = await fsService.readFile(args.path);
104
+ if (content === null) {
105
+ return JSON.stringify({ error: "Datei nicht gefunden oder nicht lesbar." });
106
+ }
107
+ return JSON.stringify({ success: true, content: content });
108
+ } catch (e) {
109
+ return JSON.stringify({ error: e.message });
110
+ }
111
+ }
112
+
113
+ export async function executeWriteLocalFile(args) {
114
+ try {
115
+ const isAllowed = await requestPermission('write', args.path);
116
+ if (!isAllowed) {
117
+ return JSON.stringify({ error: "USER_DENIED: Der Nutzer hat das Schreiben/Überschreiben dieser Datei abgelehnt." });
118
+ }
119
+ const success = await fsService.writeFile(args.path, args.content);
120
+ if (!success) {
121
+ return JSON.stringify({ error: "Schreiben fehlgeschlagen." });
122
+ }
123
+
124
+ // Inform UI that a file was updated so it can refresh the sidebar
125
+ window.dispatchEvent(new CustomEvent('filesystem-changed'));
126
+
127
+ return JSON.stringify({ success: true, message: `Datei '${args.path}' wurde erfolgreich gespeichert.` });
128
+ } catch (e) {
129
+ return JSON.stringify({ error: e.message });
130
+ }
131
+ }
132
+
133
+ export async function executeDeleteLocalFile(args) {
134
+ try {
135
+ const isAllowed = await requestPermission('delete', args.path);
136
+ if (!isAllowed) {
137
+ return JSON.stringify({ error: "USER_DENIED: Der Nutzer hat das Löschen abgelehnt." });
138
+ }
139
+ // Very basic heuristic for isDir. If it has no extension, assume dir.
140
+ // In a robust implementation, we'd check stat.
141
+ const isDir = !args.path.includes('.');
142
+ const success = await fsService.deletePath(args.path, isDir);
143
+ if (!success) {
144
+ return JSON.stringify({ error: "Löschen fehlgeschlagen." });
145
+ }
146
+
147
+ window.dispatchEvent(new CustomEvent('filesystem-changed'));
148
+
149
+ return JSON.stringify({ success: true, message: `Pfad '${args.path}' wurde gelöscht.` });
150
+ } catch (e) {
151
+ return JSON.stringify({ error: e.message });
152
+ }
153
+ }
src/app.js CHANGED
@@ -228,6 +228,18 @@ const initApp = async () => {
228
  <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" style="margin-top: 2px;"><polyline points="6 9 12 15 18 9"></polyline></svg>
229
  </button>
230
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  <div id="image-preview-container" style="display: none; padding: 12px 16px 16px 16px; z-index: 0; position: relative; gap: 12px; overflow-x: auto; white-space: nowrap; align-items: center;">
232
  </div>
233
  <div class="input-capsule siri-capsule" style="z-index: 1; position: relative;">
@@ -589,6 +601,46 @@ const initApp = async () => {
589
  window.updateChatPlaceholder();
590
  }
591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
592
  fileInput.addEventListener('change', (e) => {
593
  const files = Array.from(e.target.files);
594
  if (!files.length) return;
 
228
  <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" style="margin-top: 2px;"><polyline points="6 9 12 15 18 9"></polyline></svg>
229
  </button>
230
 
231
+ <!-- File Permission Popup -->
232
+ <div id="file-permission-popup" style="display: none; position: absolute; top: -80px; left: 16px; right: 16px; background: rgba(30, 30, 35, 0.95); border-radius: 16px; border: 1px solid rgba(182, 120, 242, 0.3); padding: 12px 16px; box-shadow: 0 8px 32px rgba(0,0,0,0.4); z-index: 101; backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); align-items: center; justify-content: space-between; gap: 12px; animation: slide-up 0.3s cubic-bezier(0.2, 0.8, 0.2, 1);">
233
+ <div style="display: flex; flex-direction: column; flex: 1; overflow: hidden;">
234
+ <div style="font-size: 12px; font-weight: 600; color: #b678f2; margin-bottom: 2px;">KI Dateizugriff</div>
235
+ <div id="file-permission-text" style="font-size: 13px; color: white; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">Gemini möchte Datei X lesen.</div>
236
+ </div>
237
+ <div style="display: flex; gap: 8px;">
238
+ <button id="file-permission-deny" style="background: rgba(255,255,255,0.1); color: white; border: none; padding: 6px 12px; border-radius: 8px; font-size: 13px; font-weight: 500; cursor: pointer;">Ablehnen</button>
239
+ <button id="file-permission-allow" style="background: #b678f2; color: white; border: none; padding: 6px 12px; border-radius: 8px; font-size: 13px; font-weight: 600; cursor: pointer;">Erlauben</button>
240
+ </div>
241
+ </div>
242
+
243
  <div id="image-preview-container" style="display: none; padding: 12px 16px 16px 16px; z-index: 0; position: relative; gap: 12px; overflow-x: auto; white-space: nowrap; align-items: center;">
244
  </div>
245
  <div class="input-capsule siri-capsule" style="z-index: 1; position: relative;">
 
601
  window.updateChatPlaceholder();
602
  }
603
 
604
+ // Handle global errors gracefully
605
+ window.addEventListener('unhandledrejection', event => {
606
+ console.error('Unhandled promise rejection:', event.reason);
607
+ });
608
+
609
+ // --- File Permission UI Logic ---
610
+ let activePermissionResolve = null;
611
+ const permPopup = document.getElementById('file-permission-popup');
612
+ const permText = document.getElementById('file-permission-text');
613
+ const permAllow = document.getElementById('file-permission-allow');
614
+ const permDeny = document.getElementById('file-permission-deny');
615
+
616
+ window.addEventListener('request-file-permission', (e) => {
617
+ const detail = e.detail;
618
+ activePermissionResolve = detail.resolve;
619
+
620
+ let actionText = 'lesen';
621
+ if (detail.action === 'write') actionText = 'erstellen/überschreiben';
622
+ if (detail.action === 'delete') actionText = 'löschen';
623
+
624
+ permText.innerText = `Die KI möchte die Datei "${detail.path}" ${actionText}.`;
625
+ permPopup.style.display = 'flex';
626
+
627
+ // Haptic feedback to alert user
628
+ if (window.navigator && window.navigator.vibrate) {
629
+ window.navigator.vibrate(50);
630
+ }
631
+ });
632
+
633
+ const closePermissionPopup = (allowed) => {
634
+ permPopup.style.display = 'none';
635
+ if (activePermissionResolve) {
636
+ activePermissionResolve(allowed);
637
+ activePermissionResolve = null;
638
+ }
639
+ };
640
+
641
+ permAllow.addEventListener('click', () => closePermissionPopup(true));
642
+ permDeny.addEventListener('click', () => closePermissionPopup(false));
643
+
644
  fileInput.addEventListener('change', (e) => {
645
  const files = Array.from(e.target.files);
646
  if (!files.length) return;