Compare commits
68
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78f2928132 | ||
|
|
877ee5d163 | ||
|
|
ac7888c9a5 | ||
|
|
2787bcc9ac | ||
|
|
3c7d2662a4 | ||
|
|
b03d71dc81 | ||
|
|
d9d0a2e849 | ||
|
|
2a147c911a | ||
|
|
1fda5c09b7 | ||
|
|
ec34fc005c | ||
|
|
f49ba2a84b | ||
|
|
c84f536c76 | ||
|
|
2005db22e6 | ||
|
|
766b2bbaeb | ||
|
|
550c94d58a | ||
|
|
a58546900f | ||
|
|
1fb1a23eea | ||
|
|
d4fd08cabe | ||
|
|
1214e00300 | ||
|
|
1dc582d689 | ||
|
|
366d6bb97a | ||
|
|
4d0662b09e | ||
|
|
e71f7089d3 | ||
|
|
e427a4079c | ||
|
|
633bbf35a0 | ||
|
|
f7411c2ade | ||
|
|
b4120aaf88 | ||
|
|
baae0d960c | ||
|
|
61c4f20fe9 | ||
|
|
10f5811d7f | ||
|
|
b8773b8fc2 | ||
|
|
b4dfbd7540 | ||
|
|
62923e8344 | ||
|
|
9821fde02b | ||
|
|
9264bd0adf | ||
|
|
9cb78880ce | ||
|
|
1cd03f93c6 | ||
|
|
8a35b39aa3 | ||
|
|
78424d2778 | ||
|
|
59bdaa6e2a | ||
|
|
c45d61387f | ||
|
|
76ff344ff5 | ||
|
|
a2968cdcef | ||
|
|
84c26cca45 | ||
|
|
75088e1f15 | ||
|
|
d01d13ff1c | ||
|
|
788a97a61d | ||
|
|
aaeadb50d5 | ||
|
|
b1869a1afd | ||
|
|
1a3c38406a | ||
|
|
b37ee69be1 | ||
|
|
86844a3646 | ||
|
|
16677278ba | ||
|
|
4a4ce6c585 | ||
|
|
7603df3666 | ||
|
|
7f5bf7b111 | ||
|
|
738c1de3f9 | ||
|
|
ee43a5cd8f | ||
|
|
b2081fa14f | ||
|
|
efe174ba64 | ||
|
|
b31fadd85a | ||
|
|
acbad2d954 | ||
|
|
26790706c8 | ||
|
|
96e8d4ce51 | ||
|
|
9eaba6aae6 | ||
|
|
2e7bee5f61 | ||
|
|
e8447c3c28 | ||
|
|
ca3c7fa45a |
No files matched your search
@@ -6,5 +6,7 @@ home/.config/beets/state.pickle
|
||||
home/.config/herdr/.plugins.lock
|
||||
home/.config/herdr/*.log
|
||||
home/.config/herdr/*.sock
|
||||
home/.config/herdr/herdr.sock.agent
|
||||
home/.config/herdr/session.json
|
||||
home/.config/herdr/release-notes.json
|
||||
home/.config/herdr/session-snapshots/
|
||||
@@ -8,9 +8,10 @@ Deliberate decisions in this repo - do NOT silently revert them:
|
||||
- Pi is managed the same way: `home/.pi/agent/{settings,models}.json`, `themes/`, and custom extensions (`terminal-status-title`, `calm`). Do not symlink the whole `~/.pi/agent` tree - sessions, auth, npm cache, and herdr's `extensions/herdr-agent-state.ts` stay live.
|
||||
- herdr stores runtime state beside its config, so `~/.config/herdr` stays a real directory and only `config.toml` is symlinked; `home.activation.herdrConfigDir` migrates the old whole-directory symlink and clears leaked artifacts. Do not symlink the whole directory - rationale and artifact list are in `home.nix`.
|
||||
- Codex runs on the OpenCode Go subscription. The ChatGPT app owns and rewrites the live `~/.codex/config.toml`, so it is NOT symlinked; `home.activation.codexOpenCodeGo` merges the repo fragment `home/.codex/config.toml` into it on every rebuild, and the app's own sections (`[desktop]`, `[plugins]`, `[mcp_servers]`, ...) survive. Auth is command-backed via `~/.local/bin/opencode-go-token` (prints the key from the opencode store), so `~/.codex/auth.json` stays in ChatGPT mode and ChatGPT sign-in coexists with Go. Only Go models that speak the Responses API work (`deepseek-v4.1-flash`, `gpt-6-luna`, `gpt-5.6-luna`, `grok-4.7/4.6`); GLM/Kimi/MiMo/LongCat are chat-completions-only and need a proxy. Desktop Codex is now the `chatgpt` cask - do not use the deprecated `codex-app` cask.
|
||||
- firstmate lives at `~/Documents/firstmate` as a mutable git clone (not in the Nix store). `home.activation.firstmate` clones it if missing and seeds `config/backend=herdr` + `config/crew-harness=opencode` only when those files are absent. Launch with shell alias `fm` (`cd` + OpenCode 2 via `~/.local/bin/oc2`). Self-update via `/updatefirstmate`, not rebuild.
|
||||
- OpenCode 2 is the firstmate primary. It is not a Homebrew formula: install `@opencode-ai/cli@beta` with Homebrew's npm (`home.activation.opencode2`). Launch through `home/bin/oc2` so `OPENCODE_CONFIG` stays at `home/.config/opencode2/opencode.json` and cannot rewrite OpenCode 1.x's `~/.config/opencode`. Do not add a brew `opencode` / `opencode2` formula; `zap` would fight the npm install. firstmate harness detection matches `*opencode*`, so the `opencode2` process name still classifies as OpenCode.
|
||||
- Shell aliases: `cc` (Claude skip-permissions), `co` (Codex full-auto), `gb` (Grok --yolo), `fm` (firstmate via OpenCode 2), `oc2` (OpenCode 2, isolated). They are intentional high-agency shortcuts.
|
||||
- firstmate lives at `~/Documents/firstmate` as a mutable git clone (not in the Nix store). `home.activation.firstmate` clones it if missing and seeds `config/backend=herdr` + `config/crew-harness=opencode` only when those files are absent. Crew routing is `home/.config/firstmate/crew-dispatch.json` (symlinked in): per the captain's order 2026-10-21, coding crewmates and scouts use `opencode` + `opencode-go/deepseek-v4.1-flash` through the OpenCode CLI. Design, architecture, and design-review tasks are the exception: the file's first rule sends them to Pi with `openai-codex/gpt-6.1-sol` at `xhigh`, and implementation tasks re-resolve their profile instead of keeping that model. The free `deepseek-v4.1-flash-free` order of 2026-10-20 resumes when that lane resets. The validation pipeline stays on Pi with `opencode-go/deepseek-v4.1-flash` steps and the `opencode-go/glm-5.3-flash` reviewer. Avoid the `muse-spark-*-contributor` models, which train on prompts, and the `exo-free`, `mimo-*-free`, and `nemotron-*-free` models, whose data may be used to improve the model. `cat-jam-free` retains for 30 days. Crews inherit the primary's OpenCode login through the spawn-owned symlink (the isolated worker data root links the primary `<XDG_DATA_HOME>/opencode/auth.json`; no `~/.pi/agent/auth.json` reliance). Launch with shell alias `fm` (`cd` + `pi` with the two firstmate primary extensions); the primary runs Pi on the OpenCode Go subscription, while crews run on the opencode harness unless a dispatch rule selects another harness. `oc2` remains the isolated-config OpenCode launcher. Self-update via `/updatefirstmate`, not rebuild.
|
||||
- OpenCode is one install: the stable Homebrew `opencode` formula, linked so `/opt/homebrew/bin/opencode` is that build. It is both the firstmate crew harness and the `oc2` binary. `oc2` only isolates the config: `OPENCODE_CONFIG` stays at `home/.config/opencode2/opencode.json` and cannot rewrite `~/.config/opencode`, and `OPENCODE2_BIN` overrides the binary. firstmate harness detection matches `*opencode*`, so it still classifies as OpenCode.
|
||||
- Shell aliases: `cc` (Claude skip-permissions), `co` (Codex full-auto), `gb` (Grok --yolo), `fm` (firstmate via Pi), `oc2` (OpenCode with isolated config). They are intentional high-agency shortcuts.
|
||||
- OpenSuperWhisper is installed by the `opensuperwhisper` cask, and `home.activation.openSuperWhisper` downloads its Whisper model (`ggml-large-v3-turbo.bin` under the app's Application Support directory, never the Nix store) and seeds the model selection only when it is missing or dangling. All other app settings (trigger, language, paste behavior) belong to the app and must not be rewritten by a rebuild, so `modifierOnlyHotkey = rightOption` on this machine stays the effective trigger. Microphone/Accessibility/Input Monitoring grants stay manual because macOS TCC cannot be declarative; do not kill a running app to apply defaults. The model is local-only.
|
||||
|
||||
## Maintaining this file
|
||||
|
||||
|
||||
+11
-1
@@ -45,6 +45,7 @@
|
||||
onActivation.extraFlags = [ "--force" ];
|
||||
brews = [
|
||||
"ffmpeg"
|
||||
"gallery-dl" # X/Twitter media download for yt-transcribe (X video needs auth yt-dlp can't get)
|
||||
"gh"
|
||||
"herdr"
|
||||
# Client-only psql for read-only DB investigation. libpq is the keg-only
|
||||
@@ -53,23 +54,32 @@
|
||||
# resolves on the normal PATH. No server, service, database, or
|
||||
# connection is configured.
|
||||
{ name = "libpq"; link = true; }
|
||||
"node" # required: opencode2 is an npm global, not a Homebrew formula
|
||||
"node" # required: backpass and acpx are npm globals, not formulae
|
||||
# Unpinned: onActivation.upgrade refreshes formulae each rebuild, so the
|
||||
# linked binary tracks the latest opencode release. Crew harness and oc2.
|
||||
"opencode"
|
||||
"pi-coding-agent"
|
||||
"tea" # Gitea CLI - PRs for firstmate crewmates on unraid.local:3003
|
||||
"tmux"
|
||||
"treehouse"
|
||||
"whisper-cpp" # whisper-cli for yt-transcribe (reuses OpenSuperWhisper's model)
|
||||
"yt-dlp" # yt-transcribe engine; same engine reclip runs in its container
|
||||
];
|
||||
casks = [
|
||||
# Codex desktop home: the standalone Codex.app was folded into the ChatGPT
|
||||
# app (2026-07); the deprecated `codex-app` cask must not be used.
|
||||
"chatgpt"
|
||||
"codex" # Codex CLI; shares ~/.codex/config.toml with the desktop app
|
||||
"coteditor" # plain-text editor; cask id is one lowercase word
|
||||
"docker-desktop"
|
||||
"grok-build"
|
||||
"opensuperwhisper" # local Whisper dictation; model seed in home.nix
|
||||
"puremac"
|
||||
"utm"
|
||||
"wezterm"
|
||||
];
|
||||
};
|
||||
|
||||
launchd.user.agents = { };
|
||||
}
|
||||
|
||||
Generated
+16
-16
@@ -3,16 +3,16 @@
|
||||
"brew-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1788591592,
|
||||
"narHash": "sha256-NbwVKwKLFl0oXub7oPjvmDaOygCtV2oboeKTu4xXFTk=",
|
||||
"lastModified": 1793000687,
|
||||
"narHash": "sha256-8mCor0DDjNhi+0e+FllfqiMABujBl+/RxYW+wgMpcto=",
|
||||
"owner": "Homebrew",
|
||||
"repo": "brew",
|
||||
"rev": "08e85c4e42f5d8f1ea17c36cb59cf61c2ccb26c3",
|
||||
"rev": "c6069d2a943b71b0a90d91fc1ac93cb9c1634dcc",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "Homebrew",
|
||||
"ref": "6.0.22",
|
||||
"ref": "7.0.11",
|
||||
"repo": "brew",
|
||||
"type": "github"
|
||||
}
|
||||
@@ -24,11 +24,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1789267039,
|
||||
"narHash": "sha256-LWiBv9yAYFi2LPbUhDGHPGKYskJQjj2fw12OlyO1uQo=",
|
||||
"lastModified": 1792818383,
|
||||
"narHash": "sha256-199i7ubVSXTMl+0AAlL7cVCXSjcI+jWByMcimYjeMX0=",
|
||||
"owner": "nix-community",
|
||||
"repo": "home-manager",
|
||||
"rev": "ec172013fa62135f58fb58dd17ae9651e8f39727",
|
||||
"rev": "24f2190587513b9c2f73db112a17844ae912d965",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -45,11 +45,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1783744694,
|
||||
"narHash": "sha256-2cp6N3rrwnGYLTx9l6N+NI+kwrCWxvJUbj5WJhvB29A=",
|
||||
"lastModified": 1792800221,
|
||||
"narHash": "sha256-53jIZEWNh96irEXhsMZFoNhLJgGSU3nYl1i4wFQHAsU=",
|
||||
"owner": "nix-darwin",
|
||||
"repo": "nix-darwin",
|
||||
"rev": "c3e90c89649b07d1a96e4b9dd6cd0d6e44b91a74",
|
||||
"rev": "d31953cf55f9027a56e9be938daf5db8c5655663",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -64,11 +64,11 @@
|
||||
"brew-src": "brew-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1788981439,
|
||||
"narHash": "sha256-fEaFq0XgpgWFPLfpq1UK4/8ylHd2T0+fo6O3hKz1LUM=",
|
||||
"lastModified": 1793543863,
|
||||
"narHash": "sha256-oDYLVD8KGT/M57c8HziYSSj0le4wCyA+jZ7+/qUS91M=",
|
||||
"owner": "zhaofengli",
|
||||
"repo": "nix-homebrew",
|
||||
"rev": "09a921d0181146cf6163ec2cc1db7b6fd539a885",
|
||||
"rev": "52bc87da3f30c2261a6d1cfef3c892097b53daeb",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -79,11 +79,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1789485310,
|
||||
"narHash": "sha256-VsDMTLSkAAJmbNha6sGNzlF33X7RESWLl3SnjDQu+4U=",
|
||||
"lastModified": 1793976852,
|
||||
"narHash": "sha256-bWDN3JZcE9ovYoaD0/6WYbMtXYpUu0vd5onpK0pc/SE=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "0c32f40fe3e2a9adfc427fd5abc061a31043ea44",
|
||||
"rev": "57f1c8965649ce5bcac5118a0d2e41f1fbdc56e5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -4,6 +4,35 @@ let
|
||||
home = config.home.homeDirectory;
|
||||
dotfiles = "${home}/.dotfiles";
|
||||
firstmateHome = "${home}/Documents/firstmate";
|
||||
# yt-transcribe: captions-first transcription for YouTube/X/local media.
|
||||
# Source of truth is this repo's home/bin scripts; nix copies them into the
|
||||
# store so every context (launchd, shells) executes from local disk. Stable
|
||||
# ~/.local/bin symlinks below survive store-path changes between rebuilds.
|
||||
ytTranscribe = pkgs.runCommand "yt-transcribe" { } ''
|
||||
install -Dm755 ${./home/bin/yt-transcribe} $out/bin/yt-transcribe
|
||||
'';
|
||||
# Pinned pstack skills tree (cursor/plugins). `tdd` is deliberately absent:
|
||||
# an existing user-level tdd skill owns that name. See firstmate's
|
||||
# docs/adopted-skills.md for why these eleven skills exist.
|
||||
pstackSkillNames = [
|
||||
"statechart"
|
||||
"create-verification-skill"
|
||||
"maintain-verification-skill"
|
||||
"correct"
|
||||
"benchmark-checklist"
|
||||
"architect"
|
||||
"technical-writing"
|
||||
"unslop"
|
||||
"recall"
|
||||
"ketchup"
|
||||
"blast-radius"
|
||||
];
|
||||
pstackSkills = pkgs.fetchFromGitHub {
|
||||
owner = "cursor";
|
||||
repo = "plugins";
|
||||
rev = "6b0300214a09fd6029cfb7077043125758cd1fd2";
|
||||
hash = "sha256-TDuZ1v+taPdqyvvCs1VHUjtpSy8zHxhQKJv/kIPTpK8=";
|
||||
};
|
||||
in
|
||||
|
||||
{
|
||||
@@ -24,7 +53,7 @@ in
|
||||
nerd-fonts.hack
|
||||
ngrok # reverse TCP tunnel so the phone can SSH in over cellular (unfree)
|
||||
beets # music tagger / library organizer + navidrome sync plugin
|
||||
];
|
||||
] ++ [ ytTranscribe ];
|
||||
fonts.fontconfig.enable = true;
|
||||
home.sessionVariables.EDITOR = "nvim";
|
||||
|
||||
@@ -34,6 +63,11 @@ in
|
||||
syntaxHighlighting.enable = true; # commands turn green when valid
|
||||
initContent = ''
|
||||
bindkey '^f' autosuggest-accept
|
||||
# Keep the OpenCode Go CLI, Pi, no-mistakes, and Hermes key aligned with
|
||||
# the desktop app login after an account switch.
|
||||
if [ -x "$HOME/.local/bin/opencode-go-key-sync" ]; then
|
||||
"$HOME/.local/bin/opencode-go-key-sync" >/dev/null 2>&1 || true
|
||||
fi
|
||||
'';
|
||||
shellAliases = {
|
||||
".." = "cd ..";
|
||||
@@ -46,11 +80,15 @@ in
|
||||
cc = "claude --dangerously-skip-permissions";
|
||||
co = "codex --full-auto";
|
||||
gb = "grok --yolo";
|
||||
# firstmate primary session via OpenCode 2 (isolated config; crewmates = OpenCode)
|
||||
fm = "cd ${firstmateHome} && exec ${home}/.local/bin/oc2";
|
||||
# firstmate primary session via Pi on the OpenCode Go subscription; crewmates = OpenCode by default
|
||||
fm = "cd ${firstmateHome} && exec pi";
|
||||
oc2 = "${home}/.local/bin/oc2";
|
||||
# Sync ~/Music into the beets library on Unraid (requires NAS mounted).
|
||||
sync-music = "~/.local/bin/sync-music";
|
||||
# Transcribe a YouTube/X URL or a local media file. Tool code lives in
|
||||
# this repo (nix store); the Unraid share holds only data — mount it at
|
||||
# /Volumes/data (or set YT_SHARE_ROOT for a different mount point).
|
||||
yt-transcribe = "${home}/.local/bin/yt-transcribe";
|
||||
# Start the reverse tunnel so you can SSH into this Mac from your phone.
|
||||
# Run once when you go remote: `ngrok-tunnel`. Reads authtoken from
|
||||
# ~/.config/ngrok (set once per machine with `ngrok config add-authtoken <TOK>`)
|
||||
@@ -157,6 +195,12 @@ in
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/opencode-go-token";
|
||||
force = true;
|
||||
};
|
||||
# Copy the desktop app's OpenCode Go login into the CLI, Pi, and Hermes stores.
|
||||
# The app writes opencode.db only; those tools read auth.json and .env.
|
||||
home.file.".local/bin/opencode-go-key-sync" = {
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/opencode-go-key-sync";
|
||||
force = true;
|
||||
};
|
||||
# Codex 0.160+ profiles live in $CODEX_HOME/<name>.config.toml. The app does not
|
||||
# touch these, so they can be symlinked normally.
|
||||
home.file.".codex/luna.config.toml" = {
|
||||
@@ -175,7 +219,7 @@ in
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/.config/opencode/skills";
|
||||
force = true;
|
||||
};
|
||||
# OpenCode 2 isolated config - never share ~/.config/opencode with 1.x
|
||||
# OpenCode isolated config - keep it separate from ~/.config/opencode
|
||||
home.file.".config/opencode2/opencode.json" = {
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/.config/opencode2/opencode.json";
|
||||
force = true;
|
||||
@@ -188,6 +232,16 @@ in
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/oc2";
|
||||
force = true;
|
||||
};
|
||||
home.file.".local/bin/security-audit-sandbox" = {
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/security-audit-sandbox";
|
||||
force = true;
|
||||
};
|
||||
# Stable symlink for yt-transcribe: shells exec it from local disk. The
|
||||
# repo's home/bin script is the source of truth — a repo edit takes effect
|
||||
# on the next rebuild; the Unraid share holds only data.
|
||||
home.file.".local/bin/yt-transcribe" = {
|
||||
source = "${ytTranscribe}/bin/yt-transcribe";
|
||||
};
|
||||
home.file.".grok/AGENTS.md" = {
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/AGENTS.md";
|
||||
force = true;
|
||||
@@ -315,22 +369,9 @@ in
|
||||
"$HOME/.codex/config.toml"
|
||||
'';
|
||||
|
||||
# OpenCode 2 is not on Homebrew (beta). Install via Homebrew's npm, never
|
||||
# Nix's npm (EACCES on the store). Skip when already present so a rebuild
|
||||
# does not pull a new beta under a live TUI.
|
||||
home.activation.opencode2 = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
|
||||
set -euo pipefail
|
||||
npm=/opt/homebrew/bin/npm
|
||||
bin=/opt/homebrew/bin/opencode2
|
||||
if [ -x "$bin" ]; then
|
||||
exit 0
|
||||
fi
|
||||
if [ ! -x "$npm" ]; then
|
||||
echo "opencode2: /opt/homebrew/bin/npm missing (declare node in homebrew.brews)" >&2
|
||||
exit 1
|
||||
fi
|
||||
"$npm" install -g --allow-scripts=@opencode-ai/cli @opencode-ai/cli@beta
|
||||
'';
|
||||
# OpenCode is the stable Homebrew `opencode` formula, linked in
|
||||
# configuration.nix; home/bin/oc2 runs its keg binary with an isolated config.
|
||||
# Nothing to install here.
|
||||
|
||||
# backpass (kunchenguid/backpass) - gradient descent for agent memory: reads
|
||||
# the transcript stores of the harnesses this config already declares
|
||||
@@ -339,8 +380,8 @@ in
|
||||
# to a harness you already authenticated, so acpx is a hard runtime dep and
|
||||
# must be on PATH. Homebrew node v26 satisfies backpass (>= 22.5) and acpx
|
||||
# (>= 22.13). Neither is a Homebrew formula: install via Homebrew's npm,
|
||||
# never Nix's npm (EACCES on the store). Skip-if-present like opencode2 so a
|
||||
# rebuild never pulls a new version mid-session; refresh manually with
|
||||
# never Nix's npm (EACCES on the store). Skip-if-present so a rebuild never
|
||||
# pulls a new version mid-session; refresh manually with
|
||||
# /opt/homebrew/bin/npm update -g backpass acpx
|
||||
home.activation.backpass = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
|
||||
set -euo pipefail
|
||||
@@ -389,7 +430,137 @@ in
|
||||
mkdir -p "$(dirname "$cfg")"
|
||||
printf 'agent: [pi]\n' > "$cfg"
|
||||
fi
|
||||
# Ensure the captain's model split (idempotent and additive, so hand edits survive).
|
||||
# Implementer, pipeline default, and pipeline fixer run deepseek-v4.1-flash;
|
||||
# the review role runs glm-5.3-flash, so review never uses the implementing model.
|
||||
if ! grep -qE '^[[:space:]]*agent_config:' "$cfg"; then
|
||||
printf 'agent_config:\n pi:\n model: opencode-go/deepseek-v4.1-flash\n' >> "$cfg"
|
||||
fi
|
||||
if ! grep -qE '^[[:space:]]*review_agents:' "$cfg"; then
|
||||
printf 'review_agents:\n reviewer:\n agent: pi\n model: opencode-go/glm-5.3-flash\n' >> "$cfg"
|
||||
fi
|
||||
# Ensure daemon running (launchd on macOS)
|
||||
"$bin" daemon restart >/dev/null 2>&1 || "$bin" daemon start >/dev/null 2>&1 || true
|
||||
'';
|
||||
|
||||
# cloudflare/security-audit - vulnerability-hunting skill for the coding agents.
|
||||
# Installed by the upstream Skills CLI through Homebrew's npx, because the skill
|
||||
# is a multi-file bundle and an upstream refresh must stay byte-identical.
|
||||
# Scope: the CLI's "universal" target is ~/.agents/skills, which Codex, Pi, and
|
||||
# OpenCode read as a user-level skill directory; Claude Code reads
|
||||
# ~/.claude/skills, so the CLI also links the skill there. Grok Build is out of
|
||||
# scope for this install: its skill directory is ~/.grok/skills, and the CLI
|
||||
# only populates it when `grok` is named in --agent. Never target
|
||||
# ~/.config/opencode/skills: home-manager owns that path with force = true and
|
||||
# mkOutOfStoreSymlink into the mutable dotfiles checkout, so a rebuild would
|
||||
# clobber the CLI's link and CLI writes would land in the git checkout. Skip
|
||||
# when installed, like backpass, so a rebuild never pulls a new skill
|
||||
# version mid-session. The skill's own README still requires an OS-enforced
|
||||
# sandbox before it may run target-controlled builds, tests, browsers, or
|
||||
# fuzzers. That sandbox is home/bin/security-audit-sandbox; without it, those
|
||||
# leads stay `needs_validation`.
|
||||
# Install and refresh commands, plus the sandbox docs, are in readme.md.
|
||||
home.activation.securityAuditSkill = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
|
||||
set -euo pipefail
|
||||
# Activation PATH lacks /opt/homebrew/bin, so npx's `#!/usr/bin/env node`
|
||||
# shebang fails. It also lacks /usr/bin, so the Skills CLI cannot spawn
|
||||
# /usr/bin/git and the clone fails with "spawn git ENOENT". Prepend both -
|
||||
# replacing PATH breaks the rest of the HM activation (nix-env, gettext).
|
||||
export PATH="/opt/homebrew/bin:/usr/bin:$PATH"
|
||||
npx=/opt/homebrew/bin/npx
|
||||
# Canonical copy plus the Claude Code link: rerun when either is missing so a
|
||||
# half-removed install heals, then skip while both exist. No `exit 0` here:
|
||||
# activation blocks are inlined into one flat script, and later blocks must
|
||||
# still run.
|
||||
if [ ! -f "$HOME/.agents/skills/security-audit/SKILL.md" ] \
|
||||
|| [ ! -e "$HOME/.claude/skills/security-audit" ]; then
|
||||
if [ ! -x "$npx" ]; then
|
||||
echo "securityAuditSkill: /opt/homebrew/bin/npx missing (declare node in homebrew.brews)" >&2
|
||||
exit 1
|
||||
fi
|
||||
# A rebuild must not fail when GitHub or npm is unreachable: the skill is an
|
||||
# enhancement, so warn and keep the rest of the switch going.
|
||||
if ! "$npx" --yes skills add https://github.com/cloudflare/security-audit-skill \
|
||||
--skill security-audit --global \
|
||||
--agent claude-code codex pi opencode --yes; then
|
||||
echo "securityAuditSkill: WARNING: skill install failed (network or Skills CLI unavailable); rebuild continues." >&2
|
||||
echo "securityAuditSkill: rerun ./rebuild.sh or install manually with the command in readme.md." >&2
|
||||
fi
|
||||
fi
|
||||
'';
|
||||
|
||||
# pstack skills installed from the pinned `pstackSkills` source above (folder
|
||||
# pstack/skills). The record of why these eleven skills exist is firstmate's
|
||||
# docs/adopted-skills.md. They live only in ~/.agents/skills, which is outside
|
||||
# git and Nix, so this block restores them on a fresh machine.
|
||||
# `tdd` is skipped on purpose: an existing user-level tdd skill owns that
|
||||
# name, so the pstack copy is never installed.
|
||||
# Each run replaces only the eleven target directories; every other skill,
|
||||
# including an existing tdd skill, stays untouched. No `exit 0` here,
|
||||
# because activation blocks are inlined into one flat script, so an early
|
||||
# exit would skip the blocks that follow.
|
||||
home.activation.pstackSkills = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
|
||||
set -euo pipefail
|
||||
src="${pstackSkills}/pstack/skills"
|
||||
dest="$HOME/.agents/skills"
|
||||
if [ ! -d "$src" ]; then
|
||||
echo "pstackSkills: pinned source tree missing at $src" >&2
|
||||
exit 1
|
||||
fi
|
||||
mkdir -p "$dest"
|
||||
for name in ${lib.concatStringsSep " " pstackSkillNames}; do
|
||||
if [ ! -d "$src/$name" ]; then
|
||||
echo "pstackSkills: pinned source is missing skill $name" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Remove first so a renamed source file never lingers in the old copy.
|
||||
rm -rf "$dest/$name"
|
||||
if ! cp -R "$src/$name" "$dest/$name"; then
|
||||
echo "pstackSkills: failed to install $name" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Store files are read-only; make the installed copy writable again.
|
||||
chmod -R u+w "$dest/$name"
|
||||
done
|
||||
echo "pstackSkills: installed ${toString (lib.length pstackSkillNames)} pinned skills into $dest"
|
||||
'';
|
||||
|
||||
# OpenSuperWhisper - local voice-first prompting (cask in configuration.nix).
|
||||
# The app reads its model from its own Application Support directory, so the
|
||||
# 1.6 GB Whisper model is downloaded here once and kept outside the Nix store.
|
||||
# A failed download must not fail the switch: warn, drop the partial file, and
|
||||
# let the app's Settings download it later. Only a missing or unusable model
|
||||
# selection is seeded; every other setting belongs to the app and survives the
|
||||
# rebuild. Never write hasCompletedOnboarding - onboarding must still run so the
|
||||
# captain can grant Microphone/Accessibility (macOS TCC grants are manual by
|
||||
# design). A running app picks up new defaults on its next launch; do not kill
|
||||
# it here.
|
||||
home.activation.openSuperWhisper = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
|
||||
set -euo pipefail
|
||||
supportDir="$HOME/Library/Application Support/ru.starmel.OpenSuperWhisper"
|
||||
modelDir="$supportDir/whisper-models"
|
||||
modelPath="$modelDir/ggml-large-v3-turbo.bin"
|
||||
modelUrl="https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3-turbo.bin?download=true"
|
||||
modelSha="1fc70f774d38eb169993ac391eea357ef47c88757ef72ee5943879b7e8e2bc69"
|
||||
curl="${pkgs.curl}/bin/curl"
|
||||
|
||||
mkdir -p "$modelDir"
|
||||
if [ ! -f "$modelPath" ]; then
|
||||
tmp="$(${pkgs.coreutils}/bin/mktemp "$modelDir/.ggml-large-v3-turbo.XXXXXX")"
|
||||
if "$curl" -fL --retry 3 --connect-timeout 30 -o "$tmp" "$modelUrl" \
|
||||
&& printf '%s %s\n' "$modelSha" "$tmp" | ${pkgs.coreutils}/bin/sha256sum -c - >/dev/null 2>&1; then
|
||||
mv "$tmp" "$modelPath"
|
||||
else
|
||||
echo "openSuperWhisper: WARNING: could not download or verify the Whisper model." >&2
|
||||
echo "openSuperWhisper: the app still works; download \"Whisper V3 Large\" in Settings later." >&2
|
||||
${pkgs.coreutils}/bin/rm -f "$tmp"
|
||||
fi
|
||||
fi
|
||||
|
||||
defaults=/usr/bin/defaults
|
||||
selectedModel="$("$defaults" read ru.starmel.OpenSuperWhisper selectedWhisperModelPath 2>/dev/null || true)"
|
||||
if [ -f "$modelPath" ] && { [ -z "$selectedModel" ] || [ ! -f "$selectedModel" ]; }; then
|
||||
"$defaults" write ru.starmel.OpenSuperWhisper selectedWhisperModelPath -string "$modelPath"
|
||||
fi
|
||||
'';
|
||||
}
|
||||
@@ -3,5 +3,19 @@
|
||||
"statusLine": {
|
||||
"type": "command",
|
||||
"command": "input=$(cat); model=$(echo \"$input\" | jq -r '.model.display_name'); used=$(echo \"$input\" | jq -r '.context_window.used_percentage // empty'); if [ -n \"$used\" ]; then printf \"%s | ctx: %.0f%% used\" \"$model\" \"$used\"; else printf \"%s\" \"$model\"; fi"
|
||||
},
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "lavish-axi",
|
||||
"timeout": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,32 @@
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"when": "Well-specified implementation with clear acceptance criteria: pure functions, tests, repositories, adapters, or external-fetch integration.",
|
||||
"use": [{ "harness": "opencode", "model": "opencode-go/deepseek-v4.1-flash", "provider": "opencode-go" }],
|
||||
"why": "DeepSeek V4.1 Flash is the default OpenCode Go implementation worker; it is fast, economical, and strong on agentic coding tasks."
|
||||
"when": "Design, architecture, architectural review, or design review tasks. This includes product design, UI/UX design, system design, and design investigations. For design tasks with screenshots or other image context, this rule takes precedence over the UI implementation rule. Ordinary implementation and routine code validation do not match this rule. When a task moves from design to implementation, resolve the implementation profile again rather than retaining this model for continuity.",
|
||||
"use": {
|
||||
"harness": "pi",
|
||||
"model": "openai-codex/gpt-6.1-sol",
|
||||
"effort": "xhigh",
|
||||
"provider": "codex"
|
||||
},
|
||||
"why": "Captain's order: use GPT-6.1 Sol through openai-codex in Pi for design and architectural review tasks. Other task types retain their existing profiles."
|
||||
},
|
||||
{
|
||||
"when": "UI work where supplied screenshots or other image context materially affect the implementation or verification.",
|
||||
"use": [{ "harness": "opencode", "model": "opencode-go/glm-5.3-flash", "provider": "opencode-go" }],
|
||||
"why": "GLM-5.3-Flash is the Go worker with image input; use it when visual context matters."
|
||||
},
|
||||
{
|
||||
"when": "Ambiguous investigation, difficult debugging, architectural tradeoffs, or broad changes with high uncertainty or blast radius.",
|
||||
"use": [{ "harness": "opencode", "model": "opencode-go/gpt-6-luna", "provider": "opencode-go" }],
|
||||
"why": "Reserve GPT-6 Luna for work that benefits from stronger reasoning than the fast implementation tier."
|
||||
"use": [
|
||||
{
|
||||
"harness": "opencode",
|
||||
"model": "opencode-go/deepseek-v4.1-flash",
|
||||
"provider": "opencode-go"
|
||||
}
|
||||
],
|
||||
"why": "Captain's order 2026-10-21: paid Go for every crewmate and scout after the free lane hit 'Free usage exceeded' with a 10.5 hour retry, which ended five sessions in forty minutes. The free deepseek-v4.1-flash-free order of 2026-10-20 resumes when that lane resets; paid Go had 5 percent of its monthly window left, projected empty 2026-10-22T05:43Z."
|
||||
}
|
||||
],
|
||||
"default": [{ "harness": "opencode", "model": "opencode-go/deepseek-v4.1-flash", "provider": "opencode-go" }]
|
||||
"default": [
|
||||
{
|
||||
"harness": "opencode",
|
||||
"model": "opencode-go/deepseek-v4.1-flash",
|
||||
"provider": "opencode-go"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -16,3 +16,7 @@ copy_mode = "prefix+y" # herdr's copy-mode entry key; copy-mode's own internal
|
||||
[ui]
|
||||
# Agents panel order: explicit choice of "spaces" (grouped by space, the default) over "priority".
|
||||
agent_panel_sort = "spaces"
|
||||
|
||||
[theme]
|
||||
name = "dracula"
|
||||
auto_switch = false
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"diffview.nvim": { "branch": "main", "commit": "4516612fe98ff56ae0415a259ff6361a89419b0a" },
|
||||
"gitsigns.nvim": { "branch": "main", "commit": "31d6fb2d618bca1482b9f274751ead5f03461408" },
|
||||
"lazy.nvim": { "branch": "main", "commit": "306a05526ada86a7b30af95c5cc81ffba93fef97" },
|
||||
"lazy.nvim": { "branch": "main", "commit": "85c7ff3711b730b4030d03144f6db6375044ae82" },
|
||||
"neogit": { "branch": "master", "commit": "f8674ec894315c02449b61c9de9a116c5aafeb90" },
|
||||
"oil.nvim": { "branch": "master", "commit": "b73018b75affd13fa38e2fc94ef753b465f770d7" },
|
||||
"plenary.nvim": { "branch": "master", "commit": "74b06c6c75e4eeb3108ec01852001636d85a932b" },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"model": "opencode-go/gpt-6-luna",
|
||||
"model": "opencode-go/deepseek-v4.1-flash",
|
||||
"instructions": ["AGENTS.md"],
|
||||
"provider": {
|
||||
"omlx": {
|
||||
@@ -22,6 +22,31 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"opencode": {
|
||||
"models": {
|
||||
"muse-spark-1.3-contributor-free": {
|
||||
"limit": {
|
||||
"context": 256000,
|
||||
"input": 256000,
|
||||
"output": 128000
|
||||
}
|
||||
},
|
||||
"muse-spark-1.3": {
|
||||
"limit": {
|
||||
"context": 256000,
|
||||
"input": 256000,
|
||||
"output": 128000
|
||||
}
|
||||
},
|
||||
"muse-spark-1.2": {
|
||||
"limit": {
|
||||
"context": 256000,
|
||||
"input": 256000,
|
||||
"output": 128000
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"opencode-go": {
|
||||
"models": {
|
||||
"gpt-6-luna": {
|
||||
@@ -37,6 +62,20 @@
|
||||
"input": 256000,
|
||||
"output": 128000
|
||||
}
|
||||
},
|
||||
"muse-spark-1.3-contributor": {
|
||||
"limit": {
|
||||
"context": 256000,
|
||||
"input": 256000,
|
||||
"output": 128000
|
||||
}
|
||||
},
|
||||
"muse-spark-1.2-contributor": {
|
||||
"limit": {
|
||||
"context": 256000,
|
||||
"input": 256000,
|
||||
"output": 128000
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"model": "opencode-go/gpt-6-luna",
|
||||
"model": "opencode-go/deepseek-v4.1-flash",
|
||||
"autoupdate": false,
|
||||
"providers": {
|
||||
"omlx": {
|
||||
|
||||
@@ -38,6 +38,38 @@
|
||||
"contextWindow": 272000
|
||||
}
|
||||
}
|
||||
},
|
||||
"opencode-go": {
|
||||
"modelOverrides": {
|
||||
"deepseek-v4-flash": {
|
||||
"contextWindow": 256000
|
||||
},
|
||||
"deepseek-v4-flash-vision-exp": {
|
||||
"contextWindow": 256000
|
||||
},
|
||||
"deepseek-v4-pro": {
|
||||
"contextWindow": 256000
|
||||
},
|
||||
"deepseek-v4.1-flash": {
|
||||
"contextWindow": 256000
|
||||
}
|
||||
}
|
||||
},
|
||||
"opencode": {
|
||||
"modelOverrides": {
|
||||
"deepseek-v4-flash": {
|
||||
"contextWindow": 256000
|
||||
},
|
||||
"deepseek-v4-flash-vision-exp": {
|
||||
"contextWindow": 256000
|
||||
},
|
||||
"deepseek-v4-pro": {
|
||||
"contextWindow": 256000
|
||||
},
|
||||
"deepseek-v4.1-flash": {
|
||||
"contextWindow": 256000
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"lastChangelogVersion": "0.87.1",
|
||||
"lastChangelogVersion": "1.5.0",
|
||||
"theme": "rose-pine-moon",
|
||||
"defaultProvider": "opencode-go",
|
||||
"defaultModel": "deepseek-v4.1-flash",
|
||||
@@ -17,8 +17,8 @@
|
||||
},
|
||||
"packages": [
|
||||
"npm:pi-context",
|
||||
"npm:pi-web-access@0.14.0",
|
||||
"npm:@ryan_nookpi/pi-extension-codex-fast-mode@0.2.6",
|
||||
"npm:pi-web-access@0.36.0",
|
||||
"npm:@ryan_nookpi/pi-extension-codex-fast-mode@0.2.8",
|
||||
"git:github.com/algal/pi-openai-server-compaction@c6d593087709e9481223dc6c6c2269b371b5e055",
|
||||
"../../.automaton/plugins/pi-read-tweet"
|
||||
],
|
||||
@@ -33,5 +33,9 @@
|
||||
"quietStartup": true,
|
||||
"steeringMode": "all",
|
||||
"followUpMode": "all",
|
||||
"collapseChangelog": true
|
||||
}
|
||||
"collapseChangelog": true,
|
||||
"extensionChangelogVersions": {
|
||||
"{\"source\":\"npm:pi-web-access@0.36.0\",\"scope\":\"user\"}": "0.36.0",
|
||||
"{\"source\":\"git:github.com/algal/pi-openai-server-compaction@c6d593087709e9481223dc6c6c2269b371b5e055\",\"scope\":\"user\"}": "0.1.0"
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,19 @@
|
||||
- Apply that same high standard to engineering excellence: lint, test failures, and test flakiness.
|
||||
If you see one, even if it is not caused by what you are working on right now, still get it fixed.
|
||||
- Before using "dynamic workflows", "ultra code" or any harness feature that immediately spawns a large swarm of subagents, always explain the tradeoffs and ask the user for explicit approval.
|
||||
|
||||
## Response style (ASD-STE100, evidence-backed 2026-10-06)
|
||||
|
||||
Source: 10 randomly sampled interactive transcripts from the past week (seed 20261006; population was 11: 8 Codex sessions Oct 3-4, 3 opencode backpass sessions Oct 5). The sampled assistant texts repeatedly violated the same STE rules at the exact points where the conversation stalled or confused. Follow these rules in every assistant response:
|
||||
- Short sentences: max 20 words per instruction, 25 per explanation (STE 5.1/6.3). Observed worst case was a 57-word status sentence; split it instead.
|
||||
- One instruction per sentence; use a vertical list for multi-step directions (STE 5.2/4.3).
|
||||
- Instructions in the imperative; status in simple present or past. Report results, do not narrate intentions ("Let me X" appeared ~20 times in one session) (STE 5.3/3.2).
|
||||
- Active voice with a named agent. "Commands are being rejected" hid who rejects them (STE 3.6).
|
||||
- Condition before command: "If X, do Y" (STE 5.4). A buried proxy precondition sent the user to a dead URL first.
|
||||
- One name per thing for the whole response (STE 1.11/9.4). Observed rotation: proxy/server/relay and page/app/calculator for single objects.
|
||||
- Plain verbs, no phrasal verbs or jargon verbs: fall back, fill in, queued, wiring, smoke-test (STE 9.3).
|
||||
- No -ing forms as verbs or subjects, no contractions, no dropped objects ("Confirming:" with no object; "isn't running") (STE 3.5/4.2).
|
||||
- Only can/will/must as modals. The would/could/should sentences were exactly the untested claims that later confused (STE 3.2).
|
||||
- Max three words per noun stack; define thread slang on first use (STE 2.1/1.10).
|
||||
- No semicolons, including inside JSON rationale strings; write two sentences (STE 8.1).
|
||||
- American spelling ("colour-coded" slipped through) and keep the articles a/the (STE 1.14/4.5).
|
||||
+5
-5
@@ -1,14 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
# Launch OpenCode 2 with an isolated config so it cannot rewrite
|
||||
# ~/.config/opencode/opencode.json (OpenCode 1 / firstmate).
|
||||
# Launch OpenCode with an isolated config so it cannot rewrite
|
||||
# ~/.config/opencode/opencode.json (firstmate).
|
||||
set -euo pipefail
|
||||
|
||||
bin="${OPENCODE2_BIN:-/opt/homebrew/bin/opencode2}"
|
||||
bin="${OPENCODE2_BIN:-/opt/homebrew/opt/opencode/bin/opencode}"
|
||||
cfg="${OPENCODE_CONFIG:-$HOME/.config/opencode2/opencode.json}"
|
||||
|
||||
if [ ! -x "$bin" ]; then
|
||||
echo "oc2: opencode2 not installed. Rebuild, or run:" >&2
|
||||
echo " /opt/homebrew/bin/npm install -g --allow-scripts=@opencode-ai/cli @opencode-ai/cli@beta" >&2
|
||||
echo "oc2: stable opencode not installed. Rebuild, or run:" >&2
|
||||
echo " brew install opencode" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -e "$cfg" ]; then
|
||||
|
||||
Executable
+178
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Copy the OpenCode Go key from the desktop app store into the CLI auth files.
|
||||
|
||||
The OpenCode desktop app writes its login to
|
||||
<XDG_DATA_HOME>/opencode/opencode.db (table credential, integration opencode-go)
|
||||
but the opencode CLI, firstmate workers, pi, and no-mistakes read
|
||||
<XDG_DATA_HOME>/opencode/auth.json (opencode-go.key)
|
||||
~/.pi/agent/auth.json (opencode-go.key)
|
||||
|
||||
After an account switch the app store is current and those JSON files still hold
|
||||
the old key, so workers and the validation pipeline fail with a usage or auth
|
||||
error. Run this after switching accounts.
|
||||
|
||||
Safety:
|
||||
* The app credential is the source only when it is newer than the target file.
|
||||
* If a target file is newer than the app credential, it is left alone and the
|
||||
command reports a conflict instead of overwriting a manual login.
|
||||
* The key is never printed.
|
||||
|
||||
Exit status: 0 in sync or updated, 2 conflict, 1 no source credential.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
def data_home():
|
||||
return os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
|
||||
|
||||
|
||||
def app_credential():
|
||||
db = os.path.join(data_home(), "opencode", "opencode.db")
|
||||
if not os.path.exists(db):
|
||||
return None
|
||||
con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
|
||||
try:
|
||||
row = con.execute(
|
||||
"select value, time_updated from credential"
|
||||
" where integration_id='opencode-go' order by time_updated desc limit 1"
|
||||
).fetchone()
|
||||
finally:
|
||||
con.close()
|
||||
if not row:
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(row[0])
|
||||
except Exception:
|
||||
return None
|
||||
key = payload.get("key") if isinstance(payload, dict) else None
|
||||
if not key:
|
||||
return None
|
||||
return key, int(row[1]) / 1000.0
|
||||
|
||||
|
||||
def read_target(path):
|
||||
with open(path) as fh:
|
||||
data = json.load(fh)
|
||||
entry = data.get("opencode-go")
|
||||
key = entry.get("key") if isinstance(entry, dict) else None
|
||||
return data, key
|
||||
|
||||
|
||||
def write_target(path, data):
|
||||
directory = os.path.dirname(path)
|
||||
fd, tmp = tempfile.mkstemp(dir=directory, prefix=".auth.", suffix=".json")
|
||||
try:
|
||||
with os.fdopen(fd, "w") as fh:
|
||||
json.dump(data, fh)
|
||||
os.chmod(tmp, 0o600)
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
|
||||
|
||||
def target_paths():
|
||||
return [
|
||||
os.path.join(data_home(), "opencode", "auth.json"),
|
||||
os.path.expanduser("~/.pi/agent/auth.json"),
|
||||
]
|
||||
|
||||
|
||||
def sync_hermes(source_key, check):
|
||||
"""Update OPENCODE_GO_API_KEY in the Hermes env file when it differs."""
|
||||
path = os.path.expanduser("~/.hermes/.env")
|
||||
if not os.path.exists(path):
|
||||
return 0
|
||||
with open(path) as fh:
|
||||
lines = fh.readlines()
|
||||
current = None
|
||||
for line in lines:
|
||||
stripped = line.rstrip("\n")
|
||||
if stripped.startswith("OPENCODE_GO_API_KEY="):
|
||||
current = stripped.split("=", 1)[1]
|
||||
break
|
||||
if current is None:
|
||||
return 0
|
||||
label = "hermes/.env"
|
||||
if current == source_key:
|
||||
print(f"{label}: in sync")
|
||||
return 0
|
||||
if check:
|
||||
print(f"{label}: stale, would update", file=sys.stderr)
|
||||
return 2
|
||||
rewritten = []
|
||||
for line in lines:
|
||||
if line.startswith("OPENCODE_GO_API_KEY="):
|
||||
rewritten.append(f"OPENCODE_GO_API_KEY={source_key}\n")
|
||||
else:
|
||||
rewritten.append(line)
|
||||
with open(path, "w") as fh:
|
||||
fh.writelines(rewritten)
|
||||
os.chmod(path, 0o600)
|
||||
print(f"{label}: updated")
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--check",
|
||||
action="store_true",
|
||||
help="report drift and exit 2 instead of updating",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
source = app_credential()
|
||||
if not source:
|
||||
print(
|
||||
"opencode-go-key-sync: no opencode-go credential in the app store",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
source_key, source_time = source
|
||||
|
||||
status = 0
|
||||
for path in target_paths():
|
||||
label = os.path.basename(os.path.dirname(path)) + "/" + os.path.basename(path)
|
||||
if not os.path.exists(path):
|
||||
print(f"{label}: missing, skipped", file=sys.stderr)
|
||||
status = max(status, 2)
|
||||
continue
|
||||
data, current_key = read_target(path)
|
||||
if current_key == source_key:
|
||||
print(f"{label}: in sync")
|
||||
continue
|
||||
target_time = os.path.getmtime(path)
|
||||
if target_time > source_time:
|
||||
print(
|
||||
f"{label}: has a newer key than the app store, left unchanged"
|
||||
" (log in again in the app, or update this file by hand)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
status = max(status, 2)
|
||||
continue
|
||||
if args.check:
|
||||
print(f"{label}: stale, would update", file=sys.stderr)
|
||||
status = max(status, 2)
|
||||
continue
|
||||
entry = data.get("opencode-go")
|
||||
if not isinstance(entry, dict):
|
||||
entry = {"type": "api"}
|
||||
entry["key"] = source_key
|
||||
data["opencode-go"] = entry
|
||||
write_target(path, data)
|
||||
print(f"{label}: updated")
|
||||
|
||||
status = max(status, sync_hermes(source_key, args.check))
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+576
@@ -0,0 +1,576 @@
|
||||
#!/usr/bin/env bash
|
||||
# security-audit-sandbox - OS-enforced Docker sandbox for the security-audit skill.
|
||||
#
|
||||
# Copies target code into a scratch directory and runs it in a locked-down
|
||||
# container: no network, read-only root, scratch-only writes, dropped
|
||||
# capabilities, no-new-privileges, and CPU/memory/PID limits.
|
||||
#
|
||||
# Usage:
|
||||
# security-audit-sandbox start <app> [--image <image>] [--exclude <pattern>]...
|
||||
# security-audit-sandbox exec <app> [--timeout <seconds>] -- <command>...
|
||||
# security-audit-sandbox stop <app> [--keep]
|
||||
# security-audit-sandbox status <app>
|
||||
# security-audit-sandbox --help
|
||||
#
|
||||
# Optional <app>/security-audit.conf (simple KEY=value lines, never sourced):
|
||||
# IMAGE=node:22-bookworm
|
||||
# EXCLUDE="node_modules dist coverage"
|
||||
#
|
||||
# Default exclusions: .git, .env*, and the top-level /data directory.
|
||||
# The original app directory is never mounted into the container.
|
||||
set -euo pipefail
|
||||
|
||||
PROG=security-audit-sandbox
|
||||
RUN_PARENT="$HOME/security-audit-runs"
|
||||
STATE_ROOT="${XDG_STATE_HOME:-$HOME/.local/state}/security-audit-sandbox"
|
||||
CONF_NAME=security-audit.conf
|
||||
DEFAULT_TIMEOUT=600
|
||||
|
||||
die() {
|
||||
printf '%s: %s\n' "$PROG" "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Copy target code into a scratch directory and run it in a locked-down Docker
|
||||
container: no network, read-only root, scratch-only writes, dropped
|
||||
capabilities, no-new-privileges, and CPU/memory/PID limits.
|
||||
|
||||
Usage:
|
||||
security-audit-sandbox start <app> [--image <image>] [--exclude <pattern>]...
|
||||
Copy <app> to $HOME/security-audit-runs/<slug>.XXXXXX and start the
|
||||
container. Repeat --exclude to add rsync exclusions.
|
||||
|
||||
security-audit-sandbox exec <app> [--timeout <seconds>] -- <command>...
|
||||
Run <command> inside the running container from /scratch/app under
|
||||
`timeout --signal=KILL`. Default timeout: 600 seconds.
|
||||
|
||||
security-audit-sandbox stop <app> [--keep]
|
||||
Remove the container and state file. Remove the run directory too,
|
||||
unless --keep is given.
|
||||
|
||||
security-audit-sandbox status <app>
|
||||
Print the container name, run directory, and whether it is running.
|
||||
|
||||
security-audit-sandbox --help
|
||||
Show this help.
|
||||
|
||||
Optional <app>/security-audit.conf (simple KEY=value lines, never sourced):
|
||||
IMAGE=node:22-bookworm
|
||||
EXCLUDE="node_modules dist coverage"
|
||||
|
||||
Image resolution order:
|
||||
1. --image
|
||||
2. IMAGE= in security-audit.conf
|
||||
3. package.json -> node:22-bookworm
|
||||
pyproject.toml or requirements.txt -> python:3.12-slim
|
||||
go.mod -> golang:1.24-bookworm
|
||||
Cargo.toml -> rust:1-bookworm
|
||||
Gemfile -> ruby:3.3-bookworm
|
||||
|
||||
Always excluded from the copy: .git, .env*, and the top-level /data directory.
|
||||
The original app directory is never mounted into the container.
|
||||
|
||||
Docker Desktop on macOS may refuse the fsize ulimit. The wrapper then starts
|
||||
the container without that one limit and prints a warning; nofile stays in
|
||||
place. On Linux hosts that accept fsize, the 100 MiB file-size cap is applied.
|
||||
EOF
|
||||
}
|
||||
|
||||
need_docker() {
|
||||
command -v docker >/dev/null 2>&1 || die "docker is not installed or not on PATH"
|
||||
docker info >/dev/null 2>&1 || die "cannot reach the Docker daemon; is Docker running?"
|
||||
}
|
||||
|
||||
canonical_app() {
|
||||
local app=$1
|
||||
[ -d "$app" ] || die "app directory not found: $app"
|
||||
(cd -P "$app" && pwd -P)
|
||||
}
|
||||
|
||||
app_slug() {
|
||||
local name
|
||||
name=$(basename "$1")
|
||||
name=${name//[^A-Za-z0-9_.-]/-}
|
||||
[ -n "$name" ] || name=app
|
||||
printf '%s' "$name"
|
||||
}
|
||||
|
||||
app_hash() {
|
||||
printf '%s' "$1" | shasum -a 256 | cut -c1-8
|
||||
}
|
||||
|
||||
state_file_for() {
|
||||
local app=$1 slug hash
|
||||
slug=$(app_slug "$app")
|
||||
hash=$(app_hash "$app")
|
||||
printf '%s/state-%s-%s' "$STATE_ROOT" "$slug" "$hash"
|
||||
}
|
||||
|
||||
container_name_for() {
|
||||
local app=$1 slug hash
|
||||
slug=$(app_slug "$app")
|
||||
hash=$(app_hash "$app")
|
||||
printf 'security-audit-%s-%s' "$slug" "$hash"
|
||||
}
|
||||
|
||||
strip_quotes() {
|
||||
local value=$1
|
||||
case $value in
|
||||
\"*\") value=${value#\"}; value=${value%\"} ;;
|
||||
\'*\') value=${value#\'}; value=${value%\'} ;;
|
||||
esac
|
||||
printf '%s' "$value"
|
||||
}
|
||||
|
||||
trim() {
|
||||
local value=$1
|
||||
value=${value#"${value%%[![:space:]]*}"}
|
||||
value=${value%"${value##*[![:space:]]}"}
|
||||
printf '%s' "$value"
|
||||
}
|
||||
|
||||
CONF_IMAGE=""
|
||||
CONF_EXCLUDE=""
|
||||
load_conf() {
|
||||
local app=$1 conf line key value
|
||||
conf="$app/$CONF_NAME"
|
||||
[ -f "$conf" ] || return 0
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
line=${line%$'\r'}
|
||||
line=$(trim "$line")
|
||||
case $line in
|
||||
''|'#'*) continue ;;
|
||||
esac
|
||||
case $line in
|
||||
*=*) ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
key=$(trim "${line%%=*}")
|
||||
value=$(trim "${line#*=}")
|
||||
value=$(strip_quotes "$value")
|
||||
case $key in
|
||||
IMAGE) CONF_IMAGE=$value ;;
|
||||
EXCLUDE) CONF_EXCLUDE="${CONF_EXCLUDE:+$CONF_EXCLUDE }$value" ;;
|
||||
esac
|
||||
done < "$conf"
|
||||
}
|
||||
|
||||
infer_image() {
|
||||
local app=$1
|
||||
if [ -f "$app/package.json" ]; then
|
||||
printf 'node:22-bookworm'
|
||||
elif [ -f "$app/pyproject.toml" ] || [ -f "$app/requirements.txt" ]; then
|
||||
printf 'python:3.12-slim'
|
||||
elif [ -f "$app/go.mod" ]; then
|
||||
printf 'golang:1.24-bookworm'
|
||||
elif [ -f "$app/Cargo.toml" ]; then
|
||||
printf 'rust:1-bookworm'
|
||||
elif [ -f "$app/Gemfile" ]; then
|
||||
printf 'ruby:3.3-bookworm'
|
||||
else
|
||||
printf ''
|
||||
fi
|
||||
}
|
||||
|
||||
load_state() {
|
||||
local app=$1 file key value
|
||||
file=$(state_file_for "$app")
|
||||
[ -f "$file" ] || return 1
|
||||
STATE_CONTAINER=""
|
||||
STATE_RUN_DIR=""
|
||||
STATE_APP=""
|
||||
STATE_IMAGE=""
|
||||
STATE_FSIZE=""
|
||||
while IFS='=' read -r key value || [ -n "$key" ]; do
|
||||
case $key in
|
||||
CONTAINER) STATE_CONTAINER=$value ;;
|
||||
RUN_DIR) STATE_RUN_DIR=$value ;;
|
||||
APP) STATE_APP=$value ;;
|
||||
IMAGE) STATE_IMAGE=$value ;;
|
||||
FSIZE) STATE_FSIZE=$value ;;
|
||||
esac
|
||||
done < "$file"
|
||||
[ -n "$STATE_CONTAINER" ] && [ -n "$STATE_RUN_DIR" ]
|
||||
}
|
||||
|
||||
container_running() {
|
||||
local name=$1 state
|
||||
state=$(docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null) || return 1
|
||||
[ "$state" = "true" ]
|
||||
}
|
||||
|
||||
container_exists() {
|
||||
docker inspect "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
WALL_CLOCK_PROBE_SECS=2
|
||||
|
||||
check_wall_clock_guard() {
|
||||
local container=$1 status elapsed out
|
||||
SECONDS=0
|
||||
set +e
|
||||
out=$(docker exec "$container" timeout --signal=KILL "$WALL_CLOCK_PROBE_SECS" sleep 10 2>&1)
|
||||
status=$?
|
||||
set -e
|
||||
elapsed=$SECONDS
|
||||
case $status in
|
||||
124|137) ;;
|
||||
*)
|
||||
[ -z "$out" ] || printf '%s\n' "$out" >&2
|
||||
die "image $STATE_IMAGE's 'timeout' does not enforce '--signal=KILL'; refusing to run without a wall-clock limit"
|
||||
;;
|
||||
esac
|
||||
if [ "$elapsed" -lt 1 ] || [ "$elapsed" -gt $((WALL_CLOCK_PROBE_SECS + 4)) ]; then
|
||||
die "image $STATE_IMAGE's 'timeout' did not stop the probe after ${WALL_CLOCK_PROBE_SECS}s; refusing to run without a wall-clock limit"
|
||||
fi
|
||||
}
|
||||
|
||||
check_run_dir() {
|
||||
local dir=$1
|
||||
case $dir in
|
||||
"$RUN_PARENT"/*) ;;
|
||||
*) die "refusing to remove unexpected run directory: $dir" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
rm_run_dir() {
|
||||
local dir=$1
|
||||
check_run_dir "$dir"
|
||||
rm -rf "$dir"
|
||||
}
|
||||
|
||||
cleanup_failed_start() {
|
||||
local run_dir=$1 state_file=$2
|
||||
[ -n "$run_dir" ] && [ -d "$run_dir" ] && rm_run_dir "$run_dir"
|
||||
[ -n "$state_file" ] && rm -f "$state_file"
|
||||
}
|
||||
|
||||
cmd_start() {
|
||||
local app_arg="" image_opt="" conf_image inferred
|
||||
local app app_dir run_dir container state_file fsize_note out
|
||||
local -a cli_excludes rsync_cmd docker_cmd
|
||||
cli_excludes=()
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--image)
|
||||
[ $# -ge 2 ] || die "--image needs a value"
|
||||
image_opt=$2
|
||||
shift 2
|
||||
;;
|
||||
--image=*)
|
||||
image_opt=${1#--image=}
|
||||
shift
|
||||
;;
|
||||
--exclude)
|
||||
[ $# -ge 2 ] || die "--exclude needs a value"
|
||||
cli_excludes+=("$2")
|
||||
shift 2
|
||||
;;
|
||||
--exclude=*)
|
||||
cli_excludes+=("${1#--exclude=}")
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
-*)
|
||||
die "unknown option for start: $1"
|
||||
;;
|
||||
*)
|
||||
[ -z "$app_arg" ] || die "unexpected argument for start: $1"
|
||||
app_arg=$1
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ -n "$app_arg" ] || die "start needs an app directory"
|
||||
need_docker
|
||||
app_dir=$(canonical_app "$app_arg")
|
||||
|
||||
load_conf "$app_dir"
|
||||
conf_image=$CONF_IMAGE
|
||||
|
||||
if [ -n "$image_opt" ]; then
|
||||
image=$image_opt
|
||||
elif [ -n "$conf_image" ]; then
|
||||
image=$conf_image
|
||||
else
|
||||
inferred=$(infer_image "$app_dir")
|
||||
[ -n "$inferred" ] || die "cannot infer an image for $app_dir; pass --image or set IMAGE= in $CONF_NAME"
|
||||
image=$inferred
|
||||
fi
|
||||
|
||||
state_file=$(state_file_for "$app_dir")
|
||||
container=$(container_name_for "$app_dir")
|
||||
|
||||
if load_state "$app_dir"; then
|
||||
if container_running "$STATE_CONTAINER"; then
|
||||
die "a sandbox for $app_dir is already running (container $STATE_CONTAINER); run '$PROG stop $app_arg' first"
|
||||
fi
|
||||
if container_exists "$STATE_CONTAINER"; then
|
||||
docker rm -f "$STATE_CONTAINER" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -f "$state_file"
|
||||
printf '%s: removed stale state for stopped container %s\n' "$PROG" "$STATE_CONTAINER" >&2
|
||||
fi
|
||||
|
||||
if container_exists "$container"; then
|
||||
die "container $container already exists but is not recorded in state; remove it with 'docker rm -f $container'"
|
||||
fi
|
||||
|
||||
mkdir -p "$RUN_PARENT" || die "cannot create $RUN_PARENT"
|
||||
run_dir=$(mktemp -d "$RUN_PARENT/$(app_slug "$app_dir").XXXXXX") || die "cannot create run directory under $RUN_PARENT"
|
||||
mkdir -p "$run_dir/app" "$run_dir/home" "$run_dir/tmp" "$run_dir/cache" || {
|
||||
cleanup_failed_start "$run_dir" "$state_file"
|
||||
die "cannot prepare run directory $run_dir"
|
||||
}
|
||||
|
||||
rsync_cmd=(rsync -a --exclude=.git --exclude='.env*' --exclude=/data)
|
||||
if [ -n "$CONF_EXCLUDE" ]; then
|
||||
local conf_pat
|
||||
local -a conf_pats
|
||||
read -r -a conf_pats <<< "$CONF_EXCLUDE"
|
||||
for conf_pat in "${conf_pats[@]}"; do
|
||||
rsync_cmd+=("--exclude=$conf_pat")
|
||||
done
|
||||
fi
|
||||
if [ ${#cli_excludes[@]} -gt 0 ]; then
|
||||
local cli_pat
|
||||
for cli_pat in "${cli_excludes[@]}"; do
|
||||
rsync_cmd+=("--exclude=$cli_pat")
|
||||
done
|
||||
fi
|
||||
|
||||
if ! "${rsync_cmd[@]}" "$app_dir/" "$run_dir/app/"; then
|
||||
cleanup_failed_start "$run_dir" "$state_file"
|
||||
die "rsync failed while copying $app_dir"
|
||||
fi
|
||||
|
||||
docker_cmd=(docker run -d --name "$container"
|
||||
--network none
|
||||
--read-only
|
||||
-v "$run_dir:/scratch"
|
||||
--tmpfs '/tmp:rw,nosuid,size=512m'
|
||||
-e HOME=/scratch/home
|
||||
-e TMPDIR=/scratch/tmp
|
||||
-e XDG_CACHE_HOME=/scratch/cache
|
||||
--user "$(id -u):$(id -g)"
|
||||
--memory 4g
|
||||
--cpus 2
|
||||
--pids-limit 256
|
||||
--cap-drop ALL
|
||||
--security-opt no-new-privileges
|
||||
--init
|
||||
--ulimit nofile=1024:1024
|
||||
--workdir /scratch/app)
|
||||
|
||||
fsize_note=""
|
||||
if out=$("${docker_cmd[@]}" --ulimit fsize=104857600 "$image" sleep infinity 2>&1); then
|
||||
STATE_FSIZE=on
|
||||
fsize_note=on
|
||||
else
|
||||
case $out in
|
||||
*fsize*|*FSIZE*)
|
||||
printf '%s: Docker refused the fsize ulimit; starting without the file-size cap\n' "$PROG" >&2
|
||||
if out=$("${docker_cmd[@]}" "$image" sleep infinity 2>&1); then
|
||||
STATE_FSIZE=off
|
||||
fsize_note=off
|
||||
else
|
||||
cleanup_failed_start "$run_dir" "$state_file"
|
||||
die "docker run failed: $out"
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
cleanup_failed_start "$run_dir" "$state_file"
|
||||
die "docker run failed: $out"
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
mkdir -p "$STATE_ROOT" || {
|
||||
docker rm -f "$container" >/dev/null 2>&1 || true
|
||||
cleanup_failed_start "$run_dir" "$state_file"
|
||||
die "cannot create state directory $STATE_ROOT"
|
||||
}
|
||||
if ! {
|
||||
printf 'CONTAINER=%s\n' "$container"
|
||||
printf 'RUN_DIR=%s\n' "$run_dir"
|
||||
printf 'APP=%s\n' "$app_dir"
|
||||
printf 'IMAGE=%s\n' "$image"
|
||||
printf 'FSIZE=%s\n' "$STATE_FSIZE"
|
||||
} > "$state_file"; then
|
||||
docker rm -f "$container" >/dev/null 2>&1 || true
|
||||
cleanup_failed_start "$run_dir" "$state_file"
|
||||
die "cannot write state file $state_file"
|
||||
fi
|
||||
|
||||
printf 'container: %s\n' "$container"
|
||||
printf 'run dir: %s\n' "$run_dir"
|
||||
printf 'scratch: %s\n' "$run_dir (mounted at /scratch)"
|
||||
printf 'app copy: %s/app (mounted at /scratch/app)\n' "$run_dir"
|
||||
printf 'image: %s\n' "$image"
|
||||
if [ "$fsize_note" = off ]; then
|
||||
printf 'note: fsize ulimit refused by Docker; no file-size cap applied\n'
|
||||
fi
|
||||
}
|
||||
|
||||
cmd_exec() {
|
||||
local app_arg="" timeout_secs=$DEFAULT_TIMEOUT saw_sep=0
|
||||
local app_dir container
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--timeout)
|
||||
[ $# -ge 2 ] || die "--timeout needs a value"
|
||||
timeout_secs=$2
|
||||
shift 2
|
||||
;;
|
||||
--timeout=*)
|
||||
timeout_secs=${1#--timeout=}
|
||||
shift
|
||||
;;
|
||||
--)
|
||||
shift
|
||||
saw_sep=1
|
||||
break
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
-*)
|
||||
die "unknown option for exec: $1"
|
||||
;;
|
||||
*)
|
||||
[ -z "$app_arg" ] || die "unexpected argument for exec: $1"
|
||||
app_arg=$1
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ -n "$app_arg" ] || die "exec needs an app directory"
|
||||
[ "$saw_sep" = 1 ] || die "exec needs -- before the command"
|
||||
[ $# -gt 0 ] || die "exec needs a command after --"
|
||||
case $timeout_secs in
|
||||
''|*[!0-9]*) die "--timeout must be a positive integer number of seconds" ;;
|
||||
esac
|
||||
[ "$timeout_secs" -gt 0 ] || die "--timeout must be greater than zero"
|
||||
|
||||
need_docker
|
||||
app_dir=$(canonical_app "$app_arg")
|
||||
load_state "$app_dir" || die "no sandbox recorded for $app_dir; run '$PROG start $app_arg' first"
|
||||
container=$STATE_CONTAINER
|
||||
container_running "$container" || die "container $container is not running; run '$PROG stop $app_arg' and start again"
|
||||
|
||||
check_wall_clock_guard "$container"
|
||||
|
||||
docker exec --workdir /scratch/app "$container" timeout --signal=KILL "$timeout_secs" "$@"
|
||||
}
|
||||
|
||||
cmd_stop() {
|
||||
local app_arg="" keep=0 app_dir run_dir
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--keep)
|
||||
keep=1
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
-*)
|
||||
die "unknown option for stop: $1"
|
||||
;;
|
||||
*)
|
||||
[ -z "$app_arg" ] || die "unexpected argument for stop: $1"
|
||||
app_arg=$1
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ -n "$app_arg" ] || die "stop needs an app directory"
|
||||
app_dir=$(canonical_app "$app_arg")
|
||||
load_state "$app_dir" || die "no sandbox recorded for $app_dir"
|
||||
|
||||
run_dir=$STATE_RUN_DIR
|
||||
[ "$keep" = 1 ] || check_run_dir "$run_dir"
|
||||
docker rm -f "$STATE_CONTAINER" >/dev/null 2>&1 || true
|
||||
rm -f "$(state_file_for "$app_dir")"
|
||||
|
||||
if [ "$keep" = 1 ]; then
|
||||
printf 'removed container %s; kept run dir %s\n' "$STATE_CONTAINER" "$run_dir"
|
||||
else
|
||||
rm_run_dir "$run_dir"
|
||||
printf 'removed container %s and run dir %s\n' "$STATE_CONTAINER" "$run_dir"
|
||||
fi
|
||||
}
|
||||
|
||||
cmd_status() {
|
||||
local app_arg="" app_dir running
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
-*)
|
||||
die "unknown option for status: $1"
|
||||
;;
|
||||
*)
|
||||
[ -z "$app_arg" ] || die "unexpected argument for status: $1"
|
||||
app_arg=$1
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ -n "$app_arg" ] || die "status needs an app directory"
|
||||
app_dir=$(canonical_app "$app_arg")
|
||||
load_state "$app_dir" || die "no sandbox recorded for $app_dir"
|
||||
|
||||
if container_running "$STATE_CONTAINER"; then
|
||||
running=running
|
||||
elif container_exists "$STATE_CONTAINER"; then
|
||||
running=stopped
|
||||
else
|
||||
running=missing
|
||||
fi
|
||||
|
||||
printf 'container: %s\n' "$STATE_CONTAINER"
|
||||
printf 'run dir: %s\n' "$STATE_RUN_DIR"
|
||||
printf 'app: %s\n' "$STATE_APP"
|
||||
printf 'image: %s\n' "$STATE_IMAGE"
|
||||
printf 'fsize cap: %s\n' "$STATE_FSIZE"
|
||||
printf 'state: %s\n' "$running"
|
||||
}
|
||||
|
||||
main() {
|
||||
[ $# -gt 0 ] || {
|
||||
usage >&2
|
||||
exit 1
|
||||
}
|
||||
local cmd=$1
|
||||
shift
|
||||
case $cmd in
|
||||
start) cmd_start "$@" ;;
|
||||
exec) cmd_exec "$@" ;;
|
||||
stop) cmd_stop "$@" ;;
|
||||
status) cmd_status "$@" ;;
|
||||
-h|--help|help) usage ;;
|
||||
*)
|
||||
die "unknown command: $cmd (try --help)"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+339
@@ -0,0 +1,339 @@
|
||||
#!/usr/bin/env bash
|
||||
# ============================================================================
|
||||
# yt-transcribe — repeatable YouTube/X transcription
|
||||
#
|
||||
# Strategy: captions first (exact text, fast); Whisper fallback ONLY when no
|
||||
# captions exist, reusing the OpenSuperWhisper model already on this Mac.
|
||||
# Accepts a URL (YouTube, X/Twitter, anything yt-dlp supports) OR a local
|
||||
# media file (skips straight to Whisper; used by the watcher for reclip
|
||||
# downloads).
|
||||
#
|
||||
# Usage:
|
||||
# yt-transcribe <url-or-file> # transcript → media/transcripts/<id>/ (URL)
|
||||
# # or <file>.txt sidecar (file)
|
||||
# yt-transcribe <url> --lang de # prefer German captions
|
||||
# yt-transcribe <url> --srt # also produce an .srt (whisper path)
|
||||
# yt-transcribe <url> --force # redo even if transcript exists
|
||||
#
|
||||
# X/Twitter: X has no public captions and now requires auth for most video
|
||||
# extraction, so URLs on x.com/twitter.com go through gallery-dl (set
|
||||
# YT_COOKIES=/path/to/cookies.txt for locked/NSFW/older tweets; exported
|
||||
# cookies.txt format from a browser extension works for both yt-dlp and
|
||||
# gallery-dl).
|
||||
#
|
||||
# Outputs (URL mode) in <share>/media/transcripts/<id>/:
|
||||
# <id>.txt plain transcript (always)
|
||||
# <id>.vtt raw captions (captions path)
|
||||
# <id>.srt subtitles (whisper path, with --srt)
|
||||
# <id>.metadata.json provenance: title, channel, source, date
|
||||
#
|
||||
# Dependencies (declared in dotfiles configuration.nix homebrew.brews):
|
||||
# yt-dlp, gallery-dl (X only), whisper-cli (whisper-cpp), ffmpeg (fallback only)
|
||||
# Whisper model: auto-detected from OpenSuperWhisper's model store,
|
||||
# or WHISPER_MODEL=/path/to/ggml-*.bin, or --model.
|
||||
# Env overrides: YT_SHARE_ROOT (data share mount, default /Volumes/data),
|
||||
# YT_TRANSCRIBE_ROOT (transcript root), YT_MEDIA_DIR (reclip download dir),
|
||||
# YT_COOKIES (cookies.txt for yt-dlp/gallery-dl).
|
||||
# Index: `yt-transcribe --list` prints id->title mapping; --index rewrites
|
||||
# INDEX.md next to the transcripts; both modes refresh it after each run.
|
||||
# ============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
# --- locate the data share ---------------------------------------------------
|
||||
# The tool lives in this repo (installed into the nix store by the dotfiles
|
||||
# rebuild; stable symlink at ~/.local/bin/yt-transcribe). The Unraid share
|
||||
# holds only data — media and transcripts.
|
||||
SHARE_ROOT="${YT_SHARE_ROOT:-/Volumes/data}"
|
||||
OUT_ROOT="${YT_TRANSCRIBE_ROOT:-$SHARE_ROOT/media/transcripts}"
|
||||
|
||||
# --- PATH: cover Homebrew on Apple Silicon / Intel (launchd PATH too) ------
|
||||
for p in /opt/homebrew/bin /usr/local/bin; do
|
||||
[ -d "$p" ] && [[ ":$PATH:" != *":$p:"* ]] && PATH="$p:$PATH"
|
||||
done
|
||||
|
||||
LANG_PREF="en"
|
||||
KEEP_SRT=false
|
||||
FORCE=false
|
||||
DO_INDEX=false
|
||||
DO_LIST=false
|
||||
WHISPER_MODEL_ARG=""
|
||||
INPUT=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--lang) LANG_PREF="$2"; shift 2 ;;
|
||||
--srt) KEEP_SRT=true; shift ;;
|
||||
--force) FORCE=true; shift ;;
|
||||
--model) WHISPER_MODEL_ARG="$2"; shift 2 ;;
|
||||
--index) DO_INDEX=true; shift ;;
|
||||
--list) DO_LIST=true; shift ;;
|
||||
-h|--help) grep '^# ' "$0" | sed 's/^# //'; exit 0 ;;
|
||||
*) INPUT="$1"; shift ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$INPUT" ] || $DO_INDEX || $DO_LIST || { echo "usage: yt-transcribe <url-or-file> [--lang L] [--srt] [--force] [--model ggml.bin] [--index|--list]" >&2; exit 1; }
|
||||
|
||||
# --- transcript index (INDEX.md / --list) -----------------------------------
|
||||
rebuild_index() {
|
||||
python3 - "$OUT_ROOT" "${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" <<'PY'
|
||||
import json, os, sys, time
|
||||
out_root, scan_dir = sys.argv[1], sys.argv[2]
|
||||
rows = []
|
||||
for dirpath, _, files in os.walk(out_root):
|
||||
for fn in files:
|
||||
if fn.endswith(".metadata.json"):
|
||||
try:
|
||||
d = json.load(open(os.path.join(dirpath, fn), encoding="utf-8"))
|
||||
except Exception:
|
||||
continue
|
||||
rows.append((d.get("transcribed_at") or "", d))
|
||||
rows.sort(key=lambda r: r[0], reverse=True)
|
||||
clean = lambda s: (s or "").replace("|", "/").replace("`", "/")
|
||||
L = ["# Transcript Index", "",
|
||||
"URL transcripts live in `media/transcripts/<id>/` — the `<id>.txt` is the",
|
||||
"transcript, `<id>.metadata.json` has full provenance. Local files keep their",
|
||||
"`.txt` sidecar next to the media file.", "",
|
||||
"## URL transcripts", "", "| transcribed | id | title | channel | source |", "|---|---|---|---|---|"]
|
||||
for ts, d in rows:
|
||||
L.append(f'| {ts} | `{clean(d.get("id"))}` | {clean(d.get("title"))} | {clean(d.get("channel"))} | {clean(d.get("source"))} |')
|
||||
L += ["", "## Local media files (sidecar .txt in media/video)", "", "| file | modified |", "|---|---|"]
|
||||
found = False
|
||||
for dirpath, dirs, files in os.walk(scan_dir):
|
||||
dirs[:] = [d for d in dirs if not d.startswith(".")]
|
||||
for fn in sorted(files):
|
||||
if fn.endswith(".txt"):
|
||||
found = True
|
||||
p = os.path.join(dirpath, fn)
|
||||
mt = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(p)))
|
||||
L.append(f"| `{clean(fn)}` | {mt} |")
|
||||
if not found:
|
||||
L.append("| _(none yet — patched reclip or manual file-mode runs add one per download)_ | |")
|
||||
print("\n".join(L))
|
||||
PY
|
||||
}
|
||||
if $DO_INDEX || $DO_LIST; then
|
||||
mkdir -p "$OUT_ROOT"
|
||||
if $DO_LIST; then
|
||||
rebuild_index
|
||||
else
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md"
|
||||
echo "== index rebuilt: $OUT_ROOT/INDEX.md"
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
need() { command -v "$1" >/dev/null || { echo "MISSING DEP: $1 — install it first" >&2; exit 2; }; }
|
||||
|
||||
DL_ARGS=()
|
||||
[ -n "${YT_COOKIES:-}" ] && DL_ARGS=(--cookies "$YT_COOKIES")
|
||||
|
||||
resolve_model() {
|
||||
local MODEL="${WHISPER_MODEL_ARG:-${WHISPER_MODEL:-}}"
|
||||
if [ -z "$MODEL" ]; then
|
||||
MODEL="$(find "$HOME/Library/Application Support/ru.starmel.OpenSuperWhisper/whisper-models" \
|
||||
-name 'ggml-*.bin' 2>/dev/null | head -1 || true)"
|
||||
fi
|
||||
printf '%s' "$MODEL"
|
||||
}
|
||||
|
||||
# whisper_transcribe <wav> <out-stem> — writes <out-stem>.txt (and .srt w/ --srt)
|
||||
whisper_transcribe() {
|
||||
local WAV="$1" STEM="$2" MODEL
|
||||
MODEL="$(resolve_model)"
|
||||
[ -n "$MODEL" ] && [ -f "$MODEL" ] || {
|
||||
echo "ERROR: no whisper model. Download one (e.g. ggml-large-v3-turbo.bin from huggingface.co/ggerganov/whisper.cpp)" >&2
|
||||
echo " and pass --model or set WHISPER_MODEL." >&2; exit 4; }
|
||||
echo ">> model: $MODEL"
|
||||
local WARGS=(-m "$MODEL" -f "$WAV" -of "$STEM" -otxt)
|
||||
$KEEP_SRT && WARGS+=(-osrt)
|
||||
echo ">> transcribing with whisper-cli (this is the slow part)..."
|
||||
whisper-cli "${WARGS[@]}" 2>>"$(dirname "$STEM")/whisper.log"
|
||||
[ -s "$STEM.txt" ] || { echo "ERROR: whisper produced no text" >&2; exit 6; }
|
||||
}
|
||||
|
||||
TMPD="$(mktemp -d)"
|
||||
cleanup() { rm -rf "$TMPD"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
SOURCE=""
|
||||
SOURCE_PREFIX=""
|
||||
if [ -f "$INPUT" ]; then
|
||||
# ==========================================================================
|
||||
# FILE MODE — local media (reclip download, screen recording, anything)
|
||||
# ==========================================================================
|
||||
need ffmpeg; need whisper-cli
|
||||
SRC_FILE="$INPUT"
|
||||
STEM="$(basename "$SRC_FILE")"
|
||||
STEM="${STEM%.*}"
|
||||
OUT_DIR="$(cd "$(dirname "$SRC_FILE")" && pwd)"
|
||||
TXT="$OUT_DIR/$STEM.txt"
|
||||
if [ -s "$TXT" ] && ! $FORCE; then
|
||||
echo "== already transcribed: $TXT (use --force to redo)"
|
||||
exit 0
|
||||
fi
|
||||
echo ">> file mode: $SRC_FILE"
|
||||
echo ">> converting to 16 kHz mono wav..."
|
||||
ffmpeg -y -loglevel error -i "$SRC_FILE" -ac 1 -ar 16000 "$TMPD/in.wav"
|
||||
whisper_transcribe "$TMPD/in.wav" "$OUT_DIR/$STEM"
|
||||
SOURCE="whisper-local"
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
|
||||
echo "== done: $TXT (source: $SOURCE)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ==========================================================================
|
||||
# URL MODE
|
||||
# ==========================================================================
|
||||
need yt-dlp
|
||||
URL="$INPUT"
|
||||
IS_X=false
|
||||
case "$URL" in
|
||||
*x.com/*|*twitter.com/*|*//t.co/*) IS_X=true ;;
|
||||
esac
|
||||
|
||||
# --- metadata (yt-dlp; gallery-dl for X when yt-dlp can't) -------------------
|
||||
VIDEO_ID=""; TITLE=""; CHANNEL=""
|
||||
if META="$(yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--print "id=%(id)s" --print "title=%(title)s" --print "channel=%(channel|uploader)s" "$URL" 2>/dev/null)"; then
|
||||
VIDEO_ID="$(printf '%s\n' "$META" | sed -n 's/^id=//p')"
|
||||
TITLE="$(printf '%s\n' "$META" | sed -n 's/^title=//p')"
|
||||
CHANNEL="$(printf '%s\n' "$META" | sed -n 's/^channel=//p')"
|
||||
fi
|
||||
|
||||
if $IS_X && [ -z "$VIDEO_ID" ]; then
|
||||
# X/Twitter via gallery-dl
|
||||
need gallery-dl
|
||||
echo ">> X URL — resolving via gallery-dl: $URL"
|
||||
VIDEO_ID="$(printf '%s' "$URL" | grep -oE 'status(es)?/[0-9]+' | grep -oE '[0-9]+' | head -1 || true)"
|
||||
if [ -z "$VIDEO_ID" ] && GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1)"; then
|
||||
VIDEO_ID="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tweet_id',''))" 2>/dev/null || true)"
|
||||
TITLE="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print((d.get('content') or '')[:200])" 2>/dev/null || true)"
|
||||
CHANNEL="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); a=d.get('author') or {}; print(a.get('nick') or a.get('name') or '')" 2>/dev/null || true)"
|
||||
fi
|
||||
[ -n "$VIDEO_ID" ] || { echo "ERROR: could not resolve a tweet id from: $URL" >&2; exit 3; }
|
||||
fi
|
||||
# Fill X title/channel from gallery-dl metadata when yt-dlp gave none
|
||||
if $IS_X && { [ -z "$TITLE" ] || [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; } && command -v gallery-dl >/dev/null; then
|
||||
GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1 || true)"
|
||||
if [ -n "$GJ" ]; then
|
||||
XMETA="$(printf '%s' "$GJ" | python3 -c '
|
||||
import json, sys
|
||||
def walk(o):
|
||||
if isinstance(o, dict):
|
||||
if "author" in o or "tweet_id" in o:
|
||||
yield o
|
||||
for v in o.values(): yield from walk(v)
|
||||
elif isinstance(o, list):
|
||||
for v in o: yield from walk(v)
|
||||
items = list(walk(json.load(sys.stdin)))
|
||||
d = items[-1] if items else {}
|
||||
a = d.get("author") or {}
|
||||
print(d.get("tweet_id") or "")
|
||||
print((d.get("content") or "").replace("\n", " ")[:200])
|
||||
print(a.get("nick") or a.get("name") or "")
|
||||
' 2>/dev/null || true)"
|
||||
if [ -n "$XMETA" ]; then
|
||||
[ -z "$VIDEO_ID" ] && VIDEO_ID="$(printf '%s\n' "$XMETA" | sed -n '1p')"
|
||||
[ -z "$TITLE" ] && TITLE="$(printf '%s\n' "$XMETA" | sed -n '2p')"
|
||||
if [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; then
|
||||
CHANNEL="$(printf '%s\n' "$XMETA" | sed -n '3p')"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
TITLE="${TITLE:-x.com post}"
|
||||
CHANNEL="${CHANNEL:-x.com}"
|
||||
OUT_DIR="$OUT_ROOT/$VIDEO_ID"
|
||||
mkdir -p "$OUT_DIR"
|
||||
TXT="$OUT_DIR/$VIDEO_ID.txt"
|
||||
else
|
||||
[ -n "$VIDEO_ID" ] || { echo "ERROR: yt-dlp could not resolve the URL (private, geo-blocked, or unsupported?)" >&2; exit 3; }
|
||||
OUT_DIR="$OUT_ROOT/$VIDEO_ID"
|
||||
mkdir -p "$OUT_DIR"
|
||||
TXT="$OUT_DIR/$VIDEO_ID.txt"
|
||||
fi
|
||||
|
||||
if [ -s "$TXT" ] && ! $FORCE; then
|
||||
echo "== already transcribed: $TXT (use --force to redo)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# --- path 1: captions -------------------------------------------------------
|
||||
echo ">> trying captions ($LANG_PREF)..."
|
||||
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--write-subs --write-auto-subs \
|
||||
--sub-langs "$LANG_PREF" --sub-format "vtt" \
|
||||
-o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
|
||||
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF.vtt" | head -1)"
|
||||
if [ -z "$VTT" ]; then
|
||||
# exact code missing (e.g. video tagged en-US only) — broaden once, keep best, delete the rest
|
||||
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--write-subs --write-auto-subs \
|
||||
--sub-langs "$LANG_PREF.*" --sub-format "vtt" \
|
||||
-o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
|
||||
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF-*.vtt" | sort | head -1)"
|
||||
find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.*.vtt" ! -path "$VTT" -delete 2>/dev/null || true
|
||||
fi
|
||||
if [ -n "$VTT" ]; then
|
||||
echo ">> captions found: $(basename "$VTT") -> converting"
|
||||
python3 - "$VTT" "$TXT" <<'PY'
|
||||
import re, sys
|
||||
src, dst = sys.argv[1], sys.argv[2]
|
||||
out, prev = [], None
|
||||
for raw in open(src, encoding="utf-8", errors="replace"):
|
||||
line = raw.strip()
|
||||
if (not line or "-->" in line or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
|
||||
or re.match(r"^\d+$", line)):
|
||||
continue
|
||||
line = re.sub(r"<[^>]+>", "", line) # strip inline tags
|
||||
if line and line != prev:
|
||||
out.append(line); prev = line
|
||||
text = " ".join(out)
|
||||
open(dst, "w", encoding="utf-8").write(text + "\n")
|
||||
print(f" {len(text.split())} words")
|
||||
PY
|
||||
if $IS_X; then SOURCE="x-captions"; else SOURCE="youtube-captions"; fi
|
||||
else
|
||||
# --- path 2: Whisper fallback --------------------------------------------
|
||||
echo ">> no captions — falling back to Whisper"
|
||||
need ffmpeg; need whisper-cli
|
||||
MEDIA_DIR="${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" # e.g. reclip's downloads on the share
|
||||
echo ">> checking $MEDIA_DIR for an existing download..."
|
||||
LOCAL_MEDIA="$(find "$MEDIA_DIR" -maxdepth 4 -iname "*$VIDEO_ID*" \
|
||||
\( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.webm' -o -iname '*.m4a' \
|
||||
-o -iname '*.mp3' -o -iname '*.flac' -o -iname '*.mov' -o -iname '*.avi' -o -iname '*.wav' \) \
|
||||
2>/dev/null | head -1 || true)"
|
||||
WAV="$TMPD/in.wav"
|
||||
if [ -n "$LOCAL_MEDIA" ]; then
|
||||
echo ">> reusing existing file: $LOCAL_MEDIA"
|
||||
ffmpeg -y -loglevel error -i "$LOCAL_MEDIA" -ac 1 -ar 16000 "$WAV"
|
||||
elif $IS_X && command -v gallery-dl >/dev/null; then
|
||||
echo ">> downloading X media via gallery-dl..."
|
||||
gallery-dl "${DL_ARGS[@]}" \
|
||||
--filter "extension not in ('jpg','jpeg','png','webp','gif')" \
|
||||
-o "filename={tweet_id}.{extension}" \
|
||||
-D "$TMPD" "$URL"
|
||||
XMEDIA="$(find "$TMPD" -maxdepth 1 -type f \( -iname '*.mp4' -o -iname '*.m4a' -o -iname '*.mov' -o -iname '*.webm' \) | sort | tail -1)"
|
||||
[ -n "$XMEDIA" ] || { echo "ERROR: gallery-dl found no video (private tweet? set YT_COOKIES=/path/to/cookies.txt)" >&2; exit 5; }
|
||||
ffmpeg -y -loglevel error -i "$XMEDIA" -ac 1 -ar 16000 "$WAV"
|
||||
SOURCE_PREFIX="gallery-dl"
|
||||
else
|
||||
echo ">> not found — downloading audio (16 kHz mono)..."
|
||||
yt-dlp --no-playlist --no-warnings "${DL_ARGS[@]}" -x --audio-format wav \
|
||||
--postprocessor-args "ffmpeg:-ac 1 -ar 16000" \
|
||||
-o "$TMPD/%(id)s.%(ext)s" "$URL"
|
||||
fi
|
||||
[ -f "$WAV" ] || { echo "ERROR: audio acquisition failed" >&2; exit 5; }
|
||||
whisper_transcribe "$WAV" "$OUT_DIR/$VIDEO_ID"
|
||||
SOURCE="${SOURCE_PREFIX:+$SOURCE_PREFIX+}whisper-local"
|
||||
fi
|
||||
|
||||
# --- provenance --------------------------------------------------------------
|
||||
TRANSCRIBED_AT="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
|
||||
python3 - "$VIDEO_ID" "$TITLE" "$CHANNEL" "$URL" "$SOURCE" "$LANG_PREF" "$TRANSCRIBED_AT" \
|
||||
> "$OUT_DIR/$VIDEO_ID.metadata.json" <<'PY'
|
||||
import json, sys
|
||||
keys = ["id", "title", "channel", "url", "source", "lang_pref", "transcribed_at"]
|
||||
print(json.dumps(dict(zip(keys, sys.argv[1:])), indent=2, ensure_ascii=False))
|
||||
PY
|
||||
|
||||
echo "== done: $TXT (source: $SOURCE)"
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
|
||||
@@ -0,0 +1,44 @@
|
||||
# Patched reclip — source of truth
|
||||
|
||||
Our transcription + history additions to [averygan/reclip](https://github.com/averygan/reclip),
|
||||
kept here so container updates and new machines can't lose them.
|
||||
|
||||
- `app.py`, `index.html` — the full patched files (deployed via bind-mounts
|
||||
from `documents/reclip/` on the Unraid share; see that dir's DEPLOY.md)
|
||||
- `reclip-transcript.patch` — the same delta as a diff against upstream,
|
||||
for rebasing onto future upstream versions
|
||||
|
||||
Patch base: upstream `1d161d1` (cloned 2026-10-25).
|
||||
|
||||
## What the patch adds
|
||||
|
||||
1. `fetch_transcript()` — after each download, pull yt-dlp captions
|
||||
(YouTube subs; X auto-captions) → `<stem>.txt` sidecar, never fails the job
|
||||
2. `/api/transcript/<job_id>` + Transcript button + auto-save in the UI
|
||||
3. Persisted download history (`history.json` in the downloads volume) +
|
||||
`/api/history` + History section with a live transcript-available flag
|
||||
(manual `yt-transcribe` sidecars are detected at read time)
|
||||
4. `/api/file` + `/api/transcript` fall back to history, so old links
|
||||
survive restarts
|
||||
|
||||
## Updating reclip (when upstream changes)
|
||||
|
||||
git clone --depth 1 https://github.com/averygan/reclip.git /tmp/reclip-new
|
||||
cd /tmp/reclip-new
|
||||
git apply --3way ~/Documents/dotfiles/patches/reclip/reclip-transcript.patch
|
||||
|
||||
Resolve any conflicts (the additions are mostly self-contained: one new
|
||||
function, two routes, one status field, UI button + History section), then
|
||||
copy the updated `app.py` + `templates/index.html`:
|
||||
|
||||
- into this directory (commit — new source of truth)
|
||||
- to the share: `/Volumes/data/documents/reclip/{app.py,index.html}`
|
||||
- restart the reclip container (gunicorn reloads at start; the entrypoint
|
||||
also pip-updates yt-dlp at every container start)
|
||||
|
||||
If `git apply` fails on a drifted file, the fastest path is re-porting by
|
||||
hand from the conflict markers — the four additions are small and greppable
|
||||
(`fetch_transcript`, `history.json`, `resolve_download`, `saveTranscript`).
|
||||
|
||||
If an image update happens WITHOUT re-porting: the old patched files keep
|
||||
working (bind-mounts win), you just may miss upstream improvements.
|
||||
@@ -0,0 +1,403 @@
|
||||
import os
|
||||
import uuid
|
||||
import glob
|
||||
import json
|
||||
import re
|
||||
import hashlib
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from flask import Flask, request, jsonify, send_file, render_template
|
||||
|
||||
app = Flask(__name__)
|
||||
DOWNLOAD_DIR = os.path.join(os.path.dirname(__file__), "downloads")
|
||||
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
||||
|
||||
jobs = {}
|
||||
|
||||
HISTORY_FILE = os.path.join(DOWNLOAD_DIR, "history.json")
|
||||
_history_lock = threading.Lock()
|
||||
|
||||
|
||||
def load_history():
|
||||
try:
|
||||
with open(HISTORY_FILE, encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def save_history(history):
|
||||
try:
|
||||
tmp = HISTORY_FILE + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as fh:
|
||||
json.dump(history, fh, indent=2)
|
||||
os.replace(tmp, HISTORY_FILE)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def sidecar_transcript(file_path):
|
||||
"""Manual-fallback transcripts (yt-transcribe <file>) live beside the
|
||||
media as <stem>.txt — recognize them at read time so history stays
|
||||
truthful without re-downloading anything."""
|
||||
if not file_path:
|
||||
return None
|
||||
stem = os.path.splitext(file_path)[0] + ".txt"
|
||||
return stem if os.path.exists(stem) else None
|
||||
|
||||
|
||||
def record_history(job):
|
||||
"""Persist the completed job so history + file/transcript downloads
|
||||
survive process restarts (downloads dir is the mapped volume)."""
|
||||
with _history_lock:
|
||||
history = [h for h in load_history() if h.get("job_id") != job.get("job_id")]
|
||||
history.insert(0, {
|
||||
"job_id": job.get("job_id"),
|
||||
"url": job.get("url", ""),
|
||||
"title": job.get("title", ""),
|
||||
"thumbnail": job.get("thumbnail", ""),
|
||||
"filename": job.get("filename", ""),
|
||||
"file": job.get("file", ""),
|
||||
"transcript": job.get("transcript") or "",
|
||||
"transcript_name": job.get("transcript_name", ""),
|
||||
"has_transcript": bool(job.get("transcript")),
|
||||
"size": os.path.getsize(job["file"]) if job.get("file") and os.path.exists(job["file"]) else 0,
|
||||
"date": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
})
|
||||
save_history(history[:200])
|
||||
|
||||
|
||||
MEDIA_EXTS = (".mp4", ".mkv", ".webm", ".m4a", ".mp3", ".flac", ".mov", ".avi", ".wav", ".ts")
|
||||
|
||||
|
||||
def backfill_history():
|
||||
"""Add on-disk downloads that predate history.json (or were dropped into
|
||||
the downloads dir manually) so the whole library shows up on the page.
|
||||
The transcript flag is resolved live at read time, so backfilled entries
|
||||
pick up manual yt-transcribe sidecars automatically."""
|
||||
for name in sorted(os.listdir(DOWNLOAD_DIR)):
|
||||
path = os.path.join(DOWNLOAD_DIR, name)
|
||||
if not os.path.isfile(path) or not name.lower().endswith(MEDIA_EXTS):
|
||||
continue
|
||||
with _history_lock:
|
||||
history = load_history()
|
||||
if any(h.get("file") == path for h in history):
|
||||
continue
|
||||
stem = os.path.splitext(name)[0]
|
||||
# a 10-hex stem is a reclip job id — the real title wasn't kept
|
||||
title = "" if re.fullmatch(r"[0-9a-f]{10}", stem) else stem
|
||||
history.insert(0, {
|
||||
"job_id": hashlib.sha1(path.encode()).hexdigest()[:10],
|
||||
"url": "",
|
||||
"title": title,
|
||||
"filename": name,
|
||||
"file": path,
|
||||
"transcript": "",
|
||||
"transcript_name": "",
|
||||
"has_transcript": False,
|
||||
"size": os.path.getsize(path),
|
||||
"date": time.strftime("%Y-%m-%d %H:%M:%S",
|
||||
time.localtime(os.path.getmtime(path))),
|
||||
})
|
||||
save_history(history[:200])
|
||||
|
||||
|
||||
backfill_history()
|
||||
|
||||
|
||||
def parse_ytdlp_json(stdout):
|
||||
"""Parse yt-dlp JSON output.
|
||||
|
||||
With ``-j`` yt-dlp prints one JSON object per line. Some extractors
|
||||
emit multiple videos even with ``--no-playlist``, so stdout contains
|
||||
several objects and a plain ``json.loads`` raises "Extra data".
|
||||
Return the first valid object.
|
||||
"""
|
||||
for line in stdout.splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
return json.loads(line)
|
||||
raise ValueError("yt-dlp returned no data")
|
||||
|
||||
|
||||
def fetch_transcript(url, chosen_path):
|
||||
"""Best-effort transcript via yt-dlp captions (manual or auto-generated;
|
||||
includes X's auto-captions). Writes <video stem>.txt beside the download.
|
||||
Returns the .txt path, or None when the video has no captions. Never
|
||||
raises — a transcript is a bonus, not a download requirement."""
|
||||
stem = os.path.splitext(chosen_path)[0]
|
||||
try:
|
||||
cmd = ["yt-dlp", "--no-playlist", "--skip-download", "--no-warnings",
|
||||
"--write-subs", "--write-auto-subs",
|
||||
"--sub-langs", "en,en-orig",
|
||||
"--sub-format", "vtt",
|
||||
"-o", stem + ".%(ext)s", url]
|
||||
subprocess.run(cmd, capture_output=True, text=True, timeout=180)
|
||||
|
||||
vtts = glob.glob(stem + ".*.vtt")
|
||||
if not vtts:
|
||||
return None
|
||||
vtts.sort(key=lambda p: (0 if p.endswith(".en.vtt") else 1, p))
|
||||
|
||||
lines, prev = [], None
|
||||
with open(vtts[0], encoding="utf-8", errors="replace") as fh:
|
||||
for raw in fh:
|
||||
line = raw.strip()
|
||||
if (not line or "-->" in line
|
||||
or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
|
||||
or re.match(r"^\d+$", line)):
|
||||
continue
|
||||
line = re.sub(r"<[^>]+>", "", line)
|
||||
if line and line != prev:
|
||||
lines.append(line)
|
||||
prev = line
|
||||
|
||||
txt = stem + ".txt"
|
||||
with open(txt, "w", encoding="utf-8") as out:
|
||||
out.write(" ".join(lines) + "\n")
|
||||
|
||||
for f in vtts:
|
||||
try:
|
||||
os.remove(f)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return txt if lines else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def run_download(job_id, url, format_choice, format_id):
|
||||
job = jobs[job_id]
|
||||
out_template = os.path.join(DOWNLOAD_DIR, f"{job_id}.%(ext)s")
|
||||
|
||||
cmd = ["yt-dlp", "--no-playlist", "-o", out_template]
|
||||
|
||||
if format_choice == "audio":
|
||||
cmd += ["-x", "--audio-format", "mp3"]
|
||||
elif format_id:
|
||||
cmd += ["-f", f"{format_id}+bestaudio/best", "--merge-output-format", "mp4"]
|
||||
else:
|
||||
cmd += ["-f", "bestvideo+bestaudio/best", "--merge-output-format", "mp4"]
|
||||
|
||||
cmd.append(url)
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
if result.returncode != 0:
|
||||
job["status"] = "error"
|
||||
job["error"] = result.stderr.strip().split("\n")[-1]
|
||||
return
|
||||
|
||||
files = glob.glob(os.path.join(DOWNLOAD_DIR, f"{job_id}.*"))
|
||||
if not files:
|
||||
job["status"] = "error"
|
||||
job["error"] = "Download completed but no file was found"
|
||||
return
|
||||
|
||||
if format_choice == "audio":
|
||||
target = [f for f in files if f.endswith(".mp3")]
|
||||
chosen = target[0] if target else files[0]
|
||||
else:
|
||||
target = [f for f in files if f.endswith(".mp4")]
|
||||
chosen = target[0] if target else files[0]
|
||||
|
||||
for f in files:
|
||||
if f != chosen:
|
||||
try:
|
||||
os.remove(f)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
job["status"] = "done"
|
||||
job["file"] = chosen
|
||||
ext = os.path.splitext(chosen)[1]
|
||||
title = job.get("title", "").strip()
|
||||
# Sanitize title for filename
|
||||
if title:
|
||||
safe_title = "".join(c for c in title if c not in r'\/:*?"<>|').strip()[:100].strip()
|
||||
job["filename"] = f"{safe_title}{ext}" if safe_title else os.path.basename(chosen)
|
||||
else:
|
||||
job["filename"] = os.path.basename(chosen)
|
||||
|
||||
# Best-effort transcript sidecar: yt-dlp captions (X auto-captions
|
||||
# included) -> plain .txt next to the chosen file. Never fails the job.
|
||||
job["transcript"] = fetch_transcript(url, chosen)
|
||||
job["transcript_name"] = os.path.splitext(job["filename"])[0] + ".txt"
|
||||
record_history(job)
|
||||
except subprocess.TimeoutExpired:
|
||||
job["status"] = "error"
|
||||
job["error"] = "Download timed out (5 min limit)"
|
||||
except Exception as e:
|
||||
job["status"] = "error"
|
||||
job["error"] = str(e)
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
@app.route("/api/info", methods=["POST"])
|
||||
def get_info():
|
||||
data = request.json
|
||||
url = data.get("url", "").strip()
|
||||
if not url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
cmd = ["yt-dlp", "--no-playlist", "-j", url]
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
|
||||
if result.returncode != 0:
|
||||
return jsonify({"error": result.stderr.strip().split("\n")[-1]}), 400
|
||||
|
||||
info = parse_ytdlp_json(result.stdout)
|
||||
|
||||
# Build quality options — keep best format per resolution
|
||||
best_by_height = {}
|
||||
for f in info.get("formats", []):
|
||||
height = f.get("height")
|
||||
if height and f.get("vcodec", "none") != "none":
|
||||
tbr = f.get("tbr") or 0
|
||||
if height not in best_by_height or tbr > (best_by_height[height].get("tbr") or 0):
|
||||
best_by_height[height] = f
|
||||
|
||||
formats = []
|
||||
for height, f in best_by_height.items():
|
||||
formats.append({
|
||||
"id": f["format_id"],
|
||||
"label": f"{height}p",
|
||||
"height": height,
|
||||
})
|
||||
formats.sort(key=lambda x: x["height"], reverse=True)
|
||||
|
||||
return jsonify({
|
||||
"title": info.get("title", ""),
|
||||
"thumbnail": info.get("thumbnail", ""),
|
||||
"duration": info.get("duration"),
|
||||
"uploader": info.get("uploader", ""),
|
||||
"formats": formats,
|
||||
})
|
||||
except subprocess.TimeoutExpired:
|
||||
return jsonify({"error": "Timed out fetching video info"}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
|
||||
@app.route("/api/playlist", methods=["POST"])
|
||||
def get_playlist_info():
|
||||
data = request.json
|
||||
url = data.get("url", "").strip()
|
||||
if not url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
cmd = ["yt-dlp", "--flat-playlist", "-J", url]
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
|
||||
if result.returncode != 0:
|
||||
return jsonify({"error": result.stderr.strip().split("\n")[-1]}), 400
|
||||
|
||||
info = json.loads(result.stdout)
|
||||
entries = info.get("entries", [])
|
||||
urls = [entry.get("url") for entry in entries if entry.get("url")]
|
||||
return jsonify({"urls": urls})
|
||||
except subprocess.TimeoutExpired:
|
||||
return jsonify({"error": "Timed out fetching playlist info"}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
|
||||
@app.route("/api/download", methods=["POST"])
|
||||
def start_download():
|
||||
data = request.json
|
||||
url = data.get("url", "").strip()
|
||||
format_choice = data.get("format", "video")
|
||||
format_id = data.get("format_id")
|
||||
title = data.get("title", "")
|
||||
|
||||
if not url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
job_id = uuid.uuid4().hex[:10]
|
||||
jobs[job_id] = {"job_id": job_id, "status": "downloading", "url": url, "title": title,
|
||||
"thumbnail": (data.get("thumbnail") or "")[:500]}
|
||||
|
||||
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return jsonify({"job_id": job_id})
|
||||
|
||||
|
||||
def resolve_download(job_id, key):
|
||||
"""Find a completed job in memory, falling back to the on-disk history
|
||||
(paths point into DOWNLOAD_DIR, so they survive restarts)."""
|
||||
job = jobs.get(job_id)
|
||||
if job and job.get("status") == "done" and job.get(key):
|
||||
return job
|
||||
for entry in load_history():
|
||||
if entry.get("job_id") == job_id and entry.get(key):
|
||||
return entry
|
||||
return None
|
||||
|
||||
|
||||
@app.route("/api/status/<job_id>")
|
||||
def check_status(job_id):
|
||||
job = jobs.get(job_id)
|
||||
if not job:
|
||||
return jsonify({"error": "Job not found"}), 404
|
||||
return jsonify({
|
||||
"status": job["status"],
|
||||
"error": job.get("error"),
|
||||
"filename": job.get("filename"),
|
||||
"transcript": bool(job.get("transcript")),
|
||||
})
|
||||
|
||||
|
||||
@app.route("/api/history")
|
||||
def get_history():
|
||||
rows = load_history()[:50]
|
||||
for r in rows:
|
||||
# Truth at read time: a recorded caption-transcript may have been
|
||||
# deleted, and a manual yt-transcribe sidecar may have appeared since.
|
||||
path = r.get("transcript") or sidecar_transcript(r.get("file"))
|
||||
if path and os.path.exists(path):
|
||||
r["transcript"] = path
|
||||
r["has_transcript"] = True
|
||||
if not r.get("transcript_name"):
|
||||
r["transcript_name"] = os.path.splitext(os.path.basename(path))[0] + ".txt"
|
||||
else:
|
||||
r["transcript"] = ""
|
||||
r["has_transcript"] = False
|
||||
return jsonify(rows)
|
||||
|
||||
|
||||
@app.route("/api/transcript/<job_id>")
|
||||
def download_transcript(job_id):
|
||||
rec = resolve_download(job_id, "file") or resolve_download(job_id, "transcript")
|
||||
path = (rec.get("transcript") if rec else None) \
|
||||
or (sidecar_transcript(rec.get("file")) if rec else None)
|
||||
if not rec or not path or not os.path.exists(path):
|
||||
return jsonify({"error": "Transcript not found"}), 404
|
||||
default_name = os.path.splitext(os.path.basename(path))[0] + ".txt"
|
||||
return send_file(path, as_attachment=True,
|
||||
download_name=rec.get("transcript_name") or default_name)
|
||||
|
||||
|
||||
@app.route("/api/file/<job_id>")
|
||||
def download_file(job_id):
|
||||
rec = resolve_download(job_id, "file")
|
||||
path = rec.get("file") if rec else None
|
||||
if not rec or not path or not os.path.exists(path):
|
||||
return jsonify({"error": "File not found"}), 404
|
||||
return send_file(path, as_attachment=True,
|
||||
download_name=rec.get("filename") or os.path.basename(path))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
port = int(os.environ.get("PORT", 8899))
|
||||
host = os.environ.get("HOST", "127.0.0.1")
|
||||
app.run(host=host, port=port)
|
||||
@@ -0,0 +1,772 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>ReClip — Free Media Downloader</title>
|
||||
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f4f1eb;
|
||||
--fg: #3a3a38;
|
||||
--accent: #e85d2a;
|
||||
--accent-hover: #d04e1f;
|
||||
--muted: #9c9889;
|
||||
--card: #fff;
|
||||
--card-border: #e2ded6;
|
||||
--success: #2d8a4e;
|
||||
--error: #c43d3d;
|
||||
--radius: 14px;
|
||||
--shimmer: linear-gradient(90deg, #ebe8e2 25%, #f0ede7 50%, #ebe8e2 75%);
|
||||
}
|
||||
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
font-family: 'DM Mono', monospace;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
min-height: 100vh;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
body::after {
|
||||
content: '';
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
opacity: 0.03;
|
||||
pointer-events: none;
|
||||
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E");
|
||||
background-size: 128px;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 620px;
|
||||
margin: 0 auto;
|
||||
padding: 60px 24px 80px;
|
||||
}
|
||||
|
||||
.brand { margin-bottom: 48px; }
|
||||
.brand h1 {
|
||||
font-family: 'Instrument Serif', serif;
|
||||
font-size: 4.2rem;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.03em;
|
||||
line-height: 1;
|
||||
color: var(--fg);
|
||||
}
|
||||
.brand h1 em { font-style: italic; color: var(--accent); }
|
||||
.brand p {
|
||||
margin-top: 10px;
|
||||
font-size: 0.78rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 18px 20px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--card);
|
||||
color: var(--fg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.88rem;
|
||||
outline: none;
|
||||
resize: none;
|
||||
min-height: 56px;
|
||||
transition: border-color 0.25s, box-shadow 0.25s;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
textarea:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px rgba(232, 93, 42, 0.08);
|
||||
}
|
||||
textarea::placeholder { color: var(--muted); }
|
||||
|
||||
.hint {
|
||||
font-size: 0.7rem;
|
||||
color: var(--muted);
|
||||
margin-bottom: 20px;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.pill-group {
|
||||
display: flex;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: var(--card);
|
||||
}
|
||||
.pill {
|
||||
padding: 9px 18px;
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.76rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.pill.active { background: var(--fg); color: var(--bg); }
|
||||
.pill:not(.active):hover { color: var(--fg); }
|
||||
|
||||
.fetch-btn {
|
||||
flex: 1;
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, transform 0.1s;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.fetch-btn:hover { background: var(--accent-hover); }
|
||||
.fetch-btn:active { transform: scale(0.98); }
|
||||
.fetch-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
|
||||
|
||||
/* Cards */
|
||||
.cards { margin-top: 24px; }
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--card);
|
||||
padding: 14px;
|
||||
margin-bottom: 10px;
|
||||
animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
@keyframes slideUp {
|
||||
from { opacity: 0; transform: translateY(12px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.card-thumb {
|
||||
width: 120px;
|
||||
min-width: 120px;
|
||||
height: 80px;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--card-border);
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
}
|
||||
.card-thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
/* No-thumbnail icon */
|
||||
.card-thumb .no-thumb {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--muted);
|
||||
}
|
||||
.card-thumb .no-thumb svg {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* Shimmer skeleton for loading state */
|
||||
.card-thumb.loading {
|
||||
background: var(--shimmer);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s infinite;
|
||||
}
|
||||
.skeleton-line {
|
||||
height: 12px;
|
||||
border-radius: 4px;
|
||||
background: var(--shimmer);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s infinite;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.skeleton-line.short { width: 40%; height: 10px; }
|
||||
.skeleton-line.medium { width: 75%; }
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
.card-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
.card-title {
|
||||
font-family: 'Instrument Serif', serif;
|
||||
font-size: 1rem;
|
||||
line-height: 1.3;
|
||||
color: var(--fg);
|
||||
margin-bottom: 2px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.card-meta {
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.card-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.card-dl-btn {
|
||||
padding: 6px 14px;
|
||||
border: none;
|
||||
border-radius: 7px;
|
||||
background: var(--fg);
|
||||
color: var(--bg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.card-dl-btn:hover { background: #2d2d2a; }
|
||||
.card-dl-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.card-dl-btn.done { background: var(--success); color: #fff; }
|
||||
.card-dl-btn.error { background: var(--error); color: #fff; }
|
||||
|
||||
.card-status {
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
.card-status.downloading { color: var(--accent); }
|
||||
.card-status.done { color: var(--success); }
|
||||
.card-status.error { color: var(--error); }
|
||||
|
||||
.q-chip {
|
||||
padding: 4px 10px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.65rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.q-chip.active {
|
||||
border-color: var(--fg);
|
||||
color: var(--fg);
|
||||
background: rgba(26,26,24,0.04);
|
||||
}
|
||||
.q-chip:hover:not(.active) { border-color: var(--muted); }
|
||||
|
||||
/* Error card */
|
||||
.card.card-error {
|
||||
border-color: rgba(196, 61, 61, 0.2);
|
||||
background: rgba(196, 61, 61, 0.03);
|
||||
}
|
||||
.card-error-icon {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(196, 61, 61, 0.08);
|
||||
color: var(--error);
|
||||
}
|
||||
.card-error-icon svg {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
.card-error-msg {
|
||||
font-size: 0.72rem;
|
||||
color: var(--error);
|
||||
margin-top: 2px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.card-error-url {
|
||||
font-size: 0.65rem;
|
||||
color: var(--muted);
|
||||
word-break: break-all;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Download all bar */
|
||||
.dl-all-bar {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.dl-all-btn {
|
||||
flex: 1;
|
||||
padding: 12px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: var(--fg);
|
||||
color: var(--bg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.dl-all-btn:hover { background: #2d2d2a; }
|
||||
.dl-all-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
|
||||
/* History — same card language as the fetch results */
|
||||
.hist-h {
|
||||
font-family: 'Instrument Serif', serif;
|
||||
font-size: 1.9rem;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.02em;
|
||||
margin: 44px 0 14px;
|
||||
color: var(--fg);
|
||||
}
|
||||
#history .card { animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1); }
|
||||
a.card-dl-btn { text-decoration: none; display: inline-block; }
|
||||
|
||||
.spin {
|
||||
display: inline-block;
|
||||
width: 10px; height: 10px;
|
||||
border: 2px solid currentColor;
|
||||
border-right-color: transparent;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
vertical-align: middle;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.footer {
|
||||
margin-top: 48px;
|
||||
text-align: center;
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
/* Mobile */
|
||||
@media (max-width: 500px) {
|
||||
.brand h1 { font-size: 3rem; }
|
||||
.page { padding: 40px 16px 60px; }
|
||||
.card { flex-direction: column; gap: 10px; }
|
||||
.card-thumb {
|
||||
width: 100%;
|
||||
min-width: unset;
|
||||
height: 160px;
|
||||
}
|
||||
.card-title { white-space: normal; }
|
||||
.controls { flex-wrap: wrap; }
|
||||
.fetch-btn { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div class="brand">
|
||||
<h1>Re<em>Clip</em></h1>
|
||||
<p>Free media downloader</p>
|
||||
</div>
|
||||
|
||||
<textarea id="urls" placeholder="Paste one or more URLs..." rows="2"></textarea>
|
||||
<p class="hint">Multiple links? Separate with spaces, commas, or newlines.</p>
|
||||
|
||||
<div class="controls">
|
||||
<div class="pill-group">
|
||||
<button class="pill active" data-format="video" onclick="setFormat(this)">MP4</button>
|
||||
<button class="pill" data-format="audio" onclick="setFormat(this)">MP3</button>
|
||||
</div>
|
||||
<button class="fetch-btn" id="goBtn" onclick="go()">Fetch</button>
|
||||
</div>
|
||||
|
||||
<div id="cards" class="cards"></div>
|
||||
<div id="history"></div>
|
||||
|
||||
<div class="footer">
|
||||
YouTube · TikTok · Instagram · Twitter/X · Reddit · Facebook<br>
|
||||
Vimeo · Twitch · Dailymotion · SoundCloud · Loom · Streamable<br>
|
||||
Pinterest · Tumblr · Threads · LinkedIn · 1000+ more
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let currentFormat = 'video';
|
||||
let cardData = [];
|
||||
|
||||
function setFormat(btn) {
|
||||
document.querySelectorAll('.pill').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
currentFormat = btn.dataset.format;
|
||||
}
|
||||
|
||||
function parseUrls(text) {
|
||||
return [...new Set(text.split(/[\s,]+/).map(u => u.trim()).filter(u => u.startsWith('http')))];
|
||||
}
|
||||
|
||||
function fmtDur(s) {
|
||||
if (!s) return '';
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = Math.floor(s % 60);
|
||||
return `${m}:${sec.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function esc(s) {
|
||||
const d = document.createElement('div');
|
||||
d.textContent = s;
|
||||
return d.innerHTML;
|
||||
}
|
||||
|
||||
function friendlyError(err) {
|
||||
if (err.includes('Unsupported URL')) return 'This URL is not supported';
|
||||
if (err.includes('Video unavailable')) return 'Video is unavailable or private';
|
||||
if (err.includes('Private video')) return 'This video is private';
|
||||
if (err.includes('HTTP Error 403')) return 'Access denied by the platform';
|
||||
if (err.includes('HTTP Error 404')) return 'Video not found';
|
||||
if (err.includes('copyright')) return 'Video blocked due to copyright';
|
||||
if (err.includes('geo')) return 'Video not available in your region';
|
||||
if (err.includes('timed out') || err.includes('Timed out')) return 'Request timed out — try again';
|
||||
if (err.includes('network') || err.includes('Network')) return 'Network error — check your connection';
|
||||
return err.length > 80 ? err.slice(0, 80) + '...' : err;
|
||||
}
|
||||
|
||||
document.getElementById('urls').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); go(); }
|
||||
});
|
||||
|
||||
async function go() {
|
||||
const urls = parseUrls(document.getElementById('urls').value);
|
||||
if (!urls.length) return;
|
||||
|
||||
const btn = document.getElementById('goBtn');
|
||||
const container = document.getElementById('cards');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Loading...';
|
||||
container.innerHTML = '';
|
||||
cardData = [];
|
||||
|
||||
// Check if youtube playlist URL
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
if (urls[i].includes('list=')) {
|
||||
const res = await fetch('/api/playlist', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: urls[i] }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.urls) {
|
||||
// replace playlist URL with individual video URLs
|
||||
urls.splice(i, 1, ...data.urls);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
const url = urls[i];
|
||||
const idx = cardData.length;
|
||||
cardData.push({ url, status: 'loading' });
|
||||
renderCard(idx);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/info', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
cardData[idx] = { ...cardData[idx], status: 'info-error', error: data.error };
|
||||
} else {
|
||||
cardData[idx] = {
|
||||
...cardData[idx],
|
||||
status: 'ready',
|
||||
title: data.title || '',
|
||||
thumbnail: data.thumbnail || '',
|
||||
duration: data.duration,
|
||||
uploader: data.uploader || '',
|
||||
formats: data.formats || [],
|
||||
selectedFormatId: data.formats?.[0]?.id || null,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
cardData[idx] = { ...cardData[idx], status: 'info-error', error: err.message };
|
||||
}
|
||||
renderCard(idx);
|
||||
}
|
||||
|
||||
if (cardData.filter(c => c.status === 'ready').length > 1) {
|
||||
renderDownloadAll();
|
||||
}
|
||||
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Fetch';
|
||||
}
|
||||
|
||||
function renderCard(idx) {
|
||||
const c = cardData[idx];
|
||||
let el = document.getElementById(`card-${idx}`);
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.id = `card-${idx}`;
|
||||
el.className = 'card';
|
||||
document.getElementById('cards').appendChild(el);
|
||||
}
|
||||
|
||||
// Loading skeleton
|
||||
if (c.status === 'loading') {
|
||||
el.className = 'card';
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb loading"></div>
|
||||
<div class="card-body">
|
||||
<div class="skeleton-line medium"></div>
|
||||
<div class="skeleton-line short"></div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (c.status === 'info-error') {
|
||||
el.className = 'card card-error';
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb">
|
||||
<div class="card-error-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title" style="color:var(--error)">Could not fetch video</div>
|
||||
<div class="card-error-msg">${esc(friendlyError(c.error || ''))}</div>
|
||||
<div class="card-error-url">${esc(c.url)}</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Ready / downloading / done / error states
|
||||
el.className = 'card';
|
||||
const isAudio = currentFormat === 'audio';
|
||||
|
||||
let thumbHtml;
|
||||
if (isAudio) {
|
||||
thumbHtml = `<div class="no-thumb" style="color:var(--accent)"><svg viewBox="0 0 24 24" fill="currentColor" stroke="none"><polygon points="5 3 19 12 5 21 5 3"/></svg></div>`;
|
||||
} else if (c.thumbnail) {
|
||||
thumbHtml = `<img src="${c.thumbnail}" alt="">`;
|
||||
} else {
|
||||
thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
|
||||
}
|
||||
|
||||
let qualityChips = '';
|
||||
if (!isAudio && c.formats && c.formats.length > 1) {
|
||||
qualityChips = c.formats.map(f =>
|
||||
`<button class="q-chip${f.id === c.selectedFormatId ? ' active' : ''}" onclick="pickFormat(${idx}, '${f.id}')">${f.label}</button>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
let actionHtml = '';
|
||||
if (c.status === 'ready') {
|
||||
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Download</button>${qualityChips}`;
|
||||
} else if (c.status === 'downloading') {
|
||||
actionHtml = `<span class="card-status downloading"><span class="spin"></span> Downloading...</span>`;
|
||||
} else if (c.status === 'done') {
|
||||
actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>` +
|
||||
(c.hasTranscript ? `<button class="card-dl-btn" onclick="saveTranscript(${idx})">Transcript</button>` : '') +
|
||||
`<span class="card-status done">${esc(c.filename || '')}</span>`;
|
||||
} else if (c.status === 'error') {
|
||||
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Retry</button>
|
||||
<span class="card-status error">${esc(friendlyError(c.error || 'Download failed'))}</span>`;
|
||||
}
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb">${thumbHtml}</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title">${esc(c.title || 'Untitled')}</div>
|
||||
<div class="card-meta">${esc(c.uploader)}${c.duration ? ' · ' + fmtDur(c.duration) : ''}</div>
|
||||
<div class="card-actions">${actionHtml}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderDownloadAll() {
|
||||
const existing = document.getElementById('dl-all-bar');
|
||||
if (existing) existing.remove();
|
||||
|
||||
const bar = document.createElement('div');
|
||||
bar.id = 'dl-all-bar';
|
||||
bar.className = 'dl-all-bar';
|
||||
bar.innerHTML = `<button class="dl-all-btn" onclick="dlAll()">Download All</button>`;
|
||||
document.getElementById('cards').appendChild(bar);
|
||||
}
|
||||
|
||||
function pickFormat(idx, formatId) {
|
||||
cardData[idx].selectedFormatId = formatId;
|
||||
renderCard(idx);
|
||||
}
|
||||
|
||||
async function dlCard(idx) {
|
||||
const c = cardData[idx];
|
||||
c.status = 'downloading';
|
||||
c.error = null;
|
||||
renderCard(idx);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/download', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
url: c.url,
|
||||
format: currentFormat,
|
||||
format_id: c.selectedFormatId,
|
||||
title: c.title || '',
|
||||
thumbnail: c.thumbnail || '',
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
c.status = 'error';
|
||||
c.error = data.error;
|
||||
renderCard(idx);
|
||||
return;
|
||||
}
|
||||
c.jobId = data.job_id;
|
||||
pollCard(idx);
|
||||
} catch (err) {
|
||||
c.status = 'error';
|
||||
c.error = err.message;
|
||||
renderCard(idx);
|
||||
}
|
||||
}
|
||||
|
||||
function pollCard(idx) {
|
||||
const c = cardData[idx];
|
||||
const iv = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/status/${c.jobId}`);
|
||||
const data = await res.json();
|
||||
if (data.status === 'done') {
|
||||
clearInterval(iv);
|
||||
c.status = 'done';
|
||||
c.filename = data.filename;
|
||||
c.hasTranscript = !!data.transcript;
|
||||
renderCard(idx);
|
||||
saveCard(idx);
|
||||
if (c.hasTranscript) saveTranscript(idx);
|
||||
} else if (data.status === 'error') {
|
||||
clearInterval(iv);
|
||||
c.status = 'error';
|
||||
c.error = data.error;
|
||||
renderCard(idx);
|
||||
}
|
||||
} catch {
|
||||
clearInterval(iv);
|
||||
c.status = 'error';
|
||||
c.error = 'Lost connection to server';
|
||||
renderCard(idx);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function saveCard(idx) {
|
||||
const c = cardData[idx];
|
||||
if (!c.jobId) return;
|
||||
const a = document.createElement('a');
|
||||
a.href = `/api/file/${c.jobId}`;
|
||||
a.download = c.filename || '';
|
||||
a.click();
|
||||
}
|
||||
|
||||
function saveTranscript(idx) {
|
||||
const c = cardData[idx];
|
||||
if (!c.jobId || !c.hasTranscript) return;
|
||||
const a = document.createElement('a');
|
||||
a.href = `/api/transcript/${c.jobId}`;
|
||||
a.download = (c.filename || 'transcript').replace(/\.[^.]+$/, '') + '.txt';
|
||||
a.click();
|
||||
}
|
||||
|
||||
async function dlAll() {
|
||||
const btn = document.querySelector('.dl-all-btn');
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'Downloading...'; }
|
||||
|
||||
for (let i = 0; i < cardData.length; i++) {
|
||||
if (cardData[i].status === 'ready') {
|
||||
await dlCard(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Download All'; }
|
||||
}
|
||||
|
||||
function fmtSize(bytes) {
|
||||
if (!bytes) return '';
|
||||
const mb = bytes / 1048576;
|
||||
return mb >= 1024 ? (mb / 1024).toFixed(2) + ' GB' : mb.toFixed(1) + ' MB';
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
try {
|
||||
const res = await fetch('/api/history');
|
||||
const rows = await res.json();
|
||||
const box = document.getElementById('history');
|
||||
if (!Array.isArray(rows) || !rows.length) return;
|
||||
const items = rows.map(r => {
|
||||
let thumbHtml;
|
||||
if (r.thumbnail) {
|
||||
thumbHtml = `<img src="${r.thumbnail}" alt="">`;
|
||||
} else {
|
||||
thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
|
||||
}
|
||||
const flag = r.has_transcript
|
||||
? `<span class="card-status done">transcript ✓</span>`
|
||||
: `<span class="card-status">no transcript</span>`;
|
||||
return `
|
||||
<div class="card">
|
||||
<div class="card-thumb">${thumbHtml}</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title">${esc(r.title || r.filename || r.url || 'Untitled')}</div>
|
||||
<div class="card-meta">${esc(r.date || '')}${r.size ? ' · ' + fmtSize(r.size) : ''} · <span class="${r.has_transcript ? 'card-status done' : ''}">${r.has_transcript ? 'transcript ✓' : 'no transcript'}</span></div>
|
||||
<div class="card-actions">
|
||||
<a class="card-dl-btn" href="/api/file/${r.job_id}" download>Save</a>
|
||||
${r.has_transcript ? `<a class="card-dl-btn" href="/api/transcript/${r.job_id}" download>Transcript</a>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
box.innerHTML = `<h2 class="hist-h">History</h2>${items}`;
|
||||
} catch { /* history unavailable */ }
|
||||
}
|
||||
|
||||
loadHistory();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,389 @@
|
||||
diff --git a/app.py b/app.py
|
||||
index 2b5eaa5..1dfbbd0 100644
|
||||
--- a/app.py
|
||||
+++ b/app.py
|
||||
@@ -2,8 +2,11 @@ import os
|
||||
import uuid
|
||||
import glob
|
||||
import json
|
||||
+import re
|
||||
+import hashlib
|
||||
import subprocess
|
||||
import threading
|
||||
+import time
|
||||
from flask import Flask, request, jsonify, send_file, render_template
|
||||
|
||||
app = Flask(__name__)
|
||||
@@ -12,6 +15,97 @@ os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
||||
|
||||
jobs = {}
|
||||
|
||||
+HISTORY_FILE = os.path.join(DOWNLOAD_DIR, "history.json")
|
||||
+_history_lock = threading.Lock()
|
||||
+
|
||||
+
|
||||
+def load_history():
|
||||
+ try:
|
||||
+ with open(HISTORY_FILE, encoding="utf-8") as fh:
|
||||
+ data = json.load(fh)
|
||||
+ return data if isinstance(data, list) else []
|
||||
+ except Exception:
|
||||
+ return []
|
||||
+
|
||||
+
|
||||
+def save_history(history):
|
||||
+ try:
|
||||
+ tmp = HISTORY_FILE + ".tmp"
|
||||
+ with open(tmp, "w", encoding="utf-8") as fh:
|
||||
+ json.dump(history, fh, indent=2)
|
||||
+ os.replace(tmp, HISTORY_FILE)
|
||||
+ except OSError:
|
||||
+ pass
|
||||
+
|
||||
+
|
||||
+def sidecar_transcript(file_path):
|
||||
+ """Manual-fallback transcripts (yt-transcribe <file>) live beside the
|
||||
+ media as <stem>.txt — recognize them at read time so history stays
|
||||
+ truthful without re-downloading anything."""
|
||||
+ if not file_path:
|
||||
+ return None
|
||||
+ stem = os.path.splitext(file_path)[0] + ".txt"
|
||||
+ return stem if os.path.exists(stem) else None
|
||||
+
|
||||
+
|
||||
+def record_history(job):
|
||||
+ """Persist the completed job so history + file/transcript downloads
|
||||
+ survive process restarts (downloads dir is the mapped volume)."""
|
||||
+ with _history_lock:
|
||||
+ history = [h for h in load_history() if h.get("job_id") != job.get("job_id")]
|
||||
+ history.insert(0, {
|
||||
+ "job_id": job.get("job_id"),
|
||||
+ "url": job.get("url", ""),
|
||||
+ "title": job.get("title", ""),
|
||||
+ "thumbnail": job.get("thumbnail", ""),
|
||||
+ "filename": job.get("filename", ""),
|
||||
+ "file": job.get("file", ""),
|
||||
+ "transcript": job.get("transcript") or "",
|
||||
+ "transcript_name": job.get("transcript_name", ""),
|
||||
+ "has_transcript": bool(job.get("transcript")),
|
||||
+ "size": os.path.getsize(job["file"]) if job.get("file") and os.path.exists(job["file"]) else 0,
|
||||
+ "date": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
+ })
|
||||
+ save_history(history[:200])
|
||||
+
|
||||
+
|
||||
+MEDIA_EXTS = (".mp4", ".mkv", ".webm", ".m4a", ".mp3", ".flac", ".mov", ".avi", ".wav", ".ts")
|
||||
+
|
||||
+
|
||||
+def backfill_history():
|
||||
+ """Add on-disk downloads that predate history.json (or were dropped into
|
||||
+ the downloads dir manually) so the whole library shows up on the page.
|
||||
+ The transcript flag is resolved live at read time, so backfilled entries
|
||||
+ pick up manual yt-transcribe sidecars automatically."""
|
||||
+ for name in sorted(os.listdir(DOWNLOAD_DIR)):
|
||||
+ path = os.path.join(DOWNLOAD_DIR, name)
|
||||
+ if not os.path.isfile(path) or not name.lower().endswith(MEDIA_EXTS):
|
||||
+ continue
|
||||
+ with _history_lock:
|
||||
+ history = load_history()
|
||||
+ if any(h.get("file") == path for h in history):
|
||||
+ continue
|
||||
+ stem = os.path.splitext(name)[0]
|
||||
+ # a 10-hex stem is a reclip job id — the real title wasn't kept
|
||||
+ title = "" if re.fullmatch(r"[0-9a-f]{10}", stem) else stem
|
||||
+ history.insert(0, {
|
||||
+ "job_id": hashlib.sha1(path.encode()).hexdigest()[:10],
|
||||
+ "url": "",
|
||||
+ "title": title,
|
||||
+ "filename": name,
|
||||
+ "file": path,
|
||||
+ "transcript": "",
|
||||
+ "transcript_name": "",
|
||||
+ "has_transcript": False,
|
||||
+ "size": os.path.getsize(path),
|
||||
+ "date": time.strftime("%Y-%m-%d %H:%M:%S",
|
||||
+ time.localtime(os.path.getmtime(path))),
|
||||
+ })
|
||||
+ save_history(history[:200])
|
||||
+
|
||||
+
|
||||
+backfill_history()
|
||||
+
|
||||
|
||||
def parse_ytdlp_json(stdout):
|
||||
"""Parse yt-dlp JSON output.
|
||||
@@ -29,6 +123,53 @@ def parse_ytdlp_json(stdout):
|
||||
raise ValueError("yt-dlp returned no data")
|
||||
|
||||
|
||||
+def fetch_transcript(url, chosen_path):
|
||||
+ """Best-effort transcript via yt-dlp captions (manual or auto-generated;
|
||||
+ includes X's auto-captions). Writes <video stem>.txt beside the download.
|
||||
+ Returns the .txt path, or None when the video has no captions. Never
|
||||
+ raises — a transcript is a bonus, not a download requirement."""
|
||||
+ stem = os.path.splitext(chosen_path)[0]
|
||||
+ try:
|
||||
+ cmd = ["yt-dlp", "--no-playlist", "--skip-download", "--no-warnings",
|
||||
+ "--write-subs", "--write-auto-subs",
|
||||
+ "--sub-langs", "en,en-orig",
|
||||
+ "--sub-format", "vtt",
|
||||
+ "-o", stem + ".%(ext)s", url]
|
||||
+ subprocess.run(cmd, capture_output=True, text=True, timeout=180)
|
||||
+
|
||||
+ vtts = glob.glob(stem + ".*.vtt")
|
||||
+ if not vtts:
|
||||
+ return None
|
||||
+ vtts.sort(key=lambda p: (0 if p.endswith(".en.vtt") else 1, p))
|
||||
+
|
||||
+ lines, prev = [], None
|
||||
+ with open(vtts[0], encoding="utf-8", errors="replace") as fh:
|
||||
+ for raw in fh:
|
||||
+ line = raw.strip()
|
||||
+ if (not line or "-->" in line
|
||||
+ or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
|
||||
+ or re.match(r"^\d+$", line)):
|
||||
+ continue
|
||||
+ line = re.sub(r"<[^>]+>", "", line)
|
||||
+ if line and line != prev:
|
||||
+ lines.append(line)
|
||||
+ prev = line
|
||||
+
|
||||
+ txt = stem + ".txt"
|
||||
+ with open(txt, "w", encoding="utf-8") as out:
|
||||
+ out.write(" ".join(lines) + "\n")
|
||||
+
|
||||
+ for f in vtts:
|
||||
+ try:
|
||||
+ os.remove(f)
|
||||
+ except OSError:
|
||||
+ pass
|
||||
+
|
||||
+ return txt if lines else None
|
||||
+ except Exception:
|
||||
+ return None
|
||||
+
|
||||
+
|
||||
def run_download(job_id, url, format_choice, format_id):
|
||||
job = jobs[job_id]
|
||||
out_template = os.path.join(DOWNLOAD_DIR, f"{job_id}.%(ext)s")
|
||||
@@ -81,6 +222,12 @@ def run_download(job_id, url, format_choice, format_id):
|
||||
job["filename"] = f"{safe_title}{ext}" if safe_title else os.path.basename(chosen)
|
||||
else:
|
||||
job["filename"] = os.path.basename(chosen)
|
||||
+
|
||||
+ # Best-effort transcript sidecar: yt-dlp captions (X auto-captions
|
||||
+ # included) -> plain .txt next to the chosen file. Never fails the job.
|
||||
+ job["transcript"] = fetch_transcript(url, chosen)
|
||||
+ job["transcript_name"] = os.path.splitext(job["filename"])[0] + ".txt"
|
||||
+ record_history(job)
|
||||
except subprocess.TimeoutExpired:
|
||||
job["status"] = "error"
|
||||
job["error"] = "Download timed out (5 min limit)"
|
||||
@@ -175,7 +322,8 @@ def start_download():
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
job_id = uuid.uuid4().hex[:10]
|
||||
- jobs[job_id] = {"status": "downloading", "url": url, "title": title}
|
||||
+ jobs[job_id] = {"job_id": job_id, "status": "downloading", "url": url, "title": title,
|
||||
+ "thumbnail": (data.get("thumbnail") or "")[:500]}
|
||||
|
||||
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
|
||||
thread.daemon = True
|
||||
@@ -184,6 +332,18 @@ def start_download():
|
||||
return jsonify({"job_id": job_id})
|
||||
|
||||
|
||||
+def resolve_download(job_id, key):
|
||||
+ """Find a completed job in memory, falling back to the on-disk history
|
||||
+ (paths point into DOWNLOAD_DIR, so they survive restarts)."""
|
||||
+ job = jobs.get(job_id)
|
||||
+ if job and job.get("status") == "done" and job.get(key):
|
||||
+ return job
|
||||
+ for entry in load_history():
|
||||
+ if entry.get("job_id") == job_id and entry.get(key):
|
||||
+ return entry
|
||||
+ return None
|
||||
+
|
||||
+
|
||||
@app.route("/api/status/<job_id>")
|
||||
def check_status(job_id):
|
||||
job = jobs.get(job_id)
|
||||
@@ -193,15 +353,48 @@ def check_status(job_id):
|
||||
"status": job["status"],
|
||||
"error": job.get("error"),
|
||||
"filename": job.get("filename"),
|
||||
+ "transcript": bool(job.get("transcript")),
|
||||
})
|
||||
|
||||
|
||||
+@app.route("/api/history")
|
||||
+def get_history():
|
||||
+ rows = load_history()[:50]
|
||||
+ for r in rows:
|
||||
+ # Truth at read time: a recorded caption-transcript may have been
|
||||
+ # deleted, and a manual yt-transcribe sidecar may have appeared since.
|
||||
+ path = r.get("transcript") or sidecar_transcript(r.get("file"))
|
||||
+ if path and os.path.exists(path):
|
||||
+ r["transcript"] = path
|
||||
+ r["has_transcript"] = True
|
||||
+ if not r.get("transcript_name"):
|
||||
+ r["transcript_name"] = os.path.splitext(os.path.basename(path))[0] + ".txt"
|
||||
+ else:
|
||||
+ r["transcript"] = ""
|
||||
+ r["has_transcript"] = False
|
||||
+ return jsonify(rows)
|
||||
+
|
||||
+
|
||||
+@app.route("/api/transcript/<job_id>")
|
||||
+def download_transcript(job_id):
|
||||
+ rec = resolve_download(job_id, "file") or resolve_download(job_id, "transcript")
|
||||
+ path = (rec.get("transcript") if rec else None) \
|
||||
+ or (sidecar_transcript(rec.get("file")) if rec else None)
|
||||
+ if not rec or not path or not os.path.exists(path):
|
||||
+ return jsonify({"error": "Transcript not found"}), 404
|
||||
+ default_name = os.path.splitext(os.path.basename(path))[0] + ".txt"
|
||||
+ return send_file(path, as_attachment=True,
|
||||
+ download_name=rec.get("transcript_name") or default_name)
|
||||
+
|
||||
+
|
||||
@app.route("/api/file/<job_id>")
|
||||
def download_file(job_id):
|
||||
- job = jobs.get(job_id)
|
||||
- if not job or job["status"] != "done":
|
||||
- return jsonify({"error": "File not ready"}), 404
|
||||
- return send_file(job["file"], as_attachment=True, download_name=job["filename"])
|
||||
+ rec = resolve_download(job_id, "file")
|
||||
+ path = rec.get("file") if rec else None
|
||||
+ if not rec or not path or not os.path.exists(path):
|
||||
+ return jsonify({"error": "File not found"}), 404
|
||||
+ return send_file(path, as_attachment=True,
|
||||
+ download_name=rec.get("filename") or os.path.basename(path))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
diff --git a/templates/index.html b/templates/index.html
|
||||
index 1f566d1..4807aa1 100644
|
||||
--- a/templates/index.html
|
||||
+++ b/templates/index.html
|
||||
@@ -343,6 +343,18 @@
|
||||
.dl-all-btn:hover { background: #2d2d2a; }
|
||||
.dl-all-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
|
||||
+ /* History — same card language as the fetch results */
|
||||
+ .hist-h {
|
||||
+ font-family: 'Instrument Serif', serif;
|
||||
+ font-size: 1.9rem;
|
||||
+ font-weight: 400;
|
||||
+ letter-spacing: -0.02em;
|
||||
+ margin: 44px 0 14px;
|
||||
+ color: var(--fg);
|
||||
+ }
|
||||
+ #history .card { animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1); }
|
||||
+ a.card-dl-btn { text-decoration: none; display: inline-block; }
|
||||
+
|
||||
.spin {
|
||||
display: inline-block;
|
||||
width: 10px; height: 10px;
|
||||
@@ -399,6 +411,7 @@
|
||||
</div>
|
||||
|
||||
<div id="cards" class="cards"></div>
|
||||
+ <div id="history"></div>
|
||||
|
||||
<div class="footer">
|
||||
YouTube · TikTok · Instagram · Twitter/X · Reddit · Facebook<br>
|
||||
@@ -586,8 +599,9 @@
|
||||
} else if (c.status === 'downloading') {
|
||||
actionHtml = `<span class="card-status downloading"><span class="spin"></span> Downloading...</span>`;
|
||||
} else if (c.status === 'done') {
|
||||
- actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>
|
||||
- <span class="card-status done">${esc(c.filename || '')}</span>`;
|
||||
+ actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>` +
|
||||
+ (c.hasTranscript ? `<button class="card-dl-btn" onclick="saveTranscript(${idx})">Transcript</button>` : '') +
|
||||
+ `<span class="card-status done">${esc(c.filename || '')}</span>`;
|
||||
} else if (c.status === 'error') {
|
||||
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Retry</button>
|
||||
<span class="card-status error">${esc(friendlyError(c.error || 'Download failed'))}</span>`;
|
||||
@@ -634,6 +648,7 @@
|
||||
format: currentFormat,
|
||||
format_id: c.selectedFormatId,
|
||||
title: c.title || '',
|
||||
+ thumbnail: c.thumbnail || '',
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
@@ -662,8 +677,10 @@
|
||||
clearInterval(iv);
|
||||
c.status = 'done';
|
||||
c.filename = data.filename;
|
||||
+ c.hasTranscript = !!data.transcript;
|
||||
renderCard(idx);
|
||||
saveCard(idx);
|
||||
+ if (c.hasTranscript) saveTranscript(idx);
|
||||
} else if (data.status === 'error') {
|
||||
clearInterval(iv);
|
||||
c.status = 'error';
|
||||
@@ -688,6 +705,15 @@
|
||||
a.click();
|
||||
}
|
||||
|
||||
+ function saveTranscript(idx) {
|
||||
+ const c = cardData[idx];
|
||||
+ if (!c.jobId || !c.hasTranscript) return;
|
||||
+ const a = document.createElement('a');
|
||||
+ a.href = `/api/transcript/${c.jobId}`;
|
||||
+ a.download = (c.filename || 'transcript').replace(/\.[^.]+$/, '') + '.txt';
|
||||
+ a.click();
|
||||
+ }
|
||||
+
|
||||
async function dlAll() {
|
||||
const btn = document.querySelector('.dl-all-btn');
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'Downloading...'; }
|
||||
@@ -700,6 +726,47 @@
|
||||
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Download All'; }
|
||||
}
|
||||
+
|
||||
+ function fmtSize(bytes) {
|
||||
+ if (!bytes) return '';
|
||||
+ const mb = bytes / 1048576;
|
||||
+ return mb >= 1024 ? (mb / 1024).toFixed(2) + ' GB' : mb.toFixed(1) + ' MB';
|
||||
+ }
|
||||
+
|
||||
+ async function loadHistory() {
|
||||
+ try {
|
||||
+ const res = await fetch('/api/history');
|
||||
+ const rows = await res.json();
|
||||
+ const box = document.getElementById('history');
|
||||
+ if (!Array.isArray(rows) || !rows.length) return;
|
||||
+ const items = rows.map(r => {
|
||||
+ let thumbHtml;
|
||||
+ if (r.thumbnail) {
|
||||
+ thumbHtml = `<img src="${r.thumbnail}" alt="">`;
|
||||
+ } else {
|
||||
+ thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
|
||||
+ }
|
||||
+ const flag = r.has_transcript
|
||||
+ ? `<span class="card-status done">transcript ✓</span>`
|
||||
+ : `<span class="card-status">no transcript</span>`;
|
||||
+ return `
|
||||
+ <div class="card">
|
||||
+ <div class="card-thumb">${thumbHtml}</div>
|
||||
+ <div class="card-body">
|
||||
+ <div class="card-title">${esc(r.title || r.filename || r.url || 'Untitled')}</div>
|
||||
+ <div class="card-meta">${esc(r.date || '')}${r.size ? ' · ' + fmtSize(r.size) : ''} · <span class="${r.has_transcript ? 'card-status done' : ''}">${r.has_transcript ? 'transcript ✓' : 'no transcript'}</span></div>
|
||||
+ <div class="card-actions">
|
||||
+ <a class="card-dl-btn" href="/api/file/${r.job_id}" download>Save</a>
|
||||
+ ${r.has_transcript ? `<a class="card-dl-btn" href="/api/transcript/${r.job_id}" download>Transcript</a>` : ''}
|
||||
+ </div>
|
||||
+ </div>
|
||||
+ </div>`;
|
||||
+ }).join('');
|
||||
+ box.innerHTML = `<h2 class="hist-h">History</h2>${items}`;
|
||||
+ } catch { /* history unavailable */ }
|
||||
+ }
|
||||
+
|
||||
+ loadHistory();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -13,4 +13,97 @@ The firstmate crew dispatch + Gitea PR helper are wired by `darwin-rebuild`, but
|
||||
cd ~/Documents/investor-flow
|
||||
git remote set-url origin http://unraid.local:3003/transnet/investor-flow
|
||||
|
||||
Verify: `fm` launches OpenCode 2 as the first mate (isolated `~/.config/opencode2`); `oc2 --version` prints an OpenCode 2 version; `pi --list-models mimo` shows `opencode-go/mimo-v2.5-pro`; `tea pulls list --repo transnet/investor-flow` works.
|
||||
Verify: `fm` launches Pi as the first mate (accept project trust once); `oc2 --version` prints the Homebrew opencode version; `pi --list-models mimo` shows `opencode-go/mimo-v2.5-pro`; `tea pulls list --repo transnet/investor-flow` works.
|
||||
|
||||
## security-audit skill (agent security reviews)
|
||||
|
||||
`home.activation.securityAuditSkill` installs Cloudflare's `security-audit` skill from `https://github.com/cloudflare/security-audit-skill` so the coding agents can run a structured vulnerability audit. The exact command:
|
||||
|
||||
```bash
|
||||
/opt/homebrew/bin/npx --yes skills add https://github.com/cloudflare/security-audit-skill \
|
||||
--skill security-audit --global \
|
||||
--agent claude-code codex pi opencode --yes
|
||||
```
|
||||
|
||||
The install needs Homebrew's `node`, which `configuration.nix` already declares, plus the system Git at `/usr/bin/git` for the clone. Renew or update the skill by hand with:
|
||||
|
||||
```bash
|
||||
/opt/homebrew/bin/npx --yes skills update security-audit --global --yes
|
||||
```
|
||||
|
||||
Agent scope: the Skills CLI installs the bundle once under `~/.agents/skills/security-audit`, the universal user-level directory that Codex, Pi, and OpenCode read, and it links that directory into `~/.claude/skills` for Claude Code. Grok Build is out of scope for this install: its skill directory is `~/.grok/skills`, and the CLI only populates it when `grok` is named in `--agent`. The install leaves `~/.config/opencode/skills` alone because home-manager owns that path with `force = true` and `mkOutOfStoreSymlink` into the mutable dotfiles checkout: a rebuild would clobber the CLI's link, and CLI writes would land in the git checkout. That is why the install uses the shared directory instead.
|
||||
|
||||
The activation is idempotent and non-interactive: it skips the install when both the canonical copy and the Claude Code link exist, and a failed download only warns so the rebuild still completes. Trigger it in an agent with "security audit this codebase".
|
||||
|
||||
Sandbox: the skill's README requires an OS-enforced sandbox (no external network, sanitized environment, resource limits, scratch-only writes) before it may run target-controlled builds, tests, browser automation, emulators, fuzzers, or fixtures. `security-audit-sandbox` below provides that sandbox. Run target code only through it; otherwise the workflow keeps such leads as `needs_validation` rather than executing target code.
|
||||
|
||||
## Security audit sandbox
|
||||
|
||||
`security-audit-sandbox` (installed as `~/.local/bin/security-audit-sandbox`) runs untrusted target code in a Docker container. It is for target code only: do not run the audit agent or your own tools inside it.
|
||||
|
||||
```bash
|
||||
security-audit-sandbox start ~/code/myapp [--image node:22-bookworm] [--exclude dist]...
|
||||
security-audit-sandbox exec ~/code/myapp [--timeout 600] -- npm test
|
||||
security-audit-sandbox stop ~/code/myapp [--keep]
|
||||
security-audit-sandbox status ~/code/myapp
|
||||
```
|
||||
|
||||
`start` canonicalizes the app path, copies the app to `~/security-audit-runs/<slug>.XXXXXX`, and starts a detached container. The original app directory is never mounted into the container, so the copy is the only thing the target code can see.
|
||||
|
||||
Image resolution order:
|
||||
|
||||
1. `--image`
|
||||
2. `IMAGE=` in the app's `security-audit.conf`
|
||||
3. Inference: `package.json` gives `node:22-bookworm`, `pyproject.toml` or `requirements.txt` gives `python:3.12-slim`, `go.mod` gives `golang:1.24-bookworm`, `Cargo.toml` gives `rust:1-bookworm`, and `Gemfile` gives `ruby:3.3-bookworm`.
|
||||
|
||||
`start` stops with an error when nothing resolves an image. To support another runtime, add a marker file mapping or pass `--image`.
|
||||
|
||||
The optional `security-audit.conf` in the app root holds simple `KEY=value` lines. It is parsed, never sourced:
|
||||
|
||||
```ini
|
||||
IMAGE=node:22-bookworm
|
||||
EXCLUDE="node_modules dist coverage"
|
||||
```
|
||||
|
||||
`EXCLUDE=` is a whitespace-separated list, and the key may be repeated: every `EXCLUDE=` line applies. CLI `--exclude` patterns are added on top of it. The copy always excludes `.git`, `.env*`, and the top-level `/data` directory, so secrets and live data stay on the host.
|
||||
|
||||
Container controls:
|
||||
|
||||
- `--network none`: no external network, only loopback for local tests.
|
||||
- `--read-only` root with writes limited to the bind-mounted scratch directory at `/scratch`, plus a 512 MiB tmpfs at `/tmp`.
|
||||
- `HOME=/scratch/home`, `TMPDIR=/scratch/tmp`, and `XDG_CACHE_HOME=/scratch/cache`.
|
||||
- Runs as your host UID:GID, with `--cap-drop ALL`, `no-new-privileges`, and `--init`.
|
||||
- `--memory 4g`, `--cpus 2`, `--pids-limit 256`, and `nofile=1024:1024`.
|
||||
- `fsize=104857600` (100 MiB) when the Docker host accepts it. Docker Desktop on macOS may refuse `fsize`; the wrapper then starts without only that cap and prints a warning.
|
||||
|
||||
`exec` runs the command from `/scratch/app` under `timeout --signal=KILL`, default 600 seconds. It passes no host environment variables. If the image has no `timeout` binary, or its `timeout` does not enforce the `--signal=KILL` wall-clock limit, `exec` refuses to run rather than dropping the limit.
|
||||
|
||||
`stop` removes the container, the state file, and the run directory. Pass `--keep` to keep the run directory for inspection. State lives under `${XDG_STATE_HOME:-~/.local/state}/security-audit-sandbox` and is keyed by the canonical app path, so `exec`, `stop`, and `status` find the same run.
|
||||
|
||||
Use dummy data only. The exclusions cover common secrets and the top-level `data` directory, not every possible secret path. Review the copied tree, or add `--exclude` patterns, before you run a target that reads credentials from unexpected places. Audit findings do not belong in this repo or in the run directory.
|
||||
|
||||
## pstack skills (pinned on every rebuild)
|
||||
|
||||
`home.activation.pstackSkills` restores the eleven adopted pstack skills into `~/.agents/skills`, the shared user-level skill directory that the security-audit section describes. The source is `https://github.com/cursor/plugins` at a fixed commit (folder `pstack/skills`), pinned by the `pstackSkills` `fetchFromGitHub` in `home.nix`. That pin is the only record of the commit in this repo: to move to newer upstream content, change `rev` and `hash` together, then rerun `./rebuild.sh`.
|
||||
|
||||
Each run removes and recopies only those eleven directories, so a renamed upstream file never lingers and every other skill in `~/.agents/skills` stays untouched, including an existing tdd skill. `tdd` is skipped on purpose: an existing user-level tdd skill owns that name, so the pstack copy is never installed. The block adds no `~/.claude/skills` link, so Claude Code does not see these eleven skills.
|
||||
|
||||
Why these eleven skills exist is recorded in firstmate's `docs/adopted-skills.md`, outside this repo.
|
||||
|
||||
## OpenSuperWhisper (local voice input)
|
||||
|
||||
Hold a shortcut, speak, release, and the transcript pastes into the focused app. Everything runs on the Mac: no audio or transcript leaves the machine.
|
||||
|
||||
First run:
|
||||
|
||||
1. The `opensuperwhisper` cask is installed and `home.activation.openSuperWhisper` pre-downloads the model to `~/Library/Application Support/ru.starmel.OpenSuperWhisper/whisper-models/ggml-large-v3-turbo.bin`. It selects "Whisper V3 Large" only when no model is selected or the selected file is gone, so a model you pick in the app stays selected.
|
||||
2. Open the app. Onboarding should already show "Whisper V3 Large" as downloaded.
|
||||
3. Grant **Microphone**, **Accessibility**, and **Input Monitoring** when macOS asks. Input Monitoring is needed because the trigger is Right Option, a single modifier key.
|
||||
4. Keep the Right Option trigger (or change it in the app's settings). Hold it, speak, release. Auto-paste puts the text into the focused terminal or editor.
|
||||
|
||||
Notes:
|
||||
|
||||
- A fresh install starts with Option plus backtick instead of Right Option, and that combination needs no Input Monitoring. The activation never writes the trigger, the language, or the paste settings, so whatever you choose in the app survives the next rebuild.
|
||||
- The model is local-only (about 1.6 GB). If the download failed during the rebuild, rerun `./rebuild.sh` or download the large Turbo V3 model ("Turbo V3 large" in the app's Settings) by hand.
|
||||
- Voice is for prompts and prose. Type URLs, file paths, and exact identifiers yourself.
|
||||
- The first-run steps above are manual on purpose: macOS TCC permissions cannot be granted declaratively.
|
||||
+64
-13
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Rebuild nix-darwin + home-manager. Rotates stale home-manager *.backup files
|
||||
# so a second switch never fails with "would be clobbered".
|
||||
# Also upgrades grok-build and installs OpenCode 1.x (stable CLI for free-tier).
|
||||
# Also updates flake inputs, upgrades grok-build, removes retired npm OpenCode
|
||||
# packages, updates no-mistakes, and updates pi extensions.
|
||||
set -euo pipefail
|
||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
|
||||
ln -sfn "$DIR" ~/.dotfiles
|
||||
@@ -15,20 +16,51 @@ else
|
||||
echo "==> WARNING: grok-build upgrade failed (network issue). Skipping."
|
||||
fi
|
||||
|
||||
# Install OpenCode 1.x (stable CLI, binary "opencode") if absent.
|
||||
# Required for free-tier models; opencode2 beta returns HTTP 426 on those endpoints.
|
||||
# Uses Homebrew's npm (not Nix's npm) to avoid EACCES on the store.
|
||||
# Skip if npm is unavailable (e.g., network issues preventing fetch).
|
||||
OPENCODE_BIN=/opt/homebrew/bin/opencode
|
||||
if [ ! -x "$OPENCODE_BIN" ]; then
|
||||
echo "==> Installing OpenCode 1.x (stable) via Homebrew npm..."
|
||||
if /opt/homebrew/bin/npm install -g --allow-scripts=opencode-ai opencode-ai@1.18 2>&1; then
|
||||
echo "==> OpenCode 1.x installed successfully"
|
||||
# Remove retired npm OpenCode installs if an older rebuild installed them:
|
||||
# the `@opencode-ai/cli` beta and the older `opencode-ai` CLI. The Homebrew
|
||||
# `opencode` formula declared in configuration.nix is now the only OpenCode
|
||||
# install, unpinned so it tracks the latest release. The guard is a local check
|
||||
# for npm, so a rebuild without npm skips this instead of failing.
|
||||
NPM=/opt/homebrew/bin/npm
|
||||
if [ -x "$NPM" ] && npm_root="$("$NPM" root -g 2>/dev/null)"; then
|
||||
for pkg in @opencode-ai/cli opencode-ai; do
|
||||
if [ -d "$npm_root/$pkg" ]; then
|
||||
if "$NPM" uninstall -g "$pkg" >/dev/null 2>&1; then
|
||||
echo "==> Removed retired npm package $pkg"
|
||||
else
|
||||
echo "==> WARNING: $pkg removal failed. Remove it manually: $NPM uninstall -g $pkg"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
fi
|
||||
# `opencode` links without --overwrite, so any npm shim left in the Homebrew
|
||||
# prefix aborts the switch's brew bundle link step. Drop the retired packages'
|
||||
# shims directly, which also covers a failed uninstall and a missing npm.
|
||||
for link in /opt/homebrew/bin/*; do
|
||||
case "$(readlink "$link" 2>/dev/null || true)" in
|
||||
*/node_modules/@opencode-ai/cli/* | */node_modules/opencode-ai/*)
|
||||
rm -f "$link"
|
||||
echo "==> Removed stale OpenCode npm shim $link"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "==> Updating no-mistakes..."
|
||||
NO_MISTAKES_BIN="$HOME/.no-mistakes/bin/no-mistakes"
|
||||
if [ -x "$NO_MISTAKES_BIN" ]; then
|
||||
if "$NO_MISTAKES_BIN" update 2>&1; then
|
||||
echo "==> no-mistakes update complete"
|
||||
else
|
||||
echo "==> WARNING: OpenCode 1.x installation failed (network issue). Skipping."
|
||||
echo "==> WARNING: no-mistakes update failed. Skipping."
|
||||
fi
|
||||
elif command -v no-mistakes >/dev/null 2>&1; then
|
||||
if no-mistakes update 2>&1; then
|
||||
echo "==> no-mistakes update complete"
|
||||
else
|
||||
echo "==> WARNING: no-mistakes update failed. Skipping."
|
||||
fi
|
||||
else
|
||||
echo "==> OpenCode 1.x already installed: $(${OPENCODE_BIN} --version)"
|
||||
echo "==> WARNING: no-mistakes not found. Skipping update."
|
||||
fi
|
||||
|
||||
stamp="$(date +%Y%m%d-%H%M%S)"
|
||||
@@ -47,6 +79,7 @@ managed=(
|
||||
"$HOME/.config/opencode2/AGENTS.md"
|
||||
"$HOME/.local/bin/oc2"
|
||||
"$HOME/.local/bin/opencode-go-token"
|
||||
"$HOME/.local/bin/opencode-go-key-sync"
|
||||
"$HOME/.pi/agent/settings.json"
|
||||
"$HOME/.pi/agent/models.json"
|
||||
"$HOME/.pi/agent/AGENTS.md"
|
||||
@@ -74,4 +107,22 @@ do
|
||||
fi
|
||||
done
|
||||
|
||||
exec sudo darwin-rebuild switch --flake ~/.dotfiles#lt-mbp
|
||||
echo "==> Updating flake inputs..."
|
||||
if nix flake update --flake ~/.dotfiles 2>&1; then
|
||||
echo "==> flake update complete"
|
||||
else
|
||||
echo "==> WARNING: flake update failed. Continuing with locked inputs."
|
||||
fi
|
||||
|
||||
sudo darwin-rebuild switch --flake ~/.dotfiles#lt-mbp
|
||||
|
||||
# Update installed pi packages after the switch, because the Homebrew bundle
|
||||
# may have upgraded the pi binary.
|
||||
echo "==> Updating pi extensions..."
|
||||
if ! command -v pi >/dev/null 2>&1; then
|
||||
echo "==> WARNING: pi not found. Skipping extension update."
|
||||
elif pi update --extensions --no-approve 2>&1; then
|
||||
echo "==> pi extension update complete"
|
||||
else
|
||||
echo "==> WARNING: pi extension update failed. Skipping."
|
||||
fi
|
||||
Reference in new issue
Block a user