YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
add a new linear pipe, not finished though
Louis Beaumont8125b9e43bba
diff --git a/Cargo.toml b/Cargo.tomlindex 0444df585..02fecde36 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -48,3 +48,7 @@ dynamic = true[profile.release]lto = true++[profile.dev-release]+inherits = "release"+lto = falsediff --git a/examples/typescript/pipe-llama32-comment-linear-while-you-work/README.md b/examples/typescript/pipe-llama32-comment-linear-while-you-work/README.mdnew file mode 100644index 000000000..9796e65d5--- /dev/null+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/README.md@@ -0,0 +1,39 @@+### llama3.2 linear task commenter++are you the kind of engineer who hates product management and considers it bullshit?++no worries, llama3.2 got you covered.++this pipe will automate your PM work by adding comments to linear tasks based on your screen activity or meeting audio using screenpipe and llama3.2 ai.++(please avoid watching netflix (or something else ;)) during work hours or it will be written in linear :))++#### quick setup++1. run ollama:+ ```+ ollama run nemotron-mini:4b-instruct-q4_K_M+ ```++2. set up linear:+ - get your linear api key from https://linear.app/settings/api++3. configure pipe in the app ui:+ - set your linear api key+ - adjust interval and other settings as needed+ - save and enable the pipe+ - restart screenpipe recording++boom! it'll add comments to your linear tasks based on your work every 5 minutes (or your set interval).++wanna tweak it? check `pipe.ts` to adjust the ai prompt or modify the comment generation logic.++#### cli usage++```+screenpipe download examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.ts # or https url+screenpipe enable pipe-llama32-comment-linear-while-you-work+screenpipe+```++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.jsonnew file mode 100644index 000000000..87af3a56e--- /dev/null+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.json@@ -0,0 +1,40 @@+{+ "fields": [+ {+ "name": "interval",+ "type": "number",+ "default": 300,+ "description": "interval in seconds to stream data (default: 5 minutes)"+ },+ {+ "name": "linearApiKey",+ "type": "string",+ "default": "<fill your linear api key here>",+ "description": "linear api key for authentication"+ },+ {+ "name": "ollamaApiUrl",+ "type": "string",+ "default": "http://localhost:11434/api/chat",+ "description": "ollama api url"+ },+ {+ "name": "ollamaModel",+ "type": "string",+ "default": "nemotron-mini:4b-instruct-q4_K_M",+ "description": "ollama model"+ },+ {+ "name": "pageSize",+ "type": "number",+ "default": 100,+ "description": "number of records to retrieve from screenpipe per page"+ },+ {+ "name": "customCommentPrompt",+ "type": "string",+ "default": "",+ "description": "custom prompt to override part of the system prompt for comment generation"+ }+ ]+}\ No newline at end of filediff --git a/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.ts b/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.tsnew file mode 100644index 000000000..3d4f03f41--- /dev/null+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/pipe.ts@@ -0,0 +1,319 @@+const LINEAR_API_URL = "https://api.linear.app/graphql";++interface LinearComment {+ taskId: string;+ body: string;+}++async function generateLinearSearchQuery(+ screenData: ContentItem[],+ ollamaApiUrl: string,+ ollamaModel: string+): Promise<string> {+ const prompt = `based on the following screen data, generate a search query for linear tasks:++ ${JSON.stringify(screenData)}++ 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" }+ - { "query": "windows" }+ - { "query": "docs" }+ - { "query": "ocr" }+ - { "query": "vad" }+ - { "query": "debian" }++ rules:+ - format JSON correctly+ - query should be relevant to the screen/audio data+ - return only a short phrase or few keywords, not a full sentence+ - do not add backticks to the json+ - 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" },+ }),+ });++ 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();++ console.log("ai answer:", result);++ return JSON.parse(result.message.content.trim());+}++async function generateLinearComment(+ screenData: ContentItem[],+ relevantTasks: any[],+ ollamaApiUrl: string,+ ollamaModel: string,+ customCommentPrompt: string+): Promise<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:++ screen data: ${JSON.stringify(screenData)}+ relevant tasks: ${JSON.stringify(relevantTasks)}++ 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"+ }++ 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+ - 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+ - do not add backticks to the json+ - return only the json object, no additional text`;++ const prompt = customCommentPrompt+ ? `${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" },+ }),+ });++ if (!response.ok) {+ const errorBody = await response.text();+ throw new Error(+ `http error! status: ${response.status}, body: ${errorBody}`+ );+ }++ const result = await response.json();++ return JSON.parse(result.message.content.trim());+}++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;+}++async function addCommentToLinear(+ comment: LinearComment,+ apiKey: string+): Promise<void> {+ 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,+ 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}`+ );+ }++ 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",+ },+ 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;+}++async function streamCommentsToLinear(): Promise<void> {+ console.log("starting comments stream to linear");++ const config = await pipe.loadConfig();+ console.log("loaded config:", JSON.stringify(config, null, 2));++ const interval = config.interval * 1000;+ const apiKey = config.linearApiKey;+ const ollamaApiUrl = config.ollamaApiUrl;+ const ollamaModel = config.ollamaModel;+ const customCommentPrompt = config.customCommentPrompt;++ while (true) {+ 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(),+ limit: config.pageSize,+ content_type: "all",+ });++ if (screenData && screenData.data.length > 0) {+ // step 1: ask llm to generate a function call to search linear tasks+ const searchQuery = await generateLinearSearchQuery(+ screenData.data,+ ollamaApiUrl,+ ollamaModel+ );++ // step 2: execute the search on linear+ const relevantTasks = await searchLinearTasks(searchQuery, apiKey);++ if (relevantTasks.length === 0) {+ console.log("no relevant tasks found");+ continue;+ }++ // step 3: ask llm to generate a comment for the most relevant task+ const comment = await generateLinearComment(+ screenData.data,+ relevantTasks,+ ollamaApiUrl,+ ollamaModel,+ customCommentPrompt+ );++ // step 4: add the comment to the linear task+ await addCommentToLinear(comment, apiKey);++ // randomly send a notification+ await pipe.sendNotification({+ title: "linear comment pipeline update",+ body: `comment added to task ${comment.taskId}`,+ });+ } else {+ console.log("no relevant work detected in the last interval");+ }+ } catch (error: any) {}+ await new Promise((resolve) => setTimeout(resolve, interval));+ }+}++streamCommentsToLinear();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.tsnew file mode 100644index 000000000..327a2ee5d--- /dev/null+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/screenpipe.d.ts@@ -0,0 +1,252 @@+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.jsonnew file mode 100644index 000000000..c4e6dfdd7--- /dev/null+++ b/examples/typescript/pipe-llama32-comment-linear-while-you-work/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "es2018",+ "module": "esnext",+ "moduleResolution": "node",+ "outDir": "./",+ "rootDir": "./",+ "strict": true,+ "esModuleInterop": true+ },+ "include": [+ "./**/*.ts"+ ],+ "exclude": [+ "node_modules"+ ]+}\ No newline at end of filediff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.tsindex 57628e941..af78836fc 100644--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts@@ -1,39 +1,13 @@const NOTION_API_URL = "https://api.notion.com/v1/pages";-interface ScreenData {- data: {- content: {- timestamp: string;- text: string;- };- }[];-}-interface EngineeringLog {title: string;description: string;tags: string[];}-async function queryScreenpipe(- startTime: string,- endTime: string-): Promise<ScreenData> {- try {- const queryParams = `start_time=${startTime}&end_time=${endTime}&limit=50&content_type=ocr`;- 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 { data: [] };- }-}-async function generateEngineeringLog(- screenData: ScreenData,+ screenData: ContentItem[],ollamaApiUrl: string,ollamaModel: string): Promise<EngineeringLog> {@@ -134,14 +108,16 @@ async function streamEngineeringLogsToNotion(): Promise<void> {const now = new Date();const oneHourAgo = new Date(now.getTime() - interval);- const screenData = await queryScreenpipe(- oneHourAgo.toISOString(),- now.toISOString()- );+ const screenData = await pipe.queryScreenpipe({+ start_time: oneHourAgo.toISOString(),+ end_time: now.toISOString(),+ limit: 50,+ content_type: "ocr",+ });- if (screenData.data && screenData.data.length > 0) {+ if (screenData && screenData.data.length > 0) {const logEntry = await generateEngineeringLog(- screenData,+ screenData.data,ollamaApiUrl,ollamaModel);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.tsindex 05f902db5..820e1a2d0 100644--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/screenpipe.d.ts+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/screenpipe.d.ts@@ -1,30 +1,138 @@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;};@@ -41,6 +149,97 @@ declare global {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/screenpipe-core/src/deno/runtime.js b/screenpipe-core/src/deno/runtime.jsindex 0da7ac047..a79906588 100644--- a/screenpipe-core/src/deno/runtime.js+++ b/screenpipe-core/src/deno/runtime.js@@ -232,3 +232,62 @@ 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.rsindex 26ae35150..65d13d7a1 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -434,6 +434,10 @@ mod pipes {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));}@@ -444,6 +448,11 @@ mod pipes {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 differentlyErr(anyhow::anyhow!("javascript module evaluation error: {}", e))}