smsberthandleSmsMessage.ts5 matches
30* Store a chat message in the database
31*/
32export async function storeChatMessage(
33chatId,
34senderId,
63* Retrieve chat history for a specific chat
64*/
65export async function getChatHistory(chatId, limit = 50) {
66try {
67const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
88* Format chat history for Anthropic API
89*/
90function formatChatHistoryForAI(history) {
91const messages = [];
92112* Analyze a Telegram message and extract memories from it
113*/
114async function analyzeMessageContent(
115anthropic,
116username,
498499// Handle webhook requests
500export default async function(req: Request): Promise<Response> {
501// Set webhook if it is not set yet
502if (req.method === "POST") {
67Synthesize these inputs into a clear summary. Briefly recap the key points from each hat used. Conclude with a statement about the overall thinking process or potential next steps based on the analysis. Start directly with the synthesis. Avoid using backticks (\`).`;
6869// --- HTML Generation Function (Adapted for ThinkingFlow) ---
70function generateHtmlShell(initialQuery, initialSequence, sourceUrl) {
71const escapedQuery = initialQuery.replace(/"/g, """);
72const escapedSequence = initialSequence.replace(/"/g, """);
178const submitButtonText = submitButton.querySelector('span');
179180// Function to safely escape HTML
181function escapeHTML(str) {
182const p = document.createElement('p');
183p.textContent = str;
186187// Render conversation log
188function renderConversation(log) {
189if (!log || log.length === 0) {
190conversationDiv.innerHTML = '<p style="text-align:center; color: #546e7a;">No thinking process data received.</p>';
236237// Show client errors
238function showClientError(message) {
239errorContainer.innerHTML = ''; // Clear previous errors
240const errorDiv = document.createElement('div');
333334// --- Main Request Handler (Server Code for ThinkingFlow MVP) ---
335export default async function(req: Request) {
336// Dynamic Import of OpenAI Library
337const { OpenAI } = await import("https://esm.town/v/std/openai");
338339// --- OpenAI API Call Helper (Reused) ---
340async function callOpenAI(
341systemPrompt: string,
342userMessage: string, // Can be query or intermediate context
377378// --- Helper: Map Hat Code to Prompt and Name ---
379function getHatDetails(hatCode: string): { name: string; prompt: string } {
380switch (hatCode.toUpperCase()) {
381case "W":
397398// --- Helper: Run the ThinkingFlow Workflow ---
399async function runThinkingFlow(
400userQuery: string,
401sequenceString: string,
2223// deno-lint-ignore no-unused-vars
24export default async function (interval: Interval) {
25try {
26const getEtagResponse = await getEtag();
102Combine the key points from the agent responses into a unified message. Start with a brief acknowledgement of the user's query. Then, integrate the advice logically. Ensure the final output flows well and directly addresses the user's core need. Avoid repetition. If any agent failed or provided an error, briefly mention that that aspect couldn't be addressed fully. End with an encouraging closing statement. Keep the overall tone holistic and supportive. Avoid using backticks (\`) in your response.`;
103104// --- HTML Generation Function (Generates the initial page structure and client-side JS) ---
105// Includes updates for LifeSync agents and styling
106function generateHtmlShell(initialQuery, sourceUrl) {
107const escapedQuery = initialQuery.replace(/"/g, """);
108const currentDate = new Date().toLocaleDateString(); // Get current date
201const submitButtonText = submitButton.querySelector('span');
202203function renderConversation(log) {
204if (!log || log.length === 0) {
205conversationDiv.innerHTML = '<p style="text-align:center; color: #6c757d;">No conversation data received.</p>';
246}
247248function showClientError(message) {
249errorContainer.innerHTML = ''; // Clear previous errors
250const errorDiv = document.createElement('div');
321// --- Main Request Handler (Server Code) ---
322// Includes LifeSync agent flow
323export default async function(req: Request) {
324const { OpenAI } = await import("https://esm.town/v/std/openai");
325326// --- Helper Function: Call OpenAI API ---
327// (Mostly unchanged, but updated the JSON mode check)
328async function callOpenAI(
329systemPrompt: string,
330userMessage: string,
390}
391392// --- Helper Function: Map Domain to Agent Details ---
393function getAgentDetails(domain: string): { name: string; prompt: string; icon: string } {
394switch (domain.toUpperCase()) {
395case "VISIONARY":
416}
417418// --- Helper Function: Run the LifeSync Multi-Agent Workflow ---
419async function runAgentFlow(userQuery: string): Promise<Array<{ agent: string; message: string }>> {
420const conversationLog: Array<{ agent: string; message: string }> = [];
421
stevensDemotestDailyBrief.ts1 match
4import { DateTime } from "https://esm.sh/luxon@3.4.4";
56export async function testDailyBrief() {
7try {
8const testChatId = Deno.env.get("TEST_TELEGRAM_CHAT_ID");
2// Run this script manually to create the database table
34export default async function setupTelegramChatDb() {
5try {
6// Import SQLite module
stevensDemosendDailyBrief.ts6 matches
13} from "../memoryUtils.ts";
1415async function generateBriefingContent(anthropic, memories, today, isSunday) {
16try {
17const weekdaysHelp = generateWeekDays(today);
96}
9798export async function sendDailyBriefing(chatId?: string, today?: DateTime) {
99// Get API keys from environment
100const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
135const lastSunday = today.startOf("week").minus({ days: 1 });
136137// Fetch relevant memories using the utility function
138const memories = await getRelevantMemories();
139216}
217218function generateWeekDays(today) {
219let output = [];
220239// console.log(weekDays);
240241// Export a function that calls sendDailyBriefing with no parameters
242// This maintains backward compatibility with existing cron jobs
243export default async function (overrideToday?: DateTime) {
244return await sendDailyBriefing(undefined, overrideToday);
245}
stevensDemoREADME.md2 matches
16In a normal server environment, you would likely use a middleware [like this one](https://hono.dev/docs/getting-started/nodejs#serve-static-files) to serve static files. Some frameworks or deployment platforms automatically make any content inside a `public/` folder public.
1718However in Val Town you need to handle this yourself, and it can be suprisingly difficult to read and serve files in a Val Town Project. This template uses helper functions from [stevekrouse/utils/serve-public](https://www.val.town/x/stevekrouse/utils/branch/main/code/serve-public/README.md), which handle reading project files in a way that will work across branches and forks, automatically transpiles typescript to javascript, and assigns content-types based on the file's extension.
1920### `index.html`
26## CRUD API Routes
2728This app has two CRUD API routes: for reading and inserting into the messages table. They both speak JSON, which is standard. They import their functions from `/backend/database/queries.ts`. These routes are called from the React app to refresh and update data.
2930## Errors
stevensDemoREADME.md2 matches
45* `migrations.ts` - code to set up the database tables the app needs
6* `queries.ts` - functions to run queries against those tables, which are imported and used in the main Hono server in `/backend/index.ts`
78## Migrations
18The queries file is where running the migrations happen in this app. It'd also be reasonable for that to happen in index.ts, or as is said above, for that line to be commented out, and only run when actual changes are made to your database schema.
1920The queries file exports functions to get and write data. It relies on shared types and data imported from the `/shared` directory.
stevensDemoqueries.ts4 matches
6const tableName = "memories_demo";
78export async function getAllMemories(): Promise<Memory[]> {
9const result = await sqlite.execute(
10`SELECT id, date, text, createdBy, createdDate, tags FROM ${tableName}
23}
2425export async function createMemory(
26memory: Omit<Memory, "id">
27): Promise<Memory> {
51}
5253export async function updateMemory(
54id: string,
55memory: Partial<Omit<Memory, "id">>
70}
7172export async function deleteMemory(id: string): Promise<void> {
73await sqlite.execute(`DELETE FROM ${tableName} WHERE id = ?`, [id]);
74}