stevennshandleUSPSEmail.ts3 matches
4const RECIPIENTS = ["Geoffrey", "Maggie"] as const;
56function parseDateFromSubject(subject: string): string | null {
7const match = subject.match(/(\w{3}), (\d{1,2}\/\d{1,2})/);
8if (match) {
19};
2021async function analyzeHtmlContent(
22anthropic: Anthropic,
23htmlContent: string,
80}
8182export default async function (e: Email) {
83console.log("email content");
84console.log(e.html);
stevennshandleTelegramMessage.ts5 matches
36* Store a chat message in the database
37*/
38export async function storeChatMessage(
39chatId,
40senderId,
69* Retrieve chat history for a specific chat
70*/
71export async function getChatHistory(chatId, limit = 50) {
72try {
73const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
94* Format chat history for Anthropic API
95*/
96function formatChatHistoryForAI(history) {
97const messages = [];
98118* Analyze a Telegram message and extract memories from it
119*/
120async function analyzeMessageContent(
121anthropic,
122username,
499500// Handle webhook requests
501export default async function (req: Request): Promise<Response> {
502// Set webhook if it is not set yet
503if (!isEndpointSet) {
stevennsgetWeather.ts5 matches
8const TABLE_NAME = `memories`;
910function summarizeWeather(weather: WeatherResponse) {
11const summarizeDay = (day: WeatherResponse["weather"][number]) => ({
12date: day.date,
25}
2627async function generateConciseWeatherSummary(weatherDay) {
28try {
29// Get API key from environment
83}
8485async function deleteExistingForecast(date: string) {
86await sqlite.execute(
87`
93}
9495async function insertForecast(date: string, forecast: string) {
96const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
97112}
113114export default async function getWeatherForecast(interval: number) {
115const weather = await getWeather("Washington, DC");
116console.log({ weather });
stevennsgetCalendarEvents.ts6 matches
6const LOCAL_TIMEZONE = "America/New_York";
78async function deleteExistingCalendarEvents() {
9await sqlite.execute(
10`
15}
1617// Helper function to extract time from ISO string without timezone conversion
18function extractTimeFromISO(isoString) {
19// Match the time portion of the ISO string
20const timeMatch = isoString.match(/T(\d{2}):(\d{2}):/);
31}
3233function formatEventToNaturalLanguage(event) {
34const summary = event.summary || "Untitled event";
3583}
8485async function insertCalendarEvent(date, eventText) {
86const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
8797}
9899export default async function getCalendarEvents() {
100try {
101const events = await getEvents(
stevennsgenerateFunFacts.ts8 matches
11* @returns Array of previous fun facts
12*/
13async function getPreviousFunFacts() {
14try {
15const result = await sqlite.execute(
32* @param dates Array of date strings in ISO format
33*/
34async function deleteExistingFunFacts(dates) {
35try {
36for (const date of dates) {
51* @param factText The fun fact text
52*/
53async function insertFunFact(date, factText) {
54try {
55await sqlite.execute(
75* @returns Array of generated fun facts
76*/
77async function generateFunFacts(previousFacts) {
78try {
79// Get API key from environment
197* @returns Array of parsed facts
198*/
199function parseFallbackFacts(responseText, expectedDates) {
200// Try to extract facts using regex
201const factPattern = /(\d{4}-\d{2}-\d{2})["']?[,:]?\s*["']?(.*?)["']?[,}]/gs;
260261/**
262* Main function to generate and store fun facts for the next 7 days
263*/
264export async function generateAndStoreFunFacts() {
265try {
266// Get previous fun facts
301* Intended to be used as a Val Town cron job
302*/
303export default async function() {
304console.log("Running fun facts generation cron job...");
305return await generateAndStoreFunFacts();
stevenns.cursorrules15 matches
8### 1. Script Vals
910- Basic JavaScript/TypeScript functions
11- Can be imported by other vals
12- Example structure:
1314```typescript
15export function myFunction() {
16// Your code here
17}
2526```typescript
27export default async function (req: Request) {
28return new Response("Hello World");
29}
3738```typescript
39export default async function () {
40// Scheduled task code
41}
4950```typescript
51export default async function (email: Email) {
52// Process email
53}
5758- Ask clarifying questions when requirements are ambiguous
59- Provide complete, functional solutions rather than skeleton implementations
60- Test your logic against edge cases before presenting the final solution
61- Ensure all code follows Val Town's specific platform requirements
70- **Never bake in secrets into the code** - always use environment variables
71- Include comments explaining complex logic (avoid commenting obvious operations)
72- Follow modern ES6+ conventions and functional programming practices if possible
7374## Val Town Standard Libraries
7576Val Town provides several hosted services and utility functions.
7778### Blob Storage
124```
125126## Val Town Utility Functions
127128Val Town provides several utility functions to help with common project tasks.
129130### Importing Utilities
176{
177name: "should add numbers correctly",
178function: () => {
179expect(1 + 1).toBe(2);
180},
210โ โโโ database/
211โ โ โโโ migrations.ts # Schema definitions
212โ โ โโโ queries.ts # DB query functions
213โ โ โโโ README.md
214โ โโโ index.ts # Main entry point
226โโโ shared/
227โโโ README.md
228โโโ utils.ts # Shared types and functions
229```
230232- Hono is the recommended API framework (similar to Express, Flask, or Sinatra)
233- Main entry point should be `backend/index.ts`
234- **Static asset serving:** Use the utility functions to read and serve project files:
235```ts
236// Use the serveFile utility to handle content types automatically
273- Run migrations on startup or comment out for performance
274- Change table names when modifying schemas rather than altering
275- Export clear query functions with proper TypeScript typing
276- Follow the queries and migrations pattern from the example
277
stevennscronDailyBrief.ts1 match
1import { sendDailyBriefing } from "./sendDailyBrief.ts";
23export async function cronDailyBrief() {
4try {
5const chatId = Deno.env.get("TELEGRAM_CHAT_ID");
62};
6364export function App() {
65const [memories, setMemories] = useState<Memory[]>([]);
66const [loading, setLoading] = useState(true);
139const data = await response.json();
140141// Change the sorting function to show memories in chronological order
142const sortedMemories = [...data].sort((a, b) => {
143const dateA = a.createdDate || 0;
170}
171172// --- HTML Generation Function (Glassmorphism UI) ---
173function generateHtmlShell(initialUrl, initialText, sourceUrl, appConfig, analysisAgents, currentLocaleStrings) {
174const escapedUrl = initialUrl ? initialUrl.replace(/"/g, """) : "";
175const escapedText = initialText ? initialText.replace(/</g, "<").replace(/>/g, ">") : "";
416let currentLocale = APP_CONFIG.default_language || 'en';
417418// --- Localization Functions (largely unchanged, uses 'locales' object) ---
419function translate(key, replacements = {}) { /* ... original ... */ }
420function applyTranslations() { /* ... original ... */ }
421function setLocale(locale) { /* ... original ... */ }
422function updateLocaleButtons() {
423document.querySelectorAll('.lang-btn').forEach(btn => btn.classList.toggle('active', btn.dataset.lang === currentLocale));
424const linkHtml = \`<a href="\${APP_CONFIG.footer_powered_by_url}" target="_top">\${APP_CONFIG.footer_powered_by_link_text}</a>\`;
436const resultsContainer = document.getElementById('results-content-cards'); // Container for dynamic cards
437438// --- UI Update Functions ---
439function setLoadingState(isLoading) { /* ... original, use translate for button text ... */ }
440function displayError(messageKey, replacements = {}) { /* ... original, use translate for error messages ... */ }
441function clearResults() {
442ANALYSIS_AGENTS.forEach(agent => {
443if (agent.ui_display_info) {
459noResultsMessage.style.display = 'block';
460}
461function updateLoadingProgress(percentage, statusKey, agentName = '') {
462progressBar.style.width = \`\${percentage}%\`;
463let statusText = translate(statusKey);
468}
469470// --- Result Rendering Functions (DYNAMIC based on ANALYSIS_AGENTS) ---
471function renderAgentResult(agentId, agentResultData, agentConfig) {
472const card = document.getElementById(\`card-\${agentId}\`);
473const contentEl = document.getElementById(\`content-\${agentId}\`);
637638// --- Main Request Handler (Server Code) ---
639export default async function(req: Request) {
640// --- Dynamic Imports (Unchanged) ---
641const { OpenAI } = await import("https://esm.town/v/std/openai");
649650// --- Helper: Extract Text using pdf.js-extract (Unchanged) ---
651async function extractPdfTextNative(data: ArrayBuffer, fileName: string, log: LogEntry[]): Promise<string | null> { /* ... original ... */ }
652653// --- Helper Function: Call OpenAI API (Uses APP_CONFIG for model) ---
654async function callOpenAI(
655openai: OpenAI,
656systemPrompt: string,
661/* ... original logic, but use modelFromConfig ... */
662const model = modelFromConfig;
663// ... rest of the original callOpenAI function
664try {
665const response = await openai.chat.completions.create({
678}
679680// --- Helper Function: Traverse References (Optional, could be an agent itself) ---
681// This function is specific. If reference traversal is a common need, keep it.
682// Otherwise, this logic could be part of a dedicated "Reference Traversal Agent".
683// For this template, we'll assume it's a potential fixed post-processing step for a reference agent.
684async function traverseReferences(references: Reference[], log: LogEntry[]): Promise<Reference[]> {
685const agent = "Reference Traversal Agent"; // Fixed name for this specialized step
686// ... original traverseReferences logic ...
697698// --- Main Agent Flow Logic (DYNAMIC based on ANALYSIS_AGENTS) ---
699async function runAgentFlow(
700input: { documentUrl?: string; documentText?: string; documentFile?: File },
701log: LogEntry[],
761if (extractedReferencesForTraversal && extractedReferencesForTraversal.length > 0) {
762log.push({ agent: "System", type: "step", message: "Attempting to verify reference URLs..." });
763// The traverseReferences function logs its own 'final' results for the 'Reference Traversal Agent'
764await traverseReferences(extractedReferencesForTraversal, log);
765} else {
848* Fill in `{{localization_strings_en_json}}` and `{{localization_strings_es_json}}` with all
849* UI text for English and Spanish respectively. Ensure keys match `data-translate` attributes in the HTML
850* and keys used in the JavaScript `translate()` function.
851* Card titles and table headers defined in `ui_display_info` for agents will also need corresponding
852* entries if you want them translated beyond the direct `card_title_en/es` provided (e.g. for dynamic labels within a key_value_pairs display).
862*
863* 6. Deployment:
864* This script is designed to be deployed as a single serverless function (e.g., on Val Town).
865* It serves both the HTML interface and the backend API endpoint.
866*
869* To implement agent chaining (where one agent's output is input to another), you would modify
870* `runAgentFlow` to pass `previousAgentOutput` and update agent prompts to accept/use it (e.g. `{{previous_output}}`).
871* - Advanced UI Rendering: The `renderAgentResult` function provides basic rendering for different data types.
872* For more complex visualizations or interactions, you'd expand this function or add new `display_type` handlers.
873* - Styling: The CSS is extensive. You can customize it directly or by templatizing CSS variables within the `<style>` block.
874* - Error Handling: Server-side and client-side error handling can be further enhanced.
35const app = new Hono();
3637// --- Helper Functions ---
38async function updateJobStatus(jobId: string, status: string, errorMessage?: string) {
39await sqlite.execute({
40sql: `UPDATE jobs SET status = ?, updated_at = ?, error_message = ? WHERE id = ?;`,
43}
4445async function updateLeadStatus(leadId: string, status: string, updates: Partial<Lead> = {}, errorMessage?: string) {
46let sql = `UPDATE leads SET status = ?, updated_at = ?`;
47const args: any[] = [status, new Date().toISOString()];
7778// WARNING: Scraping search engines like DuckDuckGo is fragile and might break.
79async function searchWebsites(searchQuery: string, jobId: string): Promise<{ name: string; url: string }[]> {
80const searchUrl = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(searchQuery)}`;
81console.log(`Searching: ${searchUrl}`);
124}
125126async function extractEmailsFromWebsite(websiteUrl: string, leadId: string): Promise<string | null> {
127console.log(`Scraping ${websiteUrl} for lead ${leadId}`);
128try {
189}
190191async function draftColdEmail(
192openai: OpenAI,
193businessName: string | undefined,
284}
285286async function processJob(jobId: string, searchQuery: string) {
287await updateJobStatus(jobId, "processing_search");
288const openaiApiKey = Deno.env.get("openai");