Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base
init
Hugo Richardc633b3a00dad
diff --git a/.gitignore b/.gitignoreindex a3c487f..279febd 100644--- a/.gitignore+++ b/.gitignore@@ -30,4 +30,5 @@ logs.swc*.workflow-data*apps/web/.data-apps/chat/.data\ No newline at end of file+apps/chat/.data+apps/github-bot/.data\ No newline at end of filediff --git a/apps/github-bot/.env.example b/apps/github-bot/.env.examplenew file mode 100644index 0000000..1f586bb--- /dev/null+++ b/apps/github-bot/.env.example@@ -0,0 +1,16 @@+# GitHub App credentials+NUXT_GITHUB_APP_ID=your_app_id+NUXT_GITHUB_APP_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"+NUXT_GITHUB_WEBHOOK_SECRET=your_webhook_secret++# Savoir API (apps/chat)+NUXT_SAVOIR_API_URL=http://localhost:3000+NUXT_SAVOIR_API_KEY=your_api_key++# AI Gateway API key (Vercel AI Gateway)+# Get one at: https://vercel.com/dashboard/ai+AI_GATEWAY_API_KEY=your_gateway_key++# Bot trigger - must match your GitHub App slug (derived from app name)+# Example: "My Bot App" -> "my-bot-app" -> mention as @my-bot-app[bot]+NUXT_PUBLIC_BOT_TRIGGER=@your-app-slugdiff --git a/apps/github-bot/.gitkeep b/apps/github-bot/.gitkeepdeleted file mode 100644index e69de29..0000000diff --git a/apps/github-bot/README.md b/apps/github-bot/README.mdnew file mode 100644index 0000000..3129540--- /dev/null+++ b/apps/github-bot/README.md@@ -0,0 +1,228 @@+# GitHub Bot Example++Example bot demonstrating how to integrate [chat-sdk](https://github.com/example/chat-sdk) with the Savoir AI platform to build an intelligent documentation assistant.++## What This Example Demonstrates++1. **Custom Platform Adapter** - How to implement chat-sdk's `Adapter` interface for a new platform (GitHub)+2. **StateAdapter with NuxtHub KV** - Persistent state management without Redis+3. **AI Integration** - Calling the Savoir API for documentation search+4. **Webhook Security** - GitHub signature verification using HMAC-SHA256++## Quick Start++```bash+# Install dependencies+bun install++# Copy environment file and configure+cp .env.example .env++# Start the dev server (runs on port 3001)+bun run dev++# Expose via ngrok for testing with GitHub webhooks+ngrok http 3001+```++## Configuration++Create a `.env` file with:++```bash+# GitHub App/Webhook credentials+NUXT_GITHUB_WEBHOOK_SECRET=your_webhook_secret+NUXT_GITHUB_TOKEN=ghp_xxx # or use GitHub App installation token++# Savoir API (the main chat app)+NUXT_SAVOIR_API_URL=http://localhost:3000+NUXT_SAVOIR_API_KEY=your_api_key++# Bot trigger (public)+NUXT_PUBLIC_BOT_TRIGGER=@your-bot-name+```++## GitHub Setup++1. **Create a GitHub App** (or configure repository webhooks directly)+ - Go to Settings → Developer settings → GitHub Apps → New GitHub App++2. **Configure Webhook**+ - Webhook URL: `https://your-domain.com/api/webhook`+ - Webhook Secret: Generate a random string+ - Events: Subscribe to "Issue comments"++3. **Permissions**+ - Issues: Read & Write+ - Pull requests: Read & Write (if you want PR comment support)++4. **Install the App**+ - Install on your target repositories++## Project Structure++```+apps/github-bot/+├── nuxt.config.ts # Nuxt configuration with NuxtHub KV+├── package.json # Dependencies including chat-sdk+├── .env.example # Environment variables template+└── server/+ ├── api/+ │ └── webhook.post.ts # GitHub webhook endpoint+ └── utils/+ ├── adapter.ts # GitHubAdapter - platform adapter+ ├── state-kv.ts # KVStateAdapter - state management+ ├── markdown.ts # GitHub Flavored Markdown converter+ ├── chat.ts # Chat instance & message handlers+ └── ai.ts # AI response generation+```++## How It Works++```+GitHub Issue Comment+ ↓+ Webhook POST+ ↓+ Signature Verification+ ↓+ GitHubAdapter+ ↓+ Chat.processMessage()+ ↓+ onNewMention Handler+ ↓+ Savoir API Search+ ↓+ Post Response+```++1. User mentions `@bot-name` in an issue comment+2. GitHub sends a webhook to `/api/webhook`+3. `GitHubAdapter` verifies the signature and parses the payload+4. The `Chat` instance routes to the `onNewMention` handler+5. Handler searches docs via Savoir API and posts a response++## Creating Your Own Bot++Use this example as a template:++### 1. Copy This Folder++```bash+cp -r apps/github-bot apps/my-new-bot+```++### 2. Create Your Platform Adapter++Implement the `Adapter` interface from chat-sdk:++```typescript+// server/utils/adapter.ts+export class MyAdapter implements Adapter<MyThreadId, MyRawMessage> {+ readonly name = 'myplatform'++ async handleWebhook(request: Request): Promise<Response> {+ // Verify signature, parse payload, call chat.processMessage()+ }++ async postMessage(threadId: string, message): Promise<RawMessage> {+ // Post message to your platform+ }++ // ... implement other required methods+}+```++### 3. Configure Message Handlers++```typescript+// server/utils/chat.ts+chat.onNewMention(async (thread, message) => {+ // React to @mentions+ const response = await generateResponse(message.text)+ await thread.post({ markdown: response })+})++chat.onSubscribedMessage(async (thread, message) => {+ // Handle follow-up messages in subscribed threads+})+```++### 4. Deploy++The bot can be deployed anywhere that supports Nuxt/Nitro:+- Cloudflare Workers (with KV)+- Vercel+- Railway+- Self-hosted++## Key Concepts++### Thread IDs++chat-sdk uses a standard format for thread IDs: `{adapter}:{channel}:{thread}`++For GitHub: `github:{owner}/{repo}:issue:{number}`++Example: `github:nuxt/nuxt:issue:12345`++### StateAdapter++The `KVStateAdapter` demonstrates how to implement persistent state:+- **Subscriptions**: Track which threads the bot is watching+- **Locks**: Prevent concurrent processing of the same thread+- **Cache**: Store temporary data with TTL++### Message Handlers++- `onNewMention`: Called when bot is @mentioned in an unsubscribed thread+- `onSubscribedMessage`: Called for any message in a subscribed thread+- `onReaction`: Handle emoji reactions+- `onAction`: Handle button clicks (cards)++## Extending the Bot++### Add AI-Powered Responses++Replace the simple search with AI SDK:++```typescript+import { generateText } from 'ai'+import { openai } from '@ai-sdk/openai'++const response = await generateText({+ model: openai('gpt-4'),+ system: 'You are a helpful documentation assistant...',+ prompt: message.text,+ tools: {+ searchDocs: savoir.tools.searchAndRead,+ },+})+```++### Support More Events++Extend the adapter to handle:+- `pull_request_review_comment` - PR review comments+- `discussion_comment` - GitHub Discussions+- `issues` - Issue opened/closed events++### Add Subscription Mode++Enable follow-up conversations:++```typescript+chat.onNewMention(async (thread, message) => {+ await thread.subscribe() // Watch this thread+ await thread.post('I\'ll continue helping in this thread!')+})++chat.onSubscribedMessage(async (thread, message) => {+ // Handle follow-up questions+})+```++## License++MITdiff --git a/apps/github-bot/nuxt.config.ts b/apps/github-bot/nuxt.config.tsnew file mode 100644index 0000000..270756e--- /dev/null+++ b/apps/github-bot/nuxt.config.ts@@ -0,0 +1,48 @@+export default defineNuxtConfig({+ modules: ['@nuxthub/core'],++ hub: {+ kv: true,+ },++ devtools: { enabled: true },++ // Disable type generation to avoid Nuxt 4.3.0 bug with sharedTsConfig+ // See: https://github.com/nuxt/nuxt/issues/33579+ typescript: {+ typeCheck: false,+ },++ $development: {+ vite: {+ server: {+ allowedHosts: true // Allow ngrok and other tunnels+ }+ },+ },++ // Workaround for prepare:types hook error+ hooks: {+ 'prepare:types': (opts) => {+ // Ensure sharedTsConfig exists to prevent nitro-server error+ opts.sharedTsConfig = opts.sharedTsConfig || { compilerOptions: {} }+ },+ },++ runtimeConfig: {+ github: {+ webhookSecret: '',+ appId: '',+ appPrivateKey: '',+ },+ savoir: {+ apiUrl: 'http://localhost:3000',+ apiKey: '',+ },+ public: {+ botTrigger: '',+ },+ },++ compatibilityDate: 'latest',+})diff --git a/apps/github-bot/package.json b/apps/github-bot/package.jsonnew file mode 100644index 0000000..6cc8358--- /dev/null+++ b/apps/github-bot/package.json@@ -0,0 +1,29 @@+{+ "name": "@savoir/github-bot",+ "version": "0.0.1",+ "private": true,+ "type": "module",+ "scripts": {+ "dev": "nuxt dev --port 3001",+ "build": "nuxt build",+ "preview": "nuxt preview",+ "postinstall": "nuxt prepare",+ "typecheck": "nuxt typecheck"+ },+ "dependencies": {+ "@ai-sdk/gateway": "^3.0.29",+ "@savoir/sdk": "workspace:*",+ "ai": "^6.0.62",+ "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"+ },+ "devDependencies": {+ "@nuxthub/core": "^0.10.5",+ "@types/mdast": "^4.0.4",+ "typescript": "^5.9.3"+ }+}diff --git a/apps/github-bot/server/utils/adapter.ts b/apps/github-bot/server/utils/adapter.tsnew file mode 100644index 0000000..8a02071--- /dev/null+++ b/apps/github-bot/server/utils/adapter.ts@@ -0,0 +1,883 @@+/**+ * GitHubAdapter - Platform adapter for GitHub issue comments+ *+ * This adapter demonstrates how to implement chat-sdk's Adapter interface+ * for a new platform. It handles:+ * - Webhook signature verification (HMAC-SHA256)+ * - Issue comment parsing and posting+ * - Thread ID encoding/decoding+ * - Markdown format conversion (GitHub Flavored Markdown)+ *+ * Thread ID format: github:{owner}/{repo}:issue:{number}+ * Example: github:nuxt/nuxt:issue:12345+ */++import { createHmac, createSign, timingSafeEqual } from 'node:crypto'+import type {+ Adapter,+ AdapterPostableMessage,+ Author,+ ChatInstance,+ EmojiValue,+ FetchOptions,+ FetchResult,+ FormattedContent,+ RawMessage,+ ThreadInfo,+ WebhookOptions,+} from 'chat'+import { Message, NotImplementedError } from 'chat'+import { GitHubFormatConverter } from './markdown'++// ============================================================================+// GitHub App JWT Token Generation+// ============================================================================++/**+ * Generate a JWT for GitHub App authentication.+ * The JWT is used to authenticate as the GitHub App itself.+ */+function generateAppJWT(appId: string, privateKey: string): string {+ const now = Math.floor(Date.now() / 1000)+ const payload = {+ iat: now - 60, // Issued 60 seconds ago to account for clock drift+ exp: now + 600, // Expires in 10 minutes (max allowed by GitHub)+ iss: appId,+ }++ // Create JWT header+ const header = { alg: 'RS256', typ: 'JWT' }+ const headerB64 = Buffer.from(JSON.stringify(header)).toString('base64url')+ const payloadB64 = Buffer.from(JSON.stringify(payload)).toString('base64url')++ // Sign with RSA-SHA256+ const signatureInput = `${headerB64}.${payloadB64}`+ const sign = createSign('RSA-SHA256')+ sign.update(signatureInput)+ const signature = sign.sign(privateKey, 'base64url')++ return `${headerB64}.${payloadB64}.${signature}`+}++/**+ * Cache for installation tokens.+ * Key: installation ID, Value: { token, expiresAt }+ */+const tokenCache = new Map<number, { token: string, expiresAt: Date }>()++/**+ * Get an installation access token for a GitHub App.+ * Caches tokens and refreshes them when expired.+ */+async function getInstallationToken(+ appId: string,+ privateKey: string,+ installationId: number,+): Promise<string> {+ // Check cache+ const cached = tokenCache.get(installationId)+ if (cached && cached.expiresAt > new Date(Date.now() + 60000)) {+ // Token is still valid for at least 1 minute+ return cached.token+ }++ // Generate new token+ const jwt = generateAppJWT(appId, privateKey)++ const response = await fetch(+ `https://api.github.com/app/installations/${installationId}/access_tokens`,+ {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${jwt}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ },+ )++ if (!response.ok) {+ const error = await response.text()+ throw new Error(`Failed to get installation token: ${response.status} ${error}`)+ }++ const data = await response.json() as { token: string, expires_at: string }++ // Cache the token+ tokenCache.set(installationId, {+ token: data.token,+ expiresAt: new Date(data.expires_at),+ })++ return data.token+}++/**+ * Get installation ID for a repository.+ */+async function getInstallationId(+ appId: string,+ privateKey: string,+ owner: string,+ repo: string,+): Promise<number> {+ const jwt = generateAppJWT(appId, privateKey)++ const response = await fetch(+ `https://api.github.com/repos/${owner}/${repo}/installation`,+ {+ headers: {+ 'Authorization': `Bearer ${jwt}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ },+ )++ if (!response.ok) {+ const error = await response.text()+ throw new Error(`Failed to get installation: ${response.status} ${error}`)+ }++ const data = await response.json() as { id: number }+ return data.id+}++/** Cache for installation IDs (repo -> installation ID) */+const installationIdCache = new Map<string, number>()++// ============================================================================+// Types+// ============================================================================++/** GitHub-specific thread ID components */+export interface GitHubThreadId {+ owner: string+ repo: string+ issueNumber: number+}++/** GitHub issue comment (raw message format) */+export interface GitHubComment {+ id: number+ node_id: string+ body: string+ user: {+ id: number+ login: string+ avatar_url: string+ type: string // "User" or "Bot"+ }+ created_at: string+ updated_at: string+ html_url: string+ issue_url: string+}++/** GitHub webhook payload for issue_comment event */+interface GitHubIssueCommentPayload {+ action: 'created' | 'edited' | 'deleted'+ issue: {+ number: number+ title: string+ state: string+ user: {+ id: number+ login: string+ }+ }+ comment: GitHubComment+ repository: {+ id: number+ name: string+ full_name: string+ owner: {+ login: string+ }+ }+ sender: {+ id: number+ login: string+ type: string+ }+}++/** Configuration for GitHubAdapter */+export interface GitHubAdapterConfig {+ /** Bot username (without @) */+ userName: string+ /** GitHub webhook secret for signature verification */+ webhookSecret: string+ /** GitHub App ID */+ appId: string+ /** GitHub App private key (PEM format) */+ appPrivateKey: string+}++// ============================================================================+// Adapter Implementation+// ============================================================================++export class GitHubAdapter implements Adapter<GitHubThreadId, GitHubComment> {++ readonly name = 'github'+ readonly userName: string++ private chat!: ChatInstance+ private webhookSecret: string+ private appId: string+ private appPrivateKey: string+ private formatConverter: GitHubFormatConverter++ constructor(config: GitHubAdapterConfig) {+ this.userName = config.userName+ this.webhookSecret = config.webhookSecret+ this.appId = config.appId+ this.appPrivateKey = config.appPrivateKey+ this.formatConverter = new GitHubFormatConverter()+ }++ /**+ * Get an access token for a specific repository.+ * Uses the GitHub App credentials to generate an installation token.+ */+ private async getToken(owner: string, repo: string): Promise<string> {+ const cacheKey = `${owner}/${repo}`++ // Get installation ID (cached)+ let installationId = installationIdCache.get(cacheKey)+ if (!installationId) {+ installationId = await getInstallationId(this.appId, this.appPrivateKey, owner, repo)+ installationIdCache.set(cacheKey, installationId)+ }++ // Get installation token (cached)+ return getInstallationToken(this.appId, this.appPrivateKey, installationId)+ }++ /**+ * Called when Chat instance is created.+ * Store reference for calling processMessage.+ */+ async initialize(chat: ChatInstance): Promise<void> {+ this.chat = chat+ }++ // ==========================================================================+ // Webhook Handling+ // ==========================================================================++ /**+ * Handle incoming GitHub webhook requests.+ * Verifies signature, parses payload, and dispatches to chat handlers.+ */+ async handleWebhook(+ request: Request,+ options?: WebhookOptions,+ ): Promise<Response> {+ const body = await request.text()++ // Verify webhook signature+ const signature = request.headers.get('X-Hub-Signature-256')+ if (!this.verifySignature(body, signature)) {+ return new Response('Invalid signature', { status: 401 })+ }++ // Check event type+ const event = request.headers.get('X-GitHub-Event')+ if (event === 'ping') {+ return new Response('pong', { status: 200 })+ }++ if (event !== 'issue_comment') {+ // Ignore other events for now+ return new Response('OK', { status: 200 })+ }++ const payload = JSON.parse(body) as GitHubIssueCommentPayload++ // Only handle new comments+ if (payload.action !== 'created') {+ return new Response('OK', { status: 200 })+ }++ // Ignore bot's own comments to prevent loops+ // For GitHub Apps, the username is "app-slug[bot]"+ const botUserName = `${this.userName}[bot]`+ if (payload.comment.user.login === this.userName || payload.comment.user.login === botUserName) {+ return new Response('OK', { status: 200 })+ }++ // Build thread ID+ const threadId = this.encodeThreadId({+ owner: payload.repository.owner.login,+ repo: payload.repository.name,+ issueNumber: payload.issue.number,+ })++ // Parse message and dispatch to handlers+ const message = this.parseMessage(payload.comment)++ // Process message (handles mention detection, handler routing, etc.)+ this.chat.processMessage(this, threadId, message, options)++ return new Response('OK', { status: 200 })+ }++ /**+ * Verify GitHub webhook signature using HMAC-SHA256.+ */+ 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+ }+ }++ // ==========================================================================+ // Message Operations+ // ==========================================================================++ /**+ * Post a comment to a GitHub issue.+ */+ 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,+ }+ }++ /**+ * Edit an existing comment.+ */+ 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,+ }+ }++ /**+ * Delete a comment.+ */+ 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}`)+ }+ }++ // ==========================================================================+ // Reactions+ // ==========================================================================++ /**+ * Add a reaction to a comment.+ * GitHub supports: +1, -1, laugh, confused, heart, hooray, rocket, eyes+ */+ async addReaction(+ threadId: string,+ messageId: string,+ emoji: EmojiValue | string,+ ): Promise<void> {+ const { owner, repo } = this.decodeThreadId(threadId)+ const reaction = this.emojiToGitHubReaction(emoji)+ const token = await this.getToken(owner, repo)++ const response = await fetch(+ `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}/reactions`,+ {+ 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}`)+ }+ }++ /**+ * Remove a reaction from a comment.+ * Note: GitHub requires the reaction ID, so we need to list reactions first.+ */+ async removeReaction(+ threadId: string,+ messageId: string,+ emoji: EmojiValue | string,+ ): Promise<void> {+ const { owner, repo } = this.decodeThreadId(threadId)+ const reaction = this.emojiToGitHubReaction(emoji)+ const token = await this.getToken(owner, repo)++ // First, list reactions to find our reaction ID+ const listResponse = await fetch(+ `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}/reactions`,+ {+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ },+ )++ if (!listResponse.ok) {+ return // Silently fail if we can't list reactions+ }++ const reactions = (await listResponse.json()) as Array<{+ id: number+ content: string+ user: { login: string }+ }>++ // Find our reaction (by bot username and emoji type)+ // Note: For GitHub Apps, the username is "app-name[bot]"+ 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 // Reaction not found+ }++ // Delete the reaction+ await fetch(+ `https://api.github.com/repos/${owner}/${repo}/issues/comments/${messageId}/reactions/${ourReaction.id}`,+ {+ method: 'DELETE',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Accept': 'application/vnd.github.v3+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ },+ )+ }++ /**+ * Convert chat-sdk emoji to GitHub reaction string.+ */+ 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',+ // Default to eyes for unknown emoji+ }++ return mapping[name] || 'eyes'+ }++ // ==========================================================================+ // Typing Indicator+ // ==========================================================================++ /**+ * GitHub doesn't support typing indicators.+ * We use a reaction as a workaround (eyes emoji).+ */+ async startTyping(_threadId: string): Promise<void> {+ // GitHub doesn't have typing indicators+ // Could potentially add/remove a reaction as visual feedback+ }++ // ==========================================================================+ // Fetch Operations+ // ==========================================================================++ /**+ * Fetch comments from an issue.+ */+ 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'++ // GitHub uses page-based pagination+ let url = `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/comments?per_page=${limit}`++ if (options?.cursor) {+ url += `&page=${options.cursor}`+ }++ // GitHub sorts ascending by default (oldest first)+ // For backward (most recent), we'd need to calculate the last page+ 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[]++ // Parse Link header for pagination+ 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))++ // Reverse if backward direction to get most recent first+ if (direction === 'backward') {+ messages.reverse()+ }++ return {+ messages,+ nextCursor,+ }+ }++ /**+ * Fetch thread (issue) metadata.+ */+ 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,+ },+ }+ }++ /**+ * Fetch full issue context for AI agent.+ * Includes title, body, labels, and recent comments.+ */+ async fetchIssueContext(threadId: string): Promise<{+ number: number+ title: string+ body: string | null+ labels: string[]+ state: string+ owner: string+ repo: string+ previousComments?: Array<{+ author: string+ body: string+ isBot: boolean+ }>+ }> {+ const { owner, repo, issueNumber } = this.decodeThreadId(threadId)+ const token = await this.getToken(owner, repo)++ // Fetch issue details+ 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 }>+ }++ // Fetch recent comments for context+ 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,+ }+ }++ // ==========================================================================+ // Thread ID Encoding+ // ==========================================================================++ /**+ * Encode platform data into a thread ID string.+ * Format: github:{owner}/{repo}:issue:{number}+ */+ encodeThreadId(data: GitHubThreadId): string {+ return `github:${data.owner}/${data.repo}:issue:${data.issueNumber}`+ }++ /**+ * Decode thread ID string back to platform data.+ */+ decodeThreadId(threadId: string): GitHubThreadId {+ // Format: github:{owner}/{repo}:issue:{number}+ 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),+ }+ }++ // ==========================================================================+ // Message Parsing & Formatting+ // ==========================================================================++ /**+ * Parse a GitHub comment into a normalized Message.+ */+ parseMessage(raw: GitHubComment): Message<GitHubComment> {+ return new Message<GitHubComment>({+ id: String(raw.id),+ threadId: '', // Will be set by caller+ 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',+ // For GitHub Apps, the username is "app-slug[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: [], // GitHub comments can have inline images but we don't extract them+ })+ }++ /**+ * Render formatted content to GitHub Flavored Markdown.+ */+ renderFormatted(content: FormattedContent): string {+ return this.formatConverter.fromAst(content)+ }++ /**+ * Render a postable message to a string.+ */+ 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) {+ // GitHub doesn't support rich cards, render as markdown+ throw new NotImplementedError('Cards are not supported on GitHub')+ }++ // CardElement directly+ throw new NotImplementedError('Cards are not supported on GitHub')+ }++}++/**+ * Create a new GitHubAdapter instance.+ */+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.tsnew file mode 100644index 0000000..cabbac7--- /dev/null+++ b/apps/github-bot/server/utils/ai.ts@@ -0,0 +1,244 @@+/**+ * AI Agent for GitHub Bot+ *+ * Uses AI SDK's generateText with Savoir SDK tools to answer questions+ * by searching and reading documentation iteratively.+ */++import { ToolLoopAgent, stepCountIs } from 'ai'+import { gateway } from '@ai-sdk/gateway'+import { createSavoir } from '@savoir/sdk'++/**+ * Issue context for the AI agent+ */+export interface IssueContext {+ /** Issue number */+ number: number+ /** Issue title */+ title: string+ /** Issue body/description */+ body: string | null+ /** Issue labels */+ labels: string[]+ /** Issue state (open/closed) */+ state: string+ /** Repository owner */+ owner: string+ /** Repository name */+ repo: string+ /** Previous comments in the thread (for context) */+ previousComments?: Array<{+ author: string+ body: string+ isBot: boolean+ }>+}++/**+ * Generate an AI response using the Savoir SDK tools.+ *+ * This function:+ * 1. Creates a Savoir client with documentation tools+ * 2. Uses the AI SDK to generate a response with tool calling+ * 3. The agent can search and read documentation iteratively+ *+ * @param question - The user's question/message+ * @param context - Full context from the GitHub issue+ * @returns A markdown-formatted response+ */+export async function generateAIResponse(+ question: string,+ context?: IssueContext,+): Promise<string> {+ const config = useRuntimeConfig()++ // Check if Savoir API is configured+ if (!config.savoir.apiUrl) {+ return formatNoConfigResponse()+ }++ try {+ console.log('[ai] Creating Savoir SDK instance...')++ // Create Savoir SDK instance with tools+ const savoir = createSavoir({+ apiUrl: config.savoir.apiUrl,+ apiKey: config.savoir.apiKey || undefined,+ onToolCall: (info) => {+ console.log(`[ai] Tool ${info.toolName} called:`, info.args)+ },+ })++ // Build the system prompt with context+ const systemPrompt = buildSystemPrompt(context)++ // Build the user message+ const userMessage = buildUserMessage(question, context)++ console.log('[ai] Creating ToolLoopAgent...')+ console.log('[ai] User message:', userMessage.slice(0, 200))++ // Create agent with ToolLoopAgent+ const agent = new ToolLoopAgent({+ model: 'google/gemini-3-flash',+ instructions: systemPrompt,+ tools: savoir.tools as any,+ onStepFinish: ({ usage, finishReason, toolCalls }) => {+ console.log('[ai] Step completed:', {+ inputTokens: usage.inputTokens,+ outputTokens: usage.outputTokens,+ finishReason,+ toolsUsed: toolCalls?.map(tc => tc.toolName),+ })+ },+ })++ // Generate response+ const result = await agent.generate({+ prompt: userMessage,+ })++ console.log('[ai] Response generated:', result.text?.slice(0, 100))++ // Return the generated response+ if (!result.text) {+ return formatNoResultsResponse(question)+ }++ return result.text+ } catch (error) {+ console.error('[ai] Error generating response:', error)+ return formatErrorResponse(question, error)+ }+}++/**+ * Build the system prompt for the AI agent.+ */+function buildSystemPrompt(context?: IssueContext): string {+ const basePrompt = `You are a helpful documentation assistant for the Savoir project.+Your role is to help users by searching and reading the project documentation.++## Your Capabilities+- You have access to documentation search tools+- You can read specific files from the documentation+- You should search for relevant information before answering++## Guidelines+- Always search the documentation first to find accurate information+- If you find relevant documentation, cite the source file+- Be concise but thorough in your answers+- Use markdown formatting for better readability+- If you can't find specific information, say so honestly+- Suggest related topics or alternative approaches when helpful++## Response Format+- Use clear headings and bullet points when appropriate+- Include code examples if they help explain concepts+- Link to relevant documentation sections when possible`++ if (context) {+ return `${basePrompt}++## Current Context+You are responding to an issue in the repository: ${context.owner}/${context.repo}+Issue #${context.number}: "${context.title}"+Issue state: ${context.state}+${context.labels.length > 0 ? `Labels: ${context.labels.join(', ')}` : ''}`+ }++ return basePrompt+}++/**+ * Build the user message with full context.+ */+function buildUserMessage(question: string, context?: IssueContext): string {+ // Clean the question (remove bot mentions)+ const cleanQuestion = question+ .replace(/@[\w-]+(\[bot\])?/gi, '')+ .trim()++ let message = cleanQuestion++ // Add issue context if available+ if (context) {+ const parts: string[] = []++ // Add issue description if present and different from the question+ if (context.body && context.body !== cleanQuestion) {+ parts.push(`**Issue Description:**\n${context.body}`)+ }++ // Add previous comments for conversation context+ if (context.previousComments && context.previousComments.length > 0) {+ const relevantComments = context.previousComments+ .filter(c => !c.isBot) // Only human comments+ .slice(-3) // Last 3 comments++ if (relevantComments.length > 0) {+ parts.push('**Previous Discussion:**')+ for (const comment of relevantComments) {+ parts.push(`- @${comment.author}: ${comment.body.slice(0, 200)}${comment.body.length > 200 ? '...' : ''}`)+ }+ }+ }++ if (parts.length > 0) {+ message = `${parts.join('\n\n')}\n\n**Current Question:**\n${cleanQuestion}`+ }+ }++ return message+}++/**+ * Format response when no configuration is set.+ */+function formatNoConfigResponse(): string {+ return `👋 Hello! I'm the documentation bot, but I'm not fully configured yet.++Please set the following environment variables:+- \`NUXT_SAVOIR_API_URL\` - URL of the Savoir chat API+- \`NUXT_SAVOIR_API_KEY\` - API key (if required)++Once configured, I'll be able to search the documentation and help answer your questions!`+}++/**+ * Format response when no results are found.+ */+function formatNoResultsResponse(question: string): string {+ return `I searched the documentation but couldn't generate a helpful response for:++> ${question}++**Suggestions:**+- Try rephrasing your question with different keywords+- Check the official documentation directly+- Open a discussion for more complex questions++I'm continuously learning and improving! 🚀`+}++/**+ * Format error response.+ */+function formatErrorResponse(question: string, error: unknown): string {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error'++ return `Sorry, I encountered an error while processing your question:++> ${question}++<details>+<summary>Error details</summary>++\`\`\`+${errorMessage}+\`\`\`+</details>++Please try again later or open a discussion if this persists.`+}diff --git a/apps/github-bot/server/utils/chat.ts b/apps/github-bot/server/utils/chat.tsnew file mode 100644index 0000000..afdd70c--- /dev/null+++ b/apps/github-bot/server/utils/chat.ts@@ -0,0 +1,136 @@+/**+ * GitHub Chat Instance+ *+ * This module creates and configures the chat-sdk Chat instance+ * with the GitHub adapter and message handlers.+ *+ * The singleton pattern ensures we reuse the same instance across requests.+ */++import { Chat } from 'chat'+import { createGitHubAdapter, type GitHubAdapter } from './adapter'+import { generateAIResponse, type IssueContext } from './ai'+import { KVStateAdapter } from './state-kv'++let chatInstance: Chat | null = null++/**+ * Get or create the GitHub Chat instance.+ *+ * This is a singleton - the same instance is reused across all requests.+ * The Chat instance is configured with:+ * - GitHubAdapter for handling GitHub webhooks+ * - KVStateAdapter for persistent state (subscriptions, locks)+ * - Message handlers for processing mentions+ */+export function useGitHubChat(): Chat {+ if (chatInstance) {+ return chatInstance+ }++ const config = useRuntimeConfig()++ // Validate required config+ if (!config.github.webhookSecret) {+ throw new Error('NUXT_GITHUB_WEBHOOK_SECRET is required')+ }++ // Extract bot username from trigger (remove @ prefix)+ const botTrigger = config.public.botTrigger as string+ const botUserName = botTrigger.replace('@', '')++ // Validate GitHub App credentials+ if (!config.github.appId || !config.github.appPrivateKey) {+ throw new Error('NUXT_GITHUB_APP_ID and NUXT_GITHUB_APP_PRIVATE_KEY are required')+ }++ // Create the Chat instance+ 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',+ })++ // ==========================================================================+ // Message Handlers+ // ==========================================================================++ /**+ * Handle @mentions in unsubscribed threads.+ *+ * This is the main entry point for the bot. When someone mentions+ * the bot in an issue comment, we:+ * 1. Add an "eyes" reaction to show we're processing+ * 2. Search the documentation for relevant content+ * 3. Generate an AI response+ * 4. Post the response as a comment+ * 5. Update reactions to show completion+ */+ chatInstance.onNewMention(async (thread, message) => {+ const logger = console++ logger.info(`[github-bot] New mention from @${message.author.userName}`)+ logger.info(`[github-bot] Message: ${message.text.slice(0, 100)}...`)++ try {+ // Add "eyes" reaction to indicate we're processing+ const adapter = thread.adapter as GitHubAdapter+ await adapter.addReaction(thread.id, message.id, 'eyes')++ // Fetch full issue context for the AI agent+ let issueContext: IssueContext | undefined+ try {+ issueContext = await adapter.fetchIssueContext(thread.id)+ logger.info(`[github-bot] Fetched issue context: "${issueContext.title}"`)+ } catch (err) {+ logger.warn(`[github-bot] Could not fetch issue context:`, err)+ }++ // Generate AI response with full context+ const response = await generateAIResponse(message.text, issueContext)++ // Post the response+ await thread.post({ markdown: response })++ // Update reactions: remove eyes, add checkmark+ await adapter.removeReaction(thread.id, message.id, 'eyes')+ await adapter.addReaction(thread.id, message.id, 'thumbs_up')++ logger.info(`[github-bot] Response posted successfully`)+ } catch (error) {+ logger.error(`[github-bot] Error processing message:`, error)++ // Try to post an error message+ 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+ }+ }+ })++ /**+ * Handle messages in subscribed threads (optional).+ *+ * If you want the bot to continue responding in a thread after+ * the initial mention, you can subscribe to the thread and handle+ * follow-up messages here.+ *+ * For now, we don't subscribe - each interaction requires a new @mention.+ */+ // chatInstance.onSubscribedMessage(async (thread, message) => {+ // // Handle follow-up messages in subscribed threads+ // });++ return chatInstance+}diff --git a/apps/github-bot/server/utils/markdown.ts b/apps/github-bot/server/utils/markdown.tsnew file mode 100644index 0000000..1fbc411--- /dev/null+++ b/apps/github-bot/server/utils/markdown.ts@@ -0,0 +1,89 @@+/**+ * GitHubFormatConverter - Markdown format converter for GitHub+ *+ * Converts between GitHub Flavored Markdown (GFM) and mdast AST.+ * GFM is very close to standard markdown, so we use the standard+ * mdast utilities with GFM extensions.+ */++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'++/**+ * Format converter for GitHub Flavored Markdown.+ *+ * GFM adds the following extensions to standard markdown:+ * - Autolinks (URLs and emails)+ * - Strikethrough (~~text~~)+ * - Tables+ * - Task lists (- [ ] / - [x])+ */+export class GitHubFormatConverter {++ /**+ * Parse GitHub Flavored Markdown to mdast AST.+ *+ * @param text - The GFM text to parse+ * @returns The mdast AST+ *+ * @example+ * ```typescript+ * const ast = converter.toAst("Hello **world**");+ * // { type: "root", children: [{ type: "paragraph", ... }] }+ * ```+ */+ toAst(text: string): Root {+ return fromMarkdown(text, {+ extensions: [gfm()],+ mdastExtensions: [gfmFromMarkdown()],+ })+ }++ /**+ * Convert mdast AST back to GitHub Flavored Markdown.+ *+ * @param ast - The mdast AST to convert+ * @returns The GFM text+ *+ * @example+ * ```typescript+ * const text = converter.fromAst(ast);+ * // "Hello **world**"+ * ```+ */+ fromAst(ast: Root): string {+ return toMarkdown(ast, {+ extensions: [gfmToMarkdown()],+ })+ }++ /**+ * Extract plain text from markdown, stripping all formatting.+ *+ * @param text - The markdown text+ * @returns Plain text without formatting+ */+ toPlainText(text: string): string {+ const ast = this.toAst(text)+ return this.extractText(ast)+ }++ /**+ * Recursively extract text content from an AST node.+ */+ private extractText(node: Root | Root['children'][number]): string {+ if ('value' in node && typeof node.value === 'string') {+ return node.value+ }++ if ('children' in node && Array.isArray(node.children)) {+ return node.children.map(child => this.extractText(child)).join('')+ }++ return ''+ }++}diff --git a/apps/github-bot/server/utils/state-kv.ts b/apps/github-bot/server/utils/state-kv.tsnew file mode 100644index 0000000..312f26f--- /dev/null+++ b/apps/github-bot/server/utils/state-kv.ts@@ -0,0 +1,172 @@+/**+ * KVStateAdapter - StateAdapter implementation using NuxtHub KV+ *+ * This adapter demonstrates how to implement chat-sdk's StateAdapter interface+ * using NuxtHub's KV storage instead of Redis.+ *+ * Key prefixes:+ * - chat:sub:{threadId} - Thread subscriptions+ * - chat:lock:{threadId} - Distributed locks+ * - chat:cache:{key} - General cache+ */++import type { Lock, StateAdapter } from 'chat'+import { kv } from 'hub:kv'++export class KVStateAdapter implements StateAdapter {++ private connected = false++ /**+ * Connect to the state backend.+ * For KV, this is a no-op since KV is always available.+ */+ async connect(): Promise<void> {+ this.connected = true+ }++ /**+ * Disconnect from the state backend.+ */+ async disconnect(): Promise<void> {+ this.connected = false+ }++ // =========================================================================+ // Subscriptions+ // =========================================================================++ /**+ * Subscribe to a thread. Subscribed threads will receive all messages+ * via onSubscribedMessage handlers.+ */+ async subscribe(threadId: string): Promise<void> {+ await kv.set(`chat:sub:${threadId}`, true)+ }++ /**+ * Unsubscribe from a thread.+ */+ async unsubscribe(threadId: string): Promise<void> {+ await kv.del(`chat:sub:${threadId}`)+ }++ /**+ * Check if a thread is subscribed.+ */+ async isSubscribed(threadId: string): Promise<boolean> {+ return await kv.has(`chat:sub:${threadId}`)+ }++ /**+ * List all subscriptions, optionally filtered by adapter name.+ */+ 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+ }+ }+ }++ // =========================================================================+ // Distributed Locking+ // =========================================================================++ /**+ * Acquire a lock on a thread. Returns null if already locked.+ * Used to prevent concurrent message processing on the same thread.+ */+ async acquireLock(threadId: string, ttlMs: number): Promise<Lock | null> {+ const key = `chat:lock:${threadId}`+ const existing = await kv.get<Lock>(key)++ // Check if lock exists and hasn't expired+ if (existing && existing.expiresAt > Date.now()) {+ return null+ }++ // Create new lock+ const lock: Lock = {+ threadId,+ token: `kv_${Date.now()}_${Math.random().toString(36).slice(2)}`,+ expiresAt: Date.now() + ttlMs,+ }++ // Store with TTL (NuxtHub KV uses seconds)+ await kv.set(key, lock, { ttl: Math.ceil(ttlMs / 1000) })+ return lock+ }++ /**+ * Release a lock. Only the lock owner (matching token) can release.+ */+ async releaseLock(lock: Lock): Promise<void> {+ const key = `chat:lock:${lock.threadId}`+ const existing = await kv.get<Lock>(key)++ // Only delete if token matches (we own the lock)+ if (existing && existing.token === lock.token) {+ await kv.del(key)+ }+ }++ /**+ * Extend a lock's TTL. Returns false if lock expired or token doesn't match.+ */+ 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()) {+ // Lock has already expired+ await kv.del(key)+ return false+ }++ // Extend the lock+ existing.expiresAt = Date.now() + ttlMs+ await kv.set(key, existing, { ttl: Math.ceil(ttlMs / 1000) })+ return true+ }++ // =========================================================================+ // Cache+ // =========================================================================++ /**+ * Get a cached value by key.+ */+ async get<T = unknown>(key: string): Promise<T | null> {+ return await kv.get<T>(`chat:cache:${key}`)+ }++ /**+ * Set a cached value with optional TTL in milliseconds.+ */+ async set<T = unknown>(key: string, value: T, ttlMs?: number): Promise<void> {+ const opts = ttlMs ? { ttl: Math.ceil(ttlMs / 1000) } : undefined+ await kv.set(`chat:cache:${key}`, value, opts)+ }++ /**+ * Delete a cached value.+ */+ async delete(key: string): Promise<void> {+ await kv.del(`chat:cache:${key}`)+ }++}++/**+ * Create a new KVStateAdapter instance.+ */+export function createKVState(): KVStateAdapter {+ return new KVStateAdapter()+}diff --git a/apps/github-bot/tsconfig.json b/apps/github-bot/tsconfig.jsonnew file mode 100644index 0000000..6ae5970--- /dev/null+++ b/apps/github-bot/tsconfig.json@@ -0,0 +1,17 @@+{+ "files": [],+ "references": [+ {+ "path": "./.nuxt/tsconfig.app.json"+ },+ {+ "path": "./.nuxt/tsconfig.server.json"+ },+ {+ "path": "./.nuxt/tsconfig.shared.json"+ },+ {+ "path": "./.nuxt/tsconfig.node.json"+ }+ ]+}diff --git a/bun.lock b/bun.lockindex a2f1f47..2bf5c78 100644--- a/bun.lock+++ b/bun.lock@@ -48,6 +48,26 @@"vue-tsc": "^3.2.4",},},+ "apps/github-bot": {+ "name": "@savoir/github-bot",+ "version": "0.0.1",+ "dependencies": {+ "@ai-sdk/gateway": "^3.0.29",+ "@savoir/sdk": "workspace:*",+ "ai": "^6.0.62",+ "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",+ },+ "devDependencies": {+ "@nuxthub/core": "^0.10.5",+ "@types/mdast": "^4.0.4",+ "typescript": "^5.9.3",+ },+ },"packages/sdk": {"name": "@savoir/sdk","version": "0.0.1",@@ -73,11 +93,11 @@"packages": {"@adonisjs/hash": ["@adonisjs/[email protected]", "", { "dependencies": { "@phc/format": "^1.0.0", "@poppinss/utils": "^6.9.3" }, "peerDependencies": { "argon2": "^0.31.2 || ^0.41.0 || ^0.43.0", "bcrypt": "^5.1.1 || ^6.0.0" }, "optionalPeers": ["argon2", "bcrypt"] }, "sha512-ZkRguwjAp4skKvKDdRAfdJ2oqQ0N7p9l3sioyXO1E8o0WcsyDgEpsTQtuVNoIdMiw4sn4gJlmL3nyF4BcK1ZDQ=="],- "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.5", "@ai-sdk/provider-utils": "4.0.9", "@vercel/oidc": "3.1.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-hievGeM4cXkKvEbaHvlfVDubyp+XiTZmd0f2uvzBEMKfA98lDw0Fg/RKvNwQE6DQjRADkvVJNhSaHmlZRZeh3g=="],+ "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.6", "@ai-sdk/provider-utils": "4.0.11", "@vercel/oidc": "3.1.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-zf6yXT+7DcVGWG7ntxVCYC48X/opsWlO5ePvgH8W9DaEVUtkemqKUEzBqowQ778PkZo8sqMnRfD0+fi9HamRRQ=="],- "@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-2Xmoq6DBJqmSl80U6V9z5jJSJP7ehaJJQMy2iFUqTay06wdCqTnPVBBQbtEL8RCChenL+q5DC5H5WzU3vV3v8w=="],+ "@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-hSfoJtLtpMd7YxKM+iTqlJ0ZB+kJ83WESMiWuWrNVey3X8gg97x0OdAAaeAeclZByCX3UdPOTqhvJdK8qYA3ww=="],- "@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.5", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-bB4r6nfhBOpmoS9mePxjRoCy+LnzP3AfhyMGCkGL4Mn9clVNlqEeKj26zEKEtB6yoSVcT1IQ0Zh9fytwMCDnow=="],+ "@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.6", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-y/WOPpcZaBjvNaogy83mBsCRPvbtaK0y1sY9ckRrrbTGMvG2HC/9Y/huqNXKnLAxUIME2PGa2uvF2CDwIsxoXQ=="],"@ai-sdk/vue": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider-utils": "4.0.9", "ai": "6.0.50", "swrv": "^1.0.4" }, "peerDependencies": { "vue": "^3.3.4" } }, "sha512-uJsS3ohuVPCUSbXL/ZL6wy7xm8XzIxbbNJDsyf0Uu1W283MTaDSWlM/i9AuAKrpj4uHE3StrgIkU4H+6aFmD+g=="],@@ -781,6 +801,8 @@"@savoir/chat": ["@savoir/chat@workspace:apps/chat"],+ "@savoir/github-bot": ["@savoir/github-bot@workspace:apps/github-bot"],+"@savoir/sdk": ["@savoir/sdk@workspace:packages/sdk"],"@sec-ant/readable-stream": ["@sec-ant/[email protected]", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="],@@ -1251,7 +1273,7 @@"agent-base": ["[email protected]", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],- "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "3.0.23", "@ai-sdk/provider": "3.0.5", "@ai-sdk/provider-utils": "4.0.9", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-JlwqjkRTa6GR2CF+JksCuh1+jeZATJvvja53cj880bJsEgkMpS+rqjwr1E397WeRjkmoicbGGD8QxIDaFbsWHg=="],+ "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "3.0.29", "@ai-sdk/provider": "3.0.6", "@ai-sdk/provider-utils": "4.0.11", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-0ArQPYmSnwoDG1nQ7GQ2XyEtYEWMSK4pVV9S9nsChRY2D6P2H2ntMEDV/CqTF6GTSwJpBJHAOSvsgEqSc7dx5g=="],"ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="],@@ -1363,6 +1385,8 @@"character-reference-invalid": ["[email protected]", "", {}, "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="],+ "chat": ["[email protected]", "", { "dependencies": { "@workflow/serde": "4.0.1-beta.1", "mdast-util-to-string": "^4.0.0", "remark-gfm": "^4.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.5" } }, "sha512-y9QCeY4b7e4Emap0MjZtohZieQA47dhe9c4wUBtAI5HSTTn6Y9N4tEckVm04pHosSthqRZTjBEToM/wSCTzpLw=="],+"chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="],"chownr": ["[email protected]", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="],@@ -2921,6 +2945,10 @@"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],+ "@ai-sdk/vue/@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.5", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-bB4r6nfhBOpmoS9mePxjRoCy+LnzP3AfhyMGCkGL4Mn9clVNlqEeKj26zEKEtB6yoSVcT1IQ0Zh9fytwMCDnow=="],++ "@ai-sdk/vue/ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "3.0.23", "@ai-sdk/provider": "3.0.5", "@ai-sdk/provider-utils": "4.0.9", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-JlwqjkRTa6GR2CF+JksCuh1+jeZATJvvja53cj880bJsEgkMpS+rqjwr1E397WeRjkmoicbGGD8QxIDaFbsWHg=="],+"@aws-crypto/sha256-browser/@aws-sdk/types": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-jYIdB7a7jhRTvyb378nsjyvJh1Si+zVduJ6urMNGpz8RjkmHZ+9vM2H07XaIB2Cfq0GhJRZYOfUCH8uqQhqBkQ=="],"@aws-crypto/sha256-browser/@smithy/util-utf8": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],@@ -3481,6 +3509,12 @@"yaml-eslint-parser/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],+ "@ai-sdk/vue/@ai-sdk/provider-utils/@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-2Xmoq6DBJqmSl80U6V9z5jJSJP7ehaJJQMy2iFUqTay06wdCqTnPVBBQbtEL8RCChenL+q5DC5H5WzU3vV3v8w=="],++ "@ai-sdk/vue/ai/@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.5", "@ai-sdk/provider-utils": "4.0.9", "@vercel/oidc": "3.1.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-hievGeM4cXkKvEbaHvlfVDubyp+XiTZmd0f2uvzBEMKfA98lDw0Fg/RKvNwQE6DQjRADkvVJNhSaHmlZRZeh3g=="],++ "@ai-sdk/vue/ai/@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-2Xmoq6DBJqmSl80U6V9z5jJSJP7ehaJJQMy2iFUqTay06wdCqTnPVBBQbtEL8RCChenL+q5DC5H5WzU3vV3v8w=="],+"@aws-crypto/sha256-browser/@aws-sdk/types/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-9YcuJVTOBDjg9LWo23Qp0lTQ3D7fQsQtwle0jVfpbUHy9qBwCEgKuVH4FqFB3VYu0nwdHKiEMA+oXz7oV8X1kw=="],"@aws-crypto/sha256-browser/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],diff --git a/package.json b/package.jsonindex 0755f2e..ef57e9a 100644--- a/package.json+++ b/package.json@@ -21,6 +21,7 @@"build": "turbo run build","dev": "turbo run dev","dev:chat": "turbo run dev --filter=@savoir/chat",+ "dev:github-bot": "turbo run dev --filter=@savoir/github-bot","sync:docs": "turbo run sync:docs --filter=@savoir/chat","snapshot:create": "turbo run snapshot:create --filter=@savoir/chat","lint": "turbo run lint",