Skip to content

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

test deno thru cli (#462)

Louis Beaumontd211cd7a5c21
diff --git a/examples/typescript/pipe-activity-topic-tracker/README.md b/examples/typescript/pipe-activity-topic-tracker/README.md
deleted file mode 100644
index 767bd93b3..000000000
--- a/examples/typescript/pipe-activity-topic-tracker/README.md
+++ /dev/null
@@ -1,45 +0,0 @@
-![Screenpipe Pipe Store json](https://github.com/user-attachments/assets/6c074beb-5b0f-4829-8a07-52805a78e80c)
-
-in screenpipe we have a plugin system called "pipe store" or "pipes"
-
-think of it like this:
-
-screenpipe data -> your pipe like "AI annotate" or "send to salesforce"
-
-a more dev-friendly explanation:
-
-screenpipe | AI tag | notion update
-
-or
-
-screenpipe | AI tag | slack send report
-
-or
-
-screenpipe | fill salesforce
-
-or
-
-screenpipe | logs daily
-
-basically it would read, process, annotate, analyse, summarize, send, your data customisable to your desire, effortlessly
-
-### pipe-activity-topic-tracker
-
-this is an experimental, but official pipe, that will use ollama + phi3.5 to track your activities and generate summaries every 1 min
-
-soon we'll make it easier to search through these summaries but in the meantime you can use it to enrich your data
-
-and AI will be able to provide you more relevant answers about your activities
-
-this is how you run it through the app:
-
-```bash
-ollama run phi3.5
-```
-
-add the url of this pipe in the input and click "add" and install
-
-`https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-activity-topic-tracker`
-
-wait a few minutes then look at the json file
diff --git a/examples/typescript/pipe-activity-topic-tracker/pipe.js b/examples/typescript/pipe-activity-topic-tracker/pipe.js
deleted file mode 100644
index 9311b202c..000000000
--- a/examples/typescript/pipe-activity-topic-tracker/pipe.js
+++ /dev/null
@@ -1,151 +0,0 @@
-const INTERVAL = 1 * 60 * 1000; // 1 minutes in milliseconds
-
-async function queryScreenpipe(params) {
- try {
- console.log("params", params);
- const queryParams = Object.entries({
- q: params.q,
- offset: params.offset,
- limit: params.limit,
- start_time: params.start_time,
- end_time: params.end_time,
- content_type: params.content_type,
- app_name: params.app_name,
- })
- .filter(([_, v]) => v != null)
- .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
- .join('&');
- console.log("calling screenpipe", JSON.stringify(params));
- const result = await pipe.get(`http://localhost:3030/search?${queryParams}`);
- console.log("got", result.data.length, "items from screenpipe");
-
- return result;
- } catch (error) {
- console.error("Error querying screenpipe:", error);
- return null;
- }
-}
-
-async function getAIProvider() {
- // Default to OpenAI if no provider is specified
- const provider = "ollama";
- const model = "phi3.5";
-
- return { provider, model };
-}
-
-async function generateActivityData(provider) {
- const now = new Date();
- const fiveMinutesAgo = new Date(now.getTime() - INTERVAL);
-
- const screenData = await queryScreenpipe({
- start_time: fiveMinutesAgo.toISOString(),
- end_time: now.toISOString(),
- limit: 50,
- content_type: "ocr",
- });
-
- const prompt = `Based on the following screen and audio data, generate an activity summary for the last minutes:
-
- ${JSON.stringify(screenData)}
-
- You should return a JSON object with the following fields:
- - topics: an array of topics
- - tags: an array of tags
- - summary: a concise summary of the activity
- - timestamp: the timestamp of the activity
- - sources: an array of absolute file paths to mp4 videos in the user's screenpipe data directory
-
- Examples:
- - { "topics": ["meeting", "project", "discussion"], "tags": ["work", "team", "important"], "summary": "Discussed project requirements and assigned tasks.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-50-00.mp4", "/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-55-00.mp4"] }
- - { "topics": ["game", "strategy", "multiplayer"], "tags": ["gaming", "online", "competitive"], "summary": "Played a multiplayer strategy game with friends.", "timestamp": "2024-08-18T06:13:55Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_06-10-00.mp4"] }
- - { "topics": ["sales", "meeting", "presentation"], "tags": ["work", "team", "important"], "summary": "Presented the new product to the sales team.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-45-00.mp4"] }
- - { "topics": ["programming", "code", "debugging"], "tags": ["work", "team", "important"], "summary": "Debugged a bug in the codebase.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-30-00.mp4", "/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-40-00.mp4", "/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-50-00.mp4"] }
- - { "topics": ["writing", "blog", "content"], "tags": ["work", "team", "important"], "summary": "Wrote a blog post about the new product.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-30-00.mp4"] }
- - { "topics": ["content creation", "social media", "marketing"], "tags": ["work", "team", "important"], "summary": "Created a social media post about the new product.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-40-00.mp4", "/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-50-00.mp4"] }
-
- Provide a concise summary, relevant topics, tags, and sources (absolute file paths to mp4 videos in /Users/louisbeaumont/.screenpipe/data/). The sources array may contain one or more file paths.`;
-
- const result = await pipe.post(
- provider.provider === "openai"
- ? "https://api.openai.com/v1/chat/completions"
- : "http://localhost:11434/api/chat",
- JSON.stringify({
- model: provider.model,
- messages: [{ role: "user", content: prompt }],
- ...(provider.provider === "openai" && {
- response_format: { type: "json_object" },
- }),
- stream: false,
- }),
- );
-
- console.log("AI answer:", result);
-
- const content =
- provider.provider === "openai"
- ? result.choices[0].message.content
- : result.message.content;
- return JSON.parse(content);
-}
-
-// Global variable to store our activities in memory
-let activityLog = [];
-
-async function mergeAndSaveActivity(fileName, activity) {
- let existingLog = [];
- try {
- const fileContent = await pipe.readFile(fileName);
- existingLog = JSON.parse(fileContent);
- } catch (error) {
- console.error("Error reading existing log, starting fresh:", error);
- }
-
- // Add the new activity to the existing log
- existingLog.push(activity);
-
- console.log("will write", JSON.stringify(existingLog, null, 2));
-
- // Write the updated log back to the file
- await pipe.writeFile(fileName, JSON.stringify(existingLog, null, 2));
-
- // Update the in-memory activityLog
- activityLog = existingLog;
-
- // Log the current state of our activity log
- console.log("Updated activity log:", JSON.stringify(activityLog, null, 2));
-}
-
-async function runActivityTracker() {
- const provider = await getAIProvider();
-
- console.log("Starting Activity Topic Tracker with provider:", provider);
-
- const fileName = `activity-log-${new Date().toLocaleString("en-US", { dateStyle: "short", timeStyle: "short" }).replace(/[/:]/g, "-")}.json`;
- while (true) {
- try {
- const activity = await generateActivityData(provider);
- await mergeAndSaveActivity(fileName, activity);
- console.log("Activity logged:", activity);
- } catch (error) {
- console.error("Error logging activity:", error);
- }
- await new Promise((resolve) => setTimeout(resolve, INTERVAL));
- }
-}
-
-// Self-invoking async function to run the activity tracker
-(async () => {
- try {
- await runActivityTracker();
- } catch (error) {
- console.error("Fatal error in Activity Topic Tracker:");
- if (error instanceof Error) {
- console.error("Error name:", error.name);
- console.error("Error message:", error.message);
- console.error("Error stack:", error.stack);
- } else {
- console.error("Unexpected error:", error);
- }
- }
-})();
diff --git a/examples/typescript/pipe-email-daily-log/deno.json b/examples/typescript/pipe-email-daily-log/deno.json
new file mode 100644
index 000000000..3f17849cf
--- /dev/null
+++ b/examples/typescript/pipe-email-daily-log/deno.json
@@ -0,0 +1,10 @@
+{
+ "imports": {
+ "zod": "npm:zod",
+ "ai": "npm:ai",
+ "ollama-ai-provider": "npm:ollama-ai-provider",
+ "fs": "node:fs",
+ "nodemailer": "npm:nodemailer",
+ "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/deno-thru-cli/screenpipe-js/main.ts"
+ }
+}
\ No newline at end of file
diff --git a/examples/typescript/pipe-email-daily-log/pipe.json b/examples/typescript/pipe-email-daily-log/pipe.json
index 5e6308944..a566fe72a 100644
--- a/examples/typescript/pipe-email-daily-log/pipe.json
+++ b/examples/typescript/pipe-email-daily-log/pipe.json
@@ -33,7 +33,7 @@
{
"name": "ollamaApiUrl",
"type": "string",
- "default": "http://localhost:11434/api/chat",
+ "default": "http://localhost:11434/api",
"description": "AI API URL, can be ollama, openai, any openai compatible API, risky to use cloud providers due to high usage"
},
{
diff --git a/examples/typescript/pipe-email-daily-log/pipe.ts b/examples/typescript/pipe-email-daily-log/pipe.ts
index 3cca6fc2a..dfdc8f52c 100644
--- a/examples/typescript/pipe-email-daily-log/pipe.ts
+++ b/examples/typescript/pipe-email-daily-log/pipe.ts
@@ -1,3 +1,11 @@
+import * as fs from "fs";
+import nodemailer from "nodemailer";
+import { queryScreenpipe, loadPipeConfig, ContentItem } from "screenpipe";
+import process from "node:process";
+import { z } from "zod";
+import { generateObject, generateText } from "ai";
+import { createOllama } from "ollama-ai-provider";
+
interface DailyLog {
activity: string;
category: string;
@@ -5,6 +13,12 @@ interface DailyLog {
timestamp: string;
}
+const dailyLog = z.object({
+ activity: z.string(),
+ category: z.string(),
+ tags: z.array(z.string()),
+});
+
async function generateDailyLog(
screenData: ContentItem[],
customPrompt: string,
@@ -31,48 +45,23 @@ async function generateDailyLog(
`;
- const response = await fetch(ollamaApiUrl + "/chat", {
- headers: {
- "Content-Type": "application/json",
- },
- method: "POST",
- body: JSON.stringify({
- model: ollamaModel,
- messages: [{ role: "user", content: prompt }],
- stream: false,
- response_format: { type: "json_object" },
- }),
- });
-
- if (!response.ok) {
- console.log("ollama response:", await response.text());
- throw new Error(`http error! status: ${response.status}`);
- }
+ const provider = createOllama({ baseURL: ollamaApiUrl });
- const result = await response.json();
+ const response = await generateObject({
+ model: provider(ollamaModel),
+ messages: [{ role: "user", content: prompt }],
+ schema: dailyLog,
+ });
- console.log("ai answer:", result);
- // clean up the result
- const cleanedResult = result.message.content
- .trim()
- .replace(/^```(?:json)?\s*|\s*```$/g, "") // remove start and end code block markers
- .replace(/\n/g, "") // remove newlines
- .replace(/\\n/g, "") // remove escaped newlines
- .trim(); // trim any remaining whitespace
+ console.log("ai answer:", response);
- let content;
- try {
- content = JSON.parse(cleanedResult);
- } catch (error) {
- console.warn("failed to parse ai response:", error);
- console.warn("cleaned result:", cleanedResult);
- throw new Error("invalid ai response format");
- }
+ const result = response.object as DailyLog;
+ result.timestamp = new Date().toISOString();
- return content;
+ return result;
}
-async function saveDailyLog(logEntry: DailyLog): Promise<void> {
+function saveDailyLog(logEntry: DailyLog): void {
console.log("creating logs dir");
const logsDir = `${process.env.PIPE_DIR}/logs`;
console.log("logs dir:", logsDir);
@@ -84,10 +73,7 @@ async function saveDailyLog(logEntry: DailyLog): Promise<void> {
.replace(/\..+/, "");
const filename = `${timestamp}-${logEntry.category.replace("/", "-")}.json`;
console.log("filename:", filename);
- await fs.writeFile(
- `${logsDir}/${filename}`,
- JSON.stringify(logEntry, null, 2)
- );
+ fs.writeFileSync(`${logsDir}/${filename}`, JSON.stringify(logEntry, null, 2));
}
async function generateDailySummary(
@@ -112,26 +98,14 @@ async function generateDailySummary(
Provide a human-readable summary that highlights key activities and insights.`;
console.log("daily summary prompt:", prompt);
- const response = await fetch(ollamaApiUrl + "/chat", {
- method: "POST",
- body: JSON.stringify({
- model: ollamaModel,
- messages: [{ role: "user", content: prompt }],
- stream: false,
- }),
+ const provider = createOllama({ baseURL: ollamaApiUrl });
+ const response = await generateText({
+ model: provider(ollamaModel),
+ messages: [{ role: "user", content: prompt }],
});
console.log("daily summary ollama response:", response);
- if (!response.ok) {
- console.log("ollama response:", await response.text());
- throw new Error(`http error! status: ${response.status}`);
- }
-
- const result = await response.json();
-
- console.log("ai summary:", result);
-
- return result.message.content;
+ return response.text;
}
async function retry<T>(
@@ -159,36 +133,47 @@ async function sendEmail(
subject: string,
body: string
): Promise<void> {
- const from = to; // assuming the sender is the same as the recipient
await retry(async () => {
- const result = await pipe.sendEmail({
- to,
- from,
- password,
- subject,
- body,
+ // Create a transporter using SMTP
+ const transporter = nodemailer.createTransport({
+ host: "smtp.gmail.com", // Replace with your SMTP server
+ port: 587,
+ secure: false, // Use TLS
+ auth: {
+ user: to, // assuming the sender is the same as the recipient
+ pass: password,
+ },
+ });
+
+ // Send mail with defined transport object
+ const info = await transporter.sendMail({
+ from: to, // sender address
+ to: to, // list of receivers
+ subject: subject, // Subject line
+ text: body, // plain text body
});
- if (!result) {
+
+ if (!info) {
throw new Error("failed to send email");
}
console.log(`email sent to ${to} with subject: ${subject}`);
});
}
-async function getTodayLogs(): Promise<DailyLog[]> {
+function getTodayLogs(): DailyLog[] {
try {
const logsDir = `${process.env.PIPE_DIR}/logs`;
const today = new Date().toISOString().replace(/:/g, "-").split("T")[0]; // Get today's date in YYYY-MM-DD format
console.log("reading logs dir:", logsDir);
- const files = await fs.readdir(logsDir);
+ const files = fs.readdirSync(logsDir);
console.log("files:", files);
const todayFiles = files.filter((file) => file.startsWith(today));
console.log("today's files:", todayFiles);
const logs: DailyLog[] = [];
for (const file of todayFiles) {
- const content = await fs.readFile(`${logsDir}/${file}`);
+ const content = fs.readFileSync(`${logsDir}/${file}`, "utf8");
logs.push(JSON.parse(content));
}
@@ -202,7 +187,7 @@ async function getTodayLogs(): Promise<DailyLog[]> {
async function dailyLogPipeline(): Promise<void> {
console.log("starting daily log pipeline");
- const config = await pipe.loadConfig();
+ const config = await loadPipeConfig();
console.log("loaded config:", JSON.stringify(config, null, 2));
const interval = config.interval * 1000;
@@ -221,9 +206,11 @@ async function dailyLogPipeline(): Promise<void> {
console.log("creating logs dir");
const logsDir = `${process.env.PIPE_DIR}/logs`;
console.log("logs dir:", logsDir);
- await fs.mkdir(logsDir).catch((error) => {
- console.warn("error creating logs dir:", error);
- });
+ try {
+ fs.mkdirSync(logsDir);
+ } catch (_error) {
+ console.warn("error creating logs dir, probably already exists");
+ }
let lastEmailSent = new Date(0); // Initialize to a past date
@@ -251,12 +238,12 @@ async function dailyLogPipeline(): Promise<void> {
const now = new Date();
const oneMinuteAgo = new Date(now.getTime() - interval);
- const screenData = await pipe.queryScreenpipe({
- start_time: oneMinuteAgo.toISOString(),
- end_time: now.toISOString(),
- window_name: windowName,
+ const screenData = await queryScreenpipe({
+ startTime: oneMinuteAgo.toISOString(),
+ endTime: now.toISOString(),
+ windowName: windowName,
limit: pageSize,
- content_type: contentType,
+ contentType: contentType,
});
if (screenData && screenData.data && screenData.data.length > 0) {
@@ -291,7 +278,6 @@ async function dailyLogPipeline(): Promise<void> {
}
if (shouldSendSummary) {
- // await retry(async () => {
const todayLogs = await getTodayLogs();
console.log("today's logs:", todayLogs);
@@ -311,7 +297,6 @@ async function dailyLogPipeline(): Promise<void> {
);
lastEmailSent = now;
}
- // });
}
} catch (error) {
console.warn("error in daily log pipeline:", error);
diff --git a/examples/typescript/pipe-email-daily-log/screenpipe.d.ts b/examples/typescript/pipe-email-daily-log/screenpipe.d.ts
deleted file mode 100644
index 820e1a2d0..000000000
--- a/examples/typescript/pipe-email-daily-log/screenpipe.d.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-declare global {
- const pipe: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Removes a file.
- * @param path - The path to the file to be removed.
- * @returns A promise that resolves when the file is removed.
- */
- removeFile: (path: string) => Promise<void>;
-
- /**
- * Performs a GET request to the specified URL.
- * @param url - The URL to send the GET request to.
- * @returns A promise that resolves with the response data.
- */
- get: (url: string) => Promise<any>;
-
- /**
- * Performs a POST request to the specified URL.
- * @param url - The URL to send the POST request to.
- * @param body - The body of the POST request.
- * @returns A promise that resolves with the response data.
- */
- post: (url: string, body: string) => Promise<any>;
-
- /**
- * Performs a fetch request.
- * @param url - The URL to fetch.
- * @param options - Optional fetch options.
- * @returns A promise that resolves with the fetch response.
- */
- fetch: (url: string, options?: RequestInit) => Promise<Response>;
-
- /**
- * Sends a notification.
- * @param options - The notification options.
- * @returns A promise that resolves when the notification is sent.
- */
- sendNotification: (options: {
- title: string;
- body: string;
- }) => Promise<any>;
-
- /**
- * Loads the configuration for the pipe.
- * @returns A promise that resolves with the configuration object.
- */
- loadConfig: () => Promise<Record<string, any>>;
-
- /**
- * The current configuration of the pipe.
- */
- config: Record<string, any>;
-
- /**
- * Metadata about the current pipe.
- */
- metadata: {
- id: string;
- };
-
- /**
- * Sends an email.
- * @param options - The email options.
- * @returns A promise that resolves to true if the email was sent successfully, false otherwise.
- */
- sendEmail: (options: {
- to: string;
- from: string;
- password: string;
- subject: string;
- body: string;
- }) => Promise<boolean>;
-
- /**
- * Queries the Screenpipe database.
- * @param params - The query parameters.
- * @returns A promise that resolves with the query results or null if an error occurred.
- */
- queryScreenpipe: (
- params: ScreenpipeQueryParams
- ) => Promise<ScreenpipeResponse | null>;
- };
-
- const fs: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Reads the contents of a directory.
- * @param path - The path to the directory to be read.
- * @returns A promise that resolves with an array of file names in the directory.
- */
- readdir: (path: string) => Promise<string[]>;
-
- /**
- * Creates a new directory.
- * @param path - The path of the directory to be created.
- * @returns A promise that resolves when the directory is created.
- */
- mkdir: (path: string) => Promise<void>;
- };
-
- const path: {
- /**
- * Joins multiple path segments into a single path.
- * @param paths - The path segments to join.
- * @returns The joined path string.
- */
- join: (...paths: string[]) => string;
- };
-
- namespace NodeJS {
- interface ProcessEnv {
- SCREENPIPE_DIR: string;
- SCREENPIPE_LOG_API_URL?: string;
- SCREENPIPE_SERVER_URL?: string;
- PIPE_DIR: string;
- NOTION_DATABASE_ID: string;
- NOTION_API_KEY: string;
- }
- }
- const process: {
- env: NodeJS.ProcessEnv;
- };
-
- /**
- * Types of content that can be queried in Screenpipe.
- */
- type ContentType = "ocr" | "audio" | "all";
-
- /**
- * Parameters for querying Screenpipe.
- */
- interface ScreenpipeQueryParams {
- q?: string;
- content_type?: ContentType;
- limit?: number;
- offset?: number;
- start_time?: string;
- end_time?: string;
- app_name?: string;
- window_name?: string;
- include_frames?: boolean;
- min_length?: number;
- max_length?: number;
- }
-
- /**
- * Structure of OCR (Optical Character Recognition) content.
- */
- interface OCRContent {
- frame_id: number;
- text: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- app_name: string;
- window_name: string;
- tags: string[];
- frame?: string;
- }
-
- /**
- * Structure of audio content.
- */
- interface AudioContent {
- chunk_id: number;
- transcription: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- tags: string[];
- device_name: string;
- device_type: string;
- }
-
- /**
- * Structure of Full Text Search content.
- */
- interface FTSContent {
- text_id: number;
- matched_text: string;
- frame_id: number;
- timestamp: string;
- app_name: string;
- window_name: string;
- file_path: string;
- original_frame_text?: string;
- tags: string[];
- }
-
- /**
- * Union type for different types of content items.
- */
- type ContentItem =
- | { type: "OCR"; content: OCRContent }
- | { type: "Audio"; content: AudioContent }
- | { type: "FTS"; content: FTSContent };
-
- /**
- * Pagination information for search results.
- */
- interface PaginationInfo {
- limit: number;
- offset: number;
- total: number;
- }
-
- /**
- * Structure of the response from a Screenpipe query.
- */
- interface ScreenpipeResponse {
- data: ContentItem[];
- pagination: PaginationInfo;
- }
-}
-
-export {};
diff --git a/examples/typescript/pipe-email-daily-log/tsconfig.json b/examples/typescript/pipe-email-daily-log/tsconfig.json
deleted file mode 100644
index c4e6dfdd7..000000000
--- a/examples/typescript/pipe-email-daily-log/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "esnext",
- "moduleResolution": "node",
- "outDir": "./",
- "rootDir": "./",
- "strict": true,
- "esModuleInterop": true
- },
- "include": [
- "./**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-focus-notification-buddy/README.md b/examples/typescript/pipe-focus-notification-buddy/README.md
deleted file mode 100644
index f54a25c00..000000000
--- a/examples/typescript/pipe-focus-notification-buddy/README.md
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-
-https://github.com/user-attachments/assets/f5695ba3-b37f-4bb9-be55-56d60144c7f3
-
-
-
-in screenpipe we have a plugin system called "pipe store" or "pipes"
-
-think of it like this:
-
-screenpipe data -> your pipe like "AI annotate" or "send to salesforce"
-
-a more dev-friendly explanation:
-
-screenpipe | AI tag | notion update
-
-or
-
-screenpipe | AI tag | slack send report
-
-or
-
-screenpipe | fill salesforce
-
-or
-
-screenpipe | logs daily
-
-basically it would read, process, annotate, analyse, summarize, send, your data customisable to your desire, effortlessly
-
-### pipe-focus-notification-buddy
-
-this is an experimental, but official pipe
-
-this is how you run it through the app:
-
-`ollama run phi3.5`
-
-then drop the url of this folder in the pipe store and it works
-
-works also with CLI
diff --git a/examples/typescript/pipe-focus-notification-buddy/pipe.js b/examples/typescript/pipe-focus-notification-buddy/pipe.js
deleted file mode 100644
index 329fde001..000000000
--- a/examples/typescript/pipe-focus-notification-buddy/pipe.js
+++ /dev/null
@@ -1,97 +0,0 @@
-const INTERVAL = 1 * 6 * 1000; // 1 minute in milliseconds
-
-async function queryScreenpipe(params) {
- try {
- const queryParams = Object.entries(params)
- .filter(([_, v]) => v != null)
- .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
- .join('&');
- console.log("Calling Screenpipe:", JSON.stringify(params));
- const result = await pipe.get(`http://localhost:3030/search?${queryParams}`);
- console.log("Retrieved", result.data.length, "items from Screenpipe");
- return result;
- } catch (error) {
- console.error("Error querying Screenpipe:", error);
- return null;
- }
-}
-
-async function getAIProvider() {
- const provider = "ollama";
- const model = "phi3.5";
- return { provider, model };
-}
-
-async function detectWorkStatus(provider, screenData) {
- const prompt = `Based on the following screen data, determine if the user is working or not:
-
- ${JSON.stringify(screenData)}
-
- We will show a desktop notification if the user is not working.
- Not working:
- - Social media
- - Chatting
- - Youtube
- - Netflix
- - Games
- - Porn
- - Other distracting websites
-
- Be funny, sarcastic, like say "stop watching porn bro", use techbro language. Keep body short as it's a notification.
-
- Return a JSON object with the following structure:
- {
- "work": boolean,
- "title": "A brief title with advice or support",
- "body": "A brief message with advice or support"
- }
- Do not say anything else but JSON.`;
-
- const result = await pipe.post(
- "http://localhost:11434/api/chat",
- JSON.stringify({
- model: provider.model,
- messages: [{ role: "user", content: prompt }],
- response_format: { type: "json_object" },
- stream: false,
- }),
- );
-
- console.log("AI answer:", result);
-
- const content = result.message.content;
- return JSON.parse(content);
-}
-
-async function main() {
- const provider = await getAIProvider();
-
- while (true) {
- try {
- const screenData = await queryScreenpipe({
- limit: 10,
- offset: 0,
- start_time: new Date(Date.now() - INTERVAL).toISOString(),
- end_time: new Date().toISOString(),
- content_type: "ocr",
- });
-
- if (screenData && screenData.data) {
- const workStatus = await detectWorkStatus(provider, screenData.data);
-
- if (!workStatus.work) {
- pipe.sendNotification({
- title: workStatus.title,
- body: workStatus.body,
- });
- }
- }
- } catch (error) {
- console.error("Error in main loop:", error);
- }
-
- await new Promise(resolve => setTimeout(resolve, INTERVAL));
- }
-}
-
-main();
\ No newline at end of file
diff --git a/examples/typescript/pipe-llama32-comment-linear-while-you-work/deno.json b/examples/typescript/pipe-llama32-comment-linear-while-you-work/deno.json
new file mode 100644
index 000000000..88c9f36d9
--- /dev/null
+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/deno.json
@@ -0,0 +1,8 @@
+{
+ "imports": {
+ "zod": "npm:zod",
+ "ai": "npm:ai",
+ "ollama-ai-provider": "npm:ollama-ai-provider",
+ "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/deno-thru-cli/screenpipe-js/main.ts"
+ }
+}
\ No newline at end of file
diff --git a/examples/typescript/pipe-llama32-comment-linear-while-you-work/deno.lock b/examples/typescript/pipe-llama32-comment-linear-while-you-work/deno.lock
new file mode 100644
index 000000000..00060d865
--- /dev/null
+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/deno.lock
@@ -0,0 +1,491 @@
+{
+ "version": "4",
+ "specifiers": {
+ "npm:@linear/sdk@*": "[email protected]",
+ "npm:@types/node@*": "22.5.4",
+ "npm:ai@*": "[email protected]",
+ "npm:ollama-ai-provider@*": "[email protected]",
+ "npm:zod@*": "3.23.8"
+ },
+ "npm": {
+ "integrity": "sha512-ngg/RGpnA00eNOWEtXHenpX1MsM2QshQh4QJFjUfwcqHpM5kTfG7je7Rc3HcEDP+OkRVv2GF+X4fC1Vfcnl8Ow==",
+ "dependencies": [
+ "@ai-sdk/provider",
+ "eventsource-parser",
+ "secure-json-parse",
+ "zod"
+ ]
+ },
+ "@ai-sdk/[email protected]": {
+ "integrity": "sha512-XMsNGJdGO+L0cxhhegtqZ8+T6nn4EoShS819OvCgI2kLbYTIvk0GWFGD0AXJmxkxs3DrpsJxKAFukFR7bvTkgQ==",
+ "dependencies": [
+ "json-schema"
+ ]
+ },
+ "integrity": "sha512-1asDpxgmeHWL0/EZPCLENxfOHT+0jce0z/zasRhascodm2S6f6/KZn5doLG9jdmarcb+GjMjFmmwyOVXz3W1xg==",
+ "dependencies": [
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/ui-utils",
+ "swr",
+ "zod"
+ ]
+ },
+ "integrity": "sha512-KnfWTt640cS1hM2fFIba8KHSPLpOIWXtEm28pNCHTvqasVKlh2y/zMQANTwE18pF2nuXL9P9F5/dKWaPsaEzQw==",
+ "dependencies": [
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/ui-utils"
+ ]
+ },
+ "integrity": "sha512-aIZJaIds+KpCt19yUDCRDWebzF/17GCY7gN9KkcA2QM6IKRO5UmMcqEYja0ZmwFQPm1kBZkF2njhr8VXis2mAw==",
+ "dependencies": [
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/ui-utils",
+ "sswr"
+ ]
+ },
+ "integrity": "sha512-ZG/wneyJG+6w5Nm/hy1AKMuRgjPQToAxBsTk61c9sVPUTaxo+NNjM2MhXQMtmsja2N5evs8NmHie+ExEgpL3cA==",
+ "dependencies": [
+ "@ai-sdk/provider",
+ "@ai-sdk/provider-utils",
+ "json-schema",
+ "secure-json-parse",
+ "zod",
+ "zod-to-json-schema"
+ ]
+ },
+ "integrity": "sha512-Ltu6gbuii8Qlp3gg7zdwdnHdS4M8nqKDij2VVO1223VOtIFwORFJzKqpfx44U11FW8z2TPVBYN+FjkyVIcN2hg==",
+ "dependencies": [
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/ui-utils",
+ "swrv"
+ ]
+ },
+ "@ampproject/[email protected]": {
+ "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
+ "dependencies": [
+ "@jridgewell/gen-mapping",
+ "@jridgewell/trace-mapping"
+ ]
+ },
+ "@babel/[email protected]": {
+ "integrity": "sha512-CbkjYdsJNHFk8uqpEkpCvRs3YRp9tY6FmFY7wLMSYuGYkrdUi7r2lc4/wqsvlHoMznX3WJ9IP8giGPq68T/Y6g=="
+ },
+ "@babel/[email protected]": {
+ "integrity": "sha512-AM6TzwYqGChO45oiuPqwL2t20/HdMC1rTPAesnBCgPCSF1x3oN9MVUwQV2iyz4xqWrctwK5RNC8LV22kaQCNYg=="
+ },
+ "@babel/[email protected]": {
+ "integrity": "sha512-HcttkxzdPucv3nNFmfOOMfFf64KgdJVqm1KaCm25dPGMLElo9nsLvXeJECQg8UzPuBGLyTSA0ZzqCtDSzKTEoQ==",
+ "dependencies": [
+ "@babel/types"
+ ]
+ },
+ "@babel/[email protected]": {
+ "integrity": "sha512-JWtuCu8VQsMladxVz/P4HzHUGCAwpuqacmowgXFs5XjxIgKuNjnLokQzuVjlTvIzODaDmpjT3oxcC48vyk9EWg==",
+ "dependencies": [
+ "@babel/helper-string-parser",
+ "@babel/helper-validator-identifier",
+ "to-fast-properties"
+ ]
+ },
+ "@graphql-typed-document-node/[email protected][email protected]": {
+ "integrity": "sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==",
+ "dependencies": [
+ "graphql"
+ ]
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==",
+ "dependencies": [
+ "@jridgewell/set-array",
+ "@jridgewell/sourcemap-codec",
+ "@jridgewell/trace-mapping"
+ ]
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A=="
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ=="
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==",
+ "dependencies": [
+ "@jridgewell/resolve-uri",
+ "@jridgewell/sourcemap-codec"
+ ]
+ },
+ "integrity": "sha512-51mKO/R5JBnQERDfg5uMryHGRyavUAkveIiHxxshItvEIwFVACJi8S7N2oabhSlqqNZf2rL0YlVokeRxd72s6A==",
+ "dependencies": [
+ "@graphql-typed-document-node/core",
+ "graphql",
+ "isomorphic-unfetch"
+ ]
+ },
+ "@opentelemetry/[email protected]": {
+ "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="
+ },
+ "@types/[email protected]": {
+ "integrity": "sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg=="
+ },
+ "@types/[email protected]": {
+ "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw=="
+ },
+ "@types/[email protected]": {
+ "integrity": "sha512-FDuKUJQm/ju9fT/SeX/6+gBzoPzlVCzfzmGkwKvRHQVxi4BntVbyIwf6a4Xn62mrvndLiml6z/UBXIdEVjQLXg==",
+ "dependencies": [
+ "undici-types"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-PwAdxs7/9Hc3ieBO12tXzmTD+Ln4qhT/56S+8DvrrZ4kLDn4Z/AMUr8tXJD0axiJBS0RKIoNaR0yMuQB9v9Udg==",
+ "dependencies": [
+ "@babel/parser",
+ "@vue/shared",
+ "entities",
+ "source-map-js"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-pyGf8zdbDDRkBrEzf8p7BQlMKNNF5Fk/Cf/fQ6PiUz9at4OaUfyXW0dGJTo2Vl1f5U9jSLCNf0EZJEogLXoeew==",
+ "dependencies": [
+ "@vue/compiler-core",
+ "@vue/shared"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-gsbBtT4N9ANXXepprle+X9YLg2htQk1sqH/qGJ/EApl+dgpUBdTv3yP7YlR535uHZY3n6XaR0/bKo0BgwwDniw==",
+ "dependencies": [
+ "@babel/parser",
+ "@vue/compiler-core",
+ "@vue/compiler-dom",
+ "@vue/compiler-ssr",
+ "@vue/shared",
+ "magic-string",
+ "postcss",
+ "source-map-js"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-P4+GPjOuC2aFTk1Z4WANvEhyOykcvEd5bIj2KVNGKGfM745LaXGr++5njpdBTzVz5pZifdlR1kpYSJJpIlSePA==",
+ "dependencies": [
+ "@vue/compiler-dom",
+ "@vue/shared"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-Nqo5VZEn8MJWlCce8XoyVqHZbd5P2NH+yuAaFzuNSR96I+y1cnuUiq7xfSG+kyvLSiWmaHTKP1r3OZY4mMD50w==",
+ "dependencies": [
+ "@vue/shared"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-7PsxFGqwfDhfhh0OcDWBG1DaIQIVOLgkwA5q6MtkPiDFjp5gohVnJEahSktwSFLq7R5PtxDKy6WKURVN1UDbzA==",
+ "dependencies": [
+ "@vue/reactivity",
+ "@vue/shared"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-GNghjecT6IrGf0UhuYmpgaOlN7kxzQBhxWEn08c/SQDxv1yy4IXI1bn81JgEpQ4IXjRxWtPyI8x0/7TF5rPfYQ==",
+ "dependencies": [
+ "@vue/reactivity",
+ "@vue/runtime-core",
+ "@vue/shared",
+ "csstype"
+ ]
+ },
+ "integrity": "sha512-cVOwYBxR7Wb1B1FoxYvtjJD8X/9E5nlH4VSkJy2uMA1MzYNdzAAB//l8nrmN9py/4aP+3NjWukf9PZ3TeWULaA==",
+ "dependencies": [
+ "@vue/compiler-ssr",
+ "@vue/shared",
+ "vue"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-W8GgysJVnFo81FthhzurdRAWP/byq3q2qIw70e0JWblzVhjgOMiC2GyovXrZTFQJnFVryYaKGP3Tc9vYzYm6PQ=="
+ },
+ "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg=="
+ },
+ "integrity": "sha512-wmVzpIHNGjCEjIJ/3945a/DIkz+gwObjC767ZRgO8AmtIZMO5KqvqNr7n2KF+gQrCPCMC8fM1ICQFXSvBZnBlA==",
+ "dependencies": [
+ "@ai-sdk/provider",
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/react",
+ "@ai-sdk/solid",
+ "@ai-sdk/svelte",
+ "@ai-sdk/ui-utils",
+ "@ai-sdk/vue",
+ "@opentelemetry/api",
+ "eventsource-parser",
+ "json-schema",
+ "jsondiffpatch",
+ "secure-json-parse",
+ "zod",
+ "zod-to-json-schema"
+ ]
+ },
+ "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw=="
+ },
+ "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="
+ },
+ "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w=="
+ },
+ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="
+ },
+ "integrity": "sha512-7qJWqItLA8/VPVlKJlFXU+NBlo/qyfs39aJcuMT/2ere32ZqvF5OSxgdM5xOfJJ7O429gg2HM47y8v9P+9wrNw==",
+ "dependencies": [
+ "@jridgewell/sourcemap-codec",
+ "@types/estree",
+ "acorn",
+ "periscopic"
+ ]
+ },
+ "integrity": "sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==",
+ "dependencies": [
+ "mdn-data",
+ "source-map-js"
+ ]
+ },
+ "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="
+ },
+ "integrity": "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw=="
+ },
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="
+ },
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="
+ },
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dependencies": [
+ "@types/estree"
+ ]
+ },
+ "integrity": "sha512-v0eOBUbiaFojBu2s2NPBfYUoRR9GjcDNvCXVaqEf5vVfpIAh9f8RCo4vXTP8c63QRKCFwoLpMpTdPwwhEKVgzA=="
+ },
+ "integrity": "sha512-GCOQdvm7XxV1S4U4CGrsdlEN37245eC8P9zaYCMr6K1BG0IPGy5lUwmJsEOGyl1GD6HXjOtl2keCP9asRBwNvA=="
+ },
+ "integrity": "sha512-v3rht/LgVcsdZa3O2Nqs+NMowLOxeOm7Ay9+/ARQ2F+qEoANRcqrjAZKGN0v8ymUetZGgkp26LTnGT7H0Qo9Pg==",
+ "dependencies": [
+ "@types/estree"
+ ]
+ },
+ "integrity": "sha512-geDJjpoZ8N0kWexiwkX8F9NkTsXhetLPVbZFQ+JTW239QNOwvB0gniuR1Wc6f0AMTn7/mFGyXvHTifrCp/GH8Q==",
+ "dependencies": [
+ "node-fetch",
+ "unfetch"
+ ]
+ },
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
+ },
+ "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="
+ },
+ "integrity": "sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==",
+ "dependencies": [
+ "@types/diff-match-patch",
+ "chalk",
+ "diff-match-patch"
+ ]
+ },
+ "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA=="
+ },
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "dependencies": [
+ "js-tokens"
+ ]
+ },
+ "integrity": "sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==",
+ "dependencies": [
+ "@jridgewell/sourcemap-codec"
+ ]
+ },
+ "integrity": "sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA=="
+ },
+ "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA=="
+ },
+ "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g=="
+ },
+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
+ "dependencies": [
+ "whatwg-url"
+ ]
+ },
+ "integrity": "sha512-bMDUlYmohulD87Xrv6meuftQdmFTygtrQywy6/gqdf1bTsJFP1VCx3MrisLFBzb4mMOj02NER7yZhiGIlAx30w==",
+ "dependencies": [
+ "@ai-sdk/provider",
+ "@ai-sdk/provider-utils",
+ "partial-json",
+ "zod"
+ ]
+ },
+ "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA=="
+ },
+ "integrity": "sha512-vKiQ8RRtkl9P+r/+oefh25C3fhybptkHKCZSPlcXiJux2tJF55GnEj3BVn4A5gKfq9NWWXXrxkHBwVPUfH0opw==",
+ "dependencies": [
+ "@types/estree",
+ "is-reference"
+ ]
+ },
+ "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw=="
+ },
+ "integrity": "sha512-56rxCq7G/XfB4EkXq9Egn5GCqugWvDFjafDOThIdMBsI15iqPqR5r15TfSr1YPYeEI19YeaXMCbY6u88Y76GLQ==",
+ "dependencies": [
+ "picocolors",
+ "source-map-js"
+ ]
+ },
+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
+ "dependencies": [
+ "loose-envify"
+ ]
+ },
+ "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw=="
+ },
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="
+ },
+ "integrity": "sha512-Cqc355SYlTAaUt8iDPaC/4DPPXK925PePLMxyBKuWd5kKc5mwsG3nT9+Mq2tyguL5s7b4Jg+IRMpTRsNTAfpSQ==",
+ "dependencies": [
+ "svelte",
+ "swrev"
+ ]
+ },
+ "integrity": "sha512-IY1rnGr6izd10B0A8LqsBfmlT5OILVuZ7XsI0vdGPEvuonFV7NYEUK4dAkm9Zg2q0Um92kYjTpS1CAP3Nh/KWw==",
+ "dependencies": [
+ "@ampproject/remapping",
+ "@jridgewell/sourcemap-codec",
+ "@jridgewell/trace-mapping",
+ "@types/estree",
+ "acorn",
+ "aria-query",
+ "axobject-query",
+ "code-red",
+ "css-tree",
+ "is-reference",
+ "locate-character",
+ "magic-string",
+ "periscopic"
+ ]
+ },
+ "integrity": "sha512-QtxqyclFeAsxEUeZIYmsaQ0UjimSq1RZ9Un7I68/0ClKK/U3LoyQunwkQfJZr2fc22DfIXLNDc2wFyTEikCUpg==",
+ "dependencies": [
+ "client-only",
+ "react",
+ "use-sync-external-store"
+ ]
+ },
+ "integrity": "sha512-LqVcOHSB4cPGgitD1riJ1Hh4vdmITOp+BkmfmXRh4hSF/t7EnS4iD+SOTmq7w5pPm/SiPeto4ADbKS6dHUDWFA=="
+ },
+ "integrity": "sha512-zjEkcP8Ywmj+xOJW3lIT65ciY/4AL4e/Or7Gj0MzU3zBJNMdJiT8geVZhINavnlHRMMCcJLHhraLTAiDOTmQ9g==",
+ "dependencies": [
+ "vue"
+ ]
+ },
+ "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog=="
+ },
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
+ },
+ "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw=="
+ },
+ "integrity": "sha512-F9p7yYCn6cIW9El1zi0HI6vqpeIvBsr3dSuRO6Xuppb1u5rXpCPmMvLSyECLhybr9isec8Ohl0hPekMVrEinDA=="
+ },
+ "integrity": "sha512-PElTlVMwpblvbNqQ82d2n6RjStvdSoNe9FG28kNfz3WiXilJm4DdNkEzRhCZuIDwY8U08WVihhGR5iRqAwfDiw==",
+ "dependencies": [
+ "react"
+ ]
+ },
+ "integrity": "sha512-/8Wurrd9J3lb72FTQS7gRMNQD4nztTtKPmuDuPuhqXmmpD6+skVjAeahNpVzsuky6Sy9gy7wn8UadqPtt9SQIg==",
+ "dependencies": [
+ "@vue/compiler-dom",
+ "@vue/compiler-sfc",
+ "@vue/runtime-dom",
+ "@vue/server-renderer",
+ "@vue/shared"
+ ]
+ },
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
+ },
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
+ "dependencies": [
+ "tr46",
+ "webidl-conversions"
+ ]
+ },
+ "integrity": "sha512-uSt90Gzc/tUfyNqxnjlfBs8W6WSGpNBv0rVsNxP/BVSMHMKGdthPYff4xtCHYloJGM0CFxFsb3NbC0eqPhfImw==",
+ "dependencies": [
+ "zod"
+ ]
+ },
+ "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g=="
+ }
+ },
+ "remote": {
+ "https://raw.githubusercontent.com/mediar-ai/screenpipe/deno-thru-cli/screenpipe-js/main.ts": "b18e7291d9336bac7c3423b5192acae65580fd08bf2ced8ddd3332d576063e46"
+ }
+}
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.json
index 87af3a56e..0113a65d5 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
@@ -10,12 +10,12 @@
"name": "linearApiKey",
"type": "string",
"default": "<fill your linear api key here>",
- "description": "linear api key for authentication"
+ "description": "linear api key for authentication https://linear.app/mediar/settings/api"
},
{
"name": "ollamaApiUrl",
"type": "string",
- "default": "http://localhost:11434/api/chat",
+ "default": "http://localhost:11434/api",
"description": "ollama api url"
},
{
@@ -35,6 +35,18 @@
"type": "string",
"default": "",
"description": "custom prompt to override part of the system prompt for comment generation"
+ },
+ {
+ "name": "windowName",
+ "type": "window",
+ "default": "",
+ "description": "Specific window name to filter the screen data, for example 'gmail', 'john', 'slack', 'myCodeFile.tsx', etc. this will filter out audio"
+ },
+ {
+ "name": "contentType",
+ "type": "contentType",
+ "default": "ocr",
+ "description": "Type of content to analyze: 'ocr', 'audio', or 'all'. OCR usually contains more content, so it's recommended to choose either OCR or audio rather than 'all' for better performance."
}
]
}
\ No newline at end of file
diff --git a/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.ts b/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.ts
index 3d4f03f41..d7bd54c79 100644
--- a/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.ts
+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.ts
@@ -1,9 +1,24 @@
-const LINEAR_API_URL = "https://api.linear.app/graphql";
-
-interface LinearComment {
- taskId: string;
- body: string;
-}
+import {
+ queryScreenpipe,
+ loadPipeConfig,
+ ContentItem,
+ sendDesktopNotification,
+} from "screenpipe";
+
+import { z } from "zod";
+import { generateObject } from "ai";
+import { createOllama } from "ollama-ai-provider";
+import { LinearClient } from "npm:@linear/sdk";
+
+const linearSearchQuery = z.object({
+ query: z.string(),
+});
+
+const linearComment = z.object({
+ taskId: z.string(),
+ body: z.string(),
+ nothingToDo: z.boolean().optional(),
+});
async function generateLinearSearchQuery(
screenData: ContentItem[],
@@ -14,6 +29,8 @@ async function generateLinearSearchQuery(
${JSON.stringify(screenData)}
+ the query should be relevant to the screen/audio data and will be used to search for relevant linear tasks in the product management tool of the user to comment on it
+
return a json object with a single 'query' field containing only the text to search for in the task title. here are some examples:
- { "query": "audio" }
- { "query": "macos" }
@@ -31,33 +48,19 @@ async function generateLinearSearchQuery(
- return only the json object, no additional text
`;
- const response = await fetch(ollamaApiUrl, {
- headers: {
- "Content-Type": "application/json",
- },
- method: "POST",
- body: JSON.stringify({
- model: ollamaModel,
- messages: [{ role: "user", content: prompt }],
- stream: false,
- response_format: { type: "json_object" },
- }),
+ const provider = createOllama({
+ baseURL: ollamaApiUrl,
});
- console.log("response", response);
-
- if (!response.ok) {
- const errorBody = await response.text();
- throw new Error(
- `http error! status: ${response.status}, body: ${errorBody}`
- );
- }
-
- const result = await response.json();
+ const response = await generateObject({
+ model: provider(ollamaModel),
+ messages: [{ role: "user", content: prompt }],
+ schema: linearSearchQuery,
+ });
- console.log("ai answer:", result);
+ console.log("ai response", response);
- return JSON.parse(result.message.content.trim());
+ return response.object.query;
}
async function generateLinearComment(
@@ -66,7 +69,7 @@ async function generateLinearComment(
ollamaApiUrl: string,
ollamaModel: string,
customCommentPrompt: string
-): Promise<LinearComment> {
+): Promise<z.infer<typeof linearComment>> {
console.log("generating linear comment for tasks:", relevantTasks);
const basePrompt = `based on the following screen data and relevant linear tasks, generate a concise, informative comment for the most relevant task:
@@ -75,36 +78,16 @@ async function generateLinearComment(
return a json object with the following structure:
{
- "taskId": "linear task id of the most relevant task",
- "body": "informative comment about work done, progress made, or insights gained"
+ "taskId": "linear task id of the most relevant task (must be one of the provided task ids)",
+ "body": "informative comment about work done, progress made, or insights gained related to the chosen task"
+ "nothingToDo": "no task to comment on based on the screen data"
}
- here are some examples:
- {
- "taskId": "ISS-42",
- "body": "implemented pagination for user list. load times improved by 60%. next: add infinite scroll"
- }
- {
- "taskId": "BUG-17",
- "body": "debugged async data fetching. root cause: race condition. proposed fix: implement mutex. need review"
- }
- {
- "taskId": "FEAT-23",
- "body": "drafted new onboarding flow. key changes: simplified sign-up form, added progress indicator. ready for design review"
- }
- {
- "taskId": "PERF-08",
- "body": "optimized db queries. avg response time: 500ms -> 150ms. identified potential for further improvement in caching layer"
- }
- {
- "taskId": "DOC-12",
- "body": "updated api docs with new endpoints. added example requests and responses. todo: update postman collection"
- }
-
rules:
- format JSON correctly
- - comment should directly relate to the task and recent work/activity
- - include specific details, metrics, or insights from the screen data
+ - taskId MUST be one of the provided task ids, do not invent new ones
+ - comment should directly relate to the chosen task and recent work/activity
+ - include specific details, metrics, or insights from the screen data if applicable
- mention progress made, challenges encountered, or next steps if applicable
- keep it concise but informative (aim for 2-3 sentences)
- use technical language appropriate for the task context
@@ -115,146 +98,70 @@ async function generateLinearComment(
? `${basePrompt}\n\nadditional instructions: ${customCommentPrompt}`
: basePrompt;
- const response = await fetch(ollamaApiUrl, {
- headers: {
- "Content-Type": "application/json",
- },
- method: "POST",
- body: JSON.stringify({
- model: ollamaModel,
- messages: [{ role: "user", content: prompt }],
- stream: false,
- response_format: { type: "json_object" },
- }),
+ const provider = createOllama({
+ baseURL: ollamaApiUrl,
});
- if (!response.ok) {
- const errorBody = await response.text();
- throw new Error(
- `http error! status: ${response.status}, body: ${errorBody}`
- );
- }
+ const response = await generateObject({
+ model: provider(ollamaModel),
+ messages: [{ role: "user", content: prompt }],
+ schema: linearComment,
+ });
- const result = await response.json();
+ console.log("ai response", response);
- return JSON.parse(result.message.content.trim());
+ return response.object;
}
async function getCurrentUser(
apiKey: string
): Promise<{ id: string; name: string }> {
- const query = `
- {
- viewer {
- id
- name
- }
- }
- `;
-
- const response = await fetch(LINEAR_API_URL, {
- method: "POST",
- headers: {
- Authorization: apiKey,
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ query }),
- });
-
- if (!response.ok) {
- const errorBody = await response.text();
- throw new Error(
- `http error! status: ${response.status}, body: ${errorBody}`
- );
- }
-
- const result = await response.json();
- return result.data.viewer;
+ const client = new LinearClient({ apiKey });
+ const viewer = await client.viewer;
+ return { id: viewer.id, name: viewer.name };
}
async function addCommentToLinear(
- comment: LinearComment,
+ comment: z.infer<typeof linearComment>,
apiKey: string
): Promise<void> {
+ const client = new LinearClient({ apiKey });
const user = await getCurrentUser(apiKey);
const commentWithMention = `<@${user.id}>: ${comment.body}`;
- const mutation = `
- mutation CreateComment($input: CommentCreateInput!) {
- commentCreate(input: $input) {
- success
- }
- }
- `;
-
- const variables = {
- input: {
- issueId: comment.taskId,
+ try {
+ await client.createComment({
+ issueId: comment.taskId as string,
body: commentWithMention,
- },
- };
-
- const response = await fetch(LINEAR_API_URL, {
- method: "POST",
- headers: {
- Authorization: apiKey, // Remove the "Bearer" prefix
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ query: mutation, variables }),
- });
-
- if (!response.ok) {
- const errorBody = await response.text();
- throw new Error(
- `http error! status: ${response.status}, body: ${errorBody}`
- );
+ });
+ console.log("comment added to linear successfully");
+ } catch (error) {
+ console.error("linear api error:", error);
+ throw new Error("failed to add comment to linear");
}
-
- const result = await response.json();
- console.log("result", result);
-
- console.log("comment added to linear successfully");
}
async function searchLinearTasks(
queryText: string,
apiKey: string
): Promise<any[]> {
- const query = `
- {
- issues(filter: { title: { contains: "${queryText}" } }) {
- nodes {
- id
- title
- }
- }
- }
- `;
-
- const response = await fetch(LINEAR_API_URL, {
- method: "POST",
- headers: {
- Authorization: apiKey, // Remove the "Bearer" prefix
- "Content-Type": "application/json",
+ const client = new LinearClient({ apiKey });
+ const issues = await client.issues({
+ filter: {
+ title: { contains: queryText },
},
- body: JSON.stringify({ query }),
});
- if (!response.ok) {
- const errorBody = await response.text();
- throw new Error(
- `http error! status: ${response.status}, body: ${errorBody}`
- );
- }
-
- const result = await response.json();
- return result.data.issues.nodes;
+ return issues.nodes.map((issue) => ({
+ id: issue.id,
+ title: issue.title,
+ }));
}
async function streamCommentsToLinear(): Promise<void> {
console.log("starting comments stream to linear");
- const config = await pipe.loadConfig();
+ const config = await loadPipeConfig();
console.log("loaded config:", JSON.stringify(config, null, 2));
const interval = config.interval * 1000;
@@ -262,17 +169,22 @@ async function streamCommentsToLinear(): Promise<void> {
const ollamaApiUrl = config.ollamaApiUrl;
const ollamaModel = config.ollamaModel;
const customCommentPrompt = config.customCommentPrompt;
+ const windowName = config.windowName;
+ const contentType = config.contentType;
while (true) {
+ await new Promise((resolve) => setTimeout(resolve, interval));
+
try {
const now = new Date();
const intervalAgo = new Date(now.getTime() - interval);
- const screenData = await pipe.queryScreenpipe({
- start_time: intervalAgo.toISOString(),
- end_time: now.toISOString(),
+ const screenData = await queryScreenpipe({
+ startTime: intervalAgo.toISOString(),
+ endTime: now.toISOString(),
limit: config.pageSize,
- content_type: "all",
+ contentType: contentType,
+ windowName: windowName,
});
if (screenData && screenData.data.length > 0) {
@@ -300,11 +212,16 @@ async function streamCommentsToLinear(): Promise<void> {
customCommentPrompt
);
+ if (comment.nothingToDo) {
+ console.log("no comment to add to linear");
+ continue;
+ }
+
// step 4: add the comment to the linear task
await addCommentToLinear(comment, apiKey);
// randomly send a notification
- await pipe.sendNotification({
+ await sendDesktopNotification({
title: "linear comment pipeline update",
body: `comment added to task ${comment.taskId}`,
});
diff --git a/examples/typescript/pipe-llama32-comment-linear-while-you-work/screenpipe.d.ts b/examples/typescript/pipe-llama32-comment-linear-while-you-work/screenpipe.d.ts
deleted file mode 100644
index 327a2ee5d..000000000
--- a/examples/typescript/pipe-llama32-comment-linear-while-you-work/screenpipe.d.ts
+++ /dev/null
@@ -1,252 +0,0 @@
-declare global {
- const pipe: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Removes a file.
- * @param path - The path to the file to be removed.
- * @returns A promise that resolves when the file is removed.
- */
- removeFile: (path: string) => Promise<void>;
-
- /**
- * Performs a GET request to the specified URL.
- * @param url - The URL to send the GET request to.
- * @returns A promise that resolves with the response data.
- */
- get: (url: string) => Promise<any>;
-
- /**
- * Performs a POST request to the specified URL.
- * @param url - The URL to send the POST request to.
- * @param body - The body of the POST request.
- * @returns A promise that resolves with the response data.
- */
- post: (url: string, body: string) => Promise<any>;
-
- /**
- * Performs a fetch request.
- * @param url - The URL to fetch.
- * @param options - Optional fetch options.
- * @returns A promise that resolves with the fetch response.
- */
- fetch: (url: string, options?: RequestInit) => Promise<Response>;
-
- /**
- * Sends a notification.
- * @param options - The notification options.
- * @returns A promise that resolves when the notification is sent.
- */
- sendNotification: (options: {
- title: string;
- body: string;
- }) => Promise<any>;
-
- /**
- * Loads the configuration for the pipe.
- * @returns A promise that resolves with the configuration object.
- */
- loadConfig: () => Promise<Record<string, any>>;
-
- /**
- * The current configuration of the pipe.
- */
- config: Record<string, any>;
-
- /**
- * Metadata about the current pipe.
- */
- metadata: {
- id: string;
- };
-
- /**
- * Sends an email.
- * @param options - The email options.
- * @returns A promise that resolves to true if the email was sent successfully, false otherwise.
- */
- sendEmail: (options: {
- to: string;
- from: string;
- password: string;
- subject: string;
- body: string;
- }) => Promise<boolean>;
-
- /**
- * Queries the Screenpipe database.
- * @param params - The query parameters.
- * @returns A promise that resolves with the query results or null if an error occurred.
- */
- queryScreenpipe: (
- params: ScreenpipeQueryParams
- ) => Promise<ScreenpipeResponse | null>;
-
- /**
- * Extracts a JSON object from a string. Useful for parsing JSON out of drunk LLM responses.
- * @param response - The string to extract the JSON object from.
- * @returns The JSON object.
- */
- extractJsonFromLlmResponse: (response: string) => any;
- };
-
- const fs: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Reads the contents of a directory.
- * @param path - The path to the directory to be read.
- * @returns A promise that resolves with an array of file names in the directory.
- */
- readdir: (path: string) => Promise<string[]>;
-
- /**
- * Creates a new directory.
- * @param path - The path of the directory to be created.
- * @returns A promise that resolves when the directory is created.
- */
- mkdir: (path: string) => Promise<void>;
- };
-
- const path: {
- /**
- * Joins multiple path segments into a single path.
- * @param paths - The path segments to join.
- * @returns The joined path string.
- */
- join: (...paths: string[]) => string;
- };
-
- namespace NodeJS {
- interface ProcessEnv {
- SCREENPIPE_DIR: string;
- SCREENPIPE_LOG_API_URL?: string;
- SCREENPIPE_SERVER_URL?: string;
- PIPE_DIR: string;
- NOTION_DATABASE_ID: string;
- NOTION_API_KEY: string;
- }
- }
- const process: {
- env: NodeJS.ProcessEnv;
- };
-
- /**
- * Types of content that can be queried in Screenpipe.
- */
- type ContentType = "ocr" | "audio" | "all";
-
- /**
- * Parameters for querying Screenpipe.
- */
- interface ScreenpipeQueryParams {
- q?: string;
- content_type?: ContentType;
- limit?: number;
- offset?: number;
- start_time?: string;
- end_time?: string;
- app_name?: string;
- window_name?: string;
- include_frames?: boolean;
- min_length?: number;
- max_length?: number;
- }
-
- /**
- * Structure of OCR (Optical Character Recognition) content.
- */
- interface OCRContent {
- frame_id: number;
- text: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- app_name: string;
- window_name: string;
- tags: string[];
- frame?: string;
- }
-
- /**
- * Structure of audio content.
- */
- interface AudioContent {
- chunk_id: number;
- transcription: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- tags: string[];
- device_name: string;
- device_type: string;
- }
-
- /**
- * Structure of Full Text Search content.
- */
- interface FTSContent {
- text_id: number;
- matched_text: string;
- frame_id: number;
- timestamp: string;
- app_name: string;
- window_name: string;
- file_path: string;
- original_frame_text?: string;
- tags: string[];
- }
-
- /**
- * Union type for different types of content items.
- */
- type ContentItem =
- | { type: "OCR"; content: OCRContent }
- | { type: "Audio"; content: AudioContent }
- | { type: "FTS"; content: FTSContent };
-
- /**
- * Pagination information for search results.
- */
- interface PaginationInfo {
- limit: number;
- offset: number;
- total: number;
- }
-
- /**
- * Structure of the response from a Screenpipe query.
- */
- interface ScreenpipeResponse {
- data: ContentItem[];
- pagination: PaginationInfo;
- }
-}
-
-export {};
diff --git a/examples/typescript/pipe-llama32-comment-linear-while-you-work/tsconfig.json b/examples/typescript/pipe-llama32-comment-linear-while-you-work/tsconfig.json
deleted file mode 100644
index c4e6dfdd7..000000000
--- a/examples/typescript/pipe-llama32-comment-linear-while-you-work/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "esnext",
- "moduleResolution": "node",
- "outDir": "./",
- "rootDir": "./",
- "strict": true,
- "esModuleInterop": true
- },
- "include": [
- "./**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/README.md b/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/README.md
deleted file mode 100644
index 6afa6a69d..000000000
--- a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/README.md
+++ /dev/null
@@ -1,52 +0,0 @@
-# pipe-llama32-sync-user-conversation-to-notion
-
-This pipe automatically summarizes your user conversations (screen text only) and sends the summaries to a Notion database. It uses AI to analyze screen content from your meetings and generate structured tables.
-
-## Quick Setup
-
-1. Run Ollama:
- ```
- ollama run llama3.2:3b-instruct-q4_K_M
- ```
-
-2. Set up Notion:
- a. Create a new integration at https://www.notion.so/my-integrations
- b. Copy the API key for later use
- c. Create a new database in Notion with the following properties:
- - Summary (Title)
- - Key Points (Rich text)
- - Action Items (Rich text)
- - Pain Points (Rich text)
- - Needs (Rich text)
- - Sentiment (Select)
- - Timestamp (Date)
- d. Share the database with your integration:
- - Open the database
- - Click the '...' menu in the top right
- - Go to 'Add connections' and select your integration
- e. Copy the database ID from the URL:
- - Open the database in full-page view
- - The URL will look like: https://www.notion.so/your-workspace/database-id?v=...
- - Copy the 'database-id' part
-
-3. Configure the pipe:
- a. Open the Screenpipe app
- b. Go to the Pipes section
- c. Find or add the "pipe-meeting-summary-by-notion" pipe
- d. Configure the following fields:
- - Polling Interval (default: 3600000 ms / 1 hour)
- - Notion API Key (from step 2b)
- - Notion Database ID (from step 2e)
- - AI API URL (default: http://localhost:11434/api/chat for Ollama)
- - AI Model (default: llama3.2:3b-instruct-q4_K_M)
- - Custom Summary Prompt (optional)
- e. Save the configuration
- f. Enable the pipe
-
-4. Restart Screenpipe recording
-
-That's it! The pipe will now periodically check for new audio content, summarize it using AI, and send the summaries to your Notion database.
-
-## Customization
-
-To customize the pipe's behavior, you can modify the `pipe.ts` file. Key areas you might want to adjust include:
diff --git a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/pipe.json b/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/pipe.json
deleted file mode 100644
index 959826d9a..000000000
--- a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/pipe.json
+++ /dev/null
@@ -1,52 +0,0 @@
-{
- "fields": [
- {
- "name": "pollingInterval",
- "type": "number",
- "default": 60000,
- "description": "interval in milliseconds to poll conversation content (default: 2 minutes)"
- },
- {
- "name": "pollingSize",
- "type": "number",
- "default": 100,
- "description": "number of records to retrieve from Screenpipe per page"
- },
- {
- "name": "windowName",
- "type": "window",
- "default": "",
- "description": "specific window name to filter the conversation data, e.g., 'slack', 'gmail', etc."
- },
- {
- "name": "aiApiUrl",
- "type": "string",
- "default": "http://localhost:11434/api/chat",
- "description": "ai api url, can be ollama, openai, or any openai compatible api"
- },
- {
- "name": "aiModel",
- "type": "string",
- "default": "llama3.2:3b-instruct-q4_K_M",
- "description": "ai model to use for summarizing conversations"
- },
- {
- "name": "notionApiKey",
- "type": "string",
- "default": "<fill your notion api key here>",
- "description": "notion api key for authentication https://www.notion.so/my-integrations"
- },
- {
- "name": "notionDatabaseId",
- "type": "string",
- "default": "<fill your notion database id here>",
- "description": "id of the notion database to sync conversations to eg https://www.notion.so/your-workspace/database-id?v=..."
- },
- {
- "name": "customSummaryPrompt",
- "type": "string",
- "default": "you are an expert in user research and product development, trained in 'the mom test' methodology. analyze this user conversation with the following guidelines:\n\n1. focus on extracting specific examples and stories, not opinions.\n2. identify problems and frustrations the user is currently facing.\n3. uncover the user's current behaviors and workflows.\n4. look for emotional responses and strong reactions.\n5. detect any mentions of money or time investments.\n6. note any alternative solutions the user has tried.\n7. capture any future plans or intended actions.\n8. identify potential product ideas or feature requests.\n9. highlight any misunderstandings or areas of confusion.\n10. detect any 'maybes' or non-committal responses that need further exploration.\n\nremember, good user research is about listening and observing, not pitching or leading the user. extract insights that can drive product decisions and improvements.",
- "description": "custom prompt for the ai to analyze and summarize the conversation"
- }
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/pipe.ts b/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/pipe.ts
deleted file mode 100644
index 51c3e972a..000000000
--- a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/pipe.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-interface ConversationEntry {
- summary: string;
- keyPoints: string[];
- actionItems: string[];
- painPoints: string[];
- needs: string[];
- sentiment: string;
- timestamp: string;
-}
-
-function extractJsonFromLlmResponse(response: string): any {
- // Remove any markdown code block syntax
- let cleaned = response.replace(/^```(?:json)?\s*|\s*```$/g, "");
-
- // Try to find JSON-like content
- const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
- if (jsonMatch) {
- cleaned = jsonMatch[0];
- }
-
- // Remove any non-JSON content before or after the main object
- cleaned = cleaned.replace(/^[^{]*/, "").replace(/[^}]*$/, "");
-
- // Replace any escaped newlines and remove actual newlines
- cleaned = cleaned.replace(/\\n/g, "").replace(/\n/g, "");
-
- try {
- return JSON.parse(cleaned);
- } catch (error) {
- console.warn("failed to parse json:", error);
- console.warn("cleaned content:", cleaned);
-
- // Attempt to fix common issues
- cleaned = cleaned
- .replace(/,\s*}/g, "}") // Remove trailing commas
- .replace(/'/g, '"') // Replace single quotes with double quotes
- .replace(/(\w+):/g, '"$1":') // Add quotes to keys
- .replace(/:\s*'([^']*)'/g, ': "$1"'); // Replace single-quoted values with double-quoted values
-
- try {
- return JSON.parse(cleaned);
- } catch (secondError) {
- console.warn("failed to parse json after attempted fixes:", secondError);
- throw new Error("invalid json format in llm response");
- }
- }
-}
-
-async function summarizeConversation(
- conversationData: ContentItem[],
- aiApiUrl: string,
- aiModel: string,
- customSummaryPrompt: string
-): Promise<ConversationEntry | null> {
- const prompt = `${customSummaryPrompt}
-
- analyze the following conversation:
-
- ${JSON.stringify(conversationData)}
-
- return a json object with the following structure:
- {
- "summary": "brief summary of the conversation",
- "keyPoints": ["key point 1", "key point 2", ...],
- "actionItems": ["action item 1", "action item 2", ...],
- "painPoints": ["pain point 1", "pain point 2", ...],
- "needs": ["need 1", "need 2", ...],
- "sentiment": "positive/neutral/negative"
- }
-
- rules:
- - do not add backticks to the json eg \`\`\`json\`\`\` is wrong
- - do not return anything but json. no comments below the json.
- - if the data does not seem to be related to user conversation, return "false"
- `;
-
- const response = await fetch(aiApiUrl, {
- headers: {
- "Content-Type": "application/json",
- },
- method: "POST",
- body: JSON.stringify({
- model: aiModel,
- messages: [{ role: "user", content: prompt }],
- stream: false,
- response_format: { type: "json_object" },
- }),
- });
-
- if (!response.ok) {
- console.log("ai response:", await response.text());
- throw new Error(`http error! status: ${response.status}`);
- }
-
- const result = await response.json();
- console.log("ai answer:", result);
- if (result.message.content === "false") {
- return null;
- }
-
- let content;
- try {
- content = extractJsonFromLlmResponse(result.message.content);
- } catch (error) {
- console.warn("failed to parse ai response:", error, result);
- throw new Error("invalid ai response format");
- }
-
- return {
- ...content,
- timestamp: new Date().toISOString(),
- };
-}
-
-async function addToNotion(
- notionApiKey: string,
- databaseId: string,
- entry: ConversationEntry
-): Promise<void> {
- const response = await fetch(`https://api.notion.com/v1/pages`, {
- method: "POST",
- headers: {
- Authorization: `Bearer ${notionApiKey}`,
- "Notion-Version": "2022-06-28",
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- parent: { database_id: databaseId },
- properties: {
- "Summary": { title: [{ text: { content: entry.summary } }] },
- "Key Points": {
- rich_text: [{ text: { content: entry.keyPoints.join(", ") } }],
- },
- "Action Items": {
- rich_text: [{ text: { content: entry.actionItems.join(", ") } }],
- },
- "Pain Points": {
- rich_text: [{ text: { content: entry.painPoints.join(", ") } }],
- },
- "Needs": { rich_text: [{ text: { content: entry.needs.join(", ") } }] },
- "Sentiment": { select: { name: entry.sentiment } },
- "Timestamp": { date: { start: entry.timestamp } },
- },
- }),
- });
-
- if (!response.ok) {
- throw new Error(`failed to add to notion: ${response.statusText}`);
- }
-
- console.log("successfully added to notion");
-}
-
-async function syncConversationPipeline(): Promise<void> {
- console.log("starting conversation sync pipeline");
-
- const config = await pipe.loadConfig();
- console.log("loaded config:", JSON.stringify(config, null, 2));
-
- const {
- pollingInterval,
- windowName,
- aiApiUrl,
- aiModel,
- notionApiKey,
- notionDatabaseId,
- customSummaryPrompt,
- } = config;
-
- while (true) {
- try {
- const now = new Date();
- const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
-
- const conversationData = await pipe.queryScreenpipe({
- start_time: fiveMinutesAgo.toISOString(),
- end_time: now.toISOString(),
- window_name: windowName,
- content_type: "ocr",
- limit: 1000,
- });
-
- if (
- conversationData &&
- conversationData.data &&
- conversationData.data.length > 0
- ) {
- const summary = await summarizeConversation(
- conversationData.data,
- aiApiUrl,
- aiModel,
- customSummaryPrompt
- );
- if (!summary) {
- console.log("no summary found");
- continue;
- }
- console.log("conversation summary:", summary);
-
- await addToNotion(notionApiKey, notionDatabaseId, summary);
- console.log("added to notion");
- }
- } catch (error) {
- console.warn("error in conversation sync pipeline:", error);
- }
- console.log("sleeping for", pollingInterval, "ms");
- await new Promise((resolve) => setTimeout(resolve, pollingInterval));
- }
-}
-
-syncConversationPipeline();
diff --git a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/screenpipe.d.ts b/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/screenpipe.d.ts
deleted file mode 100644
index 820e1a2d0..000000000
--- a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/screenpipe.d.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-declare global {
- const pipe: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Removes a file.
- * @param path - The path to the file to be removed.
- * @returns A promise that resolves when the file is removed.
- */
- removeFile: (path: string) => Promise<void>;
-
- /**
- * Performs a GET request to the specified URL.
- * @param url - The URL to send the GET request to.
- * @returns A promise that resolves with the response data.
- */
- get: (url: string) => Promise<any>;
-
- /**
- * Performs a POST request to the specified URL.
- * @param url - The URL to send the POST request to.
- * @param body - The body of the POST request.
- * @returns A promise that resolves with the response data.
- */
- post: (url: string, body: string) => Promise<any>;
-
- /**
- * Performs a fetch request.
- * @param url - The URL to fetch.
- * @param options - Optional fetch options.
- * @returns A promise that resolves with the fetch response.
- */
- fetch: (url: string, options?: RequestInit) => Promise<Response>;
-
- /**
- * Sends a notification.
- * @param options - The notification options.
- * @returns A promise that resolves when the notification is sent.
- */
- sendNotification: (options: {
- title: string;
- body: string;
- }) => Promise<any>;
-
- /**
- * Loads the configuration for the pipe.
- * @returns A promise that resolves with the configuration object.
- */
- loadConfig: () => Promise<Record<string, any>>;
-
- /**
- * The current configuration of the pipe.
- */
- config: Record<string, any>;
-
- /**
- * Metadata about the current pipe.
- */
- metadata: {
- id: string;
- };
-
- /**
- * Sends an email.
- * @param options - The email options.
- * @returns A promise that resolves to true if the email was sent successfully, false otherwise.
- */
- sendEmail: (options: {
- to: string;
- from: string;
- password: string;
- subject: string;
- body: string;
- }) => Promise<boolean>;
-
- /**
- * Queries the Screenpipe database.
- * @param params - The query parameters.
- * @returns A promise that resolves with the query results or null if an error occurred.
- */
- queryScreenpipe: (
- params: ScreenpipeQueryParams
- ) => Promise<ScreenpipeResponse | null>;
- };
-
- const fs: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Reads the contents of a directory.
- * @param path - The path to the directory to be read.
- * @returns A promise that resolves with an array of file names in the directory.
- */
- readdir: (path: string) => Promise<string[]>;
-
- /**
- * Creates a new directory.
- * @param path - The path of the directory to be created.
- * @returns A promise that resolves when the directory is created.
- */
- mkdir: (path: string) => Promise<void>;
- };
-
- const path: {
- /**
- * Joins multiple path segments into a single path.
- * @param paths - The path segments to join.
- * @returns The joined path string.
- */
- join: (...paths: string[]) => string;
- };
-
- namespace NodeJS {
- interface ProcessEnv {
- SCREENPIPE_DIR: string;
- SCREENPIPE_LOG_API_URL?: string;
- SCREENPIPE_SERVER_URL?: string;
- PIPE_DIR: string;
- NOTION_DATABASE_ID: string;
- NOTION_API_KEY: string;
- }
- }
- const process: {
- env: NodeJS.ProcessEnv;
- };
-
- /**
- * Types of content that can be queried in Screenpipe.
- */
- type ContentType = "ocr" | "audio" | "all";
-
- /**
- * Parameters for querying Screenpipe.
- */
- interface ScreenpipeQueryParams {
- q?: string;
- content_type?: ContentType;
- limit?: number;
- offset?: number;
- start_time?: string;
- end_time?: string;
- app_name?: string;
- window_name?: string;
- include_frames?: boolean;
- min_length?: number;
- max_length?: number;
- }
-
- /**
- * Structure of OCR (Optical Character Recognition) content.
- */
- interface OCRContent {
- frame_id: number;
- text: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- app_name: string;
- window_name: string;
- tags: string[];
- frame?: string;
- }
-
- /**
- * Structure of audio content.
- */
- interface AudioContent {
- chunk_id: number;
- transcription: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- tags: string[];
- device_name: string;
- device_type: string;
- }
-
- /**
- * Structure of Full Text Search content.
- */
- interface FTSContent {
- text_id: number;
- matched_text: string;
- frame_id: number;
- timestamp: string;
- app_name: string;
- window_name: string;
- file_path: string;
- original_frame_text?: string;
- tags: string[];
- }
-
- /**
- * Union type for different types of content items.
- */
- type ContentItem =
- | { type: "OCR"; content: OCRContent }
- | { type: "Audio"; content: AudioContent }
- | { type: "FTS"; content: FTSContent };
-
- /**
- * Pagination information for search results.
- */
- interface PaginationInfo {
- limit: number;
- offset: number;
- total: number;
- }
-
- /**
- * Structure of the response from a Screenpipe query.
- */
- interface ScreenpipeResponse {
- data: ContentItem[];
- pagination: PaginationInfo;
- }
-}
-
-export {};
diff --git a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/tsconfig.json b/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/tsconfig.json
deleted file mode 100644
index c4e6dfdd7..000000000
--- a/examples/typescript/pipe-llama32-sync-user-conversation-to-notion/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "esnext",
- "moduleResolution": "node",
- "outDir": "./",
- "rootDir": "./",
- "strict": true,
- "esModuleInterop": true
- },
- "include": [
- "./**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-meeting-summary-by-email/deno.json b/examples/typescript/pipe-meeting-summary-by-email/deno.json
new file mode 100644
index 000000000..d707298e3
--- /dev/null
+++ b/examples/typescript/pipe-meeting-summary-by-email/deno.json
@@ -0,0 +1,6 @@
+{
+ "imports": {
+ "nodemailer": "npm:nodemailer",
+ "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/deno-thru-cli/screenpipe-js/main.ts"
+ }
+}
\ No newline at end of file
diff --git a/examples/typescript/pipe-meeting-summary-by-email/pipe.ts b/examples/typescript/pipe-meeting-summary-by-email/pipe.ts
index 4cf3b115e..0027c9b8c 100644
--- a/examples/typescript/pipe-meeting-summary-by-email/pipe.ts
+++ b/examples/typescript/pipe-meeting-summary-by-email/pipe.ts
@@ -1,3 +1,11 @@
+import {
+ queryScreenpipe,
+ loadPipeConfig,
+ ContentItem,
+ extractJsonFromLlmResponse,
+} from "screenpipe";
+import nodemailer from "nodemailer";
+
async function summarizeAudio(
audioData: ContentItem[],
aiApiUrl: string,
@@ -38,15 +46,26 @@ async function sendEmail(
subject: string,
body: string
): Promise<void> {
- const from = to;
- const result = await pipe.sendEmail({
- to,
- from,
- password,
- subject,
- body,
+ // Create a transporter using SMTP
+ const transporter = nodemailer.createTransport({
+ host: "smtp.gmail.com", // Replace with your SMTP server
+ port: 587,
+ secure: false, // Use TLS
+ auth: {
+ user: to, // assuming the sender is the same as the recipient
+ pass: password,
+ },
});
- if (!result) {
+
+ // Send mail with defined transport object
+ const info = await transporter.sendMail({
+ from: to, // sender address
+ to: to, // list of receivers
+ subject: subject, // Subject line
+ text: body, // plain text body
+ });
+
+ if (!info) {
throw new Error("failed to send email");
}
console.log(`email sent to ${to} with subject: ${subject}`);
@@ -114,48 +133,10 @@ async function checkTimeAdjustment(
return content;
}
-function extractJsonFromLlmResponse(response: string): any {
- // Remove any markdown code block syntax
- let cleaned = response.replace(/^```(?:json)?\s*|\s*```$/g, "");
-
- // Try to find JSON-like content
- const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
- if (jsonMatch) {
- cleaned = jsonMatch[0];
- }
-
- // Remove any non-JSON content before or after the main object
- cleaned = cleaned.replace(/^[^{]*/, "").replace(/[^}]*$/, "");
-
- // Replace any escaped newlines and remove actual newlines
- cleaned = cleaned.replace(/\\n/g, "").replace(/\n/g, "");
-
- try {
- return JSON.parse(cleaned);
- } catch (error) {
- console.warn("failed to parse json:", error);
- console.warn("cleaned content:", cleaned);
-
- // Attempt to fix common issues
- cleaned = cleaned
- .replace(/,\s*}/g, "}") // Remove trailing commas
- .replace(/'/g, '"') // Replace single quotes with double quotes
- .replace(/(\w+):/g, '"$1":') // Add quotes to keys
- .replace(/:\s*'([^']*)'/g, ': "$1"'); // Replace single-quoted values with double-quoted values
-
- try {
- return JSON.parse(cleaned);
- } catch (secondError) {
- console.warn("failed to parse json after attempted fixes:", secondError);
- throw new Error("invalid json format in llm response");
- }
- }
-}
-
async function meetingSummaryPipeline(): Promise<void> {
console.log("starting meeting summary pipeline");
- const config = await pipe.loadConfig();
+ const config = await loadPipeConfig();
console.log("loaded config:", JSON.stringify(config, null, 2));
const {
@@ -180,10 +161,10 @@ async function meetingSummaryPipeline(): Promise<void> {
console.log("oneHourAgo:", oneHourAgo);
console.log("now:", now);
- let audioData = await pipe.queryScreenpipe({
- start_time: oneHourAgo.toISOString(),
- end_time: now.toISOString(),
- content_type: "audio",
+ const audioData = await queryScreenpipe({
+ startTime: oneHourAgo.toISOString(),
+ endTime: now.toISOString(),
+ contentType: "audio",
limit: 10_000,
});
@@ -216,10 +197,10 @@ async function meetingSummaryPipeline(): Promise<void> {
console.log("New end:", adjustedEnd);
// Query additional data
- const additionalData = await pipe.queryScreenpipe({
- start_time: adjustedStart.toISOString(),
- end_time: adjustedEnd.toISOString(),
- content_type: "audio",
+ const additionalData = await queryScreenpipe({
+ startTime: adjustedStart.toISOString(),
+ endTime: adjustedEnd.toISOString(),
+ contentType: "audio",
limit: 10_000,
});
diff --git a/examples/typescript/pipe-meeting-summary-by-email/screenpipe.d.ts b/examples/typescript/pipe-meeting-summary-by-email/screenpipe.d.ts
deleted file mode 100644
index 820e1a2d0..000000000
--- a/examples/typescript/pipe-meeting-summary-by-email/screenpipe.d.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-declare global {
- const pipe: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Removes a file.
- * @param path - The path to the file to be removed.
- * @returns A promise that resolves when the file is removed.
- */
- removeFile: (path: string) => Promise<void>;
-
- /**
- * Performs a GET request to the specified URL.
- * @param url - The URL to send the GET request to.
- * @returns A promise that resolves with the response data.
- */
- get: (url: string) => Promise<any>;
-
- /**
- * Performs a POST request to the specified URL.
- * @param url - The URL to send the POST request to.
- * @param body - The body of the POST request.
- * @returns A promise that resolves with the response data.
- */
- post: (url: string, body: string) => Promise<any>;
-
- /**
- * Performs a fetch request.
- * @param url - The URL to fetch.
- * @param options - Optional fetch options.
- * @returns A promise that resolves with the fetch response.
- */
- fetch: (url: string, options?: RequestInit) => Promise<Response>;
-
- /**
- * Sends a notification.
- * @param options - The notification options.
- * @returns A promise that resolves when the notification is sent.
- */
- sendNotification: (options: {
- title: string;
- body: string;
- }) => Promise<any>;
-
- /**
- * Loads the configuration for the pipe.
- * @returns A promise that resolves with the configuration object.
- */
- loadConfig: () => Promise<Record<string, any>>;
-
- /**
- * The current configuration of the pipe.
- */
- config: Record<string, any>;
-
- /**
- * Metadata about the current pipe.
- */
- metadata: {
- id: string;
- };
-
- /**
- * Sends an email.
- * @param options - The email options.
- * @returns A promise that resolves to true if the email was sent successfully, false otherwise.
- */
- sendEmail: (options: {
- to: string;
- from: string;
- password: string;
- subject: string;
- body: string;
- }) => Promise<boolean>;
-
- /**
- * Queries the Screenpipe database.
- * @param params - The query parameters.
- * @returns A promise that resolves with the query results or null if an error occurred.
- */
- queryScreenpipe: (
- params: ScreenpipeQueryParams
- ) => Promise<ScreenpipeResponse | null>;
- };
-
- const fs: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Reads the contents of a directory.
- * @param path - The path to the directory to be read.
- * @returns A promise that resolves with an array of file names in the directory.
- */
- readdir: (path: string) => Promise<string[]>;
-
- /**
- * Creates a new directory.
- * @param path - The path of the directory to be created.
- * @returns A promise that resolves when the directory is created.
- */
- mkdir: (path: string) => Promise<void>;
- };
-
- const path: {
- /**
- * Joins multiple path segments into a single path.
- * @param paths - The path segments to join.
- * @returns The joined path string.
- */
- join: (...paths: string[]) => string;
- };
-
- namespace NodeJS {
- interface ProcessEnv {
- SCREENPIPE_DIR: string;
- SCREENPIPE_LOG_API_URL?: string;
- SCREENPIPE_SERVER_URL?: string;
- PIPE_DIR: string;
- NOTION_DATABASE_ID: string;
- NOTION_API_KEY: string;
- }
- }
- const process: {
- env: NodeJS.ProcessEnv;
- };
-
- /**
- * Types of content that can be queried in Screenpipe.
- */
- type ContentType = "ocr" | "audio" | "all";
-
- /**
- * Parameters for querying Screenpipe.
- */
- interface ScreenpipeQueryParams {
- q?: string;
- content_type?: ContentType;
- limit?: number;
- offset?: number;
- start_time?: string;
- end_time?: string;
- app_name?: string;
- window_name?: string;
- include_frames?: boolean;
- min_length?: number;
- max_length?: number;
- }
-
- /**
- * Structure of OCR (Optical Character Recognition) content.
- */
- interface OCRContent {
- frame_id: number;
- text: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- app_name: string;
- window_name: string;
- tags: string[];
- frame?: string;
- }
-
- /**
- * Structure of audio content.
- */
- interface AudioContent {
- chunk_id: number;
- transcription: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- tags: string[];
- device_name: string;
- device_type: string;
- }
-
- /**
- * Structure of Full Text Search content.
- */
- interface FTSContent {
- text_id: number;
- matched_text: string;
- frame_id: number;
- timestamp: string;
- app_name: string;
- window_name: string;
- file_path: string;
- original_frame_text?: string;
- tags: string[];
- }
-
- /**
- * Union type for different types of content items.
- */
- type ContentItem =
- | { type: "OCR"; content: OCRContent }
- | { type: "Audio"; content: AudioContent }
- | { type: "FTS"; content: FTSContent };
-
- /**
- * Pagination information for search results.
- */
- interface PaginationInfo {
- limit: number;
- offset: number;
- total: number;
- }
-
- /**
- * Structure of the response from a Screenpipe query.
- */
- interface ScreenpipeResponse {
- data: ContentItem[];
- pagination: PaginationInfo;
- }
-}
-
-export {};
diff --git a/examples/typescript/pipe-meeting-summary-by-email/tsconfig.json b/examples/typescript/pipe-meeting-summary-by-email/tsconfig.json
deleted file mode 100644
index c4e6dfdd7..000000000
--- a/examples/typescript/pipe-meeting-summary-by-email/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "esnext",
- "moduleResolution": "node",
- "outDir": "./",
- "rootDir": "./",
- "strict": true,
- "esModuleInterop": true
- },
- "include": [
- "./**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.json b/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.json
new file mode 100644
index 000000000..1b28405fa
--- /dev/null
+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.json
@@ -0,0 +1,5 @@
+{
+ "imports": {
+ "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/deno-thru-cli/screenpipe-js/main.ts"
+ }
+}
\ No newline at end of file
diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts
index af78836fc..d6257a615 100644
--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts
+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts
@@ -1,3 +1,4 @@
+import { queryScreenpipe, loadPipeConfig, ContentItem } from "screenpipe";
const NOTION_API_URL = "https://api.notion.com/v1/pages";
interface EngineeringLog {
@@ -94,7 +95,7 @@ async function syncLogToNotion(
async function streamEngineeringLogsToNotion(): Promise<void> {
console.log("Starting Engineering Logs Stream to Notion");
- const config = await pipe.loadConfig();
+ const config = await loadPipeConfig();
console.log("loaded config:", JSON.stringify(config, null, 2));
const interval = config.interval * 1000;
@@ -108,11 +109,11 @@ async function streamEngineeringLogsToNotion(): Promise<void> {
const now = new Date();
const oneHourAgo = new Date(now.getTime() - interval);
- const screenData = await pipe.queryScreenpipe({
- start_time: oneHourAgo.toISOString(),
- end_time: now.toISOString(),
+ const screenData = await queryScreenpipe({
+ startTime: oneHourAgo.toISOString(),
+ endTime: now.toISOString(),
limit: 50,
- content_type: "ocr",
+ contentType: "ocr",
});
if (screenData && screenData.data.length > 0) {
diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/screenpipe.d.ts b/examples/typescript/pipe-phi3.5-engineering-team-logs/screenpipe.d.ts
deleted file mode 100644
index 820e1a2d0..000000000
--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/screenpipe.d.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-declare global {
- const pipe: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Removes a file.
- * @param path - The path to the file to be removed.
- * @returns A promise that resolves when the file is removed.
- */
- removeFile: (path: string) => Promise<void>;
-
- /**
- * Performs a GET request to the specified URL.
- * @param url - The URL to send the GET request to.
- * @returns A promise that resolves with the response data.
- */
- get: (url: string) => Promise<any>;
-
- /**
- * Performs a POST request to the specified URL.
- * @param url - The URL to send the POST request to.
- * @param body - The body of the POST request.
- * @returns A promise that resolves with the response data.
- */
- post: (url: string, body: string) => Promise<any>;
-
- /**
- * Performs a fetch request.
- * @param url - The URL to fetch.
- * @param options - Optional fetch options.
- * @returns A promise that resolves with the fetch response.
- */
- fetch: (url: string, options?: RequestInit) => Promise<Response>;
-
- /**
- * Sends a notification.
- * @param options - The notification options.
- * @returns A promise that resolves when the notification is sent.
- */
- sendNotification: (options: {
- title: string;
- body: string;
- }) => Promise<any>;
-
- /**
- * Loads the configuration for the pipe.
- * @returns A promise that resolves with the configuration object.
- */
- loadConfig: () => Promise<Record<string, any>>;
-
- /**
- * The current configuration of the pipe.
- */
- config: Record<string, any>;
-
- /**
- * Metadata about the current pipe.
- */
- metadata: {
- id: string;
- };
-
- /**
- * Sends an email.
- * @param options - The email options.
- * @returns A promise that resolves to true if the email was sent successfully, false otherwise.
- */
- sendEmail: (options: {
- to: string;
- from: string;
- password: string;
- subject: string;
- body: string;
- }) => Promise<boolean>;
-
- /**
- * Queries the Screenpipe database.
- * @param params - The query parameters.
- * @returns A promise that resolves with the query results or null if an error occurred.
- */
- queryScreenpipe: (
- params: ScreenpipeQueryParams
- ) => Promise<ScreenpipeResponse | null>;
- };
-
- const fs: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Reads the contents of a directory.
- * @param path - The path to the directory to be read.
- * @returns A promise that resolves with an array of file names in the directory.
- */
- readdir: (path: string) => Promise<string[]>;
-
- /**
- * Creates a new directory.
- * @param path - The path of the directory to be created.
- * @returns A promise that resolves when the directory is created.
- */
- mkdir: (path: string) => Promise<void>;
- };
-
- const path: {
- /**
- * Joins multiple path segments into a single path.
- * @param paths - The path segments to join.
- * @returns The joined path string.
- */
- join: (...paths: string[]) => string;
- };
-
- namespace NodeJS {
- interface ProcessEnv {
- SCREENPIPE_DIR: string;
- SCREENPIPE_LOG_API_URL?: string;
- SCREENPIPE_SERVER_URL?: string;
- PIPE_DIR: string;
- NOTION_DATABASE_ID: string;
- NOTION_API_KEY: string;
- }
- }
- const process: {
- env: NodeJS.ProcessEnv;
- };
-
- /**
- * Types of content that can be queried in Screenpipe.
- */
- type ContentType = "ocr" | "audio" | "all";
-
- /**
- * Parameters for querying Screenpipe.
- */
- interface ScreenpipeQueryParams {
- q?: string;
- content_type?: ContentType;
- limit?: number;
- offset?: number;
- start_time?: string;
- end_time?: string;
- app_name?: string;
- window_name?: string;
- include_frames?: boolean;
- min_length?: number;
- max_length?: number;
- }
-
- /**
- * Structure of OCR (Optical Character Recognition) content.
- */
- interface OCRContent {
- frame_id: number;
- text: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- app_name: string;
- window_name: string;
- tags: string[];
- frame?: string;
- }
-
- /**
- * Structure of audio content.
- */
- interface AudioContent {
- chunk_id: number;
- transcription: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- tags: string[];
- device_name: string;
- device_type: string;
- }
-
- /**
- * Structure of Full Text Search content.
- */
- interface FTSContent {
- text_id: number;
- matched_text: string;
- frame_id: number;
- timestamp: string;
- app_name: string;
- window_name: string;
- file_path: string;
- original_frame_text?: string;
- tags: string[];
- }
-
- /**
- * Union type for different types of content items.
- */
- type ContentItem =
- | { type: "OCR"; content: OCRContent }
- | { type: "Audio"; content: AudioContent }
- | { type: "FTS"; content: FTSContent };
-
- /**
- * Pagination information for search results.
- */
- interface PaginationInfo {
- limit: number;
- offset: number;
- total: number;
- }
-
- /**
- * Structure of the response from a Screenpipe query.
- */
- interface ScreenpipeResponse {
- data: ContentItem[];
- pagination: PaginationInfo;
- }
-}
-
-export {};
diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/tsconfig.json b/examples/typescript/pipe-phi3.5-engineering-team-logs/tsconfig.json
deleted file mode 100644
index c4e6dfdd7..000000000
--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "esnext",
- "moduleResolution": "node",
- "outDir": "./",
- "rootDir": "./",
- "strict": true,
- "esModuleInterop": true
- },
- "include": [
- "./**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-post-questions-on-reddit/deno.json b/examples/typescript/pipe-post-questions-on-reddit/deno.json
new file mode 100644
index 000000000..1ba1da3e3
--- /dev/null
+++ b/examples/typescript/pipe-post-questions-on-reddit/deno.json
@@ -0,0 +1,7 @@
+{
+ "imports": {
+ "fs": "node:fs",
+ "nodemailer": "npm:nodemailer",
+ "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/deno-thru-cli/screenpipe-js/main.ts"
+ }
+}
\ No newline at end of file
diff --git a/examples/typescript/pipe-post-questions-on-reddit/pipe.ts b/examples/typescript/pipe-post-questions-on-reddit/pipe.ts
index 63eb74a48..c04070a1d 100644
--- a/examples/typescript/pipe-post-questions-on-reddit/pipe.ts
+++ b/examples/typescript/pipe-post-questions-on-reddit/pipe.ts
@@ -1,3 +1,8 @@
+import * as fs from "fs";
+import nodemailer from "nodemailer";
+import { queryScreenpipe, loadPipeConfig, ContentItem } from "screenpipe";
+import process from "node:process";
+
interface DailyLog {
activity: string;
category: string;
@@ -36,7 +41,7 @@ async function generateDailyLog(
method: "POST",
headers: {
"Content-Type": "application/json",
- "Authorization": `Bearer ${openaiApiKey}`,
+ Authorization: `Bearer ${openaiApiKey}`,
},
body: JSON.stringify({
model: gptModel,
@@ -73,7 +78,7 @@ async function generateDailyLog(
return content;
}
-async function saveDailyLog(logEntry: DailyLog): Promise<void> {
+function saveDailyLog(logEntry: DailyLog): void {
console.log("creating logs dir");
const logsDir = `${process.env.PIPE_DIR}/logs`;
console.log("logs dir:", logsDir);
@@ -85,15 +90,12 @@ async function saveDailyLog(logEntry: DailyLog): Promise<void> {
.replace(/\..+/, "");
const filename = `${timestamp}-${logEntry.category.replace("/", "-")}.json`;
console.log("filename:", filename);
- await fs.writeFile(
- `${logsDir}/${filename}`,
- JSON.stringify(logEntry, null, 2)
- );
+ fs.writeFileSync(`${logsDir}/${filename}`, JSON.stringify(logEntry, null, 2));
}
function generateRedditLinks(content: string): string {
const posts = content.split(/\[\d+\]/g).filter(Boolean);
- let result = '';
+ let result = "";
posts.forEach((post, index) => {
const titleMatch = post.match(/\[TITLE\](.*?)\[\/TITLE\]/s);
@@ -108,13 +110,13 @@ function generateRedditLinks(content: string): string {
result += `[${index + 1}] ${title}\n\n${body}\n\n`;
- subredditsMatch.forEach(subreddit => {
+ subredditsMatch.forEach((subreddit) => {
const subredditName = subreddit.slice(2, -1);
const link = `https://www.reddit.com/r/${subredditName}/submit?title=${encodedTitle}&text=${encodedBody}`;
result += `${subreddit} <a href="${link}">SEND</a>\n`;
});
- result += '\n';
+ result += "\n";
}
});
@@ -150,7 +152,7 @@ async function generateRedditQuestions(
method: "POST",
headers: {
"Content-Type": "application/json",
- "Authorization": `Bearer ${openaiApiKey}`,
+ Authorization: `Bearer ${openaiApiKey}`,
},
body: JSON.stringify({
model: gptModel,
@@ -172,75 +174,41 @@ async function generateRedditQuestions(
return generateRedditLinks(content);
}
-async function retry<T>(
- fn: () => Promise<T>,
- maxAttempts: number = 3,
- delay: number = 3000
-): Promise<T> {
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
- try {
- return await fn();
- } catch (error) {
- if (attempt === maxAttempts) {
- throw error;
- }
- console.log(`attempt ${attempt} failed, retrying in ${delay}ms...`);
- await new Promise((resolve) => setTimeout(resolve, delay));
- }
- }
- throw new Error("this should never happen");
-}
-
async function sendEmail(
to: string,
password: string,
subject: string,
body: string
): Promise<void> {
- const from = to; // assuming the sender is the same as the recipient
- await retry(async () => {
- const result = await pipe.sendEmail({
- to,
- from,
- password,
- subject,
- body,
- });
- if (!result) {
- throw new Error("failed to send email");
- }
- console.log(`email sent to ${to} with subject: ${subject}`);
+ // Create a transporter using SMTP
+ const transporter = nodemailer.createTransport({
+ host: "smtp.gmail.com", // Replace with your SMTP server
+ port: 587,
+ secure: false, // Use TLS
+ auth: {
+ user: to, // assuming the sender is the same as the recipient
+ pass: password,
+ },
});
-}
-async function getTodayLogs(): Promise<DailyLog[]> {
- try {
- const logsDir = `${process.env.PIPE_DIR}/logs`;
- const today = new Date().toISOString().replace(/:/g, "-").split("T")[0]; // Get today's date in YYYY-MM-DD format
-
- console.log("reading logs dir:", logsDir);
- const files = await fs.readdir(logsDir);
- console.log("files:", files);
- const todayFiles = files.filter((file) => file.startsWith(today));
- console.log("today's files:", todayFiles);
-
- const logs: DailyLog[] = [];
- for (const file of todayFiles) {
- const content = await fs.readFile(`${logsDir}/${file}`);
- logs.push(JSON.parse(content));
- }
+ // Send mail with defined transport object
+ const info = await transporter.sendMail({
+ from: to, // sender address
+ to: to, // list of receivers
+ subject: subject, // Subject line
+ text: body, // plain text body
+ });
- return logs;
- } catch (error) {
- console.warn("error getting today's logs:", error);
- return [];
+ if (!info) {
+ throw new Error("failed to send email");
}
+ console.log(`email sent to ${to} with subject: ${subject}`);
}
async function dailyLogPipeline(): Promise<void> {
console.log("starting daily log pipeline");
- const config = await pipe.loadConfig();
+ const config = await loadPipeConfig();
console.log("loaded config:", JSON.stringify(config, null, 2));
const interval = config.interval * 1000;
@@ -260,9 +228,11 @@ async function dailyLogPipeline(): Promise<void> {
console.log("creating logs dir");
const logsDir = `${process.env.PIPE_DIR}/logs`;
console.log("logs dir:", logsDir);
- await fs.mkdir(logsDir).catch((error) => {
- console.warn("error creating logs dir:", error);
- });
+ try {
+ fs.mkdirSync(logsDir);
+ } catch (_error) {
+ console.warn("failed to create logs dir, probably already exists");
+ }
let lastEmailSent = new Date(0); // Initialize to a past date
@@ -290,18 +260,18 @@ async function dailyLogPipeline(): Promise<void> {
const now = new Date();
const oneMinuteAgo = new Date(now.getTime() - interval);
- const screenData = await pipe.queryScreenpipe({
- start_time: oneMinuteAgo.toISOString(),
- end_time: now.toISOString(),
- window_name: windowName,
+ const screenData = await queryScreenpipe({
+ startTime: oneMinuteAgo.toISOString(),
+ endTime: now.toISOString(),
+ windowName: windowName,
limit: pageSize,
- content_type: contentType,
+ contentType: contentType,
});
if (screenData && screenData.data && screenData.data.length > 0) {
const logEntry = await generateDailyLog(
screenData.data,
- dailylogPrompt, // Use dailylogPrompt here instead of customPrompt
+ dailylogPrompt, // Use dailylogPrompt here instead of customPrompt
gptModel,
gptApiUrl,
openaiApiKey
@@ -331,12 +301,12 @@ async function dailyLogPipeline(): Promise<void> {
}
if (shouldSendSummary) {
- const screenData = await pipe.queryScreenpipe({
- start_time: oneMinuteAgo.toISOString(),
- end_time: now.toISOString(),
- window_name: windowName,
+ const screenData = await queryScreenpipe({
+ startTime: oneMinuteAgo.toISOString(),
+ endTime: now.toISOString(),
+ windowName: windowName,
limit: pageSize,
- content_type: contentType,
+ contentType: contentType,
});
if (screenData && screenData.data && screenData.data.length > 0) {
diff --git a/examples/typescript/pipe-post-questions-on-reddit/screenpipe.d.ts b/examples/typescript/pipe-post-questions-on-reddit/screenpipe.d.ts
deleted file mode 100644
index 820e1a2d0..000000000
--- a/examples/typescript/pipe-post-questions-on-reddit/screenpipe.d.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-declare global {
- const pipe: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Removes a file.
- * @param path - The path to the file to be removed.
- * @returns A promise that resolves when the file is removed.
- */
- removeFile: (path: string) => Promise<void>;
-
- /**
- * Performs a GET request to the specified URL.
- * @param url - The URL to send the GET request to.
- * @returns A promise that resolves with the response data.
- */
- get: (url: string) => Promise<any>;
-
- /**
- * Performs a POST request to the specified URL.
- * @param url - The URL to send the POST request to.
- * @param body - The body of the POST request.
- * @returns A promise that resolves with the response data.
- */
- post: (url: string, body: string) => Promise<any>;
-
- /**
- * Performs a fetch request.
- * @param url - The URL to fetch.
- * @param options - Optional fetch options.
- * @returns A promise that resolves with the fetch response.
- */
- fetch: (url: string, options?: RequestInit) => Promise<Response>;
-
- /**
- * Sends a notification.
- * @param options - The notification options.
- * @returns A promise that resolves when the notification is sent.
- */
- sendNotification: (options: {
- title: string;
- body: string;
- }) => Promise<any>;
-
- /**
- * Loads the configuration for the pipe.
- * @returns A promise that resolves with the configuration object.
- */
- loadConfig: () => Promise<Record<string, any>>;
-
- /**
- * The current configuration of the pipe.
- */
- config: Record<string, any>;
-
- /**
- * Metadata about the current pipe.
- */
- metadata: {
- id: string;
- };
-
- /**
- * Sends an email.
- * @param options - The email options.
- * @returns A promise that resolves to true if the email was sent successfully, false otherwise.
- */
- sendEmail: (options: {
- to: string;
- from: string;
- password: string;
- subject: string;
- body: string;
- }) => Promise<boolean>;
-
- /**
- * Queries the Screenpipe database.
- * @param params - The query parameters.
- * @returns A promise that resolves with the query results or null if an error occurred.
- */
- queryScreenpipe: (
- params: ScreenpipeQueryParams
- ) => Promise<ScreenpipeResponse | null>;
- };
-
- const fs: {
- /**
- * Reads the contents of a file.
- * @param path - The path to the file to be read.
- * @returns A promise that resolves with the file contents as a string.
- */
- readFile: (path: string) => Promise<string>;
-
- /**
- * Writes content to a file.
- * @param path - The path to the file to be written.
- * @param contents - The content to write to the file.
- * @returns A promise that resolves when the write operation is complete.
- */
- writeFile: (path: string, contents: string) => Promise<void>;
-
- /**
- * Reads the contents of a directory.
- * @param path - The path to the directory to be read.
- * @returns A promise that resolves with an array of file names in the directory.
- */
- readdir: (path: string) => Promise<string[]>;
-
- /**
- * Creates a new directory.
- * @param path - The path of the directory to be created.
- * @returns A promise that resolves when the directory is created.
- */
- mkdir: (path: string) => Promise<void>;
- };
-
- const path: {
- /**
- * Joins multiple path segments into a single path.
- * @param paths - The path segments to join.
- * @returns The joined path string.
- */
- join: (...paths: string[]) => string;
- };
-
- namespace NodeJS {
- interface ProcessEnv {
- SCREENPIPE_DIR: string;
- SCREENPIPE_LOG_API_URL?: string;
- SCREENPIPE_SERVER_URL?: string;
- PIPE_DIR: string;
- NOTION_DATABASE_ID: string;
- NOTION_API_KEY: string;
- }
- }
- const process: {
- env: NodeJS.ProcessEnv;
- };
-
- /**
- * Types of content that can be queried in Screenpipe.
- */
- type ContentType = "ocr" | "audio" | "all";
-
- /**
- * Parameters for querying Screenpipe.
- */
- interface ScreenpipeQueryParams {
- q?: string;
- content_type?: ContentType;
- limit?: number;
- offset?: number;
- start_time?: string;
- end_time?: string;
- app_name?: string;
- window_name?: string;
- include_frames?: boolean;
- min_length?: number;
- max_length?: number;
- }
-
- /**
- * Structure of OCR (Optical Character Recognition) content.
- */
- interface OCRContent {
- frame_id: number;
- text: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- app_name: string;
- window_name: string;
- tags: string[];
- frame?: string;
- }
-
- /**
- * Structure of audio content.
- */
- interface AudioContent {
- chunk_id: number;
- transcription: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- tags: string[];
- device_name: string;
- device_type: string;
- }
-
- /**
- * Structure of Full Text Search content.
- */
- interface FTSContent {
- text_id: number;
- matched_text: string;
- frame_id: number;
- timestamp: string;
- app_name: string;
- window_name: string;
- file_path: string;
- original_frame_text?: string;
- tags: string[];
- }
-
- /**
- * Union type for different types of content items.
- */
- type ContentItem =
- | { type: "OCR"; content: OCRContent }
- | { type: "Audio"; content: AudioContent }
- | { type: "FTS"; content: FTSContent };
-
- /**
- * Pagination information for search results.
- */
- interface PaginationInfo {
- limit: number;
- offset: number;
- total: number;
- }
-
- /**
- * Structure of the response from a Screenpipe query.
- */
- interface ScreenpipeResponse {
- data: ContentItem[];
- pagination: PaginationInfo;
- }
-}
-
-export {};
diff --git a/examples/typescript/pipe-post-questions-on-reddit/tsconfig.json b/examples/typescript/pipe-post-questions-on-reddit/tsconfig.json
deleted file mode 100644
index c4e6dfdd7..000000000
--- a/examples/typescript/pipe-post-questions-on-reddit/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "esnext",
- "moduleResolution": "node",
- "outDir": "./",
- "rootDir": "./",
- "strict": true,
- "esModuleInterop": true
- },
- "include": [
- "./**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-screen-to-crm/README.md b/examples/typescript/pipe-screen-to-crm/README.md
deleted file mode 100644
index f0f400ffb..000000000
--- a/examples/typescript/pipe-screen-to-crm/README.md
+++ /dev/null
@@ -1,97 +0,0 @@
-
-
-![Rocks screenshot (1)](https://github.com/user-attachments/assets/be5f8df5-ebc8-422f-a059-e5055c7c601b)
-
-
-
-https://github.com/user-attachments/assets/ee2ea7fa-d723-4f8e-9ed0-78241851b066
-
-
-
-in screenpipe we have a plugin system called "pipe store" or "pipes"
-
-think of it like this:
-
-screenpipe data -> your pipe like "AI annotate" or "send to salesforce"
-
-a more dev-friendly explanation:
-
-screenpipe | AI tag | notion update
-
-or
-
-screenpipe | AI tag | slack send report
-
-or
-
-screenpipe | fill salesforce
-
-or
-
-screenpipe | logs daily
-
-basically it would read, process, annotate, analyse, summarize, send, your data customisable to your desire, effortlessly
-
-### pipe-screen-to-crm
-
-this is an experimental, that will fill with notion table CRM while you work
-
-instructions to run this pipe:
-
-1. install screenpipe and git clone this repo
- ```
- git clone https://github.com/mediar-ai/screenpipe.git
- cd screenpipe
- ```
-
-2. install and run ollama:
- - follow instructions at https://github.com/jmorganca/ollama
- - run `ollama run phi3.5:3.8b-mini-instruct-q4_K_M`
-
-3. set up notion:
- - create a notion integration: https://www.notion.so/my-integrations - copy the API key
- - create a database with properties: Name (text), Company (text), Position (text), LinkedIn URL (url), Last Interaction (text), Potential Opportunity (text), Date (date)
- - share database with your integration - copy the database ID eg https://www.notion.so/<THIS>?<NOTTHIS>
-
-4. set environment variables:
- ```
- export SCREENPIPE_NOTION_API_KEY=your_notion_api_key
- export SCREENPIPE_NOTION_DATABASE_ID=your_notion_database_id
- ```
-
-5. run the pipe:
- ```
- screenpipe pipe download ./examples/typescript/pipe-screen-to-crm
- screenpipe pipe enable screen-to-crm
- screenpipe
- ```
-
-### tech details
-
-we run deno runtime (a JS/TS engine) within the rust code, which host your pipes, its 99.9% similar to normal JS code
-
-### dev mode
-
-if you're in dev mode you can run the cli like this:
-
-```bash
-screenpipe pipe download https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-stream-ocr-text
-screenpipe pipe enable pipe-stream-ocr-text
-```
-
-this would download the pipe in your local files and enable it
-
-then you need to restart screenpipe backend
-
-### get featured in the pipe store
-
-<img width="1312" alt="Screenshot 2024-08-27 at 17 06 45" src="https://github.com/user-attachments/assets/b6856bf4-2cfd-4888-be11-ee7baae6b84b">
-
-just ask @louis030195
-
-### what's next for pipes
-
-- use dependencies (like vercel/ai so cool)
-- access to screenpipe desktop api (control your computer, embedded LLM, better UI feedback API, etc.)
-- easier to publish your pipes (like obsidian store)
-- everything frictionless, effortless, and maximize the value you get out of screenpipe
diff --git a/examples/typescript/pipe-screen-to-crm/pipe.json b/examples/typescript/pipe-screen-to-crm/pipe.json
deleted file mode 100644
index 285b53a2b..000000000
--- a/examples/typescript/pipe-screen-to-crm/pipe.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "fields": [
- {
- "name": "interval",
- "type": "number",
- "default": 60,
- "description": "Interval in seconds to stream data"
- },
- {
- "name": "notionApiKey",
- "type": "string",
- "default": "<fill your notion api key here>",
- "description": "notion api key for authentication https://www.notion.so/my-integrations"
- },
- {
- "name": "notionDatabaseId",
- "type": "string",
- "default": "<fill your notion database id here>",
- "description": "id of the notion database to sync conversations to eg https://www.notion.so/your-workspace/database-id?v=..."
- },
- {
- "name": "ollamaApiUrl",
- "type": "string",
- "default": "http://localhost:11434/api/chat",
- "description": "Ollama API URL"
- },
- {
- "name": "ollamaModel",
- "type": "string",
- "default": "phi3.5:3.8b-mini-instruct-q4_K_M",
- "description": "Ollama Model"
- },
- {
- "name": "pageSize",
- "type": "number",
- "default": 100,
- "description": "Number of records to retrieve from Screenpipe per page"
- }
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-screen-to-crm/pipe.ts b/examples/typescript/pipe-screen-to-crm/pipe.ts
deleted file mode 100644
index ca1214451..000000000
--- a/examples/typescript/pipe-screen-to-crm/pipe.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-const DEFAULT_INTERVAL = 60; // 1 minute in seconds
-const DEFAULT_OLLAMA_API_URL = "http://localhost:11434/api/chat";
-const DEFAULT_OLLAMA_MODEL = "phi3.5:3.8b-mini-instruct-q4_K_M";
-const NOTION_API_BASE = "https://api.notion.com/v1";
-const DEFAULT_NOTION_DATABASE_ID = process.env.NOTION_DATABASE_ID;
-const DEFAULT_NOTION_API_KEY = process.env.NOTION_API_KEY;
-const DEFAULT_PAGE_SIZE = 100;
-
-/*
-Instructions to run this pipe:
-
-1. install screenpipe and git clone this repo
- ```
- git clone https://github.com/mediar-ai/screenpipe.git
- cd screenpipe
- ```
-
-2. install and run ollama:
- - follow instructions at https://github.com/jmorganca/ollama
- - run `ollama run phi3.5:3.8b-mini-instruct-q4_K_M`
-
-3. set up notion:
- - create a notion integration: https://www.notion.so/my-integrations - copy the API key
- - create a database with properties: Name (text), Company (text), Position (text), LinkedIn URL (url), Last Interaction (text), Potential Opportunity (text), Date (date)
- - share database with your integration - copy the database ID eg https://www.notion.so/<THIS>?<NOTTHIS>
-
-4. set environment variables:
- ```
- export SCREENPIPE_NOTION_API_KEY=your_notion_api_key
- export SCREENPIPE_NOTION_DATABASE_ID=your_notion_database_id
- ```
-
-5. run the pipe:
- ```
- screenpipe pipe download ./examples/typescript/pipe-screen-to-crm
- screenpipe pipe enable screen-to-crm
- screenpipe
- ```
-
-*/
-
-async function queryScreenpipe(interval: number, pageSize: number) {
- try {
- const now = new Date();
- const oneMinuteAgo = new Date(now.getTime() - interval);
-
- const queryParams = `start_time=${oneMinuteAgo.toISOString()}&end_time=${now.toISOString()}&limit=${pageSize}&content_type=ocr`;
-
- console.log(`querying screenpipe with params: ${queryParams}`);
- const result = await fetch(
- `http://localhost:3030/search?${queryParams}`
- ).then((r) => r.json());
- console.log("retrieved", result.data.length, "items from screenpipe");
- return result.data;
- } catch (error) {
- console.error("error querying screenpipe:", error);
- return [];
- }
-}
-
-async function extractLinkedInData(
- screenData: any,
- ollamaApiUrl: string,
- ollamaModel: string
-) {
- console.log(
- "extracting linkedin data from",
- screenData.length,
- "screen data items"
- );
- const prompt = `
-You are an AI assistant tasked with extracting LinkedIn sales-related information from screen data (OCR).
-Analyze the following screen data and extract relevant information about potential sales leads or customers.
-Only extract information if you are highly confident it is related to LinkedIn and sales activities.
-
-Screen Data:
-${JSON.stringify(screenData)}
-
-Return a JSON array of objects with the following structure:
-[
- {
- "name": "Full name of the person",
- "company": "Company name",
- "position": "Job title",
- "linkedInUrl": "LinkedIn profile URL",
- "lastInteraction": "Brief description of last interaction",
- "potentialOpportunity": "Brief description of potential sales opportunity",
- "confidence": 0.95 // Your confidence level in the extracted information (0.0 to 1.0)
- }
-]
-
-Rules:
-- Do not add backticks to the JSON eg \`\`\`json\`\`\` is WRONG
-- If no relevant information is found, return an empty array. NOTHING ELSE.
-- DO NOT RETURN ANYTHING BUT JSON. NO COMMENTS BELOW THE JSON.
-- In the potentialOpportunity field, feel free to say you should follow up with the lead at specific date in the future (provide the date).
-`;
-
- try {
- console.log(`sending request to ollama api: ${ollamaApiUrl}`);
- const response = await fetch(ollamaApiUrl, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- model: ollamaModel,
- messages: [{ role: "user", content: prompt }],
- stream: false,
- response_format: { type: "json_object" },
- }),
- });
-
- if (!response.ok) {
- console.log("ollama response:", await response.text());
- throw new Error(`http error! status: ${response.status}`);
- }
-
- const result = await response.json();
- console.log("ollama result:", JSON.stringify(result, null, 2));
-
- // remove backticks from the result
- const cleanedResult = result.message.content
- .trim()
- .replace(/```json\n/g, "")
- .replace(/\n```/g, "");
- const extractedData = JSON.parse(cleanedResult);
- console.log(
- "extracted linkedin data:",
- JSON.stringify(extractedData, null, 2)
- );
- return extractedData;
- } catch (error) {
- console.error("error extracting linkedin data:", error);
- return [];
- }
-}
-
-async function readFromNotion(databaseId: string, apiKey: string) {
- const url = `${NOTION_API_BASE}/databases/${databaseId}/query`;
- console.log("reading from notion:", url);
- const response = await fetch(url, {
- method: "POST",
- headers: {
- Authorization: `Bearer ${apiKey}`,
- "Notion-Version": "2022-06-28",
- "Content-Type": "application/json",
- },
- body: JSON.stringify({}),
- });
- if (!response.ok) {
- console.log("notion response:", await response.text());
- throw new Error(`http error! status: ${response.status}`);
- }
-
- const data = await response.json();
- console.log("notion data:", JSON.stringify(data, null, 2));
- return data.results.map((page: any) => page.properties);
-}
-
-async function updateNotion(
- databaseId: string,
- records: any[],
- apiKey: string
-) {
- const url = `${NOTION_API_BASE}/pages`;
- const updatedRecords = [];
-
- for (const record of records) {
- console.log("updating record:", JSON.stringify(record, null, 2));
- const response = await fetch(url, {
- method: "POST",
- headers: {
- Authorization: `Bearer ${apiKey}`,
- "Notion-Version": "2022-06-28",
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- parent: { database_id: databaseId },
- properties: record,
- }),
- });
- if (!response.ok) {
- console.log("notion response:", await response.text());
- throw new Error(`http error! status: ${response.status}`);
- }
- updatedRecords.push(await response.json());
- console.log("updated record:", JSON.stringify(updatedRecords[0], null, 2));
- }
-
- return updatedRecords;
-}
-
-async function updateNotionWithLinkedInData(
- existingData: any[],
- linkedInData: any[]
-) {
- console.log(
- "updating notion with",
- linkedInData.length,
- "linkedin data items"
- );
- const updatedRecords = [];
-
- for (const item of linkedInData) {
- console.log("processing item:", item);
- const existingRecord = existingData.find(
- (record) => record.Name.title[0]?.plain_text === item.name
- );
- console.log("existing record:", existingRecord);
-
- const linkedInUrl =
- item.linkedInUrl && item.linkedInUrl.trim() !== ""
- ? item.linkedInUrl
- : null;
-
- if (existingRecord) {
- // update existing record
- updatedRecords.push({
- Name: { title: [{ text: { content: item.name } }] },
- Company: { rich_text: [{ text: { content: item.company || "" } }] },
- Position: { rich_text: [{ text: { content: item.position || "" } }] },
- "LinkedIn URL": { url: linkedInUrl },
- "Last Interaction": {
- rich_text: [{ text: { content: item.lastInteraction || "" } }],
- },
- "Potential Opportunity": {
- rich_text: [{ text: { content: item.potentialOpportunity || "" } }],
- },
- Date: { date: { start: new Date().toISOString() } },
- });
- } else {
- // add new record
- updatedRecords.push({
- Name: { title: [{ text: { content: item.name } }] },
- Company: { rich_text: [{ text: { content: item.company || "" } }] },
- Position: { rich_text: [{ text: { content: item.position || "" } }] },
- "LinkedIn URL": { url: linkedInUrl },
- "Last Interaction": {
- rich_text: [{ text: { content: item.lastInteraction || "" } }],
- },
- "Potential Opportunity": {
- rich_text: [{ text: { content: item.potentialOpportunity || "" } }],
- },
- Date: { date: { start: new Date().toISOString() } },
- });
- }
- }
-
- return updatedRecords;
-}
-
-async function enrichCRM(
- linkedInData: any,
- databaseId: string,
- apiKey: string
-) {
- console.log("enriching crm with", linkedInData.length, "linkedin data items");
- try {
- // read existing data from notion
- const existingData = await readFromNotion(databaseId, apiKey);
- console.log("existing data records:", existingData.length);
-
- // update notion with linkedin data
- const updatedRecords = await updateNotionWithLinkedInData(
- existingData,
- linkedInData
- );
-
- console.log("updating notion with", updatedRecords.length, "records");
- // update the notion database
- await updateNotion(databaseId, updatedRecords, apiKey);
- console.log("updated notion with linkedin data");
- } catch (error) {
- console.error("error enriching crm:", error);
- }
-}
-
-async function runLinkedInCRMEnricher() {
- console.log("starting linkedin crm enricher");
- const config = await pipe.loadConfig();
- console.log("loaded config:", JSON.stringify(config, null, 2));
- const interval = (config.interval || DEFAULT_INTERVAL) * 1000;
- const databaseId = config.notionDatabaseId || DEFAULT_NOTION_DATABASE_ID;
- const apiKey = config.notionApiKey || DEFAULT_NOTION_API_KEY;
- const ollamaApiUrl = config.ollamaApiUrl || DEFAULT_OLLAMA_API_URL;
- const ollamaModel = config.ollamaModel || DEFAULT_OLLAMA_MODEL;
- const pageSize = config.pageSize || DEFAULT_PAGE_SIZE;
- while (true) {
- try {
- console.log("starting new enrichment cycle");
- const screenData = await queryScreenpipe(interval, pageSize);
- if (screenData.length === 0) {
- console.log("no screen data found in this interval");
- continue;
- }
- const linkedInData = await extractLinkedInData(
- screenData,
- ollamaApiUrl,
- ollamaModel
- );
- if (linkedInData.length > 0) {
- await enrichCRM(linkedInData, databaseId, apiKey);
- } else {
- console.log("no relevant linkedin data found in this interval");
- }
- } catch (error) {
- console.error("error in linkedin crm enrichment cycle:", error);
- } finally {
- console.log(`waiting ${interval / 1000} seconds before next cycle`);
- }
- await new Promise((resolve) => setTimeout(resolve, interval));
- }
-}
-
-// Self-invoking async function to run the LinkedIn CRM enricher
-(async () => {
- try {
- await runLinkedInCRMEnricher();
- } catch (error) {
- console.error("fatal error in linkedin crm enricher:", error);
- }
-})();
diff --git a/examples/typescript/pipe-screen-to-crm/screenpipe.d.ts b/examples/typescript/pipe-screen-to-crm/screenpipe.d.ts
deleted file mode 100644
index 480eb00bc..000000000
--- a/examples/typescript/pipe-screen-to-crm/screenpipe.d.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-declare global {
- const pipe: {
- readFile: (path: string) => Promise<string>;
- writeFile: (path: string, contents: string) => Promise<void>;
- removeFile: (path: string) => Promise<void>;
- get: (url: string) => Promise<any>;
- post: (url: string, body: string) => Promise<any>;
- fetch: (url: string, options?: RequestInit) => Promise<Response>;
- sendNotification: (options: {
- title: string;
- body: string;
- }) => Promise<any>;
- loadConfig: () => Promise<Record<string, any>>;
- config: Record<string, any>;
- metadata: {
- id: string;
- };
- };
-
- const fs: {
- readFile: (path: string) => Promise<string>;
- writeFile: (path: string, contents: string) => Promise<void>;
- readdir: (path: string) => Promise<string[]>;
- mkdir: (path: string) => Promise<void>;
- };
- const path: {
- join: (...paths: string[]) => string;
- };
-
- namespace NodeJS {
- interface ProcessEnv {
- SCREENPIPE_DIR: string;
- SCREENPIPE_LOG_API_URL?: string;
- SCREENPIPE_SERVER_URL?: string;
- PIPE_DIR: string;
- NOTION_DATABASE_ID: string;
- NOTION_API_KEY: string;
- }
- }
- const process: {
- env: NodeJS.ProcessEnv;
- };
-}
-
-export {};
diff --git a/examples/typescript/pipe-screen-to-crm/tsconfig.json b/examples/typescript/pipe-screen-to-crm/tsconfig.json
deleted file mode 100644
index c4e6dfdd7..000000000
--- a/examples/typescript/pipe-screen-to-crm/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "esnext",
- "moduleResolution": "node",
- "outDir": "./",
- "rootDir": "./",
- "strict": true,
- "esModuleInterop": true
- },
- "include": [
- "./**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-security-check/README.md b/examples/typescript/pipe-security-check/README.md
deleted file mode 100644
index d2d7cf874..000000000
--- a/examples/typescript/pipe-security-check/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-
-send a notification to the user when exposed to a security risk on your screen
-
-
-
-https://github.com/user-attachments/assets/a4ab0d24-996c-45f5-bffd-142f9757cca5
-
-
-
-
-```bash
-ollama run mistral-nemo
-```
-
-```bash
-curl -X POST "http://localhost:3030/pipes/download" -H "Content-Type: application/json" -d '{"url": "$(pwd)/examples/typescript/pipe-security-check"}'
-
-curl -X POST "http://localhost:3030/pipes/enable" -H "Content-Type: application/json" -d '{"pipe_id": "pipe-security-check"}'
-```
-
-or
-
-```bash
-./target/release/screenpipe pipe download $(pwd)/examples/typescript/pipe-security-check
-
-./target/release/screenpipe pipe enable pipe-security-check
-```
-
-
-
diff --git a/examples/typescript/pipe-security-check/main.js b/examples/typescript/pipe-security-check/main.js
deleted file mode 100644
index cb7e3a36d..000000000
--- a/examples/typescript/pipe-security-check/main.js
+++ /dev/null
@@ -1,134 +0,0 @@
-const INTERVAL = 1 * 60 * 1000; // 1 minute in milliseconds
-
-async function queryScreenpipe(params) {
- try {
- const queryParams = Object.entries(params)
- .filter(([_, v]) => v != null)
- .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
- .join("&");
- console.log("Calling Screenpipe:", JSON.stringify(params));
- const result = await pipe.get(
- `http://localhost:3030/search?${queryParams}`
- );
- // console.log("Retrieved", result.data.length, "items from Screenpipe");
- return result;
- } catch (error) {
- console.error("Error querying Screenpipe:", error);
- return null;
- }
-}
-
-async function getAIProvider() {
- const provider = "ollama";
- const model = "mistral-nemo";
- return { provider, model };
-}
-
-async function checkSecurity(provider, screenData) {
-
- const listOfBrowsers = ["arc", "chrome", "edge", "safari", "firefox"];
- const browserData = screenData.data.filter(item =>
- listOfBrowsers.some(browser =>
- item.content.app_name.toLowerCase().includes(browser) ||
- item.content.window_name.toLowerCase().includes(browser)
- )
- );
- const prompt = `Act like a cybersecurity expert with 10 years of experience detecting suspicious activity. Analyze the following screen data and determine if a security issue is present.
-
- Analyze the screen data for suspicious activity.
- Return a JSON object with the following structure:
- {
- "securityIssueFound": true, // or false
- "reason": "Specify the reason for the issue"
- "summary": "One-sentence summary of the security threat"
- }
-
- Rules:
- - do not add \`\`\`json or \`\`\` at the beginning or end of the JSON object.
- - do not add any other text.
- - do not add any other comments.
- - only return the JSON object.
- - only take into account browser activity, not other apps.
- Input:
- ${JSON.stringify(browserData)}
- Output only the JSON object.`;
-
- try {
- const result = await pipe.post(
- "http://localhost:11434/api/chat",
- JSON.stringify({
- model: provider.model,
- messages: [{ role: "user", content: prompt }],
- response_format: { type: "json_object" },
- stream: false,
- })
- );
- console.log("AI answer:", result);
- const content = result.message.content;
- console.log("AI answer content:", content);
- // if present, remove the ```json and ``` at the beginning and end of the content
- // content = content.replace(/^```json\n/, "").replace(/\n```$/, "").trim();
- return JSON.parse(content);
- } catch (error) {
- console.error("Error in AI Response:", error);
- }
-}
-
-async function checkRecentActivities(provider) {
- const now = new Date();
- const oneMinuteAgo = new Date(now.getTime() - INTERVAL);
-
- const screenData = await queryScreenpipe({
- start_time: oneMinuteAgo.toISOString(),
- end_time: now.toISOString(),
- limit: 5,
- content_type: "ocr",
- });
-
- // console.log("Screenpipe data:", screenData);
-
- if (!screenData || !screenData.data || screenData.data.length === 0) {
- console.log("No data retrieved from Screenpipe");
- return;
- }
-
- const response = await checkSecurity(provider, screenData);
- console.log("Security check for recent activities response: ", response);
- if (response.securityIssueFound) {
- console.log("Security issue detected", response.reason);
- await pipe.sendNotification({ title: "Security issue detected", body: response.reason });
- } else {
- console.log("No security issue detected");
- }
-}
-
-async function runSecurityChecker() {
- const provider = await getAIProvider();
- console.log("Starting Security Checker with provider:", provider);
-
- while (true) {
- try {
- await checkRecentActivities(provider);
- } catch (error) {
- // await pipe.sendNotification({ title: "Error in security check", body: error.message })
- console.error("Error in security check of activity:", error);
- }
- await new Promise(resolve => setTimeout(resolve, INTERVAL));
- }
-}
-
-// Self-invoking async function to run the activity tagger
-(async () => {
- try {
- await runSecurityChecker();
- } catch (error) {
- console.error("Fatal error in Activity Tagger:");
- if (error instanceof Error) {
- console.error("Error name:", error.name);
- console.error("Error message:", error.message);
- console.error("Error stack:", error.stack);
- } else {
- console.error("Unexpected error:", error);
- }
- }
-})();
diff --git a/examples/typescript/pipe-stream-ocr-text/README.md b/examples/typescript/pipe-stream-ocr-text/README.md
deleted file mode 100644
index a740c1e91..000000000
--- a/examples/typescript/pipe-stream-ocr-text/README.md
+++ /dev/null
@@ -1,64 +0,0 @@
-
-in screenpipe we have a plugin system called "pipe store" or "pipes"
-
-think of it like this:
-
-screenpipe data -> your pipe like "AI annotate" or "send to salesforce"
-
-a more dev-friendly explanation:
-
-screenpipe | AI tag | notion update
-
-or
-
-screenpipe | AI tag | slack send report
-
-or
-
-screenpipe | fill salesforce
-
-or
-
-screenpipe | logs daily
-
-basically it would read, process, annotate, analyse, summarize, send, your data customisable to your desire, effortlessly
-
-### pipe-stream-ocr-text
-
-this is an experimental, but official pipe, that will stream OCR text from your screen data every 1 min
-
-this is how you run it through the app:
-
-add the url of this pipe
-
-`https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-stream-ocr-text`
-
-### tech details
-
-we run deno runtime (a JS/TS engine) within the rust code, which host your pipes, its 99.9% similar to normal JS code
-
-### dev mode
-
-if you're in dev mode you can run the cli like this:
-
-```bash
-screenpipe pipe download https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-stream-ocr-text
-screenpipe pipe enable pipe-stream-ocr-text
-```
-
-this would download the pipe in your local files and enable it
-
-then you need to restart screenpipe backend
-
-### get featured in the pipe store
-
-<img width="1312" alt="Screenshot 2024-08-27 at 17 06 45" src="https://github.com/user-attachments/assets/b6856bf4-2cfd-4888-be11-ee7baae6b84b">
-
-just ask @louis030195
-
-### what's next for pipes
-
-- use dependencies (like vercel/ai so cool)
-- access to screenpipe desktop api (control your computer, embedded LLM, better UI feedback API, etc.)
-- easier to publish your pipes (like obsidian store)
-- everything frictionless, effortless, and maximize the value you get out of screenpipe
diff --git a/examples/typescript/pipe-stream-ocr-text/pipe.json b/examples/typescript/pipe-stream-ocr-text/pipe.json
deleted file mode 100644
index 48174032c..000000000
--- a/examples/typescript/pipe-stream-ocr-text/pipe.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "fields": [
- {
- "name": "interval",
- "type": "number",
- "default": 60,
- "description": "Interval in seconds to stream data"
- }
- ]
- }
\ No newline at end of file
diff --git a/examples/typescript/pipe-stream-ocr-text/pipe.ts b/examples/typescript/pipe-stream-ocr-text/pipe.ts
deleted file mode 100644
index 379a0bffd..000000000
--- a/examples/typescript/pipe-stream-ocr-text/pipe.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-let INTERVAL = 10 * 1000; // 10 seconds in milliseconds
-
-async function queryScreenpipe() {
- try {
- const now = new Date();
- const oneMinuteAgo = new Date(now.getTime() - INTERVAL);
-
- const queryParams = `start_time=${oneMinuteAgo.toISOString()}&end_time=${now.toISOString()}&limit=50&content_type=ocr`;
-
- const result = await fetch(
- `http://localhost:3030/search?${queryParams}`
- ).then((r) => r.json());
- console.log("Retrieved", result.data.length, "items from screenpipe");
- return result.data;
- } catch (error) {
- console.error("Error querying screenpipe:", error);
- return [];
- }
-}
-
-async function writeToMarkdown(data: any) {
- console.log("Writing to markdown", JSON.stringify(data));
- const fileName = `screen-ocr-${new Date()
- .toISOString()
- .replace(/[:.]/g, "-")}.md`;
- const content = data
- .map(
- (item: any) =>
- `## ${item.content.timestamp}\n\n${item.content.text}\n\n---\n`
- )
- .join("\n");
-
- const dir = path.join(process.env.PIPE_DIR, fileName);
- console.log("Writing to", dir);
- await fs.writeFile(dir, content);
- console.log(`Written OCR data to ${fileName}`);
-}
-
-async function runOCRTracker() {
- console.log("Starting OCR Tracker");
- // wait 2 seocnds
- await new Promise((resolve) => setTimeout(resolve, 1000));
-
- console.log(pipe);
- await pipe.loadConfig();
- INTERVAL = pipe.config.interval * 1000;
- console.log("INTERVAL", INTERVAL);
-
- while (true) {
- try {
- const screenData = await queryScreenpipe();
- await writeToMarkdown(screenData);
- } catch (error) {
- console.error("Error in OCR tracking:", error);
- } finally {
- await new Promise((resolve) => setTimeout(resolve, INTERVAL));
- }
-
- // const isEnabled = await pipe.isEnabled();
- // if (!isEnabled) {
- // console.log("pipe is disabled");
- // break;
- // }
- }
-}
-
-// Self-invoking async function to run the OCR tracker
-(async () => {
- try {
- await runOCRTracker();
- } catch (error) {
- console.error("Fatal error in OCR Tracker:", error);
- }
-})();
diff --git a/examples/typescript/pipe-stream-ocr-text/screenpipe.d.ts b/examples/typescript/pipe-stream-ocr-text/screenpipe.d.ts
deleted file mode 100644
index e98bc8eb9..000000000
--- a/examples/typescript/pipe-stream-ocr-text/screenpipe.d.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-declare global {
- const pipe: {
- readFile: (path: string) => Promise<string>;
- writeFile: (path: string, contents: string) => Promise<void>;
- removeFile: (path: string) => Promise<void>;
- get: (url: string) => Promise<any>;
- post: (url: string, body: string) => Promise<any>;
- fetch: (url: string, options?: RequestInit) => Promise<Response>;
- sendNotification: (options: {
- title: string;
- body: string;
- }) => Promise<any>;
- loadConfig: () => Promise<Record<string, any>>;
- config: Record<string, any>;
- metadata: {
- id: string;
- };
- };
-
- const fs: {
- readFile: (path: string) => Promise<string>;
- writeFile: (path: string, contents: string) => Promise<void>;
- readdir: (path: string) => Promise<string[]>;
- mkdir: (path: string) => Promise<void>;
- };
-
- const path: {
- join: (...paths: string[]) => string;
- };
-
- namespace NodeJS {
- interface ProcessEnv {
- SCREENPIPE_DIR: string;
- SCREENPIPE_LOG_API_URL?: string;
- SCREENPIPE_SERVER_URL?: string;
- PIPE_DIR: string;
- }
- }
-
- const process: {
- env: NodeJS.ProcessEnv;
- };
-}
-
-export {};
diff --git a/examples/typescript/pipe-stream-ocr-text/tsconfig.json b/examples/typescript/pipe-stream-ocr-text/tsconfig.json
deleted file mode 100644
index c4e6dfdd7..000000000
--- a/examples/typescript/pipe-stream-ocr-text/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "esnext",
- "moduleResolution": "node",
- "outDir": "./",
- "rootDir": "./",
- "strict": true,
- "esModuleInterop": true
- },
- "include": [
- "./**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
-}
\ No newline at end of file
diff --git a/examples/typescript/pipe-sync-meetings-to-notion/README.md b/examples/typescript/pipe-sync-meetings-to-notion/README.md
deleted file mode 100644
index e2308320b..000000000
--- a/examples/typescript/pipe-sync-meetings-to-notion/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-
-https://github.com/user-attachments/assets/795dfd91-393a-4eef-a20b-5b2c35d594f9
-
-in screenpipe we have a plugin system called "pipe store" or "pipes"
-
-think of it like this:
-
-screenpipe data -> your pipe like "AI annotate" or "send to salesforce"
-
-a more dev-friendly explanation:
-
-screenpipe | AI tag | notion update
-
-or
-
-screenpipe | AI tag | slack send report
-
-or
-
-screenpipe | fill salesforce
-
-or
-
-screenpipe | logs daily
-
-basically it would read, process, annotate, analyse, summarize, send, your data customisable to your desire, effortlessly
-
-### pipe-sync-meetings-to-notion
-
-this is an experimental, but official pipe, that will sync your meetings to notion
diff --git a/examples/typescript/pipe-sync-meetings-to-notion/pipe.js b/examples/typescript/pipe-sync-meetings-to-notion/pipe.js
deleted file mode 100644
index d7e126899..000000000
--- a/examples/typescript/pipe-sync-meetings-to-notion/pipe.js
+++ /dev/null
@@ -1,94 +0,0 @@
-const INTERVAL = 30 * 1000; // 30 seconds in milliseconds
-const NOTION_API_URL = 'https://api.notion.com/v1/pages';
-const NOTION_DATABASE_ID = process.env.SCREENPIPE_NOTION_DATABASE_ID;
-const NOTION_API_KEY = process.env.SCREENPIPE_NOTION_API_KEY;
-
-
-
-async function queryScreenpipe(startTime, endTime) {
- try {
- const queryParams = `start_time=${startTime}&end_time=${endTime}&limit=50&content_type=audio`;
- const response = await fetch(`http://localhost:3030/search?${queryParams}`);
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- return await response.json();
- } catch (error) {
- console.error("Error querying screenpipe:", error.toString());
- return [];
- }
-}
-
-async function syncAudioToNotion(audioData) {
- try {
- const title = `Audio - ${audioData.content.timestamp}`;
- const date = audioData.content.timestamp;
- const transcription = audioData.content.transcription;
-
- // Split transcription into chunks of 2000 characters
- const chunks = splitTranscription(transcription);
-
- for (let i = 0; i < chunks.length; i++) {
- const response = await fetch(NOTION_API_URL, {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${NOTION_API_KEY}`,
- 'Notion-Version': '2022-06-28',
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- parent: { database_id: NOTION_DATABASE_ID },
- properties: {
- Title: { title: [{ text: { content: `${title} (Part ${i + 1}/${chunks.length})` } }] },
- Date: { date: { start: date } },
- Transcription: { rich_text: [{ text: { content: chunks[i] } }] },
- },
- }),
- });
-
- if (!response.ok) {
- const errorBody = await response.text();
- throw new Error(`HTTP error! status: ${response.status}, body: ${errorBody}`);
- }
- }
-
- console.log("Audio synced to Notion successfully");
- } catch (error) {
- console.error("Error syncing audio to Notion:", error);
- }
-}
-
-function splitTranscription(transcription, chunkSize = 2000) {
- const chunks = [];
- for (let i = 0; i < transcription.length; i += chunkSize) {
- chunks.push(transcription.slice(i, i + chunkSize));
- }
- return chunks;
-}
-
-async function streamAudioToNotion() {
- console.log("Starting Audio Stream to Notion");
-
- while (true) {
- try {
- const now = new Date();
- const thirtySecondsAgo = new Date(now.getTime() - INTERVAL);
-
- const audioData = await queryScreenpipe(thirtySecondsAgo.toISOString(), now.toISOString());
-
- console.log("Audio data:", audioData);
- for (const audio of audioData.data) {
- await syncAudioToNotion(audio);
- }
- } catch (error) {
- console.error("Error syncing audio to Notion:", {
- message: error.message,
- stack: error.stack,
- audioData: JSON.stringify(audioData)
- });
- }
- await new Promise((resolve) => setTimeout(resolve, INTERVAL));
- }
-}
-
-streamAudioToNotion();
\ No newline at end of file
diff --git a/examples/typescript/pipe-tagging-activity/README.md b/examples/typescript/pipe-tagging-activity/README.md
deleted file mode 100644
index 86cc4c913..000000000
--- a/examples/typescript/pipe-tagging-activity/README.md
+++ /dev/null
@@ -1,47 +0,0 @@
-
-in screenpipe we have a plugin system called "pipe store" or "pipes"
-
-think of it like this:
-
-screenpipe data -> your pipe like "AI annotate" or "send to salesforce"
-
-a more dev-friendly explanation:
-
-screenpipe | AI tag | notion update
-
-or
-
-screenpipe | AI tag | slack send report
-
-or
-
-screenpipe | fill salesforce
-
-or
-
-screenpipe | logs daily
-
-basically it would read, process, annotate, analyse, summarize, send, your data customisable to your desire, effortlessly
-
-### pipe-tagging-activity
-
-this is an experimental, but official pipe, that will use ollama + phi3.5 to annotate your screen data (only OCR) every 1 min
-
-soon we'll make is easier to search through these annotations / tags but in the meantime you can you use to enrich your data
-
-and AI will be able to provide you more relevant answers
-
-this is how you run it through the app:
-
-```bash
-ollama run phi3.5
-```
-
-click "install"
-
-wait a few minutes then ask AI "read my data from last 5 minutes and list tags you see"
-
-
-### tech details
-
-we run deno runtime (a JS/TS engine) within the rust code, which host your pipes, its 99.9% similar to normal JS code
diff --git a/examples/typescript/pipe-tagging-activity/pipe.js b/examples/typescript/pipe-tagging-activity/pipe.js
deleted file mode 100644
index d97b86677..000000000
--- a/examples/typescript/pipe-tagging-activity/pipe.js
+++ /dev/null
@@ -1,123 +0,0 @@
-const INTERVAL = 1 * 60 * 1000; // 1 minute in milliseconds
-
-async function queryScreenpipe(params) {
- try {
- const queryParams = Object.entries(params)
- .filter(([_, v]) => v != null)
- .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
- .join('&');
- console.log("Calling Screenpipe:", JSON.stringify(params));
- const result = await pipe.get(`http://localhost:3030/search?${queryParams}`);
- console.log("Retrieved", result.data.length, "items from Screenpipe");
- return result;
- } catch (error) {
- console.error("Error querying Screenpipe:", error);
- return null;
- }
-}
-
-async function getAIProvider() {
- const provider = "ollama";
- const model = "phi3.5";
- return { provider, model };
-}
-
-async function generateTags(provider, screenData) {
- const prompt = `Based on the following screen data, generate relevant tags for the user's activity:
-
- ${JSON.stringify(screenData)}
-
- Return a JSON object with the following structure:
- {
- "tags": ["tag1", "tag2", "tag3"]
- }
- Do not say anything else but JSON.
- Provide 3-5 relevant tags that describe the user's activity.`;
-
- const result = await pipe.post(
- "http://localhost:11434/api/chat",
- JSON.stringify({
- model: provider.model,
- messages: [{ role: "user", content: prompt }],
- response_format: { type: "json_object" },
- stream: false,
- }),
- );
-
- console.log("AI answer:", result);
-
- const content = result.message.content;
- return JSON.parse(content);
-}
-
-async function addTags(contentType, id, tags) {
- try {
- console.log(`Adding tags to ${contentType} item ${id}:`, tags);
- const result = await pipe.post(
- `http://localhost:3030/tags/${contentType}/${id}`,
- JSON.stringify({ tags })
- );
- console.log("Tags added successfully:", result);
- return result;
- } catch (error) {
- console.error(`Error adding tags to ${contentType} item ${id}:`, error);
- return null;
- }
-}
-
-async function tagRecentActivities(provider) {
- const now = new Date();
- const oneMinuteAgo = new Date(now.getTime() - INTERVAL);
-
- const screenData = await queryScreenpipe({
- start_time: oneMinuteAgo.toISOString(),
- end_time: now.toISOString(),
- limit: 50,
- content_type: "ocr",
- });
-
- if (!screenData || !screenData.data || screenData.data.length === 0) {
- console.log("No data retrieved from Screenpipe");
- return;
- }
-
- const { tags } = await generateTags(provider, screenData);
-
- for (const item of screenData.data) {
- const contentType = "vision";
- const id = item.content.frame_id;
- await addTags(contentType, id, tags);
- }
-
- console.log("Tags added to recent activities:", tags);
-}
-
-async function runActivityTagger() {
- const provider = await getAIProvider();
- console.log("Starting Activity Tagger with provider:", provider);
-
- while (true) {
- try {
- await tagRecentActivities(provider);
- } catch (error) {
- console.error("Error in activity tagging:", error);
- }
- await new Promise(resolve => setTimeout(resolve, INTERVAL));
- }
-}
-
-// Self-invoking async function to run the activity tagger
-(async () => {
- try {
- await runActivityTagger();
- } catch (error) {
- console.error("Fatal error in Activity Tagger:");
- if (error instanceof Error) {
- console.error("Error name:", error.name);
- console.error("Error message:", error.message);
- console.error("Error stack:", error.stack);
- } else {
- console.error("Unexpected error:", error);
- }
- }
-})();
\ No newline at end of file
diff --git a/examples/typescript/rag-over-your-life-in-obsidian/README.md b/examples/typescript/rag-over-your-life-in-obsidian/README.md
deleted file mode 100644
index e4fdac3d1..000000000
--- a/examples/typescript/rag-over-your-life-in-obsidian/README.md
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-https://github.com/user-attachments/assets/41c0d4cb-5ce5-4011-93b8-fa71363e6c48
-
-
-
-https://github.com/mediar-ai/screenpipe/assets/25003283/f730cc55-933b-4ddb-a89a-d6607783704a
-
-
-
-how to setup:
-https://youtu.be/xyvdOfXwRgg
-
-need help? [i'll install this with you in less than 10 minutes](https://cal.com/louis030195/screenpipe)
-
diff --git a/examples/typescript/rag-over-your-life-in-obsidian/conf.js b/examples/typescript/rag-over-your-life-in-obsidian/conf.js
deleted file mode 100644
index 1a68c364e..000000000
--- a/examples/typescript/rag-over-your-life-in-obsidian/conf.js
+++ /dev/null
@@ -1,7 +0,0 @@
-const conf = () => {
- const secrets = process.env.HOME + '/secrets.json'
- console.log("fetching secrets.json from", secrets)
- return require(secrets);
-}
-module.exports = conf;
-// ~/secrets.json: {"OPENAI_API_KEY": "sk-..."}
\ No newline at end of file
diff --git a/examples/typescript/rag-over-your-life-in-obsidian/screenpipe.js b/examples/typescript/rag-over-your-life-in-obsidian/screenpipe.js
deleted file mode 100644
index 4cb30d848..000000000
--- a/examples/typescript/rag-over-your-life-in-obsidian/screenpipe.js
+++ /dev/null
@@ -1,154 +0,0 @@
-const OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions';
-const OPENAI_MODEL = 'gpt-4o';
-// to use ollama just comment out the above and uncomment below:
-// const OPENAI_API_URL = 'http://localhost:11434/api/chat';
-// const OPENAI_MODEL = 'phi3:medium-128k';
-// make sure to run "ollama run phi3:medium-128k"
-
-// example in obsidian use:
-// can you create a bullet list for me to share with my colleagues
-// my changes in the code of screenpipe? Use the queries like "lldb", "gdp", "discord"
-
-const screenpipe = async (conf) => {
- const openAIKey = conf.openai;
- document.body.style.cursor = "wait";
- const msg = window.getSelection().toString();
-
- // Generate parameters for 3 different queries
- const paramsResponse = await fetch(OPENAI_API_URL, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${openAIKey}`,
- },
- body: JSON.stringify({
- 'response_format': { type: 'json_object' },
- 'messages': [
- {
- 'role': 'user',
- 'content': `Based on this user selection: "${msg}", generate parameters as JSON for 3 different queries to screenpipe.
- Each query should have "q", "offset", "limit", and start_time, end_time fields.
- Rules:
- - q should be a single keyword that would properly find in the text found on the user screen some information that would help answering the user question.
- Return a list of objects with the key "queries"
- - q contains a single query, again, for example instead of "life plan" just use "life"
- - Respond with only the updated JSON object
- - If you return something else than JSON the universe will come to an end
- - DO NOT add \`\`\`json at the beginning or end of your response
- - Do not use '"' around your response
- - Date & time now is ${new Date().toISOString()}
-
- Example answers from you:
- "{
- "queries": [
- {"q": "goal", "offset": 0, "limit": 10, "start_time": "2024-07-21T11:30:25Z", "end_time": "2024-07-21T11:35:25Z"},
- {"q": "stripe", "offset": 0, "limit": 50, "start_time": "2024-07-19T08:00:25Z", "end_time": "2024-07-20T09:00:25Z"},
- {"q": "customer", "offset": 0, "limit": 20, "start_time": "2024-07-19T08:00:25Z", "end_time": "2024-07-20T09:00:25Z"}
- ]
- }"
-
- or
- "{
- "queries": [
- {"q": "sales", "offset": 0, "limit": 10, "start_time": "2024-07-21T11:30:25Z", "end_time": "2024-07-21T11:35:25Z"},
- {"q": "customer", "offset": 0, "limit": 20, "start_time": "2024-07-19T08:00:25Z", "end_time": "2024-07-20T09:00:25Z"},
- {"q": "goal", "offset": 0, "limit": 10, "start_time": "2024-07-19T08:00:25Z", "end_time": "2024-07-20T09:00:25Z"}
- ]
- }"
-
- Bad example
- "Here's the JSON you wanted:
- [
- {
- "queries": [{"q": "sales", "offset": 0, "limit": 10}]
- },
- {
- "queries": [{"q": "customer", "offset": 0, "limit": 20}]
- },
- {
- "queries": [{"q": "goal", "offset": 0, "limit": 10}]
- }
- ]"
- or
- "\`\`\`json
- [
- {
- "queries": [
- {"q": "goals", "offset": 0, "limit": 3}
- ]
- },
- {
- "queries": [
- {"q": "life plans", "offset": 0, "limit": 5}
- ]
- },
- {
- "queries": [
- {"q": "ambitions", "offset": 0, "limit": 3}
- ]
- }
- ]
- \`\`\`"
- JSON?
- `
- },
- ],
- 'model': OPENAI_MODEL,
- 'stream': false,
- })
- }).then(res => res.json());
-
- console.log(paramsResponse);
-
-
-
- // phi3 models are drunk af thats why
- const { queries } = JSON.parse((paramsResponse.choices?.[0]?.message?.content ||
- // ollama not respecting openai api
- paramsResponse.message?.content).trim()
- // remove " at the start and end
- .replace(/^"|"$/g, "")
- // remove ```json at the start and end
- .replace(/^```json\n/, "")
- .replace(/\n```$/, "")
- );
-
- console.log("queries", queries);
-
- // Query screenpipe 3 times with generated parameters
- const screenpipeResults = await Promise.all(queries.map(async (query) => {
- const response = await fetch(`http://localhost:3030/search?q=${encodeURIComponent(query.q)}&offset=${query.offset}&limit=${query.limit}`);
- return response.json();
- }));
-
- console.log("screenpipeResults", screenpipeResults);
-
- // Ask ChatGPT to write an answer based on screenpipe results
- const finalResponse = await fetch(OPENAI_API_URL, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${openAIKey}`,
- },
- body: JSON.stringify({
- 'messages': [
- { 'role': 'user', 'content': `Based on the user question "${msg}" and these data which corresponds to what has been seen on the user screen or through his mic: ${JSON.stringify(screenpipeResults)}, provide a comprehensive answer to the user intent.` },
- ],
- 'model': OPENAI_MODEL,
- 'stream': false,
- })
- }).then(res => res.json());
-
- document.body.style.cursor = "default";
- console.log(finalResponse);
-
- const txtResponse = finalResponse.choices?.[0]?.message?.content || finalResponse?.message?.content.trim()
- if (!txtResponse) {
- new Notice('Error from OpenAI');
- new Notice(JSON.stringify(finalResponse));
- }
-
- return `${msg}${txtResponse}`;
-}
-
-module.exports = screenpipe;
diff --git a/examples/typescript/rag-over-your-life-in-obsidian/screenpipe.md b/examples/typescript/rag-over-your-life-in-obsidian/screenpipe.md
deleted file mode 100644
index 7ff22907a..000000000
--- a/examples/typescript/rag-over-your-life-in-obsidian/screenpipe.md
+++ /dev/null
@@ -1 +0,0 @@
-<% tp.user.screenpipe(tp.user.conf()) %>
diff --git a/screenpipe-app-tauri/scripts/pre_build.js b/screenpipe-app-tauri/scripts/pre_build.js
index 0ab60a40c..6c78b38c4 100644
--- a/screenpipe-app-tauri/scripts/pre_build.js
+++ b/screenpipe-app-tauri/scripts/pre_build.js
@@ -95,6 +95,41 @@ const exports = {
cmake: 'C:\\Program Files\\CMake\\bin',
}
+// Add this function to install Deno
+async function installDeno() {
+ console.log('installing deno...');
+
+ if (platform === 'windows') {
+ await $`powershell -c "irm https://deno.land/install.ps1 | iex"`
+ } else {
+ // for macos and linux
+ await $`curl -fsSL https://deno.land/install.sh | sh`
+ }
+
+ console.log('deno installed successfully.');
+}
+
+// Add this function to copy the Deno binary
+async function copyDenoBinary() {
+ console.log('copying deno binary for tauri...');
+
+ let denoPath;
+ if (platform === 'windows') {
+ denoPath = path.join(os.homedir(), '.deno', 'bin', 'deno.exe');
+ } else {
+ denoPath = path.join(os.homedir(), '.deno', 'bin', 'deno');
+ }
+
+ const destPath = path.join(cwd, platform === 'windows' ? 'deno.exe' : 'deno');
+
+ try {
+ await fs.copyFile(denoPath, destPath);
+ console.log('deno binary copied successfully.');
+ } catch (error) {
+ console.error('failed to copy deno binary:', error);
+ }
+}
+
/* ########## Linux ########## */
if (platform == 'linux') {
// Install APT packages
@@ -509,6 +544,10 @@ if (process.env.GITHUB_ENV) {
}
}
+// Install and setup Deno (add this near the end of the script)
+await installDeno();
+await copyDenoBinary();
+
// --dev or --build
const action = process.argv?.[2]
if (action?.includes('--build' || action.includes('--dev'))) {
diff --git a/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json b/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json
index 9669514ca..00b8afe09 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json
@@ -1,7 +1,8 @@
{
"bundle": {
"externalBin": [
- "screenpipe"
+ "screenpipe",
+ "deno"
],
"linux": {
"deb": {
diff --git a/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json b/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
index c15fc9a97..be05cc9f3 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
@@ -24,7 +24,8 @@
},
"externalBin": [
"screenpipe",
- "ffmpeg"
+ "ffmpeg",
+ "deno"
]
}
}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json b/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json
index e1d5c2558..2a8e72c96 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json
@@ -1,7 +1,8 @@
{
"bundle": {
"externalBin": [
- "screenpipe"
+ "screenpipe",
+ "deno"
],
"resources": {
"ffmpeg\\bin\\x64\\*": "./",
diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.toml
index 3d6ff7e24..b4e5ef2cb 100644
--- a/screenpipe-core/Cargo.toml
+++ b/screenpipe-core/Cargo.toml
@@ -23,8 +23,6 @@ hf-hub = { workspace = true, features = ["tokio"], optional = true }
reqwest = { workspace = true }
tokio = { workspace = true }
-deno_core = { version = "0.311.0", optional = true }
-deno_ast = { version = "0.38.2", features = ["transpiling"], optional = true }
# Security
regex = { version = "1.10.6", features = ["std"], optional = true }
lazy_static = { version = "1.4.0", optional = true }
@@ -35,11 +33,10 @@ tracing = { workspace = true }
tracing-subscriber = { workspace = true }
dirs = "5.0.0"
-lettre = "0.11.0"
[features]
default = ["pipes", "security"]
llm = ["candle", "candle-nn", "candle-transformers", "tokenizers", "hf-hub"]
-pipes = ["dep:deno_core", "dep:deno_ast"]
+pipes = []
security = ["dep:regex", "dep:lazy_static"]
metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
diff --git a/screenpipe-core/build.rs b/screenpipe-core/build.rs
deleted file mode 100644
index fe4beffed..000000000
--- a/screenpipe-core/build.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-fn main() {
- #[cfg(feature = "pipes")]
- {
- use deno_core::extension;
- use std::env;
- use std::path::PathBuf;
-
- extension!(runjs, js = ["src/deno/runtime.js",]);
-
- let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
- let snapshot_path = out_dir.join("RUNJS_SNAPSHOT.bin");
-
- let snapshot = deno_core::snapshot::create_snapshot(
- deno_core::snapshot::CreateSnapshotOptions {
- cargo_manifest_dir: env!("CARGO_MANIFEST_DIR"),
- startup_snapshot: None,
- skip_op_registration: false,
- extensions: vec![runjs::init_ops_and_esm()],
- with_runtime_cb: None,
- extension_transpiler: None,
- },
- None,
- )
- .unwrap();
-
- std::fs::write(snapshot_path, snapshot.output).unwrap();
- }
-}
diff --git a/screenpipe-core/examples/simple-node-api-pipe/deno.json b/screenpipe-core/examples/simple-node-api-pipe/deno.json
new file mode 100644
index 000000000..0a4396f5e
--- /dev/null
+++ b/screenpipe-core/examples/simple-node-api-pipe/deno.json
@@ -0,0 +1,10 @@
+{
+ "imports": {
+ "zod": "npm:zod",
+ "ai": "npm:ai",
+ "ollama-ai-provider": "npm:ollama-ai-provider"
+ },
+ "tasks": {
+ "start": "deno run --allow-read --allow-write --allow-net --allow-env pipe.ts"
+ }
+}
\ No newline at end of file
diff --git a/screenpipe-core/examples/simple-node-api-pipe/main.rs b/screenpipe-core/examples/simple-node-api-pipe/main.rs
new file mode 100644
index 000000000..36290736f
--- /dev/null
+++ b/screenpipe-core/examples/simple-node-api-pipe/main.rs
@@ -0,0 +1,36 @@
+use std::path::Path;
+use anyhow::Result;
+use dirs::home_dir;
+use screenpipe_core::{download_pipe, run_pipe};
+use tracing::info;
+use tracing_subscriber::{fmt, prelude::*, EnvFilter};
+
+// ollama run nemotron-mini:4b-instruct-q4_k_m
+// cargo run --package screenpipe-core --example simple-node-api-pipe --features metal --features pipes
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let console_layer = fmt::layer()
+ .with_writer(std::io::stdout)
+ .with_filter(EnvFilter::new("info"));
+ tracing_subscriber::registry().with(console_layer).init();
+
+ // Set up the path to the screenpipe directory
+ let screenpipe_dir = home_dir().unwrap().join(".screenpipe");
+
+ // The name of the pipe (folder name in examples)
+ let pipe_url = "screenpipe-core/examples/simple-node-api-pipe";
+ let pipe_name = Path::new(pipe_url).file_name().unwrap().to_str().unwrap();
+ info!("Starting the simple Node.js API pipe...");
+
+ // download the pipe
+ download_pipe(pipe_url, screenpipe_dir.clone()).await?;
+
+ // Run the pipe
+ match run_pipe(pipe_name, screenpipe_dir).await {
+ Ok(_) => println!("Pipe execution completed successfully."),
+ Err(e) => eprintln!("Error executing pipe: {}", e),
+ }
+
+ Ok(())
+}
diff --git a/screenpipe-core/examples/simple-node-api-pipe/pipe.ts b/screenpipe-core/examples/simple-node-api-pipe/pipe.ts
new file mode 100644
index 000000000..eb227128f
--- /dev/null
+++ b/screenpipe-core/examples/simple-node-api-pipe/pipe.ts
@@ -0,0 +1,88 @@
+
+import { z } from "zod";
+import { streamText } from "ai";
+import { ollama } from "ollama-ai-provider";
+import * as fs from "node:fs/promises";
+
+const screenpipeQuery = z.object({
+ q: z.string().optional(),
+ content_type: z.enum(["ocr", "audio", "all"]).default("all"),
+ limit: z.number().default(20),
+ start_time: z.string().default(new Date(Date.now() - 3600000).toISOString()),
+ end_time: z.string().default(new Date().toISOString()),
+});
+
+async function queryScreenpipe(params: z.infer<typeof screenpipeQuery>) {
+ try {
+ const queryParams = new URLSearchParams(
+ Object.entries(params).filter(([_, v]) => v != null) as [string, string][]
+ );
+ console.log("calling screenpipe", JSON.stringify(params));
+ const response = await fetch(`http://localhost:3030/search?${queryParams}`);
+ if (!response.ok) {
+ throw new Error(`http error! status: ${response.status}`);
+ }
+ return await response.json();
+ } catch (error) {
+ console.error("error querying screenpipe:", error);
+ return null;
+ }
+}
+
+const simpleOllamaChat = async () => {
+ console.log(
+ "starting simple ollama chat. make sure to run `ollama run nemotron-mini:4b-instruct-q4_k_m` before running this script."
+ );
+ const provider = ollama("nemotron-mini:4b-instruct-q4_k_m");
+
+ while (true) {
+ try {
+ // query last 1 min of screenpipe
+ const screenpipe = await queryScreenpipe({
+ content_type: "all",
+ limit: 10,
+ start_time: new Date(Date.now() - 60000).toISOString(),
+ end_time: new Date().toISOString(),
+ });
+ console.log(
+ "got some screenpipe data of length:",
+ screenpipe.data.length
+ );
+
+ const conversation: { role: string; content: string }[] = [
+ {
+ role: "user",
+ content:
+ "what did i do in the last minute? here is the screenpipe data: " +
+ JSON.stringify(screenpipe),
+ },
+ ];
+
+ const { textStream } = await streamText({
+ model: provider,
+ messages: conversation,
+ maxToolRoundtrips: 3,
+ });
+
+ process.stdout.write("ai: ");
+ for await (const chunk of textStream) {
+ process.stdout.write(chunk);
+ }
+ console.log(); // new line after the complete response
+
+ // log conversation to file
+ await fs.appendFile(
+ "conversation_log.txt",
+ JSON.stringify(conversation) + "\n"
+ );
+ } catch (error) {
+ console.error("error in ollama chat:", error);
+ }
+ }
+};
+
+const main = async () => {
+ await simpleOllamaChat();
+};
+
+main();
diff --git a/screenpipe-core/examples/simple-ollama-pipe/deno.json b/screenpipe-core/examples/simple-ollama-pipe/deno.json
new file mode 100644
index 000000000..58f418473
--- /dev/null
+++ b/screenpipe-core/examples/simple-ollama-pipe/deno.json
@@ -0,0 +1,7 @@
+{
+ "imports": {
+ "zod": "npm:zod",
+ "ai": "npm:ai",
+ "ollama-ai-provider": "npm:ollama-ai-provider"
+ }
+}
\ No newline at end of file
diff --git a/screenpipe-core/examples/simple-ollama-pipe/deno.lock b/screenpipe-core/examples/simple-ollama-pipe/deno.lock
new file mode 100644
index 000000000..7d1086ef9
--- /dev/null
+++ b/screenpipe-core/examples/simple-ollama-pipe/deno.lock
@@ -0,0 +1,438 @@
+{
+ "version": "4",
+ "specifiers": {
+ "npm:ai@*": "[email protected]",
+ "npm:ollama-ai-provider@*": "[email protected]",
+ "npm:zod@*": "3.23.8"
+ },
+ "npm": {
+ "integrity": "sha512-ngg/RGpnA00eNOWEtXHenpX1MsM2QshQh4QJFjUfwcqHpM5kTfG7je7Rc3HcEDP+OkRVv2GF+X4fC1Vfcnl8Ow==",
+ "dependencies": [
+ "@ai-sdk/provider",
+ "eventsource-parser",
+ "secure-json-parse",
+ "zod"
+ ]
+ },
+ "@ai-sdk/[email protected]": {
+ "integrity": "sha512-XMsNGJdGO+L0cxhhegtqZ8+T6nn4EoShS819OvCgI2kLbYTIvk0GWFGD0AXJmxkxs3DrpsJxKAFukFR7bvTkgQ==",
+ "dependencies": [
+ "json-schema"
+ ]
+ },
+ "integrity": "sha512-1asDpxgmeHWL0/EZPCLENxfOHT+0jce0z/zasRhascodm2S6f6/KZn5doLG9jdmarcb+GjMjFmmwyOVXz3W1xg==",
+ "dependencies": [
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/ui-utils",
+ "swr",
+ "zod"
+ ]
+ },
+ "integrity": "sha512-KnfWTt640cS1hM2fFIba8KHSPLpOIWXtEm28pNCHTvqasVKlh2y/zMQANTwE18pF2nuXL9P9F5/dKWaPsaEzQw==",
+ "dependencies": [
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/ui-utils"
+ ]
+ },
+ "integrity": "sha512-aIZJaIds+KpCt19yUDCRDWebzF/17GCY7gN9KkcA2QM6IKRO5UmMcqEYja0ZmwFQPm1kBZkF2njhr8VXis2mAw==",
+ "dependencies": [
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/ui-utils",
+ "sswr"
+ ]
+ },
+ "integrity": "sha512-ZG/wneyJG+6w5Nm/hy1AKMuRgjPQToAxBsTk61c9sVPUTaxo+NNjM2MhXQMtmsja2N5evs8NmHie+ExEgpL3cA==",
+ "dependencies": [
+ "@ai-sdk/provider",
+ "@ai-sdk/provider-utils",
+ "json-schema",
+ "secure-json-parse",
+ "zod",
+ "zod-to-json-schema"
+ ]
+ },
+ "integrity": "sha512-Ltu6gbuii8Qlp3gg7zdwdnHdS4M8nqKDij2VVO1223VOtIFwORFJzKqpfx44U11FW8z2TPVBYN+FjkyVIcN2hg==",
+ "dependencies": [
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/ui-utils",
+ "swrv"
+ ]
+ },
+ "@ampproject/[email protected]": {
+ "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
+ "dependencies": [
+ "@jridgewell/gen-mapping",
+ "@jridgewell/trace-mapping"
+ ]
+ },
+ "@babel/[email protected]": {
+ "integrity": "sha512-CbkjYdsJNHFk8uqpEkpCvRs3YRp9tY6FmFY7wLMSYuGYkrdUi7r2lc4/wqsvlHoMznX3WJ9IP8giGPq68T/Y6g=="
+ },
+ "@babel/[email protected]": {
+ "integrity": "sha512-AM6TzwYqGChO45oiuPqwL2t20/HdMC1rTPAesnBCgPCSF1x3oN9MVUwQV2iyz4xqWrctwK5RNC8LV22kaQCNYg=="
+ },
+ "@babel/[email protected]": {
+ "integrity": "sha512-HcttkxzdPucv3nNFmfOOMfFf64KgdJVqm1KaCm25dPGMLElo9nsLvXeJECQg8UzPuBGLyTSA0ZzqCtDSzKTEoQ==",
+ "dependencies": [
+ "@babel/types"
+ ]
+ },
+ "@babel/[email protected]": {
+ "integrity": "sha512-JWtuCu8VQsMladxVz/P4HzHUGCAwpuqacmowgXFs5XjxIgKuNjnLokQzuVjlTvIzODaDmpjT3oxcC48vyk9EWg==",
+ "dependencies": [
+ "@babel/helper-string-parser",
+ "@babel/helper-validator-identifier",
+ "to-fast-properties"
+ ]
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==",
+ "dependencies": [
+ "@jridgewell/set-array",
+ "@jridgewell/sourcemap-codec",
+ "@jridgewell/trace-mapping"
+ ]
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A=="
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ=="
+ },
+ "@jridgewell/[email protected]": {
+ "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==",
+ "dependencies": [
+ "@jridgewell/resolve-uri",
+ "@jridgewell/sourcemap-codec"
+ ]
+ },
+ "@opentelemetry/[email protected]": {
+ "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="
+ },
+ "@types/[email protected]": {
+ "integrity": "sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg=="
+ },
+ "@types/[email protected]": {
+ "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw=="
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-PwAdxs7/9Hc3ieBO12tXzmTD+Ln4qhT/56S+8DvrrZ4kLDn4Z/AMUr8tXJD0axiJBS0RKIoNaR0yMuQB9v9Udg==",
+ "dependencies": [
+ "@babel/parser",
+ "@vue/shared",
+ "entities",
+ "source-map-js"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-pyGf8zdbDDRkBrEzf8p7BQlMKNNF5Fk/Cf/fQ6PiUz9at4OaUfyXW0dGJTo2Vl1f5U9jSLCNf0EZJEogLXoeew==",
+ "dependencies": [
+ "@vue/compiler-core",
+ "@vue/shared"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-gsbBtT4N9ANXXepprle+X9YLg2htQk1sqH/qGJ/EApl+dgpUBdTv3yP7YlR535uHZY3n6XaR0/bKo0BgwwDniw==",
+ "dependencies": [
+ "@babel/parser",
+ "@vue/compiler-core",
+ "@vue/compiler-dom",
+ "@vue/compiler-ssr",
+ "@vue/shared",
+ "magic-string",
+ "postcss",
+ "source-map-js"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-P4+GPjOuC2aFTk1Z4WANvEhyOykcvEd5bIj2KVNGKGfM745LaXGr++5njpdBTzVz5pZifdlR1kpYSJJpIlSePA==",
+ "dependencies": [
+ "@vue/compiler-dom",
+ "@vue/shared"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-Nqo5VZEn8MJWlCce8XoyVqHZbd5P2NH+yuAaFzuNSR96I+y1cnuUiq7xfSG+kyvLSiWmaHTKP1r3OZY4mMD50w==",
+ "dependencies": [
+ "@vue/shared"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-7PsxFGqwfDhfhh0OcDWBG1DaIQIVOLgkwA5q6MtkPiDFjp5gohVnJEahSktwSFLq7R5PtxDKy6WKURVN1UDbzA==",
+ "dependencies": [
+ "@vue/reactivity",
+ "@vue/shared"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-GNghjecT6IrGf0UhuYmpgaOlN7kxzQBhxWEn08c/SQDxv1yy4IXI1bn81JgEpQ4IXjRxWtPyI8x0/7TF5rPfYQ==",
+ "dependencies": [
+ "@vue/reactivity",
+ "@vue/runtime-core",
+ "@vue/shared",
+ "csstype"
+ ]
+ },
+ "integrity": "sha512-cVOwYBxR7Wb1B1FoxYvtjJD8X/9E5nlH4VSkJy2uMA1MzYNdzAAB//l8nrmN9py/4aP+3NjWukf9PZ3TeWULaA==",
+ "dependencies": [
+ "@vue/compiler-ssr",
+ "@vue/shared",
+ "vue"
+ ]
+ },
+ "@vue/[email protected]": {
+ "integrity": "sha512-W8GgysJVnFo81FthhzurdRAWP/byq3q2qIw70e0JWblzVhjgOMiC2GyovXrZTFQJnFVryYaKGP3Tc9vYzYm6PQ=="
+ },
+ "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg=="
+ },
+ "integrity": "sha512-wmVzpIHNGjCEjIJ/3945a/DIkz+gwObjC767ZRgO8AmtIZMO5KqvqNr7n2KF+gQrCPCMC8fM1ICQFXSvBZnBlA==",
+ "dependencies": [
+ "@ai-sdk/provider",
+ "@ai-sdk/provider-utils",
+ "@ai-sdk/react",
+ "@ai-sdk/solid",
+ "@ai-sdk/svelte",
+ "@ai-sdk/ui-utils",
+ "@ai-sdk/vue",
+ "@opentelemetry/api",
+ "eventsource-parser",
+ "json-schema",
+ "jsondiffpatch",
+ "secure-json-parse",
+ "zod",
+ "zod-to-json-schema"
+ ]
+ },
+ "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw=="
+ },
+ "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="
+ },
+ "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w=="
+ },
+ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="
+ },
+ "integrity": "sha512-7qJWqItLA8/VPVlKJlFXU+NBlo/qyfs39aJcuMT/2ere32ZqvF5OSxgdM5xOfJJ7O429gg2HM47y8v9P+9wrNw==",
+ "dependencies": [
+ "@jridgewell/sourcemap-codec",
+ "@types/estree",
+ "acorn",
+ "periscopic"
+ ]
+ },
+ "integrity": "sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==",
+ "dependencies": [
+ "mdn-data",
+ "source-map-js"
+ ]
+ },
+ "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="
+ },
+ "integrity": "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw=="
+ },
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="
+ },
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="
+ },
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dependencies": [
+ "@types/estree"
+ ]
+ },
+ "integrity": "sha512-v0eOBUbiaFojBu2s2NPBfYUoRR9GjcDNvCXVaqEf5vVfpIAh9f8RCo4vXTP8c63QRKCFwoLpMpTdPwwhEKVgzA=="
+ },
+ "integrity": "sha512-v3rht/LgVcsdZa3O2Nqs+NMowLOxeOm7Ay9+/ARQ2F+qEoANRcqrjAZKGN0v8ymUetZGgkp26LTnGT7H0Qo9Pg==",
+ "dependencies": [
+ "@types/estree"
+ ]
+ },
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
+ },
+ "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="
+ },
+ "integrity": "sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==",
+ "dependencies": [
+ "@types/diff-match-patch",
+ "chalk",
+ "diff-match-patch"
+ ]
+ },
+ "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA=="
+ },
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "dependencies": [
+ "js-tokens"
+ ]
+ },
+ "integrity": "sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==",
+ "dependencies": [
+ "@jridgewell/sourcemap-codec"
+ ]
+ },
+ "integrity": "sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA=="
+ },
+ "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA=="
+ },
+ "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g=="
+ },
+ "integrity": "sha512-bMDUlYmohulD87Xrv6meuftQdmFTygtrQywy6/gqdf1bTsJFP1VCx3MrisLFBzb4mMOj02NER7yZhiGIlAx30w==",
+ "dependencies": [
+ "@ai-sdk/provider",
+ "@ai-sdk/provider-utils",
+ "partial-json",
+ "zod"
+ ]
+ },
+ "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA=="
+ },
+ "integrity": "sha512-vKiQ8RRtkl9P+r/+oefh25C3fhybptkHKCZSPlcXiJux2tJF55GnEj3BVn4A5gKfq9NWWXXrxkHBwVPUfH0opw==",
+ "dependencies": [
+ "@types/estree",
+ "is-reference"
+ ]
+ },
+ "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw=="
+ },
+ "integrity": "sha512-56rxCq7G/XfB4EkXq9Egn5GCqugWvDFjafDOThIdMBsI15iqPqR5r15TfSr1YPYeEI19YeaXMCbY6u88Y76GLQ==",
+ "dependencies": [
+ "picocolors",
+ "source-map-js"
+ ]
+ },
+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
+ "dependencies": [
+ "loose-envify"
+ ]
+ },
+ "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw=="
+ },
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="
+ },
+ "integrity": "sha512-Cqc355SYlTAaUt8iDPaC/4DPPXK925PePLMxyBKuWd5kKc5mwsG3nT9+Mq2tyguL5s7b4Jg+IRMpTRsNTAfpSQ==",
+ "dependencies": [
+ "svelte",
+ "swrev"
+ ]
+ },
+ "integrity": "sha512-IY1rnGr6izd10B0A8LqsBfmlT5OILVuZ7XsI0vdGPEvuonFV7NYEUK4dAkm9Zg2q0Um92kYjTpS1CAP3Nh/KWw==",
+ "dependencies": [
+ "@ampproject/remapping",
+ "@jridgewell/sourcemap-codec",
+ "@jridgewell/trace-mapping",
+ "@types/estree",
+ "acorn",
+ "aria-query",
+ "axobject-query",
+ "code-red",
+ "css-tree",
+ "is-reference",
+ "locate-character",
+ "magic-string",
+ "periscopic"
+ ]
+ },
+ "integrity": "sha512-QtxqyclFeAsxEUeZIYmsaQ0UjimSq1RZ9Un7I68/0ClKK/U3LoyQunwkQfJZr2fc22DfIXLNDc2wFyTEikCUpg==",
+ "dependencies": [
+ "client-only",
+ "react",
+ "use-sync-external-store"
+ ]
+ },
+ "integrity": "sha512-LqVcOHSB4cPGgitD1riJ1Hh4vdmITOp+BkmfmXRh4hSF/t7EnS4iD+SOTmq7w5pPm/SiPeto4ADbKS6dHUDWFA=="
+ },
+ "integrity": "sha512-zjEkcP8Ywmj+xOJW3lIT65ciY/4AL4e/Or7Gj0MzU3zBJNMdJiT8geVZhINavnlHRMMCcJLHhraLTAiDOTmQ9g==",
+ "dependencies": [
+ "vue"
+ ]
+ },
+ "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog=="
+ },
+ "integrity": "sha512-PElTlVMwpblvbNqQ82d2n6RjStvdSoNe9FG28kNfz3WiXilJm4DdNkEzRhCZuIDwY8U08WVihhGR5iRqAwfDiw==",
+ "dependencies": [
+ "react"
+ ]
+ },
+ "integrity": "sha512-/8Wurrd9J3lb72FTQS7gRMNQD4nztTtKPmuDuPuhqXmmpD6+skVjAeahNpVzsuky6Sy9gy7wn8UadqPtt9SQIg==",
+ "dependencies": [
+ "@vue/compiler-dom",
+ "@vue/compiler-sfc",
+ "@vue/runtime-dom",
+ "@vue/server-renderer",
+ "@vue/shared"
+ ]
+ },
+ "integrity": "sha512-uSt90Gzc/tUfyNqxnjlfBs8W6WSGpNBv0rVsNxP/BVSMHMKGdthPYff4xtCHYloJGM0CFxFsb3NbC0eqPhfImw==",
+ "dependencies": [
+ "zod"
+ ]
+ },
+ "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g=="
+ }
+ },
+ "workspace": {
+ "dependencies": [
+ "npm:ai@*",
+ "npm:ollama-ai-provider@*",
+ "npm:zod@*"
+ ]
+ }
+}
diff --git a/screenpipe-core/examples/simple-ollama-pipe/main.rs b/screenpipe-core/examples/simple-ollama-pipe/main.rs
new file mode 100644
index 000000000..750280d4d
--- /dev/null
+++ b/screenpipe-core/examples/simple-ollama-pipe/main.rs
@@ -0,0 +1,37 @@
+use std::path::Path;
+
+use anyhow::Result;
+use dirs::home_dir;
+use screenpipe_core::{download_pipe, run_pipe};
+use tracing::info;
+use tracing_subscriber::{fmt, prelude::*, EnvFilter};
+
+// ollama run nemotron-mini:4b-instruct-q4_k_m
+// cargo run --package screenpipe-core --example simple-ollama-pipe --features metal --features pipes
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let console_layer = fmt::layer()
+ .with_writer(std::io::stdout)
+ .with_filter(EnvFilter::new("info"));
+ tracing_subscriber::registry().with(console_layer).init();
+
+ // Set up the path to the screenpipe directory
+ let screenpipe_dir = home_dir().unwrap().join(".screenpipe");
+
+ // The name of the pipe (folder name in examples)
+ let pipe_url = "screenpipe-core/examples/simple-ollama-pipe";
+ let pipe_name = Path::new(pipe_url).file_name().unwrap().to_str().unwrap();
+ info!("Starting the simple Ollama chat pipe...");
+
+ // download the pipe
+ download_pipe(pipe_url, screenpipe_dir.clone()).await?;
+
+ // Run the pipe
+ match run_pipe(pipe_name, screenpipe_dir).await {
+ Ok(_) => println!("Pipe execution completed successfully."),
+ Err(e) => eprintln!("Error executing pipe: {}", e),
+ }
+
+ Ok(())
+}
diff --git a/screenpipe-core/examples/simple-ollama-pipe/pipe.ts b/screenpipe-core/examples/simple-ollama-pipe/pipe.ts
new file mode 100644
index 000000000..e476211d4
--- /dev/null
+++ b/screenpipe-core/examples/simple-ollama-pipe/pipe.ts
@@ -0,0 +1,80 @@
+import { z } from "zod";
+import { streamText } from "ai";
+import { ollama } from "ollama-ai-provider";
+
+const screenpipeQuery = z.object({
+ q: z.string().optional(),
+ content_type: z.enum(["ocr", "audio", "all"]).default("all"),
+ limit: z.number().default(20),
+ start_time: z.string().default(new Date(Date.now() - 3600000).toISOString()),
+ end_time: z.string().default(new Date().toISOString()),
+});
+
+async function queryScreenpipe(params: z.infer<typeof screenpipeQuery>) {
+ try {
+ const queryParams = new URLSearchParams(
+ Object.entries(params).filter(([_, v]) => v != null) as [string, string][]
+ );
+ console.log("Calling screenpipe", JSON.stringify(params));
+ const response = await fetch(`http://localhost:3030/search?${queryParams}`);
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ return await response.json();
+ } catch (error) {
+ console.error("Error querying screenpipe:", error);
+ return null;
+ }
+}
+
+const simpleOllamaChat = async () => {
+ console.log(
+ "Starting simple Ollama chat. Make sure to run `ollama run nemotron-mini:4b-instruct-q4_K_M` before running this script."
+ );
+ const provider = ollama("nemotron-mini:4b-instruct-q4_K_M");
+
+ while (true) {
+ try {
+ // query last 1 min of screenpipe
+ const screenpipe = await queryScreenpipe({
+ content_type: "all",
+ limit: 10,
+ start_time: new Date(Date.now() - 60000).toISOString(),
+ end_time: new Date().toISOString(),
+ });
+ console.log(
+ "got some screenpipe data of length:",
+ screenpipe.data.length
+ );
+
+ const conversation: { role: string; content: string }[] = [
+ {
+ role: "user",
+ content:
+ "What did I do in the last minute? Here is the screenpipe data: " +
+ JSON.stringify(screenpipe),
+ },
+ ];
+
+ const { textStream } = await streamText({
+ model: provider,
+ messages: conversation,
+ maxToolRoundtrips: 3,
+ });
+
+ process.stdout.write("ai: ");
+ for await (const chunk of textStream) {
+ process.stdout.write(chunk);
+ }
+ console.log(); // new line after the complete response
+ } catch (error) {
+ console.error("error in ollama chat:", error);
+ }
+ }
+};
+
+const main = async () => {
+ await simpleOllamaChat();
+};
+
+main();
diff --git a/screenpipe-core/examples/simple-pipe-api-pipe/deno.json b/screenpipe-core/examples/simple-pipe-api-pipe/deno.json
new file mode 100644
index 000000000..0a4396f5e
--- /dev/null
+++ b/screenpipe-core/examples/simple-pipe-api-pipe/deno.json
@@ -0,0 +1,10 @@
+{
+ "imports": {
+ "zod": "npm:zod",
+ "ai": "npm:ai",
+ "ollama-ai-provider": "npm:ollama-ai-provider"
+ },
+ "tasks": {
+ "start": "deno run --allow-read --allow-write --allow-net --allow-env pipe.ts"
+ }
+}
\ No newline at end of file
diff --git a/screenpipe-core/examples/simple-pipe-api-pipe/main.rs b/screenpipe-core/examples/simple-pipe-api-pipe/main.rs
new file mode 100644
index 000000000..d5b2ee4df
--- /dev/null
+++ b/screenpipe-core/examples/simple-pipe-api-pipe/main.rs
@@ -0,0 +1,36 @@
+use std::path::Path;
+use anyhow::Result;
+use dirs::home_dir;
+use screenpipe_core::{download_pipe, run_pipe};
+use tracing::info;
+use tracing_subscriber::{fmt, prelude::*, EnvFilter};
+
+// ollama run nemotron-mini:4b-instruct-q4_k_m
+// cargo run --package screenpipe-core --example simple-pipe-api-pipe --features metal --features pipes
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let console_layer = fmt::layer()
+ .with_writer(std::io::stdout)
+ .with_filter(EnvFilter::new("info"));
+ tracing_subscriber::registry().with(console_layer).init();
+
+ // Set up the path to the screenpipe directory
+ let screenpipe_dir = home_dir().unwrap().join(".screenpipe");
+
+ // The name of the pipe (folder name in examples)
+ let pipe_url = "screenpipe-core/examples/simple-pipe-api-pipe";
+ let pipe_name = Path::new(pipe_url).file_name().unwrap().to_str().unwrap();
+ info!("Starting the simple pipe API pipe...");
+
+ // download the pipe
+ download_pipe(pipe_url, screenpipe_dir.clone()).await?;
+
+ // Run the pipe
+ match run_pipe(pipe_name, screenpipe_dir).await {
+ Ok(_) => println!("Pipe execution completed successfully."),
+ Err(e) => eprintln!("Error executing pipe: {}", e),
+ }
+
+ Ok(())
+}
diff --git a/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts b/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts
new file mode 100644
index 000000000..0181075ee
--- /dev/null
+++ b/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts
@@ -0,0 +1,56 @@
+import { z } from "zod";
+import { streamText } from "ai";
+import { ollama } from "ollama-ai-provider";
+import { queryScreenpipe } from "https://raw.githubusercontent.com/mediar-ai/screenpipe/deno-thru-cli/screenpipe-js/main.ts";
+
+const simpleOllamaChat = async () => {
+ console.log(
+ "starting simple ollama chat. make sure to run `ollama run nemotron-mini:4b-instruct-q4_k_m` before running this script."
+ );
+ const provider = ollama("nemotron-mini:4b-instruct-q4_k_m");
+
+ while (true) {
+ try {
+ // query last 1 min of screenpipe
+ const screenpipe = await queryScreenpipe({
+ content_type: "all",
+ limit: 10,
+ start_time: new Date(Date.now() - 60000).toISOString(),
+ end_time: new Date().toISOString(),
+ });
+ console.log(
+ "got some screenpipe data of length:",
+ screenpipe.data.length
+ );
+
+ const conversation: { role: string; content: string }[] = [
+ {
+ role: "user",
+ content:
+ "what did i do in the last minute? here is the screenpipe data: " +
+ JSON.stringify(screenpipe),
+ },
+ ];
+
+ const { textStream } = await streamText({
+ model: provider,
+ messages: conversation,
+ maxToolRoundtrips: 3,
+ });
+
+ process.stdout.write("ai: ");
+ for await (const chunk of textStream) {
+ process.stdout.write(chunk);
+ }
+ console.log(); // new line after the complete response
+ } catch (error) {
+ console.error("error in ollama chat:", error);
+ }
+ }
+};
+
+const main = async () => {
+ await simpleOllamaChat();
+};
+
+main();
diff --git a/screenpipe-core/src/deno/runtime.js b/screenpipe-core/src/deno/runtime.js
deleted file mode 100644
index a79906588..000000000
--- a/screenpipe-core/src/deno/runtime.js
+++ /dev/null
@@ -1,293 +0,0 @@
-const { core } = Deno;
-const { ops } = core;
-const Path = {
- isAbsolute: (path) => path.startsWith('/') || /^[A-Za-z]:\\/.test(path),
- join: (...parts) => parts.join('/').replace(/\/+/g, '/'),
-};
-
-function argsToMessage(...args) {
- return args.map((arg) => JSON.stringify(arg)).join(" ");
-}
-
-const sendLog = async (level, ...args) => {
- const message = argsToMessage(...args);
- const logApiUrl = process.env.SCREENPIPE_LOG_API_URL || "http://localhost:11435/log";
- const pipeId = globalThis.metadata.id || "unknown";
-
- try {
- await ops.op_fetch(logApiUrl, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- pipeId,
- level,
- message,
- timestamp: new Date().toISOString(),
- }),
- });
- } catch (error) {
- // core.print(`[js][error]: Failed to send log: ${error}\n`, true);
- }
-};
-
-const console = {
- log: (...args) => {
- core.print(`[pipe][${globalThis.metadata.id}][info]: ${argsToMessage(...args)}\n`, false);
- // sendLog("info", ...args);
- },
- error: (...args) => {
- core.print(`[pipe][${globalThis.metadata.id}][error]: ${argsToMessage(...args)}\n`, true);
- // sendLog("error", ...args);
- },
- warn: (...args) => {
- core.print(`[pipe][${globalThis.metadata.id}][warn]: ${argsToMessage(...args)}\n`, true);
- // sendLog("warn", ...args);
- }
-};
-
-globalThis.console = console;
-
-const pipe = {
- readFile: (path) => {
- let fullPath;
- if (Path.isAbsolute(path)) {
- fullPath = path;
- } else {
- const pipeDir = `${process.env.SCREENPIPE_DIR}/pipes/${globalThis.metadata.id}`;
- fullPath = Path.join(pipeDir, path);
- }
- return ops.op_read_file(fullPath);
- },
-
- removeFile: (path) => {
- let fullPath;
- if (Path.isAbsolute(path)) {
- fullPath = path;
- } else {
- const pipeDir = `${process.env.SCREENPIPE_DIR}/pipes/${globalThis.metadata.id}`;
- fullPath = Path.join(pipeDir, path);
- }
- return ops.op_remove_file(fullPath);
- },
-
- get: async (url) => {
- const response = await ops.op_fetch_get(url);
- return JSON.parse(response);
- },
- post: async (url, body) => {
- const response = await ops.op_fetch_post(url, body);
- return JSON.parse(response);
- },
- fetch: async (url, options) => {
- try {
- const responseString = await ops.op_fetch(url, options);
- const response = JSON.parse(responseString);
- return {
- ok: response.status >= 200 && response.status < 300,
- status: response.status,
- statusText: response.statusText,
- headers: response.headers, // Use the headers directly without wrapping in Headers object
- text: async () => response.text,
- json: async () => {
- try {
- return JSON.parse(response.text);
- } catch (error) {
- console.error("Error parsing JSON:", error);
- return response.text;
- }
- },
- };
- } catch (error) {
- console.error("Fetch error:", error);
- throw error;
- }
- },
- sendNotification: async ({ title, body }) => {
- // try to fetch this url, if not live do try to send the notification to the server
- const notificationApiUrl = process.env.SCREENPIPE_SERVER_URL || "http://localhost:11435";
-
- try {
- const response = await ops.op_fetch(notificationApiUrl + "/notify", {
- headers: {
- "Content-Type": "application/json",
- },
- method: "POST",
- body: JSON.stringify({ title, body })
- });
- console.log("Notification sent:", response);
- return JSON.parse(response);
- } catch (error) {
- console.log("Failed to send notification to server, is your notification server running?");
- return false;
- }
- },
- loadConfig: async () => {
- try {
- console.log("Attempting to load pipe.json");
- const configContent = await ops.op_read_file(process.env.SCREENPIPE_DIR + "/pipes/" + globalThis.metadata.id + "/pipe.json");
- console.log("pipe.json content:", configContent);
- const parsedConfig = JSON.parse(configContent);
- console.log("Parsed config:", parsedConfig);
-
- // Process the fields and set the config values
- const config = {};
- parsedConfig.fields.forEach(field => {
- config[field.name] = field.value !== undefined ? field.value : field.default;
- });
-
- pipe.config = config; // Set the processed config
- console.log("Processed config:", config);
- return config;
- } catch (error) {
- console.error("Error loading pipe.json:", error);
- pipe.config = {}; // Set an empty object if loading fails
- return {};
- }
- },
- sendEmail: async ({ to, from, password, subject, body, contentType = 'text/plain' }) => {
- try {
- await ops.op_send_email(to, from, password, subject, body, contentType);
- return true;
- } catch (error) {
- console.error("Error sending email:", error);
- return false;
- }
- },
- // isEnabled: async () => {
- // return ops.op_is_enabled();
- // }
-};
-
-function encodeQueryData(data) {
- return Object.keys(data)
- .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
- .join('&');
-}
-
-pipe.queryScreenpipe = async (params) => {
- try {
- const queryParams = {
- content_type: params.content_type || 'all',
- limit: params.limit || 50,
- offset: params.offset || 0,
- start_time: params.start_time || new Date(Date.now() - 3600000).toISOString(),
- end_time: params.end_time || new Date().toISOString(),
- min_length: params.min_length || 50,
- max_length: params.max_length || 10000,
- include_frames: params.include_frames || false,
- };
-
- if (params.q) queryParams.q = params.q;
- if (params.app_name) queryParams.app_name = params.app_name;
- if (params.window_name) queryParams.window_name = params.window_name;
-
- const queryString = encodeQueryData(queryParams);
- const url = `http://localhost:3030/search?${queryString}`;
- console.log("calling screenpipe", url);
-
- const response = await pipe.fetch(url);
- if (!response.ok) {
- const text = await response.text();
- throw new Error(`http error! status: ${response.status} ${text}`);
- }
- return await response.json();
- } catch (error) {
- console.error("error querying screenpipe:", error);
- return null;
- }
-};
-
-const fs = {
- readFile: async (path) => {
- return await ops.op_read_file(path);
- },
- writeFile: async (path, contents) => {
- return await ops.op_write_file(path, contents);
- },
- readdir: async (path) => {
- return await ops.op_readdir(path);
- },
- mkdir: async (path) => {
- return await ops.op_create_dir(path);
- }
-};
-
-const path = {
- join: (...paths) => {
- const sep = process.env.OS === "windows" ? "\\" : "/";
- // This implementation works on both Unix and Windows
- return paths.join(sep).replace(new RegExp(`\\${sep}+`, 'g'), sep);
- },
-};
-
-globalThis.fs = fs;
-globalThis.path = path;
-
-globalThis.setTimeout = (callback, delay) => {
- ops.op_set_timeout(delay).then(callback);
-};
-globalThis.pipe = pipe;
-globalThis.pipe.metadata = globalThis.metadata;
-globalThis.fetch = pipe.fetch;
-globalThis.loadConfig = pipe.loadConfig;
-
-
-pipe.extractJsonFromLlmResponse = (response) => {
- // Remove any markdown code block syntax
- let cleaned = response.replace(/^```(?:json)?\s*|\s*```$/g, "");
-
- console.log("cleaned", cleaned);
-
- // Try to find JSON-like content
- const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
-
- console.log("jsonMatch", jsonMatch);
- if (jsonMatch) {
- cleaned = jsonMatch[0];
- }
-
- console.log("cleaned", cleaned);
- // Remove any non-JSON content before or after the main object
- cleaned = cleaned.replace(/^[^{]*/, "").replace(/[^}]*$/, "");
-
- console.log("cleaned", cleaned);
-
- // Replace any escaped newlines and remove actual newlines
- cleaned = cleaned.replace(/\\n/g, "").replace(/\n/g, "");
-
- console.log("cleaned", cleaned);
-
- // Handle nested JSON strings
- cleaned = cleaned.replace(/"(\\"|[^"])*"/g, (match) => {
- return match.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
- });
-
- console.log("cleaned", cleaned);
-
- try {
- return JSON.parse(cleaned);
- } catch (error) {
- console.warn("failed to parse json:", error);
- console.warn("cleaned content:", cleaned);
-
- // Attempt to fix common issues
- cleaned = cleaned
- .replace(/,\s*}/g, "}") // Remove trailing commas
- .replace(/'/g, '"') // Replace single quotes with double quotes
- .replace(/(\w+):/g, '"$1":') // Add quotes to keys
- .replace(/:\s*'([^']*)'/g, ': "$1"') // Replace single-quoted values with double-quoted values
- .replace(/\\"/g, '"') // Replace escaped double quotes with regular double quotes
- .replace(/"{/g, '{"') // Fix improperly escaped nested JSON
- .replace(/}"/g, '"}');
-
- try {
- return JSON.parse(cleaned);
- } catch (secondError) {
- console.warn("failed to parse json after attempted fixes:", secondError);
- throw new Error("invalid json format in llm response");
- }
- }
-};
-
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index 65d13d7a1..39f57068d 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -1,33 +1,19 @@
#[allow(clippy::module_inception)]
#[cfg(feature = "pipes")]
mod pipes {
- use deno_ast::MediaType;
- use deno_ast::ParseParams;
- use deno_ast::SourceTextInfo;
- use deno_core::error::AnyError;
- use deno_core::extension;
- use deno_core::op2;
- use deno_core::v8;
- use deno_core::ModuleLoadResponse;
- use deno_core::ModuleSourceCode;
- use lettre::message::header::ContentType;
use regex::Regex;
- use reqwest::header::HeaderMap;
- use reqwest::header::HeaderValue;
- use reqwest::header::CONTENT_TYPE;
- use std::collections::HashMap;
- use std::env;
use std::path::PathBuf;
- use std::rc::Rc;
- use tracing::debug;
+ use tokio::process::Command;
use reqwest::Client;
use serde_json::Value;
- use lettre::transport::smtp::authentication::Credentials;
- use lettre::{Message, SmtpTransport, Transport};
+ use anyhow::Result;
use reqwest;
+ use std::future::Future;
use std::path::Path;
+ use std::pin::Pin;
+ use tokio::io::{AsyncBufReadExt, BufReader};
use tracing::{error, info};
use url::Url;
@@ -44,554 +30,156 @@ mod pipes {
.to_string()
}
- #[op2]
- #[string]
- fn op_get_env(#[string] key: String) -> Option<String> {
- env::var(&key).ok()
- }
-
- #[op2(async)]
- #[string]
- async fn op_fetch(
- #[string] url: String,
- #[serde] options: Option<Value>,
- ) -> anyhow::Result<String, AnyError> {
- let client = Client::new();
- let mut request = client.get(&url);
-
- if let Some(opts) = options {
- if let Some(method) = opts.get("method").and_then(|m| m.as_str()) {
- request = match method.to_uppercase().as_str() {
- "GET" => client.get(&url),
- "POST" => client.post(&url),
- "PUT" => client.put(&url),
- "DELETE" => client.delete(&url),
- // Add other methods as needed
- _ => return Err(anyhow::anyhow!("Unsupported HTTP method")),
- };
- }
+ pub async fn run_pipe(pipe: &str, screenpipe_dir: PathBuf) -> Result<()> {
+ let pipe_dir = screenpipe_dir.join("pipes").join(pipe);
+ let main_module = find_pipe_file(&pipe_dir)?;
- if let Some(headers) = opts.get("headers").and_then(|h| h.as_object()) {
- for (key, value) in headers {
- if let Some(value_str) = value.as_str() {
- request = request.header(key, value_str);
- }
+ info!("executing pipe: {:?}", main_module);
+
+ // Prepare environment variables
+ let mut env_vars = std::env::vars().collect::<Vec<(String, String)>>();
+ env_vars.push((
+ "SCREENPIPE_DIR".to_string(),
+ screenpipe_dir.to_str().unwrap().to_string(),
+ ));
+ env_vars.push(("PIPE_ID".to_string(), pipe.to_string()));
+ env_vars.push((
+ "PIPE_FILE".to_string(),
+ main_module.to_str().unwrap().to_string(),
+ ));
+ env_vars.push((
+ "PIPE_DIR".to_string(),
+ pipe_dir.to_str().unwrap().to_string(),
+ ));
+
+ // Execute Deno
+ let mut child = Command::new("deno")
+ .arg("run")
+ .arg("--config")
+ .arg(pipe_dir.join("deno.json"))
+ .arg("--allow-read")
+ .arg("--allow-write")
+ .arg("--allow-net")
+ .arg("--allow-env")
+ .arg(&main_module)
+ .envs(env_vars)
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()?;
+
+ let stdout = child.stdout.take().expect("failed to get stdout");
+ let stderr = child.stderr.take().expect("failed to get stderr");
+
+ let pipe_clone = pipe.to_string();
+
+ // Spawn tasks to handle stdout and stderr
+ let stdout_handle = tokio::spawn(async move {
+ let reader = BufReader::new(stdout);
+ let mut lines = reader.lines();
+ while let Ok(line) = lines.next_line().await {
+ if let Some(line) = line {
+ info!("[pipe][info][{}] {}", pipe_clone, line);
}
}
-
- if let Some(body) = opts.get("body").and_then(|b| b.as_str()) {
- request = request.body(body.to_string());
- }
- }
-
- let response = match request.send().await {
- Ok(resp) => resp,
- Err(e) => return Err(anyhow::anyhow!(e)),
- };
-
- let status = response.status();
- let headers = response.headers().clone();
- let text = match response.text().await {
- Ok(t) => t,
- Err(e) => return Err(anyhow::anyhow!(e)),
- };
-
- let result = serde_json::json!({
- "status": status.as_u16(),
- "statusText": status.to_string(),
- "headers": headers.iter()
- .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
- .collect::<HashMap<String, String>>(),
- "text": text,
});
- Ok(result.to_string())
- }
-
- #[op2(async)]
- #[string]
- async fn op_read_file(#[string] path: String) -> anyhow::Result<String, AnyError> {
- let current_dir = std::env::current_dir()?;
- let full_path = current_dir.join(path);
- tokio::fs::read_to_string(&full_path).await.map_err(|e| {
- error!("Failed to read file '{}': {}", full_path.display(), e);
- AnyError::from(e)
- })
- }
-
- #[op2(async)]
- #[string]
- async fn op_write_file(
- #[string] path: String,
- #[string] contents: String,
- ) -> anyhow::Result<(), AnyError> {
- tokio::fs::write(&path, contents).await.map_err(|e| {
- error!("Failed to write file '{}': {}", path, e);
- AnyError::from(e)
- })
- }
+ let pipe_clone = pipe.to_string();
- #[op2(async)]
- #[serde]
- async fn op_readdir(#[string] path: String) -> anyhow::Result<Vec<String>, AnyError> {
- let mut entries = tokio::fs::read_dir(&path).await?;
- let mut file_names = Vec::new();
- while let Some(entry) = entries.next_entry().await? {
- if let Some(file_name) = entry.file_name().to_str() {
- file_names.push(file_name.to_string());
+ let stderr_handle = tokio::spawn(async move {
+ let reader = BufReader::new(stderr);
+ let mut lines = reader.lines();
+ while let Ok(line) = lines.next_line().await {
+ if let Some(line) = line {
+ error!("[pipe][error][{}] {}", pipe_clone, line);
+ }
}
- }
- Ok(file_names)
- }
+ });
- #[op2(async)]
- #[string]
- async fn op_fetch_get(#[string] url: String) -> anyhow::Result<String, AnyError> {
- let response = reqwest::get(&url).await?;
- let status = response.status();
- let text = response.text().await?;
-
- if !status.is_success() {
- error!("HTTP error status: {}, text: {}", status, text);
- return Err(AnyError::msg(format!(
- "HTTP error status: {}, text: {}",
- status, text
- )));
- }
+ // Wait for the child process to finish
+ let status = child.wait().await?;
- Ok(text)
- }
+ // Wait for the output handling tasks to finish
+ stdout_handle.await?;
+ stderr_handle.await?;
- #[op2(async)]
- #[string]
- async fn op_fetch_post(
- #[string] url: String,
- #[string] body: String,
- ) -> anyhow::Result<String, AnyError> {
- let client = reqwest::Client::new();
-
- // Create a HeaderMap and add the Content-Type header
- let mut headers = HeaderMap::new();
- headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
-
- let response = client.post(&url).headers(headers).body(body).send().await?;
-
- let status = response.status();
- let text = response.text().await?;
-
- if !status.is_success() {
- error!("HTTP error status: {}, text: {}", status, text);
- return Err(AnyError::msg(format!(
- "HTTP error status: {}, text: {}",
- status, text
- )));
+ if !status.success() {
+ anyhow::bail!("deno execution failed with status: {}", status);
}
- Ok(text)
- }
-
- #[op2(async)]
- async fn op_set_timeout(delay: f64) -> anyhow::Result<(), AnyError> {
- tokio::time::sleep(std::time::Duration::from_millis(delay as u64)).await;
- Ok(())
- }
-
- #[op2(fast)]
- fn op_remove_file(#[string] path: String) -> anyhow::Result<()> {
- std::fs::remove_file(path)?;
+ info!("deno execution completed successfully");
Ok(())
}
- #[op2(async)]
- #[string]
- async fn op_send_email(
- #[string] to: String,
- #[string] from: String,
- #[string] password: String,
- #[string] subject: String,
- #[string] body: String,
- #[string] content_type: String,
- ) -> anyhow::Result<String, AnyError> {
- let email = Message::builder()
- .from(from.parse()?)
- .to(to.parse()?)
- .subject(subject)
- .header(ContentType::parse(content_type.as_str())?)
- .body(body)?;
-
- let creds = Credentials::new(from.clone(), password);
-
- let mailer = SmtpTransport::relay("smtp.gmail.com")?
- .credentials(creds)
- .build();
-
- match mailer.send(&email) {
- Ok(_) => Ok("Email sent successfully".to_string()),
- Err(e) => Err(anyhow::anyhow!("Could not send email: {:?}", e)),
- }
- }
-
- #[op2(async)]
- async fn op_create_dir(#[string] path: String) -> anyhow::Result<(), AnyError> {
- tokio::fs::create_dir_all(&path).await.map_err(|e| {
- error!("Failed to create directory '{}': {}", path, e);
- AnyError::from(e)
- })
- }
-
- struct TsModuleLoader;
-
- impl deno_core::ModuleLoader for TsModuleLoader {
- fn resolve(
- &self,
- specifier: &str,
- referrer: &str,
- _kind: deno_core::ResolutionKind,
- ) -> Result<deno_core::ModuleSpecifier, AnyError> {
- deno_core::resolve_import(specifier, referrer).map_err(|e| e.into())
- }
-
- fn load(
- &self,
- module_specifier: &deno_core::ModuleSpecifier,
- _maybe_referrer: Option<&reqwest::Url>,
- _is_dyn_import: bool,
- _requested_module_type: deno_core::RequestedModuleType,
- ) -> ModuleLoadResponse {
- let module_specifier = module_specifier.clone();
-
- let module_load = Box::pin(async move {
- let path = module_specifier.to_file_path().unwrap();
-
- let media_type = MediaType::from_path(&path);
- let (module_type, should_transpile) = match MediaType::from_path(&path) {
- MediaType::JavaScript | MediaType::Mjs | MediaType::Cjs => {
- (deno_core::ModuleType::JavaScript, false)
- }
- MediaType::Jsx => (deno_core::ModuleType::JavaScript, true),
- MediaType::TypeScript
- | MediaType::Mts
- | MediaType::Cts
- | MediaType::Dts
- | MediaType::Dmts
- | MediaType::Dcts
- | MediaType::Tsx => (deno_core::ModuleType::JavaScript, true),
- MediaType::Json => (deno_core::ModuleType::Json, false),
- _ => panic!("Unknown extension {:?}", path.extension()),
- };
-
- let code = std::fs::read_to_string(&path)?;
- let code = if should_transpile {
- let parsed = deno_ast::parse_module(ParseParams {
- specifier: module_specifier.clone(),
- text_info: SourceTextInfo::from_string(code),
- media_type,
- capture_tokens: false,
- scope_analysis: false,
- maybe_syntax: None,
- })?;
- parsed
- .transpile(&Default::default(), &Default::default())?
- .into_source()
- .text
- } else {
- code
- };
- let module = deno_core::ModuleSource::new(
- module_type,
- ModuleSourceCode::String(code.into()),
- &module_specifier,
- None,
- );
- Ok(module)
- });
-
- ModuleLoadResponse::Async(module_load)
- }
- }
-
- static RUNTIME_SNAPSHOT: &[u8] =
- include_bytes!(concat!(env!("OUT_DIR"), "/RUNJS_SNAPSHOT.bin"));
-
- extension! {
- runjs,
- ops = [
- op_read_file,
- op_write_file,
- op_remove_file,
- op_readdir,
- op_create_dir,
-
- op_fetch_get,
- op_fetch_post,
- op_set_timeout,
- op_fetch,
- op_get_env,
- op_send_email,
- ]
- }
-
- pub async fn run_js(
- pipe: &str,
- file_path: &str,
- screenpipe_dir: PathBuf,
- ) -> anyhow::Result<()> {
- let main_module = deno_core::resolve_path(file_path, env::current_dir()?.as_path())?;
-
- // Adjust these values as needed
- let max_old_space_size = 2 * 1024 * 1024 * 1024; // 2GB
- let initial_old_space_size = 512 * 1024 * 1024; // 512MB
-
- let platform_params =
- v8::CreateParams::default().heap_limits(initial_old_space_size, max_old_space_size);
-
- let mut js_runtime = deno_core::JsRuntime::new(deno_core::RuntimeOptions {
- module_loader: Some(Rc::new(TsModuleLoader)),
- startup_snapshot: Some(RUNTIME_SNAPSHOT),
- create_params: Some(platform_params),
- extensions: vec![runjs::init_ops()],
- v8_platform: Some(v8::new_default_platform(0, false).make_shared()),
- ..Default::default()
- });
-
- // set some metadata on the runtime
- js_runtime.execute_script("main", "globalThis.metadata = { }")?;
- // set the pipe id
- js_runtime.execute_script("main", format!("globalThis.metadata.id = '{}'", pipe))?;
-
- // initialize process.env
- js_runtime.execute_script("main", "globalThis.process = { env: {} }")?;
-
- for (key, value) in env::vars() {
- if key.starts_with("SCREENPIPE_") {
- let escaped_value = value.replace('\\', "\\\\").replace('\"', "\\\"");
- js_runtime.execute_script(
- "main",
- format!(
- "process.env[{}] = \"{}\";",
- serde_json::to_string(&key)?,
- escaped_value
- ),
- )?;
- }
- }
-
- // set additional environment variables
- let home_dir = dirs::home_dir().unwrap_or_default();
- let current_dir = env::current_dir()?;
- let temp_dir = env::temp_dir();
-
- js_runtime.execute_script(
- "main",
- format!(
- r#"
- globalThis.process.env.SCREENPIPE_DIR = "{}";
- globalThis.process.env.HOME = "{}";
- globalThis.process.env.CURRENT_DIR = "{}";
- globalThis.process.env.TEMP_DIR = "{}";
- globalThis.process.env.PIPE_ID = "{}";
- globalThis.process.env.PIPE_FILE = "{}";
- globalThis.process.env.PIPE_DIR = "{}";
- globalThis.process.env.OS = "{}";
- "#,
- screenpipe_dir
- .to_string_lossy()
- .replace('\\', "\\\\")
- .replace('\"', "\\\""),
- home_dir
- .to_string_lossy()
- .replace('\\', "\\\\")
- .replace('\"', "\\\""),
- current_dir
- .to_string_lossy()
- .replace('\\', "\\\\")
- .replace('\"', "\\\""),
- temp_dir
- .to_string_lossy()
- .replace('\\', "\\\\")
- .replace('\"', "\\\""),
- pipe.replace('\"', "\\\""),
- file_path.replace('\\', "\\\\").replace('\"', "\\\""),
- screenpipe_dir
- .join("pipes")
- .join(pipe)
- .to_string_lossy()
- .replace('\\', "\\\\")
- .replace('\"', "\\\""),
- if cfg!(target_os = "windows") {
- "windows"
- } else {
- "unix"
- }
- ),
- )?;
-
- let mod_id = js_runtime.load_main_es_module(&main_module).await?;
- let evaluate_future = js_runtime.mod_evaluate(mod_id);
-
- // run the event loop and handle potential errors
- match js_runtime.run_event_loop(Default::default()).await {
- Ok(_) => (),
- Err(e) => {
- error!("error in javascript runtime event loop: {}", e);
- if let Some(source) = e.source() {
- error!(" Caused by: {}", source);
- }
- error!(" Backtrace: {:?}", e.backtrace());
- // you can choose to return the error or handle it differently
- // return Err(anyhow::anyhow!("javascript runtime error: {}", e));
- }
- }
-
- // evaluate the module and handle potential errors
- match evaluate_future.await {
- Ok(_) => Ok(()),
- Err(e) => {
- error!("error evaluating javascript module: {}", e);
- if let Some(source) = e.source() {
- error!(" Caused by: {}", source);
- }
- error!(" Backtrace: {:?}", e.backtrace());
-
- // you can choose to return the error or handle it differently
- Err(anyhow::anyhow!("javascript module evaluation error: {}", e))
- }
- }
- }
-
- pub async fn run_pipe(pipe: String, screenpipe_dir: PathBuf) -> anyhow::Result<()> {
- debug!(
- "Running pipe: {}, screenpipe_dir: {}",
- pipe,
- screenpipe_dir.display()
- );
-
- let pipe_dir = match Url::parse(&pipe) {
- Ok(_) => {
- info!("Input appears to be a URL. Attempting to download...");
-
- PathBuf::from(&pipe)
- }
- Err(_) => {
- info!("Input appears to be a local path. Attempting to canonicalize...");
- match screenpipe_dir.join("pipes").join(&pipe).canonicalize() {
- Ok(path) => path,
- Err(e) => {
- error!("Failed to canonicalize path: {}", e);
- anyhow::bail!("Failed to canonicalize path: {}", e);
- }
- }
- }
- };
-
- info!("Pipe directory: {:?}", pipe_dir);
-
- let main_module = find_pipe_file(&pipe_dir)?;
-
- info!("Executing pipe: {:?}", main_module);
+ pub async fn download_pipe(source: &str, screenpipe_dir: PathBuf) -> anyhow::Result<PathBuf> {
+ info!("processing pipe from source: {}", source);
- match run_js(&pipe, &main_module.to_string_lossy(), screenpipe_dir).await {
- Ok(_) => info!("JS execution completed successfully"),
- Err(error) => {
- error!("Error during JS execution: {}", error);
- anyhow::bail!("Error during JS execution: {}", error);
- }
- }
+ let pipe_name =
+ sanitize_pipe_name(Path::new(source).file_name().unwrap().to_str().unwrap());
+ let dest_dir = screenpipe_dir.join("pipes").join(&pipe_name);
- Ok(())
- }
+ // if dest_dir.exists() {
+ // info!("pipe already exists: {:?}", dest_dir);
+ // return Ok(dest_dir);
+ // }
+ // TODO
- pub async fn download_pipe(source: &str, screenpipe_dir: PathBuf) -> anyhow::Result<PathBuf> {
- info!("Processing pipe from source: {}", source);
+ tokio::fs::create_dir_all(&dest_dir).await?;
if let Ok(parsed_url) = Url::parse(source) {
- // Handle URLs
- let client = Client::new();
- match parsed_url.host_str() {
- Some("github.com") => {
- let api_url = get_raw_github_url(source)
- .map_err(|e| anyhow::anyhow!("Failed to parse GitHub URL: {}", e))?;
- let pipe_name = sanitize_pipe_name(
- Path::new(&api_url).file_name().unwrap().to_str().unwrap(),
- );
- download_github_folder(&client, &api_url, screenpipe_dir, &pipe_name).await
- }
- _ => anyhow::bail!("Unsupported URL format"),
+ if parsed_url.host_str() == Some("github.com") {
+ download_github_folder(&parsed_url, &dest_dir).await?;
+ } else {
+ anyhow::bail!("unsupported url format");
}
} else {
- // Handle local folders
let source_path = Path::new(source);
if !source_path.exists() {
- anyhow::bail!("Local source path does not exist");
+ anyhow::bail!("local source path does not exist");
}
if !source_path.is_dir() {
- anyhow::bail!("Local source is not a directory");
+ anyhow::bail!("local source is not a directory");
}
- let pipe_name = sanitize_pipe_name(
- source_path
- .file_name()
- .and_then(|name| name.to_str())
- .unwrap_or("unknown_pipe"),
- );
- let dest_dir = screenpipe_dir.join("pipes").join(&pipe_name);
-
- tokio::fs::create_dir_all(&dest_dir).await?;
- copy_local_folder(source_path, &dest_dir).await?;
-
- info!("Local pipe copied successfully to: {:?}", dest_dir);
- Ok(dest_dir)
+ copy_dir_all(source_path, &dest_dir).await?;
+ info!("Copied local folder: {:?} to {:?}", source_path, dest_dir);
}
+
+ info!("pipe copied successfully to: {:?}", dest_dir);
+ Ok(dest_dir)
}
- async fn copy_local_folder(src: &Path, dst: &Path) -> anyhow::Result<()> {
- let mut pipe_json: Value = serde_json::json!({});
- let pipe_json_path = dst.join("pipe.json");
+ async fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> anyhow::Result<()> {
+ tokio::fs::create_dir_all(&dst).await?;
+ let mut entries = tokio::fs::read_dir(src).await?;
- for entry in std::fs::read_dir(src)? {
- let entry = entry?;
- let file_type = entry.file_type()?;
- let file_name = entry.file_name();
+ while let Some(entry) = entries.next_entry().await? {
+ let ty = entry.file_type().await?;
+ let src_path = entry.path();
+ let dst_path = dst.as_ref().join(entry.file_name());
- if file_type.is_file() {
- if let Some(file_name_str) = file_name.clone().to_str() {
- if file_name_str == "pipe.js"
- || file_name_str == "pipe.ts"
- || file_name_str == "pipe.json"
- || file_name_str == "README.md"
- {
- let src_path = entry.path();
- let dst_path = dst.join(file_name);
- tokio::fs::copy(&src_path, &dst_path).await?;
- info!("Copied: {:?} to {:?}", src_path, dst_path);
-
- if file_name_str == "pipe.json" {
- let content = tokio::fs::read_to_string(&dst_path).await?;
- pipe_json = serde_json::from_str(&content)?;
- }
- }
- }
+ if ty.is_dir() {
+ copy_dir_all_boxed(src_path, dst_path).await?;
+ } else {
+ tokio::fs::copy(src_path, dst_path).await?;
}
}
- // Update pipe.json with the local source path at the root level
- // pipe_json["source"] = serde_json::json!(src.to_string_lossy().to_string());
-
- // Write updated pipe.json
- tokio::fs::write(&pipe_json_path, serde_json::to_string_pretty(&pipe_json)?).await?;
- info!("Updated pipe.json with local source path");
-
Ok(())
}
- async fn download_github_folder(
- client: &Client,
- api_url: &str,
- screenpipe_dir: PathBuf,
- pipe_name: &str,
- ) -> anyhow::Result<PathBuf> {
+ fn copy_dir_all_boxed(
+ src: impl AsRef<Path> + Send + Sync + 'static,
+ dst: impl AsRef<Path> + Send + Sync + 'static,
+ ) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + Sync>> {
+ Box::pin(async move { copy_dir_all(src, dst).await })
+ }
+
+ async fn download_github_folder(url: &Url, dest_dir: &Path) -> anyhow::Result<()> {
+ let client = Client::new();
+ let api_url = get_raw_github_url(url.as_str())?;
+
let response = client
- .get(api_url)
+ .get(&api_url)
.header("Accept", "application/vnd.github.v3+json")
.header("User-Agent", "screenpipe")
.send()
@@ -600,52 +188,20 @@ mod pipes {
let contents: Value = response.json().await?;
if !contents.is_array() {
- anyhow::bail!("Invalid response from GitHub API");
- }
-
- let pipe_dir = screenpipe_dir.join("pipes").join(pipe_name);
-
- // Check if the pipe directory already exists
- if pipe_dir.exists() {
- info!("Pipe already exists: {:?}", pipe_dir);
- return Ok(pipe_dir);
+ anyhow::bail!("invalid response from github api");
}
- tokio::fs::create_dir_all(&pipe_dir).await?;
-
- let mut pipe_json: Value = serde_json::json!({});
-
for item in contents.as_array().unwrap() {
let file_name = item["name"].as_str().unwrap();
let download_url = item["download_url"].as_str().unwrap();
- if file_name == "pipe.js"
- || file_name == "pipe.ts"
- || file_name == "pipe.json"
- || file_name == "README.md"
- {
- let file_content = client.get(download_url).send().await?.bytes().await?;
- let file_path = pipe_dir.join(file_name);
- tokio::fs::write(&file_path, &file_content).await?;
- info!("Downloaded: {:?}", file_path);
-
- if file_name == "pipe.json" {
- pipe_json = serde_json::from_slice(&file_content)?;
- }
- }
+ let file_content = client.get(download_url).send().await?.bytes().await?;
+ let file_path = dest_dir.join(file_name);
+ tokio::fs::write(&file_path, &file_content).await?;
+ info!("downloaded: {:?}", file_path);
}
- // Update pipe.json with the original GitHub URL at the root level
- // let github_url = api_url_to_github_url(api_url);
- // pipe_json["source"] = serde_json::json!(github_url);
-
- // Write updated pipe.json
- let pipe_json_path = pipe_dir.join("pipe.json");
- tokio::fs::write(&pipe_json_path, serde_json::to_string_pretty(&pipe_json)?).await?;
- info!("updated pipe.json with source url");
-
- info!("Pipe downloaded successfully to: {:?}", pipe_dir);
- Ok(pipe_dir)
+ Ok(())
}
fn get_raw_github_url(url: &str) -> anyhow::Result<String> {
diff --git a/screenpipe-js/deno.json b/screenpipe-js/deno.json
new file mode 100644
index 000000000..c6a373173
--- /dev/null
+++ b/screenpipe-js/deno.json
@@ -0,0 +1,3 @@
+{
+ "imports": {}
+}
\ No newline at end of file
diff --git a/screenpipe-js/main.ts b/screenpipe-js/main.ts
new file mode 100644
index 000000000..277a6503b
--- /dev/null
+++ b/screenpipe-js/main.ts
@@ -0,0 +1,229 @@
+import * as fs from "node:fs";
+import process from "node:process";
+
+// Type definitions
+export interface PipeConfig {
+ [key: string]: object | string | number | boolean;
+}
+
+export interface NotificationOptions {
+ title: string;
+ body: string;
+}
+
+/**
+ * Types of content that can be queried in Screenpipe.
+ */
+export type ContentType = "ocr" | "audio" | "all";
+
+/**
+ * Parameters for querying Screenpipe.
+ */
+export interface ScreenpipeQueryParams {
+ q?: string;
+ contentType?: ContentType;
+ limit?: number;
+ offset?: number;
+ startTime?: string;
+ endTime?: string;
+ appName?: string;
+ windowName?: string;
+ includeFrames?: boolean;
+ minLength?: number;
+ maxLength?: number;
+}
+
+/**
+ * Structure of OCR (Optical Character Recognition) content.
+ */
+export interface OCRContent {
+ frameId: number;
+ text: string;
+ timestamp: string;
+ filePath: string;
+ offsetIndex: number;
+ appName: string;
+ windowName: string;
+ tags: string[];
+ frame?: string;
+}
+
+/**
+ * Structure of audio content.
+ */
+export interface AudioContent {
+ chunkId: number;
+ transcription: string;
+ timestamp: string;
+ filePath: string;
+ offsetIndex: number;
+ tags: string[];
+ deviceName: string;
+ deviceType: string;
+}
+
+/**
+ * Structure of Full Text Search content.
+ */
+export interface FTSContent {
+ textId: number;
+ matchedText: string;
+ frameId: number;
+ timestamp: string;
+ appName: string;
+ windowName: string;
+ filePath: string;
+ originalFrameText?: string;
+ tags: string[];
+}
+
+/**
+ * Union type for different types of content items.
+ */
+export type ContentItem =
+ | { type: "OCR"; content: OCRContent }
+ | { type: "Audio"; content: AudioContent }
+ | { type: "FTS"; content: FTSContent };
+
+/**
+ * Pagination information for search results.
+ */
+export interface PaginationInfo {
+ limit: number;
+ offset: number;
+ total: number;
+}
+
+/**
+ * Structure of the response from a Screenpipe query.
+ */
+export interface ScreenpipeResponse {
+ data: ContentItem[];
+ pagination: PaginationInfo;
+}
+
+/**
+ * Utility function to convert snake_case to camelCase
+ */
+function toCamelCase(str: string): string {
+ return str.replace(/([-_][a-z])/g, (group) =>
+ group.toUpperCase().replace("-", "").replace("_", "")
+ );
+}
+
+/**
+ * Function to recursively convert object keys from snake_case to camelCase
+ */
+function convertToCamelCase(obj: any): any {
+ if (Array.isArray(obj)) {
+ return obj.map(convertToCamelCase);
+ } else if (obj !== null && typeof obj === "object") {
+ return Object.keys(obj).reduce((result, key) => {
+ const camelKey = toCamelCase(key);
+ result[camelKey] = convertToCamelCase(obj[key]);
+ return result;
+ }, {} as any);
+ }
+ return obj;
+}
+
+/**
+ * Function to convert camelCase to snake_case
+ */
+function toSnakeCase(str: string): string {
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
+}
+
+export async function sendDesktopNotification(
+ options: NotificationOptions
+): Promise<boolean> {
+ const notificationApiUrl =
+ process.env.SCREENPIPE_SERVER_URL || "http://localhost:11435";
+ try {
+ await fetch(`${notificationApiUrl}/notify`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(options),
+ });
+ return true;
+ } catch (error) {
+ console.error("Failed to send notification:", error);
+ return false;
+ }
+}
+
+export function loadPipeConfig(): PipeConfig {
+ try {
+ const configPath = `${process.env.SCREENPIPE_DIR}/pipes/${process.env.PIPE_ID}/pipe.json`;
+ const configContent = fs.readFileSync(configPath, "utf8");
+ const parsedConfig = JSON.parse(configContent);
+ const config: PipeConfig = {};
+ parsedConfig.fields.forEach((field: any) => {
+ config[field.name] =
+ field.value !== undefined ? field.value : field.default;
+ });
+ return config;
+ } catch (error) {
+ console.error("Error loading pipe.json:", error);
+ return {};
+ }
+}
+
+export async function queryScreenpipe(
+ params: ScreenpipeQueryParams
+): Promise<ScreenpipeResponse | null> {
+ const queryParams = new URLSearchParams();
+ Object.entries(params).forEach(([key, value]) => {
+ if (value !== undefined) {
+ const snakeKey = toSnakeCase(key);
+ queryParams.append(snakeKey, value.toString());
+ }
+ });
+
+ const url = `http://localhost:3030/search?${queryParams}`;
+ try {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ const data = await response.json();
+ return convertToCamelCase(data) as ScreenpipeResponse;
+ } catch (error) {
+ console.error("error querying screenpipe:", error);
+ return null;
+ }
+}
+
+export function extractJsonFromLlmResponse(response: string): any {
+ let cleaned = response.replace(/^```(?:json)?\s*|\s*```$/g, "");
+ const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
+ if (jsonMatch) {
+ cleaned = jsonMatch[0];
+ }
+ cleaned = cleaned.replace(/^[^{]*/, "").replace(/[^}]*$/, "");
+ cleaned = cleaned.replace(/\\n/g, "").replace(/\n/g, "");
+ cleaned = cleaned.replace(/"(\\"|[^"])*"/g, (match) => {
+ return match.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+ });
+
+ try {
+ return JSON.parse(cleaned);
+ } catch (error) {
+ console.warn("failed to parse json:", error);
+ cleaned = cleaned
+ .replace(/,\s*}/g, "}")
+ .replace(/'/g, '"')
+ .replace(/(\w+):/g, '"$1":')
+ .replace(/:\s*'([^']*)'/g, ': "$1"')
+ .replace(/\\"/g, '"')
+ .replace(/"{/g, '{"')
+ .replace(/}"/g, '"}');
+
+ try {
+ return JSON.parse(cleaned);
+ } catch (secondError) {
+ console.warn("failed to parse json after attempted fixes:", secondError);
+ throw new Error("invalid json format in llm response");
+ }
+ }
+}
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 262eca51a..f401886f0 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -110,7 +110,7 @@ name = "new_db_benchmark"
harness = false
[features]
-default = ["pipes"]
+default = []
metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
pipes = ["screenpipe-core/pipes", "tempfile", "url"]
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 28627e53d..52d707367 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -132,23 +132,23 @@ async fn main() -> anyhow::Result<()> {
env_filter
};
+ // ignore mut warning
+ #[allow(unused_mut)]
let mut h: Option<Highlight> = None;
if !cli.disable_telemetry {
- // TODO crashes on init
+ // ! do not use yet - leaks too much privacy and does not catch errors properly
// h = Some(Highlight::init(HighlightConfig {
// project_id: "82688".to_string(),
- // logger: Box::new(NopLogger),
// ..Default::default()
// }).expect("Failed to initialize Highlight.io"));
- }
-
- // Initialize tracing without OpenTelemetry if telemetry is disabled
+ }
+ // } else {
tracing_subscriber::registry()
.with(env_filter)
.with(file_layer)
.with(console_layer)
.init();
-
+ // }
let all_audio_devices = list_audio_devices().await?;
let mut devices_status = HashMap::new();
@@ -398,7 +398,7 @@ async fn main() -> anyhow::Result<()> {
"open source | runs locally | developer friendly".bright_green()
);
- println!("┌───────────────────┬────────────────────────────────────┐");
+ println!("┌─────────────────────┬────────────────────────────────────┐");
println!("│ setting │ value │");
println!("├─────────────────────┼────────────────────────────────────┤");
println!("│ fps │ {:<34} │", cli.fps);
diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rs
index fb652ba24..a70083dd3 100644
--- a/screenpipe-server/src/pipe_manager.rs
+++ b/screenpipe-server/src/pipe_manager.rs
@@ -1,5 +1,5 @@
use anyhow::Result;
-use screenpipe_core::{download_pipe, run_pipe};
+use screenpipe_core::download_pipe;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::future::Future;
@@ -35,7 +35,7 @@ impl PipeManager {
let pipe_id = id.to_string();
let screenpipe_dir = self.screenpipe_dir.clone();
- let future = run_pipe(pipe_id.clone(), screenpipe_dir);
+ let future = async move { screenpipe_core::run_pipe(&pipe_id, screenpipe_dir).await };
self.update_config(
id,