https://github.com/NeuroSkill-com/skill
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/NeuroSkill-com/skill with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/NeuroSkill-com/skill'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/neuroskill-com--skill)HTML
<a href="/listings/neuroskill-com--skill"><img src="/api/listings/neuroskill-com--skill/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
These steps run a script from the network that findsafeskills does not scan.
Product version lives in the repo-root [`VERSION`](VERSION) file (`npm run bump` keeps `package.json`, `src-tauri/tauri.conf.json`, and `src-tauri/Cargo.toml` in sync). Release builds enable one daemon OS umbrella (`apple` / `linux` / `windows`). PR CI runs clippy/tests; signed product builds run on release tags or Preview Build. Details: [CONTRIBUTING.md](CONTRIBUTING.md) · [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md).
`npm run setup` checks that Rust is installed, offers to install Node.js 22 into `~/.local` if it is missing or older than 22.17, offers to install CMake, protoc and the other native build tools (Homebrew on macOS, the system package manager on Linux), and installs the JavaScript dependencies with `npm ci`, the same way CI does. On Windows, follow [docs/WINDOWS.md](docs/WINDOWS.md) instead.
Install the [Hugging Face CLI](https://huggingface.co/docs/huggingface_hub/guides/cli) (`curl -LsSf https://hf.co/cli/install.sh | bash` on macOS/Linux, `powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex"` on Windows), then:
npm run setup -- --yes hf download Zyphra/ZUNA npm run tauri dev
Build production app:
npm run tauri:build
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 4,351 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # NeuroSkill™ CLI — Complete Reference
- NeuroSkill™ exposes a real-time EEG analysis API through a local WebSocket server and an HTTP tunnel.
- The `cli.ts` script is the fastest way to query it from a terminal, shell script, or any
- automation pipeline.
- ---
- ## Contents
- 1. [Supported Devices](#supported-devices)
- 2. [Transport — WebSocket & HTTP](#transport--websocket--http)
- 3. [Quick Start](#quick-start)
- 4. [Output Modes](#output-modes)
- - [Default — summary only](#default-no-flag--human-readable-summary-only)
- - [`--json` — raw JSON, pipe-safe](#--json--raw-json-only-pipe-safe)
- - [`--full` — summary and JSON](#--full--human-readable-summary-and-colorized-json)
- - [What `--full` reveals](#what---full-reveals)
- 5. [Global Options](#global-options)
- 6. [Polling with `status`](#polling-with-status)
- 7. [Commands](#commands)
- - [status](#status)
- - [session](#session)
- - [sessions](#sessions)
- - [say](#say)
- - [label](#label)
- - [hooks](#hooks)
- - [search-labels](#search-labels)
- - [interactive](#interactive)
- - [search](#search)
- - [compare](#compare)
- - [sleep](#sleep)
- - [sleep-schedule](#sleep-schedule)
- - [umap](#umap)
- - [listen](#listen)
- - [notify](#notify)
- - [calibrations](#calibrations)
- - [calibrate](#calibrate)
- - [timer](#timer)
- - [health](#health)
- - [dnd](#dnd)
- - [raw](#raw)
- - [search-images](#search-images)
- - [screenshots-around](#screenshots-around)
- - [screenshots-for-eeg](#screenshots-for-eeg)
- - [eeg-for-screenshots](#eeg-for-screenshots)
- 8. [Screenshots](#screenshots)
- 9. [Data Reference](#data-reference)
- - [EEG Band Powers](#eeg-band-powers)
- - [EEG Ratios & Indices](#eeg-ratios--indices)
- - [Core Scores](#core-scores)
- - [Complexity Measures](#complexity-measures)
- - [PPG / Heart Rate Variability](#ppg--heart-rate-variability)
- - [Motion & Artifacts](#motion--artifacts)
- - [Sleep Stages](#sleep-stages)
- - [Migraine EEG Correlate](#migraine-eeg-correlate)
- - [Consciousness Metrics](#consciousness-metrics)
- 10. [Use-Case Recipes](#use-case-recipes)
- - [Focus & Productivity](#focus--productivity)
- - [Stress & Anxiety](#stress--anxiety)
- - [Sleep Quality](#sleep-quality)
- - [Cognitive Load](#cognitive-load)
- - [Meditation & Relaxation](#meditation--relaxation)
- - [Comparing Two Sessions](#comparing-two-sessions)
- - [Time-Range Queries](#time-range-queries)
- - [Automation & Scripting](#automation--scripting)
- ---
- ## Supported Devices
- NeuroSkill™ supports multiple EEG headsets. The CLI and API work identically
- regardless of which device is connected — all commands, scores, and metrics are
- device-agnostic.
- | Device | Channels | Sample Rate | Connection | Notes |
- |---|---|---|---|---|
- | **Muse** (S, 2, 2016) | 4 (TP9, AF7, AF8, TP10) | 256 Hz | BLE | Default device. PPG + IMU included. |
- | **OpenBCI Ganglion** | 4 | 200 Hz | BLE | Open-source research-grade board. |
- | **OpenBCI Cyton / Cyton+Daisy** | 8 / 16 | 250 Hz | Serial / WiFi | Full 10-20 montage capable. |
- | **Neurable MW75 Neuro** | 12 (FT7/T7/TP7/CP5/P7/C5, FT8/T8/TP8/CP6/P8/C6) | 500 Hz | BLE + RFCOMM | Noise-cancelling headphones with EEG. Behind `mw75-rfcomm` feature flag. |
- | **Vital Neuro** | 3 (ch1–ch3) | 250 Hz | BLE | Headphones with EEG; audio runs over a separate Bluetooth Classic link. Accelerometer + battery. Device reports no electrode montage. |
- | **RE-AK Nucleus Hermes** | 8 (Fp1, Fp2, AF3, AF4, F3, F4, FC1, FC2) | 250 Hz | BLE GATT | ADS1299 + 9-DOF IMU. |
- | **Emotiv** (EPOC/Insight/Flex/MN8) | 14 / 5 / 32 | 128 Hz | Cortex WebSocket | IMU included. Connected via Emotiv Cortex API. |
- | **IDUN Guardian** | 1 (bipolar in-ear) | 250 Hz | BLE | Single-channel earbud EEG + 6-DOF IMU. |
- | **Mendi** | — (fNIRS optical) | — | BLE | Frontal fNIRS headband with IMU + battery telemetry. Not traditional EEG. |
- | **Cognionics / CGX** (Quick-20/32r/8r, AIM-2, Patch) | 2–30 | up to 500 Hz | USB Serial (FTDI) | Research-grade; full 10-20 montage on Quick-20+. IMU on r/m variants. |
- | **AttentivU** | 4 ExG | 250 Hz | BLE | EEG glasses with 9-axis IMU. |
- | **BrainBit** (Original, 2, Pro, Flex 4/8) | 4 (O1, O2, T3, T4) | 250 Hz | BLE (NeuroSDK2) | Consumer EEG headband. |
- | **g.tec Unicorn Hybrid Black** | 8 | 250 Hz | BLE (Unicorn API) | Research-grade headset with IMU. |
- | **NeuroField Q21** | 20 | 256 Hz | PCAN-USB (CAN bus) | Full 10-20 montage. |
- | **BrainMaster** (Atlantis/Discovery/Freedom) | 2–24 | 256 Hz | USB Serial | Neurofeedback amplifiers. Discovery/Freedom support up to 24 channels. |
- | **NeuroSky MindWave** | 1 (Fp1) | 512 Hz | Serial (ThinkGear) | Single-channel consumer headset. |
- | **Neurosity** (Crown / Notion) | 8 (CP3, C3, F5, PO3, PO4, F6, C4, CP4) | 256 Hz | Cloud-streamed | IMU included. |
- | **Brain Products BrainVision** | 16 | 500 Hz | TCP/IP (RDA) | Research-grade; full 10-20 montage. |
- The DSP pipeline dynamically scales to the active channel count (1–32).
- Inactive channels have zero overhead.
- ---
- ## Transport — WebSocket & HTTP
- NeuroSkill™ runs a local server (auto-discovered via mDNS or `lsof`). All commands work over
- **both** transports; the CLI picks the best one automatically.
- ### WebSocket (`ws://127.0.0.1:<port>`)
- - **Full-duplex, low-latency.** Best for live data, event streaming, and polling loops.
- - Commands are JSON messages sent over the socket; responses arrive as JSON messages.
- - Supports real-time broadcast events (EEG packets, scores, label-created, …).
- - Used by default when the server is reachable.
- ```
- # Force WebSocket:
- node cli.ts status --ws
- # Direct WebSocket from any language (wscat example):
- wscat -c ws://127.0.0.1:8375
- > {"command":"status"}
- < {"command":"status","ok":true,"device":{...},"scores":{...},...}
- ```
- ### HTTP (`http://127.0.0.1:<port>/`)
- - **Request / response only.** No live streaming, no broadcast events.
- - All commands are `POST /` with a JSON body; the response is JSON.
- - Useful from `curl`, Python `requests`, Node `fetch`, or any HTTP client.
- - Automatic fallback when the WebSocket is unreachable.
- ```bash
- # Force HTTP:
- node cli.ts status --http
- # curl equivalent of every CLI command:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"status"}'
- # Extract a single field with jq:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"status"}' | jq '.scores.relaxation'
- ```
- ### Auto-transport (default)
- When neither `--ws` nor `--http` is given, the CLI probes WebSocket first and silently
- falls back to HTTP. Informational lines are written to **stderr** (not stdout), so JSON
- piping is never polluted.
- ### Port Discovery
- The CLI finds the port automatically via:
- 1. `--port <n>` flag (explicit, skips all discovery)
- 2. mDNS (`_skill._tcp` service advertisement, 5 s timeout)
- 3. `lsof` / `pgrep` fallback (probes each TCP LISTEN port)
- ```bash
- node cli.ts status --port 62853 # skip discovery entirely
- ```
- ---
- ## Quick Start
- ```bash
- # Prerequisites (run once):
- npm install
- # Snapshot of everything:
- node cli.ts status
- # Pipe-friendly JSON output:
- node cli.ts status --json | jq '.scores'
- # Print full help with examples:
- node cli.ts --help
- ```
- > **Aliases:** `node cli.ts`, `npx tsx cli.ts`, and `./cli.ts` (after `chmod +x`) all work.
- ---
- ## Output Modes
- Every command has three output modes. Choose the one that suits your use case.
- ### Default (no flag) — human-readable summary only
- The CLI prints a structured, colored, human-readable summary to **stdout**.
- The underlying raw JSON response is **not printed** — it is discarded after the
- summary is rendered.
- ```bash
- node cli.ts status # colored summary, no JSON
- node cli.ts session 0 # trend table, no JSON
- node cli.ts sleep # stage counts, no JSON
- ```
- This is the fastest way to read results at a glance, but data that the summary
- doesn't surface — such as per-epoch arrays, full reference objects, or every
- metric field — is silently dropped. See [What `--full` reveals](#what---full-reveals)
- for a command-by-command breakdown.
- ---
- ### `--json` — raw JSON only, pipe-safe
- `print()` calls are suppressed entirely; only `printResult()` fires.
- Output is plain JSON with no ANSI codes, written to **stdout**.
- Informational lines (transport, connection, mDNS discovery) go to **stderr** and
- never pollute the JSON stream.
- ```bash
- node cli.ts status --json # full JSON, no summary
- node cli.ts status --json | jq '.scores.relaxation' # pipe to jq
- node cli.ts sleep --json | jq '.summary'
- node cli.ts search --json | jq '.result.results[0].neighbors'
- node cli.ts umap --json | jq '.result.points | length'
- ```
- Use `--json` whenever you need to pipe output to another tool, parse it in a
- script, or feed it into an API.
- ---
- ### `--full` — human-readable summary **and** colorized JSON
- Both `print()` and `printResult()` fire. The human-readable summary prints first,
- then the complete colorized JSON response is appended below it.
- ```bash
- node cli.ts status --full # summary + full colorized JSON
- node cli.ts session 0 --full # trend table + raw first/second/trends objects
- node cli.ts sleep --full # stage counts + full epochs[] array
- node cli.ts umap --full # cluster analysis + full points[] array
- node cli.ts search --full # match summary + all neighbors for every query epoch
- ```
- `--full` is the inspection mode: use it when you want to see which exact fields the
- server returned, discover keys the summary omits, or verify data before writing a
- `--json` pipeline.
- > **Colors:** `--full` uses ANSI-colored JSON (keys in blue, strings in green,
- > numbers in cyan). If you need plain text from `--full`, pipe through `sed 's/\x1b\[[0-9;]*m//g'`
- > or just switch to `--json`.
- ---
- ### What `--full` reveals
- The following data exists in the server response but is **omitted by the default
- summary**. It is only visible with `--full` (colorized) or `--json` (plain).
- #### `status`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `scores.faa`, `scores.tar`, `scores.bar` … | numbers | EEG ratios and spectral indices not surfaced in the summary's Scores section |
- | `calibration.actions[]` | array | Full ordered list of calibration step objects (name, duration, …) |
- | `labels.recent[]` | array | Full label objects; summary only prints text + timestamp |
- | `hooks.latest_trigger` | object | Most recent hook trigger across all hooks: `{ hook, triggered_at_utc, distance, label_id, label_text }`. The summary shows hook name, timestamp, and distance; the JSON has the full object. |
- | `history.today_vs_avg` | object | Per-metric today-vs-7-day-avg comparison table (metric, today, avg_7d, delta_pct, direction) |
- | `apps` | object | Most-used apps by window-switch count. Contains `top_all_time`, `top_24h`, `top_7d` arrays. Each entry: `{ app_name, switches, last_seen }`. |
- | `labels.top_all_time` | array | Most frequent label texts (all time). Each: `{ text, count }`. |
- | `labels.top_24h` / `labels.top_7d` | array | Most frequent label texts in the last 24 h / 7 d. |
- | `labels.embedded` | number | Count of labels with text embeddings computed. |
- | `screenshots` | object | Screenshot/OCR summary counts: `total`, `with_embedding`, `with_ocr`, `with_ocr_embedding`. Also `top_apps_all_time` and `top_apps_24h` arrays (each: `{ app_name, count }`). |
- ```bash
- node cli.ts status --json | jq '.history.today_vs_avg'
- node cli.ts status --json | jq '.calibration.actions'
- node cli.ts status --json | jq '.labels.recent'
- node cli.ts status --json | jq '.hooks.latest_trigger'
- node cli.ts status --json | jq '.apps.top_all_time[:5]'
- node cli.ts status --json | jq '.apps.top_24h'
- node cli.ts status --json | jq '.labels.top_all_time'
- node cli.ts status --json | jq '.screenshots'
- node cli.ts status --json | jq '.screenshots.top_apps_24h'
- ```
- #### `session`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `first` | object | Every metric averaged over the **first half** of the session |
- | `second` | object | Every metric averaged over the **second half** |
- | `trends` | object | Direction string (`"up"` / `"down"` / `"flat"`) for every metric key |
- | `metrics` | object | All ~50 metric fields — the summary only prints a curated subset |
- ```bash
- node cli.ts session 0 --json | jq '.metrics' # all metric averages
- node cli.ts session 0 --json | jq '.trends' # all trend directions
- node cli.ts session 0 --json | jq '{r1: .first.relaxation, r2: .second.relaxation}'
- node cli.ts session 0 --json | jq '[.trends | to_entries[] | select(.value == "up") | .key]'
- ```
- #### `sessions`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `sessions[]` | array | Raw session objects — the summary formats them into a table but the JSON contains the same data |
- ```bash
- node cli.ts sessions --json | jq '.sessions[0]'
- # → { "day": "20260224", "start_utc": 1740412800, "end_utc": 1740415510, "n_epochs": 541 }
- ```
- #### `search`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `result.results[]` | array | Full list of query epochs, each with its complete `neighbors[]` array. The summary only shows the 5 closest overall — `--full` shows every neighbor for every query epoch. |
- | `result.analysis.temporal_distribution` | object | Hour-of-day match counts (the bar chart in the summary, but as raw numbers) |
- | `result.analysis.top_days` | array | `[["YYYYMMDD", count], …]` |
- ```bash
- node cli.ts search --json | jq '.result.results | length' # query epoch count
- node cli.ts search --json | jq '.result.results[0].neighbors' # all neighbors for epoch 0
- node cli.ts search --json | jq '[.result.results[].neighbors[]] | sort_by(.distance) | .[0]'
- node cli.ts search --json | jq '.result.analysis.temporal_distribution'
- ```
- #### `compare`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `a` | object | All ~50 averaged metrics for session A |
- | `b` | object | All ~50 averaged metrics for session B |
- | `sleep_a` / `sleep_b` | objects | Full sleep staging summary for each range |
- | `insights.deltas` | object | Full delta table for every metric (not just the key ones shown in the summary) |
- | `umap` | object | Enqueued job info: `job_id`, `estimated_secs`, `n_a`, `n_b` |
- ```bash
- node cli.ts compare --json | jq '.a' # all metrics for A
- node cli.ts compare --json | jq '.b' # all metrics for B
- node cli.ts compare --json | jq '.insights.deltas' # every metric delta
- node cli.ts compare --json | jq '.insights.deltas | to_entries | sort_by(.value.pct) | reverse'
- node cli.ts compare --json | jq '.umap.job_id' # use with umap --json
- ```
- #### `sleep`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `epochs[]` | array | Per-epoch classification: `{ utc, stage, rel_delta, rel_theta, rel_alpha, rel_beta }` for every 5-second window. Can be thousands of entries for a full night. |
- ```bash
- node cli.ts sleep --json | jq '.epochs | length' # total epochs
- node cli.ts sleep --json | jq '.epochs[0]' # first epoch
- node cli.ts sleep --json | jq '[.epochs[] | select(.stage == 3)] | length' # N3 epochs
- node cli.ts sleep --json | jq '[.epochs[] | {utc: .utc, stage: .stage}]' # hypnogram data
- ```
- #### `umap`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `result.points[]` | array | 3D coordinates for every embedding epoch: `{ x, y, z, session, utc, label? }`. Typically 500–2000+ entries. |
- ```bash
- node cli.ts umap --json | jq '.result.points | length'
- node cli.ts umap --json | jq '.result.points[0]'
- # → { "x": 1.23, "y": -0.45, "z": 2.01, "session": "A", "utc": 1740380105 }
- node cli.ts umap --json | jq '[.result.points[] | select(.session == "B")]'
- node cli.ts umap --json | jq '[.result.points[] | select(.label != null)]' # labeled points only
- ```
- #### `search-labels`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `results[].eeg_metrics` | object | Full EEG metrics object for the label window — the summary shows only 5 fields; the JSON has all available metrics |
- | `results[].context` | string | Long-context string (if set) — only a truncated preview is shown in the summary |
- ```bash
- node cli.ts search-labels "deep focus" --json | jq '.results[0].eeg_metrics'
- node cli.ts search-labels "stress" --json | jq '[.results[].eeg_metrics.tbr]'
- node cli.ts search-labels "meditation" --json | jq '.results[0].context'
- ```
- #### `interactive`
- | Hidden field | Type | Contents |
- |---|---|---|
- | `nodes[]` | array | All graph nodes — the summary prints each layer; `--json` gives the raw array with all fields |
- | `edges[]` | array | All graph edges with `from_id`, `to_id`, `distance`, `kind` |
- | `dot` | string | Complete Graphviz DOT source — only accessible via `--dot` or `--json` (never printed in default or `--full`) |
- | `svg` | string | Pre-rendered SVG — PCA-scatter layout for found_labels |
- | `svg_col` | string | Pre-rendered SVG — column-per-EEG-parent layout |
- | `svg_3d` | string | Pre-rendered SVG — 3-D perspective-projected view of all nodes including screenshots (dark theme with depth cues) |
- | `nodes[].eeg_metrics` | object | Full EEG metrics for `text_label` nodes — the summary shows 5 fields; JSON has all |
- | `nodes[].proj_x/y/z` | numbers | 3-D PCA coordinates (normalised [-1, 1]) for all nodes with text embeddings |
- | `nodes[].filename` | string | Screenshot image path (screenshot nodes only) |
- | `nodes[].app_name` | string | Application name at capture time (screenshot nodes only) |
- | `nodes[].window_title` | string | Window title at capture time (screenshot nodes only) |
- | `nodes[].ocr_text` | string | OCR-extracted text (screenshot nodes only) |
- | `nodes[].ocr_similarity` | number | Cosine similarity between query and OCR text (screenshot nodes only) |
- ```bash
- node cli.ts interactive "deep focus" --json | jq '.nodes | length'
- node cli.ts interactive "meditation" --json | jq '.edges | map(.kind) | unique'
- node cli.ts interactive "anxiety" --json | jq '[.nodes[] | select(.kind == "text_label") | .text]'
- node cli.ts interactive "coding" --json | jq '[.nodes[] | select(.kind == "screenshot") | {file: .filename, app: .app_name}]'
- node cli.ts interactive "focus" --dot | dot -Tsvg > graph.svg # visualize with graphviz
- node cli.ts interactive "stress" --dot | dot -Tpng > graph.png
- node cli.ts interactive "relaxed" --json | jq '.dot' -r | dot -Tsvg > graph.svg # same via --json
- node cli.ts interactive "work" --json | jq '.svg_3d' -r > graph_3d.svg # 3D perspective SVG
- ```
- ---
- #### `say`
- Like `notify`, `say` produces only a one-line confirmation in default mode.
- | Hidden field | Type | Contents |
- |---|---|---|
- | `ok` | boolean | Confirmation that the utterance was enqueued |
- | `spoken` | string | Echo of the text that was sent to TTS |
- | `voice` | string | Voice name used (only present when `--voice` was specified) |
- ```bash
- node cli.ts say "Eyes open" --json
- # → { "command": "say", "ok": true, "spoken": "Eyes open" }
- ```
- ---
- #### `calibrations`
- The `calibrations` summary formats profiles into a table but the JSON contains
- the full profile objects with all actions, durations, and settings.
- | Hidden field | Type | Contents |
- |---|---|---|
- | `profiles[].actions[]` | array | Full ordered list of action objects (name, duration_secs) |
- | `profiles[].break_duration_secs` | number | Break between action loops |
- | `profiles[].auto_start` | boolean | Whether the profile auto-starts on window open |
- ```bash
- node cli.ts calibrations --json | jq '.profiles[0].actions'
- node cli.ts calibrations get 3 --json | jq '.profile'
- ```
- ---
- #### `dnd`
- The `dnd` summary prints a rich visual status (bars, scores, tips) but several
- raw fields are only visible via `--json`.
- | Hidden field | Type | Contents |
- |---|---|---|
- | `avg_score` | number | Current rolling average focus score (0–100) |
- | `sample_count` | number | How many focus score samples have been collected |
- | `window_size` | number | Target number of samples for the rolling window |
- | `mode_identifier` | string | DND automation mode identifier |
- | `dnd_active` | boolean | Whether this app activated DND |
- | `os_active` | boolean | Whether the OS reports DND as active |
- ```bash
- node cli.ts dnd --json | jq '{avg: .avg_score, threshold: .threshold, active: .dnd_active}'
- ```
- ---
- #### `notify`
- `notify` has almost no human-readable summary — only a one-line echo of the title and body.
- The entire JSON confirmation from the server is suppressed in default mode.
- | Hidden field | Type | Contents |
- |---|---|---|
- | `ok` | boolean | Confirmation that the OS notification was dispatched |
- | `command` | string | Echo of the command name (`"notify"`) |
- ```bash
- node cli.ts notify "done" --full
- # default output: ⚡ notify "done"
- # --full appends: { "command": "notify", "ok": true }
- node cli.ts notify "done" --json
- # → { "command": "notify", "ok": true }
- ```
- If `ok` is `false` the CLI exits with an error even in default mode, so `--full`
- or `--json` is only useful when you need the confirmation in a script:
- ```bash
- # Verify notification was delivered before continuing a script:
- node cli.ts notify "build finished" --json | jq -e '.ok' > /dev/null \
- && echo "notification sent" || echo "notification failed"
- ```
- ---
- #### `calibrate`
- `calibrate` has two hidden layers:
- **Layer 1 — the `list_calibrations` intermediate call.**
- When `--profile` is given, the CLI internally calls `list_calibrations` to resolve the
- profile name to a UUID. That response — which contains the **full list of all calibration
- profiles with their actions, durations, and settings** — is consumed internally and
- **never printed, not even with `--full`**. To inspect it, use `raw` or HTTP directly:
- ```bash
- # See all profiles and their full action sequences:
- node cli.ts raw '{"command":"list_calibrations"}' --json
- # or:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"list_calibrations"}' | jq '.'
- ```
- The `list_calibrations` response shape:
- ```jsonc
- {
- "command": "list_calibrations",
- "ok": true,
- "profiles": [
- {
- "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
- "name": "Eyes Open/Closed",
- "loop_count": 3,
- "break_duration_secs": 5,
- "auto_start": true,
- "actions": [
- { "name": "Eyes Open", "duration_secs": 20 },
- { "name": "Eyes Closed", "duration_secs": 20 }
- ]
- },
- // ... more profiles
- ]
- }
- ```
- **Layer 2 — the `run_calibration` confirmation.**
- The actual calibration trigger response is suppressed in default mode, just like `notify`.
- | Hidden field | Type | Contents |
- |---|---|---|
- | `ok` | boolean | Confirmation that the calibration window opened and started |
- | `command` | string | Echo of the command name (`"run_calibration"`) |
- ```bash
- node cli.ts calibrate --full
- # default output:
- # ⚡ calibrate
- # profile: Eyes Open/Closed (a1b2c3d4-…)
- # --full appends:
- # { "command": "run_calibration", "ok": true }
- node cli.ts calibrate --json
- # → { "command": "run_calibration", "ok": true }
- # Check all available profile names without starting calibration:
- node cli.ts raw '{"command":"list_calibrations"}' --json | jq '[.profiles[].name]'
- # Verify calibration started in a script:
- node cli.ts calibrate --profile "Eyes Open" --json | jq -e '.ok' > /dev/null \
- && echo "calibration started" || echo "failed — is a Muse connected?"
- ```
- ---
- #### `timer`
- Like `notify`, `timer` produces only a one-line header in default mode.
- The server confirmation is suppressed.
- | Hidden field | Type | Contents |
- |---|---|---|
- | `ok` | boolean | Confirmation that the focus-timer window opened and started |
- | `command` | string | Echo of the command name (`"timer"`) |
- ```bash
- node cli.ts timer --full
- # default output: ⚡ timer
- # --full appends: { "command": "timer", "ok": true }
- node cli.ts timer --json
- # → { "command": "timer", "ok": true }
- # Use in a script after a calibration block:
- node cli.ts calibrate --json | jq -e '.ok' > /dev/null \
- && node cli.ts timer --json | jq -e '.ok' > /dev/null \
- && echo "calibration + timer both started"
- ```
- ---
- #### `listen`
- | Hidden field | Type | Contents |
- |---|---|---|
- | events array | array | Full array of every raw broadcast event received. The summary only prints `event_type × count` (plus a dedicated 🪝 section for hook triggers); `--full` appends every packet. |
- | hook events | objects | Full `{ event: "hook", payload: { hook, scenario, distance, label_id, label_text, triggered_at_utc, command, text, context } }` for each Proactive Hook trigger — the summary shows hook name, distance, and matched label; `--json` gives the complete payload for scripting. |
- ```bash
- node cli.ts listen --seconds 10 --json | jq '[.[] | select(.event == "scores")]'
- node cli.ts listen --seconds 5 --json | jq '.[0]' # first event in full
- node cli.ts listen --seconds 60 --json | jq '[.[] | select(.event == "hook") | .payload]'
- ```
- ---
- ## Global Options
- | Flag | Description |
- |---|---|
- | `--port <n>` | Connect to an explicit port (skips mDNS) |
- | `--ws` | Force WebSocket; error if unreachable |
- | `--http` | Force HTTP REST; no live-event commands |
- | `--json` | Raw JSON only — no summary, no colors, pipe-safe |
- | `--full` | Human-readable summary **and** colorized full JSON appended below |
- | `--no-color` | Disable ANSI color output (also honoured via `NO_COLOR` env var or non-TTY stdout) |
- | `--version`, `-v` | Print CLI version and exit |
- | `--help`, `-h` | Show full help and exit |
- | `--poll <n>` | (`status` only) Re-poll every N seconds; keeps the socket open |
- | `--dot` | (`interactive` only) Graphviz DOT to stdout — pipe to `dot -Tsvg` |
- | `--trends` | (`sessions` only) Show first-half → second-half deltas |
- | `--mode <m>` | (`search-labels`) `text` \| `context` \| `both`; (`search-images`) `semantic` \| `substring` |
- | `--k <n>` | Number of nearest neighbors (`search`, `search-labels`, `search-images`, `eeg-for-screenshots`) |
- | `--by-image <path>` | (`search-images`) Search by visual similarity using CLIP embeddings instead of OCR text |
- | `--window <n>` | (`screenshots-for-eeg`, `eeg-for-screenshots`) Temporal window in seconds (default 30 / 60) |
- | `--k-text <n>` | (`interactive`) k for text-label HNSW search (default 5) |
- | `--k-eeg <n>` | (`interactive`) k for EEG-similarity HNSW search (default 5) |
- | `--k-labels <n>` | (`interactive`) k for label-proximity step (default 3) |
- | `--reach <n>` | (`interactive`) temporal window in minutes around each EEG point (default 10) |
- | `--ef <n>` | HNSW ef parameter (`search-labels`; default `max(k×4, 64)`) |
- | `--seconds <n>` | Duration for `listen` (default 5) |
- | `--profile <p>` | Profile name or UUID for `calibrate` |
- | `--context "..."` | (`label`) Long-form annotation body; used by `search-labels --mode context` |
- | `--at <utc>` | (`label`) Backdate to a specific unix second (default: now) |
- | `--voice <name>` | (`say`) Voice name to use (e.g. `Jasper`); omit for server default |
- | `--keywords <csv>` | (`hooks add`/`update`) Comma-separated keywords |
- | `--scenario <s>` | (`hooks add`/`update`) `any` \| `cognitive` \| `emotional` \| `physical` |
- | `--command <cmd>` | (`hooks add`/`update`) Command to run on trigger |
- | `--hook-text <txt>` | (`hooks add`/`update`) Payload text |
- | `--threshold <f>` | (`hooks add`/`update`) Distance threshold (0.01–1.0) |
- | `--recent <n>` | (`hooks add`/`update`) Recent-refs limit (10–20) |
- | `--limit <n>` | (`hooks log`) Page size (default: 20) |
- | `--offset <n>` | (`hooks log`) Row offset (default: 0) |
- | `--actions "L1:20,L2:20"` | (`calibrations create`/`update`) Actions as `label:secs` pairs |
- | `--loops <n>` | (`calibrations create`/`update`) Loop count (default: 3) |
- | `--break <n>` | (`calibrations create`/`update`) Break duration in seconds (default: 5) |
- | `--auto-start` | (`calibrations create`/`update`) Auto-start when opened |
- | `--name "…"` | (`calibrations update`) Rename the profile |
- | `--system "..."` | (`llm chat`) Prepend a system prompt |
- | `--temperature <f>` | (`llm chat`) Sampling temperature 0–2 (default 0.8) |
- | `--max-tokens <n>` | (`llm chat`) Maximum tokens to generate per turn (default 2048) |
- | `--image <path>` | (`llm chat`) Attach image file (can repeat: `--image a.jpg --image b.png`) |
- | `--mmproj <file>` | (`llm add`) Also download a vision projector from the same repo |
- | `--bedtime <HH:MM>` | (`sleep-schedule set`) Bedtime in 24-h format (e.g. `23:00`) |
- | `--wake <HH:MM>` | (`sleep-schedule set`) Wake-up time in 24-h format (e.g. `07:00`) |
- | `--preset <id>` | (`sleep-schedule set`) Apply a named preset: `default`, `early_bird`, `night_owl`, `short_sleeper`, `long_sleeper` |
- | `--metric-type <t>` | (`health metrics`) Metric type to query: `restingHeartRate`, `hrv`, `vo2Max`, `bodyMass`, etc. |
- ---
- ## Polling with `status`
- `status` is the single fastest call to get a complete system snapshot.
- Poll it periodically from any script or external tool to react to EEG state changes.
- The `--poll <n>` flag keeps the WebSocket connection open and re-polls every N seconds
- with a live timestamp header — no need for a shell loop:
- ```bash
- # Built-in polling (single connection, live updates):
- node cli.ts status --poll 5 # refresh every 5 s
- node cli.ts status --poll 10 --json # JSON snapshot every 10 s (Ctrl+C to stop)
- # One-shot snapshot:
- node cli.ts status --json
- # Manual shell loop (opens a new connection each time):
- while true; do
- node cli.ts status --json | jq '.scores.relaxation'
- sleep 5
- done
- # Alert when focus drops below 0.4:
- while true; do
- RELAX=$(node cli.ts status --json | jq '.scores.relaxation')
- if (( $(echo "$FOCUS < 0.4" | bc -l) )); then
- node cli.ts notify "Relaxation dropped" "Current: $FOCUS"
- fi
- sleep 10
- done
- ```
- ### What `status` returns
- ```jsonc
- {
- "command": "status",
- "ok": true,
- "device": {
- "state": "connected", // "connected" | "connecting" | "disconnected"
- "name": "Muse-A1B2", // or "MW75-Neuro-XXXX", "Hermes-XXXX", "Ganglion-XXXX"
- "battery": 73, // percent
- "firmware": "1.3.4",
- "eeg_samples": 195840, // cumulative samples this run
- "ppg_samples": 30600, // Muse only (PPG sensor)
- "imu_samples": 122400,
- "eeg_channels": 4 // 4 (Muse/Ganglion), 8 (Hermes), or 12 (MW75)
- },
- "session": {
- "start_utc": 1740412800, // Unix seconds (UTC)
- "duration_secs": 1847,
- "n_epochs": 369 // 5-second embedding epochs computed so far
- },
- "signal_quality": {
- // Keys vary by device — Muse: tp9/af7/af8/tp10; Hermes: fp1/fp2/af3/af4/f3/f4/fc1/fc2
- // MW75: ft7/t7/tp7/cp5/p7/c5/ft8/t8/tp8/cp6/p8/c6
- "tp9": 0.95, // 0–1; ≥0.9 = good, ≥0.7 = acceptable
- "af7": 0.88,
- "af8": 0.91,
- "tp10": 0.97
- },
- "scores": {
- // Core scores (0–1 unless noted):
- "relaxation": 0.38,
- "relaxation": 0.40,
- "engagement": 0.60,
- "meditation": 0.52,
- "mood": 0.55,
- "cognitive_load": 0.33,
- "drowsiness": 0.10,
- "hr": 68.2, // bpm (from PPG)
- "snr": 14.3, // signal-to-noise ratio in dB
- "stillness": 0.88, // 0–1; 1 = perfectly still
- // Band powers (relative, sum ≈ 1):
- "bands": {
- "rel_delta": 0.28,
- "rel_theta": 0.18,
- "rel_alpha": 0.32,
- "rel_beta": 0.17,
- "rel_gamma": 0.05
- },
- // EEG ratios & spectral indices:
- "faa": 0.042, // Frontal Alpha Asymmetry (positive = approach)
- "tar": 0.56, // Theta/Alpha Ratio
- "bar": 0.53, // Beta/Alpha Ratio
- "tbr": 1.06, // Theta/Beta Ratio
- "apf": 10.1, // Alpha Peak Frequency (Hz)
- "coherence": 0.614,
- "mu_suppression": 0.031
- },
- "embeddings": {
- "today": 342,
- "total": 14820,
- "recording_days": 31
- },
- "labels": {
- "total": 58,
- "embedded": 42,
- "recent": [
- { "id": 42, "text": "meditation start", "created_at": 1740413100 }
- ],
- "top_all_time": [
- { "text": "deep focus", "count": 12 },
- { "text": "meditation", "count": 8 }
- ],
- "top_24h": [ { "text": "deep focus", "count": 3 } ],
- "top_7d": [ { "text": "deep focus", "count": 7 } ]
- },
- "apps": {
- "top_all_time": [
- { "app_name": "VS Code", "switches": 342, "last_seen": 1740413000 },
- { "app_name": "Firefox", "switches": 198, "last_seen": 1740412900 }
- ],
- "top_24h": [ { "app_name": "VS Code", "switches": 28, "last_seen": 1740413000 } ],
- "top_7d": [ { "app_name": "VS Code", "switches": 142, "last_seen": 1740413000 } ]
- },
- "screenshots": {
- "total": 1842,
- "with_embedding": 1840,
- "with_ocr": 1780,
- "with_ocr_embedding": 1756,
- "top_apps_all_time": [
- { "app_name": "VS Code", "count": 620 },
- { "app_name": "Firefox", "count": 310 }
- ],
- "top_apps_24h": [ { "app_name": "VS Code", "count": 48 } ]
- },
- "sleep": {
- // Last 48 h sleep staging summary:
- "total_epochs": 1054,
- "wake_epochs": 134,
- "n1_epochs": 89,
- "n2_epochs": 421,
- "n3_epochs": 298,
- "rem_epochs": 112,
- "epoch_secs": 5
- },
- "hooks": {
- "total": 3, // total configured hooks
- "enabled": 2, // how many are enabled
- "latest_trigger": { // most recent trigger across all hooks (null if never)
- "hook": "Deep Work Guard", // hook name that fired
- "triggered_at_utc": 1740413100,
- "distance": 0.0892, // cosine distance to matched reference
- "label_id": 7,
- "label_text": "focused reading session"
- }
- },
- "history": {
- "total_sessions": 63,
- "recording_days": 31,
- "current_streak_days": 7,
- "total_recording_hours": 94.2,
- "longest_session_min": 187,
- "avg_session_min": 89
- }
- }
- ```
- ---
- ## Commands
- ### `status`
- Full snapshot: device state, session, signal quality, scores, bands, embeddings, labels
- (with most-frequent texts), hooks (with latest trigger), sleep summary, recording history,
- app usage analytics, and screenshot/OCR statistics.
- Use `--poll <n>` to re-poll every N seconds over the same open connection
- (keeps the socket open; press Ctrl+C to stop).
- ```bash
- node cli.ts status
- node cli.ts status --json
- node cli.ts status --json | jq '.scores.relaxation'
- node cli.ts status --json | jq '.scores.bands'
- node cli.ts status --json | jq '.device.battery'
- node cli.ts status --json | jq '.signal_quality'
- node cli.ts status --json | jq '.sleep'
- node cli.ts status --json | jq '.history.current_streak_days'
- node cli.ts status --json | jq '.hooks' # hook summary + latest trigger
- node cli.ts status --json | jq '.hooks.latest_trigger' # most recent hook trigger
- node cli.ts status --json | jq '.hooks.latest_trigger.hook' # which hook fired last
- node cli.ts status --json | jq '.apps.top_24h' # most-used apps in last 24h
- node cli.ts status --json | jq '.apps.top_all_time[:5]' # top 5 apps all-time
- node cli.ts status --json | jq '.labels.top_all_time' # most frequent label texts
- node cli.ts status --json | jq '.screenshots' # screenshot/OCR counts
- node cli.ts status --json | jq '.screenshots.top_apps_24h' # top screenshot apps (24h)
- node cli.ts status --poll 5 # refresh every 5 seconds
- node cli.ts status --poll 10 --json # JSON snapshot every 10 seconds
- ```
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"status"}'
- ```
- ---
- ### `session`
- Full metric breakdown for a single recording session, with first-half → second-half trend arrows.
- Index `0` = most recent, `1` = previous, and so on.
- ```bash
- node cli.ts session # most recent session (default: 0)
- node cli.ts session 0 # same
- node cli.ts session 1 # previous session
- node cli.ts session 2 # two sessions ago
- node cli.ts session --json
- node cli.ts session 1 --json | jq '.metrics.relaxation'
- node cli.ts session 0 --json | jq '{relaxation: .metrics.relaxation, hr: .metrics.hr, trend: .trends.relaxation}'
- ```
- **HTTP (two requests):**
- ```bash
- # Step 1 — get session list to find timestamps:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"sessions"}' | jq '.sessions[0]'
- # Step 2 — fetch full metrics for that session:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"session_metrics","start_utc":1740412800,"end_utc":1740415510}'
- ```
- **Example output:**
- ```
- ⚡ session [0]
- 20260224 2/24/2026, 8:00:00 AM → 8:45:10 AM 45m 10s 541 epochs
- Core Scores
- focus 0.70 ↑ (0.64 → 0.76)
- relaxation 0.40 ↓ (0.44 → 0.36)
- engagement 0.60 → (0.60 → 0.61)
- meditation 0.52 ↑ (0.47 → 0.57)
- mood 0.55 → (0.54 → 0.56)
- cognitive load 0.33 ↓ (0.38 → 0.28)
- drowsiness 0.10 → (0.11 → 0.09)
- PPG / Heart
- heart rate (bpm) 68.2 ↓ (70.1 → 66.3)
- rmssd (ms) 42.1 ↑ (38.4 → 45.8)
- ...
- EEG Bands
- δ delta 28% ↓ (31% → 25%)
- θ theta 18% ↓ (21% → 15%)
- α alpha 32% ↑ (28% → 36%)
- β beta 17% → (17% → 17%)
- γ gamma 5% → (5% → 5%)
- ```
- **JSON response structure:**
- ```jsonc
- {
- "ok": true,
- "metrics": {
- "relaxation": 0.38,
- "relaxation": 0.40,
- "n_epochs": 541,
- // ... all metrics (see Data Reference)
- },
- "first": {
- "relaxation": 0.38, // first-half average
- // ...
- },
- "second": {
- "relaxation": 0.41, // second-half average
- // ...
- },
- "trends": {
- "relaxation": "up", // "up" | "down" | "flat"
- "relaxation": "down",
- // ...
- }
- }
- ```
- ---
- ### `sessions`
- List every recorded session across all days. Sessions are contiguous embedding ranges
- (gap threshold: 120 seconds between epochs).
- ```bash
- node cli.ts sessions
- node cli.ts sessions --json
- node cli.ts sessions --json | jq '.sessions | length'
- node cli.ts sessions --json | jq '.sessions[0]'
- node cli.ts sessions --json | jq '[.sessions[] | {day, dur: (.end_utc - .start_utc)}]'
- node cli.ts sessions --trends # show per-session metric trends
- ```
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"sessions"}'
- ```
- **Example output:**
- ```
- ⚡ sessions
- 3 session(s)
- 20260223 2/23/2026, 9:15:00 AM → 10:02:33 AM 47m 33s 570 epochs
- 20260223 2/23/2026, 2:30:00 PM → 3:12:45 PM 42m 45s 513 epochs
- 20260224 2/24/2026, 8:00:00 AM → 8:45:10 AM 45m 10s 541 epochs
- ```
- **JSON response:**
- ```jsonc
- {
- "command": "sessions",
- "ok": true,
- "sessions": [
- {
- "day": "20260224",
- "start_utc": 1740412800, // Unix seconds
- "end_utc": 1740415510,
- "n_epochs": 541 // 5-second embedding windows
- },
- {
- "day": "20260223",
- "start_utc": 1740380100,
- "end_utc": 1740382665,
- "n_epochs": 513
- }
- // ...newest first
- ]
- }
- ```
- > **Getting Unix timestamps for other commands:**
- > ```bash
- > # Get start/end of the most recent session:
- > node cli.ts sessions --json | jq '{start: .sessions[0].start_utc, end: .sessions[0].end_utc}'
- > ```
- ---
- ### `say`
- Speak text aloud via the on-device KittenTTS engine (fire-and-forget).
- The server enqueues the utterance on a dedicated TTS thread and returns immediately —
- the response arrives before audio playback begins.
- Requires `espeak-ng` on PATH. First run downloads a ~30 MB TTS model from HuggingFace Hub.
- ```bash
- node cli.ts say "Eyes open. Starting calibration."
- node cli.ts say "Break time. Next: Eyes Closed." --voice Jasper
- node cli.ts say "Calibration complete." --http
- node cli.ts say "Hello!" --json
- ```
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"say","text":"Eyes open. Starting calibration."}'
- # With a specific voice:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"say","text":"Break time.","voice":"Jasper"}'
- ```
- **Response:**
- ```jsonc
- { "command": "say", "ok": true, "spoken": "Eyes open. Starting calibration." }
- // With --voice Jasper:
- { "command": "say", "ok": true, "spoken": "Break time.", "voice": "Jasper" }
- ```
- > **Note:** `--voice` is optional; omitting it uses the voice last selected in Settings → Voice.
- ---
- ### `label`
- Create a timestamped text annotation on the current EEG moment.
- Labels are stored in the database, shown in the dashboard, and searchable via `search-labels`.
- Optional flags:
- - `--context "..."` — long-form body stored alongside the short text; used by
- `search-labels --mode context` and `--mode both`.
- - `--at <utc>` — backdate the label to a specific unix second instead of using
- the current time (useful for retrospective annotation).
- ```bash
- node cli.ts label "meditation start"
- node cli.ts label "eyes closed"
- node cli.ts label "feeling anxious"
- node cli.ts label "coffee just finished"
- node cli.ts label "task switch: coding → email"
- node cli.ts label "phone notification distracted me"
- node cli.ts label --json "focus block start" # just print the label_id
- node cli.ts label "breathwork" --context "box breathing 4-4-4-4, 10 min"
- node cli.ts label "retrospective note" --at 1740412800
- ```
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"label","text":"meditation start"}'
- # With long-form context:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"label","text":"eyes closed","context":"4-7-8 breathing exercise"}'
- # Backdated to a specific timestamp:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"label","text":"retrospective note","label_start_utc":1740412800}'
- # Save the label_id for later reference:
- LABEL_ID=$(curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"label","text":"focus block start"}' | jq '.label_id')
- echo "Created label #$LABEL_ID"
- ```
- **Response:**
- ```jsonc
- { "command": "label", "ok": true, "label_id": 42 }
- ```
- ---
- ### `hooks`
- List configured Proactive Hooks with scenario + last-trigger metadata.
- Supports the following subcommands:
- | Subcommand | Description |
- |---|---|
- | `hooks` (or `hooks status`) | List hooks with scenario + last-trigger metadata |
- | `hooks list` | List raw hook rules (name, keywords, threshold, enabled, …) |
- | `hooks add <name> [opts]` | Add a new hook rule |
- | `hooks remove <name>` | Delete a hook by name |
- | `hooks enable <name>` | Enable a hook |
- | `hooks disable <name>` | Disable a hook |
- | `hooks update <name> [opts]` | Update fields on an existing hook |
- | `hooks suggest "kw1,kw2"` | Suggest threshold from matching labels + recent EEG embeddings |
- | `hooks log [--limit N --offset M]` | View paginated hook trigger audit log rows |
- **Hook mutation flags** (for `hooks add` and `hooks update`):
- | Flag | Description |
- |---|---|
- | `--keywords <csv>` | Comma-separated keywords (e.g. `"focus,deep work,flow"`) |
- | `--scenario <s>` | `any` \| `cognitive` \| `emotional` \| `physical` |
- | `--command <cmd>` | Command to run on trigger |
- | `--hook-text <txt>` | Payload text |
- | `--threshold <f>` | Distance threshold (0.01–1.0) |
- | `--recent <n>` | Recent-refs limit (10–20) |
- ```bash
- # Status (default) — hooks with scenario + last trigger
- node cli.ts hooks
- node cli.ts hooks --json
- node cli.ts hooks --json | jq '.hooks[] | {name: .hook.name, scenario: .hook.scenario, last: .last_trigger.triggered_at_utc}'
- # List raw hook rules
- node cli.ts hooks list
- node cli.ts hooks list --json
- # Add a new hook
- node cli.ts hooks add "Deep Work Guard" --keywords "focus,deep work,flow" --scenario cognitive --threshold 0.14
- node cli.ts hooks add "Stress Alert" --keywords "stress,anxious,overwhelmed" --scenario emotional --threshold 0.12
- # Update an existing hook
- node cli.ts hooks update "Deep Work Guard" --keywords "focus,flow" --threshold 0.12
- # Enable / disable
- node cli.ts hooks enable "Deep Work Guard"
- node cli.ts hooks disable "Deep Work Guard"
- # Remove
- node cli.ts hooks remove "Deep Work Guard"
- # Suggest threshold from real EEG/label data
- node cli.ts hooks suggest "focus,deep work"
- node cli.ts hooks suggest "focus" --json | jq '.suggestion.suggested'
- # Scenario-focused quick examples:
- # cognitive: deep work overload guard
- node cli.ts hooks suggest "focus,deep work"
- # emotional: stress-recovery style labels
- node cli.ts hooks suggest "stress,anxious,overwhelmed"
- # physical: fatigue/body-state style labels
- node cli.ts hooks suggest "fatigue,tired,slump"
- # View hook trigger audit log
- node cli.ts hooks log --limit 20 --offset 0
- node cli.ts hooks log --json | jq '.rows[] | {ts: .triggered_at_utc, hook: (.hook_json|fromjson).name, scenario: (.hook_json|fromjson).scenario}'
- ```
- **HTTP:**
- ```bash
- # Status
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"hooks_status"}'
- # List raw rules
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"hooks_get"}'
- # Set hooks (add/remove/update — sends the full array)
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"hooks_set","hooks":[...]}'
- # Suggest threshold
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"hooks_suggest","keywords":["focus","deep work"]}'
- # Audit log
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"hooks_log","limit":20,"offset":0}'
- ```
- #### How Proactive Hooks Work (Broadcast → `listen`)
- Proactive Hooks are a **real-time pattern matching system** that runs inside the
- EEG embedding pipeline. Every 5 seconds, when a new EEG embedding epoch is
- computed, the server checks all enabled hooks against the live brain state:
- ```
- EEG stream → 5 s epoch → embedding vector → cosine distance to hook references
- ↓
- distance ≤ threshold?
- ↓
- scenario gate passes?
- ↓
- broadcast { event: "hook", payload: {...} }
- + audit log in hooks.duckdb
- + OS toast notification
- ```
- **Step by step:**
- 1. **Labels as reference patterns** — When you create labels (`node cli.ts label "deep focus"`),
- the server embeds both the text and the surrounding EEG window. Each hook's
- `keywords` are matched against label texts to build a set of reference EEG
- embeddings (up to `recent_limit` most recent matches).
- 2. **Live comparison** — Every new 5-second EEG epoch is compared (cosine distance)
- against every enabled hook's reference embeddings. If the closest match is
- within the hook's `distance_threshold`, the hook fires.
- 3. **Scenario gating** — Before firing, the hook checks the current epoch's metrics
- against the scenario filter:
- - `any` — always passes
- - `cognitive` — requires elevated theta/beta ratio or cognitive load ≥ 55
- - `emotional` — requires stress index ≥ 55, mood ≤ 45, or relaxation ≤ 35
- - `physical` — requires drowsiness ≥ 55, migraine index ≥ 45, or extreme HR
- 4. **Cooldown** — A hook cannot fire more than once every 10 seconds (prevents
- rapid-fire spam when the brain state is sustained).
- 5. **Broadcast** — When a hook fires, the server pushes a `{ "event": "hook" }` message
- over WebSocket to **all connected clients**. This is the same broadcast mechanism
- used for EEG, scores, and label events — any WebSocket listener receives it.
- 6. **Audit log** — Every trigger is persisted to `hooks.duckdb` for later review
- via `hooks log`.
- **Why this matters for the CLI:**
- Because hook triggers are broadcast events, `listen` captures them automatically.
- This lets you build automation pipelines that react to your brain state in real time:
- ```bash
- # ── React to hook triggers in a shell script ──────────────────────────────────
- # Listen for 5 minutes and act on any hook triggers:
- node cli.ts listen --seconds 300 --json | jq -c '.[] | select(.event == "hook") | .payload' | while read -r payload; do
- HOOK=$(echo "$payload" | jq -r '.hook')
- DIST=$(echo "$payload" | jq -r '.distance')
- LABEL=$(echo "$payload" | jq -r '.label_text')
- echo "Hook triggered: $HOOK (dist=$DIST, label=$LABEL)"
- # Run custom actions based on hook name:
- case "$HOOK" in
- "Deep Work Guard")
- node cli.ts notify "Deep Focus Detected" "Distance: $DIST to '$LABEL'"
- ;;
- "Stress Alert")
- osascript -e 'display notification "Take a break" with title "Stress Detected"'
- ;;
- esac
- done
- # ── Python real-time hook listener ────────────────────────────────────────────
- python3 - <<'EOF'
- import asyncio, json
- import websockets
- async def listen_for_hooks(port: int):
- async with websockets.connect(f"ws://127.0.0.1:{port}") as ws:
- print("Listening for hook triggers…")
- async for raw in ws:
- msg = json.loads(raw)
- if msg.get("event") == "hook":
- p = msg["payload"]
- print(f"🪝 {p['hook']} fired! distance={p['distance']:.4f} label=\"{p['label_text']}\"")
- # Do something: send Slack message, log to CSV, trigger HomeKit, etc.
- asyncio.run(listen_for_hooks(8375))
- EOF
- # ── End-to-end workflow: create labels, add hook, listen for triggers ─────────
- # 1. Record some EEG while in a specific state and label it:
- node cli.ts label "deep focus coding"
- node cli.ts label "deep concentration"
- # 2. Create a hook that fires when your brain returns to that state:
- node cli.ts hooks add "Focus Mode" \
- --keywords "focus,concentration,deep" \
- --scenario cognitive \
- --threshold 0.15
- # 3. Verify the threshold makes sense:
- node cli.ts hooks suggest "focus,concentration,deep"
- # 4. Listen and watch for triggers:
- node cli.ts listen --seconds 300
- # 5. Check the audit log after the session:
- node cli.ts hooks log --limit 10
- ```
- **Hook trigger event shape (WebSocket):**
- ```jsonc
- {
- "event": "hook",
- "payload": {
- "hook": "Deep Work Guard", // hook rule name
- "scenario": "cognitive", // scenario filter
- "context": "labels", // match source
- "distance": 0.0892, // cosine distance to closest reference
- "label_id": 7, // which label's EEG pattern matched
- "label_text": "focused reading session",
- "triggered_at_utc": 1740412830, // unix seconds
- "command": "notify", // configured action
- "text": "You're in deep focus!" // configured payload
- }
- }
- ```
- > **Note:** Hook broadcast events are only available over WebSocket. HTTP transport
- > (`--http`) has no push streaming, so you cannot receive hook triggers via HTTP.
- > Use `listen` (which requires WebSocket) or connect directly via `ws://`.
- ---
- ### `search-labels`
- Semantic (vector) search across all your EEG annotations.
- The query is embedded and compared against the label HNSW index.
- ```bash
- node cli.ts search-labels "deep focus"
- node cli.ts search-labels "relaxed meditation" --k 10
- node cli.ts search-labels "anxiety" --mode context
- node cli.ts search-labels "flow state" --mode both --k 5
- node cli.ts search-labels "creative work" --json | jq '.results[].text'
- node cli.ts search-labels "morning routine" --json | jq '.results[] | {text, sim: .similarity}'
- ```
- **Modes:**
- - `text` (default) — searches the label short-text HNSW index
- - `context` — searches the long-context HNSW (requires context fields to be set)
- - `both` — runs both indexes, deduplicates by best cosine distance
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"search_labels","query":"deep focus","k":10,"mode":"text"}'
- ```
- **Example output:**
- ```
- ⚡ search-labels "deep focus" (mode: text, k: 10)
- model: Xenova/bge-small-en-v1.5
- k: 10 results: 3
- #7 "focused reading session"
- similarity: 88% distance: 0.1204 model: bge-small-en-v1.5
- recorded: 2/24/2026, 8:05:00 AM (300s window)
- eeg: focus=0.74 relaxation=0.38 engagement=0.62 hr=66.10 mood=0.58
- #12 "deep work block"
- similarity: 84% distance: 0.1601
- recorded: 2/23/2026, 9:20:00 AM (300s window)
- eeg: focus=0.71 relaxation=0.42 engagement=0.65 hr=68.30 mood=0.55
- ```
- **JSON response:**
- ```jsonc
- {
- "command": "search_labels",
- "ok": true,
- "query": "deep focus",
- "mode": "text",
- "model": "Xenova/bge-small-en-v1.5",
- "k": 10,
- "count": 3,
- "results": [
- {
- "label_id": 7,
- "text": "focused reading session",
- "context": "",
- "distance": 0.1204,
- "similarity": 0.8796, // 1 − distance
- "eeg_start": 1740412800,
- "eeg_end": 1740413100,
- "created_at": 1740412810,
- "embedding_model": "bge-small-en-v1.5",
- "eeg_metrics": {
- "relaxation": 0.38,
- "relaxation": 0.38,
- "engagement": 0.62,
- "hr": 66.1,
- "mood": 0.58,
- "rel_alpha": 0.35,
- "rel_beta": 0.19
- }
- }
- ]
- }
- ```
- ---
- ### `interactive`
- Cross-modal 5-layer graph search. Combines semantic text search, EEG similarity search,
- temporal label proximity, and screenshot discovery into a single directed graph:
- ```
- "deep focus" → text_label nodes (semantically similar annotations)
- ↓
- eeg_point nodes (raw EEG moments from label time windows)
- ↓
- found_label nodes (labels near those EEG moments in time)
- ↓
- screenshot nodes (screenshots near EEG timestamps, ranked by
- window-title / OCR-text proximity to query)
- ```
- Four output formats — choose exactly one:
- | Flag | Output |
- |---|---|
- | _(none)_ | Colored human-readable summary of all four layers |
- | `--full` | Summary **+** colorized JSON appended below |
- | `--json` | Raw JSON: `{ query, nodes, edges, dot }` — pipe-safe |
- | `--dot` | Graphviz DOT source only — pipe directly to `dot -Tsvg` or `dot -Tpng` |
- ```bash
- # Default summary:
- node cli.ts interactive "deep focus"
- # Tune the pipeline:
- node cli.ts interactive "meditation" --k-text 8 --k-eeg 8 --k-labels 5 --reach 15
- # Raw JSON — count nodes:
- node cli.ts interactive "flow state" --json | jq '.nodes | length'
- # Extract text_label texts:
- node cli.ts interactive "focus" --json | jq '[.nodes[] | select(.kind == "text_label") | .text]'
- # Extract EEG moment timestamps:
- node cli.ts interactive "anxiety" --json | jq '[.nodes[] | select(.kind == "eeg_point") | .timestamp_unix]'
- # Extract discovered nearby labels:
- node cli.ts interactive "stress" --json | jq '[.nodes[] | select(.kind == "found_label") | .text]'
- # Extract discovered screenshots:
- node cli.ts interactive "coding" --json | jq '[.nodes[] | select(.kind == "screenshot") | {file: .filename, app: .app_name, ocr_sim: .ocr_similarity}]'
- # Render graph as SVG (requires graphviz):
- node cli.ts interactive "deep focus" --dot | dot -Tsvg > graph.svg
- # Render graph as PNG:
- node cli.ts interactive "meditation" --dot | dot -Tpng > graph.png
- # Pull DOT from JSON output instead:
- node cli.ts interactive "focus" --json | jq -r '.dot' | dot -Tsvg > graph.svg
- # Full inspection (summary + full JSON):
- node cli.ts interactive "anxiety" --full
- ```
- **Pipeline parameters:**
- | Flag | Default | Range | Description |
- |---|---|---|---|
- | `--k-text <n>` | 5 | 1–20 | k for text-label HNSW search |
- | `--k-eeg <n>` | 5 | 1–20 | k for EEG-similarity HNSW per text label |
- | `--k-labels <n>` | 3 | 1–10 | k for label-proximity per EEG point |
- | `--reach <n>` | 10 | 1–60 | Temporal window (minutes) around each EEG point |
- All parameters are server-clamped to their stated range. Out-of-range values are silently adjusted.
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{
- "command": "interactive_search",
- "query": "deep focus",
- "k_text": 5,
- "k_eeg": 5,
- "k_labels": 3,
- "reach_minutes": 10
- }'
- ```
- **Example default output:**
- ```
- ⚡ interactive "deep focus" (k-text:5, k-eeg:5, k-labels:3, reach:10m)
- Graph 7 nodes · 9 edges
- edges: text_sim ×2 eeg_bridge ×3 label_prox ×4
- ──────────────────────────────────────────────────────
- ● query "deep focus"
- ◆ Text Labels (2 semantically similar labels)
- #0 "focused reading session" 2/24/2026, 8:00:00 AM PST
- similarity: 88% dist: 0.1204
- focus 0.74 relaxation 0.38 engagement 0.62 hr 66.10 meditation 0.44
- #1 "concentration phase" 2/23/2026, 2:30:00 PM PST
- similarity: 82% dist: 0.1805
- ◈ EEG Moments (3 neural moments found)
- #0 2/24/2026, 8:12:45 AM PST dist: 0.0231 ← tl_0
- #1 2/22/2026, 10:14:00 AM PST dist: 0.0319 ← tl_0
- #2 2/21/2026, 3:02:00 PM PST dist: 0.0487 ← tl_1
- ◉ Nearby Labels (2 labels found near EEG moments)
- #0 "eyes closed" 2/24/2026, 8:13:00 AM PST 0.8m from EEG point
- #1 "task complete" 2/22/2026, 10:18:00 AM PST 4.0m from EEG point
- tip: rerun with --dot | dot -Tsvg > graph.svg to visualize
- ```
- **JSON response structure:**
- ```jsonc
- {
- "command": "interactive_search",
- "ok": true,
- "query": "deep focus",
- "k_text": 5,
- "k_eeg": 5,
- "k_labels": 3,
- "reach_minutes": 10,
- "nodes": [
- {
- "id": "query",
- "kind": "query",
- "text": "deep focus",
- "timestamp_unix": null,
- "distance": 0.0,
- "eeg_metrics": null,
- "parent_id": null
- },
- {
- "id": "tl_0",
- "kind": "text_label",
- "text": "focused reading session",
- "timestamp_unix": 1740412800,
- "distance": 0.1204, // cosine distance from query
- "eeg_metrics": {
- "relaxation": 0.38, "engagement": 0.62,
- "hr": 66.1, "meditation": 0.44, "rel_alpha": 0.35
- },
- "parent_id": "query"
- },
- {
- "id": "ep_1740413565",
- "kind": "eeg_point",
- "text": null,
- "timestamp_unix": 1740413565,
- "distance": 0.0231, // cosine distance in EEG embedding space
- "eeg_metrics": null,
- "parent_id": "tl_0"
- },
- {
- "id": "fl_42",
- "kind": "found_label",
- "text": "eyes closed",
- "timestamp_unix": 1740413580,
- "distance": 0.133, // fraction of reach window (0 = right at the EEG point)
- "eeg_metrics": null,
- "parent_id": "ep_1740413565"
- },
- {
- "id": "ss_20260224080530",
- "kind": "screenshot",
- "text": null,
- "timestamp_unix": 1740413130,
- "distance": 0.05,
- "eeg_metrics": null,
- "parent_id": "ep_1740413565",
- "filename": "20260224/20260224080530.webp",
- "app_name": "VS Code",
- "window_title": "main.rs",
- "ocr_text": "fn dispatch(app: &AppHandle, command: &str…",
- "ocr_similarity": 0.42,
- "proj_x": 0.31,
- "proj_y": -0.18,
- "proj_z": 0.72
- }
- // ... more nodes
- ],
- "edges": [
- { "from_id": "query", "to_id": "tl_0", "distance": 0.1204, "kind": "text_sim" },
- { "from_id": "tl_0", "to_id": "ep_1740413565", "distance": 0.0231, "kind": "eeg_bridge" },
- { "from_id": "ep_1740413565","to_id": "fl_42", "distance": 0.133, "kind": "label_prox" },
- { "from_id": "ep_1740413565","to_id": "ss_20260224080530","distance": 2.0, "kind": "screenshot_prox" },
- { "from_id": "ep_1740413565","to_id": "ss_20260224080530","distance": 0.42, "kind": "ocr_sim" }
- // ...
- ],
- "dot": "digraph interactive_search {\n graph [rankdir=TB, ...];\n \"query\" [...];\n ...",
- "svg": "<svg ...>...</svg>",
- "svg_col": "<svg ...>...</svg>",
- "svg_3d": "<svg ...>...</svg>"
- }
- ```
- **Node kinds:**
- | Kind | Layer | Color | Description |
- |---|---|---|---|
- | `query` | 0 | violet | The embedded search keyword (always exactly 1) |
- | `text_label` | 1 | blue | Annotations semantically similar to the query |
- | `eeg_point` | 2 | amber | Raw EEG moments from label time windows |
- | `found_label` | 3 | emerald | Annotations discovered near EEG moments in time |
- | `screenshot` | 4 | pink | Screenshots near EEG timestamps, ranked by window-title / OCR proximity |
- **Edge kinds:**
- | Kind | Connects | What the distance means |
- |---|---|---|
- | `text_sim` | query → text_label | Cosine distance in text embedding space |
- | `eeg_bridge` | text_label → eeg_point | Cosine distance in EEG embedding space |
- | `eeg_sim` | eeg_point → eeg_point | Cosine distance (shared EEG point, cross-edge) |
- | `label_prox` | eeg_point → found_label | Temporal proximity (fraction of reach window) |
- | `screenshot_prox` | eeg_point → screenshot | Temporal proximity (seconds between EEG epoch and screenshot capture) |
- | `ocr_sim` | eeg_point → screenshot | Cosine similarity between query text and screenshot OCR text |
- **Screenshot node fields** (only present on `screenshot` kind nodes):
- | Field | Type | Description |
- |---|---|---|
- | `filename` | string | Relative path to the screenshot image file |
- | `app_name` | string | Application name at capture time |
- | `window_title` | string | Window title at capture time |
- | `ocr_text` | string | OCR-extracted text from the screenshot |
- | `ocr_similarity` | number | Cosine similarity (0–1) between query text and OCR text |
- **3-D projection fields** (present on all nodes when text embeddings are available):
- | Field | Type | Description |
- |---|---|---|
- | `proj_x` | number | PCA axis 1, normalised to [-1, 1] |
- | `proj_y` | number | PCA axis 2, normalised to [-1, 1] |
- | `proj_z` | number | PCA axis 3, normalised to [-1, 1] |
- > **Empty results:** If no labels have been embedded yet, only the query node is returned
- > (`nodes.length === 1`, `edges.length === 0`). Annotate moments with `label` first, then
- > run `search-labels` to verify the embedding index, then re-run `interactive`.
- ---
- ### `search`
- Find EEG moments from your entire history that are neurally similar to a query range.
- Uses approximate nearest-neighbor (ANN) search over the 5-second embedding HNSW index.
- Auto-range: when no `--start`/`--end` flags are given, the CLI automatically uses your
- most recent session and prints a `rerun:` line you can copy-paste.
- ```bash
- node cli.ts search # auto: last session, k=5
- node cli.ts search --k 10 # 10 nearest neighbors
- node cli.ts search --start 1740412800 --end 1740415500
- node cli.ts search --start 1740412800 --end 1740415500 --k 20
- node cli.ts search --json | jq '.result.results | length'
- node cli.ts search --json | jq '.result.results[0].neighbors[0]'
- ```
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"search","start_utc":1740412800,"end_utc":1740415500,"k":5}'
- ```
- **Example output:**
- ```
- ⚡ search
- range: 1740412800–1740415500 (auto: 2/24/2026 8:00 AM → 8:45 AM, 45m 0s)
- k: 5
- rerun: node cli.ts search --start 1740412800 --end 1740415500 --k 5
- Search Results
- query epochs: 541 searched days: 31 total matches: 2705 span: 744.3h
- Match Quality (cosine distance — lower = more similar)
- ████████████████████░░░░ similarity 82%
- min 0.0231 mean 0.1842 max 0.3901 σ 0.0612
- Neighbor Metrics (avg · min–max across 2705 matches)
- focus 0.67 0.34 – 0.91
- relaxation 0.43 0.19 – 0.74
- hr (bpm) 67.4 52.0 – 88.3
- α alpha 0.33 0.18 – 0.51
- θ/α ratio 0.54 0.28 – 0.89
- Top Matches (closest by cosine distance)
- #1 2/22/2026, 10:14:00 AM dist 0.0231 focus 0.73 relax 0.41 hr 66.2
- #2 2/21/2026, 3:02:00 PM dist 0.0319 focus 0.69 relax 0.44 hr 67.8
- ...
- Temporal Distribution (matches by hour of day, UTC)
- 08:00 ████████████░░░░░░░░ 142 20:00 ███░░░░░░░░░░░░░░░░░ 38
- 09:00 ████████████████░░░░ 198 21:00 █░░░░░░░░░░░░░░░░░░░ 12
- ...
- ```
- **JSON response:**
- ```jsonc
- {
- "command": "search",
- "ok": true,
- "result": {
- "query_count": 541,
- "searched_days": ["20260224", "20260223", ...],
- "analysis": {
- "distance_stats": { "min": 0.0231, "mean": 0.1842, "max": 0.3901, "stddev": 0.0612 },
- "time_span_hours": 744.3,
- "neighbor_metrics": { "relaxation": 0.38, "relaxation": 0.43, "hr": 67.4, ... },
- "temporal_distribution": { "8": 142, "9": 198, ... },
- "top_days": [["20260222", 312], ["20260221", 289], ...]
- },
- "results": [
- {
- "timestamp_unix": 1740412800,
- "neighbors": [
- {
- "distance": 0.0231, // cosine distance — lower = more similar
- "timestamp_unix": 1740320040,
- "date": "20260222",
- "device_name": "Muse-A1B2",
- "labels": [{ "text": "morning focus block" }],
- "metrics": {
- "relaxation": 0.38,
- "relaxation": 0.41,
- "hr": 66.2,
- "rel_alpha": 0.34
- }
- }
- ]
- }
- ]
- }
- }
- ```
- ---
- ### `compare`
- Side-by-side A/B comparison of two sessions.
- Returns averaged metrics for both ranges, delta values, and trend direction for every metric.
- Also enqueues a 3D UMAP projection (use `umap` to get the spatial points).
- Auto-range: uses your last two sessions as A (older) and B (newer).
- ```bash
- node cli.ts compare # auto: last 2 sessions
- node cli.ts compare --a-start 1740380100 --a-end 1740382665 \
- --b-start 1740412800 --b-end 1740415510
- node cli.ts compare --json
- node cli.ts compare --json | jq '{a_relax: .a.relaxation, b_relax: .b.relaxation}'
- node cli.ts compare --json | jq '.insights.deltas.relaxation'
- node cli.ts compare --json | jq '.insights.improved'
- node cli.ts compare --json | jq '.insights.declined'
- ```
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{
- "command": "compare",
- "a_start_utc": 1740380100, "a_end_utc": 1740382665,
- "b_start_utc": 1740412800, "b_end_utc": 1740415510
- }' | jq '{a_relax: .a.relaxation, b_relax: .b.relaxation}'
- ```
- **Example output:**
- ```
- ⚡ compare
- A: 1740380100–1740382665 (auto: 2/23/2026 2:30 PM → 3:12 PM, 42m 45s)
- B: 1740412800–1740415510 (auto: 2/24/2026 8:00 AM → 8:45 AM, 45m 10s)
- rerun: node cli.ts compare --a-start 1740380100 --a-end 1740382665 ...
- Compare Insights (513 vs 541 epochs)
- metric A B Δ Δ% dir
- ────────────────────────────────────────────────────────
- focus 0.62 0.71 +0.09 +14.5% ↑
- relaxation 0.45 0.38 -0.07 -15.6% ↓
- engagement 0.58 0.60 +0.02 +3.4% →
- hr 72.1 68.4 -3.70 -5.1% ↓
- meditation 0.44 0.52 +0.08 +18.2% ↑
- drowsiness 0.18 0.10 -0.08 -44.4% ↓
- ▲ improved: focus, meditation, engagement
- ▼ declined: relaxation, hr
- ```
- **JSON response:**
- ```jsonc
- {
- "ok": true,
- "a": { "relaxation": 0.45, "engagement": 0.62, "hr": 72.1, "n_epochs": 513, ... },
- "b": { "relaxation": 0.38, "engagement": 0.71, "hr": 68.4, "n_epochs": 541, ... },
- "sleep_a": { "total_epochs": 0, ... },
- "sleep_b": { "total_epochs": 0, ... },
- "insights": {
- "n_epochs_a": 513,
- "n_epochs_b": 541,
- "deltas": {
- "relaxation": { "a": 0.45, "b": 0.38, "abs": 0.07, "pct": -15.6, "direction": "down" },
- "relaxation": { "a": 0.45, "b": 0.38, "abs": -0.07, "pct": -15.6, "direction": "down" },
- ...
- },
- "improved": ["focus", "meditation", "engagement"],
- "declined": ["relaxation", "hr"]
- },
- "umap": {
- "queued": true,
- "job_id": 5,
- "estimated_secs": 14,
- "n_a": 513,
- "n_b": 541
- }
- }
- ```
- ---
- ### `sleep`
- Classify EEG epochs into sleep stages (Wake / N1 / N2 / N3 / REM) using
- relative band-power ratios and simplified AASM heuristics.
- Auto-range: all sessions from the last 24 hours.
- By index: `sleep 0` = most recent session, `sleep 1` = previous, etc.
- ```bash
- node cli.ts sleep # auto: last 24h of sessions
- node cli.ts sleep 0 # most recent session's sleep data
- node cli.ts sleep 1 # previous session
- node cli.ts sleep --start 1740380100 --end 1740415510
- node cli.ts sleep --json | jq '.summary'
- node cli.ts sleep --json | jq '.analysis'
- node cli.ts sleep --json | jq '.summary | {n3: .n3_epochs, rem: .rem_epochs}'
- ```
- **HTTP:**
- ```bash
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"sleep","start_utc":1740380100,"end_utc":1740415510}' | jq '.summary'
- ```
- **Example output:**
- ```
- ⚡ sleep
- range: 1740380100–1740415510 (auto: 2/23/2026 2:30 PM → 2/24/2026 8:45 AM, 9h 50m)
- rerun: node cli.ts sleep --start 1740380100 --end 1740415510
- Sleep Summary
- total: 1054 epochs (87 min)
- Wake 134 (12.7%)
- N1 89 (8.4%)
- N2 421 (39.9%)
- N3 298 (28.3%)
- REM 112 (10.6%)
- Sleep Analysis
- efficiency: 85.2%
- onset latency: 12.5 min
- REM latency: 62.0 min
- transitions: 38 awakenings: 11
- Stage durations: Wake 11m N1 7m N2 35m N3 25m REM 9m
- Bout analysis:
- WAKE 11 bouts avg 1.0m max 3.5m
- N2 14 bouts avg 2.5m max 8.0m
- N3 6 bouts avg 4.2m max 9.0m
- REM 4 bouts avg 2.3m max 4.5m
- ```
- **JSON response:**
- ```jsonc
- {
- "command": "sleep",
- "ok": true,
- "summary": {
- "total_epochs": 1054,
- "wake_epochs": 134,
- "n1_epochs": 89,
- "n2_epochs": 421,
- "n3_epochs": 298,
- "rem_epochs": 112,
- "epoch_secs": 5
- },
- "analysis": {
- "efficiency_pct": 85.2,
- "onset_latency_min": 12.5,
- "rem_latency_min": 62.0,
- "transitions": 38,
- "awakenings": 11,
- "stage_minutes": { "wake": 11, "n1": 7, "n2": 35, "n3": 25, "rem": 9 },
- "bouts": {
- "WAKE": { "count": 11, "mean_min": 1.0, "max_min": 3.5 },
- "N3": { "count": 6, "mean_min": 4.2, "max_min": 9.0 },
- "REM": { "count": 4, "mean_min": 2.3, "max_min": 4.5 }
- }
- },
- "epochs": [
- { "utc": 1740380100, "stage": 0, "rel_delta": 0.18, "rel_theta": 0.21, "rel_alpha": 0.38, "rel_beta": 0.17 },
- { "utc": 1740380105, "stage": 2, "rel_delta": 0.41, "rel_theta": 0.28, "rel_alpha": 0.19, "rel_beta": 0.09 },
- ...
- ]
- }
- ```
- > **Stage codes:** `0` = Wake, `1` = N1, `2` = N2, `3` = N3, `4` = REM.
- ---
- ### `sleep-schedule`
- View or update the sleep schedule used for session classification and sleep staging analysis.
- The schedule defines your expected bedtime and wake-up time, and can be set to one of five
- built-in presets or a fully custom window.
- ```bash
- # Show current schedule:
- node cli.ts sleep-schedule
- node cli.ts sleep-schedule --json
- # Update with explicit times:
- node cli.ts sleep-schedule set --bedtime 23:00 --wake 07:00
- node cli.ts sleep-schedule set --bedtime 01:00 --wake 09:00
- # Apply a named preset:
- node cli.ts sleep-schedule set --preset early_bird
- node cli.ts sleep-schedule set --preset night_owl
- # Combine preset with override:
- node cli.ts sleep-schedule set --preset short_sleeper
- node cli.ts sleep-schedule set --bedtime 00:30 --wake 06:30 --preset custom
- ```
- **Available presets:**
- | Preset | Bedtime | Wake | Duration |
- |---|---|---|---|
- | `default` | 23:00 | 07:00 | 8 h |
- | `early_bird` | 21:30 | 05:30 | 8 h |
- | `night_owl` | 01:00 | 09:00 | 8 h |
- | `short_sleeper` | 00:00 | 06:00 | 6 h |
- | `long_sleeper` | 22:00 | 08:00 | 10 h |
- When you set `--bedtime` or `--wake` without `--preset`, the preset is automatically
- set to `custom`.
- **HTTP:**
- ```bash
- # Get current schedule:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"sleep_schedule"}'
- # Update schedule:
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"sleep_schedule_set","bedtime":"23:00","wake_time":"07:00","preset":"default"}'
- # Apply a preset (only the fields you send are updated):
- curl -s -X POST http://127.0.0.1:8375/ \
- -H "Content-Type: application/json" \
- -d '{"command":"sleep_schedule_set","preset":"early_bird","bedtime":"21:30","wake_time":"05:30"}'
- ```
- **Example output (default):**
- ```
- ⚡ sleep-schedule current schedule
- Sleep Schedule
- bedtime 23:00
- wake 07:00
- duration 8h (480 min)
- preset default
- Available presets:
- ● default 23:00 — 07:00 (8h)
- ○ early_bird 21:30 — 05:30 (8h)
- ○ night_owl 01:00 — 09:00 (8h)
- ○ short_sleeper 00:00 — 06:00 (6h)
Lines 2,001–4,351 are not shown. The link to the file on GitHub has every line.
README.md · README · 158 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # NeuroSkill™
- [www.neuroskill.com](https://neuroskill.com)
- [](https://github.com/NeuroSkill-com/skill/releases/latest)
- [](https://github.com/NeuroSkill-com/skill/blob/main/LICENSE)
- [](https://discord.gg/Rcvb8Cx4cZ)
- > ⚠️ **Research use only — not a medical device.**
- > NeuroSkill is an open-source EXG/BCI research tool. It is not FDA/CE approved and must not be used for diagnosis or treatment.
- NeuroSkill is a local-first desktop neurofeedback + BCI app built with **Tauri v2 (Rust)** and **SvelteKit**.
- <p align="center">
- <img src="./docs/dashboard.png" alt="NeuroSkill Dashboard" width="49%" />
- <img src="./docs/devices.png" alt="NeuroSkill Supported Devices" width="49%" />
- </p>
- ## Quick links
- - **Downloads:** [latest release](https://github.com/NeuroSkill-com/skill/releases/latest): macOS `.dmg` (Apple Silicon), Windows `-setup.exe`, Linux `.deb`, `.rpm` or portable `.tar.gz`
- - **Install (Homebrew):** `brew install --cask https://raw.githubusercontent.com/NeuroSkill-com/skill/main/Casks/neuroskill.rb`
- - **Contributing:** [CONTRIBUTING.md](CONTRIBUTING.md)
- - **Security:** [SECURITY.md](SECURITY.md): how to report a vulnerability, and how remote devices are paired
- - **Changelog:** [CHANGELOG.md](CHANGELOG.md)
- ## What it does
- - Real-time EXG streaming and visualization
- - GPU band-power analysis + neural embeddings
- - Session comparison, sleep staging, and UMAP visualization
- - Labeling, similarity search, and screenshot-based search
- - Local LLM + TTS integration
- - LSL + remote rlsl-iroh streaming
- - Remote access from a phone over iroh, paired with single-use codes ([SECURITY.md](SECURITY.md))
- - WebSocket/HTTP API
- Models run on the GPU where there is one: Metal on macOS, CUDA or DirectX 12 on
- Windows, CUDA or Vulkan on Linux. Without a usable GPU they run on the CPU.
- ## Supported devices
- <!-- AUTO-GENERATED:SUPPORTED_DEVICES:START -->
- <!-- Run: npm run sync:readme:supported -->
- - **ANT Neuro:** eego 8, eego 24, eego 64, eego mylab, eego sport, eego rt, eego hub
- - **AttentivU:** AttentivU Glasses *(iOS bridge only)*
- - **AWEAR:** AWEAR EEG
- - **BrainBit LLC:** BrainBit, BrainBit 2, BrainBit Flex 4/8
- - **BrainMaster Technologies:** Atlantis 4×4 (4-ch), Discovery (24-ch), Freedom (24-ch wireless)
- - **Cognionics / CGX:** Quick-20r, Quick-32r, Quick-8r, AIM-2
- - **EmotiBit:** EmotiBit sensor board (WiFi / BLE)
- - **Emotiv:** EPOC X, FLEX Saline, Insight, MN8
- - **g.tec medical engineering:** Unicorn Hybrid Black
- - **IDUN:** Guardian
- - **InteraXon:** Muse 2016, Muse 2, Muse S, Muse S Athena
- - **Mendi:** Mendi Headband
- - **Neurofield Inc:** Q21 (20-ch)
- - **Neurosity:** Crown / Notion
- - **NeuroSky:** MindWave / MindWave Mobile
- - **Neurable:** MW75 Neuro
- - **OpenBCI:** Cyton, Cyton Daisy, Galea, Ganglion
- - **Ōura:** Oura Ring (Gen 3 / Gen 4)
- - **Brain Products:** BrainVision RDA
- - **RE-AK:** Nucleus-Hermès
- - **Vital Neuro:** Vital Neuro Headphones
- - **WHOOP:** WHOOP 4.0 / 5.0 / MG strap
- Plus any compatible **LSL** source (e.g. BrainFlow, MATLAB, pylsl).
- <!-- AUTO-GENERATED:SUPPORTED_DEVICES:END -->
- ## Supported EXG/BCI foundation models
- Canonical source: `src-tauri/exg_catalog.json`
- <!-- AUTO-GENERATED:SUPPORTED_MODELS:START -->
- <!-- Run: npm run sync:readme:supported -->
- - **ZUNA** (`Zyphra/ZUNA`)
- - **LUNA Base** (`PulpBio/LUNA`)
- - **LUNA Large** (`PulpBio/LUNA`)
- - **LUNA Huge** (`PulpBio/LUNA`)
- - **REVE Base** (`brain-bzh/reve-base`)
- - **REVE Large** (`brain-bzh/reve-large`)
- - **Brain-JEPA** (`eugenehp/BrainJEPA`)
- - **OpenTSLM** (`StanfordBDHG/OpenTSLM`)
- - **SensorLM** (`google/sensorlm`)
- - **SleepFM** (`zou-group/sleepfm-clinical`)
- - **SleepLM** (`yang-ai-lab/SleepLM`)
- - **OSF Base** (`yang-ai-lab/OSF-Base`)
- - **SignalJEPA** (`braindecode/SignalJEPA-PreLocal-pretrained`)
- - **LaBraM** (`braindecode/labram-pretrained`)
- - **EEGPT** (`braindecode/eegpt-pretrained`)
- - **TRIBE v2** (`eugenehp/tribev2`)
- - **EEG-DINO Small** (`eugenehp/eegdino`)
- - **EEG-DINO Medium** (`eugenehp/eegdino`)
- - **EEG-DINO Large** (`eugenehp/eegdino`)
- - **LuMamba (Reconstruction)** (`PulpBio/LuMamba`)
- - **LuMamba (LeJEPA+Recon 128)** (`PulpBio/LuMamba`)
- - **LuMamba (LeJEPA+Recon 300)** (`PulpBio/LuMamba`)
- - **LuMamba (LeJEPA only)** (`PulpBio/LuMamba`)
- - **NeuroRVQ** (`eugenehp/NeuroRVQ`)
- - **CBraMod** (`braindecode/cbramod-pretrained`)
- - **ST-EEGFormer Small** (`eugenehp/ST-EEGFormer`)
- - **ST-EEGFormer Base** (`eugenehp/ST-EEGFormer`)
- - **ST-EEGFormer Large** (`eugenehp/ST-EEGFormer`)
- <!-- AUTO-GENERATED:SUPPORTED_MODELS:END -->
- ## Documentation
- Long-form documentation lives in `./docs`:
- - Docs index: [docs/README.md](docs/README.md)
- - Architecture overview: [docs/architecture.md](docs/architecture.md)
- - AI/ML model inventory (LLM, EXG, vision, OCR): [docs/AI.md](docs/AI.md)
- - Device support and integration notes: [docs/DEVICES.md](docs/DEVICES.md)
- - UI notes: [docs/UI.md](docs/UI.md)
- - Metrics reference and formulas: [docs/METRICS.md](docs/METRICS.md)
- - Hooks: [docs/HOOKS.md](docs/HOOKS.md)
- - LLM internals: [docs/LLM.md](docs/LLM.md)
- - LSL integration notes: [docs/lsl-integration.md](docs/lsl-integration.md)
- - API reference (WebSocket + HTTP): [docs/API.md](docs/API.md)
- - Development guide: [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)
- - Linux build/packaging: [docs/LINUX.md](docs/LINUX.md)
- - Raspberry Pi (4/5, 64-bit): [docs/RASPBERRY_PI.md](docs/RASPBERRY_PI.md)
- - Windows build setup: [docs/WINDOWS.md](docs/WINDOWS.md)
- ## Development (quickstart)
- Product version lives in the repo-root [`VERSION`](VERSION) file (`npm run bump`
- keeps `package.json`, `src-tauri/tauri.conf.json`, and `src-tauri/Cargo.toml` in
- sync). Release builds enable one daemon OS umbrella (`apple` / `linux` /
- `windows`). PR CI runs clippy/tests; signed product builds run on release tags
- or Preview Build. Details: [CONTRIBUTING.md](CONTRIBUTING.md) ·
- [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md).
- `npm run setup` checks that Rust is installed, offers to install Node.js 22 into
- `~/.local` if it is missing or older than 22.17, offers to install CMake, protoc
- and the other native build tools (Homebrew on macOS, the system package manager
- on Linux), and installs the JavaScript dependencies with
- `npm ci`, the same way CI does. On Windows, follow
- [docs/WINDOWS.md](docs/WINDOWS.md) instead.
- Install the [Hugging Face CLI](https://huggingface.co/docs/huggingface_hub/guides/cli) (`curl -LsSf https://hf.co/cli/install.sh | bash` on macOS/Linux, `powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex"` on Windows), then:
- ```bash
- npm run setup -- --yes
- hf download Zyphra/ZUNA
- npm run tauri dev
- ```
- Build production app:
- ```bash
- npm run tauri:build
- ```
- ## License
- GPL-3.0-only. See [LICENSE](LICENSE).
scripts/ci.mjs · Bundled script · 960 lines · 1 finding marked
- #!/usr/bin/env node
- // SPDX-License-Identifier: GPL-3.0-only
- //
- // Shared CI helpers — single cross-platform entry point (Node.js).
- //
- // Usage:
- // node scripts/ci.mjs <command> [args...]
- //
- // Commands:
- // resolve-version Resolve version from VERSION, validate tag + derived files
- // verify-secrets V1 V2 ... Check env vars are non-empty
- // prepare-changelog VER OUT [RANGE] Generate release notes markdown
- // publish-llm-catalog [--tag T --upload] [--mirror-to-rc-latest] Validate + publish src-tauri/llm_catalog.json
- // update-latest-json ... Merge platform entry into Tauri updater manifest
- // discord-notify ... Send Discord webhook notification
- // import-apple-cert Import .p12 into temporary keychain (macOS)
- // setup-widget-signing Prepare WidgetKit automatic signing (macOS CI)
- // build-widgets Build SkillWidgets.appex with CI signing (macOS)
- // validate-notarization Check Apple notarization credentials (macOS)
- // validate-apple-signing-identity Assert APPLE_SIGNING_IDENTITY is a Developer ID Application cert
- // free-disk-space Remove unused toolchains on Linux runners
- // install-protoc-windows Install protoc via choco or direct download (Windows)
- // compile-product Shared daemon+tty+app cargo recipe (release CI)
- // self-test Validate all commands + workflow references
- // dry-run-release Local release dry-run
- import { execSync, spawnSync } from "child_process";
- import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, rmSync, statSync } from "fs";
- import { basename, join, dirname } from "path";
- import { tmpdir } from "os";
- import { createHash } from "crypto";
- import {
- compileProduct,
- daemonOsFeature,
- parseCompileProductArgs,
- printCompileProductHelp,
- } from "./lib/compile-product.mjs";
- // ── Globals ──────────────────────────────────────────────────────────────────
- let CMD = "ci";
- const T0 = performance.now();
- // ── Helpers ──────────────────────────────────────────────────────────────────
- function log(msg) {
- console.log(`[${CMD}] ${msg}`);
- }
- function ghOutput(key, value) {
- const p = process.env.GITHUB_OUTPUT;
- if (p) writeFileSync(p, `${key}=${value}\n`, { flag: "a" });
- log(`output ${key}=${value}`);
- }
- function ghEnv(key, value) {
- const p = process.env.GITHUB_ENV;
- if (p) writeFileSync(p, `${key}=${value}\n`, { flag: "a" });
- log(`env ${key}=${value}`);
- }
- function ghPath(dir) {
- const p = process.env.GITHUB_PATH;
- if (p) writeFileSync(p, `${dir}\n`, { flag: "a" });
- log(`path +=${dir}`);
- }
- function error(msg) {
- console.log(`::error::[${CMD}] ${msg}`);
- }
- function warning(msg) {
- console.log(`::warning::[${CMD}] ${msg}`);
- }
- /** Product version from repo-root VERSION (source of truth). */
- function confVersion() {
- const raw = readFileSync("VERSION", "utf8").trim();
- const version = raw.split(/\r?\n/)[0]?.trim() ?? "";
- if (!version) throw new Error("VERSION file is empty");
- if (!/^\d+\.\d+\.\d+(?:-rc\.\d+)?$/.test(version)) {
- throw new Error(`Invalid VERSION "${version}" (expected x.y.z or x.y.z-rc.N)`);
- }
- // Derived consumers must stay in sync with VERSION (bump.js writes all of them).
- const pkg = JSON.parse(readFileSync("package.json", "utf8"));
- if (pkg.version !== version) {
- throw new Error(`package.json version (${pkg.version}) does not match VERSION (${version})`);
- }
- const tauriText = readFileSync("src-tauri/tauri.conf.json", "utf8");
- const tauriMatch = tauriText.match(/"version"\s*:\s*"([^"]+)"/);
- if (!tauriMatch) throw new Error("Could not find version in src-tauri/tauri.conf.json");
- if (tauriMatch[1] !== version) {
- throw new Error(
- `src-tauri/tauri.conf.json version (${tauriMatch[1]}) does not match VERSION (${version})`,
- );
- }
- const cargoText = readFileSync("src-tauri/Cargo.toml", "utf8");
- const cargoMatch = cargoText.match(/^version\s*=\s*"([^"]+)"/m);
- if (!cargoMatch) throw new Error("Could not find package version in src-tauri/Cargo.toml");
- if (cargoMatch[1] !== version) {
- throw new Error(
- `src-tauri/Cargo.toml version (${cargoMatch[1]}) does not match VERSION (${version})`,
- );
- }
- for (const path of ["crates/skill-daemon/Cargo.toml", "crates/skill-tty/Cargo.toml"]) {
- const text = readFileSync(path, "utf8");
- const m = text.match(/^version\s*=\s*"([^"]+)"/m);
- if (!m) throw new Error(`Could not find package version in ${path}`);
- if (m[1] !== version) {
- throw new Error(`${path} version (${m[1]}) does not match VERSION (${version})`);
- }
- }
- return version;
- }
- function run(cmd, opts = {}) {
- const isArray = Array.isArray(cmd);
- const label = isArray ? cmd.join(" ") : cmd;
- log(`$ ${label}`);
- const args = isArray ? cmd : [cmd];
- const result = spawnSync(args[0], args.slice(1), {
- stdio: opts.capture ? "pipe" : "inherit",
- shell: !isArray, // shell only for string commands, not arrays
- encoding: "utf8",
- cwd: opts.cwd,
- env: { ...process.env, ...opts.env },
- });
- if (opts.check && result.status !== 0) {
- const err = new Error(`Command failed (exit ${result.status}): ${label}`);
- err.status = result.status;
- err.stdout = result.stdout;
- err.stderr = result.stderr;
- throw err;
- }
- return result;
- }
- function parseArgs(argv, spec) {
- // Minimal arg parser: spec = { "--flag": "key", "--opt": "key" }
- const result = { _: [] };
- let i = 0;
- while (i < argv.length) {
- const arg = argv[i];
- if (spec[arg] !== undefined) {
- if (spec[arg] === true) {
- result[arg.replace(/^--/, "")] = true;
- i++;
- } else {
- result[spec[arg]] = argv[i + 1];
- i += 2;
- }
- } else if (arg.startsWith("--")) {
- // Boolean flag
- result[arg.replace(/^--/, "")] = true;
- i++;
- } else {
- result._.push(arg);
- i++;
- }
- }
- return result;
- }
- // ── Commands ─────────────────────────────────────────────────────────────────
- function cmdResolveVersion() {
- const version = confVersion();
- const event = process.env.GITHUB_EVENT_NAME || "";
- const ref = process.env.GITHUB_REF || "";
- const refName = process.env.GITHUB_REF_NAME || "";
- const dryRun = process.env.DRY_RUN || "false";
- let isRelease = "false";
- let tag = "";
- if (dryRun === "true") {
- tag = `v${version}`;
- log(`[dry-run] Using version from VERSION: ${version}`);
- } else if (event === "push" && ref.startsWith("refs/tags/v")) {
- isRelease = "true";
- tag = refName;
- const tagVer = tag.replace(/^v/, "");
- if (tagVer !== version) {
- error(`Tag version (${tagVer}) does not match VERSION (${version}).`);
- error("Run npm run bump (writes VERSION + derived files), then re-tag.");
- process.exit(1);
- }
- }
- // Channel is derived from the version string itself: a `-rc.N` suffix marks
- // a release candidate. The CI workflow uses `prerelease` to set the GitHub
- // Release flag, and `channel` to decide whether to mirror latest.json into
- // the `rc-latest` mutable release.
- const isRc = /-rc\.\d+$/.test(version);
- const channel = isRc ? "rc" : "stable";
- const prerelease = isRc ? "true" : "false";
- for (const [k, v] of [
- ["is_release", isRelease],
- ["version", version],
- ["tag", tag],
- ["dry_run", dryRun],
- ["channel", channel],
- ["prerelease", prerelease],
- ]) {
- ghOutput(k, v);
- }
- ghEnv("VERSION", version);
- ghEnv("TAG", tag);
- console.log(`✓ Version: ${version} (release=${isRelease}, channel=${channel}, dry_run=${dryRun})`);
- }
- function cmdVerifySecrets(args) {
- const names = args._;
- let ok = true;
- for (const name of names) {
- if (!process.env[name]) {
- error(`Secret '${name}' is empty or not set.`);
- ok = false;
- }
- }
- if (!ok) process.exit(1);
- console.log(`✓ All required secrets are present (${names.length} checked).`);
- }
- function cmdPrepareChangelog(args) {
- const [version, output] = args._;
- const commitRange = args._[2] || "HEAD~50..HEAD";
- if (!version || !output) {
- console.error("Usage: prepare-changelog <version> <output> [range]");
- process.exit(1);
- }
- // Extract changelog section
- let section = "";
- try {
- const changelog = readFileSync("CHANGELOG.md", "utf8");
- const re = new RegExp(`^## \\[${version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\]`, "m");
- const start = changelog.search(re);
- if (start >= 0) {
- const afterHeader = changelog.indexOf("\n", start) + 1;
- const nextSection = changelog.indexOf("\n## [", afterHeader);
- section = changelog.slice(afterHeader, nextSection > 0 ? nextSection : undefined).trim();
- }
- } catch {}
- // Contributors
- let contributors = "";
- try {
- const r = run(["git", "log", `--format=%aN`, commitRange], { capture: true });
- const seen = new Set();
- for (const name of (r.stdout || "").split("\n").map((l) => l.trim()).filter(Boolean)) {
- if (!seen.has(name)) {
- seen.add(name);
- contributors += `- ${name}\n`;
- }
- }
- } catch {}
- let body = "## Changelog\n\n";
- body += section || `_No changelog section found for version ${version} in CHANGELOG.md._`;
- body += "\n\n## Contributors\n\n";
- body += contributors || `_No commit contributors found in range ${commitRange}._\n`;
- writeFileSync(output, body);
- const lines = body.split("\n").length;
- console.log(`✓ Release notes written to ${output} (${lines} lines)`);
- }
- function cmdUpdateLatestJson(args) {
- const { platform, url, "sig-file": sigFile, tag, version, upload } = args;
- const mirrorToRcLatest = args["mirror-to-rc-latest"] || false;
- const signature = readFileSync(sigFile, "utf8").trim();
- // Try to download existing manifest
- const dl = run(["gh", "release", "download", tag, "--pattern", "latest.json", "--output", "latest.json", "--clobber"], { capture: true });
- let manifest;
- if (dl.status === 0 && existsSync("latest.json")) {
- manifest = JSON.parse(readFileSync("latest.json", "utf8"));
- } else {
- let notes = "";
- try {
- const r = run(["git", "tag", "-l", "--format=%(contents)", tag], { capture: true });
- notes = (r.stdout || "").trim();
- } catch {}
- if (!notes) notes = `NeuroSkill\u2122 v${version}`;
- manifest = {
- version,
- notes,
- pub_date: new Date().toISOString().replace(/\.\d+Z$/, "Z"),
- platforms: {},
- };
- }
- manifest.platforms = manifest.platforms || {};
- manifest.platforms[platform] = { url, signature };
- writeFileSync("latest.json", JSON.stringify(manifest, null, 2) + "\n");
- const plats = Object.keys(manifest.platforms).sort().join(", ");
- console.log(`Updated latest.json (${Object.keys(manifest.platforms).length} platform(s): ${plats})`);
- if (upload) {
- run(["gh", "release", "upload", tag, "latest.json", "--clobber"], { check: true });
- console.log(`✓ latest.json uploaded to release ${tag}`);
- }
- // The `rc-latest` release is a mutable pointer used by the RC update channel.
- // Both stable and RC builds mirror their latest.json here so opted-in users
- // always receive the most recent build of either kind. Stable users hit
- // `releases/latest/download/latest.json` instead, which GitHub auto-resolves
- // to the most recent non-prerelease release (skipping RCs).
- if (mirrorToRcLatest) {
- ensureRcLatestRelease();
- run(["gh", "release", "upload", "rc-latest", "latest.json", "--clobber"], { check: true });
- console.log("✓ latest.json mirrored to rc-latest");
- }
- }
- /**
- * Ensure the `rc-latest` GitHub Release exists. It's a mutable pointer release
- * tagged at whatever commit was current when first created — the tag itself
- * doesn't matter because the URL clients use is
- * https://github.com/<repo>/releases/download/rc-latest/latest.json
- * which is asset-based, not commit-based. Marked `prerelease` so it never
- * becomes "latest" in GitHub's auto-resolution.
- */
- function ensureRcLatestRelease() {
- const view = run(["gh", "release", "view", "rc-latest"], { capture: true });
- if (view.status === 0) return;
- log("rc-latest release does not exist — creating");
- run([
- "gh", "release", "create", "rc-latest",
- "--prerelease",
- "--title", "RC channel pointer",
- "--notes", "Mutable release that always carries the latest latest.json (RC or stable build). Used by users opted into the rc update channel. Do not delete.",
- ], { check: true });
- }
- /**
- * Problems with an LLM catalog that would mislead users or break the app; [] if
- * none. Curated quirks the app tolerates (a family with two hand-picked
- * recommended quants) are not errors.
- */
- export function validateLlmCatalog(cat) {
- const errors = [];
- if (!cat || typeof cat !== "object") return ["catalog is not a JSON object"];
- const families = cat.families ?? {};
- const models = Array.isArray(cat.models) ? cat.models : [];
- if (models.length === 0) errors.push("no models");
- const seen = new Set();
- for (const m of models) {
- const id = `${m.family}/${m.filename}`;
- if (!families[m.family]) errors.push(`${id}: unknown family`);
- // GGUF files, or multi-file packs (mlx-community) listing their files.
- const isPack = Array.isArray(m.shard_files) && m.shard_files.includes(m.filename);
- if (!/\.gguf$/i.test(m.filename ?? "") && !isPack) errors.push(`${id}: not a .gguf file or a listed pack file`);
- if (!(typeof m.size_gb === "number" && m.size_gb > 0)) errors.push(`${id}: size_gb must be > 0`);
- if (seen.has(id)) errors.push(`${id}: duplicate entry`);
- seen.add(id);
- }
- for (const [id, f] of Object.entries(families)) {
- if (!f.repo) errors.push(`family ${id}: no repo`);
- }
- const isMmproj = (m) => /mmproj/i.test(m.filename);
- const active = models.find((m) => m.filename === cat.active_model);
- if (!active) errors.push(`active_model ${cat.active_model} is not in the catalog`);
- else if (isMmproj(active)) errors.push(`active_model ${cat.active_model} is a vision projector`);
- if (cat.active_mmproj && !models.some((m) => isMmproj(m) && m.filename === cat.active_mmproj)) {
- errors.push(`active_mmproj ${cat.active_mmproj} is not a projector in the catalog`);
- }
- return errors;
- }
- /**
- * Publish the bundled LLM catalog (src-tauri/llm_catalog.json — the file
- * compiled into this build) as release assets with a `compatibility` block
- * ([`llmCatalogCompatibility`]) prepended, plus a SHA-256.
- *
- * Usage:
- * node scripts/ci.mjs publish-llm-catalog [--tag <tag>] [--upload] [--mirror-to-rc-latest]
- *
- * Without --upload it only validates and writes the files (dry run). Stable
- * clients can then fetch releases/latest/download/llm_catalog.json; the RC
- * channel reads the copy mirrored to the `rc-latest` release.
- */
- /** Layout of llm_catalog.json (normalized `families` + `models`). Bump when
- * the app can no longer read an older catalog, or an older app a newer one. */
- const LLM_CATALOG_SCHEMA = 1;
- /** First release whose app reads schema 1 (catalog normalized in d04cd538). */
- const LLM_CATALOG_MIN_APP_VERSION = "0.0.131-rc.10";
- /** Platforms every release builds — the latest.json platform keys. */
- const RELEASE_PLATFORMS = ["darwin-aarch64", "linux-x86_64", "windows-x86_64"];
- /** The rlx git revision this build runs models on, from Cargo.lock. */
- function lockedRlxRevision() {
- const lock = readFileSync("Cargo.lock", "utf8");
- const m = lock.match(/\[\[package\]\]\nname = "rlx"\nversion = "([^"]+)"\nsource = "([^"]+)"/);
- if (!m) return null;
- const [, version, source] = m;
- return { version, source: source.replace(/#.*$/, ""), rev: source.includes("#") ? source.split("#").pop() : null };
- }
- /**
- * What a published catalog is compatible with. Reading it needs an app of at
- * least `min_app_version`; the models in it were bundled with, and validated
- * against, `bundled_in` (that app build) running `runtime.rlx`. An older app
- * can read the catalog but may lack runtime support for a newer model.
- */
- function llmCatalogCompatibility() {
- const version = confVersion();
- const commit = process.env.GITHUB_SHA || run(["git", "rev-parse", "HEAD"], { capture: true }).stdout.trim();
- return {
- schema: LLM_CATALOG_SCHEMA,
- min_app_version: LLM_CATALOG_MIN_APP_VERSION,
- bundled_in: { version, tag: `v${version}`, commit, platforms: RELEASE_PLATFORMS },
- runtime: { rlx: lockedRlxRevision() },
- };
- }
- function cmdPublishLlmCatalog(args) {
- const src = "src-tauri/llm_catalog.json";
- const cat = JSON.parse(readFileSync(src, "utf8"));
- const errors = validateLlmCatalog(cat);
- if (errors.length) {
- throw new Error(`${src} is not publishable:\n ${errors.join("\n ")}`);
- }
- // The bundled catalog plus where it is compatible (the app ignores unknown
- // top-level fields, so this stays readable by any schema-1 app).
- const compatibility = llmCatalogCompatibility();
- const raw = `${JSON.stringify({ compatibility, ...cat }, null, 2)}\n`;
- const files = ["llm_catalog.json", "llm_catalog.json.sha256"];
- writeFileSync(files[0], raw);
- writeFileSync(files[1], `${createHash("sha256").update(raw).digest("hex")} llm_catalog.json\n`);
- console.log(`✓ llm_catalog.json valid (${cat.models.length} models, ${Object.keys(cat.families).length} families, default ${cat.active_model})`);
- console.log(` compatible: app >= ${compatibility.min_app_version} (schema ${compatibility.schema}); bundled in v${compatibility.bundled_in.version}, rlx ${compatibility.runtime.rlx?.rev?.slice(0, 8) ?? "?"}`);
- if (args.upload) {
- if (!args.tag) throw new Error("--upload needs --tag");
- run(["gh", "release", "upload", args.tag, ...files, "--clobber"], { check: true });
- console.log(`✓ llm_catalog.json uploaded to release ${args.tag}`);
- }
- if (args["mirror-to-rc-latest"]) {
- ensureRcLatestRelease();
- run(["gh", "release", "upload", "rc-latest", ...files, "--clobber"], { check: true });
- console.log("✓ llm_catalog.json mirrored to rc-latest");
- }
- }
- /**
- * Reconcile the Homebrew cask (Casks/neuroskill.rb) to a released build.
- *
- * Usage:
- * node scripts/ci.mjs update-cask [--version <ver>] [--sha256 <hex>]
- * [--dmg <path>] [--cask <path>] [--repo <owner/name>]
- *
- * Resolution:
- * version : --version, else the latest *stable* (non-prerelease) GitHub release.
- * sha256 : --sha256, else computed from --dmg, else the release asset's digest
- * fetched via `gh api` (no download of the ~100 MB DMG).
- *
- * Only the `version` and `sha256` lines are rewritten — every other stanza
- * (depends_on, zap, url template, …) is preserved. Idempotent: a no-op when the
- * cask already matches, so the reconcile workflow only opens a PR on real drift.
- */
- function cmdUpdateCask(args) {
- const repo = args.repo || process.env.GITHUB_REPOSITORY || "NeuroSkill-com/skill";
- const caskPath = args.cask || "Casks/neuroskill.rb";
- // 1. Resolve the target version — explicit, or the latest non-prerelease release.
- let version = args.version;
- if (version) {
- version = version.replace(/^v/, "");
- } else {
- const r = run(["gh", "api", `repos/${repo}/releases/latest`, "-q", ".tag_name"], { capture: true, check: true });
- version = (r.stdout || "").trim().replace(/^v/, "");
- if (!version) throw new Error("could not resolve the latest stable release");
- }
- const dmgName = `NeuroSkill_${version}_aarch64.dmg`;
- // 2. Resolve the sha256 — explicit, from a local DMG, or the release asset digest.
- let sha256 = args.sha256;
- if (!sha256 && args.dmg) {
- sha256 = createHash("sha256").update(readFileSync(args.dmg)).digest("hex");
- }
- if (!sha256) {
- const q = `.assets[] | select(.name=="${dmgName}") | .digest`;
- const r = run(["gh", "api", `repos/${repo}/releases/tags/v${version}`, "-q", q], { capture: true, check: true });
- const digest = (r.stdout || "").trim();
- if (!digest) throw new Error(`release v${version} has no asset named ${dmgName}`);
- sha256 = digest.replace(/^sha256:/, "");
- }
- if (!/^[0-9a-f]{64}$/.test(sha256)) throw new Error(`invalid sha256: ${sha256}`);
- // 3. Rewrite the version + sha256 lines, preserving everything else.
- const before = readFileSync(caskPath, "utf8");
- if (!/^\s*version\s+"/m.test(before) || !/^\s*sha256\s+"/m.test(before)) {
- throw new Error(`${caskPath} is missing a version or sha256 stanza`);
- }
- const after = before
- .replace(/^(\s*version\s+)"[^"]*"/m, `$1"${version}"`)
- .replace(/^(\s*sha256\s+)"[^"]*"/m, `$1"${sha256}"`);
- if (after === before) {
- console.log(`Cask already current: version ${version}, sha256 ${sha256.slice(0, 12)}…`);
- return;
- }
- writeFileSync(caskPath, after);
- console.log(`Updated ${caskPath} → version ${version}, sha256 ${sha256.slice(0, 12)}…`);
- }
- async function cmdDiscordNotify(args) {
- const webhook = process.env.DISCORD_WEBHOOK_URL;
- if (!webhook) {
- console.log("⚠ DISCORD_WEBHOOK_URL not set, skipping.");
- return;
- }
- let commit = "";
- try {
- // Full message (subject + body). Cap for the Discord embed field
- // (limit 1024) and add an ellipsis when truncated.
- const r = run(["git", "log", "-1", "--format=%B"], { capture: true });
- const full = (r.stdout || "").trim();
- commit = full.length > 500 ? `${full.slice(0, 500)}…` : full;
- } catch {}
- const { status, title, version, tag, platform } = args;
- const releaseUrl = args["release-url"] || "";
- const runUrl = args["run-url"] || "";
- const color = status === "success" ? 3066993 : 15158332;
- const desc = status === "success"
- ? `Build published and ready to download.\n\n**[Download v${version}](${releaseUrl || runUrl})**`
- : `The build failed. Check the run for details.\n\n**[View failed run](${runUrl})**`;
- const payload = JSON.stringify({
- embeds: [{
- title, description: desc, url: runUrl, color,
- fields: [
- { name: "Tag", value: `\`${tag}\``, inline: true },
- { name: "Version", value: `\`${version}\``, inline: true },
- { name: "Platform", value: platform, inline: true },
- { name: "Actor", value: process.env.GITHUB_ACTOR || "ci", inline: true },
- { name: "Commit", value: commit, inline: false },
- ],
- footer: { text: process.env.GITHUB_REPOSITORY || "" },
- }],
- });
- try {
- // Use built-in fetch (Node 18+) to avoid platform-specific curl quoting issues.
- const r = await fetch(webhook, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: payload,
- });
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
- } catch {
- console.log("⚠ Discord notification failed (non-fatal).");
- }
- }
- function findFiles(dir) {
- const results = [];
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
- const full = join(dir, entry.name);
- if (entry.isDirectory()) results.push(...findFiles(full));
- else results.push(full);
- }
- return results;
- }
- // Apple ships several certificate types under "codesigning". Only one of them
- // — `Developer ID Application` — produces binaries Gatekeeper trusts for
- // distribution. The Safari extension wrapper this app builds at runtime is
- // only loaded by Safari when the parent (.app) clears Gatekeeper, so signing
- // the main app with anything else (Apple Development, Mac Developer, ad-hoc,
- // self-signed) silently breaks the Safari extension flow on end-user Macs.
- //
- // Catch the wrong identity here, before a 15-minute build burns a release
- // slot. The check is cheap: just inspect the secret string.
- function cmdValidateAppleSigningIdentity() {
- const id = process.env.APPLE_SIGNING_IDENTITY || "";
- if (!id) {
- error("APPLE_SIGNING_IDENTITY is empty.");
- process.exit(1);
- }
- if (!id.startsWith("Developer ID Application")) {
- error(`APPLE_SIGNING_IDENTITY must be a 'Developer ID Application' certificate.`);
- error(` Got: ${id.replace(/\(.+\)/, "(…)")}`);
- error(` Why: only Developer ID Application certs pass Gatekeeper for distribution.`);
- error(` Apple Development / Mac Developer certs only work for the signing`);
- error(` developer's own Mac via Xcode — Safari refuses to load extensions`);
- error(` from apps Gatekeeper rejects on end-user machines.`);
- error(` Fix: regenerate the cert at https://developer.apple.com/account/resources/certificates`);
- error(` choosing 'Developer ID Application', export to .p12, and update both`);
- error(` APPLE_CERTIFICATE and APPLE_SIGNING_IDENTITY secrets.`);
- process.exit(1);
- }
- console.log(`✓ APPLE_SIGNING_IDENTITY is a Developer ID Application certificate.`);
- }
- function cmdImportAppleCert() {
- const tmp = process.env.RUNNER_TEMP;
- const keychain = join(tmp, "app-signing.keychain-db");
- const password = execSync("openssl rand -base64 32", { encoding: "utf8" }).trim();
- ghEnv("KEYCHAIN_PATH", keychain);
- ghEnv("KEYCHAIN_PASSWORD", password);
- run(["security", "create-keychain", "-p", password, keychain], { check: true });
- run(["security", "set-keychain-settings", "-lut", "21600", keychain], { check: true });
- run(["security", "unlock-keychain", "-p", password, keychain], { check: true });
- const certPath = join(tmp, "cert.p12");
- writeFileSync(certPath, Buffer.from(process.env.APPLE_CERTIFICATE, "base64"));
- run(["security", "import", certPath, "-k", keychain, "-P", process.env.APPLE_CERTIFICATE_PASSWORD, "-T", "/usr/bin/codesign", "-T", "/usr/bin/security"], { check: true });
- rmSync(certPath);
- run(["security", "set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", password, keychain], { check: true });
- run(["security", "list-keychains", "-d", "user", "-s", keychain, "login.keychain"], { check: true });
- Dismissed after review: Reads a credential file in a script that also sends data over the network
- Line 625 on GitHub
- console.log(`✓ Apple Developer certificate imported into ${keychain}`);
- }
- /** Prepare WidgetKit automatic signing on GitHub Actions runners. */
- function cmdSetupWidgetSigning() {
- const teamId = process.env.APPLE_TEAM_ID;
- if (!teamId) {
- warning("APPLE_TEAM_ID not set — skipping widget signing setup");
- return;
- }
- ghEnv("WIDGET_CODE_SIGN_STYLE", "Automatic");
- // Optional: App Store Connect API key for -allowProvisioningUpdates.
- const ascKeyId = process.env.APPLE_ASC_KEY_ID;
- const ascIssuer = process.env.APPLE_ASC_KEY_ISSUER_ID;
- const ascKeyB64 = process.env.APPLE_ASC_KEY_BASE64;
- if (ascKeyId && ascIssuer && ascKeyB64) {
- const keyDir = join(process.env.HOME, ".private_keys");
- mkdirSync(keyDir, { recursive: true });
- const keyPath = join(keyDir, `AuthKey_${ascKeyId}.p8`);
- writeFileSync(keyPath, Buffer.from(ascKeyB64, "base64"), { mode: 0o600 });
- ghEnv("AUTH_KEY_PATH", keyPath);
- ghEnv("AUTH_KEY_ID", ascKeyId);
- ghEnv("AUTH_KEY_ISSUER_ID", ascIssuer);
- console.log(`✓ App Store Connect API key installed for widget provisioning (${ascKeyId})`);
- } else {
- console.log("ℹ No APPLE_ASC_KEY_* secrets — relying on portal profiles + -allowProvisioningUpdates");
- }
- // Optional: pre-downloaded macOS provisioning profile (base64 .provisionprofile).
- const profileB64 = process.env.APPLE_WIDGET_PROVISIONING_PROFILE_BASE64;
- if (profileB64) {
- const profileDir = join(process.env.HOME, "Library/MobileDevice/Provisioning Profiles");
- mkdirSync(profileDir, { recursive: true });
- const profilePath = join(profileDir, "SkillWidgetsWidgetExtension.provisionprofile");
- writeFileSync(profilePath, Buffer.from(profileB64, "base64"));
- console.log(`✓ Widget provisioning profile installed (${profilePath})`);
- }
- console.log(`✓ Widget signing ready (team ${teamId}, automatic)`);
- }
- function cmdBuildWidgets() {
- const widgetScript = join("extensions", "widgets", "build-widgets.sh");
- if (!existsSync(widgetScript)) {
- throw new Error(`Missing ${widgetScript}`);
- }
- run(["bash", widgetScript, "--release", "--ci"], { check: true });
- }
- function cmdValidateNotarization() {
- console.log("Checking notarization credentials …");
- const r = run(["xcrun", "notarytool", "history", "--apple-id", process.env.APPLE_ID, "--password", process.env.APPLE_PASSWORD, "--team-id", process.env.APPLE_TEAM_ID, "--output-format", "json"], { capture: true });
- const output = (r.stdout || "") + (r.stderr || "");
- if (output.includes('"history"')) {
- console.log("✓ Notarization credentials are valid.");
- } else if (/unauthorized|invalid.*credentials|401/i.test(output)) {
- error("Apple notarization credentials are invalid.");
- error("Generate a new app-specific password at https://appleid.apple.com");
- error("Then update APPLE_PASSWORD in: GitHub → Settings → Environments → Release → Secrets");
- process.exit(1);
- } else {
- warning("Could not verify notarization credentials (Apple API may be intermittent).");
- warning(`Output: ${output.slice(0, 500)}`);
- console.log("Proceeding — actual notarization will fail later if credentials are invalid.");
- }
- }
- function cmdFreeDiskSpace() {
- const dirs = ["/usr/local/lib/android", "/usr/share/dotnet", "/opt/ghc", "/usr/local/.ghcup", "/usr/local/share/powershell", "/usr/local/share/chromium", "/usr/share/swift", "/opt/hostedtoolcache/CodeQL"];
- for (const d of dirs) {
- if (existsSync(d)) run(["sudo", "rm", "-rf", d]);
- }
- run(["sudo", "docker", "image", "prune", "-af"], { capture: true });
- run(["df", "-h", "/"]);
- }
- function cmdInstallProtocWindows() {
- // Check if already installed
- const which = run(["where", "protoc"], { capture: true });
- if (which.status === 0) {
- run(["protoc", "--version"]);
- return;
- }
- // Try Chocolatey
- let installed = false;
- for (let i = 1; i <= 3; i++) {
- run(["choco", "install", "protoc", "--no-progress", "-y"], { capture: true });
- const check = run(["where", "protoc"], { capture: true });
- if (check.status === 0) {
- installed = true;
- break;
- }
- log(`choco attempt ${i} failed, retrying in ${5 * i}s...`);
- execSync(`timeout /t ${5 * i} /nobreak >nul 2>&1`, { shell: true, stdio: "ignore" });
- }
- if (!installed) {
- console.log("[warn] Chocolatey unavailable; falling back to direct download");
- const ver = "25.3";
- const url = `https://github.com/protocolbuffers/protobuf/releases/download/v${ver}/protoc-${ver}-win64.zip`;
- const tmp = process.env.RUNNER_TEMP || tmpdir();
- const zipPath = join(tmp, `protoc-${ver}-win64.zip`);
- const dest = join(tmp, `protoc-${ver}`);
- execSync(`curl -fSL "${url}" -o "${zipPath}"`, { stdio: "inherit" });
- execSync(`tar -xf "${zipPath}" -C "${dest}"`, { stdio: "inherit" });
- const binDir = join(dest, "bin");
- if (!existsSync(join(binDir, "protoc.exe"))) {
- throw new Error("protoc fallback install failed: protoc.exe not found");
- }
- ghPath(binDir);
- process.env.PATH = `${binDir};${process.env.PATH}`;
- console.log("[ok] Installed protoc via direct download");
- }
- run(["protoc", "--version"]);
- }
- function cmdCompileProduct() {
- const opts = parseCompileProductArgs(process.argv.slice(3));
- if (opts.help) {
- printCompileProductHelp();
- return;
- }
- compileProduct(opts);
- }
- function cmdSelfTest() {
- const errors = [];
- const commandMap = {
- "resolve-version": cmdResolveVersion, "verify-secrets": cmdVerifySecrets,
- "prepare-changelog": cmdPrepareChangelog, "update-latest-json": cmdUpdateLatestJson,
- "discord-notify": cmdDiscordNotify,
- "import-apple-cert": cmdImportAppleCert,
- "setup-widget-signing": cmdSetupWidgetSigning,
- "build-widgets": cmdBuildWidgets,
- "validate-notarization": cmdValidateNotarization,
- "validate-apple-signing-identity": cmdValidateAppleSigningIdentity,
- "free-disk-space": cmdFreeDiskSpace, "install-protoc-windows": cmdInstallProtocWindows,
- "compile-product": cmdCompileProduct,
- "self-test": cmdSelfTest, "dry-run-release": cmdDryRunRelease,
- "update-cask": cmdUpdateCask, "publish-llm-catalog": cmdPublishLlmCatalog,
- };
- for (const [name, fn] of Object.entries(commandMap)) {
- if (typeof fn !== "function") errors.push(` ${name}: not a function`);
- else log(`✓ ${name}`);
- }
- // Check workflow references
- try {
- const known = new Set(Object.keys(commandMap));
- for (const yml of readdirSync(".github/workflows").filter((f) => f.endsWith(".yml"))) {
- const content = readFileSync(join(".github/workflows", yml), "utf8");
- const re = /scripts\/ci\.mjs\s+([a-z][-a-z]*)/g;
- let m;
- while ((m = re.exec(content))) {
- if (!known.has(m[1])) errors.push(` ${yml}: unknown command '${m[1]}'`);
- }
- }
- } catch {}
- // The catalog every release publishes (publish-llm-catalog) must be valid.
- try {
- const catErrors = validateLlmCatalog(JSON.parse(readFileSync("src-tauri/llm_catalog.json", "utf8")));
- if (catErrors.length) errors.push(...catErrors.map((e) => ` llm_catalog.json: ${e}`));
- else log("✓ llm_catalog.json publishable");
- } catch (e) {
- errors.push(` llm_catalog.json: ${e.message}`);
- }
- // Verify confVersion
- try {
- const v = confVersion();
- log(`✓ confVersion() = ${v}`);
- } catch (e) {
- errors.push(` confVersion(): ${e.message}`);
- }
- // OS umbrella mapping
- try {
- const cases = [
- ["aarch64-apple-darwin", "apple"],
- ["x86_64-unknown-linux-gnu", "linux"],
- ["x86_64-pc-windows-msvc", "windows"],
- ];
- for (const [triple, want] of cases) {
- const got = daemonOsFeature(triple);
- if (got !== want) {
- errors.push(` daemonOsFeature(${triple}): got ${got}, want ${want}`);
- }
- }
- log("✓ daemonOsFeature OS mapping");
- } catch (e) {
- errors.push(` daemonOsFeature(): ${e.message}`);
- }
- if (errors.length) {
- error("self-test failed:");
- errors.forEach((e) => console.log(e));
- process.exit(1);
- }
- log(`✓ all ${Object.keys(commandMap).length} commands OK`);
- }
- function cmdDryRunRelease(args) {
- const target = args.target || "aarch64-apple-darwin";
- const skipCompile = args["skip-compile"] || false;
- log("Step 1/6: resolve version");
- const version = confVersion();
- log(`version = ${version}`);
- log("Step 2/6: build frontend");
- if (!skipCompile) run(["npm", "run", "build"], { check: true });
- else log("(skipped)");
- log("Step 3/6: cargo build (compile-product)");
- if (!skipCompile) {
- compileProduct({
- target,
- release: true,
- locked: false,
- timings: false,
- daemon: true,
- app: true,
- tty: "auto",
- });
- } else log("(skipped)");
- log("Step 4/6: assemble .app bundle");
- const binary = `src-tauri/target/${target}/release/skill`;
- if (!existsSync(binary)) {
- if (skipCompile) warning(`Binary not found at ${binary} — run without --skip-compile first`);
- else { error(`Binary not found at ${binary} after build`); process.exit(1); }
- } else {
- run(["bash", "scripts/assemble-macos-app.sh", target], { check: true });
- }
- log("Step 5/6: prepare changelog");
- const tag = `v${version}`;
- const prev = run(["git", "describe", "--tags", "--abbrev=0", `${tag}^`], { capture: true });
- const prevTag = prev.status === 0 ? prev.stdout.trim() : "";
- const range = prevTag ? `${prevTag}..HEAD` : "HEAD~20..HEAD";
- cmdPrepareChangelog({ _: [version, "dry-run-release-notes.md", range] });
- log("Step 6/6: summary");
- const app = `src-tauri/target/${target}/release/bundle/macos/NeuroSkill.app`;
- console.log("\n" + "=".repeat(60));
- console.log(` Dry-run release: v${version} (${target})`);
- console.log("=".repeat(60));
- if (existsSync(app)) {
- const size = findFiles(app).reduce((s, f) => s + statSync(f).size, 0);
- console.log(` .app bundle: ${app} (${(size / 1048576).toFixed(1)} MB)`);
- } else console.log(" .app bundle: (not found)");
- console.log(" changelog: dry-run-release-notes.md");
- console.log(`\n To run: open '${app}'`);
- console.log(` To sign: APPLE_SIGNING_IDENTITY=... bash scripts/assemble-macos-app.sh ${target}`);
- console.log("=".repeat(60) + "\n");
- }
- // ── CLI ──────────────────────────────────────────────────────────────────────
- const COMMANDS = {
- "resolve-version": cmdResolveVersion,
- "verify-secrets": cmdVerifySecrets,
- "prepare-changelog": cmdPrepareChangelog,
- "update-latest-json": (a) => cmdUpdateLatestJson(a),
- "discord-notify": (a) => cmdDiscordNotify(a),
- "import-apple-cert": cmdImportAppleCert,
- "setup-widget-signing": cmdSetupWidgetSigning,
- "build-widgets": cmdBuildWidgets,
- "validate-notarization": cmdValidateNotarization,
- "validate-apple-signing-identity": cmdValidateAppleSigningIdentity,
- "free-disk-space": cmdFreeDiskSpace,
- "install-protoc-windows": cmdInstallProtocWindows,
- "compile-product": cmdCompileProduct,
- "self-test": cmdSelfTest,
- "dry-run-release": (a) => cmdDryRunRelease(a),
- "update-cask": cmdUpdateCask,
- "publish-llm-catalog": cmdPublishLlmCatalog,
- };
- async function main() {
- const argv = process.argv.slice(2);
- const command = argv[0];
- if (!command || command === "--help" || command === "-h") {
- console.log("Usage: node scripts/ci.mjs <command> [args...]");
- console.log("\nCommands:");
- for (const name of Object.keys(COMMANDS)) console.log(` ${name}`);
- process.exit(0);
- }
- if (!COMMANDS[command]) {
- error(`Unknown command: ${command}`);
- process.exit(1);
- }
- CMD = command;
- const args = parseArgs(argv.slice(1), {
- "--platform": "platform", "--url": "url", "--sig-file": "sig-file",
- "--tag": "tag", "--version": "version", "--upload": true,
- "--mirror-to-rc-latest": true,
- "--status": "status", "--title": "title", "--release-url": "release-url",
- "--run-url": "run-url", "--target": "target", "--skip-compile": true,
- "--sha256": "sha256", "--dmg": "dmg", "--cask": "cask", "--repo": "repo",
- });
- log("starting");
- try {
- await COMMANDS[command](args);
- } catch (e) {
- if (e.status !== undefined) {
- error(`Command failed (exit ${e.status}): ${e.message}`);
- if (e.stdout) console.log(`[${CMD}] stdout:\n${e.stdout.trim()}`);
- if (e.stderr) console.log(`[${CMD}] stderr:\n${e.stderr.trim()}`);
- } else {
- error(`${e.constructor.name}: ${e.message}`);
- console.error(e.stack);
- }
- const elapsed = ((performance.now() - T0) / 1000).toFixed(1);
- error(`Failed after ${elapsed}s`);
- process.exit(1);
- }
- const elapsed = ((performance.now() - T0) / 1000).toFixed(1);
- log(`done (${elapsed}s)`);
- }
- main();
scripts/create-windows-nsis.ps1 · Bundled script · 910 lines · 2 findings marked
- <#
- .SYNOPSIS
- Create a Windows NSIS installer from a pre-built release binary.
- .DESCRIPTION
- Assembles the application directory structure, generates an NSIS installer
- with background/banner images (app icon + version), and optionally signs
- the installer with a code-signing certificate.
- This script bypasses the Tauri CLI bundler for cases where it fails or
- when a standalone packaging step is preferred.
- Prerequisites:
- - NSIS installed (makensis on PATH, or set $env:NSIS_DIR)
- Install: choco install nsis -or- winget install NSIS.NSIS
- - Python 3 with Pillow (for installer images)
- Install: pip install Pillow
- - The release binary must be pre-built
- .PARAMETER Target
- Rust target triple (default: x86_64-pc-windows-msvc)
- .PARAMETER Sign
- When set, sign the installer with signtool.exe using $env:CERTIFICATE_THUMBPRINT
- .EXAMPLE
- .\scripts\create-windows-nsis.ps1
- .\scripts\create-windows-nsis.ps1 -Sign
- $env:CERTIFICATE_THUMBPRINT = "ABC123..." ; .\scripts\create-windows-nsis.ps1 -Sign
- #>
- param(
- [string]$Target = "x86_64-pc-windows-msvc",
- [switch]$Sign
- )
- Set-StrictMode -Version Latest
- $ErrorActionPreference = "Stop"
- # Ensure consistent UTF-8 handling for trademark and other non-ASCII UI text.
- try {
- $utf8NoBom = New-Object System.Text.UTF8Encoding($false)
- [Console]::InputEncoding = $utf8NoBom
- [Console]::OutputEncoding = $utf8NoBom
- $OutputEncoding = $utf8NoBom
- chcp 65001 | Out-Null
- } catch {
- # best-effort only; keep script functional in restricted hosts
- }
- $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
- $Root = Split-Path -Parent $ScriptDir
- $TauriDir = Join-Path $Root "src-tauri"
- $Conf = Get-Content (Join-Path $TauriDir "tauri.conf.json") -Raw | ConvertFrom-Json
- $ProductName = $Conf.productName
- $ProductDisplayName = if ($ProductName.EndsWith("™")) { $ProductName } else { "$ProductName™" }
- $Version = $Conf.version
- # NSIS's VIProductVersion requires strict 4-segment numeric format X.X.X.X
- # (Win32 VS_FIXEDFILEINFO). User-facing ProductVersion/FileVersion strings
- # accept any text, but VIProductVersion does not — it rejects "-rc.N" suffixes.
- # Map the SemVer string to a numeric 4-tuple:
- # "0.0.130" -> "0.0.130.0"
- # "0.0.130-rc.2" -> "0.0.130.2" (use RC number as fourth segment)
- # "0.0.130-beta.7" -> "0.0.130.7"
- if ($Version -match '^(\d+\.\d+\.\d+)(?:-[A-Za-z]+\.(\d+))?') {
- $vibase = $Matches[1]
- $vibuild = if ($Matches[2]) { $Matches[2] } else { "0" }
- $VIVersion = "$vibase.$vibuild"
- } else {
- $VIVersion = "0.0.0.0"
- }
- $BinaryName = "skill.exe"
- $TargetReleaseDir = Join-Path $TauriDir "target/$Target/release"
- $HostReleaseDir = Join-Path $TauriDir "target/release"
- $TargetBinary = Join-Path -Path $TargetReleaseDir -ChildPath $BinaryName
- $HostBinary = Join-Path -Path $HostReleaseDir -ChildPath $BinaryName
- $BinaryCandidates = @(
- $TargetBinary,
- $HostBinary
- )
- $Binary = $null
- $ReleaseDir = $null
- foreach ($candidate in $BinaryCandidates) {
- if (Test-Path $candidate) {
- $Binary = $candidate
- $ReleaseDir = Split-Path -Parent $candidate
- break
- }
- }
- if (-not $Binary) {
- Write-Error @"
- Release binary not found.
- Checked:
- - $($BinaryCandidates[0])
- - $($BinaryCandidates[1])
- Run first: npx tauri build --target $Target --no-bundle
- -or- npx tauri build --no-bundle
- -or- cargo build --release --target $Target --features custom-protocol
- "@
- exit 1
- }
- if ($Binary -eq $HostBinary) {
- Write-Warning "Using host release binary layout at target/release/$BinaryName (no explicit Rust target output path found)."
- }
- Write-Host "-> Creating NSIS installer for $ProductName v$Version ($Target)"
- # ── Locate NSIS ─────────────────────────────────────────────────────────────
- $NsisDir = $env:NSIS_DIR
- if ($NsisDir -and (Test-Path $NsisDir) -and -not (Test-Path (Join-Path $NsisDir "makensis.exe"))) {
- $item = Get-Item $NsisDir -ErrorAction SilentlyContinue
- if ($item -and -not $item.PSIsContainer -and $item.Name -ieq "makensis.exe") {
- $NsisDir = Split-Path -Parent $item.FullName
- }
- }
- if (-not $NsisDir -or -not (Test-Path (Join-Path $NsisDir "makensis.exe"))) {
- $makensis = Get-Command makensis -ErrorAction SilentlyContinue
- if ($makensis) {
- $NsisDir = Split-Path -Parent $makensis.Source
- } else {
- # Common install locations
- foreach ($path in @(
- "C:\Program Files (x86)\NSIS",
- "C:\Program Files\NSIS",
- "$env:LOCALAPPDATA\NSIS"
- )) {
- if (Test-Path (Join-Path $path "makensis.exe")) {
- $NsisDir = $path
- break
- }
- }
- }
- }
- if (-not $NsisDir -or -not (Test-Path (Join-Path $NsisDir "makensis.exe"))) {
- Write-Error @"
- NSIS not found. Install it:
- choco install nsis
- -or- winget install NSIS.NSIS
- -or- set `$env:NSIS_DIR to the NSIS install directory
- "@
- exit 1
- }
- $MakeNsis = Join-Path $NsisDir "makensis.exe"
- Write-Host " NSIS: $MakeNsis"
- # ── Prepare staging directory ───────────────────────────────────────────────
- $BundleDir = Join-Path $ReleaseDir "bundle"
- $NsisOutDir = Join-Path $BundleDir "nsis"
- $Staging = Join-Path $env:TEMP "neuroskill-nsis-staging-$(Get-Random)"
- New-Item -ItemType Directory -Force -Path $Staging | Out-Null
- New-Item -ItemType Directory -Force -Path $NsisOutDir | Out-Null
- try {
- # Binary
- Copy-Item $Binary (Join-Path $Staging $BinaryName)
- Write-Host " [ok] $BinaryName"
- # Daemon sidecar (must sit next to skill.exe in installed dir)
- $DaemonName = "skill-daemon.exe"
- $DaemonCandidates = @(
- (Join-Path $ReleaseDir $DaemonName),
- (Join-Path $TauriDir "binaries/skill-daemon-$Target.exe")
- )
- $Daemon = $null
- foreach ($candidate in $DaemonCandidates) {
- if (Test-Path $candidate) {
- $Daemon = $candidate
- break
- }
- }
- if ($Daemon) {
- Copy-Item $Daemon (Join-Path $Staging $DaemonName) -Force
- Write-Host " [ok] $DaemonName"
- } else {
- Write-Warning " Missing daemon sidecar (checked release + src-tauri/binaries)"
- }
- # Icon
- $IconIco = Join-Path $TauriDir "icons/icon.ico"
- if (Test-Path $IconIco) {
- Copy-Item $IconIco (Join-Path $Staging "icon.ico")
- Write-Host " [ok] icon.ico"
- }
- # ── ONNX Runtime — no longer used on any platform ─────────────────────────
- # KittenTTS was the only `ort` consumer and now runs natively on RLX, so
- # `ort` / `ort-sys` are absent from Cargo.lock entirely and there is no
- # onnxruntime.dll to ship on any target. The Linux .so bundling was removed
- # for the same reason.
- # ── Bundle OpenBLAS DLL ──────────────────────────────────────────────────
- # rlx-cpu's `blas` default feature links against openblas; turbovec on
- # Linux/macOS does the same. The upstream OpenBLAS 0.3.30 Windows DLL
- # is statically linked against the MinGW runtime so no extra DLLs are
- # needed alongside it.
- $OpenBlasDll = $null
- if ($env:OPENBLAS_DLL -and (Test-Path $env:OPENBLAS_DLL)) {
- $OpenBlasDll = Get-Item $env:OPENBLAS_DLL
- } else {
- $OpenBlasDll = Get-ChildItem -Path $ReleaseDir -Recurse -Filter "openblas.dll" `
- -ErrorAction SilentlyContinue |
- Select-Object -First 1
- }
- if (-not $OpenBlasDll -and $env:OPENBLAS_DIR) {
- $alt = Join-Path $env:OPENBLAS_DIR "bin\openblas.dll"
- if (Test-Path $alt) { $OpenBlasDll = Get-Item $alt }
- }
- if ($OpenBlasDll) {
- Copy-Item $OpenBlasDll.FullName (Join-Path $Staging "openblas.dll") -Force
- Write-Host " [ok] openblas.dll (from $($OpenBlasDll.FullName))"
- } else {
- Write-Warning " openblas.dll not found — turboquant / rlx-cpu BLAS paths will fail at runtime"
- }
- # ── Bundle VC++ CRT DLLs (app-local deployment) ─────────────────────────
- # The binary uses dynamic CRT (/MD) because native deps (DirectML, ONNX
- # Runtime, Vulkan loader) ship as pre-built /MD DLLs. Bundling the CRT
- # DLLs alongside skill.exe means users don't need the VC++ Redistributable
- # pre-installed. Windows finds DLLs in the exe directory first (app-local).
- #
- # Required DLLs: vcruntime140.dll, vcruntime140_1.dll, msvcp140.dll,
- # msvcp140_1.dll, vcomp140.dll (OpenMP, used by llama.cpp)
- #
- # Source: CRT_REDIST_DIR env var (set by CI), or auto-detected via vswhere.
- $crtRedistDir = $env:CRT_REDIST_DIR
- if (-not $crtRedistDir -or -not (Test-Path $crtRedistDir)) {
- # Auto-detect from Visual Studio installation
- $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
- if (Test-Path $vswhere) {
- $vsPath = & $vswhere -latest -property installationPath 2>$null
- if ($vsPath) {
- $redistRoot = Join-Path $vsPath "VC\Redist\MSVC"
- if (Test-Path $redistRoot) {
- $crtRedistDir = Get-ChildItem $redistRoot -Directory |
- Sort-Object Name -Descending |
- ForEach-Object { Join-Path $_.FullName "x64\Microsoft.VC143.CRT" } |
- Where-Object { Test-Path $_ } |
- Select-Object -First 1
- if (-not $crtRedistDir) {
- # Fallback to VC142
- $crtRedistDir = Get-ChildItem $redistRoot -Directory |
- Sort-Object Name -Descending |
- ForEach-Object { Join-Path $_.FullName "x64\Microsoft.VC142.CRT" } |
- Where-Object { Test-Path $_ } |
- Select-Object -First 1
- }
- }
- }
- }
- }
- $crtDllNames = @(
- "vcruntime140.dll",
- "vcruntime140_1.dll",
- "msvcp140.dll",
- "msvcp140_1.dll",
- "vcomp140.dll"
- )
- # If no redist dir found yet, fall back to System32 (works if VC++ Redist
- # is installed system-wide, e.g. by the CI step or on developer machines).
- if (-not $crtRedistDir -or -not (Test-Path $crtRedistDir)) {
- $sys32 = "$env:SystemRoot\System32"
- $allInSys32 = $true
- foreach ($dllName in @("vcruntime140.dll", "msvcp140.dll")) {
- if (-not (Test-Path (Join-Path $sys32 $dllName))) { $allInSys32 = $false; break }
- }
- if ($allInSys32) {
- $crtRedistDir = $sys32
- Write-Host " [info] Using System32 as CRT source: $crtRedistDir"
- }
- }
- $bundledCrt = @()
- if ($crtRedistDir -and (Test-Path $crtRedistDir)) {
- foreach ($dllName in $crtDllNames) {
- $src = Join-Path $crtRedistDir $dllName
- if (Test-Path $src) {
- Copy-Item $src (Join-Path $Staging $dllName) -Force
- $bundledCrt += $dllName
- Write-Host " [ok] $dllName (from $crtRedistDir)"
- }
- }
- }
- if ($bundledCrt.Count -eq 0) {
- Write-Error @"
- VC++ CRT DLLs not found. The installer cannot be built without them.
- The binary uses dynamic CRT (/MD) and requires vcruntime140.dll etc.
- to be bundled alongside skill.exe for app-local deployment.
- Fix: ensure Visual Studio with the 'Desktop development with C++'
- workload is installed, or set `$env:CRT_REDIST_DIR to the directory
- containing the MSVC redistributable DLLs (e.g.
- C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Redist\MSVC\14.x.y\x64\Microsoft.VC143.CRT
- ).
- "@
- exit 1
- }
- # Verify all required DLLs were found
- $requiredCrt = @("vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll")
- # Under strict mode, Where-Object may return $null (no misses) or a scalar
- # string (single miss). Force array semantics before reading .Count.
- $missingCrt = @($requiredCrt | Where-Object { $_ -notin $bundledCrt })
- if ($missingCrt.Count -gt 0) {
- Write-Error "Required CRT DLLs missing from bundle: $($missingCrt -join ', ')"
- Write-Host "Found: $($bundledCrt -join ', ')"
- Write-Host "CRT redist dir: $crtRedistDir"
- exit 1
- }
- Write-Host " [ok] Bundled $($bundledCrt.Count) CRT DLLs for app-local deployment"
- # Resources (espeak-ng-data, neutts-samples)
- $resources = $Conf.bundle.resources
- if ($resources) {
- foreach ($prop in $resources.PSObject.Properties) {
- $srcRel = $prop.Name
- $dstRel = $prop.Value
- $src = Join-Path $TauriDir $srcRel
- $dst = Join-Path $Staging $dstRel
- if (Test-Path $src) {
- if ((Get-Item $src).PSIsContainer) {
- Copy-Item $src $dst -Recurse -Force
- } else {
- New-Item -ItemType Directory -Force -Path (Split-Path $dst) | Out-Null
- Copy-Item $src $dst -Force
- }
- Write-Host " [ok] $dstRel"
- } else {
- Write-Warning " Missing resource: $srcRel"
- }
- }
- }
- # Docs
- foreach ($doc in @("README.md", "CHANGELOG.md", "LICENSE")) {
- $docPath = Join-Path $Root $doc
- if (Test-Path $docPath) {
- Copy-Item $docPath (Join-Path $Staging $doc)
- Write-Host " [ok] $doc"
- }
- }
- # ── Generate installer images ───────────────────────────────────────────
- # NSIS uses two bitmap images:
- # - Header image (150×57) — top-right of installer pages
- # - Welcome/Finish image (164×314) — left panel of welcome/finish pages
- $HeaderBmp = Join-Path $Staging "header.bmp"
- $WelcomeBmp = Join-Path $Staging "welcome.bmp"
- $IconPng = Join-Path $TauriDir "icons/icon.png"
- $imagesGenerated = $false
- if (Test-Path $IconPng) {
- try {
- python3 -c @"
- import sys
- from PIL import Image, ImageDraw, ImageFont
- icon_path = sys.argv[1]
- version = sys.argv[2]
- header_out = sys.argv[3]
- welcome_out = sys.argv[4]
- icon = Image.open(icon_path).convert('RGBA')
- # ── Header image (150x57) ──────────────────────────────────────────
- header = Image.new('RGB', (150, 57), (30, 30, 30))
- hi = icon.resize((45, 45), Image.LANCZOS)
- header.paste(hi, (8, 6), hi)
- draw_h = ImageDraw.Draw(header)
- font_h = None
- for fp in [
- 'C:/Windows/Fonts/segoeui.ttf',
- 'C:/Windows/Fonts/arial.ttf',
- ]:
- try:
- font_h = ImageFont.truetype(fp, 14)
- break
- except (OSError, IOError):
- continue
- if font_h is None:
- font_h = ImageFont.load_default()
- draw_h.text((60, 12), f'v{version}', fill=(200, 200, 200), font=font_h)
- header.save(header_out, 'BMP')
- # ── Welcome/Finish image (164x314) ─────────────────────────────────
- welcome = Image.new('RGB', (164, 314), (30, 30, 30))
- wi = icon.resize((100, 100), Image.LANCZOS)
- welcome.paste(wi, (32, 60), wi)
- draw_w = ImageDraw.Draw(welcome)
- font_w = None
- font_ws = None
- for fp in [
- 'C:/Windows/Fonts/segoeui.ttf',
- 'C:/Windows/Fonts/arial.ttf',
- ]:
- try:
- font_w = ImageFont.truetype(fp, 16)
- font_ws = ImageFont.truetype(fp, 12)
- break
- except (OSError, IOError):
- continue
- if font_w is None:
- font_w = ImageFont.load_default()
- font_ws = font_w
- vtxt = f'v{version}'
- vbox = draw_w.textbbox((0, 0), vtxt, font=font_w)
- vw = vbox[2] - vbox[0]
- draw_w.text(((164 - vw) // 2, 170), vtxt, fill=(200, 200, 200), font=font_w)
- welcome.save(welcome_out, 'BMP')
- print(' [ok] installer images generated')
- "@ -- $IconPng $Version $HeaderBmp $WelcomeBmp 2>&1
- if ($LASTEXITCODE -eq 0) {
- $imagesGenerated = $true
- }
- } catch {
- Write-Host " [skip] Could not generate installer images (Pillow not available?)"
- }
- }
- # ── Write NSIS script ───────────────────────────────────────────────────
- $InstallerExe = "NeuroSkill_${Version}_x64-setup.exe"
- $InstallerPath = Join-Path $NsisOutDir $InstallerExe
- $NsiScript = Join-Path $Staging "installer.nsi"
- # Build the file/directory install commands and uninstall commands
- $installFiles = @(' SetOutPath "$INSTDIR"')
- $installFiles += ' File "skill.exe"'
- if (Test-Path (Join-Path $Staging "skill-daemon.exe")) {
- $installFiles += ' File "skill-daemon.exe"'
- }
- if (Test-Path (Join-Path $Staging "icon.ico")) {
- $installFiles += ' File "icon.ico"'
- }
- foreach ($doc in @("README.md", "CHANGELOG.md", "LICENSE")) {
- if (Test-Path (Join-Path $Staging $doc)) {
- $installFiles += " File `"$doc`""
- }
- }
- # Bundle OpenBLAS DLL if present (rlx-cpu / turbovec runtime dependency)
- if (Test-Path (Join-Path $Staging "openblas.dll")) {
- $installFiles += ' File "openblas.dll"'
- }
- # Bundle VC++ CRT DLLs (app-local deployment)
- $crtDlls = Get-ChildItem $Staging -Filter "*.dll" |
- Where-Object { $_.Name -match "(?i)^(vcruntime|msvcp|concrt|vcomp)" }
- foreach ($dll in $crtDlls) {
- $installFiles += " File `"$($dll.Name)`""
- }
- $uninstallFiles = @()
- $uninstallFiles += ' Delete "$INSTDIR\skill.exe"'
- $uninstallFiles += ' Delete "$INSTDIR\skill-daemon.exe"'
- $uninstallFiles += ' Delete "$INSTDIR\icon.ico"'
- $uninstallFiles += ' Delete "$INSTDIR\openblas.dll"'
- foreach ($doc in @("README.md", "CHANGELOG.md", "LICENSE")) {
- $uninstallFiles += " Delete `"`$INSTDIR\$doc`""
- }
- # VC++ CRT DLLs (app-local deployment)
- foreach ($dll in $crtDlls) {
- $uninstallFiles += " Delete `"`$INSTDIR\$($dll.Name)`""
- }
- # Resource directories
- $resourceDirs = @()
- if ($resources) {
- foreach ($prop in $resources.PSObject.Properties) {
- $dstRel = $prop.Value
- $srcStaging = Join-Path $Staging $dstRel
- if (Test-Path $srcStaging) {
- $installFiles += " SetOutPath `"`$INSTDIR\$dstRel`""
- $installFiles += " File /r `"$dstRel\*.*`""
- $resourceDirs += $dstRel
- $uninstallFiles += " RMDir /r `"`$INSTDIR\$dstRel`""
- }
- }
- }
- # Header/welcome image directives
- $imageDirectives = ""
- if ($imagesGenerated) {
- $imageDirectives = @"
- !define MUI_HEADERIMAGE
- !define MUI_HEADERIMAGE_BITMAP "header.bmp"
- !define MUI_HEADERIMAGE_RIGHT
- !define MUI_WELCOMEFINISHPAGE_BITMAP "welcome.bmp"
- "@
- }
- $nsiContent = @"
- ; NeuroSkill NSIS Installer Script
- ; Generated by create-windows-nsis.ps1
- !include "MUI2.nsh"
- !include "FileFunc.nsh"
- !include "Sections.nsh"
- !include "nsDialogs.nsh"
- ; ── General ─────────────────────────────────────────────────────────────
- Name "$ProductName"
- OutFile "$InstallerPath"
- InstallDir "`$PROGRAMFILES64\$ProductName"
- InstallDirRegKey HKLM "Software\$ProductName" "InstallDir"
- RequestExecutionLevel admin
- Unicode True
- ; ── Branding ────────────────────────────────────────────────────────────
- !define MUI_ICON "icon.ico"
- !define MUI_UNICON "icon.ico"
- $imageDirectives
- !define MUI_ABORTWARNING
- ; ── Finish page: launch app after install ───────────────────────────────
- ; MUI_FINISHPAGE_RUN is intentionally left empty — we use a custom callback
- ; (un-elevated launch) instead. The installer runs as admin
- ; (RequestExecutionLevel admin), so a naive Exec/ExecShell would launch the
- ; app as Administrator. The MUI_FINISHPAGE_RUN_FUNCTION callback invokes
- ; explorer.exe to start the app in the real user's context (not elevated).
- !define MUI_FINISHPAGE_RUN
- !define MUI_FINISHPAGE_RUN_TEXT "Launch $ProductDisplayName"
- !define MUI_FINISHPAGE_RUN_FUNCTION LaunchAsCurrentUser
- ; ── Pages ───────────────────────────────────────────────────────────────
- !insertmacro MUI_PAGE_WELCOME
- !insertmacro MUI_PAGE_LICENSE "LICENSE"
- !insertmacro MUI_PAGE_COMPONENTS
- !insertmacro MUI_PAGE_DIRECTORY
- !insertmacro MUI_PAGE_INSTFILES
- !insertmacro MUI_PAGE_FINISH
- !insertmacro MUI_UNPAGE_CONFIRM
- !insertmacro MUI_UNPAGE_INSTFILES
- !insertmacro MUI_LANGUAGE "English"
- ; ── Version info ────────────────────────────────────────────────────────
- VIProductVersion "$VIVersion"
- VIAddVersionKey "ProductName" "$ProductDisplayName"
- VIAddVersionKey "ProductVersion" "$Version"
- VIAddVersionKey "FileVersion" "$Version"
- VIAddVersionKey "LegalCopyright" "GPL-3.0-only"
- VIAddVersionKey "FileDescription" "$ProductDisplayName Installer"
- ; ── Launch helper (drop admin elevation) ────────────────────────────────
- ; The installer runs elevated (admin). Launching the app directly with
- ; Exec/ExecShell would run it as Administrator, which breaks per-user
- ; paths, tray registration, and autostart.
- ;
- ; The reliable no-plugin approach: use the Windows "runas" trick in
- ; reverse — ask Explorer (running as the real user) to open the exe.
- ; We do this by invoking explorer.exe with the full exe path, which
- ; causes Explorer to ShellExecute it in the user's own session context.
- Function LaunchAsCurrentUser
- Exec '"`$WINDIR\explorer.exe" "`$INSTDIR\skill.exe"'
- FunctionEnd
- ; ── Kill running instance before install ─────────────────────────────────
- ; If the app is already running, the installer cannot replace skill.exe.
- ; Gracefully ask the user, then force-kill if needed.
- Function KillRunningInstance
- FindWindow `$0 "" "$ProductDisplayName"
- IntCmp `$0 0 not_running
- ; App window found — ask user
- MessageBox MB_OKCANCEL|MB_ICONINFORMATION "$ProductDisplayName is currently running and must be closed before installing.$\n$\nClick OK to close it automatically, or Cancel to abort." IDOK kill_it
- Abort
- kill_it:
- ; Try graceful WM_CLOSE first
- SendMessage `$0 `${WM_CLOSE} 0 0
- Sleep 2000
- ; Force-kill if still running
- nsExec::ExecToLog 'taskkill /F /IM skill.exe'
- nsExec::ExecToLog 'taskkill /F /IM skill-daemon.exe'
- Sleep 500
- not_running:
- FunctionEnd
- ; ── Install section ─────────────────────────────────────────────────────
- Section "$ProductName (required)" SEC_MAIN
- SectionIn RO ; required — cannot be unchecked
- ; Kill any running instance before overwriting files
- Call KillRunningInstance
- $($installFiles -join "`n")
- ; Uninstaller
- SetOutPath "`$INSTDIR"
- WriteUninstaller "`$INSTDIR\uninstall.exe"
- ; Start Menu shortcut
- CreateDirectory "`$SMPROGRAMS\$ProductName"
- CreateShortCut "`$SMPROGRAMS\$ProductName\$ProductName.lnk" "`$INSTDIR\skill.exe" "" "`$INSTDIR\icon.ico"
- CreateShortCut "`$SMPROGRAMS\$ProductName\Uninstall.lnk" "`$INSTDIR\uninstall.exe"
- ; Desktop shortcut
- CreateShortCut "`$DESKTOP\$ProductName.lnk" "`$INSTDIR\skill.exe" "" "`$INSTDIR\icon.ico"
- ; Registry (Add/Remove Programs)
- WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "DisplayName" "$ProductDisplayName"
- WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "DisplayVersion" "$Version"
- WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "UninstallString" "`$INSTDIR\uninstall.exe"
- WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "DisplayIcon" "`$INSTDIR\icon.ico"
- WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "Publisher" "NeuroSkill"
- WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "InstallLocation" "`$INSTDIR"
- WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "NoModify" 1
- WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "NoRepair" 1
- ; Estimated size
- `${GetSize} "`$INSTDIR" "/S=0K" `$0 `$1 `$2
- IntFmt `$0 "0x%08X" `$0
- WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName" "EstimatedSize" `$0
- WriteRegStr HKLM "Software\$ProductName" "InstallDir" "`$INSTDIR"
- ; ── Enable Win32 long paths ──────────────────────────────────────────────
- ; HuggingFace model cache paths can exceed the 260-char MAX_PATH limit.
- ; This registry key (available since Windows 10 1607) lifts the restriction
- ; for long-path-aware applications. Requires a reboot to take effect, but
- ; the installer does not force one — it takes effect on next login.
- WriteRegDWORD HKLM "SYSTEM\CurrentControlSet\Control\FileSystem" "LongPathsEnabled" 1
- ; ── Windows Firewall rule for the local LLM/WebSocket server ───────────
- ; The app listens on localhost for LLM inference and WebSocket commands.
- ; Pre-adding a firewall rule prevents the "allow access?" popup on first
- ; launch. Failure is non-fatal (user can allow manually).
- nsExec::ExecToLog 'netsh advfirewall firewall delete rule name="$ProductName"'
- nsExec::ExecToLog 'netsh advfirewall firewall add rule name="$ProductName" dir=in action=allow program="`$INSTDIR\skill.exe" enable=yes profile=private,public'
- nsExec::ExecToLog 'netsh advfirewall firewall delete rule name="$ProductName Daemon"'
- nsExec::ExecToLog 'netsh advfirewall firewall add rule name="$ProductName Daemon" dir=in action=allow program="`$INSTDIR\skill-daemon.exe" enable=yes profile=private,public'
- SectionEnd
- ; ── Vulkan Runtime section (optional, auto-selected when missing) ───────
- ; GPU-accelerated LLM inference requires the Vulkan loader (vulkan-1.dll).
- ; Most Windows 10/11 PCs with discrete GPUs already have it. If it is
- ; missing, this section downloads and silently installs the LunarG Vulkan
- ; Runtime, which is ~3 MB and redistributable.
- Section /o "Install Vulkan Runtime (GPU acceleration)" SEC_VULKAN
- ; Temporary download path
- StrCpy `$0 "`$TEMP\VulkanRT-Installer.exe"
- ; Download the latest Vulkan Runtime installer from LunarG
- DetailPrint "Downloading Vulkan Runtime..."
- NSISdl::download "https://sdk.lunarg.com/sdk/download/latest/windows/vulkan-runtime.exe" `$0
- Note: Links to a Windows program from code, which is how droppers fetch their payload
- Line 659 on GitHub
- Pop `$1
- StrCmp `$1 "success" +3
- DetailPrint "Vulkan Runtime download failed (`$1). GPU acceleration may not work."
- Goto vulkan_done
- ; Silent install (/S = silent mode for the NSIS-based LunarG installer)
- DetailPrint "Installing Vulkan Runtime..."
- nsExec::ExecToLog '"`$0" /S'
- Pop `$1
- ; Non-zero exit is non-fatal — the app still works (falls back to CPU)
- IntCmp `$1 0 +2
- DetailPrint "Vulkan Runtime installer exited with code `$1 (non-fatal)."
- Delete `$0
- vulkan_done:
- SectionEnd
- ; ── VC++ Redistributable section (on by default) ───────────────────────
- ; The binary uses dynamic CRT (/MD) and requires vcruntime140.dll /
- ; msvcp140.dll. CRT DLLs are bundled app-locally in `$INSTDIR, but the
- ; full VC++ Redistributable is also installed as a system-wide fallback.
- ; The official Microsoft installer is ~25 MB and is a no-op if already
- ; present — it silently exits with code 0 or 1638 (already installed).
- Section "Install VC++ Redistributable" SEC_VCREDIST
- StrCpy `$0 "`$TEMP\vc_redist.x64.exe"
- DetailPrint "Downloading Visual C++ Redistributable..."
- NSISdl::download "https://aka.ms/vs/17/release/vc_redist.x64.exe" `$0
- Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
- Line 688 on GitHub
- Pop `$1
- StrCmp `$1 "success" +3
- DetailPrint "VC++ Redistributable download failed (`$1). Some features may not work."
- Goto vcredist_done
- ; /install /quiet /norestart — standard silent switches for the VC++ installer.
- ; Exit code 0 = success, 1638 = already installed (both are fine).
- DetailPrint "Installing Visual C++ Redistributable..."
- nsExec::ExecToLog '"`$0" /install /quiet /norestart'
- Pop `$1
- IntCmp `$1 0 vcredist_ok
- IntCmp `$1 1638 vcredist_ok
- DetailPrint "VC++ Redistributable installer exited with code `$1 (non-fatal)."
- Goto vcredist_cleanup
- vcredist_ok:
- DetailPrint "Visual C++ Redistributable installed successfully."
- vcredist_cleanup:
- Delete `$0
- vcredist_done:
- SectionEnd
- ; ── WebView2 Runtime section (optional, auto-selected when missing) ─────
- ; Tauri 2 requires the Microsoft Edge WebView2 Runtime to render the app
- ; UI. It is built into Windows 11 but may be absent on older Windows 10
- ; machines. The Evergreen Bootstrapper is ~1.8 MB and installs silently.
- Section /o "Install WebView2 Runtime (required for UI)" SEC_WEBVIEW2
- StrCpy `$0 "`$TEMP\MicrosoftEdgeWebview2Setup.exe"
- DetailPrint "Downloading WebView2 Runtime..."
- NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" `$0
- Pop `$1
- StrCmp `$1 "success" +3
- DetailPrint "WebView2 download failed (`$1). The app may not display correctly."
- Goto webview2_done
- ; /silent /install — standard quiet switches for the Evergreen Bootstrapper.
- DetailPrint "Installing WebView2 Runtime..."
- nsExec::ExecToLog '"`$0" /silent /install'
- Pop `$1
- IntCmp `$1 0 webview2_ok
- DetailPrint "WebView2 installer exited with code `$1 (may already be installed)."
- Goto webview2_cleanup
- webview2_ok:
- DetailPrint "WebView2 Runtime installed successfully."
- webview2_cleanup:
- Delete `$0
- webview2_done:
- SectionEnd
- ; ── GPU TDR timeout section (optional) ──────────────────────────────────
- ; Windows kills GPU compute shaders after 2 seconds by default (Timeout
- ; Detection and Recovery). LLM inference on GPU can exceed this, causing
- ; the driver to reset and the inference to fail. Increasing TdrDelay to
- ; 60 seconds prevents this. Requires a reboot to take effect.
- ; See: https://learn.microsoft.com/en-us/windows-hardware/drivers/display/tdr-registry-keys
- Section /o "Increase GPU timeout for LLM inference" SEC_TDR
- WriteRegDWORD HKLM "SYSTEM\CurrentControlSet\Control\GraphicsDrivers" "TdrDelay" 60
- DetailPrint "GPU TDR timeout set to 60 seconds (reboot required to take effect)."
- SectionEnd
- ; ── Launch at login section (on by default) ─────────────────────────────
- ; Registers the app in HKCU\...\Run so it starts automatically on login.
- ; The user can also toggle this later from Settings inside the app.
- ; Uses the same registry key that the in-app autostart crate writes.
- Section "Launch at login" SEC_AUTOSTART
- WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "skill" '"`$INSTDIR\skill.exe"'
- DetailPrint "Autostart enabled (HKCU\Software\Microsoft\Windows\CurrentVersion\Run\skill)."
- SectionEnd
- ; ── Component descriptions ──────────────────────────────────────────────
- !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
- !insertmacro MUI_DESCRIPTION_TEXT `${SEC_MAIN} "Install $ProductDisplayName application files."
- !insertmacro MUI_DESCRIPTION_TEXT `${SEC_VULKAN} "Download and install the Vulkan Runtime for GPU-accelerated LLM inference. Not needed if your GPU driver already provides Vulkan support."
- !insertmacro MUI_DESCRIPTION_TEXT `${SEC_VCREDIST} "Download and install the Microsoft Visual C++ 2015-2022 Redistributable (x64). Required for the application to run. CRT DLLs are also bundled locally, but the system-wide install ensures long-term compatibility. Safe to install even if already present."
- !insertmacro MUI_DESCRIPTION_TEXT `${SEC_WEBVIEW2} "Download and install the Microsoft Edge WebView2 Runtime. Required to display the application interface. Already included in Windows 11."
- !insertmacro MUI_DESCRIPTION_TEXT `${SEC_TDR} "Increase the Windows GPU timeout from 2 to 60 seconds. Prevents GPU driver resets during long LLM inference runs. Requires a reboot."
- !insertmacro MUI_DESCRIPTION_TEXT `${SEC_AUTOSTART} "Start $ProductDisplayName automatically when you log in to Windows. You can change this later in the app settings."
- !insertmacro MUI_FUNCTION_DESCRIPTION_END
- ; ── Auto-select optional sections when prerequisites are missing ────────
- Function .onInit
- ; Vulkan Runtime
- IfFileExists "`$SYSDIR\vulkan-1.dll" vulkan_found vulkan_missing
- vulkan_missing:
- !insertmacro SelectSection `${SEC_VULKAN}
- Goto vulkan_check_done
- vulkan_found:
- vulkan_check_done:
- ; VC++ Redistributable — always on by default (Section without /o).
- ; No auto-select logic needed since the section is already enabled.
- ; WebView2 — check registry for installed WebView2 Runtime
- ; The Evergreen Runtime writes to this key on both per-user and per-machine installs.
- ReadRegStr `$0 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
- StrCmp `$0 "" 0 webview2_reg_found
- ReadRegStr `$0 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
- StrCmp `$0 "" 0 webview2_reg_found
- ; Not found — select the WebView2 section
- !insertmacro SelectSection `${SEC_WEBVIEW2}
- Goto webview2_check_done
- webview2_reg_found:
- webview2_check_done:
- FunctionEnd
- ; ── Uninstall: kill running instance ─────────────────────────────────────
- Function un.KillRunningInstance
- nsExec::ExecToLog 'taskkill /F /IM skill.exe'
- nsExec::ExecToLog 'taskkill /F /IM skill-daemon.exe'
- ; Remove the daemon Windows service if it was registered at runtime
- nsExec::ExecToLog 'sc.exe stop com.skill.daemon'
- nsExec::ExecToLog 'sc.exe delete com.skill.daemon'
- Sleep 500
- FunctionEnd
- ; ── Uninstall section ───────────────────────────────────────────────────
- Section "Uninstall"
- ; Kill the app if it is still running
- Call un.KillRunningInstance
- $($uninstallFiles -join "`n")
- Delete "`$INSTDIR\uninstall.exe"
- ; Shortcuts
- Delete "`$SMPROGRAMS\$ProductName\$ProductName.lnk"
- Delete "`$SMPROGRAMS\$ProductName\Uninstall.lnk"
- RMDir "`$SMPROGRAMS\$ProductName"
- Delete "`$DESKTOP\$ProductName.lnk"
- ; Firewall rules
- nsExec::ExecToLog 'netsh advfirewall firewall delete rule name="$ProductName"'
- nsExec::ExecToLog 'netsh advfirewall firewall delete rule name="$ProductName Daemon"'
- ; Autostart registry entry (the app registers as "skill" in HKCU\...\Run)
- DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "skill"
- ; Registry
- DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\$ProductName"
- DeleteRegKey HKLM "Software\$ProductName"
- ; Remove install directory (only if empty after file deletions)
- RMDir "`$INSTDIR"
- ; ── Offer to remove user data ────────────────────────────────────────
- ; %LOCALAPPDATA%\NeuroSkill contains settings, sessions, databases, and
- ; downloaded models. Ask the user whether to keep or delete it.
- IfFileExists "`$LOCALAPPDATA\NeuroSkill\*.*" 0 skip_data_prompt
- MessageBox MB_YESNO|MB_ICONQUESTION "Do you want to remove your $ProductDisplayName data folder?$\n$\n`$LOCALAPPDATA\NeuroSkill$\n$\nThis includes settings, session recordings, and downloaded AI models. Choose No to keep your data for a future reinstall." IDYES remove_data
- Goto skip_data_prompt
- remove_data:
- RMDir /r "`$LOCALAPPDATA\NeuroSkill"
- skip_data_prompt:
- SectionEnd
- "@
- # NSIS with `Unicode True` requires a BOM to detect UTF-8 encoding.
- # Without BOM it falls back to the system ANSI codepage and mangles
- # non-ASCII characters like ™ in the product display name.
- $utf8WithBom = New-Object System.Text.UTF8Encoding($true)
- [System.IO.File]::WriteAllText($NsiScript, $nsiContent, $utf8WithBom)
- Write-Host " [ok] NSIS script written (UTF-8 with BOM)"
- # ── Run NSIS ────────────────────────────────────────────────────────────
- Write-Host " Compiling installer ..."
- & $MakeNsis /V2 $NsiScript
- if ($LASTEXITCODE -ne 0) {
- Write-Error "makensis failed with exit code $LASTEXITCODE"
- exit $LASTEXITCODE
- }
- Write-Host " [ok] $InstallerExe"
- # ── Sign installer (optional) ───────────────────────────────────────────
- if ($Sign) {
- $thumbprint = $env:CERTIFICATE_THUMBPRINT
- if (-not $thumbprint) {
- Write-Warning " -Sign requested but `$env:CERTIFICATE_THUMBPRINT is not set. Skipping."
- } else {
- Write-Host " Signing installer ..."
- & signtool sign `
- /sha1 $thumbprint `
- /fd sha256 `
- /tr http://timestamp.digicert.com `
- /td sha256 `
- /v `
- $InstallerPath
- if ($LASTEXITCODE -ne 0) {
- Write-Error "signtool failed with exit code $LASTEXITCODE"
- exit $LASTEXITCODE
- }
- Write-Host " [ok] Installer signed"
- }
- }
- # ── Summary ─────────────────────────────────────────────────────────────
- $size = "{0:N1} MB" -f ((Get-Item $InstallerPath).Length / 1MB)
- Write-Host ""
- Write-Host "[ok] $InstallerPath ($size)"
- Write-Host ""
- Write-Host "Contents:"
- Write-Host " - $BinaryName"
- Write-Host " - icon.ico"
- foreach ($dll in $bundledCrt) {
- Write-Host " - $dll (CRT app-local)"
- }
- foreach ($doc in @("README.md", "CHANGELOG.md", "LICENSE")) {
- if (Test-Path (Join-Path $Staging $doc)) {
- Write-Host " - $doc"
- }
- }
- if ($resources) {
- foreach ($prop in $resources.PSObject.Properties) {
- Write-Host " - $($prop.Value)/"
- }
- }
- Write-Host ""
- Write-Host "To install: run $InstallerExe"
- } finally {
- # Clean up staging directory
- if (Test-Path $Staging) {
- Remove-Item $Staging -Recurse -Force -ErrorAction SilentlyContinue
- }
- }
scripts/ensure-vcredist.ps1 · Bundled script · 150 lines · 1 finding marked
- <#
- .SYNOPSIS
- Ensure VC++ Redistributable CRT DLLs are available for app-local bundling.
- .DESCRIPTION
- Locates the MSVC CRT redistributable DLLs (vcruntime140.dll, msvcp140.dll,
- etc.) needed for app-local deployment.
- Strategy order:
- 1. VCToolsRedistDir env var (set by ilammy/msvc-dev-cmd on CI)
- 2. vswhere to find VS install path
- 3. Download + install VC++ Redistributable from Microsoft, copy from System32
- On success, sets CRT_REDIST_DIR via GITHUB_ENV (CI) or process env.
- #>
- Set-StrictMode -Version Latest
- $ErrorActionPreference = "Stop"
- $required = @(
- "vcruntime140.dll",
- "vcruntime140_1.dll",
- "msvcp140.dll",
- "msvcp140_1.dll",
- "vcomp140.dll"
- )
- function Test-AllDlls($dir) {
- foreach ($dll in $required) {
- if (-not (Test-Path (Join-Path $dir $dll))) { return $false }
- }
- return $true
- }
- function Find-CrtInRedistRoot($redistRoot) {
- if (-not $redistRoot -or -not (Test-Path $redistRoot)) { return $null }
- foreach ($vcVer in @("VC143", "VC142")) {
- $dirs = Get-ChildItem $redistRoot -Directory -ErrorAction SilentlyContinue |
- Sort-Object Name -Descending
- foreach ($d in $dirs) {
- $candidate = Join-Path $d.FullName "x64\Microsoft.$vcVer.CRT"
- if (Test-Path $candidate) { return $candidate }
- }
- }
- return $null
- }
- $crtDir = $null
- # ── Strategy 1: VCToolsRedistDir (set by ilammy/msvc-dev-cmd) ───────────────
- if ($env:VCToolsRedistDir) {
- Write-Host "[info] VCToolsRedistDir = $env:VCToolsRedistDir"
- $crtDir = Find-CrtInRedistRoot $env:VCToolsRedistDir
- if (-not $crtDir) {
- # VCToolsRedistDir itself may be the parent — try going up
- $parent = Split-Path $env:VCToolsRedistDir -Parent
- $crtDir = Find-CrtInRedistRoot $parent
- }
- if ($crtDir -and (Test-AllDlls $crtDir)) {
- Write-Host "[ok] CRT DLLs found via VCToolsRedistDir: $crtDir"
- }
- else {
- Write-Host "[warn] VCToolsRedistDir set but DLLs not found there"
- $crtDir = $null
- }
- }
- # ── Strategy 2: vswhere ──────────────────────────────────────────────────────
- if (-not $crtDir) {
- $pf86 = [Environment]::GetFolderPath("ProgramFilesX86")
- if (-not $pf86) { $pf86 = "C:\Program Files (x86)" }
- $vswhere = Join-Path $pf86 "Microsoft Visual Studio\Installer\vswhere.exe"
- if (Test-Path $vswhere) {
- $vsPath = & $vswhere -latest -property installationPath 2>$null
- if ($vsPath) {
- $redistRoot = Join-Path $vsPath "VC\Redist\MSVC"
- $crtDir = Find-CrtInRedistRoot $redistRoot
- if ($crtDir -and (Test-AllDlls $crtDir)) {
- Write-Host "[ok] CRT DLLs found via vswhere: $crtDir"
- }
- else {
- $crtDir = $null
- }
- }
- }
- }
- # ── Strategy 3: Download + install VC++ Redistributable ──────────────────────
- if (-not $crtDir) {
- Write-Host "[info] Downloading VC++ Redistributable from Microsoft..."
- $tempDir = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } else { $env:TEMP }
- $vcRedistExe = Join-Path $tempDir "vc_redist.x64.exe"
- Invoke-WebRequest -Uri "https://aka.ms/vs/17/release/vc_redist.x64.exe" `
- Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
- Line 96 on GitHub
- -OutFile $vcRedistExe -UseBasicParsing
- if (-not (Test-Path $vcRedistExe)) {
- Write-Error "Failed to download VC++ Redistributable"
- exit 1
- }
- $sizeMB = [math]::Round((Get-Item $vcRedistExe).Length / 1MB, 1)
- Write-Host "[ok] Downloaded ($sizeMB MB)"
- Write-Host "[info] Installing VC++ Redistributable..."
- $proc = Start-Process -FilePath $vcRedistExe `
- -ArgumentList "/install", "/quiet", "/norestart" `
- -Wait -PassThru
- $exitCode = $proc.ExitCode
- if ($exitCode -ne 0 -and $exitCode -ne 1638) {
- Write-Error "VC++ Redistributable install failed (exit $exitCode)"
- exit 1
- }
- Write-Host "[ok] VC++ Redistributable installed (exit $exitCode)"
- Remove-Item $vcRedistExe -Force -ErrorAction SilentlyContinue
- $crtDir = Join-Path $env:SystemRoot "System32"
- }
- # ── Final verification ───────────────────────────────────────────────────────
- $missing = @()
- foreach ($dll in $required) {
- if (-not (Test-Path (Join-Path $crtDir $dll))) {
- $missing += $dll
- }
- }
- if ($missing.Count -gt 0) {
- $missingList = $missing -join ", "
- Write-Error "CRT DLLs still missing after all strategies: $missingList"
- exit 1
- }
- Write-Host "[ok] All $($required.Count) CRT DLLs verified:"
- foreach ($dll in $required) {
- Write-Host " $(Join-Path $crtDir $dll)"
- }
- # ── Export CRT_REDIST_DIR ────────────────────────────────────────────────────
- $env:CRT_REDIST_DIR = $crtDir
- if ($env:GITHUB_ENV) {
- "CRT_REDIST_DIR=$crtDir" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
- }
- Write-Host "[ok] CRT_REDIST_DIR=$crtDir"
src/lib/chat/chat-utils.ts · Bundled script · 290 lines · 1 finding marked
- // SPDX-License-Identifier: GPL-3.0-only
- // Copyright (C) 2026 NeuroSkill.com
- /**
- * Pure utility functions for the chat page — tool-call parsing,
- * danger detection, and assistant output parsing.
- *
- * Extracted from `routes/chat/+page.svelte` to reduce file size and
- * allow independent unit testing.
- */
- import type { TranslationKey } from "#lib/i18n/keys";
- // ── Generation-phase progress labels ────────────────────────────────────────
- /** Backend generation-phase identifiers, delivered on `status` chunks during
- * the pre-token lead-in (see `ChatChunkStatus`). Kept here so the string
- * literals live in exactly one place on the frontend. */
- export const GEN_PHASE = {
- vision: "vision",
- prefill: "prefill",
- /** A built-in tool is executing (web_search, location, …). These can take
- * tens of seconds, and before they were reported the client simply went
- * quiet for the whole round-trip. */
- tool: "tool",
- } as const;
- /** i18n key for the pre-token "processing" indicator: the real backend phase
- * when known ("vision" → reading image, "prefill" → preparing response),
- * otherwise the image/text fallback. */
- export function processingLabelKey(phase: string | undefined, hasImage: boolean | undefined): TranslationKey {
- switch (phase) {
- case GEN_PHASE.vision:
- return "chat.phaseVision";
- case GEN_PHASE.prefill:
- return "chat.phasePrefill";
- case GEN_PHASE.tool:
- return "chat.phaseTool";
- default:
- return hasImage ? "chat.analyzingImage" : "chat.processing";
- }
- }
- // ── Tool-call stripping ─────────────────────────────────────────────────────
- /** Known built-in tool names — must stay in sync with KNOWN_TOOL_NAMES in tools.rs */
- const KNOWN_TOOLS = new Set([
- "date",
- "location",
- "web_search",
- "web_fetch",
- "bash",
- "read_file",
- "write_file",
- "edit_file",
- "search_output",
- ]);
- function isToolCallObject(v: Record<string, unknown>): boolean {
- if (("name" in v || "tool" in v || "tool_calls" in v) && ("parameters" in v || "arguments" in v || "tool_calls" in v))
- return true;
- const keys = Object.keys(v);
- return (
- keys.length > 0 &&
- keys.some((k) => KNOWN_TOOLS.has(k)) &&
- Object.values(v).every((val) => typeof val === "object" && val !== null)
- );
- }
- function looksLikeToolCallJsonPrefix(s: string): boolean {
- const trimmed = s.trimStart();
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return false;
- const probe = trimmed.slice(0, 320).toLowerCase();
- const isDictStyle = [...KNOWN_TOOLS].some((name) => probe.includes(`"${name}":`) || probe.includes(`"${name}": `));
- if (isDictStyle) return true;
- const mentionsToolName =
- probe.includes('"name"') ||
- probe.includes('"tool"') ||
- probe.includes('"tool_calls"') ||
- probe.includes('"function"');
- const mentionsArgs = probe.includes('"parameter') || probe.includes('"argument') || probe.includes("<think>");
- return mentionsToolName && mentionsArgs;
- }
- function isToolCallArray(v: unknown): boolean {
- if (!Array.isArray(v)) return false;
- return v.some(
- (item) =>
- typeof item === "object" &&
- item !== null &&
- !Array.isArray(item) &&
- isToolCallObject(item as Record<string, unknown>),
- );
- }
- /**
- * Strip tool-call JSON code fences that leaked into rawAcc.
- *
- * The streaming sanitizer on the Rust side holds back tool-call JSON, but
- * it can only recognise a fence as a tool call once it has seen BOTH a
- * "tool"/"name" key AND a "parameters"/"arguments" key. Tokens emitted
- * before that threshold are already in rawAcc and need to be cleaned here.
- */
- export function stripToolCallFences(raw: string): string {
- // 1. Complete fenced blocks
- let s = raw.replace(/```(?:json)?\n([\s\S]*?)\n?```/g, (match, body: string) => {
- const trimmedBody = body.trim();
- try {
- const v = JSON.parse(trimmedBody);
- if (typeof v === "object" && v !== null && !Array.isArray(v) && isToolCallObject(v)) return "";
- if (isToolCallArray(v)) return "";
- } catch {
- /* not JSON — keep */
- }
- if (looksLikeToolCallJsonPrefix(trimmedBody)) return "";
- return match;
- });
- // 2a. Incomplete fence immediately before a <think> tag.
- s = s.replace(/```(?:json)?\n([\s\S]*?)(?=\n*<think>)/g, (match, body: string) =>
- looksLikeToolCallJsonPrefix(body) ? "" : match,
- );
- // 2b. Incomplete fence at end of string (still streaming).
- s = s.replace(/```(?:json)?\n([\s\S]*)$/g, (match, body: string) => (looksLikeToolCallJsonPrefix(body) ? "" : match));
- // 3. Bare inline tool-call JSON (not fenced)
- s = s.replace(/(?:^|\n)\s*[[{][\s\S]*$/gm, (match) => {
- if (looksLikeToolCallJsonPrefix(match.trim())) return "";
- return match;
- });
- // 4. Complete [TOOL_CALL]…[/TOOL_CALL] blocks
- s = s.replace(/\[TOOL_CALL\][\s\S]*?\[\/TOOL_CALL\]/g, "");
- // 5. Incomplete [TOOL_CALL] at end of string (mid-stream)
- s = s.replace(/\[TOOL_C[\s\S]*$/g, "");
- return s;
- }
- // ── Lead-in cleaning ────────────────────────────────────────────────────────
- export function cleanAssistantLeadIn(raw: string): string {
- return raw
- .replace(/```[a-z]*\s*/gi, "")
- .split("\n")
- .filter((line) => !/^\s*(json|copy)\s*$/i.test(line))
- .join("\n")
- .trim();
- }
- /**
- * Clean lead-in text for display. When tool calls are active, aggressively
- * strip ALL incomplete code fences and any JSON-like fragments.
- */
- export function cleanLeadInForDisplay(raw: string, hasToolUses: boolean): string {
- if (!raw.trim()) return "";
- let s = stripToolCallFences(raw);
- if (hasToolUses) {
- s = s.replace(/```[a-z]*\n[\s\S]*$/gi, "");
- s = s.replace(/\n\s*[[{][\s\S]*$/g, "");
- }
- return s.trim();
- }
- // ── Danger detection ────────────────────────────────────────────────────────
- /** Bash patterns that indicate a potentially dangerous command (mirrored from Rust). */
- const DANGEROUS_BASH_PATTERNS = [
- "rm ",
- "rm\t",
- "rmdir",
- "shred",
- "mkfs",
- "dd if=",
- "dd of=",
- "sudo ",
- "su -",
- "su\t",
- "> /dev/",
- "chmod",
- "chown",
- "kill ",
- "killall",
- "pkill",
- "shutdown",
- "reboot",
- "halt",
- "poweroff",
- "systemctl stop",
- "systemctl disable",
- ":(){ :|:& };:",
- Note: Quoted as data in code: Matches a classic shell fork-bomb pattern
- Line 198 on GitHub
- "/etc/",
- "/boot/",
- "/usr/",
- "/var/",
- "/sys/",
- "/proc/",
- ];
- /** Sensitive path prefixes (mirrored from Rust). */
- const SENSITIVE_PATH_PREFIXES = [
- "/etc/",
- "/boot/",
- "/usr/",
- "/var/",
- "/sys/",
- "/proc/",
- "/bin/",
- "/sbin/",
- "/lib/",
- "/opt/",
- ];
- /**
- * Check if a tool call looks dangerous based on its name and arguments.
- * Returns a danger reason i18n key, or null if safe.
- *
- * Accepts any object with `tool` and optional `args` fields.
- */
- export function detectToolDanger(tu: { tool: string; args?: Record<string, unknown> }): string | null {
- if (tu.tool === "bash" && typeof tu.args?.command === "string") {
- const cmd = tu.args.command.toLowerCase();
- for (const pat of DANGEROUS_BASH_PATTERNS) {
- if (cmd.includes(pat)) {
- return `chat.tools.dangerBash`;
- }
- }
- }
- if (["write_file", "edit_file", "read_file"].includes(tu.tool) && typeof tu.args?.path === "string") {
- const path = tu.args.path;
- for (const prefix of SENSITIVE_PATH_PREFIXES) {
- if (path.startsWith(prefix)) {
- return `chat.tools.dangerPath`;
- }
- }
- }
- return null;
- }
- // ── Assistant output parsing ────────────────────────────────────────────────
- /**
- * Split raw assistant output into three display zones:
- * - `leadIn` = inter-think text segments (all except the last)
- * - `thinking` = merged <think>…</think> blocks
- * - `content` = the final answer (last non-empty segment)
- */
- export function parseAssistantOutput(raw: string): {
- leadIn: string;
- thinking: string;
- content: string;
- } {
- const s = stripToolCallFences(raw);
- if (!s.includes("<think>")) return { leadIn: "", thinking: "", content: s };
- const thinkingParts: string[] = [];
- let withoutThink = s.replace(/<think>([\s\S]*?)<\/think>/g, (_: string, inner: string) => {
- thinkingParts.push(inner.trim());
- return "\x00";
- });
- // Handle an unclosed <think> at the end (still streaming)
- const openIdx = withoutThink.indexOf("<think>");
- if (openIdx !== -1) {
- thinkingParts.push(withoutThink.slice(openIdx + 7).trim());
- withoutThink = withoutThink.slice(0, openIdx);
- }
- const thinking = thinkingParts.join("\n\n");
- const parts = withoutThink
- .split("\x00")
- .map((p: string) => p.trim())
- .filter(Boolean);
- if (parts.length === 0) return { leadIn: "", thinking, content: "" };
- const content = parts[parts.length - 1];
- const leadIn = parts.slice(0, -1).map(cleanAssistantLeadIn).filter(Boolean).join("\n\n");
- return { leadIn, thinking, content };
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.