惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
Google DeepMind News
Google DeepMind News
罗磊的独立博客
Martin Fowler
Martin Fowler
博客园_首页
Stack Overflow Blog
Stack Overflow Blog
Last Week in AI
Last Week in AI
The GitHub Blog
The GitHub Blog
B
Blog
C
Check Point Blog
WordPress大学
WordPress大学
G
Google Developers Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
量子位
月光博客
月光博客
U
Unit 42
Engineering at Meta
Engineering at Meta
有赞技术团队
有赞技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Y
Y Combinator Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Vercel News
Vercel News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 【当耐特】
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Jina AI
Jina AI
S
Secure Thoughts
aimingoo的专栏
aimingoo的专栏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
Intezer
Latest news
Latest news
V
Vulnerabilities – Threatpost
D
Docker
Attack and Defense Labs
Attack and Defense Labs
Help Net Security
Help Net Security
S
Security @ Cisco Blogs
Forbes - Security
Forbes - Security
MongoDB | Blog
MongoDB | Blog
云风的 BLOG
云风的 BLOG
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
Cloudbric
Cloudbric
Spread Privacy
Spread Privacy

Hacker News: Show HN

PurrrrrFocus: Pomodoro Timer App - App Store Workflow Engine — Multi-Step Orchestration for Bun RapidPhoto: Pro Photo Editor App - App Store GitHub - DheerG/swarms: Achieve extraordinary results with claude code across a variety of tasks SPICE simulation → oscilloscope → verification with Claude Code — Lucas Gerads Show HN: VCoding – A 5 MB native Windows IDE with no dynamic dependencies Show HN: LLMs don't hallucinate because they're bad at math, it's the format GitHub - Agent-FM/agentfm-core: AgentFM is a peer-to-peer network that turns everyday computers into a decentralized AI supercomputer. AgentFM lets you run massive AI workloads directly across a global mesh of idle CPUs and GPUs. Show HN: Tracking Top US Science Olympiad Alumni over Last 25 Years GitHub - Potarix/agent-hub: One place to talk to all your agents Show HN: Runtime security for AI agents(injection,tool abuse, data exfiltration) GitHub - dubeyKartikay/lazyspotify: Terminal Spotify client for macOS and Linux GitHub - the-banana-tool/king-louie: Easy to use GUI Personal AI Assistant. Win/Linux/Mac. Show HN I made my vacation rental bookable by AI agents–no Airbnb, 0% commission GitHub - basteez/jsf-autoreload: maven plugin to enable hot reload on jsf projects uvm32/hosts/host-gdbstub at main · ringtailsoftware/uvm32 GitHub - labsai/EDDI: Config-driven engine that turns JSON into production-grade AI agents. Multi-agent orchestration, 12+ LLM providers, MCP/A2A protocols, RAG, persistent memory, and enterprise compliance (EU AI Act, GDPR, HIPAA). Built on Quarkus. GitHub - glitchnsec/fortyone-oss: AI Executive Assistant Platform Quickstart | Alien GitHub - muxshed/shed: One stream in, or many. Every destination, simultaneously. No cloud middleman, no per-channel fees, no limits. GitHub - ocrbase-hq/ocrbase: 📄 PDF/IMG ->.MD/JSON Document OCR API for PaddleOCR and GLMOCR. Self-hostable. GitHub - impactjo/home-memory: MCP server that lets your AI assistant remember everything about your home. GitHub - Sets88/dbcls: DbCls is a powerful terminal database client that supports various databases GitHub - neptun2000/heor-agent-mcp GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh RollQuation: Math Puzzles - Apps on Google Play GitHub - dropbox/witchcraft Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis GitHub - opentalon/opentalon: OpenTalon is an open-source platform built from the ground up in Go as a robust alternative to OpenClaw LinkedIn™ 职位抓取工具 - Chrome 应用商店 GitHub - EdoardoBambini/Agent-Armor-Iaga: AI agents are getting tool access — shell, file system, databases, APIs, secrets. But **nobody is governing what they actually do with it**. Frameworks like LangChain, CrewAI, AutoGen, and Claude Code give agents the power to execute. Agent Armor gives you the power to control, audit, and approve every single action before it happens. HN Vibes — Week 15, Apr 7–13 2026 GitHub - chojs23/ec: Easy terminal-native 3-way git mergetool vim-like workflow GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - JakOb-dotcom/cloud-sandbox-security-analysis: Technical analysis and Proof of Concept (PoC) regarding environment variable exfiltration in containerized cloud sandboxes via side-channel data leaks. Springboards - Flint Alpha Show HN: A simpler coding agent harness GitHub - audiodude/sudomake-friends GitHub - 256thFission/mini-mythos: OSS clone of Anthropic’s Mythos harness to locate C/C++ memory vulnerabilities Show HN: OpenParallax: OS-level privilege separation for AI agent execution Hacker News Sorted - Chrome 应用商店 Show HN: How to Install Docker on Ubuntu 24.04 LTS: Complete 2026 Guide GitHub - himanshudongre/smriti GitHub - sverrirsig/claude-control: macOS desktop dashboard for monitoring and managing multiple Claude Code sessions GitHub - ory/dockertest: Write better integration tests! Dockertest helps you boot up ephermal docker images for your Go tests with minimal work. Chiral - Chrome 应用商店 Show HN: Two Claudes collaborating through shared memory on a $100 mini-PC GitHub - pmichaillat/latex-cv: Minimalist LaTeX template for academic CVs GitHub - oguzbilgic/posse: A web UI for Anthropic Managed Agents. GitHub - sshiraz/depsly: Dependency risk analysis tool for npm packages ABI Add safari/agent-harness — Safari browser automation via safari-mcp by achiya-automation · Pull Request #212 · HKUDS/CLI-Anything GitHub - Halfblood-Prince/trustcheck: Verify PyPI package attestations and improve Python supply-chain security GitHub - oguzbilgic/kern-ai: Agents that do the work and show it. GitHub - bruits/satteri: High-performance Markdown and MDX processing for the JavaScript ecosystem GitHub - tylergibbs1/feedstock: High-performance web crawler and scraper for TypeScript, powered by Bun and Playwright GitHub - Grimm67123/grimmbot: The self-improving sandboxed and open-source AI agent. With persistent memory and scheduling. GitHub - whitevanillaskies/whitebloom: Local whiteboard that blooms. GitHub - hwdsl2/docker-whisper: Docker image for a self-hosted Whisper speech-to-text server with speaker diarization and OpenAI-compatible transcription and translation APIs. Powered by faster-whisper. Supports all Whisper models, NVIDIA GPU (CUDA) acceleration, JSON/SRT/VTT output, SSE streaming, offline mode, and multi-arch (amd64, arm64). GitHub - yisding/reviewwiggum GitHub - MarwanAlsoltany/serrors: Structured errors for Go: sentinel hierarchies, typed data, custom formatting, and slog integration. GitHub - soatok/age-php GitHub - Luthiraa/markitme GitHub - stagas/rtdiff: realtime git diff gui and AI-assisted commits GitHub - tombedor/excalicharts GitHub - wh1le/excalidraw-edit: Open and edit .excalidraw files from the terminal. Offline, auto-saves to disk. MalExt Sentry - Malicious Extension Scanner - Chrome 应用商店 GitHub - syi0808/asciianimesvg: Generate animated ASCII art SVGs from text. CLI, Rust library, WASM, and web editor. GitHub - zaina-ml/ml_forge: A visual-based graph node editor for training computer vision models. GitHub - anakin87/llm-rl-environments-lil-course: 🌱 A little course on Reinforcement Learning Environments for evaluating and training Language Models GitHub - takaakit/superpowers-uml: Superpowers-UML modifies Superpowers to ensure a software development workflow in which AI agents design through UML modeling. AdriByte Studio - Sviluppo Web e Soluzioni Digitali GitHub - chouligi/angel-copilot: Your personalized Angel Investment Advisor Show HN: MoodSense AI (ML and FastAPI and Gradio, Deployed on Hugging Face) Moodsense Ai - a Hugging Face Space by aman179102 GitHub - agenteractai/lodmem: Level Of Detail Context Management for Agents GitHub - ostefani/subnetlens: A fast, concurrent network scanner with a TUI and plain-text CLI, built in Go. It discovers live hosts on your network, scans their open ports, resolves hostnames, and fingerprints operating systems—delivered. Cyber Pulse: Agentic Intel - Apps on Google Play Whisper API: Self-Hostable Speech to Text Transcription The Agent-Web Protocol Stack: A Research Thesis GitHub - msmarkgu/RelayFreeLLM: A restful API designed to route user prompts to various AI model providers. Show HN: Provepy – A Python decorator that proves your code using Lean and LLMs Show HN: Pardonned.com – A searchable database of US Pardons GitHub - patrickdappollonio/dux: Dux is a terminal UI that lets you run multiple AI coding agents side by side, each in its own git worktree, with full companion terminals, macros, commit generation, and a command palette that knows more tricks than you do. kMC Crystal Simulator Show HN: HyperFlow – A self-improving agent framework built on LangGraph GitHub - stef41/vibescore: 🎵 Grade your vibe-coded project. One command, instant letter grade across security, quality, dependencies, and testing. GitHub - stef41/lmscan: 🔍 Detect AI-generated text and fingerprint which LLM wrote it. Open-source GPTZero alternative. Zero dependencies, works offline. imgur.com GitHub - visionscaper/collabmem: Enabling long-term collaboration with Agentic AI - building up episodic and world model memory over time with in-context awareness 在 Steam 上购买 FriedrichAI: Offline AI 立省 10% GitHub - atripati/ark: AI Runtime Kernel — a context operating system for AI agents. Eliminates tool bloat, loads only what’s needed, and gives LLMs their reasoning space back. GitHub - nowork-studio/toprank: Open-source Claude Code skills for SEO, SEM, Google Ads GitHub - tacomanator/sash: Lightweight macOS menu bar app for reliably cycling through windows of the current application. Appents | Social Media Management for Product-First Teams GitHub - pnhoang/youtube-spam-blocker: Automatically detects and hides spam messages in YouTube Live chat. Set rate limits, keyword filters, and block repeat offenders. GitHub - decisionnode/DecisionNode: CLI + Local MCP - A shared structured memory store across Claude Code, Cursor, Windsurf, Antigravity, and every MCP client. Semantically queryable. GitHub - AvaCodeSolutions/django-email-learning: An open source Django app for creating email-based learning platforms with IMAP integration and React frontend components. The $100K Gap in Kubernetes Security Tooling Function Calling Harness: From 6.75% to 100%
GitHub - localflow-ai/localflow-core: The core API to enable metadata-first AI in your projects.
renaudpawlak · 2026-06-02 · via Hacker News: Show HN

