Skip to content

Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base

lots of improvements

Hugo Richarde1e6021e96f4
diff --git a/apps/chat/app/app.config.ts b/apps/chat/app/app.config.ts
index 32914ec..15c332a 100644
--- a/apps/chat/app/app.config.ts
+++ b/apps/chat/app/app.config.ts
@@ -1,7 +1,7 @@
export default defineAppConfig({
ui: {
colors: {
- primary: 'blue',
+ primary: 'primary',
neutral: 'neutral'
}
}
diff --git a/apps/chat/app/app.vue b/apps/chat/app/app.vue
index 832afe0..9c46494 100644
--- a/apps/chat/app/app.vue
+++ b/apps/chat/app/app.vue
@@ -17,16 +17,16 @@ useHead({
}
})
-const title = 'Nuxt AI Chatbot template'
-const description = 'A full-featured, hackable Nuxt AI chatbot template made with Nuxt UI.'
+const title = 'Savoir'
+const description = 'Savoir - Your intelligent AI assistant for knowledge and insights.'
useSeoMeta({
title,
description,
ogTitle: title,
ogDescription: description,
- ogImage: 'https://ui.nuxt.com/assets/templates/nuxt/chat-light.png',
- twitterImage: 'https://ui.nuxt.com/assets/templates/nuxt/chat-light.png',
+ ogImage: '/og-image.png',
+ twitterImage: '/og-image.png',
twitterCard: 'summary_large_image'
})
</script>
diff --git a/apps/chat/app/assets/css/main.css b/apps/chat/app/assets/css/main.css
index c10e75f..0e5aef3 100644
--- a/apps/chat/app/assets/css/main.css
+++ b/apps/chat/app/assets/css/main.css
@@ -2,21 +2,26 @@
@import "@nuxt/ui";
@theme static {
- --font-sans: 'Public Sans', sans-serif;
+ --font-sans: 'Barlow', sans-serif;
- --color-green-50: #EFFDF5;
- --color-green-100: #D9FBE8;
- --color-green-200: #B3F5D1;
- --color-green-300: #75EDAE;
- --color-green-400: #00DC82;
- --color-green-500: #00C16A;
- --color-green-600: #00A155;
- --color-green-700: #007F45;
- --color-green-800: #016538;
- --color-green-900: #0A5331;
- --color-green-950: #052E16;
+ --color-primary-50: #E6EBFA;
+ --color-primary-100: #C2CDF3;
+ --color-primary-200: #99ABEA;
+ --color-primary-300: #6B85E0;
+ --color-primary-400: #4766D8;
+ --color-primary-500: #0035D0;
+ --color-primary-600: #002EB8;
+ --color-primary-700: #00259E;
+ --color-primary-800: #001D85;
+ --color-primary-900: #00155C;
+ --color-primary-950: #000D3D;
}
:root {
--ui-container: var(--container-3xl);
}
+
+::view-transition-old(root),
+::view-transition-new(root) {
+ animation: none;
+}
diff --git a/apps/chat/app/assets/icons/custom/savoir.svg b/apps/chat/app/assets/icons/custom/savoir.svg
new file mode 100644
index 0000000..69b72a1
--- /dev/null
+++ b/apps/chat/app/assets/icons/custom/savoir.svg
@@ -0,0 +1,8 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" aria-hidden="true" id="reading">
+ <title>savoir</title>
+ <g fill="currentColor">
+ <circle cx="9" cy="3.75" r="2.75" stroke-width="0"></circle>
+ <path d="m8.25,8.4724l-3.9668-1.2693c-.5376-.1699-1.1079-.0791-1.5649.2529-.4565.3335-.7183.8486-.7183,1.4141v4.6499c0,.7637.4888,1.4336,1.2168,1.667l5.0332,1.6104v-8.325Z" stroke-width="0"></path>
+ <path d="m15.2817,7.4561c-.4561-.332-1.0273-.4248-1.5649-.2529l-3.9668,1.2693v8.325l5.0337-1.6104c.7275-.2334,1.2163-.9033,1.2163-1.667v-4.6499c0-.5654-.2617-1.0806-.7183-1.4141Z" stroke-width="0"></path>
+ </g>
+</svg>
\ No newline at end of file
diff --git a/apps/chat/app/components/ChatLoading.vue b/apps/chat/app/components/ChatLoading.vue
index be448eb..3d7a7b5 100644
--- a/apps/chat/app/components/ChatLoading.vue
+++ b/apps/chat/app/components/ChatLoading.vue
@@ -123,7 +123,7 @@ watch(() => props.isLoading, (isLoading) => {
:transition="{ duration: 0.2 }"
class="shrink-0 mr-2.5"
>
- <ChatMatrix :size="4" :dot-size="3" :gap="3" />
+ <ChatMatrix :size="5" :dot-size="1.5" :gap="1.5" />
</motion.div>
<motion.span
:animate="{ x: 0 }"
@@ -137,7 +137,7 @@ watch(() => props.isLoading, (isLoading) => {
<div
v-if="toolCalls?.length"
class="flex flex-col gap-0.5"
- :class="isLoading ? 'pl-[31px]' : 'pl-0'"
+ :class="isLoading ? 'pl-[28px]' : 'pl-0'"
>
<ToolCallItem
v-for="tool in toolCalls"
diff --git a/apps/chat/app/components/ChatMatrix.vue b/apps/chat/app/components/ChatMatrix.vue
index 443742d..2079b00 100644
--- a/apps/chat/app/components/ChatMatrix.vue
+++ b/apps/chat/app/components/ChatMatrix.vue
@@ -8,7 +8,7 @@ interface Props {
}
const props = withDefaults(defineProps<Props>(), {
- size: 4,
+ size: 5,
dotSize: 2,
gap: 2,
})
@@ -17,14 +17,76 @@ const totalDots = computed(() => props.size * props.size)
const activeDots = ref<Set<number>>(new Set())
const patterns = [
- [[0], [1], [2], [3], [7], [11], [15], [14], [13], [12], [8], [4], [5], [6], [10], [9]],
- [[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]],
- [[5, 6, 9, 10], [1, 4, 7, 8, 11, 14], [0, 3, 12, 15], [1, 4, 7, 8, 11, 14], [5, 6, 9, 10]],
- [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]],
- [[0], [3], [15], [12]],
- [[5, 6, 9, 10], [1, 2, 4, 7, 8, 11, 13, 14], [0, 3, 12, 15]],
- [[0], [1], [2], [3], [7], [6], [5], [4], [8], [9], [10], [11], [15], [14], [13], [12]],
- [[0], [1, 4], [2, 5, 8], [3, 6, 9, 12], [7, 10, 13], [11, 14], [15]],
+ // Spiral pattern from outside to center
+ [[0], [1], [2], [3], [4], [9], [14], [19], [24], [23], [22], [21], [20], [15], [10], [5], [6], [7], [8], [13], [18], [17], [16], [11], [12]],
+
+ // Vertical waves
+ [[0, 5, 10, 15, 20], [1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24]],
+
+ // Center expand
+ [[12], [6, 7, 8, 11, 13, 16, 17, 18], [1, 2, 3, 5, 9, 10, 14, 15, 19, 21, 22, 23], [0, 4, 20, 24]],
+
+ // Horizontal waves
+ [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]],
+
+ // Corners
+ [[0], [4], [24], [20], [12]],
+
+ // Cross pattern
+ [[2, 10, 11, 12, 13, 14, 22], [6, 7, 8, 16, 17, 18], [0, 1, 3, 4, 5, 9, 15, 19, 20, 21, 23, 24]],
+
+ // Diagonal
+ [[0], [1, 5], [2, 6, 10], [3, 7, 11, 15], [4, 8, 12, 16, 20], [9, 13, 17, 21], [14, 18, 22], [19, 23], [24]],
+
+ // Random clusters
+ [[6, 7, 8, 11, 12, 13, 16, 17, 18], [1, 3, 5, 9, 10, 14, 15, 19, 21, 23], [0, 2, 4, 20, 22, 24]],
+
+ // Checkerboard
+ [
+ [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
+ [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
+ ],
+
+ // Rain drops (columns falling one by one)
+ [[0], [5], [10], [15], [20], [1], [6], [11], [16], [21], [2], [7], [12], [17], [22], [3], [8], [13], [18], [23], [4], [9], [14], [19], [24]],
+
+ // Square outline inwards
+ [
+ [0, 1, 2, 3, 4, 9, 14, 19, 24, 23, 22, 21, 20, 15, 10, 5],
+ [6, 7, 8, 13, 18, 17, 16, 11],
+ [12]
+ ],
+
+ // Zigzag rows
+ [
+ [0, 1, 2, 3, 4],
+ [9, 8, 7, 6, 5],
+ [10, 11, 12, 13, 14],
+ [19, 18, 17, 16, 15],
+ [20, 21, 22, 23, 24]
+ ],
+
+ // Pulsating fill - all on, then all off, then center only, then outwards
+ [
+ Array.from({ length: 25 }, (_, i) => i), // all on
+ [], // all off
+ [12],
+ [6, 7, 8, 11, 13, 16, 17, 18, 12],
+ [0, 4, 20, 24, 12],
+ Array.from({ length: 25 }, (_, i) => i)
+ ],
+
+ // Arrow right
+ [[0, 5, 10, 15, 20], [6, 11, 16, 21], [12, 17, 22], [13, 18, 23], [14, 19, 24]],
+
+ // Arrow left
+ [[4, 9, 14, 19, 24], [3, 8, 13, 18], [2, 7, 12, 17], [1, 6, 11, 16], [0, 5, 10, 15, 20]],
+
+ // X pattern
+ [[0, 4, 6, 8, 12, 16, 18, 20, 24], [1, 3, 7, 11, 13, 17, 21, 23], [2, 12, 22], [5, 15], [9, 19]],
+
+ // Spiral in reverse (center to outside)
+ [[12], [11, 13, 7, 17], [6, 8, 16, 18], [1, 2, 3, 5, 9, 10, 14, 15, 19, 21, 22, 23], [0, 4, 20, 24]],
]
let patternIndex = 0
@@ -64,8 +126,8 @@ useIntervalFn(nextStep, 120, { immediateCallback: true })
<span
v-for="i in totalDots"
:key="i"
- class="rounded-[0.5px] bg-current transition-opacity duration-100"
- :class="activeDots.has(i - 1) ? 'opacity-100' : 'opacity-20'"
+ class="rounded-full bg-current transition-all duration-150 ease-out"
+ :class="activeDots.has(i - 1) ? 'opacity-100 scale-115' : 'opacity-15 scale-75'"
:style="dotStyle"
/>
</div>
diff --git a/apps/chat/app/components/Logo.vue b/apps/chat/app/components/Logo.vue
deleted file mode 100644
index 3916f5f..0000000
--- a/apps/chat/app/components/Logo.vue
+++ /dev/null
@@ -1,11 +0,0 @@
-<template>
- <svg
- width="264"
- height="264"
- viewBox="0 0 264 264"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path d="M146.496 211.2H234.822C237.627 211.2 240.383 210.468 242.813 209.078C245.242 207.688 247.259 205.688 248.662 203.279C250.064 200.871 250.801 198.139 250.8 195.359C250.799 192.579 250.059 189.847 248.655 187.44L189.337 85.612C187.935 83.2043 185.918 81.2049 183.489 79.8147C181.06 78.4246 178.305 77.6927 175.5 77.6927C172.695 77.6927 169.94 78.4246 167.511 79.8147C165.082 81.2049 163.065 83.2043 161.663 85.612L146.496 111.666L116.841 60.7179C115.438 58.3104 113.42 56.3113 110.991 54.9214C108.561 53.5315 105.805 52.7998 103 52.7998C100.195 52.7998 97.4386 53.5315 95.0089 54.9214C92.5793 56.3113 90.5615 58.3104 89.1583 60.7179L15.3453 187.44C13.9411 189.847 13.2012 192.579 13.2 195.359C13.1987 198.139 13.9363 200.871 15.3384 203.279C16.7405 205.688 18.7578 207.688 21.1873 209.078C23.6168 210.468 26.3728 211.2 29.1783 211.2H84.6219C106.589 211.2 122.789 201.636 133.937 182.979L161 136.526L175.496 111.666L219 186.34H161L146.496 211.2ZM83.7181 186.314L45.0255 186.306L103.026 86.7466L131.966 136.526L112.589 169.798C105.186 181.904 96.7763 186.314 83.7181 186.314Z" fill="var(--ui-primary)" />
- </svg>
-</template>
diff --git a/apps/chat/app/components/ToolCallItem.vue b/apps/chat/app/components/ToolCallItem.vue
index 877e683..3008947 100644
--- a/apps/chat/app/components/ToolCallItem.vue
+++ b/apps/chat/app/components/ToolCallItem.vue
@@ -160,12 +160,12 @@ function truncateOutput(text: string, maxLines = 8): string {
<template>
<motion.div
- :initial="{ opacity: 0, x: -6 }"
+ :initial="{ opacity: 0, x: -4 }"
:animate="{ opacity: 1, x: 0 }"
- :transition="{ duration: 0.35, ease: [0.25, 0.1, 0.25, 1] }"
+ :transition="{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }"
>
<button
- class="flex items-center gap-2 w-full text-left py-0.5 group rounded -mx-1 px-1 outline-none focus-visible:ring-1 focus-visible:ring-muted/30"
+ class="flex items-center gap-1.5 w-full text-left group rounded -mx-1 px-1 outline-none focus-visible:ring-1 focus-visible:ring-muted/30"
:class="[
canExpand ? 'cursor-pointer hover:bg-muted/5' : 'cursor-default',
isExpanded && 'bg-muted/5',
@@ -173,24 +173,24 @@ function truncateOutput(text: string, maxLines = 8): string {
:tabindex="canExpand ? 0 : -1"
@click="canExpand && (isExpanded = !isExpanded)"
>
- <span class="relative flex size-1.5 shrink-0">
+ <span class="relative flex size-1 shrink-0">
<span
v-if="tool.state === 'loading'"
class="animate-ping absolute inline-flex h-full w-full rounded-full bg-current opacity-75"
/>
<span
- class="relative inline-flex rounded-full size-1.5 bg-current"
+ class="relative inline-flex rounded-full size-1 bg-current"
:class="tool.state === 'loading' ? 'opacity-100' : 'opacity-40'"
/>
</span>
- <span class="text-xs text-dimmed font-mono flex-1 truncate">
+ <span class="text-[11px] text-dimmed font-mono flex-1 truncate leading-tight">
{{ displayedLabel }}<span v-if="tool.state === 'loading'" class="animate-pulse">_</span>
</span>
<span
v-if="tool.result?.durationMs && tool.state === 'done'"
- class="text-[10px] text-muted/40 tabular-nums"
+ class="text-[9px] text-muted/40 tabular-nums"
>
{{ tool.result.durationMs }}ms
</span>
@@ -198,9 +198,9 @@ function truncateOutput(text: string, maxLines = 8): string {
<motion.span
v-if="canExpand"
:animate="{ rotate: isExpanded ? 180 : 0 }"
- :transition="{ duration: 0.35, ease: [0.25, 0.1, 0.25, 1] }"
+ :transition="{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }"
>
- <UIcon name="i-lucide-chevron-down" class="size-3 text-muted/40" />
+ <UIcon name="i-lucide-chevron-down" class="size-2.5 text-muted/40" />
</motion.span>
</button>
@@ -210,38 +210,38 @@ function truncateOutput(text: string, maxLines = 8): string {
:initial="{ height: 0, opacity: 0 }"
:animate="{ height: 'auto', opacity: 1 }"
:exit="{ height: 0, opacity: 0 }"
- :transition="{ duration: 0.4, ease: [0.25, 0.1, 0.25, 1] }"
+ :transition="{ duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }"
class="overflow-hidden"
>
- <div class="ml-3.5 pl-2 border-l border-muted/20 mt-1 mb-2 space-y-2">
+ <div class="ml-2.5 pl-1.5 border-l border-muted/15 mt-0.5 mb-1 space-y-1">
<div
v-for="(cmd, idx) in commandsToShow"
:key="idx"
- class="space-y-1"
+ class="space-y-0.5"
>
- <div class="flex items-start gap-1.5 text-[11px]">
- <span class="text-muted/60 font-mono shrink-0">$</span>
- <code class="text-muted/80 font-mono break-all">{{ cmd.command }}</code>
+ <div class="flex items-start gap-1 text-[10px]">
+ <span class="text-muted/50 font-mono shrink-0">$</span>
+ <code class="text-muted/70 font-mono break-all leading-tight">{{ cmd.command }}</code>
</div>
<div
v-if="cmd.stdout || cmd.stderr"
- class="bg-muted/5 rounded px-2 py-1.5 font-mono text-[10px] text-dimmed/70 overflow-x-auto max-h-40 overflow-y-auto"
+ class="bg-muted/5 rounded px-1.5 py-1 font-mono text-[9px] text-dimmed/60 overflow-x-auto max-h-32 overflow-y-auto"
>
- <pre v-if="cmd.stdout" class="whitespace-pre-wrap">{{ truncateOutput(cmd.stdout) }}</pre>
- <pre v-if="cmd.stderr" class="whitespace-pre-wrap text-muted/60 mt-1">{{ truncateOutput(cmd.stderr, 3) }}</pre>
+ <pre v-if="cmd.stdout" class="whitespace-pre-wrap leading-tight">{{ truncateOutput(cmd.stdout) }}</pre>
+ <pre v-if="cmd.stderr" class="whitespace-pre-wrap text-muted/50 mt-0.5 leading-tight">{{ truncateOutput(cmd.stderr, 3) }}</pre>
</div>
<div
v-else-if="tool.state === 'loading'"
- class="text-[10px] text-muted/40 italic"
+ class="text-[9px] text-muted/40 italic"
>
running...
</div>
<div
v-else-if="tool.state === 'done' && tool.result"
- class="text-[10px] text-muted/30 italic"
+ class="text-[9px] text-muted/25 italic"
>
(no output)
</div>
diff --git a/apps/chat/app/components/UserMenu.vue b/apps/chat/app/components/UserMenu.vue
index 0d6ae60..7e65569 100644
--- a/apps/chat/app/components/UserMenu.vue
+++ b/apps/chat/app/components/UserMenu.vue
@@ -1,6 +1,5 @@
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
-import type { GitHubSource, SourcesResponse, YouTubeSource } from '@savoir/sdk'
defineProps<{
collapsed?: boolean
@@ -10,64 +9,10 @@ const colorMode = useColorMode()
const appConfig = useAppConfig()
const { user, clear } = useUserSession()
const { isAdmin } = useAdmin()
-const toast = useToast()
const colors = ['red', 'orange', 'amber', 'yellow', 'lime', 'green', 'emerald', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose']
const neutrals = ['slate', 'gray', 'zinc', 'neutral', 'stone']
-const { data: sources } = useLazyFetch<SourcesResponse>('/api/sources')
-
-async function triggerSync() {
- try {
- await $fetch('/api/sync', { method: 'POST' })
- toast.add({
- title: 'Sync started',
- description: 'Documentation sync workflow has been triggered.',
- color: 'success',
- })
- } catch (error) {
- toast.add({
- title: 'Sync failed',
- description: error instanceof Error ? error.message : 'Unknown error',
- color: 'error',
- })
- }
-}
-
-async function triggerSyncSource(sourceId: string, label: string) {
- try {
- await $fetch(`/api/sync/${sourceId}`, { method: 'POST' })
- toast.add({
- title: 'Sync started',
- description: `Sync workflow for "${label}" has been triggered.`,
- color: 'success',
- })
- } catch (error) {
- toast.add({
- title: 'Sync failed',
- description: error instanceof Error ? error.message : 'Unknown error',
- color: 'error',
- })
- }
-}
-
-async function triggerSnapshot() {
- try {
- await $fetch('/api/sandbox/snapshot', { method: 'POST' })
- toast.add({
- title: 'Snapshot started',
- description: 'Snapshot creation workflow has been triggered.',
- color: 'success',
- })
- } catch (error) {
- toast.add({
- title: 'Snapshot failed',
- description: error instanceof Error ? error.message : 'Unknown error',
- color: 'error',
- })
- }
-}
-
const items = computed<DropdownMenuItem[][]>(() => {
const baseItems: DropdownMenuItem[][] = [
[
@@ -156,53 +101,6 @@ const items = computed<DropdownMenuItem[][]>(() => {
}
]
}
- ], [
- {
- label: 'Templates',
- icon: 'i-lucide-layout-template',
- children: [
- {
- label: 'Starter',
- to: 'https://starter-template.nuxt.dev/'
- }, {
- label: 'Landing',
- to: 'https://landing-template.nuxt.dev/'
- }, {
- label: 'Docs',
- to: 'https://docs-template.nuxt.dev/'
- }, {
- label: 'SaaS',
- to: 'https://saas-template.nuxt.dev/'
- }, {
- label: 'Dashboard',
- to: 'https://dashboard-template.nuxt.dev/'
- }, {
- label: 'Chat',
- to: 'https://chat-template.nuxt.dev/',
- color: 'primary',
- checked: true,
- type: 'checkbox'
- }, {
- label: 'Portfolio',
- to: 'https://portfolio-template.nuxt.dev/'
- }, {
- label: 'Changelog',
- to: 'https://changelog-template.nuxt.dev/'
- }
- ]
- }
- ], [
- {
- label: 'Documentation',
- icon: 'i-lucide-book-open',
- to: 'https://ui.nuxt.com/docs/getting-started/installation/nuxt',
- target: '_blank'
- }, {
- label: 'GitHub repository',
- icon: 'i-simple-icons-github',
- to: 'https://github.com/nuxt-ui-templates/chat',
- target: '_blank'
- }
]
]
@@ -211,39 +109,7 @@ const items = computed<DropdownMenuItem[][]>(() => {
{
label: 'Admin',
icon: 'i-lucide-settings',
- children: [
- {
- label: 'Sources',
- icon: 'i-lucide-database',
- to: '/admin',
- },
- {
- label: 'Sync all',
- icon: 'i-lucide-refresh-cw',
- onSelect: triggerSync,
- },
- {
- label: 'Sync source',
- icon: 'i-lucide-git-branch',
- children: sources.value ? [
- ...sources.value.github.sources.map((source: GitHubSource) => ({
- label: source.label,
- icon: 'i-simple-icons-github',
- onSelect: () => triggerSyncSource(source.id, source.label),
- })),
- ...sources.value.youtube.sources.map((source: YouTubeSource) => ({
- label: source.label,
- icon: 'i-simple-icons-youtube',
- onSelect: () => triggerSyncSource(source.id, source.label),
- })),
- ] : [{ label: 'Loading...', disabled: true }],
- },
- {
- label: 'Create snapshot',
- icon: 'i-lucide-camera',
- onSelect: triggerSnapshot,
- },
- ],
+ to: '/admin',
},
])
}
diff --git a/apps/chat/app/components/UserStats.vue b/apps/chat/app/components/UserStats.vue
new file mode 100644
index 0000000..f1bc1c1
--- /dev/null
+++ b/apps/chat/app/components/UserStats.vue
@@ -0,0 +1,32 @@
+<script setup lang="ts">
+defineProps<{
+ collapsed?: boolean
+}>()
+
+const { data: stats } = await useLazyFetch<UserStats>('/api/stats/me', {
+ key: 'user-stats',
+})
+
+function formatNumber(num: number): string {
+ if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
+ if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
+ return num.toString()
+}
+</script>
+
+<template>
+ <div v-if="stats && stats.totalMessages > 0">
+ <UTooltip v-if="collapsed" :text="`${formatNumber(stats.totalMessages)} messages · ${formatNumber(stats.totalInputTokens + stats.totalOutputTokens)} tokens`">
+ <div class="flex items-center justify-center p-1.5">
+ <UIcon name="i-lucide-activity" class="size-4 text-muted" />
+ </div>
+ </UTooltip>
+
+ <div v-else class="flex items-center gap-1.5 px-2.5 py-1 text-[11px] text-muted">
+ <UIcon name="i-lucide-activity" class="size-3 shrink-0" />
+ <span class="tabular-nums"><span class="text-highlighted">{{ formatNumber(stats.totalMessages) }}</span> msg</span>
+ <span class="opacity-40">·</span>
+ <span class="tabular-nums"><span class="text-highlighted">{{ formatNumber(stats.totalInputTokens + stats.totalOutputTokens) }}</span> tok</span>
+ </div>
+ </div>
+</template>
diff --git a/apps/chat/app/layouts/admin.vue b/apps/chat/app/layouts/admin.vue
index 1331389..ea3f282 100644
--- a/apps/chat/app/layouts/admin.vue
+++ b/apps/chat/app/layouts/admin.vue
@@ -16,6 +16,11 @@ const navigation = [
icon: 'i-lucide-box',
to: '/admin/sandbox',
},
+ {
+ label: 'Statistics',
+ icon: 'i-lucide-bar-chart-3',
+ to: '/admin/stats',
+ },
]
</script>
diff --git a/apps/chat/app/layouts/default.vue b/apps/chat/app/layouts/default.vue
index 614c7ca..6e7d578 100644
--- a/apps/chat/app/layouts/default.vue
+++ b/apps/chat/app/layouts/default.vue
@@ -106,9 +106,9 @@ defineShortcuts({
class="bg-elevated/50"
>
<template #header="{ collapsed }">
- <NuxtLink to="/" class="flex items-end gap-0.5">
- <Logo class="h-8 w-auto shrink-0" />
- <span v-if="!collapsed" class="text-xl font-bold text-highlighted">Chat</span>
+ <NuxtLink to="/" class="flex items-center gap-0.5" :class="{ 'mx-auto': collapsed }">
+ <UIcon name="custom:savoir" class="size-6" />
+ <span v-if="!collapsed" class="text-xl font-semibold text-highlighted">Savoir</span>
</NuxtLink>
<div v-if="!collapsed" class="flex items-center gap-1.5 ms-auto">
@@ -166,16 +166,19 @@ defineShortcuts({
</template>
<template #footer="{ collapsed }">
- <UserMenu v-if="loggedIn" :collapsed />
- <UButton
- v-else
- :label="collapsed ? '' : 'Login with GitHub'"
- icon="i-simple-icons-github"
- color="neutral"
- variant="ghost"
- class="w-full"
- @click="openInPopup('/auth/github')"
- />
+ <div class="flex flex-col gap-2 w-full">
+ <UserStats v-if="loggedIn" :collapsed />
+ <UserMenu v-if="loggedIn" :collapsed />
+ <UButton
+ v-else
+ :label="collapsed ? '' : 'Login with GitHub'"
+ icon="i-simple-icons-github"
+ color="neutral"
+ variant="ghost"
+ class="w-full"
+ @click="openInPopup('/auth/github')"
+ />
+ </div>
</template>
</UDashboardSidebar>
diff --git a/apps/chat/app/pages/admin/index.vue b/apps/chat/app/pages/admin/index.vue
index 4260593..fe6d80a 100644
--- a/apps/chat/app/pages/admin/index.vue
+++ b/apps/chat/app/pages/admin/index.vue
@@ -285,7 +285,7 @@ const hasSources = computed(() => (sources.value?.github?.count || 0) + (sources
color="neutral"
variant="ghost"
class="w-full h-14 border border-dashed border-default hover:border-muted"
- to="/admin/new"
+ to="/admin/new?type=github"
icon="i-lucide-plus"
>
Add a GitHub repository
@@ -336,7 +336,7 @@ const hasSources = computed(() => (sources.value?.github?.count || 0) + (sources
color="neutral"
variant="ghost"
class="w-full h-14 border border-dashed border-default hover:border-muted"
- to="/admin/new"
+ to="/admin/new?type=youtube"
icon="i-lucide-plus"
>
Add a YouTube channel
diff --git a/apps/chat/app/pages/admin/new.vue b/apps/chat/app/pages/admin/new.vue
index 714a0cc..e6b1fd0 100644
--- a/apps/chat/app/pages/admin/new.vue
+++ b/apps/chat/app/pages/admin/new.vue
@@ -30,15 +30,45 @@ const CONFIG_EXTENSIONS = ['.ts', '.js', '.json', '.yml', '.yaml', '.toml']
const CONFIG_ACCEPT = CONFIG_EXTENSIONS.join(',')
const router = useRouter()
+const route = useRoute()
const toast = useToast()
+// Get type from query param (defaults to 'github')
+const initialType = (route.query.type === 'youtube' ? 'youtube' : 'github') as 'github' | 'youtube'
+
const isSubmitting = ref(false)
const isExtracting = ref(false)
const isDragging = ref(false)
+const showQuickImport = ref(false)
const pendingFiles = ref<PendingFile[]>([])
-const sources = ref<ExtractedSource[]>([])
+const sources = ref<ExtractedSource[]>([
+ {
+ id: crypto.randomUUID(),
+ data: {
+ type: initialType,
+ label: '',
+ repo: '',
+ branch: 'main',
+ contentPath: '',
+ outputPath: '',
+ basePath: initialType === 'youtube' ? '/youtube' : '/docs',
+ readmeOnly: false,
+ channelId: '',
+ handle: '',
+ maxVideos: 50,
+ },
+ confidence: 1,
+ }
+])
const fileInputRef = ref<HTMLInputElement | null>(null)
+// Auto-expand Quick Import when files are dragged
+watch(pendingFiles, (files) => {
+ if (files.length > 0 && !showQuickImport.value) {
+ showQuickImport.value = true
+ }
+})
+
function createSourceData(item?: SourceOcrItem) {
return {
type: (item?.type || 'github') as 'github' | 'youtube',
@@ -204,7 +234,10 @@ function handleFileSelect(event: Event) {
}
function removeSource(id: string) {
- sources.value = sources.value.filter(s => s.id !== id)
+ // Keep at least one source
+ if (sources.value.length > 1) {
+ sources.value = sources.value.filter(s => s.id !== id)
+ }
}
function addManualSource() {
@@ -298,11 +331,12 @@ const validSourcesCount = computed(() => sources.value.filter(s => s.data.label)
Add Sources
</h1>
<p class="text-sm text-muted">
- Sources provide context to the AI. Add GitHub docs or YouTube channels to make the assistant knowledgeable about specific tools and frameworks.
+ Sources provide context to the AI. Connect your GitHub docs or YouTube channels.
</p>
</header>
- <section class="mb-8">
+ <!-- Expandable Quick Import Section -->
+ <section v-if="showQuickImport" class="mb-8">
<p class="text-xs text-muted mb-3">
Quick import
</p>
@@ -394,17 +428,17 @@ const validSourcesCount = computed(() => sources.value.filter(s => s.data.label)
</div>
</section>
- <section v-if="sources.length > 0" class="mb-8">
+ <section class="mb-2">
<div class="flex items-center justify-between mb-3">
<p class="text-xs text-muted">
- Sources
+ Your sources
</p>
<button
class="text-xs text-muted hover:text-highlighted transition-colors flex items-center gap-1"
@click="addManualSource"
>
<UIcon name="i-lucide-plus" class="size-3" aria-hidden="true" />
- Add manually
+ Add source
</button>
</div>
@@ -497,31 +531,18 @@ const validSourcesCount = computed(() => sources.value.filter(s => s.data.label)
</div>
</section>
- <div
- v-if="sources.length === 0 && pendingFiles.length === 0"
- class="text-center py-10"
- >
- <p class="text-sm text-muted mb-1">
- No files uploaded yet
- </p>
- <p class="text-xs text-muted mb-4">
- Or skip the import and configure sources manually
- </p>
- <UButton
- icon="i-lucide-plus"
- color="neutral"
- variant="ghost"
- size="xs"
- @click="addManualSource"
+ <!-- Power users notice above separator -->
+ <div class="mb-2 text-center">
+ <button
+ class="text-xs text-muted hover:text-primary transition-colors inline-flex items-center gap-1.5"
+ @click="showQuickImport = !showQuickImport"
>
- Add manually
- </UButton>
+ <UIcon name="i-lucide-sparkles" class="size-3" />
+ <span>{{ showQuickImport ? 'Hide quick import' : 'Power users: upload config files or screenshots' }}</span>
+ </button>
</div>
- <div
- v-if="sources.length > 0"
- class="flex items-center justify-end gap-2 pt-4 border-t border-default"
- >
+ <div class="flex items-center justify-end gap-2 pt-4 border-t border-default">
<UButton
color="neutral"
variant="ghost"
diff --git a/apps/chat/app/pages/admin/stats.vue b/apps/chat/app/pages/admin/stats.vue
new file mode 100644
index 0000000..6791c7e
--- /dev/null
+++ b/apps/chat/app/pages/admin/stats.vue
@@ -0,0 +1,403 @@
+<script setup lang="ts">
+const toast = useToast()
+
+const periodOptions = [
+ { label: '7 days', value: 7 },
+ { label: '30 days', value: 30 },
+ { label: '90 days', value: 90 },
+]
+
+const selectedPeriod = ref(30)
+
+const { data: stats, refresh, status } = await useFetch<GlobalStatsResponse>('/api/stats', {
+ query: computed(() => ({ days: selectedPeriod.value })),
+ watch: [selectedPeriod],
+})
+
+// Track if we're refreshing (vs initial load) to avoid flickering
+const isRefreshing = computed(() => status.value === 'pending' && stats.value !== null)
+
+const isComputing = ref(false)
+
+function formatNumber(num: number): string {
+ return num.toLocaleString()
+}
+
+function formatDuration(ms: number): string {
+ if (ms < 1000) return `${ms}ms`
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`
+ return `${(ms / 60000).toFixed(1)}m`
+}
+
+function formatModelName(modelId: string): string {
+ const name = modelId.split('/')[1] || modelId
+ return name.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')
+}
+
+// Feedback score color
+function getScoreColor(score: number | null): string {
+ if (score === null) return 'text-muted'
+ if (score >= 80) return 'text-success'
+ if (score >= 50) return 'text-warning'
+ return 'text-error'
+}
+
+// Model satisfaction rate
+function getModelSatisfaction(model: { positive: number, negative: number }): number | null {
+ const total = model.positive + model.negative
+ if (total === 0) return null
+ return Math.round((model.positive / total) * 100)
+}
+
+const chartData = computed(() => {
+ if (!stats.value?.daily) return []
+
+ const byDate = new Map<string, { input: number, output: number }>()
+
+ for (const day of stats.value.daily) {
+ const existing = byDate.get(day.date) ?? { input: 0, output: 0 }
+ existing.input += day.inputTokens
+ existing.output += day.outputTokens
+ byDate.set(day.date, existing)
+ }
+
+ return Array.from(byDate.entries())
+ .map(([date, tokens]) => ({
+ date: date.slice(5), // MM-DD format
+ fullDate: date, // Keep full date for tooltip
+ input: tokens.input,
+ output: tokens.output,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date))
+})
+
+// Get evenly spaced date labels for the x-axis (5 labels max)
+const chartDateLabels = computed(() => {
+ if (chartData.value.length === 0) return []
+ if (chartData.value.length <= 5) {
+ return chartData.value.map((d, i) => ({ index: i, label: d.date }))
+ }
+
+ const count = chartData.value.length
+ const step = (count - 1) / 4 // 5 labels: start, 3 middle, end
+
+ return [0, 1, 2, 3, 4].map(i => {
+ const index = Math.round(i * step)
+ return { index, label: chartData.value[index]?.date ?? '' }
+ })
+})
+
+async function triggerCompute() {
+ try {
+ isComputing.value = true
+ await $fetch('/api/stats/compute', { method: 'POST' })
+ toast.add({
+ title: 'Stats computation started',
+ description: 'The workflow has been triggered.',
+ icon: 'i-lucide-check',
+ })
+ setTimeout(() => refresh(), 2000)
+ } catch (error) {
+ toast.add({
+ title: 'Error',
+ description: error instanceof Error ? error.message : 'Failed to compute stats',
+ color: 'error',
+ icon: 'i-lucide-alert-circle',
+ })
+ } finally {
+ isComputing.value = false
+ }
+}
+</script>
+
+<template>
+ <div class="px-6 lg:px-10 py-8 max-w-4xl">
+ <header class="mb-6">
+ <div class="flex items-center justify-between gap-4">
+ <div>
+ <h1 class="text-lg font-medium text-highlighted mb-1">
+ Usage Statistics
+ </h1>
+ <p class="text-sm text-muted max-w-lg">
+ Monitor AI usage, response quality, and model performance.
+ <span v-if="stats?.period" class="block text-xs mt-0.5">
+ {{ stats.period.from }} → {{ stats.period.to }}
+ </span>
+ </p>
+ </div>
+ <div class="flex items-center gap-6">
+ <div class="flex items-center gap-1">
+ <UButton
+ v-for="option in periodOptions"
+ :key="option.value"
+ size="xs"
+ :color="selectedPeriod === option.value ? 'primary' : 'neutral'"
+ :variant="selectedPeriod === option.value ? 'solid' : 'ghost'"
+ :disabled="isRefreshing"
+ @click="selectedPeriod = option.value"
+ >
+ {{ option.label }}
+ </UButton>
+ </div>
+ <UDropdownMenu
+ :items="[
+ {
+ label: 'Refresh data',
+ icon: 'i-lucide-refresh-cw',
+ onClick: () => refresh(),
+ },
+ {
+ label: 'Recompute stats',
+ icon: 'i-lucide-calculator',
+ description: 'Run workflow (may take a few seconds)',
+ onClick: triggerCompute,
+ },
+ ]"
+ >
+ <UButton
+ icon="i-lucide-more-vertical"
+ color="neutral"
+ variant="ghost"
+ size="xs"
+ :loading="status === 'pending' || isComputing"
+ />
+ </UDropdownMenu>
+ </div>
+ </div>
+ </header>
+
+ <div v-if="status === 'pending' && !stats" class="flex items-center justify-center py-16">
+ <UIcon name="i-lucide-loader-2" class="size-6 animate-spin text-muted" />
+ </div>
+
+ <template v-else-if="stats">
+ <div
+ class="transition-opacity duration-200"
+ :class="isRefreshing ? 'opacity-50 pointer-events-none' : 'opacity-100'"
+ >
+ <div class="grid grid-cols-2 md:grid-cols-5 gap-3 mb-8">
+ <div class="rounded-lg border border-default bg-elevated/50 p-3">
+ <p class="text-[11px] text-muted mb-0.5">
+ Messages
+ </p>
+ <p class="text-xl font-semibold text-highlighted tabular-nums">
+ {{ formatNumber(stats.totals.messages) }}
+ </p>
+ </div>
+ <div class="rounded-lg border border-default bg-elevated/50 p-3">
+ <p class="text-[11px] text-muted mb-0.5">
+ Total Tokens
+ </p>
+ <p class="text-xl font-semibold text-highlighted tabular-nums">
+ {{ formatNumber(stats.totals.totalTokens) }}
+ </p>
+ <p class="text-[10px] text-muted">
+ {{ formatNumber(stats.totals.inputTokens) }} in / {{ formatNumber(stats.totals.outputTokens) }} out
+ </p>
+ </div>
+ <div class="rounded-lg border border-default bg-elevated/50 p-3">
+ <p class="text-[11px] text-muted mb-0.5">
+ Avg Response
+ </p>
+ <p class="text-xl font-semibold text-highlighted tabular-nums">
+ {{ formatDuration(stats.totals.avgDurationMs) }}
+ </p>
+ </div>
+ <div class="rounded-lg border border-default bg-elevated/50 p-3">
+ <p class="text-[11px] text-muted mb-0.5">
+ Models
+ </p>
+ <p class="text-xl font-semibold text-highlighted tabular-nums">
+ {{ stats.byModel.length }}
+ </p>
+ </div>
+ <div class="rounded-lg border border-default bg-elevated/50 p-3">
+ <p class="text-[11px] text-muted mb-0.5">
+ Satisfaction
+ </p>
+ <p class="text-xl font-semibold tabular-nums" :class="getScoreColor(stats.feedback.score)">
+ <template v-if="stats.feedback.score !== null">
+ {{ stats.feedback.score }}%
+ </template>
+ <template v-else>
+ <span class="text-muted">—</span>
+ </template>
+ </p>
+ <p v-if="stats.feedback.total > 0" class="text-[10px] text-muted">
+ {{ stats.feedback.positive }} <UIcon name="i-lucide-thumbs-up" class="size-2.5 inline" /> · {{ stats.feedback.negative }} <UIcon name="i-lucide-thumbs-down" class="size-2.5 inline" />
+ </p>
+ </div>
+ </div>
+
+ <section class="mb-8">
+ <h2 class="text-sm font-medium text-highlighted mb-3">
+ Token Usage
+ </h2>
+ <div v-if="chartData.length > 0" class="rounded-lg border border-default bg-elevated/50 p-4">
+ <div class="h-40 flex items-end gap-0.5">
+ <div
+ v-for="(day, index) in chartData"
+ :key="index"
+ class="flex-1 flex flex-col justify-end group"
+ >
+ <UTooltip
+ :text="`${day.fullDate} — In: ${formatNumber(day.input)} / Out: ${formatNumber(day.output)}`"
+ :content="{ side: 'top', sideOffset: 6 }"
+ >
+ <div class="w-full flex flex-col gap-px relative before:absolute before:inset-x-0 before:bottom-full before:h-40">
+ <div
+ class="w-full bg-primary rounded-t-sm transition-opacity group-hover:opacity-80"
+ :style="{ height: `${Math.max(2, (day.output / Math.max(...chartData.map(d => d.input + d.output))) * 100)}px` }"
+ />
+ <div
+ class="w-full bg-primary/40 rounded-b-sm transition-opacity group-hover:opacity-80"
+ :style="{ height: `${Math.max(2, (day.input / Math.max(...chartData.map(d => d.input + d.output))) * 100)}px` }"
+ />
+ </div>
+ </UTooltip>
+ </div>
+ </div>
+ <div class="relative h-4 mt-2">
+ <span
+ v-for="label in chartDateLabels"
+ :key="label.index"
+ class="absolute text-[10px] text-muted transform -translate-x-1/2"
+ :style="{ left: `${(label.index / (chartData.length - 1)) * 100}%` }"
+ >
+ {{ label.label }}
+ </span>
+ </div>
+ <div class="flex items-center justify-center gap-4 mt-2 pt-2 border-t border-default text-[10px] text-muted">
+ <span class="flex items-center gap-1">
+ <span class="inline-block size-2 rounded bg-primary/40" />
+ Input
+ </span>
+ <span class="flex items-center gap-1">
+ <span class="inline-block size-2 rounded bg-primary" />
+ Output
+ </span>
+ </div>
+ </div>
+ <div v-else class="rounded-lg border border-dashed border-default p-6 text-center">
+ <p class="text-sm text-muted">
+ No usage data yet
+ </p>
+ </div>
+ </section>
+
+ <section v-if="stats.bySource && stats.bySource.length > 1" class="mb-8">
+ <h2 class="text-sm font-medium text-highlighted mb-3">
+ By Source
+ </h2>
+ <div class="rounded-lg border border-default overflow-hidden">
+ <table class="w-full text-sm">
+ <thead class="bg-elevated/50">
+ <tr class="border-b border-default text-xs text-muted">
+ <th class="text-left font-medium px-4 py-2.5">
+ Source
+ </th>
+ <th class="text-right font-medium px-3 py-2.5">
+ Requests
+ </th>
+ <th class="text-right font-medium px-3 py-2.5">
+ Tokens
+ </th>
+ <th class="text-right font-medium px-4 py-2.5">
+ Avg Time
+ </th>
+ </tr>
+ </thead>
+ <tbody class="divide-y divide-default">
+ <tr v-for="source in stats.bySource" :key="source.source" class="hover:bg-elevated/30">
+ <td class="px-4 py-2.5">
+ <div class="flex items-center gap-2">
+ <UIcon
+ :name="source.source === 'web' ? 'i-lucide-globe' : source.source === 'github-bot' ? 'i-simple-icons-github' : 'i-lucide-code'"
+ class="size-4 text-muted"
+ />
+ <span class="text-highlighted capitalize">{{ source.source.replace('-', ' ') }}</span>
+ </div>
+ </td>
+ <td class="text-right text-muted tabular-nums px-3 py-2.5">
+ {{ formatNumber(source.requests) }}
+ </td>
+ <td class="text-right text-muted tabular-nums px-3 py-2.5">
+ {{ formatNumber(source.totalTokens) }}
+ </td>
+ <td class="text-right text-muted tabular-nums px-4 py-2.5">
+ {{ formatDuration(source.avgDurationMs) }}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+
+ <section>
+ <h2 class="text-sm font-medium text-highlighted mb-3">
+ By Model
+ </h2>
+ <div v-if="stats.byModel.length > 0" class="rounded-lg border border-default overflow-hidden">
+ <table class="w-full text-sm">
+ <thead class="bg-elevated/50">
+ <tr class="border-b border-default text-xs text-muted">
+ <th class="text-left font-medium px-4 py-2.5">
+ Model
+ </th>
+ <th class="text-right font-medium px-3 py-2.5">
+ Msgs
+ </th>
+ <th class="text-right font-medium px-3 py-2.5">
+ Tokens
+ </th>
+ <th class="text-right font-medium px-4 py-2.5">
+ <UIcon name="i-lucide-thumbs-up" class="size-3.5" />
+ </th>
+ </tr>
+ </thead>
+ <tbody class="divide-y divide-default">
+ <tr v-for="model in stats.byModel" :key="model.model" class="hover:bg-elevated/30">
+ <td class="px-4 py-2.5">
+ <span class="text-highlighted">{{ formatModelName(model.model) }}</span>
+ <span class="text-xs text-muted block truncate max-w-48">{{ model.model }}</span>
+ </td>
+ <td class="text-right text-muted tabular-nums px-3 py-2.5">
+ {{ formatNumber(model.messageCount) }}
+ </td>
+ <td class="text-right text-muted tabular-nums px-3 py-2.5">
+ {{ formatNumber(model.inputTokens + model.outputTokens) }}
+ </td>
+ <td class="text-right tabular-nums px-4 py-2.5" :class="getScoreColor(getModelSatisfaction(model))">
+ <template v-if="getModelSatisfaction(model) !== null">
+ {{ getModelSatisfaction(model) }}%
+ </template>
+ <template v-else>
+ <span class="text-muted">—</span>
+ </template>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <div v-else class="rounded-lg border border-dashed border-default p-6 text-center">
+ <p class="text-sm text-muted">
+ No model data yet
+ </p>
+ </div>
+ </section>
+ </div>
+ </template>
+
+ <div v-else class="flex flex-col items-center py-16 border border-dashed border-default rounded-lg">
+ <div class="size-10 rounded-lg bg-elevated flex items-center justify-center mb-4">
+ <UIcon name="i-lucide-bar-chart-3" class="size-5 text-muted" aria-hidden="true" />
+ </div>
+ <p class="text-sm font-medium text-highlighted mb-1">
+ No statistics available
+ </p>
+ <p class="text-xs text-muted text-center max-w-xs">
+ Start chatting to generate usage statistics
+ </p>
+ </div>
+ </div>
+</template>
diff --git a/apps/chat/app/pages/chat/[id].vue b/apps/chat/app/pages/chat/[id].vue
index dd4ab11..2425a73 100644
--- a/apps/chat/app/pages/chat/[id].vue
+++ b/apps/chat/app/pages/chat/[id].vue
@@ -96,6 +96,63 @@ function copy(_e: MouseEvent, message: UIMessage) {
}, 2000)
}
+type FeedbackType = 'positive' | 'negative' | null
+const feedbackMap = ref<Record<string, FeedbackType>>({})
+
+if (data.value?.messages) {
+ for (const msg of data.value.messages) {
+ const msgWithFeedback = msg as typeof msg & { feedback?: FeedbackType }
+ if (msg.role === 'assistant' && msgWithFeedback.feedback) {
+ feedbackMap.value[msg.id] = msgWithFeedback.feedback
+ }
+ }
+}
+
+async function toggleFeedback(_e: MouseEvent, message: UIMessage, type: 'positive' | 'negative') {
+ const currentFeedback = feedbackMap.value[message.id] ?? null
+ const newFeedback = currentFeedback === type ? null : type
+
+ feedbackMap.value[message.id] = newFeedback
+
+ try {
+ await $fetch(`/api/messages/${message.id}/feedback`, {
+ method: 'PATCH',
+ body: { feedback: newFeedback }
+ })
+ } catch {
+ feedbackMap.value[message.id] = currentFeedback
+ toast.add({
+ description: 'Failed to save feedback',
+ icon: 'i-lucide-alert-circle',
+ color: 'error'
+ })
+ }
+}
+
+function getAssistantActions(message: UIMessage) {
+ const feedback = feedbackMap.value[message.id]
+ return [
+ {
+ label: 'Like',
+ icon: 'i-lucide-thumbs-up',
+ color: feedback === 'positive' ? 'primary' : 'neutral',
+ onClick: (e: MouseEvent) => toggleFeedback(e, message, 'positive')
+ },
+ {
+ label: 'Dislike',
+ icon: 'i-lucide-thumbs-down',
+ color: feedback === 'negative' ? 'error' : 'neutral',
+ onClick: (e: MouseEvent) => toggleFeedback(e, message, 'negative')
+ },
+ {
+ label: 'Copy',
+ icon: copied.value ? 'i-lucide-copy-check' : 'i-lucide-copy',
+ color: 'neutral',
+ onClick: copy
+ }
+ ]
+}
+
interface CommandResult {
command: string
stdout: string
@@ -133,6 +190,12 @@ onMounted(() => {
chat.regenerate()
}
})
+
+watch(() => chat.status, (newStatus, oldStatus) => {
+ if (oldStatus === 'streaming' && newStatus === 'ready') {
+ refreshNuxtData('user-stats')
+ }
+})
</script>
<template>
@@ -148,7 +211,6 @@ onMounted(() => {
should-auto-scroll
:messages="chat.messages"
:status="chat.status"
- :assistant="chat.status !== 'streaming' ? { actions: [{ label: 'Copy', icon: copied ? 'i-lucide-copy-check' : 'i-lucide-copy', onClick: copy }] } : { actions: [] }"
:spacing-offset="160"
class="lg:pt-(--ui-header-height) pb-4 sm:pb-6"
>
@@ -156,6 +218,21 @@ onMounted(() => {
<ChatLoading :is-loading="true" />
</template>
+ <template #actions="{ message }">
+ <template v-if="message.role === 'assistant' && chat.status !== 'streaming'">
+ <UButton
+ v-for="action in getAssistantActions(message)"
+ :key="action.label"
+ variant="ghost"
+ :color="action.color as any"
+ size="xs"
+ :icon="action.icon"
+ :aria-label="action.label"
+ @click="(e: MouseEvent) => action.onClick(e, message)"
+ />
+ </template>
+ </template>
+
<template #content="{ message }">
<ChatLoading
v-if="message.role === 'assistant' && chat.status === 'streaming' && !message.parts.some(p => p.type === 'text' && p.text)"
diff --git a/apps/chat/app/pages/shared/[token].vue b/apps/chat/app/pages/shared/[token].vue
index fdf3ede..79d075f 100644
--- a/apps/chat/app/pages/shared/[token].vue
+++ b/apps/chat/app/pages/shared/[token].vue
@@ -39,7 +39,7 @@ if (error.value) {
}
useHead({
- title: data.value?.title || 'Shared Chat'
+ title: data.value?.title || 'Shared Chat | Savoir'
})
definePageMeta({
@@ -56,7 +56,7 @@ definePageMeta({
<div class="flex items-center gap-3">
<NuxtLink to="/" class="flex items-end gap-0.5">
<Logo class="h-8 w-auto shrink-0" />
- <span class="text-xl font-bold text-highlighted">Chat</span>
+ <span class="text-xl font-bold text-highlighted">Savoir</span>
</NuxtLink>
</div>
</template>
diff --git a/apps/chat/nuxt.config.ts b/apps/chat/nuxt.config.ts
index ffede01..48f26e8 100644
--- a/apps/chat/nuxt.config.ts
+++ b/apps/chat/nuxt.config.ts
@@ -41,6 +41,20 @@ export default defineNuxtConfig({
viewTransition: true
},
+ icon: {
+ customCollections: [
+ {
+ prefix: 'custom',
+ dir: './app/assets/icons/custom',
+ },
+ ],
+ clientBundle: {
+ scan: true,
+ includeCustomCollections: true,
+ },
+ provider: 'iconify',
+ },
+
compatibilityDate: 'latest',
nitro: {
diff --git a/apps/chat/server/api/chats.post.ts b/apps/chat/server/api/chats.post.ts
index 9f72106..29ce029 100644
--- a/apps/chat/server/api/chats.post.ts
+++ b/apps/chat/server/api/chats.post.ts
@@ -20,6 +20,7 @@ export default defineEventHandler(async (event) => {
}
await db.insert(schema.messages).values({
+ id: message.id,
chatId: chat.id,
role: 'user',
parts: message.parts
diff --git a/apps/chat/server/api/chats/[id].post.ts b/apps/chat/server/api/chats/[id].post.ts
index 136b759..dd964e5 100644
--- a/apps/chat/server/api/chats/[id].post.ts
+++ b/apps/chat/server/api/chats/[id].post.ts
@@ -134,6 +134,7 @@ export default defineEventHandler(async (event) => {
const lastMessage = messages[messages.length - 1]
if (lastMessage?.role === 'user' && messages.length > 1) {
await db.insert(schema.messages).values({
+ id: lastMessage.id,
chatId: id as string,
role: 'user',
parts: lastMessage.parts,
@@ -191,6 +192,9 @@ export default defineEventHandler(async (event) => {
log.info('chat', `[${requestId}] Starting agent with ${effectiveModel} (routed: ${routerConfig.complexity}, ${effectiveMaxSteps} steps, multiplier: ${agentConfigData.maxStepsMultiplier}x)`)
+ // Track overall request timing for stats
+ const requestStartTime = Date.now()
+
const stream = createUIMessageStream({
execute: async ({ writer }) => {
streamWriter = writer
@@ -256,10 +260,20 @@ export default defineEventHandler(async (event) => {
},
onFinish: async ({ messages: responseMessages }) => {
const dbStartTime = Date.now()
+ const totalDurationMs = Date.now() - requestStartTime
+
await db.insert(schema.messages).values(responseMessages.map((message: UIMessage) => ({
+ id: message.id, // Preserve the ID from the streaming response
chatId: chat.id,
role: message.role as 'user' | 'assistant',
parts: message.parts,
+ // Stats fields for assistant messages
+ ...(message.role === 'assistant' && {
+ model: effectiveModel,
+ inputTokens: totalInputTokens,
+ outputTokens: totalOutputTokens,
+ durationMs: totalDurationMs,
+ }),
})))
const dbDurationMs = Date.now() - dbStartTime
@@ -267,6 +281,7 @@ export default defineEventHandler(async (event) => {
outcome: 'success',
responseMessageCount: responseMessages.length,
dbInsertMs: dbDurationMs,
+ totalDurationMs,
})
},
})
diff --git a/apps/chat/server/api/messages/[id]/feedback.patch.ts b/apps/chat/server/api/messages/[id]/feedback.patch.ts
new file mode 100644
index 0000000..b34fb4f
--- /dev/null
+++ b/apps/chat/server/api/messages/[id]/feedback.patch.ts
@@ -0,0 +1,50 @@
+import { db, schema } from '@nuxthub/db'
+import { and, eq } from 'drizzle-orm'
+import { z } from 'zod'
+
+export default defineEventHandler(async (event) => {
+ const session = await getUserSession(event)
+ const { id } = getRouterParams(event)
+
+ const { feedback } = await readValidatedBody(event, z.object({
+ feedback: z.enum(['positive', 'negative']).nullable()
+ }).parse)
+
+ // Find the message and verify it belongs to the user's chat
+ const message = await db.query.messages.findFirst({
+ where: () => eq(schema.messages.id, id as string),
+ with: {
+ chat: true
+ }
+ })
+
+ if (!message) {
+ throw createError({
+ statusCode: 404,
+ statusMessage: 'Message not found'
+ })
+ }
+
+ // Verify the message belongs to a chat owned by the user
+ if (message.chat.userId !== session.user?.id && message.chat.userId !== session.id) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Forbidden'
+ })
+ }
+
+ // Only allow feedback on assistant messages
+ if (message.role !== 'assistant') {
+ throw createError({
+ statusCode: 400,
+ statusMessage: 'Feedback can only be added to assistant messages'
+ })
+ }
+
+ const [updated] = await db.update(schema.messages)
+ .set({ feedback })
+ .where(eq(schema.messages.id, id as string))
+ .returning()
+
+ return updated
+})
diff --git a/apps/chat/server/api/stats/compute.post.ts b/apps/chat/server/api/stats/compute.post.ts
new file mode 100644
index 0000000..5b29b65
--- /dev/null
+++ b/apps/chat/server/api/stats/compute.post.ts
@@ -0,0 +1,31 @@
+import { z } from 'zod'
+import { computeStats } from '../../workflows/compute-stats'
+
+/**
+ * POST /api/stats/compute
+ * Trigger stats computation workflow (admin only)
+ */
+export default defineEventHandler(async (event) => {
+ await requireAdmin(event)
+
+ // Body is optional - parse empty body as empty object
+ const rawBody = await readBody(event) ?? {}
+ const body = z.object({
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
+ }).parse(rawBody)
+
+ // Use provided date or yesterday (since today's data may be incomplete)
+ const targetDate = body.date ?? (() => {
+ const yesterday = new Date()
+ yesterday.setDate(yesterday.getDate() - 1)
+ return yesterday.toISOString().split('T')[0]!
+ })()
+
+ await computeStats({ date: targetDate })
+
+ return {
+ status: 'started',
+ message: `Stats computation started for ${targetDate}`,
+ date: targetDate,
+ }
+})
diff --git a/apps/chat/server/api/stats/index.get.ts b/apps/chat/server/api/stats/index.get.ts
new file mode 100644
index 0000000..cc0439e
--- /dev/null
+++ b/apps/chat/server/api/stats/index.get.ts
@@ -0,0 +1,211 @@
+import { db, schema } from '@nuxthub/db'
+import { desc, and, gte, eq } from 'drizzle-orm'
+
+/**
+ * GET /api/stats
+ * Get global usage statistics (admin only)
+ *
+ * Query params:
+ * - days: number of days to look back (default: 30)
+ */
+export default defineEventHandler(async (event) => {
+ await requireAdmin(event)
+
+ const query = getQuery(event)
+ const days = Math.min(Math.max(Number(query.days) || 30, 1), 365)
+
+ const startDate = new Date()
+ startDate.setDate(startDate.getDate() - days)
+
+ const messagesWithStats = await db
+ .select({
+ model: schema.messages.model,
+ inputTokens: schema.messages.inputTokens,
+ outputTokens: schema.messages.outputTokens,
+ durationMs: schema.messages.durationMs,
+ feedback: schema.messages.feedback,
+ createdAt: schema.messages.createdAt,
+ })
+ .from(schema.messages)
+ .where(
+ and(
+ eq(schema.messages.role, 'assistant'),
+ gte(schema.messages.createdAt, startDate)
+ )
+ )
+ .orderBy(desc(schema.messages.createdAt))
+
+ const apiUsageData = await db
+ .select({
+ source: schema.apiUsage.source,
+ model: schema.apiUsage.model,
+ inputTokens: schema.apiUsage.inputTokens,
+ outputTokens: schema.apiUsage.outputTokens,
+ durationMs: schema.apiUsage.durationMs,
+ createdAt: schema.apiUsage.createdAt,
+ })
+ .from(schema.apiUsage)
+ .where(gte(schema.apiUsage.createdAt, startDate))
+ .orderBy(desc(schema.apiUsage.createdAt))
+
+ let totalMessages = 0
+ let totalInputTokens = 0
+ let totalOutputTokens = 0
+ let totalDurationMs = 0
+ let messagesWithDuration = 0
+ let positiveFeedback = 0
+ let negativeFeedback = 0
+
+ const byModelMap = new Map<string, {
+ messageCount: number
+ inputTokens: number
+ outputTokens: number
+ positive: number
+ negative: number
+ }>()
+
+ const dailyMap = new Map<string, Map<string, {
+ messageCount: number
+ inputTokens: number
+ outputTokens: number
+ totalDurationMs: number
+ }>>()
+
+ const bySourceMap = new Map<string, {
+ requests: number
+ inputTokens: number
+ outputTokens: number
+ totalDurationMs: number
+ }>()
+
+ bySourceMap.set('web', { requests: 0, inputTokens: 0, outputTokens: 0, totalDurationMs: 0 })
+
+ for (const msg of messagesWithStats) {
+ totalMessages++
+ totalInputTokens += msg.inputTokens ?? 0
+ totalOutputTokens += msg.outputTokens ?? 0
+
+ if (msg.durationMs && msg.durationMs > 0) {
+ totalDurationMs += msg.durationMs
+ messagesWithDuration++
+ }
+
+ if (msg.feedback === 'positive') positiveFeedback++
+ if (msg.feedback === 'negative') negativeFeedback++
+
+ const modelKey = msg.model ?? 'unknown'
+ const modelStats = byModelMap.get(modelKey) ?? { messageCount: 0, inputTokens: 0, outputTokens: 0, positive: 0, negative: 0 }
+ modelStats.messageCount++
+ modelStats.inputTokens += msg.inputTokens ?? 0
+ modelStats.outputTokens += msg.outputTokens ?? 0
+ if (msg.feedback === 'positive') modelStats.positive++
+ if (msg.feedback === 'negative') modelStats.negative++
+ byModelMap.set(modelKey, modelStats)
+
+ const dateStr = msg.createdAt.toISOString().split('T')[0]!
+ if (!dailyMap.has(dateStr)) {
+ dailyMap.set(dateStr, new Map())
+ }
+ const dayModelMap = dailyMap.get(dateStr)!
+ const dayModelStats = dayModelMap.get(modelKey) ?? {
+ messageCount: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ totalDurationMs: 0,
+ }
+ dayModelStats.messageCount++
+ dayModelStats.inputTokens += msg.inputTokens ?? 0
+ dayModelStats.outputTokens += msg.outputTokens ?? 0
+ dayModelStats.totalDurationMs += msg.durationMs ?? 0
+ dayModelMap.set(modelKey, dayModelStats)
+
+ const webStats = bySourceMap.get('web')!
+ webStats.requests++
+ webStats.inputTokens += msg.inputTokens ?? 0
+ webStats.outputTokens += msg.outputTokens ?? 0
+ webStats.totalDurationMs += msg.durationMs ?? 0
+ }
+
+ for (const usage of apiUsageData) {
+ const { source } = usage
+ const sourceStats = bySourceMap.get(source) ?? { requests: 0, inputTokens: 0, outputTokens: 0, totalDurationMs: 0 }
+ sourceStats.requests++
+ sourceStats.inputTokens += usage.inputTokens ?? 0
+ sourceStats.outputTokens += usage.outputTokens ?? 0
+ sourceStats.totalDurationMs += usage.durationMs ?? 0
+ bySourceMap.set(source, sourceStats)
+
+ totalMessages++
+ totalInputTokens += usage.inputTokens ?? 0
+ totalOutputTokens += usage.outputTokens ?? 0
+ if (usage.durationMs && usage.durationMs > 0) {
+ totalDurationMs += usage.durationMs
+ messagesWithDuration++
+ }
+
+ const modelKey = usage.model ?? 'unknown'
+ const modelStats = byModelMap.get(modelKey) ?? { messageCount: 0, inputTokens: 0, outputTokens: 0, positive: 0, negative: 0 }
+ modelStats.messageCount++
+ modelStats.inputTokens += usage.inputTokens ?? 0
+ modelStats.outputTokens += usage.outputTokens ?? 0
+ byModelMap.set(modelKey, modelStats)
+ }
+
+ const byModel = Array.from(byModelMap.entries())
+ .filter(([model]) => model !== 'unknown')
+ .map(([model, stats]) => ({
+ model,
+ ...stats,
+ }))
+
+ const bySource = Array.from(bySourceMap.entries())
+ .filter(([, stats]) => stats.requests > 0)
+ .map(([source, stats]) => ({
+ source,
+ requests: stats.requests,
+ inputTokens: stats.inputTokens,
+ outputTokens: stats.outputTokens,
+ totalTokens: stats.inputTokens + stats.outputTokens,
+ avgDurationMs: stats.requests > 0 ? Math.round(stats.totalDurationMs / stats.requests) : 0,
+ }))
+
+ const daily = Array.from(dailyMap.entries())
+ .flatMap(([date, modelMap]) =>
+ Array.from(modelMap.entries()).map(([model, stats]) => ({
+ date,
+ model,
+ messageCount: stats.messageCount,
+ inputTokens: stats.inputTokens,
+ outputTokens: stats.outputTokens,
+ avgDurationMs: stats.messageCount > 0 ? Math.round(stats.totalDurationMs / stats.messageCount) : 0,
+ }))
+ )
+ .sort((a, b) => a.date.localeCompare(b.date))
+
+ const totalFeedback = positiveFeedback + negativeFeedback
+ const feedbackScore = totalFeedback > 0 ? Math.round((positiveFeedback / totalFeedback) * 100) : null
+
+ return {
+ period: {
+ days,
+ from: startDate.toISOString().split('T')[0]!,
+ to: new Date().toISOString().split('T')[0]!,
+ },
+ totals: {
+ messages: totalMessages,
+ inputTokens: totalInputTokens,
+ outputTokens: totalOutputTokens,
+ totalTokens: totalInputTokens + totalOutputTokens,
+ avgDurationMs: messagesWithDuration > 0 ? Math.round(totalDurationMs / messagesWithDuration) : 0,
+ },
+ feedback: {
+ positive: positiveFeedback,
+ negative: negativeFeedback,
+ total: totalFeedback,
+ score: feedbackScore,
+ },
+ byModel,
+ bySource,
+ daily,
+ }
+})
diff --git a/apps/chat/server/api/stats/me.get.ts b/apps/chat/server/api/stats/me.get.ts
new file mode 100644
index 0000000..bda0576
--- /dev/null
+++ b/apps/chat/server/api/stats/me.get.ts
@@ -0,0 +1,89 @@
+import { db, schema } from '@nuxthub/db'
+import { eq, and, isNotNull } from 'drizzle-orm'
+import type { UserStats } from '../../../shared/types/stats'
+
+/**
+ * GET /api/stats/me
+ * Get current user's usage statistics
+ */
+export default defineEventHandler(async (event) => {
+ const session = await getUserSession(event)
+ const userId = session.user?.id || session.id
+
+ // Get all chats for this user
+ const userChats = await db
+ .select({ id: schema.chats.id })
+ .from(schema.chats)
+ .where(eq(schema.chats.userId, userId))
+
+ if (userChats.length === 0) {
+ return {
+ totalMessages: 0,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalDurationMs: 0,
+ modelsUsed: [],
+ } satisfies UserStats
+ }
+
+ const chatIds = userChats.map(c => c.id)
+
+ // Get all assistant messages with stats for user's chats
+ const messagesWithStats = await db
+ .select({
+ model: schema.messages.model,
+ inputTokens: schema.messages.inputTokens,
+ outputTokens: schema.messages.outputTokens,
+ durationMs: schema.messages.durationMs,
+ })
+ .from(schema.messages)
+ .where(
+ and(
+ isNotNull(schema.messages.model),
+ // Filter by chat IDs - using SQL IN
+ chatIds.length === 1
+ ? eq(schema.messages.chatId, chatIds[0]!)
+ : undefined // Will need to handle multiple chats differently
+ )
+ )
+
+ // For multiple chats, we need to filter in JS since drizzle doesn't have a nice IN helper
+ const filteredMessages = chatIds.length > 1
+ ? await db
+ .select({
+ chatId: schema.messages.chatId,
+ model: schema.messages.model,
+ inputTokens: schema.messages.inputTokens,
+ outputTokens: schema.messages.outputTokens,
+ durationMs: schema.messages.durationMs,
+ })
+ .from(schema.messages)
+ .where(isNotNull(schema.messages.model))
+ .then(msgs => msgs.filter(m => chatIds.includes(m.chatId)))
+ : messagesWithStats
+
+ // Calculate totals
+ let totalMessages = 0
+ let totalInputTokens = 0
+ let totalOutputTokens = 0
+ let totalDurationMs = 0
+ const modelsSet = new Set<string>()
+
+ for (const msg of filteredMessages) {
+ if (!msg.model) continue
+
+ totalMessages++
+ totalInputTokens += msg.inputTokens ?? 0
+ totalOutputTokens += msg.outputTokens ?? 0
+ totalDurationMs += msg.durationMs ?? 0
+ modelsSet.add(msg.model)
+ }
+
+ return {
+ totalMessages,
+ totalInputTokens,
+ totalOutputTokens,
+ totalDurationMs,
+ modelsUsed: Array.from(modelsSet),
+ } satisfies UserStats
+})
diff --git a/apps/chat/server/api/stats/usage.post.ts b/apps/chat/server/api/stats/usage.post.ts
new file mode 100644
index 0000000..19eb52d
--- /dev/null
+++ b/apps/chat/server/api/stats/usage.post.ts
@@ -0,0 +1,51 @@
+import { z } from 'zod'
+import { db, schema } from '@nuxthub/db'
+
+const usageSchema = z.object({
+ source: z.string().min(1).max(50), // 'github-bot', 'discord-bot', 'sdk', etc.
+ sourceId: z.string().nullish(), // Issue number, PR number, etc.
+ model: z.string().nullish(),
+ inputTokens: z.number().int().nonnegative().nullish(),
+ outputTokens: z.number().int().nonnegative().nullish(),
+ durationMs: z.number().int().nonnegative().nullish(),
+ metadata: z.record(z.string(), z.unknown()).nullish(), // Additional context
+})
+
+/**
+ * POST /api/stats/usage
+ * Record API usage from external sources (SDK, GitHub bot, etc.)
+ *
+ * @example
+ * ```ts
+ * await $fetch('/api/stats/usage', {
+ * method: 'POST',
+ * body: {
+ * source: 'github-bot',
+ * sourceId: 'issue-123',
+ * model: 'google/gemini-3-flash',
+ * inputTokens: 1000,
+ * outputTokens: 500,
+ * durationMs: 2500,
+ * metadata: { repo: 'owner/repo', user: 'username' }
+ * }
+ * })
+ * ```
+ */
+export default defineEventHandler(async (event) => {
+ const body = await readValidatedBody(event, usageSchema.parse)
+
+ const usage = await db.insert(schema.apiUsage).values({
+ source: body.source,
+ sourceId: body.sourceId ?? undefined,
+ model: body.model ?? undefined,
+ inputTokens: body.inputTokens ?? undefined,
+ outputTokens: body.outputTokens ?? undefined,
+ durationMs: body.durationMs ?? undefined,
+ metadata: body.metadata ?? undefined,
+ }).returning()
+
+ return {
+ id: usage[0]?.id,
+ recorded: true,
+ }
+})
diff --git a/apps/chat/server/db/migrations/sqlite/0000_simple_marvel_boy.sql b/apps/chat/server/db/migrations/sqlite/0000_simple_marvel_boy.sql
new file mode 100644
index 0000000..7d86dbd
--- /dev/null
+++ b/apps/chat/server/db/migrations/sqlite/0000_simple_marvel_boy.sql
@@ -0,0 +1,103 @@
+CREATE TABLE `agent_config` (
+ `id` text PRIMARY KEY NOT NULL,
+ `name` text DEFAULT 'default' NOT NULL,
+ `additional_prompt` text,
+ `response_style` text DEFAULT 'concise',
+ `language` text DEFAULT 'en',
+ `default_model` text,
+ `max_steps_multiplier` real DEFAULT 1,
+ `temperature` real DEFAULT 0.7,
+ `search_instructions` text,
+ `citation_format` text DEFAULT 'inline',
+ `is_active` integer DEFAULT true NOT NULL,
+ `created_at` integer NOT NULL,
+ `updated_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE `api_usage` (
+ `id` text PRIMARY KEY NOT NULL,
+ `source` text NOT NULL,
+ `source_id` text,
+ `model` text,
+ `input_tokens` integer,
+ `output_tokens` integer,
+ `duration_ms` integer,
+ `metadata` text,
+ `created_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX `api_usage_source_idx` ON `api_usage` (`source`);--> statement-breakpoint
+CREATE INDEX `api_usage_created_at_idx` ON `api_usage` (`created_at`);--> statement-breakpoint
+CREATE TABLE `chats` (
+ `id` text PRIMARY KEY NOT NULL,
+ `title` text,
+ `user_id` text NOT NULL,
+ `is_public` integer DEFAULT false NOT NULL,
+ `share_token` text,
+ `created_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX `chats_user_id_idx` ON `chats` (`user_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `chats_share_token_idx` ON `chats` (`share_token`);--> statement-breakpoint
+CREATE TABLE `messages` (
+ `id` text PRIMARY KEY NOT NULL,
+ `chat_id` text NOT NULL,
+ `role` text NOT NULL,
+ `parts` text,
+ `feedback` text,
+ `model` text,
+ `input_tokens` integer,
+ `output_tokens` integer,
+ `duration_ms` integer,
+ `source` text DEFAULT 'web',
+ `created_at` integer NOT NULL,
+ FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `messages_chat_id_idx` ON `messages` (`chat_id`);--> statement-breakpoint
+CREATE TABLE `sources` (
+ `id` text PRIMARY KEY NOT NULL,
+ `type` text NOT NULL,
+ `label` text NOT NULL,
+ `base_path` text DEFAULT '/docs',
+ `repo` text,
+ `branch` text,
+ `content_path` text,
+ `output_path` text,
+ `readme_only` integer DEFAULT false,
+ `channel_id` text,
+ `handle` text,
+ `max_videos` integer DEFAULT 50,
+ `created_at` integer NOT NULL,
+ `updated_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX `sources_type_idx` ON `sources` (`type`);--> statement-breakpoint
+CREATE TABLE `usage_stats` (
+ `id` text PRIMARY KEY NOT NULL,
+ `date` text NOT NULL,
+ `user_id` text,
+ `source` text DEFAULT 'web' NOT NULL,
+ `model` text NOT NULL,
+ `message_count` integer DEFAULT 0 NOT NULL,
+ `total_input_tokens` integer DEFAULT 0 NOT NULL,
+ `total_output_tokens` integer DEFAULT 0 NOT NULL,
+ `total_duration_ms` integer DEFAULT 0 NOT NULL,
+ `created_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX `usage_stats_date_idx` ON `usage_stats` (`date`);--> statement-breakpoint
+CREATE UNIQUE INDEX `usage_stats_date_user_source_model_idx` ON `usage_stats` (`date`,`user_id`,`source`,`model`);--> statement-breakpoint
+CREATE TABLE `users` (
+ `id` text PRIMARY KEY NOT NULL,
+ `email` text NOT NULL,
+ `name` text NOT NULL,
+ `avatar` text NOT NULL,
+ `username` text NOT NULL,
+ `provider` text NOT NULL,
+ `provider_id` text NOT NULL,
+ `role` text DEFAULT 'user' NOT NULL,
+ `created_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `users_provider_id_idx` ON `users` (`provider`,`provider_id`);
\ No newline at end of file
diff --git a/apps/chat/server/db/migrations/sqlite/0000_steady_magdalene.sql b/apps/chat/server/db/migrations/sqlite/0000_steady_magdalene.sql
deleted file mode 100644
index 9a91015..0000000
--- a/apps/chat/server/db/migrations/sqlite/0000_steady_magdalene.sql
+++ /dev/null
@@ -1,52 +0,0 @@
-CREATE TABLE `chats` (
- `id` text PRIMARY KEY NOT NULL,
- `title` text,
- `user_id` text NOT NULL,
- `is_public` integer DEFAULT false NOT NULL,
- `share_token` text,
- `created_at` integer NOT NULL
-);
---> statement-breakpoint
-CREATE INDEX `chats_user_id_idx` ON `chats` (`user_id`);--> statement-breakpoint
-CREATE UNIQUE INDEX `chats_share_token_idx` ON `chats` (`share_token`);--> statement-breakpoint
-CREATE TABLE `messages` (
- `id` text PRIMARY KEY NOT NULL,
- `chat_id` text NOT NULL,
- `role` text NOT NULL,
- `parts` text,
- `created_at` integer NOT NULL,
- FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade
-);
---> statement-breakpoint
-CREATE INDEX `messages_chat_id_idx` ON `messages` (`chat_id`);--> statement-breakpoint
-CREATE TABLE `sources` (
- `id` text PRIMARY KEY NOT NULL,
- `type` text NOT NULL,
- `label` text NOT NULL,
- `base_path` text DEFAULT '/docs',
- `repo` text,
- `branch` text,
- `content_path` text,
- `output_path` text,
- `readme_only` integer DEFAULT false,
- `channel_id` text,
- `handle` text,
- `max_videos` integer DEFAULT 50,
- `created_at` integer NOT NULL,
- `updated_at` integer NOT NULL
-);
---> statement-breakpoint
-CREATE INDEX `sources_type_idx` ON `sources` (`type`);--> statement-breakpoint
-CREATE TABLE `users` (
- `id` text PRIMARY KEY NOT NULL,
- `email` text NOT NULL,
- `name` text NOT NULL,
- `avatar` text NOT NULL,
- `username` text NOT NULL,
- `provider` text NOT NULL,
- `provider_id` text NOT NULL,
- `role` text DEFAULT 'user' NOT NULL,
- `created_at` integer NOT NULL
-);
---> statement-breakpoint
-CREATE UNIQUE INDEX `users_provider_id_idx` ON `users` (`provider`,`provider_id`);
\ No newline at end of file
diff --git a/apps/chat/server/db/migrations/sqlite/0001_certain_paibok.sql b/apps/chat/server/db/migrations/sqlite/0001_certain_paibok.sql
deleted file mode 100644
index 206438b..0000000
--- a/apps/chat/server/db/migrations/sqlite/0001_certain_paibok.sql
+++ /dev/null
@@ -1,15 +0,0 @@
-CREATE TABLE `agent_config` (
- `id` text PRIMARY KEY NOT NULL,
- `name` text DEFAULT 'default' NOT NULL,
- `additional_prompt` text,
- `response_style` text DEFAULT 'concise',
- `language` text DEFAULT 'en',
- `default_model` text,
- `max_steps_multiplier` real DEFAULT 1,
- `temperature` real DEFAULT 0.7,
- `search_instructions` text,
- `citation_format` text DEFAULT 'inline',
- `is_active` integer DEFAULT true NOT NULL,
- `created_at` integer NOT NULL,
- `updated_at` integer NOT NULL
-);
diff --git a/apps/chat/server/db/migrations/sqlite/0004_api_usage.sql b/apps/chat/server/db/migrations/sqlite/0004_api_usage.sql
new file mode 100644
index 0000000..54ceaf6
--- /dev/null
+++ b/apps/chat/server/db/migrations/sqlite/0004_api_usage.sql
@@ -0,0 +1,24 @@
+-- Add source field to messages table
+ALTER TABLE `messages` ADD `source` text DEFAULT 'web';--> statement-breakpoint
+
+-- Create api_usage table for external API tracking (SDK, GitHub bot, etc.)
+CREATE TABLE `api_usage` (
+ `id` text PRIMARY KEY NOT NULL,
+ `source` text NOT NULL,
+ `source_id` text,
+ `model` text,
+ `input_tokens` integer,
+ `output_tokens` integer,
+ `duration_ms` integer,
+ `metadata` text,
+ `created_at` integer NOT NULL
+);--> statement-breakpoint
+CREATE INDEX `api_usage_source_idx` ON `api_usage` (`source`);--> statement-breakpoint
+CREATE INDEX `api_usage_created_at_idx` ON `api_usage` (`created_at`);--> statement-breakpoint
+
+-- Add source field to usage_stats table
+ALTER TABLE `usage_stats` ADD `source` text DEFAULT 'web' NOT NULL;--> statement-breakpoint
+
+-- Drop old unique index and create new one with source
+DROP INDEX IF EXISTS `usage_stats_date_user_model_idx`;--> statement-breakpoint
+CREATE UNIQUE INDEX `usage_stats_date_user_source_model_idx` ON `usage_stats` (`date`,`user_id`,`source`,`model`);
diff --git a/apps/chat/server/db/migrations/sqlite/meta/0000_snapshot.json b/apps/chat/server/db/migrations/sqlite/meta/0000_snapshot.json
index d0c4afe..e3a2fc5 100644
--- a/apps/chat/server/db/migrations/sqlite/meta/0000_snapshot.json
+++ b/apps/chat/server/db/migrations/sqlite/meta/0000_snapshot.json
@@ -1,9 +1,205 @@
{
"version": "6",
"dialect": "sqlite",
- "id": "6813eb3d-c05b-4506-b750-ae137da56780",
+ "id": "e5378405-eb7b-479e-9b85-a639ffb8f09b",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
+ "agent_config": {
+ "name": "agent_config",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'default'"
+ },
+ "additional_prompt": {
+ "name": "additional_prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response_style": {
+ "name": "response_style",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'concise'"
+ },
+ "language": {
+ "name": "language",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'en'"
+ },
+ "default_model": {
+ "name": "default_model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_steps_multiplier": {
+ "name": "max_steps_multiplier",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 1
+ },
+ "temperature": {
+ "name": "temperature",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0.7
+ },
+ "search_instructions": {
+ "name": "search_instructions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "citation_format": {
+ "name": "citation_format",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'inline'"
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "api_usage": {
+ "name": "api_usage",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "api_usage_source_idx": {
+ "name": "api_usage_source_idx",
+ "columns": [
+ "source"
+ ],
+ "isUnique": false
+ },
+ "api_usage_created_at_idx": {
+ "name": "api_usage_created_at_idx",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
"chats": {
"name": "chats",
"columns": {
@@ -103,6 +299,49 @@
"notNull": false,
"autoincrement": false
},
+ "feedback": {
+ "name": "feedback",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'web'"
+ },
"created_at": {
"name": "created_at",
"type": "integer",
@@ -258,6 +497,109 @@
"uniqueConstraints": {},
"checkConstraints": {}
},
+ "usage_stats": {
+ "name": "usage_stats",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'web'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message_count": {
+ "name": "message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_input_tokens": {
+ "name": "total_input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_output_tokens": {
+ "name": "total_output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_duration_ms": {
+ "name": "total_duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "usage_stats_date_idx": {
+ "name": "usage_stats_date_idx",
+ "columns": [
+ "date"
+ ],
+ "isUnique": false
+ },
+ "usage_stats_date_user_source_model_idx": {
+ "name": "usage_stats_date_user_source_model_idx",
+ "columns": [
+ "date",
+ "user_id",
+ "source",
+ "model"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
"users": {
"name": "users",
"columns": {
diff --git a/apps/chat/server/db/migrations/sqlite/meta/0001_snapshot.json b/apps/chat/server/db/migrations/sqlite/meta/0001_snapshot.json
deleted file mode 100644
index b24936d..0000000
--- a/apps/chat/server/db/migrations/sqlite/meta/0001_snapshot.json
+++ /dev/null
@@ -1,463 +0,0 @@
-{
- "version": "6",
- "dialect": "sqlite",
- "id": "0e8e9ef9-86ad-4cee-9874-85d58fdd97d7",
- "prevId": "6813eb3d-c05b-4506-b750-ae137da56780",
- "tables": {
- "agent_config": {
- "name": "agent_config",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true,
- "autoincrement": false
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false,
- "default": "'default'"
- },
- "additional_prompt": {
- "name": "additional_prompt",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "response_style": {
- "name": "response_style",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false,
- "default": "'concise'"
- },
- "language": {
- "name": "language",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false,
- "default": "'en'"
- },
- "default_model": {
- "name": "default_model",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "max_steps_multiplier": {
- "name": "max_steps_multiplier",
- "type": "real",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false,
- "default": 1
- },
- "temperature": {
- "name": "temperature",
- "type": "real",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false,
- "default": 0.7
- },
- "search_instructions": {
- "name": "search_instructions",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "citation_format": {
- "name": "citation_format",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false,
- "default": "'inline'"
- },
- "is_active": {
- "name": "is_active",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false,
- "default": true
- },
- "created_at": {
- "name": "created_at",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "updated_at": {
- "name": "updated_at",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- }
- },
- "indexes": {},
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "checkConstraints": {}
- },
- "chats": {
- "name": "chats",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true,
- "autoincrement": false
- },
- "title": {
- "name": "title",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "user_id": {
- "name": "user_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "is_public": {
- "name": "is_public",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false,
- "default": false
- },
- "share_token": {
- "name": "share_token",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "created_at": {
- "name": "created_at",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- }
- },
- "indexes": {
- "chats_user_id_idx": {
- "name": "chats_user_id_idx",
- "columns": [
- "user_id"
- ],
- "isUnique": false
- },
- "chats_share_token_idx": {
- "name": "chats_share_token_idx",
- "columns": [
- "share_token"
- ],
- "isUnique": true
- }
- },
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "checkConstraints": {}
- },
- "messages": {
- "name": "messages",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true,
- "autoincrement": false
- },
- "chat_id": {
- "name": "chat_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "role": {
- "name": "role",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "parts": {
- "name": "parts",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "created_at": {
- "name": "created_at",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- }
- },
- "indexes": {
- "messages_chat_id_idx": {
- "name": "messages_chat_id_idx",
- "columns": [
- "chat_id"
- ],
- "isUnique": false
- }
- },
- "foreignKeys": {
- "messages_chat_id_chats_id_fk": {
- "name": "messages_chat_id_chats_id_fk",
- "tableFrom": "messages",
- "tableTo": "chats",
- "columnsFrom": [
- "chat_id"
- ],
- "columnsTo": [
- "id"
- ],
- "onDelete": "cascade",
- "onUpdate": "no action"
- }
- },
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "checkConstraints": {}
- },
- "sources": {
- "name": "sources",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true,
- "autoincrement": false
- },
- "type": {
- "name": "type",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "label": {
- "name": "label",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "base_path": {
- "name": "base_path",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false,
- "default": "'/docs'"
- },
- "repo": {
- "name": "repo",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "branch": {
- "name": "branch",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "content_path": {
- "name": "content_path",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "output_path": {
- "name": "output_path",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "readme_only": {
- "name": "readme_only",
- "type": "integer",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false,
- "default": false
- },
- "channel_id": {
- "name": "channel_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "handle": {
- "name": "handle",
- "type": "text",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false
- },
- "max_videos": {
- "name": "max_videos",
- "type": "integer",
- "primaryKey": false,
- "notNull": false,
- "autoincrement": false,
- "default": 50
- },
- "created_at": {
- "name": "created_at",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "updated_at": {
- "name": "updated_at",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- }
- },
- "indexes": {
- "sources_type_idx": {
- "name": "sources_type_idx",
- "columns": [
- "type"
- ],
- "isUnique": false
- }
- },
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "checkConstraints": {}
- },
- "users": {
- "name": "users",
- "columns": {
- "id": {
- "name": "id",
- "type": "text",
- "primaryKey": true,
- "notNull": true,
- "autoincrement": false
- },
- "email": {
- "name": "email",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "name": {
- "name": "name",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "avatar": {
- "name": "avatar",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "username": {
- "name": "username",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "provider": {
- "name": "provider",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "provider_id": {
- "name": "provider_id",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- },
- "role": {
- "name": "role",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false,
- "default": "'user'"
- },
- "created_at": {
- "name": "created_at",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false
- }
- },
- "indexes": {
- "users_provider_id_idx": {
- "name": "users_provider_id_idx",
- "columns": [
- "provider",
- "provider_id"
- ],
- "isUnique": true
- }
- },
- "foreignKeys": {},
- "compositePrimaryKeys": {},
- "uniqueConstraints": {},
- "checkConstraints": {}
- }
- },
- "views": {},
- "enums": {},
- "_meta": {
- "schemas": {},
- "tables": {},
- "columns": {}
- },
- "internal": {
- "indexes": {}
- }
-}
\ No newline at end of file
diff --git a/apps/chat/server/db/migrations/sqlite/meta/_journal.json b/apps/chat/server/db/migrations/sqlite/meta/_journal.json
index 791c81c..04b1262 100644
--- a/apps/chat/server/db/migrations/sqlite/meta/_journal.json
+++ b/apps/chat/server/db/migrations/sqlite/meta/_journal.json
@@ -5,15 +5,8 @@
{
"idx": 0,
"version": "6",
- "when": 1769440810870,
- "tag": "0000_steady_magdalene",
- "breakpoints": true
- },
- {
- "idx": 1,
- "version": "6",
- "when": 1770128425579,
- "tag": "0001_certain_paibok",
+ "when": 1770290453735,
+ "tag": "0000_simple_marvel_boy",
"breakpoints": true
}
]
diff --git a/apps/chat/server/db/schema.ts b/apps/chat/server/db/schema.ts
index 2b1e9c9..f2b334c 100644
--- a/apps/chat/server/db/schema.ts
+++ b/apps/chat/server/db/schema.ts
@@ -11,7 +11,7 @@ export const users = sqliteTable('users', {
name: text('name').notNull(),
avatar: text('avatar').notNull(),
username: text('username').notNull(),
- provider: text('provider').notNull(), // 'github'
+ provider: text('provider').notNull(),
providerId: text('provider_id').notNull(),
role: text('role', { enum: ['user', 'admin'] }).notNull().default('user'),
...timestamps
@@ -46,6 +46,13 @@ export const messages = sqliteTable('messages', {
chatId: text('chat_id').notNull().references(() => chats.id, { onDelete: 'cascade' }),
role: text('role', { enum: ['user', 'assistant', 'system'] }).notNull(),
parts: text('parts', { mode: 'json' }),
+ feedback: text('feedback', { enum: ['positive', 'negative'] }),
+ // Stats fields (for assistant messages only)
+ model: text('model'),
+ inputTokens: integer('input_tokens'),
+ outputTokens: integer('output_tokens'),
+ durationMs: integer('duration_ms'),
+ source: text('source', { enum: ['web', 'api'] }).default('web'),
...timestamps
}, table => [index('messages_chat_id_idx').on(table.chatId)])
@@ -88,3 +95,34 @@ export const agentConfig = sqliteTable('agent_config', {
...timestamps,
updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
})
+
+export const apiUsage = sqliteTable('api_usage', {
+ id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
+ source: text('source').notNull(), // 'github-bot', 'sdk', 'discord-bot', etc.
+ sourceId: text('source_id'), // Optional: issue number, PR number, etc.
+ model: text('model'),
+ inputTokens: integer('input_tokens'),
+ outputTokens: integer('output_tokens'),
+ durationMs: integer('duration_ms'),
+ metadata: text('metadata', { mode: 'json' }), // Additional context (repo, user, etc.)
+ ...timestamps
+}, table => [
+ index('api_usage_source_idx').on(table.source),
+ index('api_usage_created_at_idx').on(table.createdAt)
+])
+
+export const usageStats = sqliteTable('usage_stats', {
+ id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
+ date: text('date').notNull(), // Format: YYYY-MM-DD
+ userId: text('user_id'), // null = global stats
+ source: text('source').notNull().default('web'), // 'web', 'github-bot', 'sdk', etc.
+ model: text('model').notNull(),
+ messageCount: integer('message_count').notNull().default(0),
+ totalInputTokens: integer('total_input_tokens').notNull().default(0),
+ totalOutputTokens: integer('total_output_tokens').notNull().default(0),
+ totalDurationMs: integer('total_duration_ms').notNull().default(0),
+ ...timestamps,
+}, table => [
+ index('usage_stats_date_idx').on(table.date),
+ uniqueIndex('usage_stats_date_user_source_model_idx').on(table.date, table.userId, table.source, table.model),
+])
diff --git a/apps/chat/server/utils/chat/generate-title.ts b/apps/chat/server/utils/chat/generate-title.ts
index 45b3d40..9e7504f 100644
--- a/apps/chat/server/utils/chat/generate-title.ts
+++ b/apps/chat/server/utils/chat/generate-title.ts
@@ -18,13 +18,10 @@ export function generateTitle(options: GenerateTitleOptions): void {
const { firstMessage, chatId, requestId, writer } = options
generateText({
- model: 'google/gemini-3-flash',
- system: `You are a title generator for a chat:
- - Generate a short title based on the first user's message
- - The title should be less than 30 characters long
- - The title should be a summary of the user's message
- - Do not use quotes (' or ") or colons (:) or any other punctuation
- - Do not use markdown, just plain text`,
+ model: 'google/gemini-2.5-flash-lite',
+ system: `Generate a short chat title (max 30 chars) from the user's message.
+Rules: no quotes, no colons, no punctuation, plain text only.
+If the message is a simple greeting (hi, hey, hello, etc.), respond with a generic title like "New conversation" or "Quick chat".`,
prompt: JSON.stringify(firstMessage),
}).then(async ({ text: title }) => {
writer.write({
diff --git a/apps/chat/server/workflows/compute-stats/index.ts b/apps/chat/server/workflows/compute-stats/index.ts
new file mode 100644
index 0000000..32b2969
--- /dev/null
+++ b/apps/chat/server/workflows/compute-stats/index.ts
@@ -0,0 +1,2 @@
+export { computeStats } from './workflow'
+export type { ComputeStatsConfig, ComputeStatsResult, AggregatedStats } from './types'
diff --git a/apps/chat/server/workflows/compute-stats/steps/aggregate.ts b/apps/chat/server/workflows/compute-stats/steps/aggregate.ts
new file mode 100644
index 0000000..964084f
--- /dev/null
+++ b/apps/chat/server/workflows/compute-stats/steps/aggregate.ts
@@ -0,0 +1,171 @@
+/**
+ * Aggregate stats for a specific date
+ */
+
+import { log } from 'evlog'
+import { db, schema } from '@nuxthub/db'
+import { and, gte, lt, isNotNull, eq } from 'drizzle-orm'
+import type { AggregatedStats, ComputeStatsResult } from '../types'
+
+export async function stepAggregateStats(date: string): Promise<ComputeStatsResult> {
+ 'use step'
+
+ log.info('stats', `Computing stats for ${date}`)
+
+ // Parse date boundaries
+ const startDate = new Date(`${date}T00:00:00.000Z`)
+ const endDate = new Date(`${date}T23:59:59.999Z`)
+
+ // Get all assistant messages with stats for this date
+ const messagesWithStats = await db
+ .select({
+ chatId: schema.messages.chatId,
+ model: schema.messages.model,
+ inputTokens: schema.messages.inputTokens,
+ outputTokens: schema.messages.outputTokens,
+ durationMs: schema.messages.durationMs,
+ })
+ .from(schema.messages)
+ .where(
+ and(
+ isNotNull(schema.messages.model),
+ gte(schema.messages.createdAt, startDate),
+ lt(schema.messages.createdAt, endDate)
+ )
+ )
+
+ if (messagesWithStats.length === 0) {
+ log.info('stats', `No messages found for ${date}`)
+ return {
+ success: true,
+ date,
+ statsCreated: 0,
+ userStats: 0,
+ globalStats: 0,
+ }
+ }
+
+ log.info('stats', `Found ${messagesWithStats.length} messages to aggregate`)
+
+ // Get chat -> user mapping
+ const chatIds = [...new Set(messagesWithStats.map(m => m.chatId))]
+ const chats = await db
+ .select({ id: schema.chats.id, userId: schema.chats.userId })
+ .from(schema.chats)
+ .where(
+ chatIds.length === 1
+ ? eq(schema.chats.id, chatIds[0]!)
+ : undefined // Will filter in JS for multiple
+ )
+
+ const chatUserMap = new Map<string, string>()
+ for (const chat of chats) {
+ if (chatIds.includes(chat.id)) {
+ chatUserMap.set(chat.id, chat.userId)
+ }
+ }
+
+ // Aggregate by userId + model
+ const userModelMap = new Map<string, AggregatedStats>()
+ const globalModelMap = new Map<string, AggregatedStats>()
+
+ for (const msg of messagesWithStats) {
+ if (!msg.model) continue
+
+ const userId = chatUserMap.get(msg.chatId) ?? null
+ const inputTokens = msg.inputTokens ?? 0
+ const outputTokens = msg.outputTokens ?? 0
+ const durationMs = msg.durationMs ?? 0
+
+ // User stats
+ if (userId) {
+ const userKey = `${userId}:${msg.model}`
+ const userStats = userModelMap.get(userKey) ?? {
+ userId,
+ model: msg.model,
+ messageCount: 0,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalDurationMs: 0,
+ }
+ userStats.messageCount++
+ userStats.totalInputTokens += inputTokens
+ userStats.totalOutputTokens += outputTokens
+ userStats.totalDurationMs += durationMs
+ userModelMap.set(userKey, userStats)
+ }
+
+ // Global stats (userId = null)
+ const globalKey = msg.model
+ const globalStats = globalModelMap.get(globalKey) ?? {
+ userId: null,
+ model: msg.model,
+ messageCount: 0,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalDurationMs: 0,
+ }
+ globalStats.messageCount++
+ globalStats.totalInputTokens += inputTokens
+ globalStats.totalOutputTokens += outputTokens
+ globalStats.totalDurationMs += durationMs
+ globalModelMap.set(globalKey, globalStats)
+ }
+
+ // Upsert into usage_stats table
+ const allStats = [...userModelMap.values(), ...globalModelMap.values()]
+
+ for (const stats of allStats) {
+ // Check if record exists
+ const existing = await db
+ .select()
+ .from(schema.usageStats)
+ .where(
+ and(
+ eq(schema.usageStats.date, date),
+ stats.userId
+ ? eq(schema.usageStats.userId, stats.userId)
+ : isNotNull(schema.usageStats.userId) === false as any, // null check
+ eq(schema.usageStats.model, stats.model)
+ )
+ )
+ .limit(1)
+
+ if (existing.length > 0) {
+ // Update existing record
+ await db
+ .update(schema.usageStats)
+ .set({
+ messageCount: stats.messageCount,
+ totalInputTokens: stats.totalInputTokens,
+ totalOutputTokens: stats.totalOutputTokens,
+ totalDurationMs: stats.totalDurationMs,
+ })
+ .where(eq(schema.usageStats.id, existing[0]!.id))
+ } else {
+ // Insert new record
+ await db.insert(schema.usageStats).values({
+ date,
+ userId: stats.userId,
+ model: stats.model,
+ messageCount: stats.messageCount,
+ totalInputTokens: stats.totalInputTokens,
+ totalOutputTokens: stats.totalOutputTokens,
+ totalDurationMs: stats.totalDurationMs,
+ })
+ }
+ }
+
+ const userStatsCount = userModelMap.size
+ const globalStatsCount = globalModelMap.size
+
+ log.info('stats', `Created ${allStats.length} stats records (${userStatsCount} user, ${globalStatsCount} global)`)
+
+ return {
+ success: true,
+ date,
+ statsCreated: allStats.length,
+ userStats: userStatsCount,
+ globalStats: globalStatsCount,
+ }
+}
diff --git a/apps/chat/server/workflows/compute-stats/steps/index.ts b/apps/chat/server/workflows/compute-stats/steps/index.ts
new file mode 100644
index 0000000..91680be
--- /dev/null
+++ b/apps/chat/server/workflows/compute-stats/steps/index.ts
@@ -0,0 +1 @@
+export { stepAggregateStats } from './aggregate'
diff --git a/apps/chat/server/workflows/compute-stats/types.ts b/apps/chat/server/workflows/compute-stats/types.ts
new file mode 100644
index 0000000..5a1ecd3
--- /dev/null
+++ b/apps/chat/server/workflows/compute-stats/types.ts
@@ -0,0 +1,28 @@
+/**
+ * Types for compute-stats workflow
+ */
+
+export interface ComputeStatsConfig {
+ /**
+ * Date to compute stats for (YYYY-MM-DD format)
+ * Defaults to yesterday
+ */
+ date: string
+}
+
+export interface AggregatedStats {
+ userId: string | null // null = global stats
+ model: string
+ messageCount: number
+ totalInputTokens: number
+ totalOutputTokens: number
+ totalDurationMs: number
+}
+
+export interface ComputeStatsResult {
+ success: boolean
+ date: string
+ statsCreated: number
+ userStats: number
+ globalStats: number
+}
diff --git a/apps/chat/server/workflows/compute-stats/workflow.ts b/apps/chat/server/workflows/compute-stats/workflow.ts
new file mode 100644
index 0000000..20e4358
--- /dev/null
+++ b/apps/chat/server/workflows/compute-stats/workflow.ts
@@ -0,0 +1,26 @@
+/**
+ * Compute Stats Workflow
+ *
+ * Aggregates daily usage statistics from messages into the usage_stats table.
+ * Can be triggered manually via API or scheduled via cron.
+ */
+
+import { log } from 'evlog'
+import type { ComputeStatsConfig, ComputeStatsResult } from './types'
+import { stepAggregateStats } from './steps'
+
+export async function computeStats(config: ComputeStatsConfig): Promise<ComputeStatsResult> {
+ 'use workflow'
+
+ log.info('stats', `Starting stats computation for ${config.date}`)
+
+ const result = await stepAggregateStats(config.date)
+
+ if (result.success) {
+ log.info('stats', `✓ Stats computed: ${result.statsCreated} records for ${config.date}`)
+ } else {
+ log.error('stats', `✗ Stats computation failed for ${config.date}`)
+ }
+
+ return result
+}
diff --git a/apps/chat/shared/types/stats.d.ts b/apps/chat/shared/types/stats.d.ts
new file mode 100644
index 0000000..e89b5f3
--- /dev/null
+++ b/apps/chat/shared/types/stats.d.ts
@@ -0,0 +1,73 @@
+/**
+ * User statistics summary
+ */
+export interface UserStats {
+ totalMessages: number
+ totalInputTokens: number
+ totalOutputTokens: number
+ totalDurationMs: number
+ modelsUsed: string[]
+}
+
+/**
+ * Daily aggregated statistics
+ */
+export interface DailyStats {
+ date: string
+ model: string
+ messageCount: number
+ inputTokens: number
+ outputTokens: number
+ avgDurationMs: number
+}
+
+/**
+ * Feedback statistics
+ */
+export interface FeedbackStats {
+ positive: number
+ negative: number
+ total: number
+ score: number | null // 0-100 percentage, null if no feedback
+}
+
+/**
+ * Statistics by source
+ */
+export interface SourceStats {
+ source: string // 'web', 'github-bot', 'sdk', etc.
+ requests: number
+ inputTokens: number
+ outputTokens: number
+ totalTokens: number
+ avgDurationMs: number
+}
+
+/**
+ * Global stats response (admin)
+ */
+export interface GlobalStatsResponse {
+ period: {
+ days: number
+ from: string
+ to: string
+ }
+ totals: {
+ messages: number
+ inputTokens: number
+ outputTokens: number
+ totalTokens: number
+ avgDurationMs: number
+ }
+ feedback: FeedbackStats
+ byModel: Array<{
+ model: string
+ messageCount: number
+ inputTokens: number
+ outputTokens: number
+ positive: number
+ negative: number
+ }>
+ bySource: SourceStats[]
+ daily: DailyStats[]
+}
diff --git a/bun.lock b/bun.lock
index 2c87d73..0ecbb33 100644
--- a/bun.lock
+++ b/bun.lock
@@ -55,17 +55,11 @@
"@ai-sdk/gateway": "^3.0.32",
"@savoir/sdk": "workspace:*",
"ai": "^6.0.68",
- "chat": "^4.7.1",
- "mdast-util-from-markdown": "^2.0.2",
- "mdast-util-gfm": "^3.1.0",
- "mdast-util-to-markdown": "^2.1.2",
- "micromark-extension-gfm": "^3.0.0",
"nuxt": "^4.3.0",
"zod": "^4.3.6",
},
"devDependencies": {
"@nuxthub/core": "^0.10.5",
- "@types/mdast": "^4.0.4",
"typescript": "^5.9.3",
},
},
@@ -1386,8 +1380,6 @@
"character-reference-invalid": ["[email protected]", "", {}, "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="],
- "chat": ["[email protected]", "", { "dependencies": { "@workflow/serde": "4.0.1-beta.1", "mdast-util-to-string": "^4.0.0", "remark-gfm": "^4.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.5" } }, "sha512-y9QCeY4b7e4Emap0MjZtohZieQA47dhe9c4wUBtAI5HSTTn6Y9N4tEckVm04pHosSthqRZTjBEToM/wSCTzpLw=="],
-
"chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="],
"chownr": ["[email protected]", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="],
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
new file mode 100644
index 0000000..8e978d4
--- /dev/null
+++ b/packages/sdk/README.md
@@ -0,0 +1,213 @@
+# @savoir/sdk
+
+SDK for [Savoir](https://github.com/HugoRCD/savoir) - AI agents with real-time knowledge base access.
+
+Provides [AI SDK](https://ai-sdk.dev) compatible tools to query documentation in a sandboxed environment.
+
+## Installation
+
+```bash
+npm install @savoir/sdk
+# or
+bun add @savoir/sdk
+# or
+pnpm add @savoir/sdk
+```
+
+## Configuration
+
+Set the following environment variables:
+
+| Variable | Required | Description |
+|----------|----------|-------------|
+| `SAVOIR_API_URL` | Yes | Base URL of your Savoir API (e.g., `https://chat.savoir.dev`) |
+| `SAVOIR_API_KEY` | No | API key for authentication. Required if the API has `SAVOIR_SECRET_KEY` configured. |
+
+## Quick Start
+
+```ts
+import { createSavoir } from '@savoir/sdk'
+import { generateText } from 'ai'
+
+const savoir = createSavoir({
+ apiUrl: process.env.SAVOIR_API_URL!,
+ apiKey: process.env.SAVOIR_API_KEY, // Optional if API doesn't require auth
+})
+
+const { text } = await generateText({
+ model: 'google/gemini-3-flash',
+ tools: savoir.tools,
+ maxSteps: 10,
+ prompt: 'How do I use useAsyncData in Nuxt?',
+})
+
+console.log(text)
+```
+
+## API Reference
+
+### `createSavoir(config)`
+
+Creates a Savoir instance with API client and AI SDK tools.
+
+```ts
+import { createSavoir } from '@savoir/sdk'
+
+const savoir = createSavoir({
+ apiUrl: process.env.SAVOIR_API_URL!,
+ apiKey: process.env.SAVOIR_API_KEY,
+ sessionId: 'optional-session-id', // For sandbox reuse
+ onToolCall: (info) => {
+ // Optional callback for tool execution states
+ console.log(`Tool ${info.toolName}: ${info.state}`)
+ },
+})
+```
+
+#### Config Options
+
+| Option | Type | Required | Description |
+|--------|------|----------|-------------|
+| `apiUrl` | `string` | Yes | Base URL of your Savoir API |
+| `apiKey` | `string` | No | API key for authentication |
+| `sessionId` | `string` | No | Reuse an existing sandbox session |
+| `onToolCall` | `function` | No | Callback fired on tool execution (loading/done/error) |
+
+#### Returns
+
+```ts
+interface Savoir {
+ client: SavoirClient // Low-level HTTP client
+ tools: {
+ bash: Tool // Execute single bash command
+ bash_batch: Tool // Execute multiple commands (more efficient)
+ }
+ getSessionId(): string | undefined
+ setSessionId(sessionId: string): void
+ getAgentConfig(): Promise<AgentConfig>
+}
+```
+
+### Tools
+
+#### `bash`
+
+Execute a single bash command in the documentation sandbox.
+
+```ts
+const { text } = await generateText({
+ model,
+ tools: { bash: savoir.tools.bash },
+ prompt: 'List all markdown files in the docs folder',
+})
+```
+
+#### `bash_batch`
+
+Execute multiple bash commands in a single request. More efficient than multiple single calls as the sandbox is reused between commands.
+
+```ts
+const { text } = await generateText({
+ model,
+ tools: { bash_batch: savoir.tools.bash_batch },
+ prompt: 'Find all TypeScript files and show their first 10 lines',
+})
+```
+
+### `SavoirClient`
+
+Low-level HTTP client for direct API access. Use `createSavoir()` for the high-level interface.
+
+```ts
+import { SavoirClient } from '@savoir/sdk'
+
+const client = new SavoirClient({
+ apiUrl: process.env.SAVOIR_API_URL!,
+ apiKey: process.env.SAVOIR_API_KEY,
+})
+
+// Execute bash command
+const result = await client.bash('ls -la')
+console.log(result.stdout)
+
+// Execute multiple commands
+const batchResult = await client.bashBatch(['pwd', 'ls', 'cat README.md'])
+
+// Get sources configuration
+const sources = await client.getSources()
+
+// Trigger sync
+await client.sync({ reset: false, push: true })
+
+// Get agent configuration
+const config = await client.getAgentConfig()
+```
+
+## Error Handling
+
+The SDK exports two error classes:
+
+### `SavoirError`
+
+Thrown when the API returns an error response.
+
+```ts
+import { SavoirError } from '@savoir/sdk'
+
+try {
+ await client.bash('some-command')
+} catch (error) {
+ if (error instanceof SavoirError) {
+ console.log(error.statusCode) // HTTP status code
+ console.log(error.message) // Error message
+
+ if (error.isAuthError()) {
+ // Handle 401
+ } else if (error.isRateLimitError()) {
+ // Handle 429
+ } else if (error.isServerError()) {
+ // Handle 5xx
+ }
+ }
+}
+```
+
+### `NetworkError`
+
+Thrown when the request fails to reach the API (network issues, DNS errors, etc.).
+
+```ts
+import { NetworkError } from '@savoir/sdk'
+
+try {
+ await client.bash('some-command')
+} catch (error) {
+ if (error instanceof NetworkError) {
+ console.log(error.message)
+ console.log(error.cause) // Original error
+ }
+}
+```
+
+## Types
+
+All types are exported for TypeScript users:
+
+```ts
+import type {
+ SavoirConfig,
+ ShellResponse,
+ ShellBatchResponse,
+ SyncOptions,
+ SyncResponse,
+ SourcesResponse,
+ AgentConfig,
+ ToolCallInfo,
+ ToolCallCallback,
+ ToolCallState,
+} from '@savoir/sdk'
+```
+
+## License
+
+MIT
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index 4ae3b29..b901090 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -1,7 +1,26 @@
{
"name": "@savoir/sdk",
- "version": "0.0.1",
+ "version": "0.1.0-alpha.1",
"description": "SDK for Savoir documentation AI with AI SDK compatible tools",
+ "license": "MIT",
+ "author": "Hugo Richard",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/hugorichard/savoir.git",
+ "directory": "packages/sdk"
+ },
+ "homepage": "https://github.com/hugorichard/savoir/tree/main/packages/sdk#readme",
+ "bugs": {
+ "url": "https://github.com/hugorichard/savoir/issues"
+ },
+ "keywords": [
+ "savoir",
+ "ai",
+ "ai-sdk",
+ "documentation",
+ "rag",
+ "sandbox"
+ ],
"type": "module",
"exports": {
".": {
@@ -14,7 +33,8 @@
"types": "./dist/index.d.mts",
"sideEffects": false,
"files": [
- "dist"
+ "dist",
+ "README.md"
],
"scripts": {
"build": "tsdown",
@@ -26,7 +46,6 @@
},
"dependencies": {
"ai": "^6.0.68",
- "evlog": "^1.1.0",
"zod": "^4.3.6"
},
"devDependencies": {
@@ -42,5 +61,8 @@
"ai": {
"optional": true
}
+ },
+ "engines": {
+ "node": ">=20.0.0"
}
}
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index 0232463..ca314e0 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -1,4 +1,3 @@
-import { createError } from 'evlog'
import type {
AgentConfig,
SavoirConfig,
@@ -21,11 +20,10 @@ export class SavoirClient {
constructor(config: SavoirConfig) {
if (!config.apiUrl) {
- throw createError({
- message: 'Missing apiUrl in Savoir configuration',
- why: 'The Savoir SDK requires an API URL to connect to',
- fix: 'Set SAVOIR_API_URL environment variable or pass apiUrl to createSavoir()',
- })
+ throw new Error(
+ 'Missing apiUrl in Savoir configuration. ' +
+ 'Set SAVOIR_API_URL environment variable or pass apiUrl to createSavoir()',
+ )
}
this.apiUrl = config.apiUrl.replace(/\/$/, '')