-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude-fixes.patch
More file actions
7206 lines (6894 loc) · 311 KB
/
claude-fixes.patch
File metadata and controls
7206 lines (6894 loc) · 311 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
From e2a6633954bd45d4b736852af2c2d44402c0a66e Mon Sep 17 00:00:00 2001
From: serafim <serafimcloud@gmail.com>
Date: Thu, 15 Jan 2026 17:24:06 -0800
Subject: [PATCH 01/33] Release v0.0.14
## What's New in v0.0.14
### Features
- Custom agents support with @ mentions integration
### Improvements & Fixes
- Improved mentions experience
- Improved UI to display user answers to clarifying questions
---
package.json | 2 +-
scripts/upload-release-wrangler.sh | 185 ------
src/main/lib/trpc/routers/agent-utils.ts | 244 ++++++++
src/main/lib/trpc/routers/agents.ts | 275 +++++++++
src/main/lib/trpc/routers/claude.ts | 167 ++++-
src/main/lib/trpc/routers/index.ts | 2 +
.../dialogs/agents-settings-dialog.tsx | 18 +-
.../dialogs/settings-tabs/agent-dialog.tsx | 368 +++++++++++
.../agents-custom-agents-tab.tsx | 282 +++++++++
.../settings-tabs/agents-skills-tab.tsx | 19 +-
.../components/dialogs/settings-tabs/index.ts | 1 +
.../dialogs/settings-tabs/tool-selector.tsx | 159 +++++
src/renderer/features/agents/atoms/index.ts | 4 +
.../features/agents/lib/ipc-chat-transport.ts | 57 +-
.../features/agents/main/active-chat.tsx | 131 +++-
.../agents/mentions/agents-file-mention.tsx | 577 ++++++++----------
.../mentions/agents-mentions-editor.tsx | 8 +-
.../agents/mentions/render-file-mentions.tsx | 45 +-
.../ui/agent-ask-user-question-tool.tsx | 62 +-
.../agents/ui/agent-user-question.tsx | 1 +
.../features/agents/ui/sub-chat-selector.tsx | 15 +-
.../features/agents/utils/auto-rename.ts | 5 +-
.../features/sub-chats/sub-chats-sidebar.tsx | 14 +-
src/renderer/lib/atoms/index.ts | 5 +-
24 files changed, 2045 insertions(+), 601 deletions(-)
delete mode 100755 scripts/upload-release-wrangler.sh
create mode 100644 src/main/lib/trpc/routers/agent-utils.ts
create mode 100644 src/main/lib/trpc/routers/agents.ts
create mode 100644 src/renderer/components/dialogs/settings-tabs/agent-dialog.tsx
create mode 100644 src/renderer/components/dialogs/settings-tabs/agents-custom-agents-tab.tsx
create mode 100644 src/renderer/components/dialogs/settings-tabs/tool-selector.tsx
diff --git a/package.json b/package.json
index cec6ef3..f3ecc3b 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "21st-desktop",
- "version": "0.0.13",
+ "version": "0.0.14",
"private": true,
"description": "1Code - UI for parallel work with AI agents",
"author": "21st.dev",
diff --git a/scripts/upload-release-wrangler.sh b/scripts/upload-release-wrangler.sh
deleted file mode 100755
index d3f7b09..0000000
--- a/scripts/upload-release-wrangler.sh
+++ /dev/null
@@ -1,185 +0,0 @@
-#!/bin/bash
-
-# Build, notarize, and release desktop app
-# Usage: ./scripts/upload-release-wrangler.sh
-#
-# Requires:
-# - Keychain profile "21st-notarize" (xcrun notarytool store-credentials)
-# - wrangler authenticated (npx wrangler login)
-# - gh CLI authenticated (gh auth login)
-
-set -e
-
-SCRIPT_DIR="$(dirname "$0")"
-BUCKET="components-code"
-PREFIX="releases/desktop"
-RELEASE_DIR="$SCRIPT_DIR/../release"
-PACKAGE_JSON="$SCRIPT_DIR/../package.json"
-KEYCHAIN_PROFILE="21st-notarize"
-
-# Get version from package.json
-VERSION=$(node -p "require('$PACKAGE_JSON').version")
-TAG="v$VERSION"
-
-echo "============================================================"
-echo "📦 Releasing Desktop v$VERSION"
-echo "============================================================"
-echo ""
-
-if [ ! -d "$RELEASE_DIR" ]; then
- echo "❌ Release directory not found: $RELEASE_DIR"
- echo " Run 'bun run build && bun run package:mac && bun run dist:manifest' first"
- exit 1
-fi
-
-cd "$RELEASE_DIR"
-
-# ============================================================
-# Part 0: Submit DMGs for notarization (async, no waiting)
-# ============================================================
-echo "🔏 Submitting DMGs for notarization..."
-echo ""
-
-for dmg in *.dmg; do
- if [ -f "$dmg" ]; then
- echo " Submitting $dmg..."
- xcrun notarytool submit "$dmg" --keychain-profile "$KEYCHAIN_PROFILE"
- echo ""
- fi
-done
-
-echo "✅ Notarization submitted! Check status with:"
-echo " xcrun notarytool history --keychain-profile \"$KEYCHAIN_PROFILE\""
-echo ""
-echo " After approved, staple with:"
-echo " cd release && xcrun stapler staple *.dmg"
-echo ""
-
-# ============================================================
-# Part 1: Upload to R2 CDN
-# ============================================================
-echo "📤 Uploading to R2 CDN..."
-echo ""
-
-# Upload manifests first
-echo " Uploading manifests..."
-npx wrangler r2 object put "$BUCKET/$PREFIX/latest-mac.yml" --file=latest-mac.yml --content-type="text/yaml"
-npx wrangler r2 object put "$BUCKET/$PREFIX/latest-mac-x64.yml" --file=latest-mac-x64.yml --content-type="text/yaml"
-echo " ✅ Manifests uploaded"
-
-# Upload blockmaps (for delta updates)
-echo ""
-echo " Uploading blockmaps..."
-for f in *.blockmap; do
- if [ -f "$f" ]; then
- npx wrangler r2 object put "$BUCKET/$PREFIX/$f" --file="$f" --content-type="application/octet-stream"
- fi
-done
-echo " ✅ Blockmaps uploaded"
-
-# Upload ZIP files (for auto-update)
-echo ""
-echo " Uploading ZIP files..."
-for f in *-mac.zip; do
- if [ -f "$f" ]; then
- SIZE=$(ls -lh "$f" | awk '{print $5}')
- echo " Uploading $f ($SIZE)..."
- npx wrangler r2 object put "$BUCKET/$PREFIX/$f" --file="$f" --content-type="application/zip"
- fi
-done
-echo " ✅ ZIP files uploaded"
-
-# Upload DMG files (for manual download)
-echo ""
-echo " Uploading DMG files..."
-for f in *.dmg; do
- if [ -f "$f" ]; then
- SIZE=$(ls -lh "$f" | awk '{print $5}')
- echo " Uploading $f ($SIZE)..."
- npx wrangler r2 object put "$BUCKET/$PREFIX/$f" --file="$f" --content-type="application/x-apple-diskimage"
- fi
-done
-echo " ✅ DMG files uploaded"
-
-echo ""
-echo "✅ R2 CDN upload complete!"
-echo ""
-
-# ============================================================
-# Part 2: Create/Update GitHub Release
-# ============================================================
-echo "============================================================"
-echo "🐙 Creating GitHub Release $TAG..."
-echo "============================================================"
-echo ""
-
-# Check if gh is installed
-if ! command -v gh &> /dev/null; then
- echo "❌ GitHub CLI (gh) not found. Install it: brew install gh"
- exit 1
-fi
-
-# Check if release exists
-if gh release view "$TAG" &> /dev/null; then
- echo " Release $TAG exists, updating..."
-
- # Delete existing assets
- echo " Deleting old assets..."
- ASSETS=$(gh release view "$TAG" --json assets -q '.assets[].name')
- for asset in $ASSETS; do
- echo " Deleting $asset..."
- gh release delete-asset "$TAG" "$asset" --yes 2>/dev/null || true
- done
-
- # Upload new assets
- echo ""
- echo " Uploading new assets..."
- for f in *.dmg *.zip *.blockmap; do
- if [ -f "$f" ]; then
- echo " Uploading $f..."
- gh release upload "$TAG" "$f" --clobber
- fi
- done
-
- echo ""
- echo " ✅ Release $TAG updated!"
-else
- echo " Creating new release $TAG..."
-
- # Collect asset files
- ASSETS=""
- for f in *.dmg *.zip *.blockmap; do
- if [ -f "$f" ]; then
- ASSETS="$ASSETS $f"
- fi
- done
-
- # Create release with assets (not draft, mark as latest)
- gh release create "$TAG" \
- --title "1Code $TAG" \
- --latest \
- --notes "## What's New
-
-- Desktop app release $TAG
-
-## Downloads
-
-- **macOS ARM64 (Apple Silicon)**: Download the \`-arm64.dmg\` file
-- **macOS Intel**: Download the \`-x64.dmg\` file
-
-Auto-updates are enabled. Existing users will be notified automatically." \
- $ASSETS
-
- echo ""
- echo " ✅ Release $TAG created!"
-fi
-
-echo ""
-echo "============================================================"
-echo "✅ Release complete!"
-echo ""
-echo "🔗 URLs:"
-echo " CDN ARM64: https://cdn.21st.dev/$PREFIX/latest-mac.yml"
-echo " CDN x64: https://cdn.21st.dev/$PREFIX/latest-mac-x64.yml"
-echo " GitHub: https://github.com/21st-dev/21st/releases/tag/$TAG"
-echo "============================================================"
diff --git a/src/main/lib/trpc/routers/agent-utils.ts b/src/main/lib/trpc/routers/agent-utils.ts
new file mode 100644
index 0000000..fab52f4
--- /dev/null
+++ b/src/main/lib/trpc/routers/agent-utils.ts
@@ -0,0 +1,244 @@
+import * as fs from "fs/promises"
+import * as path from "path"
+import * as os from "os"
+import matter from "gray-matter"
+
+// Valid model values for agents
+export const VALID_AGENT_MODELS = ["sonnet", "opus", "haiku", "inherit"] as const
+export type AgentModel = (typeof VALID_AGENT_MODELS)[number]
+
+// Agent definition parsed from markdown file
+export interface ParsedAgent {
+ name: string
+ description: string
+ prompt: string
+ tools?: string[]
+ disallowedTools?: string[]
+ model?: AgentModel
+}
+
+// Agent with source/path metadata
+export interface FileAgent extends ParsedAgent {
+ source: "user" | "project"
+ path: string
+}
+
+/**
+ * Parse agent markdown file with YAML frontmatter
+ * Format:
+ * ---
+ * name: code-reviewer
+ * description: Reviews code for quality
+ * tools: Read, Glob, Grep
+ * model: sonnet
+ * ---
+ *
+ * You are a code reviewer. When invoked...
+ */
+export function parseAgentMd(
+ content: string,
+ filename: string
+): Partial<ParsedAgent> {
+ try {
+ const { data, content: body } = matter(content)
+
+ // Parse tools - can be comma-separated string or array
+ let tools: string[] | undefined
+ if (typeof data.tools === "string") {
+ tools = data.tools
+ .split(",")
+ .map((t: string) => t.trim())
+ .filter(Boolean)
+ } else if (Array.isArray(data.tools)) {
+ tools = data.tools
+ }
+
+ // Parse disallowedTools
+ let disallowedTools: string[] | undefined
+ if (typeof data.disallowedTools === "string") {
+ disallowedTools = data.disallowedTools
+ .split(",")
+ .map((t: string) => t.trim())
+ .filter(Boolean)
+ } else if (Array.isArray(data.disallowedTools)) {
+ disallowedTools = data.disallowedTools
+ }
+
+ // Validate model
+ const model =
+ data.model && VALID_AGENT_MODELS.includes(data.model)
+ ? (data.model as AgentModel)
+ : undefined
+
+ return {
+ name:
+ typeof data.name === "string" ? data.name : filename.replace(".md", ""),
+ description: typeof data.description === "string" ? data.description : "",
+ prompt: body.trim(),
+ tools,
+ disallowedTools,
+ model,
+ }
+ } catch (err) {
+ console.error("[agents] Failed to parse markdown:", err)
+ return {}
+ }
+}
+
+/**
+ * Generate markdown content for agent file
+ */
+export function generateAgentMd(agent: {
+ name: string
+ description: string
+ prompt: string
+ tools?: string[]
+ disallowedTools?: string[]
+ model?: AgentModel
+}): string {
+ const frontmatter: string[] = []
+ frontmatter.push(`name: ${agent.name}`)
+ frontmatter.push(`description: ${agent.description}`)
+ if (agent.tools && agent.tools.length > 0) {
+ frontmatter.push(`tools: ${agent.tools.join(", ")}`)
+ }
+ if (agent.disallowedTools && agent.disallowedTools.length > 0) {
+ frontmatter.push(`disallowedTools: ${agent.disallowedTools.join(", ")}`)
+ }
+ if (agent.model && agent.model !== "inherit") {
+ frontmatter.push(`model: ${agent.model}`)
+ }
+
+ return `---\n${frontmatter.join("\n")}\n---\n\n${agent.prompt}`
+}
+
+/**
+ * Load agent definition from filesystem by name
+ * Searches in user (~/.claude/agents/) and project (.claude/agents/) directories
+ */
+export async function loadAgent(
+ name: string,
+ cwd?: string
+): Promise<ParsedAgent | null> {
+ const locations = [
+ path.join(os.homedir(), ".claude", "agents"),
+ ...(cwd ? [path.join(cwd, ".claude", "agents")] : []),
+ ]
+
+ for (const dir of locations) {
+ const agentPath = path.join(dir, `${name}.md`)
+ try {
+ const content = await fs.readFile(agentPath, "utf-8")
+ const parsed = parseAgentMd(content, `${name}.md`)
+
+ if (parsed.description && parsed.prompt) {
+ return {
+ name: parsed.name || name,
+ description: parsed.description,
+ prompt: parsed.prompt,
+ tools: parsed.tools,
+ disallowedTools: parsed.disallowedTools,
+ model: parsed.model,
+ }
+ }
+ } catch {
+ continue
+ }
+ }
+
+ return null
+}
+
+/**
+ * Scan directory for agent .md files
+ * Format: .claude/agents/agent-name.md
+ */
+export async function scanAgentsDirectory(
+ dir: string,
+ source: "user" | "project"
+): Promise<FileAgent[]> {
+ const agents: FileAgent[] = []
+
+ try {
+ await fs.access(dir)
+ const entries = await fs.readdir(dir, { withFileTypes: true })
+
+ for (const entry of entries) {
+ // Validate entry name for security (prevent path traversal)
+ if (
+ entry.name.includes("..") ||
+ entry.name.includes("/") ||
+ entry.name.includes("\\")
+ ) {
+ console.warn(`[agents] Skipping invalid filename: ${entry.name}`)
+ continue
+ }
+
+ // Accept .md files (Claude Code native format)
+ if (entry.isFile() && entry.name.endsWith(".md")) {
+ const agentPath = path.join(dir, entry.name)
+ try {
+ const content = await fs.readFile(agentPath, "utf-8")
+ const parsed = parseAgentMd(content, entry.name)
+
+ if (parsed.description && parsed.prompt) {
+ agents.push({
+ name: parsed.name || entry.name.replace(".md", ""),
+ description: parsed.description,
+ prompt: parsed.prompt,
+ tools: parsed.tools,
+ disallowedTools: parsed.disallowedTools,
+ model: parsed.model,
+ source,
+ path: agentPath,
+ })
+ }
+ } catch (err) {
+ console.error(`[agents] Failed to read agent ${entry.name}:`, err)
+ }
+ }
+ }
+ } catch (err) {
+ // Directory doesn't exist or not accessible
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
+ console.warn(`[agents] Could not scan directory ${dir}:`, err)
+ }
+ }
+
+ return agents
+}
+
+/**
+ * Build agents Record for SDK Options
+ * This properly registers agents with the SDK so Claude can invoke them via Task tool
+ */
+export async function buildAgentsOption(
+ agentNames: string[],
+ cwd?: string
+): Promise<
+ Record<
+ string,
+ { description: string; prompt: string; tools?: string[]; model?: AgentModel }
+ >
+> {
+ if (agentNames.length === 0) return {}
+
+ const agents: Record<
+ string,
+ { description: string; prompt: string; tools?: string[]; model?: AgentModel }
+ > = {}
+
+ for (const name of agentNames) {
+ const agent = await loadAgent(name, cwd)
+ if (agent) {
+ agents[name] = {
+ description: agent.description,
+ prompt: agent.prompt,
+ ...(agent.tools && { tools: agent.tools }),
+ ...(agent.model && { model: agent.model }),
+ }
+ }
+ }
+
+ return agents
+}
diff --git a/src/main/lib/trpc/routers/agents.ts b/src/main/lib/trpc/routers/agents.ts
new file mode 100644
index 0000000..423061d
--- /dev/null
+++ b/src/main/lib/trpc/routers/agents.ts
@@ -0,0 +1,275 @@
+import { z } from "zod"
+import { router, publicProcedure } from "../index"
+import * as fs from "fs/promises"
+import * as path from "path"
+import * as os from "os"
+import {
+ parseAgentMd,
+ generateAgentMd,
+ scanAgentsDirectory,
+ VALID_AGENT_MODELS,
+ type FileAgent,
+} from "./agent-utils"
+
+// Shared procedure for listing agents
+const listAgentsProcedure = publicProcedure
+ .input(
+ z
+ .object({
+ cwd: z.string().optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ input }) => {
+ const userAgentsDir = path.join(os.homedir(), ".claude", "agents")
+ const userAgentsPromise = scanAgentsDirectory(userAgentsDir, "user")
+
+ let projectAgentsPromise = Promise.resolve<FileAgent[]>([])
+ if (input?.cwd) {
+ const projectAgentsDir = path.join(input.cwd, ".claude", "agents")
+ projectAgentsPromise = scanAgentsDirectory(projectAgentsDir, "project")
+ }
+
+ const [userAgents, projectAgents] = await Promise.all([
+ userAgentsPromise,
+ projectAgentsPromise,
+ ])
+
+ return [...projectAgents, ...userAgents]
+ })
+
+export const agentsRouter = router({
+ /**
+ * List all agents from filesystem
+ * - User agents: ~/.claude/agents/
+ * - Project agents: .claude/agents/ (relative to cwd)
+ */
+ list: listAgentsProcedure,
+
+ /**
+ * Alias for list - used by @ mention
+ */
+ listEnabled: listAgentsProcedure,
+
+ /**
+ * Get single agent by name
+ */
+ get: publicProcedure
+ .input(z.object({ name: z.string(), cwd: z.string().optional() }))
+ .query(async ({ input }) => {
+ const locations = [
+ {
+ dir: path.join(os.homedir(), ".claude", "agents"),
+ source: "user" as const,
+ },
+ ...(input.cwd
+ ? [
+ {
+ dir: path.join(input.cwd, ".claude", "agents"),
+ source: "project" as const,
+ },
+ ]
+ : []),
+ ]
+
+ for (const { dir, source } of locations) {
+ const agentPath = path.join(dir, `${input.name}.md`)
+ try {
+ const content = await fs.readFile(agentPath, "utf-8")
+ const parsed = parseAgentMd(content, `${input.name}.md`)
+ return {
+ ...parsed,
+ source,
+ path: agentPath,
+ }
+ } catch {
+ continue
+ }
+ }
+ return null
+ }),
+
+ /**
+ * Create a new agent
+ */
+ create: publicProcedure
+ .input(
+ z.object({
+ name: z.string(),
+ description: z.string(),
+ prompt: z.string(),
+ tools: z.array(z.string()).optional(),
+ disallowedTools: z.array(z.string()).optional(),
+ model: z.enum(VALID_AGENT_MODELS).optional(),
+ source: z.enum(["user", "project"]),
+ cwd: z.string().optional(),
+ })
+ )
+ .mutation(async ({ input }) => {
+ // Validate name (kebab-case, no special chars)
+ const safeName = input.name.toLowerCase().replace(/[^a-z0-9-]/g, "-")
+ if (!safeName || safeName.includes("..")) {
+ throw new Error("Invalid agent name")
+ }
+
+ // Determine target directory
+ let targetDir: string
+ if (input.source === "project") {
+ if (!input.cwd) {
+ throw new Error("Project path (cwd) required for project agents")
+ }
+ targetDir = path.join(input.cwd, ".claude", "agents")
+ } else {
+ targetDir = path.join(os.homedir(), ".claude", "agents")
+ }
+
+ // Ensure directory exists
+ await fs.mkdir(targetDir, { recursive: true })
+
+ const agentPath = path.join(targetDir, `${safeName}.md`)
+
+ // Check if already exists
+ try {
+ await fs.access(agentPath)
+ throw new Error(`Agent "${safeName}" already exists`)
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
+ throw err
+ }
+ }
+
+ // Generate and write file
+ const content = generateAgentMd({
+ name: safeName,
+ description: input.description,
+ prompt: input.prompt,
+ tools: input.tools,
+ disallowedTools: input.disallowedTools,
+ model: input.model,
+ })
+
+ await fs.writeFile(agentPath, content, "utf-8")
+
+ return {
+ name: safeName,
+ path: agentPath,
+ source: input.source,
+ }
+ }),
+
+ /**
+ * Update an existing agent
+ */
+ update: publicProcedure
+ .input(
+ z.object({
+ originalName: z.string(),
+ name: z.string(),
+ description: z.string(),
+ prompt: z.string(),
+ tools: z.array(z.string()).optional(),
+ disallowedTools: z.array(z.string()).optional(),
+ model: z.enum(VALID_AGENT_MODELS).optional(),
+ source: z.enum(["user", "project"]),
+ cwd: z.string().optional(),
+ })
+ )
+ .mutation(async ({ input }) => {
+ // Validate names
+ const safeOriginalName = input.originalName.toLowerCase().replace(/[^a-z0-9-]/g, "-")
+ const safeName = input.name.toLowerCase().replace(/[^a-z0-9-]/g, "-")
+ if (!safeOriginalName || !safeName || safeName.includes("..")) {
+ throw new Error("Invalid agent name")
+ }
+
+ // Determine target directory
+ let targetDir: string
+ if (input.source === "project") {
+ if (!input.cwd) {
+ throw new Error("Project path (cwd) required for project agents")
+ }
+ targetDir = path.join(input.cwd, ".claude", "agents")
+ } else {
+ targetDir = path.join(os.homedir(), ".claude", "agents")
+ }
+
+ const originalPath = path.join(targetDir, `${safeOriginalName}.md`)
+ const newPath = path.join(targetDir, `${safeName}.md`)
+
+ // Check original exists
+ try {
+ await fs.access(originalPath)
+ } catch {
+ throw new Error(`Agent "${safeOriginalName}" not found`)
+ }
+
+ // If renaming, check new name doesn't exist
+ if (safeOriginalName !== safeName) {
+ try {
+ await fs.access(newPath)
+ throw new Error(`Agent "${safeName}" already exists`)
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
+ throw err
+ }
+ }
+ }
+
+ // Generate and write file
+ const content = generateAgentMd({
+ name: safeName,
+ description: input.description,
+ prompt: input.prompt,
+ tools: input.tools,
+ disallowedTools: input.disallowedTools,
+ model: input.model,
+ })
+
+ // Delete old file if renaming
+ if (safeOriginalName !== safeName) {
+ await fs.unlink(originalPath)
+ }
+
+ await fs.writeFile(newPath, content, "utf-8")
+
+ return {
+ name: safeName,
+ path: newPath,
+ source: input.source,
+ }
+ }),
+
+ /**
+ * Delete an agent
+ */
+ delete: publicProcedure
+ .input(
+ z.object({
+ name: z.string(),
+ source: z.enum(["user", "project"]),
+ cwd: z.string().optional(),
+ })
+ )
+ .mutation(async ({ input }) => {
+ const safeName = input.name.toLowerCase().replace(/[^a-z0-9-]/g, "-")
+ if (!safeName || safeName.includes("..")) {
+ throw new Error("Invalid agent name")
+ }
+
+ let targetDir: string
+ if (input.source === "project") {
+ if (!input.cwd) {
+ throw new Error("Project path (cwd) required for project agents")
+ }
+ targetDir = path.join(input.cwd, ".claude", "agents")
+ } else {
+ targetDir = path.join(os.homedir(), ".claude", "agents")
+ }
+
+ const agentPath = path.join(targetDir, `${safeName}.md`)
+
+ await fs.unlink(agentPath)
+
+ return { deleted: true }
+ }),
+})
diff --git a/src/main/lib/trpc/routers/claude.ts b/src/main/lib/trpc/routers/claude.ts
index 7f2472b..e2d2548 100644
--- a/src/main/lib/trpc/routers/claude.ts
+++ b/src/main/lib/trpc/routers/claude.ts
@@ -2,6 +2,8 @@ import { observable } from "@trpc/server/observable"
import { eq } from "drizzle-orm"
import { app, safeStorage } from "electron"
import path from "path"
+import * as os from "os"
+import * as fs from "fs/promises"
import { z } from "zod"
import {
buildClaudeEnv,
@@ -13,6 +15,55 @@ import {
} from "../../claude"
import { chats, claudeCodeCredentials, getDatabase, subChats } from "../../db"
import { publicProcedure, router } from "../index"
+import { buildAgentsOption } from "./agent-utils"
+
+/**
+ * Parse @[agent:name] and @[skill:name] mentions from prompt text
+ * Returns the cleaned prompt and lists of mentioned agents/skills
+ */
+function parseMentions(prompt: string): {
+ cleanedPrompt: string
+ agentMentions: string[]
+ skillMentions: string[]
+ fileMentions: string[]
+ folderMentions: string[]
+} {
+ const agentMentions: string[] = []
+ const skillMentions: string[] = []
+ const fileMentions: string[] = []
+ const folderMentions: string[] = []
+
+ // Match @[prefix:name] pattern
+ const mentionRegex = /@\[(file|folder|skill|agent):([^\]]+)\]/g
+ let match
+
+ while ((match = mentionRegex.exec(prompt)) !== null) {
+ const [, type, name] = match
+ switch (type) {
+ case "agent":
+ agentMentions.push(name)
+ break
+ case "skill":
+ skillMentions.push(name)
+ break
+ case "file":
+ fileMentions.push(name)
+ break
+ case "folder":
+ folderMentions.push(name)
+ break
+ }
+ }
+
+ // Clean agent/skill mentions from prompt (they will be added as context)
+ // Keep file/folder mentions as they are useful context
+ const cleanedPrompt = prompt
+ .replace(/@\[agent:[^\]]+\]/g, "")
+ .replace(/@\[skill:[^\]]+\]/g, "")
+ .trim()
+
+ return { cleanedPrompt, agentMentions, skillMentions, fileMentions, folderMentions }
+}
/**
* Decrypt token using Electron's safeStorage
@@ -235,9 +286,42 @@ export const claudeRouter = router({
// Capture stderr from Claude process for debugging
const stderrLines: string[] = []
+ // Parse mentions from prompt (agents, skills, files, folders)
+ const { cleanedPrompt, agentMentions, skillMentions } = parseMentions(input.prompt)
+
+ // Build agents option for SDK (proper registration via options.agents)
+ const agentsOption = await buildAgentsOption(agentMentions, input.cwd)
+
+ // Log if agents were mentioned
+ if (agentMentions.length > 0) {
+ console.log(`[claude] Registering agents via SDK:`, Object.keys(agentsOption))
+ }
+
+ // Log if skills were mentioned
+ if (skillMentions.length > 0) {
+ console.log(`[claude] Skills mentioned:`, skillMentions)
+ }
+
+ // Build final prompt with skill instructions if needed
+ let finalPrompt = cleanedPrompt
+
+ // Handle empty prompt when only mentions are present
+ if (!finalPrompt.trim()) {
+ if (agentMentions.length > 0 && skillMentions.length > 0) {
+ finalPrompt = `Use the ${agentMentions.join(", ")} agent(s) and invoke the "${skillMentions.join('", "')}" skill(s) using the Skill tool for this task.`
+ } else if (agentMentions.length > 0) {
+ finalPrompt = `Use the ${agentMentions.join(", ")} agent(s) for this task.`
+ } else if (skillMentions.length > 0) {
+ finalPrompt = `Invoke the "${skillMentions.join('", "')}" skill(s) using the Skill tool for this task.`
+ }
+ } else if (skillMentions.length > 0) {
+ // Append skill instruction to existing prompt
+ finalPrompt = `${finalPrompt}\n\nUse the "${skillMentions.join('", "')}" skill(s) for this task.`
+ }
+
// Build prompt: if there are images, create an AsyncIterable<SDKUserMessage>
// Otherwise use simple string prompt
- let prompt: string | AsyncIterable<any> = input.prompt
+ let prompt: string | AsyncIterable<any> = finalPrompt
if (input.images && input.images.length > 0) {
// Create message content array with images first, then text
@@ -253,10 +337,10 @@ export const claudeRouter = router({
]
// Add text if present
- if (input.prompt.trim()) {
+ if (finalPrompt.trim()) {
messageContent.push({
type: "text" as const,
- text: input.prompt,
+ text: finalPrompt,
})
}
@@ -295,6 +379,44 @@ export const claudeRouter = router({
input.subChatId
)
+ // Ensure isolated config dir exists and symlink skills/agents from ~/.claude/
+ // This is needed because SDK looks for skills at $CLAUDE_CONFIG_DIR/skills/
+ try {
+ await fs.mkdir(isolatedConfigDir, { recursive: true })
+
+ const homeClaudeDir = path.join(os.homedir(), ".claude")
+ const skillsSource = path.join(homeClaudeDir, "skills")
+ const skillsTarget = path.join(isolatedConfigDir, "skills")
+ const agentsSource = path.join(homeClaudeDir, "agents")
+ const agentsTarget = path.join(isolatedConfigDir, "agents")
+
+ // Symlink skills directory if source exists and target doesn't
+ try {
+ const skillsSourceExists = await fs.stat(skillsSource).then(() => true).catch(() => false)
+ const skillsTargetExists = await fs.lstat(skillsTarget).then(() => true).catch(() => false)
+ if (skillsSourceExists && !skillsTargetExists) {
+ await fs.symlink(skillsSource, skillsTarget, "dir")
+ console.log(`[claude] Symlinked skills: ${skillsTarget} -> ${skillsSource}`)
+ }
+ } catch (symlinkErr) {
+ // Ignore symlink errors (might already exist or permission issues)
+ }
+
+ // Symlink agents directory if source exists and target doesn't
+ try {
+ const agentsSourceExists = await fs.stat(agentsSource).then(() => true).catch(() => false)
+ const agentsTargetExists = await fs.lstat(agentsTarget).then(() => true).catch(() => false)
+ if (agentsSourceExists && !agentsTargetExists) {
+ await fs.symlink(agentsSource, agentsTarget, "dir")
+ console.log(`[claude] Symlinked agents: ${agentsTarget} -> ${agentsSource}`)
+ }
+ } catch (symlinkErr) {
+ // Ignore symlink errors (might already exist or permission issues)
+ }
+ } catch (mkdirErr) {
+ console.error(`[claude] Failed to setup isolated config dir:`, mkdirErr)
+ }
+
// Build final env - only add OAuth token if we have one
const finalEnv = {
...claudeEnv,
@@ -317,8 +439,9 @@ export const claudeRouter = router({
systemPrompt: {
type: "preset" as const,
preset: "claude_code" as const,
- append: " ",
},
+ // Register mentioned agents with SDK via options.agents
+ ...(Object.keys(agentsOption).length > 0 && { agents: agentsOption }),
env: finalEnv,
permissionMode:
input.mode === "plan"
@@ -370,12 +493,43 @@ export const claudeRouter = router({
})
})
+ // Find the tool part in accumulated parts
+ const askToolPart = parts.find(
+ (p) => p.toolCallId === toolUseID && p.type === "tool-AskUserQuestion"
+ )
+
if (!response.approved) {
+ // Update the tool part with error result for skipped/denied
+ const errorMessage = response.message || "Skipped"
+ if (askToolPart) {
+ askToolPart.result = errorMessage
+ askToolPart.state = "result"
+ }
+ // Emit result to frontend so it updates in real-time
+ safeEmit({
+ type: "ask-user-question-result",
+ toolUseId: toolUseID,
+ result: errorMessage,
+ } as UIMessageChunk)
return {
behavior: "deny",
- message: response.message || "Skipped",
+ message: errorMessage,
}
}
+
+ // Update the tool part with answers result for approved
+ const answers = (response.updatedInput as any)?.answers
+ const answerResult = { answers }
+ if (askToolPart) {
+ askToolPart.result = answerResult
+ askToolPart.state = "result"
+ }