npm License: Apache 2.0 Live demo


Table of contents

  • What is Metadata-first AI?
    • The metadata boundary
    • Two-step execution
    • Key properties
  • Architecture overview
    • What leaves the browser?
    • Limitations
  • Quick start
  • Use an actual proxy
  • API Reference
    • LocalAssistant
      • Constructor
      • Configuration
      • Datasets
      • External APIs
      • Conversation & prompt()
      • Analysis match hook
      • Events
    • Proxy / LocalProxy / ProxyClient
  • Building
  • Package structure
  • Roadmap
  • License

What is Metadata-first AI?

In metadata-first AI, only metadata about your data ever reaches the LLM — column names, statistical samples, document structure. The actual rows, values, and documents stay on your machine. The model acts as a code generator: given a description of the data's shape, it writes analysis code that executes locally in a sandbox on your real data.

This is a different axis than the two approaches usually discussed:

  • Classical cloud AI — sends raw data to the model. Powerful and flexible, but your data leaves your environment and every result is a fresh inference, non-deterministic by nature.
  • Local-model AI (Ollama, llama.cpp, etc.) — runs the model on your device so data stays local, but you are constrained by what fits on your hardware, and results remain non-deterministic.

Metadata-first AI makes the constraint explicit: only metadata crosses the inference boundary — raw data never does. When using a cloud LLM, metadata (column names, statistics, document structure) does leave your machine, which is an acceptable exposure for most organisations. For the strictest privacy requirements, combining metadata-first AI with a self-hosted LLM eliminates even that: nothing crosses your infrastructure boundary. The generated code runs deterministically in your browser on your real data.

