xonecas.io
53129
Pa

PAT / commit 9916a7f

refactor: simplify tools, remove outdated JSDocs

xonecas2025-12-22 9916a7f98707d221e4a3ddd3000f7c51dbf31cb5 parent b49cd51

22 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

.husky/pre-commit+1−1
@@ -8,4 +8,4 @@ npm run lint || exit 1
88 npm run typecheck || exit 1
99
1010 # Run tests (will fail if tests fail)
11-npm run test:run || exit 1
11+# npm run test:run || exit 1 # No tests yet
package-lock.json+26−0
@@ -18,6 +18,7 @@
1818 "highlight.js": "^11.11.1",
1919 "iovalkey": "^0.3.3",
2020 "next": "^16.0.10",
21+ "node-html-better-parser": "^1.5.8",
2122 "ollama": "^0.6.3",
2223 "postcss": "^8.4.30",
2324 "postgres": "^3.4.5",
@@ -6157,6 +6158,22 @@
61576158 "node": ">=12.0.0"
61586159 }
61596160 },
6161+ "node_modules/html-entities": {
6162+ "version": "2.6.0",
6163+ "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz",
6164+ "integrity": "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==",
6165+ "funding": [
6166+ {
6167+ "type": "github",
6168+ "url": "https://github.com/sponsors/mdevils"
6169+ },
6170+ {
6171+ "type": "patreon",
6172+ "url": "https://patreon.com/mdevils"
6173+ }
6174+ ],
6175+ "license": "MIT"
6176+ },
61606177 "node_modules/html-url-attributes": {
61616178 "version": "3.0.1",
61626179 "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
@@ -8170,6 +8187,15 @@
81708187 "url": "https://opencollective.com/node-fetch"
81718188 }
81728189 },
8190+ "node_modules/node-html-better-parser": {
8191+ "version": "1.5.8",
8192+ "resolved": "https://registry.npmjs.org/node-html-better-parser/-/node-html-better-parser-1.5.8.tgz",
8193+ "integrity": "sha512-t/wAKvaTSKco43X+yf9+76RiMt18MtMmzd4wc7rKj+fWav6DV4ajDEKdWlLzSE8USDF5zr/06uGj0Wr/dGAFtw==",
8194+ "license": "MIT",
8195+ "dependencies": {
8196+ "html-entities": "^2.3.2"
8197+ }
8198+ },
81738199 "node_modules/node-releases": {
81748200 "version": "2.0.27",
81758201 "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",
package.json+1−0
@@ -36,6 +36,7 @@
3636 "highlight.js": "^11.11.1",
3737 "iovalkey": "^0.3.3",
3838 "next": "^16.0.10",
39+ "node-html-better-parser": "^1.5.8",
3940 "ollama": "^0.6.3",
4041 "postcss": "^8.4.30",
4142 "postgres": "^3.4.5",
src/components/Button.tsx+0−5
@@ -10,11 +10,6 @@ type ButtonProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
1010 inline?: boolean;
1111 };
1212
13-/**
14- * Button: A reusable button component with neutral hover and selection states.
15- * When selected (isSelected=true), displays a neutral-800 background (dark) or neutral-200 (light).
16- * On hover, displays a neutral-700 background (dark) or neutral-300 (light).
17- */
1813 export default function Button({
1914 children,
2015 isSelected = false,
src/components/Switch.tsx+0−12
@@ -12,18 +12,6 @@ type SwitchProps = {
1212 "aria-label"?: string;
1313 };
1414
15-/**
16- * Switch component: accessible, keyboard-navigable, styled toggle.
17- *
18- * @param checked - Whether the switch is on
19- * @param onChange - Change handler
20- * @param disabled - Optional, disables interaction
21- * @param id - Optional, input id
22- * @param name - Optional, form input name
23- * @param className - Optional additional class names
24- * @param aria-label - Optional accessibility label
25- * @returns React component
26- */
2715 export const Switch = forwardRef<HTMLInputElement, SwitchProps>(function Switch(
2816 { checked, onChange, disabled = false, id, name, className = "", "aria-label": ariaLabel },
2917 ref
src/hooks/api/useModels.ts+0−5
@@ -5,11 +5,6 @@ export type Model = {
55 model: string;
66 };
77
8-/**
9- * Hook to fetch available models from the API.
10- *
11- * @returns a list of Models
12- */
138 export function useModels() {
149 return useQuery<{ models: Model[] }, Error>({
1510 queryKey: ["models"],
src/hooks/api/useThreadMessages.ts+0−7
@@ -2,13 +2,6 @@ import { Message } from "@/src/lib/db/schema";
22 import { useQuery } from "@tanstack/react-query";
33 import { useEffect } from "react";
44
5-/**
6- * Fetches messages for a given thread using react-query.
7- *
8- * @param threadId - The ID of the thread whose messages you want to fetch, or null to skip fetching.
9- * @param optionalRoles - (Optional) Array of message roles (e.g., ["user", "assistant"]) to filter retrieved messages.
10- * @returns react-query's useQuery result containing messages and error state.
11- */
125 export function useThreadMessages(
136 threadId: number | null,
147 optionalRoles: string[] = [],
src/hooks/api/useThreads.ts+0−6
@@ -7,12 +7,6 @@ export type ThreadsData = {
77 totalCount: number;
88 };
99
10-/**
11- * Fetches threads using react-query's useInfiniteQuery for paginated data.
12- *
13- * @param limit Number of threads to fetch per page.
14- * @returns InfiniteQuery result with `ThreadsData` pages.
15- */
1610 export function useThreads(limit: number = 8) {
1711 return useInfiniteQuery<ThreadsData, Error>({
1812 queryKey: ["threads", limit],
src/hooks/useAutoResizeTextarea.ts+0−9
@@ -1,14 +1,5 @@
11 import { useEffect, useRef } from "react";
22
3-/**
4- * Custom hook for auto-resizing a textarea element.
5- * Keeps an empty line at the bottom and enforces min/max height constraints.
6- *
7- * @param value - The current value of the textarea
8- * @param minLines - Minimum number of lines (default: 3)
9- * @param maxLines - Maximum number of lines (default: 10)
10- * @returns Ref to attach to the textarea element
11- */
123 export function useAutoResizeTextarea(
134 value: string,
145 minLines = 3,
src/hooks/useLocalStorage.ts+0−7
@@ -1,12 +1,5 @@
11 import { useState } from "react";
22
3-/**
4- * Custom hook for persisting state to localStorage.
5- *
6- * @param key - The localStorage key
7- * @param initialValue - The initial value if no stored value exists
8- * @returns A tuple of [value, setValue] similar to useState
9- */
103 export function useLocalStorage<T>(
114 key: string,
125 initialValue: T
src/hooks/useTheme.ts+0−8
@@ -1,14 +1,6 @@
11 import { useLocalStorage } from "@/src/hooks/useLocalStorage";
22 import { useEffect } from "react";
33
4-/**
5- * Custom hook for managing theme mode (device, dark, or light).
6- * Automatically applies the theme and listens for system preference changes when in device mode.
7- *
8- * @returns Object containing:
9- * - `themeMode` - Current theme mode: "device", "dark", or "light"
10- * - `handleThemeChange` - Function to change the theme mode
11- */
124 export function useTheme() {
135 const [themeMode, setThemeMode] = useLocalStorage<"device" | "dark" | "light">(
146 "theme.mode",
src/lib/cache/index.ts+8−16
@@ -1,5 +1,3 @@
1-/* personal-assistant-thing/src/lib/cache/index.ts */
2-
31 import ValKey from "iovalkey";
42
53 const valkeyUrl = process.env.VALKEY_URL;
@@ -9,14 +7,6 @@ if (!valkeyUrl) {
97
108 const valkey = new ValKey(valkeyUrl);
119
12-/**
13- * Sets a value in the cache with an optional TTL (time-to-live).
14- *
15- * @param key - The cache key
16- * @param value - The value to cache (must be JSON-serializable)
17- * @param ttlMs - Optional time-to-live in milliseconds. If provided, the entry will expire after this duration.
18- * @returns Promise that resolves when the value is cached
19- */
2010 export async function setCache<T>(key: string, value: T, ttlMs?: number): Promise<void> {
2111 try {
2212 const serialized = JSON.stringify(value);
@@ -33,12 +23,14 @@ export async function setCache<T>(key: string, value: T, ttlMs?: number): Promis
3323 }
3424 }
3525
36-/**
37- * Gets a value from the cache.
38- *
39- * @param key - The cache key
40- * @returns The cached value, or null if not found or expired
41- */
26+export async function incrementCache(key: string): Promise<void> {
27+ try {
28+ await valkey.incr(key);
29+ } catch {
30+ // Don't throw - cache operations should continue even if persistence fails
31+ }
32+}
33+
4234 export async function getCache<T>(key: string): Promise<T | null> {
4335 try {
4436 const serialized = await valkey.get(key);
src/lib/chat.ts+2−2
@@ -1,7 +1,7 @@
11 import { db } from "@/src/lib/db";
22 import { messages, threads } from "@/src/lib/db/schema";
33 import { createMessage } from "@/src/lib/messages";
4-import { executeToolCall, fetchPageTool, weatherTool, webSearchTool } from "@/src/lib/tools";
4+import { executeToolCall, fetchPageTool, webSearchTool } from "@/src/lib/tools";
55 import { asc, eq } from "drizzle-orm";
66 import ollama, { type Tool, type ToolCall } from "ollama";
77
@@ -40,7 +40,7 @@ async function agentLoop(
4040 messageHistory: MessageHistory,
4141 enqueue: (message: MessageHistoryEntry & { done?: boolean }) => void
4242 ) {
43- const tools: Tool[] = [weatherTool, fetchPageTool, webSearchTool];
43+ const tools: Tool[] = [fetchPageTool, webSearchTool];
4444 const newMessages: MessageHistory = [];
4545 let maxIterations = 6;
4646
src/lib/db/index.ts+0−11
@@ -1,4 +1,3 @@
1-/* personal-assistant-thing/src/lib/db/index.ts */
21 import { drizzle } from "drizzle-orm/postgres-js";
32 import postgres from "postgres";
43 import * as schema from "./schema";
@@ -17,13 +16,3 @@ const client = postgres(connectionString, {
1716
1817 // Create drizzle instance
1918 export const db = drizzle(client, { schema });
20-
21-/**
22- * Closes the database connection.
23- * Useful for cleanup operations, especially in serverless environments.
24- *
25- * @returns Promise that resolves when the connection is closed
26- */
27-export async function closeDatabase() {
28- await client.end();
29-}
src/lib/db/schema.ts+0−1
@@ -1,4 +1,3 @@
1-/* personal-assistant-thing/src/lib/db/schema.ts */
21 import { relations } from "drizzle-orm";
32 import { integer, pgTable, serial, text, timestamp } from "drizzle-orm/pg-core";
43
src/lib/debug.ts+0−6
@@ -1,9 +1,3 @@
1-/* personal-assistant-thing/src/lib/debug.ts */
2-
3-/**
4- * Debug logging utility that only logs in development mode.
5- * Accepts the same arguments as console.debug().
6- */
71 export function debug(...args: Parameters<typeof console.debug>): void {
82 if (process.env.NODE_ENV === "development") {
93 console.debug(...args);
src/lib/ratelimit.ts+0−166
@@ -1,166 +0,0 @@
1-/* personal-assistant-thing/src/lib/ratelimit.ts */
2-
3-import { getCache, setCache } from "./cache";
4-
5-/**
6- * Rate limit state structure.
7- */
8-interface RateLimitState {
9- windowStart: number; // Unix timestamp in milliseconds
10- requestCount: number;
11-}
12-
13-/**
14- * Configuration for a rate limiter.
15- */
16-export interface RateLimitConfig {
17- maxRequests: number; // Maximum number of requests allowed
18- windowMs: number; // Time window in milliseconds
19- identifier: string; // Unique identifier for this rate limiter (used as cache key prefix)
20-}
21-
22-/**
23- * Result of a rate limit check.
24- */
25-export interface RateLimitResult {
26- allowed: boolean; // Whether the request is allowed
27- remaining: number; // Number of requests remaining in the current window
28- resetAt: number; // Unix timestamp when the rate limit window resets
29- hoursUntilReset?: number; // Optional: hours until reset (for user-friendly messages)
30-}
31-
32-/**
33- * Creates a rate limiter with the specified configuration.
34- * Uses the cache utility for persistence across restarts.
35- *
36- * @param config - Rate limit configuration
37- * @returns Rate limiter functions
38- */
39-export function createRateLimiter(config: RateLimitConfig) {
40- const cacheKey = `ratelimit:${config.identifier}`;
41-
42- /**
43- * Loads the current rate limit state from cache.
44- * Automatically resets the window if it has expired.
45- *
46- * @returns Current rate limit state
47- */
48- async function loadState(): Promise<RateLimitState> {
49- const cached = await getCache<RateLimitState>(cacheKey);
50- const now = Date.now();
51-
52- if (!cached) {
53- // No existing state, start fresh
54- const newState: RateLimitState = {
55- windowStart: now,
56- requestCount: 0,
57- };
58- await setCache(cacheKey, newState);
59- return newState;
60- }
61-
62- const timeSinceWindowStart = now - cached.windowStart;
63-
64- // If the window has expired, reset it
65- if (timeSinceWindowStart >= config.windowMs) {
66- const newState: RateLimitState = {
67- windowStart: now,
68- requestCount: 0,
69- };
70- await setCache(cacheKey, newState);
71- return newState;
72- }
73-
74- return cached;
75- }
76-
77- /**
78- * Saves the rate limit state to cache.
79- *
80- * @param state - The state to save
81- */
82- async function saveState(state: RateLimitState): Promise<void> {
83- await setCache(cacheKey, state);
84- }
85-
86- /**
87- * Checks if a request is allowed within the rate limit.
88- *
89- * @returns Rate limit check result
90- */
91- async function check(): Promise<RateLimitResult> {
92- const state = await loadState();
93- const now = Date.now();
94-
95- // Calculate when the window resets
96- const resetAt = state.windowStart + config.windowMs;
97- const hoursUntilReset = Math.ceil((resetAt - now) / (60 * 60 * 1000));
98-
99- // Check if we've exceeded the limit
100- if (state.requestCount >= config.maxRequests) {
101- return {
102- allowed: false,
103- remaining: 0,
104- resetAt,
105- hoursUntilReset,
106- };
107- }
108-
109- const remaining = config.maxRequests - state.requestCount;
110-
111- return {
112- allowed: true,
113- remaining,
114- resetAt,
115- hoursUntilReset,
116- };
117- }
118-
119- /**
120- * Increments the request counter and saves the state.
121- * Should be called after a request is made (or attempted).
122- */
123- async function increment(): Promise<void> {
124- const state = await loadState();
125- state.requestCount++;
126- await saveState(state);
127- }
128-
129- /**
130- * Resets the rate limit window manually.
131- */
132- async function reset(): Promise<void> {
133- const newState: RateLimitState = {
134- windowStart: Date.now(),
135- requestCount: 0,
136- };
137- await saveState(newState);
138- }
139-
140- /**
141- * Gets the current rate limit state without modifying it.
142- *
143- * @returns Current rate limit state
144- */
145- async function getState(): Promise<RateLimitResult> {
146- const state = await loadState();
147- const now = Date.now();
148- const resetAt = state.windowStart + config.windowMs;
149- const hoursUntilReset = Math.ceil((resetAt - now) / (60 * 60 * 1000));
150- const remaining = Math.max(0, config.maxRequests - state.requestCount);
151-
152- return {
153- allowed: state.requestCount < config.maxRequests,
154- remaining,
155- resetAt,
156- hoursUntilReset,
157- };
158- }
159-
160- return {
161- check,
162- increment,
163- reset,
164- getState,
165- };
166-}
src/lib/tools/fetchpage.ts+37−128
@@ -1,147 +1,56 @@
11 import { getCache, setCache } from "@/src/lib/cache";
2-import { createRateLimiter } from "@/src/lib/ratelimit";
2+import { debug } from "@/src/lib/debug";
3+import { parse } from "node-html-better-parser";
34
45 const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
56
6-const fetchPageRateLimiter = createRateLimiter({
7- maxRequests: 100,
8- windowMs: 24 * 60 * 60 * 1000, // 24 hours in milliseconds
9- identifier: "fetchpage",
10-});
11-
12-/**
13- * Sanitizes HTML content by extracting text and removing scripts, styles, and other non-content elements.
14- * Returns a clean text string with normalized whitespace.
15- */
16-function sanitizeHtml(html: string): string {
17- // Remove script and style tags and their content
18- let sanitized = html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "");
19- sanitized = sanitized.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
20- sanitized = sanitized.replace(/<noscript[^>]*>[\s\S]*?<\/noscript>/gi, "");
21-
22- // Remove HTML comments
23- sanitized = sanitized.replace(/<!--[\s\S]*?-->/g, "");
24-
25- // Extract text from common content tags
26- const textMatches = sanitized.match(
27- /<(?:p|div|h[1-6]|article|section|main|header|footer|li|td|th|span|a|strong|em|b|i|blockquote|pre|code)[^>]*>([\s\S]*?)<\/[^>]+>/gi
28- );
29-
30- if (!textMatches || textMatches.length === 0) {
31- // Fallback: extract all text between tags
32- sanitized = sanitized.replace(/<[^>]+>/g, " ");
33- } else {
34- // Extract text content from matched tags
35- sanitized = textMatches
36- .map((match) => {
37- // Remove nested tags and extract text
38- return match.replace(/<[^>]+>/g, " ").trim();
39- })
40- .join("\n");
41- }
42-
43- // Remove remaining HTML tags
44- sanitized = sanitized.replace(/<[^>]+>/g, " ");
45-
46- // Decode common HTML entities
47- sanitized = sanitized
48- .replace(/&nbsp;/g, " ")
49- .replace(/&amp;/g, "&")
50- .replace(/&lt;/g, "<")
51- .replace(/&gt;/g, ">")
52- .replace(/&quot;/g, '"')
53- .replace(/&#39;/g, "'")
54- .replace(/&apos;/g, "'");
55-
56- // Normalize whitespace
57- sanitized = sanitized
58- .replace(/\s+/g, " ")
59- .replace(/\n\s*\n/g, "\n")
60- .trim();
61-
62- return sanitized;
63-}
7+type FetchPageResult = {
8+ title: string;
9+ content: string;
10+ links: string[];
11+};
6412
65-/**
66- * Fetches a web page from the given URL and returns sanitized text content.
67- * Results are cached for 6 hours.
68- *
69- * @param url - The URL of the web page to fetch.
70- * @returns A sanitized string containing the text content of the page.
71- */
72-export async function fetchPage(url: string): Promise<string> {
73- // Validate URL
74- let parsedUrl: URL;
75- try {
76- parsedUrl = new URL(url);
77- // Only allow http and https protocols
78- if (!["http:", "https:"].includes(parsedUrl.protocol)) {
79- throw new Error("Only HTTP and HTTPS URLs are allowed");
13+const extractText = (el: unknown): string => {
14+ if (!el || typeof el !== "object") return "";
15+ const elem = el as { text?: string; childNodes?: unknown[] };
16+ let text = elem.text || "";
17+ if (elem.childNodes) {
18+ for (const child of elem.childNodes) {
19+ text += extractText(child);
8020 }
81- } catch {
82- throw new Error(`Invalid URL: ${url}`);
8321 }
22+ return text;
23+};
8424
85- // Check cache first
86- const cacheKey = `fetchpage:${url}`;
87- const cached = await getCache<string>(cacheKey);
88- if (cached !== null) {
25+export async function fetchPage(url: string): Promise<FetchPageResult> {
26+ const cached = await getCache<FetchPageResult>(`fetchpage:${url}`);
27+ if (cached) {
8928 return cached;
9029 }
9130
92- // Check rate limit
93- const rateLimitCheck = await fetchPageRateLimiter.check();
94- if (!rateLimitCheck.allowed) {
95- throw new Error("Service temporarily unavailable");
96- }
97-
98- await fetchPageRateLimiter.increment();
99-
100- try {
101- // Fetch the page with a timeout and user agent
102- const controller = new AbortController();
103- const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
104-
105- const response = await fetch(url, {
106- signal: controller.signal,
107- headers: {
108- "User-Agent": "Mozilla/5.0 (compatible; PersonalAssistant/1.0)",
109- },
110- });
31+ const result: FetchPageResult = {
32+ title: "",
33+ content: "",
34+ links: [],
35+ };
11136
112- clearTimeout(timeoutId);
37+ const response = await fetch(url);
38+ const html = await response.text();
39+ const root = parse(html);
11340
114- if (!response.ok) {
115- throw new Error(`Failed to fetch page: ${response.status} ${response.statusText}`);
116- }
41+ const title = root.querySelector("title")?.text;
42+ const content = extractText(root.querySelector("body"));
43+ const links = root.querySelectorAll("a").map((a) => a.getAttribute("href"));
11744
118- const html = await response.text();
119- const sanitized = sanitizeHtml(html);
45+ result.title = title?.trim() || "";
46+ result.content = content?.trim() || "";
47+ result.links = links.filter((link): link is string => link !== null);
12048
121- if (!sanitized || sanitized.trim().length === 0) {
122- const result = `No text content found at: ${url}`;
123- await setCache(cacheKey, result, CACHE_TTL_MS);
124- return result;
125- }
49+ debug(`fetched page ${url}`, result);
12650
127- // Limit result length to prevent excessive token usage
128- const maxLength = 10000;
129- const result =
130- sanitized.length > maxLength
131- ? `${sanitized.substring(0, maxLength)}... [content truncated]`
132- : sanitized;
51+ await setCache<FetchPageResult>(`fetchpage:${url}`, result, CACHE_TTL_MS);
13352
134- await setCache(cacheKey, result, CACHE_TTL_MS);
135- return result;
136- } catch (error) {
137- if (error instanceof Error) {
138- if (error.name === "AbortError") {
139- throw new Error("Request timeout: The page took too long to load");
140- }
141- throw error;
142- }
143- throw new Error("Unknown error occurred while fetching the page");
144- }
53+ return result;
14554 }
14655
14756 export const fetchPageTool = {
@@ -149,7 +58,7 @@ export const fetchPageTool = {
14958 function: {
15059 name: "fetch_page",
15160 description:
152- "Fetches a web page from a given URL and returns sanitized text content. Use this tool when asked to fetch a web page, retrieve content from a URL, or read information from a specific webpage.",
61+ "Fetch a web page and return the title, content, and links in JSON format. Use this tool when asked to fetch a web page, retrieve content from a URL, or read information from a specific webpage.",
15362 parameters: {
15463 type: "object",
15564 properties: {
src/lib/tools/index.ts+4−12
@@ -1,26 +1,18 @@
11 /* personal-assistant-thing/src/lib/ollama/tools/index.ts */
22
33 import { fetchPage } from "@/src/lib/tools/fetchpage";
4-import { queryWeather } from "@/src/lib/tools/weather";
5-import { queryWebSearch } from "@/src/lib/tools/websearch";
4+import { webSearch } from "@/src/lib/tools/websearch";
65 import type { ToolCall } from "ollama";
76
87 export { fetchPage, fetchPageTool } from "@/src/lib/tools/fetchpage";
9-export { queryWeather, weatherTool } from "@/src/lib/tools/weather";
10-export { queryWebSearch, webSearchTool } from "@/src/lib/tools/websearch";
8+export { webSearch, webSearchTool } from "@/src/lib/tools/websearch";
119
1210 export async function executeToolCall(toolCall: ToolCall) {
1311 switch (toolCall.function.name) {
14- case "query_weather":
15- return await queryWeather(
16- toolCall.function.arguments.query,
17- toolCall.function.arguments.timezone,
18- toolCall.function.arguments.forecastDays
19- );
2012 case "fetch_page":
2113 return await fetchPage(toolCall.function.arguments.url);
22- case "query_web_search":
23- return await queryWebSearch(toolCall.function.arguments.query);
14+ case "web_search":
15+ return await webSearch(toolCall.function.arguments.query);
2416 default:
2517 throw new Error(`Unknown tool: ${toolCall.function.name}`);
2618 }
src/lib/tools/weather.ts+0−178
@@ -1,178 +0,0 @@
1-import { getCache, setCache } from "@/src/lib/cache";
2-import { createRateLimiter } from "@/src/lib/ratelimit";
3-
4-const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
5-
6-/**
7- * Rate limiter for weather API requests.
8- * Tracks requests per 24-hour rolling window.
9- */
10-const weatherRateLimiter = createRateLimiter({
11- maxRequests: 1000,
12- windowMs: 24 * 60 * 60 * 1000, // 24 hours in milliseconds
13- identifier: "weather",
14-});
15-
16-/**
17- * Queries Open-Meteo's weather API for current weather and forecast information.
18- * Results are cached for 6 hours.
19- *
20- * @param query - The location name (e.g., 'New York', 'London', 'Tokyo').
21- * @param timezone - Timezone (e.g., 'America/New_York', 'Europe/London', 'auto'). Defaults to 'auto'.
22- * @param forecastDays - Number of forecast days (1-16). Defaults to 3.
23- * @returns A formatted string containing weather information or an error message.
24- */
25-export async function queryWeather(
26- query: string,
27- timezone = "auto",
28- forecastDays = 0
29-): Promise<string> {
30- // Validate forecastDays (0 means no forecast, 1-16 for forecast days)
31- const days = Math.max(0, Math.min(16, Math.round(forecastDays)));
32-
33- // Check cache first
34- const cacheKey = `weather:${query.toLowerCase().trim()}:${timezone}:${days}`;
35- const cached = await getCache<string>(cacheKey);
36- if (cached !== null) {
37- return cached;
38- }
39-
40- // Check rate limit before making the request
41- const rateLimitCheck = await weatherRateLimiter.check();
42- if (!rateLimitCheck.allowed) {
43- const hoursRemaining = rateLimitCheck.hoursUntilReset || 0;
44- throw new Error(
45- `Weather API rate limit exceeded. Maximum of 1000 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`
46- );
47- }
48-
49- // Increment rate limit counter before making the request
50- // This ensures all API attempts are counted, not just successful ones
51- await weatherRateLimiter.increment();
52-
53- const sanitizedQuery = query.trim();
54- // First, geocode the location to get coordinates
55- const geocodeUrl = "https://geocoding-api.open-meteo.com/v1/search";
56- const geocodeParams = new URLSearchParams({
57- name: sanitizedQuery,
58- count: "1",
59- language: "en",
60- format: "json",
61- });
62-
63- const geocodeResponse = await fetch(`${geocodeUrl}?${geocodeParams.toString()}`);
64- if (!geocodeResponse.ok) {
65- throw new Error(`Failed to geocode location "${query}" (${geocodeResponse.status})`);
66- }
67-
68- const geocodeData = await geocodeResponse.json();
69-
70- if (!geocodeData.results || geocodeData.results.length === 0) {
71- throw new Error(
72- `Could not find location "${query}". Please provide a more specific location name.`
73- );
74- }
75-
76- const { latitude, longitude, name, country, admin1 } = geocodeData.results[0];
77- const locationName = `${name}${admin1 ? `, ${admin1}` : ""}${country ? `, ${country}` : ""}`;
78-
79- // Now fetch weather data - focus on temperature and precipitation
80- const weatherUrl = "https://api.open-meteo.com/v1/forecast";
81- const weatherParams = new URLSearchParams({
82- latitude: latitude.toString(),
83- longitude: longitude.toString(),
84- current: "temperature_2m,precipitation",
85- timezone: timezone,
86- });
87-
88- // Only request daily forecast if forecastDays > 0
89- if (days > 0) {
90- weatherParams.append("daily", "temperature_2m_max,temperature_2m_min,precipitation_sum");
91- weatherParams.append("forecast_days", days.toString());
92- }
93-
94- const weatherResponse = await fetch(`${weatherUrl}?${weatherParams.toString()}`);
95- if (!weatherResponse.ok) {
96- throw new Error(
97- `Failed to fetch weather data for "${locationName}" (${weatherResponse.status})`
98- );
99- }
100-
101- const weatherData = await weatherResponse.json();
102-
103- // Format concise response focusing on temperature and precipitation
104- const parts: string[] = [];
105- parts.push(`${locationName}:`);
106-
107- // Current conditions
108- if (weatherData.current) {
109- const current = weatherData.current;
110- const temp = current.temperature_2m;
111- const precip = current.precipitation;
112- if (temp !== undefined) {
113- parts.push(`Now: ${temp}°C${precip !== undefined && precip > 0 ? `, ${precip}mm rain` : ""}`);
114- }
115- }
116-
117- // Daily forecast (only if forecastDays > 0)
118- if (days > 0 && weatherData.daily && weatherData.daily.time) {
119- for (let i = 0; i < Math.min(days, weatherData.daily.time.length); i++) {
120- const date = new Date(weatherData.daily.time[i]);
121- const dayName = date.toLocaleDateString("en-US", { weekday: "short" });
122- const maxTemp = weatherData.daily.temperature_2m_max?.[i];
123- const minTemp = weatherData.daily.temperature_2m_min?.[i];
124- const precipitation = weatherData.daily.precipitation_sum?.[i];
125-
126- const tempStr =
127- maxTemp !== undefined && minTemp !== undefined
128- ? `${minTemp}°/${maxTemp}°C`
129- : maxTemp !== undefined
130- ? `${maxTemp}°C`
131- : "";
132- const precipStr =
133- precipitation !== undefined && precipitation > 0 ? `, ${precipitation}mm` : "";
134-
135- if (tempStr) {
136- parts.push(`${dayName}: ${tempStr}${precipStr}`);
137- }
138- }
139- }
140-
141- const result = parts.join("\n");
142- // Cache successful results
143- await setCache(cacheKey, result, CACHE_TTL_MS);
144- return result;
145-}
146-
147-/**
148- * Defines the weather query tool for Ollama.
149- */
150-export const weatherTool = {
151- type: "function" as const,
152- function: {
153- name: "query_weather",
154- description:
155- "Query Open-Meteo's weather API to get current weather conditions and optionally forecast for a location. Returns temperature and precipitation data. By default returns only current weather. Use forecastDays parameter to include forecast. Use this when users ask about weather, temperature, forecast, or current conditions for any location worldwide.",
156- parameters: {
157- type: "object",
158- properties: {
159- query: {
160- type: "string",
161- description:
162- "Location name (e.g., 'New York', 'London', 'Tokyo', 'Paris'). Can be a city name, city with country, or more specific location.",
163- },
164- timezone: {
165- type: "string",
166- description:
167- "Timezone (e.g., 'America/New_York', 'Europe/London', 'Asia/Tokyo'). Use 'auto' to automatically detect. Defaults to 'auto'.",
168- },
169- forecastDays: {
170- type: "number",
171- description:
172- "Number of forecast days (0-16). Use 0 for current weather only (default), or 1-16 for forecast days.",
173- },
174- },
175- required: ["query"],
176- },
177- },
178-};
src/lib/tools/websearch.ts+23−39
@@ -1,28 +1,30 @@
1-/* personal-assistant-thing/src/lib/ollama/tools/websearch.ts */
2-
3-import { getCache, setCache } from "@/src/lib/cache";
4-import { createRateLimiter } from "@/src/lib/ratelimit";
1+import { getCache, incrementCache, setCache } from "@/src/lib/cache";
52 import { google } from "googleapis";
3+import type { customsearch_v1 } from "googleapis/build/src/apis/customsearch/v1";
64
7-const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
8-
9-const webSearchRateLimiter = createRateLimiter({
10- maxRequests: 100,
11- windowMs: 24 * 60 * 60 * 1000, // 24 hours in milliseconds
12- identifier: "websearch",
13-});
5+const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
146
15-/**
16- * Performs web search via Google Custom Search API. Results cached 6h.
17- */
18-export async function queryWebSearch(query: string): Promise<string> {
7+export async function webSearch(query: string): Promise<customsearch_v1.Schema$Result[] | null> {
198 // Check cache first
209 const cacheKey = `websearch:${query.toLowerCase().trim()}`;
21- const cached = await getCache<string>(cacheKey);
10+ const cached = await getCache<customsearch_v1.Schema$Result[]>(cacheKey);
2211 if (cached !== null) {
2312 return cached;
2413 }
2514
15+ // Check rate limit, reset every 24 hours
16+ const countKey = `websearch:count:${query.toLowerCase().trim()}`;
17+ const count = await getCache<number>(countKey);
18+ if (count === null) {
19+ await setCache(countKey, 1, CACHE_TTL_MS);
20+ } else {
21+ await incrementCache(countKey);
22+ }
23+
24+ if (count && count >= 100) {
25+ throw new Error("Service temporarily unavailable, rate limit exceeded");
26+ }
27+
2628 const apiKey = process.env.GOOGLE_CUSTOM_SEARCH_API_KEY;
2729 const cx = process.env.GOOGLE_CUSTOM_SEARCH_ENGINE_ID;
2830
@@ -30,13 +32,6 @@ export async function queryWebSearch(query: string): Promise<string> {
3032 throw new Error("Service unavailable");
3133 }
3234
33- const rateLimitCheck = await webSearchRateLimiter.check();
34- if (!rateLimitCheck.allowed) {
35- throw new Error("Service temporarily unavailable");
36- }
37-
38- await webSearchRateLimiter.increment();
39-
4035 const customsearch = google.customsearch("v1");
4136 const res = await customsearch.cse.list({
4237 cx: cx,
@@ -45,22 +40,10 @@ export async function queryWebSearch(query: string): Promise<string> {
4540 });
4641
4742 if (!res.data.items || res.data.items.length === 0) {
48- const result = `No results for: ${query}`;
49- await setCache(cacheKey, result, CACHE_TTL_MS);
50- return result;
43+ return null;
5144 }
5245
53- const results = res.data.items
54- .slice(0, 5)
55- .map((item) => {
56- const parts: string[] = [];
57- if (item.title) parts.push(item.title);
58- if (item.snippet) parts.push(item.snippet);
59- if (item.link) parts.push(`(${item.link})`);
60- return parts.join(" | ");
61- })
62- .join("\n");
63-
46+ const results = res.data.items;
6447 await setCache(cacheKey, results, CACHE_TTL_MS);
6548 return results;
6649 }
@@ -68,8 +51,9 @@ export async function queryWebSearch(query: string): Promise<string> {
6851 export const webSearchTool = {
6952 type: "function" as const,
7053 function: {
71- name: "query_web_search",
72- description: "Search the web for current info, news, articles, or any content.",
54+ name: "web_search",
55+ description:
56+ "Search the web, use this tool to augment your responses with current and local information, news, articles, or any other relevant content.",
7357 parameters: {
7458 type: "object",
7559 properties: {
src/tests/lib/ratelimit.test.ts+0−557
@@ -1,557 +0,0 @@
1-/* personal-assistant-thing/src/lib/ratelimit.test.ts */
2-
3-import * as cacheModule from "@/src/lib/cache";
4-import { createRateLimiter, type RateLimitConfig } from "@/src/lib/ratelimit";
5-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6-
7-// Mock the cache module
8-vi.mock("@/src/lib/cache", () => ({
9- getCache: vi.fn(),
10- setCache: vi.fn(),
11-}));
12-
13-describe("createRateLimiter", () => {
14- const mockGetCache = vi.mocked(cacheModule.getCache);
15- const mockSetCache = vi.mocked(cacheModule.setCache);
16-
17- beforeEach(() => {
18- vi.clearAllMocks();
19- vi.useFakeTimers();
20- });
21-
22- afterEach(() => {
23- vi.useRealTimers();
24- });
25-
26- describe("Initial state", () => {
27- it("should create a new rate limiter with no existing cache", async () => {
28- mockGetCache.mockResolvedValue(null);
29- mockSetCache.mockResolvedValue(undefined);
30-
31- const config: RateLimitConfig = {
32- maxRequests: 10,
33- windowMs: 1000,
34- identifier: "test-limiter",
35- };
36-
37- const limiter = createRateLimiter(config);
38- const result = await limiter.check();
39-
40- expect(result.allowed).toBe(true);
41- expect(result.remaining).toBe(10);
42- expect(mockGetCache).toHaveBeenCalledWith("ratelimit:test-limiter");
43- expect(mockSetCache).toHaveBeenCalled();
44- });
45-
46- it("should use existing cache state if available", async () => {
47- const existingState = {
48- windowStart: Date.now() - 100,
49- requestCount: 3,
50- };
51- mockGetCache.mockResolvedValue(existingState);
52-
53- const config: RateLimitConfig = {
54- maxRequests: 10,
55- windowMs: 1000,
56- identifier: "test-limiter",
57- };
58-
59- const limiter = createRateLimiter(config);
60- const result = await limiter.check();
61-
62- expect(result.allowed).toBe(true);
63- expect(result.remaining).toBe(7);
Cut short: this commit's diff is over 1000 lines.