amaan can't into kernel

do 400 pushups per cache miss idiot
This commit is contained in:
atagen 2026-04-27 16:09:39 +10:00
parent 848ed62c5d
commit 4921973b9a
34 changed files with 3240 additions and 605 deletions

View file

@ -40,7 +40,7 @@ scope "boot" {
maxGenerations = 5;
};
plymouth = {
enable = true;
enable = false;
inherit (config.rice.plymouth) theme themePackages font;
};

View file

@ -1 +1 @@
/nix/store/bc2v8k5620k5p57ggrxy6i5w6pay9kis-Colours.qml
/nix/store/1ajn9faiksanmy64n7sg4xjqij1cc5qc-Colours.qml

View file

@ -5,6 +5,7 @@
mainUser,
getPkgs,
config,
getFlakePkg,
...
}:
let
@ -13,8 +14,8 @@ let
let
grim = lib.getExe pkgs.grim;
slurp = lib.getExe pkgs.slurp;
wl-copy = lib.getExe' pkgs.wl-clipboard-rs "wl-copy";
wl-paste = lib.getExe' pkgs.wl-clipboard-rs "wl-paste";
wl-copy = lib.getExe' (getFlakePkg inputs.stash) "wl-copy";
wl-paste = lib.getExe' (getFlakePkg inputs.stash) "wl-paste";
in
pkgs.writeScriptBin "shotta" ''
#! /usr/bin/env nu
@ -29,28 +30,12 @@ in
environment.systemPackages = getPkgs {
inherit shotta;
inherit (pkgs.kdePackages) qtbase qtdeclarative;
inherit (pkgs) wl-clipboard quickshell;
inherit (pkgs) quickshell;
};
imports = [
inputs.stasis.nixosModules.default
inputs.stash.nixosModules.default
];
services.stasis = {
enable = false;
extraConfig = ''
default:
dpms_off:
timeout 300
command "niri msg action power-off-monitors"
end
suspend:
timeout 600
command "systemctl suspend"
end
end
'';
};
services.stash-clipboard = {
enable = true;

View file

@ -104,6 +104,7 @@ in
config.programs.niri = {
enable = true;
package = niri;
useNautilus = false;
};
config.services.niri-tag = {

View file

@ -26,7 +26,7 @@ in
services.greetd = {
enable = true;
settings.default_session.command = "${lib.getExe (getFlakePkg inputs.tuigreet)} --sessions /etc/greetd/wayland-sessions --remember-session";
settings.default_session.command = "${lib.getExe (getFlakePkg inputs.tuigreet)} --sessions /etc/greetd/wayland-sessions --remember-session --animation doom";
};
environment.etc."greetd/wayland-sessions/wry.desktop".text = ''

View file

@ -7,6 +7,7 @@
programs.git = {
enable = true;
package = pkgs.gitMinimal;
config = {
user = {
name = "atagen";

View file

@ -1,9 +1,11 @@
{
pkgs,
config,
mkWrappers,
...
}:
let
inherit (mkWrappers pkgs) wrap;
ui = config.rice.roles config.rice.palette.hex;
zathuraConfigDir = pkgs.runCommand "zathura-config" { } ''
mkdir -p $out
@ -44,14 +46,10 @@ let
set index-active-bg "${ui.secondary}"
''} $out/zathurarc
'';
zathuraWrapped = pkgs.symlinkJoin {
zathuraWrapped = wrap {
name = "zathura";
paths = [ pkgs.zathura ];
nativeBuildInputs = [ pkgs.makeWrapper ];
postBuild = ''
wrapProgram $out/bin/zathura \
--add-flags "--config-dir=${zathuraConfigDir}"
'';
pkg = pkgs.zathura;
args = [ "--config-dir=${zathuraConfigDir}" ];
};
in
with pkgs;
@ -59,7 +57,7 @@ scope "apps" {
officeSuite = libreoffice;
mailClient = thunderbird;
noteTaking = obsidian;
ebookReader = foliate;
# ebookReader = foliate; # contains perl
pdfReader = zathuraWrapped;
calculator = mate-calc;
}

1902
graphical/foot-tabs.patch Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,13 @@
{
lib,
pkgs,
...
}:
{
xdg.autostart.enable = lib.mkForce false;
xdg.portal.extraPortals = lib.mkForce [ pkgs.xdg-desktop-portal-gtk ];
environment.pathsToLink = [
"/share/xdg-desktop-portal"
"/share/applications"

View file

@ -4,6 +4,6 @@
services.scx = {
enable = true;
scheduler = "scx_bpfland";
scheduler = "scx_lavd";
};
}

View file

@ -1,177 +0,0 @@
{
pkgs,
lib,
mainUser,
...
}:
let
clodTools = with pkgs; [
bash
procps
ripgrep
socat
bubblewrap
];
mkClod =
{
confDir ? null,
suffix ? null,
}:
let
version = "2.1.81";
runtimeDeps = lib.makeBinPath clodTools;
patchScript = pkgs.writeScript "patch-claude-src" ''
#!${pkgs.python3}/bin/python3
import re, sys
W = rb"[\w$]+"
data = open(sys.argv[1], "rb").read()
pat = (rb"let (" + W + rb")=(" + W + rb")\((" + W + rb'),"CLAUDE\.md"\);'
rb"(" + W + rb")\.push\(\.\.\.(" + W + rb')\(\1,"Project",([^)]+)\)\)')
def agents(m):
v, pj, d, a, lf, rest = [m.group(i) for i in range(1, 7)]
return (b'for(let _f of["CLAUDE.md","AGENTS.md"]){let ' + v + b"=" + pj
+ b"(" + d + b",_f);" + a + b".push(..." + lf + b"(" + v
+ b',"Project",' + rest + b"))}")
data, n = re.subn(pat, agents, data)
sys.stderr.write(f"AGENTS.md: {n} site(s)\n")
data = data.replace(
b'case"macos":return"/Library/Application Support/ClaudeCode"',
b'case"macos":return"/etc/claude-code"',
)
# Enable hard-disabled slash commands: /btw, /files, /tag
for anchor, label in [
(b'name:"btw",description:"Ask a quick side question', b"/btw"),
(b'name:"files",description:"List all files currently in context"', b"/files"),
(b'name:"tag",userFacingName', b"/tag"),
]:
pos = data.find(anchor)
if pos < 0:
sys.stderr.write(f"{label.decode()}: NOT FOUND\n"); continue
window = data[pos:pos+500]
patched = window.replace(b"isEnabled:()=>!1", b"isEnabled:()=>!0", 1)
data = data[:pos] + patched + data[pos+500:]
sys.stderr.write(f"{label.decode()}: enabled\n")
# Bypass e2() for thinkback (e2 returns false when DISABLE_TELEMETRY is set)
data = data.replace(
b'e2("tengu_thinkback")',
b'!0||"tengu_thinkback"',
)
sys.stderr.write("thinkback: force-enabled\n")
# Enable custom keybindings (qA default is false, flip to true)
data = data.replace(
b'qA("tengu_keybinding_customization_release",!1)',
b'qA("tengu_keybinding_customization_release",!0)',
)
sys.stderr.write("keybindings: force-enabled\n")
# Force-enable remote control / bridge feature gate
data = data.replace(
b'function ek(){return qA("tengu_ccr_bridge",!1)}',
b'function ek(){return!0} ',
)
sys.stderr.write("remote-control: force-enabled\n")
# Fix Deno-compile bridge spawn: Deno compiled binaries intercept --flags
# as V8 flags. Rewrite spawn to go through env(1) which breaks the Deno
# runtime's flag parsing.
data = data.replace(
b'let O=iHz(A.execPath,$,',
b'let O=iHz("env",["--",A.execPath,...$],',
)
sys.stderr.write("bridge-spawn: patched via env(1)\n")
# Kill claude-developer-platform bundled skill (~400 tokens/turn dead weight)
data = data.replace(
b'name:"claude-developer-platform",description:`',
b'name:"claude-developer-platform",isEnabled:()=>!1,description:`',
)
sys.stderr.write("claude-developer-platform: killed\n")
pat = (rb"context_window:\{total_input_tokens:(" + W + rb"\(\)),"
rb"total_output_tokens:(" + W + rb"\(\)),"
rb"context_window_size:(" + W + rb"),"
rb"current_usage:(" + W + rb"),"
rb"used_percentage:(" + W + rb")\.used,"
rb"remaining_percentage:\5\.remaining\}")
rl = re.search(rb"(" + W + rb')=\{status:"allowed",unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1\}', data)
m = re.search(pat, data)
if m and rl:
ci, co, sz, u, p, r = *[m.group(i) for i in range(1, 6)], rl.group(1)
data = data.replace(m[0],
b"context_window:{...(" + u + b"||{}),"
b"context_window_size:" + sz + b",current_usage:" + u + b","
b"used_percentage:" + p + b".used,remaining_percentage:" + p + b".remaining,"
b"rate_limit:" + r + b",s_in:" + ci + b",s_out:" + co + b"}")
open(sys.argv[1], "wb").write(data)
'';
in
pkgs.writeShellScriptBin "claude${lib.optionalString (suffix != null) "-${suffix}"}" ''
set -euo pipefail
export DISABLE_AUTOUPDATER=1
export DISABLE_INSTALLATION_CHECKS=1
export USE_BUILTIN_RIPGREP=0
export PATH="${runtimeDeps}:${pkgs.deno}/bin:$PATH"
CACHE="''${XDG_CACHE_HOME:-$HOME/.cache}/claude-code"
BIN="$CACHE/claude-${version}"
${lib.optionalString (confDir != null) "export CLAUDE_CONFIG_DIR=\"$HOME/${confDir}\""}
if [ ! -x "$BIN" ]; then
mkdir -p "$CACHE"
DENO_DIR="$CACHE/.deno"
export DENO_DIR
deno cache "npm:@anthropic-ai/claude-code@${version}"
${patchScript} "$DENO_DIR/npm/registry.npmjs.org/@anthropic-ai/claude-code/${version}/cli.js"
deno compile --allow-all --output "$BIN" "npm:@anthropic-ai/claude-code@${version}" 2>&1
rm -rf "$DENO_DIR"
fi
exec "$BIN" "$@"
'';
claude-code = mkClod { };
in
(scope "apps" {
"slop" = claude-code;
})
// {
# required for loader
programs.nix-ld = {
enable = true;
libraries = [ pkgs.stdenv.cc.cc.lib ];
};
# experiment with our own sandboxing
# security.yoke.wrappers =
# let
# basePaths = [
# "wrx=/home/${mainUser}/.claude.json:/home/${mainUser}/.claude-code:/home/${mainUser}/.cache/claude-code:$PWD/.claude"
# "rx=/"
# ];
# base = {
# package = claude-code;
# executable = "claude";
# retainEnv = true;
# unrestrictTcp = true;
# extraPackages = clodTools;
# };
# in
# {
# clod-cuck = base // {
# pathRules = basePaths + [ "rx=$PWD" ];
# };
# clod = base // {
# pathRules = basePaths ++ [
# "wrx=/home/${mainUser}"
# ];
# addPwd = true;
# unrestrictSockets = true;
# unrestrictSignals = true;
# };
# };
}

126
graphical/llm/launcher.nu Normal file
View file

@ -0,0 +1,126 @@
def detect-platform []: nothing -> string {
let os = $nu.os-info.name | str downcase
let arch = $nu.os-info.arch | str downcase
let norm_arch = match $arch {
"x86_64" | "x64" | "amd64" => "x64"
"aarch64" | "arm64" => "arm64"
_ => { error make { msg: $"unsupported arch: ($arch)" } }
}
match $os {
"linux" => {
let musl_ld = $"/lib/ld-musl-($arch).so.1"
let suffix = if ($musl_ld | path exists) { "-musl" } else { "" }
$"linux-($norm_arch)($suffix)"
}
"macos" | "darwin" => $"darwin-($norm_arch)"
"windows" => { error make { msg: "windows unsupported by this launcher" } }
_ => { error make { msg: $"unsupported os: ($os)" } }
}
}
def build-binary [version: string, binary_path: string, cache: string] {
let platform = detect-platform
let pkg = $"@anthropic-ai/claude-code-($platform)"
let tarball_url = $"https://registry.npmjs.org/($pkg)/-/claude-code-($platform)-($version).tgz"
let tgz_dir = $cache | path join "tgz"
mkdir $tgz_dir
let tgz = $tgz_dir | path join $"claude-code-($platform)-($version).tgz"
if not ($tgz | path exists) {
print --stderr $"(ansi cyan)fetch:(ansi reset) ($tarball_url)"
http get --raw $tarball_url | save --force --raw $tgz
}
let workdir = $cache | path join $"build-($version)"
rm -rf $workdir
mkdir $workdir
run-external $env._TAR "-xzf" $tgz "-C" $workdir
let native_bin = $workdir | path join "package" "claude"
if not ($native_bin | path exists) {
error make { msg: $"lift: ($native_bin) missing after tar extract" }
}
let cli = $workdir | path join "cli.cjs"
run-external $env._LIFT_SCRIPT $native_bin $cli
run-external $env._PATCH_SCRIPT $cli
# Bun's bundler keeps a handful of http/ws/schema libs as runtime-external.
# Deno has no equivalent provision — drop a package.json next to cli.cjs,
# resolve deps into a local node_modules/, and bundle that tree into the
# executable via --include.
cp --force $env._EXTERNAL_PACKAGE_JSON ($workdir | path join "package.json")
cd $workdir
$env.DENO_DIR = ($workdir | path join ".deno")
run-external $env._DENO "install" "--node-modules-dir=auto"
run-external $env._DENO "compile" "--allow-all" "--no-check" "--node-modules-dir=auto" "--include=node_modules" "--output" $binary_path "cli.cjs"
# nushell refuses to delete a directory you're currently inside
cd $cache
rm -rf $workdir
}
def main --wrapped [...args] {
let cache = $env
| get --optional "XDG_CACHE_HOME"
| default ($env.HOME | path join ".cache")
| path join "claude-code"
mkdir $cache
let config_dir = $env | get --optional "CLAUDE_CONFIG_DIR" | default (
$env
| get --optional "XDG_CONFIG_HOME"
| default ($env.HOME | path join ".config")
| path join "claude"
)
mkdir $config_dir
# Sync declarative settings into writable config dir
cp --force $env._SETTINGS_JSON ($config_dir | path join "settings.json")
let version = do {
let version_file = $cache | path join "latest-version"
let stale = try { (date now) - (ls $version_file | get 0.modified) > 6hr } catch { true }
if not $stale { return (try { open $version_file } catch { "" }) }
let version = try {
http get --max-time 5sec https://registry.npmjs.org/@anthropic-ai/claude-code/latest
| get version
} catch {
print --stderr $"(ansi yellow_bold)warn:(ansi reset) version cache stale, can't re-fetch"
return ""
}
try {
$version | save --force $version_file
}
$version
}
let binary_path = if ($version | is-empty) {
print --stderr $"(ansi yellow_bold)warn:(ansi reset) falling back to latest binary"
try {
glob ($cache | path join "claude-*") | sort | last
} catch {
print --stderr $"(ansi red_bold)error:(ansi reset) no binary found"
exit 67
}
} else {
$cache | path join $"claude-($version)"
}
if not ($binary_path | path exists) {
build-binary $version $binary_path $cache
}
$env.PATH = ($env.PATH | prepend ($env._RUNTIME_DEPS | split row ":"))
$env._ENV_JSON | load-env
exec $binary_path ...$args
}

View file

@ -0,0 +1,92 @@
from __future__ import annotations
# Extract the cli.js bundle from a bun --compile --bytecode executable.
#
# Starting with @anthropic-ai/claude-code 2.1.113 the npm package stopped
# shipping cli.js and instead publishes platform-specific tarballs that contain
# a bun-compiled ELF (~226 MB). The JavaScript is still fully embedded in the
# binary as plaintext — the @bytecode marker just means a V8 parse-cache lives
# alongside it, not instead of it.
#
# Layout of each CJS module inside the bun SEA payload:
# // @bun[ @bytecode] @bun-cjs\n
# (function(exports, require, module, __filename, __dirname) {<BODY>})\n
# \x00/$bunfs/root/<next-module-name>\x00...
#
# Claude Code ships three real modules in the tail region (past 0x6000000):
# the main cli (~12 MB), then two tiny native-loader stubs for the optional
# image-processor.node and audio-capture.node. Only the first is interesting.
import sys
from pathlib import Path
# Skip over .rodata / .text — those contain `// @bun` string literals (error
# messages, help text) that would confuse the scanner. The first real module
# sat at ~0xd333ec8 in 2.1.113; staying well below that survives future growth.
SCAN_FROM: int = 0x6000000
HEADERS: list[bytes] = [
b"// @bun @bytecode @bun-cjs\n(function(exports, require, module, __filename, __dirname) {",
b"// @bun @bun-cjs\n(function(exports, require, module, __filename, __dirname) {",
]
CJS_OPEN: bytes = b"(function(exports, require, module, __filename, __dirname) {"
CJS_END: bytes = b"})\n\x00"
def find_main_module(data: bytes) -> tuple[int, int]:
for header in HEADERS:
start = data.find(header, SCAN_FROM)
if start >= 0:
break
else:
sys.exit("lift: no bun CJS module header found past 0x6000000")
end = data.find(CJS_END, start)
if end < 0:
sys.exit("lift: could not find module terminator (})\\n\\x00)")
return start, end + 3 # include })\n, exclude trailing NUL
def unwrap(mod: bytes) -> bytes:
nl = mod.find(b"\n")
if nl < 0:
sys.exit("lift: module has no header newline")
body = mod[nl + 1 :]
if not body.startswith(CJS_OPEN):
sys.exit("lift: module does not open with expected CJS wrapper")
body = body[len(CJS_OPEN) :]
# tail is either `})\n` or `})`
if body.endswith(b"})\n"):
body = body[:-3]
elif body.endswith(b"})"):
body = body[:-2]
else:
sys.exit("lift: module does not end with `})` wrapper close")
return body
def main() -> None:
if len(sys.argv) != 3:
sys.exit("usage: lift-claude-bun <claude-binary> <output.cjs>")
binary = Path(sys.argv[1])
output = Path(sys.argv[2])
data = binary.read_bytes()
start, end = find_main_module(data)
body = unwrap(data[start:end])
# Sanity: the real claude-code cli.js always contains this legal banner.
if b"Anthropic" not in body[:4096]:
sys.exit("lift: extracted body is missing Anthropic banner — layout changed?")
output.write_bytes(body)
sys.stderr.write(
f"lifted {len(body):,} bytes from {binary.name} "
f"(module @ {start:#x}..{end:#x}) -> {output}\n"
)
if __name__ == "__main__":
main()

152
graphical/llm/llm.nix Normal file
View file

@ -0,0 +1,152 @@
{
lib,
pkgs,
...
}:
let
inherit (lib) optionals;
settings = {
"$schema" = "https://json.schemastore.org/claude-code-settings.json";
env = {
CLAUDE_BASH_NO_LOGIN = "1";
CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING = "1";
CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY = "1";
CLAUDE_CODE_DISABLE_TERMINAL_TITLE = "1";
CLAUDE_CODE_EAGER_FLUSH = "1";
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1";
CLAUDE_CODE_FORCE_GLOBAL_CACHE = "1";
CLAUDE_CODE_HIDE_ACCOUNT_INFO = "1";
CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY = "20";
CLAUDE_CODE_PLAN_V2_AGENT_COUNT = "5";
CLAUDE_CODE_PLAN_V2_EXPLORE_AGENT_COUNT = "5";
DISABLE_AUTO_COMPACT = "1";
DISABLE_AUTOUPDATER = "1";
DISABLE_COST_WARNINGS = "1";
DISABLE_ERROR_REPORTING = "1";
DISABLE_INSTALLATION_CHECKS = "1";
DISABLE_TELEMETRY = "1";
ENABLE_MCP_LARGE_OUTPUT_FILES = "1";
ENABLE_TOOL_SEARCH = "auto:5";
MAX_THINKING_TOKENS = "31999";
MCP_CONNECTION_NONBLOCKING = "1";
UV_THREADPOOL_SIZE = "16";
};
attribution = {
commit = "";
pr = "";
};
permissions = {
allow = [
"Read"
];
defaultMode = "bypassPermissions";
};
statusLine = {
type = "command";
command = "/etc/claude/statusline-command.nu";
};
enabledPlugins = {
"clangd-lsp@claude-plugins-official" = true;
"rust-analyzer-lsp@claude-plugins-official" = true;
"context7@claude-plugins-official" = true;
"code-review@claude-plugins-official" = true;
"linear@claude-plugins-official" = true;
};
skipWebFetchPreflight = true;
spinnerVerbs = {
mode = "replace";
verbs = [
"Redeeming"
"Clodding"
"Tokenmaxxing"
"Slopping"
"Clanking"
"Churning"
"Forgetting"
"Splurging"
"Ignoring GPL"
"Increasing ram prices"
];
};
cleanupPeriodDays = 90;
alwaysThinkingEnabled = true;
remoteControlAtStartup = true;
showClearContextOnPlanAccept = true;
skipDangerousModePermissionPrompt = true;
};
settingsJson = pkgs.writeText "claude-settings.json" (builtins.toJSON settings);
runtimeDeps = lib.makeBinPath ([
pkgs.bash
pkgs.procps
pkgs.ripgrep
pkgs.bubblewrap
pkgs.socat
]);
patchScript = pkgs.writeScript "patch-claude-src" ''
#!${pkgs.python3}/bin/python3
${builtins.readFile ./patch-claude-src.py}
'';
liftScript = pkgs.writeScript "lift-claude-bun" ''
#!${pkgs.python3}/bin/python3
${builtins.readFile ./lift-claude-bun.py}
'';
externalPackageJson = pkgs.writeText "claude-code-external-package.json" (
builtins.toJSON {
name = "claude-code-lifted";
type = "commonjs";
dependencies = {
ws = "^8";
undici = "^6";
node-fetch = "^3";
ajv = "^8";
ajv-formats = "^3";
yaml = "^2";
};
}
);
mkClod =
suffix:
let
finalSuffix = "-${suffix}";
in
pkgs.writeScriptBin "claude${finalSuffix}" ''
#!${pkgs.nushell}/bin/nu --no-config-file
$env._SETTINGS_JSON = "${settingsJson}"
$env._DENO = "${pkgs.deno}/bin/deno"
$env._PATCH_SCRIPT = "${patchScript}"
$env._LIFT_SCRIPT = "${liftScript}"
$env._EXTERNAL_PACKAGE_JSON = "${externalPackageJson}"
$env._TAR = "${pkgs.gnutar}/bin/tar"
$env._RUNTIME_DEPS = "${runtimeDeps}"
$env._ENV_JSON = ${lib.strings.toJSON settings.env}
$env.CLAUDE_CONFIG_DIR = ("~/.claude${finalSuffix}" | path expand)
${builtins.readFile ./launcher.nu}
'';
in
{
environment.systemPackages = [
(mkClod "lillis")
(mkClod "amaan")
];
environment.etc."claude/statusline-command.nu".source = ./statusline-command.nu;
programs.nix-ld.enable = true;
}

View file

@ -0,0 +1,231 @@
from __future__ import annotations
import re
import sys
from collections.abc import Callable
from pathlib import Path
from typing import Union
type Replacement = Union[bytes, Callable[[re.Match[bytes]], bytes]]
W: bytes = rb"[\w$]+"
# Qualified name: matches `FN` and also `NS.FN` (e.g. `Lf.join`, `Oc7.spawn`).
# Since 2.1.113 bun's bundler emits more member-style calls for path/spawn helpers.
Q: bytes = rb"[\w$]+(?:\.[\w$]+)*"
data: bytes = Path(sys.argv[1]).read_bytes()
SEARCH_WINDOW: int = 500
def log(msg: str) -> None:
sys.stderr.write(msg + "\n")
def patch(label: str, pattern: bytes, replacement: Replacement) -> None:
global data
data, n = re.subn(pattern, replacement, data)
log(f"{label} ({n})")
def replace(label: str, old: bytes, new: bytes) -> None:
global data
n: int = data.count(old)
if n == 0:
log(f"{label}: NOT FOUND")
return
data = data.replace(old, new)
log(f"{label} ({n})")
def flip_gates(gates: list[tuple[bytes, str]]) -> None:
"""Flip all gate defaults from false to true in a single regex pass."""
global data
gate_keys: list[bytes] = [g for g, _ in gates]
labels: dict[bytes, str] = dict(gates)
alternation: bytes = b"|".join(re.escape(g) for g in gate_keys)
pat: bytes = W + rb'\("(' + alternation + rb')",!1\)'
flipped: set[bytes] = set()
def replacer(m: re.Match[bytes]) -> bytes:
flipped.add(m.group(1))
return m[0].replace(b",!1)", b",!0)")
data, n = re.subn(pat, replacer, data)
log(f"feature gates: {n} flipped across {len(flipped)} gates")
for key in gate_keys:
status = "ok" if key in flipped else "MISSED"
log(f" {labels[key]} [{status}]")
# --- AGENTS.md support ---
# The CLAUDE.md loader only reads CLAUDE.md. Patch it to also load AGENTS.md
# from the same directories. Pattern: let VAR=ME(DIR,"CLAUDE.md");ARR.push(...await XE(VAR,"Project",ARG,BOOL))
agents_pat: bytes = (
rb"let (" + W + rb")=(" + Q + rb")\((" + W + rb'),"CLAUDE\.md"\);'
rb"(" + W + rb")\.push\(\.\.\.await (" + W + rb")\(\1,\"Project\",(" + W + rb"),(" + W + rb")\)\)"
)
def agents_repl(m: re.Match[bytes]) -> bytes:
var, join_fn, dir_, arr, load_fn, arg, flag = [m.group(i) for i in range(1, 8)]
return (
b'for(let _f of["CLAUDE.md","AGENTS.md"]){let '
+ var + b"=" + join_fn + b"(" + dir_ + b",_f);"
+ arr + b".push(...await " + load_fn + b"(" + var + b',"Project",' + arg + b"," + flag + b"))}"
)
patch("agents.md loader", agents_pat, agents_repl)
# --- macOS config path ---
replace(
"macOS config path",
b'case"macos":return"/Library/Application Support/ClaudeCode"',
b'case"macos":return"/etc/claude-code"',
)
# --- Enable hard-disabled slash commands ---
slash_commands: list[tuple[bytes, str]] = [
(b'name:"btw",description:"Ask a quick side question', "/btw"),
(b'name:"bridge-kick",description:"Inject bridge failure states', "/bridge-kick"),
(b'name:"files",description:"List all files currently in context"', "/files"),
]
for anchor, label in slash_commands:
pos: int = data.find(anchor)
if pos < 0:
log(f"slash command {label}: NOT FOUND")
continue
window: bytes = data[pos : pos + SEARCH_WINDOW]
patched: bytes = window.replace(b"isEnabled:()=>!1", b"isEnabled:()=>!0", 1)
if patched == window:
log(f"slash command {label}: isEnabled not found in window")
continue
data = data[:pos] + patched + data[pos + SEARCH_WINDOW :]
log(f"slash command {label}: enabled")
# --- Bypass telemetry gate in feature flag checker ---
# The chain is: h8(featureGate) bails to default if !Qo(); Qo()=Ew6();
# Ew6()=!Cq6(); Cq6() returns true when on bedrock/vertex/foundry OR when
# user-facing telemetry is disabled (s_1()/equivalent). Drop the trailing
# telemetry-disabled check so feature gates still resolve with
# DISABLE_TELEMETRY=1 while preserving the bedrock/vertex/foundry detection.
# Anchor on the stable env-var literal CLAUDE_CODE_USE_BEDROCK; the obfuscated
# function name (Cq6) and the trailing wrapper name (s_1) both rotate.
patch(
"telemetry gate (drop telemetry-disabled check)",
(
rb"function (" + W + rb")\(\)\{return (" + W + rb")\(process\.env\.CLAUDE_CODE_USE_BEDROCK\)"
rb"\|\|\2\(process\.env\.CLAUDE_CODE_USE_VERTEX\)"
rb"\|\|\2\(process\.env\.CLAUDE_CODE_USE_FOUNDRY\)"
rb"\|\|" + W + rb"\(\)\}"
),
lambda m: re.sub(rb"\|\|" + W + rb"\(\)\}$", b"||!1}", m[0]),
)
# --- Restore 1h prompt cache TTL when telemetry is off ---
# https://github.com/anthropics/claude-code/issues/45381
# The GrowthBook allowlist for "ttl":"1h" cache_control falls back to the
# default object when telemetry is off. Anthropic now ships
# {allowlist:["repl_main_thread*","sdk","auto_mode"]} as the default (up
# from the broken {} in earlier versions), so the TUI and SDK already get
# 1h TTL — but batch agents and less-common query sources still miss.
# Widen the default to ["*"] so everything matches.
patch(
"1h prompt cache TTL fallback",
rb'(' + W + rb')\("tengu_prompt_cache_1h_config",\{allowlist:\[[^\]]+\]\}\)\.allowlist\?\?\[\]',
lambda m: m[1] + b'("tengu_prompt_cache_1h_config",{allowlist:["*"]}).allowlist??[]',
)
# --- Fix Deno-compile bridge spawn ---
# Deno-compiled binaries eat --flags as V8 args, so we route spawns through
# env(1) to pass them as normal CLI flags instead.
patch(
"deno bridge spawn fix",
rb"let (" + W + rb")=(" + Q + rb")\((" + W + rb")\.execPath,(" + W + rb"),",
lambda m: (
b"let "
+ m[1]
+ b"="
+ m[2]
+ b'("env",["--",'
+ m[3]
+ b".execPath,..."
+ m[4]
+ b"],"
),
)
# --- Flip feature gates ---
# DISABLE_TELEMETRY=1 prevents GrowthBook feature flag resolution, so all gates
# fall back to their hardcoded defaults (false). Flip them to true.
Gate = tuple[bytes, str]
core_gates: list[Gate] = [
(b"tengu_ccr_bridge", "remote control"),
(b"tengu_bridge_system_init", "bridge SDK init on connect"),
(b"tengu_bridge_client_presence_enabled", "bridge presence heartbeats"),
(b"tengu_bridge_requires_action_details", "bridge rich tool-use payloads"),
(b"tengu_remote_backend", "remote backend"),
(b"tengu_immediate_model_command", "instant /model switching"),
(b"tengu_fgts", "fine-grained tool streaming"),
(b"tengu_auto_background_agents", "background agent timeout"),
(b"tengu_plan_mode_interview_phase", "plan mode interview"),
(b"tengu_surreal_dali", "scheduled agents/cron"),
]
memory_gates: list[Gate] = [
# (b"tengu_session_memory", "session memory"), # auto-memory; pollutes unrelated convos
(b"tengu_pebble_leaf_prune", "message pruning"),
(b"tengu_herring_clock", "team memory directory"),
(b"tengu_passport_quail", "typed combined memory prompts"),
(b"tengu_paper_halyard", "memory dedup in nested dirs"),
]
ux_gates: list[Gate] = [
(b"tengu_coral_fern", "grep hints in prompt"),
(b"tengu_kairos_brief", "brief output mode"),
(b"tengu_destructive_command_warning", "destructive command warnings"),
(b"tengu_amber_prism", "permission denial context"),
(b"tengu_hawthorn_steeple", "context windowing"),
(b"tengu_loud_sugary_rock", "Opus 4.7 terse output guidance"),
(b"tengu_verified_vs_assumed", "verified-vs-assumed reporting"),
(b"tengu_pewter_brook", "fullscreen TUI default"),
]
tool_gates: list[Gate] = [
(b"tengu_chrome_auto_enable", "auto-enable chrome devtools"),
(b"tengu_plum_vx3", "web search reranking"),
# (b"tengu_moth_copse", "relevant memory recall"), # auto-recall; pollutes unrelated convos
(b"tengu_cork_m4q", "batch command processing"),
(b"tengu_harbor", "plugin marketplace"),
(b"tengu_harbor_permissions", "plugin permissions"),
(b"tengu_relay_chain_v1", "parallel command chaining guidance"),
(b"tengu_edit_minimalanchor_jrn", "Edit tool minimal-anchor instructions"),
(b"tengu_slate_reef", "Read tool clearer offset/limit docs"),
(b"tengu_otk_slot_v1", "output-token escalation for complex tasks"),
(b"tengu_onyx_basin_m1k", "subagent tool-result truncation"),
(b"tengu_sub_nomdrep_q7k", "block subagent report .md writes"),
(b"tengu_amber_sentinel", "Monitor tool for streaming bg scripts"),
(b"tengu_miraculo_the_bard", "skip penguin-mode startup prefetch"),
(b"tengu_noreread_q7m_velvet", "sharper 'wasted read' feedback"),
]
flip_gates(core_gates + memory_gates + ux_gates + tool_gates)
# --- Bump background agent timeout from 120s to 240s ---
patch(
"background agent timeout",
rb'"tengu_auto_background_agents",![01]\)\)return 120000',
lambda m: m[0].replace(b"120000", b"240000"),
)
Path(sys.argv[1]).write_bytes(data)

View file

@ -0,0 +1,137 @@
#!/usr/bin/env -S nu --no-config-file
def format-duration [ms: int] {
let total_s = $ms // 1000
let h = $total_s // 3600
let m = ($total_s mod 3600) // 60
let s = $total_s mod 60
if $h > 0 {
$"($h)h($m | fill -a r -w 2 -c '0')m($s | fill -a r -w 2 -c '0')s"
} else if $m > 0 {
$"($m)m($s | fill -a r -w 2 -c '0')s"
} else {
$"($s)s"
}
}
def color-for-pct [pct: number] {
let pct_int = $pct | math floor | into int
if $pct_int >= 80 {
"\e[31m"
} else if $pct_int >= 50 {
"\e[33m"
} else {
"\e[32m"
}
}
def format-rate-limits [input: record] {
let session_pct = try { $input | get rate_limits.five_hour.used_percentage } catch { null }
let week_pct = try { $input | get rate_limits.seven_day.used_percentage } catch { null }
let session_part = if $session_pct != null {
let c = color-for-pct $session_pct
let v = $session_pct | math round --precision 0 | into int
$"session: ($c)($v)%\e[0m"
} else { "" }
let week_part = if $week_pct != null {
let c = color-for-pct $week_pct
let v = $week_pct | math round --precision 0 | into int
$"week: ($c)($v)%\e[0m"
} else { "" }
[$session_part $week_part] | where {|x| $x | is-not-empty} | str join " "
}
# --- Main ---
let input = (^cat | from json)
let usage_info = format-rate-limits $input
let model_name = ($input | get model?.display_name? | default ($input | get model?.id? | default "unknown"))
let used_pct = ($input | get context_window?.used_percentage? | default null)
let total_cost = ($input | get cost?.total_cost_usd? | default 0)
let total_input = ($input | get context_window?.s_in? | default ($input | get context_window?.total_input_tokens? | default 0))
let total_output = ($input | get context_window?.s_out? | default ($input | get context_window?.total_output_tokens? | default 0))
let duration_ms = ($input | get cost?.total_duration_ms? | default 0)
let api_duration_ms = ($input | get cost?.total_api_duration_ms? | default 0)
let lines_added = ($input | get cost?.total_lines_added? | default 0)
let lines_removed = ($input | get cost?.total_lines_removed? | default 0)
let exceeds_200k = ($input | get exceeds_200k_tokens? | default false)
let cache_read = ($input | get context_window?.cache_read_tokens? | default 0)
let cache_create = ($input | get context_window?.cache_creation_tokens? | default 0)
let total_tokens = $total_input + $total_output
def format-tokens [n: int] {
if $n >= 1_000_000 {
$"($n / 1_000_000.0 | math round --precision 1)M"
} else if $n >= 1_000 {
$"($n / 1_000.0 | math round --precision 1)k"
} else {
$"($n)"
}
}
let in_display = (format-tokens ($total_input | into int))
let out_display = (format-tokens ($total_output | into int))
let tok_display = $"($in_display)/($out_display)"
let cache_total = $cache_read + $cache_create
let cache_display = if $cache_total > 0 {
let cache_pct = ($cache_read * 100 / $cache_total | math round --precision 0 | into int)
let cache_color = if $cache_pct >= 70 {
"\e[32m"
} else if $cache_pct >= 40 {
"\e[33m"
} else {
"\e[31m"
}
$" cache:($cache_color)($cache_pct)%\e[0m"
} else { "" }
let context_display = if $used_pct != null {
let color = color-for-pct $used_pct
let pct_str = $used_pct | math round --precision 1
$"($color)($pct_str)%\e[0m"
} else { "--" }
let cost_cents = ($total_cost * 100 | math round | into int)
let cost_dollars = $cost_cents // 100
let cost_frac = ($cost_cents mod 100 | math abs | into string | fill -a r -w 2 -c '0')
let cost_display = $"$($cost_dollars).($cost_frac)"
let elapsed_display = (format-duration ($duration_ms | into int))
let wait_display = (format-duration ($api_duration_ms | into int))
let churn_display = $"\e[32m+($lines_added)\e[0m/\e[31m-($lines_removed)\e[0m"
let marker_200k = if $exceeds_200k { " | \e[31m!200k\e[0m" } else { "" }
def format-cwd [dir: string] {
if ($dir | is-empty) { return "" }
let home = ($env.HOME? | default "")
let display = if ($home | is-not-empty) and ($dir | str starts-with $home) {
let rel = ($dir | str replace $home "" | str trim -l -c '/')
$"~/($rel)"
} else {
$dir
}
let parts = ($display | split row "/")
let shortened = if ($parts | length) <= 5 {
$display
} else {
let tail = ($parts | last 5 | str join "/")
$"…/($tail)"
}
$shortened
}
let cwd_raw = ($input | get workspace?.current_dir? | default "")
let cwd_display = if ($cwd_raw | is-not-empty) {
let formatted = (format-cwd $cwd_raw)
$" | ($formatted)"
} else { "" }
let quota_section = if ($usage_info | is-not-empty) {
" | (usage) " + $usage_info
} else { "" }
print -n $"($model_name) | Ctx: ($context_display) | ($tok_display)($cache_display) | ($cost_display) | t:($elapsed_display) w:($wait_display) | ($churn_display)($marker_200k)($quota_section)($cwd_display)"

View file

@ -1,9 +1,11 @@
{
config,
pkgs,
mkWrappers,
...
}:
let
inherit (mkWrappers pkgs) wrap;
ui = config.rice.roles config.rice.palette.hex;
imvConfig = pkgs.writeText "imv-config" ''
[options]
@ -12,14 +14,10 @@ let
overlay_text_color=${ui.fg}
overlay_background_color=${ui.surface}
'';
imvWrapped = pkgs.symlinkJoin {
imvWrapped = wrap {
name = "imv";
paths = [ pkgs.imv ];
nativeBuildInputs = [ pkgs.makeWrapper ];
postBuild = ''
wrapProgram $out/bin/imv \
--set imv_config "${imvConfig}"
'';
pkg = pkgs.imv;
envs = { imv_config = "${imvConfig}"; };
};
in
with pkgs;

View file

@ -20,6 +20,7 @@ let
--set XDG_CONFIG_HOME "${rbwConfigDir}"
done
'';
meta.mainProgram = "rbw";
};
in
{

View file

@ -10,12 +10,8 @@
let
inherit (config) rice;
in
(with pkgs.kdePackages; [
[
pkgs.gtk-engine-murrine
breeze
breeze.qt5
])
++ [
rice.gtk-theme.package
rice.fonts.sans.package
rice.icons.package
@ -27,7 +23,9 @@
config = {
theme = {
colorScheme =
let ui = config.rice.roles config.rice.palette.hex; in
let
ui = config.rice.roles config.rice.palette.hex;
in
pkgs.runCommand "theme.colors" { } ''
sed \
-e "s|@bg@|${ui.bg}|g" \
@ -43,7 +41,7 @@
> $out
'';
iconTheme = config.rice.icons.name;
style = "breeze";
style = "fusion";
font = with config.rice.fonts.sans; {
family = name;
size = size;

View file

@ -2,55 +2,74 @@
pkgs,
lib,
config,
mkWrappers,
...
}:
(scope "apps.terminal" <| pkgs.foot)
// scope "programs.foot" {
enable = true;
enableFishIntegration = true;
settings = {
main =
let
font =
config.rice.fonts.monospace.name + ":size=" + (builtins.toString config.rice.fonts.monospace.size);
in
{
inherit font;
font-bold = font;
font-italic = font;
};
bell = {
system = true;
urgent = true;
notify = true;
visual = true;
};
colors-dark =
let
pal = config.rice.palette.shortHex;
in
{
background = pal.util.bg;
foreground = pal.util.fg;
regular0 = pal.normal.black;
regular1 = pal.normal.red;
regular2 = pal.normal.green;
regular3 = pal.normal.yellow;
regular4 = pal.normal.blue;
regular5 = pal.normal.magenta;
regular6 = pal.normal.cyan;
regular7 = pal.normal.white;
bright0 = pal.bright.black;
bright1 = pal.bright.red;
bright2 = pal.bright.green;
bright3 = pal.bright.yellow;
bright4 = pal.bright.blue;
bright5 = pal.bright.magenta;
bright6 = pal.bright.cyan;
bright7 = pal.bright.white;
let
inherit (mkWrappers pkgs) wrap;
font =
config.rice.fonts.monospace.name + ":size=" + (builtins.toString config.rice.fonts.monospace.size);
pal = config.rice.palette.shortHex;
selection-foreground = pal.util.fg_sel;
selection-background = pal.util.bg_sel;
};
footConfig = pkgs.writeText "foot.ini" ''
[main]
font=${font}
font-bold=${font}
font-italic=${font}
[bell]
system=yes
urgent=yes
notify=yes
visual=yes
[colors-dark]
background=${pal.util.bg}
foreground=${pal.util.fg}
regular0=${pal.normal.black}
regular1=${pal.normal.red}
regular2=${pal.normal.green}
regular3=${pal.normal.yellow}
regular4=${pal.normal.blue}
regular5=${pal.normal.magenta}
regular6=${pal.normal.cyan}
regular7=${pal.normal.white}
bright0=${pal.bright.black}
bright1=${pal.bright.red}
bright2=${pal.bright.green}
bright3=${pal.bright.yellow}
bright4=${pal.bright.blue}
bright5=${pal.bright.magenta}
bright6=${pal.bright.cyan}
bright7=${pal.bright.white}
selection-foreground=${pal.util.fg_sel}
selection-background=${pal.util.bg_sel}
[tabs]
enabled=yes
position=bottom
inherit-cwd=yes
style=gradient
label-padding=15
height=26
background=${pal.bright.black}
foreground=${pal.util.fg}
active-background=${pal.util.bg_sel}
active-foreground=${pal.util.fg_sel}
layout=floating
tab-width=180
tab-padding=10
margin=8
'';
footPatched = pkgs.foot.overrideAttrs (old: {
patches = (old.patches or [ ]) ++ [ ./foot-tabs.patch ];
});
foot = wrap {
name = "foot";
pkg = footPatched;
args = [ "--config=${footConfig}" ];
};
}
in
scope "apps.terminal" foot