Classical cloud AI Local-model AI Metadata-first AI
Raw data stays local
Metadata stays local ⚠️ cloud / ✅ self-hosted
Computation executes locally
Uses best available models Limited
Compatible with self-hosted LLMs
Results are deterministic
Re-runs without AI (no tokens/GPU)
Works on large datasets Limited

Typical use cases range from "Talk to your Data" on sensitive enterprise spreadsheets — where you want natural language querying without exposing values to the model — to large-scale geospatial analysis, document intelligence on confidential PDFs, and any analytical pipeline where deterministic, repeatable results matter.

The metadata boundary

LocalFlow defines precisely what constitutes metadata for each data type:

  • Structured data (CSV, Excel, CRM): column headers and statistical samples — enough for the LLM to write correct analysis code. Raw rows are never sent.
  • Documents (PDF): the extracted text is needed so the LLM understands the document's structure and can write a reliable parser. Users can work with obfuscated or template documents to generate formulas, then run them locally on real documents — the LLM only needs the structure, not the actual values.

Two-step execution

Code generation (step 1) and local execution (step 2) are invisible to the user — the assistant behaves like a regular AI assistant. The difference is that generated analyses can be saved and re-run on any compatible dataset without making another LLM call.

Key properties

  1. Full AI power — use the best available LLM to analyse complex, heterogeneous data
  2. Data safety — raw data never reaches the LLM. Metadata (schema, statistics) leaves only for code generation; a self-hosted LLM removes even that exposure
  3. No hallucinated results — outputs are computed from real data by deterministic code, not inferred by the model
  4. Scalable — once generated, run the same analysis on large datasets as many times as needed, consuming no additional AI tokens
  5. Explainable — the generated code is fully inspectable; any AI can explain why a formula works or debug why it fails
  6. Green and sustainable — AI is used only for code generation, a one-time cost per analysis. Subsequent runs consume no AI inference at all, reducing dependence on energy-intensive infrastructure

Architecture overview

┌─────────────────────────────────────────────────────┐
│                  Browser (client)                   │
│                                                     │
│  ┌─────────────────┐      ┌──────────────────────┐  │
│  │  Host App / UI  │      │      Sandbox         │  │
│  │  (React or any) │      │  formula execution   │  │
│  │                 │      │  charts / maps       │  │
│  │  LocalAssistant │◄────►│  fetch → proxy relay │  │
│  │  (vanilla JS)   │      └──────────────────────┘  │
│  └────────┬────────┘                                │
│           │ HTTPS (column stats + generated code)   │
└───────────┼─────────────────────────────────────────┘
            │
   ┌────────▼────────┐
   │ LocalFlow Proxy │  (manages keys, auth,
   │                 │   whitelists APIs,
   └────────┬────────┘   edge services: PDF, OCR...)
            │
            ├──────────────────┐─────────────────────┐
            │                  │                     │
   ┌────────▼────────┐ ┌───────▼───────┐ ┌───────────▼───────────┐
   │     LLM API     │ │ Whitelisted   │ │  Your CRM / ERP / DB  │
   └─────────────────┘ │ external APIs │ └───────────────────────┘
                       └───────────────┘

