-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1732 lines (1713 loc) · 65.1 KB
/
Copy pathmain.js
File metadata and controls
1732 lines (1713 loc) · 65.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => ClaudeDesktopMirror
});
module.exports = __toCommonJS(main_exports);
var import_obsidian6 = require("obsidian");
// src/ChatView.ts
var import_obsidian2 = require("obsidian");
// src/AnthropicClient.ts
var AnthropicClient = class {
constructor(apiKey) {
this.baseUrl = "https://api.anthropic.com/v1";
this.apiKey = apiKey;
}
setApiKey(key) {
this.apiKey = key;
}
async streamMessage(params) {
var _a;
const { model, messages, system, tools, maxTokens, callbacks } = params;
if (!this.apiKey) {
callbacks.onError(new Error("No API key set. Add your Anthropic API key in Settings \u2192 Claude Desktop Mirror."));
return;
}
const body = {
model,
messages,
max_tokens: maxTokens,
stream: true
};
if (system) body.system = system;
if (tools && tools.length > 0) body.tools = tools;
let response;
try {
response = await fetch(`${this.baseUrl}/messages`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": this.apiKey,
"anthropic-version": "2023-06-01",
"anthropic-dangerous-direct-browser-access": "true"
},
body: JSON.stringify(body)
});
} catch (err) {
callbacks.onError(new Error(`Network error: ${err}`));
return;
}
if (!response.ok) {
let msg = `API error ${response.status}`;
try {
const errBody = await response.json();
msg = ((_a = errBody == null ? void 0 : errBody.error) == null ? void 0 : _a.message) || msg;
} catch (e) {
}
callbacks.onError(new Error(msg));
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let currentToolId = "";
let currentToolName = "";
let currentToolInputStr = "";
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const data = line.slice(6).trim();
if (data === "[DONE]" || !data) continue;
let event;
try {
event = JSON.parse(data);
} catch (e) {
continue;
}
switch (event.type) {
case "content_block_start": {
const cb = event.content_block;
if ((cb == null ? void 0 : cb.type) === "tool_use") {
currentToolId = cb.id;
currentToolName = cb.name;
currentToolInputStr = "";
}
break;
}
case "content_block_delta": {
const delta = event.delta;
if ((delta == null ? void 0 : delta.type) === "text_delta") {
callbacks.onText(delta.text);
} else if ((delta == null ? void 0 : delta.type) === "input_json_delta") {
currentToolInputStr += delta.partial_json;
}
break;
}
case "content_block_stop": {
if (currentToolName) {
let input = {};
try {
input = JSON.parse(currentToolInputStr || "{}");
} catch (e) {
}
callbacks.onToolUse(currentToolId, currentToolName, input);
currentToolName = "";
currentToolId = "";
currentToolInputStr = "";
}
break;
}
case "message_delta": {
const delta = event.delta;
if (delta == null ? void 0 : delta.stop_reason) {
callbacks.onComplete(delta.stop_reason);
}
break;
}
}
}
}
} catch (err) {
callbacks.onError(err instanceof Error ? err : new Error(String(err)));
}
}
async simpleMessage(params) {
var _a;
const { model, messages, system, tools, maxTokens } = params;
const body = { model, messages, max_tokens: maxTokens };
if (system) body.system = system;
if (tools && tools.length > 0) body.tools = tools;
const response = await fetch(`${this.baseUrl}/messages`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": this.apiKey,
"anthropic-version": "2023-06-01",
"anthropic-dangerous-direct-browser-access": "true"
},
body: JSON.stringify(body)
});
if (!response.ok) {
const errBody = await response.json().catch(() => ({}));
throw new Error(((_a = errBody == null ? void 0 : errBody.error) == null ? void 0 : _a.message) || `API error ${response.status}`);
}
const result = await response.json();
const text = result.content.filter((b) => b.type === "text").map((b) => b.text).join("");
const toolUses = result.content.filter((b) => b.type === "tool_use").map((b) => ({ id: b.id, name: b.name, input: b.input }));
return { text, stopReason: result.stop_reason, toolUses };
}
};
// src/VaultTools.ts
var import_obsidian = require("obsidian");
function getVaultTools() {
return [
{
name: "read_note",
description: "Read the full content of a note in the user's Obsidian vault",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: 'Path to the note, e.g. "folder/note.md" or "note.md"' }
},
required: ["path"]
}
},
{
name: "search_vault",
description: "Search for notes in the vault by filename or text content. Returns matching excerpts.",
input_schema: {
type: "object",
properties: {
query: { type: "string", description: "Text to search for" },
limit: { type: "number", description: "Max results to return (default 8)" }
},
required: ["query"]
}
},
{
name: "create_or_update_note",
description: "Create a new note or overwrite/append to an existing note",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: 'Path for the note, e.g. "folder/note.md"' },
content: { type: "string", description: "Markdown content to write" },
append: { type: "boolean", description: "If true, append to existing content instead of replacing" }
},
required: ["path", "content"]
}
},
{
name: "list_notes",
description: "List notes in a vault folder",
input_schema: {
type: "object",
properties: {
folder: { type: "string", description: "Folder path (empty string for root)" },
recursive: { type: "boolean", description: "Include subfolders (default true)" }
}
}
},
{
name: "get_active_note",
description: "Get the content of the note the user currently has open in Obsidian",
input_schema: {
type: "object",
properties: {}
}
},
{
name: "get_vault_structure",
description: "Get a tree overview of the vault folder structure",
input_schema: {
type: "object",
properties: {
depth: { type: "number", description: "How many folder levels deep (default 3)" }
}
}
},
{
name: "delete_note",
description: "Delete a note from the vault (moves to trash)",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "Path to the note to delete" }
},
required: ["path"]
}
},
{
name: "move_note",
description: "Move or rename a note",
input_schema: {
type: "object",
properties: {
from: { type: "string", description: "Current path of the note" },
to: { type: "string", description: "New path for the note" }
},
required: ["from", "to"]
}
}
];
}
async function executeVaultTool(app, name, input) {
const vault = app.vault;
switch (name) {
case "read_note": {
const path = input.path;
const file = findFile(vault, path);
if (!file) return `Error: Note not found \u2014 tried "${path}" and "${path}.md"`;
return await vault.read(file);
}
case "search_vault": {
const query = input.query.toLowerCase();
const limit = Math.min(input.limit || 8, 20);
const files = vault.getMarkdownFiles();
const results = [];
for (const file of files) {
if (results.length >= limit) break;
const nameMatch = file.name.toLowerCase().includes(query);
const content = await vault.read(file);
const contentLower = content.toLowerCase();
const contentMatch = contentLower.includes(query);
if (nameMatch || contentMatch) {
let excerpt = "";
if (contentMatch) {
const idx = contentLower.indexOf(query);
const start = Math.max(0, idx - 80);
excerpt = (start > 0 ? "..." : "") + content.slice(start, start + 300) + "...";
} else {
excerpt = content.slice(0, 200) + "...";
}
results.push({ path: file.path, excerpt: excerpt.replace(/\n+/g, " ") });
}
}
if (results.length === 0) return `No notes found matching "${input.query}".`;
return results.map((r) => `### ${r.path}
${r.excerpt}`).join("\n\n---\n\n");
}
case "create_or_update_note": {
const path = normPath(input.path);
const content = input.content;
const append = input.append;
await ensureFolders(vault, path);
const existing = vault.getAbstractFileByPath(path);
if (existing instanceof import_obsidian.TFile) {
if (append) {
const current = await vault.read(existing);
await vault.modify(existing, current + "\n\n" + content);
return `Appended to: ${path}`;
} else {
await vault.modify(existing, content);
return `Updated: ${path}`;
}
} else {
await vault.create(path, content);
return `Created: ${path}`;
}
}
case "list_notes": {
const folder = input.folder || "";
const recursive = input.recursive !== false;
const files = vault.getMarkdownFiles();
const filtered = files.filter((f) => {
var _a, _b;
if (!folder) return true;
const normalizedFolder = folder.endsWith("/") ? folder : folder + "/";
if (recursive) return f.path.startsWith(normalizedFolder) || ((_a = f.parent) == null ? void 0 : _a.path) === folder;
return ((_b = f.parent) == null ? void 0 : _b.path) === folder;
});
if (filtered.length === 0) return "No notes found in that folder.";
return filtered.map((f) => f.path).sort().join("\n");
}
case "get_active_note": {
const activeFile = app.workspace.getActiveFile();
if (!activeFile) return "No note is currently open.";
const content = await vault.read(activeFile);
return `**Active note:** ${activeFile.path}
${content}`;
}
case "get_vault_structure": {
const depth = Math.min(input.depth || 3, 5);
const root = vault.getRoot();
return buildTree(root, depth, 0);
}
case "delete_note": {
const path = input.path;
const file = findFile(vault, path);
if (!file) return `Error: Note not found \u2014 "${path}"`;
await vault.trash(file, true);
return `Moved to trash: ${file.path}`;
}
case "move_note": {
const from = input.from;
const to = normPath(input.to);
const file = findFile(vault, from);
if (!file) return `Error: Source note not found \u2014 "${from}"`;
await ensureFolders(vault, to);
await app.fileManager.renameFile(file, to);
return `Moved: ${file.path} \u2192 ${to}`;
}
default:
return `Unknown vault tool: ${name}`;
}
}
function findFile(vault, path) {
let f = vault.getAbstractFileByPath(path);
if (f instanceof import_obsidian.TFile) return f;
f = vault.getAbstractFileByPath(path + ".md");
if (f instanceof import_obsidian.TFile) return f;
return null;
}
function normPath(path) {
return path.endsWith(".md") ? path : path + ".md";
}
async function ensureFolders(vault, filePath) {
const parts = filePath.split("/");
if (parts.length <= 1) return;
const folders = parts.slice(0, -1);
let current = "";
for (const part of folders) {
current = current ? current + "/" + part : part;
if (!vault.getAbstractFileByPath(current)) {
await vault.createFolder(current);
}
}
}
function buildTree(folder, maxDepth, depth) {
if (depth >= maxDepth) return "";
const indent = " ".repeat(depth);
const lines = [];
const sorted = [...folder.children].sort((a, b) => {
const aIsFolder = a instanceof import_obsidian.TFolder ? 0 : 1;
const bIsFolder = b instanceof import_obsidian.TFolder ? 0 : 1;
return aIsFolder - bIsFolder || a.name.localeCompare(b.name);
});
for (const child of sorted) {
if (child instanceof import_obsidian.TFolder) {
lines.push(`${indent}\u{1F4C1} ${child.name}/`);
const subtree = buildTree(child, maxDepth, depth + 1);
if (subtree) lines.push(subtree);
} else {
lines.push(`${indent}\u{1F4C4} ${child.name}`);
}
}
return lines.join("\n");
}
// src/CodeTools.ts
var import_child_process = require("child_process");
var import_util = require("util");
var import_fs = require("fs");
var import_path = require("path");
var execAsync = (0, import_util.promisify)(import_child_process.exec);
function getCodeTools() {
return [
{
name: "run_command",
description: "Execute a shell command and return stdout/stderr. Use PowerShell syntax on Windows.",
input_schema: {
type: "object",
properties: {
command: { type: "string", description: "Shell command to run" },
cwd: { type: "string", description: "Working directory (optional)" },
timeout: { type: "number", description: "Timeout in ms (default 30000)" }
},
required: ["command"]
}
},
{
name: "read_file",
description: "Read a file from the filesystem (outside the vault)",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "Absolute file path" },
encoding: { type: "string", description: "Encoding (default utf8)" }
},
required: ["path"]
}
},
{
name: "write_file",
description: "Write content to a file on the filesystem",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "Absolute file path" },
content: { type: "string", description: "Content to write" }
},
required: ["path", "content"]
}
},
{
name: "list_directory",
description: "List files and directories at a path",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "Directory path" }
},
required: ["path"]
}
}
];
}
async function executeCodeTool(name, input) {
switch (name) {
case "run_command": {
const command = input.command;
const cwd = input.cwd || process.cwd();
const timeout = input.timeout || 3e4;
try {
const { stdout, stderr } = await execAsync(command, { cwd, timeout });
const out = stdout.trim();
const err = stderr.trim();
let result = "";
if (out) result += `STDOUT:
${out}`;
if (err) result += (result ? "\n\n" : "") + `STDERR:
${err}`;
return result || "(no output)";
} catch (e) {
const err = e;
return `Error: ${err.message || e}
${err.stderr || ""}`.trim();
}
}
case "read_file": {
const path = input.path;
if (!(0, import_fs.existsSync)(path)) return `Error: File not found: ${path}`;
try {
const content = (0, import_fs.readFileSync)(path, input.encoding || "utf8");
return content;
} catch (e) {
return `Error reading file: ${e}`;
}
}
case "write_file": {
const path = input.path;
const content = input.content;
try {
(0, import_fs.writeFileSync)(path, content, "utf8");
return `Written: ${path}`;
} catch (e) {
return `Error writing file: ${e}`;
}
}
case "list_directory": {
const path = input.path;
if (!(0, import_fs.existsSync)(path)) return `Error: Directory not found: ${path}`;
try {
const entries = (0, import_fs.readdirSync)(path);
return entries.map((name2) => {
const full = (0, import_path.join)(path, name2);
const isDir = (0, import_fs.statSync)(full).isDirectory();
return isDir ? `\u{1F4C1} ${name2}/` : `\u{1F4C4} ${name2}`;
}).join("\n");
} catch (e) {
return `Error listing directory: ${e}`;
}
}
default:
return `Unknown code tool: ${name}`;
}
}
// src/CoworkManager.ts
var CoworkManager = class {
constructor(client, app, model, maxTokens) {
this.client = client;
this.app = app;
this.model = model;
this.maxTokens = maxTokens;
}
async runCowork(task, onAgentUpdate, enableVaultTools) {
const tools = enableVaultTools ? getVaultTools() : [];
const agents = [
{
id: "researcher",
name: "\u{1F50D} Researcher",
role: "Thoroughly research the task and gather all relevant context",
model: this.model,
systemPrompt: [
"You are a meticulous research agent. Your job is to thoroughly investigate the given task.",
"Gather all relevant information, context, and details. Be comprehensive and thorough.",
enableVaultTools ? "You have access to the user's Obsidian vault \u2014 use it to find relevant notes and context." : "",
"Format your output as a structured research report."
].filter(Boolean).join("\n"),
status: "idle"
},
{
id: "critic",
name: "\u{1F9D0} Critic",
role: "Identify gaps, challenges, and alternative perspectives",
model: this.model,
systemPrompt: [
"You are a critical analyst. You receive research findings and must:",
"1. Identify gaps and missing information",
"2. Challenge assumptions",
"3. Find potential issues or edge cases",
"4. Suggest alternative perspectives",
"Be constructively critical \u2014 your goal is to improve the final output."
].join("\n"),
status: "idle"
},
{
id: "synthesizer",
name: "\u2728 Synthesizer",
role: "Combine insights into a final comprehensive response",
model: this.model,
systemPrompt: [
"You are a synthesis agent. Given the original task, research findings, and critique:",
"1. Integrate the best insights from all sources",
"2. Address the critique points",
"3. Produce a comprehensive, well-structured final response",
"4. Use clear headings and formatting",
"Your output IS the final answer the user will see."
].join("\n"),
status: "idle"
}
];
const researcher = agents[0];
researcher.status = "thinking";
onAgentUpdate({ ...researcher });
try {
researcher.output = await this.runAgentWithTools(researcher, task, tools);
researcher.status = "done";
} catch (e) {
researcher.output = `Error: ${e}`;
researcher.status = "error";
}
onAgentUpdate({ ...researcher });
const critic = agents[1];
critic.status = "thinking";
onAgentUpdate({ ...critic });
const criticTask = `**Original task:** ${task}
**Research findings:**
${researcher.output || "(none)"}`;
try {
critic.output = await this.runAgentSimple(critic, criticTask);
critic.status = "done";
} catch (e) {
critic.output = `Error: ${e}`;
critic.status = "error";
}
onAgentUpdate({ ...critic });
const synthesizer = agents[2];
synthesizer.status = "thinking";
onAgentUpdate({ ...synthesizer });
const synthTask = [
`**Original task:** ${task}`,
`
**Research:**
${researcher.output || "(none)"}`,
`
**Critique:**
${critic.output || "(none)"}`
].join("\n");
try {
synthesizer.output = await this.runAgentSimple(synthesizer, synthTask);
synthesizer.status = "done";
} catch (e) {
synthesizer.output = `Error: ${e}`;
synthesizer.status = "error";
}
onAgentUpdate({ ...synthesizer });
return { agents, synthesis: synthesizer.output || "" };
}
async runAgentSimple(agent, task) {
const result = await this.client.simpleMessage({
model: agent.model,
messages: [{ role: "user", content: task }],
system: agent.systemPrompt,
maxTokens: Math.min(this.maxTokens, 8096)
});
return result.text;
}
async runAgentWithTools(agent, task, tools) {
const messages = [
{ role: "user", content: task }
];
let finalText = "";
let maxTurns = 6;
while (maxTurns-- > 0) {
const result = await this.client.simpleMessage({
model: agent.model,
messages,
system: agent.systemPrompt,
tools: tools.length > 0 ? tools : void 0,
maxTokens: Math.min(this.maxTokens, 8096)
});
finalText = result.text;
if (result.stopReason !== "tool_use" || result.toolUses.length === 0) break;
const assistantContent = [];
if (result.text) assistantContent.push({ type: "text", text: result.text });
for (const tu of result.toolUses) {
assistantContent.push({ type: "tool_use", id: tu.id, name: tu.name, input: tu.input });
}
messages.push({ role: "assistant", content: assistantContent });
const toolResults = [];
for (const tu of result.toolUses) {
const output = await executeVaultTool(this.app, tu.name, tu.input);
toolResults.push({ type: "tool_result", tool_use_id: tu.id, content: output });
}
messages.push({ role: "user", content: toolResults });
}
return finalText;
}
};
// src/ChatView.ts
var VIEW_TYPE_CLAUDE = "claude-desktop-mirror";
var ClaudeView = class extends import_obsidian2.ItemView {
constructor(leaf, plugin) {
super(leaf);
this.currentConv = null;
this.conversations = [];
this.isStreaming = false;
this.plugin = plugin;
this.client = new AnthropicClient(plugin.settings.apiKey);
}
getViewType() {
return VIEW_TYPE_CLAUDE;
}
getDisplayText() {
return "Claude";
}
getIcon() {
return "bot";
}
async onOpen() {
this.client = new AnthropicClient(this.plugin.settings.apiKey);
this.buildUI();
this.conversations = await this.plugin.store.loadAll();
this.renderConvList();
this.startNew();
}
async onClose() {
}
refreshClient() {
this.client.setApiKey(this.plugin.settings.apiKey);
this.updateModeOptions();
}
// ─── UI Build ────────────────────────────────────────────────────────────────
buildUI() {
const root = this.containerEl.children[1];
root.empty();
root.addClass("cdm-root");
this.sidebarEl = root.createDiv({ cls: "cdm-sidebar" });
this.buildSidebar();
const main = root.createDiv({ cls: "cdm-main" });
this.buildMain(main);
}
buildSidebar() {
const hdr = this.sidebarEl.createDiv({ cls: "cdm-sidebar-hdr" });
const brand = hdr.createDiv({ cls: "cdm-brand" });
brand.createEl("span", { cls: "cdm-brand-icon", text: "C" });
brand.createEl("span", { cls: "cdm-brand-name", text: "Claude" });
const newBtn = hdr.createEl("button", { cls: "cdm-icon-btn", attr: { title: "New conversation" } });
(0, import_obsidian2.setIcon)(newBtn, "square-pen");
newBtn.addEventListener("click", () => this.startNew());
this.convListEl = this.sidebarEl.createDiv({ cls: "cdm-conv-list" });
}
buildMain(main) {
const topbar = main.createDiv({ cls: "cdm-topbar" });
this.topbarTitleEl = topbar.createDiv({ cls: "cdm-topbar-title" });
const controls = topbar.createDiv({ cls: "cdm-topbar-controls" });
this.modelSelect = controls.createEl("select", { cls: "cdm-select" });
[
["claude-haiku-4-5-20251001", "\u26A1 Haiku 4.5"],
["claude-sonnet-4-6", "\u2726 Sonnet 4.6"],
["claude-opus-4-8", "\u25C8 Opus 4.8"]
].forEach(([value, label]) => {
const opt = this.modelSelect.createEl("option", { value, text: label });
if (value === this.plugin.settings.defaultModel) opt.selected = true;
});
this.modelSelect.addEventListener("change", () => {
if (this.currentConv) this.currentConv.model = this.modelSelect.value;
});
this.modeSelect = controls.createEl("select", { cls: "cdm-select" });
this.updateModeOptions();
this.modeSelect.addEventListener("change", () => {
if (this.currentConv) this.currentConv.mode = this.modeSelect.value;
});
this.statusEl = topbar.createDiv({ cls: "cdm-status" });
this.messagesEl = main.createDiv({ cls: "cdm-messages" });
const inputArea = main.createDiv({ cls: "cdm-input-area" });
const wrap = inputArea.createDiv({ cls: "cdm-input-wrap" });
this.inputEl = wrap.createEl("textarea", {
cls: "cdm-input",
attr: { placeholder: "Message Claude\u2026", rows: "1" }
});
this.inputEl.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
this.send();
}
});
this.inputEl.addEventListener("input", () => this.autoResize());
this.sendBtn = wrap.createEl("button", { cls: "cdm-send-btn", attr: { title: "Send" } });
(0, import_obsidian2.setIcon)(this.sendBtn, "send");
this.sendBtn.addEventListener("click", () => this.send());
inputArea.createEl("p", {
text: "Claude can make mistakes. Vault tools enabled.",
cls: "cdm-footer-note"
});
}
updateModeOptions() {
if (!this.modeSelect) return;
const current = this.modeSelect.value;
this.modeSelect.empty();
this.modeSelect.createEl("option", { value: "chat", text: "\u{1F4AC} Chat" });
if (this.plugin.settings.enableCowork)
this.modeSelect.createEl("option", { value: "cowork", text: "\u{1F91D} Co-work" });
if (this.plugin.settings.enableCodeMode)
this.modeSelect.createEl("option", { value: "code", text: "\u{1F4BB} Code" });
if (current) this.modeSelect.value = current;
}
// ─── Conversation List ────────────────────────────────────────────────────────
renderConvList() {
var _a;
this.convListEl.empty();
if (this.conversations.length === 0) {
this.convListEl.createEl("p", { text: "No conversations yet", cls: "cdm-conv-empty" });
return;
}
const today = (/* @__PURE__ */ new Date()).toDateString();
const yesterday = new Date(Date.now() - 864e5).toDateString();
let lastGroup = "";
for (const conv of this.conversations) {
const d = new Date(conv.updatedAt);
const group = d.toDateString() === today ? "Today" : d.toDateString() === yesterday ? "Yesterday" : d.toLocaleDateString(void 0, { month: "short", day: "numeric" });
if (group !== lastGroup) {
this.convListEl.createEl("div", { text: group, cls: "cdm-conv-group" });
lastGroup = group;
}
const item = this.convListEl.createDiv({ cls: "cdm-conv-item" });
if (conv.id === ((_a = this.currentConv) == null ? void 0 : _a.id)) item.addClass("active");
const modeEmoji = conv.mode === "cowork" ? "\u{1F91D} " : conv.mode === "code" ? "\u{1F4BB} " : "";
item.createEl("span", { text: modeEmoji + conv.title, cls: "cdm-conv-title" });
item.addEventListener("click", () => this.loadConv(conv));
const del = item.createEl("button", { cls: "cdm-conv-del", attr: { title: "Delete" } });
(0, import_obsidian2.setIcon)(del, "trash-2");
del.addEventListener("click", async (e) => {
var _a2;
e.stopPropagation();
await this.plugin.store.delete(conv.id);
this.conversations = this.conversations.filter((c) => c.id !== conv.id);
if (((_a2 = this.currentConv) == null ? void 0 : _a2.id) === conv.id) this.startNew();
this.renderConvList();
});
}
}
startNew() {
var _a, _b, _c;
const mode = ((_a = this.modeSelect) == null ? void 0 : _a.value) || "chat";
const model = ((_b = this.modelSelect) == null ? void 0 : _b.value) || this.plugin.settings.defaultModel;
this.currentConv = this.plugin.store.create(model, mode);
(_c = this.messagesEl) == null ? void 0 : _c.empty();
this.renderWelcome();
this.renderConvList();
this.topbarTitleEl && (this.topbarTitleEl.textContent = "");
}
loadConv(conv) {
this.currentConv = conv;
if (this.modelSelect) this.modelSelect.value = conv.model;
if (this.modeSelect) this.modeSelect.value = conv.mode;
if (this.topbarTitleEl) this.topbarTitleEl.textContent = conv.title;
this.messagesEl.empty();
this.renderAllMessages();
this.renderConvList();
}
// ─── Welcome ─────────────────────────────────────────────────────────────────
renderWelcome() {
var _a;
const el = this.messagesEl.createDiv({ cls: "cdm-welcome" });
el.createEl("div", { cls: "cdm-welcome-logo", text: "C" });
el.createEl("h2", { text: "How can I help you today?" });
const mode = ((_a = this.modeSelect) == null ? void 0 : _a.value) || "chat";
if (mode === "cowork") {
el.createEl("p", { text: "\u{1F91D} Co-work mode \u2014 a team of agents (Researcher, Critic, Synthesizer) will collaborate on your request." });
} else if (mode === "code") {
el.createEl("p", { text: "\u{1F4BB} Code mode \u2014 I can run shell commands, read and write files, and help with technical tasks." });
} else if (this.plugin.settings.enableVaultTools) {
el.createEl("p", { text: "I have access to your vault and can read, search, and write notes." });
}
}
// ─── Sending ──────────────────────────────────────────────────────────────────
async send() {
if (!this.currentConv || this.isStreaming) return;
const text = this.inputEl.value.trim();
if (!text) return;
this.inputEl.value = "";
this.autoResize();
const mode = this.modeSelect.value;
if (mode === "cowork" && this.plugin.settings.enableCowork) {
await this.runCowork(text);
} else {
await this.runChat(text);
}
}
// ─── Chat ────────────────────────────────────────────────────────────────────
async runChat(text) {
var _a;
if (!this.currentConv) return;
(_a = this.messagesEl.querySelector(".cdm-welcome")) == null ? void 0 : _a.remove();
this.isStreaming = true;
this.sendBtn.disabled = true;
const userMsg = this.addMessage("user", text);
this.renderConvList();
if (this.currentConv.messages.length === 1) {
const title = text.slice(0, 52) + (text.length > 52 ? "\u2026" : "");
this.currentConv.title = title;
if (this.topbarTitleEl) this.topbarTitleEl.textContent = title;
}
const tools = [
...this.plugin.settings.enableVaultTools ? getVaultTools() : [],
...this.modeSelect.value === "code" && this.plugin.settings.enableCodeMode ? getCodeTools() : []
];
const system = this.buildSystem();
this.setStatus("Thinking\u2026");
const { wrap: assistantWrap, bubble } = this.createMessageBubble("assistant");
const streamEl = bubble.createDiv({ cls: "cdm-stream" });
let streamText = "";
const pendingToolUses = [];
try {
await this.client.streamMessage({
model: this.currentConv.model,
messages: this.buildApiMessages(),
system,
tools: tools.length > 0 ? tools : void 0,
maxTokens: this.plugin.settings.maxTokens,
callbacks: {
onText: (chunk) => {
streamText += chunk;
streamEl.empty();
import_obsidian2.MarkdownRenderer.render(this.app, streamText, streamEl, "", this);
this.scrollBottom();
},
onToolUse: (id, name, input) => {
pendingToolUses.push({ id, name, input });
},
onComplete: async () => {
if (pendingToolUses.length > 0) {
await this.handleToolUses(streamText, pendingToolUses, bubble, tools, system);
} else {
this.finalizeMessage(streamText);
}
},
onError: (err) => {
streamEl.empty();
streamEl.createEl("p", { text: `\u274C ${err.message}`, cls: "cdm-error" });
this.done();
}
}
});
} catch (e) {
new import_obsidian2.Notice(`Claude error: ${e}`);
this.done();
}
}
async handleToolUses(precedingText, toolUses, bubble, tools, system) {
if (!this.currentConv) return;
const assistantContent = [];
if (precedingText) assistantContent.push({ type: "text", text: precedingText });
for (const tu of toolUses) {
assistantContent.push({ type: "tool_use", id: tu.id, name: tu.name, input: tu.input });
this.renderToolUse(bubble, tu.name, tu.input);
}
this.currentConv.messages.push({
id: `msg_${Date.now()}_a`,
role: "assistant",
content: assistantContent,
timestamp: Date.now()
});
this.setStatus("Running tools\u2026");
const toolResults = [];
for (const tu of toolUses) {
const result = tu.name.startsWith("run_command") || tu.name === "read_file" || tu.name === "write_file" || tu.name === "list_directory" ? await executeCodeTool(tu.name, tu.input) : await executeVaultTool(this.app, tu.name, tu.input);
toolResults.push({ type: "tool_result", tool_use_id: tu.id, content: result });
this.renderToolResult(bubble, result);
}
this.currentConv.messages.push({
id: `msg_${Date.now()}_tr`,
role: "user",
content: toolResults,
timestamp: Date.now()
});
this.setStatus("Continuing\u2026");
const continueEl = bubble.createDiv({ cls: "cdm-stream" });
let continueText = "";
await this.client.streamMessage({
model: this.currentConv.model,
messages: this.buildApiMessages(),
system,
tools: tools.length > 0 ? tools : void 0,
maxTokens: this.plugin.settings.maxTokens,
callbacks: {
onText: (chunk) => {
continueText += chunk;
continueEl.empty();
import_obsidian2.MarkdownRenderer.render(this.app, continueText, continueEl, "", this);
this.scrollBottom();
},
onToolUse: () => {
},
onComplete: () => this.finalizeMessage(continueText),
onError: (err) => {
continueEl.createEl("p", { text: `\u274C ${err.message}`, cls: "cdm-error" });
this.done();
}
}
});
}
finalizeMessage(text) {
if (!this.currentConv) return;
this.currentConv.messages.push({
id: `msg_${Date.now()}_f`,
role: "assistant",
content: text,
timestamp: Date.now()
});
this.plugin.store.save(this.currentConv);
if (this.plugin.settings.autoExportChats) {
this.plugin.exporter.export(this.currentConv).catch(() => {
});
}
if (!this.conversations.find((c) => c.id === this.currentConv.id)) {
this.conversations.unshift(this.currentConv);
}