summaryrefslogtreecommitdiffhomepage
path: root/packages/frontend/src/lib/components/AgentBuilder.svelte
blob: f1c9cdf543e161f2d62506192ab6b023e4fb8362 (plain)
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
<script module>
// Session-level cache for models per key; avoids refetching across component instances
const modelCache = new Map();
</script>

<script lang="ts">
	import {
		DEFAULT_REASONING_EFFORT,
		REASONING_EFFORTS,
		REASONING_EFFORT_LABELS,
	} from "@dispatch/core/src/types/index.js";
	import { config } from "../config.js";
	import { router } from "../router.svelte.js";
	import type { KeyInfo } from "../types.js";
	import SkillsBrowser from "./SkillsBrowser.svelte";
	import ToolPermissions from "./ToolPermissions.svelte";

	interface AgentModelEntry {
		key_id: string;
		model_id: string;
		effort?: string;
	}

	interface AgentDefinition {
		name: string;
		description: string;
		skills: string[];
		tools: string[];
		models: AgentModelEntry[];
		scope: string;
		slug: string;
		cwd?: string;
		is_subagent?: boolean;
	}

	interface DirEntry {
		label: string;
		path: string;
		scope: string;
	}

	const { keys = [] }: { keys?: KeyInfo[] } = $props();



	// Portal action (escape stacking context)
	function portal(node: HTMLElement) {
		document.body.appendChild(node);
		return {
			destroy() {
				node.remove();
			},
		};
	}

	// State
	let agents = $state<AgentDefinition[]>([]);
	let dirs = $state<DirEntry[]>([]);
	let loading = $state(false);
	let error = $state<string | null>(null);

	// Editor state
	let editing = $state(false);
	let editingSlug = $state<string | null>(null); // null = new agent

	let formName = $state("");
	let formDescription = $state("");
	let formScope = $state("global");
	let formCwd = $state("");
	let cwdExists = $state<boolean | null>(null);
	let cwdResolved = $state<string | null>(null);
	let cwdCheckTimer: ReturnType<typeof setTimeout> | null = null;
	let formSkills = $state<Set<string>>(new Set());
	let formTools = $state<Set<string>>(new Set());
	let formModels = $state<AgentModelEntry[]>([]);
	let formIsSubagent = $state(false);

	// Model selection modal state
	let modelModalIndex = $state<number | null>(null);
	let modelModalType = $state<"key" | "model">("key");
	let modalAvailableModels = $state<string[]>([]);
	let modalLoadingModels = $state(false);
	let modalModelError = $state<string | null>(null);

	// Drag-and-drop reorder state
	let dragIndex = $state<number | null>(null);
	let dragOverIndex = $state<number | null>(null);

	// Delete confirm
	let deletingAgent = $state<AgentDefinition | null>(null);

	function slugify(name: string): string {
		return name
			.toLowerCase()
			.replace(/[^a-z0-9]+/g, "-")
			.replace(/^-+|-+$/g, "")
			|| "agent";
	}

	async function fetchAgents() {
		loading = true;
		error = null;
		try {
			const res = await fetch(`${config.apiBase}/agents`);
			if (!res.ok) throw new Error(`HTTP ${res.status}`);
			const data = await res.json();
			agents = data.agents ?? [];
			dirs = data.dirs ?? [];
		} catch (e) {
			error = e instanceof Error ? e.message : "Failed to fetch agents";
		} finally {
			loading = false;
		}
	}

	function handleSkillToggle(key: string, checked: boolean) {
		const next = new Set(formSkills);
		if (checked) next.add(key);
		else next.delete(key);
		formSkills = next;
	}

	function startNewAgent() {
		formReady = false;
		editingSlug = null;
		formName = "";
		formDescription = "";
		formScope = dirs[0]?.scope ?? "global";
		formCwd = "";
		formSkills = new Set();
		formTools = new Set();
		formModels = [];
		formIsSubagent = true;
		editing = true;
		// Allow the effect to skip the initial population
		setTimeout(() => { formReady = true; }, 0);
	}

	function startEdit(agent: AgentDefinition) {
		formReady = false;
		editingSlug = agent.slug;
		formName = agent.name;
		formDescription = agent.description;
		formScope = agent.scope;
		formCwd = agent.cwd ?? "";
		formSkills = new Set(agent.skills);
		formTools = new Set(agent.tools);
		formModels = agent.models.map((m) => ({ ...m }));
		formIsSubagent = agent.is_subagent ?? false;
		editing = true;
		// Allow the effect to skip the initial population
		setTimeout(() => { formReady = true; }, 0);
	}

	function cancelEdit() {
		// Flush any pending debounced save before leaving
		if (debounceTimer) {
			clearTimeout(debounceTimer);
			debounceTimer = null;
			saveAgent();
		}
		formReady = false;
		editing = false;
		editingSlug = null;
	}

	function handleToolToggle(id: string, checked: boolean) {
		const next = new Set(formTools);
		if (checked) next.add(id);
		else next.delete(id);
		formTools = next;
	}

	function addModelEntry() {
		formModels = [...formModels, { key_id: "", model_id: "" }];
	}

	function removeModelEntry(i: number) {
		formModels = formModels.filter((_, idx) => idx !== i);
	}

	function setEffortEntry(i: number, effort: string) {
		formModels = formModels.map((m, idx) => {
			if (idx !== i) return m;
			// Empty string = "inherit" (no per-model override). Strip the key so
			// the saved TOML omits `effort` and the call site falls back to the
			// per-tab selector / default.
			if (!effort) {
				const { effort: _dropped, ...rest } = m;
				return rest;
			}
			return { ...m, effort };
		});
	}

	async function openKeyModal(i: number) {
		modelModalIndex = i;
		modelModalType = "key";
	}

	async function openModelModal(i: number) {
		const entry = formModels[i];
		if (!entry || !entry.key_id) return;
		modelModalIndex = i;
		modelModalType = "model";
		modalModelError = null;
		modalAvailableModels = [];

		if (modelCache.has(entry.key_id)) {
			modalAvailableModels = modelCache.get(entry.key_id)!;
			return;
		}

		modalLoadingModels = true;
		try {
			const res = await fetch(
				`${config.apiBase}/models/available?keyId=${encodeURIComponent(entry.key_id)}`,
			);
			if (!res.ok) {
				const d = await res.json().catch(() => ({}));
				modalModelError = d.error ?? `HTTP ${res.status}`;
				return;
			}
			const d = await res.json();
			modalAvailableModels = d.models ?? [];
			modelCache.set(entry.key_id, modalAvailableModels);
		} catch (e) {
			modalModelError = e instanceof Error ? e.message : "Failed";
		} finally {
			modalLoadingModels = false;
		}
	}

	function selectKey(keyId: string) {
		if (modelModalIndex === null) return;
		const idx = modelModalIndex;
		formModels = formModels.map((m, i) =>
			i === idx ? { key_id: keyId, model_id: "" } : m,
		);
		modelModalIndex = null;
		// Immediately open model selection for the same row
		openModelModal(idx);
	}

	function selectModel(model: string) {
		if (modelModalIndex === null) return;
		formModels = formModels.map((m, i) =>
			i === modelModalIndex ? { ...m, model_id: model } : m,
		);
		modelModalIndex = null;
	}

	function closeModal() {
		modelModalIndex = null;
	}

	let formError = $state<string | null>(null);
	let saving = $state(false);
	let formReady = false;
	let debounceTimer: ReturnType<typeof setTimeout> | null = null;
	let saveAbort: AbortController | null = null;

	function isFormValid(): boolean {
		if (!formName.trim()) return false;
		if (formModels.length === 0) return false;
		if (formModels.some((m) => !m.key_id || !m.model_id)) return false;
		return true;
	}

	async function saveAgent() {
		if (!isFormValid()) return;
		formError = null;

		// Cancel any in-flight save
		saveAbort?.abort();
		const controller = new AbortController();
		saveAbort = controller;

		const payload: AgentDefinition = {
			name: formName.trim(),
			description: formDescription.trim(),
			skills: Array.from(formSkills),
			tools: Array.from(formTools),
			models: formModels,
			scope: formScope,
			slug: editingSlug ?? slugify(formName.trim()),
			...(formCwd.trim() ? { cwd: formCwd.trim() } : {}),
			...(formIsSubagent ? { is_subagent: true } : {}),
		};

		saving = true;
		try {
			const res = await fetch(`${config.apiBase}/agents`, {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify(payload),
				signal: controller.signal,
			});
			if (!res.ok) {
				const d = await res.json().catch(() => ({}));
				formError = d.error ?? `HTTP ${res.status}`;
				return;
			}
			// If this was a new agent, lock in the slug for future saves
			if (!editingSlug) {
				editingSlug = payload.slug;
			}
			await fetchAgents();
		} catch (e) {
			if (e instanceof DOMException && e.name === "AbortError") return;
			formError = e instanceof Error ? e.message : "Failed to save";
		} finally {
			if (saveAbort === controller) {
				saving = false;
				saveAbort = null;
			}
		}
	}

	// Check if CWD directory exists (debounced)
	$effect(() => {
		const cwd = formCwd;
		if (!cwd.trim()) {
			cwdExists = null;
			cwdResolved = null;
			return;
		}
		if (cwdCheckTimer) clearTimeout(cwdCheckTimer);
		cwdCheckTimer = setTimeout(async () => {
			try {
				const res = await fetch(
					`${config.apiBase}/agents/check-dir?path=${encodeURIComponent(cwd.trim())}`,
				);
				if (res.ok) {
					const data = await res.json();
					cwdExists = data.exists ?? false;
					cwdResolved = data.resolved ?? null;
				}
			} catch {
				cwdExists = null;
				cwdResolved = null;
			}
		}, 300);
	});

	// Auto-save with debounce whenever form fields change
	$effect(() => {
		// Read all reactive form fields to subscribe
		// noinspection: intentionally unused — reading these values subscribes the effect to them
		void [formName, formDescription, formScope, formCwd, formSkills, formTools, formModels, formIsSubagent];
		if (!formReady || !editing) return;
		if (debounceTimer) clearTimeout(debounceTimer);
		debounceTimer = setTimeout(() => {
			saveAgent();
		}, 600);
	});

	async function deleteAgent(agent: AgentDefinition) {
		try {
			// Prevent auto-save from re-creating the deleted agent
			formReady = false;
			if (debounceTimer) {
				clearTimeout(debounceTimer);
				debounceTimer = null;
			}
			saveAbort?.abort();

			const res = await fetch(
				`${config.apiBase}/agents/${encodeURIComponent(agent.slug)}?scope=${encodeURIComponent(agent.scope)}`,
				{ method: "DELETE" },
			);
			if (!res.ok) throw new Error(`HTTP ${res.status}`);
			deletingAgent = null;
			editing = false;
			editingSlug = null;
			await fetchAgents();
		} catch (e) {
			error = e instanceof Error ? e.message : "Failed to delete";
		}
	}

	const hasName = $derived(formName.trim().length > 0);

	const globalAgents = $derived(agents.filter((a) => a.scope === "global"));
	const projectAgents = $derived(agents.filter((a) => a.scope !== "global"));

	// Fetch on mount
	$effect(() => {
		fetchAgents();
	});