What leaves the browser?

Operation Data sent Where
Tabular analysis — code generation Column headers + statistics 🟠 LLM
PDF extraction Raw PDF bytes 🔵 Proxy
PDF analysis — code generation Extracted document text 🟠 LLM
Analysis execution Actual data 🟢 Browser
External API calls (optional) Query parameters only 🔵 Proxy

🟢 Browser — stays in your browser  ·  🔵 Proxy — goes to your server only and proxied APIs  ·  🟠 LLM — forwarded to the AI model via your proxy

Limitations

Because the LLM only ever sees metadata — never the actual rows — there are tasks that a metadata-first approach cannot perform on its own. Inference excels at understanding natural language, translating free-form content, summarising documents, or spotting patterns across raw text. When those capabilities need to operate on the full dataset, a classical AI pipeline (one that sends the data to the model) remains the right tool.

LocalFlow is therefore a complement to classical AI, not a replacement. It opens up use cases that are out of reach for classical AI — large-scale data analysis without privacy exposure, deterministic and repeatable results, scalable execution at zero marginal AI cost — while leaving room for classical approaches where they are genuinely needed.

That boundary is not fixed. The proxy can expose tools — including LLM-powered ones — that operate on a carefully scoped subset of data, defined and controlled by the administrator or the user. A formula could, for example, call a proxy-hosted service that summarises a specific field or translates a column, without the LLM ever seeing the full dataset. This kind of extension requires intentional configuration of your proxy environment and its available tools, tailoring the setup to your specific use cases and acceptable data-sharing boundaries.


📄 For a deeper dive into these concepts, read the LocalFlow white paper.

Quick start — embedding LocalAssistant in your app

No server required — LocalProxy runs entirely in the browser and calls the LLM directly. See localflow-examples for complete React and vanilla JS apps you can run immediately.

1. Install

npm install @localflow/core

2. Create the assistant

import { LocalProxy, LocalAssistant } from '@localflow/core'

// No server needed — LocalProxy calls the LLM directly from the browser
const proxy = new LocalProxy()

const assistant = new LocalAssistant({
  proxy,
  llm: {
    type: 'gemini',
    model: 'gemini-3-flash-preview',   // optional, this is the default
  },

  // Point to the div where formula results should be rendered.
  // Accepts an HTMLElement, a CSS selector string, or a factory function.
  resultContainer: '#result',
})

// Pass the user's Gemini API key — stored locally, never sent to any third party
// NOTE: automatically encryted when using an actual proxy
await assistant.setLlmApiKey('AIza...')

// Persist LLM config whenever it changes (user sets a new key, model, etc.)
assistant.on('llm:change', (llm) => {
  if (llm.apiKey) localStorage.setItem('llm-key', llm.apiKey)
})

To restore a key across page loads, pass it at construction:

const assistant = new LocalAssistant({
  proxy,
  llm: { type: 'gemini', apiKey: localStorage.getItem('llm-key') ?? '' },
  resultContainer: '#result',
})

3. Load your data

// Tabular data — from any source: CSV parse, DB query, API response, etc.
assistant.addDataset('portfolio', portfolioRows)   // rows: Record<string, unknown>[]
assistant.addDataset('market',    marketRows)

// Mark which dataset is the "active" one (the `data` variable in formulas)
assistant.setActiveDataset('portfolio')

4. Send a message and render the result

With resultContainer configured, the assistant takes care of everything — creating the iframe, setting sandbox permissions, and relaying proxied API calls. No boilerplate needed.

assistant.on('message', (response) => {
  // Show response.answer in your chat UI
  appendChatBubble(response.answer)
})

assistant.on('formula:done', ({ data }) => {
  // Optional: react to the formula's output data
  console.log('Analysis result:', data)
})

// Send a message — the LLM generates a formula, and the assistant
// renders it automatically in the configured resultContainer.
const response = await assistant.prompt('Show me the allocation by asset class')

You can change the result container at any time:

assistant.resultContainer = document.getElementById('result')
// or: assistant.resultContainer = '#result'
// or: assistant.resultContainer = () => document.querySelector('.panel.active')

5. Save and replay formulas (optional)

Generated formulas are deterministic — you can save them and re-run on any compatible dataset without an additional LLM call.

// Get the formula from the last response
const formula = assistant.getLastFormula()

// Save it to your catalog...
saveToCatalog({ formula, title: response.title, description: response.description })

// ...and replay it later
assistant.executeFormula(savedFormula)

6. Register a semantic analysis-match hook (optional)

This lets the assistant inject a relevant past analysis as a system-prompt example before calling the LLM, improving output quality.

