Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat: Apple Foundation Models integration — on-device AI for screenpipe (macOS 26+) (#2178)

Louis Beaumontd4abc619c0df
diff --git a/.pi/skills/release/SKILL.md b/.pi/skills/release/SKILL.md
index 1cd16b80b..ed3cb6120 100644
--- a/.pi/skills/release/SKILL.md
+++ b/.pi/skills/release/SKILL.md
@@ -53,42 +53,46 @@ echo "=== MCP ===" && grep '"version"' screenpipe-integrations/screenpipe-mcp/pa
### 2. Generate Changelog
-Get commits since last release and generate a user-friendly changelog:
+**Automated (preferred)**: Run the changelog generation script in the website repo:
```bash
-# Get last release tag
-LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
-
-# Get commits since last release (or last 50 if no tag)
-if [ -n "$LAST_TAG" ]; then
- git log $LAST_TAG..HEAD --oneline --no-merges
-else
- git log -50 --oneline --no-merges
-fi
+cd ~/Documents/website-screenpipe
+bun scripts/generate-changelog.ts --since <LAST_BUMP_COMMIT> --version v<NEW_VERSION>
```
-Then create changelog at `content/changelogs/vX.Y.Z.md` with format:
+This uses Claude Haiku to summarize commits into a structured JSON entry at
+`content/changelogs/<version>.json`, which renders on https://screenpi.pe/changelog.
-```markdown
-## New Features
-- Feature description (from commit context)
+Requires `ANTHROPIC_API_KEY` in environment.
-## Improvements
-- Improvement description
+**Manual fallback**: If the script isn't available, create the JSON manually:
-## Bug Fixes
-- Fix description
+```bash
+# Get commits since last release
+git log <LAST_TAG>..HEAD --oneline --no-merges
+```
-#### **Full Changelog:** [abc123..def456](https://github.com/mediar-ai/screenpipe/compare/abc123..def456)
+Then create `~/Documents/website-screenpipe/content/changelogs/<version>.json`:
+
+```json
+{
+ "version": "2.0.XXX",
+ "date": "YYYY-MM-DD",
+ "summary": "One sentence summary of the release",
+ "features": ["new feature descriptions"],
+ "improvements": ["improvement descriptions"],
+ "fixes": ["bug fix descriptions"],
+ "commitCount": 30
+}
```
Guidelines:
- Only include changes that bring clear **customer value**
- Skip: CI changes, refactors, dependency bumps, merge commits
-- Be concise but descriptive
-- Group related changes together
+- Be concise but descriptive — max 5 items per category
+- Write for non-technical users
-Also copy to `screenpipe-app-tauri/public/CHANGELOG.md` for in-app display.
+After generating, commit and push the website repo to deploy.
### 3. Bump Version
diff --git a/Cargo.lock b/Cargo.lock
index e2072f7d3..f737ca0fe 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6624,9 +6624,25 @@ dependencies = [
"windows 0.58.0",
]
+[[package]]
+name = "screenpipe-apple-intelligence"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "chrono",
+ "reqwest 0.12.12",
+ "serde",
+ "serde_json",
+ "tokio",
+ "tokio-stream",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "screenpipe-audio"
-version = "0.3.102"
+version = "0.3.106"
dependencies = [
"anyhow",
"bytemuck",
@@ -6679,7 +6695,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.102"
+version = "0.3.106"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -6730,7 +6746,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.102"
+version = "0.3.106"
dependencies = [
"anyhow",
"chrono",
@@ -6754,7 +6770,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.102"
+version = "0.3.106"
dependencies = [
"anyhow",
"chrono",
@@ -6772,7 +6788,7 @@ dependencies = [
[[package]]
name = "screenpipe-integrations"
-version = "0.3.102"
+version = "0.3.106"
dependencies = [
"anyhow",
"image",
@@ -6787,7 +6803,7 @@ dependencies = [
[[package]]
name = "screenpipe-server"
-version = "0.3.102"
+version = "0.3.106"
dependencies = [
"anyhow",
"async-trait",
@@ -6857,7 +6873,7 @@ dependencies = [
[[package]]
name = "screenpipe-vision"
-version = "0.3.102"
+version = "0.3.106"
dependencies = [
"accessibility-sys",
"anyhow",
diff --git a/apps/screenpipe-app-tauri/components/settings/apple-intelligence-card.tsx b/apps/screenpipe-app-tauri/components/settings/apple-intelligence-card.tsx
new file mode 100644
index 000000000..ec39584cb
--- /dev/null
+++ b/apps/screenpipe-app-tauri/components/settings/apple-intelligence-card.tsx
@@ -0,0 +1,478 @@
+"use client";
+
+import React, { useState, useEffect, useCallback } from "react";
+import { Card, CardContent } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Label } from "@/components/ui/label";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
+import {
+ Loader2,
+ ChevronDown,
+ ChevronRight,
+ Copy,
+ Check,
+ AlertCircle,
+ Sparkles,
+ X,
+ Trash2,
+} from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { useToast } from "@/components/ui/use-toast";
+import { platform } from "@tauri-apps/plugin-os";
+
+const AppleLogo = ({ className }: { className?: string }) => (
+ <svg
+ viewBox="0 0 814 1000"
+ xmlns="http://www.w3.org/2000/svg"
+ className={className}
+ fill="currentColor"
+ >
+ <path d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57.8-155.5-127.4c-58.3-81.6-105.6-207.2-105.6-326.4C-1.4 320.7 77.8 210.4 182.7 210.4c65.2 0 119.6 42.8 160.5 42.8 39 0 99.8-45.4 174.7-45.4 28.2 0 129.7 2.6 196.2 133.1zm-270-244.9c31.5-37 53.5-88.4 53.5-139.8 0-7.1-.6-14.3-1.9-20.1-51 1.9-111.4 33.9-147.8 76.5-27.6 31.5-56.5 82.3-56.5 134.6 0 7.8.6 15.6 1.3 18.2 2.6.6 6.5 1.3 10.4 1.3 45.9-.1 103-30.5 141-70.7z" />
+ </svg>
+);
+
+// ─── Types ──────────────────────────────────────────────────────────────────
+
+interface TodoItem {
+ text: string;
+ app?: string;
+ urgency: "low" | "medium" | "high";
+}
+
+const API = "http://localhost:3030";
+
+const SYSTEM_PROMPT = `You extract action items from screen recordings and audio transcripts.
+Rules:
+- Only extract clear, actionable tasks
+- Each item: short, clear sentence
+- Set urgency: high (deadline/urgent), medium (should do soon), low (nice to have)
+- Include the app name if visible
+- Respond ONLY with a JSON array, no other text
+- Example: [{"text":"Review PR #42","app":"GitHub","urgency":"high"}]
+- If none found, respond with: []`;
+
+// ─── Component ──────────────────────────────────────────────────────────────
+
+export function AppleIntelligenceCard() {
+ const { toast } = useToast();
+ const [os, setOs] = useState<string>("");
+ const [isExpanded, setIsExpanded] = useState(false);
+ const [aiStatus, setAiStatus] = useState<
+ "unknown" | "available" | "unavailable"
+ >("unknown");
+ const [isExtracting, setIsExtracting] = useState(false);
+ const [todos, setTodos] = useState<TodoItem[]>([]);
+ const [todosOpen, setTodosOpen] = useState(true);
+ const [lastRun, setLastRun] = useState<Date | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [copied, setCopied] = useState(false);
+ const [lookbackMinutes, setLookbackMinutes] = useState(30);
+
+ useEffect(() => {
+ setOs(platform());
+ }, []);
+
+ // Load cached results
+ useEffect(() => {
+ try {
+ const saved = localStorage?.getItem("apple-intelligence-todos");
+ if (saved) {
+ const parsed = JSON.parse(saved);
+ setTodos(parsed.items || []);
+ if (parsed.lastRun) setLastRun(new Date(parsed.lastRun));
+ }
+ const lb = localStorage?.getItem("apple-intelligence-lookback");
+ if (lb) setLookbackMinutes(parseInt(lb));
+ } catch {}
+ }, []);
+
+ // Persist
+ useEffect(() => {
+ try {
+ localStorage?.setItem(
+ "apple-intelligence-todos",
+ JSON.stringify({ items: todos, lastRun: lastRun?.toISOString() })
+ );
+ } catch {}
+ }, [todos, lastRun]);
+
+ useEffect(() => {
+ try {
+ localStorage?.setItem(
+ "apple-intelligence-lookback",
+ String(lookbackMinutes)
+ );
+ } catch {}
+ }, [lookbackMinutes]);
+
+ // Check AI availability
+ const checkStatus = useCallback(async () => {
+ try {
+ const resp = await fetch(`${API}/ai/status`, {
+ signal: AbortSignal.timeout(3000),
+ });
+ if (resp.ok) {
+ const data = await resp.json();
+ setAiStatus(data.available ? "available" : "unavailable");
+ } else {
+ setAiStatus("unavailable");
+ }
+ } catch {
+ setAiStatus("unavailable");
+ }
+ }, []);
+
+ useEffect(() => {
+ checkStatus();
+ const interval = setInterval(checkStatus, 30000);
+ return () => clearInterval(interval);
+ }, [checkStatus]);
+
+ // ─── Extract TODOs ──────────────────────────────────────────────────────
+
+ const runExtraction = async () => {
+ if (isExtracting || aiStatus !== "available") return;
+ setIsExtracting(true);
+ setError(null);
+
+ try {
+ // 1. Fetch recent data from screenpipe
+ const now = new Date();
+ const start = new Date(now.getTime() - lookbackMinutes * 60 * 1000);
+ const params = new URLSearchParams({
+ content_type: "all",
+ start_time: start.toISOString(),
+ end_time: now.toISOString(),
+ limit: "50",
+ min_length: "20",
+ });
+
+ const searchResp = await fetch(`${API}/search?${params}`);
+ if (!searchResp.ok) throw new Error("Failed to fetch screenpipe data");
+ const searchData = await searchResp.json();
+
+ // 2. Build context string from results
+ const parts: string[] = [];
+ for (const item of searchData.data || []) {
+ if (item.type === "OCR") {
+ const c = item.content;
+ const text = c?.text?.trim();
+ if (text) parts.push(`[${c.app_name || "?"}] ${text}`);
+ } else if (item.type === "Audio") {
+ const c = item.content;
+ const text = c?.transcription?.trim();
+ if (text) parts.push(`[Audio] ${text}`);
+ }
+ }
+
+ if (parts.length === 0) {
+ setError("No recent data found");
+ return;
+ }
+
+ // 3. Truncate to fit model context (~1500 chars for content)
+ let context = parts.join("\n");
+ if (context.length > 1500) {
+ context = context.slice(0, 1500);
+ }
+
+ // 4. Single call to generic AI endpoint
+ const aiResp = await fetch(`${API}/ai/chat/completions`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: [
+ { role: "system", content: SYSTEM_PROMPT },
+ { role: "user", content: context },
+ ],
+ }),
+ });
+
+ if (!aiResp.ok) {
+ const err = await aiResp.json().catch(() => ({}));
+ throw new Error(err.error || `AI error: ${aiResp.status}`);
+ }
+
+ const aiData = await aiResp.json();
+ const raw = aiData.choices?.[0]?.message?.content || "[]";
+
+ // 5. Parse JSON (strip markdown fences if present)
+ let jsonStr = raw.trim();
+ if (jsonStr.startsWith("```")) {
+ jsonStr = jsonStr
+ .split("\n")
+ .slice(1)
+ .filter((l: string) => !l.startsWith("```"))
+ .join("\n");
+ }
+
+ const items: TodoItem[] = JSON.parse(jsonStr);
+ const valid = items.filter((t) => t.text?.trim());
+
+ setTodos(valid);
+ setLastRun(new Date());
+
+ if (valid.length > 0) {
+ toast({
+ title: `Found ${valid.length} action item${valid.length > 1 ? "s" : ""}`,
+ });
+ } else {
+ toast({ title: "No action items found" });
+ }
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ setError(msg);
+ } finally {
+ setIsExtracting(false);
+ }
+ };
+
+ // ─── Helpers ──────────────────────────────────────────────────────────────
+
+ const copyTodos = () => {
+ const text = todos
+ .map(
+ (t, i) =>
+ `${i + 1}. ${t.text}${t.app ? ` (${t.app})` : ""}${t.urgency === "high" ? " ⚡" : ""}`
+ )
+ .join("\n");
+ navigator.clipboard.writeText(text);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ };
+
+ const formatLastRun = (date: Date | null) => {
+ if (!date) return "Never";
+ const diff = Date.now() - date.getTime();
+ const mins = Math.floor(diff / 60000);
+ if (mins < 1) return "Just now";
+ if (mins < 60) return `${mins}m ago`;
+ return `${Math.floor(mins / 60)}h ago`;
+ };
+
+ const urgencyIcon = (u: string) =>
+ u === "high" ? "⚡" : u === "medium" ? "●" : "○";
+ const urgencyColor = (u: string) =>
+ u === "high"
+ ? "text-red-500"
+ : u === "medium"
+ ? "text-yellow-500"
+ : "text-muted-foreground";
+
+ if (os && os !== "macos") return null;
+
+ return (
+ <Card className="border-border bg-card overflow-hidden">
+ <CardContent className="p-0">
+ <div className="flex items-start p-4 gap-4">
+ <div className="flex-shrink-0">
+ <div className="w-10 h-10 rounded-xl bg-gradient-to-b from-[#147CE5] to-[#0E5FC2] flex items-center justify-center">
+ <AppleLogo className="w-5 h-5 text-white" />
+ </div>
+ </div>
+
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <h3 className="text-sm font-semibold text-foreground">
+ Apple Intelligence
+ </h3>
+ <span className="px-2 py-0.5 text-xs font-medium bg-muted text-muted-foreground rounded-full">
+ on-device
+ </span>
+ {aiStatus === "available" && (
+ <span className="px-2 py-0.5 text-xs font-medium bg-foreground text-background rounded-full">
+ available
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground mb-3">
+ Extract action items from your screen & audio using on-device AI.
+ {aiStatus === "unavailable" && (
+ <span className="block mt-1">
+ <AlertCircle className="h-3 w-3 inline mr-1" />
+ Requires macOS 26+ with Apple Intelligence enabled.
+ </span>
+ )}
+ </p>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ onClick={runExtraction}
+ disabled={isExtracting || aiStatus !== "available"}
+ size="sm"
+ className="gap-1.5 h-7 text-xs"
+ >
+ {isExtracting ? (
+ <>
+ <Loader2 className="h-3 w-3 animate-spin" />
+ Extracting...
+ </>
+ ) : (
+ <>
+ <Sparkles className="h-3 w-3" />
+ Extract TODOs
+ </>
+ )}
+ </Button>
+
+ <Select
+ value={String(lookbackMinutes)}
+ onValueChange={(v) => setLookbackMinutes(parseInt(v))}
+ >
+ <SelectTrigger className="h-7 text-xs w-[90px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="15">15 min</SelectItem>
+ <SelectItem value="30">30 min</SelectItem>
+ <SelectItem value="60">1 hour</SelectItem>
+ <SelectItem value="120">2 hours</SelectItem>
+ </SelectContent>
+ </Select>
+
+ {todos.length > 0 && (
+ <Button
+ onClick={() => {
+ setTodos([]);
+ setLastRun(null);
+ }}
+ variant="ghost"
+ size="sm"
+ className="gap-1 h-7 text-xs text-muted-foreground"
+ >
+ <Trash2 className="h-3 w-3" />
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* TODO items */}
+ {todos.length > 0 && (
+ <div className="border-t border-border">
+ <Collapsible open={todosOpen} onOpenChange={setTodosOpen}>
+ <CollapsibleTrigger asChild>
+ <button className="flex items-center justify-between w-full px-4 py-2 hover:bg-muted/50 transition-colors">
+ <div className="flex items-center gap-2">
+ {todosOpen ? (
+ <ChevronDown className="h-3 w-3 text-muted-foreground" />
+ ) : (
+ <ChevronRight className="h-3 w-3 text-muted-foreground" />
+ )}
+ <span className="text-xs font-medium">Action Items</span>
+ <Badge
+ variant="secondary"
+ className="h-4 px-1.5 text-[10px]"
+ >
+ {todos.length}
+ </Badge>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 px-2 text-[10px] gap-1"
+ onClick={(e) => {
+ e.stopPropagation();
+ copyTodos();
+ }}
+ >
+ {copied ? (
+ <Check className="h-3 w-3" />
+ ) : (
+ <Copy className="h-3 w-3" />
+ )}
+ </Button>
+ </button>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <div className="px-4 pb-3 space-y-1">
+ {todos.map((todo, i) => (
+ <div
+ key={i}
+ className="flex items-start gap-2 py-1.5 px-2 rounded hover:bg-muted/50 group"
+ >
+ <span
+ className={`text-xs mt-0.5 ${urgencyColor(todo.urgency)}`}
+ >
+ {urgencyIcon(todo.urgency)}
+ </span>
+ <div className="flex-1 min-w-0">
+ <p className="text-xs text-foreground leading-relaxed">
+ {todo.text}
+ </p>
+ {todo.app && (
+ <span className="text-[10px] text-muted-foreground">
+ {todo.app}
+ </span>
+ )}
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-5 w-5 p-0 opacity-0 group-hover:opacity-100"
+ onClick={() => {
+ navigator.clipboard.writeText(todo.text);
+ toast({ title: "Copied" });
+ }}
+ >
+ <Copy className="h-2.5 w-2.5" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ )}
+
+ {/* Error */}
+ {error && (
+ <div className="px-4 py-2 border-t border-border">
+ <div className="flex items-center gap-2 text-xs text-red-500">
+ <AlertCircle className="h-3 w-3 flex-shrink-0" />
+ <span className="truncate">{error}</span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-5 w-5 p-0 ml-auto"
+ onClick={() => setError(null)}
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {/* Status bar */}
+ <div className="px-4 py-2 bg-muted/50 border-t border-border">
+ <div className="flex items-center gap-3 text-xs text-muted-foreground">
+ <span>
+ Last:{" "}
+ <span className="text-foreground">{formatLastRun(lastRun)}</span>
+ </span>
+ <span
+ className={`ml-auto ${aiStatus === "available" ? "text-green-500" : ""}`}
+ >
+ {aiStatus === "available"
+ ? "● on-device"
+ : aiStatus === "unavailable"
+ ? "○ not available"
+ : "○ checking..."}
+ </span>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
index 8f845bd83..11dff6f40 100644
--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
@@ -11,6 +11,7 @@ import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
import { platform } from "@tauri-apps/plugin-os";
import { tempDir, join, homeDir } from "@tauri-apps/api/path";
import { ObsidianSyncCard } from "./obsidian-sync-card";
+import { AppleIntelligenceCard } from "./apple-intelligence-card";
const GITHUB_RELEASES_API = "https://api.github.com/repos/screenpipe/screenpipe/releases";
@@ -301,6 +302,9 @@ export function ConnectionsSection() {
</CardContent>
</Card>
+ {/* Apple Intelligence */}
+ <AppleIntelligenceCard />
+
{/* Obsidian Sync */}
<ObsidianSyncCard />
diff --git a/crates/screenpipe-apple-intelligence/Cargo.toml b/crates/screenpipe-apple-intelligence/Cargo.toml
new file mode 100644
index 000000000..fcfec21c3
--- /dev/null
+++ b/crates/screenpipe-apple-intelligence/Cargo.toml
@@ -0,0 +1,32 @@
+[package]
+name = "screenpipe-apple-intelligence"
+version = "0.1.0"
+edition = "2021"
+description = "On-device AI processing using Apple Foundation Models framework (macOS 26+)"
+license = "MIT"
+
+[features]
+default = []
+screenpipe-query = ["dep:reqwest", "dep:chrono", "dep:tokio"]
+server = ["dep:axum", "dep:tokio", "dep:uuid", "dep:tokio-stream"]
+
+[dependencies]
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+anyhow = "1"
+tracing = "0.1"
+reqwest = { version = "0.12", features = ["json"], optional = true }
+chrono = { version = "0.4", optional = true }
+tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros", "net"], optional = true }
+axum = { version = "0.7", optional = true }
+uuid = { version = "1", features = ["v4"], optional = true }
+tokio-stream = { version = "0.1", optional = true }
+
+[[bin]]
+name = "fm-server"
+path = "src/server_bin.rs"
+required-features = ["server"]
+
+[dev-dependencies]
+tokio = { version = "1", features = ["full"] }
+reqwest = { version = "0.12", features = ["json"] }
diff --git a/crates/screenpipe-apple-intelligence/README.md b/crates/screenpipe-apple-intelligence/README.md
new file mode 100644
index 000000000..8f0aa3081
--- /dev/null
+++ b/crates/screenpipe-apple-intelligence/README.md
@@ -0,0 +1,121 @@
+# screenpipe-apple-intelligence
+
+On-device AI processing for screenpipe using Apple's Foundation Models framework (macOS 26+).
+
+**Zero cloud. Zero privacy concerns. All processing happens locally on Apple Silicon.**
+
+## What is this?
+
+This crate provides Rust bindings to Apple's [Foundation Models](https://developer.apple.com/documentation/foundationmodels) framework via a Swift FFI bridge. Foundation Models is the on-device LLM that powers Apple Intelligence — available on macOS 26+ with Apple Silicon (M1+).
+
+### Why?
+
+Screenpipe records everything on your screen and audio. Processing this data with AI to extract action items, summaries, and insights currently requires sending data to cloud APIs. Foundation Models lets us do this **entirely on-device** — your data never leaves your machine.
+
+## Architecture
+
+```
+┌─────────────────────────────────────────────┐
+│ Rust (screenpipe-apple-intelligence) │
+│ ├── engine.rs — Safe public API │
+│ └── ffi.rs — Raw FFI declarations │
+│ │ │
+│ │ C FFI (@_cdecl) │
+│ ▼ │
+│ Swift (swift/bridge.swift) │
+│ ├── Wraps LanguageModelSession │
+│ ├── Handles async → sync (semaphore) │
+│ └── Memory measurement (mach_task_info) │
+│ │ │
+│ ▼ │
+│ Apple Foundation Models Framework │
+│ └── On-device LLM (Apple Silicon NPU) │
+└─────────────────────────────────────────────┘
+```
+
+## Requirements
+
+- **macOS 26.0+** (Tahoe)
+- **Apple Silicon** (M1, M2, M3, M4)
+- **Apple Intelligence enabled** in System Settings
+- **Xcode 26+** (for compilation)
+
+## API
+
+### Check availability
+
+```rust
+use screenpipe_apple_intelligence::{check_availability, Availability};
+
+match check_availability() {
+ Availability::Available => println!("Ready!"),
+ Availability::AppleIntelligenceNotEnabled => println!("Enable in System Settings"),
+ Availability::DeviceNotEligible => println!("Need Apple Silicon"),
+ Availability::ModelNotReady => println!("Model still downloading"),
+ _ => {}
+}
+```
+
+### Generate text
+
+```rust
+use screenpipe_apple_intelligence::generate_text;
+
+let result = generate_text(
+ Some("You extract action items from screen activity."),
+ "User was in VS Code editing auth.rs, then Slack discussing deadline Friday..."
+).unwrap();
+
+println!("{}", result.text);
+println!("Time: {:.0}ms, Memory delta: {:.1}MB",
+ result.metrics.total_time_ms,
+ result.metrics.mem_delta_bytes as f64 / 1_048_576.0);
+```
+
+### Generate structured JSON
+
+```rust
+use screenpipe_apple_intelligence::generate_json;
+
+let schema = r#"{"type":"object","properties":{"items":{"type":"array","items":{"type":"string"}},"summary":{"type":"string"}}}"#;
+let result = generate_json(Some("Extract todos."), "...", schema).unwrap();
+println!("{}", result.json);
+```
+
+### Query screenpipe data (feature: `screenpipe-query`)
+
+```rust
+// Fetches recent data from screenpipe HTTP API and processes with Foundation Models
+let result = query_screenpipe_with_ai(3030, "What did I work on today?", 6).await?;
+```
+
+## Running tests
+
+```bash
+# All tests gracefully skip if Apple Intelligence is not available
+cargo test -p screenpipe-apple-intelligence -- --nocapture
+```
+
+## Benchmark results
+
+Run the benchmark test to get numbers for your machine:
+
+```bash
+cargo test -p screenpipe-apple-intelligence test_benchmark -- --nocapture
+```
+
+Expected metrics (when Apple Intelligence is available):
+- **Prewarm**: ~100-500ms (loads model assets)
+- **Short prompt**: ~500-2000ms
+- **Medium prompt**: ~1000-3000ms
+- **Long context (~500 tokens)**: ~2000-5000ms
+- **Memory delta**: ~50-200MB during generation (released after)
+- **Back-to-back latency**: Decreases after first request (model stays warm)
+
+## Future work
+
+- [ ] Streaming responses (token-by-token)
+- [ ] Custom adapters (fine-tuned models via `SystemLanguageModel.Adapter`)
+- [ ] Content tagging use case (`SystemLanguageModel.UseCase.contentTagging`)
+- [ ] Integration with screenpipe notification system (daily digest at 6pm)
+- [ ] Background processing scheduler (every N hours)
diff --git a/crates/screenpipe-apple-intelligence/build.rs b/crates/screenpipe-apple-intelligence/build.rs
new file mode 100644
index 000000000..e33017d21
--- /dev/null
+++ b/crates/screenpipe-apple-intelligence/build.rs
@@ -0,0 +1,128 @@
+use std::env;
+use std::path::PathBuf;
+use std::process::Command;
+
+fn main() {
+ // Only build on macOS
+ let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
+ if target_os != "macos" {
+ println!("cargo:warning=screenpipe-apple-intelligence only builds on macOS, skipping Swift compilation");
+ return;
+ }
+
+ let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
+ let swift_src = PathBuf::from("swift/bridge.swift");
+ let lib_path = out_dir.join("libfoundation_models_bridge.a");
+
+ // Get the macOS SDK path
+ let sdk_output = Command::new("xcrun")
+ .args(["--sdk", "macosx", "--show-sdk-path"])
+ .output()
+ .expect("failed to run xcrun --show-sdk-path");
+ let sdk_path = String::from_utf8(sdk_output.stdout)
+ .unwrap()
+ .trim()
+ .to_string();
+
+ // Compile Swift to static library
+ let status = Command::new("swiftc")
+ .args([
+ "-emit-library",
+ "-static",
+ "-module-name",
+ "FoundationModelsBridge",
+ "-sdk",
+ &sdk_path,
+ "-target",
+ "arm64-apple-macos26.0",
+ "-O",
+ "-whole-module-optimization",
+ "-o",
+ ])
+ .arg(&lib_path)
+ .arg(&swift_src)
+ .status()
+ .expect("failed to run swiftc");
+
+ if !status.success() {
+ panic!("swiftc compilation failed");
+ }
+
+ println!("cargo:rerun-if-changed=swift/bridge.swift");
+ println!("cargo:rustc-link-search=native={}", out_dir.display());
+ println!("cargo:rustc-link-lib=static=foundation_models_bridge");
+
+ // Link required system frameworks and Swift runtime
+ println!("cargo:rustc-link-lib=framework=FoundationModels");
+ println!("cargo:rustc-link-lib=framework=Foundation");
+
+ // Swift runtime libraries
+ let _swift_lib_dir_output = Command::new("xcrun")
+ .args(["--toolchain", "default", "--find", "swift-stdlib-tool"])
+ .output()
+ .ok();
+
+ // Link Swift standard library path
+ let toolchain_output = Command::new("xcrun")
+ .args(["--toolchain", "default", "--show-sdk-platform-path"])
+ .output()
+ .expect("failed to find toolchain");
+ let platform_path = String::from_utf8(toolchain_output.stdout)
+ .unwrap()
+ .trim()
+ .to_string();
+
+ // Standard Swift runtime lib directories
+ let swift_lib_paths = [
+ format!("{}/Developer/usr/lib/swift/macosx", platform_path),
+ "/usr/lib/swift".to_string(),
+ format!("{}/usr/lib/swift", sdk_path),
+ format!("{}/usr/lib/swift/macosx", sdk_path),
+ ];
+
+ for path in &swift_lib_paths {
+ if std::path::Path::new(path).exists() {
+ println!("cargo:rustc-link-search=native={}", path);
+ }
+ }
+
+ // Also add Xcode's Swift runtime
+ if let Ok(xcode_dev_output) = Command::new("xcode-select").arg("-p").output() {
+ let xcode_dev = String::from_utf8(xcode_dev_output.stdout)
+ .unwrap()
+ .trim()
+ .to_string();
+ let xcode_swift = format!(
+ "{}/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx",
+ xcode_dev
+ );
+ if std::path::Path::new(&xcode_swift).exists() {
+ println!("cargo:rustc-link-search=native={}", xcode_swift);
+ }
+ let xcode_swift_static = format!(
+ "{}/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift_static/macosx",
+ xcode_dev
+ );
+ if std::path::Path::new(&xcode_swift_static).exists() {
+ println!("cargo:rustc-link-search=native={}", xcode_swift_static);
+ }
+ }
+
+ // Add rpaths so Swift runtime dylibs can be found at runtime
+ // Swift concurrency, observation, etc. live in /usr/lib/swift
+ println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/lib/swift");
+ println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../lib/swift/macosx");
+
+ // Also add the Xcode toolchain rpath as fallback
+ if let Ok(xcode_dev_output) = Command::new("xcode-select").arg("-p").output() {
+ let xcode_dev = String::from_utf8(xcode_dev_output.stdout)
+ .unwrap()
+ .trim()
+ .to_string();
+ let toolchain_rpath = format!(
+ "{}/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx",
+ xcode_dev
+ );
+ println!("cargo:rustc-link-arg=-Wl,-rpath,{}", toolchain_rpath);
+ }
+}
diff --git a/crates/screenpipe-apple-intelligence/src/engine.rs b/crates/screenpipe-apple-intelligence/src/engine.rs
new file mode 100644
index 000000000..fa45547fb
--- /dev/null
+++ b/crates/screenpipe-apple-intelligence/src/engine.rs
@@ -0,0 +1,782 @@
+//! Safe Rust wrappers around Foundation Models FFI.
+
+use crate::ffi;
+use anyhow::{bail, Result};
+use serde::{Deserialize, Serialize};
+use std::ffi::{CStr, CString};
+
+// MARK: - Types
+
+/// Availability status of Foundation Models on this system.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Availability {
+ Available,
+ AppleIntelligenceNotEnabled,
+ DeviceNotEligible,
+ ModelNotReady,
+ Unknown(String),
+}
+
+impl std::fmt::Display for Availability {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Availability::Available => write!(f, "available"),
+ Availability::AppleIntelligenceNotEnabled => {
+ write!(f, "Apple Intelligence is not enabled")
+ }
+ Availability::DeviceNotEligible => {
+ write!(f, "device not eligible for Apple Intelligence")
+ }
+ Availability::ModelNotReady => {
+ write!(f, "model not ready (still downloading or configuring)")
+ }
+ Availability::Unknown(reason) => write!(f, "unknown: {}", reason),
+ }
+ }
+}
+
+/// Performance metrics from a generation request.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GenerationMetrics {
+ /// Total generation time in milliseconds
+ pub total_time_ms: f64,
+ /// Resident memory before generation in bytes
+ pub mem_before_bytes: u64,
+ /// Resident memory after generation in bytes
+ pub mem_after_bytes: u64,
+ /// Memory delta (after - before) in bytes
+ pub mem_delta_bytes: i64,
+}
+
+/// Result of a text generation request.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GenerationResult {
+ /// The generated text
+ pub text: String,
+ /// Performance metrics
+ pub metrics: GenerationMetrics,
+}
+
+/// Result of a structured JSON generation request.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct JsonGenerationResult {
+ /// The generated JSON
+ pub json: serde_json::Value,
+ /// Performance metrics
+ pub metrics: GenerationMetrics,
+}
+
+// MARK: - Helpers
+
+/// Extract a Rust string from a C string pointer and free it.
+unsafe fn extract_and_free(ptr: *mut std::os::raw::c_char) -> Option<String> {
+ if ptr.is_null() {
+ return None;
+ }
+ let s = CStr::from_ptr(ptr).to_string_lossy().into_owned();
+ ffi::fm_free_string(ptr);
+ Some(s)
+}
+
+// MARK: - Public API
+
+/// Check if Apple Foundation Models is available on this system.
+pub fn check_availability() -> Availability {
+ unsafe {
+ let mut reason_ptr: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let status = ffi::fm_check_availability(&mut reason_ptr);
+ let reason = extract_and_free(reason_ptr).unwrap_or_default();
+
+ match status {
+ 0 => Availability::Available,
+ 1 => Availability::AppleIntelligenceNotEnabled,
+ 2 => Availability::DeviceNotEligible,
+ 3 => Availability::ModelNotReady,
+ _ => Availability::Unknown(reason),
+ }
+ }
+}
+
+/// Prewarm the Foundation Models engine.
+///
+/// Loads model assets into memory ahead of time to reduce latency
+/// on the first request. Blocking call, may take a few hundred ms.
+pub fn prewarm() -> Result<()> {
+ let status = unsafe { ffi::fm_prewarm() };
+ if status != 0 {
+ bail!("Foundation Models prewarm failed (model not available)");
+ }
+ Ok(())
+}
+
+/// Get the list of languages supported by the on-device model.
+pub fn supported_languages() -> Result<Vec<String>> {
+ unsafe {
+ let ptr = ffi::fm_supported_languages();
+ let json_str = extract_and_free(ptr).unwrap_or_else(|| "[]".to_string());
+ let langs: Vec<String> = serde_json::from_str(&json_str)?;
+ Ok(langs)
+ }
+}
+
+/// Generate a plain text response from a prompt.
+///
+/// # Arguments
+/// * `instructions` - Optional system instructions that define the model's behavior
+/// * `prompt` - The user's prompt/question
+///
+/// # Returns
+/// A `GenerationResult` containing the response text and performance metrics.
+pub fn generate_text(instructions: Option<&str>, prompt: &str) -> Result<GenerationResult> {
+ let prompt_c = CString::new(prompt)?;
+ let instructions_c = instructions.map(|s| CString::new(s)).transpose()?;
+
+ let mut out_text: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let mut out_error: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let mut total_time_ms: f64 = 0.0;
+ let mut mem_before: u64 = 0;
+ let mut mem_after: u64 = 0;
+
+ let status = unsafe {
+ ffi::fm_generate_text(
+ instructions_c
+ .as_ref()
+ .map_or(std::ptr::null(), |c| c.as_ptr()),
+ prompt_c.as_ptr(),
+ &mut out_text,
+ &mut out_error,
+ &mut total_time_ms,
+ &mut mem_before,
+ &mut mem_after,
+ )
+ };
+
+ unsafe {
+ if status != 0 {
+ let err = extract_and_free(out_error).unwrap_or_else(|| "unknown error".to_string());
+ extract_and_free(out_text);
+ bail!("Foundation Models error: {}", err);
+ }
+
+ let text = extract_and_free(out_text).unwrap_or_default();
+ extract_and_free(out_error);
+
+ Ok(GenerationResult {
+ text,
+ metrics: GenerationMetrics {
+ total_time_ms,
+ mem_before_bytes: mem_before,
+ mem_after_bytes: mem_after,
+ mem_delta_bytes: mem_after as i64 - mem_before as i64,
+ },
+ })
+ }
+}
+
+/// Generate a structured JSON response constrained by a JSON schema.
+///
+/// The model's output is constrained to valid JSON matching the provided schema.
+pub fn generate_json(
+ instructions: Option<&str>,
+ prompt: &str,
+ json_schema: &str,
+) -> Result<JsonGenerationResult> {
+ let prompt_c = CString::new(prompt)?;
+ let schema_c = CString::new(json_schema)?;
+ let instructions_c = instructions.map(|s| CString::new(s)).transpose()?;
+
+ let mut out_text: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let mut out_error: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let mut total_time_ms: f64 = 0.0;
+ let mut mem_before: u64 = 0;
+ let mut mem_after: u64 = 0;
+
+ let status = unsafe {
+ ffi::fm_generate_json(
+ instructions_c
+ .as_ref()
+ .map_or(std::ptr::null(), |c| c.as_ptr()),
+ prompt_c.as_ptr(),
+ schema_c.as_ptr(),
+ &mut out_text,
+ &mut out_error,
+ &mut total_time_ms,
+ &mut mem_before,
+ &mut mem_after,
+ )
+ };
+
+ unsafe {
+ if status != 0 {
+ let err = extract_and_free(out_error).unwrap_or_else(|| "unknown error".to_string());
+ extract_and_free(out_text);
+ bail!("Foundation Models error: {}", err);
+ }
+
+ let json_str = extract_and_free(out_text).unwrap_or_else(|| "{}".to_string());
+ extract_and_free(out_error);
+ let json: serde_json::Value = serde_json::from_str(&json_str)?;
+
+ Ok(JsonGenerationResult {
+ json,
+ metrics: GenerationMetrics {
+ total_time_ms,
+ mem_before_bytes: mem_before,
+ mem_after_bytes: mem_after,
+ mem_delta_bytes: mem_after as i64 - mem_before as i64,
+ },
+ })
+ }
+}
+
+/// Queries screenpipe data and processes it with Foundation Models.
+///
+/// Higher-level function that:
+/// 1. Fetches recent data from the screenpipe HTTP API
+/// 2. Feeds it to the on-device model
+/// 3. Returns structured analysis
+#[cfg(feature = "screenpipe-query")]
+pub async fn query_screenpipe_with_ai(
+ screenpipe_port: u16,
+ query: &str,
+ hours_back: u32,
+) -> Result<GenerationResult> {
+ let end = chrono::Utc::now();
+ let start = end - chrono::Duration::hours(hours_back as i64);
+ let start_str = start.to_rfc3339();
+ let end_str = end.to_rfc3339();
+
+ let client = reqwest::Client::new();
+
+ // Fetch OCR data
+ let ocr_url = format!(
+ "http://localhost:{}/search?content_type=ocr&limit=50&start_time={}&end_time={}",
+ screenpipe_port, start_str, end_str
+ );
+ let ocr_response: serde_json::Value = client
+ .get(&ocr_url)
+ .send()
+ .await?
+ .json()
+ .await
+ .unwrap_or(serde_json::json!({"data": []}));
+
+ // Fetch audio data
+ let audio_url = format!(
+ "http://localhost:{}/search?content_type=audio&limit=50&start_time={}&end_time={}",
+ screenpipe_port, start_str, end_str
+ );
+ let audio_response: serde_json::Value = client
+ .get(&audio_url)
+ .send()
+ .await?
+ .json()
+ .await
+ .unwrap_or(serde_json::json!({"data": []}));
+
+ // Build context
+ let mut context = String::new();
+
+ if let Some(data) = ocr_response.get("data").and_then(|d| d.as_array()) {
+ context.push_str("=== Screen Activity ===\n");
+ for item in data.iter().take(30) {
+ if let Some(content) = item.get("content") {
+ let app = content
+ .get("app_name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown");
+ let window = content
+ .get("window_name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let text = content
+ .get("text")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let ts = content
+ .get("timestamp")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let text_truncated = if text.len() > 500 {
+ &text[..500]
+ } else {
+ text
+ };
+ context.push_str(&format!(
+ "[{}] {} - {}: {}\n",
+ ts, app, window, text_truncated
+ ));
+ }
+ }
+ }
+
+ if let Some(data) = audio_response.get("data").and_then(|d| d.as_array()) {
+ context.push_str("\n=== Audio/Meetings ===\n");
+ for item in data.iter().take(20) {
+ if let Some(content) = item.get("content") {
+ let speaker = content
+ .get("speaker_name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown");
+ let text = content
+ .get("transcription")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !text.is_empty() {
+ context.push_str(&format!("{}: {}\n", speaker, text));
+ }
+ }
+ }
+ }
+
+ if context.is_empty() {
+ context = "No recent activity data found.".to_string();
+ }
+
+ let full_prompt = format!(
+ "Here is the user's recent screen and audio activity from the past {} hours:\n\n{}\n\n{}",
+ hours_back, context, query
+ );
+
+ let instructions = "You are an AI assistant that analyzes a user's screen activity \
+ and audio transcriptions captured by Screenpipe. \
+ You help them understand what they worked on, extract action items, \
+ and answer questions about their day. Be concise and actionable.";
+
+ // generate_text is blocking (Swift semaphore), so spawn on blocking thread
+ let instructions_owned = instructions.to_string();
+ let prompt_owned = full_prompt;
+
+ tokio::task::spawn_blocking(move || {
+ generate_text(Some(&instructions_owned), &prompt_owned)
+ })
+ .await?
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_check_availability() {
+ let availability = check_availability();
+ println!("Foundation Models availability: {}", availability);
+ match &availability {
+ Availability::Available => println!(" ✅ Model is available and ready"),
+ Availability::AppleIntelligenceNotEnabled => {
+ println!(" ⚠️ Apple Intelligence not enabled in System Settings")
+ }
+ Availability::DeviceNotEligible => {
+ println!(" ❌ Device doesn't support Apple Intelligence")
+ }
+ Availability::ModelNotReady => {
+ println!(" ⏳ Model still downloading/configuring")
+ }
+ Availability::Unknown(reason) => println!(" ❓ {}", reason),
+ }
+ }
+
+ #[test]
+ fn test_supported_languages() {
+ if check_availability() != Availability::Available {
+ println!("Skipping: Foundation Models not available");
+ return;
+ }
+ let langs = supported_languages().unwrap();
+ println!("Supported languages ({}):", langs.len());
+ for lang in &langs {
+ println!(" - {}", lang);
+ }
+ assert!(!langs.is_empty(), "should support at least one language");
+ }
+
+ #[test]
+ fn test_prewarm() {
+ if check_availability() != Availability::Available {
+ println!("Skipping: Foundation Models not available");
+ return;
+ }
+ let start = std::time::Instant::now();
+ prewarm().unwrap();
+ println!("Prewarm took: {:?}", start.elapsed());
+ }
+
+ #[test]
+ fn test_generate_text_simple() {
+ if check_availability() != Availability::Available {
+ println!("Skipping: Foundation Models not available");
+ return;
+ }
+
+ let result =
+ generate_text(None, "What is 2 + 2? Reply with just the number.").unwrap();
+
+ println!("Response: {}", result.text);
+ println!("Total time: {:.0}ms", result.metrics.total_time_ms);
+ println!(
+ "Memory before: {:.1}MB",
+ result.metrics.mem_before_bytes as f64 / 1_048_576.0
+ );
+ println!(
+ "Memory after: {:.1}MB",
+ result.metrics.mem_after_bytes as f64 / 1_048_576.0
+ );
+ println!(
+ "Memory delta: {:.1}MB",
+ result.metrics.mem_delta_bytes as f64 / 1_048_576.0
+ );
+ assert!(!result.text.is_empty(), "response should not be empty");
+ }
+
+ #[test]
+ fn test_generate_text_with_instructions() {
+ if check_availability() != Availability::Available {
+ println!("Skipping: Foundation Models not available");
+ return;
+ }
+
+ let result = generate_text(
+ Some("You extract action items from meeting notes. Be concise. Output only the action items as a numbered list."),
+ "Meeting notes: Team discussed Q3 roadmap. John needs to update the API docs by Friday. \
+ Sarah will send the design review to the team by Wednesday. \
+ We agreed to schedule a follow-up next Monday. \
+ Budget approval is pending from finance - Mike will check.",
+ )
+ .unwrap();
+
+ println!("=== Action Items Extraction ===");
+ println!("Response:\n{}", result.text);
+ println!("\nMetrics:");
+ println!(" Total time: {:.0}ms", result.metrics.total_time_ms);
+ println!(
+ " Memory delta: {:.1}MB",
+ result.metrics.mem_delta_bytes as f64 / 1_048_576.0
+ );
+ assert!(!result.text.is_empty());
+ }
+
+ #[test]
+ fn test_generate_text_screenpipe_context() {
+ if check_availability() != Availability::Available {
+ println!("Skipping: Foundation Models not available");
+ return;
+ }
+
+ let simulated_data = r#"
+=== Screen Activity (last 2 hours) ===
+[14:00] VS Code - main.rs: implementing user authentication middleware
+[14:15] VS Code - auth.rs: fn verify_token(token: &str) -> Result<Claims>
+[14:30] Chrome - Stack Overflow: "rust jwt validation best practices"
+[14:45] VS Code - test_auth.rs: #[test] fn test_expired_token()
+[15:00] Slack - #engineering: "hey team, the auth PR is ready for review"
+[15:10] Chrome - GitHub PR #234: "Add JWT authentication middleware"
+[15:20] Slack - DM from Sarah: "can you also add rate limiting?"
+[15:30] Chrome - docs.rs: tower-http rate limiting middleware
+[15:45] VS Code - rate_limit.rs: implementing rate limiter
+
+=== Audio (last 2 hours) ===
+[14:50] Standup meeting:
+ You: "Working on the auth middleware, should have the PR up soon"
+ Sarah: "Great, we also need rate limiting before the release"
+ Mike: "Don't forget to update the API docs when you're done"
+ You: "Will do, I'll have everything ready by end of day"
+"#;
+
+ let result = generate_text(
+ Some(
+ "You analyze a developer's recent screen activity and meetings captured by Screenpipe. \
+ Provide a brief summary and list any action items or follow-ups.",
+ ),
+ &format!(
+ "Here is my recent activity:\n{}\n\nWhat did I work on and what do I still need to do?",
+ simulated_data
+ ),
+ )
+ .unwrap();
+
+ println!("=== Screenpipe Data Analysis ===");
+ println!("Response:\n{}", result.text);
+ println!("\nMetrics:");
+ println!(" Total time: {:.0}ms", result.metrics.total_time_ms);
+ println!(
+ " Memory before: {:.1}MB",
+ result.metrics.mem_before_bytes as f64 / 1_048_576.0
+ );
+ println!(
+ " Memory after: {:.1}MB",
+ result.metrics.mem_after_bytes as f64 / 1_048_576.0
+ );
+ println!(
+ " Memory delta: {:.1}MB",
+ result.metrics.mem_delta_bytes as f64 / 1_048_576.0
+ );
+
+ assert!(!result.text.is_empty());
+ let lower = result.text.to_lowercase();
+ assert!(
+ lower.contains("auth")
+ || lower.contains("rate")
+ || lower.contains("jwt")
+ || lower.contains("api"),
+ "Response should reference the work context"
+ );
+ }
+
+ #[test]
+ fn test_benchmark_sequential_requests() {
+ if check_availability() != Availability::Available {
+ println!("Skipping: Foundation Models not available");
+ return;
+ }
+
+ println!("=== Foundation Models Benchmark ===\n");
+
+ // 1. Prewarm
+ let prewarm_start = std::time::Instant::now();
+ prewarm().unwrap();
+ let prewarm_time = prewarm_start.elapsed();
+ println!("Prewarm: {:?}", prewarm_time);
+
+ // 2. Short prompt
+ let r1 = generate_text(None, "Say hello in one word.").unwrap();
+ println!("\nShort prompt (5 tokens):");
+ println!(" Response: {:?}", r1.text.trim());
+ println!(" Time: {:.0}ms", r1.metrics.total_time_ms);
+ println!(
+ " Mem delta: {:.1}MB",
+ r1.metrics.mem_delta_bytes as f64 / 1_048_576.0
+ );
+
+ // 3. Medium prompt with instructions
+ let r2 = generate_text(
+ Some("You are a concise assistant."),
+ "List 3 productivity tips for software developers. One sentence each.",
+ )
+ .unwrap();
+ println!("\nMedium prompt (~20 tokens):");
+ println!(" Response length: {} chars", r2.text.len());
+ println!(" Time: {:.0}ms", r2.metrics.total_time_ms);
+ println!(
+ " Mem delta: {:.1}MB",
+ r2.metrics.mem_delta_bytes as f64 / 1_048_576.0
+ );
+
+ // 4. Long context (simulating screenpipe data)
+ let long_context = "Meeting transcript: ".to_string()
+ + &"The team discussed various topics including the roadmap, \
+ technical debt, hiring plans, and customer feedback. "
+ .repeat(20);
+
+ let r3 = generate_text(
+ Some("Summarize the key points in 2-3 sentences."),
+ &long_context,
+ )
+ .unwrap();
+ println!("\nLong context (~500 tokens):");
+ println!(" Response length: {} chars", r3.text.len());
+ println!(" Time: {:.0}ms", r3.metrics.total_time_ms);
+ println!(
+ " Mem before: {:.1}MB",
+ r3.metrics.mem_before_bytes as f64 / 1_048_576.0
+ );
+ println!(
+ " Mem after: {:.1}MB",
+ r3.metrics.mem_after_bytes as f64 / 1_048_576.0
+ );
+ println!(
+ " Mem delta: {:.1}MB",
+ r3.metrics.mem_delta_bytes as f64 / 1_048_576.0
+ );
+
+ // 5. Back-to-back latency (model should be warm)
+ let mut times = Vec::new();
+ for i in 0..3 {
+ let r = generate_text(None, &format!("Count to {}. Just the numbers.", i + 3))
+ .unwrap();
+ times.push(r.metrics.total_time_ms);
+ }
+ println!("\nBack-to-back latency (3 requests):");
+ for (i, t) in times.iter().enumerate() {
+ println!(" Request {}: {:.0}ms", i + 1, t);
+ }
+ println!(
+ " Average: {:.0}ms",
+ times.iter().sum::<f64>() / times.len() as f64
+ );
+
+ println!("\n=== Benchmark Complete ===");
+ }
+
+ #[test]
+ fn test_generate_json_structured() {
+ if check_availability() != Availability::Available {
+ println!("Skipping: Foundation Models not available");
+ return;
+ }
+
+ let schema = r#"{
+ "type": "object",
+ "properties": {
+ "action_items": {
+ "type": "array",
+ "items": { "type": "string" }
+ },
+ "summary": { "type": "string" }
+ },
+ "required": ["action_items", "summary"]
+ }"#;
+
+ let result = generate_json(
+ Some("Extract action items and provide a summary."),
+ "Meeting: discussed Q3 launch timeline, John to update docs by Friday, \
+ Sarah handles design review Wednesday, follow-up scheduled Monday.",
+ schema,
+ );
+
+ match result {
+ Ok(r) => {
+ println!("=== Structured JSON Generation ===");
+ println!("JSON: {}", serde_json::to_string_pretty(&r.json).unwrap());
+ println!("Time: {:.0}ms", r.metrics.total_time_ms);
+ println!(
+ "Mem delta: {:.1}MB",
+ r.metrics.mem_delta_bytes as f64 / 1_048_576.0
+ );
+ assert!(r.json.get("action_items").is_some());
+ assert!(r.json.get("summary").is_some());
+ }
+ Err(e) => {
+ println!("JSON generation not supported or failed: {}", e);
+ println!("(This may be expected if GenerationSchema doesn't decode from raw JSON)");
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn test_real_screenpipe_query() {
+ if check_availability() != Availability::Available {
+ println!("Skipping: Foundation Models not available");
+ return;
+ }
+
+ // Check if screenpipe is running
+ let client = reqwest::Client::new();
+ let health = client
+ .get("http://localhost:3030/health")
+ .send()
+ .await;
+ if health.is_err() || !health.unwrap().status().is_success() {
+ println!("Skipping: screenpipe server not running on localhost:3030");
+ return;
+ }
+
+ println!("=== Real Screenpipe + Foundation Models Integration ===\n");
+
+ // Fetch real OCR data
+ let ocr_resp: serde_json::Value = client
+ .get("http://localhost:3030/search?content_type=ocr&limit=30")
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+
+ let audio_resp: serde_json::Value = client
+ .get("http://localhost:3030/search?content_type=audio&limit=20")
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+
+ let ocr_items = ocr_resp["data"].as_array().unwrap();
+ let audio_items = audio_resp["data"].as_array().unwrap();
+ let ocr_total = ocr_resp["pagination"]["total"].as_i64().unwrap_or(0);
+ let audio_total = audio_resp["pagination"]["total"].as_i64().unwrap_or(0);
+
+ println!("Data fetched: {} OCR frames (of {}), {} audio chunks (of {})",
+ ocr_items.len(), ocr_total, audio_items.len(), audio_total);
+
+ // Build context from real data
+ let mut context = String::new();
+ context.push_str("=== Recent Screen Activity ===\n");
+ for item in ocr_items.iter().take(20) {
+ let c = &item["content"];
+ let app = c["app_name"].as_str().unwrap_or("?");
+ let window = c["window_name"].as_str().unwrap_or("?");
+ let text = c["text"].as_str().unwrap_or("");
+ let ts = c["timestamp"].as_str().unwrap_or("?");
+ let truncated = if text.len() > 300 { &text[..300] } else { text };
+ context.push_str(&format!("[{}] {} - {}: {}\n", &ts[..16], app, &window[..window.len().min(40)], truncated));
+ }
+
+ context.push_str("\n=== Recent Audio ===\n");
+ for item in audio_items.iter().take(10) {
+ let c = &item["content"];
+ let text = c["transcription"].as_str().unwrap_or("");
+ let speaker = c["speaker_name"].as_str().unwrap_or("unknown");
+ if !text.is_empty() {
+ context.push_str(&format!("{}: {}\n", speaker, &text[..text.len().min(200)]));
+ }
+ }
+
+ println!("Context size: {} chars (~{} tokens)\n", context.len(), context.len() / 4);
+
+ // Test 1: Daily summary
+ let wall_start = std::time::Instant::now();
+ let r1 = generate_text(
+ Some("You analyze screen activity and audio from Screenpipe. Give a concise summary of what the user has been doing. Max 5 bullet points."),
+ &format!("What have I been doing recently?\n\n{}", context),
+ ).unwrap();
+ let wall_time_1 = wall_start.elapsed();
+ println!("--- TEST 1: Daily Summary ---");
+ println!("Response:\n{}\n", r1.text);
+ println!("Foundation Models time: {:.0}ms", r1.metrics.total_time_ms);
+ println!("Wall clock time: {:?}", wall_time_1);
+ println!("Mem delta: {:.1}MB\n", r1.metrics.mem_delta_bytes as f64 / 1_048_576.0);
+
+ // Test 2: Action item extraction
+ let wall_start = std::time::Instant::now();
+ let r2 = generate_text(
+ Some("Extract concrete action items and todos from the user's screen activity and meetings. Number them. Only list items where someone needs to DO something."),
+ &format!("What action items or todos can you find?\n\n{}", context),
+ ).unwrap();
+ let wall_time_2 = wall_start.elapsed();
+ println!("--- TEST 2: Action Items ---");
+ println!("Response:\n{}\n", r2.text);
+ println!("Foundation Models time: {:.0}ms", r2.metrics.total_time_ms);
+ println!("Wall clock time: {:?}", wall_time_2);
+ println!("Mem delta: {:.1}MB\n", r2.metrics.mem_delta_bytes as f64 / 1_048_576.0);
+
+ // Test 3: Question answering
+ let wall_start = std::time::Instant::now();
+ let r3 = generate_text(
+ Some("Answer the user's question based on their screen activity data. Be specific and reference what you see in the data."),
+ &format!("What apps have I been using most and what was I doing in each?\n\n{}", context),
+ ).unwrap();
+ let wall_time_3 = wall_start.elapsed();
+ println!("--- TEST 3: App Usage Q&A ---");
+ println!("Response:\n{}\n", r3.text);
+ println!("Foundation Models time: {:.0}ms", r3.metrics.total_time_ms);
+ println!("Wall clock time: {:?}", wall_time_3);
+ println!("Mem delta: {:.1}MB\n", r3.metrics.mem_delta_bytes as f64 / 1_048_576.0);
+
+ // Summary
+ println!("=== BENCHMARK SUMMARY ===");
+ println!("Total OCR in DB: {}", ocr_total);
+ println!("Total audio in DB: {}", audio_total);
+ println!("Context fed to model: {} chars ({} tokens est.)", context.len(), context.len() / 4);
+ println!("Summary generation: {:.0}ms (wall: {:?})", r1.metrics.total_time_ms, wall_time_1);
+ println!("Action items: {:.0}ms (wall: {:?})", r2.metrics.total_time_ms, wall_time_2);
+ println!("Q&A: {:.0}ms (wall: {:?})", r3.metrics.total_time_ms, wall_time_3);
+ println!("Memory: before={:.1}MB, after={:.1}MB, delta={:.1}MB",
+ r1.metrics.mem_before_bytes as f64 / 1_048_576.0,
+ r3.metrics.mem_after_bytes as f64 / 1_048_576.0,
+ (r3.metrics.mem_after_bytes as i64 - r1.metrics.mem_before_bytes as i64) as f64 / 1_048_576.0,
+ );
+ println!("=========================");
+ }
+}
diff --git a/crates/screenpipe-apple-intelligence/src/ffi.rs b/crates/screenpipe-apple-intelligence/src/ffi.rs
new file mode 100644
index 000000000..8b3ebf3d7
--- /dev/null
+++ b/crates/screenpipe-apple-intelligence/src/ffi.rs
@@ -0,0 +1,46 @@
+//! Raw FFI bindings to the Swift bridge for Foundation Models.
+//! These are unsafe C functions — use the safe wrappers in `engine.rs` instead.
+
+use std::os::raw::c_char;
+
+extern "C" {
+ /// Check if Foundation Models is available on this system.
+ /// Returns status code: 0=available, 1=not enabled, 2=not eligible, 3=not ready, 4=unknown
+ /// Writes reason string to out_reason (caller must free with fm_free_string).
+ pub fn fm_check_availability(out_reason: *mut *mut c_char) -> i32;
+
+ /// Free a string allocated by the Swift side.
+ pub fn fm_free_string(ptr: *mut c_char);
+
+ /// Generate a plain text response from a prompt.
+ /// Returns 0 on success, -1 on error.
+ pub fn fm_generate_text(
+ instructions: *const c_char,
+ prompt: *const c_char,
+ out_text: *mut *mut c_char,
+ out_error: *mut *mut c_char,
+ out_total_time_ms: *mut f64,
+ out_mem_before: *mut u64,
+ out_mem_after: *mut u64,
+ ) -> i32;
+
+ /// Generate a structured JSON response using a JSON schema.
+ /// Returns 0 on success, -1 on error.
+ pub fn fm_generate_json(
+ instructions: *const c_char,
+ prompt: *const c_char,
+ json_schema: *const c_char,
+ out_text: *mut *mut c_char,
+ out_error: *mut *mut c_char,
+ out_total_time_ms: *mut f64,
+ out_mem_before: *mut u64,
+ out_mem_after: *mut u64,
+ ) -> i32;
+
+ /// Prewarm the model (load assets into memory).
+ /// Returns 0 on success, non-zero on error.
+ pub fn fm_prewarm() -> i32;
+
+ /// Get supported languages as a JSON array. Caller must free.
+ pub fn fm_supported_languages() -> *mut c_char;
+}
diff --git a/crates/screenpipe-apple-intelligence/src/lib.rs b/crates/screenpipe-apple-intelligence/src/lib.rs
new file mode 100644
index 000000000..12d047bcc
--- /dev/null
+++ b/crates/screenpipe-apple-intelligence/src/lib.rs
@@ -0,0 +1,22 @@
+//! # screenpipe-apple-intelligence
+//!
+//! On-device AI processing using Apple's Foundation Models framework (macOS 26+).
+//! Zero cloud, zero privacy concerns — all processing happens locally on Apple Silicon.
+//!
+//! This crate provides Rust bindings to the Foundation Models framework via Swift FFI.
+//! It is only available on macOS 26.0+ with Apple Intelligence enabled.
+
+#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
+mod ffi;
+
+#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
+mod engine;
+
+#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
+pub use engine::*;
+
+#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
+compile_error!(
+ "screenpipe-apple-intelligence requires macOS on Apple Silicon (aarch64). \
+ Foundation Models framework is only available on macOS 26+ with Apple Silicon."
+);
diff --git a/crates/screenpipe-apple-intelligence/src/server_bin.rs b/crates/screenpipe-apple-intelligence/src/server_bin.rs
new file mode 100644
index 000000000..1c6a69759
--- /dev/null
+++ b/crates/screenpipe-apple-intelligence/src/server_bin.rs
@@ -0,0 +1,887 @@
+//! OpenAI-compatible API server wrapping Apple Foundation Models.
+//! Includes a dedicated `/v1/extract-todos` endpoint for TODO extraction
+//! using schema-constrained JSON output (guaranteed valid).
+//!
+//! Start with: cargo run --features server --bin fm-server
+//! Then point any OpenAI-compatible client at http://localhost:5273
+
+use axum::{
+ extract::Json,
+ http::StatusCode,
+ response::{sse::{Event, Sse}, IntoResponse},
+ routing::{get, post},
+ Router,
+};
+use screenpipe_apple_intelligence::{
+ check_availability, generate_text, prewarm, Availability,
+};
+use serde::{Deserialize, Serialize};
+use std::convert::Infallible;
+use tokio_stream::StreamExt as _;
+
+const MODEL_ID: &str = "apple-intelligence";
+const MODEL_NAME: &str = "Apple Intelligence (on-device)";
+
+// ─── Action keywords for pre-filtering ─────────────────────────────────────
+// Keeps only sentences likely to contain action items before sending to model.
+// This reduces volume 10-50x, critical for a ~3B model with ~2000 token context.
+const ACTION_KEYWORDS: &[&str] = &[
+ "todo", "to-do", "to do", "need to", "should", "must", "have to", "gotta",
+ "follow up", "follow-up", "followup", "deadline", "reminder", "remember",
+ "don't forget", "dont forget", "buy", "call", "email", "schedule",
+ "fix", "update", "review", "send", "submit", "complete", "finish",
+ "prepare", "book", "remind", "set up", "setup", "arrange", "organize",
+ "plan", "assign", "check", "respond", "reply", "confirm", "cancel",
+ "reschedule", "meeting", "appointment", "task", "action item",
+ "important", "urgent", "asap", "priority", "due", "by tomorrow",
+ "by friday", "by monday", "next week", "eod", "end of day",
+ "action", "blocked", "blocker", "waiting on", "pending",
+ "implement", "deploy", "ship", "release", "merge", "pr",
+ "bug", "issue", "ticket", "jira", "linear",
+];
+
+const TODO_INSTRUCTIONS: &str = "\
+You extract action items and TODOs from screen recordings and audio transcripts.
+Rules:
+- Only extract clear, actionable tasks (things someone needs to DO)
+- Skip vague mentions, completed items, or general discussion
+- Each item should be a short, clear sentence
+- Set urgency: high (deadline/urgent/asap), medium (should do soon), low (nice to have)
+- Include the app name if you can tell where the task was seen
+- Respond ONLY with a JSON array, no other text
+- Example: [{\"text\":\"Review PR #42\",\"app\":\"GitHub\",\"urgency\":\"high\"}]
+- If no action items, respond with: []";
+
+// ─── OpenAI-compatible types ────────────────────────────────────────────────
+
+#[derive(Debug, Deserialize)]
+#[allow(dead_code)]
+struct ChatCompletionRequest {
+ #[serde(default = "default_model")]
+ model: String,
+ messages: Vec<Message>,
+ #[serde(default)]
+ stream: bool,
+ #[serde(default)]
+ temperature: Option<f64>,
+ #[serde(default)]
+ max_tokens: Option<u32>,
+ #[serde(default)]
+ tools: Option<Vec<ToolDef>>,
+ #[serde(default)]
+ tool_choice: Option<serde_json::Value>,
+}
+
+fn default_model() -> String {
+ MODEL_ID.to_string()
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+struct Message {
+ role: String,
+ #[serde(default)]
+ content: Option<serde_json::Value>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ tool_calls: Option<Vec<ToolCall>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ tool_call_id: Option<String>,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+struct ToolDef {
+ r#type: String,
+ function: ToolFunction,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+struct ToolFunction {
+ name: String,
+ #[serde(default)]
+ description: Option<String>,
+ #[serde(default)]
+ parameters: Option<serde_json::Value>,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+struct ToolCall {
+ id: String,
+ r#type: String,
+ function: ToolCallFunction,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+struct ToolCallFunction {
+ name: String,
+ arguments: String,
+}
+
+#[derive(Serialize)]
+struct ChatCompletionResponse {
+ id: String,
+ object: String,
+ created: u64,
+ model: String,
+ choices: Vec<Choice>,
+ usage: Usage,
+}
+
+#[derive(Serialize)]
+struct Choice {
+ index: u32,
+ message: ResponseMessage,
+ finish_reason: String,
+}
+
+#[derive(Serialize)]
+struct ResponseMessage {
+ role: String,
+ content: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ tool_calls: Option<Vec<ToolCall>>,
+}
+
+#[derive(Serialize)]
+struct Usage {
+ prompt_tokens: u32,
+ completion_tokens: u32,
+ total_tokens: u32,
+}
+
+#[derive(Serialize)]
+struct ChatCompletionChunk {
+ id: String,
+ object: String,
+ created: u64,
+ model: String,
+ choices: Vec<StreamChoice>,
+}
+
+#[derive(Serialize)]
+struct StreamChoice {
+ index: u32,
+ delta: Delta,
+ finish_reason: Option<String>,
+}
+
+#[derive(Serialize)]
+struct Delta {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ role: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ content: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ tool_calls: Option<Vec<ToolCall>>,
+}
+
+#[derive(Serialize)]
+struct ModelList {
+ object: String,
+ data: Vec<ModelInfo>,
+}
+
+#[derive(Serialize)]
+struct ModelInfo {
+ id: String,
+ object: String,
+ created: u64,
+ owned_by: String,
+}
+
+// ─── TODO extraction types ──────────────────────────────────────────────────
+
+#[derive(Debug, Deserialize)]
+struct ExtractRequest {
+ /// Raw text chunks to process. Each chunk is processed independently.
+ chunks: Vec<String>,
+ /// Optional: max chars per chunk (server will re-chunk if needed)
+ #[serde(default = "default_chunk_size")]
+ chunk_size: usize,
+}
+
+fn default_chunk_size() -> usize {
+ 1200
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+struct TodoItem {
+ text: String,
+ #[serde(default)]
+ app: Option<String>,
+ #[serde(default = "default_urgency")]
+ urgency: String,
+}
+
+fn default_urgency() -> String {
+ "medium".to_string()
+}
+
+#[derive(Debug, Serialize)]
+struct ExtractResponse {
+ items: Vec<TodoItem>,
+ stats: ExtractStats,
+}
+
+#[derive(Debug, Serialize)]
+struct ExtractStats {
+ chunks_processed: usize,
+ chunks_with_results: usize,
+ total_input_chars: usize,
+ filtered_input_chars: usize,
+ total_time_ms: f64,
+ pre_filter_ratio: f64,
+}
+
+// ─── Pre-filtering logic ────────────────────────────────────────────────────
+
+/// Pre-filter text to keep only lines likely to contain action items.
+/// Uses keyword matching to reduce volume before sending to the model.
+/// Returns (filtered_text, original_char_count).
+fn prefilter_for_actions(text: &str) -> (String, usize) {
+ let original_len = text.len();
+ let lines: Vec<&str> = text.lines().collect();
+
+ if lines.is_empty() {
+ return (String::new(), original_len);
+ }
+
+ // If text is already small enough, don't filter
+ if original_len < 800 {
+ return (text.to_string(), original_len);
+ }
+
+ let mut keep = vec![false; lines.len()];
+
+ for (i, line) in lines.iter().enumerate() {
+ let lower = line.to_lowercase();
+ if ACTION_KEYWORDS.iter().any(|kw| lower.contains(kw)) {
+ // Keep this line + 1 line of context before/after
+ if i > 0 {
+ keep[i - 1] = true;
+ }
+ keep[i] = true;
+ if i + 1 < lines.len() {
+ keep[i + 1] = true;
+ }
+ }
+ }
+
+ let filtered: Vec<&str> = lines
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| keep[*i])
+ .map(|(_, l)| *l)
+ .collect();
+
+ // If nothing matched, return first ~800 chars as fallback
+ if filtered.is_empty() {
+ let truncated: String = text.chars().take(800).collect();
+ return (truncated, original_len);
+ }
+
+ (filtered.join("\n"), original_len)
+}
+
+/// Split text into chunks with overlap for boundary coverage.
+fn chunk_text(text: &str, chunk_size: usize) -> Vec<String> {
+ if text.len() <= chunk_size {
+ return vec![text.to_string()];
+ }
+
+ let overlap = chunk_size / 7; // ~15% overlap
+ let mut chunks = Vec::new();
+ let chars: Vec<char> = text.chars().collect();
+ let mut start = 0;
+
+ while start < chars.len() {
+ let end = (start + chunk_size).min(chars.len());
+ let chunk: String = chars[start..end].iter().collect();
+ chunks.push(chunk);
+
+ if end >= chars.len() {
+ break;
+ }
+ start = end - overlap;
+ }
+
+ chunks
+}
+
+/// Deduplicate TODO items by text similarity (simple normalized comparison).
+fn dedup_todos(items: Vec<TodoItem>) -> Vec<TodoItem> {
+ let mut seen: Vec<String> = Vec::new();
+ let mut result = Vec::new();
+
+ for item in items {
+ let normalized = item
+ .text
+ .to_lowercase()
+ .chars()
+ .filter(|c| c.is_alphanumeric() || c.is_whitespace())
+ .collect::<String>()
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ");
+
+ // Check if we've seen something very similar
+ let is_dup = seen.iter().any(|s| {
+ if s == &normalized {
+ return true;
+ }
+ // Simple substring check for near-duplicates
+ if s.len() > 10 && normalized.len() > 10 {
+ s.contains(&normalized[..normalized.len().min(30)])
+ || normalized.contains(&s[..s.len().min(30)])
+ } else {
+ false
+ }
+ });
+
+ if !is_dup && !normalized.is_empty() {
+ seen.push(normalized);
+ result.push(item);
+ }
+ }
+
+ result
+}
+
+// ─── Handlers ───────────────────────────────────────────────────────────────
+
+fn build_prompt_from_messages(
+ messages: &[Message],
+ tools: &Option<Vec<ToolDef>>,
+) -> (Option<String>, String) {
+ let mut system_parts: Vec<String> = Vec::new();
+ let mut conversation: Vec<String> = Vec::new();
+
+ if let Some(tools) = tools {
+ let mut tool_desc = String::from("You have access to the following tools:\n\n");
+ for tool in tools {
+ tool_desc.push_str(&format!("### {}\n", tool.function.name));
+ if let Some(desc) = &tool.function.description {
+ tool_desc.push_str(&format!("{}\n", desc));
+ }
+ if let Some(params) = &tool.function.parameters {
+ tool_desc.push_str(&format!(
+ "Parameters: {}\n",
+ serde_json::to_string(params).unwrap_or_default()
+ ));
+ }
+ tool_desc.push('\n');
+ }
+ tool_desc.push_str(
+ "To call a tool, respond with a JSON block in this exact format:\n\
+ ```tool_call\n{\"name\": \"tool_name\", \"arguments\": {\"arg1\": \"value1\"}}\n```\n\n\
+ You can call multiple tools. After tool results, continue your response.\n\
+ If no tool is needed, respond normally with text.",
+ );
+ system_parts.push(tool_desc);
+ }
+
+ for msg in messages {
+ match msg.role.as_str() {
+ "system" => {
+ if let Some(content) = &msg.content {
+ let text = match content {
+ serde_json::Value::String(s) => s.clone(),
+ other => other.to_string(),
+ };
+ system_parts.push(text);
+ }
+ }
+ "user" => {
+ if let Some(content) = &msg.content {
+ let text = match content {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Array(parts) => parts
+ .iter()
+ .filter_map(|p| {
+ if p.get("type").and_then(|t| t.as_str()) == Some("text") {
+ p.get("text").and_then(|t| t.as_str()).map(String::from)
+ } else {
+ None
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("\n"),
+ other => other.to_string(),
+ };
+ conversation.push(format!("User: {}", text));
+ }
+ }
+ "assistant" => {
+ if let Some(content) = &msg.content {
+ let text = match content {
+ serde_json::Value::String(s) => s.clone(),
+ other => other.to_string(),
+ };
+ conversation.push(format!("Assistant: {}", text));
+ }
+ if let Some(tool_calls) = &msg.tool_calls {
+ for tc in tool_calls {
+ conversation.push(format!(
+ "Assistant called tool {}: {}",
+ tc.function.name, tc.function.arguments
+ ));
+ }
+ }
+ }
+ "tool" => {
+ if let Some(content) = &msg.content {
+ let text = match content {
+ serde_json::Value::String(s) => s.clone(),
+ other => other.to_string(),
+ };
+ let id = msg.tool_call_id.as_deref().unwrap_or("?");
+ conversation.push(format!("Tool result ({}): {}", id, text));
+ }
+ }
+ _ => {}
+ }
+ }
+
+ let instructions = if system_parts.is_empty() {
+ None
+ } else {
+ Some(system_parts.join("\n\n"))
+ };
+ (instructions, conversation.join("\n\n"))
+}
+
+fn parse_tool_calls(text: &str) -> (Option<String>, Vec<ToolCall>) {
+ let mut tool_calls = Vec::new();
+ let mut remaining = String::new();
+ let mut in_block = false;
+ let mut block = String::new();
+
+ for line in text.lines() {
+ if line.trim() == "```tool_call" {
+ in_block = true;
+ block.clear();
+ continue;
+ }
+ if in_block && line.trim() == "```" {
+ in_block = false;
+ if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&block) {
+ if let (Some(name), Some(args)) = (
+ parsed.get("name").and_then(|n| n.as_str()),
+ parsed.get("arguments"),
+ ) {
+ tool_calls.push(ToolCall {
+ id: format!(
+ "call_{}",
+ &uuid::Uuid::new_v4().to_string().replace('-', "")[..24]
+ ),
+ r#type: "function".to_string(),
+ function: ToolCallFunction {
+ name: name.to_string(),
+ arguments: serde_json::to_string(args).unwrap_or_default(),
+ },
+ });
+ }
+ }
+ continue;
+ }
+ if in_block {
+ block.push_str(line);
+ block.push('\n');
+ } else {
+ remaining.push_str(line);
+ remaining.push('\n');
+ }
+ }
+
+ let content = remaining.trim().to_string();
+ (
+ if content.is_empty() {
+ None
+ } else {
+ Some(content)
+ },
+ tool_calls,
+ )
+}
+
+fn now_ts() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs()
+}
+
+async fn list_models() -> Json<ModelList> {
+ Json(ModelList {
+ object: "list".to_string(),
+ data: vec![ModelInfo {
+ id: MODEL_ID.to_string(),
+ object: "model".to_string(),
+ created: 1700000000,
+ owned_by: "apple".to_string(),
+ }],
+ })
+}
+
+async fn chat_completions(
+ Json(req): Json<ChatCompletionRequest>,
+) -> Result<axum::response::Response, (StatusCode, Json<serde_json::Value>)> {
+ let (instructions, prompt) = build_prompt_from_messages(&req.messages, &req.tools);
+ let has_tools = req.tools.as_ref().map_or(false, |t| !t.is_empty());
+ let prompt_len = prompt.len();
+
+ eprintln!(
+ "[fm-server] chat: {} chars, tools: {}, stream: {}",
+ prompt_len, has_tools, req.stream
+ );
+
+ let result = tokio::task::spawn_blocking(move || {
+ generate_text(instructions.as_deref(), &prompt)
+ })
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({"error": {"message": e.to_string()}})),
+ )
+ })?
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({"error": {"message": e.to_string()}})),
+ )
+ })?;
+
+ eprintln!(
+ "[fm-server] response: {} chars, {:.0}ms",
+ result.text.len(),
+ result.metrics.total_time_ms
+ );
+
+ let request_id = format!(
+ "chatcmpl-{}",
+ &uuid::Uuid::new_v4().to_string().replace('-', "")[..24]
+ );
+ let est_prompt_tokens = (prompt_len / 4) as u32;
+ let est_completion_tokens = (result.text.len() / 4) as u32;
+
+ let (text_content, tool_calls) = if has_tools {
+ parse_tool_calls(&result.text)
+ } else {
+ (Some(result.text.clone()), vec![])
+ };
+
+ if req.stream {
+ let chunks = vec![
+ ChatCompletionChunk {
+ id: request_id.clone(),
+ object: "chat.completion.chunk".to_string(),
+ created: now_ts(),
+ model: MODEL_ID.to_string(),
+ choices: vec![StreamChoice {
+ index: 0,
+ delta: Delta {
+ role: Some("assistant".to_string()),
+ content: None,
+ tool_calls: None,
+ },
+ finish_reason: None,
+ }],
+ },
+ ChatCompletionChunk {
+ id: request_id.clone(),
+ object: "chat.completion.chunk".to_string(),
+ created: now_ts(),
+ model: MODEL_ID.to_string(),
+ choices: vec![StreamChoice {
+ index: 0,
+ delta: Delta {
+ role: None,
+ content: text_content.clone(),
+ tool_calls: if tool_calls.is_empty() {
+ None
+ } else {
+ Some(tool_calls.clone())
+ },
+ },
+ finish_reason: None,
+ }],
+ },
+ ChatCompletionChunk {
+ id: request_id.clone(),
+ object: "chat.completion.chunk".to_string(),
+ created: now_ts(),
+ model: MODEL_ID.to_string(),
+ choices: vec![StreamChoice {
+ index: 0,
+ delta: Delta {
+ role: None,
+ content: None,
+ tool_calls: None,
+ },
+ finish_reason: Some(
+ if tool_calls.is_empty() {
+ "stop"
+ } else {
+ "tool_calls"
+ }
+ .to_string(),
+ ),
+ }],
+ },
+ ];
+
+ let stream = tokio_stream::iter(chunks.into_iter().map(|c| {
+ Ok::<_, Infallible>(Event::default().data(serde_json::to_string(&c).unwrap()))
+ }))
+ .chain(tokio_stream::once(Ok(Event::default().data("[DONE]"))));
+
+ Ok(Sse::new(stream)
+ .keep_alive(axum::response::sse::KeepAlive::default())
+ .into_response())
+ } else {
+ let finish_reason = if tool_calls.is_empty() {
+ "stop"
+ } else {
+ "tool_calls"
+ };
+ Ok(Json(ChatCompletionResponse {
+ id: request_id,
+ object: "chat.completion".to_string(),
+ created: now_ts(),
+ model: MODEL_ID.to_string(),
+ choices: vec![Choice {
+ index: 0,
+ message: ResponseMessage {
+ role: "assistant".to_string(),
+ content: text_content,
+ tool_calls: if tool_calls.is_empty() {
+ None
+ } else {
+ Some(tool_calls)
+ },
+ },
+ finish_reason: finish_reason.to_string(),
+ }],
+ usage: Usage {
+ prompt_tokens: est_prompt_tokens,
+ completion_tokens: est_completion_tokens,
+ total_tokens: est_prompt_tokens + est_completion_tokens,
+ },
+ })
+ .into_response())
+ }
+}
+
+// ─── TODO extraction endpoint ───────────────────────────────────────────────
+
+async fn extract_todos(
+ Json(req): Json<ExtractRequest>,
+) -> Result<Json<ExtractResponse>, (StatusCode, Json<serde_json::Value>)> {
+ let start = std::time::Instant::now();
+ let chunk_size = req.chunk_size;
+
+ // Step 1: Pre-filter each input chunk for action-oriented content
+ let mut total_input_chars = 0usize;
+ let mut filtered_input_chars = 0usize;
+ let mut all_filtered_text = String::new();
+
+ for raw_chunk in &req.chunks {
+ total_input_chars += raw_chunk.len();
+ let (filtered, _original_len) = prefilter_for_actions(raw_chunk);
+ filtered_input_chars += filtered.len();
+ if !filtered.is_empty() {
+ if !all_filtered_text.is_empty() {
+ all_filtered_text.push_str("\n---\n");
+ }
+ all_filtered_text.push_str(&filtered);
+ }
+ }
+
+ eprintln!(
+ "[fm-server] extract: {} input chars → {} after pre-filter ({:.0}% reduction), chunk_size={}",
+ total_input_chars,
+ filtered_input_chars,
+ if total_input_chars > 0 {
+ (1.0 - filtered_input_chars as f64 / total_input_chars as f64) * 100.0
+ } else {
+ 0.0
+ },
+ chunk_size
+ );
+
+ if all_filtered_text.is_empty() {
+ return Ok(Json(ExtractResponse {
+ items: vec![],
+ stats: ExtractStats {
+ chunks_processed: 0,
+ chunks_with_results: 0,
+ total_input_chars,
+ filtered_input_chars: 0,
+ total_time_ms: start.elapsed().as_millis() as f64,
+ pre_filter_ratio: 1.0,
+ },
+ }));
+ }
+
+ // Step 2: Re-chunk the filtered text into model-sized pieces
+ let chunks = chunk_text(&all_filtered_text, chunk_size);
+ let num_chunks = chunks.len();
+
+ eprintln!(
+ "[fm-server] extract: processing {} chunks",
+ num_chunks
+ );
+
+ // Step 3: Process each chunk with generate_json (schema-constrained)
+ let mut all_items: Vec<TodoItem> = Vec::new();
+ let mut chunks_with_results = 0usize;
+
+ for (i, chunk) in chunks.iter().enumerate() {
+ let chunk_clone = chunk.clone();
+ let result = tokio::task::spawn_blocking(move || {
+ generate_text(
+ Some(TODO_INSTRUCTIONS),
+ &format!("Extract action items from this screen/audio activity:\n\n{}", chunk_clone),
+ )
+ })
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({"error": {"message": e.to_string()}})),
+ )
+ })?;
+
+ match result {
+ Ok(gen_result) => {
+ eprintln!(
+ "[fm-server] extract chunk {}/{}: {:.0}ms, {} chars",
+ i + 1,
+ num_chunks,
+ gen_result.metrics.total_time_ms,
+ gen_result.text.len()
+ );
+
+ // Parse JSON from the text response (model returns JSON array)
+ let text = gen_result.text.trim();
+ // Strip markdown code fences if present
+ let json_text = if text.starts_with("```") {
+ text.lines()
+ .skip(1)
+ .take_while(|l| !l.starts_with("```"))
+ .collect::<Vec<_>>()
+ .join("\n")
+ } else {
+ text.to_string()
+ };
+
+ // Try parsing as array directly, or as object with "items" key
+ let items_result: Option<Vec<TodoItem>> = serde_json::from_str(&json_text)
+ .ok()
+ .or_else(|| {
+ // Try as {"items": [...]}
+ serde_json::from_str::<serde_json::Value>(&json_text)
+ .ok()
+ .and_then(|v| v.get("items").cloned())
+ .and_then(|v| serde_json::from_value(v).ok())
+ });
+
+ if let Some(chunk_items) = items_result {
+ let valid_items: Vec<TodoItem> = chunk_items
+ .into_iter()
+ .filter(|item| !item.text.trim().is_empty())
+ .collect();
+ if !valid_items.is_empty() {
+ chunks_with_results += 1;
+ all_items.extend(valid_items);
+ }
+ } else {
+ eprintln!(
+ "[fm-server] extract chunk {}/{}: failed to parse JSON: {}",
+ i + 1,
+ num_chunks,
+ &json_text[..json_text.len().min(200)]
+ );
+ }
+ }
+ Err(e) => {
+ eprintln!(
+ "[fm-server] extract chunk {}/{} failed: {}",
+ i + 1,
+ num_chunks,
+ e
+ );
+ // Continue processing other chunks
+ }
+ }
+ }
+
+ // Step 4: Deduplicate
+ let deduped = dedup_todos(all_items);
+
+ let elapsed = start.elapsed().as_millis() as f64;
+ eprintln!(
+ "[fm-server] extract done: {} items from {} chunks in {:.0}ms",
+ deduped.len(),
+ num_chunks,
+ elapsed
+ );
+
+ Ok(Json(ExtractResponse {
+ items: deduped,
+ stats: ExtractStats {
+ chunks_processed: num_chunks,
+ chunks_with_results,
+ total_input_chars,
+ filtered_input_chars,
+ total_time_ms: elapsed,
+ pre_filter_ratio: if total_input_chars > 0 {
+ 1.0 - filtered_input_chars as f64 / total_input_chars as f64
+ } else {
+ 0.0
+ },
+ },
+ }))
+}
+
+async fn health() -> Json<serde_json::Value> {
+ let avail = check_availability();
+ Json(serde_json::json!({
+ "status": if avail == Availability::Available { "ok" } else { "unavailable" },
+ "model": MODEL_ID,
+ "endpoints": ["/v1/chat/completions", "/v1/models", "/v1/extract-todos", "/health"]
+ }))
+}
+
+#[tokio::main]
+async fn main() {
+ let avail = check_availability();
+ eprintln!("Foundation Models: {}", avail);
+ if avail != Availability::Available {
+ eprintln!("ERROR: Apple Intelligence not available. Enable in System Settings.");
+ std::process::exit(1);
+ }
+
+ eprint!("Prewarming...");
+ let _ = prewarm();
+ eprintln!(" done");
+
+ let app = Router::new()
+ .route("/v1/chat/completions", post(chat_completions))
+ .route("/v1/extract-todos", post(extract_todos))
+ .route("/v1/models", get(list_models))
+ .route("/health", get(health));
+
+ let port = std::env::var("FM_PORT").unwrap_or_else(|_| "5273".to_string());
+ eprintln!("\n🧠 Apple Intelligence API at http://localhost:{}/v1", port);
+ eprintln!(" Model: {}", MODEL_NAME);
+ eprintln!(" Endpoints:");
+ eprintln!(" POST /v1/chat/completions (OpenAI-compatible)");
+ eprintln!(" POST /v1/extract-todos (TODO extraction)");
+ eprintln!(" GET /v1/models");
+ eprintln!(" GET /health\n");
+
+ let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))
+ .await
+ .unwrap();
+ axum::serve(listener, app).await.unwrap();
+}
diff --git a/crates/screenpipe-apple-intelligence/swift/bridge.swift b/crates/screenpipe-apple-intelligence/swift/bridge.swift
new file mode 100644
index 000000000..0bb4d0db5
--- /dev/null
+++ b/crates/screenpipe-apple-intelligence/swift/bridge.swift
@@ -0,0 +1,239 @@
+// screenpipe-apple-intelligence Swift bridge
+// Provides C-callable functions that wrap Apple's Foundation Models framework.
+// Compiled by build.rs → linked into the Rust crate.
+
+import Foundation
+import FoundationModels
+
+// MARK: - Memory helpers
+
+private func getResidentMemory() -> UInt64 {
+ var info = mach_task_basic_info()
+ var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4
+ let result = withUnsafeMutablePointer(to: &info) {
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
+ task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
+ }
+ }
+ return result == KERN_SUCCESS ? UInt64(info.resident_size) : 0
+}
+
+private func makeCString(_ str: String) -> UnsafeMutablePointer<CChar> {
+ return strdup(str)!
+}
+
+// MARK: - Exported C functions
+
+/// Check if Foundation Models is available.
+/// Returns status code: 0=available, 1=not enabled, 2=not eligible, 3=not ready, 4=unknown
+/// Writes reason string to `out_reason` (caller must free with fm_free_string).
+@_cdecl("fm_check_availability")
+public func fmCheckAvailability(
+ _ out_reason: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>
+) -> Int32 {
+ let model = SystemLanguageModel.default
+
+ switch model.availability {
+ case .available:
+ out_reason.pointee = makeCString("available")
+ return 0
+ case .unavailable(let reason):
+ switch reason {
+ case .appleIntelligenceNotEnabled:
+ out_reason.pointee = makeCString("Apple Intelligence is not enabled")
+ return 1
+ case .deviceNotEligible:
+ out_reason.pointee = makeCString("Device not eligible for Apple Intelligence")
+ return 2
+ case .modelNotReady:
+ out_reason.pointee = makeCString("Model not ready (still downloading or configuring)")
+ return 3
+ @unknown default:
+ out_reason.pointee = makeCString("Unknown unavailability reason")
+ return 4
+ }
+ }
+}
+
+/// Free a string allocated by the Swift side.
+@_cdecl("fm_free_string")
+public func fmFreeString(_ ptr: UnsafeMutablePointer<CChar>?) {
+ if let ptr = ptr { free(ptr) }
+}
+
+/// Generate a plain text response from a prompt.
+///
+/// Parameters:
+/// - instructions: system instructions (nullable)
+/// - prompt: user prompt (required)
+/// - out_text: receives response text (caller frees)
+/// - out_error: receives error message on failure (caller frees)
+/// - out_total_time_ms: receives total generation time
+/// - out_mem_before: receives resident memory before (bytes)
+/// - out_mem_after: receives resident memory after (bytes)
+///
+/// Returns 0 on success, -1 on error.
+@_cdecl("fm_generate_text")
+public func fmGenerateText(
+ _ instructions: UnsafePointer<CChar>?,
+ _ prompt: UnsafePointer<CChar>?,
+ _ out_text: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>,
+ _ out_error: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>,
+ _ out_total_time_ms: UnsafeMutablePointer<Double>,
+ _ out_mem_before: UnsafeMutablePointer<UInt64>,
+ _ out_mem_after: UnsafeMutablePointer<UInt64>
+) -> Int32 {
+ guard let prompt = prompt else {
+ out_error.pointee = makeCString("prompt is null")
+ return -1
+ }
+
+ let promptStr = String(cString: prompt)
+ let instructionsStr = instructions.map { String(cString: $0) }
+
+ let semaphore = DispatchSemaphore(value: 0)
+ var status: Int32 = 0
+
+ Task {
+ let memBefore = getResidentMemory()
+ out_mem_before.pointee = memBefore
+ let startTime = ContinuousClock.now
+
+ do {
+ let session: LanguageModelSession
+ if let inst = instructionsStr {
+ session = LanguageModelSession(instructions: inst)
+ } else {
+ session = LanguageModelSession()
+ }
+
+ let response = try await session.respond(to: promptStr)
+ let totalDuration = ContinuousClock.now - startTime
+ let memAfter = getResidentMemory()
+
+ out_text.pointee = makeCString(response.content)
+ out_total_time_ms.pointee = Double(totalDuration.components.seconds) * 1000.0
+ + Double(totalDuration.components.attoseconds) / 1_000_000_000_000_000.0
+ out_mem_after.pointee = memAfter
+ status = 0
+ } catch {
+ out_error.pointee = makeCString(error.localizedDescription)
+ status = -1
+ }
+
+ semaphore.signal()
+ }
+
+ semaphore.wait()
+ return status
+}
+
+/// Generate a structured JSON response using a JSON schema string.
+///
+/// The schema constrains the model output. The response is a JSON string
+/// derived from GeneratedContent's debug description (since GeneratedContent
+/// is not directly Encodable).
+///
+/// Returns 0 on success, -1 on error.
+@_cdecl("fm_generate_json")
+public func fmGenerateJson(
+ _ instructions: UnsafePointer<CChar>?,
+ _ prompt: UnsafePointer<CChar>?,
+ _ jsonSchema: UnsafePointer<CChar>?,
+ _ out_text: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>,
+ _ out_error: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>,
+ _ out_total_time_ms: UnsafeMutablePointer<Double>,
+ _ out_mem_before: UnsafeMutablePointer<UInt64>,
+ _ out_mem_after: UnsafeMutablePointer<UInt64>
+) -> Int32 {
+ guard let prompt = prompt else {
+ out_error.pointee = makeCString("prompt is null")
+ return -1
+ }
+ guard let jsonSchema = jsonSchema else {
+ out_error.pointee = makeCString("jsonSchema is null")
+ return -1
+ }
+
+ let promptStr = String(cString: prompt)
+ let instructionsStr = instructions.map { String(cString: $0) }
+ let schemaStr = String(cString: jsonSchema)
+
+ let semaphore = DispatchSemaphore(value: 0)
+ var status: Int32 = 0
+
+ Task {
+ let memBefore = getResidentMemory()
+ out_mem_before.pointee = memBefore
+ let startTime = ContinuousClock.now
+
+ do {
+ guard let schemaData = schemaStr.data(using: .utf8) else {
+ out_error.pointee = makeCString("Failed to encode schema as UTF-8")
+ status = -1
+ semaphore.signal()
+ return
+ }
+
+ let schemaObj = try JSONDecoder().decode(GenerationSchema.self, from: schemaData)
+
+ let session: LanguageModelSession
+ if let inst = instructionsStr {
+ session = LanguageModelSession(instructions: inst)
+ } else {
+ session = LanguageModelSession()
+ }
+
+ let response = try await session.respond(
+ to: promptStr,
+ schema: schemaObj
+ )
+
+ let totalDuration = ContinuousClock.now - startTime
+ let memAfter = getResidentMemory()
+
+ // GeneratedContent has a built-in .jsonString property
+ let jsonStr = response.content.jsonString
+
+ out_text.pointee = makeCString(jsonStr)
+ out_total_time_ms.pointee = Double(totalDuration.components.seconds) * 1000.0
+ + Double(totalDuration.components.attoseconds) / 1_000_000_000_000_000.0
+ out_mem_after.pointee = memAfter
+ status = 0
+ } catch {
+ out_error.pointee = makeCString(error.localizedDescription)
+ status = -1
+ }
+
+ semaphore.signal()
+ }
+
+ semaphore.wait()
+ return status
+}
+
+// No manual JSON conversion needed — GeneratedContent has .jsonString built-in
+
+/// Prewarm the model (loads assets into memory). Blocking call.
+/// Returns 0 on success, non-zero on error.
+@_cdecl("fm_prewarm")
+public func fmPrewarm() -> Int32 {
+ let model = SystemLanguageModel.default
+ guard model.availability == .available else { return -1 }
+
+ let session = LanguageModelSession()
+ session.prewarm()
+ return 0
+}
+
+/// Get supported languages as a JSON array string. Caller must free.
+@_cdecl("fm_supported_languages")
+public func fmSupportedLanguages() -> UnsafeMutablePointer<CChar> {
+ let model = SystemLanguageModel.default
+ let langs = model.supportedLanguages.map { $0.languageCode?.identifier ?? "unknown" }
+ guard let data = try? JSONEncoder().encode(langs),
+ let str = String(data: data, encoding: .utf8) else {
+ return makeCString("[]")
+ }
+ return makeCString(str)
+}
diff --git a/crates/screenpipe-server/Cargo.toml b/crates/screenpipe-server/Cargo.toml
index c1db2f272..c0457f12c 100644
--- a/crates/screenpipe-server/Cargo.toml
+++ b/crates/screenpipe-server/Cargo.toml
@@ -20,6 +20,7 @@ screenpipe-audio = { path = "../screenpipe-audio" }
screenpipe-core = { path = "../screenpipe-core", features = ["security", "cloud-sync"] }
screenpipe-db = { path = "../screenpipe-db" }
screenpipe-accessibility = { path = "../screenpipe-accessibility", features = ["db"], optional = true }
+screenpipe-apple-intelligence = { path = "../screenpipe-apple-intelligence", optional = true }
killport = { version = "1.1.0" }
# Image processing
@@ -142,6 +143,7 @@ experimental = []
debug-console = ["console-subscriber"]
adaptive-fps = ["screenpipe-vision/adaptive-fps"]
ui-events = ["screenpipe-accessibility"]
+apple-intelligence = ["dep:screenpipe-apple-intelligence"]
[[bin]]
name = "screenpipe"
diff --git a/crates/screenpipe-server/src/apple_intelligence_api.rs b/crates/screenpipe-server/src/apple_intelligence_api.rs
new file mode 100644
index 000000000..4b52e790b
--- /dev/null
+++ b/crates/screenpipe-server/src/apple_intelligence_api.rs
@@ -0,0 +1,135 @@
+//! Generic OpenAI-compatible API wrapping Apple Foundation Models.
+//!
+//! Thin layer: HTTP in → generate_text() via Swift FFI → HTTP out.
+//! No application-specific logic — just an AI endpoint anyone can use.
+//! Feature-gated behind `apple-intelligence` (macOS aarch64 only).
+
+use axum::{http::StatusCode, Json};
+use screenpipe_apple_intelligence::{check_availability, generate_text, prewarm, Availability};
+use serde::{Deserialize, Serialize};
+use std::sync::Once;
+use tracing::{info, warn};
+
+static PREWARM: Once = Once::new();
+
+// ─── OpenAI-compatible types ────────────────────────────────────────────────
+
+#[derive(Debug, Deserialize)]
+pub struct ChatCompletionRequest {
+ messages: Vec<Message>,
+ #[serde(default)]
+ temperature: Option<f64>,
+ #[serde(default)]
+ max_tokens: Option<u32>,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+pub struct Message {
+ role: String,
+ content: String,
+}
+
+#[derive(Serialize)]
+pub struct ChatCompletionResponse {
+ id: String,
+ object: String,
+ created: u64,
+ model: String,
+ choices: Vec<Choice>,
+ usage: Usage,
+}
+
+#[derive(Serialize)]
+pub struct Choice {
+ index: u32,
+ message: Message,
+ finish_reason: String,
+}
+
+#[derive(Serialize)]
+pub struct Usage {
+ prompt_tokens: u32,
+ completion_tokens: u32,
+ total_tokens: u32,
+}
+
+#[derive(Serialize)]
+pub struct StatusResponse {
+ available: bool,
+ status: String,
+ model: String,
+}
+
+// ─── Handlers ───────────────────────────────────────────────────────────────
+
+/// GET /ai/status
+pub async fn ai_status() -> Json<StatusResponse> {
+ let avail = check_availability();
+ Json(StatusResponse {
+ available: avail == Availability::Available,
+ status: avail.to_string(),
+ model: "apple-intelligence".to_string(),
+ })
+}
+
+/// POST /ai/chat/completions — OpenAI-compatible chat completions
+pub async fn chat_completions(
+ Json(req): Json<ChatCompletionRequest>,
+) -> Result<Json<ChatCompletionResponse>, (StatusCode, Json<serde_json::Value>)> {
+ // Prewarm on first call
+ PREWARM.call_once(|| {
+ info!("prewarming apple intelligence model");
+ if let Err(e) = prewarm() {
+ warn!("prewarm failed: {}", e);
+ }
+ });
+
+ // Build prompt from messages
+ let mut system: Option<String> = None;
+ let mut conversation = Vec::new();
+
+ for msg in &req.messages {
+ match msg.role.as_str() {
+ "system" => system = Some(msg.content.clone()),
+ "user" => conversation.push(format!("User: {}", msg.content)),
+ "assistant" => conversation.push(format!("Assistant: {}", msg.content)),
+ _ => {}
+ }
+ }
+
+ let prompt = conversation.join("\n\n");
+ let prompt_len = prompt.len();
+
+ // Call Foundation Models (blocking FFI → spawn_blocking)
+ let result = tokio::task::spawn_blocking(move || {
+ generate_text(system.as_deref(), &prompt)
+ })
+ .await
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))))?
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))))?;
+
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+
+ Ok(Json(ChatCompletionResponse {
+ id: format!("chatcmpl-{}", now),
+ object: "chat.completion".to_string(),
+ created: now,
+ model: "apple-intelligence".to_string(),
+ choices: vec![Choice {
+ index: 0,
+ message: Message {
+ role: "assistant".to_string(),
+ content: result.text,
+ },
+ finish_reason: "stop".to_string(),
+ }],
+ usage: Usage {
+ prompt_tokens: (prompt_len / 4) as u32,
+ completion_tokens: 0, // we don't track this
+ total_tokens: (prompt_len / 4) as u32,
+ },
+ }))
+}
diff --git a/crates/screenpipe-server/src/lib.rs b/crates/screenpipe-server/src/lib.rs
index 6b65015f0..0eb844fe2 100644
--- a/crates/screenpipe-server/src/lib.rs
+++ b/crates/screenpipe-server/src/lib.rs
@@ -1,5 +1,7 @@
mod add;
pub mod analytics;
+#[cfg(feature = "apple-intelligence")]
+mod apple_intelligence_api;
mod auto_destruct;
pub mod chunking;
pub mod cli;
diff --git a/crates/screenpipe-server/src/server.rs b/crates/screenpipe-server/src/server.rs
index 76df61dc4..c1cd7901a 100644
--- a/crates/screenpipe-server/src/server.rs
+++ b/crates/screenpipe-server/src/server.rs
@@ -1522,7 +1522,7 @@ impl SCServer {
.freeze();
// Build the main router with all routes
- Router::new()
+ let router = Router::new()
.merge(server.into_router())
// UI Events API routes
.route("/ui-events", get(ui_events_search_handler))
@@ -1537,8 +1537,19 @@ impl SCServer {
axum::routing::post(sync_api::sync_download),
)
// Vision status endpoint (not in OpenAPI spec to avoid oasgen registration issues)
- .route("/vision/status", get(api_vision_status))
- // NOTE: websockerts and sse is not supported by openapi so we move it down here
+ .route("/vision/status", get(api_vision_status));
+
+ // Apple Intelligence — generic OpenAI-compatible endpoint (macOS only)
+ #[cfg(feature = "apple-intelligence")]
+ let router = router
+ .route("/ai/status", get(crate::apple_intelligence_api::ai_status))
+ .route(
+ "/ai/chat/completions",
+ axum::routing::post(crate::apple_intelligence_api::chat_completions),
+ );
+
+ // NOTE: websockets and sse is not supported by openapi so we move it down here
+ router
.route("/stream/frames", get(stream_frames_handler))
.route("/ws/events", get(ws_events_handler))
.route("/ws/health", get(ws_health_handler))