Skip to content

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

feat: improve overall logging pattern using evlog (#35)

Hugo1581c213e6ce
diff --git a/apps/chat/app/assets/icons/custom/sparkle.svg b/apps/chat/app/assets/icons/custom/sparkle.svg
new file mode 100644
index 0000000..30c645f
--- /dev/null
+++ b/apps/chat/app/assets/icons/custom/sparkle.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><g class="nc-icon-wrapper" fill="currentColor"><path d="M3.025,5.623c.068,.204,.26,.342,.475,.342s.406-.138,.475-.342l.421-1.263,1.263-.421c.204-.068,.342-.259,.342-.474s-.138-.406-.342-.474l-1.263-.421-.421-1.263c-.137-.408-.812-.408-.949,0l-.421,1.263-1.263,.421c-.204,.068-.342,.259-.342,.474s.138,.406,.342,.474l1.263,.421,.421,1.263Z" fill="currentColor" data-color="color-2"></path><path d="M16.525,8.803l-4.535-1.793-1.793-4.535c-.227-.572-1.168-.572-1.395,0l-1.793,4.535-4.535,1.793c-.286,.113-.475,.39-.475,.697s.188,.584,.475,.697l4.535,1.793,1.793,4.535c.113,.286,.39,.474,.697,.474s.584-.188,.697-.474l1.793-4.535,4.535-1.793c.286-.113,.475-.39,.475-.697s-.188-.584-.475-.697Z" fill="currentColor"></path></g></svg>
\ No newline at end of file
diff --git a/apps/chat/app/components/SourceModal.vue b/apps/chat/app/components/SourceModal.vue
index cacbdf3..d2b709b 100644
--- a/apps/chat/app/components/SourceModal.vue
+++ b/apps/chat/app/components/SourceModal.vue
@@ -23,6 +23,7 @@ const emit = defineEmits<{
}>()
const toast = useToast()
+const { showError } = useErrorToast()
const isSubmitting = ref(false)
const isEditing = computed(() => !!props.source)
@@ -88,13 +89,8 @@ async function save() {
icon: 'i-lucide-check',
})
emit('saved')
- } catch (error: unknown) {
- toast.add({
- title: 'Error',
- description: error instanceof Error ? error.message : 'Failed to save source',
- color: 'error',
- icon: 'i-lucide-alert-circle',
- })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to save source' })
} finally {
isSubmitting.value = false
}
diff --git a/apps/chat/app/composables/useErrorToast.ts b/apps/chat/app/composables/useErrorToast.ts
new file mode 100644
index 0000000..87fefc2
--- /dev/null
+++ b/apps/chat/app/composables/useErrorToast.ts
@@ -0,0 +1,31 @@
+interface ShowErrorOptions {
+ fallback?: string
+ title?: string
+}
+
+function extractMessage(error: unknown): string {
+ if (error && typeof error === 'object') {
+ const e = error as Record<string, any>
+ if (e.data?.message) return e.data.message
+ if (e.message) return e.message
+ }
+ if (error instanceof Error) return error.message
+ return ''
+}
+
+export function useErrorToast() {
+ const toast = useToast()
+
+ function showError(error: unknown, options: ShowErrorOptions = {}) {
+ const message = extractMessage(error) || options.fallback || 'Something went wrong'
+ toast.add({
+ title: options.title || 'Error',
+ description: message,
+ color: 'error',
+ icon: 'i-lucide-alert-circle',
+ })
+ return message
+ }
+
+ return { showError }
+}
diff --git a/apps/chat/app/composables/useFileUpload.ts b/apps/chat/app/composables/useFileUpload.ts
index c7228bd..728aff6 100644
--- a/apps/chat/app/composables/useFileUpload.ts
+++ b/apps/chat/app/composables/useFileUpload.ts
@@ -23,6 +23,7 @@ function fileToInput(file: File): HTMLInputElement {
export function useFileUploadWithStatus(chatId: string) {
const files = shallowRef<FileWithStatus[]>([])
const toast = useToast()
+ const { showError } = useErrorToast()
const { loggedIn } = useUserSession()
const upload = useUpload(`/api/upload/${chatId}`, { method: 'PUT' })
@@ -66,15 +67,7 @@ export function useFileUploadWithStatus(chatId: string) {
uploadedPathname: result.pathname
})
} catch (error) {
- const errorMessage = (error as { data?: { message?: string } }).data?.message
- || (error as Error).message
- || 'Upload failed'
- toast.add({
- title: 'Upload failed',
- description: errorMessage,
- icon: 'i-lucide-alert-circle',
- color: 'error'
- })
+ const errorMessage = showError(error, { title: 'Upload failed', fallback: 'Upload failed' })
updateFileAt(fileWithStatus.id, {
status: 'error',
error: errorMessage
@@ -116,7 +109,7 @@ export function useFileUploadWithStatus(chatId: string) {
fetch(`/api/upload/${file.uploadedPathname}`, {
method: 'DELETE'
}).catch((error) => {
- console.error('Failed to delete file from blob:', error)
+ log.warn({ event: 'file.delete_failed', pathname: file.uploadedPathname, error: error instanceof Error ? error.message : 'Unknown' })
})
}
}
diff --git a/apps/chat/app/composables/useSnapshotSync.ts b/apps/chat/app/composables/useSnapshotSync.ts
index fcd2b96..c27a479 100644
--- a/apps/chat/app/composables/useSnapshotSync.ts
+++ b/apps/chat/app/composables/useSnapshotSync.ts
@@ -13,6 +13,7 @@ let pollInterval: ReturnType<typeof setInterval> | null = null
export function useSnapshotSync() {
const { isAdmin } = useAdmin()
const toast = useToast()
+ const { showError } = useErrorToast()
const needsSync = computed(() => status.value?.needsSync ?? false)
@@ -34,14 +35,7 @@ export function useSnapshotSync() {
await checkStatus(false)
} catch (e) {
- const message = (e as Error).message || 'Failed to sync snapshot'
- error.value = message
- toast.add({
- title: 'Sync failed',
- description: message,
- icon: 'i-lucide-alert-circle',
- color: 'error',
- })
+ error.value = showError(e, { title: 'Sync failed', fallback: 'Failed to sync snapshot' })
} finally {
isSyncing.value = false
}
@@ -61,7 +55,7 @@ export function useSnapshotSync() {
await syncNow()
}
} catch (e) {
- error.value = (e as Error).message || 'Failed to check snapshot status'
+ error.value = showError(e, { fallback: 'Failed to check snapshot status' })
} finally {
isLoading.value = false
}
diff --git a/apps/chat/app/pages/admin/agent.vue b/apps/chat/app/pages/admin/agent.vue
index 6352274..1209c06 100644
--- a/apps/chat/app/pages/admin/agent.vue
+++ b/apps/chat/app/pages/admin/agent.vue
@@ -2,6 +2,7 @@
useSeoMeta({ title: 'Assistant - Admin' })
const toast = useToast()
+const { showError } = useErrorToast()
interface AgentConfig {
id: string
@@ -117,13 +118,8 @@ async function saveConfig() {
icon: 'i-lucide-check',
})
await refresh()
- } catch (error: unknown) {
- toast.add({
- title: 'Error',
- description: error instanceof Error ? error.message : 'Failed to save configuration',
- color: 'error',
- icon: 'i-lucide-alert-circle',
- })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to save configuration' })
} finally {
isSaving.value = false
}
@@ -139,13 +135,8 @@ async function resetConfig() {
icon: 'i-lucide-check',
})
await refresh()
- } catch (error: unknown) {
- toast.add({
- title: 'Error',
- description: error instanceof Error ? error.message : 'Failed to reset configuration',
- color: 'error',
- icon: 'i-lucide-alert-circle',
- })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to reset configuration' })
} finally {
isResetting.value = false
}
diff --git a/apps/chat/app/pages/admin/api-keys.vue b/apps/chat/app/pages/admin/api-keys.vue
index c4fed8e..e9ba3b1 100644
--- a/apps/chat/app/pages/admin/api-keys.vue
+++ b/apps/chat/app/pages/admin/api-keys.vue
@@ -20,6 +20,7 @@ interface ApiKeyRow {
const toast = useToast()
const overlay = useOverlay()
+const { showError } = useErrorToast()
const { data: keys, refresh, status } = useLazyFetch<ApiKeyRow[]>('/api/admin/api-keys')
@@ -45,8 +46,8 @@ async function createAdminKey() {
newKeyName.value = ''
await refresh()
toast.add({ title: 'Admin API key created', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to create API key', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to create API key' })
} finally {
isCreating.value = false
}
@@ -61,8 +62,8 @@ async function revokeKey(id: string) {
await $fetch(`/api/admin/api-keys/${id}`, { method: 'DELETE' })
await refresh()
toast.add({ title: 'API key revoked', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to revoke API key', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to revoke API key' })
}
}
diff --git a/apps/chat/app/pages/admin/index.vue b/apps/chat/app/pages/admin/index.vue
index d3f7824..b255f97 100644
--- a/apps/chat/app/pages/admin/index.vue
+++ b/apps/chat/app/pages/admin/index.vue
@@ -26,6 +26,7 @@ interface SerializedSource {
const toast = useToast()
const overlay = useOverlay()
+const { showError } = useErrorToast()
const { data: sources, refresh, status } = useLazyFetch('/api/sources')
@@ -122,14 +123,9 @@ async function deleteSource(source: SerializedSource) {
title: 'Source deleted',
icon: 'i-lucide-check',
})
- } catch (error: unknown) {
+ } catch (e) {
sources.value = previousData
- toast.add({
- title: 'Error',
- description: error instanceof Error ? error.message : 'Failed to delete source',
- color: 'error',
- icon: 'i-lucide-alert-circle',
- })
+ showError(e, { fallback: 'Failed to delete source' })
}
}
@@ -146,13 +142,8 @@ async function triggerSync(sourceId?: string) {
icon: 'i-lucide-check',
})
await refresh()
- } catch (error: unknown) {
- toast.add({
- title: 'Error',
- description: error instanceof Error ? error.message : 'Failed to start sync',
- color: 'error',
- icon: 'i-lucide-alert-circle',
- })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to start sync' })
} finally {
isSyncingAll.value = false
}
diff --git a/apps/chat/app/pages/admin/logs.vue b/apps/chat/app/pages/admin/logs.vue
index 105937d..046432c 100644
--- a/apps/chat/app/pages/admin/logs.vue
+++ b/apps/chat/app/pages/admin/logs.vue
@@ -5,75 +5,224 @@ useSeoMeta({ title: 'Logs - Admin' })
const toast = useToast()
const overlay = useOverlay()
+const { showError } = useErrorToast()
+const router = useRouter()
-const { data: stats, refresh, status } = useLazyFetch<{ totalCount: number, oldestLog: string | null }>('/api/admin/logs')
+type LogStats = {
+ totalCount: number
+ oldestLog: string | null
+ newestLog: string | null
+ levelBreakdown: { level: string | null, count: number }[]
+ dailyVolume: { day: string, count: number }[]
+}
+
+const { data: stats, refresh, status } = useLazyFetch<LogStats>('/api/admin/logs/stats')
+
+const ALL_LEVELS = ['error', 'warn', 'info', 'debug'] as const
+
+const levelColors: Record<string, string> = {
+ info: 'text-blue-500',
+ warn: 'text-yellow-500',
+ error: 'text-red-500',
+ debug: 'text-muted',
+}
+
+const levelIcons: Record<string, string> = {
+ info: 'i-lucide-info',
+ warn: 'i-lucide-triangle-alert',
+ error: 'i-lucide-circle-x',
+ debug: 'i-lucide-bug',
+}
-const presets = [
- { label: '1 day', days: 1 },
- { label: '3 days', days: 3 },
- { label: '7 days', days: 7 },
- { label: '14 days', days: 14 },
- { label: '30 days', days: 30 },
+const normalizedLevels = computed(() => {
+ const breakdown = stats.value?.levelBreakdown ?? []
+ const map = Object.fromEntries(breakdown.map(r => [r.level ?? 'unknown', r.count]))
+ return ALL_LEVELS.map(level => ({ level, count: map[level] ?? 0 }))
+})
+
+const errorCount = computed(() => normalizedLevels.value.find(l => l.level === 'error')?.count ?? 0)
+
+// ─── Time unit toggle ────────────────────────────────────────────────────────
+
+type TimeUnit = 'hours' | 'days'
+const timeUnit = ref<TimeUnit>('days')
+
+const dayPresets = [
+ { label: '1d', value: 1 },
+ { label: '3d', value: 3 },
+ { label: '7d', value: 7 },
+ { label: '14d', value: 14 },
+ { label: '30d', value: 30 },
+ { label: '90d', value: 90 },
]
-const selectedDays = ref<number | null>(null)
+const hourPresets = [
+ { label: '1h', value: 1 },
+ { label: '6h', value: 6 },
+ { label: '12h', value: 12 },
+ { label: '24h', value: 24 },
+ { label: '48h', value: 48 },
+ { label: '72h', value: 72 },
+]
+
+const activePresets = computed(() => timeUnit.value === 'hours' ? hourPresets : dayPresets)
+
+// ─── Selection state ─────────────────────────────────────────────────────────
+
+const selectedPreset = ref<number | null>(null)
+const customValue = ref<number | null>(null)
+const selectedLevel = ref<string | null>(null)
const previewCount = ref<number | null>(null)
const isPreviewing = ref(false)
const isDeleting = ref(false)
+const isInvestigating = ref(false)
+
+function resetSelection() {
+ selectedPreset.value = null
+ customValue.value = null
+ previewCount.value = null
+}
+
+watch(timeUnit, resetSelection)
+
+const activeValue = computed(() => customValue.value ?? selectedPreset.value)
const cutoffDate = computed(() => {
- if (!selectedDays.value) return null
- return new Date(Date.now() - selectedDays.value * 24 * 60 * 60 * 1000).toISOString()
+ const v = activeValue.value
+ if (!v) return null
+ const ms = timeUnit.value === 'hours' ? v * 60 * 60 * 1000 : v * 24 * 60 * 60 * 1000
+ return new Date(Date.now() - ms).toISOString()
+})
+
+const cutoffLabel = computed(() => {
+ if (!cutoffDate.value) return ''
+ return new Date(cutoffDate.value).toLocaleString(undefined, {
+ year: 'numeric', month: 'short', day: 'numeric',
+ hour: timeUnit.value === 'hours' ? '2-digit' : undefined,
+ minute: timeUnit.value === 'hours' ? '2-digit' : undefined,
+ })
})
+const unitLabel = computed(() => timeUnit.value === 'hours' ? 'hour' : 'day')
+
+// ─── Chart ───────────────────────────────────────────────────────────────────
+
+const dailyChartData = computed(() => {
+ if (!stats.value?.dailyVolume?.length) return []
+ const vol = stats.value.dailyVolume
+ const maxVal = Math.max(...vol.map(d => d.count), 1)
+ return vol.slice(-60).map(d => ({
+ day: d.day,
+ count: d.count,
+ pct: Math.max(2, Math.round((d.count / maxVal) * 100)),
+ }))
+})
+
+// ─── Delete modal ────────────────────────────────────────────────────────────
+
const deleteModal = overlay.create(LazyModalConfirm, {
- props: {
- title: 'Delete logs',
- description: '',
- },
+ props: { title: 'Delete logs', description: '' },
})
-async function preview(days: number) {
- selectedDays.value = days
+// ─── Actions ─────────────────────────────────────────────────────────────────
+
+async function runPreview() {
+ if (!activeValue.value) return
previewCount.value = null
isPreviewing.value = true
try {
- const before = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString()
- const result = await $fetch<{ count: number }>('/api/admin/logs/count', { query: { before } })
+ const query: Record<string, string> = { before: cutoffDate.value! }
+ if (selectedLevel.value) query.level = selectedLevel.value
+ const result = await $fetch<{ count: number }>('/api/admin/logs/count', { query })
previewCount.value = result.count
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || 'Failed to count logs', color: 'error', icon: 'i-lucide-alert-circle' })
- selectedDays.value = null
+ } catch (e) {
+ showError(e, { fallback: 'Failed to count logs' })
+ resetSelection()
} finally {
isPreviewing.value = false
}
}
+function selectPreset(value: number) {
+ customValue.value = null
+ selectedPreset.value = value
+ runPreview()
+}
+
+watch(customValue, (val) => {
+ if (val && val > 0) {
+ selectedPreset.value = null
+ runPreview()
+ } else if (!val) {
+ previewCount.value = null
+ }
+})
+
+watch(selectedLevel, () => {
+ if (activeValue.value) runPreview()
+})
+
async function deleteLogs() {
if (!cutoffDate.value || previewCount.value === null) return
+ const levelLabel = selectedLevel.value ? ` (level: ${selectedLevel.value})` : ''
const instance = deleteModal.open({
- description: `This will permanently delete ${previewCount.value.toLocaleString()} log entries older than ${selectedDays.value} days. This cannot be undone.`,
+ description: `This will permanently delete ${previewCount.value.toLocaleString()} log entries older than ${activeValue.value} ${unitLabel.value}${activeValue.value === 1 ? '' : 's'}${levelLabel}. This cannot be undone.`,
})
const confirmed = await instance.result
if (!confirmed) return
isDeleting.value = true
try {
+ const body: Record<string, string> = { before: cutoffDate.value }
+ if (selectedLevel.value) body.level = selectedLevel.value
const result = await $fetch<{ deletedCount: number }>('/api/admin/logs', {
method: 'DELETE',
- body: { before: cutoffDate.value },
+ body,
})
toast.add({ title: `${result.deletedCount.toLocaleString()} logs deleted`, icon: 'i-lucide-check' })
- selectedDays.value = null
- previewCount.value = null
+ resetSelection()
await refresh()
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || 'Failed to delete logs', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to delete logs' })
} finally {
isDeleting.value = false
}
}
+
+async function investigateErrors() {
+ isInvestigating.value = true
+ try {
+ const chatId = crypto.randomUUID()
+ const messageId = crypto.randomUUID()
+ const errorText = errorCount.value > 0
+ ? `There are currently **${errorCount.value.toLocaleString()} errors** in production logs`
+ : 'There may be errors in production logs'
+
+ await $fetch('/api/chats', {
+ method: 'POST',
+ body: {
+ id: chatId,
+ mode: 'admin',
+ message: {
+ id: messageId,
+ role: 'user',
+ parts: [
+ {
+ type: 'text',
+ text: `${errorText}. Please investigate — use \`query_errors\` to identify error patterns and \`query_logs\` to dig into the most recent failures. Summarize what's going wrong and suggest next steps.`,
+ }
+ ],
+ },
+ },
+ })
+ refreshNuxtData('chats')
+ await router.push(`/chat/${chatId}`)
+ } catch (e) {
+ showError(e, { fallback: 'Failed to create chat' })
+ isInvestigating.value = false
+ }
+}
</script>
<template>
@@ -88,53 +237,186 @@ async function deleteLogs() {
</header>
<div class="space-y-6">
+ <!-- AI error suggestion -->
+ <div
+ v-if="status !== 'pending' && errorCount > 0"
+ class="flex items-center justify-between gap-4 rounded-lg border border-red-500/20 bg-red-500/5 px-4 py-3"
+ >
+ <div class="flex items-center gap-3 min-w-0">
+ <UIcon name="i-lucide-circle-x" class="size-4 text-red-500 shrink-0" />
+ <p class="text-sm text-highlighted truncate">
+ <span class="font-medium tabular-nums">{{ errorCount.toLocaleString() }}</span>
+ <span class="text-muted"> error{{ errorCount === 1 ? '' : 's' }} in production logs</span>
+ </p>
+ </div>
+ <UButton
+ label="Investigate with AI"
+ icon="i-custom-sparkle"
+ color="error"
+ variant="soft"
+ size="xs"
+ :loading="isInvestigating"
+ class="shrink-0"
+ @click="investigateErrors"
+ />
+ </div>
+
<section>
<h2 class="text-[10px] text-muted uppercase tracking-wide mb-3 font-pixel">
Overview
</h2>
- <div class="rounded-lg border border-default p-4">
+ <div class="rounded-lg border border-default p-4 space-y-4">
<template v-if="status === 'pending'">
<USkeleton class="h-8 w-40 mb-2" />
- <USkeleton class="h-4 w-56" />
+ <USkeleton class="h-4 w-56 mb-4" />
+ <div class="grid grid-cols-4 gap-2">
+ <USkeleton v-for="i in 4" :key="i" class="h-14 rounded-md" />
+ </div>
</template>
<template v-else-if="stats">
- <p class="text-2xl font-medium text-highlighted tabular-nums">
- {{ stats.totalCount.toLocaleString() }}
- </p>
- <p class="text-sm text-muted mt-1">
- total log entries
- <span v-if="stats.oldestLog"> · oldest from {{ new Date(stats.oldestLog).toLocaleDateString() }}</span>
- </p>
+ <div>
+ <p class="text-2xl font-medium text-highlighted tabular-nums">
+ {{ stats.totalCount.toLocaleString() }}
+ </p>
+ <p class="text-sm text-muted mt-0.5">
+ total log entries
+ <template v-if="stats.oldestLog">
+ · from {{ new Date(stats.oldestLog).toLocaleDateString() }}
+ <template v-if="stats.newestLog">
+ to {{ new Date(stats.newestLog).toLocaleDateString() }}
+ </template>
+ </template>
+ </p>
+ </div>
+
+ <!-- Level breakdown — always show all 4 levels -->
+ <div class="grid grid-cols-2 gap-2 sm:grid-cols-4">
+ <div
+ v-for="item in normalizedLevels"
+ :key="item.level"
+ class="rounded-md bg-elevated px-3 py-2"
+ >
+ <div class="flex items-center gap-1.5 mb-1">
+ <UIcon
+ :name="levelIcons[item.level]!"
+ :class="[levelColors[item.level], 'size-3']"
+ />
+ <span class="text-[11px] text-muted capitalize">{{ item.level }}</span>
+ </div>
+ <p class="text-sm font-medium tabular-nums" :class="item.count > 0 ? 'text-highlighted' : 'text-muted'">
+ {{ item.count.toLocaleString() }}
+ </p>
+ </div>
+ </div>
+
+ <!-- Daily volume chart -->
+ <div v-if="dailyChartData.length">
+ <p class="text-[11px] text-muted mb-2">
+ Daily volume (last {{ Math.min(dailyChartData.length, 60) }} days)
+ </p>
+ <div class="flex items-end gap-px h-12 overflow-hidden rounded">
+ <div
+ v-for="d in dailyChartData"
+ :key="d.day"
+ class="flex-1 min-w-0 bg-primary/40 hover:bg-primary/70 transition-colors rounded-sm cursor-default"
+ :style="{ height: `${d.pct}%` }"
+ :title="`${d.day}: ${d.count.toLocaleString()} logs`"
+ />
+ </div>
+ </div>
</template>
</div>
</section>
+ <!-- Clean up -->
<section>
<h2 class="text-[10px] text-muted uppercase tracking-wide mb-3 font-pixel">
Clean up
</h2>
<div class="rounded-lg border border-default p-4 space-y-4">
- <p class="text-sm text-muted">
- Delete logs older than:
- </p>
- <div class="flex flex-wrap gap-2">
+ <!-- Level filter -->
+ <div class="flex items-center gap-3 flex-wrap">
+ <span class="text-sm text-muted shrink-0">Level:</span>
+ <div class="flex flex-wrap gap-1.5">
+ <UButton
+ label="All"
+ size="xs"
+ :color="selectedLevel === null ? 'primary' : 'neutral'"
+ :variant="selectedLevel === null ? 'solid' : 'ghost'"
+ @click="selectedLevel = null"
+ />
+ <UButton
+ v-for="level in ALL_LEVELS"
+ :key="level"
+ :label="level"
+ size="xs"
+ :color="selectedLevel === level ? 'primary' : 'neutral'"
+ :variant="selectedLevel === level ? 'solid' : 'ghost'"
+ class="capitalize"
+ @click="selectedLevel = level"
+ />
+ </div>
+ </div>
+
+ <!-- Time unit toggle -->
+ <div class="flex items-center gap-3">
+ <span class="text-sm text-muted shrink-0">Delete older than:</span>
+ <div class="flex rounded-md border border-default overflow-hidden">
+ <button
+ v-for="unit in (['hours', 'days'] as TimeUnit[])"
+ :key="unit"
+ class="px-3 py-1 text-xs capitalize transition-colors"
+ :class="timeUnit === unit ? 'bg-primary text-white' : 'text-muted hover:text-highlighted hover:bg-elevated'"
+ @click="timeUnit = unit"
+ >
+ {{ unit }}
+ </button>
+ </div>
+ </div>
+
+ <!-- Presets + custom -->
+ <div class="flex flex-wrap items-center gap-2">
<UButton
- v-for="preset in presets"
- :key="preset.days"
+ v-for="preset in activePresets"
+ :key="preset.value"
:label="preset.label"
size="xs"
- :color="selectedDays === preset.days ? 'primary' : 'neutral'"
- :variant="selectedDays === preset.days ? 'solid' : 'soft'"
- :loading="isPreviewing && selectedDays === preset.days"
- @click="preview(preset.days)"
+ :color="selectedPreset === preset.value && !customValue ? 'primary' : 'neutral'"
+ :variant="selectedPreset === preset.value && !customValue ? 'solid' : 'soft'"
+ :loading="isPreviewing && selectedPreset === preset.value && !customValue"
+ @click="selectPreset(preset.value)"
/>
+ <div class="flex items-center gap-1.5">
+ <UInput
+ v-model="customValue"
+ type="number"
+ :placeholder="`Custom ${timeUnit === 'hours' ? 'hours' : 'days'}`"
+ size="xs"
+ :min="1"
+ :max="timeUnit === 'hours' ? 8760 : 3650"
+ class="w-36"
+ />
+ </div>
</div>
- <div v-if="previewCount !== null && selectedDays" class="flex items-center justify-between gap-4 rounded-md bg-elevated px-4 py-3">
- <p class="text-sm">
- <span class="text-highlighted font-medium tabular-nums">{{ previewCount.toLocaleString() }}</span>
- <span class="text-muted"> logs older than {{ selectedDays }} days</span>
- </p>
+ <!-- Preview result -->
+ <div
+ v-if="previewCount !== null && activeValue"
+ class="flex items-center justify-between gap-4 rounded-md bg-elevated px-4 py-3"
+ >
+ <div>
+ <p class="text-sm">
+ <span class="text-highlighted font-medium tabular-nums">{{ previewCount.toLocaleString() }}</span>
+ <span class="text-muted">
+ {{ selectedLevel ? ` ${selectedLevel}` : '' }}
+ {{ previewCount === 1 ? ' log' : ' logs' }} older than
+ {{ activeValue }} {{ unitLabel }}{{ activeValue === 1 ? '' : 's' }}
+ </span>
+ </p>
+ <p v-if="cutoffLabel" class="text-[11px] text-muted mt-0.5">
+ Before {{ cutoffLabel }}
+ </p>
+ </div>
<UButton
v-if="previewCount > 0"
label="Delete"
@@ -143,6 +425,12 @@ async function deleteLogs() {
:loading="isDeleting"
@click="deleteLogs"
/>
+ <span v-else class="text-xs text-muted italic">Nothing to delete</span>
+ </div>
+
+ <div v-else-if="isPreviewing" class="flex items-center gap-2 text-sm text-muted">
+ <UIcon name="i-lucide-loader-circle" class="size-3.5 animate-spin" />
+ Counting logs…
</div>
</div>
</section>
diff --git a/apps/chat/app/pages/admin/new.vue b/apps/chat/app/pages/admin/new.vue
index db38f11..3d03ce6 100644
--- a/apps/chat/app/pages/admin/new.vue
+++ b/apps/chat/app/pages/admin/new.vue
@@ -34,6 +34,7 @@ const CONFIG_ACCEPT = CONFIG_EXTENSIONS.join(',')
const router = useRouter()
const route = useRoute()
const toast = useToast()
+const { showError } = useErrorToast()
const { data: sourcesData } = useLazyFetch('/api/sources')
const youtubeEnabled = computed(() => sourcesData.value?.youtubeEnabled ?? false)
@@ -201,13 +202,8 @@ async function extractAll() {
icon: 'i-lucide-alert-circle',
})
}
- } catch (error) {
- toast.add({
- title: 'Extraction failed',
- description: error instanceof Error ? error.message : 'Failed to extract sources',
- color: 'error',
- icon: 'i-lucide-alert-circle',
- })
+ } catch (e) {
+ showError(e, { title: 'Extraction failed', fallback: 'Failed to extract sources' })
} finally {
isExtracting.value = false
}
diff --git a/apps/chat/app/pages/admin/users.vue b/apps/chat/app/pages/admin/users.vue
index 870967c..fd2ba32 100644
--- a/apps/chat/app/pages/admin/users.vue
+++ b/apps/chat/app/pages/admin/users.vue
@@ -16,6 +16,7 @@ interface AdminUserRow {
}
const toast = useToast()
+const { showError } = useErrorToast()
const { user: currentUser } = useUserSession()
const searchQuery = ref('')
@@ -94,14 +95,9 @@ async function saveRole(row: AdminUserRow) {
title: 'Role updated',
icon: 'i-lucide-check',
})
- } catch (error: any) {
+ } catch (e) {
draftRoles.value[row.id] = row.role
- toast.add({
- title: 'Error',
- description: error?.data?.message || error?.message || 'Failed to update role',
- color: 'error',
- icon: 'i-lucide-alert-circle',
- })
+ showError(e, { fallback: 'Failed to update role' })
} finally {
savingUserId.value = null
}
diff --git a/apps/chat/app/pages/chat/[id].vue b/apps/chat/app/pages/chat/[id].vue
index 801cbbb..8c1bc6c 100644
--- a/apps/chat/app/pages/chat/[id].vue
+++ b/apps/chat/app/pages/chat/[id].vue
@@ -16,6 +16,7 @@ const components = {
const route = useRoute()
const toast = useToast()
+const { showError } = useErrorToast()
const clipboard = useClipboard()
const { model } = useModels()
const { setMode } = useChatMode()
@@ -137,13 +138,9 @@ async function toggleFeedback(_e: MouseEvent, message: UIMessage, type: 'positiv
method: 'PATCH',
body: { feedback: newFeedback }
})
- } catch {
+ } catch (e) {
feedbackMap.value = { ...feedbackMap.value, [message.id]: currentFeedback }
- toast.add({
- description: 'Failed to save feedback',
- icon: 'i-lucide-alert-circle',
- color: 'error'
- })
+ showError(e, { fallback: 'Failed to save feedback' })
}
}
diff --git a/apps/chat/app/pages/settings/api-keys.vue b/apps/chat/app/pages/settings/api-keys.vue
index adaaebf..55bc7a4 100644
--- a/apps/chat/app/pages/settings/api-keys.vue
+++ b/apps/chat/app/pages/settings/api-keys.vue
@@ -7,6 +7,7 @@ useSeoMeta({ title: 'API Keys' })
const toast = useToast()
const overlay = useOverlay()
+const { showError } = useErrorToast()
const { client } = useUserSession()
const { data: keys, refresh, status } = useLazyAsyncData('user-api-keys', () => client!.apiKey.list())
@@ -31,8 +32,8 @@ async function createKey() {
newKeyName.value = ''
await refresh()
toast.add({ title: 'API key created', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to create API key', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to create API key' })
} finally {
isCreating.value = false
}
@@ -47,8 +48,8 @@ async function revokeKey(keyId: string) {
await client!.apiKey.delete({ keyId })
await refresh()
toast.add({ title: 'API key revoked', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to revoke API key', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to revoke API key' })
}
}
diff --git a/apps/chat/app/pages/settings/index.vue b/apps/chat/app/pages/settings/index.vue
index 760ce3e..4b02a2f 100644
--- a/apps/chat/app/pages/settings/index.vue
+++ b/apps/chat/app/pages/settings/index.vue
@@ -7,6 +7,7 @@ useSeoMeta({ title: 'Settings' })
const toast = useToast()
const overlay = useOverlay()
+const { showError } = useErrorToast()
const { client, user, session, signOut, fetchSession } = useUserSession()
const nameInput = ref(user.value?.name ?? '')
@@ -22,8 +23,8 @@ async function saveProfile() {
await client!.updateUser({ name: nameInput.value })
await fetchSession({ force: true })
toast.add({ title: 'Profile updated', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to update profile', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to update profile' })
} finally {
isSavingProfile.value = false
}
@@ -40,8 +41,8 @@ async function changePassword() {
currentPassword.value = ''
newPassword.value = ''
toast.add({ title: 'Password changed', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to change password', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to change password' })
} finally {
isChangingPassword.value = false
}
@@ -59,8 +60,8 @@ async function linkGithub() {
isLinkingGithub.value = true
try {
await client!.linkSocial({ provider: 'github' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to link GitHub', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to link GitHub' })
isLinkingGithub.value = false
}
}
@@ -71,8 +72,8 @@ async function unlinkGithub() {
await client!.unlinkAccount({ providerId: 'github' })
await refreshAccounts()
toast.add({ title: 'GitHub account unlinked', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to unlink account', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to unlink account' })
} finally {
isUnlinking.value = false
}
@@ -88,8 +89,8 @@ async function revokeSession(token: string) {
await client!.revokeSession({ token })
await refreshSessions()
toast.add({ title: 'Session revoked', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to revoke session', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to revoke session' })
} finally {
revokingSession.value = null
}
@@ -101,8 +102,8 @@ async function revokeOtherSessions() {
await client!.revokeOtherSessions()
await refreshSessions()
toast.add({ title: 'Other sessions revoked', icon: 'i-lucide-check' })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to revoke sessions', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to revoke sessions' })
} finally {
isRevokingAll.value = false
}
@@ -128,8 +129,8 @@ async function deleteAccount() {
await client!.deleteUser()
await signOut()
await navigateTo('/login', { replace: true, external: true })
- } catch (e: any) {
- toast.add({ title: 'Error', description: e?.data?.message || e?.message || 'Failed to delete account', color: 'error', icon: 'i-lucide-alert-circle' })
+ } catch (e) {
+ showError(e, { fallback: 'Failed to delete account' })
isDeletingAccount.value = false
}
}
diff --git a/apps/chat/nuxt.config.ts b/apps/chat/nuxt.config.ts
index d3452b7..62b3512 100644
--- a/apps/chat/nuxt.config.ts
+++ b/apps/chat/nuxt.config.ts
@@ -27,6 +27,32 @@ export default defineNuxtConfig({
service: 'savoir',
version: '0.1.0',
},
+ routes: {
+ '/api/admin/**': { service: 'admin-api' },
+ '/api/webhooks/**': { service: 'webhook-api' },
+ '/api/sync/**': { service: 'sync-api' },
+ '/api/sandbox/**': { service: 'sandbox-api' },
+ '/api/stats/**': { service: 'stats-api' },
+ },
+ transport: { enabled: true },
+ },
+
+ $production: {
+ evlog: {
+ sampling: {
+ rates: {
+ debug: 0,
+ info: 10,
+ warn: 50,
+ },
+ keep: [
+ { status: 400 },
+ { duration: 2000 },
+ { path: '/api/webhooks/**' },
+ { path: '/api/sandbox/**' },
+ ],
+ },
+ },
},
devtools: { enabled: true },
diff --git a/apps/chat/server/api/admin/api-keys.post.ts b/apps/chat/server/api/admin/api-keys.post.ts
index b5e74e4..abcb909 100644
--- a/apps/chat/server/api/admin/api-keys.post.ts
+++ b/apps/chat/server/api/admin/api-keys.post.ts
@@ -5,9 +5,12 @@ const bodySchema = z.object({
})
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { user } = await requireAdmin(event)
const body = await readValidatedBody(event, bodySchema.parse)
+ requestLog.set({ adminUserId: user.id, keyName: body.name || 'Admin key' })
+
const auth = serverAuth(event)
const result = await auth.api.createApiKey({
body: {
diff --git a/apps/chat/server/api/admin/api-keys/[id].delete.ts b/apps/chat/server/api/admin/api-keys/[id].delete.ts
index 302f89a..81afa77 100644
--- a/apps/chat/server/api/admin/api-keys/[id].delete.ts
+++ b/apps/chat/server/api/admin/api-keys/[id].delete.ts
@@ -2,13 +2,16 @@ import { db, schema } from '@nuxthub/db'
import { eq } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
- await requireAdmin(event)
+ const requestLog = useLogger(event)
+ const { user } = await requireAdmin(event)
const id = getRouterParam(event, 'id')
if (!id) {
- throw createError({ statusCode: 400, message: 'Missing API key ID' })
+ throw createError({ statusCode: 400, message: 'Missing API key ID', data: { why: 'The API key ID parameter is required in the URL', fix: 'Include the API key ID in the request URL: /api/admin/api-keys/:id' } })
}
+ requestLog.set({ adminUserId: user.id, apiKeyId: id })
+
await db.delete(schema.apikey).where(eq(schema.apikey.id, id))
return { deleted: true }
diff --git a/apps/chat/server/api/admin/logs.delete.ts b/apps/chat/server/api/admin/logs.delete.ts
index f4cc433..ce4df7a 100644
--- a/apps/chat/server/api/admin/logs.delete.ts
+++ b/apps/chat/server/api/admin/logs.delete.ts
@@ -1,18 +1,28 @@
import { db, schema } from '@nuxthub/db'
-import { lt, count } from 'drizzle-orm'
+import { lt, and, eq, count } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
- const { before } = await readBody<{ before: string }>(event)
- if (!before) {
- throw createError({ statusCode: 400, message: 'Missing "before" field (ISO date)' })
+ const body = await readBody<{ before: string, level?: string }>(event)
+ if (!body.before) {
+ throw createError({ statusCode: 400, message: 'Missing "before" field (ISO date)', data: { why: 'A cutoff date is required to determine which logs to delete', fix: 'Include a "before" field with an ISO date string in the request body' } })
}
- const [countResult] = await db.select({ count: count() }).from(schema.evlogEvents).where(lt(schema.evlogEvents.timestamp, before))
+ const e = schema.evlogEvents
+ const conditions = [lt(e.timestamp, body.before)]
+ if (body.level && ['info', 'warn', 'error', 'debug'].includes(body.level)) {
+ conditions.push(eq(e.level, body.level as 'info' | 'warn' | 'error' | 'debug'))
+ }
+ const where = and(...conditions)
+
+ const [countResult] = await db.select({ count: count() }).from(e).where(where)
const deletedCount = Number(countResult?.count ?? 0)
- await db.delete(schema.evlogEvents).where(lt(schema.evlogEvents.timestamp, before))
+ await db.delete(e).where(where)
+
+ requestLog.set({ before: body.before, level: body.level, deletedCount })
return { deletedCount }
})
diff --git a/apps/chat/server/api/admin/users.get.ts b/apps/chat/server/api/admin/users.get.ts
index 88c3864..b4b65b6 100644
--- a/apps/chat/server/api/admin/users.get.ts
+++ b/apps/chat/server/api/admin/users.get.ts
@@ -2,6 +2,7 @@ import { db, schema } from '@nuxthub/db'
import { desc } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const [users, chats, messages] = await Promise.all([
@@ -59,6 +60,8 @@ export default defineEventHandler(async (event) => {
}
}
+ requestLog.set({ userCount: users.length })
+
return users.map(user => ({
id: user.id,
name: user.name,
diff --git a/apps/chat/server/api/admin/users/[id].patch.ts b/apps/chat/server/api/admin/users/[id].patch.ts
index cfbffeb..210e49b 100644
--- a/apps/chat/server/api/admin/users/[id].patch.ts
+++ b/apps/chat/server/api/admin/users/[id].patch.ts
@@ -7,17 +7,20 @@ const bodySchema = z.object({
})
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { user: currentUser } = await requireAdmin(event)
const id = getRouterParam(event, 'id')
if (!id) {
- throw createError({ statusCode: 400, message: 'Missing user ID' })
+ throw createError({ statusCode: 400, message: 'Missing user ID', data: { why: 'The user ID parameter is required in the URL', fix: 'Include the user ID in the request URL: /api/admin/users/:id' } })
}
const body = await readValidatedBody(event, bodySchema.parse)
+ requestLog.set({ adminUserId: currentUser.id, targetUserId: id, role: body.role })
+
if (id === currentUser.id && body.role !== 'admin') {
- throw createError({ statusCode: 400, message: 'You cannot remove your own admin role' })
+ throw createError({ statusCode: 400, message: 'You cannot remove your own admin role', data: { why: 'Removing your own admin role would lock you out of admin features', fix: 'Ask another admin to change your role instead' } })
}
const [existingUser] = await db
@@ -27,7 +30,7 @@ export default defineEventHandler(async (event) => {
.limit(1)
if (!existingUser) {
- throw createError({ statusCode: 404, message: 'User not found' })
+ throw createError({ statusCode: 404, message: 'User not found', data: { why: 'No user exists with this ID', fix: 'Verify the user ID from the users list' } })
}
await db
diff --git a/apps/chat/server/api/agent-config/index.put.ts b/apps/chat/server/api/agent-config/index.put.ts
index e021002..50f8c60 100644
--- a/apps/chat/server/api/agent-config/index.put.ts
+++ b/apps/chat/server/api/agent-config/index.put.ts
@@ -19,9 +19,12 @@ const bodySchema = z.object({
* Update the active agent configuration (admin only)
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const body = await readValidatedBody(event, bodySchema.parse)
+ requestLog.set({ fieldsChanged: Object.keys(body) })
+
const existing = await db.query.agentConfig.findFirst({
where: () => eq(schema.agentConfig.isActive, true),
})
@@ -60,5 +63,7 @@ export default defineEventHandler(async (event) => {
invalidateAgentConfigCache()
+ requestLog.set({ configId: config?.id })
+
return config
})
diff --git a/apps/chat/server/api/agent-config/reset.post.ts b/apps/chat/server/api/agent-config/reset.post.ts
index d2a549c..8221805 100644
--- a/apps/chat/server/api/agent-config/reset.post.ts
+++ b/apps/chat/server/api/agent-config/reset.post.ts
@@ -7,6 +7,7 @@ import { invalidateAgentConfigCache, getDefaultAgentConfig } from '../../utils/a
* Reset agent configuration to defaults (admin only)
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const defaults = getDefaultAgentConfig()
@@ -56,5 +57,7 @@ export default defineEventHandler(async (event) => {
invalidateAgentConfigCache()
+ requestLog.set({ configId: config?.id })
+
return config
})
diff --git a/apps/chat/server/api/chats.post.ts b/apps/chat/server/api/chats.post.ts
index e05e88c..01a7d95 100644
--- a/apps/chat/server/api/chats.post.ts
+++ b/apps/chat/server/api/chats.post.ts
@@ -3,6 +3,7 @@ import { db, schema } from '@nuxthub/db'
import { z } from 'zod'
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { user } = await requireUserSession(event)
const { id, mode, message } = await readValidatedBody(event, z.object({
id: z.string(),
@@ -10,8 +11,10 @@ export default defineEventHandler(async (event) => {
message: z.custom<UIMessage>()
}).parse)
+ requestLog.set({ userId: user.id, chatId: id, mode })
+
if (mode === 'admin' && user.role !== 'admin') {
- throw createError({ statusCode: 403, statusMessage: 'Admin access required' })
+ throw createError({ statusCode: 403, statusMessage: 'Admin access required', data: { why: 'Admin chat mode requires the admin role', fix: 'Contact an administrator to be granted access' } })
}
const [chat] = await db.insert(schema.chats).values({
@@ -22,7 +25,7 @@ export default defineEventHandler(async (event) => {
}).returning()
if (!chat) {
- throw createError({ statusCode: 500, statusMessage: 'Failed to create chat' })
+ throw createError({ statusCode: 500, statusMessage: 'Failed to create chat', data: { why: 'The database insert did not return the created chat', fix: 'Try again or check server logs for database errors' } })
}
await db.insert(schema.messages).values({
diff --git a/apps/chat/server/api/chats/[id].delete.ts b/apps/chat/server/api/chats/[id].delete.ts
index 8c93771..cae674c 100644
--- a/apps/chat/server/api/chats/[id].delete.ts
+++ b/apps/chat/server/api/chats/[id].delete.ts
@@ -8,9 +8,12 @@ const paramsSchema = z.object({
})
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { user } = await requireUserSession(event)
const { id } = await getValidatedRouterParams(event, paramsSchema.parse)
+ requestLog.set({ chat: { id }, user: { id: user.id } })
+
const chat = await db.query.chats.findFirst({
where: () => and(eq(schema.chats.id, id), eq(schema.chats.userId, user.id))
})
@@ -18,7 +21,8 @@ export default defineEventHandler(async (event) => {
if (!chat) {
throw createError({
statusCode: 404,
- statusMessage: 'Chat not found'
+ statusMessage: 'Chat not found',
+ data: { why: 'No chat exists with this ID for your user account', fix: 'Verify the chat ID is correct' },
})
}
@@ -33,13 +37,13 @@ export default defineEventHandler(async (event) => {
await Promise.all(
blobs.map(b =>
blob.del(b.pathname).catch(error =>
- console.error('[delete-chat] Failed to delete file:', b.pathname, error)
+ log.warn({ event: 'chat.delete.file_failed', pathname: b.pathname, error: error instanceof Error ? error.message : 'Unknown' })
)
)
)
}
} catch (error) {
- console.error('Failed to list/delete chat files:', error)
+ log.warn({ event: 'chat.delete.blob_cleanup_failed', chatId: id, error: error instanceof Error ? error.message : 'Unknown' })
}
return await db.delete(schema.chats)
diff --git a/apps/chat/server/api/chats/[id].get.ts b/apps/chat/server/api/chats/[id].get.ts
index 277aa56..0042999 100644
--- a/apps/chat/server/api/chats/[id].get.ts
+++ b/apps/chat/server/api/chats/[id].get.ts
@@ -7,9 +7,12 @@ const paramsSchema = z.object({
})
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { user } = await requireUserSession(event)
const { id } = await getValidatedRouterParams(event, paramsSchema.parse)
+ requestLog.set({ chatId: id })
+
const chat = await db.query.chats.findFirst({
where: () => and(
eq(schema.chats.id, id),
@@ -23,8 +26,10 @@ export default defineEventHandler(async (event) => {
})
if (!chat) {
- throw createError({ statusCode: 404, statusMessage: 'Chat not found' })
+ throw createError({ statusCode: 404, statusMessage: 'Chat not found', data: { why: 'No chat exists with this ID for your user account', fix: 'Verify the chat ID is correct' } })
}
+ requestLog.set({ messageCount: chat.messages.length })
+
return chat
})
diff --git a/apps/chat/server/api/chats/[id].post.ts b/apps/chat/server/api/chats/[id].post.ts
index f6755f6..ad1da3f 100644
--- a/apps/chat/server/api/chats/[id].post.ts
+++ b/apps/chat/server/api/chats/[id].post.ts
@@ -54,14 +54,14 @@ export default defineEventHandler(async (event) => {
if (!chat) {
requestLog.error(new Error('Chat not found'))
requestLog.set({ outcome: 'error' })
- throw createError({ statusCode: 404, statusMessage: 'Chat not found' })
+ throw createError({ statusCode: 404, statusMessage: 'Chat not found', data: { why: 'No chat exists with this ID for your user account', fix: 'Verify the chat ID is correct' } })
}
requestLog.set({ existingMessages: chat.messages.length, chatMode: chat.mode })
const isAdminChat = chat.mode === 'admin'
if (isAdminChat && user.role !== 'admin') {
- throw createError({ statusCode: 403, statusMessage: 'Admin access required' })
+ throw createError({ statusCode: 403, statusMessage: 'Admin access required', data: { why: 'This chat is in admin mode and requires the admin role', fix: 'Contact an administrator to be granted access' } })
}
const lastMessage = messages[messages.length - 1]
diff --git a/apps/chat/server/api/chats/[id]/share.patch.ts b/apps/chat/server/api/chats/[id]/share.patch.ts
index a5e25fb..0dbfbd7 100644
--- a/apps/chat/server/api/chats/[id]/share.patch.ts
+++ b/apps/chat/server/api/chats/[id]/share.patch.ts
@@ -7,6 +7,7 @@ const paramsSchema = z.object({
})
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { user } = await requireUserSession(event)
const { id } = await getValidatedRouterParams(event, paramsSchema.parse)
@@ -14,6 +15,8 @@ export default defineEventHandler(async (event) => {
isPublic: z.boolean()
}).parse)
+ requestLog.set({ chatId: id, isPublic })
+
const chat = await db.query.chats.findFirst({
where: () => and(
eq(schema.chats.id, id),
@@ -24,7 +27,8 @@ export default defineEventHandler(async (event) => {
if (!chat) {
throw createError({
statusCode: 404,
- statusMessage: 'Chat not found'
+ statusMessage: 'Chat not found',
+ data: { why: 'No chat exists with this ID for your user account', fix: 'Verify the chat ID is correct' },
})
}
diff --git a/apps/chat/server/api/messages/[id]/feedback.patch.ts b/apps/chat/server/api/messages/[id]/feedback.patch.ts
index c16f1e0..587269b 100644
--- a/apps/chat/server/api/messages/[id]/feedback.patch.ts
+++ b/apps/chat/server/api/messages/[id]/feedback.patch.ts
@@ -7,6 +7,7 @@ const paramsSchema = z.object({
})
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { user } = await requireUserSession(event)
const { id } = await getValidatedRouterParams(event, paramsSchema.parse)
@@ -14,6 +15,8 @@ export default defineEventHandler(async (event) => {
feedback: z.enum(['positive', 'negative']).nullable()
}).parse)
+ requestLog.set({ userId: user.id, messageId: id, feedback })
+
// 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),
@@ -25,14 +28,16 @@ export default defineEventHandler(async (event) => {
if (!message) {
throw createError({
statusCode: 404,
- statusMessage: 'Message not found'
+ statusMessage: 'Message not found',
+ data: { why: 'No message exists with this ID', fix: 'Verify the message ID is correct' },
})
}
if (message.chat.userId !== user.id) {
throw createError({
statusCode: 403,
- statusMessage: 'Forbidden'
+ statusMessage: 'Forbidden',
+ data: { why: 'This message belongs to another user\'s chat', fix: 'You can only provide feedback on messages in your own chats' },
})
}
@@ -40,7 +45,8 @@ export default defineEventHandler(async (event) => {
if (message.role !== 'assistant') {
throw createError({
statusCode: 400,
- statusMessage: 'Feedback can only be added to assistant messages'
+ statusMessage: 'Feedback can only be added to assistant messages',
+ data: { why: 'User messages cannot receive feedback', fix: 'Select an assistant message to provide feedback on' },
})
}
diff --git a/apps/chat/server/api/sandbox/shell.post.ts b/apps/chat/server/api/sandbox/shell.post.ts
index 083f5f6..85e5f23 100644
--- a/apps/chat/server/api/sandbox/shell.post.ts
+++ b/apps/chat/server/api/sandbox/shell.post.ts
@@ -22,6 +22,7 @@ function validateCommand(command: string): void {
throw createError({
statusCode: 400,
message: validation.reason,
+ data: { why: 'The command failed security validation', fix: 'Use only allowed commands within /vercel/sandbox' },
})
}
}
diff --git a/apps/chat/server/api/sandbox/snapshot.post.ts b/apps/chat/server/api/sandbox/snapshot.post.ts
index e375f2c..5dc786f 100644
--- a/apps/chat/server/api/sandbox/snapshot.post.ts
+++ b/apps/chat/server/api/sandbox/snapshot.post.ts
@@ -1,7 +1,8 @@
import { start } from 'workflow/api'
import { createSnapshot } from '../../workflows/create-snapshot'
-export default defineEventHandler(async () => {
+export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const config = useRuntimeConfig()
await start(createSnapshot, [
@@ -12,5 +13,7 @@ export default defineEventHandler(async () => {
}
])
+ requestLog.set({ workflowStatus: 'started' })
+
return { status: 'started', message: 'Snapshot workflow started.' }
})
diff --git a/apps/chat/server/api/shared/[token].get.ts b/apps/chat/server/api/shared/[token].get.ts
index 1156dd3..fde3e03 100644
--- a/apps/chat/server/api/shared/[token].get.ts
+++ b/apps/chat/server/api/shared/[token].get.ts
@@ -25,7 +25,8 @@ export default defineCachedEventHandler(
if (!chat) {
throw createError({
statusCode: 404,
- statusMessage: 'Shared chat not found or no longer public'
+ statusMessage: 'Shared chat not found or no longer public',
+ data: { why: 'This share link is invalid or the chat owner has disabled sharing', fix: 'Ask the chat owner for a new share link' },
})
}
diff --git a/apps/chat/server/api/snapshot/sync.post.ts b/apps/chat/server/api/snapshot/sync.post.ts
index 72b170e..7786d7d 100644
--- a/apps/chat/server/api/snapshot/sync.post.ts
+++ b/apps/chat/server/api/snapshot/sync.post.ts
@@ -8,10 +8,13 @@ import { requireAdmin } from '../../utils/admin'
* Response: { success: true, snapshotId }
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const metadata = await syncToSnapshot()
+ requestLog.set({ snapshotId: metadata.snapshotId })
+
return {
success: true,
snapshotId: metadata.snapshotId,
diff --git a/apps/chat/server/api/sources/[id].delete.ts b/apps/chat/server/api/sources/[id].delete.ts
index 1f829ae..6fff25d 100644
--- a/apps/chat/server/api/sources/[id].delete.ts
+++ b/apps/chat/server/api/sources/[id].delete.ts
@@ -11,15 +11,18 @@ const paramsSchema = z.object({
* Delete a source (admin only)
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const { id } = await getValidatedRouterParams(event, paramsSchema.parse)
+ requestLog.set({ sourceId: id })
+
const [deleted] = await db.delete(schema.sources)
.where(eq(schema.sources.id, id))
.returning()
if (!deleted) {
- throw createError({ statusCode: 404, message: 'Source not found' })
+ throw createError({ statusCode: 404, message: 'Source not found', data: { why: 'No source exists with this ID', fix: 'Verify the source ID from the sources list' } })
}
return { success: true }
diff --git a/apps/chat/server/api/sources/[id].put.ts b/apps/chat/server/api/sources/[id].put.ts
index 36bd2b6..f3a1cff 100644
--- a/apps/chat/server/api/sources/[id].put.ts
+++ b/apps/chat/server/api/sources/[id].put.ts
@@ -27,10 +27,13 @@ const bodySchema = z.object({
* Update an existing source
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { id } = await getValidatedRouterParams(event, paramsSchema.parse)
const body = await readValidatedBody(event, bodySchema.parse)
+ requestLog.set({ sourceId: id, fieldsUpdated: Object.keys(body) })
+
const [source] = await db.update(schema.sources)
.set({
...body,
@@ -40,7 +43,7 @@ export default defineEventHandler(async (event) => {
.returning()
if (!source) {
- throw createError({ statusCode: 404, message: 'Source not found' })
+ throw createError({ statusCode: 404, message: 'Source not found', data: { why: 'No source exists with this ID', fix: 'Verify the source ID from the sources list' } })
}
return source
diff --git a/apps/chat/server/api/sources/index.post.ts b/apps/chat/server/api/sources/index.post.ts
index 13235f0..cbe9a6b 100644
--- a/apps/chat/server/api/sources/index.post.ts
+++ b/apps/chat/server/api/sources/index.post.ts
@@ -20,9 +20,12 @@ const bodySchema = z.object({
* Create a new source (admin only)
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const body = await readValidatedBody(event, bodySchema.parse)
+ requestLog.set({ type: body.type, label: body.label })
+
const [source] = await db.insert(schema.sources)
.values({
id: crypto.randomUUID(),
@@ -42,5 +45,7 @@ export default defineEventHandler(async (event) => {
})
.returning()
+ requestLog.set({ sourceId: source?.id })
+
return source
})
diff --git a/apps/chat/server/api/sources/ocr.post.ts b/apps/chat/server/api/sources/ocr.post.ts
index 1930183..03fa3f1 100644
--- a/apps/chat/server/api/sources/ocr.post.ts
+++ b/apps/chat/server/api/sources/ocr.post.ts
@@ -125,7 +125,7 @@ async function extractFromImage(image: string) {
const result = await optimizeImage(image, ocrConfig)
optimizedImage = result.buffer
} catch (error) {
- console.error('Image optimization for OCR failed, using original', { error })
+ log.warn({ event: 'ocr.optimization_failed', error: error instanceof Error ? error.message : 'Unknown' })
optimizedImage = image
}
diff --git a/apps/chat/server/api/stats/index.get.ts b/apps/chat/server/api/stats/index.get.ts
index 6ed47ad..b9810c2 100644
--- a/apps/chat/server/api/stats/index.get.ts
+++ b/apps/chat/server/api/stats/index.get.ts
@@ -11,6 +11,7 @@ import { desc, and, gte, lt, eq } from 'drizzle-orm'
* - models: comma-separated model filter
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const query = getQuery(event)
@@ -18,6 +19,8 @@ export default defineEventHandler(async (event) => {
const sourcesFilter = typeof query.sources === 'string' && query.sources ? query.sources.split(',') : null
const modelsFilter = typeof query.models === 'string' && query.models ? query.models.split(',') : null
+ requestLog.set({ days, sourcesFilter, modelsFilter })
+
const endDate = new Date()
const startDate = new Date()
startDate.setDate(startDate.getDate() - days)
@@ -448,7 +451,7 @@ export default defineEventHandler(async (event) => {
const totalFeedback = positiveFeedback + negativeFeedback
const feedbackScore = totalFeedback > 0 ? Math.round((positiveFeedback / totalFeedback) * 100) : null
- return {
+ const result = {
period: {
days,
from: startDate.toISOString().split('T')[0]!,
@@ -484,4 +487,8 @@ export default defineEventHandler(async (event) => {
availableSources,
availableModels,
}
+
+ requestLog.set({ resultMessageCount: totalMessages, resultModelCount: byModel.length })
+
+ return result
})
diff --git a/apps/chat/server/api/sync/[source].post.ts b/apps/chat/server/api/sync/[source].post.ts
index fec6cb4..82fff3b 100644
--- a/apps/chat/server/api/sync/[source].post.ts
+++ b/apps/chat/server/api/sync/[source].post.ts
@@ -14,8 +14,10 @@ const paramsSchema = z.object({
* Sync a specific source using Vercel Sandbox (admin only).
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const { source: sourceId } = await getValidatedRouterParams(event, paramsSchema.parse)
+ requestLog.set({ sourceId })
const config = useRuntimeConfig()
const dbSource = await db.query.sources.findFirst({
@@ -26,6 +28,7 @@ export default defineEventHandler(async (event) => {
throw createError({
statusCode: 404,
message: `Source not found: ${sourceId}`,
+ data: { why: 'No source exists with this ID in the database', fix: 'Verify the source ID from the sources list' },
})
}
@@ -65,6 +68,8 @@ export default defineEventHandler(async (event) => {
await start(syncDocumentation, [syncConfig, [source]])
+ requestLog.set({ type: source.type, label: source.label })
+
return {
status: 'started',
message: `Sync workflow started for "${source.label}".`,
diff --git a/apps/chat/server/api/sync/index.post.ts b/apps/chat/server/api/sync/index.post.ts
index 2679696..659f6bd 100644
--- a/apps/chat/server/api/sync/index.post.ts
+++ b/apps/chat/server/api/sync/index.post.ts
@@ -20,10 +20,13 @@ const bodySchema = z
* - sourceFilter: string - Only sync a specific source
*/
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
await requireAdmin(event)
const body = await readValidatedBody(event, data => bodySchema.parse(data))
const config = useRuntimeConfig()
+ requestLog.set({ sourceFilter: body?.sourceFilter })
+
const dbSources = await db.query.sources.findMany()
let sources: Source[] = dbSources.map((s): Source => {
@@ -60,6 +63,7 @@ export default defineEventHandler(async (event) => {
throw createError({
statusCode: 404,
message: `Source not found: ${body.sourceFilter}`,
+ data: { why: 'The specified source filter does not match any configured source', fix: 'Check the source ID and try again' },
})
}
}
@@ -68,6 +72,7 @@ export default defineEventHandler(async (event) => {
throw createError({
statusCode: 400,
message: 'No sources to sync',
+ data: { why: 'No sources have been configured yet', fix: 'Add at least one source in the admin panel before syncing' },
})
}
@@ -82,6 +87,8 @@ export default defineEventHandler(async (event) => {
await kv.set(KV_KEYS.LAST_SOURCE_SYNC, Date.now())
+ requestLog.set({ sourceCount: sources.length })
+
return {
status: 'started',
message: `Sync workflow started for ${sources.length} source(s).`,
diff --git a/apps/chat/server/api/upload/[...pathname].delete.ts b/apps/chat/server/api/upload/[...pathname].delete.ts
index a1417f6..3e8f6a9 100644
--- a/apps/chat/server/api/upload/[...pathname].delete.ts
+++ b/apps/chat/server/api/upload/[...pathname].delete.ts
@@ -2,6 +2,7 @@ import { blob } from 'hub:blob'
import { z } from 'zod'
export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
const { user } = await requireUserSession(event)
const { username } = user
@@ -9,10 +10,13 @@ export default defineEventHandler(async (event) => {
pathname: z.string().min(1)
}).parse)
+ requestLog.set({ pathname, userId: user.id })
+
if (!pathname.startsWith(`${username}/`)) {
throw createError({
statusCode: 403,
- statusMessage: 'You do not have permission to delete this file'
+ statusMessage: 'You do not have permission to delete this file',
+ data: { why: 'You can only delete files in your own upload folder', fix: 'Verify the file path belongs to your account' },
})
}
diff --git a/apps/chat/server/api/upload/[chatId].put.ts b/apps/chat/server/api/upload/[chatId].put.ts
index c2d8100..3d6a029 100644
--- a/apps/chat/server/api/upload/[chatId].put.ts
+++ b/apps/chat/server/api/upload/[chatId].put.ts
@@ -40,7 +40,7 @@ async function processFile(file: FileData): Promise<FileData> {
filename: `${base}.${ext}`,
}
} catch (error) {
- console.error('Image optimization failed, using original file', { filename: file.filename, error })
+ log.warn({ event: 'image.optimization_failed', filename: file.filename, error: error instanceof Error ? error.message : 'Unknown' })
return file
}
}
@@ -54,24 +54,24 @@ export default defineEventHandler(async (event) => {
})
if (chat && chat.userId !== user.id) {
- throw createError({ statusCode: 403, statusMessage: 'You do not have permission to upload files to this chat' })
+ throw createError({ statusCode: 403, statusMessage: 'You do not have permission to upload files to this chat', data: { why: 'This chat belongs to another user', fix: 'Verify the chat ID is correct and belongs to your account' } })
}
const formData = await readMultipartFormData(event)
const field = formData?.find(f => f.name === 'files')
if (!field?.data || !field?.filename) {
- throw createError({ statusCode: 400, statusMessage: 'No file provided' })
+ throw createError({ statusCode: 400, statusMessage: 'No file provided', data: { why: 'The request did not include a file in the "files" form field', fix: 'Attach a file using multipart form data with the field name "files"' } })
}
const originalType = field.type || 'application/octet-stream'
if (!isAllowedType(originalType, field.filename)) {
- throw createError({ statusCode: 400, statusMessage: `File type ${originalType} is not allowed` })
+ throw createError({ statusCode: 400, statusMessage: `File type ${originalType} is not allowed`, data: { why: 'Only images, PDFs, and CSV files are supported', fix: 'Upload a file with one of the supported types: image/*, application/pdf, or text/csv' } })
}
if (field.data.length > 8 * 1024 * 1024) {
- throw createError({ statusCode: 400, statusMessage: 'File size exceeds 8MB limit' })
+ throw createError({ statusCode: 400, statusMessage: 'File size exceeds 8MB limit', data: { why: 'The uploaded file is too large for processing', fix: 'Reduce the file size to under 8MB' } })
}
const processed = await processFile({
diff --git a/apps/chat/server/plugins/evlog.ts b/apps/chat/server/plugins/evlog.ts
new file mode 100644
index 0000000..a37737d
--- /dev/null
+++ b/apps/chat/server/plugins/evlog.ts
@@ -0,0 +1,8 @@
+import { createUserAgentEnricher, createGeoEnricher, createRequestSizeEnricher } from 'evlog/enrichers'
+
+export default defineNitroPlugin((nitroApp) => {
+ const enrichers = [createUserAgentEnricher(), createGeoEnricher(), createRequestSizeEnricher()]
+ nitroApp.hooks.hook('evlog:enrich', (ctx) => {
+ for (const enricher of enrichers) enricher(ctx)
+ })
+})
diff --git a/apps/chat/server/utils/admin.ts b/apps/chat/server/utils/admin.ts
index 67fb2f0..5a1814b 100644
--- a/apps/chat/server/utils/admin.ts
+++ b/apps/chat/server/utils/admin.ts
@@ -3,7 +3,7 @@ import type { H3Event } from 'h3'
export async function requireAdmin(event: H3Event) {
const { user } = await requireUserSession(event)
if (user.role !== 'admin') {
- throw createError({ statusCode: 403, message: 'Admin access required' })
+ throw createError({ statusCode: 403, message: 'Admin access required', data: { why: 'This endpoint requires the admin role', fix: 'Contact an administrator to be granted access' } })
}
return { user }
}
diff --git a/apps/chat/server/utils/bot/adapters/github.ts b/apps/chat/server/utils/bot/adapters/github.ts
index dbad69f..837afe1 100644
--- a/apps/chat/server/utils/bot/adapters/github.ts
+++ b/apps/chat/server/utils/bot/adapters/github.ts
@@ -521,7 +521,11 @@ export class SavoirGitHubAdapter implements Adapter<GitHubThreadId, GitHubRawMes
decodeThreadId(threadId: string): GitHubThreadId {
const match = threadId.match(/^github:([^/]+)\/([^:]+):issue:(\d+)$/)
if (!match || !match[1] || !match[2] || !match[3]) {
- throw new Error(`Invalid GitHub thread ID: ${threadId}`)
+ throw createError({
+ message: 'Invalid GitHub thread ID',
+ status: 400,
+ why: `Thread ID "${threadId}" does not match expected format github:{owner}/{repo}:issue:{number}`,
+ })
}
return {
diff --git a/apps/chat/server/utils/bot/ai.ts b/apps/chat/server/utils/bot/ai.ts
index c8e13f2..29f4cb0 100644
--- a/apps/chat/server/utils/bot/ai.ts
+++ b/apps/chat/server/utils/bot/ai.ts
@@ -95,7 +95,7 @@ export async function generateAIResponse(
savoir.reportUsage(result, {
startTime,
metadata: context ? { source: context.source } : undefined,
- }).catch(() => {})
+ }).catch(e => log.debug({ event: 'bot.usage_report.failed', error: e instanceof Error ? e.message : 'Unknown' }))
// If the agent exhausted all steps on tool calls without producing text,
// do one final call with NO tools to force a text response.
diff --git a/apps/chat/server/utils/bot/index.ts b/apps/chat/server/utils/bot/index.ts
index 71ae6fd..af5a48e 100644
--- a/apps/chat/server/utils/bot/index.ts
+++ b/apps/chat/server/utils/bot/index.ts
@@ -47,8 +47,8 @@ async function handleBotResponse(thread: Thread, message: Message) {
await thread.post(response)
- await adapter.removeReaction(thread.id, message.id, 'eyes').catch(() => {})
- await adapter.addReaction(thread.id, message.id, 'thumbs_up').catch(() => {})
+ await adapter.removeReaction(thread.id, message.id, 'eyes').catch(e => log.debug({ event: 'bot.reaction.cleanup_failed', emoji: 'eyes', error: e instanceof Error ? e.message : 'Unknown' }))
+ await adapter.addReaction(thread.id, message.id, 'thumbs_up').catch(e => log.debug({ event: 'bot.reaction.add_failed', emoji: 'thumbs_up', error: e instanceof Error ? e.message : 'Unknown' }))
log.info({
event: 'bot.response.success',
@@ -66,7 +66,7 @@ async function handleBotResponse(thread: Thread, message: Message) {
error: error instanceof Error ? error.message : 'Unknown',
})
- await adapter.removeReaction(thread.id, message.id, 'eyes').catch(() => {})
+ await adapter.removeReaction(thread.id, message.id, 'eyes').catch(e => log.debug({ event: 'bot.reaction.cleanup_failed', emoji: 'eyes', error: e instanceof Error ? e.message : 'Unknown' }))
try {
await thread.post(`Sorry, I encountered an error while processing your request. Please try again later.
diff --git a/apps/chat/server/utils/bot/savoir.ts b/apps/chat/server/utils/bot/savoir.ts
index 8a1fe5f..b7a6f89 100644
--- a/apps/chat/server/utils/bot/savoir.ts
+++ b/apps/chat/server/utils/bot/savoir.ts
@@ -1,6 +1,7 @@
import { tool } from 'ai'
import { z } from 'zod'
import { db, schema } from '@nuxthub/db'
+import { createError } from 'evlog'
import type { GenerateResult, ReportUsageOptions } from '@savoir/sdk'
import { getOrCreateSandbox } from '../sandbox/manager'
import { getAgentConfig, type AgentConfigData } from '../agent-config'
@@ -29,7 +30,11 @@ const MAX_OUTPUT = 50000
function validateCommand(command: string): void {
for (const pattern of BLOCKED_PATTERNS) {
if (pattern.test(command)) {
- throw new Error(`Command contains blocked pattern: ${command.slice(0, 50)}`)
+ throw createError({
+ message: 'Command blocked by security policy',
+ status: 403,
+ why: `Command contains blocked pattern: ${command.slice(0, 50)}`,
+ })
}
}
}
diff --git a/apps/chat/server/utils/sandbox/snapshot-sync.ts b/apps/chat/server/utils/sandbox/snapshot-sync.ts
index 709f515..c5d19ee 100644
--- a/apps/chat/server/utils/sandbox/snapshot-sync.ts
+++ b/apps/chat/server/utils/sandbox/snapshot-sync.ts
@@ -1,5 +1,6 @@
import { kv } from '@nuxthub/kv'
import { Snapshot } from '@vercel/sandbox'
+import { createError } from 'evlog'
import type { SnapshotMetadata, SnapshotSyncStatus } from './types'
import { KV_KEYS } from './types'
import { getCurrentSnapshot, setCurrentSnapshot } from './snapshot'
@@ -81,7 +82,11 @@ export async function syncToSnapshot(snapshotId?: string): Promise<SnapshotMetad
if (!targetSnapshotId) {
const latest = await getLatestSnapshot()
if (!latest) {
- throw new Error('No snapshots available to sync to')
+ throw createError({
+ message: 'No snapshots available to sync to',
+ why: 'No valid snapshots exist on the Vercel sandbox platform',
+ fix: 'Run the sync workflow to create a snapshot first',
+ })
}
targetSnapshotId = latest.id
}
diff --git a/apps/chat/server/utils/sandbox/snapshot.ts b/apps/chat/server/utils/sandbox/snapshot.ts
index a0ed1fb..9f42579 100644
--- a/apps/chat/server/utils/sandbox/snapshot.ts
+++ b/apps/chat/server/utils/sandbox/snapshot.ts
@@ -1,4 +1,5 @@
import { kv } from '@nuxthub/kv'
+import { createError } from 'evlog'
import type { SnapshotMetadata } from './types'
import { KV_KEYS } from './types'
@@ -22,7 +23,11 @@ export async function hasSnapshot(): Promise<boolean> {
export async function getSnapshotIdOrThrow(): Promise<string> {
const snapshot = await getCurrentSnapshot()
if (!snapshot) {
- throw new Error('No snapshot available. Please create a snapshot first.')
+ throw createError({
+ message: 'No snapshot available',
+ why: 'No sandbox snapshot has been created yet',
+ fix: 'Create a snapshot first by running the sync workflow or using the admin panel',
+ })
}
return snapshot.snapshotId
}
diff --git a/bun.lock b/bun.lock
index 2ca9601..24743fc 100644
--- a/bun.lock
+++ b/bun.lock
@@ -71,6 +71,7 @@
"dependencies": {
"@ai-sdk/gateway": "^3.0.45",
"ai": "^6.0.85",
+ "evlog": "^1.9.0",
"zod": "^4.3.6",
},
"devDependencies": {
@@ -2497,7 +2498,7 @@
"is-decimal": ["[email protected]", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="],
- "is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="],
+ "is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="],
"is-extglob": ["[email protected]", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
@@ -3373,7 +3374,7 @@
"skin-tone": ["[email protected]", "", { "dependencies": { "unicode-emoji-modifier-base": "^1.0.0" } }, "sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA=="],
- "slash": ["[email protected]", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="],
+ "slash": ["[email protected]", "", {}, "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg=="],
"smart-buffer": ["[email protected]", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="],
@@ -3603,7 +3604,7 @@
"unicode-trie": ["[email protected]", "", { "dependencies": { "pako": "^0.2.5", "tiny-inflate": "^1.0.0" } }, "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ=="],
- "unicorn-magic": ["[email protected]", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],
+ "unicorn-magic": ["[email protected]", "", {}, "sha512-wH590V9VNgYH9g3lH9wWjTrUoKsjLF6sGLjhR4sH1LWpLmCOH0Zf7PukhDA8BiS7KHe4oPNkcTHqYkj7SOGUOw=="],
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
@@ -4149,6 +4150,8 @@
"@swc/cli/commander": ["[email protected]", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="],
+ "@swc/cli/slash": ["[email protected]", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="],
+
"@tailwindcss/node/enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.0" } }, "sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" }, "bundled": true }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
@@ -4357,10 +4360,6 @@
"globby/ignore": ["[email protected]", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
- "globby/slash": ["[email protected]", "", {}, "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg=="],
-
- "globby/unicorn-magic": ["[email protected]", "", {}, "sha512-wH590V9VNgYH9g3lH9wWjTrUoKsjLF6sGLjhR4sH1LWpLmCOH0Zf7PukhDA8BiS7KHe4oPNkcTHqYkj7SOGUOw=="],
-
"got/@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-TV7t8GKYaJWsn00tFDqBw8+Uqmr8A0fRU1tvTQhyZzGv0sJCGRQL3JGMI3ucuKo3XIZdUP+Lx7/gh2t3lewy7g=="],
"got/get-stream": ["[email protected]", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="],
@@ -4371,7 +4370,7 @@
"impound/unplugin-utils": ["[email protected]", "", { "dependencies": { "pathe": "^2.0.3", "picomatch": "^4.0.3" } }, "sha512-gwXJnPRewT4rT7sBi/IvxKTjsms7jX7QIDLOClApuZwR49SXbrB1z2NLUZ+vDHyqCj/n58OzRRqaW+B8OZi8vg=="],
- "is-wsl/is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="],
+ "is-inside-container/is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="],
"jsonc-eslint-parser/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
@@ -4421,6 +4420,8 @@
"npm-run-path/path-key": ["[email protected]", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],
+ "npm-run-path/unicorn-magic": ["[email protected]", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],
+
"nuxt/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
"nuxt/hookable": ["[email protected]", "", {}, "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ=="],
@@ -4773,6 +4774,8 @@
"@nuxtjs/color-mode/pkg-types/pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
+ "@oclif/core/globby/slash": ["[email protected]", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="],
+
"@prisma/config/c12/chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="],
"@prisma/config/c12/dotenv": ["[email protected]", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],
@@ -4971,8 +4974,6 @@
"rollup-plugin-visualizer/open/define-lazy-prop": ["[email protected]", "", {}, "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="],
- "rollup-plugin-visualizer/open/is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="],
-
"unplugin-vue-router/@babel/generator/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
"unplugin-vue-router/@babel/generator/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
diff --git a/packages/agent/package.json b/packages/agent/package.json
index 476e8f3..4b25d01 100644
--- a/packages/agent/package.json
+++ b/packages/agent/package.json
@@ -26,6 +26,7 @@
"dependencies": {
"@ai-sdk/gateway": "^3.0.45",
"ai": "^6.0.85",
+ "evlog": "^1.9.0",
"zod": "^4.3.6"
},
"devDependencies": {
diff --git a/packages/agent/src/agents/base.ts b/packages/agent/src/agents/base.ts
index ef81684..405a020 100644
--- a/packages/agent/src/agents/base.ts
+++ b/packages/agent/src/agents/base.ts
@@ -1,4 +1,5 @@
import { stepCountIs, ToolLoopAgent, type StepResult, type ToolSet } from 'ai'
+import { log } from 'evlog'
import { DEFAULT_MODEL } from '../router/schema'
import { compactContext } from '../core/context'
import { callOptionsSchema } from '../core/schemas'
@@ -63,9 +64,7 @@ export function createAgent({
const compactedMessages = compactContext({ messages, steps: normalizedSteps })
if (shouldForceTextOnlyStep({ stepNumber, maxSteps, steps: normalizedSteps })) {
- console.info(
- `[agent] Forcing text-only step at ${stepNumber + 1}/${maxSteps} (tool streak=${countConsecutiveToolSteps(normalizedSteps)})`,
- )
+ log.info({ event: 'agent.force_text_step', step: stepNumber + 1, maxSteps, toolStreak: countConsecutiveToolSteps(normalizedSteps) })
return {
tools: {},
toolChoice: 'none' as const,
diff --git a/packages/agent/src/agents/source.ts b/packages/agent/src/agents/source.ts
index fa9bf85..8c1a31f 100644
--- a/packages/agent/src/agents/source.ts
+++ b/packages/agent/src/agents/source.ts
@@ -1,4 +1,5 @@
import { stepCountIs, ToolLoopAgent, type StepResult, type ToolSet, type UIMessage } from 'ai'
+import { log } from 'evlog'
import { DEFAULT_MODEL } from '../router/schema'
import { routeQuestion } from '../router/route-question'
import { buildChatSystemPrompt } from '../prompts/chat'
@@ -80,9 +81,7 @@ export function createSourceAgent({
const compactedMessages = compactContext({ messages: stepMessages, steps: normalizedSteps })
if (shouldForceTextOnlyStep({ stepNumber, maxSteps, steps: normalizedSteps })) {
- console.info(
- `[agent] Forcing text-only step at ${stepNumber + 1}/${maxSteps} (tool streak=${countConsecutiveToolSteps(normalizedSteps)})`,
- )
+ log.info({ event: 'agent.force_text_step', step: stepNumber + 1, maxSteps, toolStreak: countConsecutiveToolSteps(normalizedSteps) })
return {
tools: {},
toolChoice: 'none' as const,
diff --git a/packages/agent/src/core/sanitize.ts b/packages/agent/src/core/sanitize.ts
index dd50a02..b32d2c4 100644
--- a/packages/agent/src/core/sanitize.ts
+++ b/packages/agent/src/core/sanitize.ts
@@ -1,4 +1,5 @@
import type { ModelMessage } from 'ai'
+import { log } from 'evlog'
/**
* Ensure all tool-call `input` fields in messages are valid JSON objects.
@@ -10,7 +11,7 @@ export function sanitizeToolCallInputs(messages: ModelMessage[]): ModelMessage[]
if (message.role !== 'assistant' || !Array.isArray(message.content)) continue
for (const part of message.content) {
if (part.type === 'tool-call' && typeof part.input === 'string') {
- console.warn(`[agent] Sanitizing tool-call input for ${part.toolName}: input was a string, parsing to object`)
+ log.warn({ event: 'agent.sanitize_input', toolName: part.toolName })
try {
part.input = JSON.parse(part.input)
} catch {
diff --git a/packages/agent/src/router/route-question.ts b/packages/agent/src/router/route-question.ts
index 848c38c..48082cc 100644
--- a/packages/agent/src/router/route-question.ts
+++ b/packages/agent/src/router/route-question.ts
@@ -1,6 +1,7 @@
import { createGateway } from '@ai-sdk/gateway'
import { generateText, Output } from 'ai'
import type { UIMessage } from 'ai'
+import { log } from 'evlog'
import { ROUTER_SYSTEM_PROMPT } from '../prompts/router'
import { type AgentConfig, agentConfigSchema, getDefaultConfig, ROUTER_MODEL } from './schema'
@@ -25,7 +26,7 @@ export async function routeQuestion(
const question = extractQuestionFromMessages(messages)
if (!question) {
- console.info(`[chat] [${requestId}] Router: no question found, using default config`)
+ log.info({ event: 'router.no_question', requestId })
return getDefaultConfig()
}
@@ -40,15 +41,15 @@ export async function routeQuestion(
})
if (!output) {
- console.warn(`[chat] [${requestId}] Router returned no output, using default config`)
+ log.warn({ event: 'router.no_output', requestId })
return getDefaultConfig()
}
- console.info(`[chat] [${requestId}] Router decision: ${output.complexity} (${output.model}, ${output.maxSteps} steps) - ${output.reasoning}`)
+ log.info({ event: 'router.decision', requestId, complexity: output.complexity, model: output.model, maxSteps: output.maxSteps, reasoning: output.reasoning })
return output
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
- console.error(`[chat] [${requestId}] Router failed: ${errorMessage}, using default config`)
+ log.error({ event: 'router.failed', requestId, error: errorMessage })
return getDefaultConfig()
}
}