assistant.setAnalysisMatchHook(async (query, ctx) => {
  const analyses = catalogLoad()        // your catalog store
  return findBestMatch(query, analyses, ctx.activeColumns)
})

Use an actual proxy

LocalProxy is designed for local development and quick prototyping. For production — where you need session management, API governance, PDF extraction, BYOK key encryption, rate limiting, and data flow monitoring — replace it with a ProxyClient connected to a LocalFlow proxy server.

The proxy handles:

  • Security and session management — authenticates users against your business systems (CRM, ERP, or guest sessions), manages session tokens, and encrypts API keys so secrets are never exposed to the browser
  • API governance — defines which external APIs formulas may call; supports BYOK, per-source throttling, URL whitelisting, and OAuth 2.0 token exchange
  • Server-side edge services — PDF text extraction, OCR, and other tasks better suited to a server than a browser
  • LLM bridge — decrypts the user's API key at request time and forwards generation requests to the LLM
  • Data flow monitoring — tracks and audits what data enters and leaves the sandbox

LocalAssistant accepts any implementation of the Proxy interface — switching from LocalProxy to ProxyClient requires no other changes.

Connect to the proxy

import { ProxyClient, LocalAssistant } from '@localflow/core'

const proxy = new ProxyClient('https://your-proxy.example.com')

// Authenticate — stores the session token on the proxy instance
await proxy.connect('odoo', { url, database, login, password })
// or for a public/guest session:
await proxy.connect('public', {})

// Save the token so the session survives a page reload
localStorage.setItem('proxy-token', proxy.token!)

// Restore on next load
const proxy = new ProxyClient('https://your-proxy.example.com', localStorage.getItem('proxy-token'))
await proxy.getSessionInfo()  // throws if expired — re-authenticate if needed

const assistant = new LocalAssistant({ proxy, llm: { type: 'gemini' }, resultContainer: '#result' })

Quick testing: a hosted instance is available at https://backoffice.daquota.io/v1 — no account needed. You can start with a guest (public) session, or authenticate against your own CRM if you want to test with real data. That said, you probably don't want to point your production CRM at an instance you don't control; use a sandbox or test environment instead.

Self-hosting: for production use, run your own instance — see the localflow-proxy repository for setup instructions.

PDF extraction

PDF extraction requires a proxy (not available with LocalProxy).

// Extract text via the proxy, then load as a dataset
const { text, pageCount } = await proxy.extractPdf(pdfBuffer)
assistant.addPdfDataset('report.pdf', pdfBuffer, text, pageCount)

assistant.setActiveDataset('report.pdf')
const response = await assistant.prompt('Summarise the key figures')

Pass an optional searchString to receive only pages matching the query (plus one page of context either side):

const { text, pageCount } = await proxy.extractPdf(pdfBuffer, 'revenue')

Wire up external APIs (optional)

The proxy admin configures which external APIs analysis formulas may call. Users can opt in/out and supply their own API keys (BYOK) per API.

// Fetch the list of APIs the proxy admin has whitelisted
const apis = await assistant.fetchApiConfigs()

// Activate one for use in formulas
assistant.activateApi('overpass')

// If an API requires a user-supplied key (BYOK):
// pass the plain key — the assistant encrypts it via the proxy internally.
await assistant.setApiUserKey('my-api', plainApiKey)

// Persist API preferences whenever they change
assistant.on('prefs:change', (prefs) => {
  localStorage.setItem('api-prefs', JSON.stringify(prefs))
})

API Reference

LocalAssistant API reference

Constructor

new LocalAssistant(config: LocalAssistantConfig)
interface LocalAssistantConfig {
  proxy: Proxy             // any Proxy implementation — LocalProxy or ProxyClient
  llm: LLMConfig           // LLM backend configuration
  darkMode?: boolean       // passed to the formula sandbox (default: false)
  apiPreferences?: ApiPreference[]    // previously persisted prefs (from 'prefs:change')
  resultContainer?: ResultContainer   // where to render formula results
  sandboxPermissions?: string[]       // iframe sandbox flags (see defaults below)
  sandboxTheme?: Record<string, unknown>    // Tailwind theme object injected into the sandbox (see below)
  pdfFormulaRevision?: boolean        // silent self-correction on first PDF query (default: false)
  formulaHealingRetries?: number      // silent retries on JS syntax errors (default: 1)
}

interface LLMConfig {
  type: 'gemini' | string  // backend type — only 'gemini' is implemented today
  apiKey?: string          // encrypted key restored from storage — set via setLlmApiKey()
  model?: string           // model ID (default: 'gemini-3-flash-preview')
}

// resultContainer accepts any of:
type ResultContainer = HTMLElement | string | (() => HTMLElement | null)
//                     ^ element     ^ selector  ^ factory (evaluated at render time)

// Default sandbox permissions:
const DEFAULT_SANDBOX = [
  'allow-scripts', 'allow-downloads', 'allow-modals',
  'allow-popups',  'allow-popups-to-escape-sandbox',
]

Configuration

