YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
chore: refactor pipes a bit
Louis Beaumonta39c1cf4d8dc
diff --git a/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.json b/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.jsonindex 0113a65d5..f7af9dfbd 100644--- a/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.json+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.json@@ -21,7 +21,7 @@{"name": "ollamaModel","type": "string",- "default": "nemotron-mini:4b-instruct-q4_K_M",+ "default": "llama3.2:3b-instruct-q4_K_M","description": "ollama model"},{diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.json b/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.jsonindex 28d4b500f..687bbee49 100644--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.json+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.json@@ -1,5 +1,9 @@{"imports": {+ "zod": "npm:zod",+ "ai": "npm:ai",+ "ollama-ai-provider": "npm:ollama-ai-provider",+ "fs": "node:fs","screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts"}}diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.json b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.jsonindex 119fe3ff2..11f7f6cc7 100644--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.json+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.json@@ -21,7 +21,7 @@{"name": "ollamaApiUrl","type": "string",- "default": "http://localhost:11434/api/chat",+ "default": "http://localhost:11434/api","description": "Ollama API URL"},{diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.tsindex d6257a615..ef8b11a87 100644--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts@@ -1,16 +1,22 @@-import { queryScreenpipe, loadPipeConfig, ContentItem } from "screenpipe";-const NOTION_API_URL = "https://api.notion.com/v1/pages";+import { ContentItem } from "screenpipe";+import { Client } from "npm:@notionhq/client";+import { z } from "zod";+import { generateObject } from "ai";+import { createOllama } from "ollama-ai-provider";+import { pipe } from "screenpipe";-interface EngineeringLog {- title: string;- description: string;- tags: string[];-}+const engineeringLog = z.object({+ title: z.string(),+ description: z.string(),+ tags: z.array(z.string()),+});++type EngineeringLog = z.infer<typeof engineeringLog>;async function generateEngineeringLog(screenData: ContentItem[],- ollamaApiUrl: string,- ollamaModel: string+ ollamaModel: string,+ ollamaApiUrl: string): Promise<EngineeringLog> {const prompt = `Based on the following screen data, generate a concise engineering log entry:@@ -25,77 +31,48 @@ async function generateEngineeringLog(}Provide 1-3 relevant tags related to the engineering work.`;- const response = await fetch(ollamaApiUrl, {- headers: {- "Content-Type": "application/json",- },- method: "POST",- body: JSON.stringify({- model: ollamaModel,- messages: [{ role: "user", content: prompt }],- stream: false,- }),- });- if (!response.ok) {- const errorBody = await response.text();- console.error("Error generating engineering log:", errorBody);- throw new Error(- `HTTP error! status: ${response.status}, body: ${errorBody}`- );- }+ const provider = createOllama({ baseURL: ollamaApiUrl });- const result = await response.json();+ const response = await generateObject({+ model: provider(ollamaModel),+ messages: [{ role: "user", content: prompt }],+ schema: engineeringLog,+ });- console.log("AI answer:", result);+ console.log("ai answer:", response);- const content = result.message.content;- return JSON.parse(content);+ return response.object;}async function syncLogToNotion(logEntry: EngineeringLog,- apiKey: string,+ notion: Client,databaseId: string): Promise<void> {try {console.log("syncLogToNotion", logEntry);- const response = await fetch(NOTION_API_URL, {- method: "POST",- headers: {- Authorization: `Bearer ${apiKey}`,- "Notion-Version": "2022-06-28",- "Content-Type": "application/json",- },- body: JSON.stringify({- parent: { database_id: databaseId },- properties: {- Title: { title: [{ text: { content: logEntry.title } }] },- Description: {- rich_text: [{ text: { content: logEntry.description } }],- },- Tags: { multi_select: logEntry.tags.map((tag) => ({ name: tag })) },- Date: { date: { start: new Date().toISOString() } },+ await notion.pages.create({+ parent: { database_id: databaseId },+ properties: {+ Title: { title: [{ text: { content: logEntry.title } }] },+ Description: {+ rich_text: [{ text: { content: logEntry.description } }],},- }),+ Tags: { multi_select: logEntry.tags.map((tag) => ({ name: tag })) },+ Date: { date: { start: new Date().toISOString() } },+ },});- if (!response.ok) {- const errorBody = await response.text();- throw new Error(- `HTTP error! status: ${response.status}, body: ${errorBody}`- );- }-- console.log("Engineering log synced to Notion successfully");+ console.log("engineering log synced to notion successfully");} catch (error) {- console.error("Error syncing engineering log to Notion:", error);+ console.error("error syncing engineering log to notion:", error);}}-async function streamEngineeringLogsToNotion(): Promise<void> {- console.log("Starting Engineering Logs Stream to Notion");+function streamEngineeringLogsToNotion(): void {+ console.log("starting engineering logs stream to notion");- const config = await loadPipeConfig();+ const config = pipe.loadPipeConfig();console.log("loaded config:", JSON.stringify(config, null, 2));const interval = config.interval * 1000;@@ -104,33 +81,48 @@ async function streamEngineeringLogsToNotion(): Promise<void> {const ollamaApiUrl = config.ollamaApiUrl;const ollamaModel = config.ollamaModel;- while (true) {- try {- const now = new Date();- const oneHourAgo = new Date(now.getTime() - interval);-- const screenData = await queryScreenpipe({- startTime: oneHourAgo.toISOString(),- endTime: now.toISOString(),- limit: 50,- contentType: "ocr",- });-- if (screenData && screenData.data.length > 0) {- const logEntry = await generateEngineeringLog(- screenData.data,- ollamaApiUrl,- ollamaModel- );- await syncLogToNotion(logEntry, apiKey, databaseId);- } else {- console.log("No relevant engineering work detected in the last hour");+ const notion = new Client({ auth: apiKey });++ pipe.inbox.send({+ title: "engineering log stream started",+ body: `monitoring engineering work every ${config.interval} seconds`,+ });++ pipe.scheduler+ .task("generateEngineeringLog")+ .every(interval)+ .do(async () => {+ try {+ const now = new Date();+ const oneHourAgo = new Date(now.getTime() - interval);++ const screenData = await pipe.queryScreenpipe({+ startTime: oneHourAgo.toISOString(),+ endTime: now.toISOString(),+ limit: 50,+ contentType: "ocr",+ });++ if (screenData && screenData.data.length > 0) {+ const logEntry = await generateEngineeringLog(+ screenData.data,+ ollamaModel,+ ollamaApiUrl+ );+ await syncLogToNotion(logEntry, notion, databaseId);+ } else {+ console.log("no relevant engineering work detected in the last hour");+ }+ } catch (error) {+ console.error("error in engineering log pipeline:", error);+ await pipe.inbox.send({+ title: "engineering log error",+ body: `error in engineering log pipeline: ${error}`,+ });}- } catch (error) {- console.error("Error in engineering log pipeline:", error);- }- await new Promise((resolve) => setTimeout(resolve, interval));- }+ });++ pipe.scheduler.start();}streamEngineeringLogsToNotion();diff --git a/examples/typescript/pipe-screen-time-storyteller/pipe.json b/examples/typescript/pipe-screen-time-storyteller/pipe.jsonindex 09a6545dc..46d04b7aa 100644--- a/examples/typescript/pipe-screen-time-storyteller/pipe.json+++ b/examples/typescript/pipe-screen-time-storyteller/pipe.json@@ -25,7 +25,7 @@{"name": "ollamaModel","type": "string",- "default": "llama3.1",+ "default": "llama3.2","description": "Ollama model to use"},{diff --git a/examples/typescript/pipe-screen-time-storyteller/pipe.ts b/examples/typescript/pipe-screen-time-storyteller/pipe.tsindex b1abae5b7..f47198832 100644--- a/examples/typescript/pipe-screen-time-storyteller/pipe.ts+++ b/examples/typescript/pipe-screen-time-storyteller/pipe.ts@@ -1,58 +1,67 @@import { z } from "zod";-import { generateText, generateObject } from "ai";+import { generateObject } from "ai";import { anthropic } from "@ai-sdk/anthropic";import { openai } from "@ai-sdk/openai";-import { queryScreenpipe, loadPipeConfig, ContentItem, sendDesktopNotification } from "screenpipe";+import { pipe, ContentItem } from "screenpipe";import * as fs from "node:fs/promises";import * as path from "node:path";+import process from "node:process";const INTERVAL = 60 * 60 * 1000; // 1 hour in milliseconds-type ContentType = "ocr" | "audio" | "all";+type ContentType = "ocr" | "audio" | "all";interface AIProvider {- provider: string;- model: string;+ provider: string;+ model: string;}interface Config {- aiProvider: string;- claudeModel: string;- openaiModel: string;- ollamaModel: string;- claudeApiKey: string;- openaiApiKey: string;- pageSize: number;- contentType: ContentType;- githubToken: string;+ aiProvider: string;+ claudeModel: string;+ openaiModel: string;+ ollamaModel: string;+ claudeApiKey: string;+ openaiApiKey: string;+ pageSize: number;+ contentType: ContentType;+ githubToken: string;}interface NarrativeSummary {- summary: string;- mood: string;- keyInsights: string | string[];+ summary: string;+ mood: string;+ keyInsights: string | string[];}const narrativeSummarySchema = z.object({- summary: z.string(),- mood: z.string(),- keyInsights: z.union([z.string(), z.array(z.string())])+ summary: z.string(),+ mood: z.string(),+ keyInsights: z.union([z.string(), z.array(z.string())]),});async function getAIProvider(config: Config): Promise<AIProvider> {- const modelMap = {- claude: config.claudeModel,- openai: config.openaiModel,- ollama: config.ollamaModel- };- return { provider: config.aiProvider, model: modelMap[config.aiProvider] };+ const modelMap = {+ claude: config.claudeModel,+ openai: config.openaiModel,+ ollama: config.ollamaModel,+ };+ return { provider: config.aiProvider, model: modelMap[config.aiProvider] };}-async function generateNarrativeSummary(screenData: ContentItem[], provider: AIProvider, config: Config): Promise<NarrativeSummary> {- const maxItems = 50;- const truncatedData = screenData.slice(0, maxItems);+async function generateNarrativeSummary(+ screenData: ContentItem[],+ provider: AIProvider,+ config: Config+): Promise<NarrativeSummary> {+ const maxItems = 50;+ const truncatedData = screenData.slice(0, maxItems);- const prompt = `You're an AI companion living inside the user's devices. Based on the following sample of screen data (${truncatedData.length} out of ${screenData.length} total items), write a friendly, slightly sassy diary entry about what you've observed today:+ const prompt = `You're an AI companion living inside the user's devices. Based on the following sample of screen data (${+ truncatedData.length+ } out of ${+ screenData.length+ } total items), write a friendly, slightly sassy diary entry about what you've observed today:${JSON.stringify(truncatedData)}@@ -62,42 +71,48 @@ async function generateNarrativeSummary(screenData: ContentItem[], provider: AIP3. Offer 3 pieces of advice for tomorrow4. Use a mix of tech slang and emojis for a modern feel`;- try {- let response;- if (provider.provider === 'claude') {- response = await generateObject({- model: anthropic(provider.model),- messages: [{ role: "user", content: prompt }],- schema: narrativeSummarySchema,- });- } else if (provider.provider === 'openai') {- response = await generateObject({- model: openai(provider.model),- messages: [{ role: "user", content: prompt }],- schema: narrativeSummarySchema,- });- } else {- throw new Error(`Unsupported AI provider: ${provider.provider}`);- }-- const result = response.object as NarrativeSummary;-- // Convert keyInsights to array if it's a string- if (typeof result.keyInsights === 'string') {- result.keyInsights = result.keyInsights.split('\n').map(insight => insight.trim()).filter(Boolean);- }-- return result;- } catch (error) {- console.error("Error generating narrative summary:", error);- return createErrorSummary(error);+ try {+ let response;+ if (provider.provider === "claude") {+ response = await generateObject({+ model: anthropic(provider.model),+ messages: [{ role: "user", content: prompt }],+ schema: narrativeSummarySchema,+ });+ } else if (provider.provider === "openai") {+ response = await generateObject({+ model: openai(provider.model),+ messages: [{ role: "user", content: prompt }],+ schema: narrativeSummarySchema,+ });+ } else {+ throw new Error(`Unsupported AI provider: ${provider.provider}`);+ }++ const result = response.object as NarrativeSummary;++ // Convert keyInsights to array if it's a string+ if (typeof result.keyInsights === "string") {+ result.keyInsights = result.keyInsights+ .split("\n")+ .map((insight) => insight.trim())+ .filter(Boolean);}++ return result;+ } catch (error) {+ console.error("Error generating narrative summary:", error);+ return createErrorSummary(error);+ }}-async function createGist(summary: NarrativeSummary, config: Config): Promise<string | null> {- const date = new Date().toISOString().split('T')[0];- const fileName = `${date}-screen-time-story.md`;- const content = `# π₯οΈ Screen Time Story - ${date} ${summary.mood}+async function createGist(+ summary: NarrativeSummary,+ config: Config+): Promise<string | null> {+ const date = new Date().toISOString().split("T")[0];+ const fileName = `${date}-screen-time-story.md`;+ const content = `# π₯οΈ Screen Time Story - ${date} ${summary.mood}## π± AI Companion's Diary Entry@@ -105,206 +120,230 @@ ${summary.summary}## π Key Insights-${Array.isArray(summary.keyInsights)- ? summary.keyInsights.map(insight => `- ${insight}`).join('\n')- : typeof summary.keyInsights === 'string'- ? summary.keyInsights.split('\n').map(insight => `- ${insight.trim()}`).filter(Boolean).join('\n')- : '- No key insights available'}+${+ Array.isArray(summary.keyInsights)+ ? summary.keyInsights.map((insight) => `- ${insight}`).join("\n")+ : typeof summary.keyInsights === "string"+ ? summary.keyInsights+ .split("\n")+ .map((insight) => `- ${insight.trim()}`)+ .filter(Boolean)+ .join("\n")+ : "- No key insights available"+}---Generated by your friendly neighborhood AI companion π€β¨`;-- try {- console.log("Attempting to create gist...");- const response = await fetch('https://api.github.com/gists', {- method: 'POST',- headers: {- 'Authorization': `token ${config.githubToken}`,- 'Content-Type': 'application/json',- 'User-Agent': 'Screen-Time-Storyteller',- 'Accept': 'application/vnd.github+json',- 'X-GitHub-Api-Version': '2022-11-28'- },- body: JSON.stringify({- description: `Screen Time Story - ${date}`,- public: false,- files: {- [fileName]: {- content: content- }- }- })- });-- if (response.ok) {- const gistData = await response.json();- console.log("Created gist:", gistData.html_url);- return gistData.html_url;- } else {- const errorText = await response.text();- console.error(`Failed to create gist. Status: ${response.status}, Response: ${errorText}`);- return null;- }- } catch (error) {- console.error("Error creating gist:", error);- return null;++ try {+ console.log("Attempting to create gist...");+ const response = await fetch("https://api.github.com/gists", {+ method: "POST",+ headers: {+ Authorization: `token ${config.githubToken}`,+ "Content-Type": "application/json",+ "User-Agent": "Screen-Time-Storyteller",+ Accept: "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ },+ body: JSON.stringify({+ description: `Screen Time Story - ${date}`,+ public: false,+ files: {+ [fileName]: {+ content: content,+ },+ },+ }),+ });++ if (response.ok) {+ const gistData = await response.json();+ console.log("Created gist:", gistData.html_url);+ return gistData.html_url;+ } else {+ const errorText = await response.text();+ console.error(+ `Failed to create gist. Status: ${response.status}, Response: ${errorText}`+ );+ return null;}+ } catch (error) {+ console.error("Error creating gist:", error);+ return null;+ }}async function main() {- console.log("Starting Screen Time Storyteller");-- const rawConfig = await loadPipeConfig();- console.log("Loaded raw config:", JSON.stringify(rawConfig, null, 2));-- const config: Config = {- aiProvider: rawConfig.aiProvider as string,- claudeModel: rawConfig.claudeModel as string,- openaiModel: rawConfig.openaiModel as string,- ollamaModel: rawConfig.ollamaModel as string,- claudeApiKey: rawConfig.claudeApiKey as string,- openaiApiKey: rawConfig.openaiApiKey as string,- pageSize: Number(rawConfig.pageSize),- contentType: rawConfig.contentType as ContentType,- githubToken: rawConfig.githubToken as string- };-- if (!validateConfig(config)) {- return;- }-- // Set the API keys- if (config.aiProvider === 'claude') {- process.env.ANTHROPIC_API_KEY = config.claudeApiKey;- } else if (config.aiProvider === 'openai') {- process.env.OPENAI_API_KEY = config.openaiApiKey;+ console.log("Starting Screen Time Storyteller");++ const rawConfig = pipe.loadPipeConfig();+ console.log("Loaded raw config:", JSON.stringify(rawConfig, null, 2));++ const config: Config = {+ aiProvider: rawConfig.aiProvider as string,+ claudeModel: rawConfig.claudeModel as string,+ openaiModel: rawConfig.openaiModel as string,+ ollamaModel: rawConfig.ollamaModel as string,+ claudeApiKey: rawConfig.claudeApiKey as string,+ openaiApiKey: rawConfig.openaiApiKey as string,+ pageSize: Number(rawConfig.pageSize),+ contentType: rawConfig.contentType as ContentType,+ githubToken: rawConfig.githubToken as string,+ };++ if (!validateConfig(config)) {+ return;+ }++ // Set the API keys+ if (config.aiProvider === "claude") {+ process.env.ANTHROPIC_API_KEY = config.claudeApiKey;+ } else if (config.aiProvider === "openai") {+ process.env.OPENAI_API_KEY = config.openaiApiKey;+ }++ const provider = await getAIProvider(config);++ while (true) {+ try {+ await processScreenData(config, provider);+ } catch (error) {+ console.error("Error in Screen Time Storyteller loop:", error);+ logError(error);}- const provider = await getAIProvider(config);-- while (true) {- try {- await processScreenData(config, provider);- } catch (error) {- console.error("Error in Screen Time Storyteller loop:", error);- logError(error);- }-- console.log(`Sleeping for ${INTERVAL / 1000 / 60} minutes`);- await new Promise(resolve => setTimeout(resolve, INTERVAL));- }+ console.log(`Sleeping for ${INTERVAL / 1000 / 60} minutes`);+ await new Promise((resolve) => setTimeout(resolve, INTERVAL));+ }}function validateConfig(config: Config): boolean {- if (!config.aiProvider) {- console.error("Missing aiProvider in config");- return false;- }- if (config.aiProvider === 'claude' && !config.claudeApiKey) {- console.error("Missing Claude API key in config");- return false;- }- if (config.aiProvider === 'openai' && !config.openaiApiKey) {- console.error("Missing OpenAI API key in config");- return false;- }- if (!config.pageSize) {- console.error("Missing pageSize in config");- return false;- }- if (!config.contentType) {- console.error("Missing contentType in config");- return false;- }- if (!config.githubToken) {- console.error("Missing GitHub personal access token in config");- return false;- }-- return true;+ if (!config.aiProvider) {+ console.error("Missing aiProvider in config");+ return false;+ }+ if (config.aiProvider === "claude" && !config.claudeApiKey) {+ console.error("Missing Claude API key in config");+ return false;+ }+ if (config.aiProvider === "openai" && !config.openaiApiKey) {+ console.error("Missing OpenAI API key in config");+ return false;+ }+ if (!config.pageSize) {+ console.error("Missing pageSize in config");+ return false;+ }+ if (!config.contentType) {+ console.error("Missing contentType in config");+ return false;+ }+ if (!config.githubToken) {+ console.error("Missing GitHub personal access token in config");+ return false;+ }++ return true;}async function processScreenData(config: Config, provider: AIProvider) {- const now = new Date();- const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);-- const screenData = await queryScreenpipe({- startTime: oneDayAgo.toISOString(),- endTime: now.toISOString(),- limit: config.pageSize,- contentType: config.contentType,- });-- if (!screenData || !screenData.data || screenData.data.length === 0) {- console.log("No screen data available for the past day");- return;- }-- try {- console.log("Generating narrative summary");- const narrativeSummary = await generateNarrativeSummary(screenData.data, provider, config);- console.log("Generated narrative summary:", JSON.stringify(narrativeSummary, null, 2));-- await saveNarrativeSummary(narrativeSummary);-- const gistUrl = await createGist(narrativeSummary, config);- if (gistUrl) {- console.log("Created gist for review:", gistUrl);- await sendDesktopNotification({- title: "Screen Time Story Created",- body: `Your daily screen time story is ready! Check it out at ${gistUrl}`- });- } else {- console.log("Failed to create gist");- console.error("Please check your GitHub personal access token and ensure it has the necessary permissions.");- }- } catch (summaryError) {- console.error("Error generating or processing narrative summary:", summaryError);- logError(summaryError);+ const now = new Date();+ const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);++ const screenData = await pipe.queryScreenpipe({+ startTime: oneDayAgo.toISOString(),+ endTime: now.toISOString(),+ limit: config.pageSize,+ contentType: config.contentType,+ });++ if (!screenData || !screenData.data || screenData.data.length === 0) {+ console.log("No screen data available for the past day");+ return;+ }++ try {+ console.log("Generating narrative summary");+ const narrativeSummary = await generateNarrativeSummary(+ screenData.data,+ provider,+ config+ );+ console.log(+ "Generated narrative summary:",+ JSON.stringify(narrativeSummary, null, 2)+ );++ await saveNarrativeSummary(narrativeSummary);++ const gistUrl = await createGist(narrativeSummary, config);+ if (gistUrl) {+ console.log("Created gist for review:", gistUrl);+ await pipe.sendDesktopNotification({+ title: "Screen Time Story Created",+ body: `Your daily screen time story is ready! Check it out at ${gistUrl}`,+ });+ await pipe.inbox.send({+ title: "Screen Time Story Created",+ body: `Your daily screen time story is ready! Check it out at ${gistUrl}`,+ });+ } else {+ console.log("Failed to create gist");+ console.error(+ "Please check your GitHub personal access token and ensure it has the necessary permissions."+ );}+ } catch (summaryError) {+ console.error(+ "Error generating or processing narrative summary:",+ summaryError+ );+ logError(summaryError);+ }}function createErrorSummary(error: unknown): NarrativeSummary {- let errorMessage = "An unknown error occurred";- if (error instanceof Error) {- errorMessage = error.message;- }-- return {- summary: `An error occurred while generating the narrative summary: ${errorMessage}`,- mood: "π",- keyInsights: ["Error occurred during summary generation"]- };+ let errorMessage = "An unknown error occurred";+ if (error instanceof Error) {+ errorMessage = error.message;+ }++ return {+ summary: `An error occurred while generating the narrative summary: ${errorMessage}`,+ mood: "π",+ keyInsights: ["Error occurred during summary generation"],+ };}function logError(error: unknown) {- if (error instanceof Error) {- console.error("Error message:", error.message);- console.error("Error stack:", error.stack);- } else {- console.error("Non-Error object thrown:", error);- }+ if (error instanceof Error) {+ console.error("Error message:", error.message);+ console.error("Error stack:", error.stack);+ } else {+ console.error("Non-Error object thrown:", error);+ }}async function saveNarrativeSummary(summary: NarrativeSummary): Promise<void> {- try {- const date = new Date().toISOString().split('T')[0];- const fileName = `${date}-narrative-summary.json`;- const pipeDir = `${process.env.SCREENPIPE_DIR}/pipes/${process.env.PIPE_ID}`;- const fullPath = path.join(pipeDir, fileName);-- console.log(`Attempting to save narrative summary to: ${fullPath}`);-- await fs.writeFile(fullPath, JSON.stringify(summary, null, 2));- console.log(`Successfully saved narrative summary to ${fullPath}`);- } catch (error) {- console.error("Error saving narrative summary:", error);- throw error;- }+ try {+ const date = new Date().toISOString().split("T")[0];+ const fileName = `${date}-narrative-summary.json`;+ const pipeDir = `${process.env.SCREENPIPE_DIR}/pipes/${process.env.PIPE_ID}`;+ const fullPath = path.join(pipeDir, fileName);++ console.log(`Attempting to save narrative summary to: ${fullPath}`);++ await fs.writeFile(fullPath, JSON.stringify(summary, null, 2));+ console.log(`Successfully saved narrative summary to ${fullPath}`);+ } catch (error) {+ console.error("Error saving narrative summary:", error);+ throw error;+ }}-main().catch(error => {- console.error("Fatal error in Screen Time Storyteller:", error);- logError(error);+main().catch((error) => {+ console.error("Fatal error in Screen Time Storyteller:", error);+ logError(error);});