</script>

<div class="flex flex-col flex-1 overflow-hidden">
	<!-- Page header -->
	<div class="flex items-center gap-4 px-6 py-4 border-b border-base-300 bg-base-200 shrink-0">
		<h1 class="text-xl font-bold flex-1">Agent Settings</h1>
		<button
			type="button"
			class="btn btn-ghost btn-sm"
			onclick={() => { if (editing) { cancelEdit(); } else { router.navigate("dashboard"); } }}
		>
			{editing ? '← Back to Agent Settings' : '← Back to Dashboard'}
		</button>
	</div>

	<div class="flex-1 overflow-y-auto px-6 py-6">
		{#if error}
			<div class="alert alert-error mb-4">{error}</div>
		{/if}

		{#if editing}
			<!-- Agent Editor Form -->
			<div class="card bg-base-200 shadow-md">
				<div class="card-body gap-4">
					<h2 class="card-title">{editingSlug ? "Edit Agent" : "New Agent"}</h2>

					{#if formError}
						<div class="alert alert-error text-sm">{formError}</div>
					{/if}

					<!-- Name -->
					<div class="form-control gap-1">
						<label class="label py-0" for="agent-name">
							<span class="label-text font-semibold">Name *</span>
						</label>
						<input
							id="agent-name"
							type="text"
							class="input input-bordered"
							placeholder="my-agent"
							bind:value={formName}
						/>
						{#if formName}
							<span class="text-xs text-base-content/50">slug: {slugify(formName)}</span>
						{/if}
					</div>

					<fieldset disabled={!hasName} class="contents">
					<!-- Description -->
					<div class="form-control gap-1">
						<label class="label py-0" for="agent-desc">
							<span class="label-text font-semibold">Description</span>
						</label>
						<input
							id="agent-desc"
							type="text"
							class="input input-bordered"
							placeholder="What does this agent do?"
							bind:value={formDescription}
						/>
					</div>

					<!-- Is Subagent -->
					<div class="form-control">
						<label class="label cursor-pointer justify-start gap-3 py-1">
							<input
								type="checkbox"
								class="checkbox checkbox-sm rounded-sm"
								bind:checked={formIsSubagent}
							/>
							<div>
								<span class="label-text font-semibold">Is Subagent</span>
								<p class="text-xs text-base-content/50">Subagents are hidden from Chat Settings and can only be used by other agents.</p>
							</div>
						</label>
					</div>

					<!-- Scope -->
					<div class="form-control gap-1">
						<label class="label py-0" for="agent-scope">
							<span class="label-text font-semibold">Scope</span>
						</label>
						<select id="agent-scope" class="select select-bordered" bind:value={formScope}>
							<option value="global">Global</option>
							{#each dirs.filter((d) => d.scope !== "global") as dir}
								<option value={dir.scope}>{dir.label} ({dir.path})</option>
							{/each}
						</select>
					</div>

					<!-- Working Directory -->
					<div class="form-control gap-1">
						<label class="label py-0" for="agent-cwd">
							<span class="label-text font-semibold">Working Directory</span>
						</label>
						<div class="flex items-center gap-2">
							<input
								id="agent-cwd"
								type="text"
								class="input input-bordered font-mono text-sm flex-1"
								placeholder="default (project root)"
								bind:value={formCwd}
							/>
							{#if formCwd.trim()}
								{#if cwdExists === true}
									<span class="text-success text-lg" title="Directory exists">&#x2714;</span>
								{:else if cwdExists === false}
									<span class="text-warning text-lg" title="Directory does not exist (will be created)">&#x2716;</span>
								{:else}
									<span class="loading loading-spinner loading-xs"></span>
								{/if}
							{/if}
						</div>
						{#if cwdExists === false && formCwd.trim()}
							<span class="text-xs text-warning">Directory will be created automatically on first message.</span>
						{/if}
						{#if cwdResolved && formCwd.trim() && cwdResolved !== formCwd.trim()}
							<span class="text-xs text-base-content/50 font-mono">{cwdResolved}</span>
						{/if}
						{#if !formCwd.trim()}
							<span class="text-xs text-base-content/50">Absolute or relative path. Relative paths resolve against the parent agent's working directory, or the project root.</span>
						{/if}
					</div>

					<!-- Models -->
					<div class="form-control gap-2">
						<div class="label py-0">
							<span class="label-text font-semibold">Models *</span>
						</div>
					<div class="flex flex-col gap-2">
						{#each formModels as entry, i (i)}
							<div
								class="flex items-center gap-2 rounded p-1 transition-colors {dragOverIndex === i ? 'bg-primary/10 border border-primary/30' : ''}"
								draggable="true"
								role="listitem"
								ondragstart={(e) => {
									dragIndex = i;
									if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
								}}
								ondragover={(e) => {
									e.preventDefault();
									if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
									dragOverIndex = i;
								}}
								ondragleave={() => {
									if (dragOverIndex === i) dragOverIndex = null;
								}}
								ondrop={(e) => {
									e.preventDefault();
									if (dragIndex !== null && dragIndex !== i) {
										const reordered = [...formModels];
										const moved = reordered.splice(dragIndex, 1)[0];
										if (moved) {
											reordered.splice(i, 0, moved);
											formModels = reordered;
										}
									}
									dragIndex = null;
									dragOverIndex = null;
								}}
								ondragend={() => { dragIndex = null; dragOverIndex = null; }}
							>
								<span class="badge badge-sm badge-neutral font-mono w-6 shrink-0 cursor-grab">{i + 1}</span>
								<button
									type="button"
									class="btn btn-sm btn-outline flex-1 font-mono truncate"
									onclick={() => openKeyModal(i)}
								>
									{entry.key_id || "Select Key"}
								</button>
								<button
									type="button"
									class="btn btn-sm btn-outline flex-1 font-mono truncate"
									onclick={() => openModelModal(i)}
									disabled={!entry.key_id}
								>
									{entry.model_id || "Select Model"}
								</button>
								<select
									class="select select-bordered select-sm shrink-0 w-36"
									title="Reasoning effort for this model. 'Inherit' uses the per-tab selector / default."
									value={entry.effort ?? ""}
									onchange={(e) => setEffortEntry(i, e.currentTarget.value)}
								>
									<option value="">Inherit ({REASONING_EFFORT_LABELS[DEFAULT_REASONING_EFFORT]})</option>
									{#each REASONING_EFFORTS as effort}
										<option value={effort}>{REASONING_EFFORT_LABELS[effort]}</option>
									{/each}
								</select>
								<button
									type="button"
									class="btn btn-sm btn-ghost text-error"
									onclick={() => removeModelEntry(i)}
									aria-label="Remove model entry"
								>
									✕
								</button>
							</div>
						{/each}
					</div>
						<button
							type="button"
							class="btn btn-sm btn-ghost w-fit"
							onclick={addModelEntry}
						>
							+ Add Model
						</button>
					</div>

					<!-- Tools -->
					<div class="form-control gap-2">
						<div class="label py-0">
							<span class="label-text font-semibold">Tools</span>
						</div>
						<ToolPermissions
							checkedTools={formTools}
							onToolToggle={handleToolToggle}
						/>
					</div>

					<!-- Skills -->
					<div class="form-control gap-2">
						<div class="label py-0">
							<span class="label-text font-semibold">Skills</span>
						</div>
						<SkillsBrowser
							apiBase={config.apiBase}
							checkedSkills={formSkills}
							onSkillToggle={handleSkillToggle}
						/>
					</div>

					<!-- Actions -->
					<div class="card-actions justify-between items-center pt-2">
						{#if editingSlug && !(editingSlug === "default" && formScope === "global")}
							<button
								type="button"
								class="btn btn-error btn-ghost"
								onclick={() => {
									const agent = agents.find((a) => a.slug === editingSlug && a.scope === formScope);
									if (agent) deletingAgent = agent;
								}}
							>Delete</button>
						{:else}
							<div></div>
						{/if}
						<div class="flex items-center gap-2">
							{#if saving}
								<span class="text-xs text-base-content/50">Saving...</span>
							{/if}
						</div>
					</div>
				</fieldset>
				</div>
			</div>
		{:else}
			<!-- Agent List -->
			{#if loading}
				<div class="flex justify-center py-16">
					<span class="loading loading-spinner loading-lg"></span>
				</div>
			{:else}
				<!-- Global Agents -->
				<section class="mb-8">
					<h2 class="text-lg font-semibold mb-3">Global Agents</h2>
					<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
						{#each globalAgents as agent}
							<button
								type="button"
								class="card bg-base-200 shadow-sm hover:bg-base-300 transition-colors cursor-pointer text-left"
								onclick={() => startEdit(agent)}
							>
								<div class="card-body p-4 gap-2">
									<h3 class="font-semibold font-mono truncate">{agent.name}</h3>
									{#if agent.description}
										<p class="text-sm text-base-content/60 truncate">{agent.description}</p>
									{/if}
									<div class="flex gap-2 flex-wrap">
										<span class="badge badge-sm badge-neutral">{agent.models.length} model{agent.models.length !== 1 ? "s" : ""}</span>
										<span class="badge badge-sm badge-neutral">{agent.skills.length} skill{agent.skills.length !== 1 ? "s" : ""}</span>
										<span class="badge badge-sm badge-outline">{agent.tools.length} tool{agent.tools.length !== 1 ? "s" : ""}</span>
									</div>
								</div>
							</button>
						{/each}
						<button
							type="button"
							class="card bg-base-200 shadow-sm hover:bg-base-300 transition-colors cursor-pointer border-2 border-dashed border-base-content/20"
							onclick={startNewAgent}
						>
							<div class="card-body p-4 items-center justify-center">
								<span class="text-2xl text-base-content/30">+</span>
								<span class="text-sm text-base-content/50">New Agent</span>
							</div>
						</button>
					</div>
				</section>

				<!-- Project Agents -->
				{#if projectAgents.length > 0 || dirs.some((d) => d.scope !== "global")}
					<section>
						<h2 class="text-lg font-semibold mb-3">Project Agents</h2>
						{#if projectAgents.length === 0}
							<p class="text-base-content/50 italic text-sm">No project agents yet.</p>
						{:else}
							<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
								{#each projectAgents as agent}
									<button
										type="button"
										class="card bg-base-200 shadow-sm hover:bg-base-300 transition-colors cursor-pointer text-left"
										onclick={() => startEdit(agent)}
									>
										<div class="card-body p-4 gap-2">
											<h3 class="font-semibold font-mono truncate">{agent.name}</h3>
											{#if agent.description}
												<p class="text-sm text-base-content/60 truncate">{agent.description}</p>
											{/if}
											<p class="text-xs text-base-content/40 font-mono truncate">{agent.scope}</p>
											<div class="flex gap-2 flex-wrap">
												<span class="badge badge-sm badge-neutral">{agent.models.length} model{agent.models.length !== 1 ? "s" : ""}</span>
												<span class="badge badge-sm badge-neutral">{agent.skills.length} skill{agent.skills.length !== 1 ? "s" : ""}</span>
												<span class="badge badge-sm badge-outline">{agent.tools.length} tool{agent.tools.length !== 1 ? "s" : ""}</span>
											</div>
										</div>
									</button>
								{/each}
							</div>
						{/if}
					</section>
				{/if}
			{/if}
		{/if}
	</div>
</div>

<!-- Key selection modal -->
{#if modelModalIndex !== null && modelModalType === "key"}
	<div class="modal modal-open" use:portal>
		<div class="modal-box">
			<h3 class="font-bold text-xl">Select Key</h3>
			<div class="mt-4 flex flex-col gap-2">
				{#each keys as key}
					<button
						type="button"
						class="btn {formModels[modelModalIndex ?? 0]?.key_id === key.id ? 'btn-primary' : 'btn-ghost'} justify-start text-base"
						onclick={() => selectKey(key.id)}
					>
						<span class="font-mono">{key.id}</span>
						<span class="badge ml-auto">{key.provider}</span>
						<span class="badge {key.status === 'active' ? 'badge-success' : 'badge-error'}">{key.status}</span>
					</button>
				{/each}
			</div>
			<div class="modal-action">
				<button type="button" class="btn" onclick={closeModal}>Cancel</button>
			</div>
		</div>
		<button type="button" class="modal-backdrop" onclick={closeModal} aria-label="Close modal"></button>
	</div>
{/if}

<!-- Model selection modal -->
{#if modelModalIndex !== null && modelModalType === "model"}
	<div class="modal modal-open" use:portal>
		<div class="modal-box">
			<h3 class="font-bold text-xl">Select Model</h3>
			{#if modalLoadingModels}
				<div class="flex justify-center py-8">
					<span class="loading loading-spinner loading-lg"></span>
				</div>
			{:else if modalModelError}
				<div class="alert alert-error mt-4 text-base">
					<span>{modalModelError}</span>
				</div>
			{:else}
				<div class="mt-4 flex flex-col gap-1 max-h-96 overflow-y-auto">
					{#each modalAvailableModels as model}
						<button
							type="button"
							class="btn {formModels[modelModalIndex ?? 0]?.model_id === model ? 'btn-primary' : 'btn-ghost'} justify-start font-mono text-base"
							onclick={() => selectModel(model)}
						>
							{model}
						</button>
					{/each}
				</div>
			{/if}
			<div class="modal-action">
				<button type="button" class="btn" onclick={closeModal}>Cancel</button>
			</div>
		</div>
		<button type="button" class="modal-backdrop" onclick={closeModal} aria-label="Close modal"></button>
	</div>
{/if}

<!-- Delete confirm modal -->
{#if deletingAgent !== null}
	{@const agentToDelete = deletingAgent}
	<div class="modal modal-open" use:portal>
		<div class="modal-box">
			<h3 class="font-bold text-lg">Delete Agent</h3>
			<p class="py-4">
				Are you sure you want to delete <span class="font-mono font-semibold">{agentToDelete.name}</span>? This cannot be undone.
			</p>
			<div class="modal-action">
				<button type="button" class="btn btn-ghost" onclick={() => { deletingAgent = null; }}>Cancel</button>
				<button
					type="button"
					class="btn btn-error"
					onclick={() => deleteAgent(agentToDelete)}
				>Delete</button>
			</div>
		</div>
		<button type="button" class="modal-backdrop" onclick={() => { deletingAgent = null; }} aria-label="Close modal"></button>
	</div>
{/if}