Property / Method Type / Returns Description
assistant.llm LLMConfig Read or replace the LLM configuration. Emits 'llm:change'.
assistant.darkMode boolean Toggle dark mode in the analysis sandbox.
assistant.resultContainer ResultContainer Where formula results are rendered.
assistant.sandboxPermissions string[] iframe sandbox flags.
assistant.pdfFormulaRevision boolean When true, the first formula for a new PDF is silently run, its logs collected, and a second LLM call revises it before anything is shown to the user.
sandboxTheme (constructor only) Record<string, unknown> Tailwind theme object injected into the sandbox CDN config before it initialises. Use it to align generated UI with your host app's palette: override gray shades for dark-mode card surfaces, define a primary color referenceable via bg-primary / text-primary, etc. The sandbox body also picks up dark:bg-gray-900 dark:text-gray-100 automatically, so setting gray[900] and gray[100] covers the full background. Works with any host framework — just translate your design tokens to Tailwind color values.
assistant.proxy (read-only) Proxy The proxy implementation passed at construction.
setLlmApiKey(plainKey) Promise<void> Encrypt a plain API key via the proxy and store it. Emits 'llm:change'.

Datasets

Datasets are ordered key-value pairs: name → array of row objects (tabular) or PDF document (with extracted text). The active dataset is exposed as the data variable inside formula code; all datasets are accessible via datasets['name'].

Method Returns Description
addDataset(name, rows) void Add or replace a tabular dataset. First added becomes active.
addPdfDataset(name, buffer, extractedText, pageCount) void Add a PDF document. Pass the text returned by proxy.extractPdf().
removeDataset(name) void Remove a dataset. Active dataset moves to next available.
updateDataset(name, rows) void Replace rows for an existing dataset.
getDataset(name) rows | undefined Read rows for a named dataset.
getDatasets() Record<string, rows[]> All datasets as a plain object.
setActiveDataset(name) void Mark a dataset as active (data variable in formulas).
getActiveDataset() { name, type, rows, columns } | null Current active dataset. type is 'table' or 'pdf'.
getActivePdfBuffer() ArrayBuffer | null Raw bytes of the active PDF.
getActivePdfExtractedText() string Extracted text of the active PDF.
getActivePdfPageCount() number Page count of the active PDF.
clearDatasets() void Remove all datasets and reset active.
assistant.addDataset('Sales Q1', salesRows)
assistant.addDataset('Products', productRows)
assistant.setActiveDataset('Sales Q1')

const active = assistant.getActiveDataset()
// { name: 'Sales Q1', rows: [...], columns: ['id', 'product', 'amount', ...] }

External APIs

The proxy admin configures which external APIs analysis formulas may call. Users can opt in/out and supply their own API keys (BYOK) per API.

Method Returns Description
fetchApiConfigs() Promise<ApiConfig[]> Fetch available APIs from the proxy and store them.
setApiConfigs(configs) void Set API configs without a network call.
getApiConfigs() ApiConfig[] Currently stored API configs.
setApiPreferences(prefs) void Bulk-set user preferences (enabled flags + BYOK keys).
getApiPreferences() ApiPreference[] Current user preferences.
activateApi(id) void Enable an API for use in formulas.
deactivateApi(id) void Disable an API.
setApiUserKey(id, plainKey) Promise<void> Encrypt a BYOK key via the proxy and store it. Pass the plain key — encryption is handled internally.
getActivatedApis() ActivatedApi[] APIs that are currently active (forced or user-enabled).

Conversation

Method Returns Description
prompt(message, opts?) Promise<AssistantResponse> Send a user message. Builds system prompt, calls the LLM, appends to history, emits 'message'.
getHistory() ConversationTurn[] Full conversation history.
setHistory(turns) void Replace the conversation history (e.g. to restore a session).
appendHistory(turn) void Append a single turn.
clearHistory() void Reset conversation to empty.
getLastFormula() string | null Formula code from the most recent model response.
buildCurrentSystemPrompt(example?) string Build the system prompt for the current state without sending it.

prompt() options

await assistant.prompt('Break down revenue by region', {
  exampleAnalysis: {      // inject a catalog analysis as a system-prompt example
    formula: '...',
    title: 'Revenue by country (bar chart)',
    description: '...',
  },
})

AssistantResponse shape

interface AssistantResponse {
  answer: string          // HTML description shown before the formula runs
  formula: string         // JS code to execute in the sandbox
  title?: string          // short title for the analysis
  description?: string    // longer functional description
  dependencies?: {        // declared data dependencies
    data: string[]        // columns accessed on the active dataset
    datasets: Record<string, string[]>  // columns accessed per named dataset
  }
  systemPrompt?: string   // snapshot of the system prompt used
}

executeFormula(formula)

Renders a formula in the configured resultContainer. Creates the sandboxed iframe, applies sandboxPermissions, wires up the proxy fetch relay, and emits formula:done / formula:error. Called automatically by prompt() when resultContainer is set.

// Manual execution (e.g. replaying a catalog analysis)
assistant.executeFormula(savedAnalysis.formula)

destroy()

Removes the managed iframe and cleans up all event listeners. Call when the assistant is no longer needed.


Analysis match hook

