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
refactor: switch to bun #589
Louis Beaumonte3ebed2d2d25
diff --git a/.cursorrules b/.cursorrulesindex 98d826314..9129c320b 100644--- a/.cursorrules+++ b/.cursorrules@@ -1,5 +1,5 @@Rules:-- Coding: screenpipe is an open source positive sum endeavour that is a bridge between dull context-free AI and context aware super intelligence, this bridge is a lib, and CLI, that record screens & mics 24/7, extract OCR & STT, save to local db, connect to AI, do magic, it's written in Rust + Tauri and we write plugins (pipes) in TS + Deno. the Rust CLI is embedded as a sidecar in Tauri. it works on macos, windows, linux+- Coding: screenpipe is an open source positive sum endeavour that is a bridge between dull context-free AI and context aware super intelligence, this bridge is a lib, and CLI, that record screens & mics 24/7, extract OCR & STT, save to local db, connect to AI, do magic, it's written in Rust + Tauri and we write plugins (pipes) in TS + Bun. the Rust CLI is embedded as a sidecar in Tauri. it works on macos, windows, linux- Coding: always keep my style black and white, with some nerdy style and fonts pixelated / scientific style- Coding: do not remove @ts-ignore except if i explicitly ask you- Coding: always use lower case for logging stuff or UIdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c185d79af..0cd0ca116 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -31,9 +31,7 @@ jobs:toolchain: stableoverride: true- - uses: denoland/setup-deno@v2- with:- deno-version: v2.x+ - uses: oven-sh/setup-bun@v1- name: Install dependenciesrun: .github/scripts/install_dependencies.sh@@ -46,13 +44,13 @@ jobs:- name: Run cargo testsrun: cargo test- - name: Run deno tests+ - name: Run bun testsenv:SCREENPIPE_DIR: ${{ runner.workspace }}/screenpipePIPE_ID: testPIPE_FILE: pipe.tsPIPE_DIR: ${{ runner.workspace }}/screenpipe/pipes/test- run: deno test --allow-env --allow-write --allow-read+ run: bun ./scripts/run_tests.jsworking-directory: ./screenpipe-jstest-windows:@@ -71,9 +69,7 @@ jobs:profile: minimaltoolchain: stable- - uses: denoland/setup-deno@v2- with:- deno-version: v2.x+ - uses: oven-sh/setup-bun@v1- name: setup Bunuses: oven-sh/setup-bun@v1@@ -92,13 +88,13 @@ jobs:- name: Run specific Windows OCR cargo testrun: cargo test test_process_ocr_task_windows- - name: Run deno tests+ - name: Run bun testsenv:SCREENPIPE_DIR: ${{ runner.workspace }}/screenpipePIPE_ID: testPIPE_FILE: pipe.tsPIPE_DIR: ${{ runner.workspace }}/screenpipe/pipes/test- run: deno test --allow-env --allow-write --allow-read+ run: bun ./scripts/run_tests.jsworking-directory: ./screenpipe-jstest-macos:@@ -117,9 +113,7 @@ jobs:profile: minimaltoolchain: stable- - uses: denoland/setup-deno@v2- with:- deno-version: v2.x+ - uses: oven-sh/setup-bun@v1- name: setup Bunuses: oven-sh/setup-bun@v1@@ -143,11 +137,11 @@ jobs:DYLD_LIBRARY_PATH: /Users/runner/work/screenpipe/screenpipe/screenpipe-vision/librun: cargo test test_apple_native_ocr- - name: Run deno tests+ - name: Run bun testsenv:SCREENPIPE_DIR: ${{ runner.workspace }}/screenpipePIPE_ID: testPIPE_FILE: pipe.tsPIPE_DIR: ${{ runner.workspace }}/screenpipe/pipes/test- run: deno test --allow-env --allow-write --allow-read+ run: bun ./scripts/run_tests.jsworking-directory: ./screenpipe-jsdiff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.ymlindex ea2b35095..798f684a9 100644--- a/.github/workflows/release-app.yml+++ b/.github/workflows/release-app.yml@@ -180,7 +180,6 @@ jobs:export PKG_CONFIG_PATH="/usr/local/opt/ffmpeg/lib/pkgconfig:$PKG_CONFIG_PATH"export PKG_CONFIG_ALLOW_CROSS=1export RUSTFLAGS="-C link-arg=-Wl,-rpath,@executable_path/../Frameworks -C link-arg=-Wl,-rpath,@loader_path/../Frameworks -C link-arg=-Wl,-install_name,@rpath/libscreenpipe.dylib"- export V8_FLAGS="--max-old-space-size=8192" # https://github.com/denoland/deno_core/issues/916ficargo build --release -p screenpipe-server ${{ matrix.args }}diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c0f096408..a00366e44 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -63,7 +63,7 @@ i use cursor with this prompt to help me with the code:```Rules:-- Coding: louis is working on screenpipe most of the time, it's an open source app, lib, and CLI, that record screens & mics 24/7, extract OCR & STT, save to local db, connect to AI, do magic, it's written in Rust + Tauri and we write plugins (pipes) in TS + Deno. the Rust CLI is embedded as a sidecar in Tauri. it works on macos, windows, linux+- Coding: louis is working on screenpipe most of the time, it's an open source app, lib, and CLI, that record screens & mics 24/7, extract OCR & STT, save to local db, connect to AI, do magic, it's written in Rust + Tauri and we write plugins (pipes) in TS + Bun. the Rust CLI is embedded as a sidecar in Tauri. it works on macos, windows, linux- Coding: always keep my style black and white, with some nerdy style and fonts pixelated / scientific style- Coding: do not remove @ts-ignore except if i explicitly ask you- Coding: always use lower case for logging stuff or UIdiff --git a/Formula/screenpipe.rb b/Formula/screenpipe.rbindex 5cf68eb9a..42d2ff5d8 100644--- a/Formula/screenpipe.rb+++ b/Formula/screenpipe.rb@@ -15,7 +15,7 @@ class Screenpipe < Formulaenddepends_on "ffmpeg"- depends_on "deno"+ depends_on "bun"def installbin.install Dir["bin/*"]diff --git a/content/docs/pages/docs/architecture.mdx b/content/docs/pages/docs/architecture.mdxindex 54e806e58..ca7b0a1c9 100644--- a/content/docs/pages/docs/architecture.mdx+++ b/content/docs/pages/docs/architecture.mdx@@ -47,7 +47,7 @@ Uses 600 MB, 10% CPU.- [ ] Camera- [ ] Keyboard- [x] Browser- - [x] Pipe Store (a list of "pipes" you can build, share & easily install to get more value out of your screen & mic data without effort). It runs in Deno Typescript engine within screenpipe on your computer+ - [x] Pipe Store (a list of "pipes" you can build, share & easily install to get more value out of your screen & mic data without effort). It runs in Bun Typescript engine within screenpipe on your computer- [x] screenshots + OCR with different engines to optimise privacy, quality, or energy consumption- [x] tesseract- [x] Windows native OCRdiff --git a/content/docs/pages/docs/getting-started.mdx b/content/docs/pages/docs/getting-started.mdxindex a4e2e6cd7..cdb797d3c 100644--- a/content/docs/pages/docs/getting-started.mdx+++ b/content/docs/pages/docs/getting-started.mdx@@ -55,9 +55,9 @@ for users preferring full control or customization, building the app manually frbrew install pkg-config ffmpeg jq cmake wget```-2. install deno cli (required for building):+2. install bun cli (required for building):```bash- curl -fsSL https://deno.land/install.sh | sh+ curl -fsSL https://bun.sh/install | bash```3. clone the screenpipe repository:@@ -150,7 +150,7 @@ If this does not work for you, please [open an issue](https://github.com/mediar-Install 7zip: https://www.7-zip.org/download.html```batch-choco install pkgconfiglite deno+choco install pkgconfiglite bunwinget install -e --id GnuWin32.UnZipwinget install -e --id Rustlang.Rustupcd V:\projects@@ -190,9 +190,9 @@ bun tauri buildcurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh```-2. install deno cli (required for building):+2. install bun cli (required for building):```bash- curl -fsSL https://deno.land/install.sh | sh+ curl -fsSL https://bun.sh/install | bash```3. clone the repository and build the application:diff --git a/content/docs/pages/docs/plugins.mdx b/content/docs/pages/docs/plugins.mdxindex 3cba96b97..363e8ef3c 100644--- a/content/docs/pages/docs/plugins.mdx+++ b/content/docs/pages/docs/plugins.mdx@@ -45,11 +45,11 @@ import MotionDiv from '@/components/motion-div';| **example** | **description** | **link** || ------------------------------------ | ------------------------------------------------ | --------------------------------- |+| **pipe phi3.5 engineering team logs**| generate engineering team work logs | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-phi3.5-engineering-team-logs) || **pipe post questions on reddit** | post questions on reddit based on screen activity | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-post-questions-on-reddit) || **pipe email daily log** | send daily activity logs via email | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-email-daily-log) || **pipe llama32 comment linear while you work** | comment on linear tasks while you work using llama32 | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-llama32-comment-linear-while-you-work) || **pipe meeting summary by email** | send meeting summaries via email | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-meeting-summary-by-email) |-| **pipe phi3.5 engineering team logs**| generate engineering team work logs | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-phi3.5-engineering-team-logs) |</MotionDiv>@@ -60,16 +60,19 @@ import MotionDiv from '@/components/motion-div';screenpipe's plugin system, referred to as **pipes**, allows you to create customized pipes that automate workflows. these pipes can process, annotate, analyze, summarize, or integrate your screen and audio data with other tools.-users can begin by cloning an existing pipe, such as [pipe-post-questions-on-reddit](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-post-questions-on-reddit). you can use any javascript/typescript to build your use case, from simple to highly advanced. the primary requirement is that the pipe folder must contain a file named `pipe.js` or `pipe.ts`.+users can begin by cloning an existing pipe, such as [pipe-phi3.5-engineering-team-logs](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-phi3.5-engineering-team-logs). you can use any javascript/typescript to build your use case, from simple to highly advanced. the primary requirement is that the pipe folder must contain a file named `pipe.js` or `pipe.ts`.```bashgit clone https://github.com/mediar-ai/screenpipe.git-cp -r screenpipe/examples/typescript/pipe-post-questions-on-reddit screenpipe/examples/typescript/my-pipe+cp -r screenpipe/examples/typescript/pipe-phi3.5-engineering-team-logs screenpipe/examples/typescript/my-pipe```-we use Deno to run the pipe within the Rust codebase.+we use Bun to run the pipe within the Rust codebase.++check official [bun docs](https://bun.sh/docs) for more details on installing and running Bun.+-check official [deno docs](https://deno.com/manual/basics) for more details on installing and running Deno.+> **note**: you can also use nextjs to build your pipe, we will render the page in the pipe store. check [pipe-simple-nextjs](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-simple-nextjs) for an example.### configuring pipes@@ -102,16 +105,16 @@ here's a snippet of a `pipe.json` for the pipe-post-questions-on-reddit:### running pipes-you can run your pipe manually with deno, for example:+you can run your pipe manually with bun, for example:```bash# these are mandatory env variablesexport SCREENPIPE_DIR="$HOME/.screenpipe"-export PIPE_ID="pipe-find-leads-with-exa-ai"+export PIPE_ID="pipe-phi3.5-engineering-team-logs"export PIPE_FILE="pipe.ts"-export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-find-leads-with-exa-ai"+export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-phi3.5-engineering-team-logs"-deno run --allow-read --allow-write --allow-env --allow-net --allow-run --allow-sys examples/typescript/pipe-find-leads-with-exa-ai/pipe.ts+bun run examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts```make sure to configure your pipe.json first@@ -162,13 +165,12 @@ we're working on integration with Stripe, to allow you to monetize your pipes, f### outro-- we use deno to run the pipe within the Rust codebase.+- we use bun to run the pipe within the Rust codebase.- you can use `pipe.json` to let others pass configuration options to your pipe through the UI or CLI.- pipes have access to a special API that allows you to interact with your computer or special features like sending notifications, sending emails, etc.- check this [file](https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-core/src/pipes.rs) for more details on impl.- in general we recommend using local LLMs like ollama as the data can be large and sensitive and JSON outputs.- we recommend using [vercel ai sdk](https://github.com/vercel/ai) for faster dev.-- deno caches dependencies and sometimes need to clear/reload cache### known limitationsdiff --git a/content/docs/pages/index.mdx b/content/docs/pages/index.mdxindex 92f7c73c5..74622a315 100644--- a/content/docs/pages/index.mdx+++ b/content/docs/pages/index.mdx@@ -18,7 +18,7 @@ screenpipe is an open-source, 24/7 AI screen & mic capture app & lib. it provide- **open source & secure**: your data stays private, with complete control over storage and processing.- **cross-platform**: works on windows, macos, and linux.- **multi-device support**: supports multiple monitors & audio devices for comprehensive data capture.-- **plugins & pipes**: allows the creation and use of plugins (pipes) in TypeScript, running within a Deno runtime to extend functionality.+- **plugins & pipes**: allows the creation and use of plugins (pipes) in TypeScript, running within a JS runtime to extend functionality.</MotionDiv>diff --git a/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/deno.json b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/deno.jsondeleted file mode 100644index 55aa44e5b..000000000--- a/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/deno.json+++ /dev/null@@ -1,9 +0,0 @@-{- "imports": {- "fs": "node:fs",- "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts",- "ai": "npm:ai",- "ollama-ai-provider": "npm:ollama-ai-provider",- "zod": "npm:zod"- }-}diff --git a/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.ts b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.tsindex 9cb3ad034..785dac45a 100644--- a/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.ts+++ b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.ts@@ -1,5 +1,5 @@-import { pipe, ContentItem } from "screenpipe";-import Anthropic from "npm:@anthropic-ai/sdk";+import { pipe, ContentItem } from "@screenpipe/js";+import Anthropic from "@anthropic-ai/sdk";let anthropic: Anthropic;let meetingNotes = "";@@ -214,7 +214,7 @@ export PIPE_ID="pipe-anthropic-computer-use-meeting-assistant"export PIPE_FILE="pipe.ts"export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-anthropic-computer-use-meeting-assistant"-deno run --allow-read --allow-write --allow-env --allow-net --allow-run --allow-sys examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.ts+bun run examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.ts*/diff --git a/examples/typescript/pipe-email-daily-log/deno.json b/examples/typescript/pipe-email-daily-log/deno.jsondeleted file mode 100644index 8d6953e55..000000000--- a/examples/typescript/pipe-email-daily-log/deno.json+++ /dev/null@@ -1,10 +0,0 @@-{- "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/main/screenpipe-js/main.ts"- }-}diff --git a/examples/typescript/pipe-email-daily-log/pipe.ts b/examples/typescript/pipe-email-daily-log/pipe.tsindex 633d9d14f..7ed860ffa 100644--- a/examples/typescript/pipe-email-daily-log/pipe.ts+++ b/examples/typescript/pipe-email-daily-log/pipe.ts@@ -1,11 +1,10 @@-import * as fs from "fs";+import * as fs from "node:fs";import nodemailer from "nodemailer";-import { queryScreenpipe, loadPipeConfig, ContentItem } from "screenpipe";+import { queryScreenpipe, loadPipeConfig, ContentItem, pipe } from "@screenpipe/js";import process from "node:process";import { z } from "zod";import { generateObject, generateText } from "ai";import { createOllama } from "ollama-ai-provider";-import { pipe } from "screenpipe";interface DailyLog {activity: string;diff --git a/examples/typescript/pipe-email-exa-search/deno.json b/examples/typescript/pipe-email-exa-search/deno.jsondeleted file mode 100644index 3574b27a8..000000000--- a/examples/typescript/pipe-email-exa-search/deno.json+++ /dev/null@@ -1,11 +0,0 @@-{- "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/main/screenpipe-js/main.ts",- "exa-js" : "npm:exa-js"- }-}diff --git a/examples/typescript/pipe-email-exa-search/pipe.ts b/examples/typescript/pipe-email-exa-search/pipe.tsindex a868d160c..bff8f9811 100644--- a/examples/typescript/pipe-email-exa-search/pipe.ts+++ b/examples/typescript/pipe-email-exa-search/pipe.ts@@ -1,6 +1,6 @@-import * as fs from "fs";+import * as fs from "node:fs";import nodemailer from "nodemailer";-import { ContentItem, pipe } from "screenpipe";+import { ContentItem, pipe } from "@screenpipe/js";import process from "node:process";import Exa from "exa-js"import { z } from "zod";diff --git a/examples/typescript/pipe-find-leads-with-exa-ai/README.md b/examples/typescript/pipe-find-leads-with-exa-ai/README.mdindex e6b20a59f..498dcafa4 100644--- a/examples/typescript/pipe-find-leads-with-exa-ai/README.md+++ b/examples/typescript/pipe-find-leads-with-exa-ai/README.md@@ -16,7 +16,7 @@ this pipe automates the process of finding potential leads based on an evolving#### requirements- screenpipe installed and configured-- deno runtime+- bun runtime- exa ai api key- openai api key- gmail account for sending notifications@@ -39,7 +39,7 @@ export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-find-leads-with-exa-ai"2. run the pipe:```bash-deno run --allow-read --allow-write --allow-env --allow-net --allow-run --allow-sys $PIPE_DIR/$PIPE_FILE+bun run $PIPE_DIR/$PIPE_FILE```#### how it worksdiff --git a/examples/typescript/pipe-find-leads-with-exa-ai/deno.json b/examples/typescript/pipe-find-leads-with-exa-ai/deno.jsondeleted file mode 100644index a59b9e101..000000000--- a/examples/typescript/pipe-find-leads-with-exa-ai/deno.json+++ /dev/null@@ -1,11 +0,0 @@-{- "imports": {- "fs": "node:fs",- "nodemailer": "npm:nodemailer",- "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts",- "exa-js": "npm:exa-js",- "openai-ai-provider": "npm:@ai-sdk/openai",- "zod": "npm:zod",- "ai": "npm:ai"- }-}\ No newline at end of filediff --git a/examples/typescript/pipe-find-leads-with-exa-ai/pipe.ts b/examples/typescript/pipe-find-leads-with-exa-ai/pipe.tsindex ea8d4d594..ab421f76d 100644--- a/examples/typescript/pipe-find-leads-with-exa-ai/pipe.ts+++ b/examples/typescript/pipe-find-leads-with-exa-ai/pipe.ts@@ -1,11 +1,11 @@-import * as fs from "fs";-import nodemailer from "nodemailer";-import { ContentItem, pipe } from "screenpipe";+import * as fs from "node:fs";+import nodemailer from "npm:nodemailer";+import { ContentItem, pipe } from "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts";import process from "node:process";-import Exa from "exa-js";-import { generateObject, generateText } from "ai";-import { createOpenAI } from "openai-ai-provider";-import { z } from "zod";+import Exa from "npm:exa-js";+import { generateObject, generateText } from "npm:ai";+import { createOpenAI } from "npm:openai-ai-provider";+import { z } from "npm:zod";import * as path from "node:path";const icpSchema = z.object({@@ -311,6 +311,6 @@ export PIPE_ID="pipe-find-leads-with-exa-ai"export PIPE_FILE="pipe.ts"export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-find-leads-with-exa-ai"-deno run --allow-read --allow-write --allow-env --allow-net --allow-run --allow-sys examples/typescript/pipe-find-leads-with-exa-ai/pipe.ts+bun run examples/typescript/pipe-find-leads-with-exa-ai/pipe.ts*/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.jsondeleted file mode 100644index 207cf1eac..000000000--- a/examples/typescript/pipe-llama32-comment-linear-while-you-work/deno.json+++ /dev/null@@ -1,8 +0,0 @@-{- "imports": {- "zod": "npm:zod",- "ai": "npm:ai",- "ollama-ai-provider": "npm:ollama-ai-provider",- "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts"- }-}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.tsindex 971c0020d..ccd4c9cbf 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,9 @@-import { ContentItem, pipe } from "screenpipe";+import { ContentItem, pipe } from "@screenpipe/js";import { z } from "zod";import { generateObject } from "ai";import { createOllama } from "ollama-ai-provider";-import { LinearClient } from "npm:@linear/sdk";+import { LinearClient } from "@linear/sdk";const linearSearchQuery = z.object({query: z.string(),diff --git a/examples/typescript/pipe-meeting-summary-by-email/deno.json b/examples/typescript/pipe-meeting-summary-by-email/deno.jsondeleted file mode 100644index 17e46d1e4..000000000--- a/examples/typescript/pipe-meeting-summary-by-email/deno.json+++ /dev/null@@ -1,6 +0,0 @@-{- "imports": {- "nodemailer": "npm:nodemailer",- "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts"- }-}diff --git a/examples/typescript/pipe-meeting-summary-by-email/pipe.ts b/examples/typescript/pipe-meeting-summary-by-email/pipe.tsindex 0027c9b8c..d6708f1a1 100644--- a/examples/typescript/pipe-meeting-summary-by-email/pipe.ts+++ b/examples/typescript/pipe-meeting-summary-by-email/pipe.ts@@ -3,7 +3,7 @@ import {loadPipeConfig,ContentItem,extractJsonFromLlmResponse,-} from "screenpipe";+} from "@screenpipe/js";import nodemailer from "nodemailer";async function summarizeAudio(diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.json b/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.jsondeleted file mode 100644index 687bbee49..000000000--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/deno.json+++ /dev/null@@ -1,9 +0,0 @@-{- "imports": {- "zod": "npm:zod",- "ai": "npm:ai",- "ollama-ai-provider": "npm:ollama-ai-provider",- "fs": "node:fs",- "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts"- }-}diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.tsindex 51f9430fa..3e31ababb 100644--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts@@ -1,9 +1,8 @@-import { ContentItem } from "screenpipe";-import { Client } from "npm:@notionhq/client";+import { Client } from "@notionhq/client";import { z } from "zod";import { generateObject } from "ai";import { createOllama } from "ollama-ai-provider";-import { pipe } from "screenpipe";+import { pipe, ContentItem } from "@screenpipe/js";const engineeringLog = z.object({title: z.string(),diff --git a/examples/typescript/pipe-post-questions-on-reddit/deno.json b/examples/typescript/pipe-post-questions-on-reddit/deno.jsondeleted file mode 100644index f1ddf3ef8..000000000--- a/examples/typescript/pipe-post-questions-on-reddit/deno.json+++ /dev/null@@ -1,7 +0,0 @@-{- "imports": {- "fs": "node:fs",- "nodemailer": "npm:nodemailer",- "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts"- }-}diff --git a/examples/typescript/pipe-post-questions-on-reddit/pipe.ts b/examples/typescript/pipe-post-questions-on-reddit/pipe.tsindex fe2ae8613..8171ddb0e 100644--- a/examples/typescript/pipe-post-questions-on-reddit/pipe.ts+++ b/examples/typescript/pipe-post-questions-on-reddit/pipe.ts@@ -1,6 +1,9 @@-import * as fs from "fs";+import * as fs from "node:fs";import nodemailer from "nodemailer";-import { ContentItem, pipe } from "screenpipe";+import {+ ContentItem,+ pipe,+} from "@screenpipe/js";import process from "node:process";interface DailyLog {@@ -223,7 +226,10 @@ async function dailyLogPipeline(): Promise<void> {const openaiApiKey = config.openaiApiKey;const windowName = config.windowName || "";const pageSize = config.pageSize;- const contentType = config.contentType || "ocr"; // Default to 'ocr' if not specified+ const contentType = config.contentType || "ocr";++ const emailEnabled = !!(emailAddress && emailPassword);+ console.log("email enabled:", emailEnabled);console.log("creating logs dir");const logsDir = `${process.env.PIPE_DIR}/logs`;@@ -234,26 +240,27 @@ async function dailyLogPipeline(): Promise<void> {console.warn("failed to create logs dir, probably already exists");}- let lastEmailSent = new Date(0); // Initialize to a past date+ let lastEmailSent = new Date(0);- // send a welcome email to announce what will happen, when it will happen, and what it will do- const welcomeEmail = `- Welcome to the daily reddit questions pipeline!+ // Only send welcome email if email is enabled+ if (emailEnabled) {+ const welcomeEmail = `+ Welcome to the daily reddit questions pipeline!- This pipe will send you a daily list of reddit questions based on your screen data.- ${- summaryFrequency === "daily"- ? `It will run at ${emailTime} every day.`- : `It will run every ${summaryFrequency} hours.`- }-- `;- await sendEmail(- emailAddress,- emailPassword,- "daily reddit questions",- welcomeEmail- );+ This pipe will send you a daily list of reddit questions based on your screen data.+ ${+ summaryFrequency === "daily"+ ? `It will run at ${emailTime} every day.`+ : `It will run every ${summaryFrequency} hours.`+ }+ `;+ await sendEmail(+ emailAddress!,+ emailPassword!,+ "daily reddit questions",+ welcomeEmail+ );+ }while (true) {try {@@ -318,12 +325,18 @@ async function dailyLogPipeline(): Promise<void> {openaiApiKey);console.log("reddit questions:", redditQuestions);- await sendEmail(- emailAddress,- emailPassword,- "reddit questions",- redditQuestions- );++ // Send email only if enabled+ if (emailEnabled) {+ await sendEmail(+ emailAddress!,+ emailPassword!,+ "reddit questions",+ redditQuestions+ );+ }++ // Always send to inbox and desktop notificationawait pipe.inbox.send({title: "reddit questions",body: redditQuestions,diff --git a/examples/typescript/pipe-screen-time-storyteller/deno.json b/examples/typescript/pipe-screen-time-storyteller/deno.jsondeleted file mode 100644index 2cd86df14..000000000--- a/examples/typescript/pipe-screen-time-storyteller/deno.json+++ /dev/null@@ -1,14 +0,0 @@-{- "imports": {- "zod": "npm:zod",- "ai": "npm:ai",- "@ai-sdk/anthropic": "npm:@ai-sdk/anthropic",- "@ai-sdk/openai": "npm:@ai-sdk/openai",- "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts",- "node:fs/promises": "node:fs/promises",- "node:path": "node:path"- },- "compilerOptions": {- "types": ["node"]- }-}diff --git a/examples/typescript/pipe-screen-time-storyteller/pipe.ts b/examples/typescript/pipe-screen-time-storyteller/pipe.tsindex f47198832..ad96e79d9 100644--- a/examples/typescript/pipe-screen-time-storyteller/pipe.ts+++ b/examples/typescript/pipe-screen-time-storyteller/pipe.ts@@ -2,7 +2,7 @@ import { z } from "zod";import { generateObject } from "ai";import { anthropic } from "@ai-sdk/anthropic";import { openai } from "@ai-sdk/openai";-import { pipe, ContentItem } from "screenpipe";+import { pipe, ContentItem } from "@screenpipe/js";import * as fs from "node:fs/promises";import * as path from "node:path";import process from "node:process";diff --git a/examples/typescript/pipe-simple-nextjs/README.md b/examples/typescript/pipe-simple-nextjs/README.mdindex ff60ee6fa..2b3c8aaf0 100644--- a/examples/typescript/pipe-simple-nextjs/README.md+++ b/examples/typescript/pipe-simple-nextjs/README.md@@ -5,9 +5,9 @@ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-First, run the development server:```bash-deno run -A npm:npm@latest i+bun i-deno task --unstable-detect-cjs dev+bun dev```Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.diff --git a/examples/typescript/pipe-twitter-autopilot/pipe.ts b/examples/typescript/pipe-twitter-autopilot/pipe.tsindex 0e81401ff..e8b097e7a 100644--- a/examples/typescript/pipe-twitter-autopilot/pipe.ts+++ b/examples/typescript/pipe-twitter-autopilot/pipe.ts@@ -1,10 +1,9 @@-import { ContentItem } from "screenpipe";import { TwitterApi, type TweetV2 } from "twitter-api-v2";import { z } from "zod";import { generateObject } from "ai";import { createOllama } from "ollama-ai-provider";-import { pipe } from "screenpipe";-import { createOpenAI } from "npm:@ai-sdk/openai";+import { pipe, ContentItem } from "@screenpipe/js";+import { createOpenAI } from "@ai-sdk/openai";const twitterSuggestionLog = z.object({suggestions: z.array(@@ -113,21 +112,7 @@ async function fetchRelevantTweets(const minReplies = Math.max(1, 3 - attempt);const minRetweets = Math.max(1, 3 - attempt);- // Create search query with expanded criteria on later attempts- const baseTerms = [- "screen recording",- "screencasting",- "screen capture",- "screenpipe",- "recording software",- ];-- // Add more general terms in later attempts- if (attempt > 1) {- baseTerms.push("productivity", "software", "tech");- }-- const relevantKeywords = [...baseTerms, ...keywords]+ const relevantKeywords = keywords.filter((k) => k.length > 0).map((k) => `"${k}"`).join(" OR ");@@ -386,7 +371,7 @@ export PIPE_ID="pipe-twitter-autopilot"export PIPE_FILE="pipe.ts"export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-twitter-autopilot"-deno run --allow-read --allow-write --allow-env --allow-net --allow-run --allow-sys examples/typescript/pipe-twitter-autopilot/pipe.ts+bun run examples/typescript/pipe-twitter-autopilot/pipe.ts*/// ... existing code ...diff --git a/screenpipe-app-tauri/.gitignore b/screenpipe-app-tauri/.gitignoreindex 77c196197..f63a29cb7 100644--- a/screenpipe-app-tauri/.gitignore+++ b/screenpipe-app-tauri/.gitignore@@ -41,6 +41,6 @@ next-env.d.tsffmpeg**src-tauri/screenpipe**src-tauri/tesseract*-*src-tauri/deno*+*src-tauri/bun**src-tauri/ollama*diff --git a/screenpipe-app-tauri/scripts/pre_build.js b/screenpipe-app-tauri/scripts/pre_build.jsindex 4f4846615..b32a643e4 100644--- a/screenpipe-app-tauri/scripts/pre_build.js+++ b/screenpipe-app-tauri/scripts/pre_build.js@@ -82,135 +82,79 @@ const exports = {cmake: 'C:\\Program Files\\CMake\\bin',}-// Add this function to check if Deno is installed-async function isDenoInstalled() { // assuming it's installed in PATH+// Add this function to check if Bun is installed+async function isBunInstalled() {try {- await $`deno --version`.quiet();+ await $`bun --version`.quiet();return true;} catch (error) {return false;}}-// Add this function to install Deno-async function installDeno() {- if (await isDenoInstalled()) {- console.log('deno is already installed.');+// Add this function to install Bun+async function installBun() {+ if (await isBunInstalled()) {+ console.log('bun is already installed.');return;}- console.log('installing deno...');+ console.log('installing bun...');if (platform === 'windows') {- console.log('attempting to install deno using chocolatey...');+ console.log('attempting to install bun using powershell...');try {- await $`choco upgrade deno -y`;- console.log('deno installed/upgraded successfully using chocolatey.');- } catch (chocoError) {- console.error('failed to install/upgrade deno using chocolatey:', chocoError);- console.error('please install deno manually.');+ await $`powershell -Command "irm bun.sh/install.ps1|iex"`;+ console.log('bun installed successfully using powershell.');+ } catch (error) {+ console.error('failed to install bun:', error);+ console.error('please install bun manually.');}} else {// for macos and linux- await $`curl -fsSL https://deno.land/install.sh | sh`;+ await $`curl -fsSL https://bun.sh/install | bash`;}- console.log('deno installation attempt completed.');+ console.log('bun installation attempt completed.');}-// Add this function to copy the Deno binary-async function copyDenoBinary() {- console.log('checking deno binary for tauri...');+// Add this function to copy the Bun binary+async function copyBunBinary() {+ console.log('checking bun binary for tauri...');- let denoSrc, denoDest1, denoDest2;+ let bunSrc, bunDest1, bunDest2;if (platform === 'windows') {- // Check both potential installation locations- const chocoPathTools = 'C:\\ProgramData\\chocolatey\\lib\\deno\\tools\\deno.exe';- const chocoPathDirect = 'C:\\ProgramData\\chocolatey\\lib\\deno\\deno.exe';-- if (await fs.exists(chocoPathTools)) {- denoSrc = chocoPathTools;- } else if (await fs.exists(chocoPathDirect)) {- denoSrc = chocoPathDirect;- } else {- console.error('deno binary not found in expected locations');- return;- }- denoDest1 = path.join(cwd, 'deno-x86_64-pc-windows-msvc.exe');+ bunSrc = path.join(os.homedir(), 'AppData', 'Local', 'bun', 'bun.exe');+ bunDest1 = path.join(cwd, 'bun-x86_64-pc-windows-msvc.exe');} else if (platform === 'macos') {- denoSrc = path.join(os.homedir(), '.deno', 'bin', 'deno');- denoDest1 = path.join(cwd, 'deno-aarch64-apple-darwin');- denoDest2 = path.join(cwd, 'deno-x86_64-apple-darwin');+ bunSrc = path.join(os.homedir(), '.bun', 'bin', 'bun');+ bunDest1 = path.join(cwd, 'bun-aarch64-apple-darwin');+ bunDest2 = path.join(cwd, 'bun-x86_64-apple-darwin');} else if (platform === 'linux') {- denoSrc = path.join(os.homedir(), '.deno', 'bin', 'deno');- denoDest1 = path.join(cwd, 'deno-x86_64-unknown-linux-gnu');- } else {- console.error('unsupported platform for deno binary copy');- return;+ bunSrc = path.join(os.homedir(), '.bun', 'bin', 'bun');+ bunDest1 = path.join(cwd, 'bun-x86_64-unknown-linux-gnu');}- if (await fs.exists(denoDest1)) {- console.log('deno binary already exists for tauri.');+ if (await fs.exists(bunDest1)) {+ console.log('bun binary already exists for tauri.');return;}try {- // Check if the source file exists- await fs.access(denoSrc);-- // If it exists, proceed with copying- await copyFile(denoSrc, denoDest1);- console.log(`deno binary copied successfully to ${denoDest1}`);+ await fs.access(bunSrc);+ await copyFile(bunSrc, bunDest1);+ console.log(`bun binary copied successfully to ${bunDest1}`);if (platform === 'macos') {- await copyFile(denoSrc, denoDest2);- console.log(`deno binary also copied to ${denoDest2}`);+ await copyFile(bunSrc, bunDest2);+ console.log(`bun binary also copied to ${bunDest2}`);}} catch (error) {- if (error.code === 'ENOENT') {- console.error(`deno binary not found at expected location: ${denoSrc}`);- console.log('attempting to find deno in PATH...');-- try {- const { stdout } = await $`where deno`.quiet();- const denoPath = stdout.trim();- console.log(`found deno at: ${denoPath}`);- await fs.copyFile(denoPath, denoDest1);- await fs.chmod(denoDest1, 0o755);- console.log(`deno binary copied successfully from PATH to ${denoDest1}`);-- if (platform === 'macos') {- await fs.copyFile(denoPath, denoDest2);- await fs.chmod(denoDest2, 0o755);- console.log(`deno binary also copied to ${denoDest2}`);- }- } catch (pathError) {- console.error('failed to find deno in PATH:', pathError);- console.log('please ensure deno is installed and accessible in your PATH');- }- } else if (error.code === 'EPERM') {- console.error(`permission denied when copying deno binary. trying elevated copy...`);- await elevatedCopy(denoSrc, denoDest1);- console.log(`deno binary copied successfully to ${denoDest1} using elevated permissions`);- } else {- console.error(`unexpected error: ${error.message}`);- process.exit(1);- }+ console.error('failed to copy bun binary:', error);+ process.exit(1);}}-// Helper function to copy file with elevated permissions on Windows-async function elevatedCopy(src, dest) {- if (platform === 'win32') {- const { execSync } = require('child_process');- const command = `powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c copy ${src} ${dest}' -WindowStyle Hidden -Wait"`;- execSync(command);- } else {- // For non-Windows platforms, fall back to regular copy- await fs.copyFile(src, dest);- }- await fs.chmod(dest, 0o755); // ensure the binary is executable-}// Helper function to copy file and set permissionsasync function copyFile(src, dest) {@@ -603,8 +547,8 @@ async function installOllamaSidecar() {}// Near the end of the script, call these functions-await installDeno();-await copyDenoBinary();+await installBun();+await copyBunBinary();await installOllamaSidecar().catch(console.error);// --dev or --builddiff --git a/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json b/screenpipe-app-tauri/src-tauri/tauri.linux.conf.jsonindex a84c27153..f27755a28 100644--- a/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json+++ b/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json@@ -2,7 +2,7 @@"bundle": {"externalBin": ["screenpipe",- "deno",+ "bun","ollama"],"resources": [diff --git a/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json b/screenpipe-app-tauri/src-tauri/tauri.macos.conf.jsonindex c8dda7c50..38f47deac 100644--- a/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json+++ b/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json@@ -25,7 +25,7 @@"externalBin": ["screenpipe","ffmpeg",- "deno",+ "bun","ollama"]}diff --git a/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json b/screenpipe-app-tauri/src-tauri/tauri.windows.conf.jsonindex b6426ff0a..03e73e4c1 100644--- a/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json+++ b/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json@@ -2,7 +2,7 @@"bundle": {"externalBin": ["screenpipe",- "deno",+ "bun","ollama"],"resources": {diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.tomlindex b598d7c82..65ada8cf7 100644--- a/screenpipe-core/Cargo.toml+++ b/screenpipe-core/Cargo.toml@@ -49,6 +49,3 @@ cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]beta = ["dep:screenpipe-actions"]-[build-dependencies]-# Move this under the same feature flag-deno_core = { version = "0.311.0", optional = true }diff --git a/screenpipe-core/examples/simple-node-api-pipe/deno.json b/screenpipe-core/examples/simple-node-api-pipe/deno.jsondeleted file mode 100644index 0a4396f5e..000000000--- a/screenpipe-core/examples/simple-node-api-pipe/deno.json+++ /dev/null@@ -1,10 +0,0 @@-{- "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 filediff --git a/screenpipe-core/examples/simple-pipe-api-pipe/deno.json b/screenpipe-core/examples/simple-pipe-api-pipe/deno.jsondeleted file mode 100644index 0a4396f5e..000000000--- a/screenpipe-core/examples/simple-pipe-api-pipe/deno.json+++ /dev/null@@ -1,10 +0,0 @@-{- "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 filediff --git a/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts b/screenpipe-core/examples/simple-pipe-api-pipe/pipe.tsindex 0181075ee..41abc1ce4 100644--- a/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts+++ b/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts@@ -1,7 +1,7 @@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";+import { queryScreenpipe } from "@screenpipe/js";const simpleOllamaChat = async () => {console.log(diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 6b442b525..d94821f00 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -43,6 +43,21 @@ mod pipes {let pipe_dir = screenpipe_dir.join("pipes").join(pipe);let pipe_json_path = pipe_dir.join("pipe.json");+ // Check if pipe is still enabled+ if pipe_json_path.exists() {+ let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;+ let pipe_config: Value = serde_json::from_str(&pipe_json)?;++ if !pipe_config+ .get("enabled")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ {+ debug!("pipe {} is disabled, stopping", pipe);+ return Ok(None);+ }+ }+// Prepare environment variableslet mut env_vars = std::env::vars().collect::<Vec<(String, String)>>();env_vars.push((@@ -62,12 +77,9 @@ mod pipes {if pipe_config["is_nextjs"] == json!(true) {info!("Running Next.js pipe: {}", pipe);- // Install dependencies+ // Install dependencies using buninfo!("Installing dependencies for Next.js pipe");- let install_output = Command::new("deno")- .arg("run")- .arg("-A")- .arg("npm:npm@latest")+ let install_output = Command::new("bun").arg("install").current_dir(&pipe_dir).output()@@ -81,25 +93,6 @@ mod pipes {anyhow::bail!("Failed to install dependencies for Next.js pipe");}- // Build the Next.js project // ! broken https://github.com/denoland/deno/issues/25359- // info!("Building Next.js project");- // let build_output = Command::new("deno")- // .arg("run")- // .arg("-A")- // .arg("npm:next@latest")- // .arg("build")- // .current_dir(&pipe_dir)- // .output()- // .await?;-- // if !build_output.status.success() {- // error!(- // "Failed to build Next.js project: {}",- // String::from_utf8_lossy(&build_output.stderr)- // );- // anyhow::bail!("Failed to build Next.js project");- // }-let port = pick_unused_port().expect("No ports free");// Update pipe.json with the port@@ -109,27 +102,13 @@ mod pipes {let mut file = File::create(&pipe_json_path).await?;file.write_all(updated_pipe_json.as_bytes()).await?;- // Add the port to the environment variablesenv_vars.push(("PORT".to_string(), port.to_string()));- // Run the Next.js project- // let mut child = Command::new("deno")- // .arg("run")- // .arg("-A")- // .arg("npm:next@latest")- // .arg("start")- // .arg("-p")- // .arg(port.to_string())- // .current_dir(&pipe_dir)- // .envs(env_vars)- // .stdout(std::process::Stdio::piped())- // .stderr(std::process::Stdio::piped())- // .spawn()?;- let mut child = Command::new("deno")- .arg("task")- .arg("--unstable-detect-cjs")+ // Run the Next.js project with bun+ let mut child = Command::new("bun")+ .arg("run").arg("dev")- .arg("-p")+ .arg("--port").arg(port.to_string()).current_dir(&pipe_dir).envs(env_vars)@@ -155,16 +134,8 @@ mod pipes {main_module.to_str().unwrap().to_string(),));- // Execute Deno- let mut child = Command::new("deno")+ let mut child = Command::new("bun").arg("run")- .arg("--config")- .arg(pipe_dir.join("deno.json"))- .arg("--allow-read")- .arg("--allow-write")- .arg("--allow-net")- .arg("--allow-env")- .arg("--reload=https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts").arg(&main_module).envs(env_vars).stdout(std::process::Stdio::piped())@@ -335,11 +306,8 @@ mod pipes {info!("Detected Next.js project, setting up for production");// Run npm install- let mut install_child = Command::new("deno")- .arg("run")- .arg("-A")- .arg("npm:npm@latest")- .arg("install")+ let mut install_child = Command::new("bun")+ .arg("i").current_dir(&dest_dir).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped())@@ -348,20 +316,6 @@ mod pipes {// Stream logs for npm installstream_logs("npm install", &mut install_child).await?;- // Run next build // ! broken https://github.com/denoland/deno/issues/25359- // let mut build_child = Command::new("deno")- // .arg("run")- // .arg("-A")- // .arg("npm:next@latest")- // .arg("build")- // .current_dir(&dest_dir)- // .stdout(std::process::Stdio::piped())- // .stderr(std::process::Stdio::piped())- // .spawn()?;-- // // Stream logs for next build- // stream_logs("next build", &mut build_child).await?;-// Update pipe.json to indicate it's a Next.js projectlet mut pipe_config = if let Some(existing_json) = &existing_config {serde_json::from_str(&existing_json.as_str().unwrap())?@@ -525,72 +479,68 @@ mod pipes {}#[cfg(not(windows))]- const DENO_EXECUTABLE_NAME: &str = "deno";+ const BUN_EXECUTABLE_NAME: &str = "bun";#[cfg(windows)]- const DENO_EXECUTABLE_NAME: &str = "deno.exe";+ const BUN_EXECUTABLE_NAME: &str = "bun.exe";- pub fn find_deno() -> Option<PathBuf> {- debug!("starting search for deno executable");+ pub fn find_bun() -> Option<PathBuf> {+ debug!("starting search for bun executable");- // check if `deno` is in the PATH environment variable- if let Ok(path) = which(DENO_EXECUTABLE_NAME) {- debug!("found deno in PATH: {:?}", path);+ if let Ok(path) = which(BUN_EXECUTABLE_NAME) {+ debug!("found bun in PATH: {:?}", path);return Some(path);}- debug!("deno not found in PATH");+ debug!("bun not found in PATH");- // check in current working directoryif let Ok(cwd) = std::env::current_dir() {debug!("current working directory: {:?}", cwd);- let deno_in_cwd = cwd.join(DENO_EXECUTABLE_NAME);- if deno_in_cwd.is_file() && deno_in_cwd.exists() {- debug!("found deno in current working directory: {:?}", deno_in_cwd);- return Some(deno_in_cwd);+ let bun_in_cwd = cwd.join(BUN_EXECUTABLE_NAME);+ if bun_in_cwd.is_file() && bun_in_cwd.exists() {+ debug!("found bun in current working directory: {:?}", bun_in_cwd);+ return Some(bun_in_cwd);}- debug!("deno not found in current working directory");+ debug!("bun not found in current working directory");}- // check in the same folder as the executableif let Ok(exe_path) = std::env::current_exe() {if let Some(exe_folder) = exe_path.parent() {debug!("executable folder: {:?}", exe_folder);- let deno_in_exe_folder = exe_folder.join(DENO_EXECUTABLE_NAME);- if deno_in_exe_folder.exists() {- debug!("found deno in executable folder: {:?}", deno_in_exe_folder);- return Some(deno_in_exe_folder);+ let bun_in_exe_folder = exe_folder.join(BUN_EXECUTABLE_NAME);+ if bun_in_exe_folder.exists() {+ debug!("found bun in executable folder: {:?}", bun_in_exe_folder);+ return Some(bun_in_exe_folder);}- debug!("deno not found in executable folder");+ debug!("bun not found in executable folder");- // platform-specific checks#[cfg(target_os = "macos")]{let resources_folder = exe_folder.join("../Resources");debug!("resources folder: {:?}", resources_folder);- let deno_in_resources = resources_folder.join(DENO_EXECUTABLE_NAME);- if deno_in_resources.exists() {- debug!("found deno in resources folder: {:?}", deno_in_resources);- return Some(deno_in_resources);+ let bun_in_resources = resources_folder.join(BUN_EXECUTABLE_NAME);+ if bun_in_resources.exists() {+ debug!("found bun in resources folder: {:?}", bun_in_resources);+ return Some(bun_in_resources);}- debug!("deno not found in resources folder");+ debug!("bun not found in resources folder");}#[cfg(target_os = "linux")]{let lib_folder = exe_folder.join("lib");debug!("lib folder: {:?}", lib_folder);- let deno_in_lib = lib_folder.join(DENO_EXECUTABLE_NAME);- if deno_in_lib.exists() {- debug!("found deno in lib folder: {:?}", deno_in_lib);- return Some(deno_in_lib);+ let bun_in_lib = lib_folder.join(BUN_EXECUTABLE_NAME);+ if bun_in_lib.exists() {+ debug!("found bun in lib folder: {:?}", bun_in_lib);+ return Some(bun_in_lib);}- debug!("deno not found in lib folder");+ debug!("bun not found in lib folder");}}}- error!("deno not found");- None // return None if deno is not found+ error!("bun not found");+ None // return None if bun is not found}}diff --git a/screenpipe-js/.gitignore b/screenpipe-js/.gitignorenew file mode 100644index 000000000..b512c09d4--- /dev/null+++ b/screenpipe-js/.gitignore@@ -0,0 +1 @@+node_modules\ No newline at end of filediff --git a/screenpipe-js/bun.lockb b/screenpipe-js/bun.lockbnew file mode 100755index 000000000..08233e40fBinary files /dev/null and b/screenpipe-js/bun.lockb differdiff --git a/screenpipe-js/deno.json b/screenpipe-js/deno.jsondeleted file mode 100644index 358b7d299..000000000--- a/screenpipe-js/deno.json+++ /dev/null@@ -1,3 +0,0 @@-{- "lock": false-}diff --git a/screenpipe-js/dist/main.js b/screenpipe-js/dist/main.jsnew file mode 100644index 000000000..b265a4a80--- /dev/null+++ b/screenpipe-js/dist/main.js@@ -0,0 +1,1240 @@+import {createRequire} from "node:module";+var __create = Object.create;+var __getProtoOf = Object.getPrototypeOf;+var __defProp = Object.defineProperty;+var __getOwnPropNames = Object.getOwnPropertyNames;+var __hasOwnProp = Object.prototype.hasOwnProperty;+var __toESM = (mod, isNodeMode, target) => {+ target = mod != null ? __create(__getProtoOf(mod)) : {};+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;+ for (let key of __getOwnPropNames(mod))+ if (!__hasOwnProp.call(to, key))+ __defProp(to, key, {+ get: () => mod[key],+ enumerable: true+ });+ return to;+};+var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);+var __require = createRequire(import.meta.url);++// node_modules/node-cron/src/task.js+var require_task = __commonJS((exports, module) => {+ var EventEmitter = __require("events");++ class Task extends EventEmitter {+ constructor(execution) {+ super();+ if (typeof execution !== "function") {+ throw "execution must be a function";+ }+ this._execution = execution;+ }+ execute(now) {+ let exec;+ try {+ exec = this._execution(now);+ } catch (error) {+ return this.emit("task-failed", error);+ }+ if (exec instanceof Promise) {+ return exec.then(() => this.emit("task-finished")).catch((error) => this.emit("task-failed", error));+ } else {+ this.emit("task-finished");+ return exec;+ }+ }+ }+ module.exports = Task;+});++// node_modules/node-cron/src/convert-expression/month-names-conversion.js+var require_month_names_conversion = __commonJS((exports, module) => {+ module.exports = (() => {+ const months = [+ "january",+ "february",+ "march",+ "april",+ "may",+ "june",+ "july",+ "august",+ "september",+ "october",+ "november",+ "december"+ ];+ const shortMonths = [+ "jan",+ "feb",+ "mar",+ "apr",+ "may",+ "jun",+ "jul",+ "aug",+ "sep",+ "oct",+ "nov",+ "dec"+ ];+ function convertMonthName(expression, items) {+ for (let i = 0;i < items.length; i++) {+ expression = expression.replace(new RegExp(items[i], "gi"), parseInt(i, 10) + 1);+ }+ return expression;+ }+ function interprete(monthExpression) {+ monthExpression = convertMonthName(monthExpression, months);+ monthExpression = convertMonthName(monthExpression, shortMonths);+ return monthExpression;+ }+ return interprete;+ })();+});++// node_modules/node-cron/src/convert-expression/week-day-names-conversion.js+var require_week_day_names_conversion = __commonJS((exports, module) => {+ module.exports = (() => {+ const weekDays = [+ "sunday",+ "monday",+ "tuesday",+ "wednesday",+ "thursday",+ "friday",+ "saturday"+ ];+ const shortWeekDays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];+ function convertWeekDayName(expression, items) {+ for (let i = 0;i < items.length; i++) {+ expression = expression.replace(new RegExp(items[i], "gi"), parseInt(i, 10));+ }+ return expression;+ }+ function convertWeekDays(expression) {+ expression = expression.replace("7", "0");+ expression = convertWeekDayName(expression, weekDays);+ return convertWeekDayName(expression, shortWeekDays);+ }+ return convertWeekDays;+ })();+});++// node_modules/node-cron/src/convert-expression/asterisk-to-range-conversion.js+var require_asterisk_to_range_conversion = __commonJS((exports, module) => {+ module.exports = (() => {+ function convertAsterisk(expression, replecement) {+ if (expression.indexOf("*") !== -1) {+ return expression.replace("*", replecement);+ }+ return expression;+ }+ function convertAsterisksToRanges(expressions) {+ expressions[0] = convertAsterisk(expressions[0], "0-59");+ expressions[1] = convertAsterisk(expressions[1], "0-59");+ expressions[2] = convertAsterisk(expressions[2], "0-23");+ expressions[3] = convertAsterisk(expressions[3], "1-31");+ expressions[4] = convertAsterisk(expressions[4], "1-12");+ expressions[5] = convertAsterisk(expressions[5], "0-6");+ return expressions;+ }+ return convertAsterisksToRanges;+ })();+});++// node_modules/node-cron/src/convert-expression/range-conversion.js+var require_range_conversion = __commonJS((exports, module) => {+ module.exports = (() => {+ function replaceWithRange(expression, text, init, end) {+ const numbers = [];+ let last = parseInt(end);+ let first = parseInt(init);+ if (first > last) {+ last = parseInt(init);+ first = parseInt(end);+ }+ for (let i = first;i <= last; i++) {+ numbers.push(i);+ }+ return expression.replace(new RegExp(text, "i"), numbers.join());+ }+ function convertRange(expression) {+ const rangeRegEx = /(\d+)-(\d+)/;+ let match = rangeRegEx.exec(expression);+ while (match !== null && match.length > 0) {+ expression = replaceWithRange(expression, match[0], match[1], match[2]);+ match = rangeRegEx.exec(expression);+ }+ return expression;+ }+ function convertAllRanges(expressions) {+ for (let i = 0;i < expressions.length; i++) {+ expressions[i] = convertRange(expressions[i]);+ }+ return expressions;+ }+ return convertAllRanges;+ })();+});++// node_modules/node-cron/src/convert-expression/step-values-conversion.js+var require_step_values_conversion = __commonJS((exports, module) => {+ module.exports = (() => {+ function convertSteps(expressions) {+ var stepValuePattern = /^(.+)\/(\w+)$/;+ for (var i = 0;i < expressions.length; i++) {+ var match = stepValuePattern.exec(expressions[i]);+ var isStepValue = match !== null && match.length > 0;+ if (isStepValue) {+ var baseDivider = match[2];+ if (isNaN(baseDivider)) {+ throw baseDivider + " is not a valid step value";+ }+ var values = match[1].split(",");+ var stepValues = [];+ var divider = parseInt(baseDivider, 10);+ for (var j = 0;j <= values.length; j++) {+ var value = parseInt(values[j], 10);+ if (value % divider === 0) {+ stepValues.push(value);+ }+ }+ expressions[i] = stepValues.join(",");+ }+ }+ return expressions;+ }+ return convertSteps;+ })();+});++// node_modules/node-cron/src/convert-expression/index.js+var require_convert_expression = __commonJS((exports, module) => {+ var monthNamesConversion = require_month_names_conversion();+ var weekDayNamesConversion = require_week_day_names_conversion();+ var convertAsterisksToRanges = require_asterisk_to_range_conversion();+ var convertRanges = require_range_conversion();+ var convertSteps = require_step_values_conversion();+ module.exports = (() => {+ function appendSeccondExpression(expressions) {+ if (expressions.length === 5) {+ return ["0"].concat(expressions);+ }+ return expressions;+ }+ function removeSpaces(str) {+ return str.replace(/\s{2,}/g, " ").trim();+ }+ function normalizeIntegers(expressions) {+ for (let i = 0;i < expressions.length; i++) {+ const numbers = expressions[i].split(",");+ for (let j = 0;j < numbers.length; j++) {+ numbers[j] = parseInt(numbers[j]);+ }+ expressions[i] = numbers;+ }+ return expressions;+ }+ function interprete(expression) {+ let expressions = removeSpaces(expression).split(" ");+ expressions = appendSeccondExpression(expressions);+ expressions[4] = monthNamesConversion(expressions[4]);+ expressions[5] = weekDayNamesConversion(expressions[5]);+ expressions = convertAsterisksToRanges(expressions);+ expressions = convertRanges(expressions);+ expressions = convertSteps(expressions);+ expressions = normalizeIntegers(expressions);+ return expressions.join(" ");+ }+ return interprete;+ })();+});++// node_modules/node-cron/src/pattern-validation.js+var require_pattern_validation = __commonJS((exports, module) => {+ function isValidExpression(expression, min, max) {+ const options = expression.split(",");+ for (const option of options) {+ const optionAsInt = parseInt(option, 10);+ if (!Number.isNaN(optionAsInt) && (optionAsInt < min || optionAsInt > max) || !validationRegex.test(option))+ return false;+ }+ return true;+ }+ function isInvalidSecond(expression) {+ return !isValidExpression(expression, 0, 59);+ }+ function isInvalidMinute(expression) {+ return !isValidExpression(expression, 0, 59);+ }+ function isInvalidHour(expression) {+ return !isValidExpression(expression, 0, 23);+ }+ function isInvalidDayOfMonth(expression) {+ return !isValidExpression(expression, 1, 31);+ }+ function isInvalidMonth(expression) {+ return !isValidExpression(expression, 1, 12);+ }+ function isInvalidWeekDay(expression) {+ return !isValidExpression(expression, 0, 7);+ }+ function validateFields(patterns, executablePatterns) {+ if (isInvalidSecond(executablePatterns[0]))+ throw new Error(`${patterns[0]} is a invalid expression for second`);+ if (isInvalidMinute(executablePatterns[1]))+ throw new Error(`${patterns[1]} is a invalid expression for minute`);+ if (isInvalidHour(executablePatterns[2]))+ throw new Error(`${patterns[2]} is a invalid expression for hour`);+ if (isInvalidDayOfMonth(executablePatterns[3]))+ throw new Error(`${patterns[3]} is a invalid expression for day of month`);+ if (isInvalidMonth(executablePatterns[4]))+ throw new Error(`${patterns[4]} is a invalid expression for month`);+ if (isInvalidWeekDay(executablePatterns[5]))+ throw new Error(`${patterns[5]} is a invalid expression for week day`);+ }+ function validate(pattern) {+ if (typeof pattern !== "string")+ throw new TypeError("pattern must be a string!");+ const patterns = pattern.split(" ");+ const executablePatterns = convertExpression(pattern).split(" ");+ if (patterns.length === 5)+ patterns.unshift("0");+ validateFields(patterns, executablePatterns);+ }+ var convertExpression = require_convert_expression();+ var validationRegex = /^(?:\d+|\*|\*\/\d+)$/;+ module.exports = validate;+});++// node_modules/node-cron/src/time-matcher.js+var require_time_matcher = __commonJS((exports, module) => {+ function matchPattern(pattern, value) {+ if (pattern.indexOf(",") !== -1) {+ const patterns = pattern.split(",");+ return patterns.indexOf(value.toString()) !== -1;+ }+ return pattern === value.toString();+ }+ var validatePattern = require_pattern_validation();+ var convertExpression = require_convert_expression();++ class TimeMatcher {+ constructor(pattern, timezone) {+ validatePattern(pattern);+ this.pattern = convertExpression(pattern);+ this.timezone = timezone;+ this.expressions = this.pattern.split(" ");+ this.dtf = this.timezone ? new Intl.DateTimeFormat("en-US", {+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ hourCycle: "h23",+ fractionalSecondDigits: 3,+ timeZone: this.timezone+ }) : null;+ }+ match(date) {+ date = this.apply(date);+ const runOnSecond = matchPattern(this.expressions[0], date.getSeconds());+ const runOnMinute = matchPattern(this.expressions[1], date.getMinutes());+ const runOnHour = matchPattern(this.expressions[2], date.getHours());+ const runOnDay = matchPattern(this.expressions[3], date.getDate());+ const runOnMonth = matchPattern(this.expressions[4], date.getMonth() + 1);+ const runOnWeekDay = matchPattern(this.expressions[5], date.getDay());+ return runOnSecond && runOnMinute && runOnHour && runOnDay && runOnMonth && runOnWeekDay;+ }+ apply(date) {+ if (this.dtf) {+ return new Date(this.dtf.format(date));+ }+ return date;+ }+ }+ module.exports = TimeMatcher;+});++// node_modules/node-cron/src/scheduler.js+var require_scheduler = __commonJS((exports, module) => {+ var EventEmitter = __require("events");+ var TimeMatcher = require_time_matcher();++ class Scheduler extends EventEmitter {+ constructor(pattern, timezone, autorecover) {+ super();+ this.timeMatcher = new TimeMatcher(pattern, timezone);+ this.autorecover = autorecover;+ }+ start() {+ this.stop();+ let lastCheck = process.hrtime();+ let lastExecution = this.timeMatcher.apply(new Date);+ const matchTime = () => {+ const delay = 1000;+ const elapsedTime = process.hrtime(lastCheck);+ const elapsedMs = (elapsedTime[0] * 1e9 + elapsedTime[1]) / 1e6;+ const missedExecutions = Math.floor(elapsedMs / 1000);+ for (let i = missedExecutions;i >= 0; i--) {+ const date = new Date(new Date().getTime() - i * 1000);+ let date_tmp = this.timeMatcher.apply(date);+ if (lastExecution.getTime() < date_tmp.getTime() && (i === 0 || this.autorecover) && this.timeMatcher.match(date)) {+ this.emit("scheduled-time-matched", date_tmp);+ date_tmp.setMilliseconds(0);+ lastExecution = date_tmp;+ }+ }+ lastCheck = process.hrtime();+ this.timeout = setTimeout(matchTime, delay);+ };+ matchTime();+ }+ stop() {+ if (this.timeout) {+ clearTimeout(this.timeout);+ }+ this.timeout = null;+ }+ }+ module.exports = Scheduler;+});++// node_modules/uuid/dist/rng.js+var require_rng = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function rng() {+ if (poolPtr > rnds8Pool.length - 16) {+ _crypto.default.randomFillSync(rnds8Pool);+ poolPtr = 0;+ }+ return rnds8Pool.slice(poolPtr, poolPtr += 16);+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = rng;+ var _crypto = _interopRequireDefault(__require("crypto"));+ var rnds8Pool = new Uint8Array(256);+ var poolPtr = rnds8Pool.length;+});++// node_modules/uuid/dist/regex.js+var require_regex = __commonJS((exports) => {+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;+ exports.default = _default;+});++// node_modules/uuid/dist/validate.js+var require_validate = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function validate(uuid) {+ return typeof uuid === "string" && _regex.default.test(uuid);+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _regex = _interopRequireDefault(require_regex());+ var _default = validate;+ exports.default = _default;+});++// node_modules/uuid/dist/stringify.js+var require_stringify = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function stringify(arr, offset = 0) {+ const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();+ if (!(0, _validate.default)(uuid)) {+ throw TypeError("Stringified UUID is invalid");+ }+ return uuid;+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _validate = _interopRequireDefault(require_validate());+ var byteToHex = [];+ for (let i = 0;i < 256; ++i) {+ byteToHex.push((i + 256).toString(16).substr(1));+ }+ var _default = stringify;+ exports.default = _default;+});++// node_modules/uuid/dist/v1.js+var require_v1 = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function v1(options, buf, offset) {+ let i = buf && offset || 0;+ const b = buf || new Array(16);+ options = options || {};+ let node = options.node || _nodeId;+ let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;+ if (node == null || clockseq == null) {+ const seedBytes = options.random || (options.rng || _rng.default)();+ if (node == null) {+ node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];+ }+ if (clockseq == null) {+ clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;+ }+ }+ let msecs = options.msecs !== undefined ? options.msecs : Date.now();+ let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;+ const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;+ if (dt < 0 && options.clockseq === undefined) {+ clockseq = clockseq + 1 & 16383;+ }+ if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {+ nsecs = 0;+ }+ if (nsecs >= 1e4) {+ throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");+ }+ _lastMSecs = msecs;+ _lastNSecs = nsecs;+ _clockseq = clockseq;+ msecs += 12219292800000;+ const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;+ b[i++] = tl >>> 24 & 255;+ b[i++] = tl >>> 16 & 255;+ b[i++] = tl >>> 8 & 255;+ b[i++] = tl & 255;+ const tmh = msecs / 4294967296 * 1e4 & 268435455;+ b[i++] = tmh >>> 8 & 255;+ b[i++] = tmh & 255;+ b[i++] = tmh >>> 24 & 15 | 16;+ b[i++] = tmh >>> 16 & 255;+ b[i++] = clockseq >>> 8 | 128;+ b[i++] = clockseq & 255;+ for (let n = 0;n < 6; ++n) {+ b[i + n] = node[n];+ }+ return buf || (0, _stringify.default)(b);+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _rng = _interopRequireDefault(require_rng());+ var _stringify = _interopRequireDefault(require_stringify());+ var _nodeId;+ var _clockseq;+ var _lastMSecs = 0;+ var _lastNSecs = 0;+ var _default = v1;+ exports.default = _default;+});++// node_modules/uuid/dist/parse.js+var require_parse = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function parse(uuid) {+ if (!(0, _validate.default)(uuid)) {+ throw TypeError("Invalid UUID");+ }+ let v;+ const arr = new Uint8Array(16);+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;+ arr[1] = v >>> 16 & 255;+ arr[2] = v >>> 8 & 255;+ arr[3] = v & 255;+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;+ arr[5] = v & 255;+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;+ arr[7] = v & 255;+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;+ arr[9] = v & 255;+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;+ arr[11] = v / 4294967296 & 255;+ arr[12] = v >>> 24 & 255;+ arr[13] = v >>> 16 & 255;+ arr[14] = v >>> 8 & 255;+ arr[15] = v & 255;+ return arr;+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _validate = _interopRequireDefault(require_validate());+ var _default = parse;+ exports.default = _default;+});++// node_modules/uuid/dist/v35.js+var require_v35 = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function stringToBytes(str) {+ str = unescape(encodeURIComponent(str));+ const bytes = [];+ for (let i = 0;i < str.length; ++i) {+ bytes.push(str.charCodeAt(i));+ }+ return bytes;+ }+ function _default(name, version, hashfunc) {+ function generateUUID(value, namespace, buf, offset) {+ if (typeof value === "string") {+ value = stringToBytes(value);+ }+ if (typeof namespace === "string") {+ namespace = (0, _parse.default)(namespace);+ }+ if (namespace.length !== 16) {+ throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");+ }+ let bytes = new Uint8Array(16 + value.length);+ bytes.set(namespace);+ bytes.set(value, namespace.length);+ bytes = hashfunc(bytes);+ bytes[6] = bytes[6] & 15 | version;+ bytes[8] = bytes[8] & 63 | 128;+ if (buf) {+ offset = offset || 0;+ for (let i = 0;i < 16; ++i) {+ buf[offset + i] = bytes[i];+ }+ return buf;+ }+ return (0, _stringify.default)(bytes);+ }+ try {+ generateUUID.name = name;+ } catch (err) {+ }+ generateUUID.DNS = DNS;+ generateUUID.URL = URL;+ return generateUUID;+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = _default;+ exports.URL = exports.DNS = undefined;+ var _stringify = _interopRequireDefault(require_stringify());+ var _parse = _interopRequireDefault(require_parse());+ var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";+ exports.DNS = DNS;+ var URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";+ exports.URL = URL;+});++// node_modules/uuid/dist/md5.js+var require_md5 = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function md5(bytes) {+ if (Array.isArray(bytes)) {+ bytes = Buffer.from(bytes);+ } else if (typeof bytes === "string") {+ bytes = Buffer.from(bytes, "utf8");+ }+ return _crypto.default.createHash("md5").update(bytes).digest();+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _crypto = _interopRequireDefault(__require("crypto"));+ var _default = md5;+ exports.default = _default;+});++// node_modules/uuid/dist/v3.js+var require_v3 = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _v = _interopRequireDefault(require_v35());+ var _md = _interopRequireDefault(require_md5());+ var v3 = (0, _v.default)("v3", 48, _md.default);+ var _default = v3;+ exports.default = _default;+});++// node_modules/uuid/dist/v4.js+var require_v4 = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function v4(options, buf, offset) {+ options = options || {};+ const rnds = options.random || (options.rng || _rng.default)();+ rnds[6] = rnds[6] & 15 | 64;+ rnds[8] = rnds[8] & 63 | 128;+ if (buf) {+ offset = offset || 0;+ for (let i = 0;i < 16; ++i) {+ buf[offset + i] = rnds[i];+ }+ return buf;+ }+ return (0, _stringify.default)(rnds);+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _rng = _interopRequireDefault(require_rng());+ var _stringify = _interopRequireDefault(require_stringify());+ var _default = v4;+ exports.default = _default;+});++// node_modules/uuid/dist/sha1.js+var require_sha1 = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function sha1(bytes) {+ if (Array.isArray(bytes)) {+ bytes = Buffer.from(bytes);+ } else if (typeof bytes === "string") {+ bytes = Buffer.from(bytes, "utf8");+ }+ return _crypto.default.createHash("sha1").update(bytes).digest();+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _crypto = _interopRequireDefault(__require("crypto"));+ var _default = sha1;+ exports.default = _default;+});++// node_modules/uuid/dist/v5.js+var require_v5 = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _v = _interopRequireDefault(require_v35());+ var _sha = _interopRequireDefault(require_sha1());+ var v5 = (0, _v.default)("v5", 80, _sha.default);+ var _default = v5;+ exports.default = _default;+});++// node_modules/uuid/dist/nil.js+var require_nil = __commonJS((exports) => {+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _default = "00000000-0000-0000-0000-000000000000";+ exports.default = _default;+});++// node_modules/uuid/dist/version.js+var require_version = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ function version(uuid) {+ if (!(0, _validate.default)(uuid)) {+ throw TypeError("Invalid UUID");+ }+ return parseInt(uuid.substr(14, 1), 16);+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ exports.default = undefined;+ var _validate = _interopRequireDefault(require_validate());+ var _default = version;+ exports.default = _default;+});++// node_modules/uuid/dist/index.js+var require_dist = __commonJS((exports) => {+ function _interopRequireDefault(obj) {+ return obj && obj.__esModule ? obj : { default: obj };+ }+ Object.defineProperty(exports, "__esModule", {+ value: true+ });+ Object.defineProperty(exports, "v1", {+ enumerable: true,+ get: function() {+ return _v.default;+ }+ });+ Object.defineProperty(exports, "v3", {+ enumerable: true,+ get: function() {+ return _v2.default;+ }+ });+ Object.defineProperty(exports, "v4", {+ enumerable: true,+ get: function() {+ return _v3.default;+ }+ });+ Object.defineProperty(exports, "v5", {+ enumerable: true,+ get: function() {+ return _v4.default;+ }+ });+ Object.defineProperty(exports, "NIL", {+ enumerable: true,+ get: function() {+ return _nil.default;+ }+ });+ Object.defineProperty(exports, "version", {+ enumerable: true,+ get: function() {+ return _version.default;+ }+ });+ Object.defineProperty(exports, "validate", {+ enumerable: true,+ get: function() {+ return _validate.default;+ }+ });+ Object.defineProperty(exports, "stringify", {+ enumerable: true,+ get: function() {+ return _stringify.default;+ }+ });+ Object.defineProperty(exports, "parse", {+ enumerable: true,+ get: function() {+ return _parse.default;+ }+ });+ var _v = _interopRequireDefault(require_v1());+ var _v2 = _interopRequireDefault(require_v3());+ var _v3 = _interopRequireDefault(require_v4());+ var _v4 = _interopRequireDefault(require_v5());+ var _nil = _interopRequireDefault(require_nil());+ var _version = _interopRequireDefault(require_version());+ var _validate = _interopRequireDefault(require_validate());+ var _stringify = _interopRequireDefault(require_stringify());+ var _parse = _interopRequireDefault(require_parse());+});++// node_modules/node-cron/src/scheduled-task.js+var require_scheduled_task = __commonJS((exports, module) => {+ var EventEmitter = __require("events");+ var Task = require_task();+ var Scheduler = require_scheduler();+ var uuid = require_dist();++ class ScheduledTask extends EventEmitter {+ constructor(cronExpression, func, options) {+ super();+ if (!options) {+ options = {+ scheduled: true,+ recoverMissedExecutions: false+ };+ }+ this.options = options;+ this.options.name = this.options.name || uuid.v4();+ this._task = new Task(func);+ this._scheduler = new Scheduler(cronExpression, options.timezone, options.recoverMissedExecutions);+ this._scheduler.on("scheduled-time-matched", (now) => {+ this.now(now);+ });+ if (options.scheduled !== false) {+ this._scheduler.start();+ }+ if (options.runOnInit === true) {+ this.now("init");+ }+ }+ now(now = "manual") {+ let result = this._task.execute(now);+ this.emit("task-done", result);+ }+ start() {+ this._scheduler.start();+ }+ stop() {+ this._scheduler.stop();+ }+ }+ module.exports = ScheduledTask;+});++// node_modules/node-cron/src/background-scheduled-task/index.js+var require_background_scheduled_task = __commonJS((exports, module) => {+ var __dirname = "/Users/louisbeaumont/Documents/screen-pipe/screenpipe-js/node_modules/node-cron/src/background-scheduled-task";+ var EventEmitter = __require("events");+ var path = __require("path");+ var { fork } = __require("child_process");+ var uuid = require_dist();+ var daemonPath = `${__dirname}/daemon.js`;++ class BackgroundScheduledTask extends EventEmitter {+ constructor(cronExpression, taskPath, options) {+ super();+ if (!options) {+ options = {+ scheduled: true,+ recoverMissedExecutions: false+ };+ }+ this.cronExpression = cronExpression;+ this.taskPath = taskPath;+ this.options = options;+ this.options.name = this.options.name || uuid.v4();+ if (options.scheduled) {+ this.start();+ }+ }+ start() {+ this.stop();+ this.forkProcess = fork(daemonPath);+ this.forkProcess.on("message", (message) => {+ switch (message.type) {+ case "task-done":+ this.emit("task-done", message.result);+ break;+ }+ });+ let options = this.options;+ options.scheduled = true;+ this.forkProcess.send({+ type: "register",+ path: path.resolve(this.taskPath),+ cron: this.cronExpression,+ options+ });+ }+ stop() {+ if (this.forkProcess) {+ this.forkProcess.kill();+ }+ }+ pid() {+ if (this.forkProcess) {+ return this.forkProcess.pid;+ }+ }+ isRunning() {+ return !this.forkProcess.killed;+ }+ }+ module.exports = BackgroundScheduledTask;+});++// node_modules/node-cron/src/storage.js+var require_storage = __commonJS((exports, module) => {+ module.exports = (() => {+ if (!global.scheduledTasks) {+ global.scheduledTasks = new Map;+ }+ return {+ save: (task) => {+ if (!task.options) {+ const uuid = require_dist();+ task.options = {};+ task.options.name = uuid.v4();+ }+ global.scheduledTasks.set(task.options.name, task);+ },+ getTasks: () => {+ return global.scheduledTasks;+ }+ };+ })();+});++// node_modules/node-cron/src/node-cron.js+var require_node_cron = __commonJS((exports, module) => {+ function schedule(expression, func, options) {+ const task = createTask(expression, func, options);+ storage.save(task);+ return task;+ }+ function createTask(expression, func, options) {+ if (typeof func === "string")+ return new BackgroundScheduledTask(expression, func, options);+ return new ScheduledTask(expression, func, options);+ }+ function validate(expression) {+ try {+ validation(expression);+ return true;+ } catch (_) {+ return false;+ }+ }+ function getTasks() {+ return storage.getTasks();+ }+ var ScheduledTask = require_scheduled_task();+ var BackgroundScheduledTask = require_background_scheduled_task();+ var validation = require_pattern_validation();+ var storage = require_storage();+ module.exports = { schedule, validate, getTasks };+});++// main.ts+var import_node_cron = __toESM(require_node_cron(), 1);+import * as fs from "node:fs";+function toCamelCase(str) {+ return str.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace("-", "").replace("_", ""));+}+function convertToCamelCase(obj) {+ 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;+ }, {});+ }+ return obj;+}+function toSnakeCase(str) {+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);+}+async function sendDesktopNotification(options) {+ 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;+ }+}+function loadPipeConfig() {+ 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 = {};+ parsedConfig.fields.forEach((field) => {+ config[field.name] = field.value !== undefined ? field.value : field.default;+ });+ return config;+ } catch (error) {+ console.error("Error loading pipe.json:", error);+ return {};+ }+}+async function queryScreenpipe(params) {+ 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);+ } catch (error) {+ console.error("error querying screenpipe:", error);+ return null;+ }+}+function extractJsonFromLlmResponse(response) {+ 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");+ }+ }+}+async function sendInputControl(action) {+ const apiUrl = process.env.SCREENPIPE_SERVER_URL || "http://localhost:3030";+ try {+ const response = await fetch(`${apiUrl}/experimental/input_control`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ action })+ });+ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }+ const data = await response.json();+ return data.success;+ } catch (error) {+ console.error("failed to control input:", error);+ return false;+ }+}++class Task {+ _name;+ _interval;+ _time = null;+ _handler = null;+ _cronTask = null;+ constructor(name) {+ this._name = name;+ this._interval = 0;+ }+ every(interval) {+ this._interval = interval;+ return this;+ }+ at(time) {+ this._time = time;+ return this;+ }+ do(handler) {+ this._handler = handler;+ return this;+ }+ schedule() {+ if (!this._handler) {+ throw new Error(`No handler defined for task: ${this._name}`);+ }+ const cronExpression = this.toCronExpression();+ this._cronTask = import_node_cron.default.schedule(cronExpression, this._handler, {+ name: this._name+ });+ }+ stop() {+ return this._cronTask.stop();+ }+ toCronExpression() {+ if (typeof this._interval === "number") {+ const minutes = Math.floor(this._interval / 60000);+ return `*/${minutes} * * * *`;+ }+ const [value, unit] = this._interval.split(" ");+ switch (unit) {+ case "second":+ case "seconds":+ return `*/${value} * * * * *`;+ case "minute":+ case "minutes":+ return `*/${value} * * * *`;+ case "hour":+ case "hours":+ return `0 */${value} * * *`;+ case "day":+ case "days":+ return `0 0 */${value} * *`;+ default:+ throw new Error(`Unsupported interval unit: ${unit}`);+ }+ }+}++class Scheduler {+ tasks = [];+ task(name) {+ const task = new Task(name);+ this.tasks.push(task);+ return task;+ }+ start() {+ this.tasks.forEach((task) => task.schedule());+ }+ stop() {+ import_node_cron.default.getTasks().forEach((task) => task.stop());+ this.tasks = [];+ }+}+var pipe = {+ sendDesktopNotification,+ loadPipeConfig,+ queryScreenpipe,+ inbox: {+ send: async (message) => {+ const notificationApiUrl = process.env.SCREENPIPE_SERVER_URL || "http://localhost:11435";+ try {+ const response = await fetch(`${notificationApiUrl}/inbox`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...message, type: "inbox" })+ });+ return response.ok;+ } catch (error) {+ console.error("failed to send inbox message:", error);+ return false;+ }+ }+ },+ scheduler: new Scheduler,+ input: {+ type: (text) => {+ return sendInputControl({ type: "WriteText", data: text });+ },+ press: (key) => {+ return sendInputControl({ type: "KeyPress", data: key });+ },+ moveMouse: (x, y) => {+ return sendInputControl({ type: "MouseMove", data: { x, y } });+ },+ click: (button) => {+ return sendInputControl({ type: "MouseClick", data: button });+ }+ }+};+export {+ sendDesktopNotification,+ queryScreenpipe,+ pipe,+ loadPipeConfig,+ extractJsonFromLlmResponse+};diff --git a/screenpipe-js/main.ts b/screenpipe-js/main.tsindex 5a21b2a6e..b78d433e3 100644--- a/screenpipe-js/main.ts+++ b/screenpipe-js/main.ts@@ -1,9 +1,7 @@import * as fs from "node:fs";import * as path from "node:path";-import process from "node:process";-import cronParser from "npm:cron-parser";-// @ts-types="npm:@types/node-cron"-import cron, { type ScheduledTask } from "npm:node-cron";+import cronParser from "cron-parser";+import cron, { type ScheduledTask } from "node-cron";// Type definitionsexport interface PipeConfig {@@ -254,7 +252,6 @@ export interface InboxMessageAction {action: string;}-class Task {private _name: string;private _interval: string | number;diff --git a/screenpipe-js/package.json b/screenpipe-js/package.jsonnew file mode 100644index 000000000..1c56c11bb--- /dev/null+++ b/screenpipe-js/package.json@@ -0,0 +1,34 @@+{+ "name": "@screenpipe/js",+ "version": "0.1.0",+ "module": "main.ts",+ "type": "module",+ "files": [+ "main.ts",+ "dist"+ ],+ "exports": {+ ".": {+ "import": "./dist/main.js",+ "require": "./dist/main.cjs",+ "types": "./dist/main.d.ts"+ }+ },+ "scripts": {+ "build": "bun build ./main.ts --outdir ./dist --target node",+ "test": "bun test",+ "prepublishOnly": "bun run build"+ },+ "devDependencies": {+ "bun-types": "latest",+ "@types/node": "^22.8.4"+ },+ "dependencies": {+ "@types/node-cron": "^3.0.11",+ "cron-parser": "^4.9.0",+ "node-cron": "^3.0.3"+ },+ "peerDependencies": {+ "typescript": "^5.0.0"+ }+}\ No newline at end of filediff --git a/screenpipe-js/tests/loadPipeConfig.test.ts b/screenpipe-js/tests/loadPipeConfig.test.tsindex 616d00104..67b90574e 100644--- a/screenpipe-js/tests/loadPipeConfig.test.ts+++ b/screenpipe-js/tests/loadPipeConfig.test.ts@@ -1,71 +1,67 @@-import process from 'node:process';-import { assertEquals } from "jsr:@std/assert";-import { v1 as uuid } from 'jsr:@std/uuid';-import { ParsedConfig, loadPipeConfig } from '../main.ts';--Deno.test('should return empty object if pipe.json is not found', async () => {- // ensuring it'll not be valid values- Deno.env.set('SCREENPIPE_DIR', uuid.generate());- Deno.env.set('PIPE_ID', uuid.generate());-- const loadedConfig = await loadPipeConfig();-- assertEquals(loadedConfig, {});-});--const setupPipeDir = async (config: ParsedConfig) => {- const pipeId = uuid.generate();- const pipeDir = await Deno.makeTempDir({ prefix: 'screenpipe-test-dir' });-- // ensuring if the env vars are set using process.env, they are available in the Deno.env- process.env.SCREENPIPE_DIR = pipeDir;- process.env.PIPE_ID = pipeId;-- const encoder = new TextEncoder();- const content = encoder.encode(JSON.stringify(config));+import { describe, expect, test, beforeEach } from "bun:test";+import { v4 as uuid } from "uuid";+import { ParsedConfig, loadPipeConfig } from "../main";+import { mkdir, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";++describe("loadPipeConfig", () => {+ let pipeDir: string;+ let pipeId: string;++ const setupPipeDir = async (config: ParsedConfig) => {+ pipeId = uuid();+ pipeDir = join(tmpdir(), `screenpipe-test-${uuid()}`);++ process.env.SCREENPIPE_DIR = pipeDir;+ process.env.PIPE_ID = pipeId;++ const pipePath = join(pipeDir, "pipes", pipeId);+ await mkdir(pipePath, { recursive: true });+ await writeFile(join(pipePath, "pipe.json"), JSON.stringify(config));+ };++ const generateConfig = () => ({+ interval: Math.floor(Math.random() * 100),+ summaryFrequency: Math.floor(Math.random() * 100),+ emailAddress: `mail+${uuid()}@contact.com`,+ });- // getting value from process.env via Deno.env- const pipePath = `${Deno.env.get('SCREENPIPE_DIR')}/pipes/${Deno.env.get('PIPE_ID')}`+ test("should return empty object if pipe.json is not found", async () => {+ process.env.SCREENPIPE_DIR = uuid();+ process.env.PIPE_ID = uuid();- await Deno.mkdir(pipePath, { recursive: true });-- await Deno.writeFile(`${pipePath}/pipe.json`, content);-}+ const loadedConfig = loadPipeConfig();+ expect(loadedConfig).toEqual({});+ });-const generateConfig = () => ({- interval: Math.floor(Math.random() * 100),- summaryFrequency: Math.floor(Math.random() * 100),- emailAddress: `mail+${uuid.generate()}@contact.com`,-})+ test("should load config from SCREENPIPE_DIR/pipes/PIPE_ID/pipe.json", async () => {+ const config = generateConfig();-Deno.test('should load config from SCREENPIPE_DIR/pipes/PIPE_ID/pipe.json', async () => {- const config = generateConfig();+ await setupPipeDir({+ fields: [+ { name: "interval", value: config.interval },+ { name: "summaryFrequency", value: config.summaryFrequency },+ { name: "emailAddress", value: config.emailAddress },+ ],+ });- await setupPipeDir({- fields: [- { name: 'interval', value: config.interval },- { name: 'summaryFrequency', value: config.summaryFrequency },- { name: 'emailAddress', value: config.emailAddress },- ]+ const loadedConfig = loadPipeConfig();+ expect(loadedConfig).toEqual(config);});- const loadedConfig = await loadPipeConfig();-- assertEquals(loadedConfig, config);-});+ test("should load default values if not provided in config", async () => {+ const config = generateConfig();-Deno.test('should load default values if not provided in config', async () => {- const config = generateConfig();+ await setupPipeDir({+ fields: [+ { name: "interval", value: config.interval },+ { name: "summaryFrequency", default: 5 },+ { name: "emailAddress", value: config.emailAddress },+ ],+ });- await setupPipeDir({- fields: [- { name: 'interval', value: config.interval },- { name: 'summaryFrequency', default: 5 },- { name: 'emailAddress', value: config.emailAddress },- ]+ const loadedConfig = loadPipeConfig();+ expect(loadedConfig).toEqual({ ...config, summaryFrequency: 5 });});-- const loadedConfig = await loadPipeConfig();-- assertEquals(loadedConfig, { ...config, summaryFrequency: 5 });});diff --git a/screenpipe-js/tests/scheduler.test.ts b/screenpipe-js/tests/scheduler.test.tsindex d0884c91a..0f92a9cda 100644--- a/screenpipe-js/tests/scheduler.test.ts+++ b/screenpipe-js/tests/scheduler.test.ts@@ -1,114 +1,68 @@-import {- assertSpyCall,- assertSpyCallArgs,- assertSpyCalls,- type MethodSpy,- spy,-} from "jsr:@std/testing/mock";-import { pipe } from "../main.ts";-import { afterEach, beforeEach, describe, it } from "jsr:@std/testing/bdd";-// @ts-types="npm:@types/node-cron"-import cron from "npm:node-cron";-import { retry } from "jsr:@std/async/retry";-import { assertGreaterOrEqual, assertLessOrEqual } from "jsr:@std/assert@^1.0.6";+import { describe, expect, test, mock, beforeEach, afterEach } from "bun:test";+import { pipe } from "../main";+import cron from "node-cron";describe("Scheduler", () => {- let cronSpy: MethodSpy<- typeof cron,- Parameters<typeof cron.schedule>,- ReturnType<typeof cron.schedule>- >;-- beforeEach(async () => {- cronSpy = await spy(cron, "schedule");+ let cronSpy: any;+ let scheduledTasks: { expression: string; handler: () => Promise<void>; options: any }[] = [];++ beforeEach(() => {+ scheduledTasks = [];+ cronSpy = mock((expression: string, handler: () => Promise<void>, options: any) => {+ scheduledTasks.push({ expression, handler, options });+ return {+ stop: () => {},+ };+ });+ // @ts-ignore+ cron.schedule = cronSpy;});afterEach(() => {- cronSpy.restore();+ mock.restore();pipe.scheduler.stop();+ scheduledTasks = [];});- it("Scheduler - task execution", async () => {+ test("Scheduler - task execution", async () => {const scheduler = pipe.scheduler;- const mockTask = spy(() => Promise.resolve());+ const mockTask = mock(() => Promise.resolve());scheduler.task("testTask").every("1 second").do(mockTask);-- // Validate the cron job was not scheduled yet- assertSpyCalls(cronSpy, 0);-- // Register the routes on node-cronscheduler.start();- // Validate the cron jobs were scheduled- assertSpyCall(cronSpy, 0);- assertSpyCallArgs(cronSpy, 0, ["*/1 * * * * *", mockTask, {+ expect(cronSpy).toHaveBeenCalledTimes(1);+ expect(cronSpy).toHaveBeenCalledWith("*/1 * * * * *", mockTask, {name: "testTask",- }]);-- // retry until the task runs- await retry(() => {- assertSpyCalls(mockTask, 1);- }, {- maxAttempts: 10,- maxTimeout: 1000,- minTimeout: 200,});++ // Execute the scheduled task handler+ await scheduledTasks[0].handler();+ expect(mockTask).toHaveBeenCalled();});- it("multiple tasks", async () => {+ test("multiple tasks", async () => {const scheduler = pipe.scheduler;- const mockTask1 = spy(() => Promise.resolve());- const mockTask2 = spy(() => Promise.resolve());+ const mockTask1 = mock(() => Promise.resolve());+ const mockTask2 = mock(() => Promise.resolve());scheduler.task("task1").every("1 second").do(mockTask1);-scheduler.task("task2").every("2 seconds").do(mockTask2);-- // Validate the cron jobs were not scheduled yet- assertSpyCalls(cronSpy, 0);-- // Register the routes on node-cronscheduler.start();- // Validate the cron jobs were scheduled- assertSpyCalls(cronSpy, 2);- assertSpyCallArgs(cronSpy, 0, ["*/1 * * * * *", mockTask1, {+ expect(cronSpy).toHaveBeenCalledTimes(2);+ expect(cronSpy).toHaveBeenNthCalledWith(1, "*/1 * * * * *", mockTask1, {name: "task1",- }]);- assertSpyCallArgs(cronSpy, 1, ["*/2 * * * * *", mockTask2, {+ });+ expect(cronSpy).toHaveBeenNthCalledWith(2, "*/2 * * * * *", mockTask2, {name: "task2",- }]);-- // IMPORTANT: The assertions as below are not deterministic, thus we need to retry- // Retrying is an optimized way of `await setTimeout(xTime)` until the condition is met- // Avoid checking literal values, e.g., mockTask1.calls.length === 1 && mockTask2.calls.length === 0- // Instead, use `assertGreaterOrEqual` or `assertLessOrEqual` to make the test more resilient- // and avoid flakiness-- // retry until the first task runs- // and ensure the second was not called yet- await retry(() => {- // 1 sec job was called at least once- assertGreaterOrEqual(mockTask1.calls.length, 1);- // 2 sec job was called half the times of the 1 sec job (or less)- assertLessOrEqual(mockTask2.calls.length, Math.ceil(mockTask1.calls.length / 2));- }, {- maxAttempts: 10,- maxTimeout: 1000,- minTimeout: 100,});- // retry a bunch of times until the second task is called- await retry(() => {- // 2 sec job was called at least once- assertGreaterOrEqual(mockTask2.calls.length, 1);- // 1 sec job was called at least twice the times of the 2 sec job- assertGreaterOrEqual(mockTask1.calls.length, mockTask2.calls.length * 2);- }, {- maxAttempts: 10,- maxTimeout: 1000,- minTimeout: 100,- });+ // Execute both task handlers+ await scheduledTasks[0].handler();+ await scheduledTasks[1].handler();++ expect(mockTask1).toHaveBeenCalled();+ expect(mockTask2).toHaveBeenCalled();});});diff --git a/screenpipe-js/tsconfig.json b/screenpipe-js/tsconfig.jsonnew file mode 100644index 000000000..7768e41f4--- /dev/null+++ b/screenpipe-js/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "types": [+ "bun-types"+ ],+ "esModuleInterop": true,+ "skipLibCheck": true,+ "strict": true,+ "declaration": true,+ "outDir": "dist"+ },+ "include": [+ "src/**/*"+ ],+ "exclude": [+ "node_modules",+ "dist"+ ]+}\ No newline at end of filediff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex f22d0119a..312535d4e 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -13,7 +13,7 @@ use screenpipe_audio::{};use screenpipe_core::find_ffmpeg_path;use screenpipe_server::{- cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand}, start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server+ cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand}, start_continuous_recording, watch_pid, DatabaseManager, PipeControl, PipeManager, ResourceMonitor, Server};use screenpipe_vision::monitor::list_monitors;use serde_json::{json, Value};@@ -114,7 +114,8 @@ async fn main() -> anyhow::Result<()> {let _log_guard = setup_logging(&local_data_dir, &cli)?;- let pipe_manager = Arc::new(PipeManager::new(local_data_dir_clone.clone()));+ let (pipe_manager, mut pipe_control_rx) = PipeManager::new(local_data_dir_clone.clone());+ let pipe_manager = Arc::new(pipe_manager);if let Some(pipe_command) = cli.command {match pipe_command {@@ -420,7 +421,8 @@ async fn main() -> anyhow::Result<()> {);- let mut pipe_futures = FuturesUnordered::new();+ let pipe_futures = Arc::new(tokio::sync::Mutex::new(FuturesUnordered::new()));+ let pipe_futures_clone = pipe_futures.clone();// print screenpipe in gradientprintln!("\n\n{}", DISPLAY.truecolor(147, 112, 219).bold());@@ -650,7 +652,7 @@ async fn main() -> anyhow::Result<()> {continue;}match pipe_manager.start_pipe(&pipe.id).await {- Ok(future) => pipe_futures.push(future),+ Ok(future) => pipe_futures.lock().await.push(future),Err(e) => eprintln!("failed to start pipe {}: {}", pipe.id, e),}}@@ -660,7 +662,7 @@ async fn main() -> anyhow::Result<()> {let pipes_future = async {loop {- if let Some(result) = pipe_futures.next().await {+ if let Some(result) = pipe_futures_clone.lock().await.next().await {info!("pipe completed: {:?}", result);} else {tokio::time::sleep(std::time::Duration::from_secs(1)).await;@@ -712,6 +714,24 @@ async fn main() -> anyhow::Result<()> {}}+ let pipe_control_future = async {+ while let Some(control) = pipe_control_rx.recv().await {+ match control {+ PipeControl::Enable(pipe_id) => {+ debug!("enabling pipe: {}", pipe_id);+ match pipe_manager.start_pipe(&pipe_id).await {+ Ok(future) => pipe_futures_clone.lock().await.push(future),+ Err(e) => error!("failed to start pipe {}: {}", pipe_id, e),+ }+ }+ PipeControl::Disable(pipe_id) => {+ debug!("disabling pipe: {}", pipe_id);+ }+ }+ }+ };+ pin_mut!(pipe_control_future);+tokio::select! {_ = handle => info!("recording completed"),result = &mut server_future => {@@ -723,6 +743,9 @@ async fn main() -> anyhow::Result<()> {_ = &mut pipes_future => {info!("all pipes completed, but server is still running");}+ _ = &mut pipe_control_future => {+ info!("pipe control channel closed");+ }_ = ctrl_c_future => {info!("received ctrl+c, initiating shutdown");let _ = shutdown_tx.send(());diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex f4e6663b3..bedec86ed 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -27,3 +27,4 @@ pub use server::HealthCheckResponse;pub use server::PaginatedResponse;pub use server::Server;pub use video::VideoCapture;+pub use pipe_manager::PipeControl;diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rsindex 329f30aaf..b57c570d9 100644--- a/screenpipe-server/src/pipe_manager.rs+++ b/screenpipe-server/src/pipe_manager.rs@@ -6,6 +6,7 @@ use std::future::Future;use std::path::PathBuf;use tokio::fs::File;use tokio::io::AsyncWriteExt;+use tokio::sync::mpsc::{self, Receiver, Sender};use tracing::{debug, info, warn};#[derive(Clone, Serialize, Deserialize, Debug)]@@ -17,13 +18,27 @@ pub struct PipeInfo {pub port: Option<u16>,}+#[derive(Debug)]+pub enum PipeControl {+ Enable(String),+ Disable(String),+}+pub struct PipeManager {screenpipe_dir: PathBuf,+ control_tx: Sender<PipeControl>,}impl PipeManager {- pub fn new(screenpipe_dir: PathBuf) -> Self {- PipeManager { screenpipe_dir }+ pub fn new(screenpipe_dir: PathBuf) -> (Self, Receiver<PipeControl>) {+ let (control_tx, control_rx) = mpsc::channel(32);+ (+ PipeManager {+ screenpipe_dir,+ control_tx,+ },+ control_rx,+ )}pub async fn start_pipe(@@ -73,6 +88,9 @@ impl PipeManager {})};+ // Check enabled before moving new_config+ let enabled = new_config.get("enabled").and_then(Value::as_bool);+if let Value::Object(existing_config) = &mut config {if let Value::Object(updates) = new_config {for (key, value) in updates {@@ -85,6 +103,16 @@ impl PipeManager {return Err(anyhow::anyhow!("existing configuration is not an object"));}+ // Use the previously extracted enabled value+ if let Some(enabled) = enabled {+ let control = if enabled {+ PipeControl::Enable(id.to_string())+ } else {+ PipeControl::Disable(id.to_string())+ };+ let _ = self.control_tx.send(control).await;+ }+let updated_config_str = serde_json::to_string_pretty(&config)?;let mut file = File::create(&config_path).await?;