Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base
remove chat-sdk
Hugo Richardfb8c074411d8
diff --git a/apps/chat/app/composables/useChats.ts b/apps/chat/app/composables/useChats.tsindex 38ec744..1e26b02 100644--- a/apps/chat/app/composables/useChats.ts+++ b/apps/chat/app/composables/useChats.ts@@ -9,7 +9,6 @@ export interface UIChat {export function useChats(chats: Ref<UIChat[] | undefined>) {const groups = computed(() => {- // Group chats by dateconst today: UIChat[] = []const yesterday: UIChat[] = []const lastWeek: UIChat[] = []@@ -31,7 +30,6 @@ export function useChats(chats: Ref<UIChat[] | undefined>) {} else if (chatDate >= oneMonthAgo) {lastMonth.push(chat)} else {- // Format: "January 2023", "February 2023", etc.const monthYear = chatDate.toLocaleDateString('en-US', {month: 'long',year: 'numeric'@@ -45,21 +43,18 @@ export function useChats(chats: Ref<UIChat[] | undefined>) {}})- // Sort older chats by month-year in descending order (newest first)const sortedMonthYears = Object.keys(older).sort((a, b) => {const dateA = new Date(a)const dateB = new Date(b)return dateB.getTime() - dateA.getTime()})- // Create formatted groups for navigationconst formattedGroups = [] as Array<{id: stringlabel: stringitems: Array<UIChat>}>- // Add groups that have chatsif (today.length) {formattedGroups.push({id: 'today',@@ -92,7 +87,6 @@ export function useChats(chats: Ref<UIChat[] | undefined>) {})}- // Add each month-year groupsortedMonthYears.forEach((monthYear) => {if (older[monthYear]?.length) {formattedGroups.push({diff --git a/apps/chat/app/layouts/admin.vue b/apps/chat/app/layouts/admin.vueindex f0fc9d8..1331389 100644--- a/apps/chat/app/layouts/admin.vue+++ b/apps/chat/app/layouts/admin.vue@@ -6,6 +6,11 @@ const navigation = [to: '/admin',exact: true,},+ {+ label: 'Assistant',+ icon: 'i-lucide-bot',+ to: '/admin/agent',+ },{label: 'Sandbox',icon: 'i-lucide-box',diff --git a/apps/chat/app/layouts/default.vue b/apps/chat/app/layouts/default.vueindex b613411..3bec867 100644--- a/apps/chat/app/layouts/default.vue+++ b/apps/chat/app/layouts/default.vue@@ -39,7 +39,6 @@ const { data: chats, refresh: refreshChats } = await useFetch<Chat[]>('/api/chatonNuxtReady(async () => {const first10 = (chats.value || []).slice(0, 10)for (const chat of first10) {- // prefetch the chat and let the browser cache itawait $fetch(`/api/chats/${chat.id}`)}})diff --git a/apps/chat/app/pages/admin/agent.vue b/apps/chat/app/pages/admin/agent.vuenew file mode 100644index 0000000..2f1ed0c--- /dev/null+++ b/apps/chat/app/pages/admin/agent.vue@@ -0,0 +1,348 @@+<script setup lang="ts">+const toast = useToast()++interface AgentConfig {+ id: string+ name: string+ additionalPrompt: string | null+ responseStyle: 'concise' | 'detailed' | 'technical' | 'friendly'+ language: string+ defaultModel: string | null+ maxStepsMultiplier: number+ temperature: number+ searchInstructions: string | null+ citationFormat: 'inline' | 'footnote' | 'none'+ isActive: boolean+}++const { data: config, refresh, status } = await useFetch<AgentConfig>('/api/agent-config')++const form = ref<{+ additionalPrompt: string+ responseStyle: 'concise' | 'detailed' | 'technical' | 'friendly'+ language: string+ defaultModel: string+ maxStepsMultiplier: number+ temperature: number+ searchInstructions: string+ citationFormat: 'inline' | 'footnote' | 'none'+}>({+ additionalPrompt: '',+ responseStyle: 'concise',+ language: 'en',+ defaultModel: 'auto',+ maxStepsMultiplier: 1.0,+ temperature: 0.7,+ searchInstructions: '',+ citationFormat: 'inline',+})++const isSaving = ref(false)+const isResetting = ref(false)++watch(config, (newConfig) => {+ if (newConfig) {+ form.value = {+ additionalPrompt: newConfig.additionalPrompt || '',+ responseStyle: newConfig.responseStyle,+ language: newConfig.language,+ defaultModel: newConfig.defaultModel || 'auto',+ maxStepsMultiplier: newConfig.maxStepsMultiplier,+ temperature: newConfig.temperature,+ searchInstructions: newConfig.searchInstructions || '',+ citationFormat: newConfig.citationFormat,+ }+ }+}, { immediate: true })++const responseStyleOptions = [+ { value: 'concise', label: 'Concise', description: 'Short and direct answers' },+ { value: 'detailed', label: 'Detailed', description: 'Full explanations with context' },+ { value: 'technical', label: 'Technical', description: 'For developers, with code examples' },+ { value: 'friendly', label: 'Friendly', description: 'Casual and easy to understand' },+]++const citationFormatOptions = [+ { value: 'inline', label: 'In text', description: 'Show sources as you read' },+ { value: 'footnote', label: 'At the end', description: 'List sources at the bottom' },+ { value: 'none', label: 'Hidden', description: 'Don\'t show sources' },+]++const languageOptions = [+ { value: 'en', label: 'English' },+ { value: 'fr', label: 'French' },+ { value: 'es', label: 'Spanish' },+ { value: 'de', label: 'German' },+ { value: 'pt', label: 'Portuguese' },+ { value: 'zh', label: 'Chinese' },+ { value: 'ja', label: 'Japanese' },+]++const modelOptions = [+ { value: 'auto', label: 'Automatic (Recommended)' },+ { value: 'google/gemini-2.5-flash-lite', label: 'Fast' },+ { value: 'google/gemini-3-flash', label: 'Balanced' },+ { value: 'anthropic/claude-opus-4.5', label: 'Advanced' },+]++async function saveConfig() {+ isSaving.value = true+ try {+ await $fetch('/api/agent-config', {+ method: 'PUT',+ body: {+ additionalPrompt: form.value.additionalPrompt || null,+ responseStyle: form.value.responseStyle,+ language: form.value.language,+ defaultModel: form.value.defaultModel === 'auto' ? null : form.value.defaultModel,+ maxStepsMultiplier: form.value.maxStepsMultiplier,+ temperature: form.value.temperature,+ searchInstructions: form.value.searchInstructions || null,+ citationFormat: form.value.citationFormat,+ },+ })+ toast.add({+ title: 'Configuration saved',+ icon: 'i-lucide-check',+ })+ 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',+ })+ } finally {+ isSaving.value = false+ }+}++async function resetConfig() {+ isResetting.value = true+ try {+ await $fetch('/api/agent-config/reset', { method: 'POST' })+ toast.add({+ title: 'Configuration reset',+ description: 'Settings have been restored to defaults',+ icon: 'i-lucide-check',+ })+ 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',+ })+ } finally {+ isResetting.value = false+ }+}+</script>++<template>+ <div class="px-6 lg:px-10 py-8 max-w-3xl">+ <header class="mb-8">+ <h1 class="text-lg font-medium text-highlighted mb-1">+ Assistant Settings+ </h1>+ <p class="text-sm text-muted max-w-lg">+ Customize how the AI assistant responds to questions.+ </p>+ </header>++ <div v-if="status === 'pending'" class="flex items-center justify-center py-16">+ <UIcon name="i-lucide-loader-2" class="size-5 animate-spin text-muted" />+ </div>++ <form v-else class="space-y-8" @submit.prevent="saveConfig">+ <!-- Custom Instructions -->+ <section>+ <label class="block text-sm font-medium text-highlighted mb-2">+ Custom Instructions+ </label>+ <p class="text-xs text-muted mb-3">+ Add rules or guidelines for how the assistant should behave.+ </p>+ <UTextarea+ v-model="form.additionalPrompt"+ placeholder="Example: Always be friendly and patient. When showing code, include comments explaining what it does..."+ :rows="4"+ autoresize+ class="w-full"+ />+ </section>++ <!-- Tone -->+ <section>+ <label class="block text-sm font-medium text-highlighted mb-2">+ Tone+ </label>+ <p class="text-xs text-muted mb-3">+ Choose how the assistant communicates.+ </p>+ <div class="grid grid-cols-2 gap-3">+ <label+ v-for="option in responseStyleOptions"+ :key="option.value"+ class="relative flex items-start p-3 rounded-lg border transition-colors cursor-pointer"+ :class="form.responseStyle === option.value ? 'border-primary bg-primary/5' : 'border-default hover:border-muted'"+ >+ <input+ v-model="form.responseStyle"+ type="radio"+ name="responseStyle"+ :value="option.value"+ class="sr-only"+ >+ <div>+ <span class="text-sm font-medium text-highlighted">{{ option.label }}</span>+ <p class="text-xs text-muted mt-0.5">{{ option.description }}</p>+ </div>+ </label>+ </div>+ </section>++ <!-- Language & Intelligence Row -->+ <div class="grid grid-cols-2 gap-6">+ <section>+ <label class="block text-sm font-medium text-highlighted mb-2">+ Language+ </label>+ <p class="text-xs text-muted mb-3">+ The language the assistant will respond in.+ </p>+ <USelect+ v-model="form.language"+ :items="languageOptions"+ value-key="value"+ class="w-full"+ />+ </section>++ <section>+ <label class="block text-sm font-medium text-highlighted mb-2">+ Intelligence+ </label>+ <p class="text-xs text-muted mb-3">+ Choose between speed and quality.+ </p>+ <USelect+ v-model="form.defaultModel"+ :items="modelOptions"+ value-key="value"+ class="w-full"+ />+ </section>+ </div>++ <!-- Creativity & Search Depth Row -->+ <div class="grid grid-cols-2 gap-6">+ <section>+ <label class="block text-sm font-medium text-highlighted mb-2">+ Creativity+ </label>+ <p class="text-xs text-muted mb-3">+ How creative vs predictable the responses should be.+ </p>+ <USlider+ v-model="form.temperature"+ :min="0"+ :max="2"+ :step="0.1"+ class="w-full"+ />+ <div class="flex justify-between text-xs text-muted mt-1">+ <span>Predictable</span>+ <span>Creative</span>+ </div>+ </section>++ <section>+ <label class="block text-sm font-medium text-highlighted mb-2">+ Search Depth+ </label>+ <p class="text-xs text-muted mb-3">+ How thoroughly the assistant searches for information.+ </p>+ <USlider+ v-model="form.maxStepsMultiplier"+ :min="0.5"+ :max="3"+ :step="0.1"+ class="w-full"+ />+ <div class="flex justify-between text-xs text-muted mt-1">+ <span>Quick</span>+ <span>Thorough</span>+ </div>+ </section>+ </div>++ <!-- Search Preferences -->+ <section>+ <label class="block text-sm font-medium text-highlighted mb-2">+ Search Preferences+ </label>+ <p class="text-xs text-muted mb-3">+ Guide how the assistant finds and prioritizes information.+ </p>+ <UTextarea+ v-model="form.searchInstructions"+ placeholder="Example: Focus on official documentation first. Check for the latest version information..."+ :rows="3"+ autoresize+ class="w-full"+ />+ </section>++ <!-- Source References -->+ <section>+ <label class="block text-sm font-medium text-highlighted mb-2">+ Source References+ </label>+ <p class="text-xs text-muted mb-3">+ How the assistant shows where it found the information.+ </p>+ <div class="flex gap-3">+ <label+ v-for="option in citationFormatOptions"+ :key="option.value"+ class="relative flex items-center gap-2 px-4 py-2 rounded-lg border transition-colors cursor-pointer"+ :class="form.citationFormat === option.value ? 'border-primary bg-primary/5' : 'border-default hover:border-muted'"+ >+ <input+ v-model="form.citationFormat"+ type="radio"+ name="citationFormat"+ :value="option.value"+ class="sr-only"+ >+ <span class="text-sm font-medium text-highlighted">{{ option.label }}</span>+ </label>+ </div>+ </section>++ <!-- Actions -->+ <div class="flex items-center gap-3 pt-4 border-t border-default">+ <UButton+ type="submit"+ :loading="isSaving"+ icon="i-lucide-save"+ >+ Save Changes+ </UButton>+ <UButton+ type="button"+ color="neutral"+ variant="ghost"+ :loading="isResetting"+ @click="resetConfig"+ >+ Reset to Defaults+ </UButton>+ </div>+ </form>+ </div>+</template>diff --git a/apps/chat/server/api/agent-config/index.get.ts b/apps/chat/server/api/agent-config/index.get.tsnew file mode 100644index 0000000..58e103f--- /dev/null+++ b/apps/chat/server/api/agent-config/index.get.ts@@ -0,0 +1,10 @@+import { getAgentConfig } from '../../utils/agent-config'++/**+ * GET /api/agent-config+ * Get the active agent configuration (admin only)+ */+export default defineEventHandler(async (event) => {+ await requireAdmin(event)+ return await getAgentConfig()+})diff --git a/apps/chat/server/api/agent-config/index.put.ts b/apps/chat/server/api/agent-config/index.put.tsnew file mode 100644index 0000000..e021002--- /dev/null+++ b/apps/chat/server/api/agent-config/index.put.ts@@ -0,0 +1,64 @@+import { db, schema } from '@nuxthub/db'+import { eq } from 'drizzle-orm'+import { z } from 'zod'+import { invalidateAgentConfigCache } from '../../utils/agent-config'++const bodySchema = z.object({+ additionalPrompt: z.string().nullable().optional(),+ responseStyle: z.enum(['concise', 'detailed', 'technical', 'friendly']).optional(),+ language: z.string().optional(),+ defaultModel: z.string().nullable().optional(),+ maxStepsMultiplier: z.number().min(0.5).max(3.0).optional(),+ temperature: z.number().min(0).max(2).optional(),+ searchInstructions: z.string().nullable().optional(),+ citationFormat: z.enum(['inline', 'footnote', 'none']).optional(),+})++/**+ * PUT /api/agent-config+ * Update the active agent configuration (admin only)+ */+export default defineEventHandler(async (event) => {+ await requireAdmin(event)+ const body = await readValidatedBody(event, bodySchema.parse)++ const existing = await db.query.agentConfig.findFirst({+ where: () => eq(schema.agentConfig.isActive, true),+ })++ let config++ if (existing) {+ const [updated] = await db.update(schema.agentConfig)+ .set({+ ...body,+ updatedAt: new Date(),+ })+ .where(eq(schema.agentConfig.id, existing.id))+ .returning()+ config = updated+ } else {+ const [created] = await db.insert(schema.agentConfig)+ .values({+ id: crypto.randomUUID(),+ name: 'default',+ additionalPrompt: body.additionalPrompt ?? null,+ responseStyle: body.responseStyle ?? 'concise',+ language: body.language ?? 'en',+ defaultModel: body.defaultModel ?? null,+ maxStepsMultiplier: body.maxStepsMultiplier ?? 1.0,+ temperature: body.temperature ?? 0.7,+ searchInstructions: body.searchInstructions ?? null,+ citationFormat: body.citationFormat ?? 'inline',+ isActive: true,+ createdAt: new Date(),+ updatedAt: new Date(),+ })+ .returning()+ config = created+ }++ invalidateAgentConfigCache()++ return config+})diff --git a/apps/chat/server/api/agent-config/public.get.ts b/apps/chat/server/api/agent-config/public.get.tsnew file mode 100644index 0000000..4e18b4a--- /dev/null+++ b/apps/chat/server/api/agent-config/public.get.ts@@ -0,0 +1,28 @@+import { getAgentConfig } from '../../utils/agent-config'++/**+ * GET /api/agent-config/public+ * Get the active agent configuration for SDK (protected by API key via middleware)+ *+ * This endpoint is used by external bots (github-bot, etc.) to fetch+ * the current agent configuration via the SDK.+ */+export default defineEventHandler(async (event) => {+ // Validate API key (similar to sandbox routes)+ const config = useRuntimeConfig()+ const secretKey = config.savoirSecretKey++ if (secretKey) {+ const authHeader = getHeader(event, 'Authorization')+ const apiKey = authHeader?.replace('Bearer ', '')++ if (!apiKey || apiKey !== secretKey) {+ throw createError({+ statusCode: 401,+ message: 'Invalid or missing API key',+ })+ }+ }++ return await getAgentConfig()+})diff --git a/apps/chat/server/api/agent-config/reset.post.ts b/apps/chat/server/api/agent-config/reset.post.tsnew file mode 100644index 0000000..d2a549c--- /dev/null+++ b/apps/chat/server/api/agent-config/reset.post.ts@@ -0,0 +1,60 @@+import { db, schema } from '@nuxthub/db'+import { eq } from 'drizzle-orm'+import { invalidateAgentConfigCache, getDefaultAgentConfig } from '../../utils/agent-config'++/**+ * POST /api/agent-config/reset+ * Reset agent configuration to defaults (admin only)+ */+export default defineEventHandler(async (event) => {+ await requireAdmin(event)++ const defaults = getDefaultAgentConfig()++ const existing = await db.query.agentConfig.findFirst({+ where: () => eq(schema.agentConfig.isActive, true),+ })++ let config++ if (existing) {+ const [updated] = await db.update(schema.agentConfig)+ .set({+ additionalPrompt: null,+ responseStyle: defaults.responseStyle,+ language: defaults.language,+ defaultModel: null,+ maxStepsMultiplier: defaults.maxStepsMultiplier,+ temperature: defaults.temperature,+ searchInstructions: null,+ citationFormat: defaults.citationFormat,+ updatedAt: new Date(),+ })+ .where(eq(schema.agentConfig.id, existing.id))+ .returning()+ config = updated+ } else {+ const [created] = await db.insert(schema.agentConfig)+ .values({+ id: crypto.randomUUID(),+ name: 'default',+ additionalPrompt: null,+ responseStyle: defaults.responseStyle,+ language: defaults.language,+ defaultModel: null,+ maxStepsMultiplier: defaults.maxStepsMultiplier,+ temperature: defaults.temperature,+ searchInstructions: null,+ citationFormat: defaults.citationFormat,+ isActive: true,+ createdAt: new Date(),+ updatedAt: new Date(),+ })+ .returning()+ config = created+ }++ invalidateAgentConfigCache()++ return config+})diff --git a/apps/chat/server/api/chats/[id].post.ts b/apps/chat/server/api/chats/[id].post.tsindex d2c4db4..136b759 100644--- a/apps/chat/server/api/chats/[id].post.ts+++ b/apps/chat/server/api/chats/[id].post.ts@@ -6,8 +6,9 @@ import { createSavoir } from '@savoir/sdk'import { log, useLogger } from 'evlog'import { generateTitle } from '../../utils/chat/generate-title'import { routeQuestion, buildSystemPromptWithComplexity } from '../../utils/router/route-question'+import { getAgentConfig, type AgentConfigData } from '../../utils/agent-config'-const SYSTEM_PROMPT = `You are an AI assistant that answers questions based on the available sources.+const BASE_SYSTEM_PROMPT = `You are an AI assistant that answers questions based on the available sources.## CRITICAL: Sources First@@ -47,6 +48,41 @@ Your knowledge may be outdated. ONLY answer based on what you find in the source- Cite the source file path`+function buildDynamicSystemPrompt(agentConfigData: AgentConfigData): string {+ let prompt = BASE_SYSTEM_PROMPT++ const styleInstructions: Record<AgentConfigData['responseStyle'], string> = {+ concise: 'Keep your responses brief and to the point.',+ detailed: 'Provide comprehensive explanations with context.',+ technical: 'Focus on technical details and include code examples.',+ friendly: 'Be conversational and approachable in your responses.',+ }+ prompt = prompt.replace(+ '## Response Style\n\n- Be concise and helpful',+ `## Response Style\n\n- ${styleInstructions[agentConfigData.responseStyle]}`,+ )++ if (agentConfigData.language && agentConfigData.language !== 'en') {+ prompt += `\n\n## Language\nRespond in ${agentConfigData.language}.`+ }++ if (agentConfigData.citationFormat === 'footnote') {+ prompt += '\n\n## Citations\nPlace all source citations as footnotes at the end of your response.'+ } else if (agentConfigData.citationFormat === 'none') {+ prompt += '\n\n## Citations\nDo not include source citations in your response.'+ }++ if (agentConfigData.searchInstructions) {+ prompt += `\n\n## Custom Search Instructions\n${agentConfigData.searchInstructions}`+ }++ if (agentConfigData.additionalPrompt) {+ prompt += `\n\n## Additional Instructions\n${agentConfigData.additionalPrompt}`+ }++ return prompt+}+defineRouteMeta({openAPI: {description: 'Chat with AI about the available sources.',@@ -141,19 +177,29 @@ export default defineEventHandler(async (event) => {},})- const agentConfig = await routeQuestion(messages, requestId)+ // Get both router config and admin-defined agent config+ const [routerConfig, agentConfigData] = await Promise.all([+ routeQuestion(messages, requestId),+ getAgentConfig(),+ ])++ const effectiveMaxSteps = Math.round(routerConfig.maxSteps * agentConfigData.maxStepsMultiplier)++ const effectiveModel = agentConfigData.defaultModel || model++ const dynamicSystemPrompt = buildDynamicSystemPrompt(agentConfigData)- log.info('chat', `[${requestId}] Starting agent with ${model} (routed: ${agentConfig.complexity}, ${agentConfig.maxSteps} steps)`)+ log.info('chat', `[${requestId}] Starting agent with ${effectiveModel} (routed: ${routerConfig.complexity}, ${effectiveMaxSteps} steps, multiplier: ${agentConfigData.maxStepsMultiplier}x)`)const stream = createUIMessageStream({execute: async ({ writer }) => {streamWriter = writerconst agent = new ToolLoopAgent({- model,- instructions: buildSystemPromptWithComplexity(SYSTEM_PROMPT, agentConfig),+ model: effectiveModel,+ instructions: buildSystemPromptWithComplexity(dynamicSystemPrompt, routerConfig),tools: savoir.tools,- stopWhen: stepCountIs(agentConfig.maxSteps),+ stopWhen: stepCountIs(effectiveMaxSteps),onStepFinish: (stepResult) => {const stepDurationMs = Date.now() - stepStartTimestepDurations.push(stepDurationMs)@@ -186,9 +232,11 @@ export default defineEventHandler(async (event) => {toolCallCount,stepDurations,totalAgentMs: totalDurationMs,- routerComplexity: agentConfig.complexity,- routerMaxSteps: agentConfig.maxSteps,- routerReasoning: agentConfig.reasoning,+ routerComplexity: routerConfig.complexity,+ routerMaxSteps: routerConfig.maxSteps,+ effectiveMaxSteps,+ stepsMultiplier: agentConfigData.maxStepsMultiplier,+ routerReasoning: routerConfig.reasoning,})log.info('chat', `[${requestId}] Finished: ${result.finishReason} (total: ${totalDurationMs}ms)`)},diff --git a/apps/chat/server/api/sources/index.post.ts b/apps/chat/server/api/sources/index.post.tsindex 2798b89..13235f0 100644--- a/apps/chat/server/api/sources/index.post.ts+++ b/apps/chat/server/api/sources/index.post.ts@@ -4,15 +4,12 @@ import { z } from 'zod'const bodySchema = z.object({type: z.enum(['github', 'youtube']),label: z.string().min(1),- // Common output fieldbasePath: z.string().optional().default('/docs'),- // GitHub fieldsrepo: z.string().optional(),branch: z.string().optional().default('main'),contentPath: z.string().optional(),outputPath: z.string().optional(),readmeOnly: z.boolean().optional().default(false),- // YouTube fieldschannelId: z.string().optional(),handle: z.string().optional(),maxVideos: z.number().optional().default(50),diff --git a/apps/chat/server/api/sync/[source].post.ts b/apps/chat/server/api/sync/[source].post.tsindex d021a7a..fb6bd2f 100644--- a/apps/chat/server/api/sync/[source].post.ts+++ b/apps/chat/server/api/sync/[source].post.ts@@ -16,7 +16,6 @@ export default defineEventHandler(async (event) => {const { source: sourceId } = await getValidatedRouterParams(event, paramsSchema.parse)const config = useRuntimeConfig()- // Load the specific source from DBconst dbSource = await db.query.sources.findFirst({where: (sources, { eq, and }) => and(eq(sources.id, sourceId),diff --git a/apps/chat/server/api/sync/index.post.ts b/apps/chat/server/api/sync/index.post.tsindex 79d6a22..34f60f7 100644--- a/apps/chat/server/api/sync/index.post.ts+++ b/apps/chat/server/api/sync/index.post.ts@@ -23,10 +23,8 @@ export default defineEventHandler(async (event) => {const body = await readValidatedBody(event, data => bodySchema.parse(data))const config = useRuntimeConfig()- // Load sources from DBconst dbSources = await db.query.sources.findMany()- // Filter to GitHub sources and transformlet sources: GitHubSource[] = dbSources.filter(s => s.type === 'github').map(s => ({@@ -41,7 +39,6 @@ export default defineEventHandler(async (event) => {readmeOnly: s.readmeOnly ?? false,}))- // Apply filter if specifiedif (body?.sourceFilter) {sources = sources.filter(s => s.id === body.sourceFilter)if (sources.length === 0) {@@ -67,7 +64,6 @@ export default defineEventHandler(async (event) => {await start(syncDocumentation, [syncConfig, sources])- // Track last sync timeawait kv.set(KV_KEYS.LAST_SOURCE_SYNC, Date.now())return {diff --git a/apps/chat/server/db/migrations/sqlite/0001_certain_paibok.sql b/apps/chat/server/db/migrations/sqlite/0001_certain_paibok.sqlnew file mode 100644index 0000000..206438b--- /dev/null+++ b/apps/chat/server/db/migrations/sqlite/0001_certain_paibok.sql@@ -0,0 +1,15 @@+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/meta/0001_snapshot.json b/apps/chat/server/db/migrations/sqlite/meta/0001_snapshot.jsonnew file mode 100644index 0000000..b24936d--- /dev/null+++ b/apps/chat/server/db/migrations/sqlite/meta/0001_snapshot.json@@ -0,0 +1,463 @@+{+ "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 filediff --git a/apps/chat/server/db/migrations/sqlite/meta/_journal.json b/apps/chat/server/db/migrations/sqlite/meta/_journal.jsonindex ec0fba9..791c81c 100644--- a/apps/chat/server/db/migrations/sqlite/meta/_journal.json+++ b/apps/chat/server/db/migrations/sqlite/meta/_journal.json@@ -8,6 +8,13 @@"when": 1769440810870,"tag": "0000_steady_magdalene","breakpoints": true+ },+ {+ "idx": 1,+ "version": "6",+ "when": 1770128425579,+ "tag": "0001_certain_paibok",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/chat/server/db/schema.ts b/apps/chat/server/db/schema.tsindex c683887..2b1e9c9 100644--- a/apps/chat/server/db/schema.ts+++ b/apps/chat/server/db/schema.ts@@ -1,4 +1,4 @@-import { sqliteTable, text, integer, index, uniqueIndex } from 'drizzle-orm/sqlite-core'+import { sqliteTable, text, integer, index, uniqueIndex, real } from 'drizzle-orm/sqlite-core'import { relations } from 'drizzle-orm'const timestamps = {@@ -59,26 +59,32 @@ export const messagesRelations = relations(messages, ({ one }) => ({export const sources = sqliteTable('sources', {id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),type: text('type', { enum: ['github', 'youtube'] }).notNull(),-- // Common fieldslabel: text('label').notNull(),-- // Common output fieldbasePath: text('base_path').default('/docs'),-- // GitHub fieldsrepo: text('repo'),branch: text('branch'),contentPath: text('content_path'),outputPath: text('output_path'),readmeOnly: integer('readme_only', { mode: 'boolean' }).default(false),-- // YouTube fieldschannelId: text('channel_id'),handle: text('handle'),maxVideos: integer('max_videos').default(50),-- // Metadata...timestamps,updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),}, table => [index('sources_type_idx').on(table.type)])++export const agentConfig = sqliteTable('agent_config', {+ id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),+ name: text('name').notNull().default('default'),+ additionalPrompt: text('additional_prompt'),+ responseStyle: text('response_style', { enum: ['concise', 'detailed', 'technical', 'friendly'] }).default('concise'),+ language: text('language').default('en'),+ defaultModel: text('default_model'),+ maxStepsMultiplier: real('max_steps_multiplier').default(1.0),+ temperature: real('temperature').default(0.7),+ searchInstructions: text('search_instructions'),+ citationFormat: text('citation_format', { enum: ['inline', 'footnote', 'none'] }).default('inline'),+ isActive: integer('is_active', { mode: 'boolean' }).notNull().default(true),+ ...timestamps,+ updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),+})diff --git a/apps/chat/server/middleware/api-auth.ts b/apps/chat/server/middleware/api-auth.tsindex 1b9680d..74d45ac 100644--- a/apps/chat/server/middleware/api-auth.ts+++ b/apps/chat/server/middleware/api-auth.ts@@ -13,20 +13,17 @@export default defineEventHandler((event) => {const path = getRequestURL(event).pathname- // Only protect sync and sandbox routesif (!path.startsWith('/api/sync') && !path.startsWith('/api/sandbox')) {- return // Let other routes pass through+ return}const config = useRuntimeConfig()const secretKey = config.savoirSecretKey- // If no secret key configured, skip authentication (dev mode)if (!secretKey) {return}- // Validate API keyconst authHeader = getHeader(event, 'Authorization')const apiKey = authHeader?.replace('Bearer ', '')diff --git a/apps/chat/server/routes/auth/github.get.ts b/apps/chat/server/routes/auth/github.get.tsindex 48bc543..6aeeea6 100644--- a/apps/chat/server/routes/auth/github.get.ts+++ b/apps/chat/server/routes/auth/github.get.ts@@ -11,7 +11,6 @@ export default defineOAuthGitHubEventHandler({async onSuccess(event, { user: ghUser }) {const session = await getUserSession(event)- // Check if user already existsconst existingUser = await db.query.users.findFirst({where: and(eq(schema.users.provider, 'github'),@@ -20,14 +19,12 @@ export default defineOAuthGitHubEventHandler({})if (existingUser) {- // Migrate anonymous chats to authenticated userif (session.user?.id && session.user.id !== existingUser.id) {await db.update(schema.chats).set({ userId: existingUser.id }).where(eq(schema.chats.userId, session.user.id))}- // Update role if it changedconst newRole = isAdminUser(existingUser.email, existingUser.username) ? 'admin' : 'user'if (existingUser.role !== newRole) {await db.update(schema.users)@@ -53,7 +50,6 @@ export default defineOAuthGitHubEventHandler({throw createError({ statusCode: 500, message: 'Failed to create user' })}- // Migrate anonymous chats to new userif (session.user?.id) {await db.update(schema.chats).set({ userId: newUser.id })diff --git a/apps/chat/server/utils/agent-config.ts b/apps/chat/server/utils/agent-config.tsnew file mode 100644index 0000000..680a82f--- /dev/null+++ b/apps/chat/server/utils/agent-config.ts@@ -0,0 +1,77 @@+import { kv } from '@nuxthub/kv'+import { db, schema } from '@nuxthub/db'+import { eq } from 'drizzle-orm'+import { KV_KEYS } from './sandbox/types'++export interface AgentConfigData {+ id: string+ name: string+ additionalPrompt: string | null+ responseStyle: 'concise' | 'detailed' | 'technical' | 'friendly'+ language: string+ defaultModel: string | null+ maxStepsMultiplier: number+ temperature: number+ searchInstructions: string | null+ citationFormat: 'inline' | 'footnote' | 'none'+ isActive: boolean+}++const DEFAULT_CONFIG: AgentConfigData = {+ id: 'default',+ name: 'default',+ additionalPrompt: null,+ responseStyle: 'concise',+ language: 'en',+ defaultModel: null,+ maxStepsMultiplier: 1.0,+ temperature: 0.7,+ searchInstructions: null,+ citationFormat: 'inline',+ isActive: true,+}++const CACHE_TTL_SECONDS = 60 // 1 minute++export async function invalidateAgentConfigCache(): Promise<void> {+ await kv.del(KV_KEYS.AGENT_CONFIG_CACHE)+}++export async function getAgentConfig(): Promise<AgentConfigData> {+ const cached = await kv.get<AgentConfigData>(KV_KEYS.AGENT_CONFIG_CACHE)+ if (cached) {+ return cached+ }++ const config = await db.query.agentConfig.findFirst({+ where: () => eq(schema.agentConfig.isActive, true),+ })++ let result: AgentConfigData++ if (config) {+ result = {+ id: config.id,+ name: config.name,+ additionalPrompt: config.additionalPrompt,+ responseStyle: config.responseStyle || 'concise',+ language: config.language || 'en',+ defaultModel: config.defaultModel,+ maxStepsMultiplier: config.maxStepsMultiplier || 1.0,+ temperature: config.temperature || 0.7,+ searchInstructions: config.searchInstructions,+ citationFormat: config.citationFormat || 'inline',+ isActive: config.isActive,+ }+ } else {+ result = DEFAULT_CONFIG+ }++ await kv.set(KV_KEYS.AGENT_CONFIG_CACHE, result, { ttl: CACHE_TTL_SECONDS })++ return result+}++export function getDefaultAgentConfig(): AgentConfigData {+ return { ...DEFAULT_CONFIG }+}diff --git a/apps/chat/server/utils/router/route-question.ts b/apps/chat/server/utils/router/route-question.tsindex 7fc0097..cf65d03 100644--- a/apps/chat/server/utils/router/route-question.ts+++ b/apps/chat/server/utils/router/route-question.ts@@ -32,11 +32,9 @@ Analyze the user's question and determine the appropriate configuration for theUse claude-opus-4.5 only for the most complex cases requiring deep reasoning.`function extractQuestionFromMessages(messages: UIMessage[]): string {- // Get the last user messageconst lastUserMessage = [...messages].reverse().find(m => m.role === 'user')if (!lastUserMessage) return ''- // Extract text from message partsconst textParts = lastUserMessage.parts?.filter((p): p is { type: 'text', text: string } => p.type === 'text').map(p => p.text)diff --git a/apps/chat/server/utils/sandbox/types.ts b/apps/chat/server/utils/sandbox/types.tsindex d30ca61..8e0cd43 100644--- a/apps/chat/server/utils/sandbox/types.ts+++ b/apps/chat/server/utils/sandbox/types.ts@@ -32,5 +32,6 @@ export const KV_KEYS = {CURRENT_SNAPSHOT: 'snapshot:current',SNAPSHOT_STATUS_CACHE: 'snapshot:status-cache',LAST_SOURCE_SYNC: 'sources:last-sync',+ AGENT_CONFIG_CACHE: 'agent:config-cache',session: (sessionId: string) => `session:${sessionId}`,} as constdiff --git a/apps/github-bot/package.json b/apps/github-bot/package.jsonindex 8d8fdd0..af56daa 100644--- a/apps/github-bot/package.json+++ b/apps/github-bot/package.json@@ -14,17 +14,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"}}diff --git a/apps/github-bot/server/api/webhook.post.ts b/apps/github-bot/server/api/webhook.post.tsindex e2bbaf7..13b55bd 100644--- a/apps/github-bot/server/api/webhook.post.ts+++ b/apps/github-bot/server/api/webhook.post.ts@@ -1,15 +1,80 @@import { log } from 'evlog'-import { useGitHubChat } from '../utils/chat'+import { useGitHub } from '../utils/github'+import { handleMention } from '../utils/handler'+import type { GitHubIssueCommentPayload, GitHubIssuesPayload } from '../utils/types'export default defineEventHandler(async (event) => {- const chat = useGitHubChat()- const request = toWebRequest(event)+ const github = useGitHub()+ const body = await readRawBody(event) || ''+ const signature = getHeader(event, 'X-Hub-Signature-256')- try {- await chat.webhooks?.github?.(request)+ if (!github.verifySignature(body, signature || null)) {+ setResponseStatus(event, 401)+ return { error: 'Invalid signature' }}- catch (error) {- log.error('github-bot', `Webhook error: ${error instanceof Error ? error.message : 'Unknown'}`)++ const eventType = getHeader(event, 'X-GitHub-Event')++ if (eventType === 'ping') {+ return { ok: true, message: 'pong' }+ }++ if (eventType === 'issue_comment') {+ const payload = JSON.parse(body) as GitHubIssueCommentPayload++ if (payload.action !== 'created') {+ return { ok: true }+ }++ const botUserName = `${github.userName}[bot]`+ if (payload.comment.user.login === github.userName || payload.comment.user.login === botUserName) {+ return { ok: true }+ }++ const threadId = github.encodeThreadId({+ owner: payload.repository.owner.login,+ repo: payload.repository.name,+ issueNumber: payload.issue.number,+ })++ handleMention({+ threadId,+ messageId: String(payload.comment.id),+ text: payload.comment.body,+ }).catch(error => {+ log.error('github-bot', `Webhook handler error: ${error instanceof Error ? error.message : 'Unknown'}`)+ })++ return { ok: true }+ }++ if (eventType === 'issues') {+ const payload = JSON.parse(body) as GitHubIssuesPayload++ if (payload.action !== 'opened') {+ return { ok: true }+ }++ const botUserName = `${github.userName}[bot]`+ if (payload.issue.user.login === github.userName || payload.issue.user.login === botUserName) {+ return { ok: true }+ }++ const threadId = github.encodeThreadId({+ owner: payload.repository.owner.login,+ repo: payload.repository.name,+ issueNumber: payload.issue.number,+ })++ handleMention({+ threadId,+ messageId: `issue:${payload.issue.number}`,+ text: `${payload.issue.title}\n\n${payload.issue.body || ''}`,+ }).catch(error => {+ log.error('github-bot', `Webhook handler error: ${error instanceof Error ? error.message : 'Unknown'}`)+ })++ return { ok: true }}return { ok: true }diff --git a/apps/github-bot/server/utils/adapter.ts b/apps/github-bot/server/utils/adapter.tsdeleted file mode 100644index da068d4..0000000--- a/apps/github-bot/server/utils/adapter.ts+++ /dev/null@@ -1,528 +0,0 @@-import { createHmac, timingSafeEqual } from 'node:crypto'-import type {- Adapter,- AdapterPostableMessage,- ChatInstance,- EmojiValue,- FetchOptions,- FetchResult,- FormattedContent,- RawMessage,- ThreadInfo,- WebhookOptions,-} from 'chat'-import { Message, NotImplementedError } from 'chat'-import { createGitHubAuth, type GitHubAuth } from './auth'-import { GitHubFormatConverter } from './markdown'-import type {- GitHubAdapterConfig,- GitHubComment,- GitHubIssueCommentPayload,- GitHubIssuesPayload,- GitHubThreadId,- IssueContext,-} from './types'--export class GitHubAdapter implements Adapter<GitHubThreadId, GitHubComment> {-- readonly name = 'github'- readonly userName: string-- private chat!: ChatInstance- private webhookSecret: string- private auth: GitHubAuth- private formatConverter: GitHubFormatConverter-- constructor(config: GitHubAdapterConfig) {- this.userName = config.userName- this.webhookSecret = config.webhookSecret- this.auth = createGitHubAuth(config.appId, config.appPrivateKey)- this.formatConverter = new GitHubFormatConverter()- }-- private getToken(owner: string, repo: string): Promise<string> {- return this.auth.getToken(owner, repo)- }-- async initialize(chat: ChatInstance): Promise<void> {- this.chat = chat- }-- async handleWebhook(request: Request, options?: WebhookOptions): Promise<Response> {- const body = await request.text()-- const signature = request.headers.get('X-Hub-Signature-256')- if (!this.verifySignature(body, signature)) {- return new Response('Invalid signature', { status: 401 })- }-- const event = request.headers.get('X-GitHub-Event')-- if (event === 'ping') {- return new Response('pong', { status: 200 })- }-- if (event === 'issue_comment') {- return this.handleIssueComment(body, options)- }-- if (event === 'issues') {- return this.handleIssueEvent(body, options)- }-- return new Response('OK', { status: 200 })- }-- private handleIssueComment(body: string, options?: WebhookOptions): Response {- const payload = JSON.parse(body) as GitHubIssueCommentPayload-- if (payload.action !== 'created') {- return new Response('OK', { status: 200 })- }-- const botUserName = `${this.userName}[bot]`- if (payload.comment.user.login === this.userName || payload.comment.user.login === botUserName) {- return new Response('OK', { status: 200 })- }-- const threadId = this.encodeThreadId({- owner: payload.repository.owner.login,- repo: payload.repository.name,- issueNumber: payload.issue.number,- })-- const message = this.parseMessage(payload.comment)- this.chat.processMessage(this, threadId, message, options)-- return new Response('OK', { status: 200 })- }-- private handleIssueEvent(body: string, options?: WebhookOptions): Response {- const payload = JSON.parse(body) as GitHubIssuesPayload-- if (payload.action !== 'opened') {- return new Response('OK', { status: 200 })- }-- const botUserName = `${this.userName}[bot]`- if (payload.issue.user.login === this.userName || payload.issue.user.login === botUserName) {- return new Response('OK', { status: 200 })- }-- const threadId = this.encodeThreadId({- owner: payload.repository.owner.login,- repo: payload.repository.name,- issueNumber: payload.issue.number,- })-- const virtualComment = {- id: `issue:${payload.issue.number}` as unknown as number,- node_id: `issue_${payload.issue.id}`,- body: `${payload.issue.title}\n\n${payload.issue.body || ''}`,- user: {- id: payload.issue.user.id,- login: payload.issue.user.login,- avatar_url: payload.issue.user.avatar_url,- type: 'User',- },- created_at: payload.issue.created_at,- updated_at: payload.issue.updated_at,- html_url: payload.issue.html_url,- issue_url: payload.issue.html_url,- } as GitHubComment-- const message = this.parseMessage(virtualComment)- this.chat.processMessage(this, threadId, message, options)-- return new Response('OK', { status: 200 })- }-- private verifySignature(body: string, signature: string | null): boolean {- if (!signature || !this.webhookSecret) {- return false- }-- const expected = `sha256=${createHmac('sha256', this.webhookSecret).update(body).digest('hex')}`-- try {- return timingSafeEqual(Buffer.from(signature), Buffer.from(expected))- } catch {- return false- }- }-- async postMessage(threadId: string, message: AdapterPostableMessage): Promise<RawMessage<GitHubComment>> {- const { owner, repo, issueNumber } = this.decodeThreadId(threadId)- const body = this.renderPostable(message)- const token = await this.getToken(owner, repo)-- const response = await fetch(- `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/comments`,- {- method: 'POST',- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'Content-Type': 'application/json',- 'X-GitHub-Api-Version': '2022-11-28',- },- body: JSON.stringify({ body }),- },- )-- if (!response.ok) {- const error = await response.text()- throw new Error(`GitHub API error: ${response.status} - ${error}`)- }-- const data = (await response.json()) as GitHubComment- return { id: String(data.id), threadId, raw: data }- }-- async editMessage(threadId: string, messageId: string, message: AdapterPostableMessage): Promise<RawMessage<GitHubComment>> {- const { owner, repo } = this.decodeThreadId(threadId)- const body = this.renderPostable(message)- const token = await this.getToken(owner, repo)-- const response = await fetch(- `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}`,- {- method: 'PATCH',- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'Content-Type': 'application/json',- 'X-GitHub-Api-Version': '2022-11-28',- },- body: JSON.stringify({ body }),- },- )-- if (!response.ok) {- const error = await response.text()- throw new Error(`GitHub API error: ${response.status} - ${error}`)- }-- const data = (await response.json()) as GitHubComment- return { id: String(data.id), threadId, raw: data }- }-- async deleteMessage(threadId: string, messageId: string): Promise<void> {- const { owner, repo } = this.decodeThreadId(threadId)- const token = await this.getToken(owner, repo)-- const response = await fetch(- `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}`,- {- method: 'DELETE',- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'X-GitHub-Api-Version': '2022-11-28',- },- },- )-- if (!response.ok && response.status !== 404) {- const error = await response.text()- throw new Error(`GitHub API error: ${response.status} - ${error}`)- }- }-- async addReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void> {- const { owner, repo, issueNumber } = this.decodeThreadId(threadId)- const reaction = this.emojiToGitHubReaction(emoji)- const token = await this.getToken(owner, repo)-- const isIssue = messageId.startsWith('issue:')- const url = isIssue- ? `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/reactions`- : `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}/reactions`-- const response = await fetch(url, {- method: 'POST',- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'Content-Type': 'application/json',- 'X-GitHub-Api-Version': '2022-11-28',- },- body: JSON.stringify({ content: reaction }),- })-- if (!response.ok) {- const error = await response.text()- throw new Error(`GitHub API error: ${response.status} - ${error}`)- }- }-- async removeReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void> {- const { owner, repo, issueNumber } = this.decodeThreadId(threadId)- const reaction = this.emojiToGitHubReaction(emoji)- const token = await this.getToken(owner, repo)-- const isIssue = messageId.startsWith('issue:')- const baseUrl = isIssue- ? `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/reactions`- : `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}/reactions`-- const listResponse = await fetch(baseUrl, {- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'X-GitHub-Api-Version': '2022-11-28',- },- })-- if (!listResponse.ok) return-- const reactions = (await listResponse.json()) as Array<{- id: number- content: string- user: { login: string }- }>-- const botUserName = `${this.userName}[bot]`- const ourReaction = reactions.find(- r => r.content === reaction && (r.user.login === this.userName || r.user.login === botUserName),- )-- if (!ourReaction) return-- await fetch(`${baseUrl}/${ourReaction.id}`, {- method: 'DELETE',- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'X-GitHub-Api-Version': '2022-11-28',- },- })- }-- private emojiToGitHubReaction(emoji: EmojiValue | string): string {- const name = typeof emoji === 'string' ? emoji : emoji.name- const mapping: Record<string, string> = {- thumbs_up: '+1',- thumbs_down: '-1',- laugh: 'laugh',- confused: 'confused',- heart: 'heart',- party: 'hooray',- rocket: 'rocket',- eyes: 'eyes',- }- return mapping[name] || 'eyes'- }-- async startTyping(): Promise<void> {}-- async fetchMessages(threadId: string, options?: FetchOptions): Promise<FetchResult<GitHubComment>> {- const { owner, repo, issueNumber } = this.decodeThreadId(threadId)- const limit = options?.limit || 30- const direction = options?.direction || 'backward'-- let url = `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/comments?per_page=${limit}`- if (options?.cursor) {- url += `&page=${options.cursor}`- }- url += '&sort=created&direction=asc'-- const token = await this.getToken(owner, repo)-- const response = await fetch(url, {- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'X-GitHub-Api-Version': '2022-11-28',- },- })-- if (!response.ok) {- const error = await response.text()- throw new Error(`GitHub API error: ${response.status} - ${error}`)- }-- const comments = (await response.json()) as GitHubComment[]-- const linkHeader = response.headers.get('Link')- let nextCursor: string | undefined-- if (linkHeader) {- const nextMatch = linkHeader.match(/<[^>]+[?&]page=(\d+)[^>]*>;\s*rel="next"/)- if (nextMatch) {- nextCursor = nextMatch[1]- }- }-- const messages = comments.map(comment => this.parseMessage(comment))-- if (direction === 'backward') {- messages.reverse()- }-- return { messages, nextCursor }- }-- async fetchThread(threadId: string): Promise<ThreadInfo> {- const { owner, repo, issueNumber } = this.decodeThreadId(threadId)- const token = await this.getToken(owner, repo)-- const response = await fetch(- `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}`,- {- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'X-GitHub-Api-Version': '2022-11-28',- },- },- )-- if (!response.ok) {- const error = await response.text()- throw new Error(`GitHub API error: ${response.status} - ${error}`)- }-- const issue = (await response.json()) as {- number: number- title: string- state: string- html_url: string- }-- return {- id: threadId,- channelId: `${owner}/${repo}`,- channelName: `${owner}/${repo}#${issueNumber}`,- isDM: false,- metadata: {- title: issue.title,- state: issue.state,- url: issue.html_url,- },- }- }-- async fetchIssueContext(threadId: string): Promise<IssueContext> {- const { owner, repo, issueNumber } = this.decodeThreadId(threadId)- const token = await this.getToken(owner, repo)-- const issueResponse = await fetch(- `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}`,- {- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'X-GitHub-Api-Version': '2022-11-28',- },- },- )-- if (!issueResponse.ok) {- const error = await issueResponse.text()- throw new Error(`GitHub API error: ${issueResponse.status} - ${error}`)- }-- const issue = (await issueResponse.json()) as {- number: number- title: string- body: string | null- state: string- labels: Array<{ name: string }>- }-- const commentsResponse = await fetch(- `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/comments?per_page=10&sort=created&direction=desc`,- {- headers: {- 'Authorization': `Bearer ${token}`,- 'Accept': 'application/vnd.github.v3+json',- 'X-GitHub-Api-Version': '2022-11-28',- },- },- )-- let previousComments: Array<{ author: string, body: string, isBot: boolean }> = []- if (commentsResponse.ok) {- const comments = (await commentsResponse.json()) as Array<{- user: { login: string, type: string }- body: string- }>-- previousComments = comments.reverse().map(c => ({- author: c.user.login,- body: c.body,- isBot: c.user.type === 'Bot',- }))- }-- return {- number: issue.number,- title: issue.title,- body: issue.body,- labels: issue.labels.map(l => l.name),- state: issue.state,- owner,- repo,- previousComments,- }- }-- encodeThreadId(data: GitHubThreadId): string {- return `github:${data.owner}/${data.repo}:issue:${data.issueNumber}`- }-- 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}`)- }-- return {- owner: match[1],- repo: match[2],- issueNumber: Number.parseInt(match[3], 10),- }- }-- parseMessage(raw: GitHubComment): Message<GitHubComment> {- return new Message<GitHubComment>({- id: String(raw.id),- threadId: '',- text: raw.body,- formatted: this.formatConverter.toAst(raw.body),- raw,- author: {- userId: String(raw.user.id),- userName: raw.user.login,- fullName: raw.user.login,- isBot: raw.user.type === 'Bot',- isMe: raw.user.login === this.userName || raw.user.login === `${this.userName}[bot]`,- },- metadata: {- dateSent: new Date(raw.created_at),- edited: raw.created_at !== raw.updated_at,- editedAt: raw.created_at !== raw.updated_at ? new Date(raw.updated_at) : undefined,- },- attachments: [],- })- }-- renderFormatted(content: FormattedContent): string {- return this.formatConverter.fromAst(content)- }-- private renderPostable(message: AdapterPostableMessage): string {- if (typeof message === 'string') return message- if ('raw' in message) return message.raw- if ('markdown' in message) return message.markdown- if ('ast' in message) return this.formatConverter.fromAst(message.ast)- if ('card' in message) throw new NotImplementedError('Cards are not supported on GitHub')- throw new NotImplementedError('Cards are not supported on GitHub')- }--}--export function createGitHubAdapter(config: GitHubAdapterConfig): GitHubAdapter {- return new GitHubAdapter(config)-}diff --git a/apps/github-bot/server/utils/ai.ts b/apps/github-bot/server/utils/ai.tsindex 6b8226c..c6ea185 100644--- a/apps/github-bot/server/utils/ai.ts+++ b/apps/github-bot/server/utils/ai.ts@@ -1,7 +1,7 @@import { createGateway } from '@ai-sdk/gateway'import { generateText, Output, stepCountIs, ToolLoopAgent } from 'ai'import { log } from 'evlog'-import { createSavoir } from '@savoir/sdk'+import { createSavoir, type AgentConfig as SavoirAgentConfig } from '@savoir/sdk'import type { IssueContext } from './types'import { type AgentConfig, agentConfigSchema, getDefaultConfig } from './router-schema'@@ -102,10 +102,6 @@ Once configured, I'll be able to search the documentation and help answer your qlet toolCallCount = 0try {- const agentConfig = await routeQuestion(question, context)-- log.info('github-bot', `Starting agent for issue #${context?.number || 'unknown'} with ${agentConfig.complexity} complexity`)-const savoir = createSavoir({apiUrl: config.savoir.apiUrl,apiKey: config.savoir.apiKey || undefined,@@ -116,11 +112,26 @@ Once configured, I'll be able to search the documentation and help answer your q},})+ const [routerConfig, savoirConfig] = await Promise.all([+ routeQuestion(question, context),+ savoir.getAgentConfig().catch((error) => {+ log.warn('github-bot', `Failed to fetch agent config: ${error instanceof Error ? error.message : 'Unknown error'}`)+ return null+ }),+ ])++ const effectiveMaxSteps = savoirConfig+ ? Math.round(routerConfig.maxSteps * savoirConfig.maxStepsMultiplier)+ : routerConfig.maxSteps+ const effectiveModel = savoirConfig?.defaultModel || routerConfig.model++ log.info('github-bot', `Starting agent for issue #${context?.number || 'unknown'} with ${routerConfig.complexity} complexity (${effectiveMaxSteps} steps, multiplier: ${savoirConfig?.maxStepsMultiplier || 1}x)`)+const agent = new ToolLoopAgent({- model: agentConfig.model,- instructions: buildSystemPrompt(context, agentConfig),+ model: effectiveModel,+ instructions: buildSystemPrompt(context, routerConfig, savoirConfig),tools: savoir.tools,- stopWhen: stepCountIs(agentConfig.maxSteps),+ stopWhen: stepCountIs(effectiveMaxSteps),onStepFinish: ({ usage, toolCalls }) => {stepCount++totalInputTokens += usage.inputTokens || 0@@ -170,7 +181,7 @@ Please try again later or open a discussion if this persists.`}}-function buildSystemPrompt(context?: IssueContext, agentConfig?: AgentConfig): string {+function buildSystemPrompt(context?: IssueContext, agentConfig?: AgentConfig, savoirConfig?: SavoirAgentConfig | null): string {const basePrompt = `You are a documentation assistant with bash access to a sandbox containing docs (markdown, JSON, YAML).## Speed is Important@@ -202,6 +213,34 @@ ls docs/ && grep -rl "keyword" docs/ --include="*.md" | head -10let prompt = basePrompt+ if (savoirConfig) {+ const styleInstructions: Record<SavoirAgentConfig['responseStyle'], string> = {+ concise: 'Keep your responses brief and to the point.',+ detailed: 'Provide comprehensive explanations with context.',+ technical: 'Focus on technical details and include code examples.',+ friendly: 'Be conversational and approachable in your responses.',+ }++ if (savoirConfig.responseStyle !== 'concise') {+ prompt = prompt.replace(+ '## Response\n- Be concise and helpful',+ `## Response\n- ${styleInstructions[savoirConfig.responseStyle]}`,+ )+ }++ if (savoirConfig.language && savoirConfig.language !== 'en') {+ prompt += `\n\n## Language\nRespond in ${savoirConfig.language}.`+ }++ if (savoirConfig.searchInstructions) {+ prompt += `\n\n## Custom Search Instructions\n${savoirConfig.searchInstructions}`+ }++ if (savoirConfig.additionalPrompt) {+ prompt += `\n\n## Additional Instructions\n${savoirConfig.additionalPrompt}`+ }+ }+if (agentConfig) {const complexityHints: Record<AgentConfig['complexity'], string> = {trivial: 'This is a simple greeting or acknowledgment. Respond briefly without searching.',diff --git a/apps/github-bot/server/utils/chat.ts b/apps/github-bot/server/utils/chat.tsdeleted file mode 100644index 60ccf38..0000000--- a/apps/github-bot/server/utils/chat.ts+++ /dev/null@@ -1,77 +0,0 @@-import { Chat } from 'chat'-import { log } from 'evlog'-import { createGitHubAdapter, type GitHubAdapter } from './adapter'-import { generateAIResponse } from './ai'-import { KVStateAdapter } from './state-kv'-import type { IssueContext } from './types'--let chatInstance: Chat | null = null--export function useGitHubChat(): Chat {- if (chatInstance) {- return chatInstance- }-- const config = useRuntimeConfig()-- if (!config.github.webhookSecret) {- throw new Error('NUXT_GITHUB_WEBHOOK_SECRET is required')- }-- const botTrigger = config.public.botTrigger as string- const botUserName = botTrigger.replace('@', '')-- if (!config.github.appId || !config.github.appPrivateKey) {- throw new Error('NUXT_GITHUB_APP_ID and NUXT_GITHUB_APP_PRIVATE_KEY are required')- }-- chatInstance = new Chat({- userName: botUserName,- adapters: {- github: createGitHubAdapter({- userName: botUserName,- webhookSecret: config.github.webhookSecret,- appId: config.github.appId,- appPrivateKey: config.github.appPrivateKey,- }),- },- state: new KVStateAdapter(),- logger: 'info',- })-- chatInstance.onNewMention(async (thread, message) => {- try {- const adapter = thread.adapter as GitHubAdapter- await adapter.addReaction(thread.id, message.id, 'eyes')-- let issueContext: IssueContext | undefined- try {- issueContext = await adapter.fetchIssueContext(thread.id)- }- catch {- // Continue without issue context- }-- const response = await generateAIResponse(message.text, issueContext)-- await thread.post({ markdown: response })-- await adapter.removeReaction(thread.id, message.id, 'eyes')- await adapter.addReaction(thread.id, message.id, 'thumbs_up')- }- catch (error) {- log.error('github-bot', `Error: ${error instanceof Error ? error.message : 'Unknown'}`)-- try {- await thread.post({- markdown: `Sorry, I encountered an error while processing your request. Please try again later.\n\n<details>\n<summary>Error details</summary>\n\n\`\`\`\n${error instanceof Error ? error.message : 'Unknown error'}\n\`\`\`\n</details>`,- })- }- catch {- // Ignore error posting failure- }- }- })-- return chatInstance-}diff --git a/apps/github-bot/server/utils/github.ts b/apps/github-bot/server/utils/github.tsnew file mode 100644index 0000000..224ce12--- /dev/null+++ b/apps/github-bot/server/utils/github.ts@@ -0,0 +1,246 @@+import { createHmac, timingSafeEqual } from 'node:crypto'+import { createGitHubAuth, type GitHubAuth } from './auth'+import type { GitHubThreadId, IssueContext } from './types'++export interface GitHubConfig {+ userName: string+ webhookSecret: string+ appId: string+ appPrivateKey: string+}++let githubInstance: GitHubClient | null = null++export class GitHubClient {+ readonly userName: string+ private webhookSecret: string+ private auth: GitHubAuth++ constructor(config: GitHubConfig) {+ this.userName = config.userName+ this.webhookSecret = config.webhookSecret+ this.auth = createGitHubAuth(config.appId, config.appPrivateKey)+ }++ private getToken(owner: string, repo: string): Promise<string> {+ return this.auth.getToken(owner, repo)+ }++ verifySignature(body: string, signature: string | null): boolean {+ if (!signature || !this.webhookSecret) {+ return false+ }++ const expected = `sha256=${createHmac('sha256', this.webhookSecret).update(body).digest('hex')}`++ try {+ return timingSafeEqual(Buffer.from(signature), Buffer.from(expected))+ } catch {+ return false+ }+ }++ encodeThreadId(data: GitHubThreadId): string {+ return `github:${data.owner}/${data.repo}:issue:${data.issueNumber}`+ }++ 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}`)+ }++ return {+ owner: match[1],+ repo: match[2],+ issueNumber: Number.parseInt(match[3], 10),+ }+ }++ async postComment(threadId: string, body: string): Promise<{ id: number }> {+ const { owner, repo, issueNumber } = this.decodeThreadId(threadId)+ const token = await this.getToken(owner, repo)++ const response = await fetch(+ `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/comments`,+ {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'Content-Type': 'application/json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ body: JSON.stringify({ body }),+ },+ )++ if (!response.ok) {+ const error = await response.text()+ throw new Error(`GitHub API error: ${response.status} - ${error}`)+ }++ return response.json() as Promise<{ id: number }>+ }++ async addReaction(threadId: string, messageId: string, reaction: string): Promise<void> {+ const { owner, repo, issueNumber } = this.decodeThreadId(threadId)+ const token = await this.getToken(owner, repo)++ const isIssue = messageId.startsWith('issue:')+ const url = isIssue+ ? `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/reactions`+ : `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}/reactions`++ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'Content-Type': 'application/json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ body: JSON.stringify({ content: reaction }),+ })++ if (!response.ok) {+ const error = await response.text()+ throw new Error(`GitHub API error: ${response.status} - ${error}`)+ }+ }++ async removeReaction(threadId: string, messageId: string, reaction: string): Promise<void> {+ const { owner, repo, issueNumber } = this.decodeThreadId(threadId)+ const token = await this.getToken(owner, repo)++ const isIssue = messageId.startsWith('issue:')+ const baseUrl = isIssue+ ? `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/reactions`+ : `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}/reactions`++ const listResponse = await fetch(baseUrl, {+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ })++ if (!listResponse.ok) return++ const reactions = (await listResponse.json()) as Array<{+ id: number+ content: string+ user: { login: string }+ }>++ const botUserName = `${this.userName}[bot]`+ const ourReaction = reactions.find(+ r => r.content === reaction && (r.user.login === this.userName || r.user.login === botUserName),+ )++ if (!ourReaction) return++ await fetch(`${baseUrl}/${ourReaction.id}`, {+ method: 'DELETE',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ })+ }++ async fetchIssueContext(threadId: string): Promise<IssueContext> {+ const { owner, repo, issueNumber } = this.decodeThreadId(threadId)+ const token = await this.getToken(owner, repo)++ const issueResponse = await fetch(+ `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}`,+ {+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ },+ )++ if (!issueResponse.ok) {+ const error = await issueResponse.text()+ throw new Error(`GitHub API error: ${issueResponse.status} - ${error}`)+ }++ const issue = (await issueResponse.json()) as {+ number: number+ title: string+ body: string | null+ state: string+ labels: Array<{ name: string }>+ }++ const commentsResponse = await fetch(+ `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/comments?per_page=10&sort=created&direction=desc`,+ {+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ },+ )++ let previousComments: Array<{ author: string, body: string, isBot: boolean }> = []+ if (commentsResponse.ok) {+ const comments = (await commentsResponse.json()) as Array<{+ user: { login: string, type: string }+ body: string+ }>++ previousComments = comments.reverse().map(c => ({+ author: c.user.login,+ body: c.body,+ isBot: c.user.type === 'Bot',+ }))+ }++ return {+ number: issue.number,+ title: issue.title,+ body: issue.body,+ labels: issue.labels.map(l => l.name),+ state: issue.state,+ owner,+ repo,+ previousComments,+ }+ }+}++export function useGitHub(): GitHubClient {+ if (githubInstance) {+ return githubInstance+ }++ const config = useRuntimeConfig()++ if (!config.github.webhookSecret) {+ throw new Error('NUXT_GITHUB_WEBHOOK_SECRET is required')+ }++ const botTrigger = config.public.botTrigger as string+ const botUserName = botTrigger.replace('@', '')++ if (!config.github.appId || !config.github.appPrivateKey) {+ throw new Error('NUXT_GITHUB_APP_ID and NUXT_GITHUB_APP_PRIVATE_KEY are required')+ }++ githubInstance = new GitHubClient({+ userName: botUserName,+ webhookSecret: config.github.webhookSecret,+ appId: config.github.appId,+ appPrivateKey: config.github.appPrivateKey,+ })++ return githubInstance+}diff --git a/apps/github-bot/server/utils/handler.ts b/apps/github-bot/server/utils/handler.tsnew file mode 100644index 0000000..b72f93f--- /dev/null+++ b/apps/github-bot/server/utils/handler.ts@@ -0,0 +1,45 @@+import { log } from 'evlog'+import { generateAIResponse } from './ai'+import { useGitHub, type GitHubClient } from './github'+import type { IssueContext } from './types'++export interface MentionContext {+ threadId: string+ messageId: string+ text: string+}++export async function handleMention(ctx: MentionContext): Promise<void> {+ const github = useGitHub()++ try {+ await github.addReaction(ctx.threadId, ctx.messageId, 'eyes')++ let issueContext: IssueContext | undefined+ try {+ issueContext = await github.fetchIssueContext(ctx.threadId)+ } catch {}+++ const response = await generateAIResponse(ctx.text, issueContext)++ await github.postComment(ctx.threadId, response)++ await github.removeReaction(ctx.threadId, ctx.messageId, 'eyes')+ await github.addReaction(ctx.threadId, ctx.messageId, '+1')+ } catch (error) {+ log.error('github-bot', `Error: ${error instanceof Error ? error.message : 'Unknown'}`)++ try {+ await github.postComment(ctx.threadId, `Sorry, I encountered an error while processing your request. Please try again later.++<details>+<summary>Error details</summary>++\`\`\`+${error instanceof Error ? error.message : 'Unknown error'}+\`\`\`+</details>`)+ } catch {}+ }+}diff --git a/apps/github-bot/server/utils/markdown.ts b/apps/github-bot/server/utils/markdown.tsdeleted file mode 100644index e249c27..0000000--- a/apps/github-bot/server/utils/markdown.ts+++ /dev/null@@ -1,22 +0,0 @@-import type { Root } from 'mdast'-import { fromMarkdown } from 'mdast-util-from-markdown'-import { gfmFromMarkdown, gfmToMarkdown } from 'mdast-util-gfm'-import { toMarkdown } from 'mdast-util-to-markdown'-import { gfm } from 'micromark-extension-gfm'--export class GitHubFormatConverter {-- toAst(text: string): Root {- return fromMarkdown(text, {- extensions: [gfm()],- mdastExtensions: [gfmFromMarkdown()],- })- }-- fromAst(ast: Root): string {- return toMarkdown(ast, {- extensions: [gfmToMarkdown()],- })- }--}diff --git a/apps/github-bot/server/utils/state-kv.ts b/apps/github-bot/server/utils/state-kv.tsdeleted file mode 100644index 0cd2000..0000000--- a/apps/github-bot/server/utils/state-kv.ts+++ /dev/null@@ -1,92 +0,0 @@-import type { Lock, StateAdapter } from 'chat'-import { kv } from 'hub:kv'--export class KVStateAdapter implements StateAdapter {--- async connect(): Promise<void> {}--- async disconnect(): Promise<void> {}-- async subscribe(threadId: string): Promise<void> {- await kv.set(`chat:sub:${threadId}`, true)- }-- async unsubscribe(threadId: string): Promise<void> {- await kv.del(`chat:sub:${threadId}`)- }-- async isSubscribed(threadId: string): Promise<boolean> {- return await kv.has(`chat:sub:${threadId}`)- }-- async *listSubscriptions(adapterName?: string): AsyncIterable<string> {- const keys = await kv.keys('chat:sub:')- for (const key of keys) {- const threadId = key.replace('chat:sub:', '')- if (!adapterName || threadId.startsWith(`${adapterName}:`)) {- yield threadId- }- }- }-- async acquireLock(threadId: string, ttlMs: number): Promise<Lock | null> {- const key = `chat:lock:${threadId}`- const existing = await kv.get<Lock>(key)-- if (existing && existing.expiresAt > Date.now()) {- return null- }-- const lock: Lock = {- threadId,- token: `kv_${Date.now()}_${Math.random().toString(36).slice(2)}`,- expiresAt: Date.now() + ttlMs,- }-- await kv.set(key, lock, { ttl: Math.ceil(ttlMs / 1000) })- return lock- }-- async releaseLock(lock: Lock): Promise<void> {- const key = `chat:lock:${lock.threadId}`- const existing = await kv.get<Lock>(key)-- if (existing && existing.token === lock.token) {- await kv.del(key)- }- }-- async extendLock(lock: Lock, ttlMs: number): Promise<boolean> {- const key = `chat:lock:${lock.threadId}`- const existing = await kv.get<Lock>(key)-- if (!existing || existing.token !== lock.token) {- return false- }-- if (existing.expiresAt < Date.now()) {- await kv.del(key)- return false- }-- existing.expiresAt = Date.now() + ttlMs- await kv.set(key, existing, { ttl: Math.ceil(ttlMs / 1000) })- return true- }-- async get<T = unknown>(key: string): Promise<T | null> {- return await kv.get<T>(`chat:cache:${key}`)- }-- async set(key: string, value: unknown, ttlMs?: number): Promise<void> {- const opts = ttlMs ? { ttl: Math.ceil(ttlMs / 1000) } : undefined- await kv.set(`chat:cache:${key}`, value as string, opts)- }-- async delete(key: string): Promise<void> {- await kv.del(`chat:cache:${key}`)- }--}diff --git a/apps/github-bot/server/utils/types.ts b/apps/github-bot/server/utils/types.tsindex dcdfc00..ab450ea 100644--- a/apps/github-bot/server/utils/types.ts+++ b/apps/github-bot/server/utils/types.ts@@ -81,13 +81,6 @@ export interface GitHubIssuesPayload {}}-export interface GitHubAdapterConfig {- userName: string- webhookSecret: string- appId: string- appPrivateKey: string-}-export interface IssueContext {number: numbertitle: stringdiff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.tsindex 3cef8bd..0232463 100644--- a/packages/sdk/src/client.ts+++ b/packages/sdk/src/client.ts@@ -1,5 +1,6 @@import { createError } from 'evlog'import type {+ AgentConfig,SavoirConfig,ShellBatchResponse,ShellResponse,@@ -11,9 +12,7 @@ import type {} from './types'import { NetworkError, SavoirError } from './errors'-/**- * HTTP client for the Savoir API- */+/** Low-level HTTP client for the Savoir API. Use `createSavoir()` for the high-level interface with AI SDK tools. */export class SavoirClient {private readonly apiUrl: string@@ -34,23 +33,14 @@ export class SavoirClient {this.sessionId = config.sessionId}- /**- * Get the current session ID- */getSessionId(): string | undefined {return this.sessionId}- /**- * Set the session ID for subsequent requests- */setSessionId(sessionId: string): void {this.sessionId = sessionId}- /**- * Make a GET request to the API- */private async get<T>(path: string): Promise<T> {const url = `${this.apiUrl}${path}`@@ -85,9 +75,6 @@ export class SavoirClient {}}- /**- * Make a POST request to the API- */private async post<T>(path: string,body: Record<string, unknown> = {},@@ -140,35 +127,23 @@ export class SavoirClient {}}- /**- * Run a bash command in the sandbox- */async bash(command: string): Promise<ShellResponse> {return await this.post<ShellResponse>('/api/sandbox/shell', {command,})}- /**- * Run multiple bash commands in sequence (batch mode)- * More efficient than multiple single calls as sandbox is reused- */+ /** More efficient than multiple single calls as sandbox is reused */async bashBatch(commands: string[]): Promise<ShellBatchResponse> {return await this.post<ShellBatchResponse>('/api/sandbox/shell', {commands,})}- /**- * Get list of configured sources- */async getSources(): Promise<SourcesResponse> {return await this.get<SourcesResponse>('/api/sources')}- /**- * Trigger documentation sync workflow for all sources- */async sync(options?: SyncOptions): Promise<SyncResponse> {return await this.post<SyncResponse>('/api/sync', {reset: options?.reset ?? false,@@ -178,9 +153,6 @@ export class SavoirClient {})}- /**- * Trigger documentation sync workflow for a specific source- */async syncSource(sourceId: string, options?: SyncOptions): Promise<SyncSourceResponse> {return await this.post<SyncSourceResponse>(`/api/sync/${sourceId}`, {reset: options?.reset ?? false,@@ -188,11 +160,12 @@ export class SavoirClient {})}- /**- * Trigger snapshot creation workflow- */async createSnapshot(): Promise<SnapshotResponse> {return await this.post<SnapshotResponse>('/api/sandbox/snapshot', {})}+ async getAgentConfig(): Promise<AgentConfig> {+ return await this.get<AgentConfig>('/api/agent-config/public')+ }+}diff --git a/packages/sdk/src/errors.ts b/packages/sdk/src/errors.tsindex 9d40aaa..fc7d37e 100644--- a/packages/sdk/src/errors.ts+++ b/packages/sdk/src/errors.ts@@ -1,10 +1,6 @@import type { ApiErrorResponse } from './types'-/**- * Error class for Savoir API errors- */export class SavoirError extends Error {-readonly statusCode: numberreadonly error?: string@@ -15,34 +11,20 @@ export class SavoirError extends Error {this.error = response.error}- /**- * Check if the error is due to invalid authentication- */isAuthError(): boolean {return this.statusCode === 401}- /**- * Check if the error is due to rate limiting- */isRateLimitError(): boolean {return this.statusCode === 429}- /**- * Check if the error is a server error- */isServerError(): boolean {return this.statusCode >= 500}-}-/**- * Error class for network-related errors- */export class NetworkError extends Error {-readonly cause?: Errorconstructor(message: string, cause?: Error) {@@ -50,5 +32,4 @@ export class NetworkError extends Error {this.name = 'NetworkError'this.cause = cause}-}diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.tsindex 6e6c909..f2c7832 100644--- a/packages/sdk/src/index.ts+++ b/packages/sdk/src/index.ts@@ -1,39 +1,24 @@import { SavoirClient } from './client'import { createBashBatchTool, createBashTool } from './tools'-import type { SavoirConfig } from './types'+import type { AgentConfig, SavoirConfig } from './types'-export type { SavoirConfig, ShellResponse, ShellBatchResponse, ShellCommandResult, SyncOptions, SyncResponse, SnapshotResponse, GitHubSource, YouTubeSource, SourcesResponse, SyncSourceResponse, ToolCallInfo, ToolCallCallback, ToolCallState, ToolExecutionResult, CommandResult } from './types'+export type { SavoirConfig, ShellResponse, ShellBatchResponse, ShellCommandResult, SyncOptions, SyncResponse, SnapshotResponse, GitHubSource, YouTubeSource, SourcesResponse, SyncSourceResponse, ToolCallInfo, ToolCallCallback, ToolCallState, ToolExecutionResult, CommandResult, AgentConfig } from './types'export { SavoirError, NetworkError } from './errors'export { SavoirClient } from './client'-/**- * Savoir instance with client and AI SDK tools- */export interface Savoir {- /**- * HTTP client for direct API access- */+ /** Low-level HTTP client for direct API access */client: SavoirClient-- /**- * AI SDK tools- */+ /** AI SDK tools for use with generateText/streamText */tools: {- /** Execute a single bash command in the sandbox */bash: ReturnType<typeof createBashTool>- /** Execute multiple bash commands in one request (more efficient) */+ /** Runs multiple commands in one request (more efficient, sandbox is reused) */bash_batch: ReturnType<typeof createBashBatchTool>}-- /**- * Get the current session ID- */getSessionId: () => string | undefined-- /**- * Set the session ID for subsequent requests- */setSessionId: (sessionId: string) => void+ /** Fetch admin-defined agent customization settings */+ getAgentConfig: () => Promise<AgentConfig>}/**@@ -72,5 +57,6 @@ export function createSavoir(config: SavoirConfig): Savoir {},getSessionId: () => client.getSessionId(),setSessionId: (sessionId: string) => client.setSessionId(sessionId),+ getAgentConfig: () => client.getAgentConfig(),}}diff --git a/packages/sdk/src/tools/shell.ts b/packages/sdk/src/tools/shell.tsindex 1671c1f..5f9ba93 100644--- a/packages/sdk/src/tools/shell.ts+++ b/packages/sdk/src/tools/shell.ts@@ -3,9 +3,6 @@ import { z } from 'zod'import type { SavoirClient } from '../client'import type { ToolCallCallback, ToolExecutionResult, CommandResult } from '../types'-/**- * Create the bash tool for AI SDK - runs a single command in the sandbox- */export function createBashTool(client: SavoirClient, onToolCall?: ToolCallCallback) {return tool({description: `Execute a bash command in the documentation sandbox.@@ -78,9 +75,6 @@ Use standard Unix commands to explore and read files.`,})}-/**- * Create the bash_batch tool for AI SDK - runs multiple commands in one API call- */export function createBashBatchTool(client: SavoirClient, onToolCall?: ToolCallCallback) {return tool({description: `Execute multiple bash commands in the documentation sandbox in a single request.diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.tsindex ae60d22..cf2433b 100644--- a/packages/sdk/src/types.ts+++ b/packages/sdk/src/types.ts@@ -1,39 +1,16 @@-/**- * Configuration options for creating a Savoir client- */export interface SavoirConfig {- /**- * Base URL for the Savoir API- */+ /** Base URL of your Savoir API (e.g., 'https://chat.example.com') */apiUrl: string-- /**- * API key for authentication- * Optional if the API doesn't require authentication- */+ /** API key for authentication. Required if the API has SAVOIR_SECRET_KEY configured. */apiKey?: string-- /**- * Optional session ID for sandbox reuse- * When provided, the same sandbox will be reused for multiple requests- */+ /** Reuse an existing sandbox session instead of creating a new one. */sessionId?: string-- /**- * Optional callback when a tool call is made- * Called with tool call info when input is available- */+ /** Callback fired on tool execution (loading/done/error states). */onToolCall?: ToolCallCallback}-/**- * Tool call state- */export type ToolCallState = 'loading' | 'done' | 'error'-/**- * Result of a single command execution- */export interface CommandResult {command: stringstdout: string@@ -42,79 +19,47 @@ export interface CommandResult {success: boolean}-/**- * Tool execution result (available when state is 'done' or 'error')- */export interface ToolExecutionResult {- /** Results for each command (single item for bash, multiple for bash_batch) */commands: CommandResult[]- /** Whether all commands succeeded */success: boolean- /** Execution duration in milliseconds */durationMs: number- /** Error message if state is 'error' */error?: string}-/**- * Tool call information passed to onToolCall callback- */export interface ToolCallInfo {toolCallId: stringtoolName: stringargs: Record<string, unknown>state: ToolCallState- /** Execution result (only available when state is 'done' or 'error') */result?: ToolExecutionResult}-/**- * Callback type for tool call notifications- */export type ToolCallCallback = (info: ToolCallInfo) => void-/**- * Search result from the Savoir API- */export interface SearchResult {path: stringlineNumber: numbercontent: string}-/**- * File content from the Savoir API- * When from search-and-read, contains context snippets around matches- */export interface FileContent {path: stringcontent: string- /** Number of matches in this file (for context snippets) */matchCount?: number- /** Total lines in the file (for context snippets) */totalLines?: number}-/**- * Response from the search-and-read endpoint- */export interface SearchAndReadResponse {sessionId: stringmatches: SearchResult[]files: FileContent[]}-/**- * Response from the read endpoint- */export interface ReadResponse {sessionId: stringfiles: FileContent[]}-/**- * Response from the shell endpoint (single command)- */export interface ShellResponse {sessionId: stringstdout: string@@ -122,9 +67,6 @@ export interface ShellResponse {exitCode: number}-/**- * Single command result in batch response- */export interface ShellCommandResult {command: stringstdout: string@@ -132,59 +74,42 @@ export interface ShellCommandResult {exitCode: number}-/**- * Response from the shell endpoint (batch commands)- */export interface ShellBatchResponse {sessionId: stringresults: ShellCommandResult[]}-/**- * Error response from the Savoir API- */export interface ApiErrorResponse {statusCode: numbermessage: stringerror?: string}-/**- * Source passed for sync- */export interface SyncSource {id: stringtype: 'github' | 'youtube'label: string- // GitHub fieldsrepo?: string | nullbranch?: string | nullcontentPath?: string | nulloutputPath?: string | nullreadmeOnly?: boolean | null- // YouTube fieldschannelId?: string | nullhandle?: string | nullmaxVideos?: number | null}-/**- * Options for the sync operation- */export interface SyncOptions {- /** Clear all content before sync */+ /** Clear all content before sync (default: false) */reset?: boolean- /** Push to snapshot repo after sync */+ /** Push to snapshot repo after sync (default: true) */push?: boolean/** Sources to sync (passed from chat app DB) */sources?: SyncSource[]- /** Filter to sync only specific source */+ /** Filter to sync only a specific source by ID */sourceFilter?: string}-/**- * Response from the sync endpoint- */export interface SyncResponse {status: 'started'message: string@@ -194,17 +119,11 @@ export interface SyncResponse {}}-/**- * Response from the snapshot endpoint- */export interface SnapshotResponse {status: 'started'message: string}-/**- * GitHub source configuration- */export interface GitHubSource {id: stringlabel: string@@ -215,9 +134,6 @@ export interface GitHubSource {readmeOnly: boolean}-/**- * YouTube source configuration- */export interface YouTubeSource {id: stringlabel: string@@ -226,9 +142,6 @@ export interface YouTubeSource {handle: string}-/**- * Response from the sources endpoint- */export interface SourcesResponse {total: numbergithub: {@@ -241,9 +154,6 @@ export interface SourcesResponse {}}-/**- * Response from the sync source endpoint- */export interface SyncSourceResponse {status: 'started'message: string@@ -254,3 +164,19 @@ export interface SyncSourceResponse {sourceFilter: string}}++/** Admin-defined settings that customize agent behavior (fetched from /api/agent-config/public). */+export interface AgentConfig {+ id: string+ name: string+ additionalPrompt: string | null+ responseStyle: 'concise' | 'detailed' | 'technical' | 'friendly'+ language: string+ defaultModel: string | null+ /** Multiplier applied to router-determined maxSteps (0.5-3.0) */+ maxStepsMultiplier: number+ temperature: number+ searchInstructions: string | null+ citationFormat: 'inline' | 'footnote' | 'none'+ isActive: boolean+}