Register a function that the assistant calls before each LLM request to find a semantically similar past analysis. The result is injected into the system prompt as an example, improving output quality for recurring analysis patterns.

assistant.setAnalysisMatchHook(async (query, context) => {
  // context: { history, datasets, activeDatasetName, activeColumns }
  const best = await mySemanticSearch(query, myCatalog)
  if (!best || best.score < 0.3) return null
  return { analysis: best.formula, score: best.score }
})

// Call it directly (e.g. to check before showing a suggestion UI):
const match = await assistant.resolveAnalysisMatch('Show portfolio heatmap')

Events

assistant.on('message', (response: AssistantResponse) => {
  console.log('Formula ready:', response.formula)
})

assistant.on('dataset:change', () => {
  renderTabBar(assistant.getDatasets())
})

// Persist LLM config whenever it changes
assistant.on('llm:change', (llm: LLMConfig) => {
  if (llm.apiKey) localStorage.setItem('llm-key', llm.apiKey)
})

// Persist API preferences whenever they change — covers activateApi, deactivateApi,
// setApiPreferences, and setApiUserKey (which encrypts BYOK keys before storing).
assistant.on('prefs:change', (prefs: ApiPreference[]) => {
  localStorage.setItem('api-prefs', JSON.stringify(prefs))
})

assistant.off('message', myListener)
Event Payload When
message AssistantResponse After each successful LLM response
dataset:change (none) After any dataset add / remove / update / clear
formula:done { data: unknown } Formula finished executing; data is the formula's returned data field
formula:error { message: string } Formula threw or called console.error
llm:change LLMConfig After setLlmApiKey() or assistant.llm = .... The payload contains the encrypted key — safe to persist and pass back via llm.apiKey at construction.
prefs:change ApiPreference[] After any API preference mutation (activateApi, deactivateApi, setApiPreferences, setApiUserKey). The payload contains encrypted BYOK keys — safe to persist as-is and pass back via apiPreferences at construction.
configs:change ApiConfig[] After API configs are loaded or updated via fetchApiConfigs() or setApiConfigs().
history:reset (none) Conversation history was cleared (e.g. because the active PDF changed).
api:blocked { url, hostname, apiConfig | null } Formula called a URL not in the activated API list and the request failed. apiConfig is set if the API is known but inactive, null if completely unknown.
api:error { url, hostname, apiConfig, reason } An active API returned a JSON error body (e.g. expired key, quota exceeded). reason is extracted from the response.
data:local { data: string, action: string } An action completed entirely in the browser. E.g. file loaded from disk, formula executed in sandbox. Emitted by the app layer.
data:proxy { data: string, action: string } Data was sent to the proxy server but not to the LLM. E.g. PDF extraction. Emitted by the app layer.
data:llm LlmDataPayload Data was forwarded to the LLM. Categorical payload — no display strings. kind is 'table', 'pdf', or 'text'; always includes query (raw user message) and dataset (file/dataset name). Table events include columns: number; PDF events include pages: number. Import the type: import type { LlmDataPayload } from '@localflow/core'.
data:api-proxy ApiProxyPayload A formula fetch was routed through the api-proxy — fired on every call (success and failure). Includes url, method, body (raw request body — what left the browser), apiConfig (matched API definition or null if unrecognised), and status (HTTP response status; undefined on network error). Import the type: import type { ApiProxyPayload } from '@localflow/core'.

Proxy API reference

Proxy is the interface that both LocalProxy and ProxyClient implement. LocalAssistant depends only on this interface — you can supply any conforming implementation.

import type { Proxy } from '@localflow/core'

interface Proxy {
  readonly token: string | null

  isConnected(): boolean
  connect(type?: string, config?: Record<string, unknown>): Promise<void>
  getSessionInfo(): Promise<unknown>

  isEncrypted(str: string): boolean
  encryptMessage(message: string): Promise<string>
  decryptMessage(message: string): Promise<string>

  callGenai(payload: GenaiPayload): Promise<Response>

  getApiConfigs(): Promise<ApiConfig[]>
  proxyApiCall(url: string, method: string, headers: Record<string, string>, body: string): Promise<Response>

  extractPdf(buffer: ArrayBuffer, searchString?: string): Promise<{ text: string; pageCount: number }>

  listObjectTypes(): Promise<CrmObjectType[]>
  getObjectMetadata(objectType: string): Promise<CrmObjectType>
  getData(objectType: string, fields: string[]): Promise<Record<string, unknown>[]>
}

LocalProxy

Browser-only implementation. No server required — suitable for local development, testing, and demos.

import { LocalProxy } from '@localflow/core'

new LocalProxy(config?: {
  apis?: ApiConfig[]
  geminiBaseUrl?: string
  geminiApiKey?: string          // baked-in key used when no key is set on the assistant
  rateLimit?: {
    maxPerDay: number            // per-browser daily cap (tracked in localStorage)
    storageKey?: string          // localStorage key prefix — defaults to '_lf_rl'
  }
})

geminiApiKey — a fallback key used when the assistant has no key set. Useful for demos where you want users to try the app without supplying their own key. The user's own key (set via assistant.setLlmApiKey()) always takes precedence.

rateLimit — per-browser daily cap enforced before each callGenai call. When the limit is reached, callGenai throws LocalProxyRateLimitError. Pair with geminiApiKey to prevent a single user from exhausting a shared demo key for everyone.

import { LocalProxy, LocalProxyRateLimitError, LocalAssistant } from '@localflow/core'

const proxy = new LocalProxy({
  geminiApiKey: 'AIza...',       // shared demo key — visible in DevTools, use a limited one
  rateLimit: { maxPerDay: 20 },  // generous enough to evaluate, stingy enough to protect the key
})
const assistant = new LocalAssistant({ proxy, llm: { type: 'gemini' } })

try {
  await assistant.prompt('Show me the top 10 by revenue')
} catch (err) {
  if (err instanceof LocalProxyRateLimitError) {
    // show UI asking the user to enter their own key
  }
}
Behaviour Notes
callGenai Checks rate limit, then calls Gemini directly from the browser. Uses geminiApiKey if no key is set on the assistant.
encryptMessage / decryptMessage No-ops — the key is stored and used as plain text
extractPdf Throws — PDF extraction is not available in standalone mode
listObjectTypes / getObjectMetadata / getData Return empty results — no CRM access
connect / getSessionInfo No-ops — no session management

Not for production use. LocalProxy emits a console warning to remind you.

ProxyClient

HTTP client for a LocalFlow proxy server. Implements the full Proxy interface and adds session management.

import { ProxyClient } from '@localflow/core'

const proxy = new ProxyClient(baseUrl, token?)
Parameter Type Description
baseUrl string LocalFlow proxy base URL (e.g. 'https://backoffice.daquota.io/v1')
token string | null Optional — restore a previously saved session token

Session

Method Returns Description
connect(type, config) Promise<void> Authenticate and store the session token. type is 'odoo', 'salesforce', or 'public'. config contains connector-specific credentials.
getSessionInfo() Promise<unknown> Verify the current session. Throws if expired or not authenticated.
isConnected() boolean true if a session token is stored.
proxy.token string | null The current session token — set by connect(), readable for persistence.
proxy.baseUrl string The proxy base URL — mutable, can be changed before calling connect().

Encryption

Method Returns Description
isEncrypted(str) boolean true if the string is in the proxy-encrypted format.
encryptMessage(plainText) Promise<string> Encrypt a string via the proxy. The result is safe to store and pass to the assistant.
decryptMessage(cipherText) Promise<string> Decrypt a proxy-encrypted string.

You rarely need to call these directly — assistant.setLlmApiKey() and assistant.setApiUserKey() handle encryption internally.

PDF extraction

Method Returns Description
extractPdf(buffer, searchString?) Promise<{ text, pageCount }> Extract text from a PDF via the proxy. Pass an optional searchString to receive only pages matching the query (plus one page of context either side).

CRM

Method Returns Description
listObjectTypes() Promise<CrmObjectType[]> List all available CRM object types (without fields).
getObjectMetadata(objectType) Promise<CrmObjectType> Fetch full metadata for one object type, including its fields.
getData(objectType, fields) Promise<Record<string, unknown>[]> Fetch rows for a CRM object type.
const types = await proxy.listObjectTypes()
const meta  = await proxy.getObjectMetadata('res.partner')
const rows  = await proxy.getData('res.partner', ['name', 'email', 'country_id'])

Building

cd localflow-core
npm install
npm run build   # tsc → dist/
npm run dev     # tsc --watch (development)

The standalone tsc build produces dist/ with .js and .d.ts files and is needed when publishing the library to npm. During development inside the monorepo, localflow-app uses a Vite alias pointing to the TypeScript source directly — no pre-build required.

Package structure

localflow-core/
├── package.json          # name: "@localflow/core"
├── tsconfig.json         # emits dist/ with .js + .d.ts
└── src/
    ├── index.ts          # public exports
    ├── LocalAssistant.ts # the core class
    ├── Proxy.ts          # Proxy interface contract
    ├── LocalProxy.ts     # browser-only Proxy implementation
    ├── ProxyClient.ts    # HTTP proxy client
    └── types.ts          # all public TypeScript interfaces

Roadmap highlights

  • Pluggable LLM backends (OpenAI, Anthropic, Mistral, Ollama)
  • Interactive formula results (action buttons returned by formulas)
  • Async / streaming formula execution

Recently shipped

  • Published to npm — available as @localflow/core
  • PDF document support — PDFs as first-class datasets; text extracted via the proxy, full document text injected into LLM context
  • Data flow awarenessdata:local / data:proxy / data:llm events; animated status chip in the header; session history popover; sandbox safety indicator
  • Configurable proxy URL — proxy URL configurable at runtime; persisted in localStorage
  • CRM connectors — Odoo and Salesforce authentication and data loading via ProxyClient
  • Formula self-healingformulaHealingRetries config option; syntax errors are caught and silently retried before returning to the caller (default: 1)

License

Apache 2.0 — see LICENSE for the full text.

Copyright (c) 2026 LocalFlow (localflow.fr)