commit 693822ad5f29a973d6d14912c7852ae775f0f918 Author: Coja Date: Mon Nov 9 18:19:14 2026 +0100 dots: public mirror (history reset after licence cleanup) diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..55742dc --- /dev/null +++ b/.editorconfig @@ -0,0 +1,28 @@ +# Shell formatting for this repo. +# +# Both `shfmt` and the Claude format hook (common/.config/claude/hooks/format.py, which only +# runs shfmt/fish_indent where an .editorconfig opts in) read this file, so the policy and the +# tool that enforces it live in one place. Neovim reads it natively too. +# +# The settings were picked to stay as close as possible to how these scripts were already +# written by hand: 2-space indent, `case` arms indented under `case`, and `&&`/`||` starting +# the wrapped line rather than trailing the one before it (binary_next_line, which reproduces +# the existing `\` continuations exactly). shfmt still rewrites +# a few things no option controls — one-line `case x) a; b ;;` arms and `{ a; b; }` guards +# are split across lines, and `> file` loses its space — which is the one-time cost of +# having a formatter own the layout instead of maintaining it by hand. +# +# `keep_padding` is deliberately NOT set: it is deprecated in shfmt, and it indents the +# statements it splits by the padding column, producing a cascading staircase. +# +# Scoped to shell on purpose — there is no [*] section, so the repo's other filetypes are +# untouched (a [*] block would retune all of them in any editorconfig-aware editor, and +# would also switch on the hook's fish_indent for every fish file). + +root = true + +[{*.sh,dotsync,dotpub}] +indent_style = space +indent_size = 2 +switch_case_indent = true +binary_next_line = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6e410d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,46 @@ +# Secrets / local-only (matched at any depth) +secrets.fish +fish_variables +greet.txt +settings.local.json + +# pi agent runtime + machine-local auth/state +**/.pi/agent/auth.json +**/.pi/agent/sessions/ +**/.pi/agent/bin/ +**/.pi/agent/git/ +**/.pi/agent/npm/ +**/.pi/agent/trust.json + +# tmux plugins (tpm-managed, not vendored) +**/tmux/plugins/ + +# HyDE generated theme + wallpaper assets (per-machine, huge — bloated the old repo to 255MB) +**/hyde/themes/ +**/wallpapers/ + +# Claude Code project dir (worktrees, local settings, history) — never part of the dotfiles +.claude/ + +# backups / logs / package noise / os +*.bak +*.bak.* +*.log +package-lock.json +__pycache__/ +**/hypr/themes/ +# HyDE writes these at theme-apply time (sourced by animations/theme.conf & hyprlock/theme.conf) +**/hypr/animations/HyDE.conf +**/hypr/hyprlock/HyDE.conf + +# HyDE generates waybar's include list per machine, with ABSOLUTE $HOME paths — the committed copy +# carried fl's /home/anon into every gui host, where it resolved to nothing. Let each box write it. +**/waybar/includes/includes.json + +# dconf binary db — if stow ever folds ~/.config/dconf into a dir symlink on a fresh +# host, the dconf daemon writes the user db next to the tracked profile, into the repo. +gui/.config/dconf/hyde_hyprland + +# llama.cpp router bench ledgers — generated next to bench.py, per-machine (fl/lw/wm) +**/llamacpp/bench-results.md +**/llamacpp/bench-history.md diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..7c2f5bc --- /dev/null +++ b/.ignore @@ -0,0 +1,12 @@ +# Search config for THIS repo only (ripgrep / fd / telescope read .ignore). +# +# Everything this repo holds lives in dotfiles and dotdirs — common/.config, gui/.config, +# common/.pi, common/.bashrc — which rg and fd skip by default, so an unqualified search +# here returned nothing at all. Un-hide them, then put back the two dirs that would swamp +# every result: negating .* alone drags in the whole of .git, and .claude/worktrees holds +# entire checkouts of this same repo (background sessions create them), so every hit would +# appear several times over. Scoped to this directory tree; searches elsewhere on the +# machine are unaffected. +!.* +.git/ +.claude/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9d532de --- /dev/null +++ b/LICENSE @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + dots + Copyright (C) 2026 coja + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + dots Copyright (C) 2026 coja + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . diff --git a/README.md b/README.md new file mode 100644 index 0000000..3190d17 --- /dev/null +++ b/README.md @@ -0,0 +1,264 @@ +# dots + +Unified dotfiles for all machines: one shared base + per-host overlays, deployed with +[GNU Stow](https://www.gnu.org/software/stow/). + +## Layout + +Every top-level directory is a Stow *package* (they all share one stow dir, which `--override` +requires). `bin/` holds repo tooling and is **not** a package (never stowed): + +``` +common/ # shared everywhere (mirrors $HOME): fish, nvim, bat, btop, tmux, pi, claude, presenterm, ... +gui/ # GUI configs shared by graphical hosts: hypr, waybar, kitty, alacritty, mpv, zellij +wm/ # desktop: 4K monitors, NVIDIA, cloud LLM (duskadiy), work aliases +lw/ # laptop: no NVIDIA, roaming VPNs, network/LLM tools +fl/ # KDE Plasma box (no Hyprland session): llamacpp, whisper, evremap +bin/ # tooling (not a stow package): install.sh companions +install.sh +``` + +A **headless** (terminal-only) machine has no overlay package — it runs `common` only. Mark any box +headless with `touch ~/.config/dots-headless` (a machine-local, hostname-independent marker); it then +skips `gui` too, so the same terminal-only setup replicates across any number of machines. In other +words `common` *is* the headless baseline; `gui` and the host packages layer graphical machines on top. +Run it as a bare `./install.sh` — never `./install.sh common` (`common`/`gui` are layers, not hosts, +and install.sh refuses them). + +### How it deploys + +Deploy order is `common → gui → `; later layers win (the host package is stowed last with +`--override`, so a host file replaces the common/gui file at the same path). Stow runs with +`--no-folding`, so each *file* is symlinked individually (directories stay real) — this is what lets +a host override a single file in a shared dir without shadowing the rest. + +**Editing a config edits the repo copy directly** (it's a symlink) — no deploy step. You only re-run +`install.sh` when files are **added or removed** (to create/prune symlinks). See **Syncing** below. + +The repo must be cloned to **`~/.dots`** (the relative `../.dots` symlink convention). + +### Which host package a machine deploys + +**Hostname is not the authority** — the machine remembers its own choice, so several boxes can deploy +the same overlay without sharing a hostname. `install.sh` resolves the host as: + +1. the explicit argument (`./install.sh wm`), +2. else the name in **`~/.config/dots-host`** — written by `install.sh` itself on every run that + resolved a real package, so a one-time `./install.sh ` is all the setup there is, +3. else `hostname -s`, purely as a convenience guess for boxes where the two happen to agree. + +`~/.config/dots-host` is a machine-local, hand-editable one-word file — the sibling of the +`dots-headless` marker above. It is what makes **`bin/dotsync` correct**: dotsync re-links +automatically and has no argument to pass, so without a recorded host it could only guess. Switching +a machine to another overlay is just `./install.sh ` — the previously recorded host is +unstowed first, so the base layers don't collide with its leftover links. + +Mismatched hostnames used to fail in a way worth recognizing: `./install.sh` on a box whose hostname +matches no package deploys `common`, aborts `gui` on every file the real overlay owns +(`existing target is stowed to a different package`) and skips the overlay entirely — a loud +`exit 1`, but a half-applied one, where newly added files silently get no symlink. + +## Install (new machine) + +```fish +sudo pacman -S stow +git clone ~/.dots +cd ~/.dots +./install.sh wm # name the host package once — it is remembered (see above) +``` + +`./install.sh -h` lists all options: `-n` dry-run, `-a` adopt (first run), `-D` unstow (revert), +`-h` help. GUI hosts also need **HyDE installed** first — see *HyDE dependency* below. + +Once per machine afterwards: `:Lazy restore` inside nvim (`restore` obeys the shared +`lazy-lock.json` pins; `sync`/`update` would rewrite them). +nvim's treesitter (`main` branch) builds parsers via the `tree-sitter` CLI — `pacman -S +tree-sitter-cli` first, or `:TSInstallAll` fails with `ENOENT ... 'tree-sitter'`. + +### First run on a machine that still has real config files + +Stow **aborts the whole package on the first conflict** (one real file blocks *everything* in +`common`), and refuses to clobber real files without `--adopt` — you'll see +`cannot stow … since neither a link nor a directory`. Adopt them, review, then keep the repo's +versions: + +```fish +cd ~/.dots +git status # make sure the repo is clean first (see the restore caveat) +./install.sh -a # --adopt: pull existing files into the repo, symlink them back +git diff --stat # what this machine had vs the repo (review the drift!) +git restore . # discard adopted content, keep the repo versions +``` + +`--adopt` overwrites the repo copies with the machine's files, so `git restore .` is what keeps the +repo versions. Cautions: adopted changes can land under `common/`/`gui/` even when host-specific, and +`git restore .` drops **all** uncommitted edits — so commit/stash anything you want first. To keep a +genuine machine change (e.g. custom pyradio `stations.csv`), hand-copy it into the right package +instead of restoring that path. + +## Syncing (day-to-day) + +Because configs are symlinks into the repo, **you almost never run `install.sh` to sync**: + +- **Pull/propagate edits:** `cd ~/.dots && git pull` — changes are live in place instantly. No + re-stow, so **no symlink churn and no app reloads** (kitty etc. keep runtime state). +- **`bin/dotsync`** does this safely: `git pull`, then re-link via `install.sh` **only if** the pull + added/removed/renamed files (pure edits skip the re-stow). `dotsync -n` previews incoming changes. +- **`install.sh` is a (re)deploy tool, not a sync tool** — its `stow -R` deletes+recreates every + symlink, which is what makes apps reload. Only needed for the initial link or when files are + added/removed. +- **Never `stow` the repo root** (`stow .dots`, `stow */`) — it folds package dirs into `~` as stray + `~/common`, `~/gui`, … symlinks. `install.sh` only ever links package *contents*. +- **New host:** create a top-level `/` package (at least a `host.fish`), commit, then + `./install.sh ` (naming it once records it — later runs and dotsync need no argument). + If it's terminal-only, skip the package and just `touch ~/.config/dots-headless` (it runs + `common` only). + +## Tooling (`bin/`) + +| Command | What it does | +|---|---| +| `./install.sh [host]` | Deploy `common → gui → `. Host = arg, else `~/.config/dots-host`, else `hostname -s`; the resolved host is recorded there. Flags: `-n` dry-run, `-a` adopt (first run), `-D`/`--unstow` revert (remove this host's symlinks; repo + real files kept), `-h` help. Self-heals: headless hosts get any stray `gui` unstowed, a previously recorded host is released before re-deploying; fails loudly (exit 1) if a package couldn't stow. | +| `./bin/dotsync [-n\|host]` | Sync with least churn: `git pull`, re-stow only if files were added/removed (via `install.sh`, using the recorded host). | +| `./bin/reconcile-hyde.sh [-i\|--relink] [host]` | After a HyDE update overwrote `~/.config/hypr`, reconcile HyDE's new files against your dots versions (report / `-i` keep·take·merge each / `--relink` re-symlink). | + +## How per-host differences are expressed + +| Difference | Mechanism | +|---|---| +| Monitors | `/.config/hypr/host.lua` (`hl.monitor` + workspace pins; loaded by the shared `hyprland.lua`) | +| NVIDIA | the NVIDIA block in `wm/.config/hypr/host.lua` (lw has no NVIDIA) | +| Shell aliases | shared `config.fish` sources `~/.config/fish/host.fish` (per host) | +| Bash extras | shared `.bashrc` sources `~/.bashrc.host` (optional, per host) | +| Unique apps | in the owning host overlay (fl: llamacpp/evremap; lw: xremap) | + +`aichat`, `pi`, and `opencode` share one config in `common` (LAN-first, with the cloud provider also +listed so any host can switch). `lw` and `wm` each carry a host overlay of all three that adds their +own llama.cpp models (lw: CPU; wm: the GTX 1080 Ti router, plus the duskadiy default) — mirror +edits between the common copy and both overlays. The opencode tree is documented +in `common/.config/opencode/README.md`. + +## HyDE dependency (important for GUI hosts) + +The Hyprland config is [HyDE](https://github.com/HyDE-Project/HyDE)-based, since 2026-08-21 through +HyDE 26.x's **Lua chain** (live on wm since then and on lw since 2026-11; merged into `main` +2026-11-09 — see `LUA-PORT.md`). The repo pins `HYPRLAND_CONFIG` at +`~/.local/share/hypr/hyde.lua` in two files — `gui/.config/fish/conf.d/00-hypr-config.fish` +(SDDM/fish session path) and `gui/.config/uwsm/env-hyprland.d/10-dots.sh` (uwsm path) — and hyde.lua +loads HyDE's `lua/` modules, then the repo's override `gui/.config/hypr/hyprland.lua`, which pulls in +`dots_rules.lua` + `dots_binds.lua` (split out of it) and the per-host `host.lua`. So a GUI host must have **HyDE installed** — it ships `hyde.lua` and the +modules, both overwritten on HyDE updates; the dots layer lives only in `~/.config/hypr/*.lua`, which +survives them. `LUA-PORT.md` has the full map, flip recipe and rollback. + +The legacy hyprlang chain (`gui/.config/hypr/*.conf`, plus the two `~/.local/share/hyde/ +{hyprland,hyde}.conf` framework copies HyDE 26.x stopped shipping) was **retired 2026-09-10** +(`LUA-PORT.md` step 8) once the Lua soak closed — nothing reads a `.conf` in Lua mode. One line +survives: `gui/.local/share/hyde/hyde.conf` keeps `$default.FONT`, the fallback HyDE's rofi/menu +scripts resolve FONT through (`get_hyprConf`) when the theme's `hypr.theme` names no font. Rolling +back to hyprlang now means restoring those files from history (`git restore --source=bddbbf3 -- gui/.config/hypr wm/.config/hypr lw/.config/hypr gui/.local/share/hyde`), `./install.sh `, +repointing the two pins and relogging; d851213 is the last hyprlang `main` (the port merged +2026-11-09). After pulling the 2026-08-14 audit, a machine must run +**`./bin/hyde-materialize.sh` before `./install.sh`**: the newly-untracked files leave dangling stow +symlinks otherwise, and hypr/hyprlock treat a missing `source =` as a hard parse error. + +- Install/update HyDE with its own installer (`~/HyDE/Scripts/install.sh`); it also pulls the + required apps (`xdg-desktop-portal-hyprland`, `xdg-desktop-portal-gtk`, `hyprpolkitagent`). +- HyDE's `-r`/restore overwrites `~/.config/hypr` — use **`bin/reconcile-hyde.sh`** afterward to fold + its new defaults back against your dots configs. +- **Wallpapers and generated themes are HyDE-owned, never in dots** (`**/hyde/themes/` and + `**/wallpapers/` are gitignored — they once bloated a source repo to 255 MB). A fresh machine gets + them from HyDE, not from this repo. + +## Waybar (two worlds: HyDE-generated vs the standalone rig) + +**HyDE owns `~/.config/waybar/config.jsonc` AND `style.css`** — its `waybar.py` *writes* both on +any `--set`/`--update`, **through the stow symlinks, i.e. into this repo's checkout**. So dots +track neither. HyDE-managed customization goes via: + +- `gui/.config/waybar/layouts/*.jsonc` — dots-tracked layouts; switch with `hyde-shell waybar --set `. +- `gui/.config/waybar/modules/*.jsonc` — module defs, globbed into the generated config. + +**The custom cava rig is NOT HyDE-managed**: `layouts/custom.jsonc` + `layouts/custom.css` form a +self-contained two-bar config run by `wbar` (`gui/.local/bin/wbar`) as the supervised systemd +user unit `dots-waybar.service` (`Restart=always` — waybar 0.15.0 dies on every DP-2 link +drop/return, and as a bare process nothing relaunched it). `hc.start.bar` in `hyprland.lua`, the +Ctrl+Alt+W / Super+Shift+R binds and the `wbar` command all go through it; **never `killall +waybar`** — systemd brings it back in seconds and a raw relaunch beside it means two bars +(`wbar toggle|restart|reload|stop`). **Never route it through `hyde-shell waybar --set`** — waybar.py would clobber the repo's files as above. HyDE only reads +from `layouts/`, which is what makes them safe to track. On a rig host, HyDE's own bar must be +disabled once, or **two bars appear at every login** — and the launcher differs by HyDE vintage: + +- current HyDE: systemd user unit `hyde--bar.service` (auto-restarting) — + `systemctl --user stop ; systemctl --user mask `. +- older (pre-unit) HyDE: `exec-once = $start.BAR` in HyDE's generated `hyprland.conf` — the + hyprlang-era dots blanked it with `$start.BAR=` in `gui/.config/hypr/hyde.conf`; that file went + with the chain (LUA-PORT.md step 8), and under Lua the lever is `hc.start.bar` in + `hyprland.lua`, which launches the rig itself — see HYDE-UPDATE.md step 4. + +Note: the Arch `waybar` build has **no native `cava`** module — the rig uses the script module +`custom/cava` running `cava-waybar.sh` (self-contained, no HyDE dependency). + +## Secrets + +Never committed. Put `DUSKADIY_API_KEY` etc. in `~/.config/fish/conf.d/secrets.fish` (gitignored). +`pi`'s `auth.json` is **not** tracked — it only ever holds `$VAR` references, but pi's `/login` +rewrites it with the literal key, so one stray `/login` would commit a real token. A new host +bootstraps it with `cp common/.pi/agent/auth.json.example common/.pi/agent/auth.json`, then +`./install.sh`. Also gitignored: `fish_variables`, +`greet.txt`, pi agent runtime/state, `tmux/plugins/`, `.claude/` (Claude Code project dir/worktrees), +`*.bak`/`*.log`. + +## Merge notes (history — the one-time unification) + +The four former per-machine repos had drifted; the merge made some judgment calls: + +- **`config.fish` / `.bashrc`** were hand-reconciled into a neutral shared base + per-host + `host.fish` / `.bashrc.host` (removed a committed `fnm_multishells` runtime PATH, stray + absolute home-dir paths, duplicate git aliases). +- **`pi` lives at `~/.pi`** (repo `.pi/`); **`tmux` at `~/.config/tmux/`** (delete a legacy + `~/.tmux.conf` if present after migrating). +- **Appearance drift was unified to one canonical** (mostly wm): bat, btop, cava, fastfetch, lazygit, + mpv, pyradio, waybar, zellij, most of nvim. +- **nvim** is shared entirely (no host overrides); plugin set / `lazy-lock.json` are shared — run + `:Lazy restore` per machine once (obeys the lockfile pins — `:Lazy update` on one machine + + commit is how versions move forward; other machines converge with `restore`). +- **`zellij`** is one shared config with **vim keybinds** (h/j/k/l) + the `guvbox-dark` theme. +- **`misc/{clis,tuis}.txt`** launcher inventories use wm's lists in `common`; a machine needing its + own can override in its overlay. + +## Third-party content and licensing + +The repo is GPL-3.0 (`LICENSE`). What that does and doesn't cover: + +- **`hypr/`, `waybar/` and the other desktop configs are derived from + [HyDE](https://github.com/HyDE-Project/HyDE)** (and, further back, legacy Hyprdots). HyDE is + itself GPL-3.0, so the derivation and this repo's licence agree — no conflict, and the + Hyprdots-era ASCII banners in those files are left in place as attribution. +- **Colour themes**: the repo ships no third-party theme files, so it needs no notices file. + Each app gets its theme from somewhere else: + - **kitty**: HyDE renders `theme.conf` from the current HyDE theme. `kitty.conf` adds only + this repo's own background, foreground and tab bar. + - **aichat**: *One Half Dark* (MIT, by Son A. Pham) is downloaded from upstream at install + time by `bin/dots-themes-fetch.sh`, pinned by commit and checksum. + - **cava**: it writes its own shaders and themes. + - **zellij and bat**: their gruvbox-dark and OneHalfDark themes are built in. + + The pi, opencode and alacritty themes are the repo's own files. They hold colour values from + the Catppuccin Mocha and SynthWave '84 palettes (both MIT, by Catppuccin and Robb Owen), + mapped onto each app's keys. Credit, gladly given: a set of colour values isn't a copy of + either licensed theme. Keep it that way: a theme file copied in brings its licence notice + with it. +- **`gui/.local/share/icons/dots-icons/`** ships only its `index.theme`. Its tray/status icons + are symlinks into each host's own *Tela-circle-dracula* (by vinceliuice, installed by HyDE), + made at install time by `bin/dots-icons-link.sh`. Tela-circle publishes no licence, so the + repo doesn't redistribute its SVGs. +- **`common/.config/fastfetch/pngs/`** holds project and distro marks (Arch, the Open Source + Initiative and Open Source Hardware logos). Trademarks aren't relicensable, so GPL-3 does + not extend to them; they are bundled as nominative use, the way most dotfiles repos do. The + dmz.rs rabbit (`dmz-rabbit*.png`) and the decentrala.org network logo (`network*.png`) are + the community's own marks, used with permission. `neonom.png` is the repo owner's own render + of the Om glyph, offered as **CC0**. +- **`gui/.config/hypr/hyprlock/assets/`** — the lock screen background and logo are AI-generated + by the repo owner (February 2026). They sit outside the GPL-3 grant and are offered as **CC0**. + The keyhole in `background.jpg` is an AI-altered rendition of the Open Source Initiative mark, + used purely decoratively; no affiliation with or endorsement by the OSI is implied. diff --git a/bin/dots-icons-link.sh b/bin/dots-icons-link.sh new file mode 100755 index 0000000..e0f3015 --- /dev/null +++ b/bin/dots-icons-link.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# dots-icons-link.sh — fill the dots-icons overlay theme with symlinks into the host's own +# Tela-circle-dracula install (HyDE ships that icon theme on every GUI host). +# +# The overlay (gui/.local/share/icons/dots-icons/index.theme, searched before Tela) exists +# because Tela ships its flat tray/status icons only at fixed 16/22/24px. On a fractionally +# scaled monitor waybar asks for size×2 (44px), which falls through to Tela's coloured +# scalable/devices circles (the blue nm-applet blob). Serving Tela's 22/panel SVGs as +# Scalable keeps them flat at every size. +# +# Links, not copies: Tela-circle publishes no licence (2026-11-09), so the repo can't +# redistribute its SVGs. Each host links its own installed files instead. +# +# Usage: bin/dots-icons-link.sh [-n] (-n = dry run). Idempotent; ./install.sh runs it on +# GUI hosts. Exit 1 if Tela is missing or any icon could not be linked — the overlay then +# degrades gracefully (Inherits=Tela-circle-dracula), so callers treat that as a warning. +set -euo pipefail + +DRY=0 +[ "${1:-}" = "-n" ] && DRY=1 +data="${XDG_DATA_HOME:-$HOME/.local/share}" +src="$data/icons/Tela-circle-dracula/22/panel" +dst="$data/icons/dots-icons/scalable/status" + +icons=( + blueman-active blueman-disabled blueman-tray-active blueman-tray-disabled blueman-tray + nm-adhoc nm-device-wired-autoip nm-device-wired-secureoffline nm-device-wired-secure + nm-device-wired nm-device-wireless nm-device-wwan nm-mb-roam nm-nm-signal-00 + nm-nm-signal-100 nm-nm-signal-25 nm-nm-signal-50 nm-nm-signal-75 nm-no-connection + nm-secure-lock nm-signal-00-secure nm-signal-00 nm-signal-0-secure nm-signal-0 + nm-signal-100-secure nm-signal-100 nm-signal-25-secure nm-signal-25 nm-signal-50-secure + nm-signal-50 nm-signal-75-secure nm-signal-75 nm-tech-3g nm-tech-4g nm-tech-cdma-1x + nm-tech-edge nm-tech-evdo nm-tech-gprs nm-tech-hspa nm-tech-lte nm-tech-umts + nm-vpn-active-lock nm-vpn-lock nm-vpn-standalone-lock nm-wwan-tower +) + +if [ ! -d "$src" ]; then + echo " dots-icons: $src missing — Tela-circle-dracula not installed; overlay left empty" >&2 + exit 1 +fi +[ "$DRY" = 1 ] || mkdir -p "$dst" + +linked=0 ok=0 bad=0 +for n in "${icons[@]}"; do + s="$src/$n.svg" d="$dst/$n.svg" + if [ ! -e "$s" ]; then + echo " dots-icons: $n.svg not in Tela-circle-dracula/22/panel (renamed upstream?)" >&2 + bad=$((bad + 1)) + elif [ -L "$d" ] && [ "$(readlink "$d")" = "$s" ]; then + ok=$((ok + 1)) + elif [ -e "$d" ] && [ ! -L "$d" ]; then + echo " dots-icons: $d is a real file — left alone" >&2 + bad=$((bad + 1)) + else + [ "$DRY" = 1 ] || ln -sfn "$s" "$d" + linked=$((linked + 1)) + fi +done + +verb="linked" +[ "$DRY" = 1 ] && verb="would link" +echo " dots-icons: $verb $linked, $ok already linked, $bad problem(s)" +[ "$bad" -eq 0 ] diff --git a/bin/dots-themes-fetch.sh b/bin/dots-themes-fetch.sh new file mode 100755 index 0000000..c2d4ed6 --- /dev/null +++ b/bin/dots-themes-fetch.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# dots-themes-fetch.sh — download the third-party theme files this repo's configs use but the +# repo doesn't ship. Each host fetches its own copy from upstream, so the repo redistributes +# nothing and needs no licence notice. (Same idea as bin/dots-icons-link.sh, which links Tela's +# icons from the host instead of shipping them.) +# +# Every entry is pinned to an upstream commit plus a sha256, so a fetch is exactly the file +# that was reviewed. To update one: bump the commit in the URL, check the diff, then replace +# the checksum with `curl -fsSL | sha256sum`. +# +# Usage: bin/dots-themes-fetch.sh [-n] (-n = dry run). Idempotent; ./install.sh runs it on +# every host. A destination that's already a real file is left alone, even if its content +# differs (a local edit wins). A symlink there (e.g. the stow link left dangling after the +# repo dropped the file) is replaced: mv swaps the link itself, never writes through it. +# Exit 1 if a download or checksum failed; the app then falls back to its built-in theme, so +# install.sh only warns. +set -euo pipefail + +DRY=0 +[ "${1:-}" = "-n" ] && DRY=1 +cfg="${XDG_CONFIG_HOME:-$HOME/.config}" + +# dest|sha256|url +themes=( + # aichat: One Half Dark by Son A. Pham (MIT), loaded as /dark.tmTheme when present + "$cfg/aichat/dark.tmTheme|6205e2311e433841f0aa1b15862b46cb892b003650f31df508a4ebc39a27bdbb|https://raw.githubusercontent.com/sonph/onehalf/d13f47b0c20923eb13335f7effc5e8ec4431a5cd/sublimetext/OneHalfDark.tmTheme" +) + +fetched=0 ok=0 kept=0 bad=0 +for t in "${themes[@]}"; do + IFS='|' read -r dst sum url <<<"$t" + name="$dst" + case "$dst" in "$HOME"/*) name="~${dst#"$HOME"}" ;; esac + if [ ! -d "$(dirname "$dst")" ]; then + echo " themes: $name skipped (app not configured on this host)" + continue + fi + if [ -f "$dst" ] && [ ! -L "$dst" ]; then + if [ "$(sha256sum <"$dst" | cut -d' ' -f1)" = "$sum" ]; then + ok=$((ok + 1)) + else + echo " themes: $name is a real file with other content — left alone" + kept=$((kept + 1)) + fi + continue + fi + if [ "$DRY" = 1 ]; then + echo " themes: would fetch $name" + fetched=$((fetched + 1)) + continue + fi + tmp="$(mktemp "$dst.XXXXXX")" + if curl -fsSL --connect-timeout 5 --max-time 30 "$url" -o "$tmp" \ + && [ "$(sha256sum <"$tmp" | cut -d' ' -f1)" = "$sum" ]; then + chmod 644 "$tmp" + mv -f "$tmp" "$dst" + fetched=$((fetched + 1)) + else + rm -f "$tmp" + echo " themes: could not fetch $name (offline, or the checksum changed) — app uses its built-in theme" >&2 + bad=$((bad + 1)) + fi +done + +verb="fetched" +[ "$DRY" = 1 ] && verb="would fetch" +echo " themes: $verb $fetched, $ok already present, $kept kept as local, $bad problem(s)" +[ "$bad" -eq 0 ] diff --git a/bin/dotsync b/bin/dotsync new file mode 100755 index 0000000..e272df2 --- /dev/null +++ b/bin/dotsync @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# dotsync — sync dotfiles with the least churn. +# +# Deployed configs are symlinks into this repo, so `git pull` makes edits LIVE instantly +# with no re-stow — meaning no symlink churn and no app reloads (kitty etc. keep their +# runtime state). Re-stowing (install.sh) is only needed when files are ADDED / REMOVED, +# to create or prune symlinks. dotsync does the minimum: pull, and re-link ONLY if the +# pull added/removed/renamed files. +# +# dotsync pull, then relink only if the file set changed +# dotsync -n preview incoming changes (fetch only; no pull, no relink) +# dotsync as above, forcing the host package (normally unnecessary: install.sh +# reuses the host recorded in ~/.config/dots-host) +set -uo pipefail +DOTS="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)" +cd "$DOTS" || exit 1 + +if [ "${1:-}" = "-n" ] || [ "${1:-}" = "--dry-run" ]; then + git fetch -q 2>/dev/null || { + echo "fetch failed (offline?)" + exit 1 + } + up="$(git rev-parse --abbrev-ref '@{u}' 2>/dev/null)" || { + echo "no upstream set" + exit 1 + } + # rev-list, not diff: a plain diff also fires when the LOCAL side is ahead, mislabelling + # your own unpushed commits as incoming. Count commits that exist only on the upstream. + n="$(git rev-list --count "HEAD..$up")" + if [ "$n" -eq 0 ]; then echo "already up to date with $up."; else + echo "incoming from $up ($n commit(s)):" + git --no-pager diff --stat "HEAD...$up" + fi + exit 0 +fi + +before="$(git rev-parse HEAD)" +if ! git pull --ff-only; then + echo "pull not fast-forward (local commits or conflicts) — commit/stash, then retry." >&2 + exit 1 +fi +after="$(git rev-parse HEAD)" + +if [ "$before" = "$after" ]; then + echo "already up to date — nothing to sync." + exit 0 +fi + +# Services that read config ONCE at startup don't pick up pulled edits — nudge loudly. +# (Symlinked edits are live for everything else; these are the exceptions that bit us.) +if git diff --name-only "$before" "$after" | grep -q '\.config/llamacpp/' \ + && systemctl cat llama.service &>/dev/null; then + echo "" + echo "⚠⚠ llamacpp presets changed — the router reads them only at startup. Apply with:" + echo " sudo systemctl restart llama.service" + echo "" +fi + +# A unit file is read from /etc, not through the stow symlink — needs daemon-reload as well. +if git diff --name-only "$before" "$after" | grep -q '\.config/whisper/' \ + && systemctl cat whisper.service &>/dev/null; then + echo "" + echo "⚠⚠ whisper unit changed — apply with:" + echo " sudo systemctl daemon-reload && sudo systemctl restart whisper.service" + echo "" +fi + +# Modified files (M) are live only through INTACT symlinks — a live file severed by an +# atomic rewrite (the recurring claude/settings.json class) swallows pulled edits silently, +# so verify that premise per modified file instead of assuming it. Added/Deleted/Renamed +# always need (un)linking. The diff is captured once, not piped into `grep -q`: its early +# exit can SIGPIPE git under pipefail and turn the whole condition falsely negative. +changes="$(git diff --name-status "$before" "$after")" +need_restow="" +if printf '%s\n' "$changes" | grep -qE '^(A|D|R)'; then + need_restow="files added/removed/renamed" +else + # map each modified repo path (package/.dotpath) to its live counterpart; a real file + # (not a symlink) sitting there means the pulled edit did NOT land + while IFS= read -r rel; do + live="$HOME/$rel" + if [ -e "$live" ] && [ ! -L "$live" ]; then + echo "note: ~/$rel is a real file, not a symlink into the repo — the pulled edit has NOT landed there." + need_restow="severed symlink(s)" + fi + done < <(printf '%s\n' "$changes" | awk -F'\t' '$1 ~ /^M/ && $2 ~ /^[^\/]+\/\./ { sub(/^[^\/]+\//, "", $2); print $2 }') +fi + +if [ -n "$need_restow" ]; then + echo "$need_restow — re-linking via install.sh (this may reload some apps)…" + # Normally called with no argument, so install.sh resolves the host from ~/.config/dots-host — + # the one recorded by the last install.sh run here. That is exactly why the host must not be + # derived from `hostname -s`: this path is automatic and has nothing to pass. An explicit + # `dotsync ` is forwarded through for the rare override. + exec "$DOTS/install.sh" "$@" +else + echo "edits only — already live through the symlinks; no re-stow, no reload needed." +fi diff --git a/common/.bashrc b/common/.bashrc new file mode 100644 index 0000000..9540a7c --- /dev/null +++ b/common/.bashrc @@ -0,0 +1,143 @@ +# +# ~/.bashrc (shared; host-specific bits in ~/.bashrc.host) +# + +# If not running interactively, don't do anything +[[ $- != *i* ]] && return + +# fzf's built-in walker ignores .ignore files; fd honours them. Mirrors config.fish. +export FZF_DEFAULT_COMMAND='fd --type f --strip-cwd-prefix' + +alias grep='grep --color=auto' +alias fzf="fzf --preview 'bat --color=always {}'" +alias copy="wl-copy" +alias img="kitten icat" +alias fm="yazi" +alias lg="lazygit" +alias mkdir="mkdir -p" +alias pacs="sudo pacman -Syu --noconfirm" +alias yays="yay --noconfirm --sudoloop" +alias nmaps="sudo nmap -sn 192.168.0.0/24" +alias faillock="sudo faillock --reset" +alias xremaps="sudo xremap ~/.config/xremap/config.yml" +alias dots="cd ~/.dots/ && nvim" +alias aliases="bat ~/.config/fish/config.fish" +alias ipadd="sudo ip route add 192.168.0.234 dev wg0" + +# List directory +alias l="ls -l" +alias la="ls -a" +alias lla="ls -la" +alias lt="ls --tree" + +# Git +alias gs='git status' +alias gca='git add -p . && git commit' +alias gd="git diff --word-diff" +alias gl='git log --graph --show-signature' +alias gla="git log --all --decorate --oneline --graph" +alias gm='git merge' + +alias exti=exit +alias cat="bat -p" +alias untar="tar -xf" +alias keybinds="cd ~/.dots/ && nvim gui/.config/hypr/keybindings.conf" +alias dmz="cat ~/.config/fish/dmz.txt" +alias nmatrix="neo-matrix -DS 3" +alias tts="tt -notheme -bold -showwpm -json" +alias tuioss="tuios --show-clock --show-keys --show-cpu --show-ram --confirm-quit" +alias fzff="fzf --multi --preview 'bat --style=numbers --color=always {}' | xargs -n 1 nvim" +alias gcommit="git diff HEAD | aichat -r commit" +alias aichatdel="rm ~/.config/aichat/sessions/*.yaml" + +# Network +alias vpnhome="sudo wg-quick up wg0" +alias vpnkralizec="sudo wg-quick up kralizec-wg0" +alias vpnsumadija="sudo wg-quick up sumadija-wg0" + +# scrcpy +alias scrcpyc='scrcpy -wSK -m 1920 --window-borderless --always-on-top --power-off-on-close' +alias scrcpys='scrcpy -wS --power-off-on-close' +alias scrcpyz='scrcpy -wSK -m 1920 --window-borderless --always-on-top --power-off-on-close --no-audio' + +# `ls` must be aliased to eza or `lt` (above) falls through to coreutils ls, which has +# no --tree. bash re-expands the first word of an alias, so l/la/lla/lt all pick up eza. +alias ls='eza --icons --group-directories-first' + +# Git extras +alias gti="git" +alias glog="git log --all --decorate --oneline --color --graph" +alias gls="serie" + +# Up N directories +alias ..="cd .." +alias ...="cd ../.." +alias .3="cd ../../.." +alias .4="cd ../../../.." +alias .5="cd ../../../../.." + +# Powerline prompt, synthwave palette (needs a Nerd Font for the glyphs) +PROMPT_DIRTRIM=3 +__pl_sep=$'\ue0b0' # powerline triangle +__pl_branch=$'\ue0a0' # branch glyph +__pl_seg() { # $1=bg $2=fg $3=text (colors as "R;G;B") + [[ -n $__pl_bg ]] && PS1+="\[\e[38;2;${__pl_bg};48;2;${1}m\]${__pl_sep}\[\e[0m\]" + PS1+="\[\e[48;2;${1};38;2;${2}m\] ${3} \[\e[0m\]" + __pl_bg=$1 +} +__pl_end() { + PS1+="\[\e[38;2;${__pl_bg}m\]${__pl_sep}\[\e[0m\] " + __pl_bg='' +} +__prompt() { + local s=$? + # muted synthwave: segment colors pre-blended ~40% onto the terminal bg + # (#262335) so they read as semi-transparent overlays + local fg='205;200;220' + local purple='67;56;93' green='65;107;99' yellow='114;100;67' + local red='124;39;52' pink='122;71;77' + PS1="\[\e]0;\w\a\]" + __pl_bg='' + [[ -n $SSH_TTY ]] && __pl_seg "$pink" "$fg" '\u@\h' + __pl_seg "$purple" "$fg" '\w' + local b + if b=$(git symbolic-ref --short HEAD 2>/dev/null || git describe --contains --all HEAD 2>/dev/null); then + if [[ -n $(git status --porcelain 2>/dev/null | head -n1) ]]; then + __pl_seg "$yellow" "$fg" "${__pl_branch} ${b} ✱" + else + __pl_seg "$green" "$fg" "${__pl_branch} ${b}" + fi + fi + ((s != 0)) && __pl_seg "$red" "$fg" "✘ ${s}" + [[ $EUID == 0 ]] && __pl_seg "$red" "$fg" '#' + __pl_end +} +PROMPT_COMMAND=__prompt + +set -o vi +eval "$(fzf --bash)" +# eval "$(zoxide init --cmd cd bash)" + +# colorized --help +h() { "$@" --help 2>&1 | bat --plain --language=help; } + +# Record lookup against the local dmz db (adjust the db path to this machine) +lk(){ + local DB="$HOME/projects/dmz/soft/lk/db.rec" + passes=0 count=0; until [ "$count" -eq "1" ] || [ "$passes" -gt 2 ] ; do \ + query="$(recsel "$DB" -p aim,tag | recsel -iq "$query" -CP aim,tag | sort -u | fzf --preview="recsel \"$DB\" -e \"aim~{}\"")" \ + && count="$(recsel "$DB" -q "$query" -c )" ;\ + passes=$(( passes + 1 )) ;\ + done \ + && recsel "$DB" -q "$query" | recfmt -f "$HOME/projects/dmz/soft/lk/lists.fmt" | less +} + +# Keepassxc search +kp() { + local DB="${KP_DB:?Error: KP_DB environment variable is not set. Check .bash_profile.}" + read -sp "Enter db password: " pass; echo ""; printf '%s\n' "$pass" | keepassxc-cli ls -q -R "$DB" | fzf | (read -r entry; printf '%s\n' "$pass" | keepassxc-cli clip -q "$DB" "$entry" 0) +} + +# Per-host extras +[ -f ~/.bashrc.host ] && . ~/.bashrc.host + diff --git a/common/.config/aichat/config.yaml b/common/.config/aichat/config.yaml new file mode 100644 index 0000000..49e8d6e --- /dev/null +++ b/common/.config/aichat/config.yaml @@ -0,0 +1,66 @@ +# NOTE: the lw/ and wm/ host overlays carry full-file copies of this config — mirror changes there. +# see https://github.com/sigoden/aichat/blob/main/config.example.yaml +keybindings: vi +editor: nvim +model: local:Qwen3.6-35B-A3B-Thinking + +# Sessions: persist REPL sessions and keep more history before summarizing. +# The default compress_threshold (4000) summarizes far too early for 24k+ windows. +save_session: true +compress_threshold: 16000 + +# REPL prompts show live context usage (needs max_input_tokens, set per model below) +left_prompt: '{color.green}{?session {session}{?role /}}{role}{color.cyan}{?rag @{rag}}{color.reset}> ' +right_prompt: '{color.purple}{?session {consume_tokens}/{max_input_tokens} }{color.reset}' + +# NOTE: temperature/top_p are intentionally unset — the LAN server applies tuned +# per-model sampling via --jinja (e.g. GLM 0.6/0.95); a global value would clobber it. + +# max_input_tokens = real ctx-size (from the router) minus output headroom. +clients: +# LAN access (fast; only reachable on the home network) +- type: openai-compatible + name: local + api_base: http://192.168.0.204:11343/v1 + models: &lan_models + # Speeds are benched decode t/s (clean-night sweeps) — see fl/.config/llamacpp/README.md roster. + - name: Qwen3-Coder-30B-Instruct-UD-Q3_K_XL + max_input_tokens: 30000 # ctx 32768 · ~30 t/s — main agent coder + - name: Qwen3-Coder-Next-UD-IQ3_XXS + max_input_tokens: 128000 # ctx 131072 · ~16 t/s — long sessions (128k) + - name: Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS + max_input_tokens: 22000 # ctx 24576 · ~36 t/s — daily driver + supports_vision: true + - name: Qwen3.6-35B-A3B-Thinking + max_input_tokens: 22000 # ctx 24576 · ~39 t/s — hard problems + supports_vision: true + - name: Qwen3.5-9B-UD-Q6_K_XL + max_input_tokens: 30000 # ctx 32768 · ~32 t/s — quick tasks + supports_vision: true + - name: Qwen3.8-27B-UD-IQ3_XXS + max_input_tokens: 22000 # ctx 24576 · ~15 t/s — hybrid reasoner, quiet desktop only + supports_vision: true + - name: gemma-4-26B-A4B-it-UD-IQ4_XS + max_input_tokens: 22000 # ctx 24576 · ~34 t/s — quality generalist, best vision + supports_vision: true + - name: gemma-4-E4B-it-UD-Q8_K_XL + max_input_tokens: 62000 # ctx 65536 · ~57 t/s — fast generalist, long docs + supports_vision: true + - name: GLM-4.7-Flash-UD-Q4_K_XL + max_input_tokens: 22000 # ctx 24576 · ~21 t/s — quality coder + - name: GLM-4.7-Flash-UD-Q3_K_XL + max_input_tokens: 22000 # ctx 24576 · ~28 t/s — fast coder (3-bit) + - name: Ornith-1.5-35B-A3B-IQ3_XXS + max_input_tokens: 30000 # ctx 32768 · ~32 t/s — agentic coder, thinking + supports_vision: true + - name: gpt-oss-20b + max_input_tokens: 62000 # ctx 65536 · ~38 t/s — fast reasoning + tools + - name: gpt-oss-20b-low + max_input_tokens: 62000 # ctx 65536 · ~37 t/s — snappy answers +# Remote access via duskadiy.com (reachable from anywhere; requires an API key — +# $DUSKADIY_API_KEY, from the gitignored conf.d/secrets.fish). The LAN endpoint above is keyless. +# Same server, same model ids — reuse the list above via a YAML anchor. +- type: openai-compatible + name: duskadiy + api_base: https://llm.duskadiy.com/api/v1 + models: *lan_models diff --git a/common/.config/aichat/roles/code.md b/common/.config/aichat/roles/code.md new file mode 100644 index 0000000..a541cf0 --- /dev/null +++ b/common/.config/aichat/roles/code.md @@ -0,0 +1,9 @@ +--- +temperature: 0.2 +--- +You are a terse coding assistant. + +- Lead with the code, as a single fenced block. +- Add at most 1–2 short sentences of explanation, and only if genuinely needed. No preamble, no "here is", no closing summary. +- Match the language and style implied by the question; if unspecified, infer the most likely one. +- If the request is ambiguous, make the most reasonable assumption and state it in one line above the code. diff --git a/common/.config/aichat/roles/commit.md b/common/.config/aichat/roles/commit.md new file mode 100644 index 0000000..5e24f95 --- /dev/null +++ b/common/.config/aichat/roles/commit.md @@ -0,0 +1,11 @@ +--- +temperature: 0.2 +--- +You write a git commit message from a diff. Output ONLY the message — no preamble, no code fences, no explanation. + +- Subject: `[Scope] imperative summary`, where Scope is a short tag inferred from the changed paths, matching the style of recent `git log` (e.g. [Waybar], [Fish], [LLM]). Keep it under 70 characters. +- Imperative mood ("add", "fix", "rename"), never past tense. +- For a non-trivial change, leave a blank line then add 1–4 terse bullets ("- ...") covering what changed and why. Omit the body for small, self-explanatory changes. +- Describe only what the diff actually shows; do not invent rationale or files. + +The user's input is the diff (typically `git diff --cached`). diff --git a/common/.config/aichat/roles/fish.md b/common/.config/aichat/roles/fish.md new file mode 100644 index 0000000..ecaaf30 --- /dev/null +++ b/common/.config/aichat/roles/fish.md @@ -0,0 +1,9 @@ +--- +temperature: 0.1 +--- +You translate a request into a single shell command for the fish shell on Arch Linux. Output ONLY the command on one line — no code fence, no explanation. + +- Use fish syntax, not bash. Notably: `set -x VAR value` (not `export`), `$status` (not `$?`), the `test` / `string` / `math` builtins, and `(cmd)` for command substitution (not `$(cmd)`). `&&` / `||` work in modern fish. +- Package management is pacman / yay (`yay -S`, `pacman -Qi`, `pacman -Qo`). Clipboard is Wayland: `wl-copy` / `wl-paste`. +- Prefer one pipeline. If several steps are unavoidable, chain them with `; and`. +- If it can't be done safely in one command, output a single `# ...` comment saying why instead. diff --git a/common/.config/aichat/roles/review.md b/common/.config/aichat/roles/review.md new file mode 100644 index 0000000..6749d82 --- /dev/null +++ b/common/.config/aichat/roles/review.md @@ -0,0 +1,11 @@ +--- +temperature: 0.2 +--- +You review a code diff for defects. Be concise and specific. + +- Focus on correctness bugs, edge cases, error handling, security issues, and clear regressions. Skip style and formatting nits unless they cause a bug. +- Format each finding as `file:line — issue — why it matters`, most severe first. +- Reference exact identifiers and lines from the diff; do not speculate about code you cannot see. +- If nothing substantive is wrong, say so in one line rather than inventing issues. + +The user's input is the diff (typically `git diff`). diff --git a/common/.config/aichat/roles/shell.md b/common/.config/aichat/roles/shell.md new file mode 100644 index 0000000..f154c1c --- /dev/null +++ b/common/.config/aichat/roles/shell.md @@ -0,0 +1,10 @@ +--- +model: local:gemma-4-E4B-it-UD-Q8_K_XL +temperature: 0.1 +--- +You translate a request into a single shell command for the fish shell on Arch Linux. Output ONLY the command on one line — no code fence, no explanation. + +- Use fish syntax, not bash. Notably: `set -x VAR value` (not `export`), `$status` (not `$?`), the `test` / `string` / `math` builtins, and `(cmd)` for command substitution (not `$(cmd)`). `&&` / `||` work in modern fish. +- Package management is pacman / yay (`yay -S`, `pacman -Qi`, `pacman -Qo`). Clipboard is Wayland: `wl-copy` / `wl-paste`. +- Prefer one pipeline. If several steps are unavoidable, chain them with `; and`. +- If it can't be done safely in one command, output a single `# ...` comment saying why instead. diff --git a/common/.config/bat/config b/common/.config/bat/config new file mode 100644 index 0000000..0f447ad --- /dev/null +++ b/common/.config/bat/config @@ -0,0 +1,34 @@ +# This is `bat`s configuration file. Each line either contains a comment or +# a command-line option that you want to pass to `bat` by default. You can +# run `bat --help` to get a list of all possible configuration options. + +# Specify desired highlighting theme (e.g. "TwoDark"). Run `bat --list-themes` +# for a list of all available themes +# OneHalfDark is built into bat — no custom themes are tracked, so no `bat cache --build` step +--theme="OneHalfDark" +--style="numbers,changes,header,snip" + +# Enable this to use italic text on the terminal. This is not supported on all +# terminal emulators (like tmux, by default): +--italic-text=always + +# Uncomment the following line to disable automatic paging: +#--paging=never + +# Uncomment the following line if you are using less version >= 551 and want to +# enable mouse scrolling support in `bat` when running inside tmux. This might +# disable text selection, unless you press shift. +--pager="less --RAW-CONTROL-CHARS --quit-if-one-screen --mouse --ignore-case" + +# Syntax mappings: map a certain filename pattern to a language. +# Example 1: use the C++ syntax for Arduino .ino files +# Example 2: Use ".gitignore"-style highlighting for ".ignore" files +--map-syntax "*.ino:C++" +--map-syntax ".ignore:Git Ignore" +--map-syntax "**/hypr/**/*.conf:INI" +--map-syntax "**/kitty/*.conf:INI" +--map-syntax "*.ctl:INI" +--map-syntax ".inputrc:bash" +--map-syntax "**/cava/config:INI" +--map-syntax "**/mpv/*.conf:INI" +--map-syntax "**/btop/btop.conf:INI" diff --git a/common/.config/btop/btop.conf b/common/.config/btop/btop.conf new file mode 100644 index 0000000..3f004cb --- /dev/null +++ b/common/.config/btop/btop.conf @@ -0,0 +1,286 @@ +#? Config file for btop v.1.4.7 + +#* Name of a btop++/bpytop/bashtop formatted ".theme" file, "Default" and "TTY" for builtin themes. +#* Themes should be placed in "../share/btop/themes" relative to binary or "$HOME/.config/btop/themes" +color_theme = "Default" + +#* If the theme set background should be shown, set to False if you want terminal background transparency. +theme_background = false + +#* Sets if 24-bit truecolor should be used, will convert 24-bit colors to 256 color (6x6x6 color cube) if false. +truecolor = true + +#* Set to true to force tty mode regardless if a real tty has been detected or not. +#* Will force 16-color mode and TTY theme, set all graph symbols to "tty" and swap out other non tty friendly symbols. +force_tty = false + +#* Option to disable presets. Either the default preset, custom presets, or all presets. +#* "Off" All presets are enabled. +#* "Default" preset is disabled.#* "Custom" presets are disabled.#* "All" presets are disabled. +disable_presets = "Off" + +#* Define presets for the layout of the boxes. Preset 0 is always all boxes shown with default settings. Max 9 presets. +#* Format: "box_name:P:G,box_name:P:G" P=(0 or 1) for alternate positions, G=graph symbol to use for box. +#* Use whitespace " " as separator between different presets. +#* Example: "cpu:0:default,mem:0:tty,proc:1:default cpu:0:braille,proc:0:tty" +presets = "cpu:1:default,proc:0:default cpu:0:default,mem:0:default,net:0:default cpu:0:block,net:0:tty" + +#* Set to True to enable "h,j,k,l,g,G" keys for directional control in lists. +#* Conflicting keys for h:"help" and k:"kill" is accessible while holding shift. +vim_keys = true + +#* Disable all mouse events. +disable_mouse = false + +#* Rounded corners on boxes, is ignored if TTY mode is ON. +rounded_corners = true + +#* Use terminal synchronized output sequences to reduce flickering on supported terminals. +terminal_sync = true + +#* Default symbols to use for graph creation, "braille", "block" or "tty". +#* "braille" offers the highest resolution but might not be included in all fonts. +#* "block" has half the resolution of braille but uses more common characters. +#* "tty" uses only 3 different symbols but will work with most fonts and should work in a real TTY. +#* Note that "tty" only has half the horizontal resolution of the other two, so will show a shorter historical view. +graph_symbol = "braille" + +# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty". +graph_symbol_cpu = "default" + +# Graph symbol to use for graphs in gpu box, "default", "braille", "block" or "tty". +graph_symbol_gpu = "default" + +# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty". +graph_symbol_mem = "default" + +# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty". +graph_symbol_net = "default" + +# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty". +graph_symbol_proc = "default" + +#* Manually set which boxes to show. Available values are "cpu mem net proc" and "gpu0" through "gpu5", separate values with whitespace. +shown_boxes = "proc cpu mem net" + +#* Update time in milliseconds, recommended 2000 ms or above for better sample times for graphs. +update_ms = 2000 + +#* Processes sorting, "pid" "program" "arguments" "threads" "user" "memory" "cpu lazy" "cpu direct", +#* "cpu lazy" sorts top process over time (easier to follow), "cpu direct" updates top process directly. +proc_sorting = "cpu lazy" + +#* Reverse sorting order, True or False. +proc_reversed = false + +#* Show processes as a tree. +proc_tree = true + +#* Use the cpu graph colors in the process list. +proc_colors = true + +#* Use a darkening gradient in the process list. +proc_gradient = true + +#* If process cpu usage should be of the core it's running on or usage of the total available cpu power. +proc_per_core = false + +#* Show process memory as bytes instead of percent. +proc_mem_bytes = true + +#* Show cpu graph for each process. +proc_cpu_graphs = true + +#* Use /proc/[pid]/smaps for memory information in the process info box (very slow but more accurate) +proc_info_smaps = false + +#* Show proc box on left side of screen instead of right. +proc_left = false + +#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop). +proc_filter_kernel = false + +#* Should the process list follow the selected process when detailed view is open. +proc_follow_detailed = true + +#* In tree-view, always accumulate child process resources in the parent process. +proc_aggregate = false + +#* Should cpu and memory usage display be preserved for dead processes when paused. +keep_dead_proc_usage = false + +#* Sets the CPU stat shown in upper half of the CPU graph, "total" is always available. +#* Select from a list of detected attributes from the options menu. +cpu_graph_upper = "Auto" + +#* Sets the CPU stat shown in lower half of the CPU graph, "total" is always available. +#* Select from a list of detected attributes from the options menu. +cpu_graph_lower = "Auto" + +#* If gpu info should be shown in the cpu box. Available values = "Auto", "On" and "Off". +show_gpu_info = "Auto" + +#* Toggles if the lower CPU graph should be inverted. +cpu_invert_lower = true + +#* Set to True to completely disable the lower CPU graph. +cpu_single_graph = false + +#* Show cpu box at bottom of screen instead of top. +cpu_bottom = false + +#* Shows the system uptime in the CPU box. +show_uptime = true + +#* Shows the CPU package current power consumption in watts. Requires running `make setcap` or `make setuid` or running with sudo. +show_cpu_watts = true + +#* Show cpu temperature. +check_temp = true + +#* Which sensor to use for cpu temperature, use options menu to select from list of available sensors. +cpu_sensor = "Auto" + +#* Show temperatures for cpu cores also if check_temp is True and sensors has been found. +show_coretemp = true + +#* Set a custom mapping between core and coretemp, can be needed on certain cpus to get correct temperature for correct core. +#* Use lm-sensors or similar to see which cores are reporting temperatures on your machine. +#* Format "x:y" x=core with wrong temp, y=core with correct temp, use space as separator between multiple entries. +#* Example: "4:0 5:1 6:3" +cpu_core_map = "" + +#* Which temperature scale to use, available values: "celsius", "fahrenheit", "kelvin" and "rankine". +temp_scale = "celsius" + +#* Use base 10 for bits/bytes sizes, KB = 1000 instead of KiB = 1024. +base_10_sizes = false + +#* Show CPU frequency. +show_cpu_freq = true + +#* How to calculate CPU frequency, available values: "first", "range", "lowest", "highest" and "average". +freq_mode = "first" + +#* Draw a clock at top of screen, formatting according to strftime, empty string to disable. +#* Special formatting: /host = hostname | /user = username | /uptime = system uptime +clock_format = "%X" + +#* Update main ui in background when menus are showing, set this to false if the menus is flickering too much for comfort. +background_update = true + +#* Custom cpu model name, empty string to disable. +custom_cpu_name = "" + +#* Optional filter for shown disks, should be full path of a mountpoint, separate multiple values with whitespace " ". +#* Only disks matching the filter will be shown. Prepend exclude= to only show disks not matching the filter. Examples: disk_filter="/boot /home/user", disks_filter="exclude=/boot /home/user" +disks_filter = "" + +#* Show graphs instead of meters for memory values. +mem_graphs = true + +#* Show mem box below net box instead of above. +mem_below_net = false + +#* Count ZFS ARC in cached and available memory. +zfs_arc_cached = true + +#* If swap memory should be shown in memory box. +show_swap = true + +#* Show swap as a disk, ignores show_swap value above, inserts itself after first disk. +swap_disk = true + +#* If mem box should be split to also show disks info. +show_disks = true + +#* Filter out non physical disks. Set this to False to include network disks, RAM disks and similar. +only_physical = true + +#* Read disks list from /etc/fstab. This also disables only_physical. +use_fstab = true + +#* Setting this to True will hide all datasets, and only show ZFS pools. (IO stats will be calculated per-pool) +zfs_hide_datasets = false + +#* Set to true to show available disk space for privileged users. +disk_free_priv = false + +#* Toggles if io activity % (disk busy time) should be shown in regular disk usage view. +show_io_stat = true + +#* Toggles io mode for disks, showing big graphs for disk read/write speeds. +io_mode = false + +#* Set to True to show combined read/write io graphs in io mode. +io_graph_combined = false + +#* Set the top speed for the io graphs in MiB/s (100 by default), use format "mountpoint:speed" separate disks with whitespace " ". +#* Example: "/mnt/media:100 /:20 /boot:1". +io_graph_speeds = "" + +#* Swap the positions of the upload and download speed graphs. When true, upload will be on top. +swap_upload_download = false + +#* Set fixed values for network graphs in Mebibits. Is only used if net_auto is also set to False. +net_download = 100 + +net_upload = 100 + +#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest. +net_auto = true + +#* Sync the auto scaling for download and upload to whichever currently has the highest scale. +net_sync = true + +#* Starts with the Network Interface specified here. +net_iface = "" + +#* "True" shows bitrates in base 10 (Kbps, Mbps). "False" shows bitrates in binary sizes (Kibps, Mibps, etc.). "Auto" uses base_10_sizes. +base_10_bitrate = "Auto" + +#* Show battery stats in top right if battery is present. +show_battery = true + +#* Which battery to use if multiple are present. "Auto" for auto detection. +selected_battery = "Auto" + +#* Show power stats of battery next to charge indicator. +show_battery_watts = true + +#* Set loglevel for "~/.local/state/btop.log" levels are: "ERROR" "WARNING" "INFO" "DEBUG". +#* The level set includes all lower levels, i.e. "DEBUG" will show all logging info. +log_level = "WARNING" + +#* Automatically save current settings to config file on exit. +save_config_on_exit = false + +#* Measure PCIe throughput on NVIDIA cards, may impact performance on certain cards. +nvml_measure_pcie_speeds = true + +#* Measure PCIe throughput on AMD cards, may impact performance on certain cards. +rsmi_measure_pcie_speeds = true + +#* Horizontally mirror the GPU graph. +gpu_mirror_graph = true + +#* Set which GPU vendors to show. Available values are "nvidia amd intel apple" +shown_gpus = "nvidia amd intel" + +#* Custom gpu0 model name, empty string to disable. +custom_gpu_name0 = "" + +#* Custom gpu1 model name, empty string to disable. +custom_gpu_name1 = "" + +#* Custom gpu2 model name, empty string to disable. +custom_gpu_name2 = "" + +#* Custom gpu3 model name, empty string to disable. +custom_gpu_name3 = "" + +#* Custom gpu4 model name, empty string to disable. +custom_gpu_name4 = "" + +#* Custom gpu5 model name, empty string to disable. +custom_gpu_name5 = "" diff --git a/common/.config/cava/config b/common/.config/cava/config new file mode 100644 index 0000000..558c987 --- /dev/null +++ b/common/.config/cava/config @@ -0,0 +1,19 @@ +## cava — only this repo's own settings. Every key left out falls back to cava's built-in +## default; cava documents them all in the config it writes to an empty ~/.config/cava/config, +## and it regenerates its own shaders/ and themes/ there on first run (so the repo ships none +## of cava's files). + +[general] +framerate = 60 +autosens = 1 + +[color] +gradient = 1 +gradient_color_1 = '#d34b11' +gradient_color_2 = '#cc5933' +gradient_color_3 = '#cc8033' +gradient_color_4 = '#cca633' +gradient_color_5 = '#cccc33' +gradient_color_6 = '#a6cc33' +gradient_color_7 = '#80cc33' +gradient_color_8 = '#59cc33' diff --git a/common/.config/claude/README.md b/common/.config/claude/README.md new file mode 100644 index 0000000..e0c2020 --- /dev/null +++ b/common/.config/claude/README.md @@ -0,0 +1,179 @@ +# Claude Code config + +Portable [Claude Code](https://claude.com/claude-code) customizations, synced via these +dots. Claude Code still uses its default `~/.claude/` directory; we surface the tracked +files below into it via per-file/dir symlinks, so edits made through Claude write straight +back into this repo. + +## What's tracked here + +- `settings.json` — global settings: permissions (deny git push, `gh pr merge` / `close`, + and reads of secret files; ask before `gh pr create` and `git rebase`; allow `gh` reads, `gh pr edit`, `gh workflow run` + and `gh run rerun`; `git commit` is left to `hooks/git-guard.py`, which exempts listed repos), default `model`, `enabledPlugins`, vim mode, dark theme, `effortLevel`, + fullscreen TUI, `statusLine`, `hooks`, `worktree` defaults, a generic `autoMode.environment`, … + Nothing in here may name a specific project, path or remote: this file is published by the + public mirror, and the auto-mode classifier only reads `autoMode` from user/managed settings + anyway (never from a project's `.claude/settings*.json`). +- `statusline.py` — rich status line (dir, git, unresolved PR review threads, model, context %, cost, disk — system + metrics live in the tmux bar). + See [StatusBar.md](StatusBar.md) for what each segment and colour means. +- `keybindings.json` — custom keybindings: vim-style scroll/navigation (`alt+j/k` and + `ctrl+shift+j/k` scroll by line — kitty's own `kitty_mod+j/k` scroll only its main-screen + scrollback and pass the key through to the fullscreen TUI's alternate screen, so they do not + shadow these; dropped once by mistake on 2026-09-15), plus `ctrl+x v` for the + verbose transcript view (`app:toggleTranscript`, same keystroke as opencode's `v`; the + default `ctrl+o` still works, and `ctrl+e` inside the view expands everything). +- `CLAUDE.md` — global user preferences applied to every project. +- `hooks/format.py` — PostToolUse hook: formats edited files by extension (stylua / ruff / + prettier / gofmt / rustfmt / fish_indent / shfmt / taplo). Every formatter is opt-in: stylua, + ruff, prettier and taplo run only where the project has their config file (found walking up); + gofmt and rustfmt gate on a project marker (`go.mod` / `Cargo.toml`); fish_indent and shfmt gate + on an `.editorconfig` *section* that matches the file. Wired to `Edit|Write` **and** `Bash` — + under auto mode Claude edits through the shell, so the Bash branch scans the command for + path-like tokens and formats the ones modified in the last 30 s. No-ops if the formatter isn't + installed, and always exits 0. +- `hooks/git-guard.py` — PreToolUse hook on `Bash`: structurally blocks anything that commits, + rewrites history or discards working-tree changes — `git commit` / `push` / `revert` / + `cherry-pick` / `rebase -i|--autostash` / `merge` (not `--abort`), `clean` / `reset` in any form that moves HEAD + or unstages everything (`reset -- `, `reset HEAD ` stay allowed) / `restore ` + (`--staged ` is fine, `--staged .` is not) / `checkout --` / `checkout .` / `stash drop|pop|clear` / + `branch -D|-f|-M`, and `gh pr merge` / `close`, `gh pr create` without `--head` (gh would push + the branch itself) and `gh pr edit` beyond `--title` / `--body` — wherever the flags sit + (`git -C . push`, `/usr/bin/git push`, `sh -c 'git push'`), which the prefix-matched deny rules + can't. A plain `rebase` and its `--continue` / `--abort` pass: Claude rebases and fixes + conflicts when asked (`CLAUDE.md`), and settings.json asks before each `git rebase`. The + discard group is what protects parallel sessions sharing one checkout. Exit 2 + a + one-line reason. Heredoc bodies are skipped on purpose (file contents). Regression matrix: + `bash ~/.claude/hooks/git-guard-test.sh` (a file on purpose — typed inline, the commands under + test would trip the live hook). Repos listed in `~/.claude/git-guard-exempt` (host-local, not in + this repo — it names projects; one main checkout per line, worktrees included): `commit` and + `merge` pass there — judged from the hook input's + `cwd`, every `cd` before the call and `git -C` — except `commit --amend` / `-a`. A user-scope deny + cannot be lifted for one repo, so `git commit` is off the deny list: the hook is its only + structural block. +- `hooks/notify.py` — Notification hook (`idle_prompt|permission_prompt`): `notify-send` desktop + notification when Claude is waiting on you; no-op on a headless host. +- `../tmux/scripts/agent-state.sh` — UserPromptSubmit (busy) / Notification (input) / Stop (done) / + StopFailure (error) / SessionEnd (off) hooks, all async: marks the tmux pane this session runs in + (`@agent` pane option, drawn as ✓ ? ! after the window name by tmux.conf; visiting the pane + greys it out, the next prompt removes it) and buzzes the phone for a new mark on a pane not in + view (termux-notification, else a bell). Claude sessions run in daemon-spawned workers with no + tmux env, so the script finds the pane by the session name Claude puts in the pane title. Shared with codex + (`~/.codex/hooks.json`, untracked), pi and opencode. No-op outside tmux. +- `hooks/drift-check.sh` — SessionStart + UserPromptSubmit hook, read-only: fails loudly when a + `~/.config/claude/*` file has broken out of the repo into a plain file, or `~/.claude/*` no longer + resolves into the dots repo. That is what Claude Code's atomic settings rewrite does through the + stow layer — on 2026-09-15 it silently reverted the live config to a stale snapshot for an hour, + dropping four hook events. At session start the warning is shown to you (exit 2, session goes + on); on each prompt any drift is fed to Claude as context so it reports it. Fix is still + `link.sh` (heals identical copies, warns otherwise). +- `hooks/local-commands.py` — UserPromptExpansion hook: **TUI-side slash commands**. When you type + `/x` and `skills/x/local.py` exists, the hook runs it with the arguments, shows its output to you + and blocks the expansion (exit 2), so no prompt reaches the model and it costs nothing. Skills + without a `local.py` expand as usual. Caveat baked into the design: the hook fires *after* the + skill body expanded, so a skill with a `local.py` must not also act via a `!` inline command. +- `skills/` — custom [Agent Skills](https://code.claude.com/docs/en/skills). See **Skills** below. +- `link.sh` — idempotent bootstrap that creates the `~/.claude` symlinks below. +- `../git/claude-commit-msg` + `../git/hooks/prepare-commit-msg` — the commit-message handoff. + A session pipes its suggestion into `claude-commit-msg save` (run inside the target repo), which + stores it as its own file under `$(git rev-parse --git-path CLAUDE_COMMIT_MSG.d)/` **with the paths + it staged**; on the next `git commit` / lazygit `C` the hook prefills the editor with the message(s) + whose paths are part of that commit and consumes them (`used/`). Parallel sessions therefore never + overwrite each other, and committing one session's files gets that session's message. + `claude-commit-msg list` shows what is pending. The old single `CLAUDE_COMMIT_MSG` file is still + honoured. Both tracked here (deployed to `~/.config/git/`); the hook is installed **per repo** — see + setup step 4 — and deliberately not via a global `core.hooksPath`, which would override a project's + own hooks. The prefill only runs for an editor commit: lazygit's `c` panel passes the message to git + directly, so the hook skips and the suggestion stays pending. + +The `settings.json` hook commands for the newer scripts are wrapped in `[ -f … ]`, so a host that +has pulled the repo but not yet re-stowed just skips them instead of blocking every Bash call. + +Paths inside `settings.json` reference `~/.claude/...` via `$HOME`/`PATH` (`/usr/bin/env +python3 ~/.claude/...`), so they work regardless of the username, python location, or where the +dots repo is cloned (`~/.dots`, …). + +## What is **not** tracked (stays local, per device) + +Everything else under `~/.claude/` is machine-specific or secret and must never be committed: +credentials (`.credentials.json`), session history, `projects/` (transcripts + memory), +caches, and the `plugins/` cache/binaries. + +## Setup on a new device + +```sh +# 1. Deploy the dotfiles repo — install.sh stows ~/.config/claude AND runs link.sh for you +cd ~/.dots && ./install.sh + +# 2. Launch Claude and log in once (credentials are NOT synced) +claude + +# 3. Reinstall the plugins from settings.json -> enabledPlugins +# (typescript-lsp, frontend-design — anthropics/claude-plugins-official) via /plugin. +# Optional: install any formatters you want the hook to use (stylua, ruff, prettier, …), +# and libnotify (notify-send) on GUI hosts for hooks/notify.py. +``` + +```fish +# 4. In every repo you commit in: install the commit-message prefill hook. New clones/inits get it +# from ~/.config/git/template (init.templateDir) once that template hook is a symlink to it too. +ln -sf ~/.config/git/hooks/prepare-commit-msg (git rev-parse --git-path hooks)/prepare-commit-msg +``` + +`install.sh` deploys `~/.config/claude` (via stow) and then runs `link.sh` automatically. You only +need to run `link.sh` by hand (`bash ~/.config/claude/link.sh`) if a link later gets clobbered +(e.g. Claude's `/config` replaces one with a plain file) — it's idempotent and self-healing. + +Tracked *files* in `~/.claude` link straight at the repo copy, not through `~/.config/claude`: +Claude Code follows one symlink hop and then replaces the file atomically (temp + rename), so the +old two-hop chain lost its middle link to a plain file on every settings write (`/model`, effort, +plugins, `/config`) and the repo stopped seeing changes. With one hop the rename lands in the +checkout. Dirs (`hooks`, `skills`) still go through `~/.config/claude`. + +A **new skill/hook** added to the repo shows up after a re-stow — `./install.sh` (or `dotsync`) links +the new file into `~/.config/claude`, which `link.sh` then surfaces into `~/.claude`. + +## Skills + +Custom skills live in `skills//SKILL.md` (the directory name is the `/command`) and are +linked in as `~/.claude/skills`. All are `disable-model-invocation: true` — explicit `/` only, +so Claude never auto-triggers them. Run them inside the repo whose branch you're working on. + +- **`/review-branch [base]`** — reviews the current branch's diff (vs its merge-base with the + base branch) for 🐞 bugs / 🔒 security / ⚡ optimizations / 📖 readability, reports grouped + findings with `file:line`, then applies the readability + safe fixes *after you approve*. Never + commits. + Borrows `/code-review`'s discipline: CLAUDE.md-aware, changed-lines-only, verified bugs with a + false-positive filter (skips what linters/CI catch and pre-existing issues). Ends by pointing + you at the relevant built-in follow-ups (`/security-review`, `/code-review`, `/verify`, …). +- **`/pr-description [base]`** — auto-detects this repo's GitHub PR template + (`.github/pull_request_template.md`, …), fills it from the branch diff + commits, prints a + copy-paste markdown block, and copies it to the clipboard with `wl-copy`. Leaves verification + checkboxes for you; never creates/pushes the PR. +- **`/commit-msg [hint]`** — reads the **staged** diff, infers the repo's commit style from recent + `git log` (e.g. this repo's `[Scope] summary`), drafts a matching message, prints it, and saves + it for the `prepare-commit-msg` hook (lazygit `C` prefills it). Never stages or commits — draft + only. +- **`/verbose [on|off|status]`** — flips the *persisted* verbose view for the current project: + `viewMode` (`verbose` / `default` — the key that actually decides the view and beats a sticky + `/focus` choice for new sessions) plus `verbose` and `showThinkingSummaries`, written to the + project's `.claude/settings.local.json` (machine-local, never committed) rather than the tracked + `settings.json`, so a toggle never shows up as a dots diff. Runs **TUI-side** — `local.py` via + `hooks/local-commands.py`, no model turn — with the SKILL.md body as the fallback on a host + where the hook isn't deployed. The *live* toggle is a keypress: `ctrl+x v` / `ctrl+o`. +- **`/pr-loop [pr]`** — babysits the current branch's PR in a self-paced loop: fixes review + comments that don't need your input — from **any** reviewer (Codex, Claude, humans) plus any + `@claude` request — `git add`s them, drafts the commit message (`/commit-msg` style) and marks + each thread with a reaction instead of an "Addressed — …" reply: **👍** fixed, **👀** parked for + your decision, **👎** a bot false positive (bots only, always with a one-line why). Then pings you + to commit & push and re-checks every ~10 min (via `ScheduleWakeup`). Resolves threads once their + fix is pushed — dismissals right away, since there's nothing to land. Stops when no unresolved comments + remain or the automated reviewers (Codex/Claude) hit their limit. Prep-only — never + commits/pushes/merges; needs `gh` authed and the session left open. Each cycle it prints when it + will re-check and that `Esc` (between cycles) stops it; on the last cycle it prints a clear + **"Finished — no more active issues"** and does not reschedule. + +## Adding more config later + +Drop the file/dir under `.config/claude/` here, add its name to the `items` list in `link.sh`, +and re-run `bash ~/.config/claude/link.sh`. For example `commands/` or `agents/`. diff --git a/common/.config/claude/StatusBar.md b/common/.config/claude/StatusBar.md new file mode 100644 index 0000000..7f2cdb7 --- /dev/null +++ b/common/.config/claude/StatusBar.md @@ -0,0 +1,83 @@ +# Status line (`statusline.py`) + +The custom Claude Code status line, ordered **work info (left) → system info (right)**, +segments joined by a light-gray `│`. It's **responsive**: always a single line — if the +rendered width would exceed the terminal (`$COLUMNS`, which Claude Code re-exports on +resize), trailing (lowest-priority) segments are dropped from the right until it fits. + +Wide — everything: + +``` +📁 ~/.dots │ 🌿 .dots main* │ 💬 #42 3 · codex 2 │ 🤖 Fable 5 (1M) · xhigh │ 📝 84% (843k) │ 📊 34% 2h54m │ 💰 $0.40 $12.00/h │ 🔢 ↑63M ↓595k │ ⚡ 63 t/s │ ♻️ 91% 1h │ 💾 81% +``` + +Narrow — trailing segments trimmed: + +``` +📁 ~/.dots │ 🌿 .dots main* │ 💬 #42 3 · codex 2 │ 🤖 Fable 5 (1M) · xhigh │ 📝 84% (843k) │ 📊 34% 2h54m +``` + +Every segment is defensive: if its data is missing or a command fails, the segment is +simply omitted (the bar never crashes the UI). Secondary detail (the parts in light gray) +is supplementary to the main colored value. + +## Live segments + +| | Segment | Shows | Notes | +|---|---|---|---| +| | **Vim mode** | `[I]`/`[N]`/`[V]` editor mode | only with `editorMode: vim`; pair with `hideVimModeIndicator: true` so the built-in one doesn't duplicate it | +| 📁 | **Directory** | Current working dir, with `~` for home | cyan | +| 🌿 | **Git** | `repo branch` + `*` if dirty + `↑N`/`↓N` ahead/behind upstream | repo = magenta; branch = green when clean, yellow + red `*` when dirty; `↑` cyan, `↓` yellow. Omitted outside a repo | +| 💬 | **PR review threads** | `#N` of the current branch's open PR + its **unresolved review threads** (any author, outdated ones included; `+` past 100), Codex's share broken out as `· codex N`; green `✓` when none are left | A thread counts for whoever opened it (its first comment's author; Codex = login matching `codex`, as in `/pr-loop`). PR-conversation comments are not counted — they have no resolved state, so a summary or an LGTM would never let it reach zero. A GitHub round trip is ~0.7 s, so a render only reads the per-branch cache `~/.claude/cache/statusline.pr..json` and, once it is older than 90 s, spawns a detached `statusline.py --pr-refresh` that updates it (one at a time, via a `.lock` claim) — new counts show on the next render. A failed fetch (no GitHub remote — e.g. this repo on gitea —, gh not authed, offline) backs off 10 min and keeps the last counts with a gray `?`. Omitted with no `gh`, no open PR or a detached HEAD | +| 🤖 | **Model** | Active model display name + `· effort` level (`low`/`medium`/`high`/`xhigh`) | name = blue, effort = light gray; effort omitted for models without the param | +| 📝 | **Context** | `% of context window used` + `(Nk)` tokens | usage comes from the payload's `context_window` (`used_percentage` + `current_usage`, Claude Code 2.1.x); the transcript's last `message.usage` is only a fallback. Window from `context_window.context_window_size`, then `(1M …)` in the display name, else 200k — **not** from `model.id`, which arrives with any `[1m]` suffix already stripped. Adds a red **⚠compact** at ≥80% | +| 📊 | **5h usage** | `% of the 5-hour rolling limit used` + time until it resets | from `rate_limits.five_hour`; Pro/Max only, and absent until the first API response of a session | +| 💰 | **Cost** | `$` session cost so far + `$/h` burn rate | burn rate shown once the session exceeds ~30s | +| 🔢 | **Session tokens** | `↑` input + `↓` output tokens used so far this session (cumulative, `k`/`M`) | summed over the transcript's assistant `message.usage` blocks, de-duplicated by message id (one line per content block shares the same usage). Input = `input + cache_creation + cache_read` — everything billed as input, so on a 1M session it dwarfs output (every call re-reads the cached prefix). Main transcript only: subagent usage lives in separate sidechain files. Incremental: a per-session state file `~/.claude/cache/statusline.tokens..json` remembers the byte offset already summed, so each refresh parses only the new tail (warm ≈ 0.2 ms), at most 8 MiB per refresh (≈ 150 ms) — Claude Code kills a status script when the next refresh fires, so a cold scan of a huge resumed transcript is spread over a few refreshes (totals climb, then settle) instead of restarting from zero each time. Stale state files are pruned after 7 days once 50+ pile up. Omitted when there is no transcript; `↑` cyan, `↓` green, no thresholds | +| ⚡ | **Decode speed** | `N t/s` — tokens per second the model is generating | duration-weighted mean over the last 8 thinking blocks of the main conversation: `thinking_tokens / thinkingDurationMs` from the same transcript scan (blocks under 1 s or 50 tokens skipped). The only clean per-call timing Claude Code records: the payload's `cost.total_api_duration_ms` also absorbs subagent and advisor calls (it grew 28 s in a 12 s wall interval with no main-conversation completion) and its `output_tokens` is sometimes a mid-stream partial, so neither can give a rate. Includes first-token latency, so short blocks read a little low and long ones converge on the real decode speed (Fable 5.1 measured 60–85 t/s). Needs thinking enabled — omitted until a thinking block has completed, never shown with thinking off | +| ♻️ | **Prompt cache** | hit `%` (higher is better) + cache TTL (`5m` / `1h`), yellow `·cold` once it has expired | from the payload's `prompt_cache` (2.1.260+: `hit_ratio` 0–1, `ttl`, `warm`); computed from usage on older payloads. A `1h` TTL is what keeps a 10-min `/pr-loop` cadence warm | +| 💾 | **Disk** | `% used` of the filesystem at the cwd | from `statvfs` | + +## Colour legend + +Most numbers are **green / yellow / red** by threshold — green = healthy, red = needs +attention. Light gray = secondary detail. Thresholds (`green < … < yellow < … ≤ red`): + +| Segment | green | yellow | red | +|---|---|---|---| +| Context | `< 50%` | `50–80%` | `≥ 80%` (⚠compact) | +| PR review threads | `✓` none unresolved | thread count | `codex N` | +| 5h usage | `< 50%` | `50–80%` | `≥ 80%` | +| Decode speed (inverted) | `≥ 40 t/s` | `20–40 t/s` | `< 20 t/s` | +| Prompt cache (inverted) | `≥ 80%` | `50–80%` | `< 50%` | +| Disk | `< 75%` | `75–90%` | `≥ 90%` | + +> Light gray is `\033[37m`; dimming (`\033[2m`) is disabled because it blended the gray +> detail text into dark terminal backgrounds. To go brighter, set `"gray"` to `\033[97m` +> (bright white) in the `C` table near the top of `statusline.py`. + +## Optional segments (defined but not shown) + +These functions exist in `statusline.py` but aren't in the output. Enable one by adding it +to the `work` or `system` list in `main()`: + +RAM/CPU/temp were **retired 2026-07-26**: the status line only refreshes on message +events, so system metrics sat visibly stale between turns — the tmux status bar +(`tmux/scripts/`) owns live system metrics now. + +| | Function | Shows | +|---|---|---| +| 🧠 | `ram_segment` | `% used` + `used/totalG` from `/proc/meminfo` (green `<70%` / yellow / red `≥85%`) | +| 🖥️ | `cpu_segment` | `% busy` (diffed `/proc/stat` snapshot) + loadavg + cores (green `<60%` / red `≥85%`) | +| 🌡️ | `temp_segment` | hottest CPU thermal zone °C (green `<60` / red `≥80`) | +| ✏️ | `velocity_segment` | `+added/-removed` lines this session + lines/min | +| ⚙️ | `api_segment` | share of wall-clock time spent in API/inference | +| | `version_segment` | Claude Code version (`vX.Y.Z`) | +| 🎨 | `style_segment` | active output-style name | + +## Where it lives + +`statusline.py` is tracked in this repo and symlinked to `~/.claude/statusline.py`; +`settings.json` runs it via `statusLine` (`/usr/bin/env python3 ~/.claude/statusline.py`) on every +message event and, through `refreshInterval: 60`, once a minute while the session idles — so the PR +count moves while you wait on a review. Edits take effect on the next status refresh. diff --git a/common/.config/claude/hooks/drift-check.sh b/common/.config/claude/hooks/drift-check.sh new file mode 100755 index 0000000..59b1050 --- /dev/null +++ b/common/.config/claude/hooks/drift-check.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# SessionStart hook: refuse to let a severed dotfiles link go unnoticed. +# +# Claude Code writes settings with an atomic temp+rename. Through the stow layer that can +# replace ~/.config/claude/ (a symlink into the repo) with a plain FILE holding whatever +# snapshot the writing process had in memory -- silently freezing every later repo edit out +# of the live config. It happened on 2026-09-15 23:31: a stale copy dropped four hook events +# (git-guard among them) and nobody noticed for an hour. link.sh heals the identical case but +# only when run; this makes every session start say so instead. +# +# Read-only: it never relinks. Exit 2 on SessionStart shows stderr to the user and the session +# continues. Exit 0 when everything resolves into the repo. +set -u +src="$HOME/.config/claude" +bad="" +for f in settings.json statusline.py keybindings.json CLAUDE.md link.sh; do + p="$src/$f" + [ -e "$p" ] || continue + if [ ! -L "$p" ]; then bad="$bad $p is a plain file (should be a symlink into the dots repo)"$'\n'; fi +done +# the ~/.claude side too: link.sh's own guard covers it, but only when link.sh runs +for f in settings.json keybindings.json CLAUDE.md statusline.py; do + p="$HOME/.claude/$f" + [ -e "$p" ] || continue + case "$(readlink -f "$p")" in + *"/.dots/"*) ;; + *) bad="$bad $p resolves to $(readlink -f "$p"), not into the dots repo"$'\n' ;; + esac +done +[ -z "$bad" ] && exit 0 +printf 'DRIFT: Claude config has broken out of the dots repo; the live config is a stale copy.\n%s fix: review with `diff`, then `bash ~/.config/claude/link.sh` (heals identical copies, warns otherwise)\n' "$bad" >&2 +exit 2 diff --git a/common/.config/claude/hooks/format.py b/common/.config/claude/hooks/format.py new file mode 100755 index 0000000..8dc6ed0 --- /dev/null +++ b/common/.config/claude/hooks/format.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +"""PostToolUse hook: format an edited file with the right formatter. + +Reads the hook JSON from stdin, works out which file(s) were just edited, and runs a +language-appropriate formatter -- but, to avoid imposing a style on a project +that never asked for it, every formatter here only runs when the project opts in +via a config file discoverable by walking up from the edited file: stylua, ruff, +prettier and taplo on their own configs, gofmt and rustfmt on go.mod / Cargo.toml, +shfmt and fish_indent on .editorconfig. No marker, no formatting -- a repo that +hand-formats its shell keeps its own layout. + +Two entry points, both wired in settings.json > hooks > PostToolUse: + * Edit|Write -- the edited path is `tool_input.file_path`. + * Bash -- under `defaultMode: auto` Claude is steered to edit through the shell + (sed -i, heredocs, python), which the Edit|Write matcher never sees. + There is no per-file event for that (`FileChanged` only watches literal + filenames), so this scans `tool_input.command` for path-like tokens with a + handled extension and formats the ones modified in the last few seconds -- + the mtime gate keeps a parallel session's dirty files out of it. + +Best-effort: always exits 0 so a format hiccup never blocks an edit. jq is not +guaranteed on the host, hence python for the stdin JSON parse. +""" +import fnmatch +import json +import os +import re +import shutil +import subprocess +import sys +import time + + +def find_up(start, names): + """Nearest ancestor dir (incl. the file's own) containing any of `names`.""" + d = os.path.dirname(os.path.abspath(start)) + while True: + if any(os.path.exists(os.path.join(d, n)) for n in names): + return d + parent = os.path.dirname(d) + if parent == d: + return None + d = parent + + +def _expand_braces(pat): + """`a{b,c}` -> [`ab`, `ac`] (editorconfig sections use {,} alternation).""" + m = re.search(r"\{([^{}]*)\}", pat) + if not m: + return [pat] + out = [] + for alt in m.group(1).split(","): + out.extend(_expand_braces(pat[: m.start()] + alt + pat[m.end():])) + return out + + +def editorconfig_covers(path): + """True if the nearest ancestor .editorconfig has a section matching `path`. + + Mere existence is NOT opt-in: this repo's .editorconfig is deliberately scoped + to `[{*.sh,dotsync,dotpub}]` with no [*] block precisely so fish files stay + untouched, and a generic upstream .editorconfig must not switch a formatter on + for filetypes it never mentions. Patterns without a `/` match the basename + (the editorconfig convention); ones with a `/` match the path relative to the + .editorconfig's directory. + """ + d = find_up(path, [".editorconfig"]) + if not d: + return False + name = os.path.basename(path) + rel = os.path.relpath(os.path.abspath(path), d) + try: + with open(os.path.join(d, ".editorconfig"), errors="ignore") as fh: + for line in fh: + line = line.strip() + if not (line.startswith("[") and line.endswith("]")): + continue + for pat in _expand_braces(line[1:-1]): + target = rel if "/" in pat else name + if fnmatch.fnmatch(target, pat.lstrip("/")): + return True + except Exception: + pass + return False + + +def has_toml_section(start, filename, section): + """True if the nearest ancestor `filename` contains `section`.""" + d = find_up(start, [filename]) + if not d: + return False + try: + with open(os.path.join(d, filename), errors="ignore") as fh: + return section in fh.read() + except Exception: + return False + + +def stylua_cmd(path): + exe = os.path.expanduser("~/.local/share/nvim/mason/bin/stylua") + if not os.access(exe, os.X_OK): + exe = shutil.which("stylua") + if exe and find_up(path, [".stylua.toml", "stylua.toml"]): + return [exe, path] + return None + + +def ruff_cmd(path): + exe = shutil.which("ruff") + if exe and (find_up(path, ["ruff.toml", ".ruff.toml"]) + or has_toml_section(path, "pyproject.toml", "[tool.ruff")): + return [exe, "format", path] + return None + + +_PRETTIER_CFGS = [ + ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", + ".prettierrc.json5", ".prettierrc.js", ".prettierrc.cjs", ".prettierrc.mjs", + ".prettierrc.toml", "prettier.config.js", "prettier.config.cjs", + "prettier.config.mjs", +] + + +def prettier_cmd(path): + exe = shutil.which("prettier") + if exe and find_up(path, _PRETTIER_CFGS): + return [exe, "--write", path] + return None + + +def gofmt_cmd(path): + exe = shutil.which("gofmt") + if exe and find_up(path, ["go.mod"]): # one canonical style + return [exe, "-w", path] + return None + + +def rustfmt_cmd(path): + exe = shutil.which("rustfmt") + if exe and find_up(path, ["Cargo.toml", "rustfmt.toml", ".rustfmt.toml"]): + return [exe, path] + return None + + +# Shell and fish are opt-in too, gated on an .editorconfig SECTION that matches the file +# (shfmt reads .editorconfig natively for its settings, so the marker and the tool agree). +# "One canonical style" turned out not to mean "the style the project uses": 3 of ~/.dots's +# 25 fish files are not fish_indent-clean, so running these on sight rewrote whole files and +# buried a 40-line change in a 200-line diff. ~/.dots opts its shell in via +# `[{*.sh,dotsync,dotpub}]` while its fish files stay hand-formatted — existence of the +# .editorconfig alone must not turn either formatter on. +# Neovim agrees: conform.nvim there lists lua/css/html/ts/js only — never sh or fish. +def fish_cmd(path): + exe = shutil.which("fish_indent") + if exe and editorconfig_covers(path): + return [exe, "-w", path] + return None + + +def shfmt_cmd(path): + exe = shutil.which("shfmt") + if exe and editorconfig_covers(path): + return [exe, "-w", path] + return None + + +def taplo_cmd(path): + exe = shutil.which("taplo") + # opt-in: TOML reflow/align is intrusive, so only where the project asked. + if exe and find_up(path, ["taplo.toml", ".taplo.toml"]): + return [exe, "format", path] + return None + + +HANDLERS = { + ".lua": stylua_cmd, + ".py": ruff_cmd, + ".js": prettier_cmd, ".jsx": prettier_cmd, ".mjs": prettier_cmd, + ".cjs": prettier_cmd, ".ts": prettier_cmd, ".tsx": prettier_cmd, + ".css": prettier_cmd, ".scss": prettier_cmd, ".less": prettier_cmd, + ".html": prettier_cmd, ".vue": prettier_cmd, ".json": prettier_cmd, + ".md": prettier_cmd, ".yaml": prettier_cmd, ".yml": prettier_cmd, + ".go": gofmt_cmd, + ".rs": rustfmt_cmd, + ".fish": fish_cmd, + ".sh": shfmt_cmd, ".bash": shfmt_cmd, + ".toml": taplo_cmd, +} + + +RECENT_SECS = 30 # a Bash edit is "ours" if the file changed this recently + +_EXT_ALT = "|".join(re.escape(e[1:]) for e in HANDLERS) +_PATHISH = re.compile(r"[\w.~/@+-]+\.(?:" + _EXT_ALT + r")\b") + + +def format_one(path): + if not path or not os.path.isfile(path): + return + # Resolve symlinks before walking for markers: deployed dotfiles get edited via + # their ~/.config/... links, but the opt-in configs live beside the real file in + # the repo — a lexical walk from the link's path would never find them. + path = os.path.realpath(path) + handler = HANDLERS.get(os.path.splitext(path)[1].lower()) + if not handler: + return + cmd = handler(path) + if not cmd: + return + try: + subprocess.run(cmd, timeout=15, capture_output=True) + except Exception: + pass + + +def recent_paths_in_command(command, cwd): + """Files a shell command plausibly just wrote: path-like tokens with a handled + extension, resolved against the tool's cwd, that exist and changed within RECENT_SECS. + Unchanged mentions (the source of a `cp`, a file merely grepped) fail the mtime gate.""" + now = time.time() + seen, out = set(), [] + for tok in _PATHISH.findall(command or ""): + p = os.path.expanduser(tok) + if not os.path.isabs(p): + p = os.path.join(cwd, p) + p = os.path.normpath(p) + if p in seen: + continue + seen.add(p) + try: + if os.path.isfile(p) and now - os.path.getmtime(p) <= RECENT_SECS: + out.append(p) + except OSError: + pass + return out + + +def main(): + try: + data = json.load(sys.stdin) + except Exception: + return + ti = data.get("tool_input") or {} + tr = data.get("tool_response") or {} + if data.get("tool_name") == "Bash": + cwd = data.get("cwd") or os.getcwd() + for p in recent_paths_in_command(ti.get("command"), cwd): + format_one(p) + return + format_one(ti.get("file_path") or tr.get("filePath") or "") + + +if __name__ == "__main__": + main() diff --git a/common/.config/claude/hooks/git-guard-test.sh b/common/.config/claude/hooks/git-guard-test.sh new file mode 100755 index 0000000..52ad051 --- /dev/null +++ b/common/.config/claude/hooks/git-guard-test.sh @@ -0,0 +1,223 @@ +#!/usr/bin/env bash +# Regression matrix for git-guard.py: `bash ~/.claude/hooks/git-guard-test.sh` (exit 1 on mismatch). +# Kept as a file on purpose: typed inline, the very commands under test would trip the live hook. +G="$(dirname "$(readlink -f "$0")")/git-guard.py" +fail=0 +# No exempt repository for the rows that do not ask for one, whatever this host's ~/.claude/git-guard-exempt says. +export GIT_GUARD_EXEMPT="" +# `git reset ` is allowed only for an existing path: give the matrix one to point at. +tmp=$(mktemp -d) && cd "$tmp" && touch existing.py +trap 'rm -rf "$tmp"' EXIT +run() { + printf '%s' "{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":$(python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$2")}}" | python3 "$G" 2>/dev/null + rc=$? + got=allow + [ $rc -eq 2 ] && got=block + [ "$got" = "$1" ] && mark=ok || { + mark=MISMATCH + fail=1 + } + printf '%-8s %-6s %-6s %s\n' "$mark" "$1" "$got" "$(printf '%s' "$2" | head -1)" +} +echo "--- must block: commits / history ---" +run block 'git push' +run block 'git -C /home/coja/.dots push origin main' +run block 'git -c user.name=x commit -m fix' +run block '/usr/bin/git push' +run block 'env GIT_DIR=.git git push' +run block 'timeout 5 git push' +run block 'sudo -u me git push' +run block 'cd /tmp && git push' +run block 'git status; git commit -am wip' +run block 'x=1; git push' +run block 'git push 2>&1 | tee log' +run block "sh -c 'git push origin HEAD'" +run block 'eval "git push"' +run block 'git -C $(pwd) push' +run block 'echo "$(git push)"' +run block 'git --git-dir=/x/.git --work-tree=/x push' +run block 'git commit -m "fix: grep pattern; not a command"' +run block 'git revert HEAD' +run block 'git cherry-pick abc123' +run block 'git rebase -i HEAD~3' +run block 'git rebase --interactive main' +run block 'git -C . rebase -i --autosquash main' +run block 'git rebase --autostash origin/main' +run block 'git -c rebase.autoStash=true rebase main' +run block 'git merge feature' +run block 'git merge --no-ff feature' +echo "--- must block: discards working-tree changes ---" +run block 'git reset --hard HEAD~1' +run block 'git reset HEAD~1 --hard' +run block 'git reset --soft HEAD~1' +run block 'git reset --keep HEAD~2' +run block 'git reset --merge' +run block 'git reset' +run block 'git reset -q' +run block 'git reset HEAD' +run block 'git reset HEAD~1' +run block 'git reset abc1234' +run block 'git reset 0123456789abcdef0123456789abcdef01234567' +run block 'git reset origin/main' +run block 'git reset @{u}' +run block 'git restore --staged .' +run block 'git restore --staged :/' +run block 'git clean -fd' +run block 'git -C . clean -n' +run block 'git restore file.py' +run block 'git restore --staged --worktree file.py' +run block 'git restore -W file.py' +run block 'git checkout -- .' +run block 'git checkout -- file.py' +run block 'git checkout HEAD -- file.py' +run block 'git checkout .' +run block 'git checkout -f main' +run block 'git stash drop' +run block 'git stash pop' +run block 'git stash clear' +run block 'git branch -D feature' +run block 'git branch -f main HEAD~1' +run block 'git branch -M main trunk' +echo "--- must block: gh pr write ops (create only with --head, edit only title/body) ---" +run block 'gh pr merge 12 --squash' +run block 'gh pr close 4' +run block 'gh -R o/r pr create --fill' +run block 'gh pr create --title x --body y' +run block 'gh pr create --dry-run --fill' +run block 'gh pr edit 3 --add-reviewer bob' +run block 'gh pr edit 3 --title x --base main' +run block 'gh pr edit --add-label=bug 3' +run block 'gh pr edit 3 -b y -m v2' +echo "--- must allow ---" +run allow 'git status' +run allow 'git log -1 --oneline' +run allow 'git diff --cached --stat' +run allow 'git add -A common/.config/claude' +run allow 'git rev-parse --git-path CLAUDE_COMMIT_MSG' +run allow 'git -c core.pager=cat log -3' +run allow 'git reset -- file.txt' +run allow 'git reset HEAD file.txt' +run allow 'git reset HEAD existing.py other.py' +run allow 'git reset existing.py' +run allow 'git reset -p' +run allow 'git reset -- .' +run allow 'git restore --staged existing.py' +run allow 'git restore --staged file.py' +run allow 'git restore -S file.py' +run allow 'git checkout main' +run allow 'git checkout -b feature' +run allow 'git switch main' +run allow 'git merge --abort' +run allow 'git rebase main' +run allow 'git rebase origin/main' +run allow 'git rebase -Xtheirs main' +run allow 'git rebase --continue' +run allow 'git rebase --abort' +run allow 'git -c core.editor=true rebase --continue' +run allow 'GIT_EDITOR=true git rebase --continue' +run allow 'git stash' +run allow 'git stash list' +run allow 'git stash push -m wip' +run allow 'git stash show -p' +run allow 'git branch -d merged-branch' +run allow 'git branch --list' +run allow 'git branch -vv' +run allow 'git commit-tree HEAD^{tree} -m x' +run allow 'git worktree list' +run allow 'grep -rn "git push" README.md' +run allow 'grep -n "foo; git commit" file' +run allow "echo 'git push'" +run allow 'echo "run git push"' +run allow "cat > README.md <<'EOF' +Deploy with: + git status; git commit -am x; git push origin main +EOF +echo written" +run allow 'python3 - < : the hook input carries the session's cwd, as Claude Code sends it. +R=$tmp/repo +WT=$tmp/repo-wt +git init -q "$R" && git -C "$R" -c user.name=t -c user.email=t@t commit -q --allow-empty -m init \ + && git -C "$R" worktree add -q "$WT" 2>/dev/null && mkdir -p "$R/sub" && git init -q "$tmp/other" +runin() { + printf '%s' "$(python3 -c 'import json,sys; print(json.dumps({"tool_name":"Bash","tool_input":{"command":sys.argv[1]},"cwd":sys.argv[2]}))' "$3" "$2")" | GIT_GUARD_EXEMPT=$R python3 "$G" 2>/dev/null + rc=$? + got=allow + [ $rc -eq 2 ] && got=block + [ "$got" = "$1" ] && mark=ok || { + mark=MISMATCH + fail=1 + } + printf '%-8s %-6s %-6s [%s] %s\n' "$mark" "$1" "$got" "${2#"$tmp"/}" "$(printf '%s' "$3" | head -1)" +} +runin allow "$R" 'git commit -m "docs: x"' +runin allow "$R" 'git commit -m x -- docs/usage.md' +runin allow "$R" 'git commit -m"fix a bug"' +runin allow "$R" 'git commit -m "-a is not the flag here"' +runin allow "$R" 'git commit --allow-empty -m x' +runin allow "$R/sub" 'git commit -m x' +runin allow "$R" 'git merge --ff-only feature' +runin allow "$R" 'git merge --no-ff feature' +runin allow "$WT" 'git commit -m x' +runin allow "$tmp" "git -C $WT commit -m x" +runin allow "$tmp" "cd $R && git commit -m x" +runin allow "$tmp" 'cd repo && git commit -m x' +runin allow "$tmp" "cd $WT; git status; git merge main" +runin allow "$R" "sh -c 'git commit -m x'" +runin block "$R" 'git push' +runin block "$R" 'git commit --amend --no-edit' +runin block "$R" 'git commit -am wip' +runin block "$R" 'git commit -qa -m wip' +runin block "$R" 'git commit --all -m wip' +runin block "$R" 'git rebase -i main' +runin block "$R" 'git cherry-pick abc123' +runin block "$R" 'git revert HEAD' +runin block "$R" 'git reset --hard HEAD~1' +runin block "$R" 'git checkout -- file.py' +runin block "$R" 'GIT_DIR=/x/.git git commit -m x' +runin block "$R" 'env GIT_WORK_TREE=/x git commit -m x' +runin block "$R" 'git --git-dir=/x/.git commit -m x' +runin block "$R" 'git -C /tmp commit -m x' +runin block "$R" 'git -C $(mktemp -d) commit -m x' +runin block "$tmp" "cd $R && cd /tmp && git commit -m x" +runin block "$R" 'cd - && git commit -m x' +runin block "$R" 'cd $HOME && git commit -m x' +runin block "$R" 'pushd /tmp && git commit -m x' +runin block "$tmp" 'git commit -m x' +runin block "$tmp/other" 'git commit -m x' +runin block "$tmp" "git -C $tmp/other merge x" +echo "--- fail-open ---" +printf '%s' '{"tool_name":"Edit","tool_input":{"command":"git push"}}' | python3 "$G" +[ $? -eq 0 ] && echo "ok non-Bash tool ignored" || { + echo "MISMATCH non-Bash" + fail=1 +} +printf 'not json' | python3 "$G" +[ $? -eq 0 ] && echo "ok garbage stdin passes" || { + echo "MISMATCH garbage" + fail=1 +} +[ $fail -eq 0 ] && echo "GIT-GUARD MATRIX: all ok" || { + echo "GIT-GUARD MATRIX: mismatches above" + exit 1 +} diff --git a/common/.config/claude/hooks/git-guard.py b/common/.config/claude/hooks/git-guard.py new file mode 100755 index 0000000..07cb613 --- /dev/null +++ b/common/.config/claude/hooks/git-guard.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""PreToolUse hook (Bash): enforce the no-commit / no-push contract structurally. + +settings.json's deny rules (`Bash(git push:*)`, ...) match a literal *prefix* of the +command text, so `git -C . push`, `git -c k=v commit`, `/usr/bin/git push`, +`env X=1 git push`, `timeout 5 git push` and `sh -c 'git push'` all slip past them. +This hook parses each shell segment instead: finds the git/gh token wherever it sits, +skips git's global options (`-C dir`, `-c k=v`, `--git-dir=...`) and blocks + + git commit | push | revert | cherry-pick | merge (not --abort/--quit/--continue) + git rebase -i / --interactive / --autostash + git clean | reset (any form that moves HEAD or unstages everything; `reset -- `, + `reset HEAD ` and `reset ` are fine) | restore (--staged + alone is fine, except `--staged .` / `:/`) | checkout -- / checkout . / -f + git stash drop | pop | clear git branch -D / -f / -M + gh pr merge | close | create without --head | edit beyond --title/--body + +i.e. anything that commits, rewrites history, or discards working-tree changes -- the last +group matters most with several sessions sharing one checkout. Mirrors pi's permission-gate. +On GitHub Claude may open a PR (settings.json asks first) and retitle / redescribe one, nothing +more: `gh pr create` must name its branch with --head, without which gh pushes it itself (even +under --dry-run), and `gh pr edit` must not touch reviewers, labels, base or the like. +A plain `git rebase` (and its --continue / --abort) passes: Claude rebases and fixes the +conflicts when the user asks (global CLAUDE.md), and settings.json asks before each one, as +pi's gate does. `-i` stays blocked (the squash/reword tool, and it needs an editor), and so +does --autostash: it stashes and re-pops other sessions' uncommitted edits, where a plain +rebase refuses to start on a dirty tree. + +Exit 2 + one stderr line = the call is blocked and Claude reads the reason (stage and +stop; /commit-msg drafts the message). Mirrors pi's permission-gate.ts. + +Tokenizing is quote-aware first (shlex in punctuation mode), and only then split at the +separators `;`, `|`, `&&`, `(`, `)`: a quoted word that merely *contains* a separator and a +git verb (a grep pattern, a commit message) stays one word and is not a command. `$(...)` +and backtick bodies are scanned on their own and then collapsed, so `git -C $(pwd) push` +still parses as a push. `sh -c '...'` and `eval` bodies recurse. + +Deliberate gaps: heredoc bodies are skipped -- they are file/script *contents*, and a +README that documents pushing must stay writable -- so a script piped in through a heredoc +is not inspected. Aliases (`git ci`) are not expanded. The deny list, the auto-mode +classifier and the global CLAUDE.md still cover those; this is the belt for the prefix +rules' braces. Fails open: any parse error lets the command through (exit 0). + +Exempt repositories (one main checkout per line in ~/.claude/git-guard-exempt, host-local and +outside the dots repo on purpose: it names projects): there `git commit` and `git merge` pass +-- the user's decision for repos where Claude commits and merges itself. The repo is the one the call +actually targets: the hook input's `cwd`, moved by every `cd` before it in the command and by +`git -C`, resolved to its main checkout (so its worktrees count). Anything that hides the +target (`cd -`, `cd $VAR`, a substitution, `--git-dir`, `GIT_DIR=`) is judged not exempt. +`commit --amend` and `commit -a`/`--all` stay blocked there (they rewrite the last commit of +a shared checkout, or sweep other sessions' edits in), as do push, `rebase -i` and the discard +group. Known gap: a `cd` inside `( ... )` leaks into the commands after the parenthesis. +""" +import json +import os +import re +import shlex +import subprocess +import sys + +GIT_BLOCK = {"commit", "push", "clean", "revert", "cherry-pick"} +MERGE_OK = {"--abort", "--quit", "--continue"} +REBASE_BLOCK = {"-i", "--interactive", "--autostash"} +STASH_BLOCK = {"drop", "pop", "clear"} +BRANCH_FORCE = {"-D", "-f", "--force", "-M"} +RESET_MODES = {"--hard", "--soft", "--merge", "--keep"} +UNSTAGE_ALL = {".", ":/", "*", ":"} +_HEX = re.compile(r"^[0-9a-f]{7,40}$") + + +def looks_like_ref(a): + return (a in ("HEAD", "ORIG_HEAD", "FETCH_HEAD", "MERGE_HEAD") or a.startswith("refs/") + or "~" in a or "^" in a or "@{" in a or bool(_HEX.match(a))) +GH_PR_BLOCK = {"merge", "close"} +# `gh pr edit` may only retitle and redescribe; these take their value as the next word (or as +# `--title=x` / `-tx`). +GH_EDIT_OK = {"-t", "--title", "-b", "--body", "-F", "--body-file", "-R", "--repo"} +# Repositories (main checkouts; their worktrees count) where Claude commits and merges itself: +# one path per line, `#` comments; a missing file exempts nothing. GIT_GUARD_EXEMPT +# (colon-separated) replaces the file for the test matrix; it is read from the hook's own +# environment (Claude Code's), which a prefix on the checked command cannot reach. +EXEMPT_FILE = "~/.claude/git-guard-exempt" +EXEMPT_VERBS = {"commit", "merge"} +# `git commit` options whose value is the next word (or, for the short ones, the rest of the word). +COMMIT_ARG_SHORT = set("mFCct") +COMMIT_ARG_LONG = {"--message", "--file", "--author", "--date", "--reuse-message", "--reedit-message", + "--fixup", "--squash", "--template", "--trailer", "--cleanup", "--pathspec-from-file"} +# global options that take a *separate* argument; the `--opt=value` spelling is one token. +GIT_OPT_ARG = {"-C", "-c", "--git-dir", "--work-tree", "--exec-path", "--namespace", + "--super-prefix", "--config-env"} +GH_OPT_ARG = {"-R", "--repo"} +SHELLS = {"sh", "bash", "dash", "zsh", "ksh", "fish"} + +# `<<'EOF' ... EOF` / `<<-EOF ... EOF`: drop the body, keep the command around it. +_HEREDOC = re.compile(r"<<-?\s*(['\"]?)(\w+)\1[^\n]*\n.*?\n[ \t]*\2[ \t]*(?=\n|$)", re.S) +# innermost `$(...)` / `...` command substitutions (peeled repeatedly for nesting). +_SUBST = re.compile(r"\$\(([^()]*)\)|`([^`]*)`") +# tokens that end one simple command and start the next. +_SEP = {";", ";;", "|", "||", "|&", "&", "&&", "(", ")"} + + +def _skip_opts(args, with_arg): + j = 0 + while j < len(args) and args[j].startswith("-"): + j += 2 if args[j] in with_arg else 1 + return j + + +def exempt_repos(): + env = os.environ.get("GIT_GUARD_EXEMPT") + if env is not None: + paths = env.split(":") + else: + try: + with open(os.path.expanduser(EXEMPT_FILE)) as f: + paths = [ln.split("#", 1)[0].strip() for ln in f] + except OSError: + return set() + return {os.path.realpath(os.path.expanduser(p)) for p in paths if p} + + +def main_checkout(d): + """The main checkout of the repository `d` lies in (a worktree resolves to it), or None.""" + try: + out = subprocess.run(["git", "-C", d, "rev-parse", "--path-format=absolute", "--git-common-dir"], + capture_output=True, text=True, timeout=3) + except (OSError, subprocess.SubprocessError): + return None + common = out.stdout.strip().rstrip("/") + if out.returncode != 0 or not common: + return None + return os.path.realpath(os.path.dirname(common)) + + +def in_exempt_repo(opts, cwd, pre): + """Whether a git call with global options `opts`, run from `cwd` after the words `pre` of + its own command (`env X=1`, ...), targets an exempt repository.""" + exempt = exempt_repos() + if not exempt or cwd is None or any(t.startswith(("GIT_DIR=", "GIT_WORK_TREE=", "GIT_COMMON_DIR=")) + for t in pre): + return False + d, j = cwd, 0 + while j < len(opts): + a = opts[j] + if a in ("--git-dir", "--work-tree") or a.startswith(("--git-dir=", "--work-tree=")): + return False + if a == "-C": + if j + 1 >= len(opts) or "SUBST" in opts[j + 1] or "$" in opts[j + 1]: + return False + d = os.path.join(d, os.path.expanduser(opts[j + 1])) + j += 2 if a in GIT_OPT_ARG else 1 + return main_checkout(d) in exempt + + +def commit_rewrites_or_sweeps(rest): + """`commit --amend` (rewrites the last commit) or `-a`/`--all` (takes in every modified + tracked file, other sessions' edits included).""" + skip = False + for a in rest: + if skip: + skip = False + continue + if a == "--": + break + if a in ("--amend", "--all"): + return True + if a in COMMIT_ARG_LONG: + skip = True + elif a.startswith("-") and not a.startswith("--"): + for k, ch in enumerate(a[1:], 1): + if ch == "a": + return True + if ch in COMMIT_ARG_SHORT: + skip = k == len(a) - 1 # the value is the next word + break + return False + + +def change_dir(cwd, args): + """Where `cd args` leaves the shell started in `cwd`; None when that cannot be told.""" + args = [a for a in args if a not in ("-L", "-P", "--")] + if not args: + return os.path.expanduser("~") + t = args[0] + if t == "-" or "SUBST" in t or "$" in t or (cwd is None and not t.startswith(("/", "~"))): + return None + return os.path.normpath(os.path.join(cwd or "/", os.path.expanduser(t))) + + +def git_reason(args, cwd=None, pre=()): + j = _skip_opts(args, GIT_OPT_ARG) + if j >= len(args): + return None + sub, rest = args[j], args[j + 1:] + if (sub in EXEMPT_VERBS and not (sub == "commit" and commit_rewrites_or_sweeps(rest)) + and in_exempt_repo(args[:j], cwd, pre)): + return None + if sub in GIT_BLOCK: + return f"git {sub}" + if sub == "rebase": + flag = next((a for a in rest if a in REBASE_BLOCK), None) + if flag == "--autostash" or any(o.lower().startswith("rebase.autostash") for o in args[:j]): + return "git rebase --autostash (stashes other sessions' uncommitted edits)" + return f"git rebase {flag} (interactive history rewrite)" if flag else None + if sub == "reset": + opts = [a for a in rest if a.startswith("-") and a != "--"] + if RESET_MODES & set(opts): + return "git reset --hard/--soft/--merge/--keep (moves HEAD)" + if "-p" in opts or "--patch" in opts or "--" in rest: + return None # interactive, or the explicit path form + pos = [a for a in rest if not a.startswith("-")] + if not pos or pos == ["HEAD"]: + return "git reset (unstages everything, other sessions' rounds included)" + if len(pos) == 1 and (looks_like_ref(pos[0]) or not os.path.exists(pos[0])): + return "git reset (moves HEAD)" + return None # `reset HEAD ` / `reset ` + if sub == "merge" and not (MERGE_OK & set(rest)): + return "git merge (creates a commit)" + if sub == "restore": + staged = any(a in ("--staged", "-S") for a in rest) + worktree = any(a in ("--worktree", "-W") for a in rest) + if not staged or worktree: + return "git restore (discards working-tree changes)" + if UNSTAGE_ALL & {a for a in rest if not a.startswith("-")}: + return "git restore --staged . (unstages everything, other sessions' rounds included)" + if sub == "checkout" and ("--" in rest or "." in rest or "-f" in rest or "--force" in rest): + return "git checkout -- (discards working-tree changes)" + if sub == "stash" and rest and rest[0] in STASH_BLOCK: + return f"git stash {rest[0]}" + if sub == "branch" and BRANCH_FORCE & set(rest): + return "git branch -D/-f (force-deletes or force-moves a branch)" + return None + + +def gh_edit_extra(rest): + """The first `gh pr edit` option that is neither the title nor the body, else None.""" + k = 0 + while k < len(rest): + a = rest[k] + if a == "--": + break + name = a.split("=", 1)[0] + if name in GH_EDIT_OK: + k += 2 if name == a else 1 # skip the value, which may well start with `-` + continue + if a.startswith("-") and not (a[:2] in GH_EDIT_OK and not a.startswith("--")): + return a + k += 1 + return None + + +def gh_reason(args): + j = _skip_opts(args, GH_OPT_ARG) + if j >= len(args) or args[j] != "pr": + return None + rest = args[j + 1:] + k = _skip_opts(rest, GH_OPT_ARG) + if k >= len(rest) or "--help" in rest: + return None + sub, rest = rest[k], rest[k + 1:] + if sub in GH_PR_BLOCK: + return f"gh pr {sub}" + if sub == "create" and not any(a in ("-H", "--head") or a.startswith("--head=") + or (a.startswith("-H") and not a.startswith("--")) for a in rest): + return "gh pr create without --head: gh would push the branch itself" + if sub == "edit": + extra = gh_edit_extra(rest) + if extra: + return f"gh pr edit {extra.split('=', 1)[0]}: only --title / --body edits are allowed" + return None + + +def tokenize(text): + """Quote-aware shell words; the separator characters come out as their own tokens + (shlex punctuation mode). Comment handling is off: a `#` mid-word must not swallow + the rest of the line.""" + lex = shlex.shlex(text, posix=True, punctuation_chars=True) + lex.whitespace_split = True + lex.commenters = "" + try: + return list(lex) + except ValueError: # unbalanced quotes: best effort + return text.split() + + +def segments(toks): + seg = [] + for t in toks: + if t in _SEP: + if seg: + yield seg + seg = [] + else: + seg.append(t) + if seg: + yield seg + + +def scan(text, depth=0, cwd=None): + """Reason string for the first blocked invocation in `text` (run from `cwd`), else None.""" + if depth > 4: + return None + text = _HEREDOC.sub(" ", text) + # command substitutions: scan each body on its own, then collapse it to a plain word so + # the enclosing command still parses (`git -C $(pwd) push` -> `git -C SUBST push`). + bodies = [] + + def _grab(m): + bodies.append(m.group(1) if m.group(1) is not None else m.group(2)) + return " SUBST " + + prev = None + while prev != text: + prev, text = text, _SUBST.sub(_grab, text) + for body in bodies: + r = scan(body, depth + 1, cwd) + if r: + return r + for toks in segments(tokenize(text)): + if toks[0] == "cd": + cwd = change_dir(cwd, toks[1:]) + continue + if toks[0] in ("pushd", "popd"): + cwd = None + continue + for i, tok in enumerate(toks): + base = os.path.basename(tok) + r = None + if base == "git": + r = git_reason(toks[i + 1:], cwd, toks[:i]) + elif base == "gh": + r = gh_reason(toks[i + 1:]) + elif base == "eval": + r = scan(" ".join(toks[i + 1:]), depth + 1, cwd) + elif base in SHELLS and "-c" in toks[i + 1:]: + k = toks.index("-c", i + 1) # `sh -c ''`: the real command is one word + if k + 1 < len(toks): + r = scan(toks[k + 1], depth + 1, cwd) + if r: + return r + return None + + +def main(): + try: + data = json.load(sys.stdin) + if data.get("tool_name", "Bash") != "Bash": + return + cmd = (data.get("tool_input") or {}).get("command") or "" + reason = scan(cmd, 0, data.get("cwd") or os.getcwd()) if cmd else None + except Exception: + return # fail open: the deny list still applies + if reason: + short = cmd.strip().splitlines()[0] + short = short if len(short) <= 80 else short[:77] + "..." + hint = ("On a PR Claude reads, opens one when asked (with --head ) and edits its " + "--title / --body; pushing, merging, closing and every other edit are the user's." + if reason.startswith("gh ") else + "Rebase with a plain `git rebase` on a clean tree, and only when the user asked; if the " + "tree holds other sessions' edits, tell the user instead of stashing them." + if reason.startswith("git rebase") else + "The user commits, pushes and merges manually (global CLAUDE.md): stage and stop, " + "and draft the message with /commit-msg.") + sys.stderr.write(f"git-guard: blocked `{short}` ({reason}). {hint}\n") + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/common/.config/claude/hooks/local-commands.py b/common/.config/claude/hooks/local-commands.py new file mode 100755 index 0000000..3501519 --- /dev/null +++ b/common/.config/claude/hooks/local-commands.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""UserPromptExpansion hook: run a skill TUI-side, without a model turn. + +Custom slash commands in Claude Code are prompts -- typing `/x` expands skills/x/SKILL.md +and sends it to the model. For a command that is really just a local action (flip a +setting, print a state) that round trip is waste. This hook gives any skill a TUI-side +implementation: if `~/.claude/skills//local.py` exists, it is executed with +the command's arguments, its output is shown to you, and the expansion is blocked (exit 2), +so nothing reaches the model. Skills without a local.py expand as usual (exit 0). + +Order matters: the hook fires AFTER the skill body has been expanded, so any `!` inline +commands in that SKILL.md have already run by the time this executes. A skill with a +local.py must therefore not also apply its action via `!` -- it would happen twice. + +Input (stdin JSON): command_name, command_args (list), expanded_prompt, cwd, ... +Fails open: any error here means exit 0 and the normal expansion goes ahead. +""" +import json +import os +import subprocess +import sys + + +def main(): + try: + data = json.load(sys.stdin) + name = data.get("command_name") or "" + args = data.get("command_args") or [] + if isinstance(args, str): + args = args.split() + if not name or "/" in name or name.startswith("."): + return + script = os.path.expanduser(f"~/.claude/skills/{name}/local.py") + if not os.path.isfile(script): + return + r = subprocess.run( + [sys.executable, script, *[str(a) for a in args]], + capture_output=True, text=True, timeout=20, cwd=data.get("cwd") or None, + ) + except Exception: + return # fail open: let the skill expand normally + out = (r.stdout or "") + (r.stderr or "") + sys.stderr.write(out.rstrip("\n") + f"\n[/{name}: handled TUI-side by skills/{name}/local.py, no model turn]\n") + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/common/.config/claude/hooks/notify.py b/common/.config/claude/hooks/notify.py new file mode 100755 index 0000000..a3903a3 --- /dev/null +++ b/common/.config/claude/hooks/notify.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Notification hook: a desktop notification when Claude is waiting on you. + +settings.json wires it to `idle_prompt|permission_prompt` (the Notification matcher is the +`notification_type`). Push notifications are off in this setup, so this is the local +counterpart of pi's notify.ts. Uses notify-send where present (the Wayland/GUI hosts) and +silently no-ops on a headless box or without a session bus. Payload fields are read +defensively -- the docs do not pin the Notification input schema: `message`, `title`, +`notification_type`, `cwd`. +""" +import json +import os +import shutil +import subprocess +import sys + +TITLES = { + "idle_prompt": "Claude Code is waiting for you", + "permission_prompt": "Claude Code needs a permission", +} + + +def main(): + try: + data = json.load(sys.stdin) + except Exception: + return + exe = shutil.which("notify-send") + if not exe: + return + kind = data.get("notification_type") or "notification" + title = data.get("title") or TITLES.get(kind, "Claude Code") + body = (data.get("message") or "").strip() or kind + cwd = data.get("cwd") or "" + if cwd: + home = os.path.expanduser("~") + body += "\n" + (("~" + cwd[len(home):]) if cwd.startswith(home) else cwd) + try: + subprocess.run( + [exe, "--app-name=Claude Code", "--urgency=normal", "--expire-time=8000", + # same tag -> a newer notification replaces the previous one instead of stacking + f"--hint=string:x-canonical-private-synchronous:claude-code-{kind}", + title, body], + timeout=5, capture_output=True, + ) + except Exception: + pass + + +if __name__ == "__main__": + main() diff --git a/common/.config/claude/keybindings.json b/common/.config/claude/keybindings.json new file mode 100644 index 0000000..8a89cc3 --- /dev/null +++ b/common/.config/claude/keybindings.json @@ -0,0 +1,49 @@ +{ + "$schema": "https://www.schemastore.org/claude-code-keybindings.json", + "$docs": "https://code.claude.com/docs/en/keybindings", + "bindings": [ + { + "context": "Chat", + "bindings": { + "shift+enter": "chat:newline", + "ctrl+x v": "app:toggleTranscript" + } + }, + { + "context": "Transcript", + "bindings": { + "ctrl+x v": "app:toggleTranscript" + } + }, + { + "context": "Global", + "bindings": { + "alt+j": "scroll:lineDown", + "alt+k": "scroll:lineUp", + "ctrl+shift+j": "scroll:lineDown", + "ctrl+shift+k": "scroll:lineUp" + } + }, + { + "context": "MessageSelector", + "bindings": { + "g": "messageSelector:top", + "shift+g": "messageSelector:bottom" + } + }, + { + "context": "Select", + "bindings": { + "g": "select:first", + "shift+g": "select:last" + } + }, + { + "context": "Footer", + "bindings": { + "j": "footer:down", + "k": "footer:up" + } + } + ] +} diff --git a/common/.config/claude/link.sh b/common/.config/claude/link.sh new file mode 100755 index 0000000..ec442e0 --- /dev/null +++ b/common/.config/claude/link.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# Surface this repo's Claude Code config into ~/.claude via symlinks. +# +# `stow` deploys the repo to ~/.config/claude; Claude itself reads from ~/.claude, +# so we link the individual files/dirs across. Idempotent and self-healing: re-run +# any time. It also flags any file that has broken out of stow into a plain file — +# which silently stops Claude's edits from reaching the repo. +# (New skills/hooks added to the repo appear after a re-stow: `./install.sh` or `dotsync`.) +# +# bash ~/.config/claude/link.sh +set -eu + +SRC="$HOME/.config/claude" +DST="$HOME/.claude" + +if [ ! -e "$SRC" ]; then + echo "error: $SRC not found — run 'cd ~/.dots && ./install.sh' first" >&2 + exit 1 +fi + +mkdir -p "$DST" + +# This repo's claude dir, resolved via link.sh's own symlink (location-independent). +repo=$(dirname "$(readlink -f "$SRC/link.sh")") + +# If link.sh itself has broken out of stow into a plain file, $repo resolves to $SRC and +# the drift heal below would relink each drifted file onto ITSELF — destroying the only +# copy of its content. Refuse to continue. Both sides are canonicalized before comparing: +# $repo comes back from readlink -f, so a symlinked component anywhere in the path (say +# /home -> /var/home) would otherwise make the two spellings differ and slip the guard. +src_real=$(readlink -f "$SRC" || printf '%s' "$SRC") +if [ "$repo" = "$src_real" ]; then + echo "error: link.sh itself is a plain file (broken out of stow) — re-stow first:" >&2 + echo " cd ~/.dots && ./install.sh" >&2 + exit 1 +fi + +# Tracked items to expose in ~/.claude. Add new ones (e.g. commands agents) here. +items="settings.json statusline.py keybindings.json CLAUDE.md hooks skills" + +# Expose each item in ~/.claude (where Claude actually reads). +for item in $items; do + [ -e "$SRC/$item" ] || continue + # Files link straight at the repo copy, not through ~/.config/claude: Claude Code + # resolves ONE symlink hop, then writes atomically (temp + rename) at that path — + # verified on 2.1.296 with `claude plugin disable` against a scratch CLAUDE_CONFIG_DIR. + # Through a ~/.claude -> ~/.config/claude -> repo chain, every settings write (/model, + # effort, plugins, /config) swapped the middle link for a plain file and severed the + # repo. One hop puts the rename inside the checkout, so both links survive. A SRC file + # that already drifted into a plain file keeps being the target (it may hold the newest + # edits) until the drift guard below is reconciled. Dirs keep the stow path. + target="$SRC/$item" + [ -f "$repo/$item" ] && [ -L "$SRC/$item" ] && target="$repo/$item" + if [ -d "$DST/$item" ] && [ ! -L "$DST/$item" ]; then + echo "skip ~/.claude/$item (real directory in the way — move it aside first)" >&2 + continue + fi + # A plain FILE here means an atomic write replaced the link (Claude writes e.g. + # ~/.claude/settings.json) — it may hold newer edits, so never clobber it silently: + # heal only when provably lossless, warn otherwise (mirrors the SRC drift guard below). + if [ -f "$DST/$item" ] && [ ! -L "$DST/$item" ]; then + same=0 + case "$item" in + *.json) + python3 -c 'import json,sys; sys.exit(0 if json.load(open(sys.argv[1]))==json.load(open(sys.argv[2])) else 1)' \ + "$DST/$item" "$SRC/$item" 2>/dev/null && same=1 + ;; + *) + cmp -s "$DST/$item" "$SRC/$item" && same=1 + ;; + esac + if [ "$same" != 1 ]; then + echo "DRIFT ~/.claude/$item is a real file that differs from the repo copy —" >&2 + echo " it may hold newer edits. Review, then re-link:" >&2 + echo " diff '$DST/$item' '$target' # compare; keep whichever is right" >&2 + echo " ln -sfn '$target' '$DST/$item' # re-link" >&2 + continue + fi + echo "healed ~/.claude/$item (plain copy identical to repo — re-linking)" + fi + ln -sfn "$target" "$DST/$item" + echo "linked ~/.claude/$item -> ${target/#$HOME/\~}" +done + +# Stow-layer drift guard: each SRC *file* should be a symlink into the repo, so edits +# Claude writes (e.g. via /config) flow back and stay tracked. If an atomic write +# replaced one with a plain file, it has silently broken out of stow. Auto-heal only +# when provably lossless — the plain file is identical to the repo copy (JSON compared +# ignoring key order, since /config often just reorders keys). Otherwise warn and stop: +# the file may hold newer edits worth diffing in before re-linking. +for item in $items; do + [ -f "$SRC/$item" ] && [ ! -L "$SRC/$item" ] || continue # a real file where a link belongs + same=0 + if [ -f "$repo/$item" ]; then + case "$item" in + *.json) + python3 -c 'import json,sys; sys.exit(0 if json.load(open(sys.argv[1]))==json.load(open(sys.argv[2])) else 1)' \ + "$SRC/$item" "$repo/$item" 2>/dev/null && same=1 + ;; + *) + cmp -s "$SRC/$item" "$repo/$item" && same=1 + ;; + esac + fi + if [ "$same" = 1 ]; then + ln -sfrn "$repo/$item" "$SRC/$item" # -r: relative link, so stow keeps owning it + echo "healed ~/.config/claude/$item (plain copy identical to repo — re-linked)" + continue + fi + echo "DRIFT ~/.config/claude/$item is a real file that differs from the repo copy —" >&2 + echo " it may hold edits not yet tracked. Review, then re-link:" >&2 + echo " diff '$SRC/$item' '$repo/$item' # compare; keep whichever is right" >&2 + echo " ln -sfrn '$repo/$item' '$SRC/$item' # re-link (relative, stow-owned)" >&2 +done diff --git a/common/.config/claude/settings.json b/common/.config/claude/settings.json new file mode 100644 index 0000000..945d3e2 --- /dev/null +++ b/common/.config/claude/settings.json @@ -0,0 +1,274 @@ +{ + "attribution": { + "commit": "", + "pr": "" + }, + "permissions": { + "allow": [ + "Bash(cat:*)", + "Bash(head:*)", + "Bash(tail:*)", + "Bash(sed -n:*)", + "Bash(grep:*)", + "Bash(rg:*)", + "Bash(ls:*)", + "Bash(wc:*)", + "Bash(git status:*)", + "Bash(git diff:*)", + "Bash(git log:*)", + "Bash(git show:*)", + "Bash(git rev-parse:*)", + "Bash(git branch:*)", + "Bash(git stash list:*)", + "Bash(pnpm run:*)", + "Bash(pnpm exec:*)", + "Bash(node -p:*)", + "Bash(gh pr view:*)", + "Bash(gh pr list:*)", + "Bash(gh pr diff:*)", + "Bash(gh pr checks:*)", + "Bash(gh pr status:*)", + "Bash(gh issue view:*)", + "Bash(gh issue list:*)", + "Bash(gh issue status:*)", + "Bash(gh run view:*)", + "Bash(gh run list:*)", + "Bash(gh run watch:*)", + "Bash(gh workflow view:*)", + "Bash(gh workflow list:*)", + "Bash(gh repo view:*)", + "Bash(gh release view:*)", + "Bash(gh release list:*)", + "Bash(gh search:*)", + "Bash(gh label list:*)", + "Bash(gh status:*)", + "Bash(gh auth status:*)", + "Bash(gh pr edit:*)", + "Bash(gh workflow run:*)", + "Bash(gh run rerun:*)" + ], + "deny": [ + "Bash(git push)", + "Bash(git push:*)", + "Bash(git reset --hard)", + "Bash(git reset --hard:*)", + "Bash(git clean)", + "Bash(git clean:*)", + "Bash(gh pr merge)", + "Bash(gh pr merge:*)", + "Bash(gh pr close)", + "Bash(gh pr close:*)", + "Read(**/.env)", + "Read(**/.env.*)", + "Read(**/*.env)", + "Read(**/*.pem)", + "Read(**/*.key)", + "Read(**/*.p12)", + "Read(**/*.pfx)", + "Read(**/*.keystore)", + "Read(**/id_rsa*)", + "Read(**/.ssh/**)", + "Read(**/.aws/**)", + "Read(**/.npmrc)", + "Read(**/.netrc)", + "Read(**/.git-credentials)", + "Read(**/.claude/.credentials.json)", + "Read(**/secrets.fish)", + "Read(**/*.token)", + "Read(**/.envrc)", + "Read(**/.gnupg/**)", + "Read(**/fish_variables)" + ], + "ask": [ + "Bash(gh pr create)", + "Bash(gh pr create:*)", + "Bash(git rebase)", + "Bash(git rebase:*)" + ], + "defaultMode": "auto" + }, + "model": "opus", + "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume", + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.claude/hooks/drift-check.sh\"; if [ -f \"$f\" ]; then exec bash \"$f\"; fi", + "timeout": 5 + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.claude/hooks/drift-check.sh\"; if [ -f \"$f\" ]; then out=$(bash \"$f\" 2>&1); [ -n \"$out\" ] && printf \"%s\\n\" \"$out\"; fi; exit 0", + "timeout": 5 + } + ] + }, + { + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc busy; exit 0", + "timeout": 5, + "async": true + } + ] + } + ], + "UserPromptExpansion": [ + { + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.claude/hooks/local-commands.py\"; if [ -f \"$f\" ]; then exec /usr/bin/env python3 \"$f\"; fi", + "timeout": 25 + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.claude/hooks/git-guard.py\"; if [ -f \"$f\" ]; then exec /usr/bin/env python3 \"$f\"; fi", + "timeout": 5 + } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": "/usr/bin/env python3 ~/.claude/hooks/format.py", + "timeout": 20, + "statusMessage": "format" + } + ] + }, + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "/usr/bin/env python3 ~/.claude/hooks/format.py", + "timeout": 20 + } + ] + } + ], + "Notification": [ + { + "matcher": "idle_prompt|permission_prompt", + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.claude/hooks/notify.py\"; if [ -f \"$f\" ]; then exec /usr/bin/env python3 \"$f\"; fi", + "timeout": 5 + } + ] + }, + { + "matcher": "idle_prompt|permission_prompt", + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc input; exit 0", + "timeout": 5, + "async": true + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc done; exit 0", + "timeout": 5, + "async": true + } + ] + } + ], + "StopFailure": [ + { + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc error; exit 0", + "timeout": 5, + "async": true + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc off; exit 0" + } + ] + } + ] + }, + "worktree": { + "baseRef": "fresh" + }, + "enableWorkflows": false, + "statusLine": { + "type": "command", + "command": "/usr/bin/env python3 ~/.claude/statusline.py", + "padding": 0, + "refreshInterval": 60, + "hideVimModeIndicator": true + }, + "enabledPlugins": { + "typescript-lsp@claude-plugins-official": true, + "frontend-design@claude-plugins-official": true, + "rust-analyzer-lsp@claude-plugins-official": true + }, + "effortLevel": "xhigh", + "modelSettings": { + "claude-fable-5-1": { + "effortLevel": "xhigh" + }, + "claude-opus-5-5": { + "effortLevel": "xhigh" + } + }, + "advisorModel": "fable", + "tui": "fullscreen", + "skipWorkflowUsageWarning": true, + "theme": "dark", + "editorMode": "vim", + "verbose": true, + "autoCompactEnabled": true, + "remoteControlAtStartup": false, + "inputNeededNotifEnabled": false, + "agentPushNotifEnabled": false, + "skipAutoPermissionPrompt": true, + "autoMode": { + "environment": [ + "### User-specific", + "**Primary use of Claude Code**: software development and dotfiles maintenance on personal Arch Linux hosts", + "**Trusted repo**: the repository the session is opened in; treat it as private unless it is clearly public, and treat content ported in from outside it as not its own work", + "**Sensitive remote targets**: any namespace, host, or container whose name carries `prod` or `production` as a whole word or name segment", + "routine under a repo's own Makefile / pnpm / npm scripts is expected local development activity" + ] + } +} diff --git a/common/.config/claude/skills/commit-msg/SKILL.md b/common/.config/claude/skills/commit-msg/SKILL.md new file mode 100644 index 0000000..033278b --- /dev/null +++ b/common/.config/claude/skills/commit-msg/SKILL.md @@ -0,0 +1,45 @@ +--- +description: Draft a commit message for the staged changes, matching this repo's commit style, then print it in the reply and save it to the repo's CLAUDE_COMMIT_MSG file. Never stages or commits. Use once you've staged what you want to commit. +argument-hint: [optional focus/scope hint] +disable-model-invocation: true +allowed-tools: Bash(git diff:*), Bash(git log:*), Bash(git status:*), Bash(git rev-parse:*), Bash(~/.config/git/claude-commit-msg:*), Read, Glob +--- + +# Draft a commit message for the staged changes + +Context for the current commit — what's staged, plus this repo's recent style: + +!`echo "=== Staged (git diff --cached --stat) ==="; git --no-pager diff --cached --stat 2>/dev/null; echo; echo "=== Working tree (git status --short) ==="; git --no-pager status --short 2>/dev/null; echo; echo "=== Recent subjects — match this convention ==="; git --no-pager log -20 --pretty=format:'%s' 2>/dev/null` + +## What to do + +1. **See exactly what's being committed.** Read the full staged diff with + `git --no-pager diff --cached`. If nothing is staged (the stat above is empty), tell me and + **stop** — I stage changes myself; never run `git add`. +2. **Learn the repo's commit style** from the recent subjects above — prefix convention (this repo + uses `[Scope] summary`), imperative vs. past tense, subject length, whether bodies are used. + Match what's already there; don't impose Conventional Commits / gitmoji if the repo doesn't use + them. +3. **Write the message from the *actual* staged diff** (not a guess): + - A concise subject in the repo's style (~50 chars, imperative). Fold in my hint if given: + **$ARGUMENTS**. + - Add a short body (wrapped ~72 cols) only when the change needs the *why*; otherwise + subject-only. Don't invent motivation that isn't evident from the diff. +4. **Print the message in your reply first** — as a single fenced ` ```text ` block, copy-paste + ready. This in-reply copy is the durable one: it lives in the transcript, so it survives even + after the hook has consumed the handoff. Always print it. +5. **Hand it off** so I can recover it any time — feed the raw message to the CLI as a quoted + heredoc (so quotes, backticks and `$` in the body survive untouched): + ```sh + ~/.config/git/claude-commit-msg save <<'EOF' + + EOF + ``` + That stores it as its own file under `$(git rev-parse --git-path CLAUDE_COMMIT_MSG.d)/` **together with the staged paths + it describes**, so several sessions can hand off in parallel without overwriting each other. My + `prepare-commit-msg` hook prefills the next `git commit` / lazygit `C` with the message(s) whose + paths are part of that commit, then consumes them. Never write `CLAUDE_COMMIT_MSG` or + `COMMIT_EDITMSG` directly. The `save` output names the saved id and file path. + Then tell me both places it is: **printed above** and **saved for the hook** (with its id). +6. **Never** run `git add`, `git commit`, or `git push`, and never offer to — I stage and commit + manually. Draft only. diff --git a/common/.config/claude/skills/pr-description/SKILL.md b/common/.config/claude/skills/pr-description/SKILL.md new file mode 100644 index 0000000..fab23d8 --- /dev/null +++ b/common/.config/claude/skills/pr-description/SKILL.md @@ -0,0 +1,36 @@ +--- +description: Draft a ready-to-paste PR description by filling this repo's GitHub PR template from the branch diff and commits, then copy it to the clipboard. Use after finishing a feature. +argument-hint: [base-branch] +disable-model-invocation: true +allowed-tools: Bash(git diff:*), Bash(git log:*), Bash(git merge-base:*), Bash(git symbolic-ref:*), Bash(git rev-parse:*), Bash(git show-ref:*), Bash(ls:*), Bash(cat:*), Bash(wl-copy:*), Bash(mktemp:*), Bash(rm:*), Read, Glob +--- + +# Draft this branch's PR description + +This repo's PR template (first match), plus the branch's changes: + +!`for f in .github/pull_request_template.md .github/PULL_REQUEST_TEMPLATE.md docs/pull_request_template.md docs/PULL_REQUEST_TEMPLATE.md PULL_REQUEST_TEMPLATE.md pull_request_template.md; do if [ -f "$f" ]; then echo "=== PR template: $f ==="; cat "$f"; found=1; break; fi; done; if [ -z "$found" ]; then if [ -d .github/PULL_REQUEST_TEMPLATE ]; then echo "=== template dir .github/PULL_REQUEST_TEMPLATE/ (pick one) ==="; ls .github/PULL_REQUEST_TEMPLATE/; else echo "(no PR template found — use the fallback structure)"; fi; fi` + +!`b=$(git symbolic-ref --short -q refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@'); [ -z "$b" ] && { git show-ref -q --verify refs/heads/main && b=main || b=master; }; m=$(git merge-base "$b" HEAD 2>/dev/null); echo "Branch: $(git rev-parse --abbrev-ref HEAD 2>/dev/null) Base: $b Range: ${m:-?}..HEAD"; echo; echo "Commits:"; git --no-pager log --oneline "${m}..HEAD" 2>/dev/null; echo; echo "Files changed:"; git --no-pager diff --stat "${m}...HEAD" 2>/dev/null` + +## What to do + +1. **Resolve the base branch** (use the invocation argument if given — **$ARGUMENTS** — else the + detected base) and read the full diff + commit messages for `merge-base..HEAD`. +2. **Fill the PR template shown above** from the *actual* changes: + - Write the Summary / motivation and any "Implementation Notes" from the diff and commits. + - Fill the **Type of Change** field or boxes with the kinds that genuinely match (feature / + fix / refactor / perf / tests / docs / chore). + - Tick `Self-reviewed` and `LLM-assisted` if those boxes exist. + - **Leave verification boxes unchecked** — e.g. "tests passed", "`validate:full` passes", + "pre-commit hooks passed". I confirm those myself; never tick them for me. + - Fill **Related Issues** from issue numbers in the branch name or commit trailers; delete any + placeholder lines you can't fill (never leave a dangling `Closes #`), and drop the whole + section if there are no issues to reference. + - If a multi-template dir was listed (no single file), pick the most fitting one and say which. + - **If no template exists**, use this fallback: `## Summary` / `## Changes` / `## Testing` / + `## Notes`. +3. **Output** the filled description as a single fenced ```markdown code block, copy-paste ready. +4. **Copy it to the clipboard**: write the same markdown to a temp file (`mktemp`) and run + `wl-copy < "$tmpfile"`, then remove the temp file. Tell me it's on the clipboard. +5. **Do not** create, push, or edit the PR (`gh pr ...`) — I add the text to the PR myself. diff --git a/common/.config/claude/skills/pr-loop/SKILL.md b/common/.config/claude/skills/pr-loop/SKILL.md new file mode 100644 index 0000000..7b61a11 --- /dev/null +++ b/common/.config/claude/skills/pr-loop/SKILL.md @@ -0,0 +1,280 @@ +--- +description: Babysit the current branch's PR — address review comments that don't need my input, re-check every ~10 min, and stop when there are no open comments left or the automated reviewers (Codex, Claude) hit their limit. Prep-only — stages fixes and drafts the commit message; never commits, pushes, or merges. +argument-hint: [pr number or url — optional; defaults to the current branch's PR] +disable-model-invocation: true +allowed-tools: Bash(gh:*), Bash(git status:*), Bash(git diff:*), Bash(git log:*), Bash(git rev-parse:*), Bash(git fetch:*), Bash(git add:*), Bash(~/.config/git/claude-commit-msg:*), Read, Edit, Write, Grep, Glob, ScheduleWakeup +--- + +# Watch this PR and resolve review comments (prep-only) + +A self-paced loop over one PR's review feedback: fix the comments that don't need my judgement, +stage them, draft a commit message, then wait ~10 min and re-check — until there are no unresolved +comments left or the automated reviewers (Codex/Claude) hit a usage limit. + +**The contract — read this first:** +- **I never commit, push, or merge.** Each cycle you *prepare*: edit + `git add` + draft a commit + message + reply on the threads you handled. Then you **ping me to commit & push**, and the loop + resumes after I do. This honours the global no-commit/no-push rule; nothing in `settings.json` + changes. +- **React, don't reply — then resolve.** A handled thread gets a 👍 **reaction** on the reviewer's + comment while unpushed — never an "Addressed — …" reply, those are just noise. Once I've pushed + and its fix is live, you **resolve the thread on GitHub** (or minimize the bot comment as + RESOLVED) rather than leaving it open — see step 6. Never resolve unpushed work or a needs-input + thread. The **only** comments you ever post are the one-line decision questions for needs-input + items (step 7) and the one-line reason on a dismissal. +- **The marker vocabulary — exactly these three, never others.** Every item you triage gets exactly + one reaction, so I can read the PR's state at a glance without opening threads: + - 👍 `+1` — **addressed**: fix staged; the thread gets resolved once I push. + - 👀 `eyes` — **parked**: needs a decision from me, paired with the one-line question (step 7). + - 👎 `-1` — **dismissed**: a *bot* finding that's wrong, paired with a one-line why, then + resolved/minimized straight away (step 8). + + **Never 👎 a human's comment.** If I'm the one who's wrong, write the reasoning as a reply and + park it as 👀 — I decide, not you. And don't invent other reactions (🎉/❤️/🚀/😄/😕): an + unexplained emoji is worse than no emoji. +- The 10-minute cadence uses `ScheduleWakeup`, so the loop only advances **while this Claude + session stays open**. **To stop it: press `Esc` while I'm idle between cycles** (that clears the + queued wake-up); closing the session also stops it. A plain message does **not** cancel a pending + wake-up — use `Esc`. +- **Every token counts.** Each wake-up re-sends the whole conversation. On a Claude subscription + the prompt cache holds for **1 hour**, so the 10-min cadence stays warm; on an API key it drops to + 5 min and every cycle is a cold read. Either way every extra line in context rides along on every + later cycle. Therefore: fetch **filtered** data only (use the `--jq` filters below — never let raw + unfiltered JSON into the conversation), summarize deltas rather than restating unchanged state, + and keep idle cycles to **one cheap API call and ≤2 lines of output**. + +Current state (auth + the current branch's PR): + +!`echo "=== gh auth ==="; gh auth status 2>&1 | head -3; echo; echo "=== PR (current branch) ==="; gh pr view --json number,url,state,headRefName,baseRefName,headRefOid 2>/dev/null || echo "(no open PR for current branch — or gh not authed)"; echo; echo "=== repo ==="; gh repo view --json nameWithOwner -q .nameWithOwner 2>/dev/null` + +## Each cycle (one invocation / wake-up) + +1. **Preflight.** If `gh auth status` failed above → **stop** and tell me to run `! gh auth login`, + then re-run `/pr-loop`. Do nothing else. Capture `owner`/`repo` from `nameWithOwner`. + +2. **Load state & resolve the PR.** Read `/pr-loop-state.json` (find `` with + `git rev-parse --absolute-git-dir`). It's inside `.git/`, so it never shows in `git status` and + survives wake-ups. Shape: + ```json + { "number": 0, "lastHeadOid": "", "lastSeenUpdatedAt": "", "handledThreadIds": [], + "handledCommentIds": [], "needsInputThreadIds": [], "needsInputCommentIds": [], + "dismissedIds": [], "awaitingPush": false, "idleCount": 0, "cycleCount": 0 } + ``` + Resolve the target PR **in this order**: my argument if given (**$ARGUMENTS**) → the `number` + in the state file (wake-ups re-invoke `/pr-loop` *without* arguments — the state file is the + durable copy) → the current branch's PR from the context block. If none → **stop** and say so. + If the state file is missing or for a different `number`, start fresh. Increment `cycleCount`. + + **Then print one status line before any network call** — so I always see the loop is alive: + > 🔄 pr-loop cycle — PR #: checking… + +3. **Cheap activity check — one API call, before any heavy fetch.** + `gh pr view NUM --json headRefOid,updatedAt` + - If `updatedAt == lastSeenUpdatedAt` **and** `headRefOid == lastHeadOid` → nothing happened at + all (no comment, review, or push). This is an **idle cycle**: `idleCount += 1`; if a safety + cap (step 5) is now exceeded, STOP per step 5. Otherwise save state and jump straight to + step 10's reschedule. Total output ≤2 lines — if `awaitingPush`, one line is a brief + commit-&-push reminder (remind at most twice across idle cycles, then just the status line). + - Otherwise: remember the fetched `headRefOid` for step 6 and continue. (Don't update + `lastSeenUpdatedAt` yet — step 10 refreshes it *after* you've posted replies, so your own + replies don't defeat the next cycle's cheap check.) + +4. **Fetch review state — filtered at the source, both calls in parallel** (one message, two + tool calls). Never fetch unfiltered `reviews,comments`. + + Unresolved review threads (resolved/unresolved is GraphQL-only): + ```bash + gh api graphql --paginate -F owner=OWNER -F repo=REPO -F number=NUM -f query=' + query($owner:String!,$repo:String!,$number:Int!,$cursor:String){ + repository(owner:$owner,name:$repo){ pullRequest(number:$number){ + reviewThreads(first:100,after:$cursor){ pageInfo{hasNextPage endCursor} + nodes{ id isResolved isOutdated + comments(first:100){ nodes{ id databaseId author{login} path line body } } } } } } }' \ + --jq '.data.repository.pullRequest.reviewThreads.nodes[] + | select(.isResolved | not) + | {id, isOutdated, + comments: [.comments.nodes[] | {id, databaseId, author: .author.login, path, line, body}]}' + ``` + Mind the two id kinds: the thread's own `id` (`PRRT_…`) is what you resolve; a + `comments[].id` (`PRRC_…`) is what you react to. + + Automated-reviewer activity + `@claude` requests from the PR conversation — latest review per + bot (for the limit check in step 5) and only the relevant comments, not the whole history: + ```bash + gh pr view NUM --json reviews,comments --jq '{ + latestBotReviews: ([.reviews[] | select(.author.login | test("codex|claude"; "i"))] + | group_by(.author.login) | map(max_by(.submittedAt)) + | map({author: .author.login, state, submittedAt, body})), + relevantComments: ([.comments[] | select((.isMinimized | not) + and ((.body | test("@claude")) or (.author.login | test("codex|claude"; "i")))) + | {id, author: .author.login, body}] | .[-10:]) + }' + ``` + Act on feedback from **any** reviewer — especially the automated ones, **Codex and Claude** + (`author.login` matching `codex`/`claude`, or a Bot account). Treat any comment — inline review + **or** PR conversation — whose body **mentions `@claude`** as an explicit request to act on, + same as a review comment. + + Some bots post **findings as a plain PR-conversation comment** rather than inline review threads + (e.g. Claude when its tooling can't post inline). Triage those findings like thread findings; + since they have no thread, you "resolve" them by **minimizing** the comment once fixed (step 8). + `relevantComments[].id` is the comment's GraphQL node id (`IC_…`) used for that, and the + `isMinimized` filter above already drops ones you've resolved. A bot's pure **summary / status / + usage-limit** comment carries no finding — triage/minimize only comments with concrete asks. + +5. **Check stop conditions — before doing any work:** + - **Nothing left to address** → no unresolved review threads, no un-minimized bot **findings** + comments, and no open `@claude` requests. Anything in `dismissedIds` doesn't count as + outstanding (if a resolve/minimize failed, the 👎 + reason still stands). The PR is clean: + report done, save state, and **do not** schedule another wake-up. STOP. + - **The automated reviewers are spent** → an automated reviewer's most recent review/comment + body matches a limit signal (case-insensitive: `rate/usage/quota/credit … limit`, + `limit reached`, `exceeded … quota`, `out of … credits`). Automated reviewers = authors whose + `login` matches `codex` or `claude` (or a `[bot]` that leaves review comments; confirm with + `gh api users/ --jq .type` → `Bot`). STOP and report which reviewer hit the limit + **only** when no unresolved threads (incl. `@claude` requests) remain that you can still act + on. If one reviewer is limited but other threads still need work, handle those first, then + re-check. + - **Safety caps** (these apply on idle cycles too) → if `cycleCount > 20`, or `idleCount > 4`, + or `gh api rate_limit --jq .resources.core.remaining` is `< 100` → STOP and hand back to me + with a summary. + + **When any stop fires:** save state, do **not** call `ScheduleWakeup`, and end with a clear + final line so I know the loop is over and won't run again — e.g.: + > ✅ **Finished — no more active issues.** I won't re-check again. + + Adapt it to the reason: `✅ Finished — hit its usage limit; nothing left to address, + I won't re-check again.` or `⏹ Stopped — hit safety cap (); re-run \`/pr-loop\` to resume.` + +6. **Did I push since last cycle?** Compare the `headRefOid` from step 3 to `lastHeadOid` (no + extra API call). + - If **unchanged and `awaitingPush` is true** → I haven't pushed yet. Don't re-fix anything for + threads already handled: `idleCount += 1`, then continue with step 7 **only for genuinely new + threads/comments** (something new must exist, or step 3 would have short-circuited). + - If **changed** → I pushed. Set `awaitingPush=false`, `idleCount=0`, update `lastHeadOid`. Then, + **before handling anything new, resolve on GitHub every already-handled item whose fix is now + live** — don't leave them lingering as open, 👍-only threads. For each id in `handledThreadIds` + that is still unresolved and not re-flagged, run `resolveReviewThread`; for each id in + `handledCommentIds` not re-flagged, `minimizeComment` as RESOLVED (mutations in step 8). + Resolved threads drop out of the step-4 fetch, so each fix is resolved exactly once. Then + continue to any genuinely new threads. + +7. **Triage** each unresolved review thread, every bot **findings** comment on the PR conversation, + and every `@claude` request **not already handled**: + - **Auto-handle (no input needed):** typos, lint/format, naming, missing null/error checks, + applying the reviewer's concrete suggested diff, docs/comments, and localized bugs with one + correct fix — **including fixes that touch a shared type/contract or span multiple layers, + when the repo's existing conventions determine the shape.** Blast radius (multi-file, + contract-touching, "I'd have to pick among a few representations") is **not** a reason to + defer: pick the minimal idiomatic shape that matches existing patterns, implement it, and let + me veto. A reviewer finding that names the concrete fix is almost always auto-handleable. + - **Leave for me (needs input) — 👀:** defer **only** for genuine ambiguity — two or more + *materially different* correct behaviours, a real security/performance trade-off, or missing + product/domain knowledge that existing code can't settle. Never guess these. Post the + `path:line` + a **one-line decision I can answer in a word**, and record the id in + `needsInputThreadIds` (or `needsInputCommentIds` for a plain conversation comment) so step 3 + re-surfaces it every idle cycle instead of letting it fall silent. + - **Not an issue (dismiss) — 👎:** a **bot** finding that is simply wrong — it misread the code, + the behaviour is intentional and the surrounding code proves it, or the concern is already + handled elsewhere. Don't "fix" it to make it go away, and don't park it as needs-input either: + that leaves a false positive propping the loop open until a safety cap fires. Reply with the + one-line reason (facts, not opinion: the line/behaviour that disproves it), 👎 it, then resolve + the thread / minimize the comment **immediately** — no push required, since there's no fix to + land. Record the id in `dismissedIds` so a re-fetch can't re-litigate it. + **Only bots get dismissed.** A *human* comment you think is wrong is a needs-input item: state + your reasoning in a reply, mark it 👀, and let me settle it. If you'd be dismissing more than + one or two findings in a cycle, you're probably the one who's wrong — park them for me instead. + + Apply the same split to Codex's and Claude's review suggestions and to every `@claude` request: + a concrete ask is auto-handled; a genuine judgement call is left for me. Skip anything whose id + is already in `handledThreadIds` / `handledCommentIds` / `dismissedIds`. When I answer a needs-input item (or you + push a fix for it), drop its id from the needs-input arrays and handle/resolve it normally. + +8. **Prepare the auto-handled set (no commit, no push):** + - Apply the edits (the PostToolUse format hook auto-formats). `git add` the changed files. + - **Mark every triaged item with its reaction — never an "Addressed — …" reply.** The reaction + goes on the reviewer's comment (for a thread, its *first* comment — the finding itself): + 👍 what you fixed this cycle, 👀 what you parked for me, 👎 a dismissed bot finding. + + One mutation covers both surfaces. Pass the **comment** node id — `comments[].id` (`PRRC_…`) + from the thread query, or `relevantComments[].id` (`IC_…`) for a conversation comment; *not* + the thread's own `PRRT_…` id. `content` is `THUMBS_UP` / `EYES` / `THUMBS_DOWN`: + ```bash + gh api graphql -f query='mutation($id:ID!,$c:ReactionContent!){ + addReaction(input:{subjectId:$id,content:$c}){ reaction{ content } } }' \ + -F id=COMMENT_NODE_ID -F c=THUMBS_UP + ``` + Re-adding the same reaction is a harmless no-op, so a repeat cycle can't double-post. When an + item **changes class** — I answer a 👀, or a reviewer re-flags something you'd 👍'd — clear the + stale marker first, same call shape, so nothing ever carries two contradictory markers: + ```bash + gh api graphql -f query='mutation($id:ID!,$c:ReactionContent!){ + removeReaction(input:{subjectId:$id,content:$c}){ reaction{ content } } }' \ + -F id=COMMENT_NODE_ID -F c=EYES + ``` + - Add handled review-thread ids to `handledThreadIds` and handled conversation/`@claude` + comment ids to `handledCommentIds`; set `awaitingPush=true`. + - **Resolve** a thread — `gh api graphql -f query='mutation($id:ID!){ + resolveReviewThread(input:{threadId:$id}){ thread{ id isResolved } } }' -F id=THREAD_ID` — + **only** once its fix is live (a cycle where `headRefOid` advanced, per step 6) and the + reviewer hasn't re-flagged it. Never resolve unpushed work or a "needs input" thread. This + resolves the review *conversation*, not any linked GitHub Issue. + **The one exception is a 👎 dismissal:** there's no fix to land, so resolve/minimize it in the + same cycle you post the reason — otherwise the false positive keeps the loop alive forever. + - **Resolve a plain PR-conversation findings comment** (a bot finding with no inline thread — + e.g. Claude's) by **minimizing it as resolved** — the issue-comment equivalent, under the same + rules (only once its fix is live and not re-flagged): + ```bash + gh api graphql -f query='mutation($id:ID!){ minimizeComment(input:{subjectId:$id, + classifier:RESOLVED}){ minimizedComment{ isMinimized } } }' -F id=COMMENT_NODE_ID + ``` + `COMMENT_NODE_ID` is the `relevantComments[].id` (`IC_…`). Never minimize unpushed work, a + "needs input" comment, or a summary/status/usage-limit comment. + +9. **Draft the commit message — exactly like `/commit-msg`:** from the staged diff and the repo's + recent `git log` style (this repo uses `[Scope] summary`), write a message that matches. Then: + - **(a) Print it** in your reply as a fenced ` ```text ` block — the durable copy. + - **(b) Hand it off:** `~/.config/git/claude-commit-msg save <<'EOF'` … `EOF` (the message as a + quoted heredoc, so quotes and backticks survive) — it is stored with the paths you staged this cycle, so the `prepare-commit-msg` hook prefills it only + for the commit that contains them (other sessions' handoffs are not overwritten). Never write + `CLAUDE_COMMIT_MSG` / `COMMIT_EDITMSG` directly. + - Tell me both locations. **Never** run `git commit`. + (Skip this step when nothing new was staged this cycle.) + +10. **Ping + schedule.** Give me a tight summary — deltas only, don't restate unchanged threads: + - 👍 fixed & staged this cycle: threads (with `path:line`); + - 👀 left for you: threads + one-line reason each; + - 👎 dismissed as not-an-issue: thread + the one-line why (call these out explicitly — a + dismissal is me trusting your judgement, so I should see every one); + - resolved on GitHub this cycle (if any); + - the commit message (printed above), then "commit & push when ready". + + Refresh `lastSeenUpdatedAt` with one `gh pr view NUM --json updatedAt` call **after** any + needs-input questions are posted (reactions don't bump `updatedAt`, comments do — so your own + activity doesn't defeat the next cheap check), then save state + to `/pr-loop-state.json`. Then schedule: + - **normal cycle:** `ScheduleWakeup(delaySeconds=600, noop=false, prompt="/pr-loop", + reason="recheck PR # review comments")`; + - **idle cycle** (step 3 short-circuited): back off — `delaySeconds=1200, noop=true` (idle + ticks then collapse into one line in my terminal instead of stacking), I'm clearly away; + re-running `/pr-loop` checks immediately. + + End the turn with a sign-off that states when you'll run again and how to stop, e.g.: + > ⏳ **Next check in ~10 min** (~20 when idle). To stop, press `Esc` while I'm idle between + > cycles (or close the session). + + (When a stop condition in step 5 fired, skip both the wake-up and this sign-off — use the + **Finished** line from step 5 instead.) + +## Guardrails + +- **Never** `git commit`, `git push`, `gh pr merge`, `gh pr create`, `gh pr close`, or `gh pr edit` + — I do all of those. You stage, react, resolve, and draft; nothing more. The only comment you may + post is a needs-input decision question. Commit, push, merge and close are enforced, not just + asked: `settings.json` denies them and the `git-guard.py` PreToolUse hook blocks any spelling of + them. `gh pr create` / `edit` are allowed globally (create asks first), so for this loop the rule + above is the only thing holding them back. +- Act only on the target PR. Don't touch unrelated files or other PRs. +- **Keep context lean:** no raw JSON dumps in replies, no re-listing threads that haven't changed, + idle cycles ≤2 lines. Every line you emit is re-read (uncached) on every later cycle. +- If anything is unclear or risky, leave it for me rather than guessing. diff --git a/common/.config/claude/skills/review-branch/SKILL.md b/common/.config/claude/skills/review-branch/SKILL.md new file mode 100644 index 0000000..bc75341 --- /dev/null +++ b/common/.config/claude/skills/review-branch/SKILL.md @@ -0,0 +1,68 @@ +--- +description: Review all changes on the current branch (diff vs its base) for bugs, security issues, optimizations, and readability/scannability, then apply the readability + safe improvements after you approve. Use right before opening a PR. +argument-hint: [base-branch] +disable-model-invocation: true +allowed-tools: Bash(git diff:*), Bash(git log:*), Bash(git status:*), Bash(git merge-base:*), Bash(git symbolic-ref:*), Bash(git rev-parse:*), Bash(git show-ref:*), Bash(git branch:*), Read, Grep, Glob, Edit, Write +--- + +# Review this branch + +Context auto-collected for the current branch vs. its base: + +!`b=$(git symbolic-ref --short -q refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@'); [ -z "$b" ] && { git show-ref -q --verify refs/heads/main && b=main || b=master; }; m=$(git merge-base "$b" HEAD 2>/dev/null); echo "Current branch: $(git rev-parse --abbrev-ref HEAD 2>/dev/null)"; echo "Base branch: $b"; echo "Diff range: ${m:-?}..HEAD"; echo; echo "Commits:"; git --no-pager log --oneline "${m}..HEAD" 2>/dev/null; echo; echo "Files changed:"; git --no-pager diff --stat "${m}...HEAD" 2>/dev/null` + +## What to do + +1. **Resolve the base branch.** If a base branch was passed when invoking (it appears here: + **$ARGUMENTS** — empty if none), use that. Otherwise use the base detected above. The changes + to review are the diff `git merge-base HEAD`..`HEAD`. +2. **Gather context.** Read the full diff for that range (`git diff ...HEAD`) and + review **only the lines this branch changed** — not pre-existing code. Read surrounding code + with the Read tool when you need it to judge a finding. Also read the repo's `CLAUDE.md` (root, + and any in the directories the branch touched) and treat its guidance as a review lens. +3. **Find issues** across four lenses: + - 🐞 **Correctness / bugs** — logic errors, unhandled edge cases, swallowed/ignored errors, + race conditions, wrong/loose types, off-by-ones, and anything that violates the repo's + `CLAUDE.md`. + - 🔒 **Security** — injection (SQL / command / path traversal), missing input validation or + output encoding, authn/authz gaps, secrets or credentials committed / logged / echoed, + unsafe deserialization, SSRF, weak crypto or randomness, unsafe defaults, and sensitive data + leaked in logs or error messages. + - ⚡ **Optimizations** — redundant work, needless allocations/copies, N+1 patterns, a simpler + or standard-library equivalent. + - 📖 **Readability & scannability** — naming, structure, dead code, stale/misleading comments, + formatting, over-long functions, unclear control flow. +4. **Verify the bugs and security findings before reporting.** Double-check each 🐞 and 🔒 + finding against the real code and keep only the ones you're confident are real and exploitable + / will bite in practice. **Do not flag:** + - issues on lines the branch didn't change (pre-existing); + - theoretical vulnerabilities with no reachable exploit path in the changed code, or anything a + SAST / dependency scanner would own; + - anything a linter / type-checker / compiler / CI catches (imports, type errors, formatting) — + assume those run separately; + - pedantic nitpicks a senior engineer wouldn't raise, or "needs more tests/docs" unless the + repo's `CLAUDE.md` requires it; + - changes that are clearly intentional and part of the feature. + + (This filter is for 🐞 bugs and 🔒 security. ⚡ optimizations and 📖 readability are the + deliberate polish pass — minor suggestions there are welcome, since the goal is PR-readiness.) +5. **Report**, grouped by the four lenses, most-severe-first, each finding one or two lines with + a `path:line` reference so it's scannable. If a category is clean, say so in one line. No walls + of text. +6. **Then stop and ask** whether to apply the fixes. On approval, apply **only** the readability + improvements and behavior-preserving optimizations. Anything that changes behavior, public API, + or semantics: list it separately and let me decide — do **not** apply it silently. Treat 🔒 + security fixes the same way: propose them, but never apply them silently. After editing, re-run + the repo's formatter/linter if it has one. +7. **Point me at the relevant built-in follow-ups.** After reporting, list the Claude Code + commands worth running next as separate, deeper passes — tailored to what this review + surfaced, not a blanket dump. Only include the ones that actually fit: + - `/security-review` — a deeper, whole-branch security pass; suggest whenever the 🔒 lens + flagged something or the diff touches auth, crypto, input handling, secrets, or network I/O. + - `/code-review` (alias `/review`; add `--fix` to apply, `--comment` for inline PR comments) — + a second review of the working-tree diff, a PR number or a branch at a chosen effort level. + - `/simplify` — apply reuse / simplification / efficiency cleanups beyond the safe ones applied + here. + - `/verify` — run the app to confirm the change behaves, if this branch changed behavior. + - `/pr-description` — draft the PR text from this branch once the review is clean. +8. **Never** run `git commit` or `git push` — I do that manually. diff --git a/common/.config/claude/skills/verbose/SKILL.md b/common/.config/claude/skills/verbose/SKILL.md new file mode 100644 index 0000000..995ae7c --- /dev/null +++ b/common/.config/claude/skills/verbose/SKILL.md @@ -0,0 +1,20 @@ +--- +description: Toggle the persisted verbose view for this project (viewMode verbose/default, plus verbose + showThinkingSummaries) by writing .claude/settings.local.json, and print the live-view keybind. Usage: /verbose [on|off|status]; no argument toggles. Runs TUI-side via the UserPromptExpansion hook; this body is only the fallback. +argument-hint: [on|off|status] +disable-model-invocation: true +allowed-tools: Bash(python3:*) +--- + +# /verbose (fallback path) + +Normally you never see this: `hooks/local-commands.py` (UserPromptExpansion) runs +`skills/verbose/local.py` and blocks the expansion, so `/verbose` costs no model turn. This body +only loads on a host where that hook isn't deployed yet. + +Run exactly this, then relay its output to me verbatim in a fenced ```text block with **at most one +line** of your own: + + python3 ~/.claude/skills/verbose/local.py $ARGUMENTS + +Don't edit any settings file yourself, don't run anything else, and don't offer follow-ups. If it +reports an error, quote it and stop. diff --git a/common/.config/claude/skills/verbose/local.py b/common/.config/claude/skills/verbose/local.py new file mode 100755 index 0000000..d1b507e --- /dev/null +++ b/common/.config/claude/skills/verbose/local.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""`/verbose`, TUI-side: flip Claude Code's *persisted* verbose view for the current project. + +Run by hooks/local-commands.py from the UserPromptExpansion hook, i.e. when you type +`/verbose [on|off|status]` -- the hook executes this and blocks the skill expansion, so no +prompt ever reaches the model and the output below is shown to you directly. (On a host +without that hook, skills/verbose/SKILL.md falls back to having the model run it.) + +Claude Code has no built-in runtime `/verbose`; the live toggle is a keypress (`ctrl+x v` +here, `ctrl+o` by default -- `app:toggleTranscript`). What can be scripted is the persisted +default: `viewMode` ("verbose" | "default" | "focus" -- this is what actually decides the view; +it also beats a sticky `/focus` choice for new sessions), plus `verbose` (full tool +input/output inline) and `showThinkingSummaries` for versions without viewMode. All accept any +settings scope, so this writes the project's +`.claude/settings.local.json` -- local to this machine, never committed -- instead of the +dots-tracked ~/.claude/settings.json, which would show a diff on every toggle. Project-local +settings win over user settings, so the user default stays `verbose: true` and a project can +be quietened individually. + +usage: local.py [on|off|toggle|status] (no argument = toggle) +""" +import json +import os +import subprocess +import sys + +KEYS = ("verbose", "showThinkingSummaries") +VIEW = "viewMode" # "verbose" | "default" | "focus"; overrides KEYS and the sticky /focus choice +LIVE = "live view: ctrl+x v (or ctrl+o) toggles the transcript; ctrl+e inside it shows everything" + + +def project_root(): + try: + r = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True, timeout=2) + if r.returncode == 0 and r.stdout.strip(): + return r.stdout.strip() + except Exception: + pass + return os.getcwd() + + +def load(path): + try: + with open(path) as fh: + return json.load(fh) + except FileNotFoundError: + return {} + except Exception as e: # a broken local file must not be silently overwritten + sys.exit(f"error: cannot parse {path}: {e}") + + +def main(): + raw = " ".join(sys.argv[1:]).strip() + mode = raw.lower() or "toggle" + if mode not in ("on", "off", "toggle", "status"): + sys.exit("usage: /verbose [on|off|status]") + root = project_root() + local_path = os.path.join(root, ".claude", "settings.local.json") + user = load(os.path.expanduser("~/.claude/settings.json")) + local = load(local_path) + effective = {k: bool(local.get(k, user.get(k, False))) for k in KEYS} + view = local.get(VIEW, user.get(VIEW)) + + def state_of(view, eff): + if view == "verbose": + return "ON" + if view in ("default", "focus"): + return f"OFF ({view} forced by settings)" + if all(eff.values()): + return "ON via the verbose key (viewMode unset: a sticky /focus choice still wins)" + return "OFF" if not any(eff.values()) else "MIXED" + + if mode != "status": + current_on = state_of(view, effective).startswith("ON") + on = {"on": True, "off": False}.get(mode, not current_on) + if on: + local[VIEW] = "verbose" # forces verbose for new sessions, beating a sticky /focus + else: + local.pop(VIEW, None) # release: the sticky /focus choice (or default) applies again + for k in KEYS: + local[k] = on + os.makedirs(os.path.dirname(local_path), exist_ok=True) + with open(local_path, "w") as fh: + json.dump(local, fh, indent=2) + fh.write("\n") + effective = {k: on for k in KEYS} + view = local.get(VIEW, user.get(VIEW)) + print(f"verbose view: {'ON' if on else 'OFF'} for {root}") + print(f" written to {local_path} (viewMode applies to new sessions; the current one: ctrl+x v)") + else: + print(f"verbose view: {state_of(view, effective)} for {root}") + print(f" {VIEW}: {view or '-'} (project-local: {local.get(VIEW, '-')}, user: {user.get(VIEW, '-')})") + for k in KEYS: + print(f" {k}: {str(effective[k]).lower()} (project-local: {local.get(k, '-')}, user: {user.get(k, '-')})") + print(LIVE) + + +if __name__ == "__main__": + main() diff --git a/common/.config/claude/statusline.py b/common/.config/claude/statusline.py new file mode 100755 index 0000000..ed26d76 --- /dev/null +++ b/common/.config/claude/statusline.py @@ -0,0 +1,930 @@ +#!/usr/bin/env python3 +"""Claude Code status line. + +One line: vim mode | dir (repo-relative, hidden at the root) | +git(repo/branch +dirty +ahead/behind) | PR review threads (open count, Codex's share) | model (+effort) | +context% (+compact warn) | 5h usage (+reset eta) | cost (+burn rate) | +session tokens (cumulative in/out) | decode speed t/s (thinking blocks) | +prompt-cache hit% (+ttl, cold marker) | disk. If the +rendered line would overflow the terminal, trailing (lowest-priority) segments are +dropped until it fits. +(Dormant, re-addable in main(): ram, cpu%, temp -- retired 2026-07-26 because the +status line then only refreshed on message events, so system metrics sat visibly stale +(settings.json's 60 s refreshInterval, added for the PR count, is still too coarse for them); +tmux's status bar owns those now -- plus velocity, cache hit %, api ratio, version, +style.) + +Reads the status JSON from stdin (Claude Code statusLine command). Every segment +is wrapped defensively so the status line can never crash the UI -- on any error +a segment is simply omitted. +""" +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import time +import unicodedata + +# --- ANSI helpers ----------------------------------------------------------- +RESET = "\033[0m" +DIM = "" # disabled: "\033[2m" blended the gray detail text into dark backgrounds +BOLD = "\033[1m" +C = { + "cyan": "\033[36m", + "green": "\033[32m", + "yellow": "\033[33m", + "red": "\033[31m", + "magenta": "\033[35m", + "blue": "\033[34m", + "gray": "\033[37m", # light gray (was "\033[90m" bright-black, too dark to read) +} + + +def color(text, name="", dim=False, bold=False): + pre = "" + if dim: + pre += DIM + if bold: + pre += BOLD + pre += C.get(name, "") + return f"{pre}{text}{RESET}" if pre else str(text) + + +def bucket(value, lo, hi, invert=False): + """green/yellow/red by threshold. invert=True -> high is good.""" + if invert: + return "green" if value >= hi else ("yellow" if value >= lo else "red") + return "green" if value < lo else ("yellow" if value < hi else "red") + + +DIV = color(" │ ", "gray", dim=True) + + +def join_line(segs): + return DIV.join(s for s in segs if s) + + +_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") + + +def vlen(text): + """Visible width of a rendered string: ANSI stripped, emoji counted as 2.""" + text = _ANSI_RE.sub("", text) + w = 0 + for ch in text: + if ch in ("\u200d", "\ufe0f", "\ufe0e") or unicodedata.combining(ch): + continue # ZWJ / variation selectors / combining marks: zero width + o = ord(ch) + if o >= 0x1F000 or 0x2600 <= o <= 0x27BF or unicodedata.east_asian_width(ch) in ("W", "F"): + w += 2 + else: + w += 1 + return w + + +def term_cols(): + """Terminal width. Claude Code exports COLUMNS; 0 if unknown -> stay one line.""" + try: + return shutil.get_terminal_size(fallback=(0, 0)).columns + except Exception: + return 0 + + +# --- context usage ------------------------------------------------------------ +_USAGE_KEYS = ("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens") + + +def payload_usage(data): + """`context_window.current_usage` from the status payload, shaped like `message.usage`. + + Claude Code 2.1.x hands the status line its own token accounting, so the transcript + scan below is only a fallback for payloads that predate it (or lack a transcript). + """ + cw = data.get("context_window") + cu = cw.get("current_usage") if isinstance(cw, dict) else None + if isinstance(cu, dict) and any(isinstance(cu.get(k), (int, float)) for k in _USAGE_KEYS): + return cu + return {} + + +# --- shared transcript usage (fallback) ------------------------------------------ +def _scan_usage(text): + """Last `message.usage` block among these JSONL lines, or {}.""" + usage = {} + for line in text.splitlines(): + line = line.strip() + if not line or '"usage"' not in line: + continue + try: + obj = json.loads(line) + except Exception: + continue + msg = obj.get("message") + if isinstance(msg, dict) and isinstance(msg.get("usage"), dict): + usage = msg["usage"] + return usage + + +TRANSCRIPT_TAIL = 1 << 20 # 1 MiB + + +def last_usage(data): + """Most recent `message.usage` block from the transcript, or {}. + + Fallback only -- see payload_usage(). Reads only the tail: this runs on every status refresh and transcripts grow to + tens of MB, so re-parsing the whole file each time is unbounded work for a value + that lives at the end. Falls back to a full scan if the tail holds no usage block + (a long stretch of tool results can push it past the window). + """ + try: + path = data.get("transcript_path") + if not path or not os.path.exists(path): + return {} + with open(path, "rb") as fh: + size = fh.seek(0, os.SEEK_END) + start = max(0, size - TRANSCRIPT_TAIL) + fh.seek(start) + text = fh.read().decode("utf-8", "ignore") + if start: + text = text.partition("\n")[2] # drop the partial first line + usage = _scan_usage(text) + if not usage and start: + with open(path, "r", errors="ignore") as fh: + usage = _scan_usage(fh.read()) + return usage + except Exception: + return {} + + +# --- session token totals (transcript, incremental) --------------------------- +TOKENS_STATE_DIR = os.path.expanduser("~/.claude/cache") +TOKENS_RECENT_IDS = 20 # message ids remembered across runs for de-duplication +TPS_SAMPLES = 8 # thinking blocks the t/s readout is averaged over +TPS_MIN_MS, TPS_MIN_TOKENS = 1000, 50 # shorter blocks are first-token latency, not decode speed +TOKENS_SCAN_BUDGET = 8 << 20 # bytes parsed per refresh (~0.1 s); see session_tokens +TOKENS_STATE_MAX_AGE = 7 * 86400 # prune per-session state files older than this + + +def fmt_tokens(n): + """1234 -> 1.2k, 843000 -> 843k, 1_234_567 -> 1.2M, 12_345_678 -> 12M. + + Thresholds sit at the rounding boundaries (0.9995, 9.95) so a value never prints as + "10.0k" or "1000k" -- it rolls into the shorter form / the next unit instead.""" + n = float(n) + for unit, div in (("M", 1e6), ("k", 1e3)): + v = n / div + if v < 0.9995: + continue + return f"{v:.0f}{unit}" if v >= 9.95 else f"{v:.1f}{unit}" + return f"{n:.0f}" + + +def _tokens_state_path(data, path): + sid = data.get("session_id") or os.path.splitext(os.path.basename(path))[0] + sid = re.sub(r"[^A-Za-z0-9_-]", "_", str(sid))[:80] + return os.path.join(TOKENS_STATE_DIR, f"statusline.tokens.{sid}.json") + + +def _prune_tokens_state(keep): + """Drop stale per-session token and per-branch PR state files (one scandir, only when + the dir has piled up).""" + try: + entries = [e for e in os.scandir(TOKENS_STATE_DIR) if e.name.startswith(("statusline.tokens.", "statusline.pr."))] + if len(entries) < 50: + return + cutoff = time.time() - TOKENS_STATE_MAX_AGE + for e in entries: + if e.path != keep and e.stat().st_mtime < cutoff: + os.unlink(e.path) + except Exception: + pass + + +def session_tokens(data): + """Cumulative session token totals plus decode-speed samples, from the transcript -- + `{"in", "out", "tps"}` or None when there is no transcript. + + in/out: summed over assistant `message.usage` blocks. Input = input + cache_creation + + cache_read (everything the API billed as input), so on a 1M session it dwarfs output: + every call re-reads the whole cached prefix. Only the main transcript is counted; + subagent usage lives in separate sidechain files. + + tps: the last TPS_SAMPLES `[thinking_tokens, thinkingDurationMs]` pairs -- the only + clean per-call timing Claude Code records. The status payload's cost.total_api_duration_ms + is useless for a rate: subagent and advisor calls land in the same counter (it grew 28s + in a 12s wall interval with no main-conversation completion), and the payload's + output_tokens is sometimes a mid-stream partial. thinkingDurationMs is main-conversation + only; it includes first-token latency, so short blocks read low and long ones converge + on the real decode speed -- hence the duration-weighted mean and the minimum-size filter. + + Incremental: the status line runs on every refresh and transcripts grow to tens of + MB, so a per-session state file (~/.claude/cache/statusline.tokens..json) + remembers the byte offset already summed and only the new tail is parsed. Lines are + de-duplicated by message id: the transcript writes one line per content block of a + turn, all carrying the same id and the same usage block. Only complete lines are + consumed (the writer may be mid-line); a shrunken file (truncate/rotate) resets. + + A cold scan is spread over refreshes, TOKENS_SCAN_BUDGET bytes each: Claude Code kills + a status script when the next refresh fires, and a multi-second scan of a 100 MB + transcript that never gets to write its state would start from zero every time. + Totals climb for a few refreshes on a huge resumed transcript, then settle. + """ + path = data.get("transcript_path") + if not path or not os.path.exists(path): + return None + state_path = _tokens_state_path(data, path) + fresh = {"path": path, "offset": 0, "in": 0, "out": 0, "ids": [], "tps": [], "tps_ids": []} + state = dict(fresh) + try: + with open(state_path) as fh: + s = json.load(fh) + if ( + isinstance(s, dict) + and s.get("path") == path + and all(isinstance(s.get(k), int) and s[k] >= 0 for k in ("offset", "in", "out")) + and isinstance(s.get("ids"), list) + ): + state = s # "tps"/"tps_ids" are optional: older state files predate them + except Exception: + pass + + def result(st): + return {"in": st["in"], "out": st["out"], "tps": st.get("tps") or []} + + size = os.path.getsize(path) + if size < state["offset"]: # truncated or rotated under us: start over + state = dict(fresh) + if size == state["offset"]: + return result(state) + + with open(path, "rb") as fh: + fh.seek(state["offset"]) + chunk = fh.read(TOKENS_SCAN_BUDGET) + end = chunk.rfind(b"\n") + if end < 0 and len(chunk) == TOKENS_SCAN_BUDGET: # one line bigger than the budget: finish it + chunk += fh.readline() + end = chunk.rfind(b"\n") + if end < 0: # no complete new line yet + return result(state) + text = chunk[: end + 1].decode("utf-8", "ignore") + + tin, tout = state["in"], state["out"] + ids = [i for i in state["ids"] if isinstance(i, str)] + seen = set(ids) + tps = [s for s in (state.get("tps") or []) if isinstance(s, list) and len(s) == 2] + tps_ids = [i for i in (state.get("tps_ids") or []) if isinstance(i, str)] + tps_seen = set(tps_ids) + for line in text.splitlines(): + if '"usage"' not in line: + continue + try: + obj = json.loads(line) + except Exception: + continue + msg = obj.get("message") if isinstance(obj, dict) else None + usage = msg.get("usage") if isinstance(msg, dict) else None + if not isinstance(usage, dict): + continue + mid = msg.get("id") or obj.get("requestId") or obj.get("uuid") + if not isinstance(mid, str): + continue + + def num(d, k): + v = d.get(k, 0) if isinstance(d, dict) else 0 + return int(v) if isinstance(v, (int, float)) else 0 + + # Decode-speed sample: checked on every line (not just the first-wins one below) so + # it does not depend on the thinking block being the message's first line. + ms = num(obj, "thinkingDurationMs") + toks = num(usage.get("output_tokens_details"), "thinking_tokens") + if ms >= TPS_MIN_MS and toks >= TPS_MIN_TOKENS and mid not in tps_seen: + tps_seen.add(mid) + tps_ids.append(mid) + tps.append([toks, ms]) + + if mid in seen: + continue + seen.add(mid) + ids.append(mid) + tin += num(usage, "input_tokens") + num(usage, "cache_creation_input_tokens") + num(usage, "cache_read_input_tokens") + tout += num(usage, "output_tokens") + + state = { + "path": path, + "offset": state["offset"] + end + 1, + "in": tin, + "out": tout, + "ids": ids[-TOKENS_RECENT_IDS:], + "tps": tps[-TPS_SAMPLES:], + "tps_ids": tps_ids[-TOKENS_RECENT_IDS:], + } + try: + os.makedirs(TOKENS_STATE_DIR, exist_ok=True) + tmp = f"{state_path}.{os.getpid()}.tmp" + with open(tmp, "w") as fh: + json.dump(state, fh) + os.replace(tmp, state_path) # atomic: a concurrent refresh never reads a half-written file + _prune_tokens_state(state_path) + except Exception: + pass + return result(state) + + +# --- row 1: work ------------------------------------------------------------ +def vim_segment(data): + """Vim editor mode as a compact [I]/[N]/[V] (only present with editorMode: vim). + + Pair with `"hideVimModeIndicator": true` in the statusLine settings block so + Claude's own built-in indicator doesn't duplicate this one. + """ + mode = (data.get("vim") or {}).get("mode") + if not mode: + return "" + m = mode.upper() + if m.startswith("INSERT"): + return color("[I]", "green", bold=True) + if m.startswith("VISUAL"): + return color("[V]", "magenta", bold=True) + if m.startswith("NORMAL"): + return color("[N]", "blue", bold=True) + return color(f"[{m[:1]}]", "gray") + + +def abbrev(path): + """fish-style prompt_pwd: shrink every component but the last to one char, + keeping a leading dot (`.config` -> `.c`).""" + parts = path.split(os.sep) + out = [] + for i, p in enumerate(parts): + if i == len(parts) - 1 or p in ("", "~"): + out.append(p) + elif p.startswith("."): + out.append(p[:2]) + else: + out.append(p[:1]) + return os.sep.join(out) + + +def dir_segment(cwd, top=None): + """Path *inside* the repo -- git_segment already names the repo itself, so + repeating the full ~-path here was pure duplication. Empty at the repo root; + a fish-shortened ~-path when we're not in a repo at all.""" + try: + rel = os.path.relpath(cwd, top) if top else None + if rel and not rel.startswith(os.pardir): # `..` -> cwd is outside `top` (symlinked in); use the ~-path + if rel == os.curdir: + return "" + shown = rel if len(rel) <= 28 else abbrev(rel) + else: + home = os.path.expanduser("~") + shown = cwd + if cwd == home: + shown = "~" + elif cwd.startswith(home + os.sep): + shown = "~" + cwd[len(home):] + shown = abbrev(shown) + return "📁 " + color(shown, "cyan") + except Exception: + return "" + + +def _git(cwd, *args): + return subprocess.run( + ["git", "-C", cwd, *args], capture_output=True, text=True, timeout=1 + ) + + +def git_top(cwd): + """Absolute path of the enclosing work tree, or None.""" + try: + r = _git(cwd, "rev-parse", "--show-toplevel") + return r.stdout.strip() or None if r.returncode == 0 else None + except Exception: + return None + + +def git_segment(cwd, top): + try: + if not top: + return "" + repo = os.path.basename(top) or "repo" + branch = _git(cwd, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip() or "?" + + # `status --porcelain` walks the whole work tree, so in a big repo it can blow + # the 1s timeout -- in its own try, because letting that escape dropped the repo + # and branch we already had: a decoration failing must not take the segment down. + try: + dirty = bool(_git(cwd, "status", "--porcelain").stdout.strip()) + except Exception: + dirty = False + + # ahead/behind vs upstream (omitted when no upstream is configured) + ab = "" + rl = _git(cwd, "rev-list", "--left-right", "--count", "@{upstream}...HEAD") + if rl.returncode == 0 and rl.stdout.strip(): + try: + behind, ahead = (int(x) for x in rl.stdout.split()) + bits = [] + if ahead: + bits.append(color(f"↑{ahead}", "cyan")) + if behind: + bits.append(color(f"↓{behind}", "yellow")) + if bits: + ab = " " + "".join(bits) + except Exception: + ab = "" + + mark = color("*", "red") if dirty else "" + label = color(repo, "magenta", bold=True) + br = color(branch, "yellow" if dirty else "green") + return f"🌿 {label} {br}{mark}{ab}" + except Exception: + return "" + + +# --- PR review threads (gh, cached, fetched in the background) ------------------ +PR_TTL = 90 # seconds a fetched count stays fresh +PR_ERR_TTL = 600 # back-off after a failed fetch (no GitHub remote, gh not authed, offline) +PR_CLAIM = 30 # a refresher spawned this recently is still running: don't start another +PR_CODEX = re.compile(r"codex", re.I) # chatgpt-codex-connector; same match as /pr-loop +PR_QUERY = """query($owner:String!,$repo:String!,$branch:String!){ + repository(owner:$owner,name:$repo){ + pullRequests(headRefName:$branch,states:OPEN,first:1,orderBy:{field:UPDATED_AT,direction:DESC}){ + nodes{ number reviewThreads(first:100){ pageInfo{hasNextPage} + nodes{ isResolved comments(first:1){ nodes{ author{login} } } } } } } } }""" + + +def _pr_cache_path(top, branch): + key = hashlib.sha1(f"{top}\0{branch}".encode()).hexdigest()[:16] + return os.path.join(TOKENS_STATE_DIR, f"statusline.pr.{key}.json") + + +def _read_json(path): + try: + with open(path) as fh: + d = json.load(fh) + return d if isinstance(d, dict) else {} + except Exception: + return {} + + +def pr_refresh(cwd, branch, path): + """Background half of pr_segment (`statusline.py --pr-refresh CWD BRANCH CACHE`): fetch the + branch's open PR and write its unresolved review-thread counts to the cache. `{owner}` / + `{repo}` are gh placeholders resolved from the repo at `cwd`. A failed fetch keeps the last + counts and flags them stale; a branch without an open PR clears them.""" + state = _read_json(path) + state["ts"] = time.time() + try: + r = subprocess.run( + ["gh", "api", "graphql", "-F", "owner={owner}", "-F", "repo={repo}", + "-f", f"branch={branch}", "-f", f"query={PR_QUERY}"], + cwd=cwd, capture_output=True, text=True, timeout=20, + ) + if r.returncode != 0: + raise RuntimeError(r.stderr) + nodes = json.loads(r.stdout)["data"]["repository"]["pullRequests"]["nodes"] + state = {"ts": state["ts"]} + if nodes: + threads = nodes[0]["reviewThreads"] + # a thread belongs to whoever opened it: its first comment's author + authors = [((t["comments"]["nodes"] or [{}])[0].get("author") or {}).get("login") or "" + for t in threads["nodes"] if not t["isResolved"]] + state.update(number=nodes[0]["number"], open=len(authors), + codex=sum(1 for a in authors if PR_CODEX.search(a)), + more=threads["pageInfo"]["hasNextPage"]) + except Exception: + state["error"] = True + try: + os.makedirs(TOKENS_STATE_DIR, exist_ok=True) + tmp = f"{path}.{os.getpid()}.tmp" + with open(tmp, "w") as fh: + json.dump(state, fh) + os.replace(tmp, path) + except Exception: + pass + + +def pr_segment(cwd, top): + """Unresolved review threads (any author, outdated ones included) on the current branch's + open PR: `💬 #N ✓` when none are left, else the count with Codex's share broken out. + + A GitHub round trip takes ~0.7 s, too slow for a render, so this only reads a per-branch + cache (~/.claude/cache/statusline.pr..json) and, once it is older than PR_TTL, + spawns a detached `--pr-refresh` child to update it -- the new count shows on the next + render. PR-conversation comments are not counted: they have no resolved state, so a + summary or an LGTM would keep the count from ever reaching zero. + """ + try: + if not top or not shutil.which("gh"): + return "" + branch = _git(cwd, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip() + if not branch or branch == "HEAD": + return "" + path = _pr_cache_path(top, branch) + state = _read_json(path) + if time.time() - (state.get("ts") or 0) > (PR_ERR_TTL if state.get("error") else PR_TTL): + claim = path + ".lock" + try: + claimed = time.time() - os.path.getmtime(claim) < PR_CLAIM + except OSError: + claimed = False + if not claimed: + os.makedirs(TOKENS_STATE_DIR, exist_ok=True) + with open(claim, "w"): + pass + # own session + no inherited stdout: Claude Code reads ours to EOF, and + # cancels an in-flight render when the next one triggers + subprocess.Popen( + [sys.executable, os.path.abspath(__file__), "--pr-refresh", cwd, branch, path], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True, + ) + num = state.get("number") + if not num: + return "" + n, codex = state.get("open") or 0, state.get("codex") or 0 + out = "💬 " + color(f"#{num} ", "gray") + if not n: + out += color("✓", "green") + else: + out += color(f"{n}{'+' if state.get('more') else ''}", "yellow", bold=True) + if codex: + out += color(" · ", "gray") + color(f"codex {codex}", "red") + if state.get("error"): + out += color(" ?", "gray") # last fetch failed: these counts are stale + return out + except Exception: + return "" + + +def model_segment(data): + name = (data.get("model") or {}).get("display_name") + if not name: + return "" + name = name.replace(" context)", ")") # "Opus 4.8 (1M context)" -> "Opus 4.8 (1M)" + out = "🤖 " + color(name, "blue") + level = (data.get("effort") or {}).get("level") + if level: + out += color(f" · {level}", "gray") + return out + + +def context_window(data): + """Size of this session's context window, in tokens. + + Claude Code resolves the `[1m]` model suffix away before handing the status line + its JSON -- `model.id` is always the bare API id ("claude-fable-5") -- so sniffing + the id for "1m" could never detect a 1M session and every one of them was measured + against a 200k window (5x overstated %, ⚠compact from ~16% real usage). The payload + carries the real number; display_name ("Opus 4.8 (1M context)") is the fallback. + """ + cw = data.get("context_window") + if isinstance(cw, dict): + for key in ("context_window_size", "max_tokens", "size"): + val = cw.get(key) + if isinstance(val, (int, float)) and val > 0: + return int(val) + name = ((data.get("model") or {}).get("display_name") or "").lower() + return 1_000_000 if "1m" in name else 200_000 + + +def context_segment(data, usage): + try: + if not usage: + return "" + used = ( + usage.get("input_tokens", 0) + + usage.get("cache_creation_input_tokens", 0) + + usage.get("cache_read_input_tokens", 0) + ) + window = context_window(data) + pct = used / window * 100 if window else 0 + # Prefer Claude Code's own percentage when the payload carries it (2.1.x) -- it + # already accounts for the auto-compact reserve and window quirks we can't see. + cw = data.get("context_window") + if isinstance(cw, dict) and isinstance(cw.get("used_percentage"), (int, float)): + pct = float(cw["used_percentage"]) + col = bucket(pct, 50, 80) + out = "📝 " + color(f"{pct:.0f}%", col) + color(f" ({used / 1000:.0f}k)", "gray", dim=True) + if pct >= 80: + out += color(" ⚠compact", "red", bold=True) + return out + except Exception: + return "" + + +def usage_segment(data): + """5-hour rolling usage window: used % (+ time until it resets).""" + try: + five = (data.get("rate_limits") or {}).get("five_hour") or {} + pct = five.get("used_percentage") + if pct is None: + return "" + out = "📊 " + color(f"{pct:.0f}%", bucket(pct, 50, 80)) + resets = five.get("resets_at") + if resets: + secs = int(resets) - int(time.time()) + if secs > 0: + h, m = divmod(secs // 60, 60) + out += color(f" {h}h{m:02d}m" if h else f" {m}m", "gray") + return out + except Exception: + return "" + + +def cost_segment(data): + try: + cost = data.get("cost") or {} + usd = cost.get("total_cost_usd") + if usd is None: + return "" + out = "💰 " + color(f"${usd:.2f}", "yellow") + dur_ms = cost.get("total_duration_ms") or 0 + if dur_ms > 30_000: # need a meaningful window before extrapolating + per_hr = usd / (dur_ms / 3_600_000) + out += color(f" ${per_hr:.2f}/h", "gray", dim=True) + return out + except Exception: + return "" + + +def velocity_segment(data): + try: + cost = data.get("cost") or {} + added = cost.get("total_lines_added", 0) + removed = cost.get("total_lines_removed", 0) + if not (added or removed): + return "" + out = "✏️ " + color(f"+{added}", "green") + color("/", "gray", dim=True) + color(f"-{removed}", "red") + dur_ms = cost.get("total_duration_ms") or 0 + if dur_ms > 30_000: + per_min = added / (dur_ms / 60_000) + out += color(f" {per_min:.0f}/m", "gray", dim=True) + return out + except Exception: + return "" + + +def tokens_segment(totals): + """Cumulative session tokens: ↑ input (incl. cache reads/writes) and ↓ output.""" + try: + if not totals: + return "" + tin, tout = totals["in"], totals["out"] + if not (tin or tout): + return "" + return "🔢 " + color(f"↑{fmt_tokens(tin)}", "cyan") + " " + color(f"↓{fmt_tokens(tout)}", "green") + except Exception: + return "" + + +def tps_segment(totals): + """Decode speed in tokens/s: duration-weighted mean over the last few thinking blocks + (see session_tokens). Omitted until a thinking block ≥1s has completed -- so never + shown with thinking disabled.""" + try: + samples = (totals or {}).get("tps") or [] + toks = sum(s[0] for s in samples) + ms = sum(s[1] for s in samples) + if toks <= 0 or ms <= 0: + return "" + rate = toks / ms * 1000 + return "⚡ " + color(f"{rate:.0f} t/s", bucket(rate, 20, 40, invert=True)) + except Exception: + return "" + + +def cache_segment(usage, data=None): + """Prompt-cache hit % (higher is better) + the cache TTL, `·cold` when the cache has + expired. Hit % from the 2.1.260+ payload `prompt_cache.hit_ratio` (a 0..1 fraction, null + while all counts are zero), else computed from the usage block; ttl/cold always from the + payload when present. A 1h TTL is what keeps a 10-minute pr-loop cadence warm.""" + try: + pc = (data or {}).get("prompt_cache") + pc = pc if isinstance(pc, dict) else {} + pct = None + if isinstance(pc.get("hit_ratio"), (int, float)): + pct = float(pc["hit_ratio"]) * 100 + elif usage: + read = usage.get("cache_read_input_tokens", 0) + total = usage.get("input_tokens", 0) + usage.get("cache_creation_input_tokens", 0) + read + if total > 0: + pct = read / total * 100 + if pct is None: + return "" + out = "♻️ " + color(f"{pct:.0f}%", bucket(pct, 50, 80, invert=True)) + ttl = pc.get("ttl") + if isinstance(ttl, str) and ttl: + out += color(f" {ttl}", "gray") + if pc.get("warm") is False: + out += color(" ·cold", "yellow") + return out + except Exception: + return "" + + +def api_segment(data): + """Share of wall-clock time spent in API/inference (rough 'busy' ratio).""" + try: + cost = data.get("cost") or {} + wall = cost.get("total_duration_ms") or 0 + api = cost.get("total_api_duration_ms") or 0 + if wall <= 0 or api <= 0: + return "" + pct = min(api / wall * 100, 100) + return "⚙️ " + color(f"{pct:.0f}%", "blue") + except Exception: + return "" + + +# --- row 2: system ---------------------------------------------------------- +def ram_segment(): + try: + info = {} + with open("/proc/meminfo") as fh: + for line in fh: + k, _, v = line.partition(":") + info[k.strip()] = int(v.split()[0]) # kB + total = info.get("MemTotal", 0) + avail = info.get("MemAvailable", info.get("MemFree", 0)) + if total <= 0: + return "" + used = total - avail + pct = used / total * 100 + g = 1024 * 1024 + return ( + "🧠 " + color(f"{pct:.0f}%", bucket(pct, 70, 85)) + + color(f" {used / g:.1f}/{total / g:.0f}G", "gray", dim=True) + ) + except Exception: + return "" + + +def disk_segment(cwd): + try: + st = os.statvfs(cwd) + total = st.f_blocks + if total <= 0: + return "" + used = total - st.f_bfree + pct = used / total * 100 + return "💾 " + color(f"{pct:.0f}%", bucket(pct, 75, 90)) + except Exception: + return "" + + +def _cpu_pct(): + """Live CPU% diffed against a cached /proc/stat snapshot (no sleeping).""" + try: + with open("/proc/stat") as fh: + parts = fh.readline().split() + if not parts or parts[0] != "cpu": + return None + vals = [int(x) for x in parts[1:]] + idle = vals[3] + (vals[4] if len(vals) > 4 else 0) # idle + iowait + total = sum(vals) + + state = os.path.expanduser("~/.claude/cache/statusline.cpu") + prev = None + try: + with open(state) as fh: + pt, pi = fh.read().split() + prev = (int(pt), int(pi)) + except Exception: + prev = None + try: + os.makedirs(os.path.dirname(state), exist_ok=True) + with open(state, "w") as fh: + fh.write(f"{total} {idle}") + except Exception: + pass + + if not prev: + return None + dt = total - prev[0] + di = idle - prev[1] + if dt <= 0 or di < 0: + return None + return max(0.0, min(100.0, (1 - di / dt) * 100)) + except Exception: + return None + + +def cpu_segment(): + try: + load1 = os.getloadavg()[0] + cores = os.cpu_count() or 1 + pct = _cpu_pct() + if pct is not None: + head = color(f"{pct:.0f}%", bucket(pct, 60, 85)) + tail = color(f" {load1:.1f} {cores}c", "gray", dim=True) + else: + head = color(f"{load1:.2f}", bucket(load1 / cores, 0.7, 1.0)) + tail = color(f" {cores}c", "gray", dim=True) + return "🖥️ " + head + tail + except Exception: + return "" + + +def temp_segment(): + """Hottest CPU-ish thermal zone in °C, falling back to the max zone.""" + try: + base = "/sys/class/thermal" + if not os.path.isdir(base): + return "" + prefer = ("x86_pkg_temp", "coretemp", "cpu", "k10temp", "tctl") + chosen = None + fallback = None + for name in os.listdir(base): + if not name.startswith("thermal_zone"): + continue + d = os.path.join(base, name) + try: + with open(os.path.join(d, "temp")) as fh: + milli = int(fh.read().strip()) + except Exception: + continue + ztype = "" + try: + with open(os.path.join(d, "type")) as fh: + ztype = fh.read().strip().lower() + except Exception: + pass + if fallback is None or milli > fallback: + fallback = milli + if any(p in ztype for p in prefer) and (chosen is None or milli > chosen): + chosen = milli + milli = chosen if chosen is not None else fallback + if milli is None: + return "" + c = milli / 1000.0 + return "🌡️ " + color(f"{c:.0f}°C", bucket(c, 60, 80)) + except Exception: + return "" + + +def version_segment(data): + v = data.get("version") + return color(f"v{v}", "gray", dim=True) if v else "" + + +def style_segment(data): + name = (data.get("output_style") or {}).get("name") + return color(f"🎨{name}", "gray", dim=True) if name else "" + + +def main(): + if sys.argv[1:2] == ["--pr-refresh"] and len(sys.argv) == 5: + pr_refresh(*sys.argv[2:]) + return + try: + data = json.load(sys.stdin) + except Exception: + data = {} + + cwd = ( + (data.get("workspace") or {}).get("current_dir") + or data.get("cwd") + or os.getcwd() + ) + usage = payload_usage(data) or last_usage(data) + totals = session_tokens(data) + top = git_top(cwd) + + # One row: work (left) then system (right), joined. If it would overflow the + # terminal, trailing (lowest-priority) segments are dropped so it stays one line. + # Dormant helpers kept above for easy re-add: ram_segment, cpu_segment, + # temp_segment (retired -- they only refresh on message events, so they sat + # stale; the tmux status bar owns system metrics now), velocity_segment, + # api_segment, version_segment, style_segment. + work = [s for s in ( + vim_segment(data), + dir_segment(cwd, top), + git_segment(cwd, top), + pr_segment(cwd, top), + model_segment(data), + context_segment(data, usage), + usage_segment(data), + cost_segment(data), + tokens_segment(totals), + tps_segment(totals), + cache_segment(usage, data), + ) if s] + system = [s for s in ( + disk_segment(cwd), + ) if s] + + segs = work + system + cols = term_cols() + if cols: # trim from the right until it fits one line (cols=0 -> width unknown, keep all) + while len(segs) > 1 and vlen(join_line(segs)) > cols: + segs.pop() + sys.stdout.write(join_line(segs)) + + +if __name__ == "__main__": + main() diff --git a/common/.config/fastfetch/config.jsonc b/common/.config/fastfetch/config.jsonc new file mode 100644 index 0000000..0b6784b --- /dev/null +++ b/common/.config/fastfetch/config.jsonc @@ -0,0 +1,108 @@ +{ + "$schema": "https://github.com/fastfetch-cli/fastfetch/raw/dev/doc/json_schema.json", + "logo": { + "source": "$(find \"${XDG_CONFIG_HOME:-$HOME/.config}/fastfetch/pngs/\" -name \"*.png\" -xtype f | shuf -n 1)", + "height": 18 + }, + "display": { + "separator": " : " + }, + "modules": [ + { + "type": "custom", + "format": "\u001b[36m " + }, + { + "type": "custom", + "format": "┌──────────────────────────────────────────┐" + }, + { + "type": "os", + "key": "  OS", + "keyColor": "red" + }, + { + "type": "kernel", + "key": "  Kernel", + "keyColor": "red" + }, + { + "type": "packages", + "key": "  Packages", + "keyColor": "green" + }, + { + "type": "display", + "key": "  Display", + "keyColor": "green" + }, + { + "type": "wm", + "key": "  WM", + "keyColor": "yellow" + }, + { + "type": "terminal", + "key": "  Terminal", + "keyColor": "yellow" + }, + { + "type": "custom", + "format": "└──────────────────────────────────────────┘" + }, + "break", + { + "type": "title", + "key": " " + }, + { + "type": "custom", + "format": "┌──────────────────────────────────────────┐" + }, + { + "type": "cpu", + "format": "{1}", + "key": "  CPU", + "keyColor": "blue" + }, + { + "type": "gpu", + "format": "{2}", + "key": "  GPU", + "keyColor": "blue" + }, + { + "type": "gpu", + "format": "{3}", + "key": "  GPU Driver", + "keyColor": "magenta" + }, + { + "type": "memory", + "key": " ﬙ Memory", + "keyColor": "magenta" + }, + { + "type": "command", + "key": " 󱦟 OS Age ", + "keyColor": "31", + "text": "birth_install=$(stat -c %W /); current=$(date +%s); time_progression=$((current - birth_install)); days_difference=$((time_progression / 86400)); echo $days_difference days" + }, + { + "type": "uptime", + "key": " 󱫐 Uptime ", + "keyColor": "red" + }, + { + "type": "custom", + "format": "└──────────────────────────────────────────┘" + }, + { + "type": "colors", + "paddingLeft": 2, + "symbol": "circle" + }, + "break" + + ] +} diff --git a/common/.config/fastfetch/pngs/arch.png b/common/.config/fastfetch/pngs/arch.png new file mode 100644 index 0000000..db5a7e8 Binary files /dev/null and b/common/.config/fastfetch/pngs/arch.png differ diff --git a/common/.config/fastfetch/pngs/archlinux.png b/common/.config/fastfetch/pngs/archlinux.png new file mode 100644 index 0000000..b354eb3 Binary files /dev/null and b/common/.config/fastfetch/pngs/archlinux.png differ diff --git a/common/.config/fastfetch/pngs/dmz-rabbit.png b/common/.config/fastfetch/pngs/dmz-rabbit.png new file mode 100644 index 0000000..d0efe0c Binary files /dev/null and b/common/.config/fastfetch/pngs/dmz-rabbit.png differ diff --git a/common/.config/fastfetch/pngs/dmz-rabbit2.png b/common/.config/fastfetch/pngs/dmz-rabbit2.png new file mode 100644 index 0000000..eca1d86 Binary files /dev/null and b/common/.config/fastfetch/pngs/dmz-rabbit2.png differ diff --git a/common/.config/fastfetch/pngs/neonom.png b/common/.config/fastfetch/pngs/neonom.png new file mode 100644 index 0000000..c4a486c Binary files /dev/null and b/common/.config/fastfetch/pngs/neonom.png differ diff --git a/common/.config/fastfetch/pngs/network.png b/common/.config/fastfetch/pngs/network.png new file mode 100644 index 0000000..957300f Binary files /dev/null and b/common/.config/fastfetch/pngs/network.png differ diff --git a/common/.config/fastfetch/pngs/network_12.png b/common/.config/fastfetch/pngs/network_12.png new file mode 100644 index 0000000..b261948 Binary files /dev/null and b/common/.config/fastfetch/pngs/network_12.png differ diff --git a/common/.config/fastfetch/pngs/networkandtext.png b/common/.config/fastfetch/pngs/networkandtext.png new file mode 100644 index 0000000..bc24110 Binary files /dev/null and b/common/.config/fastfetch/pngs/networkandtext.png differ diff --git a/common/.config/fastfetch/pngs/openhardware.png b/common/.config/fastfetch/pngs/openhardware.png new file mode 100644 index 0000000..5ee03b2 Binary files /dev/null and b/common/.config/fastfetch/pngs/openhardware.png differ diff --git a/common/.config/fastfetch/pngs/opensource.png b/common/.config/fastfetch/pngs/opensource.png new file mode 100644 index 0000000..99c2816 Binary files /dev/null and b/common/.config/fastfetch/pngs/opensource.png differ diff --git a/common/.config/fastfetch/pngs/opensourcee.png b/common/.config/fastfetch/pngs/opensourcee.png new file mode 100644 index 0000000..87e73f5 Binary files /dev/null and b/common/.config/fastfetch/pngs/opensourcee.png differ diff --git a/common/.config/fastfetch/pngs/opensourcehardware.png b/common/.config/fastfetch/pngs/opensourcehardware.png new file mode 100644 index 0000000..1cd749a Binary files /dev/null and b/common/.config/fastfetch/pngs/opensourcehardware.png differ diff --git a/common/.config/fish/completions/c2-worktree.fish b/common/.config/fish/completions/c2-worktree.fish new file mode 100644 index 0000000..a4a2a4c --- /dev/null +++ b/common/.config/fish/completions/c2-worktree.fish @@ -0,0 +1,5 @@ +# Single positional arg: a branch name. It runs `git checkout -b`, so the new +# branch is typically a fresh name -- but offer existing branch names as a base +# to type from. Only suggest inside a git repo. +complete -c c2-worktree -x -n 'git rev-parse --is-inside-work-tree 2>/dev/null' \ + -a '(git for-each-ref --format="%(refname:short)" refs/heads refs/remotes 2>/dev/null | string replace -r "^origin/" "")' diff --git a/common/.config/fish/completions/h.fish b/common/.config/fish/completions/h.fish new file mode 100644 index 0000000..700542c --- /dev/null +++ b/common/.config/fish/completions/h.fish @@ -0,0 +1,3 @@ +# `h ...` shows a command's --help via bat, so complete it like a +# command line: first token = a command, rest = that command's own args. +complete -c h -x -a '(__fish_complete_subcommand)' diff --git a/common/.config/fish/completions/pipx.fish b/common/.config/fish/completions/pipx.fish new file mode 100644 index 0000000..b1180aa --- /dev/null +++ b/common/.config/fish/completions/pipx.fish @@ -0,0 +1,16 @@ +function __fish_pipx_complete + set -x _ARGCOMPLETE 1 + set -x _ARGCOMPLETE_DFS \t + set -x _ARGCOMPLETE_IFS \n + set -x _ARGCOMPLETE_SUPPRESS_SPACE 1 + set -x _ARGCOMPLETE_SHELL fish + set -x COMP_LINE (commandline -p) + set -x COMP_POINT (string length (commandline -cp)) + set -x COMP_TYPE + if set -q _ARC_DEBUG + pipx 8>&1 9>&2 1>&9 2>&1 + else + pipx 8>&1 9>&2 1>/dev/null 2>&1 + end +end +complete --command pipx -f -a '(__fish_pipx_complete)' diff --git a/common/.config/fish/conf.d/agent-state.fish b/common/.config/fish/conf.d/agent-state.fish new file mode 100644 index 0000000..dec8419 --- /dev/null +++ b/common/.config/fish/conf.d/agent-state.fish @@ -0,0 +1,27 @@ +# Mark the tmux window when a long shell command finishes, through the same +# ~/.config/tmux/scripts/agent-state.sh the coding agents use (tool tag "sh"): +# ✓ on exit 0, ! on failure — coloured when it happened while you were elsewhere, grey once +# visited, gone at the next command. Only commands longer than $agent_state_min_ms +# (default 30 s) count, and interactive programs are skipped: the agents mark themselves, +# and quitting a long nvim or lazygit session is not news. No-op outside tmux. +set -q agent_state_min_ms; or set -g agent_state_min_ms 30000 + +function __agent_state_preexec --on-event fish_preexec + set -q TMUX_PANE; or return + ~/.config/tmux/scripts/agent-state.sh sh busy +end + +function __agent_state_postexec --on-event fish_postexec + set -l st $status # first statement: anything before it would clobber the command's status + set -q TMUX_PANE; or return + test "$CMD_DURATION" -gt "$agent_state_min_ms"; or return + switch (string split -m1 ' ' -- $argv[1])[1] + case nvim vim vi less man lazygit ssh mosh tmux claude claudes pi opencode opencodes codex aichat htop btop top journalctl tail watch + return + end + if test $st -eq 0 + ~/.config/tmux/scripts/agent-state.sh sh done + else + ~/.config/tmux/scripts/agent-state.sh sh error + end +end diff --git a/common/.config/fish/conf.d/fish-ssh-agent.fish b/common/.config/fish/conf.d/fish-ssh-agent.fish new file mode 100644 index 0000000..719087a --- /dev/null +++ b/common/.config/fish/conf.d/fish-ssh-agent.fish @@ -0,0 +1,7 @@ +if test -z "$SSH_ENV" + set -xg SSH_ENV $HOME/.ssh/environment +end + +if not __ssh_agent_is_started + __ssh_agent_start +end diff --git a/common/.config/fish/conf.d/fish_frozen_key_bindings.fish b/common/.config/fish/conf.d/fish_frozen_key_bindings.fish new file mode 100644 index 0000000..fe6fe1a --- /dev/null +++ b/common/.config/fish/conf.d/fish_frozen_key_bindings.fish @@ -0,0 +1,3 @@ +set --global fish_key_bindings fish_vi_key_bindings + +set --erase --universal fish_key_bindings diff --git a/common/.config/fish/conf.d/fish_frozen_theme.fish b/common/.config/fish/conf.d/fish_frozen_theme.fish new file mode 100644 index 0000000..a9dbe13 --- /dev/null +++ b/common/.config/fish/conf.d/fish_frozen_theme.fish @@ -0,0 +1,38 @@ +set --global fish_color_autosuggestion 4D5566 +set --global fish_color_cancel -r +set --global fish_color_command 39BAE6 +set --global fish_color_comment 626A73 +set --global fish_color_cwd 59C2FF +set --global fish_color_cwd_root red +set --global fish_color_end F29668 +set --global fish_color_error FF3333 +set --global fish_color_escape 95E6CB +set --global fish_color_history_current --bold +set --global fish_color_host normal +set --global fish_color_host_remote yellow +set --global fish_color_keyword 39BAE6 +set --global fish_color_match F07178 +set --global fish_color_normal B3B1AD +set --global fish_color_operator E6B450 +set --global fish_color_option B3B1AD +set --global fish_color_param B3B1AD +set --global fish_color_quote C2D94C +set --global fish_color_redirection FFEE99 +set --global fish_color_search_match --background=E6B450 +set --global fish_color_selection --background=E6B450 +set --global fish_color_status red +set --global fish_color_user brgreen +set --global fish_color_valid_path --underline +set --global fish_pager_color_background +set --global fish_pager_color_completion normal +set --global fish_pager_color_description B3A06D yellow +set --global fish_pager_color_prefix normal --bold --underline +set --global fish_pager_color_progress brwhite --background=cyan +set --global fish_pager_color_secondary_background +set --global fish_pager_color_secondary_completion +set --global fish_pager_color_secondary_description +set --global fish_pager_color_secondary_prefix +set --global fish_pager_color_selected_background --background=E6B450 +set --global fish_pager_color_selected_completion +set --global fish_pager_color_selected_description +set --global fish_pager_color_selected_prefix diff --git a/common/.config/fish/conf.d/fnm.fish b/common/.config/fish/conf.d/fnm.fish new file mode 100644 index 0000000..542288d --- /dev/null +++ b/common/.config/fish/conf.d/fnm.fish @@ -0,0 +1,7 @@ +# fnm — single init for all hosts (config.fish must NOT source fnm again: +# every `fnm env | source` mints a fresh multishell dir onto PATH). +# fnm may be pacman-installed (on PATH) or self-installed under ~/.local/share/fnm. +test -d "$HOME/.local/share/fnm"; and fish_add_path -g "$HOME/.local/share/fnm" +if command -q fnm + fnm env --use-on-cd --version-file-strategy local --shell fish | source +end diff --git a/common/.config/fish/conf.d/kitty-public-key.fish b/common/.config/fish/conf.d/kitty-public-key.fish new file mode 100644 index 0000000..8132bb7 --- /dev/null +++ b/common/.config/fish/conf.d/kitty-public-key.fish @@ -0,0 +1,20 @@ +# Drop kitty's KITTY_PUBLIC_KEY from the shell environment. +# +# kitty generates a random 40-char base85 public key per instance and exports it +# to every child (kitty/child.py). It is only read on the password path of kitty +# remote control (kitty/remote_control.py: "Password usage requested but +# KITTY_PUBLIC_KEY environment variable is not available"), which needs +# allow_remote_control — not enabled here. `kitten ssh`, icat, clipboard and +# shell integration never touch it. +# +# Why bother: tools that inline the environment into generated code get corrupted +# when a value contains a String.replace replacement sequence. prettier's +# --experimental-cli inlines JSON.stringify(process.env) into its parallel worker +# and splices it with .replace(placeholder, bootloader); a `$` + backtick in the +# key expands to "everything before the match", injecting the worker's own source +# mid-string. Every file then fails with a bogus +# "SyntaxError: Unexpected identifier 'string'". Roughly a 1-in-185 chance per +# kitty launch, which is exactly as fun to debug as it sounds. +if set -q KITTY_PUBLIC_KEY + set -e KITTY_PUBLIC_KEY +end diff --git a/common/.config/fish/config.fish b/common/.config/fish/config.fish new file mode 100644 index 0000000..921b530 --- /dev/null +++ b/common/.config/fish/config.fish @@ -0,0 +1,135 @@ +## Shared fish config (all hosts). Host-specific bits live in host.fish (sourced at the end). +## Secrets (e.g. DUSKADIY_API_KEY) go in conf.d/secrets.fish, which is gitignored. + +set -gx EDITOR nvim +set -gx PAGER less +set -gx QT_FONT_DPI 96 +set -gx PI_SKIP_VERSION_CHECK 1 +# opencode GPT/Codex OAuth overlay (~/.config/opencode/openai-gpt.jsonc). opencode 2.x ignores +# OPENCODE_CONFIG / OPENCODE_CONFIG_CONTENT, but it merges a second global file, opencode.jsonc. +# Link the overlay under that name only where `opencode auth login` stored an OpenAI credential, +# so other hosts don't get an unusable provider; drop our link again if the login goes away. +# (Alternative: ship the link from the host's dots overlay instead of this startup check.) +set -l _oc_auth ~/.local/share/opencode/auth.json +set -l _oc_link ~/.config/opencode/opencode.jsonc +if test -r $_oc_auth; and grep -q '"openai"' $_oc_auth + test -e $_oc_link; or ln -s openai-gpt.jsonc $_oc_link +else if test -L $_oc_link; and test (readlink $_oc_link) = openai-gpt.jsonc + rm $_oc_link +end +set -gx MANPAGER "nvim +Man!" +# fzf's built-in walker is the one search tool that ignores .ignore files, so point it at +# fd, which honours them. fd still hides dotfiles by default everywhere else — this only +# changes what fzf sees inside trees that opt in (e.g. ~/.dots/.ignore). +set -gx FZF_DEFAULT_COMMAND 'fd --type f --strip-cwd-prefix' +set -gx NEWT_COLORS 'root=black,black;window=black,black;border=white,black;listbox=white,black;label=blue,black;checkbox=red,black;title=green,black;button=white,red;actsellistbox=white,red;actlistbox=white,gray;compactbutton=white,gray;actcheckbox=white,blue;entry=lightgray,black;textbox=blue,black' # themes nmtui +# set -gx BAT_THEME "Catppuccin Mocha" + +# PATH additions — global on purpose: scripts need these tools too. +# (fnm is initialized once in conf.d/fnm.fish — don't source it again here) +fish_add_path $HOME/.cargo/bin $HOME/.local/bin + +# pnpm +set -gx PNPM_HOME "$HOME/.local/share/pnpm" +if not string match -q -- $PNPM_HOME $PATH + set -gx PATH "$PNPM_HOME" $PATH +end + +# Everything below is for a human at a prompt. config.fish is sourced by EVERY fish — +# scripts and `fish -c` included — and zoxide's `--cmd cd` alias is unconditional: in a +# script, a failed `cd` would silently land in zoxide's best database match (exit 0) +# instead of erroring, and every script `cd` would pollute the database. Aliases/abbrs +# leak into scripts the same way (`ls` → eza, `mkdir` → `mkdir -p`, fzf previews …). +if status is-interactive + # Cursor / greeting + set -g fish_greeting + set -g fish_cursor_insert line + set -g fish_cursor_default block + set -g fish_cursor_visual underscore + + # Misc + alias exti=exit + alias dmz="cat ~/.config/fish/dmz.txt" + alias nmatrix="neo-matrix -DS 3" + alias grep="grep --color=auto" + alias fzf="fzf --preview 'bat --color=always {}'" + alias fzff="fzf --multi --preview 'bat --style=numbers --color=always {}' | xargs -n 1 nvim" + abbr scrcpyz 'scrcpy -wSK -m 1920 --window-borderless --always-on-top --power-off-on-close --no-audio' + + # Git + alias gti="git" + alias gs="git status -s" + alias gp="git pull" + alias gca="git add -p . && git commit" + alias gd="git diff --word-diff" + alias gl="git log --graph --show-signature" + alias glog="git log --all --decorate --oneline --color --graph" + alias gla="git log --all --decorate --oneline" + alias gls="serie" + alias gm="git merge" + + # List directory + alias ls='eza --icons --group-directories-first' + alias l="ls -l" + alias la="ls -a" + alias lla="ls -la" + alias lt="ls --tree" + + # Dotfiles + notes + alias cdots="cd ~/.dots/" + alias cpnotes="cd ~/sync/PersonalNotes/" + alias cnotes="cd ~/sync/CojaDuska/Notes/" + abbr notes "cnotes && nvim" + abbr dots "cdots && nvim" + abbr dotsync "cdots && ./bin/dotsync" + abbr pnotes "cpnotes && nvim" + abbr todo "cpnotes && nvim ToDoNext.md" + abbr aliases "bat ~/.config/fish/config.fish" + + # Handy + abbr cat "bat -p" + abbr untar "tar -xf" + abbr unarchive "atool -x" + abbr copy wl-copy + abbr img "kitten icat" + abbr fm yazi + abbr lg lazygit + abbr gcommit "git diff HEAD | aichat -r commit" + abbr aichatdel "rm ~/.config/aichat/sessions/*.yaml" + abbr mkdir "mkdir -p" + abbr faillock "sudo faillock --reset" + abbr xremaps "sudo xremap ~/.config/xremap/config.yml" + abbr pacs "sudo pacman -Syu --noconfirm" + abbr yays "yay --noconfirm --sudoloop" + abbr nmaps "sudo nmap -sn 192.168.0.0/24" + abbr scrcpyc 'scrcpy -wSK -m 1920 --window-borderless --always-on-top --power-off-on-close' + abbr scrcpys 'scrcpy -wS --power-off-on-close' + abbr tts "tt -notheme -bold -showwpm -json" + abbr tuioss "tuios --show-clock --show-keys --show-cpu --show-ram --confirm-quit" + abbr keybinds "cd ~/.dots/ && nvim gui/.config/hypr/dots_binds.lua" + abbr vpnhome "sudo wg-quick up wg0" + abbr vpnkralizec "sudo wg-quick up kralizec-wg0" + abbr vpnsumadija "sudo wg-quick up sumadija-wg0" + abbr ipadd "sudo ip route add 192.168.0.234 dev wg0" + abbr aria2cs "aria2c -x 16 -k 1M" + + # Change-dir shortcuts + abbr .. "cd .." + abbr ... "cd ../.." + abbr .3 "cd ../../.." + abbr .4 "cd ../../../.." + abbr .5 "cd ../../../../.." + + # Tool init + zoxide init --cmd cd fish | source + + # thefuck, lazy-loaded on first use (its --alias eval costs ~170ms of shell startup) + function fuck + functions -e fuck + thefuck --alias | source + fuck $argv + end +end + +# Per-host extras +test -f ~/.config/fish/host.fish; and source ~/.config/fish/host.fish diff --git a/common/.config/fish/dmz.txt b/common/.config/fish/dmz.txt new file mode 100644 index 0000000..3f99663 --- /dev/null +++ b/common/.config/fish/dmz.txt @@ -0,0 +1,30 @@ +                          .dO00Od'                           +                         d00000000d.                         +                        d0000000000k                         +                        x0000000000O                         +                         k000000000                          +                           ;0000: Okc                        +                                    kkc                      +                                      kkc                    +                                        dkl                  +                                          okl                +                                            lOl              +                                              cOo.           + .lxkOOkxl.              .lxkOOkxl.             ;OoxkOOkxl.  +'O00000000O,            'O00000000O,            '000000000O, +O0000000000OddddddddddddO00000000000ddddddddddddO00000000000 +c0000000000c            :0000000000l            :0000000000l + .00000000.              .00000000'             '000000000'  +                             00               'd0.           +                             00             ,d0.             +                             00           ,x0                +                             00         :x0                  +                             00       cxO                    +                             00     ckO                      +                           .c00l' ckk                        +                         ck000000O0                          +                        c0000000000o                         +                        O00000000000                         +                        .0000000000.                         +                          ,000000:                           +                             :c                              diff --git a/common/.config/fish/fish_plugins b/common/.config/fish/fish_plugins new file mode 100644 index 0000000..fd5963b --- /dev/null +++ b/common/.config/fish/fish_plugins @@ -0,0 +1 @@ +danhper/fish-ssh-agent diff --git a/common/.config/fish/functions/__ssh_agent_is_started.fish b/common/.config/fish/functions/__ssh_agent_is_started.fish new file mode 100644 index 0000000..4318c25 --- /dev/null +++ b/common/.config/fish/functions/__ssh_agent_is_started.fish @@ -0,0 +1,25 @@ +function __ssh_agent_is_started -d "check if ssh agent is already started" + if test -n "$SSH_CONNECTION" + # This is an SSH session + ssh-add -l >/dev/null 2>&1 + if test $status -eq 0 -o $status -eq 1 + # An SSH agent was forwarded + return 0 + end + end + + if begin + test -f "$SSH_ENV"; and test -z "$SSH_AGENT_PID" + end + source $SSH_ENV >/dev/null + end + + if test -z "$SSH_AGENT_PID" + return 1 + end + + ssh-add -l >/dev/null 2>&1 + if test $status -eq 2 + return 1 + end +end diff --git a/common/.config/fish/functions/__ssh_agent_start.fish b/common/.config/fish/functions/__ssh_agent_start.fish new file mode 100644 index 0000000..c7ae4b3 --- /dev/null +++ b/common/.config/fish/functions/__ssh_agent_start.fish @@ -0,0 +1,5 @@ +function __ssh_agent_start -d "start a new ssh agent" + ssh-agent -c | sed 's/^echo/#echo/' >$SSH_ENV + chmod 600 $SSH_ENV + source $SSH_ENV >/dev/null +end diff --git a/common/.config/fish/functions/ask.fish b/common/.config/fish/functions/ask.fish new file mode 100644 index 0000000..6b9704b --- /dev/null +++ b/common/.config/fish/functions/ask.fish @@ -0,0 +1,3 @@ +function ask --description 'answer from cht.sh' + curl -s https://cht.sh/$(string join '+' $argv[1..]) +end diff --git a/common/.config/fish/functions/bashs.fish b/common/.config/fish/functions/bashs.fish new file mode 100644 index 0000000..2075b96 --- /dev/null +++ b/common/.config/fish/functions/bashs.fish @@ -0,0 +1,3 @@ +function bashs --description 'raw bash command' + bash -c "$argv" +end diff --git a/common/.config/fish/functions/bind_M_n_history.fish b/common/.config/fish/functions/bind_M_n_history.fish new file mode 100644 index 0000000..d8d85c9 --- /dev/null +++ b/common/.config/fish/functions/bind_M_n_history.fish @@ -0,0 +1,17 @@ +function bind_M_n_history + for i in (seq 9) + set -l command + if test (count $history) -ge $i + set command "commandline -r \$history[$i]" + else + set command "echo \"No history found for number $i\"" + end + + if contains fish_vi_key_bindings $fish_key_bindings + bind -M default \e$i "$command" + bind -M insert \e$i "$command" + else + bind \e$i "$command" + end + end +end diff --git a/common/.config/fish/functions/c2-worktree.fish b/common/.config/fish/functions/c2-worktree.fish new file mode 100644 index 0000000..ede91cb --- /dev/null +++ b/common/.config/fish/functions/c2-worktree.fish @@ -0,0 +1,30 @@ +function c2-worktree + if test (count $argv) -ne 1 + echo "Usage: c2-worktree " + echo "Example: c2-worktree package/package-update" + return 1 + end + + set branch $argv[1] + + set root (git rev-parse --show-toplevel) + or return 1 + set dir $root/.worktrees/(basename $branch) + + mkdir -p $root/.worktrees + or return 1 + + git checkout -b $branch + or return 1 + + git checkout master + or return 1 + + git worktree add $dir $branch + or return 1 + + cd $dir + or return 1 + + pnpm i +end diff --git a/common/.config/fish/functions/clis.fish b/common/.config/fish/functions/clis.fish new file mode 100644 index 0000000..d4a5f9f --- /dev/null +++ b/common/.config/fish/functions/clis.fish @@ -0,0 +1,7 @@ +function clis --description 'fzf select cli' + # one eval per selection — a single eval of the joined lines would run the + # first command with the other selections as its arguments + for cmd in (cat $HOME/.config/misc/clis.txt | command fzf --multi) + eval $cmd + end +end diff --git a/common/.config/fish/functions/copy-commandline.fish b/common/.config/fish/functions/copy-commandline.fish new file mode 100644 index 0000000..97fee35 --- /dev/null +++ b/common/.config/fish/functions/copy-commandline.fish @@ -0,0 +1,18 @@ +function copy-commandline + set -l cmd (commandline) + if test -n "$cmd" + if type -q pbcopy + echo -n "$cmd" | pbcopy + else if type -q xclip + echo -n "$cmd" | xclip -selection clipboard + else if type -q wl-copy + echo -n "$cmd" | wl-copy + end + + # Provide brief visual feedback in the prompt + set -l original_cmd (commandline) + commandline -r "Copied!" + sleep 0.4 + commandline -r "$original_cmd" + end +end diff --git a/common/.config/fish/functions/extract.fish b/common/.config/fish/functions/extract.fish new file mode 100644 index 0000000..aabb31d --- /dev/null +++ b/common/.config/fish/functions/extract.fish @@ -0,0 +1,23 @@ +function extract --description 'Extract any archive' + switch $argv[1] + case '*.tar' '*.tar.*' '*.tgz' '*.tbz2' '*.txz' # tar autodetects compression + tar xf $argv[1] + case '*.zip' + unzip $argv[1] + case '*.rar' + unrar x $argv[1] + case '*.7z' + 7z x $argv[1] + case '*.gz' + gunzip -k $argv[1] + case '*.xz' + unxz -k $argv[1] + case '*.zst' + unzstd $argv[1] + case '*.bz2' + bunzip2 -k $argv[1] + case '*' + echo "Unknown extension: $argv[1]" + return 1 + end +end diff --git a/common/.config/fish/functions/fish_greeting.fish b/common/.config/fish/functions/fish_greeting.fish new file mode 100644 index 0000000..20cab0e --- /dev/null +++ b/common/.config/fish/functions/fish_greeting.fish @@ -0,0 +1,5 @@ +function fish_greeting + #curl "wttr.in/Belgrade?format=%l:+%c+%t+|+%h+|+%w+|+(%%M+%m)\n" + test -r ~/.config/fish/greet.txt; and cat ~/.config/fish/greet.txt ## populated by cronjob + date +"📅 %d. %b 🕗 %H:%M - %A" +end diff --git a/common/.config/fish/functions/fish_prompt.fish b/common/.config/fish/functions/fish_prompt.fish new file mode 100644 index 0000000..152cce9 --- /dev/null +++ b/common/.config/fish/functions/fish_prompt.fish @@ -0,0 +1,14 @@ +function fish_prompt + if test -n "$SSH_TTY" + echo -n (set_color brred)"$USER"(set_color white)'@'(set_color yellow)(prompt_hostname)' ' + end + + echo -n (set_color blue)(prompt_pwd)' ' + + set_color -o + if fish_is_root_user + echo -n (set_color red)'# ' + end + echo -n (set_color red)'❯'(set_color yellow)'❯'(set_color green)'❯ ' + set_color normal +end diff --git a/common/.config/fish/functions/fish_right_prompt.fish b/common/.config/fish/functions/fish_right_prompt.fish new file mode 100644 index 0000000..38c5b37 --- /dev/null +++ b/common/.config/fish/functions/fish_right_prompt.fish @@ -0,0 +1,161 @@ +function fish_right_prompt + set -l cmd_status $status + if test $cmd_status -ne 0 + echo -n (set_color red)" $cmd_status" + end + + if not command -sq git + set_color normal + return + end + + # Get the git directory for later use. + # Return if not inside a Git repository work tree. + if not set -l git_dir (command git rev-parse --git-dir 2>/dev/null) + set_color normal + return + end + + # Get the current action ("merge", "rebase", etc.) + # and if there's one get the current commit hash too. + set -l commit '' + if set -l action (fish_print_git_action "$git_dir") + set commit (command git rev-parse HEAD 2> /dev/null | string sub -l 7) + end + + # Get either the branch name or a branch descriptor. + set -l branch_detached 0 + if not set -l branch (command git symbolic-ref --short HEAD 2>/dev/null) + set branch_detached 1 + set branch (command git describe --contains --all HEAD 2>/dev/null) + end + + # Get the commit difference counts between local and remote. + command git rev-list --count --left-right 'HEAD...@{upstream}' 2>/dev/null \ + | read -d \t -l status_ahead status_behind + if test $status -ne 0 + set status_ahead 0 + set status_behind 0 + end + + # Get the stash status. + # (git stash list) is very slow. => Avoid using it. + set -l status_stashed 0 + if test -f "$git_dir/refs/stash" + set status_stashed 1 + else if test -r "$git_dir/commondir" + read -l commondir <"$git_dir/commondir" + if test -f "$commondir/refs/stash" + set status_stashed 1 + end + end + + # git-status' porcelain v1 format starts with 2 letters on each line: + # The first letter (X) denotes the index state. + # The second letter (Y) denotes the working directory state. + # + # The following table presents the possible combinations: + # * The underscore character denotes whitespace. + # * The cell values stand for the following file states: + # a: added + # d: deleted + # m: modified + # r: renamed + # u: unmerged + # t: untracked + # * Cells with more than one letter signify that both states + # are simultaneously the case. This is possible since the git index + # and working directory operate independently of each other. + # * Cells which are empty are unhandled by this code. + # * T (= type change) is undocumented. + # See Git v1.7.8.2 release notes for more information. + # + # \ Y→ + # X \ + # ↓ | A | C | D | M | R | T | U | X | B | ? | _ + # ----+----+----+----+----+----+----+----+----+----+----+---- + # A | u | | ad | am | r | am | u | | | | a + # C | | | ad | am | r | am | u | | | | a + # D | | | u | am | r | am | u | | | | a + # M | | | ad | am | r | am | u | | | | a + # R | r | r | rd | rm | r | rm | ur | r | r | r | r + # T | | | ad | am | r | am | u | | | | a + # U | u | u | u | um | ur | um | u | u | u | u | u + # X | | | | m | r | m | u | | | | + # B | | | | m | r | m | u | | | | + # ? | | | | m | r | m | u | | | t | + # _ | | | d | m | r | m | u | | | | + set -l porcelain_status (command git status --porcelain 2>/dev/null | string sub -l2) + + set -l status_added 0 + if string match -qr '[ACDMT][ MT]|[ACMT]D' $porcelain_status + set status_added 1 + end + set -l status_deleted 0 + if string match -qr '[ ACMRT]D' $porcelain_status + set status_deleted 1 + end + set -l status_modified 0 + if string match -qr '[MT]$' $porcelain_status + set status_modified 1 + end + set -l status_renamed 0 + if string match -qe R $porcelain_status + set status_renamed 1 + end + set -l status_unmerged 0 + if string match -qr 'AA|DD|U' $porcelain_status + set status_unmerged 1 + end + set -l status_untracked 0 + if string match -qe '\?\?' $porcelain_status + set status_untracked 1 + end + + set_color -o + + if test -n "$branch" + if test $branch_detached -ne 0 + set_color brmagenta + else + set_color green + end + echo -n " $branch" + end + if test -n "$commit" + echo -n ' '(set_color yellow)"$commit" + end + if test -n "$action" + set_color normal + echo -n (set_color white)':'(set_color -o brred)"$action" + end + if test $status_ahead -ne 0 + echo -n ' '(set_color brmagenta)'' + end + if test $status_behind -ne 0 + echo -n ' '(set_color brmagenta)'' + end + if test $status_stashed -ne 0 + echo -n ' '(set_color cyan)'' + end + if test $status_added -ne 0 + echo -n ' '(set_color green)'' + end + if test $status_deleted -ne 0 + echo -n ' '(set_color red)'' + end + if test $status_modified -ne 0 + echo -n ' '(set_color blue)'' + end + if test $status_renamed -ne 0 + echo -n ' '(set_color magenta)'' + end + if test $status_unmerged -ne 0 + echo -n ' '(set_color yellow)'═' + end + if test $status_untracked -ne 0 + echo -n ' '(set_color white)'◼' + end + + set_color normal +end diff --git a/common/.config/fish/functions/fish_user_key_bindings.fish b/common/.config/fish/functions/fish_user_key_bindings.fish new file mode 100644 index 0000000..00e16d6 --- /dev/null +++ b/common/.config/fish/functions/fish_user_key_bindings.fish @@ -0,0 +1,15 @@ +function fish_user_key_bindings + # free Ctrl+S from terminal flow control (XOFF) so it can be bound below + stty -ixon + fish_default_key_bindings -M insert + fish_vi_key_bindings --no-erase insert + bind -M default ctrl-a beginning-of-line + bind -M default ctrl-e end-of-line + bind -M insert ctrl-space accept-autosuggestion + bind -M insert ctrl-g 'git diff' repaint + bind -M insert ctrl-o execute yazi + bind -M insert ctrl-l clear-screen ls repaint + bind -M default ctrl-s copy-commandline + bind -M insert ctrl-s copy-commandline + bind -M search ctrl-s copy-commandline +end diff --git a/common/.config/fish/functions/fzfh.fish b/common/.config/fish/functions/fzfh.fish new file mode 100644 index 0000000..24c8eee --- /dev/null +++ b/common/.config/fish/functions/fzfh.fish @@ -0,0 +1,7 @@ +function fzfh --description 'Search history with fzf' + history | fzf --query="$argv" --tac | read cmd + if test -n "$cmd" + echo $cmd + commandline -r $cmd + end +end diff --git a/common/.config/fish/functions/gcap.fish b/common/.config/fish/functions/gcap.fish new file mode 100644 index 0000000..85633ed --- /dev/null +++ b/common/.config/fish/functions/gcap.fish @@ -0,0 +1,5 @@ +function gcap --description 'Git add, commit with message, and push' + git add . + and git commit -m "$argv" + and git push +end diff --git a/common/.config/fish/functions/glow.fish b/common/.config/fish/functions/glow.fish new file mode 100644 index 0000000..64e174b --- /dev/null +++ b/common/.config/fish/functions/glow.fish @@ -0,0 +1,6 @@ +function glow --wraps glow --description 'glow wrapped at the current terminal width; an explicit -w still wins' + # glow never sizes itself to the terminal: glow.yml's width (or its built-in 80) applies, and + # `width: 0` in the config means 80 too. Wide tables get squeezed into that, one word per line. + # $COLUMNS tracks window resizes; a later -w/--width in $argv overrides this one. + command glow --width $COLUMNS $argv +end diff --git a/common/.config/fish/functions/h.fish b/common/.config/fish/functions/h.fish new file mode 100644 index 0000000..aa3e2c4 --- /dev/null +++ b/common/.config/fish/functions/h.fish @@ -0,0 +1,3 @@ +function h --description "Colorized --help via bat" + $argv --help 2>&1 | bat --plain --language=help +end diff --git a/common/.config/fish/functions/kp.fish b/common/.config/fish/functions/kp.fish new file mode 100644 index 0000000..d27aa96 --- /dev/null +++ b/common/.config/fish/functions/kp.fish @@ -0,0 +1,16 @@ +function kp + if not set -q KP_DB + echo "Error: KP_DB environment variable is not set. Check ~/.config/fish/conf.d/secrets.fish" + return 1 + end + + read -s -P "Enter db password: " pass + echo "" + + # -f flattens to full paths; without it nested entries are printed indented and + # without their group prefix, so `clip` can't find them. Group lines end in "/". + set -l entry (printf '%s\n' $pass | keepassxc-cli ls -q -R -f $KP_DB | string match -v '*/' | fzf | string trim) + if test -n "$entry" + printf '%s\n' $pass | keepassxc-cli clip -q $KP_DB $entry 0 + end +end diff --git a/common/.config/fish/functions/lk.fish b/common/.config/fish/functions/lk.fish new file mode 100644 index 0000000..94a5e2e --- /dev/null +++ b/common/.config/fish/functions/lk.fish @@ -0,0 +1,18 @@ +function lk --description 'linux knowledge' + set -l DB "$HOME/projects/dmz/soft/lk/db.rec" + set -l passes 0 + set -l count 0 + set -l query "" + + while test $passes -lt 2; and test $count -eq 0 + set query (recsel "$DB" -p aim,tag | recsel -iq "$query" -CP aim,tag | sort -u | fzf --preview="recsel \"$DB\" -e \"aim~{}\" | bat") + if test -n "$query" + set count (recsel "$DB" -q "$query" -c) + end + set passes (math $passes + 1) + end + + if test $count -eq 1 + recsel "$DB" -q "$query" | recfmt -f "$HOME/projects/dmz/soft/lk/lists.fmt" | less + end +end diff --git a/common/.config/fish/functions/md2pdf.fish b/common/.config/fish/functions/md2pdf.fish new file mode 100644 index 0000000..7639c3d --- /dev/null +++ b/common/.config/fish/functions/md2pdf.fish @@ -0,0 +1,11 @@ +function md2pdf --description 'Markdown to PDF next to the source: cmark-gfm renders it, headless chromium prints it' + # Relative image paths don't resolve (the HTML is rendered from /tmp), and chromium + # leaves out backgrounds when printing, so code blocks lose their grey box. + set -l html (mktemp --suffix=.html) + begin + echo '' + cmark-gfm -e table -e strikethrough -e autolink -e tasklist $argv[1] + end >$html + chromium --headless --no-pdf-header-footer --print-to-pdf=(path change-extension pdf $argv[1]) $html 2>/dev/null + rm $html +end diff --git a/common/.config/fish/functions/opencodes.fish b/common/.config/fish/functions/opencodes.fish new file mode 100644 index 0000000..c37a3f9 --- /dev/null +++ b/common/.config/fish/functions/opencodes.fish @@ -0,0 +1,45 @@ +function opencodes --description 'contained opencode (bwrap); extra args are passed to opencode' + set -l cfg ~/.config/opencode + # ~/.config/opencode is stowed as per-file symlinks into ~/.dots. Bind each link's real parent + # dir read-only too, or the sandbox sees dangling links and opencode starts with NO config. + set -l dirs + for f in $cfg/* $cfg/*/* + test -L $f; or continue + set -l d (path resolve $f | path dirname) + string match -q "$cfg*" $d; and continue + contains -- $d $dirs; or set -a dirs $d + end + set -l binds + for d in $dirs + set -a binds --ro-bind $d $d + end + # --clearenv drops everything; pass through only what the TUI and its tools need. + set -l env --setenv PATH /usr/local/bin:/usr/bin:/bin + for v in HOME TERM COLORTERM LANG LC_ALL EDITOR OPENCODE_CONFIG DUSKADIY_API_KEY + set -l val $$v + test -n "$val"; and set -a env --setenv $v $val + end + mkdir -p ~/.cache/opencode ~/.local/state/opencode ~/.local/share/opencode + bwrap \ + --unshare-all \ + --new-session \ + --clearenv \ + --die-with-parent \ + --share-net \ + --dev /dev \ + --proc /proc \ + --ro-bind /usr /usr \ + --ro-bind /lib /lib \ + --ro-bind /lib64 /lib64 \ + --ro-bind /bin /bin \ + --ro-bind /etc /etc \ + --ro-bind $cfg $cfg \ + $binds \ + --tmpfs /tmp \ + --bind ~/.cache/opencode ~/.cache/opencode \ + --bind ~/.local/state/opencode ~/.local/state/opencode \ + --bind ~/.local/share/opencode ~/.local/share/opencode \ + --bind $PWD $PWD \ + $env \ + opencode $argv +end diff --git a/common/.config/fish/functions/ssh.fish b/common/.config/fish/functions/ssh.fish new file mode 100644 index 0000000..9977f95 --- /dev/null +++ b/common/.config/fish/functions/ssh.fish @@ -0,0 +1,7 @@ +function ssh + if type -q kitten + kitten ssh $argv + else + command ssh $argv + end +end diff --git a/common/.config/fish/functions/sshf.fish b/common/.config/fish/functions/sshf.fish new file mode 100644 index 0000000..2325d6a --- /dev/null +++ b/common/.config/fish/functions/sshf.fish @@ -0,0 +1,6 @@ +function sshf --description 'fzf-pick an ssh host from ~/.ssh/config' + # command fzf: bypass the fzf alias (its bat preview makes no sense for host names); + # skip `Host *` wildcard blocks and take every alias on multi-name Host lines + set -l host (awk '/^Host /{for (i = 2; i <= NF; i++) if ($i != "*") print $i}' ~/.ssh/config | command fzf) + test -n "$host"; and ssh $host +end diff --git a/common/.config/fish/functions/tuis.fish b/common/.config/fish/functions/tuis.fish new file mode 100644 index 0000000..a21df31 --- /dev/null +++ b/common/.config/fish/functions/tuis.fish @@ -0,0 +1,7 @@ +function tuis --description 'fzf select tui' + # one eval per selection — a single eval of the joined lines would run the + # first command with the other selections as its arguments + for cmd in (cat $HOME/.config/misc/tuis.txt | command fzf --multi) + eval $cmd + end +end diff --git a/common/.config/git/claude-commit-msg b/common/.config/git/claude-commit-msg new file mode 100755 index 0000000..a31ad02 --- /dev/null +++ b/common/.config/git/claude-commit-msg @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +"""claude-commit-msg -- hand suggested commit messages from Claude sessions to `git commit`. + +Several Claude sessions work on one checkout at once, each staging its own round. The old +handoff was ONE file (`/CLAUDE_COMMIT_MSG`) that the prepare-commit-msg hook pasted +into the editor: the second session silently overwrote the first, and the hook could not +know which message described which files. Now every handoff is its own file under +`/CLAUDE_COMMIT_MSG.d/`, tagged with the paths it describes, and the hook prefills +only the message(s) whose paths are part of the commit being made: + + .msg the raw message + .paths one repo-relative path per line (the staged set at save time) + used/ consumed messages, kept for recovery + + save [--paths P ...] [--slug S] read the message on stdin; paths default to the index + list pending messages and how they match the current index + show ID | rm ID + prefill MSGFILE [SOURCE] hook entry point (prepare-commit-msg) + +Matching in `prefill`: a message whose paths are all in the commit is a FULL match (prefilled, +then consumed); overlapping only partly = PARTIAL (prefilled, kept -- the rest may come in a +later commit); no paths recorded = WILDCARD (prefilled, consumed), which is also how a legacy +single CLAUDE_COMMIT_MSG file is treated. Several matches are all prefilled, separated by a +comment line git strips, so you pick in the editor. Nothing matching = editor untouched. +Everything lives inside the git dir, so it never shows in `git status`; `--git-path` keeps it +per-worktree. Always exits 0 from `prefill`: a hook failure must never abort a commit. +""" +import os +import re +import shutil +import subprocess +import sys +import time + + +def git(*args, check=True): + r = subprocess.run(["git", *args], capture_output=True, text=True) + if check and r.returncode != 0: + sys.exit(f"claude-commit-msg: git {' '.join(args)} failed: {r.stderr.strip()}") + return r.stdout + + +def store(): + d = git("rev-parse", "--git-path", "CLAUDE_COMMIT_MSG.d").strip() + d = os.path.abspath(d) + os.makedirs(os.path.join(d, "used"), exist_ok=True) + return d + + +def staged_paths(): + out = git("diff", "--cached", "--name-only", "-z", check=False) + return [p for p in out.split("\0") if p] + + +def comment_char(): + c = git("config", "--get", "core.commentchar", check=False).strip() + return "#" if not c or c == "auto" else c[0] + + +def pending(d): + """[(id, message, paths|None)] oldest first. paths None = wildcard.""" + out = [] + for name in sorted(os.listdir(d)): + if not name.endswith(".msg"): + continue + mid = name[:-4] + try: + with open(os.path.join(d, name)) as fh: + msg = fh.read() + except OSError: + continue + paths = None + pf = os.path.join(d, mid + ".paths") + if os.path.exists(pf): + with open(pf) as fh: + paths = [ln.rstrip("\n") for ln in fh if ln.strip()] + out.append((mid, msg, paths)) + return out + + +def slugify(text): + m = re.match(r"\s*\[([^\]]+)\]", text) # this repo's `[Scope] summary` convention + base = m.group(1) if m else " ".join(text.split()[:3]) + s = re.sub(r"[^a-z0-9]+", "-", base.lower()).strip("-") + return s[:32] or "msg" + + +def cmd_save(argv): + paths, slug = None, None + i = 0 + while i < len(argv): + if argv[i] == "--paths": + paths = [] + i += 1 + while i < len(argv) and not argv[i].startswith("--"): + paths.append(argv[i]) + i += 1 + continue + if argv[i] == "--slug" and i + 1 < len(argv): + slug = argv[i + 1] + i += 2 + continue + sys.exit(f"claude-commit-msg save: unknown argument {argv[i]!r}") + msg = sys.stdin.read().rstrip() + "\n" + if not msg.strip(): + sys.exit("claude-commit-msg save: empty message on stdin") + if paths is None: + paths = staged_paths() + d = store() + mid = time.strftime("%Y%m%d-%H%M%S") + "-" + (slug or slugify(msg)) + n = 1 + while os.path.exists(os.path.join(d, f"{mid}.msg")): + n += 1 + mid = f"{mid}-{n}" + with open(os.path.join(d, mid + ".msg"), "w") as fh: + fh.write(msg) + with open(os.path.join(d, mid + ".paths"), "w") as fh: + fh.write("".join(p + "\n" for p in paths)) + print(f"saved {mid} ({len(paths)} path{'s' if len(paths) != 1 else ''}) -> {os.path.join(d, mid + '.msg')}") + if not paths: + print("warning: no paths recorded (nothing staged?) -- it will prefill on ANY commit", file=sys.stderr) + warn_if_hook_is_old() + + +def warn_if_hook_is_old(): + """A clone still running the legacy hook (or none) reads only the single file this tool + never writes -- the editor would come up empty with no error. Say so at save time.""" + hook = git("rev-parse", "--git-path", "hooks/prepare-commit-msg", check=False).strip() + try: + with open(hook, errors="ignore") as fh: + ok = "claude-commit-msg" in fh.read() + except OSError: + ok = False + if not ok: + print( + "warning: this repo's prepare-commit-msg hook is missing or predates claude-commit-msg, so this\n" + " message will NOT be prefilled here. Install the tracked hook once per repo:\n" + " ln -sf ~/.config/git/hooks/prepare-commit-msg (git rev-parse --git-path hooks)/prepare-commit-msg", + file=sys.stderr, + ) + + +def classify(paths, staged): + if paths is None or not paths: + return "wildcard" + ps = set(paths) + if ps <= staged: + return "full" + if ps & staged: + return "partial" + return "none" + + +def cmd_list(_argv): + d = store() + staged = set(staged_paths()) + items = pending(d) + legacy = git("rev-parse", "--git-path", "CLAUDE_COMMIT_MSG").strip() + if not items and not os.path.exists(legacy): + print("no pending messages") + return + for mid, msg, paths in items: + n = len(paths) if paths else 0 + print(f"{mid} [{classify(paths, staged):8}] {n} path{'s' if n != 1 else ''} {msg.splitlines()[0][:70]}") + if os.path.exists(legacy) and os.path.getsize(legacy) > 0: + with open(legacy) as fh: + first = fh.readline().rstrip() + print(f"(legacy CLAUDE_COMMIT_MSG) [wildcard] {first[:70]}") + + +def cmd_show(argv): + d = store() + for mid in argv: + with open(os.path.join(d, mid + ".msg")) as fh: + sys.stdout.write(fh.read()) + + +def cmd_rm(argv): + d = store() + for mid in argv: + hit = False + for ext in (".msg", ".paths"): + p = os.path.join(d, mid + ext) + if os.path.exists(p): + os.remove(p) + hit = True + if hit: + print(f"removed {mid}") + elif os.path.exists(os.path.join(d, "used", mid + ".msg")): + print(f"{mid} was already consumed by a commit (see used/)") + else: + print(f"{mid}: no such pending message") + + +def consume(d, mid): + for ext in (".msg", ".paths"): + p = os.path.join(d, mid + ext) + if os.path.exists(p): + shutil.move(p, os.path.join(d, "used", mid + ext)) + + +def cmd_prefill(argv): + if not argv: + return + msg_file = argv[0] + source = argv[1] if len(argv) > 1 else "" + if source not in ("", "template"): # -m/-F, merge, squash, amend: leave alone + return + d = store() + staged = set(staged_paths()) + order = {"full": 0, "partial": 1, "wildcard": 2} + picked = [] + for mid, msg, paths in pending(d): + kind = classify(paths, staged) + if kind != "none": + picked.append((order[kind], mid, msg, kind)) + legacy = git("rev-parse", "--git-path", "CLAUDE_COMMIT_MSG").strip() + legacy_msg = None + if os.path.isfile(legacy) and os.path.getsize(legacy) > 0: + with open(legacy) as fh: + legacy_msg = fh.read() + picked.append((3, "legacy", legacy_msg, "wildcard")) + if not picked: + return + picked.sort(key=lambda t: (t[0], t[1])) + cc = comment_char() + sep = f"\n{cc} ---- another pending Claude message matched this commit; keep the right one ----\n\n" + body = sep.join(m.rstrip("\n") + "\n" for _, _, m, _ in picked) + with open(msg_file) as fh: + existing = fh.read() + tmp = msg_file + ".claude-tmp" + with open(tmp, "w") as fh: + fh.write(body + "\n" + existing) + os.replace(tmp, msg_file) + for _, mid, _, kind in picked: + if mid == "legacy": + os.replace(legacy, legacy + ".last") + elif kind in ("full", "wildcard"): + consume(d, mid) + + +def main(): + cmds = {"save": cmd_save, "list": cmd_list, "show": cmd_show, "rm": cmd_rm, "prefill": cmd_prefill} + if len(sys.argv) < 2 or sys.argv[1] not in cmds: + sys.exit("usage: claude-commit-msg save [--paths P ...] [--slug S] < message | list | show ID | rm ID | prefill MSGFILE [SOURCE]") + if sys.argv[1] == "prefill": + try: + cmd_prefill(sys.argv[2:]) + except Exception as e: # never abort a commit because of the helper + print(f"claude-commit-msg prefill: {e}", file=sys.stderr) + return + cmds[sys.argv[1]](sys.argv[2:]) + + +if __name__ == "__main__": + main() diff --git a/common/.config/git/hooks/prepare-commit-msg b/common/.config/git/hooks/prepare-commit-msg new file mode 100755 index 0000000..5805450 --- /dev/null +++ b/common/.config/git/hooks/prepare-commit-msg @@ -0,0 +1,36 @@ +#!/bin/sh +# Prefill the commit editor from pending Claude commit messages (one-shot). +# +# Claude sessions save suggestions with `~/.config/git/claude-commit-msg save` -- one file per +# message under $(git rev-parse --git-path CLAUDE_COMMIT_MSG.d)/, tagged with the paths it +# describes. On the next `git commit` / lazygit `C` this pastes the message(s) whose paths are +# part of the commit above git's comment block, then consumes them (moved to used/). Several +# sessions can hand off in parallel without overwriting each other. +# +# Falls back to the legacy single file $(git rev-parse --git-path CLAUDE_COMMIT_MSG) when the +# CLI is not deployed on this host (not re-stowed yet). Never exits non-zero: a helper problem +# must not abort a commit. +msg_file=$1 +source=$2 + +# Only prefill a fresh editor session -- skip -m/-F (message), merge, squash, amend (commit). +case "$source" in + ""|template) ;; + *) exit 0 ;; +esac + +cli="$HOME/.config/git/claude-commit-msg" +if [ -f "$cli" ] && command -v python3 >/dev/null 2>&1; then + python3 "$cli" prefill "$msg_file" "$source" + exit 0 +fi + +# --- legacy fallback: the single one-shot file --- +suggestion=$(git rev-parse --git-path CLAUDE_COMMIT_MSG) +[ -s "$suggestion" ] || exit 0 + +tmp=$(mktemp) || exit 0 +{ cat "$suggestion"; printf '\n'; cat "$msg_file"; } > "$tmp" && + mv "$tmp" "$msg_file" && + mv "$suggestion" "$suggestion.last" +exit 0 diff --git a/common/.config/lazygit/config.yml b/common/.config/lazygit/config.yml new file mode 100644 index 0000000..67ce84c --- /dev/null +++ b/common/.config/lazygit/config.yml @@ -0,0 +1,483 @@ +# Config relating to the Lazygit UI +gui: + # The number of lines you scroll by when scrolling the main window + scrollHeight: 2 + # If true, allow scrolling past the bottom of the content in the main window + scrollPastBottom: true + # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#scroll-off-margin + scrollOffMargin: 2 + # One of: 'margin' (default) | 'jump' + scrollOffBehavior: margin + # If true, capture mouse events. + # When mouse events are captured, it's a little harder to select text: e.g. requiring you to hold the option key when on macOS. + mouseEvents: true + # If true, do not show a warning when discarding changes in the staging view. + skipDiscardChangeWarning: false + # If true, do not show warning when applying/popping the stash + skipStashWarning: false + # If true, do not show a warning when attempting to commit without any staged files; instead stage all unstaged files. + skipNoStagedFilesWarning: false + # If true, do not show a warning when rewording a commit via an external editor + skipRewordInEditorWarning: false + # Fraction of the total screen width to use for the left side section. You may want to pick a small number (e.g. 0.2) if you're using a narrow screen, so that you can see more of the main section. + # Number from 0 to 1.0. + sidePanelWidth: 0.3333 + # If true, increase the height of the focused side window; creating an accordion effect. + expandFocusedSidePanel: true + # The weight of the expanded side panel, relative to the other panels. 2 means + # twice as tall as the other panels. Only relevant if `expandFocusedSidePanel` is true. + expandedSidePanelWeight: 3 + # Sometimes the main window is split in two (e.g. when the selected file has both staged and unstaged changes). This setting controls how the two sections are split. + # Options are: + # - 'horizontal': split the window horizontally + # - 'vertical': split the window vertically + # - 'flexible': (default) split the window horizontally if the window is wide enough, otherwise split vertically + mainPanelSplitMode: flexible + # How the window is split when in half screen mode (i.e. after hitting '+' once). + # Possible values: + # - 'left': split the window horizontally (side panel on the left, main view on the right) + # - 'top': split the window vertically (side panel on top, main view below) + enlargedSideViewLocation: left + # If true, wrap lines in the staging view to the width of the view. This + # makes it much easier to work with diffs that have long lines, e.g. + # paragraphs of markdown text. + wrapLinesInDiffView: true + # One of 'auto' (default) | 'en' | 'zh-CN' | 'zh-TW' | 'pl' | 'nl' | 'ja' | 'ko' | 'ru' + language: auto + # Format used when displaying time e.g. commit time. + # Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format + timeFormat: 02 Jan 06 + # Format used when displaying time if the time is less than 24 hours ago. + # Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format + shortTimeFormat: 3:04PM + # Config relating to colors and styles. + # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#color-attributes + theme: + # Border color of focused window + activeBorderColor: + - green + - bold + # Border color of non-focused windows + inactiveBorderColor: + - default + # Border color of focused window when searching in that window + searchingActiveBorderColor: + - cyan + - bold + # Color of keybindings help text in the bottom line + optionsTextColor: + - blue + # Background color of selected line. + # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#highlighting-the-selected-line + selectedRangeBgColor: + - "#444444" + selectedLineBgColor: + - "#444444" + # Background color of selected line when view doesn't have focus. + inactiveViewSelectedLineBgColor: + - bold + # Foreground color of copied commit + cherryPickedCommitFgColor: + - blue + # Background color of copied commit + cherryPickedCommitBgColor: + - cyan + # Foreground color of marked base commit (for rebase) + markedBaseCommitFgColor: + - blue + # Background color of marked base commit (for rebase) + markedBaseCommitBgColor: + - yellow + # Color for file with unstaged changes + unstagedChangesColor: + - red + # Default text color + defaultFgColor: + - default + # Config relating to the commit length indicator + commitLength: + # If true, show an indicator of commit message length + show: true + # If true, show the '5 of 20' footer at the bottom of list views + showListFooter: true + # If true, display the files in the file views as a tree. If false, display the files as a flat list. + # This can be toggled from within Lazygit with the '~' key, but that will not change the default. + showFileTree: true + # If true, show the number of lines changed per file in the Files view + showNumstatInFilesView: false + # If true, show a random tip in the command log when Lazygit starts + showRandomTip: true + # If true, show the command log + showCommandLog: true + # If true, show the bottom line that contains keybinding info and useful buttons. If false, this line will be hidden except to display a loader for an in-progress action. + showBottomLine: true + # If true, show jump-to-window keybindings in window titles. + showPanelJumps: true + # Deprecated: use nerdFontsVersion instead + showIcons: false + # Nerd fonts version to use. + # One of: '2' | '3' | empty string (default) + # If empty, do not show icons. + nerdFontsVersion: "" + # If true (default), file icons are shown in the file views. Only relevant if NerdFontsVersion is not empty. + showFileIcons: true + # Length of author name in (non-expanded) commits view. 2 means show initials only. + commitAuthorShortLength: 2 + # Length of author name in expanded commits view. 2 means show initials only. + commitAuthorLongLength: 17 + # Length of commit hash in commits view. 0 shows '*' if NF icons aren't on. + commitHashLength: 8 + # If true, show commit hashes alongside branch names in the branches view. + showBranchCommitHash: false + # Whether to show the divergence from the base branch in the branches view. + # One of: 'none' | 'onlyArrow' | 'arrowAndNumber' + showDivergenceFromBaseBranch: none + # Height of the command log view + commandLogSize: 8 + # Whether to split the main window when viewing file changes. + # One of: 'auto' | 'always' + # If 'auto', only split the main window when a file has both staged and unstaged changes + splitDiff: auto + # Default size for focused window. Window size can be changed from within Lazygit with '+' and '_' (but this won't change the default). + # One of: 'normal' (default) | 'half' | 'full' + screenMode: normal + # Window border style. + # One of 'rounded' (default) | 'single' | 'double' | 'hidden' + border: rounded + # If true, show a seriously epic explosion animation when nuking the working tree. + animateExplosion: true + # Whether to stack UI components on top of each other. + # One of 'auto' (default) | 'always' | 'never' + portraitMode: auto + # How things are filtered when typing '/'. + # One of 'substring' (default) | 'fuzzy' + filterMode: substring + # Config relating to the spinner. + spinner: + # The frames of the spinner animation. + frames: + - '|' + - / + - '-' + - \ + # The "speed" of the spinner in milliseconds. + rate: 50 + # Status panel view. + # One of 'dashboard' (default) | 'allBranchesLog' + statusPanelView: dashboard + # If true, jump to the Files panel after popping a stash + switchToFilesAfterStashPop: true + # If true, jump to the Files panel after applying a stash + switchToFilesAfterStashApply: true + # If true, when using the panel jump keys (default 1 through 5) and target panel is already active, go to next tab instead + switchTabsWithPanelJumpKeys: false +# Config relating to git +git: + # See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md + diffRenderers: + - # Value of the --color arg in the git diff command. Some pagers want this to be set to 'always' and some want it set to 'never' + colorArg: always + # If true, Lazygit will use whatever pager is specified in `$GIT_PAGER`, `$PAGER`, or your *git config*. If the pager ends with something like ` | less` we will strip that part out, because less doesn't play nice with our rendering approach. If the custom pager uses less under the hood, that will also break rendering (hence the `--paging=never` flag for the `delta` pager). + useConfig: false + type: rawGit + # Config relating to committing + commit: + # If true, pass '--signoff' flag when committing + signOff: false + # Automatic WYSIWYG wrapping of the commit message as you type + autoWrapCommitMessage: true + # If autoWrapCommitMessage is true, the width to wrap to + autoWrapWidth: 72 + # Config relating to merging + merging: + # If true, run merges in a subprocess so that if a commit message is required, Lazygit will not hang + # Only applicable to unix users. + manualCommit: false + # Extra args passed to `git merge`, e.g. --no-ff + args: "" + # The commit message to use for a squash merge commit. Can contain "{{selectedRef}}" and "{{currentBranch}}" placeholders. + squashMergeMessage: Squash merge {{selectedRef}} into {{currentBranch}} + # list of branches that are considered 'main' branches, used when displaying commits + mainBranches: + - master + - main + # Prefix to use when skipping hooks. E.g. if set to 'WIP', then pre-commit hooks will be skipped when the commit message starts with 'WIP' + skipHookPrefix: WIP + # If true, periodically fetch from remote + autoFetch: true + # If true, periodically refresh files and submodules + autoRefresh: true + # If true, pass the --all arg to git fetch + fetchAll: true + # If true, lazygit will automatically stage files that used to have merge + # conflicts but no longer do; and it will also ask you if you want to + # continue a merge or rebase if you've resolved all conflicts. If false, it + # won't do either of these things. + autoStageResolvedConflicts: true + # Command used when displaying the current branch git log in the main window + branchLogCmd: git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} -- + # If true, do not spawn a separate process when using GPG + overrideGpg: false + # If true, do not allow force pushes + disableForcePushing: false + # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-commit-message-prefix + commitPrefix: + - # pattern to match on. E.g. for 'feature/AB-123' to match on the AB-123 use "^\\w+\\/(\\w+-\\w+).*" + pattern: "" + # Replace directive. E.g. for 'feature/AB-123' to start the commit message with 'AB-123 ' use "[$1] " + replace: "" + # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-branch-name-prefix + branchPrefix: "" + # If true, parse emoji strings in commit messages e.g. render :rocket: as 🚀 + # (This should really be under 'gui', not 'git') + parseEmoji: false + # Config for showing the log in the commits view + log: + # One of: 'date-order' | 'author-date-order' | 'topo-order' | 'default' + # 'topo-order' makes it easier to read the git log graph, but commits may not + # appear chronologically. See https://git-scm.com/docs/ + # + # Deprecated: Configure this with `Log menu -> Commit sort order` ( in the commits window by default). + order: topo-order + # This determines whether the git graph is rendered in the commits panel + # One of 'always' | 'never' | 'when-maximised' + # + # Deprecated: Configure this with `Log menu -> Show git graph` ( in the commits window by default). + showGraph: always + # displays the whole git graph by default in the commits view (equivalent to passing the `--all` argument to `git log`) + showWholeGraph: false + # When copying commit hashes to the clipboard, truncate them to this + # length. Set to 40 to disable truncation. + truncateCopiedCommitHashesTo: 12 + allBranchesLogCmds: + - git log --graph --all --color=always --abbrev-commit --decorate --date=relative --pretty=medium +# Periodic update checks +update: + # One of: 'prompt' (default) | 'background' | 'never' + method: prompt + # Period in days between update checks + days: 14 +# Background refreshes +refresher: + # File/submodule refresh interval in seconds. + # Auto-refresh can be disabled via option 'git.autoRefresh'. + refreshInterval: 10 + # Re-fetch interval in seconds. + # Auto-fetch can be disabled via option 'git.autoFetch'. + fetchInterval: 60 +# If true, show a confirmation popup before quitting Lazygit +confirmOnQuit: false +# If true, exit Lazygit when the user presses escape in a context where there is nothing to cancel/close +quitOnTopLevelReturn: false +# Config relating to things outside of Lazygit like how files are opened, copying to clipboard, etc +os: + # Command for editing a file. Should contain "{{filename}}". + edit: "" + # Command for editing a file at a given line number. Should contain + # "{{filename}}", and may optionally contain "{{line}}". + editAtLine: "" + # Same as EditAtLine, except that the command needs to wait until the + # window is closed. + editAtLineAndWait: "" + # For opening a directory in an editor + openDirInEditor: "" + # A built-in preset that sets all of the above settings. Supported presets + # are defined in the getPreset function in editor_presets.go. + editPreset: "" + # Command for opening a file, as if the file is double-clicked. Should + # contain "{{filename}}", but doesn't support "{{line}}". + open: "" + # Command for opening a link. Should contain "{{link}}". + openLink: "" + # EditCommand is the command for editing a file. + # Deprecated: use Edit instead. Note that semantics are different: + # EditCommand is just the command itself, whereas Edit contains a + # "{{filename}}" variable. + editCommand: "" + # EditCommandTemplate is the command template for editing a file + # Deprecated: use EditAtLine instead. + editCommandTemplate: "" + # OpenCommand is the command for opening a file + # Deprecated: use Open instead. + openCommand: "" + # OpenLinkCommand is the command for opening a link + # Deprecated: use OpenLink instead. + openLinkCommand: "" + # CopyToClipboardCmd is the command for copying to clipboard. + # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-command-for-copying-to-and-pasting-from-clipboard + copyToClipboardCmd: "" + # ReadFromClipboardCmd is the command for reading the clipboard. + # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-command-for-copying-to-and-pasting-from-clipboard + readFromClipboardCmd: "" +# If true, don't display introductory popups upon opening Lazygit. +disableStartupPopups: false +# What to do when opening Lazygit outside of a git repo. +# - 'prompt': (default) ask whether to initialize a new repo or open in the most recent repo +# - 'create': initialize a new repo +# - 'skip': open most recent repo +# - 'quit': exit Lazygit +notARepository: prompt +# If true, display a confirmation when subprocess terminates. This allows you to view the output of the subprocess before returning to Lazygit. +promptToReturnFromSubprocess: true +# Keybindings +keybinding: + universal: + quit: q + quit-alt1: + return: + quitWithoutChangingDirectory: Q + togglePanel: + prevItem: + nextItem: + prevItem-alt: k + nextItem-alt: j + prevPage: ',' + nextPage: . + scrollLeft: H + scrollRight: L + gotoTop: < + gotoBottom: '>' + toggleRangeSelect: v + rangeSelectDown: + rangeSelectUp: + prevBlock: + nextBlock: + prevBlock-alt: h + nextBlock-alt: l + nextBlock-alt2: + prevBlock-alt2: + jumpToBlock: + - "1" + - "2" + - "3" + - "4" + - "5" + nextMatch: "n" + prevMatch: "N" + startSearch: / + optionMenu: '?' + optionMenu-alt1: + select: + goInto: + confirm: + confirmInEditor: + remove: d + new: "n" + edit: e + openFile: o + scrollUpMain: + scrollDownMain: + scrollUpMain-alt1: K + scrollDownMain-alt1: J + scrollUpMain-alt2: + scrollDownMain-alt2: + executeShellCommand: ':' + createRebaseOptionsMenu: m + # 'Files' appended for legacy reasons + pushFiles: P + # 'Files' appended for legacy reasons + pullFiles: p + refresh: R + createPatchOptionsMenu: + nextTab: ']' + prevTab: '[' + nextScreenMode: + + prevScreenMode: _ + undo: z + redo: + filteringMenu: + diffingMenu: W + diffingMenu-alt: + copyToClipboard: + openRecentRepos: + submitEditorText: + extrasMenu: '@' + toggleWhitespaceInDiffView: + increaseContextInDiffView: '}' + decreaseContextInDiffView: '{' + increaseRenameSimilarityThreshold: ) + decreaseRenameSimilarityThreshold: ( + openDiffTool: + newWorktree: w + status: + checkForUpdate: u + recentRepos: + allBranchesLogGraph: a + files: + commitChanges: c + commitChangesWithoutHook: w + amendLastCommit: A + commitChangesWithEditor: C + findBaseCommitForFixup: + confirmDiscard: x + ignoreFile: i + refreshFiles: r + stashAllChanges: s + viewStashOptions: S + toggleStagedAll: a + viewResetOptions: D + fetch: f + toggleTreeView: '`' + openMergeOptions: M + openStatusFilter: + copyFileInfoToClipboard: "y" + branches: + createPullRequest: o + viewPullRequestOptions: O + copyPullRequestURL: + checkoutBranchByName: c + forceCheckoutBranch: F + rebaseBranch: r + renameBranch: R + mergeIntoCurrentBranch: M + viewGitFlowOptions: i + fastForward: f + createTag: T + pushTag: P + setUpstream: u + fetchRemote: f + sortOrder: s + commits: + squashDown: s + renameCommit: r + renameCommitWithEditor: R + viewResetOptions: g + markCommitAsFixup: f + createFixupCommit: F + squashAboveCommits: S + moveDownCommit: + moveUpCommit: + amendToCommit: A + resetCommitAuthor: a + pickCommit: p + revertCommit: t + cherryPickCopy: C + pasteCommits: V + markCommitAsBaseForRebase: B + tagCommit: T + checkoutCommit: + # resetCherryPick: + copyCommitAttributeToClipboard: "y" + openLogMenu: + openInBrowser: o + viewBisectOptions: b + startInteractiveRebase: i + amendAttribute: + resetAuthor: a + setAuthor: A + addCoAuthor: c + stash: + popStash: g + renameStash: r + commitFiles: + checkoutCommitFile: c + main: + toggleSelectHunk: a + pickBothHunks: b + editSelectHunk: E + submodules: + init: i + update: u + bulkMenu: b + commitMessage: + commitMenu: diff --git a/common/.config/misc/appImages.txt b/common/.config/misc/appImages.txt new file mode 100644 index 0000000..961fcc2 --- /dev/null +++ b/common/.config/misc/appImages.txt @@ -0,0 +1,3 @@ +om +openWebUI +itTools diff --git a/common/.config/misc/clis.txt b/common/.config/misc/clis.txt new file mode 100644 index 0000000..86e82b8 --- /dev/null +++ b/common/.config/misc/clis.txt @@ -0,0 +1,38 @@ +jq +fq +rg +fd +fzf +lsd +bat +zoxide +resvg +mosh +tennis +dysk +dust +scrcpy +adb +gpg +fnm +recfmt +recsel +pass +xxd +voxcii +tldr +rsync +cowsay +fortune +lolcat +glow +pake +bwrap +dog +nmap +rustscan +traceroute +fuck +atool +aria2c +cmark-gfm diff --git a/common/.config/misc/tuis.txt b/common/.config/misc/tuis.txt new file mode 100644 index 0000000..3442dbe --- /dev/null +++ b/common/.config/misc/tuis.txt @@ -0,0 +1,77 @@ +browsh +wiki-tui +wikiman +yazi +tdf +dysk +dust +ncdu +duf +systemctl-tui +btop +bandwhich +mtr +gping +flow +bmon +profanity +nmtui +impala +bluetui +sshm +aichat +tt +gittype +toofan +pastel +hexyl +binsider +tmux +zellij +nvim +vim +tetrigo +pyradio +cliamp +px7-radio +kew +cmatrix +neo-matrix +cava +pipes-rs +asciiquarium +cbonsai +tclock +hunk +tuicr +gittop +lazygit +lazyjournal +lazydocker +lazyrsync +ctop +colima +dive +asciinema +posting +serie +clx +whosthere +voxcii +bookokrat +tennis +llmfit +termdraw +torlnk +riptide +quien +eilmeldung +calcure +weathr +hyprmon +hulak +netwatch +gpk +circumflex +darya +usbtree diff --git a/common/.config/nvim/.stylua.toml b/common/.config/nvim/.stylua.toml new file mode 100644 index 0000000..ecb6dca --- /dev/null +++ b/common/.config/nvim/.stylua.toml @@ -0,0 +1,6 @@ +column_width = 120 +line_endings = "Unix" +indent_type = "Spaces" +indent_width = 2 +quote_style = "AutoPreferDouble" +call_parentheses = "None" diff --git a/common/.config/nvim/README.md b/common/.config/nvim/README.md new file mode 100644 index 0000000..518a989 --- /dev/null +++ b/common/.config/nvim/README.md @@ -0,0 +1,98 @@ +# Neovim Configuration Setup + +This Neovim configuration is built on top of [NvChad](https://nvchad.com/), a popular Neovim framework designed for speed and aesthetics. It uses [lazy.nvim](https://github.com/folke/lazy.nvim) as the plugin manager. + +## Core Components + +- **Framework**: [NvChad](https://nvchad.com/) (v2.5) +- **Plugin Manager**: `lazy.nvim` +- **Theme Engine**: `base46` (integrated with NvChad) +- **Keybindings**: Custom mappings are defined in `lua/mappings.lua`. +- **Options**: Base options are inherited from NvChad, with customizations in `lua/options.lua`. + +## Installed Plugins & Features + +The configuration includes several key plugins and features: + +### Development Tools +- **LSP (Language Server Protocol)**: Configured via `nvim-lspconfig`. Note that you must install the actual language servers using [Mason.nvim](https://github.com/williamboman/mason.nvim). +- **Formatting**: Uses `conform.nvim` for code formatting (configured in `lua/configs/conform.lua`). +- **Treesitter**: Provides advanced syntax highlighting and code folding (configured in `lua/plugins/init.lua`). +- **Telescope**: Powerful fuzzy finder for files, text, and LSP symbols. + +### UI & Productivity +- **Snacks.nvim**: A collection of useful utilities including: + - `explorer`: File explorer. + - `indent`: Indent guides (replaces `indent-blankline.nvim` to avoid duplication). + - `picker`: Fast picker for various tasks. + - `notifier`: Improved notification system. + - `words`: Word count and related features. +- **Render Markdown**: Enhances the appearance of Markdown files in the buffer (`lua/configs/render-markdown.lua`). + +## Maintenance & Package Management + +### Managing Plugins (lazy.nvim) +To update your installed Neovim plugins: +1. Open Neovim. +2. Run `:Lazy` to open the plugin manager UI. +3. Press `U` to check for updates and `u` to update everything. + +### Managing LSPs & Tools (Mason.nvim) +While plugins are managed by `lazy.nvim`, the actual language servers, debuggers, and formatters are managed by **Mason**. +1. Open Neovim. +2. Run `:Mason` to open the Mason UI. +3. Use the UI to install or update your desired LSPs (e.g., `ts_ls`, `html`, `cssls`), linters, or formatters. + +### Managing Syntax Highlighting (Treesitter) +To ensure all language parsers are installed for proper syntax highlighting: +1. Open Neovim. +2. Run `:TSUpdate` (or `:TSInstall ` for a specific one). + +## Custom Keybindings + +Some notable custom mappings (defined in `lua/mappings.lua`): + +| Mapping | Action | Description | +|---------|--------|-------------| +| `gd` | `vim.lsp.buf.definition` | Go to definition | +| `gD` | `Telescope lsp_definitions` | Go to definitions (Telescope) | +| `grr` | `Telescope lsp_references` | Go to references (Telescope) | +| `da` | `vim.lsp.buf.code_action()` | Code actions | +| `dh` | `vim.diagnostic.open_float()` | Show diagnostics in float | +| `dj` | `vim.diagnostic.jump` | Go to next diagnostic | +| `dk` | `vim.diagnostic.jump` | Go to previous diagnostic | +| `fr` | `Telescope resume` | Resume last Telescope search | +| `fs` | `Telescope grep_string` | Find selected string | +| `fk` | `Telescope keymaps` | Find keymaps | +| `fd` | `Telescope diagnostics` | Search diagnostics | + +**Improved Deletion/Change:** +- `x` (in Normal/Visual mode): Deletes a character without yanking it to the register. +- `c` (in Normal/Visual mode): Changes text without yanking it to the register. + +## Directory Structure + +```text +. +├── init.lua # Entry point: bootstraps lazy.nvim and loads config +├── lazy-lock.json # Lockfile for lazy.nvim +└── lua/ + ├── chadrc.lua # NvChad configuration + ├── configs/ # Plugin-specific configurations + │ ├── conform.lua + │ ├── lazy.lua + │ ├── lspconfig.lua + │ └── render-markdown.lua + ├── mappings.lua # Custom keybindings + ├── options.lua # Custom Neovim options + └── plugins/ + └── init.lua # Plugin definitions and setup +``` + +## Installation + +1. Ensure you have [Neovim](https://neovim.io/) (latest stable or nightly) installed. +2. Clone this repository to your Neovim configuration directory (usually `~/.config/nvim`). +3. Open Neovim. `lazy.nvim` will automatically bootstrap and install all required plugins. +4. **Important**: After the initial plugin installation, run `:MasonInstall ` (or use the `:Mason` UI) to install the language servers required for your workflow. +5. Restart Neovim after the initial installation completes. diff --git a/common/.config/nvim/init.lua b/common/.config/nvim/init.lua new file mode 100644 index 0000000..af71982 --- /dev/null +++ b/common/.config/nvim/init.lua @@ -0,0 +1,38 @@ +vim.g.base46_cache = vim.fn.stdpath "data" .. "/base46/" +vim.g.mapleader = " " +vim.opt.relativenumber = true + +-- bootstrap lazy and all plugins +local lazypath = vim.fn.stdpath "data" .. "/lazy/lazy.nvim" + +if not vim.uv.fs_stat(lazypath) then + local repo = "https://github.com/folke/lazy.nvim.git" + vim.fn.system { "git", "clone", "--filter=blob:none", repo, "--branch=stable", lazypath } +end + +vim.opt.rtp:prepend(lazypath) + +local lazy_config = require "configs.lazy" + +-- load plugins +require("lazy").setup({ + { + "NvChad/NvChad", + lazy = false, + branch = "v2.5", + import = "nvchad.plugins", + }, + + { import = "plugins" }, +}, lazy_config) + +-- load theme +dofile(vim.g.base46_cache .. "defaults") +dofile(vim.g.base46_cache .. "statusline") + +require "options" +require "nvchad.autocmds" + +vim.schedule(function() + require "mappings" +end) diff --git a/common/.config/nvim/lazy-lock.json b/common/.config/nvim/lazy-lock.json new file mode 100644 index 0000000..531110c --- /dev/null +++ b/common/.config/nvim/lazy-lock.json @@ -0,0 +1,31 @@ +{ + "LuaSnip": { "branch": "master", "commit": "0abc8f390b278c3b4aabc4c004ac8a088b65cf24" }, + "NvChad": { "branch": "v2.5", "commit": "87d6a41ec07ab995de912a892749b6b4805ad2b3" }, + "base46": { "branch": "v3.0", "commit": "d870ec89a7b2f28c4accce515f97b7bcc5b9d200" }, + "cmp-async-path": { "branch": "main", "commit": "98185a91d49ff5dd249aebf2f7456e18063fa2a0" }, + "cmp-buffer": { "branch": "main", "commit": "b74fab3656eea9de20a9b8116afa3cfc4ec09657" }, + "cmp-nvim-lsp": { "branch": "main", "commit": "cbc7b02bb99fae35cb42f514762b89b5126651ef" }, + "cmp-nvim-lua": { "branch": "main", "commit": "e3a22cb071eb9d6508a156306b102c45cd2d573d" }, + "cmp_luasnip": { "branch": "master", "commit": "98d9cb5c2c38532bd9bdb481067b20fea8f32e90" }, + "conform.nvim": { "branch": "master", "commit": "016802de402556da54c36bd7359b441266b01cdd" }, + "friendly-snippets": { "branch": "main", "commit": "b2ea5c41a150ba72fb656eedb4ed0a86d138d945" }, + "gitsigns.nvim": { "branch": "main", "commit": "4bcd99167c265f135886b282baad77afe06206b2" }, + "indent-blankline.nvim": { "branch": "master", "commit": "d28a3f70721c79e3c5f6693057ae929f3d9c0a03" }, + "lazy.nvim": { "branch": "main", "commit": "306a05526ada86a7b30af95c5cc81ffba93fef97" }, + "mason.nvim": { "branch": "main", "commit": "2a6940af80375532e5e9e7c1f2fc6319a1b7a69d" }, + "menu": { "branch": "main", "commit": "7a0a4a2896b715c066cfbe320bdc048091874cc6" }, + "minty": { "branch": "main", "commit": "aafc9e8e0afe6bf57580858a2849578d8d8db9e0" }, + "nvim-autopairs": { "branch": "master", "commit": "3172f40c16563db871a58f20d205c710ad782311" }, + "nvim-cmp": { "branch": "main", "commit": "e04302f1fefcb5653848346eb3723b39b82c549b" }, + "nvim-lspconfig": { "branch": "master", "commit": "cc404d425c7752f56b8eaa269107be44d888ea51" }, + "nvim-tree.lua": { "branch": "master", "commit": "69eb0c34ed3d836d5a0d92d913b77dd73b054f2f" }, + "nvim-treesitter": { "branch": "main", "commit": "610734c5d3e59761d5f79318d120633374537fa5" }, + "nvim-web-devicons": { "branch": "master", "commit": "ec309a0eaff6ea967e58c275996155ab5c16938d" }, + "plenary.nvim": { "branch": "master", "commit": "74b06c6c75e4eeb3108ec01852001636d85a932b" }, + "render-markdown.nvim": { "branch": "main", "commit": "8e8795368391036643b622875a6da6a51bcd33f4" }, + "snacks.nvim": { "branch": "main", "commit": "882c996cf28183f4d63640de0b4c02ec886d01f2" }, + "telescope.nvim": { "branch": "master", "commit": "40aedd8a68c78a656a10a8d62d80c54af59420fb" }, + "ui": { "branch": "v3.0", "commit": "8cbf0dc1883b20a1df114149c187d250f0af0853" }, + "volt": { "branch": "main", "commit": "4351c5cd790a0d39491c4d5c75dd62d7db3d3414" }, + "which-key.nvim": { "branch": "main", "commit": "3aab2147e74890957785941f0c1ad87d0a44c15a" } +} diff --git a/common/.config/nvim/lua/chadrc.lua b/common/.config/nvim/lua/chadrc.lua new file mode 100644 index 0000000..dbf4537 --- /dev/null +++ b/common/.config/nvim/lua/chadrc.lua @@ -0,0 +1,57 @@ +-- This file needs to have same structure as nvconfig.lua +-- https://github.com/NvChad/ui/blob/v3.0/lua/nvconfig.lua +-- Please read that file to know all available options :( + +---@type ChadrcConfig + +local M = { + lsp = { signature = true }, + + base46 = { + theme = "onedark", + transparency = true, + hl_override = { + NvimTreeGitDirty = { + fg = "#DBA55D", + }, + }, + -- Comment = { italic = true }, + -- ["@comment"] = { italic = true }, + }, + + nvdash = { + load_on_startup = true, + -- buttons = { + -- { txt = " Find File", keys = "Spc f f", cmd = "Telescope find_files custom" }, + -- { txt = " Recent Files", keys = "Spc f o", cmd = "Telescope oldfiles" }, + -- -- more... check nvconfig.lua file for full list of buttons + -- }, + }, + + ui = { + -- lazyload it when there are 1+ buffers + tabufline = { + enabled = true, + lazyload = true, + order = { "treeOffset", "buffers", "tabs", "btns" }, + modules = nil, + bufwidth = 21, + }, + }, + + term = { + base46_colors = true, + winopts = { number = false }, + sizes = { sp = 0.5, vsp = 0.2, ["bo sp"] = 0.3, ["bo vsp"] = 0.2 }, + float = { + relative = "editor", + row = 0.05, + col = 0.05, + width = 0.9, + height = 0.8, + border = "single", + }, + }, +} + +return M diff --git a/common/.config/nvim/lua/configs/conform.lua b/common/.config/nvim/lua/configs/conform.lua new file mode 100644 index 0000000..c4834be --- /dev/null +++ b/common/.config/nvim/lua/configs/conform.lua @@ -0,0 +1,17 @@ +local options = { + formatters_by_ft = { + lua = { "stylua" }, + css = { "prettier" }, + html = { "prettier" }, + typescript = { "prettier" }, + javascript = { "prettier" }, + }, + + format_on_save = { + -- These options will be passed to conform.format() + timeout_ms = 500, + lsp_format = "fallback", + }, +} + +return options diff --git a/common/.config/nvim/lua/configs/lazy.lua b/common/.config/nvim/lua/configs/lazy.lua new file mode 100644 index 0000000..cd170bd --- /dev/null +++ b/common/.config/nvim/lua/configs/lazy.lua @@ -0,0 +1,47 @@ +return { + defaults = { lazy = true }, + install = { colorscheme = { "nvchad" } }, + + ui = { + icons = { + ft = "", + lazy = "󰂠 ", + loaded = "", + not_loaded = "", + }, + }, + + performance = { + rtp = { + disabled_plugins = { + "2html_plugin", + "tohtml", + "getscript", + "getscriptPlugin", + "gzip", + "logipat", + "netrw", + "netrwPlugin", + "netrwSettings", + "netrwFileHandlers", + "matchit", + "tar", + "tarPlugin", + "rrhelper", + "spellfile_plugin", + "vimball", + "vimballPlugin", + "zip", + "zipPlugin", + "tutor", + "rplugin", + "syntax", + "synmenu", + "optwin", + "compiler", + "bugreport", + "ftplugin", + }, + }, + }, +} diff --git a/common/.config/nvim/lua/configs/lspconfig.lua b/common/.config/nvim/lua/configs/lspconfig.lua new file mode 100644 index 0000000..078b3e8 --- /dev/null +++ b/common/.config/nvim/lua/configs/lspconfig.lua @@ -0,0 +1,47 @@ +require("nvchad.configs.lspconfig").defaults() + +local servers = { "html", "cssls", "ts_ls", "eslint" } +vim.lsp.enable(servers) + +-- Waybar/GTK stylesheets are GTK CSS, a different dialect: `@name` references +-- @define-color colors (waybar's theme.css) and functions like alpha() are +-- valid there but not in web CSS, so cssls floods "property value expected" / +-- "{ expected" false errors. No LSP speaks the GTK dialect, so keep cssls +-- attached (standard-property completion still useful) and mute diagnostics +-- on those buffers only. +vim.api.nvim_create_autocmd("LspAttach", { + callback = function(args) + local client = vim.lsp.get_client_by_id(args.data.client_id) + if not client or client.name ~= "cssls" then + return + end + local path = vim.api.nvim_buf_get_name(args.buf) + if path:match "/waybar/" or path:match "/gtk%-%d" then + vim.diagnostic.enable(false, { bufnr = args.buf }) + end + end, +}) + +-- local lspconfig = require "lspconfig" +-- local nvlsp = require "nvchad.configs.lspconfig" +-- +-- -- lsps with default config +-- for _, lsp in ipairs(servers) do +-- lspconfig[lsp].setup { +-- on_attach = nvlsp.on_attach, +-- on_init = nvlsp.on_init, +-- capabilities = nvlsp.capabilities, +-- } +-- end +-- +-- -- configuring single server, example: typescript +-- lspconfig.ts_ls.setup { +-- filetypes = { 'typescript', 'javascript', 'javascriptreact', 'typescriptreact', 'vue', 'markdown' }, +-- } +-- +-- -- configuring single server, example: typescript +-- -- lspconfig.ts_ls.setup { +-- -- on_attach = nvlsp.on_attach, +-- -- on_init = nvlsp.on_init, +-- -- capabilities = nvlsp.capabilities, +-- -- } diff --git a/common/.config/nvim/lua/configs/render-markdown.lua b/common/.config/nvim/lua/configs/render-markdown.lua new file mode 100644 index 0000000..9e24d04 --- /dev/null +++ b/common/.config/nvim/lua/configs/render-markdown.lua @@ -0,0 +1,851 @@ +return { + -- Whether markdown should be rendered by default. + enabled = true, + -- Vim modes that will show a rendered view of the markdown file, :h mode(), for all enabled + -- components. Individual components can be enabled for other modes. Remaining modes will be + -- unaffected by this plugin. + render_modes = { "i", "n", "c", "t" }, + -- Maximum file size (in MB) that this plugin will attempt to render. + -- Any file larger than this will effectively be ignored. + max_file_size = 10.0, + -- Milliseconds that must pass before updating marks, updates occur. + -- within the context of the visible window, not the entire buffer. + debounce = 100, + -- Pre configured settings that will attempt to mimic various target user experiences. + -- Any user provided settings will take precedence. + -- | obsidian | mimic Obsidian UI | + -- | lazy | will attempt to stay up to date with LazyVim configuration | + -- | none | does nothing | + preset = "none", + -- The level of logs to write to file: vim.fn.stdpath('state') .. '/render-markdown.log'. + -- Only intended to be used for plugin development / debugging. + log_level = "error", + -- Print runtime of main update method. + -- Only intended to be used for plugin development / debugging. + log_runtime = false, + -- Filetypes this plugin will run on. + file_types = { "markdown", "gitcommit" }, + -- Takes buffer as input, if it returns true this plugin will not attach to the buffer + ignore = function() + return false + end, + -- Additional events that will trigger this plugin's render loop. + change_events = {}, + injections = { + -- Out of the box language injections for known filetypes that allow markdown to be interpreted + -- in specified locations, see :h treesitter-language-injections. + -- Set enabled to false in order to disable. + + gitcommit = { + enabled = true, + query = [[ + ((message) @injection.content + (#set! injection.combined) + (#set! injection.include-children) + (#set! injection.language "markdown")) + ]], + }, + }, + patterns = { + -- Highlight patterns to disable for filetypes, i.e. lines concealed around code blocks + + markdown = { + disable = true, + directives = { + { id = 17, name = "conceal_lines" }, + { id = 18, name = "conceal_lines" }, + }, + }, + }, + anti_conceal = { + -- This enables hiding any added text on the line the cursor is on. + enabled = true, + -- Modes to disable anti conceal feature. + disabled_modes = false, + -- Number of lines above cursor to show. + above = 0, + -- Number of lines below cursor to show. + below = 0, + -- Which elements to always show, ignoring anti conceal behavior. Values can either be + -- booleans to fix the behavior or string lists representing modes where anti conceal + -- behavior will be ignored. Valid values are: + -- bullet + -- callout + -- check_icon, check_scope + -- code_background, code_border, code_language + -- dash + -- head_background, head_border, head_icon + -- indent + -- link + -- quote + -- sign + -- table_border + -- virtual_lines + ignore = { + code_background = true, + indent = true, + sign = true, + virtual_lines = true, + }, + }, + padding = { + -- Highlight to use when adding whitespace, should match background. + highlight = "Normal", + }, + latex = { + -- Turn on / off latex rendering. + enabled = true, + -- Additional modes to render latex. + render_modes = false, + -- Executable used to convert latex formula to rendered unicode. + converter = "latex2text", + -- Highlight for latex blocks. + highlight = "RenderMarkdownMath", + -- Determines where latex formula is rendered relative to block. + -- | above | above latex block | + -- | below | below latex block | + position = "above", + -- Number of empty lines above latex blocks. + top_pad = 0, + -- Number of empty lines below latex blocks. + bottom_pad = 0, + }, + on = { + -- Called when plugin initially attaches to a buffer. + attach = function() end, + -- Called before adding marks to the buffer for the first time. + initial = function() end, + -- Called after plugin renders a buffer. + render = function() end, + -- Called after plugin clears a buffer. + clear = function() end, + }, + completions = { + -- Settings for blink.cmp completions source + blink = { enabled = false }, + -- Settings for coq_nvim completions source + coq = { enabled = false }, + -- Settings for in-process language server completions + lsp = { enabled = false }, + filter = { + callout = function() + -- example to exclude obsidian callouts + -- return value.category ~= 'obsidian' + return true + end, + checkbox = function() + return true + end, + }, + }, + heading = { + -- Useful context to have when evaluating values. + -- | level | the number of '#' in the heading marker | + -- | sections | for each level how deeply nested the heading is | + + -- Turn on / off heading icon & background rendering. + enabled = true, + -- Additional modes to render headings. + render_modes = false, + -- Turn on / off atx heading rendering. + atx = true, + -- Turn on / off setext heading rendering. + setext = true, + -- Turn on / off any sign column related rendering. + sign = true, + -- Replaces '#+' of 'atx_h._marker'. + -- Output is evaluated depending on the type. + -- | function | `value(context)` | + -- | string[] | `cycle(value, context.level)` | + icons = { "󰲡 ", "󰲣 ", "󰲥 ", "󰲧 ", "󰲩 ", "󰲫 " }, + -- Determines how icons fill the available space. + -- | right | '#'s are concealed and icon is appended to right side | + -- | inline | '#'s are concealed and icon is inlined on left side | + -- | overlay | icon is left padded with spaces and inserted on left hiding any additional '#' | + position = "overlay", + -- Added to the sign column if enabled. + -- Output is evaluated by `cycle(value, context.level)`. + signs = { "󰫎 " }, + -- Width of the heading background. + -- | block | width of the heading text | + -- | full | full width of the window | + -- Can also be a list of the above values evaluated by `clamp(value, context.level)`. + width = "full", + -- Amount of margin to add to the left of headings. + -- Margin available space is computed after accounting for padding. + -- If a float < 1 is provided it is treated as a percentage of available window space. + -- Can also be a list of numbers evaluated by `clamp(value, context.level)`. + left_margin = 0, + -- Amount of padding to add to the left of headings. + -- Output is evaluated using the same logic as 'left_margin'. + left_pad = 0, + -- Amount of padding to add to the right of headings when width is 'block'. + -- Output is evaluated using the same logic as 'left_margin'. + right_pad = 0, + -- Minimum width to use for headings when width is 'block'. + -- Can also be a list of integers evaluated by `clamp(value, context.level)`. + min_width = 0, + -- Determines if a border is added above and below headings. + -- Can also be a list of booleans evaluated by `clamp(value, context.level)`. + border = false, + -- Always use virtual lines for heading borders instead of attempting to use empty lines. + border_virtual = false, + -- Highlight the start of the border using the foreground highlight. + border_prefix = false, + -- Used above heading for border. + above = "▄", + -- Used below heading for border. + below = "▀", + -- Highlight for the heading icon and extends through the entire line. + -- Output is evaluated by `clamp(value, context.level)`. + backgrounds = { + "RenderMarkdownH1Bg", + "RenderMarkdownH2Bg", + "RenderMarkdownH3Bg", + "RenderMarkdownH4Bg", + "RenderMarkdownH5Bg", + "RenderMarkdownH6Bg", + }, + -- Highlight for the heading and sign icons. + -- Output is evaluated using the same logic as 'backgrounds'. + foregrounds = { + "RenderMarkdownH1", + "RenderMarkdownH2", + "RenderMarkdownH3", + "RenderMarkdownH4", + "RenderMarkdownH5", + "RenderMarkdownH6", + }, + -- Define custom heading patterns which allow you to override various properties based on + -- the contents of a heading. + -- The key is for healthcheck and to allow users to change its values, value type below. + -- | pattern | matched against the heading text @see :h lua-patterns | + -- | icon | optional override for the icon | + -- | background | optional override for the background | + -- | foreground | optional override for the foreground | + custom = {}, + }, + paragraph = { + -- Useful context to have when evaluating values. + -- | text | text value of the node | + + -- Turn on / off paragraph rendering. + enabled = true, + -- Additional modes to render paragraphs. + render_modes = false, + -- Amount of margin to add to the left of paragraphs. + -- If a float < 1 is provided it is treated as a percentage of available window space. + -- Output is evaluated depending on the type. + -- | function | `value(context)` | + -- | number | `value` | + left_margin = 0, + -- Amount of padding to add to the first line of each paragraph. + -- Output is evaluated using the same logic as 'left_margin'. + indent = 0, + -- Minimum width to use for paragraphs. + min_width = 0, + }, + code = { + -- Turn on / off code block & inline code rendering. + enabled = true, + -- Additional modes to render code blocks. + render_modes = false, + -- Turn on / off any sign column related rendering. + sign = true, + -- Determines how code blocks & inline code are rendered. + -- | none | disables all rendering | + -- | normal | background highlighting + padding | + -- | language | language heading with icon + sign column | + -- | full | normal + language | + style = "full", + -- Whether to conceal nodes at the top and bottom of code blocks. + conceal_delimiters = true, + -- Turn on / off any language heading related rendering. + language = true, + -- Determines where language icon is rendered. + -- | right | right side of code block | + -- | left | left side of code block | + position = "left", + -- Whether to include the language icon above code blocks. + language_icon = true, + -- Whether to include the language name above code blocks. + language_name = true, + -- Whether to include the language info above code blocks. + language_info = true, + -- Amount of padding to add around the language. + -- If a float < 1 is provided it is treated as a percentage of available window space. + language_pad = 0, + -- A list of language names for which background highlighting will be disabled. + -- Likely because that language has background highlights itself. + -- Use a boolean to make behavior apply to all languages. + -- Borders above & below blocks will continue to be rendered. + disable_background = { "diff" }, + -- Width of the code block background. + -- | block | width of the code block | + -- | full | full width of the window | + width = "full", + -- Amount of margin to add to the left of code blocks. + -- If a float < 1 is provided it is treated as a percentage of available window space. + -- Margin available space is computed after accounting for padding. + left_margin = 0, + -- Amount of padding to add to the left of code blocks. + -- If a float < 1 is provided it is treated as a percentage of available window space. + left_pad = 0, + -- Amount of padding to add to the right of code blocks when width is 'block'. + -- If a float < 1 is provided it is treated as a percentage of available window space. + right_pad = 0, + -- Minimum width to use for code blocks when width is 'block'. + min_width = 0, + -- Determines how the top / bottom of code block are rendered. + -- | none | do not render a border | + -- | thick | use the same highlight as the code body | + -- | thin | when lines are empty overlay the above & below icons | + -- | hide | conceal lines unless language name or icon is added | + border = "hide", + -- Used above code blocks to fill remaining space around language. + language_border = "█", + -- Added to the left of language. + language_left = "", + -- Added to the right of language. + language_right = "", + -- Used above code blocks for thin border. + above = "▄", + -- Used below code blocks for thin border. + below = "▀", + -- Icon to add to the left of inline code. + inline_left = "", + -- Icon to add to the right of inline code. + inline_right = "", + -- Padding to add to the left & right of inline code. + inline_pad = 0, + -- Highlight for code blocks. + highlight = "RenderMarkdownCode", + -- Highlight for code info section, after the language. + highlight_info = "RenderMarkdownCodeInfo", + -- Highlight for language, overrides icon provider value. + highlight_language = nil, + -- Highlight for border, use false to add no highlight. + highlight_border = "RenderMarkdownCodeBorder", + -- Highlight for language, used if icon provider does not have a value. + highlight_fallback = "RenderMarkdownCodeFallback", + -- Highlight for inline code. + highlight_inline = "RenderMarkdownCodeInline", + }, + dash = { + -- Turn on / off thematic break rendering. + enabled = true, + -- Additional modes to render dash. + render_modes = false, + -- Replaces '---'|'***'|'___'|'* * *' of 'thematic_break'. + -- The icon gets repeated across the window's width. + icon = "─", + -- Width of the generated line. + -- | | a hard coded width value | + -- | full | full width of the window | + -- If a float < 1 is provided it is treated as a percentage of available window space. + width = "full", + -- Amount of margin to add to the left of dash. + -- If a float < 1 is provided it is treated as a percentage of available window space. + left_margin = 0, + -- Highlight for the whole line generated from the icon. + highlight = "RenderMarkdownDash", + }, + document = { + -- Turn on / off document rendering. + enabled = true, + -- Additional modes to render document. + render_modes = false, + -- Ability to conceal arbitrary ranges of text based on lua patterns, @see :h lua-patterns. + -- Relies entirely on user to set patterns that handle their edge cases. + conceal = { + -- Matched ranges will be concealed using character level conceal. + char_patterns = {}, + -- Matched ranges will be concealed using line level conceal. + line_patterns = {}, + }, + }, + bullet = { + -- Useful context to have when evaluating values. + -- | level | how deeply nested the list is, 1-indexed | + -- | index | how far down the item is at that level, 1-indexed | + -- | value | text value of the marker node | + + -- Turn on / off list bullet rendering + enabled = true, + -- Additional modes to render list bullets + render_modes = false, + -- Replaces '-'|'+'|'*' of 'list_item'. + -- If the item is a 'checkbox' a conceal is used to hide the bullet instead. + -- Output is evaluated depending on the type. + -- | function | `value(context)` | + -- | string | `value` | + -- | string[] | `cycle(value, context.level)` | + -- | string[][] | `clamp(cycle(value, context.level), context.index)` | + icons = { "●", "○", "◆", "◇" }, + -- Replaces 'n.'|'n)' of 'list_item'. + -- Output is evaluated using the same logic as 'icons'. + ordered_icons = function(ctx) + local value = vim.trim(ctx.value) + local index = tonumber(value:sub(1, #value - 1)) + return ("%d."):format(index > 1 and index or ctx.index) + end, + -- Padding to add to the left of bullet point. + -- Output is evaluated depending on the type. + -- | function | `value(context)` | + -- | integer | `value` | + left_pad = 0, + -- Padding to add to the right of bullet point. + -- Output is evaluated using the same logic as 'left_pad'. + right_pad = 0, + -- Highlight for the bullet icon. + -- Output is evaluated using the same logic as 'icons'. + highlight = "RenderMarkdownBullet", + -- Highlight for item associated with the bullet point. + -- Output is evaluated using the same logic as 'icons'. + scope_highlight = {}, + }, + checkbox = { + -- Checkboxes are a special instance of a 'list_item' that start with a 'shortcut_link'. + -- There are two special states for unchecked & checked defined in the markdown grammar. + + -- Turn on / off checkbox state rendering. + enabled = true, + -- Additional modes to render checkboxes. + render_modes = false, + -- Render the bullet point before the checkbox. + bullet = false, + -- Padding to add to the right of checkboxes. + right_pad = 1, + unchecked = { + -- Replaces '[ ]' of 'task_list_marker_unchecked'. + icon = "󰄱 ", + -- Highlight for the unchecked icon. + highlight = "RenderMarkdownUnchecked", + -- Highlight for item associated with unchecked checkbox. + scope_highlight = nil, + }, + checked = { + -- Replaces '[x]' of 'task_list_marker_checked'. + icon = "󰱒 ", + -- Highlight for the checked icon. + highlight = "RenderMarkdownChecked", + -- Highlight for item associated with checked checkbox. + scope_highlight = nil, + }, + -- Define custom checkbox states, more involved, not part of the markdown grammar. + -- As a result this requires neovim >= 0.10.0 since it relies on 'inline' extmarks. + -- The key is for healthcheck and to allow users to change its values, value type below. + -- | raw | matched against the raw text of a 'shortcut_link' | + -- | rendered | replaces the 'raw' value when rendering | + -- | highlight | highlight for the 'rendered' icon | + -- | scope_highlight | optional highlight for item associated with custom checkbox | + -- stylua: ignore + custom = { + todo = { raw = '[-]', rendered = '󰥔 ', highlight = 'RenderMarkdownTodo', scope_highlight = nil }, + }, + }, + quote = { + -- Turn on / off block quote & callout rendering. + enabled = true, + -- Additional modes to render quotes. + render_modes = false, + -- Replaces '>' of 'block_quote'. + icon = "▋", + -- Whether to repeat icon on wrapped lines. Requires neovim >= 0.10. This will obscure text + -- if incorrectly configured with :h 'showbreak', :h 'breakindent' and :h 'breakindentopt'. + -- A combination of these that is likely to work follows. + -- | showbreak | ' ' (2 spaces) | + -- | breakindent | true | + -- | breakindentopt | '' (empty string) | + -- These are not validated by this plugin. If you want to avoid adding these to your main + -- configuration then set them in win_options for this plugin. + repeat_linebreak = false, + -- Highlight for the quote icon. + -- If a list is provided output is evaluated by `cycle(value, level)`. + highlight = { + "RenderMarkdownQuote1", + "RenderMarkdownQuote2", + "RenderMarkdownQuote3", + "RenderMarkdownQuote4", + "RenderMarkdownQuote5", + "RenderMarkdownQuote6", + }, + }, + pipe_table = { + -- Turn on / off pipe table rendering. + enabled = true, + -- Additional modes to render pipe tables. + render_modes = false, + -- Pre configured settings largely for setting table border easier. + -- | heavy | use thicker border characters | + -- | double | use double line border characters | + -- | round | use round border corners | + -- | none | does nothing | + preset = "none", + -- Determines how the table as a whole is rendered. + -- | none | disables all rendering | + -- | normal | applies the 'cell' style rendering to each row of the table | + -- | full | normal + a top & bottom line that fill out the table when lengths match | + style = "full", + -- Determines how individual cells of a table are rendered. + -- | overlay | writes completely over the table, removing conceal behavior and highlights | + -- | raw | replaces only the '|' characters in each row, leaving the cells unmodified | + -- | padded | raw + cells are padded to maximum visual width for each column | + -- | trimmed | padded except empty space is subtracted from visual width calculation | + cell = "padded", + -- Amount of space to put between cell contents and border. + padding = 1, + -- Minimum column width to use for padded or trimmed cell. + min_width = 0, + -- Characters used to replace table border. + -- Correspond to top(3), delimiter(3), bottom(3), vertical, & horizontal. + -- stylua: ignore + border = { + '┌', '┬', '┐', + '├', '┼', '┤', + '└', '┴', '┘', + '│', '─', + }, + -- Always use virtual lines for table borders instead of attempting to use empty lines. + -- Will be automatically enabled if indentation module is enabled. + border_virtual = false, + -- Gets placed in delimiter row for each column, position is based on alignment. + alignment_indicator = "━", + -- Highlight for table heading, delimiter, and the line above. + head = "RenderMarkdownTableHead", + -- Highlight for everything else, main table rows and the line below. + row = "RenderMarkdownTableRow", + -- Highlight for inline padding used to add back concealed space. + filler = "RenderMarkdownTableFill", + }, + callout = { + -- Callouts are a special instance of a 'block_quote' that start with a 'shortcut_link'. + -- The key is for healthcheck and to allow users to change its values, value type below. + -- | raw | matched against the raw text of a 'shortcut_link', case insensitive | + -- | rendered | replaces the 'raw' value when rendering | + -- | highlight | highlight for the 'rendered' text and quote markers | + -- | quote_icon | optional override for quote.icon value for individual callout | + -- | category | optional metadata useful for filtering | + + note = { + raw = "[!NOTE]", + rendered = "󰋽 Note", + highlight = "RenderMarkdownInfo", + category = "github", + }, + tip = { + raw = "[!TIP]", + rendered = "󰌶 Tip", + highlight = "RenderMarkdownSuccess", + category = "github", + }, + important = { + raw = "[!IMPORTANT]", + rendered = "󰅾 Important", + highlight = "RenderMarkdownHint", + category = "github", + }, + warning = { + raw = "[!WARNING]", + rendered = "󰀪 Warning", + highlight = "RenderMarkdownWarn", + category = "github", + }, + caution = { + raw = "[!CAUTION]", + rendered = "󰳦 Caution", + highlight = "RenderMarkdownError", + category = "github", + }, + -- Obsidian: https://help.obsidian.md/Editing+and+formatting/Callouts + abstract = { + raw = "[!ABSTRACT]", + rendered = "󰨸 Abstract", + highlight = "RenderMarkdownInfo", + category = "obsidian", + }, + summary = { + raw = "[!SUMMARY]", + rendered = "󰨸 Summary", + highlight = "RenderMarkdownInfo", + category = "obsidian", + }, + tldr = { + raw = "[!TLDR]", + rendered = "󰨸 Tldr", + highlight = "RenderMarkdownInfo", + category = "obsidian", + }, + info = { + raw = "[!INFO]", + rendered = "󰋽 Info", + highlight = "RenderMarkdownInfo", + category = "obsidian", + }, + todo = { + raw = "[!TODO]", + rendered = "󰗡 Todo", + highlight = "RenderMarkdownInfo", + category = "obsidian", + }, + hint = { + raw = "[!HINT]", + rendered = "󰌶 Hint", + highlight = "RenderMarkdownSuccess", + category = "obsidian", + }, + success = { + raw = "[!SUCCESS]", + rendered = "󰄬 Success", + highlight = "RenderMarkdownSuccess", + category = "obsidian", + }, + check = { + raw = "[!CHECK]", + rendered = "󰄬 Check", + highlight = "RenderMarkdownSuccess", + category = "obsidian", + }, + done = { + raw = "[!DONE]", + rendered = "󰄬 Done", + highlight = "RenderMarkdownSuccess", + category = "obsidian", + }, + question = { + raw = "[!QUESTION]", + rendered = "󰘥 Question", + highlight = "RenderMarkdownWarn", + category = "obsidian", + }, + help = { + raw = "[!HELP]", + rendered = "󰘥 Help", + highlight = "RenderMarkdownWarn", + category = "obsidian", + }, + faq = { + raw = "[!FAQ]", + rendered = "󰘥 Faq", + highlight = "RenderMarkdownWarn", + category = "obsidian", + }, + attention = { + raw = "[!ATTENTION]", + rendered = "󰀪 Attention", + highlight = "RenderMarkdownWarn", + category = "obsidian", + }, + failure = { + raw = "[!FAILURE]", + rendered = "󰅖 Failure", + highlight = "RenderMarkdownError", + category = "obsidian", + }, + fail = { + raw = "[!FAIL]", + rendered = "󰅖 Fail", + highlight = "RenderMarkdownError", + category = "obsidian", + }, + missing = { + raw = "[!MISSING]", + rendered = "󰅖 Missing", + highlight = "RenderMarkdownError", + category = "obsidian", + }, + danger = { + raw = "[!DANGER]", + rendered = "󱐌 Danger", + highlight = "RenderMarkdownError", + category = "obsidian", + }, + error = { + raw = "[!ERROR]", + rendered = "󱐌 Error", + highlight = "RenderMarkdownError", + category = "obsidian", + }, + bug = { + raw = "[!BUG]", + rendered = "󰨰 Bug", + highlight = "RenderMarkdownError", + category = "obsidian", + }, + example = { + raw = "[!EXAMPLE]", + rendered = "󰉹 Example", + highlight = "RenderMarkdownHint", + category = "obsidian", + }, + quote = { + raw = "[!QUOTE]", + rendered = "󱆨 Quote", + highlight = "RenderMarkdownQuote", + category = "obsidian", + }, + cite = { + raw = "[!CITE]", + rendered = "󱆨 Cite", + highlight = "RenderMarkdownQuote", + category = "obsidian", + }, + }, + link = { + -- Turn on / off inline link icon rendering. + enabled = true, + -- Additional modes to render links. + render_modes = false, + -- How to handle footnote links, start with a '^'. + footnote = { + -- Turn on / off footnote rendering. + enabled = true, + -- Replace value with superscript equivalent. + superscript = true, + -- Added before link content. + prefix = "", + -- Added after link content. + suffix = "", + }, + -- Inlined with 'image' elements. + image = "󰥶 ", + -- Inlined with 'email_autolink' elements. + email = "󰀓 ", + -- Fallback icon for 'inline_link' and 'uri_autolink' elements. + hyperlink = "󰌹 ", + -- Applies to the inlined icon as a fallback. + highlight = "RenderMarkdownLink", + -- Applies to WikiLink elements. + wiki = { + icon = "󱗖 ", + body = function() + return nil + end, + highlight = "RenderMarkdownWikiLink", + }, + -- Define custom destination patterns so icons can quickly inform you of what a link + -- contains. Applies to 'inline_link', 'uri_autolink', and wikilink nodes. When multiple + -- patterns match a link the one with the longer pattern is used. + -- The key is for healthcheck and to allow users to change its values, value type below. + -- | pattern | matched against the destination text | + -- | icon | gets inlined before the link text | + -- | kind | optional determines how pattern is checked | + -- | | pattern | @see :h lua-patterns, is the default if not set | + -- | | suffix | @see :h vim.endswith() | + -- | priority | optional used when multiple match, uses pattern length if empty | + -- | highlight | optional highlight for 'icon', uses fallback highlight if empty | + custom = { + web = { pattern = "^http", icon = "󰖟 " }, + discord = { pattern = "discord%.com", icon = "󰙯 " }, + github = { pattern = "github%.com", icon = "󰊤 " }, + gitlab = { pattern = "gitlab%.com", icon = "󰮠 " }, + google = { pattern = "google%.com", icon = "󰊭 " }, + neovim = { pattern = "neovim%.io", icon = " " }, + reddit = { pattern = "reddit%.com", icon = "󰑍 " }, + stackoverflow = { pattern = "stackoverflow%.com", icon = "󰓌 " }, + wikipedia = { pattern = "wikipedia%.org", icon = "󰖬 " }, + youtube = { pattern = "youtube%.com", icon = "󰗃 " }, + }, + }, + sign = { + -- Turn on / off sign rendering. + enabled = true, + -- Applies to background of sign text. + highlight = "RenderMarkdownSign", + }, + inline_highlight = { + -- Mimics Obsidian inline highlights when content is surrounded by double equals. + -- The equals on both ends are concealed and the inner content is highlighted. + + -- Turn on / off inline highlight rendering. + enabled = true, + -- Additional modes to render inline highlights. + render_modes = false, + -- Applies to background of surrounded text. + highlight = "RenderMarkdownInlineHighlight", + }, + indent = { + -- Mimic org-indent-mode behavior by indenting everything under a heading based on the + -- level of the heading. Indenting starts from level 2 headings onward by default. + + -- Turn on / off org-indent-mode. + enabled = false, + -- Additional modes to render indents. + render_modes = false, + -- Amount of additional padding added for each heading level. + per_level = 2, + -- Heading levels <= this value will not be indented. + -- Use 0 to begin indenting from the very first level. + skip_level = 1, + -- Do not indent heading titles, only the body. + skip_heading = false, + -- Prefix added when indenting, one per level. + icon = "▎", + -- Priority to assign to extmarks. + priority = 0, + -- Applied to icon. + highlight = "RenderMarkdownIndent", + }, + html = { + -- Turn on / off all HTML rendering. + enabled = true, + -- Additional modes to render HTML. + render_modes = false, + comment = { + -- Turn on / off HTML comment concealing. + conceal = true, + -- Optional text to inline before the concealed comment. + text = nil, + -- Highlight for the inlined text. + highlight = "RenderMarkdownHtmlComment", + }, + -- HTML tags whose start and end will be hidden and icon shown. + -- The key is matched against the tag name, value type below. + -- | icon | gets inlined at the start | + -- | highlight | highlight for the icon | + tag = {}, + }, + win_options = { + -- Window options to use that change between rendered and raw view. + + -- @see :h 'conceallevel' + conceallevel = { + -- Used when not being rendered, get user setting. + default = vim.o.conceallevel, + -- Used when being rendered, concealed text is completely hidden. + rendered = 3, + }, + -- @see :h 'concealcursor' + concealcursor = { + -- Used when not being rendered, get user setting. + default = vim.o.concealcursor, + -- Used when being rendered, show concealed text in all modes. + rendered = "", + }, + }, + overrides = { + -- More granular configuration mechanism, allows different aspects of buffers to have their own + -- behavior. Values default to the top level configuration if no override is provided. Supports + -- the following fields: + -- enabled, max_file_size, debounce, render_modes, anti_conceal, padding, heading, paragraph, + -- code, dash, bullet, checkbox, quote, pipe_table, callout, link, sign, indent, latex, html, + -- win_options + + -- Override for different buflisted values, @see :h 'buflisted'. + buflisted = {}, + -- Override for different buftype values, @see :h 'buftype'. + buftype = { + nofile = { + render_modes = true, + padding = { highlight = "NormalFloat" }, + sign = { enabled = false }, + }, + }, + -- Override for different filetype values, @see :h 'filetype'. + filetype = {}, + }, + custom_handlers = { + -- Mapping from treesitter language to user defined handlers. + -- @see [Custom Handlers](doc/custom-handlers.md) + }, +} diff --git a/common/.config/nvim/lua/mappings.lua b/common/.config/nvim/lua/mappings.lua new file mode 100644 index 0000000..a5a3544 --- /dev/null +++ b/common/.config/nvim/lua/mappings.lua @@ -0,0 +1,25 @@ +require "nvchad.mappings" + +-- add yours here + +local map = vim.keymap.set + +map("n", "gd", vim.lsp.buf.definition, { desc = "Go to definition" }) +map("n", "gD", "Telescope lsp_definitions", { desc = "Go to Definitions" }) +map("n", "grr", "Telescope lsp_references", { desc = "Go to references" }) +map("n", "da", ":lua vim.lsp.buf.code_action()", { desc = "Code actions", noremap = true, silent = true }) +map("n", "dh", ":lua vim.diagnostic.open_float()", { desc = "Show diagnostics" }) +map("n", "dj", function() + vim.diagnostic.jump { count = 1, float = true } +end, { desc = "Go to next" }) +map("n", "dk", function() + vim.diagnostic.jump { count = -1, float = true } +end, { desc = "Go to previous" }) +-- Telescope +map("n", "fr", ":Telescope resume", { desc = "Resume last search" }) +map("n", "fs", ":Telescope grep_string", { desc = "Find selected string" }) +map("n", "fk", ":Telescope keymaps", { desc = "Find keymaps" }) +map("n", "fd", ":Telescope diagnostics", { desc = "Diagnostics" }) +-- Remaps +map({ "n", "v" }, "x", '"_x', { desc = "Delete char without yanking" }) +map({ "n", "v" }, "c", '"_c', { desc = "Change without yanking" }) diff --git a/common/.config/nvim/lua/options.lua b/common/.config/nvim/lua/options.lua new file mode 100644 index 0000000..738f20b --- /dev/null +++ b/common/.config/nvim/lua/options.lua @@ -0,0 +1,6 @@ +require "nvchad.options" + +-- add yours here! + +-- local o = vim.o +-- o.cursorlineopt ='both' -- to enable cursorline! diff --git a/common/.config/nvim/lua/plugins/init.lua b/common/.config/nvim/lua/plugins/init.lua new file mode 100644 index 0000000..7dc0aea --- /dev/null +++ b/common/.config/nvim/lua/plugins/init.lua @@ -0,0 +1,107 @@ +return { + { + "stevearc/conform.nvim", + event = "BufWritePre", -- uncomment for format on save + opts = require "configs.conform", + }, + + { + "neovim/nvim-lspconfig", + config = function() + require "configs.lspconfig" + end, + }, + + { + "nvim-treesitter/nvim-treesitter", + branch = "main", + opts = { + ensure_installed = { + "vim", + "vimdoc", + "lua", + "luadoc", + "printf", + "html", + "css", + "typescript", + "javascript", + "markdown", + "scss", + "svelte", + "typst", + "vue", + "regex", + }, + }, + -- On the main branch nothing acts on `ensure_installed` at startup: setup() takes only + -- install_dir, and NvChad's :TSInstallAll (which does read this list off the lazy spec) + -- only runs from `build`, i.e. when the plugin is installed or updated. So a language + -- added here stayed uninstalled until the next rebuild — 9 of these 15 were missing, + -- silently falling back to regex highlighting. Install whatever is absent, once, here. + config = function(_, opts) + local ts = require "nvim-treesitter" + ts.setup() + + local have = {} + for _, lang in ipairs(ts.get_installed()) do + have[lang] = true + end + local missing = vim.tbl_filter(function(lang) + return not have[lang] + end, opts.ensure_installed or {}) + if #missing > 0 then + ts.install(missing) -- async; highlighting picks each up as it lands + end + end, + }, + + { + "MeanderingProgrammer/render-markdown.nvim", + ft = { "markdown", "gitcommit" }, + opts = function() + return require "configs.render-markdown" + end, + }, + + -- snacks.indent (below) draws the indent guides — disable NvChad's indent-blankline + -- so they don't render doubled + { "lukas-reineke/indent-blankline.nvim", enabled = false }, + + { + "folke/snacks.nvim", + priority = 1000, + lazy = false, + ---@type snacks.Config + opts = { + -- your configuration comes here + -- or leave it empty to use the default settings + -- refer to the configuration section below + bigfile = { enabled = false }, + dashboard = { enabled = false }, + explorer = { enabled = true }, + indent = { enabled = true }, + input = { enabled = true }, + picker = { enabled = true }, + notifier = { enabled = true }, + quickfile = { enabled = true }, + scope = { enabled = true }, + scroll = { enabled = true }, + statuscolumn = { enabled = true }, + words = { enabled = true }, + }, + }, + + -- These are some examples, uncomment them if you want to see them work! + -- + -- { + -- "nvim-treesitter/nvim-treesitter", + -- opts = { + -- ensure_installed = { + -- "vim", "lua", "vimdoc", + -- "html", "css" + -- }, + -- }, + -- }, + -- +} diff --git a/common/.config/opencode/README.md b/common/.config/opencode/README.md new file mode 100644 index 0000000..e44101a --- /dev/null +++ b/common/.config/opencode/README.md @@ -0,0 +1,74 @@ +# opencode config + +Config tree for [opencode](https://opencode.ai) (2.x), tuned for **small local models** behind a +llama.cpp router. Stowed into `~/.config/opencode/` as per-file symlinks; editing here edits the live +config (restart opencode, or `opencode service restart`, to pick changes up — the 2.x background +service caches config). + +## Layout + +| Path | What | +|---|---| +| `opencode.json` | Providers, permissions, primary agents, defaults. Written in the v1 schema, which 2.x still accepts. | +| `openai-gpt.jsonc` | Optional GPT/Codex OAuth overlay (OpenAI provider + `opencode-openai-codex-auth` plugin). Not loaded by itself — see *GPT overlay*. | +| `AGENTS.md` | Global rules prepended to every session. Same text as the pi config's `AGENTS.md`: terse, verify-before-asserting, small-model friendly. | +| `agents/*.md` | Four subagents with real prompts and scoped permissions: `code-reviewer`, `test-runner` (hidden), `doc-writer` (edits docs only), `security-auditor` (hidden). | +| `commands/*.md` | `/commit` (Conventional Commits message, never commits) and `/review` (read-only diff review), both on the `plan` agent. | +| `plugins/verbose/` | 2.x TUI plugin: `v`, `/verbose`, or the palette entry toggles the *verbose view* — thinking blocks expanded and tool calls ungrouped — reading the live state from the built-in toggles so a mixed state converges. `server.ts` is a no-op half required by the loader. | +| `plugins/agent-state.ts` | Server-side plugin: mirrors the session state (`message.updated` user → busy, `permission.asked` → input, `session.idle` → done, `session.error` → error) into the tmux pane opencode runs in via `~/.config/tmux/scripts/agent-state.sh`, for the status-bar agent badges. Skips child sessions; only right when the TUI in the pane spawned the server (not `serve`/`attach`); under `opencodes` (bwrap) the tmux socket dir must be bound in. | +| `themes/catppuccin-mocha.json` | Catppuccin Mocha (dark) / Latte (light) theme following the pi theme's semantic mapping. Built-in `catppuccin` exists too; this one matches pi. | +| `tui.json` | TUI settings in the v1 schema (2.x compat): theme, leader timeout, stacked diffs, block cursor, attention notifications, a few extra keybinds. | + +The sandbox wrapper lives in `../fish/functions/opencodes.fish`: `opencodes` runs opencode under +bwrap with the stowed config dirs, `~/.cache/opencode`, state and data bound, and only the needed +environment passed through. Extra arguments go to opencode. + +## Providers and models + +Two OpenAI-compatible providers point at the same llama.cpp router: `llama.cpp` on the LAN and +`duskadiy` through the public hostname (`apiKey` from `$DUSKADIY_API_KEY`). Model ids are the preset +section names in `fl/.config/llamacpp/config.ini`; keep the lists in sync with it and with the pi and +aichat configs. Both providers use a one-hour request timeout — the default five minutes cut off +long local replies. + +Decisions that look odd but are deliberate: + +- **No `small_model`.** The router runs `--models-max 1`; any second model id evicts the resident one. + With `small_model` unset, title generation falls back to the session's model. Subagents carry no + pinned model for the same reason — the task tool uses the caller's model. +- **No `temperature` / `top_p` from opencode.** Verified by capturing request bodies: only + `max_tokens` is sent, so the router presets own sampling. +- **`reasoning: true`** only on the presets that actually think (no `reasoning-budget = 0`); + GLM also replays `reasoning_content` in history because its preset sets `reasoning-preserve`. +- **`snapshot: false`** — file-change undo is not used. **`tool_output`** capped at 200 lines / + 16 KiB for 24k-context models. **`compaction.reserved`/`prune`** are inert at this context size. +- **`question: allow`** everywhere so agents ask instead of guessing. + +## Agents + +`auto` is the default agent and cycles with `build` and `plan` on Tab. It runs without prompts except +for the serious set — git history rewriting and pushing, `rm`, killing processes, `systemctl`, +network transfers, package installs — which ask, and `sudo`/`dd`/`mkfs`/secret-file reads, which are +denied. Colors: build primary, plan info, auto yellow. All three cap agentic iterations at 30. + +Permission rules resolve **global first, agent rules appended, last match wins**, so an agent that +wants a blanket rule must restate its own denies after it (the `auto` block does). + +## GPT overlay + +`openai-gpt.jsonc` is a template. opencode 2.x ignores `OPENCODE_CONFIG`, but it merges a second +global file named `opencode.jsonc`. `fish/config.fish` links `opencode.jsonc → openai-gpt.jsonc` +only on a host whose `~/.local/share/opencode/auth.json` holds an OpenAI credential (from +`opencode auth login`), and removes the link again when the login is gone. + +## Host overlays + +`lw/.config/opencode/opencode.json` is a fork of the common file that adds the laptop's local CPU +llama.cpp provider (`lwcpp`). Mirror every edit between the two. + +## Lifting pieces into a stock opencode + +Everything is plain files: copy `agents/`, `commands/`, `plugins/verbose/` or the theme into your own +`~/.config/opencode/`. The plugin needs 2.x (it uses the `keymap.layer` / `dispatch` API and is +discovered as a directory under `plugins/`). The permission blocks in `opencode.json` are independent +of the providers and can be pasted as-is. diff --git a/common/.config/opencode/commands/commit.md b/common/.config/opencode/commands/commit.md new file mode 100644 index 0000000..0b84220 --- /dev/null +++ b/common/.config/opencode/commands/commit.md @@ -0,0 +1,11 @@ +--- +description: Write a Conventional Commits message for the staged changes (does not commit) +agent: plan +--- +Inspect the staged changes with `git diff --cached` (and `git status` for context). Then write a single Conventional Commits message: + +- A `(): ` summary line, imperative mood, ≤72 chars (types: feat, fix, refactor, docs, chore, test, perf, build). +- An optional short body explaining the *why* only when it isn't obvious from the diff. +- Do NOT run `git commit`. Output only the message inside a code block so I can review it. + +Extra context from me, if any: $ARGUMENTS diff --git a/common/.config/opencode/commands/review.md b/common/.config/opencode/commands/review.md new file mode 100644 index 0000000..2d2ca42 --- /dev/null +++ b/common/.config/opencode/commands/review.md @@ -0,0 +1,14 @@ +--- +description: Review the current diff (staged + unstaged) for bugs and issues, read-only +agent: plan +--- +Review the current changes. Check both `git diff` (unstaged) and `git diff --cached` (staged). Focus on: + +- Correctness and logic bugs +- Error handling and missing edge cases +- Security issues (injection, secrets, unsafe input) +- Anything that doesn't match the surrounding code's conventions + +List concrete findings as `file:line — issue — suggested fix`, ordered by severity. Be concise; skip praise. If nothing is wrong, say so. + +Extra focus this round, if any (default: general correctness): $ARGUMENTS diff --git a/common/.config/opencode/openai-gpt.jsonc b/common/.config/opencode/openai-gpt.jsonc new file mode 100644 index 0000000..85c73b6 --- /dev/null +++ b/common/.config/opencode/openai-gpt.jsonc @@ -0,0 +1,247 @@ +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [ + "opencode-openai-codex-auth" + ], + "provider": { + "openai": { + "options": { + "reasoningEffort": "medium", + "reasoningSummary": "auto", + "textVerbosity": "medium", + "include": [ + "reasoning.encrypted_content" + ], + "store": false + }, + "whitelist": [ + "gpt-5.2", + "gpt-5.2-codex", + "gpt-5.1-codex-max", + "gpt-5.1-codex", + "gpt-5.1-codex-mini", + "gpt-5.1" + ], + "models": { + "gpt-5.2": { + "name": "GPT 5.2 (OAuth)", + "limit": { + "context": 272000, + "output": 128000 + }, + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "variants": { + "none": { + "reasoningEffort": "none", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "low": { + "reasoningEffort": "low", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "medium": { + "reasoningEffort": "medium", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "high": { + "reasoningEffort": "high", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + }, + "xhigh": { + "reasoningEffort": "xhigh", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + } + } + }, + "gpt-5.2-codex": { + "name": "GPT 5.2 Codex (OAuth)", + "limit": { + "context": 272000, + "output": 128000 + }, + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "variants": { + "low": { + "reasoningEffort": "low", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "medium": { + "reasoningEffort": "medium", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "high": { + "reasoningEffort": "high", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + }, + "xhigh": { + "reasoningEffort": "xhigh", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + } + } + }, + "gpt-5.1-codex-max": { + "name": "GPT 5.1 Codex Max (OAuth)", + "limit": { + "context": 272000, + "output": 128000 + }, + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "variants": { + "low": { + "reasoningEffort": "low", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + }, + "medium": { + "reasoningEffort": "medium", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + }, + "high": { + "reasoningEffort": "high", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + }, + "xhigh": { + "reasoningEffort": "xhigh", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + } + } + }, + "gpt-5.1-codex": { + "name": "GPT 5.1 Codex (OAuth)", + "limit": { + "context": 272000, + "output": 128000 + }, + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "variants": { + "low": { + "reasoningEffort": "low", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "medium": { + "reasoningEffort": "medium", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "high": { + "reasoningEffort": "high", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + } + } + }, + "gpt-5.1-codex-mini": { + "name": "GPT 5.1 Codex Mini (OAuth)", + "limit": { + "context": 272000, + "output": 128000 + }, + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "variants": { + "medium": { + "reasoningEffort": "medium", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "high": { + "reasoningEffort": "high", + "reasoningSummary": "detailed", + "textVerbosity": "medium" + } + } + }, + "gpt-5.1": { + "name": "GPT 5.1 (OAuth)", + "limit": { + "context": 272000, + "output": 128000 + }, + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "variants": { + "none": { + "reasoningEffort": "none", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "low": { + "reasoningEffort": "low", + "reasoningSummary": "auto", + "textVerbosity": "low" + }, + "medium": { + "reasoningEffort": "medium", + "reasoningSummary": "auto", + "textVerbosity": "medium" + }, + "high": { + "reasoningEffort": "high", + "reasoningSummary": "detailed", + "textVerbosity": "high" + } + } + } + } + } + } +} diff --git a/common/.config/opencode/opencode.json b/common/.config/opencode/opencode.json new file mode 100644 index 0000000..ab2f601 --- /dev/null +++ b/common/.config/opencode/opencode.json @@ -0,0 +1,313 @@ +{ + "$schema": "https://opencode.ai/config.json", + "model": "llama.cpp/Qwen3.6-35B-A3B-Thinking", + "default_agent": "auto", + "instructions": ["CLAUDE.md", "AGENTS.md"], + "share": "disabled", + "autoupdate": "notify", + "tool_output": { "max_lines": 200, "max_bytes": 16384 }, + "snapshot": false, + "disabled_providers": [ + "gemini", + "anthropic", + "groq", + "openrouter", + "opencode" + ], + "permission": { + "edit": "deny", + "webfetch": "ask", + "websearch": "ask", + "external_directory": "ask", + "question": "allow", + "read": { + "*": "allow", + "**/.env*": "deny", + "**/*.env": "deny", + "**/*.pem": "deny", + "**/*.key": "deny", + "**/*.p12": "deny", + "**/*.pfx": "deny", + "**/*.keystore": "deny", + "**/id_rsa*": "deny", + "**/.ssh/**": "deny", + "**/.aws/**": "deny", + "**/.npmrc": "deny", + "**/.netrc": "deny" + }, + "bash": { + "*": "ask", + + "ls *": "allow", + "cat *": "allow", + "grep *": "allow", + "rg *": "allow", + "find *": "allow", + "fd *": "allow", + "which *": "allow", + "file *": "allow", + "stat *": "allow", + "wc *": "allow", + "tree *": "allow", + "diff *": "allow", + "sort *": "allow", + "uniq *": "allow", + "echo *": "ask", + "pwd": "allow", + "date": "allow", + "whoami": "allow", + "jq *": "allow", + "tsc *": "allow", + "mkdir *": "ask", + "touch *": "ask", + + "git *": "ask", + "git status": "allow", + "git status *": "allow", + "git diff": "allow", + "git diff *": "allow", + "git log": "allow", + "git log *": "allow", + "git show *": "allow", + "git branch": "allow", + "git remote -v": "allow", + + "npm *": "ask", + "pnpm *": "ask", + "npx *": "ask", + "npm list": "allow", + "npm help": "allow", + "npm version": "allow", + "pnpm list": "allow", + "pnpm help": "allow", + "npx --version": "allow", + + "curl *": "ask", + "wget *": "ask", + + "rm *": "deny", + "rmdir *": "deny", + "dd *": "deny", + "mkfs*": "deny", + "shred *": "deny", + "chmod -R *": "deny", + "sudo *": "deny", + "doas *": "deny", + + "npm install*": "deny", + "npm i": "deny", + "npm i *": "deny", + "npm ci*": "deny", + "pnpm install*": "deny", + "pnpm i": "deny", + "pnpm i *": "deny", + "pnpm add*": "deny", + "yarn add*": "deny", + "yarn install*": "deny", + "pip install*": "deny", + "pip3 install*": "deny", + "pipx install*": "deny", + "cargo install*": "deny", + "go install*": "deny", + "gem install*": "deny", + "brew install*": "deny", + + "pacman *": "deny", + "yay *": "deny", + "apt *": "deny", + "apt-get *": "deny", + "dnf *": "deny", + + "cat .env*": "deny", + "cat *.env": "deny", + "cat *.pem": "deny", + "cat *.key": "deny", + "cat *id_rsa*": "deny", + "cat *secret*": "deny", + "cat *credential*": "deny", + "cat ~/.ssh/*": "deny", + "cat ~/.aws/*": "deny", + "grep .env*": "deny", + "grep * .env*": "deny" + } + }, + "provider": { + "duskadiy": { + "npm": "@ai-sdk/openai-compatible", + "name": "DuskaDIY", + "options": { + "baseURL": "https://llm.duskadiy.com/api/v1", + "apiKey": "{env:DUSKADIY_API_KEY}", + "timeout": 3600000 + }, + "models": { + "Qwen3-Coder-30B-Instruct-UD-Q3_K_XL": { "name": "Qwen3 Coder 30B · 32k — main agent coder (~30 t/s, remote)", "limit": { "context": 32768, "output": 4096 } }, + "Qwen3-Coder-Next-UD-IQ3_XXS": { "name": "Qwen3 Coder Next 80B · 128k — long sessions (~16 t/s, remote)", "limit": { "context": 131072, "output": 16384 } }, + "Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS": { "name": "Qwen3.6 35B · 24k · vision — daily driver (~36 t/s, remote)", "attachment": true, "limit": { "context": 24576, "output": 8192 } }, + "Qwen3.6-35B-A3B-Thinking": { "reasoning": true, "name": "Qwen3.6 35B Thinking · 24k · vision — hard problems (~39 t/s, remote)", "attachment": true, "limit": { "context": 24576, "output": 8192 } }, + "Qwen3.5-9B-UD-Q6_K_XL": { "reasoning": true, "name": "Qwen3.5 9B · 32k · vision — quick tasks (~32 t/s, remote)", "attachment": true, "limit": { "context": 32768, "output": 8192 } }, + "Qwen3.8-27B-UD-IQ3_XXS": { "reasoning": true, "name": "Qwen3.8 27B · 24k · vision — hybrid reasoner, quiet desktop only (~15 t/s, remote)", "attachment": true, "limit": { "context": 24576, "output": 8192 } }, + "gemma-4-26B-A4B-it-UD-IQ4_XS": { "name": "Gemma 4 26B · 24k · vision — quality generalist (~34 t/s, remote)", "attachment": true, "limit": { "context": 24576, "output": 4096 } }, + "gemma-4-E4B-it-UD-Q8_K_XL": { "name": "Gemma 4 E4B · 64k · vision — fast generalist, long docs (~57 t/s, remote)", "attachment": true, "limit": { "context": 65536, "output": 16384 } }, + "GLM-4.7-Flash-UD-Q4_K_XL": { "reasoning": true, "interleaved": "reasoning_content", "name": "GLM-4.7 Flash · 24k — quality coder (~21 t/s, remote)", "limit": { "context": 24576, "output": 8192 } }, + "GLM-4.7-Flash-UD-Q3_K_XL": { "reasoning": true, "interleaved": "reasoning_content", "name": "GLM-4.7 Flash Q3 · 24k — fast coder (~28 t/s, remote)", "limit": { "context": 24576, "output": 8192 } }, + "Ornith-1.5-35B-A3B-IQ3_XXS": { "reasoning": true, "name": "Ornith 1.5 35B · 32k · vision — agentic coder, thinking (~32 t/s, remote)", "attachment": true, "limit": { "context": 32768, "output": 8192 } }, + "gpt-oss-20b": { "reasoning": true, "name": "gpt-oss 20B · 64k — fast reasoning + tools (~38 t/s, remote)", "limit": { "context": 65536, "output": 8192 } }, + "gpt-oss-20b-low": { "reasoning": true, "name": "gpt-oss 20B low · 64k — snappy answers (~37 t/s, remote)", "limit": { "context": 65536, "output": 8192 } } + } + }, + "llama.cpp": { + "npm": "@ai-sdk/openai-compatible", + "name": "llamacpp", + "options": { + "baseURL": "http://192.168.0.204:11343/v1", + "timeout": 3600000 + }, + "models": { + "Qwen3-Coder-Next-UD-IQ3_XXS": { "name": "Qwen3 Coder Next 80B · 128k — long sessions (~16 t/s)", "limit": { "context": 131072, "output": 16384 } }, + "Qwen3-Coder-30B-Instruct-UD-Q3_K_XL": { "name": "Qwen3 Coder 30B · 32k — main agent coder (~30 t/s)", "limit": { "context": 32768, "output": 4096 } }, + "Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS": { "name": "Qwen3.6 35B · 24k · vision — daily driver (~36 t/s)", "attachment": true, "limit": { "context": 24576, "output": 8192 } }, + "Qwen3.6-35B-A3B-Thinking": { "reasoning": true, "name": "Qwen3.6 35B Thinking · 24k · vision — hard problems (~39 t/s)", "attachment": true, "limit": { "context": 24576, "output": 8192 } }, + "Qwen3.5-9B-UD-Q6_K_XL": { "reasoning": true, "name": "Qwen3.5 9B · 32k · vision — quick tasks (~32 t/s)", "attachment": true, "limit": { "context": 32768, "output": 8192 } }, + "Qwen3.8-27B-UD-IQ3_XXS": { "reasoning": true, "name": "Qwen3.8 27B · 24k · vision — hybrid reasoner, quiet desktop only (~15 t/s)", "attachment": true, "limit": { "context": 24576, "output": 8192 } }, + "gemma-4-26B-A4B-it-UD-IQ4_XS": { "name": "Gemma 4 26B · 24k · vision — quality generalist (~34 t/s)", "attachment": true, "limit": { "context": 24576, "output": 4096 } }, + "gemma-4-E4B-it-UD-Q8_K_XL": { "name": "Gemma 4 E4B · 64k · vision — fast generalist, long docs (~57 t/s)", "attachment": true, "limit": { "context": 65536, "output": 16384 } }, + "GLM-4.7-Flash-UD-Q4_K_XL": { "reasoning": true, "interleaved": "reasoning_content", "name": "GLM-4.7 Flash · 24k — quality coder (~21 t/s)", "limit": { "context": 24576, "output": 8192 } }, + "GLM-4.7-Flash-UD-Q3_K_XL": { "reasoning": true, "interleaved": "reasoning_content", "name": "GLM-4.7 Flash Q3 · 24k — fast coder (~28 t/s)", "limit": { "context": 24576, "output": 8192 } }, + "Ornith-1.5-35B-A3B-IQ3_XXS": { "reasoning": true, "name": "Ornith 1.5 35B · 32k · vision — agentic coder, thinking (~32 t/s)", "attachment": true, "limit": { "context": 32768, "output": 8192 } }, + "gpt-oss-20b": { "reasoning": true, "name": "gpt-oss 20B · 64k — fast reasoning + tools (~38 t/s)", "limit": { "context": 65536, "output": 8192 } }, + "gpt-oss-20b-low": { "reasoning": true, "name": "gpt-oss 20B low · 64k — snappy answers (~37 t/s)", "limit": { "context": 65536, "output": 8192 } } + } + } + }, + "agent": { + "plan": { + "mode": "primary", + "color": "info", + "steps": 30, + "model": "llama.cpp/Qwen3.6-35B-A3B-Thinking", + "permission": { + "edit": "deny" + } + }, + "build": { + "mode": "primary", + "color": "primary", + "steps": 30, + "model": "llama.cpp/Qwen3.6-35B-A3B-Thinking", + "permission": { + "edit": { + "*": "allow", + "**/.env*": "deny", + "**/*.env": "deny", + "**/*.pem": "deny", + "**/*.key": "deny", + "**/id_rsa*": "deny", + "**/.ssh/**": "deny", + "**/.aws/**": "deny", + "**/.git/**": "deny", + "**/.npmrc": "deny", + "**/.netrc": "deny" + } + } + }, + "auto": { + "description": "Auto mode: acts without asking; only irreversible or outward-facing actions ask", + "mode": "primary", + "color": "#f9e2af", + "steps": 30, + "model": "llama.cpp/Qwen3.6-35B-A3B-Thinking", + "permission": { + "edit": { + "*": "allow", + "**/.env*": "deny", + "**/*.env": "deny", + "**/*.pem": "deny", + "**/*.key": "deny", + "**/id_rsa*": "deny", + "**/.ssh/**": "deny", + "**/.aws/**": "deny", + "**/.git/**": "deny", + "**/.npmrc": "deny", + "**/.netrc": "deny" + }, + "webfetch": "allow", + "websearch": "allow", + "external_directory": "ask", + "question": "allow", + "bash": { + "*": "allow", + + "git *": "allow", + "git commit*": "ask", + "git push*": "ask", + "git reset*": "ask", + "git checkout*": "ask", + "git switch*": "ask", + "git restore*": "ask", + "git rebase*": "ask", + "git merge*": "ask", + "git cherry-pick*": "ask", + "git stash*": "ask", + "git clean*": "ask", + "git branch -*": "ask", + "git tag*": "ask", + "git remote add*": "ask", + "git remote remove*": "ask", + "git remote set-url*": "ask", + + "rm *": "ask", + "rmdir *": "ask", + "kill *": "ask", + "pkill *": "ask", + "killall *": "ask", + "systemctl *": "ask", + "curl *": "ask", + "wget *": "ask", + "ssh *": "ask", + "scp *": "ask", + "rsync *": "ask", + + "npm install*": "ask", + "npm i": "ask", + "npm i *": "ask", + "npm ci*": "ask", + "pnpm install*": "ask", + "pnpm i": "ask", + "pnpm i *": "ask", + "pnpm add*": "ask", + "yarn add*": "ask", + "yarn install*": "ask", + "pip install*": "ask", + "pip3 install*": "ask", + "pipx install*": "ask", + "cargo install*": "ask", + "go install*": "ask", + "gem install*": "ask", + "yay *": "ask", + + "sudo *": "deny", + "doas *": "deny", + "dd *": "deny", + "mkfs*": "deny", + "shred *": "deny", + "chmod -R *": "deny", + "rm -rf /*": "deny", + "rm -rf ~*": "deny", + + "cat .env*": "deny", + "cat *.env": "deny", + "cat *.pem": "deny", + "cat *.key": "deny", + "cat *id_rsa*": "deny", + "cat *secret*": "deny", + "cat *credential*": "deny", + "cat ~/.ssh/*": "deny", + "cat ~/.aws/*": "deny", + "grep .env*": "deny", + "grep * .env*": "deny" + } + } + } + } +} diff --git a/common/.config/opencode/plugins/agent-state.ts b/common/.config/opencode/plugins/agent-state.ts new file mode 100644 index 0000000..3e19b4a --- /dev/null +++ b/common/.config/opencode/plugins/agent-state.ts @@ -0,0 +1,53 @@ +// opencode agent-state plugin: mirrors the session state into the tmux pane opencode runs in via +// ~/.config/tmux/scripts/agent-state.sh (oc busy|done|input|error). No-op outside tmux. +// +// Runs in the SERVER process, so TMUX_PANE is only right when the TUI in the pane spawned the +// server (plain `opencode`), not for `opencode serve` / `opencode attach`. Under the bwrap +// `opencodes` wrapper the tmux socket dir must be bound in, or the script gives up quietly. +// Child (subagent) sessions are skipped so a subagent finishing does not flag "done". +import type { Plugin } from "@opencode-ai/plugin" + +export const AgentState: Plugin = async ({ client, $ }) => { + const script = `${process.env.HOME}/.config/tmux/scripts/agent-state.sh` + const set = async (state: string) => { + if (!process.env.TMUX_PANE) return + try { + await $`${script} oc ${state}`.quiet().nothrow() + } catch {} + } + const childCache = new Map() + const isChild = async (sessionID?: string) => { + if (!sessionID) return false + if (!childCache.has(sessionID)) { + try { + const r = await client.session.get({ path: { id: sessionID } }) + childCache.set(sessionID, Boolean(r.data?.parentID)) + } catch { + childCache.set(sessionID, false) + } + } + return childCache.get(sessionID) ?? false + } + return { + event: async ({ event }) => { + const p = (event as { properties?: Record }).properties ?? {} + switch (event.type) { + case "message.updated": // a new user message = a prompt went in + if (p.info?.role === "user" && !(await isChild(p.info?.sessionID))) await set("busy") + break + case "permission.asked": + if (!(await isChild(p.sessionID))) await set("input") + break + case "permission.replied": + if (!(await isChild(p.sessionID))) await set("busy") + break + case "session.idle": + if (!(await isChild(p.sessionID))) await set("done") + break + case "session.error": + if (!(await isChild(p.sessionID))) await set("error") + break + } + }, + } +} diff --git a/common/.config/opencode/plugins/verbose/server.ts b/common/.config/opencode/plugins/verbose/server.ts new file mode 100644 index 0000000..82e5a3f --- /dev/null +++ b/common/.config/opencode/plugins/verbose/server.ts @@ -0,0 +1,8 @@ +// opencode v2 plugin "coja.verbose" — server half. Intentionally empty: all behaviour is in ./tui.ts. +// A local plugin is a DIRECTORY under ~/.config/opencode/plugins/ whose `server`/`index` and `tui` +// modules are resolved by name (packages/plugin/src/host.ts resolve()). No imports on purpose: +// `define()` is an identity helper, and a dependency-free module needs no node_modules. +export default { + id: "coja.verbose", + setup() {}, +} diff --git a/common/.config/opencode/plugins/verbose/tui.ts b/common/.config/opencode/plugins/verbose/tui.ts new file mode 100644 index 0000000..6135d06 --- /dev/null +++ b/common/.config/opencode/plugins/verbose/tui.ts @@ -0,0 +1,62 @@ +// opencode v2 TUI plugin: one key toggles the "verbose view". +// +// v2 dropped the v1 tool-details / timestamps / generic-output toggles. The session view now has two +// display toggles that matter: thinking blocks (session.thinking show|hide) and exploration grouping +// (session.grouping auto|none — "auto" folds read/glob/grep tool calls into one collapsed group). +// Verbose = thinking expanded AND tool calls shown individually. Both settings persist in the TUI config. +// +// State is read from the built-in commands' live titles (the only plugin-visible signal): +// session.toggle.thinking → "Collapse thinking" while expanded, else "Expand thinking" +// session.toggle.exploration_grouping → "Show tool calls individually" while grouped, else "Group related tool calls" +// then only the toggles that differ from the target are dispatched, so a mixed state converges. +// +// Auto-discovered from ~/.config/opencode/plugins/verbose/ (server.ts + this file). Key configurable +// via plugin options; default v. Also /verbose and a command-palette entry. +const THINKING = "session.toggle.thinking" +const GROUPING = "session.toggle.exploration_grouping" + +type Command = { readonly id?: string; readonly title?: string } +type Context = { + readonly options?: Readonly> + readonly keymap: { + layer(input: () => { readonly commands?: readonly unknown[] }): void + dispatch(id: string, input?: string): void + commands(): readonly Command[] + } + readonly ui: { readonly toast: { show(o: { message: string; variant?: string; duration?: number }): void } } +} + +export default { + id: "coja.verbose", + setup(context: Context) { + const key = typeof context.options?.key === "string" && context.options.key ? (context.options.key as string) : "v" + const title = (id: string) => context.keymap.commands().find((c) => c.id === id)?.title ?? "" + + context.keymap.layer(() => ({ + commands: [ + { + id: "verbose.toggle", + title: "Toggle verbose view (expand thinking, ungroup tool calls)", + group: "Session", + bind: key, + palette: true, + slash: { name: "verbose" }, + run() { + const thinkingTitle = title(THINKING) + const groupingTitle = title(GROUPING) + if (!thinkingTitle && !groupingTitle) { + context.ui.toast.show({ message: "Verbose view: open a session first", variant: "warning", duration: 2000 }) + return + } + const thinkingVerbose = thinkingTitle.startsWith("Collapse") + const groupingVerbose = groupingTitle.startsWith("Group") + const on = !(thinkingVerbose && groupingVerbose) + if (thinkingTitle && thinkingVerbose !== on) context.keymap.dispatch(THINKING) + if (groupingTitle && groupingVerbose !== on) context.keymap.dispatch(GROUPING) + context.ui.toast.show({ message: on ? "Verbose view on" : "Verbose view off", variant: "info", duration: 1500 }) + }, + }, + ], + })) + }, +} diff --git a/common/.config/opencode/themes/catppuccin-mocha.json b/common/.config/opencode/themes/catppuccin-mocha.json new file mode 100644 index 0000000..9186009 --- /dev/null +++ b/common/.config/opencode/themes/catppuccin-mocha.json @@ -0,0 +1,262 @@ +{ + "defs": { + "mocha_rosewater": "#f5e0dc", + "mocha_flamingo": "#f2cdcd", + "mocha_pink": "#f5c2e7", + "mocha_mauve": "#cba6f7", + "mocha_red": "#f38ba8", + "mocha_maroon": "#eba0ac", + "mocha_peach": "#fab387", + "mocha_yellow": "#f9e2af", + "mocha_green": "#a6e3a1", + "mocha_teal": "#94e2d5", + "mocha_sky": "#89dceb", + "mocha_sapphire": "#74c7ec", + "mocha_blue": "#89b4fa", + "mocha_lavender": "#b4befe", + "mocha_text": "#cdd6f4", + "mocha_subtext1": "#bac2de", + "mocha_subtext0": "#a6adc8", + "mocha_overlay2": "#9399b2", + "mocha_overlay1": "#7f849c", + "mocha_overlay0": "#6c7086", + "mocha_surface2": "#585b70", + "mocha_surface1": "#45475a", + "mocha_surface0": "#313244", + "mocha_base": "#1e1e2e", + "mocha_mantle": "#181825", + "mocha_crust": "#11111b", + "mocha_diffAddBg": "#1e2b22", + "mocha_diffDelBg": "#2b1e22", + "latte_rosewater": "#dc8a78", + "latte_flamingo": "#dd7878", + "latte_pink": "#ea76cb", + "latte_mauve": "#8839ef", + "latte_red": "#d20f39", + "latte_maroon": "#e64553", + "latte_peach": "#fe640b", + "latte_yellow": "#df8e1d", + "latte_green": "#40a02b", + "latte_teal": "#179299", + "latte_sky": "#04a5e5", + "latte_sapphire": "#209fb5", + "latte_blue": "#1e66f5", + "latte_lavender": "#7287fd", + "latte_text": "#4c4f69", + "latte_subtext1": "#5c5f77", + "latte_subtext0": "#6c6f85", + "latte_overlay2": "#7c7f93", + "latte_overlay1": "#8c8fa1", + "latte_overlay0": "#9ca0b0", + "latte_surface2": "#acb0be", + "latte_surface1": "#bcc0cc", + "latte_surface0": "#ccd0da", + "latte_base": "#eff1f5", + "latte_mantle": "#e6e9ef", + "latte_crust": "#dce0e8", + "latte_diffAddBg": "#e4f3e6", + "latte_diffDelBg": "#f9e1e6" + }, + "theme": { + "primary": { + "dark": "mocha_mauve", + "light": "latte_mauve" + }, + "secondary": { + "dark": "mocha_blue", + "light": "latte_blue" + }, + "accent": { + "dark": "mocha_peach", + "light": "latte_peach" + }, + "error": { + "dark": "mocha_red", + "light": "latte_red" + }, + "warning": { + "dark": "mocha_yellow", + "light": "latte_yellow" + }, + "success": { + "dark": "mocha_green", + "light": "latte_green" + }, + "info": { + "dark": "mocha_sapphire", + "light": "latte_sapphire" + }, + "text": { + "dark": "mocha_text", + "light": "latte_text" + }, + "textMuted": { + "dark": "mocha_subtext0", + "light": "latte_subtext0" + }, + "background": { + "dark": "mocha_base", + "light": "latte_base" + }, + "backgroundPanel": { + "dark": "mocha_mantle", + "light": "latte_mantle" + }, + "backgroundElement": { + "dark": "mocha_surface0", + "light": "latte_surface0" + }, + "border": { + "dark": "mocha_surface1", + "light": "latte_surface1" + }, + "borderActive": { + "dark": "mocha_mauve", + "light": "latte_mauve" + }, + "borderSubtle": { + "dark": "mocha_surface0", + "light": "latte_surface0" + }, + "diffAdded": { + "dark": "mocha_green", + "light": "latte_green" + }, + "diffRemoved": { + "dark": "mocha_red", + "light": "latte_red" + }, + "diffContext": { + "dark": "mocha_overlay0", + "light": "latte_overlay0" + }, + "diffHunkHeader": { + "dark": "mocha_overlay1", + "light": "latte_overlay1" + }, + "diffHighlightAdded": { + "dark": "mocha_green", + "light": "latte_green" + }, + "diffHighlightRemoved": { + "dark": "mocha_red", + "light": "latte_red" + }, + "diffAddedBg": { + "dark": "mocha_diffAddBg", + "light": "latte_diffAddBg" + }, + "diffRemovedBg": { + "dark": "mocha_diffDelBg", + "light": "latte_diffDelBg" + }, + "diffContextBg": { + "dark": "mocha_base", + "light": "latte_base" + }, + "diffLineNumber": { + "dark": "mocha_overlay0", + "light": "latte_overlay0" + }, + "diffAddedLineNumberBg": { + "dark": "mocha_diffAddBg", + "light": "latte_diffAddBg" + }, + "diffRemovedLineNumberBg": { + "dark": "mocha_diffDelBg", + "light": "latte_diffDelBg" + }, + "markdownText": { + "dark": "mocha_text", + "light": "latte_text" + }, + "markdownHeading": { + "dark": "mocha_mauve", + "light": "latte_mauve" + }, + "markdownLink": { + "dark": "mocha_sapphire", + "light": "latte_sapphire" + }, + "markdownLinkText": { + "dark": "mocha_blue", + "light": "latte_blue" + }, + "markdownCode": { + "dark": "mocha_green", + "light": "latte_green" + }, + "markdownBlockQuote": { + "dark": "mocha_subtext0", + "light": "latte_subtext0" + }, + "markdownEmph": { + "dark": "mocha_yellow", + "light": "latte_yellow" + }, + "markdownStrong": { + "dark": "mocha_peach", + "light": "latte_peach" + }, + "markdownHorizontalRule": { + "dark": "mocha_surface1", + "light": "latte_surface1" + }, + "markdownListItem": { + "dark": "mocha_mauve", + "light": "latte_mauve" + }, + "markdownListEnumeration": { + "dark": "mocha_mauve", + "light": "latte_mauve" + }, + "markdownImage": { + "dark": "mocha_sapphire", + "light": "latte_sapphire" + }, + "markdownImageText": { + "dark": "mocha_blue", + "light": "latte_blue" + }, + "markdownCodeBlock": { + "dark": "mocha_text", + "light": "latte_text" + }, + "syntaxComment": { + "dark": "mocha_overlay0", + "light": "latte_overlay0" + }, + "syntaxKeyword": { + "dark": "mocha_mauve", + "light": "latte_mauve" + }, + "syntaxFunction": { + "dark": "mocha_blue", + "light": "latte_blue" + }, + "syntaxVariable": { + "dark": "mocha_text", + "light": "latte_text" + }, + "syntaxString": { + "dark": "mocha_green", + "light": "latte_green" + }, + "syntaxNumber": { + "dark": "mocha_peach", + "light": "latte_peach" + }, + "syntaxType": { + "dark": "mocha_yellow", + "light": "latte_yellow" + }, + "syntaxOperator": { + "dark": "mocha_sky", + "light": "latte_sky" + }, + "syntaxPunctuation": { + "dark": "mocha_overlay2", + "light": "latte_overlay2" + } + } +} diff --git a/common/.config/opencode/tui.json b/common/.config/opencode/tui.json new file mode 100644 index 0000000..04ecb48 --- /dev/null +++ b/common/.config/opencode/tui.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://opencode.ai/tui.json", + "theme": "lucent-orng", + "leader_timeout": 1500, + "diff_style": "stacked", + "cursor": { "style": "block", "blinking": false }, + "attention": { "enabled": true, "notifications": true, "sound": false }, + "keybinds": { + "prompt_stash": "p", + "prompt_stash_pop": "o", + "session_fork": "f", + "messages_last_user": "k", + "display_thinking": "i" + } +} diff --git a/common/.config/presenterm/config.yaml b/common/.config/presenterm/config.yaml new file mode 100644 index 0000000..75d3086 --- /dev/null +++ b/common/.config/presenterm/config.yaml @@ -0,0 +1,106 @@ +--- +# yaml-language-server: $schema=https://raw.githubusercontent.com/mfontanini/presenterm/master/config-file-schema.json +defaults: + # override the terminal font size when in windows or when using sixel. + terminal_font_size: 16 + + # the theme to use by default in every presentation unless overridden. + theme: dark + + # the image protocol to use. + image_protocol: kitty-local + +typst: + # the pixels per inch when rendering latex/typst formulas. + ppi: 300 + +mermaid: + # the scale parameter passed to the mermaid CLI (mmdc). + scale: 1 + +options: + # whether slides are automatically terminated when a slide title is found. + implicit_slide_ends: false + + # the prefix to use for commands. + command_prefix: "" + + # show all lists incrementally, by implicitly adding pauses in between elements. + incremental_lists: false + + # this option tells presenterm you don't care about extra parameters in + # presentation's front matter. This can be useful if you're trying to load a + # presentation made for another tool + strict_front_matter_parsing: true + + # whether to treat a thematic break as a slide end. + end_slide_shorthand: false + +snippet: + exec: + # enable code snippet execution. Use at your own risk! + enable: true + + exec_replace: + # enable code snippet automatic execution + replacing the snippet with its output. Use at your own risk! + enable: true + + render: + # the number of threads to use when rendering `+render` code snippets. + threads: 2 + +speaker_notes: + # The endpoint to listen for speaker note events. + listen_address: "127.0.0.1:59418" + + # The endpoint to publish speaker note events. + publish_address: "127.0.0.1:59418" + + # Whether to always publish speaker notes even when `--publish-speaker-notes` is not set. + always_publish: false + +bindings: + # the keys that cause the presentation to move forwards. + next: ["l", "j", "", "", "", " "] + + # the keys that cause the presentation to move forwards fast. + next_fast: ["n"] + + # the keys that cause the presentation to move backwards. + previous: ["h", "k", "", "", ""] + + # the keys that cause the presentation to move backwards fast + previous_fast: ["p"] + + # the key binding to jump to the first slide. + first_slide: ["gg"] + + # the key binding to jump to the last slide. + last_slide: ["G"] + + # the key binding to jump to a specific slide. + go_to_slide: ["G"] + + # the key binding to execute a piece of shell code. + execute_code: [""] + + # the key binding to reload the presentation. + reload: [""] + + # the key binding to toggle the slide index modal. + toggle_slide_index: [""] + + # the key binding to toggle the key bindings modal. + toggle_bindings: ["?"] + + # the key binding to close the currently open modal. + close_modal: [""] + + # the key binding to close the application. + exit: ["", "q"] + + # the key binding to suspend the application. + suspend: [""] + + # the key binding to skip all pauses in the current slide. + skip_pauses: ["s"] diff --git a/common/.config/pyradio/README.md b/common/.config/pyradio/README.md new file mode 100644 index 0000000..e0e06ec --- /dev/null +++ b/common/.config/pyradio/README.md @@ -0,0 +1,45 @@ +# PyRadio Setup + +This repository contains a custom configuration and station list for [PyRadio](https://github.com/coderholic/pyradio), a terminal-based radio player. + +## Kitty Music Session + +To get a full-screen, immersive music player experience, you can use a custom [Kitty terminal session](https://sw.kovidgoyal.net/kitty/sessions/). + +The configuration file `music.conf` (found in your kitty config directory) sets up a layout that includes: +- A `pyradio` terminal. +- A `cava` terminal for audio visualization. +- A `pipes-rs` terminal for some visual flair. + +### Launching the Session + +Use keybind `$mainMod + R` or run the following command to launch the music session: + +```bash +kitty --session ~/.config/kitty/music.conf +``` + +## Setup + +1. **Install PyRadio**: Ensure you have `pyradio` installed on your system. +2. **Configuration**: + * Copy the `config` file to your PyRadio configuration directory (usually `~/.config/pyradio/config`). + * Copy the `stations.csv` file to your PyRadio directory. +3. **Using Custom Stations**: + * PyRadio can be configured to use a custom stations file. Ensure your `config` points to the `stations.csv` provided here if you want to use this specific collection of stations. + +## Station Sources + +The stations in `stations.csv` are curated from various sources, often utilizing the [Radio Browser](https://www.radio-browser.info/) API. + +### About Radio Browser +[Radio Browser](https://www.radio-browser.info/) is a community-driven database of internet radio stations. It is a free, open-source project that provides a massive API for accessing thousands of radio streams worldwide. It's a great resource for discovering new music and finding niche genres that might not be available on mainstream services. + +## Alternatives to PyRadio + +If you are looking for other ways to listen to internet radio in the terminal or via other interfaces, consider these alternatives: + +* **[Web Radio Clients](https://www.radio-browser.info/users)**: Many users of Radio Browser utilize various web-based players or custom scripts that interface directly with the Radio Browser API. +* **[MPV (Command Line)](https://mpv.io/)**: Terminal player pyradio uses as a backend `mpv ` +* **[VLC (Command Line)](https://www.videolan.org/vlc/)**: You can play many radio streams directly from the terminal using `cvlc --play-and-exit `. + diff --git a/common/.config/pyradio/config b/common/.config/pyradio/config new file mode 100644 index 0000000..43b39f0 --- /dev/null +++ b/common/.config/pyradio/config @@ -0,0 +1,6 @@ +# PyRadio User Configuration File +# To get a full list of options execute: pyradio -pc +# or examine the file: /usr/lib/python3.13/site-packages/pyradio/config +# +theme = blue-by-boxer +use_transparency = True diff --git a/common/.config/pyradio/stations.csv b/common/.config/pyradio/stations.csv new file mode 100644 index 0000000..8d5b9bd --- /dev/null +++ b/common/.config/pyradio/stations.csv @@ -0,0 +1,61 @@ +Ambient Psychill [1.FM],http://strm112.1.fm/ambientpsy_mobile_mp3,, +Chilltrax,http://server1.chilltrax.com:9000/,, +Chillout [psyradio*fm],http://streamer.psyradio.org:8020/;listen.mp3,, +Chillout [Psyndora],http://cast.magicstreams.gr:9125/stream,, +Chillout (Groove Salad) [SomaFM],https://hls.somafm.com/hls/groovesalad/320k/program.m3u8,, +Groove Salad Classic (Early 2000s Ambient),https://somafm.com/gsclassic.pls,, +Ambient and Experimental [n5MD],https://somafm.com/n5md.pls,, +Suomisaundi [Caprice],http://79.120.77.11:8004/suomisaundi,, +Vaporwaves [SomaFM],https://somafm.com/vaporwaves.pls,, +Space Music [Synphaera],https://somafm.com/synphaera.pls,, +Downtempo (Secret Agent) [SomaFM],http://somafm.com/secretagent.pls,, +Dub Step (Beyond) [SomaFM],http://somafm.com/dubstep.pls,, +Dub Techno [Schizoid], http://94.130.113.214:8000/dubtechno,nocon, +Dubplate.fm,https://sc2.dubplate.fm/radio/8030/dnb/uhifi,, +Liquid funk [Caprice], http://79.111.119.111:9115/,, +Liquid funk,https://radiorecord.hostingradio.ru/liquidfunk96.aacp,, +Liqui Radio,https://stream-162.zeno.fm/ug59eq099yzuv?zs=zaqVusVSQuWMN3O5gnh8xA,, +Liquid DnB,http://95.47.244.172:8000/live,, +Acid Techno,https://radiorecord.hostingradio.ru/techno96.aacp,, +Dark Techno [Caprice],http://79.111.14.76:8000/darktechno,, +Deep Techno/House [1.FM],http://strm112.1.fm/deeptech_mobile_mp3,, +90s90s Techno,http://streams.90s90s.de/techno/mp3-192/radiode/,, +The Trip: [SomaFM],https://somafm.com/thetrip.pls,, +ToXoRs minimalRADIO,http://95.216.245.239:8000/stream/1/,, +Minimalradio.de,https://azurafallback.de:8010/320.mp3,, +Minimal [Technolovers],https://stream.technolovers.fm/minimal,, +Suomisaundi / Freeform Psytrance / Spugedelic Trance [Caprice],http://79.120.77.11:8000/suomisaundi,, +Psychedelic Secret,https://solid48.streamupsolutions.com/proxy/bglsokon?mp=/=stream,, +Full-on psytrance [Caprice],http://79.111.14.76:9019/,, +Magnathospere Morning,https://listen7.myradio24.com/magnatos,, +Psytrance [Psyndora],https://cast.magicstreams.gr/sc/psyndora/stream,, +Hirschmilch Psytrance,https://hirschmilch.de:7001/psytrance.mp3,, +Bluffphonica,http://bluffphonica.stream.laut.fm/bluffphonica?pl=m3u&t302=2024-09-17_23-09-40&uuid=ce6a1b0b-1654-4d08-afbc-31b028f8f23b,, +BOM Psytrance [1.FM],http://strm112.1.fm/psytrance_mobile_mp3,, +TL_Psytrance,https://stream.technolovers.fm/psytrance,, +Record Goa Psy,https://radiorecord.hostingradio.ru/goa96.aacp,, +Psytrance 24/7 [DMT FM],https://dc1.serverse.com/proxy/ywycfrxn/live,, +Trance [RadiOzora],http://trance.out.airtime.pro:8000/trance_a,, +Uplifting trance [Technolovers],https://0nlineradio.stream13.radiohost.de/technolovers-uplifting-trance,, +Uplift [RadioRecord],https://radiorecord.hostingradio.ru/uplift96.aacp,, +Alternative [BAGeL],https://ais-sa3.cdnstream1.com/2606_128.aac,, +Celtic (ThistleRadio) [SomaFM],http://somafm.com/thistle.pls,, +Commodore 64 Remixes [Slay],http://www.slayradio.org/tune_in.php/128kbps/listen.m3u,, +Covers [SomaFM],http://somafm.com/covers.pls,, +Indie Pop [SomaFM],http://somafm.com/indiepop130.pls,, +Jazz (Sonic Universe) [SomaFM],http://somafm.com/startstream=sonicuniverse.pls,, +Pop (PopTron) [SomaFM],http://somafm.com/poptron.pls,, +Pop/Rock/Urban (Frequence 3 - Paris),http://streams.frequence3.net/hd-mp3.m3u,, +Progressive (Tags Trance Trip) [SomaFM],http://somafm.com/tagstrance.pls,, +Public Radio (NPR National Public Radio Stream),https://npr-ice.streamguys1.com/live.mp3,, +Heavyweight Reggae,https://somafm.com/reggae.pls,, +Rock (Digitalis) [SomaFM],http://somafm.com/digitalis.pls,, +Metal Detector,https://somafm.com/metal.pls,, +JazzGroove,https://www.internet-radio.com/servers/tools/playlistgenerator/?u=http://199.180.72.2:8015/listen.pls?sid=1&t=.pls,, +Main Mix [Paradise],http://stream.radioparadise.com/aac-128,, +Mellow Mix [Paradise] ,http://stream.radioparadise.com/mellow-128,, +Rock Mix [Paradise],http://stream.radioparadise.com/rock-128,, +Eclectic Mix [Paradise],http://stream.radioparadise.com/eclectic-128,, +Echoes of Bluemars,http://streams.echoesofbluemars.org:8000/bluemars.m3u,, +Cryosleep [Echoes of Bluemars] ,http://streams.echoesofbluemars.org:8000/cryosleep.m3u,, +Voices from Within [Echoes of Bluemars],http://streams.echoesofbluemars.org:8000/voicesfromwithin.m3u,, diff --git a/common/.config/tmux/scripts/agent-next.sh b/common/.config/tmux/scripts/agent-next.sh new file mode 100755 index 0000000..7c1a902 --- /dev/null +++ b/common/.config/tmux/scripts/agent-next.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# agent-next.sh: switch to the next window (after the current one, wrapping) that holds an +# agent mark you have not looked at yet; with none left, fall back to any grey mark; with +# nothing marked, say so. Bound to prefix+Tab and to the » tap target in the status bar. +cur=$(tmux display -p '#{window_index}') +pick() { # $1 empty = unseen marks only, "any" = grey ones too + tmux list-panes -a -F '#{window_index} #{@agent} #{@agent_seen}' | + awk -v c="$cur" -v any="$1" ' + $2 != "" && $2 != "busy" && (any != "" || $3 == "") { if ($1 > c && !n) n = $1; if (!f) f = $1 } + END { if (n) print n; else if (f) print f }' +} +w=$(pick); [ -n "$w" ] || w=$(pick any) +if [ -n "$w" ]; then tmux select-window -t ":$w"; else tmux display-message "no agent waiting"; fi diff --git a/common/.config/tmux/scripts/agent-state.sh b/common/.config/tmux/scripts/agent-state.sh new file mode 100755 index 0000000..b12d762 --- /dev/null +++ b/common/.config/tmux/scripts/agent-state.sh @@ -0,0 +1,69 @@ +#!/bin/sh +# agent-state.sh +# +# Per-pane "what is the agent in this pane doing" for tmux, shared by every agent's hooks: +# Claude Code (claude/settings.json), codex (~/.codex/hooks.json), pi (agent-state.ts +# extension) and opencode (plugins/agent-state.ts). No-op outside tmux. +# +# Which pane: $TMUX_PANE when the agent runs in the pane itself (pi, opencode, codex). Claude +# Code sessions run in a worker the claude daemon pre-spawned ("claude bg-spare"), whose +# environment has no tmux variables, so for them the worker is found by walking up the parent +# chain to the pid registered in ~/.claude/sessions/.json, and the pane is the one whose +# title Claude set to that session's name ("✳ "). +# +# Pane options read by tmux.conf's @agent_badge: @agent (the state, drawn as ✓ ? ! after the +# window name; busy draws nothing), @agent_seen (set by tmux's pane-focus-in hook: the glyph +# loses its colour once you visit the pane and stays, grey, until the next prompt turns the +# state busy) and @agent_tool (only the termux notification title uses it). `off` unsets all. +# +# Phone-level notice only for a NEW mark on a pane that is not in view: termux-notification +# when the agent runs natively in termux, otherwise a BEL into the pane (tmux forwards the bell +# to the outer terminal; termux's default bell-character=vibrate buzzes, and the window gets +# tmux's bell flag). A state change on an already-marked pane (e.g. Claude's idle_prompt ~60s +# after Stop turning done into input) only swaps the glyph: no second buzz, seen stays as is. +command -v tmux >/dev/null 2>&1 || exit 0 +tool=$1 state=$2 pane=$TMUX_PANE +if [ -z "$pane" ]; then + p=$$ worker="" + for _ in 1 2 3 4 5 6 7 8; do + p=$(ps -o ppid= -p "$p" 2>/dev/null | tr -d ' ') + [ -n "$p" ] && [ "$p" != 1 ] || break + [ -f "$HOME/.claude/sessions/$p.json" ] && { worker=$p; break; } + done + [ -n "$worker" ] || exit 0 + name=$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1])).get("name",""))' \ + "$HOME/.claude/sessions/$worker.json" 2>/dev/null) + [ -n "$name" ] || exit 0 + pane=$(tmux list-panes -a -F '#{pane_id} #{pane_title}' 2>/dev/null | + awk -F'\t' -v n="$name" '$2==n || substr($2,length($2)-length(n))==" " n {print $1; exit}') + [ -n "$pane" ] || exit 0 +fi +if [ "$state" = off ]; then + for o in @agent @agent_seen @agent_tool; do tmux set -p -t "$pane" -u "$o" 2>/dev/null; done + exit 0 +fi +tmux set -p -t "$pane" @agent_tool "$tool" 2>/dev/null || exit 0 # no server reachable (sandbox): give up quietly +case $state in + busy) + tmux set -p -t "$pane" @agent busy + tmux set -p -t "$pane" -u @agent_seen 2>/dev/null + command -v termux-notification-remove >/dev/null 2>&1 && termux-notification-remove "agent-$pane" + ;; + *) + already=$(tmux show -pv -t "$pane" @agent 2>/dev/null) + tmux set -p -t "$pane" @agent "$state" + if [ "$(tmux display -p -t "$pane" '#{pane_active}#{window_active}')" = 11 ]; then + tmux set -p -t "$pane" @agent_seen 1 # in view: you saw it happen, so it starts out seen + exit 0 + fi + [ -n "$already" ] && [ "$already" != busy ] && exit 0 # glyph swapped on an existing mark + tmux set -p -t "$pane" -u @agent_seen 2>/dev/null + if command -v termux-notification >/dev/null 2>&1; then + termux-notification --id "agent-$pane" --title "$tool: $state" --content "${PWD##*/}" \ + --vibrate 200 --action "tmux select-pane -t $pane" + else + printf '\a' > "$(tmux display -p -t "$pane" '#{pane_tty}')" 2>/dev/null + fi + ;; +esac +exit 0 diff --git a/common/.config/tmux/scripts/metrics.sh b/common/.config/tmux/scripts/metrics.sh new file mode 100755 index 0000000..e9bc907 --- /dev/null +++ b/common/.config/tmux/scripts/metrics.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# metrics.sh full|compact — the status-right system segment in ONE process per refresh. +# (tmux used to spawn net dl, net ul, cpu, mem and temp as five separate #() jobs per tick.) +# Prints #[fg=…] style markers, which tmux honours inside #() output. +# full : net dl · net ul · cpu · mem · temp (temp vanishes when no sensor exists) +# compact : cpu · mem +# CPU and net are averaged over the interval since the PREVIOUS refresh: the /proc totals +# persist in $XDG_RUNTIME_DIR state files, so no sleeps and the value covers the whole +# status-interval. First run (no state yet) shows the since-boot average. Glyphs are Waybar's: +# cpu U+F035B, memory U+F0F86, thermometer U+F050F, download U+F019, upload U+F093. +mode=${1:-full} +rt="${XDG_RUNTIME_DIR:-/tmp}" + +cpu() { # utilisation % since the previous refresh + local st="$rt/tmux_cpu_stat" u n s i w rest idle tot v p_tot=0 p_idle=0 dt di + read -r _ u n s i w rest "$st" + dt=$((tot - p_tot)) + di=$((idle - p_idle)) + printf '\U000f035b ' + if [ "$dt" -le 0 ]; then printf -- '--%%'; else printf '%d%%' $(((100 * (dt - di) + dt / 2) / dt)); fi +} + +mem() { # used = MemTotal - MemAvailable + printf '\U000f0f86 ' + awk '/^MemTotal:/{t=$2} /^MemAvailable:/{a=$2} END{if(t>0)printf "%d%%",(t-a)*100/t; else printf "--%%"}' /proc/meminfo +} + +temp() { # CPU °C: a CPU-ish thermal zone, else a CPU hwmon chip, else the hottest zone; nothing if none + local cpu_zone="" any_zone="" hw="" d t ty f + for d in /sys/class/thermal/thermal_zone*/; do + [ -r "${d}temp" ] && [ -r "${d}type" ] || continue + t=$(<"${d}temp") + case $t in '' | *[!0-9]*) continue ;; esac + ty=$(<"${d}type"); ty=${ty,,} + case $ty in *x86_pkg_temp* | *coretemp* | *k10temp* | *tctl* | *cpu*) + if [ -z "$cpu_zone" ] || [ "$t" -gt "$cpu_zone" ]; then cpu_zone=$t; fi ;; + esac + if [ -z "$any_zone" ] || [ "$t" -gt "$any_zone" ]; then any_zone=$t; fi + done + if [ -z "$cpu_zone" ]; then + for d in /sys/class/hwmon/hwmon*/; do + [ -r "${d}name" ] || continue + case $(<"${d}name") in coretemp | k10temp | zenpower | cpu_thermal) + for f in "${d}"temp*_input; do + [ -r "$f" ] || continue + t=$(<"$f") + case $t in '' | *[!0-9]*) continue ;; esac + if [ -z "$hw" ] || [ "$t" -gt "$hw" ]; then hw=$t; fi + done ;; + esac + done + fi + t=${cpu_zone:-${hw:-$any_zone}} + [ -n "$t" ] || return 0 + printf '\U000f050f %d° ' $(((t + 500) / 1000)) +} + +human() { awk -v b="$1" 'BEGIN{ split("B K M G T", u, " "); i=1; + while (b >= 1024 && i < 5) { b /= 1024; i++ } + if (i == 1) printf "%d%s", b, u[i]; else printf "%.1f%s", b, u[i] }'; } + +net() { # sets dl/ul: bytes per second over all non-lo interfaces since the previous refresh + local ctr="$rt/tmux_net_ctr" now rx tx prx ptx pnow drx=0 dtx=0 dt=1 + now=$(date +%s.%N) + read -r rx tx < <(awk 'NR>2{gsub(/:/," "); if($1!="lo"){r+=$2; t+=$10}} END{print r+0, t+0}' /proc/net/dev) + if [ -r "$ctr" ]; then + read -r prx ptx pnow <"$ctr" + dt=$(awk -v a="$now" -v b="$pnow" 'BEGIN{d=a-b; print (d>0.05)?d:1}') + drx=$((rx - prx)); dtx=$((tx - ptx)) + [ "$drx" -lt 0 ] && drx=0 + [ "$dtx" -lt 0 ] && dtx=0 + fi + printf '%s %s %s\n' "$rx" "$tx" "$now" >"$ctr" + dl=$(human "$(awk -v x="$drx" -v d="$dt" 'BEGIN{printf "%d", x/d}')") + ul=$(human "$(awk -v x="$dtx" -v d="$dt" 'BEGIN{printf "%d", x/d}')") +} + +case $mode in + compact) + printf '#[fg=#89b4fa]%s #[fg=#94e2d5]%s' "$(cpu)" "$(mem)" + ;; + *) + net + printf '#[fg=#a6e3a1]\U0000f019 %s #[fg=#f9e2af]\U0000f093 %s #[fg=#89b4fa]%s #[fg=#94e2d5]%s #[fg=#fab387]%s' \ + "$dl" "$ul" "$(cpu)" "$(mem)" "$(temp)" + ;; +esac diff --git a/common/.config/tmux/tmux.conf b/common/.config/tmux/tmux.conf new file mode 100644 index 0000000..3627f8a --- /dev/null +++ b/common/.config/tmux/tmux.conf @@ -0,0 +1,204 @@ +# Forward modified keys (Shift/Ctrl/Alt+Enter) to apps like pi-coding-agent. +# Without this, tmux collapses them to a plain Enter. Requires tmux 3.5+ for csi-u. +set -g extended-keys on +set -g extended-keys-format csi-u +# termux reports xterm-256color: without RGB every #rrggbb below is approximated to the 256 +# palette on the phone, and without extkeys tmux never asks the terminal for Shift/Ctrl+Enter. +# (kitty is xterm-kitty, whose terminfo already carries both.) +set -as terminal-features 'xterm-256color:RGB:extkeys' +# Let apps wrap escape sequences in DCS tmux passthrough (Claude Code / pi notifications, +# Claude's progress bar) so they reach the outer terminal instead of being swallowed. +set -g allow-passthrough on + +# Mouse/touch reporting. Chiefly so the window list in the status bar is +# tappable — tmux binds MouseDown1Status to `switch-client -t =` out of the box, +# and status-format[1] below keeps the `range=window|…` markers that make each +# entry a hit target, so a tap on a tab switches to it with no extra binding. +# Wheel over the bar cycles windows; right-click a tab or the session name for +# tmux's built-in menus; tmux-menus (plugin below) puts the same menus on prefix+\, +# which a phone can tap through. +# +# The cost: drag-select now goes to tmux instead of kitty, so hold Shift when you +# want kitty's own selection. Scroll wheel enters copy-mode on the pane rather +# than kitty's scrollback, and a click focuses the pane under it. +set -g mouse on + +# Number windows (and panes) from 1 instead of 0 — easier to reach on the +# keyboard. renumber-windows keeps them gap-free when a window is closed. +set -g base-index 1 +setw -g pane-base-index 1 +set -g renumber-windows on + +# One long agent turn scrolls past tmux's default 2000 lines; resurrect captures pane +# contents from this buffer too. Applies to panes created after the change. +set -g history-limit 50000 + +# Copy-mode: vi keys, v/y like an editor. set-clipboard on pushes every copy — tmux's own and +# those apps inside make (nvim, pi) — over OSC 52 to the CLIENT terminal, so a yank on the +# phone lands on the phone and on kitty lands on the desktop, wherever the server runs. +setw -g mode-keys vi +bind -T copy-mode-vi v send -X begin-selection +bind -T copy-mode-vi y send -X copy-selection-and-cancel +set -s set-clipboard on + +# --- Session persistence (survives reboot) --------------------------------- +# resurrect: save/restore sessions, windows, panes, layout and working dirs +# (prefix + Ctrl-s to save, prefix + Ctrl-r to restore). +# continuum: auto-saves every 15 min and auto-restores when the tmux server +# starts, so sessions come back after a reboot. Both via tpm. +set -g @plugin 'tmux-plugins/tpm' +set -g @plugin 'tmux-plugins/tmux-resurrect' +set -g @plugin 'tmux-plugins/tmux-continuum' +# menus: tmux's context menus on prefix+\ (tappable; no right-click needed on a phone). +set -g @plugin 'jaclu/tmux-menus' + +# Also capture pane scrollback and restore running programs (nvim, …). +# nvim 'session' strategy restores via Session.vim when present, else plain nvim. +set -g @resurrect-capture-pane-contents 'on' +set -g @resurrect-strategy-nvim 'session' + +# Auto-restore the last saved environment on tmux server start. +set -g @continuum-restore 'on' + +# Auto-start a detached tmux server at login: continuum writes and enables a +# systemd --user unit (~/.config/systemd/user/tmux.service). With the restore +# option above, sessions are already back and waiting after a reboot+login. +set -g @continuum-boot 'on' + +# --- Status bar (Catppuccin Mocha, flat) ----------------------------------- +# Palette: bg #1e1e2e · surface #313244 · divider #45475a · muted #6c7086/#7f849c +# text #cdd6f4 · subtext #a6adc8 · accent(mauve) #cba6f7 +set -g status on +set -g status-position bottom # (also tmux's default) +set -g status-interval 5 # refresh clock + CPU every 5s +set -g status-justify left +set -g status-style "bg=default,fg=#cdd6f4" # transparent: no bar background +set -g status-left-length 40 +set -g status-right-length 100 + +# --- Mobile view ----------------------------------------------------------- +# status-left and status-right are re-evaluated per client on every draw, and +# #{client_width} is that client's own width — so in `auto` mode a phone attached +# to the same session as the desktop renders the compact bars while the desktop +# keeps the full ones, simultaneously and with no intervention. +# +# @status_mode is auto (per-client, by width) | full | compact, cycled with +# prefix+S. Rather than branch each bar three ways, the mode picks the width a +# client has to beat — 0 nothing can lose, 9999 nothing can win — so each +# decision below stays a single comparison. The 100 is the switch point: the full +# right segment is ~60 columns before the window list even starts. Set +# @status_mode without -g to scope an override to one session, so a grouped +# mobile session can sit on `compact` while the desktop session stays on `auto`. +# +# Each variant lives in its own option instead of inline because #{?a,b,c} splits +# its branches on commas and the styles are full of them (#[fg=…,bold]); option +# values are substituted after the ternary is parsed, so those commas are never +# seen as separators. +# +# NOTE: the comparisons MUST use #{e|>=:…}. Plain #{>=:…} compares as strings, so +# "144" >= "100" is false and every client would get the compact bar. +set -g @status_mode auto +set -g @status_cutoff "#{?#{==:#{@status_mode},full},0,#{?#{==:#{@status_mode},compact},9999,100}}" + +# Left: session name (mauve/bold) + thin divider. Compact clips the name to two +# characters — enough to tell sessions apart when every column counts. #{=2:…} +# takes a format NAME, so it's session_name here rather than the #S shorthand. +set -g @left_full " #[fg=#cba6f7,bold]#S #[fg=#45475a]│ " +set -g @left_compact " #[fg=#cba6f7,bold]#{=2:session_name} #[fg=#45475a]│ " +set -g status-left "#{?#{e|>=:#{client_width},#{E:@status_cutoff}},#{E:@left_full},#{E:@left_compact}}" + +# Middle: flat window list — inactive muted, active mauve/bold, 2-space gaps. +set -g window-status-separator " " +setw -g window-status-format "#[fg=#7f849c]#I#{P:#{E:@agent_badge}} #[fg=#6c7086]#W#[default]" +setw -g window-status-current-format "#[fg=#cba6f7,bold]#I #[fg=#cdd6f4,bold]#W" +setw -g window-status-activity-style "fg=#f9e2af" +# The agent-state bell flags the window (monitor-bell) so the outer terminal buzzes; tmux's +# default bell style is `reverse`, which painted the window entry — only the glyph gets colour. +setw -g window-status-bell-style default + +# Right: net dl/ul · cpu · mem · temp │ date │ clock. One #() job per refresh: metrics.sh +# prints the whole coloured segment (it was five separate scripts per tick). continuum +# prepends its invisible save hook to status-right (this block sits above the tpm `run` +# line, so the hook survives every reload). The hook lands ahead of the #{?} below, i.e. +# outside it, so it keeps running for every client regardless of which variant is drawn. +set -g @right_full "#(~/.config/tmux/scripts/metrics.sh full)#[fg=#45475a]│ #[fg=#a6adc8]%a %b %-d #[fg=#45475a]│ #[fg=#cba6f7,bold]%H:%M " + +# Compact: cpu + mem only. Net rates and the temp glyph go first (widest, least +# useful on a phone), then the date, then the clock — a phone shows its own. +set -g @right_compact "#(~/.config/tmux/scripts/metrics.sh compact) " + +set -g status-right "#{?#{e|>=:#{client_width},#{E:@status_cutoff}},#{E:@right_full},#{E:@right_compact}}" + +# Cycle auto -> compact -> full -> auto. Braces instead of nested quoted strings +# so the styles' commas and the inner if-shell don't need escaping. +bind S { + if -F '#{==:#{@status_mode},auto}' { + set -g @status_mode compact + display 'status bar: compact (forced)' + } { + if -F '#{==:#{@status_mode},compact}' { + set -g @status_mode full + display 'status bar: full (forced)' + } { + set -g @status_mode auto + display 'status bar: auto — switches at 100 columns' + } + } + refresh-client -S +} + +# Two rows: [0] drawn top-border rule · [1] the bar content. The rule doubles as +# the separator from the pane content above; tmux status height is whole rows, so +# one row above the content is the smallest gap that still shows a border. +# The rule is a literal run of ─ in @rule (300 columns; tmux clips it to the client +# width), so drawing it costs no process. +# status-format[1] is tmux 3.7's default content template (status-left/windows/right). +set -g status 2 +set -g @rule "────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────" +set -g status-format[0] "#[fg=#6c7086,bg=default]#{@rule}" +set -g status-format[1] "#[align=left range=left #{E:status-left-style}]#[push-default]#{T;=/#{status-left-length}:status-left}#[pop-default]#[norange default]#[list=on align=#{status-justify}]#[list=left-marker]<#[list=right-marker]>#[list=on]#{W:#[range=window|#{window_index} #{E:window-status-style}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-format}#[pop-default]#[norange default]#{?loop_last_flag,,#{E:window-status-separator}},#[range=window|#{window_index} list=focus #{?#{!=:#{E:window-status-current-style},default},#{E:window-status-current-style},#{E:window-status-style}}#{?#{&&:#{window_last_flag},#{!=:#{E:window-status-last-style},default}}, #{E:window-status-last-style},}#{?#{&&:#{window_bell_flag},#{!=:#{E:window-status-bell-style},default}}, #{E:window-status-bell-style},#{?#{&&:#{||:#{window_activity_flag},#{window_silence_flag}},#{!=:#{E:window-status-activity-style},default}}, #{E:window-status-activity-style},}}]#[push-default]#{T:window-status-current-format}#[pop-default]#[norange list=on default]#{?loop_last_flag,,#{E:window-status-separator}}}#[range=user|newwin] #[fg=#6c7086]+#[default] #[norange]#[range=user|agentnext] #[fg=#6c7086]»#[default] #[norange]#[nolist align=right range=right #{E:status-right-style}]#[push-default]#{T;=/#{status-right-length}:status-right}#[pop-default]#[norange default]" + +# The `+` appended to the window list above sits in a `range=user|newwin` +# marker. Per tmux(1), a user range triggers the same `Status` mouse key as a +# window range and exposes its argument in #{mouse_status_range} — window ranges +# report the literal string "window" — so one binding can serve both: click a +# tab to select it (tmux's stock behaviour, kept in the else branch), click the +# `+` to open a new window, click the `»` to jump to the next window with an agent +# mark (scripts/agent-next.sh, also prefix+Tab). Padded with spaces on both sides so +# each is a wide enough target to hit with a thumb. +bind -n MouseDown1Status { + if -F '#{==:#{mouse_status_range},newwin}' { + new-window + } { + if -F '#{==:#{mouse_status_range},agentnext}' { + run-shell '~/.config/tmux/scripts/agent-next.sh' + } { + switch-client -t = + } + } +} + +# Agent state per pane — set by ~/.config/tmux/scripts/agent-state.sh from the +# Claude Code / codex / pi / opencode hooks: @agent = busy|done|input|error. @agent_badge draws +# one glyph glued to the window number ("2✓ name") in the window list, the same for every tool: ✓ done (green), +# ? waiting for input (yellow), ! error (red); busy draws nothing. Visiting the pane only takes +# the colour away (pane-focus-in sets @agent_seen; needs focus-events): the glyph stays, grey, +# until the next prompt turns the state busy. prefix K clears every mark; prefix Tab (or the » +# in the bar) jumps to the next window with a mark, coloured ones first. A coloured glyph +# always means "this happened while you were not looking". +set -g @agent_badge "#{?#{==:#{@agent},done},#{?#{@agent_seen},#[fg=#6c7086],#[fg=#a6e3a1]}✓,#{?#{==:#{@agent},input},#{?#{@agent_seen},#[fg=#6c7086],#[fg=#f9e2af]}?,#{?#{==:#{@agent},error},#{?#{@agent_seen},#[fg=#6c7086],#[fg=#f38ba8]}!,}}}" +set -g focus-events on +set-hook -g pane-focus-in 'set -p @agent_seen 1' +bind Tab run-shell '~/.config/tmux/scripts/agent-next.sh' +bind K run-shell 'for p in $(tmux list-panes -a -F "##{pane_id}"); do tmux set -p -t $p -u @agent; tmux set -p -t $p -u @agent_seen; done' \; display-message "agent marks cleared" + +# Round out the theme so no default green leaks into borders/messages/modes. +set -g pane-border-style "fg=#313244" +set -g pane-active-border-style "fg=#cba6f7" +set -g message-style "bg=#313244,fg=#cdd6f4" +set -g message-command-style "bg=#313244,fg=#cdd6f4" +set -g mode-style "bg=#45475a,fg=#cdd6f4" +set -g clock-mode-colour "#cba6f7" + +# Initialize tpm — KEEP THIS LINE AT THE VERY BOTTOM of tmux.conf. +run '~/.config/tmux/plugins/tpm/tpm' diff --git a/common/.config/tuios/config.toml b/common/.config/tuios/config.toml new file mode 100644 index 0000000..e875091 --- /dev/null +++ b/common/.config/tuios/config.toml @@ -0,0 +1,242 @@ +# TUIOS Configuration File +# This file allows you to customize appearance and keybindings +# +# Configuration location: ~/.config/tuios/config.toml +# Documentation: https://github.com/Gaurav-Gosain/tuios +# For keybindings documentation, run: tuios keybinds list + +# ============================================================================ +# APPEARANCE SETTINGS +# ============================================================================ +# border_style: Window border style +# Options: rounded, normal, thick, double, hidden, block, ascii, +# outer-half-block, inner-half-block +# Default: rounded +# +# dockbar_position: Position of the dockbar +# Options: bottom, top, hidden +# Default: bottom +# +# hide_window_buttons: Hide window control buttons (minimize, maximize, close) +# Options: true, false +# Default: false +# +# scrollback_lines: Number of lines to keep in scrollback buffer +# Range: 100 to 1000000 +# Default: 10000 +# ============================================================================ + +[appearance] +border_style = 'rounded' +hide_window_buttons = false +scrollback_lines = 10000 +dockbar_position = 'bottom' +preferred_shell = '' +whichkey_position = '' +window_title_position = '' +hide_clock = false +animations_enabled = false +show_cpu = true +show_ram = true +confirm_quit = true +# shared_borders=true + +[keybindings] +leader_key = 'ctrl+b' +# leader_key = 'shift+space' + +[keybindings.window_management] +close_window = ['w', 'x'] +minimize_window = ['m'] +new_window = ['n'] +next_window = ['tab'] +prev_window = ['shift+tab'] +rename_window = ['r'] +restore_all = ['M'] +select_window_1 = ['1'] +select_window_2 = ['2'] +select_window_3 = ['3'] +select_window_4 = ['4'] +select_window_5 = ['5'] +select_window_6 = ['6'] +select_window_7 = ['7'] +select_window_8 = ['8'] +select_window_9 = ['9'] + +[keybindings.workspaces] +move_and_follow_1 = ['alt+shift+1'] +move_and_follow_2 = ['alt+shift+2'] +move_and_follow_3 = ['alt+shift+3'] +move_and_follow_4 = ['alt+shift+4'] +move_and_follow_5 = ['alt+shift+5'] +move_and_follow_6 = ['alt+shift+6'] +move_and_follow_7 = ['alt+shift+7'] +move_and_follow_8 = ['alt+shift+8'] +move_and_follow_9 = ['alt+shift+9'] +switch_workspace_1 = ['alt+1'] +switch_workspace_2 = ['alt+2'] +switch_workspace_3 = ['alt+3'] +switch_workspace_4 = ['alt+4'] +switch_workspace_5 = ['alt+5'] +switch_workspace_6 = ['alt+6'] +switch_workspace_7 = ['alt+7'] +switch_workspace_8 = ['alt+8'] +switch_workspace_9 = ['alt+9'] + +[keybindings.layout] +equalize_splits = ['='] +preselect_down = ['alt+j'] +preselect_left = ['alt+h'] +preselect_right = ['alt+l'] +preselect_up = ['alt+k'] +resize_height_grow = ['}', 'shift+]'] +resize_height_grow_top = [']'] +resize_height_shrink = ['{', 'shift+['] +resize_height_shrink_top = ['['] +resize_master_grow = ['>', 'shift+.'] +resize_master_grow_left = ['.'] +resize_master_shrink = ['<', 'shift+,'] +resize_master_shrink_left = [','] +rotate_split = ['R'] +snap_corner_1 = ['1'] +snap_corner_2 = ['2'] +snap_corner_3 = ['3'] +snap_corner_4 = ['4'] +snap_fullscreen = ['f'] +snap_left = ['h'] +snap_right = ['l'] +split_horizontal = ['-'] +split_vertical = ['|', '\'] +swap_down = ['J', 'ctrl+down'] +swap_left = ['H', 'ctrl+left'] +swap_right = ['L', 'ctrl+right'] +swap_up = ['K', 'ctrl+up'] +toggle_tiling = ['t'] +unsnap = ['u'] + +[keybindings.mode_control] +enter_terminal_mode = ['i', 'enter'] +enter_window_mode = ['esc', 'ctrl+z'] +quit = ['q'] +toggle_help = ['?'] + +[keybindings.system] + +[keybindings.navigation] +extend_down = ['shift+down'] +extend_left = ['shift+left'] +extend_right = ['shift+right'] +extend_up = ['shift+up'] +nav_down = ['down'] +nav_left = ['left'] +nav_right = ['right'] +nav_up = ['up'] + +[keybindings.restore_minimized] +restore_minimized_1 = ['shift+1', '!'] +restore_minimized_2 = ['shift+2', '@'] +restore_minimized_3 = ['shift+3', '#'] +restore_minimized_4 = ['shift+4', '$'] +restore_minimized_5 = ['shift+5', '%'] +restore_minimized_6 = ['shift+6', '^'] +restore_minimized_7 = ['shift+7', '&'] +restore_minimized_8 = ['shift+8', '*'] +restore_minimized_9 = ['shift+9', '('] + +[keybindings.prefix_mode] +prefix_close_window = ['x'] +prefix_debug = ['D'] +prefix_detach = ['d', 'esc'] +prefix_equalize_splits = ['='] +prefix_fullscreen = ['z'] +prefix_help = ['?'] +prefix_minimize = ['m'] +prefix_new_window = ['c'] +prefix_next_window = ['n', 'tab'] +prefix_prev_window = ['p', 'shift+tab'] +prefix_quit = ['q'] +prefix_rename_window = [',', 'r'] +prefix_rotate_split = ['R'] +prefix_select_0 = ['0'] +prefix_select_1 = ['1'] +prefix_select_2 = ['2'] +prefix_select_3 = ['3'] +prefix_select_4 = ['4'] +prefix_select_5 = ['5'] +prefix_select_6 = ['6'] +prefix_select_7 = ['7'] +prefix_select_8 = ['8'] +prefix_select_9 = ['9'] +prefix_selection = ['['] +prefix_split_horizontal = ['-'] +prefix_split_vertical = ['|', '\'] +prefix_tape = ['T'] +prefix_toggle_tiling = ['space'] +prefix_window = ['t'] +prefix_workspace = ['w'] + +[keybindings.window_prefix] +window_prefix_cancel = ['esc'] +window_prefix_close = ['x'] +window_prefix_new = ['n'] +window_prefix_next = ['tab'] +window_prefix_prev = ['shift+tab'] +window_prefix_rename = ['r'] +window_prefix_tiling = ['t'] + +[keybindings.minimize_prefix] +minimize_prefix_cancel = ['esc'] +minimize_prefix_focused = ['m'] +minimize_prefix_restore_1 = ['1'] +minimize_prefix_restore_2 = ['2'] +minimize_prefix_restore_3 = ['3'] +minimize_prefix_restore_4 = ['4'] +minimize_prefix_restore_5 = ['5'] +minimize_prefix_restore_6 = ['6'] +minimize_prefix_restore_7 = ['7'] +minimize_prefix_restore_8 = ['8'] +minimize_prefix_restore_9 = ['9'] +minimize_prefix_restore_all = ['M'] + +[keybindings.workspace_prefix] +workspace_prefix_cancel = ['esc'] +workspace_prefix_move_1 = ['!'] +workspace_prefix_move_2 = ['@'] +workspace_prefix_move_3 = ['#'] +workspace_prefix_move_4 = ['$'] +workspace_prefix_move_5 = ['%'] +workspace_prefix_move_6 = ['^'] +workspace_prefix_move_7 = ['&'] +workspace_prefix_move_8 = ['*'] +workspace_prefix_move_9 = ['('] +workspace_prefix_switch_1 = ['1'] +workspace_prefix_switch_2 = ['2'] +workspace_prefix_switch_3 = ['3'] +workspace_prefix_switch_4 = ['4'] +workspace_prefix_switch_5 = ['5'] +workspace_prefix_switch_6 = ['6'] +workspace_prefix_switch_7 = ['7'] +workspace_prefix_switch_8 = ['8'] +workspace_prefix_switch_9 = ['9'] + +[keybindings.debug_prefix] +debug_prefix_animations = ['a'] +debug_prefix_cache = ['c'] +debug_prefix_cancel = ['esc'] +debug_prefix_logs = ['l'] + +[keybindings.tape_prefix] +tape_prefix_cancel = ['esc'] +tape_prefix_manager = ['m'] +tape_prefix_record = ['r'] +tape_prefix_stop = ['s'] + +[keybindings.terminal_mode] +terminal_exit_mode = ['alt+esc'] +terminal_next_window = ['alt+n'] +terminal_prev_window = ['alt+p'] + +[daemon] +log_level = 'off' +default_codec = 'gob' +socket_path = '' diff --git a/common/.inputrc b/common/.inputrc new file mode 100644 index 0000000..a76b643 --- /dev/null +++ b/common/.inputrc @@ -0,0 +1,47 @@ +# Vi mode +set editing-mode vi +set show-mode-in-prompt on +set vi-ins-mode-string "\1\e[32m\2[I] \1\e[0m\2" +set vi-cmd-mode-string "\1\e[31m\2[N] \1\e[0m\2" + +# exclude .files +set match-hidden-files off + +set show-all-if-ambiguous on +set show-all-if-unmodified on +set colored-stats on +set colored-completion-prefix on +set mark-symlinked-directories on +set completion-ignore-case on + +# Ignore duplicates in history where supported +set skip-completed-text on + +# ----- insert mode: keep the emacs-style defaults ----- +# (no \e-prefixed binds here — they would delay ESC switching to normal mode) +set keymap vi-insert +"\C-a": beginning-of-line +"\C-e": end-of-line +"\C-b": backward-char +"\C-f": forward-char +"\C-p": previous-history +"\C-n": next-history +"\C-r": reverse-search-history +"\C-k": kill-line +"\C-u": unix-line-discard +"\C-w": unix-word-rubout + +# custom binds +"\C- ": shell-expand-line +"\C-x": glob-expand-word +"\C-g": "git diff\n" +"\C-y": "| ccze\n" +"\C-o": "\C-u yazi\n\C-u" +"\C-l": "\C-u clear -x && ls\n" + +# ----- normal (command) mode ----- +set keymap vi-command +"\C-l": clear-screen +"\C-a": beginning-of-line +"\C-e": end-of-line +"\C-r": reverse-search-history diff --git a/common/.pi/README.md b/common/.pi/README.md new file mode 100644 index 0000000..e4c9b1f --- /dev/null +++ b/common/.pi/README.md @@ -0,0 +1,232 @@ +# pi config (`~/.pi`) + +On-disk configuration for **[pi](https://github.com/earendil-works/pi)**, a TUI coding +agent (binary `/usr/bin/pi`). This tree lives in the dots repo and is surfaced into +`$HOME` by GNU Stow, so `~/.pi/agent/...` symlinks back here — **editing a file here +edits the live config**, no deploy step. + + +## Install / how it's surfaced + +pi reads everything under `$PI_CODING_AGENT_DIR` (default `~/.pi/agent`). Stow +symlinks each file individually (`--no-folding`): + +``` +~/.pi/agent/settings.json -> ~/.dots/common/.pi/agent/settings.json +~/.pi/agent/extensions/statusbar.ts -> ~/.dots/common/.pi/agent/extensions/statusbar.ts +... +``` + +- **Editing** an existing tracked file = editing live config immediately. +- **Adding** a new file (e.g. a new extension) is *not* live until you re-stow — + run `./install.sh` (or `stow --no-folding -R -d ~/.dots -t ~ common`) once to + create the symlink. +- After editing an extension, prompt, theme, or `keybindings.json`, run `/reload` + inside pi to apply without restarting. + +## What's in here + +| Path | Purpose | +|---|---| +| `agent/settings.json` | runtime settings (default model, theme, compaction, retry, timeouts) | +| `agent/models.json` | provider + model catalog (two OpenAI-compatible providers) | +| `agent/auth.json` | provider → credential map (references like `$DUSKADIY_API_KEY`, never literals). **Untracked** — copy `auth.json.example` on a new host | +| `agent/keybindings.json` | key remaps (each entry **replaces** the default for that action) | +| `agent/AGENTS.md` | global system instructions injected into every session | +| `agent/prompts/*.md` | custom `/slash` commands (prompt templates) | +| `agent/themes/*.json` | custom color themes | +| `agent/extensions/**` | auto-discovered TypeScript extensions (loaded via jiti, no build) | + +Runtime artifacts (`sessions/`, `npm/`, `git/`, `trust.json`) are gitignored. + +--- + +## Addons vs. stock pi + +Stock pi ships with **no extensions enabled, two built-in themes (`dark`/`light`), +default keybindings, and default settings**. Everything below is a deviation added +here. Each is independent — pull the ones you want and delete the rest. + +### Extensions + +pi **auto-discovers** every `.ts` under `extensions/`. So the universal "remove" +step is: **delete the file (or its folder) and `/reload`.** Toggle-able ones also +have a slash command to disable them for the current session without deleting. + +| Extension | What it adds | Origin | Remove | +|---|---|---|---| +| `statusbar.ts` | Replaces the footer with a Claude-Code-style status line (cwd, git branch, model, context %, decode t/s, token counts) in Nerd Font glyphs; adds a streaming pulse + a ≥80%-context warning widget | **custom** | delete file → default footer returns; or `/statusbar` to toggle off for the session | +| `vim-toggle.ts` | `/vim` — drops the modal editor for the rest of the session, and brings it back via `ctx.reload()`. Pairs with the **`pi-vim` package** (below), which registers no command of its own | **custom** | delete file → you lose the toggle, not the editor; remove the package to drop modal editing itself | +| `plan-mode/` | Read-only "plan" mode (disables edit/write, restricts bash) bound to **Shift+Tab**; `/plan` toggles, `--plan` starts in it, `/plan-done` clears a stuck progress checklist | **vendored** copy of pi's bundled `examples/extensions/plan-mode/`, rebound from upstream `Ctrl+Alt+P` | delete the folder **and** revert the `keybindings.json` `app.thinking.cycle` remap (see below) | +| `notify.ts` | Native terminal notification (OSC 777/99, Windows toast) when the agent goes idle | **verbatim** from pi's `examples/extensions/notify.ts` | delete file | +| `agent-state.ts` | Mirrors Pi's state (`agent_start` busy, `agent_settled` done, `ui_prompt_*` input, `session_shutdown` off) into the tmux pane it runs in via `~/.config/tmux/scripts/agent-state.sh`, for the status-bar agent badges; no-op outside tmux | own | delete file | +| `questionnaire.ts` | Interactive multi-question overlay the model can call as a tool | **near-verbatim** from pi's `examples/extensions/questionnaire.ts` (one-line fix) | delete file | +| `permission-gate.ts` | Prompts before dangerous `bash` commands (blocks outright with no UI). Local list covers git history rewrites, package managers, `systemctl` and irreversible disk ops on top of upstream's `rm -rf`/`sudo`/`chmod 777` | **adapted** from pi's `examples/extensions/permission-gate.ts` | delete file | +| `protected-paths.ts` | Blocks `write`/`edit` to secrets and repo plumbing (`secrets.fish`, `auth.json`, `.env`, `.ssh/`, `.git/`, …) | **adapted** from pi's `examples/extensions/protected-paths.ts` | delete file | +| `compaction-watch.ts` | Surfaces every compaction and its `reason`; on `overflow` (recovery rather than prevention) it reads the turn that caused it and says which kind it was, with numbers — a reply pi itself had clamped (`max_tokens` = window − estimate − 4096, the usual one on thinking models) or a prompt the server really rejected | **custom** | delete file | +| `verbose.ts` | `/verbose [on|off|status]` and **Alt+V** toggle the *persisted* verbose default (`hideThinkingBlock`, `showCacheMissNotices`) and report pi's live keys — `ctrl+o` tool output, `ctrl+t` thinking, which an extension cannot drive itself | **custom** | delete file; the live keys are built in and keep working | +| `confirm-destructive.ts` | Confirms before session clear / switch / fork | **verbatim** from pi's `examples/extensions/confirm-destructive.ts` | delete file | +| `session-name.ts` | `/session-name [name]` — friendly names in the session picker instead of the first message | **verbatim** from pi's `examples/extensions/session-name.ts` | delete file | +| `todo.ts` | A `todo` tool the model calls (add/toggle/list/clear) plus `/todos` to view it; state lives in tool results, so forking rewinds it correctly. Distinct from plan-mode's checklist | **verbatim** from pi's `examples/extensions/todo.ts` | delete file (it also adds a tool schema to every request) | + +> The bundled examples live under pi's install prefix, which moves: it was +> `/opt/pi-coding-agent/` before 0.85 and is `/usr/lib/pi-coding-agent/` on current Arch +> packages. Rather than hardcode either, resolve it — +> `set -l PI_ROOT (dirname (readlink -f (which pi)))` — and read `$PI_ROOT/examples/extensions/`. +> That's +> where `notify`/`questionnaire`/`plan-mode` came from. `plan-mode/` is now the only +> **fork** left, so it's the only one to re-pull after a pi upgrade before re-applying +> the local edits (its header documents them). `notify`/`questionnaire` carry no edits +> worth keeping — just re-copy them. The modal editor used to be a fork of +> `modal-editor.ts` too; it was replaced by the `pi-vim` package on 2026-08-05 and the +> fork deleted on 2026-08-09 — `git show c6566af^:common/.pi/agent/extensions/vim-editor.ts` +> brings it back if ever wanted. + +### Modal (vim) input — the `pi-vim` package + +Modal editing is **not** an extension in this tree any more; it's the npm package +[`pi-vim`](https://github.com/lajarre/pi-vim), pinned by `settings.json > packages` +and installed into the gitignored `agent/npm/`. That swap is the point: `pi update +npm:pi-vim` instead of re-pulling and re-patching a fork on every pi upgrade. + +Five modes (INSERT/NORMAL/VISUAL/V-LINE/EX) with the usual motions, operators, text +objects, undo and `.` repeat; the mode renders as a word label at the editor's +bottom-right, doubling as a pending-command display (` NORMAL 3d2w_ `). `:` dispatches +real pi commands and shells out with `:!`. No search (`/`, `?`, `n`), macros or +visual-block — upstream implements none of those. + +```fish +pi install npm:pi-vim +``` + +> ⚠️ **This pi build needs pi-vim's peer dep installed by hand.** pi ships as a +> Bun-compiled ELF with the `@earendil-works/*` packages *embedded*, not on disk. +> pi-vim's `clipboard-mirror.ts` calls `import.meta.resolve("@earendil-works/pi-coding-agent")` +> at **module top level**, so after a bare `pi install` the resolve throws and the whole +> extension fails to load with `Cannot find module '@earendil-works/pi-coding-agent'`. +> No setting avoids it — the call runs at import time. Once per host, matching +> `pi --version` exactly: +> +> ```fish +> cd ~/.pi/agent/npm +> fnm exec --using=22 -- npm install --save-exact \ +> "@earendil-works/pi-coding-agent@"(pi --version | string trim) +> ``` +> +> `pi install` deliberately doesn't pull peers (it would duplicate the runtime). Costs +> ~170 MB, and wants re-pinning after every pi upgrade — hence `--save-exact`, since a +> caret range would quietly drift off `pi --version`. + +Configured under `settings.json > piVim`: `modeColors` (theme tokens, not raw ANSI), +`borderSync` so the input border itself takes the mode color in NORMAL/VISUAL +(mauve/yellow) and is left to pi in INSERT/EX, `labelSync` so the label always carries +its mode color, and +`clipboardMirror: "yank"` — upstream's default `"all"` mirrors deletes too, so every +`dd`/`x` would clobber the OS clipboard. `exCommand.copyInputToClipboard` is left +**off**: it copies the composed prompt out, so upstream only honours it from the +user-global settings file. + +**Remove:** `pi remove npm:pi-vim`, and delete `agent/extensions/vim-toggle.ts` plus the +`piVim` block. `@burneikis/pi-vim` and `pi-vimmode` are alternatives that need no peer +install. + +### Theme + +`themes/catppuccin-mocha.json` is a **custom** theme (stock pi only bundles `dark` +and `light`). `settings.json` sets `"theme": "catppuccin-mocha"`. + +**Remove:** delete the file and set `"theme": "dark"` (or `"light"`) in +`settings.json`. + +### Custom slash commands (prompt templates) + +`prompts/commit.md` and `prompts/review.md` add `/commit` (writes a Conventional +Commits message for the staged diff, never commits) and `/review` (reviews the +working diff). Both are **custom**. Format is YAML frontmatter + body with +`${1:-default}` positional-arg substitution. + +**Remove:** delete the file(s). Stock pi has no `/commit` or `/review`. + +### Keybindings + +`keybindings.json` overrides three actions. **A user entry replaces the default keys +for that action — it does not merge.** Action ids and their stock defaults are in +`$PI_ROOT/docs/keybindings.md` (see above for `$PI_ROOT`). + +```jsonc +{ + "app.thinking.cycle": ["alt+t"], // moved OFF Shift+Tab so plan-mode can bind it (was ctrl+shift+t = kitty new_tab, never reached pi) + "tui.editor.cursorUp": ["up", "ctrl+p"], // adds Ctrl+P as up (Emacs-style) + "app.model.cycleForward": ["alt+p"] // Alt+P cycles models +} +``` + +The `app.thinking.cycle` remap is **coupled to `plan-mode`**: plan-mode binds +Shift+Tab, so the thinking-cycle default (also Shift+Tab) is moved aside to avoid a +collision. If you drop plan-mode, drop that line too. + +**Remove:** delete the whole file to restore all stock keybindings, or delete +individual lines to restore just those. + +### `settings.json` tunings + +Beyond pointing at local models, these values deviate from pi's defaults: + +| Key | Value here | Stock default | Why | +|---|---|---|---| +| `compaction.reserveTokens` | `8192` | 16384 | small local windows (24k–128k), but **≥ every model's `maxTokens` + 4096**: pi clamps each request's `max_tokens` to `contextWindow − estimate − 4096`, and with 24k/4096 that clamp starts exactly at this threshold (see CLAUDE.md for the `overflow` recoveries it can still produce) | +| `compaction.keepRecentTokens` | `4000` | 20000 | keep less verbatim, to pay for the larger reserve and leave room after a compaction for the next one | +| `npmCommand` | `fnm exec --using=22 -- npm` | `npm` | pin extension npm installs to Node 22 via fnm | +| `retry` / `httpIdleTimeoutMs` | long (1h provider timeout, 10m idle) | shorter | local models can be slow to first token | +| `defaultThinkingLevel` | `medium` | — | the default model is a thinking preset (`Qwen3.6-35B-A3B-Thinking`); Alt+T cycles it per session | +| `thinkingBudgets` | `512 / 1024 / 2048 / 3072` (minimal / low / medium / high) | 1024 / 2048 / 8192 / 16384 | per-request cap on the `` block, sent only for models whose `compat.thinkingTokenBudgetField` is set (`Ornith`, as `thinking_budget_tokens`). pi clamps the budget to `maxTokens − 1024`, so on a 4096-token reply the stock values collapse to 3072 and leave the answer 1024 tokens — the recipe for "Response was truncated before completion." | +| `packages` | `["npm:pi-vim"]` | `[]` | the modal editor — see the pi-vim section above | +| `piVim` | mode colors, border painted per mode (NORMAL/VISUAL), `clipboardMirror: "yank"`, `:` → pi bridge | — | package config, not a pi setting; ignored if the package is removed | +| `collapseChangelog` | `true` | `false` | condensed changelog after an upgrade instead of the full screen | + +**Remove:** delete each key to fall back to pi's default (or drop the whole +`compaction`/`retry` block). + +### Providers & models + +`models.json` + `auth.json` define **two OpenAI-compatible providers** serving the +same catalog of small self-hosted models (Qwen3-Coder-30B, Gemma 4, GLM-4.7-Flash, +gpt-oss-20b, …), all `cost: 0`: + +- **`localcpp`** — LAN llama.cpp server, `http://192.168.0.204:11343/v1`, no key. +- **`duskadiy`** — remote, `https://llm.duskadiy.com/api/v1`, key `$DUSKADIY_API_KEY`. + +This is the part you'd **replace**, not just delete, to point pi at your own backend: +edit `models.json` (baseUrl + model `id`s, keeping each `id` exactly matching your +server's model id and `contextWindow` matching its loaded `ctx-size`) and set the +matching credential in `auth.json`. `settings.json > enabledModels` is a glob +allowlist for the Ctrl+P picker; `defaultProvider`/`defaultModel` pick the startup +model. + +> **Secret hygiene:** `$DUSKADIY_API_KEY` lives in +> `.config/fish/conf.d/secrets.fish` (gitignored) and is only *referenced* in tracked +> config. `auth.json` is **not tracked** (gitignored as of 2026-08-08): pi's interactive +> `/login` rewrites it with the **literal** key, and a tracked copy would be one stray +> `/login` away from committing a real token. Bootstrap a new host with +> `cp auth.json.example auth.json`. The key itself lives in a shell file that is *not* +> tracked and *not* stowed, so it never reaches this repo — `conf.d/secrets.fish` for +> fish, `~/.bash_profile` for bash. + +--- + +## Replicating just one piece + +- **Just the status bar:** copy `agent/extensions/statusbar.ts` into your + `~/.pi/agent/extensions/`, re-stow/restart, `/reload`. Colors follow your active + theme automatically. Needs a Nerd Font terminal for the glyphs. +- **Just vim input:** `pi install npm:pi-vim`, then the peer-dep install above (this + build needs it), then `/reload`. Copy the `piVim` block from `settings.json` for the + same colors and clipboard behaviour, and `agent/extensions/vim-toggle.ts` if you want + `/vim` to toggle it. +- **Just plan mode:** copy `agent/extensions/plan-mode/` **and** add the + `app.thinking.cycle` remap to your `keybindings.json` (else Shift+Tab collides). +- **Just the theme:** copy `agent/themes/catppuccin-mocha.json`, set + `"theme": "catppuccin-mocha"`. +- **Just the slash commands:** copy `agent/prompts/commit.md` / `review.md`. + +Validate any JSON edit with `jq . agent/settings.json` (there's no build/test step). diff --git a/common/.pi/agent/auth.json.example b/common/.pi/agent/auth.json.example new file mode 100644 index 0000000..921f6ae --- /dev/null +++ b/common/.pi/agent/auth.json.example @@ -0,0 +1,10 @@ +{ + "localcpp": { + "type": "api_key", + "key": "no-key-required" + }, + "duskadiy": { + "type": "api_key", + "key": "$DUSKADIY_API_KEY" + } +} diff --git a/common/.pi/agent/extensions/.upstream-baseline b/common/.pi/agent/extensions/.upstream-baseline new file mode 100644 index 0000000..bf1564e --- /dev/null +++ b/common/.pi/agent/extensions/.upstream-baseline @@ -0,0 +1,12 @@ +# Upstream example files as last reviewed against pi 0.85.1. +# Written by pi-upgrade-check -a. A file is only re-raised when UPSTREAM moves, +# so our own local edits stop generating noise on every run. +55502f82109df07e922ef3ec41af1b1a5ed33d4d6d56076654ab2bc88e2e0888 confirm-destructive.ts +70e4333e09ce00d546c116fd2e918abf7616c70b5da6e88ba8ee21a326afd483 notify.ts +e32086ba9dd9b4ba0fd308b65241d9affa0b5ecd3f90ef7ea1b9f2b30cab8cc1 permission-gate.ts +9ca66b1f3b1b9a61cc5ddc660f92cca2ea66c4264a1bdb6b00e0da5844399fe2 protected-paths.ts +3f1f719d81152ff013f5d36a97cc3976388d43f2d89bff0f19827d3443d903e6 questionnaire.ts +a0b9fd94e2cc827931150cc409238b473da635ab1a1cddce633cae5937a3ae24 session-name.ts +e46824d00217e25242c186d41837cc84ca81b23f978500323448502a9a424ee2 todo.ts +90fae53e2fada97165f7488520bd54f3cbfe5d2c7e4cfd3bd2aa07ee796e61e8 plan-mode/index.ts +12ea28d57cc55e68e8d52a2f1d16df8b2e7f2749cd694d41453028002a2bdad9 plan-mode/utils.ts diff --git a/common/.pi/agent/extensions/agent-state.ts b/common/.pi/agent/extensions/agent-state.ts new file mode 100644 index 0000000..fe3df11 --- /dev/null +++ b/common/.pi/agent/extensions/agent-state.ts @@ -0,0 +1,26 @@ +/** + * Pi agent-state extension: mirrors Pi's state into the tmux pane it runs in via + * ~/.config/tmux/scripts/agent-state.sh (pi busy|done|input|off), so the tmux status bar + * shows which pane is done or waiting for you. The script is a no-op outside tmux. + */ +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { execFile } from "node:child_process"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +const SCRIPT = join(homedir(), ".config", "tmux", "scripts", "agent-state.sh"); + +function state(s: "busy" | "done" | "input" | "error" | "off"): void { + if (!process.env.TMUX_PANE) return; + execFile(SCRIPT, ["pi", s], () => {}); +} + +export default function (pi: ExtensionAPI) { + pi.on("agent_start", async () => state("busy")); + // agent_settled, not agent_end: Pi may still retry, compact, or run queued follow-ups. + pi.on("agent_settled", async () => state("done")); + // Blocking confirm/select prompts from extensions (permission-gate, confirm-destructive, questionnaire). + pi.on("ui_prompt_start", async () => state("input")); + pi.on("ui_prompt_end", async () => state("busy")); + pi.on("session_shutdown", async () => state("off")); +} diff --git a/common/.pi/agent/extensions/compaction-watch.ts b/common/.pi/agent/extensions/compaction-watch.ts new file mode 100644 index 0000000..0adab9c --- /dev/null +++ b/common/.pi/agent/extensions/compaction-watch.ts @@ -0,0 +1,120 @@ +/** + * Compaction Watch + * + * Compaction is otherwise silent, which is why "compacting fails a lot" took code + * reading and arithmetic to diagnose rather than a glance at a log. This makes it + * visible and, for the one reason that signals trouble, says WHICH trouble. + * + * pi reports a `reason` on every compaction: + * "manual" - you ran /compact + * "threshold" - the healthy path: contextTokens passed contextWindow - reserveTokens + * "overflow" - recovery, not prevention: the previous assistant turn ended badly, + * pi compacts and (when `willRetry`) re-runs that turn once + * + * Since pi 0.84.3 "overflow" covers TWO different situations, and the numbers on the + * last assistant message tell them apart (CLAUDE.md > Compaction tuning has the + * arithmetic for both): + * + * 1. A real overflow — the server rejected the prompt (stopReason "error" matching + * pi's overflow patterns), or reported more input than the declared window. + * Fix: contextWindow / reserveTokens / maxTokens are wrong for the model in use. + * 2. Truncated-reply recovery — the reply stopped with stopReason "length" while + * usage.output is BELOW the model's maxTokens. The request itself carried a smaller + * max_tokens: before every call pi-ai clamps it to + * `contextWindow − its own token estimate − 4096` (clampMaxTokensToContext, + * CONTEXT_SAFETY_TOKENS) and then shrinks the thinking budget so that only 1024 + * answer tokens remain. The window was never full. On a 24k window with maxTokens + * 4096 the clamp bites at any estimate above 16384 — the same number as the + * compaction threshold with reserveTokens 8192 — so it hits in the gaps the threshold + * check never sees: the first request after a compaction (no server usage to anchor + * on, so the system prompt and the tool schemas join the estimate) and the first call + * of a user turn (the new message). Thinking models feel it first: 2048 of thinking + * leaves a clamped reply about 1024 tokens of answer, and a `write` payload is cut. + * + * The old message here blamed every "overflow" on `reserveTokens < maxTokens`, which is + * wrong for case 2 — the one that actually shows up (Ornith, 2026-10-22). Now the + * notification names the case and prints the numbers (output vs maxTokens, context vs + * window, the estimate the clamp implies), so the next occurrence is diagnosable from the + * screen instead of from a session file. + * + * Note there is no event for a *failed* auto-compaction — `onError` exists only on the + * manual `ctx.compact()` call — so catching the overflow entry is the earliest reliable + * warning available. Observe-only: it never alters the compaction itself. + */ + +import type { AssistantMessage } from "@earendil-works/pi-ai"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +/** pi-ai's CONTEXT_SAFETY_TOKENS: the margin clampMaxTokensToContext keeps below the window. */ +const PI_CONTEXT_SAFETY_TOKENS = 4096; + +/** Last assistant message on the branch — the turn that triggered the recovery. */ +function lastAssistant(entries: readonly unknown[]): AssistantMessage | undefined { + for (let i = entries.length - 1; i >= 0; i--) { + const e = entries[i] as { type?: string; message?: { role?: string } }; + if (e.type === "message" && e.message?.role === "assistant") return e.message as AssistantMessage; + } + return undefined; +} + +/** One line saying which kind of "overflow" this is, with the numbers that prove it. */ +export function describeOverflow(last: AssistantMessage | undefined, window: number, maxTokens: number): string { + if (!last) return "no assistant message on the branch to inspect."; + const u = last.usage; + const output = u?.output ?? 0; + const context = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0) + output; + const ctxStr = window > 0 ? `${context}/${window}` : `${context}`; + const checkWindow = "check contextWindow against the server ctx-size (CLAUDE.md > Compaction tuning)."; + + if (last.stopReason === "error") { + return `the server rejected the request at context ${ctxStr} (${last.errorMessage ?? "no message"}) — a real overflow; ${checkWindow}`; + } + if (last.stopReason === "length") { + if (output === 0 && window > 0 && context >= window * 0.99) { + return `the server produced no tokens at context ${ctxStr} — the prompt alone filled the window; ${checkWindow}`; + } + if (window > 0 && context >= window - 64) { + return ( + `the server ran out of context mid-reply (${ctxStr}, output ${output}/${maxTokens}) — the prompt was ` + + `under-estimated (big tool results or images count more than chars ÷ 4); not a reserveTokens problem.` + ); + } + if (maxTokens > 0 && output < maxTokens) { + const estimate = window > 0 ? ` pi's estimate at request time ≈ ${window - PI_CONTEXT_SAFETY_TOKENS - output}, server-side context ${ctxStr}.` : ""; + return ( + `truncated-reply recovery, NOT a full window: the reply stopped at ${output} of ${maxTokens} max tokens, ` + + `so pi had clamped max_tokens to window − estimate − ${PI_CONTEXT_SAFETY_TOKENS}.${estimate} ` + + `reserveTokens is not the knob — see CLAUDE.md > Compaction tuning > max_tokens clamp.` + ); + } + } + return `stopReason ${last.stopReason}, context ${ctxStr}, output ${output}/${maxTokens} — input reported above the declared window; ${checkWindow}`; +} + +export default function (pi: ExtensionAPI) { + let overflowCount = 0; + + pi.on("session_before_compact", async (event, ctx) => { + if (!ctx.hasUI) return undefined; + + if (event.reason === "overflow") { + overflowCount++; + const model = ctx.model; + const verdict = describeOverflow(lastAssistant(event.branchEntries), model?.contextWindow ?? 0, model?.maxTokens ?? 0); + ctx.ui.notify(`Compacting in OVERFLOW recovery (#${overflowCount}) — ${verdict}`, "warning"); + } + + // Never alter the compaction itself — observe only. + return undefined; + }); + + pi.on("session_compact", async (event, ctx) => { + if (!ctx.hasUI) return; + + const reason = event.reason ?? "unknown"; + const retrying = event.willRetry ? ", retrying the aborted turn" : ""; + const level = reason === "overflow" ? "warning" : "info"; + + ctx.ui.notify(`Compacted (${reason}${retrying})`, level); + }); +} diff --git a/common/.pi/agent/extensions/confirm-destructive.ts b/common/.pi/agent/extensions/confirm-destructive.ts new file mode 100644 index 0000000..7d4201f --- /dev/null +++ b/common/.pi/agent/extensions/confirm-destructive.ts @@ -0,0 +1,59 @@ +/** + * Confirm Destructive Actions Extension + * + * Prompts for confirmation before destructive session actions (clear, switch, branch). + * Demonstrates how to cancel session events using the before_* events. + */ + +import type { ExtensionAPI, SessionBeforeSwitchEvent, SessionMessageEntry } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("session_before_switch", async (event: SessionBeforeSwitchEvent, ctx) => { + if (!ctx.hasUI) return; + + if (event.reason === "new") { + const confirmed = await ctx.ui.confirm( + "Clear session?", + "This will delete all messages in the current session.", + ); + + if (!confirmed) { + ctx.ui.notify("Clear cancelled", "info"); + return { cancel: true }; + } + return; + } + + // reason === "resume" - check if there are unsaved changes (messages since last assistant response) + const entries = ctx.sessionManager.getEntries(); + const hasUnsavedWork = entries.some( + (e): e is SessionMessageEntry => e.type === "message" && e.message.role === "user", + ); + + if (hasUnsavedWork) { + const confirmed = await ctx.ui.confirm( + "Switch session?", + "You have messages in the current session. Switch anyway?", + ); + + if (!confirmed) { + ctx.ui.notify("Switch cancelled", "info"); + return { cancel: true }; + } + } + }); + + pi.on("session_before_fork", async (event, ctx) => { + if (!ctx.hasUI) return; + + const choice = await ctx.ui.select(`Fork from entry ${event.entryId.slice(0, 8)}?`, [ + "Yes, create fork", + "No, stay in current session", + ]); + + if (choice !== "Yes, create fork") { + ctx.ui.notify("Fork cancelled", "info"); + return { cancel: true }; + } + }); +} diff --git a/common/.pi/agent/extensions/notify.ts b/common/.pi/agent/extensions/notify.ts new file mode 100644 index 0000000..9e91400 --- /dev/null +++ b/common/.pi/agent/extensions/notify.ts @@ -0,0 +1,57 @@ +/** + * Pi Notify Extension + * + * Sends a native terminal notification when Pi agent is done and waiting for input. + * Supports multiple terminal protocols: + * - OSC 777: Ghostty, iTerm2, WezTerm, rxvt-unicode + * - OSC 99: Kitty + * - Windows toast: Windows Terminal (WSL) + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +function windowsToastScript(title: string, body: string): string { + const type = "Windows.UI.Notifications"; + const mgr = `[${type}.ToastNotificationManager, ${type}, ContentType = WindowsRuntime]`; + const template = `[${type}.ToastTemplateType]::ToastText01`; + const toast = `[${type}.ToastNotification]::new($xml)`; + return [ + `${mgr} > $null`, + `$xml = [${type}.ToastNotificationManager]::GetTemplateContent(${template})`, + `$xml.GetElementsByTagName('text')[0].AppendChild($xml.CreateTextNode('${body}')) > $null`, + `[${type}.ToastNotificationManager]::CreateToastNotifier('${title}').Show(${toast})`, + ].join("; "); +} + +function notifyOSC777(title: string, body: string): void { + process.stdout.write(`\x1b]777;notify;${title};${body}\x07`); +} + +function notifyOSC99(title: string, body: string): void { + // Kitty OSC 99: i=notification id, d=0 means not done yet, p=body for second part + process.stdout.write(`\x1b]99;i=1:d=0;${title}\x1b\\`); + process.stdout.write(`\x1b]99;i=1:p=body;${body}\x1b\\`); +} + +function notifyWindows(title: string, body: string): void { + const { execFile } = require("child_process"); + execFile("powershell.exe", ["-NoProfile", "-Command", windowsToastScript(title, body)]); +} + +function notify(title: string, body: string): void { + if (process.env.WT_SESSION) { + notifyWindows(title, body); + } else if (process.env.KITTY_WINDOW_ID) { + notifyOSC99(title, body); + } else { + notifyOSC777(title, body); + } +} + +export default function (pi: ExtensionAPI) { + // `agent_end` fires after each low-level run; Pi may still retry, compact, + // or continue with queued follow-ups. Notify only after the full run settles. + pi.on("agent_settled", async () => { + notify("Pi", "Ready for input"); + }); +} diff --git a/common/.pi/agent/extensions/permission-gate.ts b/common/.pi/agent/extensions/permission-gate.ts new file mode 100644 index 0000000..d6ebc17 --- /dev/null +++ b/common/.pi/agent/extensions/permission-gate.ts @@ -0,0 +1,69 @@ +/** + * Permission Gate Extension + * + * Prompts for confirmation before running potentially dangerous bash commands. + * + * Adapted from pi's bundled `examples/extensions/permission-gate.ts`. Upstream checks + * three patterns (rm -rf, sudo, chmod/chown 777); the list below is extended to cover + * the rules AGENTS.md only *asks* for. That distinction is the whole point of running + * this: AGENTS.md is a prompt, and the small local models this config targets follow + * prompts unreliably. This is the enforcement half — the same trick plan-mode already + * uses when it disables edit/write outright. + * + * In the TUI a match prompts (so "Yes" still gets you through); with no UI it blocks. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + const dangerousPatterns = [ + // --- upstream --- + /\brm\s+(-rf?|--recursive)/i, + /\bsudo\b/i, + /\b(chmod|chown)\b.*777/i, + + // --- LOCAL: git history is the user's to write, never the agent's --- + // The standing rule is that commits and pushes are made by hand, after review. + /\bgit\s+(commit|push|revert)\b/i, + /\bgit\s+reset\s+--hard\b/i, + /\bgit\s+(rebase|cherry-pick)\b/i, + /\bgit\s+clean\s+-[a-z]*[fd]/i, + /\bgit\s+stash\s+(drop|clear|pop)\b/i, + /--force\b|--force-with-lease\b/i, + + // --- LOCAL: system-changing commands AGENTS.md rules out --- + /\b(pacman|yay|paru)\s+-[A-Za-z]*[SRU]/, + /\b(npm|pnpm|yarn)\s+(install|i|add|remove|uninstall)\b/i, + /\bpip3?\s+(install|uninstall)\b/i, + /\bcargo\s+(install|uninstall)\b/i, + /\bsystemctl\s+(start|stop|restart|enable|disable|mask)\b/i, + + // --- LOCAL: irreversible disk / process operations --- + /\bmkfs\b|\bdd\s+if=|\bshred\b|\bwipefs\b/i, + /\b(reboot|shutdown|poweroff|halt)\b/i, + /\b(killall|pkill)\b/i, + />\s*\/dev\/(sd|nvme|vd)/i, + ]; + + pi.on("tool_call", async (event, ctx) => { + if (event.toolName !== "bash") return undefined; + + const command = event.input.command as string; + const matched = dangerousPatterns.find((p) => p.test(command)); + + if (matched) { + if (!ctx.hasUI) { + // Non-interactive (`pi -p`): nothing can confirm, so refuse. + return { block: true, reason: "Dangerous command blocked (no UI for confirmation)" }; + } + + const choice = await ctx.ui.select(`⚠️ Dangerous command:\n\n ${command}\n\nAllow?`, ["Yes", "No"]); + + if (choice !== "Yes") { + return { block: true, reason: "Blocked by user" }; + } + } + + return undefined; + }); +} diff --git a/common/.pi/agent/extensions/plan-mode/README.md b/common/.pi/agent/extensions/plan-mode/README.md new file mode 100644 index 0000000..e0c30d8 --- /dev/null +++ b/common/.pi/agent/extensions/plan-mode/README.md @@ -0,0 +1,66 @@ +# Plan Mode Extension + +Read-only exploration mode for safe code analysis. + +## Features + +- **Built-in write tools disabled**: Disables edit/write while preserving other active tools +- **Bash allowlist**: Only read-only bash commands are allowed +- **Plan extraction**: Extracts numbered steps from `Plan:` sections +- **Progress tracking**: Widget shows completion status during execution +- **[DONE:n] markers**: Explicit step completion tracking +- **Session persistence**: State survives session resume + +## Commands + +- `/plan` - Toggle plan mode +- `/todos` - Show current plan progress +- `Shift+Tab` - Toggle plan mode (shortcut; this fork rebinds it from upstream's Ctrl+Alt+P) + +## Usage + +1. Enable plan mode with `/plan` or `--plan` flag +2. Ask the agent to analyze code and create a plan +3. The agent should output a numbered plan under a `Plan:` header: + +``` +Plan: +1. First step description +2. Second step description +3. Third step description +``` + +4. Choose "Execute the plan" when prompted +5. During execution, the agent marks steps complete with `[DONE:n]` tags +6. Progress widget shows completion status + +## How It Works + +### Plan Mode (Read-Only) +- Built-in edit/write tools disabled +- Other active tools remain available +- Bash commands filtered through allowlist +- Agent creates a plan without making changes + +### Execution Mode +- Full tool access restored +- Agent executes steps in order +- `[DONE:n]` markers track completion +- Widget shows progress + +### Command Allowlist + +Safe commands (allowed): +- File inspection: `cat`, `head`, `tail`, `less`, `more` +- Search: `grep`, `find`, `rg`, `fd` +- Directory: `ls`, `pwd`, `tree` +- Git read: `git status`, `git log`, `git diff`, `git branch` +- Package info: `npm list`, `npm outdated`, `yarn info` +- System info: `uname`, `whoami`, `date`, `uptime` + +Blocked commands: +- File modification: `rm`, `mv`, `cp`, `mkdir`, `touch` +- Git write: `git add`, `git commit`, `git push` +- Package install: `npm install`, `yarn add`, `pip install` +- System: `sudo`, `kill`, `reboot` +- Editors: `vim`, `nano`, `code` diff --git a/common/.pi/agent/extensions/plan-mode/index.ts b/common/.pi/agent/extensions/plan-mode/index.ts new file mode 100644 index 0000000..8b0d96b --- /dev/null +++ b/common/.pi/agent/extensions/plan-mode/index.ts @@ -0,0 +1,407 @@ +/** + * Plan Mode Extension + * + * Read-only exploration mode for safe code analysis. + * When enabled, built-in write tools are disabled. + * + * Features: + * - /plan command or Shift+Tab to toggle + * - Bash restricted to allowlisted read-only commands + * - Extracts numbered plan steps from "Plan:" sections + * - [DONE:n] markers to complete steps during execution + * - Progress tracking widget during execution + */ + +import type { AgentMessage } from "@earendil-works/pi-agent-core"; +import type { AssistantMessage, TextContent } from "@earendil-works/pi-ai"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { extractTodoItems, isSafeCommand, markCompletedSteps, type TodoItem } from "./utils.ts"; + +// Tools +const PLAN_MODE_TOOLS = ["read", "bash", "grep", "find", "ls", "questionnaire"]; +const NORMAL_MODE_TOOLS = ["read", "bash", "edit", "write"]; +const PLAN_MODE_DISABLED_TOOLS = new Set(["edit", "write"]); +const PLAN_MANAGED_TOOLS = new Set([...PLAN_MODE_TOOLS, ...NORMAL_MODE_TOOLS]); + +interface PlanModeState { + enabled: boolean; + todos?: TodoItem[]; + executing?: boolean; + toolsBeforePlanMode?: string[]; +} + +// Type guard for assistant messages +function isAssistantMessage(m: AgentMessage): m is AssistantMessage { + return m.role === "assistant" && Array.isArray(m.content); +} + +// Extract text content from an assistant message +function getTextContent(message: AssistantMessage): string { + return message.content + .filter((block): block is TextContent => block.type === "text") + .map((block) => block.text) + .join("\n"); +} + +export default function planModeExtension(pi: ExtensionAPI): void { + let planModeEnabled = false; + let executionMode = false; + let todoItems: TodoItem[] = []; + let toolsBeforePlanMode: string[] | undefined; + + pi.registerFlag("plan", { + description: "Start in plan mode (read-only exploration)", + type: "boolean", + default: false, + }); + + function updateStatus(ctx: ExtensionContext): void { + // Footer status + if (executionMode && todoItems.length > 0) { + const completed = todoItems.filter((t) => t.completed).length; + ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("accent", `📋 ${completed}/${todoItems.length}`)); + } else if (planModeEnabled) { + ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("warning", "⏸ plan")); + } else { + ctx.ui.setStatus("plan-mode", undefined); + } + + // Widget showing todo list + if (executionMode && todoItems.length > 0) { + const lines = todoItems.map((item) => { + if (item.completed) { + return ( + ctx.ui.theme.fg("success", "☑ ") + ctx.ui.theme.fg("muted", ctx.ui.theme.strikethrough(item.text)) + ); + } + return `${ctx.ui.theme.fg("muted", "☐ ")}${item.text}`; + }); + ctx.ui.setWidget("plan-todos", lines); + } else { + ctx.ui.setWidget("plan-todos", undefined); + } + } + + function uniqueToolNames(toolNames: string[]): string[] { + return [...new Set(toolNames)]; + } + + function getPlanModeTools(activeToolNames: string[]): string[] { + return uniqueToolNames([ + ...activeToolNames.filter((name) => !PLAN_MODE_DISABLED_TOOLS.has(name)), + ...PLAN_MODE_TOOLS, + ]); + } + + function getNormalModeTools(activeToolNames: string[]): string[] { + return uniqueToolNames([ + ...NORMAL_MODE_TOOLS, + ...activeToolNames.filter((name) => !PLAN_MANAGED_TOOLS.has(name)), + ]); + } + + function enablePlanModeTools(): void { + if (toolsBeforePlanMode === undefined) { + toolsBeforePlanMode = pi.getActiveTools(); + } + pi.setActiveTools(getPlanModeTools(toolsBeforePlanMode)); + } + + function restoreNormalModeTools(): void { + pi.setActiveTools(toolsBeforePlanMode ?? getNormalModeTools(pi.getActiveTools())); + toolsBeforePlanMode = undefined; + } + + function persistState(): void { + pi.appendEntry("plan-mode", { + enabled: planModeEnabled, + todos: todoItems, + executing: executionMode, + toolsBeforePlanMode, + }); + } + + function togglePlanMode(ctx: ExtensionContext): void { + planModeEnabled = !planModeEnabled; + executionMode = false; + todoItems = []; + + if (planModeEnabled) { + enablePlanModeTools(); + ctx.ui.notify("Plan mode enabled. Built-in write tools disabled."); + } else { + restoreNormalModeTools(); + ctx.ui.notify("Plan mode disabled. Full access restored."); + } + updateStatus(ctx); + persistState(); + } + + pi.registerCommand("plan", { + description: "Toggle plan mode (read-only exploration)", + handler: async (_args, ctx) => togglePlanMode(ctx), + }); + + // LOCAL EDIT: the checklist widget only tears itself down once every step is + // marked complete, which needs the model to emit a [DONE:n] tag per step. When + // one is missed the widget sticks around after the work is finished, so give + // the user a way out that doesn't involve toggling plan mode on and off again. + pi.registerCommand("plan-done", { + description: "Clear a stuck plan checklist (stops execution tracking)", + handler: async (_args, ctx) => { + if (!executionMode && todoItems.length === 0) { + ctx.ui.notify("No plan is being tracked."); + return; + } + executionMode = false; + todoItems = []; + updateStatus(ctx); + persistState(); + ctx.ui.notify("Plan tracking cleared."); + }, + }); + + pi.registerCommand("todos", { + description: "Show current plan todo list", + handler: async (_args, ctx) => { + if (todoItems.length === 0) { + ctx.ui.notify("No todos. Create a plan first with /plan", "info"); + return; + } + const list = todoItems.map((item, i) => `${i + 1}. ${item.completed ? "✓" : "○"} ${item.text}`).join("\n"); + ctx.ui.notify(`Plan Progress:\n${list}`, "info"); + }, + }); + + pi.registerShortcut("shift+tab", { + description: "Toggle plan mode", + handler: async (ctx) => togglePlanMode(ctx), + }); + + // Block destructive bash commands in plan mode + pi.on("tool_call", async (event) => { + if (!planModeEnabled || event.toolName !== "bash") return; + + const command = event.input.command as string; + if (!isSafeCommand(command)) { + return { + block: true, + reason: `Plan mode: command blocked (not allowlisted). Use /plan to disable plan mode first.\nCommand: ${command}`, + }; + } + }); + + // Filter out stale plan mode context when not in plan mode + pi.on("context", async (event) => { + if (planModeEnabled) return; + + return { + messages: event.messages.filter((m) => { + const msg = m as AgentMessage & { customType?: string }; + if (msg.customType === "plan-mode-context") return false; + if (msg.role !== "user") return true; + + const content = msg.content; + if (typeof content === "string") { + return !content.includes("[PLAN MODE ACTIVE]"); + } + if (Array.isArray(content)) { + return !content.some( + (c) => c.type === "text" && (c as TextContent).text?.includes("[PLAN MODE ACTIVE]"), + ); + } + return true; + }), + }; + }); + + // Inject plan/execution context before agent starts + pi.on("before_agent_start", async () => { + if (planModeEnabled) { + return { + message: { + customType: "plan-mode-context", + content: `[PLAN MODE ACTIVE] +You are in plan mode - a read-only exploration mode for safe code analysis. + +Restrictions: +- Built-in edit and write tools are disabled +- Other currently active tools remain available +- Bash is restricted to an allowlist of read-only commands + +Ask clarifying questions using the questionnaire tool. + +Create a detailed numbered plan under a "Plan:" header: + +Plan: +1. First step description +2. Second step description +... + +Do NOT attempt to make changes - just describe what you would do.`, + display: false, + }, + }; + } + + if (executionMode && todoItems.length > 0) { + const remaining = todoItems.filter((t) => !t.completed); + const todoList = remaining.map((t) => `${t.step}. ${t.text}`).join("\n"); + return { + message: { + customType: "plan-execution-context", + content: `[EXECUTING PLAN - Full tool access enabled] + +Remaining steps: +${todoList} + +Execute each step in order. +After completing a step, include a [DONE:n] tag in your response.`, + display: false, + }, + }; + } + }); + + // Track progress after each turn + pi.on("turn_end", async (event, ctx) => { + if (!executionMode || todoItems.length === 0) return; + if (!isAssistantMessage(event.message)) return; + + const text = getTextContent(event.message); + if (markCompletedSteps(text, todoItems) > 0) { + updateStatus(ctx); + } + persistState(); + }); + + // Handle plan completion and plan mode UI + pi.on("agent_end", async (event, ctx) => { + // Check if execution is complete + if (executionMode && todoItems.length > 0) { + if (todoItems.every((t) => t.completed)) { + const completedList = todoItems.map((t) => `~~${t.text}~~`).join("\n"); + pi.sendMessage( + { customType: "plan-complete", content: `**Plan Complete!** ✓\n\n${completedList}`, display: true }, + { triggerTurn: false }, + ); + executionMode = false; + todoItems = []; + updateStatus(ctx); + persistState(); // Save cleared state so resume doesn't restore old execution mode + } + return; + } + + if (!planModeEnabled || !ctx.hasUI) return; + + // Extract todos from last assistant message + const lastAssistant = [...event.messages].reverse().find(isAssistantMessage); + if (lastAssistant) { + const extracted = extractTodoItems(getTextContent(lastAssistant)); + if (extracted.length > 0) { + todoItems = extracted; + } + } + + if (todoItems.length === 0) return; + persistState(); + + // Show plan steps and prompt for next action + const todoListText = todoItems.map((t, i) => `${i + 1}. ☐ ${t.text}`).join("\n"); + const planTodoListMessage = { + customType: "plan-todo-list", + content: `**Plan Steps (${todoItems.length}):**\n\n${todoListText}`, + display: true, + }; + + const choice = await ctx.ui.select("Plan mode - what next?", [ + "Execute the plan (track progress)", + "Stay in plan mode", + "Refine the plan", + ]); + + if (choice?.startsWith("Execute")) { + const firstTodoItem = todoItems[0]; + if (!firstTodoItem) return; + + planModeEnabled = false; + executionMode = true; + restoreNormalModeTools(); + updateStatus(ctx); + persistState(); + + const remainingList = todoItems.map((t) => `${t.step}. ${t.text}`).join("\n"); + const execMessage = `Execute the plan. + +Remaining steps: +${remainingList} + +Start with: ${firstTodoItem.text} +After completing a step, include a [DONE:n] tag in your response.`; + pi.sendMessage(planTodoListMessage, { deliverAs: "followUp" }); + pi.sendMessage( + { customType: "plan-mode-execute", content: execMessage, display: true }, + { triggerTurn: true, deliverAs: "followUp" }, + ); + } else if (choice === "Refine the plan") { + const refinement = await ctx.ui.editor("Refine the plan:", ""); + if (refinement?.trim()) { + pi.sendMessage(planTodoListMessage, { deliverAs: "followUp" }); + pi.sendUserMessage(refinement.trim(), { deliverAs: "followUp" }); + } + } + }); + + // Restore state on session start/resume + pi.on("session_start", async (_event, ctx) => { + if (pi.getFlag("plan") === true) { + planModeEnabled = true; + } + + const entries = ctx.sessionManager.getEntries(); + + // Restore persisted state + const planModeEntry = entries + .filter((e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "plan-mode") + .pop() as { data?: PlanModeState } | undefined; + + if (planModeEntry?.data) { + planModeEnabled = planModeEntry.data.enabled ?? planModeEnabled; + todoItems = planModeEntry.data.todos ?? todoItems; + executionMode = planModeEntry.data.executing ?? executionMode; + toolsBeforePlanMode = planModeEntry.data.toolsBeforePlanMode ?? toolsBeforePlanMode; + } + + // On resume: re-scan messages to rebuild completion state + // Only scan messages AFTER the last "plan-mode-execute" to avoid picking up [DONE:n] from previous plans + const isResume = planModeEntry !== undefined; + if (isResume && executionMode && todoItems.length > 0) { + // Find the index of the last plan-mode-execute entry (marks when current execution started) + let executeIndex = -1; + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i] as { type: string; customType?: string }; + if (entry.customType === "plan-mode-execute") { + executeIndex = i; + break; + } + } + + // Only scan messages after the execute marker + const messages: AssistantMessage[] = []; + for (let i = executeIndex + 1; i < entries.length; i++) { + const entry = entries[i]; + if (entry.type === "message" && "message" in entry && isAssistantMessage(entry.message as AgentMessage)) { + messages.push(entry.message as AssistantMessage); + } + } + const allText = messages.map(getTextContent).join("\n"); + markCompletedSteps(allText, todoItems); + } + + if (planModeEnabled) { + enablePlanModeTools(); + } + updateStatus(ctx); + }); +} diff --git a/common/.pi/agent/extensions/plan-mode/utils.ts b/common/.pi/agent/extensions/plan-mode/utils.ts new file mode 100644 index 0000000..4db2223 --- /dev/null +++ b/common/.pi/agent/extensions/plan-mode/utils.ts @@ -0,0 +1,175 @@ +/** + * Pure utility functions for plan mode. + * Extracted for testability. + */ + +// Destructive commands blocked in plan mode +const DESTRUCTIVE_PATTERNS = [ + /\brm\b/i, + /\brmdir\b/i, + /\bmv\b/i, + /\bcp\b/i, + /\bmkdir\b/i, + /\btouch\b/i, + /\bchmod\b/i, + /\bchown\b/i, + /\bchgrp\b/i, + /\bln\b/i, + /\btee\b/i, + /\btruncate\b/i, + /\bdd\b/i, + /\bshred\b/i, + /(^|[^<])>(?!>)/, + />>/, + /\bnpm\s+(install|uninstall|update|ci|link|publish)/i, + /\byarn\s+(add|remove|install|publish)/i, + /\bpnpm\s+(add|remove|install|publish)/i, + /\bpip\s+(install|uninstall)/i, + /\bapt(-get)?\s+(install|remove|purge|update|upgrade)/i, + /\bbrew\s+(install|uninstall|upgrade)/i, + /\bgit\s+(add|commit|push|pull|merge|rebase|reset|checkout|branch\s+-[dD]|stash|cherry-pick|revert|tag|init|clone)/i, + /\bsudo\b/i, + /\bsu\b/i, + /\bkill\b/i, + /\bpkill\b/i, + /\bkillall\b/i, + /\breboot\b/i, + /\bshutdown\b/i, + /\bsystemctl\s+(start|stop|restart|enable|disable)/i, + /\bservice\s+\S+\s+(start|stop|restart)/i, + /\b(vim?|nano|emacs|code|subl)\b/i, +]; + +// Safe read-only commands allowed in plan mode +const SAFE_PATTERNS = [ + /^\s*cat\b/, + /^\s*head\b/, + /^\s*tail\b/, + /^\s*less\b/, + /^\s*more\b/, + /^\s*grep\b/, + /^\s*find\b/, + /^\s*ls\b/, + /^\s*pwd\b/, + /^\s*echo\b/, + /^\s*printf\b/, + /^\s*wc\b/, + /^\s*sort\b/, + /^\s*uniq\b/, + /^\s*diff\b/, + /^\s*file\b/, + /^\s*stat\b/, + /^\s*du\b/, + /^\s*df\b/, + /^\s*tree\b/, + /^\s*which\b/, + /^\s*whereis\b/, + /^\s*type\b/, + /^\s*env\b/, + /^\s*printenv\b/, + /^\s*uname\b/, + /^\s*whoami\b/, + /^\s*id\b/, + /^\s*date\b/, + /^\s*cal\b/, + /^\s*uptime\b/, + /^\s*ps\b/, + /^\s*top\b/, + /^\s*htop\b/, + /^\s*free\b/, + /^\s*git\s+(status|log|diff|show|branch|remote|config\s+--get)/i, + /^\s*git\s+ls-/i, + /^\s*npm\s+(list|ls|view|info|search|outdated|audit)/i, + /^\s*yarn\s+(list|info|why|audit)/i, + /^\s*node\s+--version/i, + /^\s*python\s+--version/i, + /^\s*curl\s/i, + /^\s*wget\s+-O\s*-/i, + /^\s*jq\b/, + /^\s*sed\s+-n/i, + /^\s*awk\b/, + /^\s*rg\b/, + /^\s*fd\b/, + /^\s*bat\b/, + /^\s*eza\b/, +]; + +export function isSafeCommand(command: string): boolean { + const isDestructive = DESTRUCTIVE_PATTERNS.some((p) => p.test(command)); + const isSafe = SAFE_PATTERNS.some((p) => p.test(command)); + return !isDestructive && isSafe; +} + +export interface TodoItem { + step: number; + text: string; + completed: boolean; +} + +export function cleanStepText(text: string): string { + let cleaned = text + .replace(/\*{1,2}([^*]+)\*{1,2}/g, "$1") // Remove bold/italic + .replace(/`([^`]+)`/g, "$1") // Remove code + .replace( + /^(Use|Run|Execute|Create|Write|Read|Check|Verify|Update|Modify|Add|Remove|Delete|Install)\s+(the\s+)?/i, + "", + ) + .replace(/\s+/g, " ") + .trim(); + + if (cleaned.length > 0) { + cleaned = cleaned.charAt(0).toUpperCase() + cleaned.slice(1); + } + if (cleaned.length > 50) { + cleaned = `${cleaned.slice(0, 47)}...`; + } + return cleaned; +} + +export function extractTodoItems(message: string): TodoItem[] { + const items: TodoItem[] = []; + const headerMatch = message.match(/\*{0,2}Plan:\*{0,2}\s*\n/i); + if (!headerMatch) return items; + + const planSection = message.slice(message.indexOf(headerMatch[0]) + headerMatch[0].length); + const numberedPattern = /^\s*(\d+)[.)]\s+\*{0,2}([^*\n]+)/gm; + + for (const match of planSection.matchAll(numberedPattern)) { + const text = match[2] + .trim() + .replace(/\*{1,2}$/, "") + .trim(); + if (text.length > 5 && !text.startsWith("`") && !text.startsWith("/") && !text.startsWith("-")) { + const cleaned = cleanStepText(text); + if (cleaned.length > 3) { + items.push({ step: items.length + 1, text: cleaned, completed: false }); + } + } + } + return items; +} + +export function extractDoneSteps(message: string): number[] { + const steps: number[] = []; + // LOCAL EDIT: upstream matched only the literal `[DONE:3]`. Small local models + // drift on it, and one missed tag pins the plan widget on screen forever, so + // also accept `[DONE 3]`, `[DONE-3]` and comma lists `[DONE:1,2]`. The brackets + // stay required on purpose: a bare "done 3" in prose must not mark a step. + for (const match of message.matchAll(/\[\s*DONE\s*[:\-=]?\s*([\d,\s]+?)\s*\]/gi)) { + for (const part of match[1].split(/[,\s]+/)) { + if (part === "") continue; + const step = Number(part); + if (Number.isFinite(step)) steps.push(step); + } + } + return steps; +} + +export function markCompletedSteps(text: string, items: TodoItem[]): number { + const doneSteps = extractDoneSteps(text); + for (const step of doneSteps) { + const item = items.find((t) => t.step === step); + if (item) item.completed = true; + } + return doneSteps.length; +} diff --git a/common/.pi/agent/extensions/protected-paths.ts b/common/.pi/agent/extensions/protected-paths.ts new file mode 100644 index 0000000..31121e0 --- /dev/null +++ b/common/.pi/agent/extensions/protected-paths.ts @@ -0,0 +1,58 @@ +/** + * Protected Paths Extension + * + * Blocks write and edit operations to protected paths. + * + * Adapted from pi's bundled `examples/extensions/protected-paths.ts`. Upstream ships a + * three-entry demo list (.env, .git/, node_modules/); the list below names the files + * that actually matter in this dotfiles tree — the ones holding secrets, and the git + * metadata the agent has no business rewriting. + * + * Scope, so this isn't over-trusted: it guards against the *model* calling write/edit. + * It cannot stop pi's own `/login`, which rewrites auth.json with the literal key — + * that is why auth.json is gitignored and auth.json.example is the tracked copy. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + const protectedPaths = [ + // Secrets. `secrets.fish` holds $DUSKADIY_API_KEY; auth.json is pi's own + // credential map and must keep $VAR references rather than literals. + "secrets.fish", + "auth.json", + ".env", + "fish_variables", + + // Credentials outside the repo. + ".ssh/", + ".gnupg/", + ".aws/", + ".netrc", + + // Repo plumbing and vendored trees — never hand-edited. + ".git/", + "node_modules/", + ]; + + pi.on("tool_call", async (event, ctx) => { + if (event.toolName !== "write" && event.toolName !== "edit") { + return undefined; + } + + const path = event.input.path as string; + // Substring match, like upstream: cheap, and these names are distinctive enough. + // Note `auth.json.example` is intentionally caught too — it is a tracked file + // whose whole job is to contain no secret, so an agent rewrite is worth a look. + const isProtected = protectedPaths.some((p) => path.includes(p)); + + if (isProtected) { + if (ctx.hasUI) { + ctx.ui.notify(`Blocked write to protected path: ${path}`, "warning"); + } + return { block: true, reason: `Path "${path}" is protected` }; + } + + return undefined; + }); +} diff --git a/common/.pi/agent/extensions/questionnaire.ts b/common/.pi/agent/extensions/questionnaire.ts new file mode 100644 index 0000000..9b2f307 --- /dev/null +++ b/common/.pi/agent/extensions/questionnaire.ts @@ -0,0 +1,449 @@ +/** + * Questionnaire Tool - Unified tool for asking single or multiple questions + * + * Single question: simple options list + * Multiple questions: tab bar navigation between questions + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { + Editor, + type EditorTheme, + Key, + matchesKey, + Text, + visibleWidth, + wrapTextWithAnsi, +} from "@earendil-works/pi-tui"; +import { Type } from "typebox"; + +// Types +interface QuestionOption { + value: string; + label: string; + description?: string; +} + +type RenderOption = QuestionOption & { isOther?: boolean }; + +interface Question { + id: string; + label: string; + prompt: string; + options: QuestionOption[]; + allowOther: boolean; +} + +interface Answer { + id: string; + value: string; + label: string; + wasCustom: boolean; + index?: number; +} + +interface QuestionnaireResult { + questions: Question[]; + answers: Answer[]; + cancelled: boolean; +} + +// Schema +const QuestionOptionSchema = Type.Object({ + value: Type.String({ description: "The value returned when selected" }), + label: Type.String({ description: "Display label for the option" }), + description: Type.Optional(Type.String({ description: "Optional description shown below label" })), +}); + +const QuestionSchema = Type.Object({ + id: Type.String({ description: "Unique identifier for this question" }), + label: Type.Optional( + Type.String({ + description: "Short contextual label for tab bar, e.g. 'Scope', 'Priority' (defaults to Q1, Q2)", + }), + ), + prompt: Type.String({ description: "The full question text to display" }), + options: Type.Array(QuestionOptionSchema, { description: "Available options to choose from" }), + allowOther: Type.Optional(Type.Boolean({ description: "Allow 'Type something' option (default: true)" })), +}); + +const QuestionnaireParams = Type.Object({ + questions: Type.Array(QuestionSchema, { description: "Questions to ask the user" }), +}); + +function errorResult( + message: string, + questions: Question[] = [], +): { content: { type: "text"; text: string }[]; details: QuestionnaireResult } { + return { + content: [{ type: "text", text: message }], + details: { questions, answers: [], cancelled: true }, + }; +} + +export default function questionnaire(pi: ExtensionAPI) { + pi.registerTool({ + name: "questionnaire", + label: "Questionnaire", + description: + "Ask the user one or more questions. Use for clarifying requirements, getting preferences, or confirming decisions. For single questions, shows a simple option list. For multiple questions, shows a tab-based interface.", + parameters: QuestionnaireParams, + + async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + if (ctx.mode !== "tui") { + return errorResult("Error: UI not available (running in non-interactive mode)"); + } + if (params.questions.length === 0) { + return errorResult("Error: No questions provided"); + } + + // Normalize questions with defaults + const questions: Question[] = params.questions.map((q, i) => ({ + ...q, + label: q.label || `Q${i + 1}`, + allowOther: q.allowOther !== false, + })); + + const isMulti = questions.length > 1; + const totalTabs = questions.length + 1; // questions + Submit + + const result = await ctx.ui.custom((tui, theme, _kb, done) => { + // State + let currentTab = 0; + let optionIndex = 0; + let inputMode = false; + let inputQuestionId: string | null = null; + let cachedLines: string[] | undefined; + const answers = new Map(); + + // Editor for "Type something" option + const editorTheme: EditorTheme = { + borderColor: (s) => theme.fg("accent", s), + selectList: { + selectedPrefix: (t) => theme.fg("accent", t), + selectedText: (t) => theme.fg("accent", t), + description: (t) => theme.fg("muted", t), + scrollInfo: (t) => theme.fg("dim", t), + noMatch: (t) => theme.fg("warning", t), + }, + }; + const editor = new Editor(tui, editorTheme); + + // Helpers + function refresh() { + cachedLines = undefined; + tui.requestRender(); + } + + function submit(cancelled: boolean) { + done({ questions, answers: Array.from(answers.values()), cancelled }); + } + + function currentQuestion(): Question | undefined { + return questions[currentTab]; + } + + function currentOptions(): RenderOption[] { + const q = currentQuestion(); + if (!q) return []; + const opts: RenderOption[] = [...q.options]; + if (q.allowOther) { + opts.push({ value: "__other__", label: "Type something.", isOther: true }); + } + return opts; + } + + function allAnswered(): boolean { + return questions.every((q) => answers.has(q.id)); + } + + function advanceAfterAnswer() { + if (!isMulti) { + submit(false); + return; + } + if (currentTab < questions.length - 1) { + currentTab++; + } else { + currentTab = questions.length; // Submit tab + } + optionIndex = 0; + refresh(); + } + + function saveAnswer(questionId: string, value: string, label: string, wasCustom: boolean, index?: number) { + answers.set(questionId, { id: questionId, value, label, wasCustom, index }); + } + + // Editor submit callback + editor.onSubmit = (value) => { + if (!inputQuestionId) return; + const trimmed = value.trim() || "(no response)"; + saveAnswer(inputQuestionId, trimmed, trimmed, true); + inputMode = false; + inputQuestionId = null; + editor.setText(""); + advanceAfterAnswer(); + }; + + function handleInput(data: string) { + // Input mode: route to editor + if (inputMode) { + if (matchesKey(data, Key.escape)) { + inputMode = false; + inputQuestionId = null; + editor.setText(""); + refresh(); + return; + } + editor.handleInput(data); + refresh(); + return; + } + + const q = currentQuestion(); + const opts = currentOptions(); + + // Tab navigation (multi-question only) + if (isMulti) { + if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) { + currentTab = (currentTab + 1) % totalTabs; + optionIndex = 0; + refresh(); + return; + } + if (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left)) { + currentTab = (currentTab - 1 + totalTabs) % totalTabs; + optionIndex = 0; + refresh(); + return; + } + } + + // Submit tab + if (currentTab === questions.length) { + if (matchesKey(data, Key.enter) && allAnswered()) { + submit(false); + } else if (matchesKey(data, Key.escape)) { + submit(true); + } + return; + } + + // Option navigation + if (matchesKey(data, Key.up)) { + optionIndex = Math.max(0, optionIndex - 1); + refresh(); + return; + } + if (matchesKey(data, Key.down)) { + optionIndex = Math.min(opts.length - 1, optionIndex + 1); + refresh(); + return; + } + + // Select option + if (matchesKey(data, Key.enter) && q) { + const opt = opts[optionIndex]; + if (!opt) return; // empty options with allowOther=false + if (opt.isOther) { + inputMode = true; + inputQuestionId = q.id; + editor.setText(""); + refresh(); + return; + } + saveAnswer(q.id, opt.value, opt.label, false, optionIndex + 1); + advanceAfterAnswer(); + return; + } + + // Cancel + if (matchesKey(data, Key.escape)) { + submit(true); + } + } + + function render(width: number): string[] { + if (cachedLines) return cachedLines; + + const lines: string[] = []; + const renderWidth = Math.max(1, width); + const q = currentQuestion(); + const opts = currentOptions(); + + function addWrapped(text: string) { + lines.push(...wrapTextWithAnsi(text, renderWidth)); + } + + function addWrappedWithPrefix(prefix: string, text: string) { + const prefixWidth = visibleWidth(prefix); + if (prefixWidth >= renderWidth) { + addWrapped(prefix + text); + return; + } + const wrapped = wrapTextWithAnsi(text, renderWidth - prefixWidth); + const continuationPrefix = " ".repeat(prefixWidth); + for (let i = 0; i < wrapped.length; i++) { + lines.push(`${i === 0 ? prefix : continuationPrefix}${wrapped[i]}`); + } + } + + lines.push(theme.fg("accent", "─".repeat(renderWidth))); + + // Tab bar (multi-question only) + if (isMulti) { + const tabs: string[] = ["← "]; + for (let i = 0; i < questions.length; i++) { + const isActive = i === currentTab; + const isAnswered = answers.has(questions[i].id); + const lbl = questions[i].label; + const box = isAnswered ? "■" : "□"; + const color = isAnswered ? "success" : "muted"; + const text = ` ${box} ${lbl} `; + const styled = isActive ? theme.bg("selectedBg", theme.fg("text", text)) : theme.fg(color, text); + tabs.push(`${styled} `); + } + const canSubmit = allAnswered(); + const isSubmitTab = currentTab === questions.length; + const submitText = " ✓ Submit "; + const submitStyled = isSubmitTab + ? theme.bg("selectedBg", theme.fg("text", submitText)) + : theme.fg(canSubmit ? "success" : "dim", submitText); + tabs.push(`${submitStyled} →`); + addWrappedWithPrefix(" ", tabs.join("")); + lines.push(""); + } + + // Helper to render options list + function renderOptions() { + for (let i = 0; i < opts.length; i++) { + const opt = opts[i]; + const selected = i === optionIndex; + const isOther = opt.isOther === true; + const prefix = selected ? theme.fg("accent", "> ") : " "; + const label = `${i + 1}. ${opt.label}${isOther && inputMode ? " ✎" : ""}`; + const color = selected || (isOther && inputMode) ? "accent" : "text"; + + addWrappedWithPrefix(prefix, theme.fg(color, label)); + if (opt.description) { + addWrappedWithPrefix(" ", theme.fg("muted", opt.description)); + } + } + } + + // Content + if (inputMode && q) { + addWrappedWithPrefix(" ", theme.fg("text", q.prompt)); + lines.push(""); + // Show options for reference + renderOptions(); + lines.push(""); + addWrappedWithPrefix(" ", theme.fg("muted", "Your answer:")); + for (const line of editor.render(Math.max(1, renderWidth - 2))) { + lines.push(` ${line}`); + } + lines.push(""); + addWrappedWithPrefix(" ", theme.fg("dim", "Enter to submit • Esc to cancel")); + } else if (currentTab === questions.length) { + addWrappedWithPrefix(" ", theme.fg("accent", theme.bold("Ready to submit"))); + lines.push(""); + for (const question of questions) { + const answer = answers.get(question.id); + if (answer) { + const prefix = answer.wasCustom ? "(wrote) " : ""; + const summary = `${theme.fg("muted", `${question.label}: `)}${theme.fg("text", prefix + answer.label)}`; + addWrappedWithPrefix(" ", summary); + } + } + lines.push(""); + if (allAnswered()) { + addWrappedWithPrefix(" ", theme.fg("success", "Press Enter to submit")); + } else { + const missing = questions + .filter((q) => !answers.has(q.id)) + .map((q) => q.label) + .join(", "); + addWrappedWithPrefix(" ", theme.fg("warning", `Unanswered: ${missing}`)); + } + } else if (q) { + addWrappedWithPrefix(" ", theme.fg("text", q.prompt)); + lines.push(""); + renderOptions(); + } + + lines.push(""); + if (!inputMode) { + const help = isMulti + ? "Tab/←→ navigate • ↑↓ select • Enter confirm • Esc cancel" + : "↑↓ navigate • Enter select • Esc cancel"; + addWrappedWithPrefix(" ", theme.fg("dim", help)); + } + lines.push(theme.fg("accent", "─".repeat(renderWidth))); + + cachedLines = lines; + return lines; + } + + return { + render, + invalidate: () => { + cachedLines = undefined; + }, + handleInput, + }; + }); + + if (result.cancelled) { + return { + content: [{ type: "text", text: "User cancelled the questionnaire" }], + details: result, + }; + } + + const answerLines = result.answers.map((a) => { + const qLabel = questions.find((q) => q.id === a.id)?.label || a.id; + if (a.wasCustom) { + return `${qLabel}: user wrote: ${a.label}`; + } + return `${qLabel}: user selected: ${a.index}. ${a.label}`; + }); + + return { + content: [{ type: "text", text: answerLines.join("\n") }], + details: result, + }; + }, + + renderCall(args, theme, _context) { + const qs = (args.questions as Question[]) || []; + const count = qs.length; + const labels = qs.map((q) => q.label || q.id).join(", "); + let text = theme.fg("toolTitle", theme.bold("questionnaire ")); + text += theme.fg("muted", `${count} question${count !== 1 ? "s" : ""}`); + if (labels) { + text += theme.fg("dim", ` (${labels})`); + } + return new Text(text, 0, 0); + }, + + renderResult(result, _options, theme, _context) { + const details = result.details as QuestionnaireResult | undefined; + if (!details) { + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "", 0, 0); + } + if (details.cancelled) { + return new Text(theme.fg("warning", "Cancelled"), 0, 0); + } + const lines = details.answers.map((a) => { + if (a.wasCustom) { + return `${theme.fg("success", "✓ ")}${theme.fg("accent", a.id)}: ${theme.fg("muted", "(wrote) ")}${a.label}`; + } + const display = a.index ? `${a.index}. ${a.label}` : a.label; + return `${theme.fg("success", "✓ ")}${theme.fg("accent", a.id)}: ${display}`; + }); + return new Text(lines.join("\n"), 0, 0); + }, + }); +} diff --git a/common/.pi/agent/extensions/session-name.ts b/common/.pi/agent/extensions/session-name.ts new file mode 100644 index 0000000..48203de --- /dev/null +++ b/common/.pi/agent/extensions/session-name.ts @@ -0,0 +1,27 @@ +/** + * Session naming example. + * + * Shows setSessionName/getSessionName to give sessions friendly names + * that appear in the session selector instead of the first message. + * + * Usage: /session-name [name] - set or show session name + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("session-name", { + description: "Set or show session name (usage: /session-name [new name])", + handler: async (args, ctx) => { + const name = args.trim(); + + if (name) { + pi.setSessionName(name); + ctx.ui.notify(`Session named: ${name}`, "info"); + } else { + const current = pi.getSessionName(); + ctx.ui.notify(current ? `Session: ${current}` : "No session name set", "info"); + } + }, + }); +} diff --git a/common/.pi/agent/extensions/statusbar.ts b/common/.pi/agent/extensions/statusbar.ts new file mode 100644 index 0000000..3394f34 --- /dev/null +++ b/common/.pi/agent/extensions/statusbar.ts @@ -0,0 +1,394 @@ +/** + * Pi status bar (custom footer) + * + * Replaces pi's default footer via `ctx.ui.setFooter()`. It mirrors the layout + * and *meaning* of the Claude Code status line (`~/.config/claude/statusline.py`), + * but swaps the emoji for Nerd Font glyphs — the same Material Design set already + * used across tmux (waybar cpu/mem/net glyphs) and nvim — so it reads natively in + * kitty (CaskaydiaCove Nerd Font Mono). Colors come from the active pi theme + * (catppuccin-mocha), not hard-coded ANSI. + * + * Segments render left → right and truncate at the terminal edge, so the most + * useful info stays visible on a narrow pane. Each icon echoes the Claude emoji + * it replaces: + * + * 󰉋 dir cwd, ~-collapsed (Claude 📁) U+F024B nf-md-folder + * 󰘬 git current branch (only inside a repo) (Claude 🌿) U+F062C nf-md-source_branch + * 󰚩 model model id + · thinking level (Claude 🤖) U+F06A9 nf-md-robot + * 󰈚 context % of context window used (+ tokens) (Claude 📝) U+F021A nf-md-text_box + * 󰓅 t/s last response's decode throughput U+F04C5 nf-md-speedometer + * (llama.cpp's own server-side number + dim ` pp N` prompt-processing + * speed when the final SSE chunk carries `timings`; otherwise the + * client-side clock -- see "server-side timings" below) + * ↑ ↓ tokens session prompt / output tokens (Claude 🔢) plain arrows + * (prompt = input + cache read + cache write: everything the server + * processed, matching the Claude bar — llama.cpp reports a cached + * prefix as cacheRead, so bare usage.input is a few dozen tokens) + * + * git, context, t/s and tokens only appear once there is data for them (i.e. after + * the first response, and git only inside a git repo). Extension statuses (e.g. + * plan-mode's "⏸ plan") are preserved at the far left. The Claude bar's system row + * (RAM/CPU/temp/disk) is intentionally omitted — that data isn't in the footer API, + * and the tmux bar below pi already shows cpu/mem/net. + * + * Two extras beyond the footer line: + * - a themed pulse working-indicator (the spinner shown while pi streams), and + * - a 󰀪 context-budget warning widget above the editor once the window passes + * 80% full, nudging a /compact before things get truncated. + * + * Restore the built-in footer (and reset the indicator/widget) with `/statusbar`. + */ + +import type { AssistantMessage } from "@earendil-works/pi-ai"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { truncateToWidth } from "@earendil-works/pi-tui"; + +// Nerd Font (Material Design) glyphs — verified to render in the user's font. +const ICON = { + dir: "\u{F024B}", // 󰉋 nf-md-folder + git: "\u{F062C}", // 󰘬 nf-md-source_branch + model: "\u{F06A9}", // 󰚩 nf-md-robot + context: "\u{F021A}", // 󰈚 nf-md-text_box + tps: "\u{F04C5}", // 󰓅 nf-md-speedometer + warn: "\u{F002A}", // 󰀪 nf-md-alert_outline (same glyph nvim uses for warnings) + up: "↑", // ↑ + down: "↓", // ↓ +}; + +// Widget key for the context-budget warning shown above the editor. +const CTX_WIDGET = "statusbar-context-warning"; +// Show the warning once the context window is this full (%). +const CTX_WARN_AT = 80; + +// Current thinking level, tracked via thinking_level_select (footer render has no +// direct access to it). Defaults to the settings.json default of "off". +let thinkingLevel = "off"; + +// Decode throughput (tokens/sec) of the most recent assistant response. Preferred +// source: the server's own timings (below). Fallback: a client-side clock from the +// first streamed token to message end, so prompt-eval time is excluded. +let lastTps = 0; +let lastPp = 0; // prompt-processing t/s, server-side only (0 = unknown) +let genFirstTokenAt = 0; +let sawToken = false; + +// --- server-side timings (llama.cpp) ---------------------------------------- +// llama.cpp puts a `timings` object on the final SSE chunk (the one carrying `usage`): +// prompt_n / prompt_ms / prompt_per_second, predicted_n / predicted_ms / +// predicted_per_second, cache_n, draft_n / draft_n_accepted. pi-ai's openai-completions +// provider reads only `usage` and drops the rest, and the extension API has no HTTP +// hook, so the one way to see it is to wrap globalThis.fetch and tee the SSE body. +// That is sanctioned: pi's http-dispatcher installs undici's fetch at startup and +// deliberately keeps a later override ("If a caller replaced fetch after module load, +// preserve that deliberate override"), and pi-ai builds `new OpenAI({ fetch: undefined })` +// per request, which falls back to globalThis.fetch -- so a wrapper installed at +// session_start sees every chat completion. Only POST */chat/completions responses +// with a text/event-stream body are teed; other providers' streams carry no `timings` +// and are passed through untouched apart from the tee. The tap stays installed for the +// life of the process (`/statusbar` off just stops displaying it; `/reload` rebinds the +// sink instead of wrapping twice). +interface ServerTimings { + tps: number; // predicted_per_second + pp: number; // prompt_per_second + predictedN: number; + promptN: number; + cacheN: number; +} +// Latest timings seen on the wire, consumed by message_end. Paired with the message by +// predicted_n === usage.output, so a compaction/summary call's timings never get +// attributed to the next visible response. +let pendingServerTimings: ServerTimings | undefined; + +const FETCH_TAP_KEY = "__piStatusbarFetchTap"; + +/** Read one branch of a teed SSE body and report every `timings` object it carries. */ +async function scanSse(stream: ReadableStream, onTimings: (t: ServerTimings) => void): Promise { + const reader = stream.getReader(); + const dec = new TextDecoder(); + let buf = ""; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buf += dec.decode(value, { stream: true }); + let nl: number; + while ((nl = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line.startsWith("data:")) continue; + const payload = line.slice(5).trim(); + if (!payload.includes('"timings"')) continue; // cheap pre-filter: parse only the final chunk + try { + const t = JSON.parse(payload)?.timings; + if (t && typeof t.predicted_per_second === "number") { + onTimings({ + tps: t.predicted_per_second, + pp: typeof t.prompt_per_second === "number" ? t.prompt_per_second : 0, + predictedN: t.predicted_n ?? 0, + promptN: t.prompt_n ?? 0, + cacheN: t.cache_n ?? 0, + }); + } + } catch { + // not JSON: ignore + } + } + } + } catch { + // aborted / cancelled stream: the primary branch reports that, we just stop + } +} + +/** Wrap globalThis.fetch once; on /reload only rebind the sink. */ +function installFetchTap(): void { + const g = globalThis as unknown as Record; + const sink = (t: ServerTimings) => { + pendingServerTimings = t; + }; + const existing = g[FETCH_TAP_KEY] as { sink: (t: ServerTimings) => void } | undefined; + if (existing) { + existing.sink = sink; + return; + } + const tap = { sink }; + g[FETCH_TAP_KEY] = tap; + const orig = globalThis.fetch; + globalThis.fetch = (async (input: Parameters[0], init?: Parameters[1]) => { + const res = await orig(input, init); + let url = ""; + try { + url = typeof input === "string" ? input : input instanceof URL ? input.href : ((input as Request)?.url ?? ""); + } catch { + return res; + } + if (!url.endsWith("/chat/completions") || !res.body) return res; + if (!(res.headers.get("content-type") ?? "").includes("text/event-stream")) return res; + const [ours, theirs] = res.body.tee(); + void scanSse(ours, (t) => tap.sink(t)); + return new Response(theirs, res); + }) as typeof fetch; +} + +// Set from inside the footer factory so events can trigger a re-render. +let requestRender: (() => void) | undefined; + +function collapseHome(p: string): string { + const home = process.env.HOME || ""; + if (p === home) return "~"; + if (home && p.startsWith(`${home}/`)) return `~${p.slice(home.length)}`; + return p; +} + +/** 1234 -> 1.2k, 843000 -> 843k, 1234567 -> 1.2M (same boundaries as the Claude bar's + * fmt_tokens: 0.9995 / 9.95 so a value never prints as "10.0k" or "1000k"). */ +function fmtTokens(n: number): string { + for (const [unit, div] of [ + ["M", 1e6], + ["k", 1e3], + ] as const) { + const v = n / div; + if (v < 0.9995) continue; + return v >= 9.95 ? `${v.toFixed(0)}${unit}` : `${v.toFixed(1)}${unit}`; + } + return `${Math.round(n)}`; +} + +/** Cumulative session tokens, plus the last request's prompt size (~ current + * context-window fill). + * + * Prompt = input + cacheRead + cacheWrite. pi-ai splits a cached prefix out of + * `usage.input` (llama.cpp too: the second call of a session reports e.g. input 20, + * cacheRead 2417), so summing bare `input` undercounted ↑ and -- worse -- made the + * context % and the ≥80% warning read near zero on every cached call. */ +function tokenStats(ctx: ExtensionContext): { + input: number; + output: number; + lastInput: number; +} { + let input = 0; + let output = 0; + let lastInput = 0; + for (const entry of ctx.sessionManager.getBranch()) { + if (entry.type === "message" && entry.message.role === "assistant") { + const usage = (entry.message as AssistantMessage).usage; + if (!usage) continue; // aborted stream: no usage — a throwing render kills the TUI + const prompt = (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0); + input += prompt; + output += usage.output ?? 0; + lastInput = prompt; + } + } + return { input, output, lastInput }; +} + +/** Show/hide the above-editor warning when the context window is nearly full. */ +function updateContextWidget(ctx: ExtensionContext): void { + if (ctx.mode !== "tui") return; + const contextWindow = ctx.model?.contextWindow; + const { lastInput } = tokenStats(ctx); + if (!contextWindow || lastInput <= 0) { + ctx.ui.setWidget(CTX_WIDGET, undefined); + return; + } + const pct = (lastInput / contextWindow) * 100; + if (pct < CTX_WARN_AT) { + ctx.ui.setWidget(CTX_WIDGET, undefined); + return; + } + const th = ctx.ui.theme; + const col = pct >= 90 ? "error" : "warning"; + const line = + th.fg(col, `${ICON.warn} context ${pct.toFixed(0)}%`) + + th.fg("dim", ` (${fmtTokens(lastInput)}/${fmtTokens(contextWindow)}) — /compact soon`); + ctx.ui.setWidget(CTX_WIDGET, [line]); +} + +/** A gentle catppuccin "breathing" pulse for the streaming working-indicator. */ +function pulseIndicator(ctx: ExtensionContext) { + const th = ctx.ui.theme; + return { + frames: [th.fg("dim", "·"), th.fg("muted", "•"), th.fg("accent", "●"), th.fg("muted", "•")], + intervalMs: 120, + }; +} + +export default function (pi: ExtensionAPI) { + let enabled = true; + + pi.on("thinking_level_select", async (event) => { + thinkingLevel = event.level; + requestRender?.(); + }); + + pi.on("model_select", async () => { + requestRender?.(); + }); + + // --- t/s timing: bracket each assistant response and clock its generation --- + pi.on("message_start", async (event) => { + if (event.message?.role !== "assistant") return; + sawToken = false; + genFirstTokenAt = 0; + }); + + pi.on("message_update", async (event) => { + if (event.message?.role !== "assistant") return; + if (!sawToken) { + sawToken = true; + genFirstTokenAt = Date.now(); + } + }); + + pi.on("message_end", async (event, ctx) => { + if (event.message?.role !== "assistant") return; + const output = (event.message as AssistantMessage).usage?.output ?? 0; + // The tee reader and pi-ai consume the same final chunk; pi-ai's path to this + // event is longer, but give the reader one macrotask in case it is still behind. + if (!pendingServerTimings) await new Promise((r) => setTimeout(r, 20)); + const srv = pendingServerTimings; + pendingServerTimings = undefined; + if (srv && srv.predictedN > 0 && (output === 0 || srv.predictedN === output)) { + lastTps = srv.tps; + lastPp = srv.pp; + } else { + const secs = genFirstTokenAt ? (Date.now() - genFirstTokenAt) / 1000 : 0; + if (secs > 0 && output > 0) lastTps = output / secs; + lastPp = 0; + } + requestRender?.(); + if (enabled) updateContextWidget(ctx); + }); + + const install = (ctx: ExtensionContext) => { + if (ctx.mode !== "tui") return; + ctx.ui.setWorkingIndicator(pulseIndicator(ctx)); + updateContextWidget(ctx); + ctx.ui.setFooter((tui, theme, footerData) => { + const sep = theme.fg("dim", " │ "); + requestRender = () => tui.requestRender(); + const unsub = footerData.onBranchChange(() => tui.requestRender()); + return { + dispose: unsub, + invalidate() {}, + render(width: number): string[] { + const parts: string[] = []; + + // Preserve extension statuses (plan-mode "⏸ plan", etc.) up front. + for (const status of footerData.getExtensionStatuses().values()) { + if (status) parts.push(status); + } + + // 󰉋 directory + parts.push(theme.fg("accent", ICON.dir) + " " + theme.fg("text", collapseHome(ctx.cwd))); + + // 󰘬 git branch (only inside a repo) + const branch = footerData.getGitBranch(); + if (branch) parts.push(theme.fg("accent", ICON.git) + " " + theme.fg("success", branch)); + + // 󰚩 model (+ · thinking level) + if (ctx.model?.id) { + let model = theme.fg("accent", ICON.model) + " " + theme.fg("text", ctx.model.id); + if (thinkingLevel && thinkingLevel !== "off") { + model += theme.fg("dim", ` · ${thinkingLevel}`); + } + parts.push(model); + } + + // 󰈚 context window usage (% when the window is known, else raw tokens) + const { input, output, lastInput } = tokenStats(ctx); + if (lastInput > 0) { + const contextWindow = ctx.model?.contextWindow; + let seg = theme.fg("accent", ICON.context) + " "; + if (contextWindow) { + const pct = Math.min(100, (lastInput / contextWindow) * 100); + const col = pct < 50 ? "success" : pct < 80 ? "warning" : "error"; + seg += theme.fg(col, `${pct.toFixed(0)}%`) + theme.fg("dim", ` (${fmtTokens(lastInput)})`); + } else { + seg += theme.fg("text", fmtTokens(lastInput)); + } + parts.push(seg); + } + + // 󰓅 tokens/sec of the last response (+ dim prompt-processing t/s when the + // server reported it) + if (lastTps > 0) { + let seg = theme.fg("accent", ICON.tps) + " " + theme.fg("text", lastTps.toFixed(1)) + theme.fg("dim", " t/s"); + if (lastPp > 0) seg += theme.fg("dim", ` pp ${lastPp.toFixed(0)}`); + parts.push(seg); + } + + // ↑ ↓ cumulative session prompt / output tokens (Claude's 🔢 segment) + if (input || output) { + parts.push(theme.fg("dim", `${ICON.up}${fmtTokens(input)} ${ICON.down}${fmtTokens(output)}`)); + } + + return [truncateToWidth(parts.join(sep), width)]; + }, + }; + }); + }; + + pi.on("session_start", async (_event, ctx) => { + // Installed here, not at load time: pi's http-dispatcher only swaps in undici's + // fetch (idle timeout, proxy) while globalThis.fetch is still the original, so the + // tap must not get there first. By session_start, startup is done. + installFetchTap(); + if (enabled) install(ctx); + }); + + pi.registerCommand("statusbar", { + description: "Toggle the custom pi status bar footer", + handler: async (_args, ctx) => { + enabled = !enabled; + if (enabled) { + install(ctx); + ctx.ui.notify("Custom status bar enabled", "info"); + } else { + ctx.ui.setFooter(undefined); + ctx.ui.setWorkingIndicator(); // restore pi's default spinner + ctx.ui.setWidget(CTX_WIDGET, undefined); + ctx.ui.notify("Default footer restored", "info"); + } + }, + }); +} diff --git a/common/.pi/agent/extensions/todo.ts b/common/.pi/agent/extensions/todo.ts new file mode 100644 index 0000000..67cba74 --- /dev/null +++ b/common/.pi/agent/extensions/todo.ts @@ -0,0 +1,297 @@ +/** + * Todo Extension - Demonstrates state management via session entries + * + * This extension: + * - Registers a `todo` tool for the LLM to manage todos + * - Registers a `/todos` command for users to view the list + * + * State is stored in tool result details (not external files), which allows + * proper branching - when you branch, the todo state is automatically + * correct for that point in history. + */ + +import { StringEnum } from "@earendil-works/pi-ai"; +import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent"; +import { matchesKey, Text, truncateToWidth } from "@earendil-works/pi-tui"; +import { Type } from "typebox"; + +interface Todo { + id: number; + text: string; + done: boolean; +} + +interface TodoDetails { + action: "list" | "add" | "toggle" | "clear"; + todos: Todo[]; + nextId: number; + error?: string; +} + +const TodoParams = Type.Object({ + action: StringEnum(["list", "add", "toggle", "clear"] as const), + text: Type.Optional(Type.String({ description: "Todo text (for add)" })), + id: Type.Optional(Type.Number({ description: "Todo ID (for toggle)" })), +}); + +/** + * UI component for the /todos command + */ +class TodoListComponent { + private todos: Todo[]; + private theme: Theme; + private onClose: () => void; + private cachedWidth?: number; + private cachedLines?: string[]; + + constructor(todos: Todo[], theme: Theme, onClose: () => void) { + this.todos = todos; + this.theme = theme; + this.onClose = onClose; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.onClose(); + } + } + + render(width: number): string[] { + if (this.cachedLines && this.cachedWidth === width) { + return this.cachedLines; + } + + const lines: string[] = []; + const th = this.theme; + + lines.push(""); + const title = th.fg("accent", " Todos "); + const headerLine = + th.fg("borderMuted", "─".repeat(3)) + title + th.fg("borderMuted", "─".repeat(Math.max(0, width - 10))); + lines.push(truncateToWidth(headerLine, width)); + lines.push(""); + + if (this.todos.length === 0) { + lines.push(truncateToWidth(` ${th.fg("dim", "No todos yet. Ask the agent to add some!")}`, width)); + } else { + const done = this.todos.filter((t) => t.done).length; + const total = this.todos.length; + lines.push(truncateToWidth(` ${th.fg("muted", `${done}/${total} completed`)}`, width)); + lines.push(""); + + for (const todo of this.todos) { + const check = todo.done ? th.fg("success", "✓") : th.fg("dim", "○"); + const id = th.fg("accent", `#${todo.id}`); + const text = todo.done ? th.fg("dim", todo.text) : th.fg("text", todo.text); + lines.push(truncateToWidth(` ${check} ${id} ${text}`, width)); + } + } + + lines.push(""); + lines.push(truncateToWidth(` ${th.fg("dim", "Press Escape to close")}`, width)); + lines.push(""); + + this.cachedWidth = width; + this.cachedLines = lines; + return lines; + } + + invalidate(): void { + this.cachedWidth = undefined; + this.cachedLines = undefined; + } +} + +export default function (pi: ExtensionAPI) { + // In-memory state (reconstructed from session on load) + let todos: Todo[] = []; + let nextId = 1; + + /** + * Reconstruct state from session entries. + * Scans tool results for this tool and applies them in order. + */ + const reconstructState = (ctx: ExtensionContext) => { + todos = []; + nextId = 1; + + for (const entry of ctx.sessionManager.getBranch()) { + if (entry.type !== "message") continue; + const msg = entry.message; + if (msg.role !== "toolResult" || msg.toolName !== "todo") continue; + + const details = msg.details as TodoDetails | undefined; + if (details) { + todos = details.todos; + nextId = details.nextId; + } + } + }; + + // Reconstruct state on session events + pi.on("session_start", async (_event, ctx) => reconstructState(ctx)); + pi.on("session_tree", async (_event, ctx) => reconstructState(ctx)); + + // Register the todo tool for the LLM + pi.registerTool({ + name: "todo", + label: "Todo", + description: "Manage a todo list. Actions: list, add (text), toggle (id), clear", + parameters: TodoParams, + + async execute(_toolCallId, params, _signal, _onUpdate, _ctx) { + switch (params.action) { + case "list": + return { + content: [ + { + type: "text", + text: todos.length + ? todos.map((t) => `[${t.done ? "x" : " "}] #${t.id}: ${t.text}`).join("\n") + : "No todos", + }, + ], + details: { action: "list", todos: [...todos], nextId } as TodoDetails, + }; + + case "add": { + if (!params.text) { + return { + content: [{ type: "text", text: "Error: text required for add" }], + details: { action: "add", todos: [...todos], nextId, error: "text required" } as TodoDetails, + }; + } + const newTodo: Todo = { id: nextId++, text: params.text, done: false }; + todos.push(newTodo); + return { + content: [{ type: "text", text: `Added todo #${newTodo.id}: ${newTodo.text}` }], + details: { action: "add", todos: [...todos], nextId } as TodoDetails, + }; + } + + case "toggle": { + if (params.id === undefined) { + return { + content: [{ type: "text", text: "Error: id required for toggle" }], + details: { action: "toggle", todos: [...todos], nextId, error: "id required" } as TodoDetails, + }; + } + const todo = todos.find((t) => t.id === params.id); + if (!todo) { + return { + content: [{ type: "text", text: `Todo #${params.id} not found` }], + details: { + action: "toggle", + todos: [...todos], + nextId, + error: `#${params.id} not found`, + } as TodoDetails, + }; + } + todo.done = !todo.done; + return { + content: [{ type: "text", text: `Todo #${todo.id} ${todo.done ? "completed" : "uncompleted"}` }], + details: { action: "toggle", todos: [...todos], nextId } as TodoDetails, + }; + } + + case "clear": { + const count = todos.length; + todos = []; + nextId = 1; + return { + content: [{ type: "text", text: `Cleared ${count} todos` }], + details: { action: "clear", todos: [], nextId: 1 } as TodoDetails, + }; + } + + default: + return { + content: [{ type: "text", text: `Unknown action: ${params.action}` }], + details: { + action: "list", + todos: [...todos], + nextId, + error: `unknown action: ${params.action}`, + } as TodoDetails, + }; + } + }, + + renderCall(args, theme, _context) { + let text = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", args.action); + if (args.text) text += ` ${theme.fg("dim", `"${args.text}"`)}`; + if (args.id !== undefined) text += ` ${theme.fg("accent", `#${args.id}`)}`; + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + const details = result.details as TodoDetails | undefined; + if (!details) { + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "", 0, 0); + } + + if (details.error) { + return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0); + } + + const todoList = details.todos; + + switch (details.action) { + case "list": { + if (todoList.length === 0) { + return new Text(theme.fg("dim", "No todos"), 0, 0); + } + let listText = theme.fg("muted", `${todoList.length} todo(s):`); + const display = expanded ? todoList : todoList.slice(0, 5); + for (const t of display) { + const check = t.done ? theme.fg("success", "✓") : theme.fg("dim", "○"); + const itemText = t.done ? theme.fg("dim", t.text) : theme.fg("muted", t.text); + listText += `\n${check} ${theme.fg("accent", `#${t.id}`)} ${itemText}`; + } + if (!expanded && todoList.length > 5) { + listText += `\n${theme.fg("dim", `... ${todoList.length - 5} more`)}`; + } + return new Text(listText, 0, 0); + } + + case "add": { + const added = todoList[todoList.length - 1]; + return new Text( + theme.fg("success", "✓ Added ") + + theme.fg("accent", `#${added.id}`) + + " " + + theme.fg("muted", added.text), + 0, + 0, + ); + } + + case "toggle": { + const text = result.content[0]; + const msg = text?.type === "text" ? text.text : ""; + return new Text(theme.fg("success", "✓ ") + theme.fg("muted", msg), 0, 0); + } + + case "clear": + return new Text(theme.fg("success", "✓ ") + theme.fg("muted", "Cleared all todos"), 0, 0); + } + }, + }); + + // Register the /todos command for users + pi.registerCommand("todos", { + description: "Show all todos on the current branch", + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("/todos requires interactive mode", "error"); + return; + } + + await ctx.ui.custom((_tui, theme, _kb, done) => { + return new TodoListComponent(todos, theme, () => done()); + }); + }, + }); +} diff --git a/common/.pi/agent/extensions/verbose.ts b/common/.pi/agent/extensions/verbose.ts new file mode 100644 index 0000000..2ffe063 --- /dev/null +++ b/common/.pi/agent/extensions/verbose.ts @@ -0,0 +1,114 @@ +/** + * Verbose view toggle — `/verbose` and a bound key. + * + * The counterpart of the opencode TUI plugin and the Claude `/verbose` skill, adjusted for + * what pi actually allows. pi splits verbosity in two: + * + * LIVE `ctrl+o` (app.tools.expand) collapses/expands tool output and `ctrl+t` + * (app.thinking.toggle) does the same for thinking blocks. These are built-in + * keybindings. An extension cannot drive them — there is no settings API and no + * way to dispatch a built-in action — and a key maps to one action, so they + * cannot be merged into a single press the way opencode's four toggles were. + * + * PERSISTED `hideThinkingBlock` and `showCacheMissNotices` in settings.json, read at + * startup. That is what this toggles, i.e. the default you get on every new + * session, which is exactly the position the Claude skill is in. + * + * So: this sets the default and tells you the live keys. "on" shows thinking and the + * cache/compaction/recovery notices; "off" is deliberately quieter than stock pi (it hides + * thinking), matching how opencode's verbose-off state hides thinking too. + * + * ⚠️ pi writes settings.json itself (that is where `lastChangelogVersion` churn comes from), + * so a running pi may overwrite this on exit. If a toggle seems not to have stuck, re-run it + * after pi has exited. + */ + +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { getAgentDir } from "@earendil-works/pi-coding-agent"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; + +type Settings = Record; + +const LIVE = "live now: ctrl+o tool output, ctrl+t thinking"; + +// Verbose-on values. Verbose-off is the inverse, not pi's defaults: stock pi already shows +// thinking (hideThinkingBlock defaults to false), so an "off" that merely restored defaults +// would be indistinguishable from "on" for the noisiest part. +const VERBOSE_ON: Settings = { hideThinkingBlock: false, showCacheMissNotices: true }; +const VERBOSE_OFF: Settings = { hideThinkingBlock: true, showCacheMissNotices: false }; + +function settingsPath(): string { + return join(getAgentDir(), "settings.json"); +} + +function read(): Settings { + // A parse failure must never lead to a write — that would replace a hand-edited config + // with whatever this extension thinks it knows. + const raw = readFileSync(settingsPath(), "utf-8"); + return JSON.parse(raw) as Settings; +} + +function isOn(s: Settings): boolean { + return s.hideThinkingBlock === false && s.showCacheMissNotices === true; +} + +function write(s: Settings): void { + // Plain writeFileSync, deliberately NOT write-temp-then-rename: this path is a stow + // symlink into the dots repo, and renaming over it would replace the link with a real + // file, silently detaching the live config from the repo. + writeFileSync(settingsPath(), `${JSON.stringify(s, null, 2)}\n`, "utf-8"); +} + +function describe(s: Settings): string { + return `hideThinkingBlock: ${s.hideThinkingBlock ?? false}, showCacheMissNotices: ${s.showCacheMissNotices ?? false}`; +} + +function toggle(ctx: ExtensionContext, mode: "on" | "off" | "toggle" | "status"): void { + let current: Settings; + try { + current = read(); + } catch (err) { + ctx.ui.notify(`verbose: cannot read settings.json — ${err}`, "error"); + return; + } + + if (mode === "status") { + ctx.ui.notify(`Verbose ${isOn(current) ? "ON" : "OFF"} — ${describe(current)}. ${LIVE}`, "info"); + return; + } + + const on = mode === "toggle" ? !isOn(current) : mode === "on"; + const next = { ...current, ...(on ? VERBOSE_ON : VERBOSE_OFF) }; + + try { + write(next); + } catch (err) { + ctx.ui.notify(`verbose: cannot write settings.json — ${err}`, "error"); + return; + } + + ctx.ui.notify( + `Verbose ${on ? "ON" : "OFF"} — applies to new sessions (settings are read at startup). ${LIVE}`, + "info", + ); +} + +export default function (pi: ExtensionAPI) { + pi.registerCommand("verbose", { + description: "Toggle the persisted verbose view (usage: /verbose [on|off|status])", + handler: async (args, ctx) => { + const raw = args.trim().toLowerCase(); + if (raw && raw !== "on" && raw !== "off" && raw !== "status") { + ctx.ui.notify("usage: /verbose [on|off|status]", "error"); + return; + } + toggle(ctx, (raw || "toggle") as "on" | "off" | "toggle" | "status"); + }, + }); + + pi.registerShortcut("alt+v", { + description: "Toggle verbose view", + handler: async (ctx) => toggle(ctx, "toggle"), + }); +} diff --git a/common/.pi/agent/extensions/vim-toggle.ts b/common/.pi/agent/extensions/vim-toggle.ts new file mode 100644 index 0000000..cf7f704 --- /dev/null +++ b/common/.pi/agent/extensions/vim-toggle.ts @@ -0,0 +1,44 @@ +/** + * `/vim` — toggle the modal input editor off/on + * + * The modal editor itself is now the **npm package `pi-vim`** (declared in + * `settings.json > packages`, configured under `settings.json > piVim`). That + * package registers no commands, so this file restores the `/vim` toggle the + * local `vim-editor.ts` fork used to provide — the fork is kept beside it as + * `vim-editor.ts.disabled` (see ../../CLAUDE.md). + * + * OFF — drop the custom editor component, which puts pi's stock editor back for + * the rest of the session (handy for a big paste, or any key the modal + * layer swallows). + * ON — `ctx.reload()`, the same flow as `/reload`, re-runs extension discovery + * and so re-installs pi-vim's editor. That reloads statusbar/plan-mode too + * and re-instantiates *this* file, which is why turning it back on needs no + * bookkeeping: the fresh instance starts at `enabled = true` again. + * + * Nothing is installed on `session_start` — pi-vim already does that, so this + * file only ever reacts to the command and never races it for the editor slot. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + // pi-vim installs its editor at session_start, so we start out enabled. + let enabled = true; + + pi.registerCommand("vim", { + description: "Toggle the vim (modal) input editor", + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") return; // editor components are TUI-only + if (enabled) { + ctx.ui.setEditorComponent(undefined); + enabled = false; + ctx.ui.notify("Default editor restored — /vim to re-enable", "info"); + return; + } + // Notify *before* awaiting: after the reload this call frame belongs to + // the pre-reload instance, and its UI handle is on the way out. + ctx.ui.notify("Vim editor enabled", "info"); + await ctx.reload(); + }, + }); +} diff --git a/common/.pi/agent/keybindings.json b/common/.pi/agent/keybindings.json new file mode 100644 index 0000000..baed800 --- /dev/null +++ b/common/.pi/agent/keybindings.json @@ -0,0 +1,5 @@ +{ + "app.thinking.cycle": ["alt+t"], + "tui.editor.cursorUp": ["up", "ctrl+p"], + "app.model.cycleForward": ["alt+p"] +} diff --git a/common/.pi/agent/models.json b/common/.pi/agent/models.json new file mode 100644 index 0000000..f548f56 --- /dev/null +++ b/common/.pi/agent/models.json @@ -0,0 +1,274 @@ +{ + "providers": { + "duskadiy": { + "baseUrl": "https://llm.duskadiy.com/api/v1", + "api": "openai-completions", + "apiKey": "$DUSKADIY_API_KEY", + "compat": { + "supportsDeveloperRole": false, + "supportsReasoningEffort": false, + "maxTokensField": "max_tokens" + }, + "models": [ + { + "id": "gemma-4-E4B-it-UD-Q8_K_XL", + "name": "Gemma 4 E4B · 64k · vision — fast generalist, long docs (~57 t/s)", + "reasoning": false, + "input": ["text", "image"], + "contextWindow": 65536, + "maxTokens": 16384, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "gemma-4-26B-A4B-it-UD-IQ4_XS", + "name": "Gemma 4 26B · 24k · vision — quality generalist (~34 t/s)", + "reasoning": false, + "input": ["text", "image"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3-Coder-30B-Instruct-UD-Q3_K_XL", + "name": "Qwen3 Coder 30B · 32k — main agent coder (~30 t/s)", + "reasoning": false, + "input": ["text"], + "contextWindow": 32768, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3-Coder-Next-UD-IQ3_XXS", + "name": "Qwen3 Coder Next 80B · 128k — long sessions (~16 t/s)", + "reasoning": false, + "input": ["text"], + "contextWindow": 131072, + "maxTokens": 16384, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS", + "name": "Qwen3.6 35B · 24k · vision — daily driver (~36 t/s)", + "reasoning": false, + "input": ["text", "image"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3.6-35B-A3B-Thinking", + "name": "Qwen3.6 35B Thinking · 24k · vision — hard problems (~39 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text", "image"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3.5-9B-UD-Q6_K_XL", + "name": "Qwen3.5 9B · 32k · vision — quick tasks (~32 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text", "image"], + "contextWindow": 32768, + "maxTokens": 8192, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3.8-27B-UD-IQ3_XXS", + "name": "Qwen3.8 27B · 24k · vision — hybrid reasoner, quiet desktop only (~15 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text", "image"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "GLM-4.7-Flash-UD-Q4_K_XL", + "name": "GLM-4.7 Flash · 24k — quality coder (~21 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "GLM-4.7-Flash-UD-Q3_K_XL", + "name": "GLM-4.7 Flash Q3 · 24k — fast coder (~28 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Ornith-1.5-35B-A3B-IQ3_XXS", + "name": "Ornith 1.5 35B · 32k · vision — agentic coder, thinking (~32 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template", "thinkingTokenBudgetField": "thinking_budget_tokens" }, + "input": ["text", "image"], + "contextWindow": 32768, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "gpt-oss-20b", + "name": "gpt-oss 20B · 64k — fast reasoning + tools (~38 t/s)", + "reasoning": true, + "input": ["text"], + "contextWindow": 65536, + "maxTokens": 8192, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "gpt-oss-20b-low", + "name": "gpt-oss 20B low · 64k — snappy answers (~37 t/s)", + "reasoning": true, + "input": ["text"], + "contextWindow": 65536, + "maxTokens": 8192, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + } + ] + }, + "localcpp": { + "baseUrl": "http://192.168.0.204:11343/v1", + "api": "openai-completions", + "apiKey": "no-key-required", + "compat": { + "supportsDeveloperRole": false, + "supportsReasoningEffort": false, + "maxTokensField": "max_tokens" + }, + "models": [ + { + "id": "gemma-4-E4B-it-UD-Q8_K_XL", + "name": "Gemma 4 E4B · 64k · vision — fast generalist, long docs (~57 t/s)", + "reasoning": false, + "input": ["text", "image"], + "contextWindow": 65536, + "maxTokens": 16384, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "gemma-4-26B-A4B-it-UD-IQ4_XS", + "name": "Gemma 4 26B · 24k · vision — quality generalist (~34 t/s)", + "reasoning": false, + "input": ["text", "image"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3-Coder-30B-Instruct-UD-Q3_K_XL", + "name": "Qwen3 Coder 30B · 32k — main agent coder (~30 t/s)", + "reasoning": false, + "input": ["text"], + "contextWindow": 32768, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3-Coder-Next-UD-IQ3_XXS", + "name": "Qwen3 Coder Next 80B · 128k — long sessions (~16 t/s)", + "reasoning": false, + "input": ["text"], + "contextWindow": 131072, + "maxTokens": 16384, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS", + "name": "Qwen3.6 35B · 24k · vision — daily driver (~36 t/s)", + "reasoning": false, + "input": ["text", "image"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3.6-35B-A3B-Thinking", + "name": "Qwen3.6 35B Thinking · 24k · vision — hard problems (~39 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text", "image"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3.5-9B-UD-Q6_K_XL", + "name": "Qwen3.5 9B · 32k · vision — quick tasks (~32 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text", "image"], + "contextWindow": 32768, + "maxTokens": 8192, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Qwen3.8-27B-UD-IQ3_XXS", + "name": "Qwen3.8 27B · 24k · vision — hybrid reasoner, quiet desktop only (~15 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text", "image"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "GLM-4.7-Flash-UD-Q4_K_XL", + "name": "GLM-4.7 Flash · 24k — quality coder (~21 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "GLM-4.7-Flash-UD-Q3_K_XL", + "name": "GLM-4.7 Flash Q3 · 24k — fast coder (~28 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template" }, + "input": ["text"], + "contextWindow": 24576, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "Ornith-1.5-35B-A3B-IQ3_XXS", + "name": "Ornith 1.5 35B · 32k · vision — agentic coder, thinking (~32 t/s)", + "reasoning": true, + "compat": { "thinkingFormat": "qwen-chat-template", "thinkingTokenBudgetField": "thinking_budget_tokens" }, + "input": ["text", "image"], + "contextWindow": 32768, + "maxTokens": 4096, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "gpt-oss-20b", + "name": "gpt-oss 20B · 64k — fast reasoning + tools (~38 t/s)", + "reasoning": true, + "input": ["text"], + "contextWindow": 65536, + "maxTokens": 8192, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + }, + { + "id": "gpt-oss-20b-low", + "name": "gpt-oss 20B low · 64k — snappy answers (~37 t/s)", + "reasoning": true, + "input": ["text"], + "contextWindow": 65536, + "maxTokens": 8192, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + } + ] + } + } +} diff --git a/common/.pi/agent/prompts/commit.md b/common/.pi/agent/prompts/commit.md new file mode 100644 index 0000000..4734d38 --- /dev/null +++ b/common/.pi/agent/prompts/commit.md @@ -0,0 +1,11 @@ +--- +description: Write a Conventional Commits message for the staged changes +argument-hint: "[extra context]" +--- +Inspect the staged changes with `git diff --cached` (and `git status` for context). Then write a single Conventional Commits message: + +- A `(): ` summary line, imperative mood, ≤72 chars (types: feat, fix, refactor, docs, chore, test, perf, build). +- An optional short body explaining the *why* only when it isn't obvious from the diff. +- Do NOT run `git commit`. Output only the message inside a code block so I can review it. + +Extra context to incorporate: ${1:-none} diff --git a/common/.pi/agent/prompts/review.md b/common/.pi/agent/prompts/review.md new file mode 100644 index 0000000..b8ad575 --- /dev/null +++ b/common/.pi/agent/prompts/review.md @@ -0,0 +1,14 @@ +--- +description: Review the current diff for bugs and issues +argument-hint: "[focus area]" +--- +Review the current changes. Check both `git diff` (unstaged) and `git diff --cached` (staged). Focus on: + +- Correctness and logic bugs +- Error handling and missing edge cases +- Security issues (injection, secrets, unsafe input) +- Anything that doesn't match the surrounding code's conventions + +List concrete findings as `file:line — issue — suggested fix`, ordered by severity. Be concise; skip praise. If nothing is wrong, say so. + +Extra focus this round: ${1:-general correctness} diff --git a/common/.pi/agent/settings.json b/common/.pi/agent/settings.json new file mode 100644 index 0000000..3119dd8 --- /dev/null +++ b/common/.pi/agent/settings.json @@ -0,0 +1,71 @@ +{ + "defaultProvider": "localcpp", + "defaultModel": "Ornith-1.5-35B-A3B-IQ3_XXS", + "defaultThinkingLevel": "medium", + "thinkingBudgets": { + "minimal": 512, + "low": 1024, + "medium": 2048, + "high": 3072 + }, + "theme": "catppuccin-mocha", + "quietStartup": false, + "collapseChangelog": true, + "defaultProjectTrust": "ask", + "enableInstallTelemetry": false, + "enabledModels": [ + "duskadiy/*", + "localcpp/*" + ], + "compaction": { + "enabled": true, + "reserveTokens": 8192, + "keepRecentTokens": 4000 + }, + "retry": { + "enabled": true, + "maxRetries": 3, + "baseDelayMs": 2000, + "provider": { + "timeoutMs": 3600000 + } + }, + "httpIdleTimeoutMs": 600000, + "npmCommand": [ + "fnm", + "exec", + "--using=22", + "--", + "npm" + ], + "showHardwareCursor": true, + "piVim": { + "clipboardMirror": "yank", + "exCommand": { + "piDispatch": true, + "copyInputToClipboard": false + }, + "modeColors": { + "insert": "success", + "normal": "accent", + "visual": "warning", + "ex": "bashMode" + }, + "borderSync": { + "insert": "host", + "normal": "mode", + "visual": "mode", + "ex": "host" + }, + "labelSync": { + "insert": "mode", + "normal": "mode", + "visual": "mode", + "ex": "mode" + } + }, + "lastChangelogVersion": "1.5.0", + "packages": [ + "npm:pi-vim" + ] +} \ No newline at end of file diff --git a/common/.pi/agent/themes/catppuccin-mocha.json b/common/.pi/agent/themes/catppuccin-mocha.json new file mode 100644 index 0000000..ade4e41 --- /dev/null +++ b/common/.pi/agent/themes/catppuccin-mocha.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "name": "catppuccin-mocha", + "vars": { + "rosewater": "#f5e0dc", + "flamingo": "#f2cdcd", + "pink": "#f5c2e7", + "mauve": "#cba6f7", + "red": "#f38ba8", + "maroon": "#eba0ac", + "peach": "#fab387", + "yellow": "#f9e2af", + "green": "#a6e3a1", + "teal": "#94e2d5", + "sky": "#89dceb", + "sapphire": "#74c7ec", + "blue": "#89b4fa", + "lavender": "#b4befe", + "fg": "#cdd6f4", + "subtext1": "#bac2de", + "subtext0": "#a6adc8", + "overlay2": "#9399b2", + "overlay1": "#7f849c", + "overlay0": "#6c7086", + "surface2": "#585b70", + "surface1": "#45475a", + "surface0": "#313244", + "base": "#1e1e2e", + "mantle": "#181825", + "crust": "#11111b" + }, + "colors": { + "accent": "mauve", + "border": "surface1", + "borderAccent": "mauve", + "borderMuted": "surface0", + "success": "green", + "error": "red", + "warning": "yellow", + "muted": "subtext0", + "dim": "overlay0", + "text": "fg", + "thinkingText": "overlay1", + "selectedBg": "surface0", + "userMessageBg": "surface0", + "userMessageText": "fg", + "customMessageBg": "surface0", + "customMessageText": "fg", + "customMessageLabel": "mauve", + "toolPendingBg": "mantle", + "toolSuccessBg": "#1e2b22", + "toolErrorBg": "#2b1e22", + "toolTitle": "mauve", + "toolOutput": "fg", + "mdHeading": "mauve", + "mdLink": "blue", + "mdLinkUrl": "sapphire", + "mdCode": "green", + "mdCodeBlock": "fg", + "mdCodeBlockBorder": "surface1", + "mdQuote": "subtext0", + "mdQuoteBorder": "surface2", + "mdHr": "surface1", + "mdListBullet": "mauve", + "toolDiffAdded": "green", + "toolDiffRemoved": "red", + "toolDiffContext": "overlay0", + "syntaxComment": "overlay0", + "syntaxKeyword": "mauve", + "syntaxFunction": "blue", + "syntaxVariable": "fg", + "syntaxString": "green", + "syntaxNumber": "peach", + "syntaxType": "yellow", + "syntaxOperator": "sky", + "syntaxPunctuation": "overlay2", + "thinkingOff": "surface1", + "thinkingMinimal": "overlay0", + "thinkingLow": "blue", + "thinkingMedium": "teal", + "thinkingHigh": "peach", + "thinkingXhigh": "red", + "bashMode": "peach" + }, + "export": { + "pageBg": "#11111b", + "cardBg": "#1e1e2e", + "infoBg": "#313244" + } +} diff --git a/fl/.config/evremap/evremap.service b/fl/.config/evremap/evremap.service new file mode 100644 index 0000000..987fc11 --- /dev/null +++ b/fl/.config/evremap/evremap.service @@ -0,0 +1,14 @@ +[Unit] +Description=Evremap Service +After=multi-user.target + +[Service] +WorkingDirectory=/ +# Config path must stay absolute: this is a system unit running as root, so ~ or $HOME would resolve to /root. +ExecStart=bash -c "/usr/bin/evremap remap /home/anon/.config/evremap/evremap.toml -d 0" +Restart=always +StandardOutput=journal +StandardError=journal + +[Install] +WantedBy=multi-user.target diff --git a/fl/.config/evremap/evremap.toml b/fl/.config/evremap/evremap.toml new file mode 100644 index 0000000..fded262 --- /dev/null +++ b/fl/.config/evremap/evremap.toml @@ -0,0 +1,60 @@ +# The name of the device to remap. +# Run `sudo evremap list-devices` to see the devices available +# on your system. +device_name = "Logitech ERGO K860" + +# If you have multiple devices with the same name, you can optionally +# specify the `phys` value that is printed by the `list-devices` subcommand +# phys = "usb-0000:07:00.3-2.1.1/input0" + +# Configure CAPSLOCK as a Dual Role key. +# Holding it produces LEFTCTRL, but tapping it +# will produce ESC. +# Both `tap` and `hold` can expand to multiple output keys. +[[dual_role]] +input = "KEY_CAPSLOCK" +hold = ["KEY_LEFTCTRL"] +tap = ["KEY_ESC"] + +# Turn RIGHT ALT into a vim-arrow layer. +# We first neuter it: instead of ever emitting KEY_RIGHTALT (which apps treat +# as "activate menu" on a bare tap), it becomes KEY_F13 -- a real keycode that +# is unbound in every app, so tapping or holding right alt alone does nothing. +# The chords below then turn F13 + h/j/k/l into the arrow keys. +[[dual_role]] +input = "KEY_RIGHTALT" +hold = ["KEY_F13"] +tap = ["KEY_F13"] + +[[remap]] +input = ["KEY_F13", "KEY_H"] +output = ["KEY_LEFT"] + +[[remap]] +input = ["KEY_F13", "KEY_J"] +output = ["KEY_DOWN"] + +[[remap]] +input = ["KEY_F13", "KEY_K"] +output = ["KEY_UP"] + +[[remap]] +input = ["KEY_F13", "KEY_L"] +output = ["KEY_RIGHT"] + +[[remap]] +input = ["KEY_F13", "KEY_U"] +output = ["KEY_PAGEUP"] + +[[remap]] +input = ["KEY_F13", "KEY_D"] +output = ["KEY_PAGEDOWN"] + +# Word-wise motion: emit Ctrl+Arrow so it jumps by word. +[[remap]] +input = ["KEY_F13", "KEY_B"] +output = ["KEY_LEFTCTRL", "KEY_LEFT"] + +[[remap]] +input = ["KEY_F13", "KEY_W"] +output = ["KEY_LEFTCTRL", "KEY_RIGHT"] diff --git a/fl/.config/fish/host.fish b/fl/.config/fish/host.fish new file mode 100644 index 0000000..60fe8aa --- /dev/null +++ b/fl/.config/fish/host.fish @@ -0,0 +1,11 @@ +# fl runs the llama.cpp router as a systemd service (llama.service) — no launch abbr needed. +# Presets: ~/.config/llamacpp/config.ini; see ~/.config/llamacpp/README.md. + +## GPU monitors — the RX 7600 XT also drives the display, so VRAM headroom is a safety matter +## (config.ini header: keep ≥ 2.5 GB free; GTT growth = VRAM spilling to RAM = the freeze precursor). +# vram : quick rocm-smi % view + who holds the render node. fuser prints its table on STDERR, +# so it must be 2>&1 — with 2>/dev/null the "LLM GPU usage" section is always empty. +abbr vram 'watch -c -d -n 1 \'echo "=== VRAM ==="; rocm-smi --showmemuse --showuse 2>/dev/null | grep -E "GPU use|Allocated|Read/Write"; echo ""; echo "=== LLM GPU usage ==="; fuser -v /dev/dri/renderD128 2>&1 | grep -iE "COMMAND|llama"\'' +# vramx: absolute GiB used/free + GTT + temp straight from amdgpu sysfs (no ROCm), per-process VRAM +# via fdinfo, and which preset the router has resident. Body = gpumon.sh (runs bare too). +abbr vramx 'watch -c -d -n 1 ~/.config/llamacpp/gpumon.sh' diff --git a/fl/.config/kglobalshortcutsrc b/fl/.config/kglobalshortcutsrc new file mode 100644 index 0000000..742c69a --- /dev/null +++ b/fl/.config/kglobalshortcutsrc @@ -0,0 +1,372 @@ +[ActivityManager] +_k_friendly_name=Activity Manager +switch-to-activity-a8fc2925-fa8d-449a-a9be-48ffe253c900=Meta+Shift+Tab,none,Switch to activity "Work" +switch-to-activity-c0551195-8905-4f5f-9be3-86124cedc90e=Meta+Tab,none,Switch to activity "Personal" + +[KDE Keyboard Layout Switcher] +Switch keyboard layout to English (US)=none,none,Switch keyboard layout to English (US) +Switch keyboard layout to Serbian (Cyrillic, ZE and ZHE swapped)=none,none,Switch keyboard layout to Serbian (Cyrillic\\, ZE and ZHE swapped) +Switch keyboard layout to Serbian (Latin, with guillemets)=none,none,Switch keyboard layout to Serbian (Latin\\, with guillemets) +Switch to Last-Used Keyboard Layout=none,Meta+Alt+L,Switch to Last-Used Keyboard Layout +Switch to Next Keyboard Layout=none,Meta+Alt+K,Switch to Next Keyboard Layout +_k_friendly_name=Keyboard Layout Switcher + +[kmix] +_k_friendly_name=KMix +decrease_microphone_volume=Microphone Volume Down,Microphone Volume Down,Decrease Microphone Volume +decrease_volume=Volume Down,Volume Down,Decrease Volume +decrease_volume_small=Shift+Volume Down,Shift+Volume Down,Decrease Volume by 1% +increase_microphone_volume=Microphone Volume Up,Microphone Volume Up,Increase Microphone Volume +increase_volume=Volume Up,Volume Up,Increase Volume +increase_volume_small=Shift+Volume Up,Shift+Volume Up,Increase Volume by 1% +mic_mute=Microphone Mute\tMeta+Volume Mute,Microphone Mute\tMeta+Volume Mute,Mute Microphone +mute=Volume Mute,Volume Mute,Mute +push_to_talk=none,none,Push to talk + +[ksmserver] +Halt Without Confirmation=none,none,Shut Down Without Confirmation +Lock Session=Meta+L,Screensaver\tMeta+L,Lock Session +Log Out=Ctrl+Alt+Del,Ctrl+Alt+Del,Show Logout Screen +Log Out Without Confirmation=Meta+Del,none,Log Out Without Confirmation +LogOut=none,none,Log Out +Reboot=none,none,Reboot +Reboot Without Confirmation=none,none,Reboot Without Confirmation +Shut Down=none,none,Shut Down +_k_friendly_name=Session Management + +[kwin] +Activate Window Demanding Attention=Meta+Ctrl+A,Meta+Ctrl+A,Activate Window Demanding Attention +Cycle Overview=none,none,Cycle through Overview and Grid View +Cycle Overview Opposite=none,none,Cycle through Grid View and Overview +Decrease Opacity=none,none,Decrease Opacity of Active Window by 5% +Edit Tiles=none,Meta+T,Toggle Tiles Editor +Expose=Ctrl+F9\tMeta+F9,Ctrl+F9\tMeta+F9,Toggle Present Windows (Current desktop) +ExposeAll=Launch (C)\tCtrl+F10\tMeta+F10,Launch (C)\tCtrl+F10\tMeta+F10,Toggle Present Windows (All desktops) +ExposeClass=Ctrl+F7\tMeta+F7,Ctrl+F7\tMeta+F7,Toggle Present Windows (Window class) +ExposeClassCurrentDesktop=none,none,Toggle Present Windows (Window class on current desktop) +Grid View=none,Meta+G,Toggle Grid View +Increase Opacity=none,none,Increase Opacity of Active Window by 5% +Kill Window=Meta+Ctrl+Esc,Meta+Ctrl+Esc,Kill Window +Move Tablet to Next LogicalOutput=none,none,Move the tablet to the next output +Move Tablet to Next Output=none,none,Move the tablet to the next output +MoveMouseToCenter=Meta+F6,Meta+F6,Center Pointer in Screen +MoveMouseToFocus=Meta+F5,Meta+F5,Center Pointer in Focused Window +MoveZoomDown=none,none,Move Zoomed Area Downwards +MoveZoomLeft=none,none,Move Zoomed Area to Left +MoveZoomRight=none,none,Move Zoomed Area to Right +MoveZoomUp=none,none,Move Zoomed Area Upwards +Overview=none,Meta+W,Toggle Overview +Setup Window Shortcut=none,none,Setup Window Shortcut +Show Desktop=Meta+D,Meta+D,Peek at Desktop +Switch One Desktop Down=Meta+Ctrl+Down,Meta+Ctrl+Down,Switch One Desktop Down +Switch One Desktop Up=Meta+Ctrl+Up\tMeta+Ctrl+Shift+Up,Meta+Ctrl+Up,Switch One Desktop Up +Switch One Desktop to the Left=Meta+Ctrl+Left,Meta+Ctrl+Left,Switch One Desktop to the Left +Switch One Desktop to the Right=Meta+Ctrl+Right,Meta+Ctrl+Right,Switch One Desktop to the Right +Switch Window Down=Ctrl+Alt+J\tCtrl+Alt+Down\tMeta+Shift+K\tMeta+Shift+Down\tMeta+Ctrl+J,Meta+Alt+Down,Switch to Window Below +Switch Window Left=Ctrl+Alt+H\tCtrl+Alt+Left\tMeta+Shift+H\tMeta+Shift+Left\tMeta+Ctrl+H,Meta+Alt+Left,Switch to Window to the Left +Switch Window Right=Ctrl+Alt+L\tCtrl+Alt+Right\tMeta+Shift+L\tMeta+Shift+Right\tMeta+Ctrl+L,Meta+Alt+Right,Switch to Window to the Right +Switch Window Up=Ctrl+Alt+K\tCtrl+Alt+Up\tMeta+Shift+J\tMeta+Shift+Up\tMeta+Ctrl+K,Meta+Alt+Up,Switch to Window Above +Switch to Desktop 1=Ctrl+F1\tMeta+1,Ctrl+F1\tMeta+F1,Switch to Desktop 1 +Switch to Desktop 10=Meta+0,none,Switch to Desktop 10 +Switch to Desktop 11=none,none,Switch to Desktop 11 +Switch to Desktop 12=none,none,Switch to Desktop 12 +Switch to Desktop 13=none,none,Switch to Desktop 13 +Switch to Desktop 14=none,none,Switch to Desktop 14 +Switch to Desktop 15=none,none,Switch to Desktop 15 +Switch to Desktop 16=none,none,Switch to Desktop 16 +Switch to Desktop 17=none,none,Switch to Desktop 17 +Switch to Desktop 18=none,none,Switch to Desktop 18 +Switch to Desktop 19=none,none,Switch to Desktop 19 +Switch to Desktop 2=Ctrl+F2\tMeta+2,Ctrl+F2\tMeta+F2,Switch to Desktop 2 +Switch to Desktop 20=none,none,Switch to Desktop 20 +Switch to Desktop 21=none,none,Switch to Desktop 21 +Switch to Desktop 22=none,none,Switch to Desktop 22 +Switch to Desktop 23=none,none,Switch to Desktop 23 +Switch to Desktop 24=none,none,Switch to Desktop 24 +Switch to Desktop 25=none,none,Switch to Desktop 25 +Switch to Desktop 3=Ctrl+F3\tMeta+3,Ctrl+F3\tMeta+F3,Switch to Desktop 3 +Switch to Desktop 4=Ctrl+F4\tMeta+4,Ctrl+F4\tMeta+F4,Switch to Desktop 4 +Switch to Desktop 5=Meta+5,none,Switch to Desktop 5 +Switch to Desktop 6=Meta+6,none,Switch to Desktop 6 +Switch to Desktop 7=Meta+7,none,Switch to Desktop 7 +Switch to Desktop 8=Meta+8,none,Switch to Desktop 8 +Switch to Desktop 9=Meta+9,none,Switch to Desktop 9 +Switch to Next Desktop=Meta+Ctrl+Shift+L\tMeta+Ctrl+Shift+Right,none,Switch to Next Desktop +Switch to Next Screen=none,none,Switch to Next Screen +Switch to Previous Desktop=Meta+Ctrl+Shift+H\tMeta+Ctrl+Shift+Left,none,Switch to Previous Desktop +Switch to Previous Screen=none,none,Switch to Previous Screen +Switch to Screen 0=none,none,Switch to Screen 0 +Switch to Screen 1=none,none,Switch to Screen 1 +Switch to Screen 2=none,none,Switch to Screen 2 +Switch to Screen 3=none,none,Switch to Screen 3 +Switch to Screen 4=none,none,Switch to Screen 4 +Switch to Screen 5=none,none,Switch to Screen 5 +Switch to Screen 6=none,none,Switch to Screen 6 +Switch to Screen 7=none,none,Switch to Screen 7 +Switch to Screen Above=none,none,Switch to Screen Above +Switch to Screen Below=none,none,Switch to Screen Below +Switch to Screen to the Left=none,none,Switch to Screen to the Left +Switch to Screen to the Right=none,none,Switch to Screen to the Right +Toggle Night Color=none,none,Suspend/Resume Night Light +Toggle Show Compositing=none,none,Toggle “Show Compositing” effect +Toggle Window Raise/Lower=none,none,Toggle Window Raise/Lower +ToggleMouseClick=Meta+*,Meta+*,Toggle Mouse Click Animation +Walk Through Windows=Alt+Tab,Alt+Tab\tMeta+Tab,Walk Through Windows +Walk Through Windows (Reverse)=Alt+Shift+Tab,Alt+Shift+Tab\tMeta+Shift+Tab,Walk Through Windows (Reverse) +Walk Through Windows Alternative=none,none,Walk Through Windows Alternative +Walk Through Windows Alternative (Reverse)=none,none,Walk Through Windows Alternative (Reverse) +Walk Through Windows of Current Application=Alt+`,Alt+`\tMeta+`,Walk Through Windows of Current Application +Walk Through Windows of Current Application (Reverse)=Alt+~,Alt+~\tMeta+~,Walk Through Windows of Current Application (Reverse) +Walk Through Windows of Current Application Alternative=none,none,Walk Through Windows of Current Application Alternative +Walk Through Windows of Current Application Alternative (Reverse)=none,none,Walk Through Windows of Current Application Alternative (Reverse) +Window Above Other Windows=none,none,Keep Window Above Others +Window Below Other Windows=none,none,Keep Window Below Others +Window Close=Alt+F4\tMeta+Q,Alt+F4,Close Window +Window Custom Quick Tile Bottom=none,none,Custom Quick Tile Window to the Bottom +Window Custom Quick Tile Left=none,none,Custom Quick Tile Window to the Left +Window Custom Quick Tile Right=none,none,Custom Quick Tile Window to the Right +Window Custom Quick Tile Top=none,none,Custom Quick Tile Window to the Top +Window Fullscreen=Shift+F11\tAlt+Return,none,Make Window Fullscreen +Window Grow Horizontal=none,none,Expand Window Horizontally +Window Grow Vertical=none,none,Expand Window Vertically +Window Lower=none,none,Lower Window +Window Maximize=Meta+Return\tMeta+PgUp,Meta+PgUp,Maximize Window +Window Maximize Horizontal=none,none,Maximize Window Horizontally +Window Maximize Vertical=none,none,Maximize Window Vertically +Window Minimize=Meta+Esc\tMeta+PgDown,Meta+PgDown,Minimize Window +Window Move=Meta+Z,none,Move Window +Window Move Center=none,none,Move Window to the Center +Window No Border=none,none,Toggle Window Titlebar and Frame +Window On All Desktops=Meta+Shift+F,none,Keep Window on All Desktops +Window One Desktop Down=none,Meta+Ctrl+Shift+Down,Window One Desktop Down +Window One Desktop Up=none,Meta+Ctrl+Shift+Up,Window One Desktop Up +Window One Desktop to the Left=none,Meta+Ctrl+Shift+Left,Window One Desktop to the Left +Window One Desktop to the Right=none,Meta+Ctrl+Shift+Right,Window One Desktop to the Right +Window One Screen Down=none,none,Move Window One Screen Down +Window One Screen Up=none,none,Move Window One Screen Up +Window One Screen to the Left=none,none,Move Window One Screen to the Left +Window One Screen to the Right=none,none,Move Window One Screen to the Right +Window Operations Menu=Alt+F3,Alt+F3,Window Menu +Window Pack Down=Meta+Alt+Down,none,Move Window Down +Window Pack Left=Meta+Alt+Left,none,Move Window Left +Window Pack Right=Meta+Alt+Right,none,Move Window Right +Window Pack Up=Meta+Alt+Up,none,Move Window Up +Window Quick Tile Bottom=Meta+Down\tMeta+Alt+\\,\tMeta+Alt+K,Meta+Down,Quick Tile Window to the Bottom +Window Quick Tile Bottom Left=none,none,Quick Tile Window to the Bottom Left +Window Quick Tile Bottom Right=none,none,Quick Tile Window to the Bottom Right +Window Quick Tile Left=Meta+Left\tMeta+Alt+H,Meta+Left,Quick Tile Window to the Left +Window Quick Tile Right=Meta+Right\tMeta+Alt+L,Meta+Right,Quick Tile Window to the Right +Window Quick Tile Top=Meta+Up\tMeta+Alt+J,Meta+Up,Quick Tile Window to the Top +Window Quick Tile Top Left=none,none,Quick Tile Window to the Top Left +Window Quick Tile Top Right=none,none,Quick Tile Window to the Top Right +Window Raise=none,none,Raise Window +Window Resize=Meta+X,none,Resize Window +Window Restore=Meta+Backspace,Meta+Backspace,Restore Window +Window Shrink Horizontal=none,none,Shrink Window Horizontally +Window Shrink Vertical=none,none,Shrink Window Vertically +Window to Desktop 1=Meta+Ctrl+1,none,Window to Desktop 1 +Window to Desktop 10=Meta+Ctrl+0,none,Window to Desktop 10 +Window to Desktop 11=none,none,Window to Desktop 11 +Window to Desktop 12=none,none,Window to Desktop 12 +Window to Desktop 13=none,none,Window to Desktop 13 +Window to Desktop 14=none,none,Window to Desktop 14 +Window to Desktop 15=none,none,Window to Desktop 15 +Window to Desktop 16=none,none,Window to Desktop 16 +Window to Desktop 17=none,none,Window to Desktop 17 +Window to Desktop 18=none,none,Window to Desktop 18 +Window to Desktop 19=none,none,Window to Desktop 19 +Window to Desktop 2=Meta+Ctrl+2,none,Window to Desktop 2 +Window to Desktop 20=none,none,Window to Desktop 20 +Window to Desktop 21=none,none,Window to Desktop 21 +Window to Desktop 22=none,none,Window to Desktop 22 +Window to Desktop 23=none,none,Window to Desktop 23 +Window to Desktop 24=none,none,Window to Desktop 24 +Window to Desktop 25=none,none,Window to Desktop 25 +Window to Desktop 3=Meta+Ctrl+3,none,Window to Desktop 3 +Window to Desktop 4=Meta+Ctrl+4,none,Window to Desktop 4 +Window to Desktop 5=Meta+Ctrl+5,none,Window to Desktop 5 +Window to Desktop 6=Meta+Ctrl+6,none,Window to Desktop 6 +Window to Desktop 7=Meta+Ctrl+7,none,Window to Desktop 7 +Window to Desktop 8=Meta+Ctrl+8,none,Window to Desktop 8 +Window to Desktop 9=Meta+Ctrl+9,none,Window to Desktop 9 +Window to Next Desktop=Meta+Ctrl+Alt+L\tMeta+Ctrl+Alt+Right,none,Window to Next Desktop +Window to Next Screen=none,Meta+Shift+Right,Move Window to Next Screen +Window to Previous Desktop=Meta+Ctrl+Alt+H\tMeta+Ctrl+Alt+Left,none,Window to Previous Desktop +Window to Previous Screen=none,Meta+Shift+Left,Move Window to Previous Screen +Window to Screen 0=none,none,Move Window to Screen 0 +Window to Screen 1=none,none,Move Window to Screen 1 +Window to Screen 2=none,none,Move Window to Screen 2 +Window to Screen 3=none,none,Move Window to Screen 3 +Window to Screen 4=none,none,Move Window to Screen 4 +Window to Screen 5=none,none,Move Window to Screen 5 +Window to Screen 6=none,none,Move Window to Screen 6 +Window to Screen 7=none,none,Move Window to Screen 7 +_k_friendly_name=KWin +disableInputCapture=Meta+Shift+Esc,Meta+Shift+Esc,Disable Active Input Capture +view_actual_size=Meta+),Meta+0,Zoom to Actual Size +view_zoom_in=Meta++,Meta++\tMeta+=,Zoom In +view_zoom_out=Meta+_,Meta+-,Zoom Out + +[kwin][$InverseAction] +Cycle Overview=Cycle Overview Opposite +Increase Opacity=Decrease Opacity +MoveZoomDown=MoveZoomUp +MoveZoomLeft=MoveZoomRight +Switch One Desktop Down=Switch One Desktop Up +Switch One Desktop to the Left=Switch One Desktop to the Right +Switch Window Right=Switch Window Left +Switch Window Up=Switch Window Down +Switch to Next Screen=Switch to Previous Screen +Switch to Previous Desktop=Switch to Next Desktop +Switch to Screen Below=Switch to Screen Above +Switch to Screen to the Right=Switch to Screen to the Left +Walk Through Windows (Reverse)=Walk Through Windows +Walk Through Windows Alternative=Walk Through Windows Alternative (Reverse) +Walk Through Windows of Current Application (Reverse)=Walk Through Windows of Current Application +Walk Through Windows of Current Application Alternative (Reverse)=Walk Through Windows of Current Application Alternative +Window Grow Horizontal=Window Shrink Horizontal +Window Grow Vertical=Window Shrink Vertical +Window One Desktop Up=Window One Desktop Down +Window One Desktop to the Left=Window One Desktop to the Right +Window One Screen Up=Window One Screen Down +Window One Screen to the Right=Window One Screen to the Left +Window Pack Right=Window Pack Left +Window Pack Up=Window Pack Down +Window Raise=Window Lower +Window to Next Screen=Window to Previous Screen +Window to Previous Desktop=Window to Next Desktop +view_zoom_in=view_zoom_out + +[mediacontrol] +_k_friendly_name=Media Controller +mediavolumedown=none,none,Media volume down +mediavolumeup=none,none,Media volume up +nextmedia=Media Next,Media Next,Media playback next +pausemedia=Media Pause,Media Pause,Pause media playback +playmedia=none,none,Play media playback +playpausemedia=Media Play,Media Play,Play/Pause media playback +previousmedia=Media Previous,Media Previous,Media playback previous +seekbackwardmedia=Media Rewind,Media Rewind,Media playback seek backward 5s +seekbackwardmedialong=none,none,Media playback seek backward 30s +seekforwardmedia=Media Fast Forward,Media Fast Forward,Media playback seek forward 5s +seekforwardmedialong=none,none,Media playback seek forward 30s +stopmedia=Media Stop,Media Stop,Stop media playback + +[org_kde_powerdevil] +Decrease Keyboard Brightness=Keyboard Brightness Down,Keyboard Brightness Down,Decrease Keyboard Brightness +Decrease Screen Brightness=Monitor Brightness Down,Monitor Brightness Down,Decrease Screen Brightness +Decrease Screen Brightness Small=Shift+Monitor Brightness Down,Shift+Monitor Brightness Down,Decrease Screen Brightness by 1% +Hibernate=Hibernate,Hibernate,Hibernate +Increase Keyboard Brightness=Keyboard Brightness Up,Keyboard Brightness Up,Increase Keyboard Brightness +Increase Screen Brightness=Monitor Brightness Up,Monitor Brightness Up,Increase Screen Brightness +Increase Screen Brightness Small=Shift+Monitor Brightness Up,Shift+Monitor Brightness Up,Increase Screen Brightness by 1% +PowerDown=Power Down,Power Down,Power Down +PowerOff=Power Off,Power Off,Power Off +Sleep=Sleep,Sleep,Suspend +Toggle Keyboard Backlight=Keyboard Light On/Off,Keyboard Light On/Off,Toggle Keyboard Backlight +Turn Off Screen=none,none,Turn Off Screen +_k_friendly_name=Power Management +powerProfile=Battery,Battery\tMeta+B,Switch Power Profile + +[plasmashell] +Slideshow Wallpaper Next Image=Meta+Ctrl+Alt+Shift+Right,none,Next Wallpaper Image +_k_friendly_name=plasmashell +activate application launcher=Meta,Meta\tAlt+F1,Activate Application Launcher +activate next task manager entry=Meta+Ctrl+PgDown,Meta+Ctrl+PgDown,Activate Next Task Manager Entry +activate previous task manager entry=Meta+Ctrl+PgUp,Meta+Ctrl+PgUp,Activate Previous Task Manager Entry +activate task manager entry 1=none,Meta+1,Activate Task Manager Entry 1 +activate task manager entry 10=none,none,Activate Task Manager Entry 10 +activate task manager entry 2=none,Meta+2,Activate Task Manager Entry 2 +activate task manager entry 3=none,Meta+3,Activate Task Manager Entry 3 +activate task manager entry 4=none,Meta+4,Activate Task Manager Entry 4 +activate task manager entry 5=none,Meta+5,Activate Task Manager Entry 5 +activate task manager entry 6=none,Meta+6,Activate Task Manager Entry 6 +activate task manager entry 7=none,Meta+7,Activate Task Manager Entry 7 +activate task manager entry 8=none,Meta+8,Activate Task Manager Entry 8 +activate task manager entry 9=none,Meta+9,Activate Task Manager Entry 9 +activate widget 47=none,none,Activate System Monitor Widget +activate widget 61=none,none,Activate Activity Pager Widget +activate widget 69=none,none,Activate System Monitor Widget +activate widget 70=none,none,Activate System Monitor Widget +clear history=none,none,Clear Notification History +clear-history=none,none,Clear Clipboard History +clipboard_action=none,none,Toggle Automatic Popping Up of Action Menu +cycle-panels=Meta+Alt+P,Meta+Alt+P,Move keyboard focus between panels +cycleNextAction=none,none,Next History Item +cyclePrevAction=none,none,Previous History Item +edit_clipboard=none,none,Edit Contents… +manage activities=none,Meta+Q,Show Activity Switcher +move active task to left=Meta+Ctrl+Shift+PgUp,Meta+Ctrl+Shift+PgUp,Move Active Task Manager Entry Backward +move active task to right=Meta+Ctrl+Shift+PgDown,Meta+Ctrl+Shift+PgDown,Move Active Task Manager Entry Forward +next activity=none,none,Walk through activities +previous activity=Meta+Shift+A,none,Walk through activities (Reverse) +repeat_action=Meta+Ctrl+R,none,Manually Invoke Action on Current Clipboard +show dashboard=Ctrl+F12,Ctrl+F12,Show Desktop +show-barcode=none,none,Show Barcode… +show-on-mouse-pos=Meta+V,Meta+V,Show Clipboard Items at Mouse Position +switch to next activity=none,none,Switch to Next Activity +switch to previous activity=none,none,Switch to Previous Activity +toggle do not disturb=none,none,Toggle do not disturb + +[services][Alacritty.desktop] +_launch=Meta+Shift+T + +[services][FreeTube.desktop] +_launch=Meta+F + +[services][betterbird.desktop] +_launch=Meta+M + +[services][chromium.desktop] +_launch=Meta+Shift+B + +[services][com.mitchellh.ghostty.desktop] +_launch=none + +[services][ferdium.desktop] +_launch=Meta+Y + +[services][kitty.desktop] +_launch=Ctrl+Alt+T\tMeta+T + +[services][librewolf.desktop] +_launch=Meta+B + +[services][net.local.kitty-2.desktop] +_launch=Meta+I + +[services][net.local.kitty-3.desktop] +_launch=Meta+O + +[services][net.local.kitty.desktop] +_launch=Meta+R + +[services][nvim.desktop] +_launch=Meta+C + +[services][org.gajim.Gajim.desktop] +StartChat=Meta+G + +[services][org.kde.krunner.desktop] +_launch=Search\tAlt+Space\tAlt+F2\tCtrl+Alt+S\tMeta+A\tMeta+S + +[services][org.kde.plasma-systemmonitor.desktop] +_launch=Ctrl+Shift+Esc + +[services][org.kde.spectacle.desktop] +RecordRegion=Meta+Shift+R +RecordWindow=none +RectangularRegionScreenShot=Meta+P +_launch=Print\tMeta+Shift+P\tMeta+Shift+S + +[services][org.keepassxc.KeePassXC.desktop] +_launch=Meta+K + +[services][st.desktop] +_launch=Meta+Ctrl+T + +[services][systemsettings.desktop] +_launch=Tools + +[services][thorium-browser.desktop] +_launch=Meta+Ctrl+B diff --git a/fl/.config/llamacpp/README.md b/fl/.config/llamacpp/README.md new file mode 100644 index 0000000..d066898 --- /dev/null +++ b/fl/.config/llamacpp/README.md @@ -0,0 +1,231 @@ +# Local LLM server — setup & usage + +llama.cpp in **router mode** serving ~10 model presets from one 16 GB GPU. +Last full tune: **2026-07-16** (decode numbers measured then via `bench.py`, unless a preset comment in `config.ini` says otherwise). +Last full clean sweep: **2026-08-08 03:22** — all 11 presets loaded and ran green (baseline 2.0 GB) after the week's coder-race/KV-fix/gemma-sidecar round. + +- **Box**: AMD RX 7600 XT 16 GB (~288 GB/s; backend = Arch `llama-cpp` 0.5.0 + `ggml-vulkan` / RADV = llama.cpp **b11146** since 2026-10-02, **not** ROCm — + `rocm-smi` is only the VRAM monitor) + Ryzen 5600X (6 cores) + 48 GB RAM. + ⚠ The GPU **also drives the display** — see [VRAM safety](#vram-safety-the-golden-rules). +- **Endpoints**: LAN `http://$SERVER:11343/v1` · remote `https:///api/v1` + (own reverse proxy to the same server; requires an API key. Only the LAN endpoint is keyless). + `$SERVER` = the box's LAN address. +- **Files here**: `config.ini` (model presets — the section names ARE the API model ids), + `bench.py` (safety-first benchmark), `bench-results.md` / `bench-history.md` (ledgers, generated). + +## How it runs + +systemd unit **`llama.service`** (on the server, under a dedicated service user) runs a script wrapping: + +``` +llama-server --port 11343 --host 0.0.0.0 --models-max 1 --models-preset ~/.config/llamacpp/config.ini +``` + +- Router mode: each requested model loads on demand in a child process. +- **`--models-max 1` is deliberate and load-bearing**: at most one model resident; requesting + another LRU-evicts the current one *first*. Anything ≥2 lets two ~13 GB models stack → + VRAM overcommit → GTT spill → **whole-PC freeze**. Do not raise it casually. + (`sleep-idle-seconds` per preset is the second line of defense.) +- Models live in `~/software/models/` (paths in `config.ini` must stay absolute — llama-server + does not expand `~` or env vars in preset values). mmproj/draft files must match the exact + filename in the preset (watch for trailing spaces when renaming downloads!). + +**Deploying config changes**: this dir is stowed into `~/.config/llamacpp/` as per-file +symlinks, so on the server `dotsync` (pull; re-stows only if files were added/removed) then +`sudo systemctl restart llama.service` — the router reads presets once at startup. +After ANY preset change: restart + `./bench.py -m ` and check the guards. + +**Upgrading llama.cpp itself** (2026-10-02, b10615 → b11146): Arch replaced `llama.cpp-vulkan` +with a unified `llama-cpp` package on top of the system `ggml`, whose backends are split out. +`sudo pacman -Syu ggml llama-cpp ggml-vulkan` — name **`ggml`** explicitly (it conflicts with +the old `ggml-cpu` without replacing it, and the removal prompt defaults to N), and **`ggml-vulkan`** +explicitly (only an optdepend — without it llama-server silently runs on the CPU backend). +Then restart, and `llama-server --list-devices` must show `Vulkan0`. `whisper-cpp` moves to the +same `ggml` (CPU backends are inside the base package) — restart its unit too. + +## VRAM safety (the golden rules) + +The amdgpu driver does not OOM cleanly — an overcommitted model spills into GTT (system RAM), +starves the desktop and freezes the PC (reboot). Hard-won rules: + +1. Keep every preset's benched **VRAM free ≥ 2.5 GB** (idle desktop uses ~1.3 of 17.2). +2. File size > VRAM is **fine** for MoE — `n-cpu-moe N` keeps the first N layers' experts + in system RAM. It is the main tuning knob: higher = safer/slower, lower = faster. +3. Bench with a **clean baseline** (close the browser): a dirty baseline both skews the + margins and costs ~3–4 t/s of decode (GPU compute contention — measured 2026-07-08). +4. Bench after every change; config-edit without restart = numbers from the *old* config. + +## Model roster (reference numbers = clean night sweeps, 2026-07-16) + +| model id | decode t/s | ctx | extras | role | +|---|---|---|---|---| +| `gemma-4-E4B-it-UD-Q8_K_XL` | **57.3** | **96k** | vision, MTP, prefill 185 t/s | fast small generalist, long docs, images (ctx 96k ✓ 08-08, n_ctx_train 131072) | +| `Qwen3.6-35B-A3B-Thinking` | 38.8 | 24k | MTP, vision, reasoning (budget 8k = "medium") | **default model** in opencode/pi/aichat since 09-21; hard problems, slow-but-smart answers | +| `gpt-oss-20b` | 38.4 | **64k** | reasoning, tools | fast reasoning + tool use · fast long-context (37 t/s vs Coder-Next 16; 131k ruled out) | +| `gpt-oss-20b-low` | 37.2 | **64k** | reasoning LOW, TTFT 0.8 s | same model, snappy answers (no long preamble) | +| `Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS` | 35.9 | 24k | MTP, vision, thinking OFF | **daily driver** — compact instant answers | +| `gemma-4-26B-A4B-it-UD-IQ4_XS` | 33.9 | 24k | vision, MTP | quality generalist + best vision | +| `Qwen3.5-9B-UD-Q6_K_XL` | 32.1 | 32k | vision, MTP, reasoning | small Qwen, quick tasks | +| `Qwen3-Coder-30B-Instruct-UD-Q3_K_XL` | **~30** clean / 27.0 evening @moe12 | 32k | — | **main agent coder** — won the 2026-08-06 quant race; moe12 verified evening 08-07 + clean 08-08 | +| `GLM-4.7-Flash-UD-Q4_K_XL` | **21.5** @moe22 | 24k | reasoning | quality coder (opencode subagents); KV fix + moe22 ✓ verified clean 08-08 | +| `GLM-4.7-Flash-UD-Q3_K_XL` | **26.0** @moe12 (2.0 daytime baseline; ~28 clean) | 24k | reasoning | **fast coder** — re-added 09-21 because Q4's 21.5 dragged in agent loops; 3-bit, evening-safe at moe12 (13.4 used / 3.8 free @2.0); Q4 stays for hard reviews | +| `Qwen3-Coder-Next-UD-IQ3_XXS` | 16.0 | **128k** | 80B-A3B | long-session coder (128k ctx) | +| `Qwen3.8-27B-UD-IQ3_XXS` | **36–37** on b11429 (10-22 ×2; was 15.5 on b11146, 10.9 base) | 24k | vision, MTP, hybrid reasoner @ **xhigh** | ⚠ **clean-desktop specialty** (kept 09-10 over the ≥22 gate — **the speed half is now passed 1.7× over**, since llama.cpp 0.6.0 halved the per-step MTP cost; role re-rank pending the user) — dense-27B quality; prefill still GDN-bound (~20–35). 2.7 GB free @1.3 baseline @24k (✓ 10-22 on b11429, `-n 512`, acceptance 0.89, len 2.78). The *felt* slowness is the **xhigh thinking preamble** (17.5 s before the first answer token on a trivial prompt; `reasoning_effort=low` measured 6.45 s at the same decode on 10-02 — siblings benched then removed by decision, the kwarg is one line if ever wanted); **never on a busy evening desktop** (~1 GB free = GTT freeze) | +| `Qwen3-Embedding-0.6B` | 33 (CPU) | 8k | CPU-only, `/v1/embeddings` | RAG/search embedder (not a chat model) | +| `Ornith-1.5-35B-A3B-IQ3_XXS` | **32.1** @moe16 | **32k** (10-22, unbenched) | MTP, vision, thinking | **agentic coder** (added 09-21) — Qwen3.5-MoE derivative claiming +15 Terminal-Bench / +5.6 SWE-bench over Qwen3.6-35B; the only coder with MTP; 13.8 used / 3.3 free @2.0 | + +Expected run-to-run spread: MTP models swing ±15% with draft **acceptance rate** (content- +dependent); CPU-heavy presets (Coder-Next, embedder) dip under daytime CPU contention. +Treat clean night runs as the reference; don't retune on daytime deltas. + +## Which model, when + +- **Agent coding loops** (edit/test cycles): `Qwen3-Coder-30B` — best speed/quality balance at 32k. +- **Hard code, reviews, tricky bugs**: `GLM-4.7-Flash` — strongest 30B-class coder, slightly slower. +- **GLM at agent-loop speed**: `GLM-4.7-Flash-UD-Q3_K_XL` — same model, 3-bit, ~28 t/s; pick it + when the Q4's 21 t/s drags, keep Q4 for the review that has to be right. +- **Agentic coding with reasoning** (⚗ new, judge over the next weeks): `Ornith-1.5-35B-A3B` — + Qwen3.5-MoE derivative, 32 t/s *with* MTP and a thinking preamble (~4 s TTFT), vision. If its + launch numbers hold in practice it displaces GLM/Coder-30B for agent loops. +- **Marathon sessions / huge conversation history**: `Qwen3-Coder-Next` — 128k ctx at only + 6 GB VRAM (hybrid attention). Caveat: ~33 t/s prefill means it's for *growing* sessions + (`cache-reuse` makes turns incremental), **not** for cold-dumping 100k tokens. +- **Everyday questions**: `Qwen3.6-35B-A3B` — no reasoning preamble, 36 t/s. +- **Hard reasoning**: `35B-Thinking` (quality) or `gpt-oss-20b` (speed + tool use). + Their multi-second TTFT is the reasoning phase streaming first — not a slow load. + For quick interactive gpt-oss answers use `gpt-oss-20b-low` (reasoning effort low). +- **Best single-model quality** (quiet desktop only): `Qwen3.8-27B` — dense 27B hybrid reasoner + + vision at **37 t/s since llama.cpp 0.6.0** (was ~15 on 0.5.0; prefill still GDN-bound on Vulkan), + but a busy evening desktop pushes it into GTT-freeze territory — check `rocm-smi` first. +- **Images**: `gemma-4-26B` for quality, `gemma-4-E4B` or `Qwen3.5-9B` for speed, + `Qwen3.6-35B` when you want the daily driver to see the screenshot. +- **Long one-shot documents**: `gemma-4-E4B` — 185 t/s prefill eats 64k in ~6 min + (Coder-Next would take ~30 min to prefill the same). +- **RAG embeddings**: point Open WebUI etc. at `Qwen3-Embedding-0.6B`. Runs on CPU by + design — 0 VRAM, can never contribute to an overcommit. + +## Speech-to-text (separate service) + +STT deliberately does **not** live in this router — it is a CPU-only whisper.cpp service on port +11345, documented in `../whisper/README.md`. Two reasons: `models-max 1` would make every +transcription LRU-evict the resident chat model, and llama.cpp decodes audio via miniaudio +(wav/mp3/flac only) while browsers record opus. + +The router *does* answer `POST /v1/audio/transcriptions` — it rewrites the request into a chat +completion — so `gemma-4-E4B-it-UD-Q8_K_XL` (audio-capable via its mmproj) transcribes uploaded +wav/mp3/flac with no config change. Keep that as the fallback; mind the eviction. + +## Text-to-speech (separate service) + +TTS is **not servable from this router at all** — unlike STT, there is no fallback. `llama-server` +has `--model-vocoder` / `--tts-use-guide-tokens`, but exposes **no `/v1/audio/speech` route**: +the router 404s on it exactly like an undefined path, and `grep -rn "audio/speech"` over the +b10216 tree returns nothing — the only audio route registered is `/v1/audio/transcriptions` (STT). +Worse, `--model-vocoder` is accepted by the server and then **silently ignored**: it is registered +in the arg table and documented, but no server code path consumes it. `--help` listing it is not +evidence it works. `llama-tts` is a CLI. (All verified 2026-08-09.) + +So TTS is a CPU-only Kokoro-82M service on port **11347**, documented in `../tts/README.md` +(repo-side only — not installed on fl yet). The `models-max 1` argument applies even harder there +than for STT: TTS fires on *every* response, so a resident preset would evict the chat model every +single turn. + +## Client wiring + +The same catalog is mirrored in every client — when adding/removing a preset, update all: + +- `common/.config/opencode/opencode.json` (both providers + agent model overrides) +- `common/.pi/agent/models.json` (both providers; `contextWindow` = server `ctx-size`) +- `common/.config/aichat/config.yaml` (both clients) +- `wm/.config/aichat/config.yaml` — full-file overlay for the off-LAN host (default client `duskadiy`); + every aichat change must be mirrored here too (missed for GLM Q3 + Ornith until 09-21). With the + lw/ overlays that makes **seven** client files. + +Rule: client model **id = config.ini section name**, client context ≤ server `ctx-size`. +The embedder is deliberately absent from chat clients. +2026-08-06: the coder id changed `…-IQ4_XS` → `…-UD-Q3_K_XL` in all six client files +(common + lw overlays) after the quant race; OWUI picks the new id up automatically from +the router, but chats/presets saved against the old id need re-picking. +2026-08-16: `Qwen3.8-27B-UD-IQ3_XXS` (⚗ candidate) added to all six client files. +2026-09-10: kept as ⚠ clean-desktop specialty after the gate bench finally ran on the v3 gguf +(14.5 t/s MTP / 10.9 base, 2.8 GB free @1.5); server ctx restored to 24576 = client ctx, no client edits. +2026-09-21: `GLM-4.7-Flash-UD-Q3_K_XL` (⚡ fast coder) added to all six client files next to the Q4. +2026-10-22: Qwen3.8-27B quant race opened (ISTA GSQ-RCO IQ3_XXS-mtp + DFlash2 sibling) — bench-only, +NO client edits until a candidate wins; see the watch list. Same night: fl found on llama.cpp 0.6.0 +(b11429) and the Qwen3.8 incumbent re-measured 37.1 t/s (15.5 on b11146) — every MTP/hybrid preset +on the roster needs a re-sweep on this build; ledger numbers above it are from 0.5.0 unless dated 10-22. +2026-09-21: `Ornith-1.5-35B-A3B-IQ3_XXS` (agentic coder, thinking + vision) added to all six client files after passing its gate (32.1 t/s @moe16). +2026-09-21: default model → `Qwen3.6-35B-A3B-Thinking` everywhere (opencode global + plan/build/auto, pi defaultModel + thinking level medium, aichat common/lw/wm) — gemma-4-26B refused routine sysadmin work. Thinking preset gets `reasoning-budget 8192`. wm aichat caught up (GLM Q3, Ornith). +2026-10-22: Ornith in pi: `Compacting in OVERFLOW recovery` right after a truncated reply is pi's *truncated-reply* recovery, not a full window — pi clamps each request's `max_tokens` to `contextWindow − estimate − 4096`, which on 24k/4096 starts exactly at the compaction threshold, so the first request after a compaction (estimate gains the system prompt + tool schemas) can leave a thinking reply ~1024 answer tokens → `length` → compact + retry. `compaction-watch.ts` now names the case with numbers; `common/.pi/CLAUDE.md` > Compaction tuning has the arithmetic. Applied the same day, UNBENCHED: Ornith `ctx-size` 24576 → 32768 + the seven client files (pi/opencode/aichat, common+lw+wm; predicted ≈ 0.1 GB of KV on this hybrid arch) — restart llama.service, then `./bench.py -m Ornith-1.5-35B-A3B-IQ3_XXS`; gate and the revert path are in the preset comment. +2026-10-12: Ornith in pi: "Response was truncated before completion." = `finish_reason: length` — the `` block counts against pi's 4096 `max_tokens` and the preset has no reasoning-budget. Fixed client-side: pi sends `thinking_budget_tokens` per thinking level on Ornith (`compat.thinkingTokenBudgetField` + `settings.json > thinkingBudgets`, common + lw). The preset deliberately keeps NO CLI reasoning-budget — it would override the per-request field (see the preset comment). + +## Tuning cheat-sheet + +- **`n-cpu-moe`** (MoE only): experts→CPU. The speed/VRAM dial. Measured curve is gentle — + tune in steps of 2–4 layers, re-bench, keep free ≥2.5 GB. +- **`ctx-size`**: KV cost varies wildly by arch — Coder-Next 64k→128k cost 0.5 GB (hybrid + attn); dense Qwens pay ~1 GB per 16k. Raise only after a bench shows the headroom. +- **Quants**: dense = bandwidth-bound, quant size sets speed directly (9B: Q8→Q6 = +87% + with MTP). MoE = buy quality with a bigger quant, pay in CPU offload (both coders run + 4-bit now; 3-bit was only ~2 t/s faster). Coders want ≥4-bit; chat tolerates UD 3-bit. +- **MTP / spec decode** (`spec-type draft-mtp`): ~1.5–2× decode. Qwen3.5/3.6 embed the + head in the *MTP-repo* GGUF (same filename as plain repo — size is the tell); + gemma-4 uses a separate `mtp-*.gguf` draft file; Qwen3.8 ships the head in the + *main*-repo GGUFs for ≥ Q2_K_XL (≤ IQ2_S are stripped — use the repo's `MTP/mtp-*.gguf` + draft instead). On the hybrid 27B it is only +33% (10.9→14.5) and costs 1.5 GB: every + speculative step re-runs the Gated-DeltaNet layers. **No MTP possible yet for**: + GLM-4.7-Flash (conversion drops the head — expected ~1.5× when llama.cpp lands it), + Qwen3-Coder-Next (Qwen3-Next head exists upstream, no GGUF ships it), gpt-oss and + Qwen3-Coder-30B (no head exists). Recheck releases occasionally. +- **KV cache**: `q8_0` K / `q4_0` V everywhere except gpt-oss (attention-sink issues with + quantized KV — keep defaults there). + +## Benchmarking + +``` +./bench.py # full sweep (add -x Qwen3-Embedding-0.6B — it can't chat) +./bench.py -m id1,id2 # just the changed presets +./bench.py -n 512 --ctx 16000 # longer gen + long-context decode column +``` + +⚠ **Benches need the server to themselves**: with `models-max 1`, a request for another +model arriving mid-load LRU **force-kills the loading instance** → fake "failed to load" +rows (and a dirty baseline). Close chat clients / OWUI before sweeping. + +Safety-first: force-unloads resident models via the router API (`POST /models/unload`), +verifies a clean card with rocm-smi before every load, records a ⚠ row and skips +generation when a model lands too tight (free < 1.5 GB or GTT ballooning). +Results: `bench-results.md` (latest) + `bench-history.md` (append-only; diff runs there). + +**Reading TTFT**: bench.py stamps it on the first non-empty `content` delta, so for thinking +models TTFT = prompt eval **plus the whole reasoning preamble**, and `0.00` means the answer never +started within `-n` tokens (thinking ate the budget). It is the column that compares +reasoning-effort siblings; for stable MTP decode numbers use `-n 512`. + +## Watch list + +- **GLM MTP in llama.cpp** — the single biggest pending win (primary coder ~22 → ~30+). +- **Qwen3.8-27B quant race (opened 2026-10-22, bench-only, not client-wired)** — two candidate + sections in `config.ini` after the incumbent: `Qwen3.8-27B-GSQ-RCO-IQ3_XXS` (ISTA-DASLab GSQ-RCO + file, 10.44 GB with MTP head = −0.49 GB vs unsloth v3) and its `-dflash` text-only sibling + (`z-lab/Qwen3.8-27B-DFlash2-GGUF` Q4_K_M drafter, `spec-draft-n-max 3`). Expected: +4 % decode and + +0.5 GB free from the file; +5–15 % over MTP from DFlash2 on RDNA3/Vulkan (not the paper's 1.8×). + Quality is unmeasured against our file — the user's own prompts decide. First run 10-22 03:14: both + candidates HTTP 400 = fl's config.ini not pulled yet (router: "model not found"); the incumbent in + the same run read **37.1 t/s on b11429** (see its row). Re-run 03:25, one session: incumbent 36.2 / + 2.7 free, **GSQ 37.5 / 3.2 free** (+3.6 %, +0.5 GB — speed+VRAM passed, **quality call open**), + **DFlash2 15.4 / 1.9 free → dropped** (tombstoned in `config.ini`). Ruled out by the same + research: ByteShape IQ4_XS (13.1 GB), ISTA IQ3_S (12.1 GB with MTP, under the floor), the + adaptive KV-cache-streaming fork (CUDA-only, PCIe 5.0). Still open: #27408 (spec + mmproj → 500), + #28158 (Vulkan OOB draft token). Research + verdicts + download lines: the config block. +- **llama.cpp 0.7.0 (b11669) — HOLD fl at 0.6.0**: #30688, Vulkan draft-mtp decode 4× / prefill 6× + slower (target compute buffer lands in GTT = this box's freeze precursor). Every MTP preset on the + roster is exposed. When `pacman -Si llama-cpp` on fl shows 0.7.0, `IgnorePkg` it until fixed. + The 0.5.0 → 0.6.0 jump itself (Qwen3.8 15.5 → 37) is llama-side, best explained by #29856 (hybrid + graph reserve; the old 10.9 base was probably GTT-starved, not kernel-bound — see the preset block). + **ggml 0.26.0** (next `-Syu`): #30039 reports a −45 % prefill regression on a GDN hybrid — bench + Qwen3.8 before and after; downgrade ggml/ggml-vulkan from the pacman cache if prefill tanks. +- **Coder-Next 256k**: if the load log's `n_ctx_train` says 262144, ctx can likely double + again for ~1 GB (KV measured nearly flat). + +> **vLLM on this box** (bench rig, docker/ROCm, never resident together with the router): see `../vllm/README.md`. diff --git a/fl/.config/llamacpp/bench.py b/fl/.config/llamacpp/bench.py new file mode 100755 index 0000000..00594cf --- /dev/null +++ b/fl/.config/llamacpp/bench.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +""" +llama.cpp router benchmark → writes a results ledger for later tuning. + +SAFETY-FIRST: this GPU also drives the display — VRAM overcommit spills to GTT and can +freeze the whole PC. The script therefore: + - records the BASELINE VRAM before touching anything (leftover model / browser skews everything) + - ensures a CLEAN card before EVERY load (incl. the first): resident models are force-unloaded + via the router API (POST /models/unload), then VRAM is verified with rocm-smi — the poll + covers driver reclaim lag, older builds without the endpoint (sleep-idle fallback), and + desktop apps the router doesn't own. Aborts if the card never drains. + - checks free VRAM right after a model mounts; too tight (--min-free-gb) or GTT ballooning + (--max-gtt-gb, measured against a PER-MODEL baseline — GTT reclaims slowly) → records a + ⚠ row and skips generating; the sweep continues after the drain-wait + - refuses to sweep multiple models blind (no rocm-smi) unless --no-vram-ok + +Per model it records decode/prefill t/s, TTFT, VRAM used/free, and the preset's knobs +(ctx, n-cpu-moe, spec-type) parsed from config.ini. + +Output: bench-results.md (latest run, overwritten) + bench-history.md (every run, appended) +— both next to this script. Run ON the GPU box. Stdlib only. + + ./bench.py # all models the server lists + ./bench.py -m id1,id2 # only these + ./bench.py -x Qwen3-Coder-Next-UD-IQ3_XXS # skip some (e.g. not downloaded yet) + ./bench.py -n 512 --ctx 16000 # longer gen + a long-context decode column +Compare a change: edit config.ini → reload server → re-run → diff runs in bench-history.md. +""" +import argparse, json, os, re, subprocess, sys, time, urllib.request, urllib.error +from datetime import datetime + +HERE = os.path.dirname(os.path.abspath(__file__)) +_smi_warned = False + + +def rocm_mem(kind="vram"): + """(used_bytes, total_bytes) from rocm-smi for 'vram' or 'gtt'; (None, None) if unavailable.""" + global _smi_warned + try: + out = subprocess.run(["rocm-smi", "--showmeminfo", kind], + capture_output=True, text=True, timeout=15).stdout + except Exception: + out = "" + def grab(pat): + m = re.search(pat + r"\s*:?\s*(\d+)", out) + return int(m.group(1)) if m else None + label = "VRAM" if kind == "vram" else "GTT" + used = grab(label + r" Total Used Memory \(B\)") or grab(r"Used Memory \(B\)") + total = grab(label + r" Total Memory \(B\)") + if kind == "vram" and total is None and not _smi_warned: + _smi_warned = True + print(" (rocm-smi not readable here — VRAM columns and freeze guards are OFF)", file=sys.stderr) + return used, total + + +def with_retries(fn, retries, wait, label=""): + """Retry on 5xx/connection errors (model still mounting). A deterministic 'failed to + load' from the router is NOT retried — that's a broken preset, not a slow mount.""" + last = None + for i in range(retries + 1): + try: + return fn() + except urllib.error.HTTPError as e: + if e.code < 500: # 4xx = real client error + raise + body = "" + try: + body = e.read().decode("utf-8", "ignore") + except Exception: + pass + if "failed to load" in body: # deterministic → don't burn retries + raise RuntimeError("model failed to load — check `journalctl -u llama.service`") from None + last = e + except (urllib.error.URLError, ConnectionError, TimeoutError) as e: + last = e + if i < retries: + print(f" … {label} not ready ({last}); waiting {wait}s (try {i + 1}/{retries})", file=sys.stderr) + time.sleep(wait) + raise last + + +def _open(url, key, payload=None, timeout=600): + data = json.dumps(payload).encode() if payload is not None else None + hdrs = {"Authorization": f"Bearer {key}"} + if data: + hdrs["Content-Type"] = "application/json" + return urllib.request.urlopen(urllib.request.Request(url, data=data, headers=hdrs), timeout=timeout) + + +def list_models(base, key): + d = json.load(_open(base.rstrip("/") + "/models", key)) + return [m["id"] for m in d.get("data", [])] + + +def force_unload(base, key): + """Ask the router to unload every resident model (POST /models/unload on the ROOT api, + not /v1). Harmless no-op on builds without the endpoint — callers fall back to polling.""" + root = re.sub(r"/v1/?$", "", base.rstrip("/")) + try: + d = json.load(_open(root + "/models", key, timeout=30)) + except Exception as e: + print(f" (router /models not readable: {e} — relying on sleep-idle drain)", file=sys.stderr) + return + for m in d.get("data", []): + st = m.get("status", "loaded") # b11146 sends {'value': 'loaded'|'sleeping'|'unloaded'}; older a string + st = st.get("value", "loaded") if isinstance(st, dict) else st + if st not in ("loaded", "loading"): # builds without 'status': try them all + continue + try: + _open(root + "/models/unload", key, {"model": m["id"]}, timeout=30).read() + except Exception: + pass # not loaded / endpoint missing — poll covers it + + +def parse_config(path): + """{preset: {ctx, ncpumoe, spec}} from the router config.ini.""" + sections, sec = {}, None + try: + lines = open(path, encoding="utf-8").read().splitlines() + except OSError: + return {} + for ln in lines: + s = ln.strip() + if s.startswith("[") and s.endswith("]"): + sec = s[1:-1]; sections[sec] = {} + elif sec and "=" in s and not s.startswith("#"): + k, v = s.split("=", 1) + sections[sec][k.strip()] = v.split("#", 1)[0].strip() + return {sec: {"ctx": kv.get("ctx-size", "-"), + "ncpumoe": kv.get("n-cpu-moe", "-"), + "spec": kv.get("spec-type", "-") or "-"} + for sec, kv in sections.items()} + + +def run(base, key, model, prompt, n, temp, timeout): + payload = {"model": model, "messages": [{"role": "user", "content": prompt}], + "max_tokens": n, "temperature": temp, "stream": True, + "stream_options": {"include_usage": True}, + # llama.cpp extension: makes the server embed its own timings in the stream → + # the table shows the SAME predicted_per_second as the llama.cpp web UI + # (without it we fall back to wall-clock estimates, which read lower). + "timings_per_token": True} + t0 = time.perf_counter(); ttft = None; ntok = 0; usage = None; timings = None + for raw in _open(base.rstrip("/") + "/chat/completions", key, payload, timeout): + line = raw.decode("utf-8", "ignore").strip() + if not line.startswith("data:"): + continue + body = line[5:].strip() + if body == "[DONE]": + break + try: + c = json.loads(body) + except ValueError: + continue + ch = c.get("choices") or [{}] + if ch and ch[0].get("delta", {}).get("content"): + if ttft is None: + ttft = time.perf_counter() - t0 + ntok += 1 + if c.get("usage"): + usage = c["usage"] + if c.get("timings"): + timings = c["timings"] + total = time.perf_counter() - t0 + comp = (usage or {}).get("completion_tokens") or ntok + ptok = (usage or {}).get("prompt_tokens") + gen_s = total - (ttft or total) + tg = comp / gen_s if gen_s > 0 else 0.0 + pp = (ptok / ttft) if (ptok and ttft) else None + if timings: # llama.cpp's own numbers are authoritative when the router forwards them + tg = timings.get("predicted_per_second", tg) + pp = timings.get("prompt_per_second", pp) + ptok = timings.get("prompt_n", ptok) + return {"tg": tg, "pp": pp, "ttft": ttft or 0.0, "ptok": ptok or 0} + + +def wait_drain(drain_gb, window_s, label="", base=None, key=None): + """Force-unload resident models via the router API, then poll until VRAM used drops + below drain_gb (card is clean) or the window expires.""" + used, _ = rocm_mem() + if base and used is not None and used > drain_gb * 1e9: + force_unload(base, key) + end = time.time() + window_s + announced = False + while used is not None and used > drain_gb * 1e9 and time.time() < end: + if not announced: + print(f" … waiting for VRAM to drain before {label} ({gb(used)} used)", file=sys.stderr) + announced = True + time.sleep(5) + used, _ = rocm_mem() + return used + + +def gb(b): + return f"{b / 1e9:.1f} GB" if b else "-" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("-u", "--url", default="http://192.168.0.204:11343/v1") + ap.add_argument("-k", "--key", default="no-key-required") + ap.add_argument("-m", "--models", default="all", help="comma-separated ids, or 'all'") + ap.add_argument("-x", "--skip", default="", help="comma-separated ids to skip") + ap.add_argument("-n", "--tokens", type=int, default=256) + ap.add_argument("-t", "--temp", type=float, default=0.3) + ap.add_argument("--ctx", type=int, default=0, help="also record decode at ~this many prompt tokens") + ap.add_argument("--timeout", type=int, default=600, help="per-request stall timeout (s)") + ap.add_argument("--config", default=os.path.join(HERE, "config.ini")) + ap.add_argument("--out", default=os.path.join(HERE, "bench-results.md")) + ap.add_argument("--history", default=os.path.join(HERE, "bench-history.md")) + ap.add_argument("--retries", type=int, default=4, help="retries while a model is still mounting") + ap.add_argument("--retry-wait", type=int, default=15, help="seconds between retries") + ap.add_argument("--drain-gb", type=float, default=4.0, + help="VRAM considered 'clean' below this (raise it if your desktop alone uses more)") + ap.add_argument("--min-free-gb", type=float, default=1.5, + help="SAFETY: stop the sweep if a loaded model leaves less VRAM free than this") + ap.add_argument("--max-gtt-gb", type=float, default=2.0, + help="SAFETY: flag a model if GTT grows more than this over baseline (= VRAM spilling to RAM)") + ap.add_argument("--unload-wait", type=int, default=360, + help="after a too-tight model, wait up to this long for it to unload before continuing " + "(sleep-idle-seconds keeps models resident up to 300s)") + ap.add_argument("--no-vram-ok", action="store_true", + help="allow a multi-model sweep even though rocm-smi (and thus the freeze guards) is unavailable") + a = ap.parse_args() + + models = list_models(a.url, a.key) if a.models == "all" else [m.strip() for m in a.models.split(",")] + skip = {s.strip() for s in a.skip.split(",") if s.strip()} + models = [m for m in models if m not in skip] + cfg = parse_config(a.config) + + used0, total_vram = rocm_mem("vram") + if total_vram is None and len(models) > 1 and not a.no_vram_ok: + sys.exit("ABORT: rocm-smi is not readable here, so the VRAM/GTT freeze guards can't work.\n" + "Run this ON the GPU box, bench a single model with -m , or pass --no-vram-ok to accept the risk.") + if used0 is not None and used0 > a.drain_gb * 1e9: + print(f"⚠ baseline VRAM used is already {gb(used0)} — a leftover model (sleep-idle keeps them " + f"up to 5 min) or desktop apps (browser!). Results/safety margins will be skewed; " + f"ideally close GPU apps or wait, then re-run.", file=sys.stderr) + + task = "Write a Python function that merges two sorted lists, with a short docstring and one example." + filler = ("The quick brown fox jumps over the lazy dog. " * max(1, a.ctx // 9)) if a.ctx else None + + cols = ["model", "cfg ctx", "n-cpu-moe", "spec", "decode t/s", "prefill t/s", "TTFT s", "VRAM used", "VRAM free"] + if a.ctx: + cols.append(f"decode@{a.ctx // 1000}k") + + latest = open(a.out, "w", encoding="utf-8") + hist = open(a.history, "a", encoding="utf-8") + meta = (f"_Run {datetime.now():%Y-%m-%d %H:%M} · server `{a.url}` · VRAM total {gb(total_vram)} · " + f"baseline used {gb(used0)} · gen {a.tokens} tok · guards: free≥{a.min_free_gb} GB, GTT+≤{a.max_gtt_gb} GB_") + + def emit(line, both=True): + print(line) + latest.write(line + "\n"); latest.flush() + if both: + hist.write(line + "\n"); hist.flush() + + latest.write("# llama.cpp benchmark results (latest run)\n\n") + hist.write(f"\n## run {datetime.now():%Y-%m-%d %H:%M}\n\n") + emit(meta + "\n") + emit("| " + " | ".join(cols) + " |") + emit("|" + "|".join(["---"] * len(cols)) + "|") + + for m in models: + c = cfg.get(m, {}) + base_cells = [m, c.get("ctx", "-"), c.get("ncpumoe", "-"), c.get("spec", "-")] + # A CLEAN card before EVERY load (incl. the first): force-unload via the router API, + # then verify with rocm-smi — double residency = bogus numbers or a freeze. + u = wait_drain(a.drain_gb, a.unload_wait, m, a.url, a.key) + if u is not None and u > a.drain_gb * 1e9: + emit("") + emit(f"_⚠ aborted before {m}: VRAM still {gb(u)} used after {a.unload_wait}s — something " + f"won't unload (leftover model / GPU apps). If that's your normal desktop, raise --drain-gb._") + print(f"\n⚠ aborted: card not clean ({gb(u)} used).", file=sys.stderr) + break + gtt_pre, _ = rocm_mem("gtt") # per-model GTT baseline — GTT reclaims slowly across swaps + try: + # warmup — retries wait out the mount; 'failed to load' aborts immediately + with_retries(lambda: run(a.url, a.key, m, "hi", 8, a.temp, a.timeout), a.retries, a.retry_wait, m) + used, _ = rocm_mem("vram") + gtt, _ = rocm_mem("gtt") + free = (total_vram - used) if (total_vram and used) else None + gtt_delta = (gtt - gtt_pre) if (gtt is not None and gtt_pre is not None) else None + reason = None + if free is not None and free < a.min_free_gb * 1e9: + reason = f"only {gb(free)} VRAM free" + elif gtt_delta is not None and gtt_delta > a.max_gtt_gb * 1e9: + reason = f"GTT grew {gb(gtt_delta)} = spilling to system RAM" + if reason: + # Too tight — do NOT generate (allocates more). Record the row; the sweep continues + # once this model has fully unloaded (see below). + hint = ("raise n-cpu-moe" if c.get("ncpumoe", "-") != "-" + else "lower ctx / smaller quant / add n-cpu-moe if MoE") + cells = base_cells + [f"⚠ {reason} — SKIPPED ({hint})", "", "", gb(used), gb(free)] + if a.ctx: + cells.append("") + else: + r = with_retries(lambda: run(a.url, a.key, m, task, a.tokens, a.temp, a.timeout), + a.retries, a.retry_wait, m) + cells = base_cells + [f"{r['tg']:.1f}", (f"{r['pp']:.0f}" if r['pp'] else "-"), + f"{r['ttft']:.2f}", gb(used), gb(free)] + if a.ctx: + rc = with_retries(lambda: run(a.url, a.key, m, filler + "\n\n" + task, a.tokens, a.temp, a.timeout), + a.retries, a.retry_wait, m) + cells.append(f"{rc['tg']:.1f}") + except Exception as e: + err = f"HTTP {e.code} (check server log)" if isinstance(e, urllib.error.HTTPError) else f"ERROR {e}" + cells = base_cells + [err] + [""] * (len(cols) - len(base_cells) - 1) + emit("| " + " | ".join(str(x) for x in cells) + " |") + # (no post-row wait needed: the pre-load drain above protects the next iteration, + # including after ⚠-tight rows where generation was skipped) + + latest.write("\n_Tuning hints: **VRAM free** = headroom to raise `ctx-size` or lower `n-cpu-moe` " + "(more experts on GPU → faster). Low decode t/s on an offloaded MoE → lower `n-cpu-moe` " + "if free allows. High **baseline used** invalidates the run. For spec/MTP models, check " + "the server log's acceptance rate._\n") + latest.close(); hist.close() + print(f"\nwrote {a.out} (+ appended {a.history})") + + +if __name__ == "__main__": + main() diff --git a/fl/.config/llamacpp/config.ini b/fl/.config/llamacpp/config.ini new file mode 100644 index 0000000..45870ec --- /dev/null +++ b/fl/.config/llamacpp/config.ini @@ -0,0 +1,952 @@ +# llama.cpp model config — AMD RX 7600 XT · 16 GB (17.16 GB total) · backend = Arch llama.cpp-vulkan +# (RADV, device Vulkan0 — NOT ROCm/HIP; rocm-smi is used for monitoring only) +# ═════════════════════════════════════════════════════════════════════════════ +# ⚠⚠ VRAM SAFETY — READ THIS. This GPU ALSO DRIVES THE DISPLAY. If a model asks for +# more VRAM than is free, the amdgpu driver does NOT OOM cleanly — it spills into system RAM +# (GTT), which starves the desktop and FREEZES THE WHOLE PC (reboot required). +# → TARGET ≥ ~2.5 GB free (≤ ~14.5 GB used). HARD FLOOR 1.5 GB (bench.py guard stops there). +# Idle desktop uses ~1.3 GB of 17.16 — but a browser/leftover model can hold 1-3 GB more, +# so measure with a CLEAN baseline (bench.py prints "baseline used"; close GPU apps first; +# sleep-idle keeps a model resident up to 5 min after last use). +# → Verify with bench.py → ledger: bench-results.md (latest) + bench-history.md (all runs). +# → If a model is tight: LOWER ctx-size, or RAISE n-cpu-moe (MoE), or use a smaller quant. +# The values below are deliberately CONSERVATIVE after freeze incidents — raise ctx +# only after bench.py confirms the headroom. +# ═════════════════════════════════════════════════════════════════════════════ +# Speed notes: decode is memory-bandwidth-bound (~288 GB/s). Prefer MoE (few active +# params). For MoE that doesn't fit, n-cpu-moe offloads expert FFNs to CPU (48 GB RAM) — +# this is FASTER than letting VRAM spill to GTT, and frees VRAM. threads = 6 (5600X cores). +# Runtime: `sudo rocm-smi --setperflevel high`; `watch -n1 rocm-smi --showmeminfo vram`. + +# ───────────────────────────────────────────────────────────────────────────── +# Coding models +# ───────────────────────────────────────────────────────────────────────────── + +[Qwen3-Coder-Next-UD-IQ3_XXS] +# ⭐ Big-context coder: Qwen3-Coder-Next 80B-A3B (3B active), Qwen3-Next hybrid attn → cheap KV. +# Weights ~30 GB: ALL experts on CPU (n-cpu-moe 99), only attention+KV on GPU → low VRAM, safe. +# Needs a CURRENT llama.cpp build (Qwen3-Next arch). ⬇ DOWNLOAD unsloth/Qwen3-Coder-Next-GGUF:UD-IQ3_XXS. +# Froze the PC before at n-cpu-moe 48 / ctx 131072 (overcommit) — keep it conservative, verify, then raise ctx. +model = /home/anon/software/models/Qwen3-Coder-Next-UD-IQ3_XXS.gguf +ctx-size = 131072 # ✓ VERIFIED @131072/moe99 (2026-07-16): 15.7 t/s, 6.0 GB used / 11.2 free — + # full 128k at a comfortable margin. Settled. +n-gpu-layers = 99 +n-cpu-moe = 99 # ALL experts on CPU — settled AGAIN 2026-08-08 after a two-round + # experiment, CLOSED: GPU experts barely move this model. + # moe56 (04:11) = NO-OP: 6.0 used ≈ moe99's 5.8, all numbers flat → + # only ~48 MoE layers exist; moe ≥ 48 ≡ all-on-CPU. (Also: the old + # "moe48/131k froze the PC" lore was ctx-KV overcommit in a pre- + # quantized-KV config, not expert placement.) + # moe40 (04:37) = 8 layers on GPU, 10.2 used / 6.9 free: prefill + # 33→36 (+9%), decode 16.4 (noise) — 4.2 GB for a rounding error. + # The shallow curve says don't chase it: cache-reuse already makes + # growing sessions incremental, and the 6 GB footprint IS the niche. + # MEASURED (07-16): moe99 = 14.3-16.4 t/s vs moe36@65536 = 16.9. +threads = 6 +# no-mmap TRIED AND REVERTED 2026-07-18: llama.cpp's log hint suggested it (CPU experts + +# mmap = page-fault churn), but reading 26 GB fully resident exceeds the router's load +# patience → "failed to load". Retry only if the router ever gets a load-timeout knob. +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q4_0 +batch-size = 2048 +ubatch-size = 256 # small compute buffer = less VRAM +cache-reuse = 256 +defrag-thold = 0.1 +temp = 0.7 # unsloth default 1.0/top-p0.95/top-k40/min-p0.01 — lower = more deterministic +top-p = 0.95 +top-k = 40 +min-p = 0.01 +jinja = on +sleep-idle-seconds = 300 + +# ─── RETIRED 2026-07-16: [DeepSeek-Coder-V2-Lite-Instruct-Q8_0] ────────────────────────── +# Mid-2024 model, outclassed by GLM-4.7-Flash + both Qwen coders. Bench kept skipping it +# (~15.3 GB fixed footprint; measured 2026-07-03 that ctx/moe knobs barely move it — only fix +# was a Q4_K_M requant, not worth it as the 4th-best coder). Removed from opencode/pi/aichat. +# File can be deleted from the models dir: DeepSeek-Coder-V2-Lite-Instruct-Q5_K_M.gguf + +# ─── RETIRED 2026-08-06: [Qwen3-Coder-30B-Instruct-IQ4_XS] ─────────────────────────────── +# Lost the 2026-08-06 quant race to UD-Q3_K_XL@moe10 (31.3 vs 23.0 t/s, +36%, three +# consistent sweeps; it also failed twice to load on ~3.2 GB evening baselines at moe20 = +# 14.1-14.3 used). Clients rewired to Qwen3-Coder-30B-Instruct-UD-Q3_K_XL same day — the +# extended quality trial was deliberately skipped (user call; revert path = git, one commit). +# ⚠ OWUI chats/presets saved against this id need re-picking after the restart. +# File can be deleted from the models dir: Qwen3-Coder-30B-A3B-Instruct-IQ4_XS.gguf +# Reference numbers: moe24 = 21.1 t/s, 11.9/5.3 · moe20 = 23.2 (2026-07-16), 22.0-23.0 (2026-08-05/06) + +[Qwen3-Coder-30B-Instruct-UD-Q3_K_XL] +# ⭐ MAIN AGENT CODER — took the slot 2026-08-06 after winning the quant race: 31.3 t/s @moe10 +# vs IQ4_XS@moe20 = 23.0 (+36%, three consistent sweeps); Q3_K_S dominated (tombstone below). +# Same 32k ctx and sampling as the retired IQ4_XS — clients only needed the id swap. +# ⚠ QUALITY TRIAL SKIPPED (user call, 2026-08-06): Q3-on-MoE damage looks like wrong API +# signatures / off-by-one logic, NOT word salad — if opencode sessions smell off, the +# IQ4_XS preset + client wiring are one `git revert` away (and the .gguf may still be on +# disk). UD protects attn/shared tensors; the experts are still 3-bit. +# RACE NUMBERS: moe24 = 22.2 · moe16 = 25.1 (07-16) / 25.5 / 26.3 · moe10 = 31.3 (15.0 used / +# 2.1 free @3.1 GB baseline; replicate 30.9 @1.8 free under a 13.9 leftover-model baseline). +model = /home/anon/software/models/Qwen3-Coder-30B-A3B-Instruct-UD-Q3_K_XL.gguf +ctx-size = 32768 +n-gpu-layers = 99 +n-cpu-moe = 12 # ✓ VERIFIED @moe12 (2026-08-07, 2.9 GB EVENING baseline): 27.0 t/s, + # 14.2 used / 3.0 free — loaded fine in exactly the regime that killed + # IQ4_XS@moe20 twice; the insurance works. Cost vs moe10 (31.3 clean race) + # was ~4 t/s, more than the ~1 estimated — evening compute contention + # likely eats 2-3 of that; confirmed: CLEAN (2026-08-08 02:45, 1.9 + # baseline) = 29.5 t/s, 13.2 used / 4.0 free — evening cost was indeed + # contention. Settled: moe12 = 29.5 clean / 27.0 evening, always loads. +threads = 6 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q4_0 +batch-size = 2048 +ubatch-size = 1024 # ✓ SETTLED 2026-08-08: prefill 74 → 89-92 t/s (+24%), decode unchanged, + # buffer +0.5 GB. FINAL GATE PASSED (14:43 sweep, 3.0 GB dirty baseline = + # evening-class): loaded and ran at 14.6 used / 2.6 free. If a worse + # evening (3.3+) ever fails the load: revert to 512, or pay one moe + # step (12→13). +cache-reuse = 256 +defrag-thold = 0.1 +temp = 0.15 +top-p = 0.8 +top-k = 20 +min-p = 0 +repeat-penalty = 1.05 +jinja = on +sleep-idle-seconds = 300 + +# ─── RETIRED 2026-08-06: [Qwen3-Coder-30B-Instruct-Q3_K_S] ─────────────────────────────── +# Dominated in the quant race: 30.9 t/s @moe8 (15.2 used / 2.0 free, replicate 30.9) = a tie +# with UD-Q3_K_XL@moe10 (31.3) at equal headroom, from a strictly worse quant (plain Q3_K_S, +# no UD-protected attn/shared tensors). No axis where it wins. Was never client-wired. +# File can be deleted from the models dir: Qwen3-Coder-30B-A3B-Instruct-Q3_K_S.gguf + +# ───────────────────────────────────────────────────────────────────────────── +# General Qwen models (35B-A3B is fast MoE; the dense 27Bs are inherently VRAM-tight) +# ───────────────────────────────────────────────────────────────────────────── + +[Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS] +# ⭐ Fast NON-THINKING daily driver: Qwen3.6-35B-A3B (MoE, 3B active) — the "bigger Qwen3 +# Instruct". Compact precise answers, no reasoning preamble. (Alias kept for clients.) +# File is flat + named without "MTP" (unsloth MTP-repo naming). If the load log complains +# there is no MTP head in this file, comment the two spec- lines out (plain repo file). +model = /home/anon/software/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf +mmproj = /home/anon/software/models/mmproj-Qwen3.6-35B-A3B-F16.gguf # vision ✓ VERIFIED 2026-07-18: + # 13.9 used / 3.3 free (2.8 dirty baseline), decode unchanged at 36-37 t/s. +spec-type = draft-mtp +spec-draft-n-max = 2 +reasoning-budget = 0 # hard-disable thinking → instant compact answers. Delete to allow /think. + # ⚠ if startup says "option 'reasoning_budget' not recognized" → remove this line. +ctx-size = 24576 # raised from 16384 (bench @16384: 4.8 GB free) — bench to confirm ≥2.5 free +n-gpu-layers = 99 +n-cpu-moe = 16 # MEASURED @24: 19.8 t/s (MTP working!), 10.6 used / 6.6 free → pull experts onto GPU +threads = 6 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q4_0 +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 +defrag-thold = 0.1 +temp = 0.7 +top-p = 0.8 +top-k = 20 +min-p = 0 +repeat-penalty = 1.05 +jinja = on +sleep-idle-seconds = 120 + +[Qwen3.6-35B-A3B-Thinking] +# Same GGUF as above with reasoning ENABLED (no reasoning-budget line) — fills the "thinking +# model" slot at zero disk cost. Qwen thinking-mode sampling: temp 0.6 / top-p 0.95, no +# repeat-penalty. Slower per answer (reasoning preamble) — use for hard problems. +model = /home/anon/software/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf +mmproj = /home/anon/software/models/mmproj-Qwen3.6-35B-A3B-F16.gguf # vision ✓ VERIFIED 2026-07-18: + # 13.9 used / 3.3 free (2.8 dirty baseline), decode unchanged at 36-37 t/s. +spec-type = draft-mtp +spec-draft-n-max = 2 +reasoning-budget = 8192 # "MEDIUM" thinking (added 2026-09-21 when this became the default model in + # opencode/pi/aichat): caps runaway 15-20k-token think loops, leaves 16k of + # the 24k ctx for prompt+answer; normal traces (0.5-5k) are untouched. The + # Qwen3.6 template knows only enable_thinking on/off (no reasoning_effort + # levels — verified in the gguf header), so this budget IS the depth knob. + # -1 = unlimited (old behaviour), 0 = the MTP alias. b10615's server README + # documents N>0; if startup rejects it → set -1 and update llama.cpp. +ctx-size = 24576 # thinking eats ctx — same footprint as the non-thinking preset +n-gpu-layers = 99 +n-cpu-moe = 16 +threads = 6 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q4_0 +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 +defrag-thold = 0.1 +temp = 0.6 +top-p = 0.95 +top-k = 20 +min-p = 0 +jinja = on +sleep-idle-seconds = 120 + +# ─── RETIRED 2026-07-03: [Qwen3.6-27B-UD-IQ3_XXS] ──────────────────────────────────────── +# The 27B files (plain AND MTP) were deleted from the models dir — preset removed so the +# router doesn't advertise a dead model. To bring it back: re-download (MTP-repo files are +# named WITHOUT "MTP"), restore the preset, re-add the id to opencode/pi/aichat lists. + +# ─── RETIRED 2026-07-16: [Qwen3.5-27B-UD-Q3_K_XL] ──────────────────────────────────────── +# Dense 27B: 16.2 GB used / 0.9 free even @8192 (under the 1.5 floor) and ~10 t/s ceiling on +# this card. Role covered by Qwen3.6-35B-A3B (MoE, 2× faster). Removed from opencode/pi/aichat. +# File can be deleted from the models dir: Qwen3.5-27B-UD-Q3_K_XL.gguf + +[Qwen3.5-9B-UD-Q6_K_XL] +# Small fast Qwen + MTP. Replaces Qwen3.5-9B-Q8_0 (retired 2026-07-16: Q8 was quality-overkill +# and bandwidth-slow at 17.2 t/s — delete Qwen3.5-9B-Q8_0.gguf; also delete the interim +# Qwen3.5-4B-UD-Q6_K_XL.gguf, superseded by this). +# ⬇ FILE MUST COME FROM unsloth/Qwen3.5-9B-MTP-GGUF (8.99 GB — MTP head embedded, filename +# identical to the plain repo!). If the load log complains there is no MTP head in this +# file, it's the plain-repo file — comment the two spec- lines out. +# ✓ VERIFIED (2026-07-16): 32.2 t/s (MTP working — nearly 2× the Q8's 17.2), prefill 83, +# 12.4 used / 4.8 free @32768. TTFT ~3.7 s = the model thinking (reasoning streams first). +model = /home/anon/software/models/Qwen3.5-9B-UD-Q6_K_XL.gguf +mmproj = /home/anon/software/models/Qwen3.5-9B-MTP-mmproj-F16.gguf # vision (from the MTP repo) +spec-type = draft-mtp +spec-draft-n-max = 3 # ⚗→✓ KEPT (04:11): 33.8 t/s vs 32.0-33.1 @n=2 — small real win. + # Revert to 2 if a future sweep drops below 32. +ctx-size = 32768 # raise toward 65536 once bench confirms free ≥2.5 GB +n-gpu-layers = 99 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q4_0 # q4 V to save VRAM +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 +defrag-thold = 0.1 +temp = 0.7 +top-p = 0.8 +top-k = 20 +min-p = 0 +repeat-penalty = 1.05 +jinja = on +sleep-idle-seconds = 60 + +[Qwen3.8-27B-UD-IQ3_XXS] +# ⚠ CLEAN-DESKTOP SPECIALTY — KEPT by user decision 2026-09-10 despite failing the ≥22 t/s speed +# gate (14.5 t/s MTP / 10.9 base; 2.8 GB free @1.5 baseline @16k). Pick it ONLY on a quiet +# desktop: at a 3+ GB evening baseline it lands ~1 GB free = GTT-spill/freeze territory. Role: +# slow-but-smart dense-27B answers + vision. Origin (added 2026-08-16): dense 27B, but NOT like the two +# retired dense 27Bs: hybrid attention (only 16 of 64 layers full-attn, rest linear/SSM → +# cheap KV, Coder-Next-style) AND an embedded MTP head — VERIFIED in the gguf header: +# qwen35.nextn_predict_layers = 1, block_count = 65 (64+1), arch "qwen35" = the same +# draft-mtp path the working 9B preset uses. Hybrid reasoner (thinking ON by default, +# reasoning_effort tunable via chat-template-kwargs if a -low alias is ever wanted), +# vision, n_ctx_train = 262144. +# Speed math: dense 11.9 GB weights on ~288 GB/s ≈ 14-16 t/s base; MTP should lift to +# ~22-30 = roster-competitive IF the draft engages. If it doesn't, this lands in +# retired-dense-27B territory (~10-14) → retire again, quality won't pay for the speed. +# ⚠ BENCH HISTORY — still no green row, decode/MTP UNMEASURED after 5 attempts: +# · 08-16 14:59/15:19/15:29 (3.3-3.5 DIRTY baseline): 16.5-16.7 used / 0.4-0.7 free, guard +# skipped gen every time. Implied footprint 13.2 GB — MISLEADING, see below. +# · 08-17 10:31: ERROR conn-refused = bench raced llama.service coming up after boot. +# · 08-17 10:38 (1.9 near-clean baseline): 15.9 used / 1.3 free — guard floor missed by +# 0.2. TRUE footprint = 14.0 GB over baseline; the dirty runs looked 0.8 smaller because +# ROCm silently spilled that much to GTT (the exact freeze precursor the guards watch). +# · 08-17 10:43 (post-trim, 10.0 leftover start, partial drain): 15.8 / 1.4 — floor missed +# by 0.1. Trim verified live via router args; ~2.4 effective baseline poisoned it again. +# · 08-17 10:53 (1.9 baseline, NO leftovers — a genuine desktop-idle run): 15.8 / 1.4, +# floor missed by 0.1 again. DECISIVE: trimmed footprint 13.9 vs untrimmed 14.0 — both +# knobs together saved 0.1 GB. ctx/ubatch do NOT move this model (fixed SSM-state + +# big-vocab buffers). Absolute best case ≈ 2.0 free at a pristine 1.3 baseline @16k — +# permanently below the 2.5 target. → RETIREMENT RECOMMENDED 2026-08-17; decode/MTP +# never measured, academic at these margins. Third dense ~27B to die on this card, +# first one killed by fixed buffers rather than bandwidth. +# Consequences: full-ctx even on a 1.3 CLEAN night = ~15.3 used / 1.9 free (runs, but +# under the 2.5 target). EVENING regime can never fit this quant — that needs ≤ UD-IQ2_M, +# a quality gutting. → 08-17: TRIMMED FOR THE GATE BENCH: ctx 24576→16384 (~-0.25) + +# ubatch 512→256 (~-0.3-0.5) → predicted ~15.2 used / ~2.0 free @1.9 baseline. Clients +# still say 24576 — deliberately NOT re-wired for a temporary trim; do not use from +# clients anyway until this passes (a busy-desktop pick is one tab from the GTT freeze). +# DECISION GATE (superseded by the 09-10 user decision below): MTP ≥ ~22 t/s keeps it (clean-desktop specialty, restore ctx +# 24576 + re-check), anything less → retire + delete (dense 27Bs die on this card). +# ↻ REOPENED 2026-09-09 — the file on disk is STALE: unsloth re-quantized the whole repo as +# "Dynamic v3" on 2026-08-19, three days AFTER the 08-16 download (~10% better accuracy at +# equal size, per unsloth). Verified via the HF tree API at the pre/post commits: +# UD-IQ3_XXS 11.91 → 10.93 GB (SAME filename — re-download overwrites in place, no client +# or section changes); UD-Q2_K_XL 10.68 → 9.83; UD-IQ2_M DELETED (gone as an option); +# UD-IQ2_S 8.37 / UD-IQ2_XXS 7.27 are new 2-bit tiers. Header range-read 09-09: v3 +# IQ3_XXS and Q2_K_XL both still carry nextn_predict_layers = 1 (MTP head embedded); +# unsloth stripped the head from ≤ IQ2_S only and ships MTP/mtp-Qwen3.8-27B-Q4_0.gguf +# as a separate model-draft for those (gemma-4 style). +# Predicted with v3 IQ3_XXS (footprint 14.0 − 0.98 ≈ 13.0; bench.py GB = decimal): +# @1.9 real-idle baseline ≈ 14.8–15.0 used / 2.2–2.4 free · @1.3 pristine ≈ 14.2 / ~2.9. +# Clears the 1.5 floor by ~0.8 even at 1.9 → the gen bench can FINALLY run; still ~0.1–0.3 +# under the 2.5 target on a real idle desktop, clears it outright on a pristine one. Overhead datum: a third-party paired bench measured +# draft-mtp at ~+0.75 GB on this model (unsloth docs: "1-2 GB extra headroom") — a good +# part of the "fixed" ~2.1 GB is MTP + KV, not only SSM-state/vocab buffers. +# NEXT STEP (recommended, NOT yet done): re-download v3 IQ3_XXS on fl (verify 10.93 GB / +# 10.18 GiB before restarting), dotsync, restart llama.service, clean-baseline bench. +# Then the gate above decides — with one refinement: free 2.0–2.5 at ≥22 t/s = user's call +# between "clean-desktop specialty" and stepping down to v3 UD-Q2_K_XL (predicted ~13.7 / +# 3.5 @1.9 — needs the section-rename round across the six client files; sequence it +# after any in-flight client edits). Decode < 22 → retire regardless of VRAM. +# No in-family alternative: the Qwen3.8 lineup is 27B dense, Flash-Next 125B-A6B (smallest +# GGUF 72.5 GB, 75 GB RAM floor even with mmap'd n-gram tables — out on 48+16), +# 2.4T-A95B and Max. No 3.8 MoE in the 35B-A3B class exists; watch HF. +# ✦ GATE BENCH RAN 2026-09-10 02:36 (v3 file, sha verified; 2.1 baseline): 14.9 used / 2.2 free +# (footprint 12.8 — VRAM half of the gate PASSED, borderline) but decode 14.8 t/s, prefill 19, +# TTFT 11.7 s → speed half FAILED. Server log: MTP head loaded, draft acceptance 0.80 +# (157/195, mean len 2.6) — so MTP IS engaging; at 2.6 tok/step that is ~175 ms per step ≈ +# 3–4× a plain forward pass. NOTE the box runs the Arch llama.cpp-vulkan package (RADV, +# device Vulkan0) — NOT HIP/ROCm (this header said "ROCm" until 09-10); rocm-smi = monitoring only. +# [10-02: that package is gone — now Arch `llama-cpp` 0.5.0 (b11146) + `ggml-vulkan`, see RE-PROBE below] +# Suspects: the 48 GatedDeltaNet layers on the Vulkan backend (upstream #20354: missing/slow +# GDN shader → CPU fallback) and/or recurrent-state checkpoint/restore per speculative step +# (~150 MiB for this model; reported net-negative on hybrid 27Bs). The hybrid 35B-A3B does +# 37 t/s on the same backend, so it is size-specific, not Vulkan-generic. +# A/B NEXT: [Qwen3.8-27B-UD-IQ3_XXS-nomtp] (TEMP alias, used 03:19 then removed) measures +# base decode; base ≥ 18 → MTP is the net negative here, run without it (frees ~0.75 GB); +# base ≈ 9 → the GDN path is the wall → retire. Also read "graph splits" from the load log. +# cache_reuse is inert here ("not supported by multimodal") — true for every mmproj preset. +# Re-run 03:07 @0.9 PRISTINE baseline: 15.0 t/s / 17 pp / 13.9 used / 3.3 free (footprint 13.0) +# — reproducible; the VRAM half is now fully closed, only the speed half is open. +# ✦ A/B 2026-09-10 03:19 (@1.5 baseline, same run): MTP 14.5 t/s / 30 pp / 14.3 used / 2.8 free +# vs NO-MTP 10.9 t/s / 34 pp / 12.8 used / 4.4 free. → MTP WORKS (+33%, matches the sudoingX +# paired benches) and costs 1.5 GB VRAM; the wall is the BASE: 10.9 t/s = 119 GB/s effective +# (41% of the card's 288) — the 48 GatedDeltaNet layers on the Vulkan/RADV backend, exactly +# the #20354 datum (Qwen3.5-27B ≈ 11.8 t/s on Strix Halo, either backend). Prefill 30-34 on +# a fully-GPU model is the same wall (the hybrid 35B-A3B daily driver's 64 pp is GDN-bound +# too). "graphs reused" 97-260 in the log → not a graph-rebuild problem. Nothing in this +# preset can move it; a bigger K-quant (faster dequant on Vulkan) does not fit. Perfect- +# kernel ceiling on this card ≈ 20 base / ~27 MTP — an upstream Vulkan gated_delta_net +# shader improvement COULD flip it; nothing else can. +# VERDICT 2026-09-10: gate FAILED on speed (14.5 < 22) with the VRAM half passed (2.8 free +# @1.5). Per the gate → retire. Re-probe only after a llama.cpp-vulkan bump whose changelog +# touches gated_delta_net / Vulkan GDN: `./bench.py -m Qwen3.8-27B-UD-IQ3_XXS`. +# → USER DECISION 2026-09-10: KEEP as clean-desktop specialty (overrides the gate). ctx restored +# to 24576 (clients already say 24576), ubatch stays 256 (prefill is GDN-bound, the bigger +# buffer buys nothing), MTP stays (+33% for 1.5 GB). ✓ CONFIRMED @24576 2026-09-10 03:51 +# (1.6 baseline): 15.1 t/s / 31 pp / 14.6 used / 2.5 free — footprint 13.0, exactly as +# predicted; free = the 2.5 target at a normal idle, ~2.8 pristine, ~0.8 on a 3.3 evening. +# ✦ RE-PROBE 2026-10-02 03:11 on llama.cpp b11146 = Arch `llama-cpp 0.5.0` + `ggml-vulkan 0.25.3` +# (the `llama.cpp-vulkan b10615` package is gone; `ggml` conflicts with the old `ggml-cpu` and +# does not replace it → name it: `sudo pacman -Syu ggml llama-cpp ggml-vulkan`, answer y twice; +# `ggml-vulkan` is only an optdepend — without it the server silently runs on CPU). +# 4.0 DIRTY baseline: 14.8 t/s / 18 pp / 14.4 used / 2.8 free. Decode IDENTICAL to 09-10 +# (14.5–15.1) → the build moves nothing on speed, as predicted. VRAM columns INVALID this run: +# 14.4 used at a 4.0 baseline = model "added" 10.4 GB < its own 10.93 GB file — amdgpu evicted +# the desktop's allocations to GTT to make room (the 08-16 masking effect, 3 GB this time); +# footprint stays 13.0 from the clean 09-10 runs. TTFT 0.00 — decoded in the 03:34 entry +# below (NOT a bench quirk, as this line first claimed). +# Re-run 03:16 @1.8 normal-idle baseline: 13.8 t/s / 33 pp / 14.7 used / 2.4 free → footprint +# 12.9, VRAM half exactly as on 09-10 (2.5 @1.6); 13.8 is inside the ±15% MTP acceptance +# swing (14.5–15.1 before). b11146 confirmed NEUTRAL on both speed and VRAM for this preset. +# Third run 03:19 @1.7: 12.5 t/s / 38 pp / TTFT 17.1 / 14.7 used / 2.4 free. Three back-to-back +# runs → decode BAND 12.5–14.8 with VRAM identical each time; prefill 18→33→38 = Vulkan +# pipeline warm-up on the first load after the restart, decode drift = acceptance at temp 1.0 +# over 256 tokens (±15% documented) and possibly GPU heat after 3 consecutive loads. +# ✦ DEFINITIVE 2026-10-02 03:34, -n 512 @1.7 baseline: 15.5 t/s / 38 pp / TTFT 20.6 / 14.7 used / +# 2.5 free. Server log: eval 442 tok @ 15.50 t/s (64.5 ms/tok), draft acceptance 0.842 +# (278/330), mean len 2.68, graphs reused 163 → MTP = 1.42× over the 10.9 base. The 256-token +# runs under-read (short window + acceptance noise). REFERENCE: 15.5 (10.9 w/o MTP). +# TTFT DECODED (bench.py stamps ttft on the first non-empty `content` delta; reasoning deltas +# do not count): TTFT = prompt eval + the whole THINKING preamble. 17.1 s / 20.6 s ≈ 230-300 +# tokens of xhigh thinking on the bench's trivial prompt; "0.00" on the 256-token runs = +# thinking consumed the entire budget and no answer was ever produced. The GGUF's embedded +# template (header read 10-02) defaults reasoning_effort to XHIGH — heaviest of +# xhigh/medium/low — and this preset passes nothing, so every answer pays it. That, not the +# 15 t/s, is why it feels slow. → sibling presets benched 03:49 (next entry), then removed. +# ✦ SIBLING BENCH 2026-10-02 03:49, -n 512 @1.9: xhigh 16.2 t/s / TTFT 17.5 s / 14.9 used / 2.2 +# free; -low 15.9 t/s / TTFT 6.45 s / 15.0 / 2.1 → reasoning_effort=low cuts the preamble 63% +# at identical decode. -medium SKIPPED by the guard (15.7 used / 1.4 free at load) = VRAM +# drain lag after two back-to-back loads, not a medium cost (same weights). → USER DECISION +# 10-02: both siblings REMOVED from the config. The lever remains one line on THIS preset — +# chat-template-kwargs = {"reasoning_effort":"low"} (or "medium") — or per request via +# chat_template_kwargs; xhigh stays the default here. +# What b11146 DOES carry for this preset: #27812 (merged 08-28) fixes the Vulkan graph +# optimizer reordering nodes that alias Qwen3.8's recurrent state — on b10615 that meant +# possible wrong tokens at temp 0 and acceptance numbers "that mean nothing"; everything from +# 10-02 on is from a correct build. Also DFlash2 support (#27342, 08-27). NOT in b11146: +# RDNA3 int8 coopmat prefill kernels (#27952, 09-24 — K-quant/q8 tensors only, not IQ3_XXS +# blocks anyway) and the GDN tune (#29476, 09-29 — an Intel fix, AMD measured flat). +# CORRECTION to the 09-10 suspects: the Vulkan GDN shader has existed since 2026-03 +# (#20334 → #20662 → #24581); there is no CPU fallback — 10.9 base IS the RDNA3 kernel +# ceiling. The remaining lever is speculative acceptance LENGTH, not the kernel: +# z-lab/Qwen3.8-27B-DFlash2-GGUF (Q4_K_M 1.14 GB drafter, mrope-fixed 08-24) — upstream +# 10.4 → 18.9 t/s (1.81×, AL ≈ 5) on this model vs MTP's 1.33× here (AL 2.6). Costs: the +# drafter + ~150 MiB recurrent rollback plane PER draft token → spec-draft-n-max 3–4 fits +# the MTP envelope, the default 7 does not. DFlash + mmproj = open #27408 (image requests +# stall/500) → any trial is a separate TEXT-ONLY preset; this one keeps MTP + vision. +# Open on Vulkan for MTP and DFlash alike: #28158 — intermittent draft token id 248320 +# (= n_vocab) → HTTP 500 "Invalid input batch", mostly after very long prompts. If seen: that. +# ✦ 2026-10-22 QUANT RACE OPENED (reddit tip: ByteShape / ISTA 3-bit quants + DFlash2 + KV streaming): +# two bench-only candidate sections follow this preset — [Qwen3.8-27B-GSQ-RCO-IQ3_XXS] (ISTA file, +# −0.49 GB, MTP) and its -dflash text-only sibling; the research + verdicts live in that block. +# ⚠ llama.cpp 0.7.0 (b11669) = #30688, Vulkan draft decode 4× slower (compute buffer lands in GTT): +# hold fl at 0.6.0 until fixed — hits EVERY MTP preset here, not only this one. +# ✦ BUILD DATUM 2026-10-22 03:15 — fl turned out to be on 0.6.0 (b11429) + ggml-vulkan 0.25.3-2 (the +# SAME kernels as 10-02): bench 37.1 t/s / 21 pp / TTFT 3.3 / 14.4 used / 2.7 free @1.3 (-n 512). +# Server: 221 tok @ 37.07, draft acceptance 0.892 (141/158), mean len 2.78 → ~75 ms per +# speculative step vs ~173 on b11146 — a llama.cpp-side change (b11147..b11429), NOT the Vulkan +# kernels (ggml is a separate package, unchanged). A 4096-token think-run: 27.3 t/s @ acceptance +# 0.51 / len 2.02 = the same ~74 ms step; acceptance sags over long thinking. Footprint 13.1, +# unchanged. → the ≥22 gate is PASSED 1.7× over; the 'clean-desktop specialty' verdict's SPEED half +# is obsolete (the VRAM half — never on a busy desktop — still stands). Role re-rank = user's call. +# 03:25 re-run: 36.2 / 45 pp / TTFT 8.6 / 14.5 / 2.7 — reproducible. +# CAUSE (researched 10-22; a hypothesis — no PR in b11147..b11429 claims any such gain): Arch's llama-cpp +# links the SYSTEM ggml (-DLLAMA_USE_SYSTEM_GGML=ON), so every ggml-side Vulkan PR (#29476 GDN tune, +# #29280 descriptor reuse, FA work) is EXCLUDED — those ship in ggml 0.26.0, not on fl yet. Best fit: +# #29856 (10-03) "gather the recurrent states once so the reserve covers every split" — on 0.5.0 the +# hybrid graph was silently re-reserved after the first speculative step and the target compute +# buffer could land partly in GTT = the #30688 mechanism seen from the other side. The arithmetic +# agrees: the old no-MTP base (10.9 t/s = 92 ms/token) was SLOWER than today's whole MTP step (75 ms +# for ≥3 verified tokens + 2 draft passes), so the "10.9 base = the GDN kernel wall" story above is +# SUSPECT: that base was most likely GTT-starved, not kernel-bound. Cheap check whenever the card is +# free: a TEMP -nomtp alias on 0.6.0 — ~22–26 t/s confirms it, ~11 refutes it. #27694 (probabilistic +# drafter, 10-02) explains acceptance 0.84 → 0.89, not the step time. (Also learned: the 9B is hybrid +# too, 24 GDN + 8 attn per #30039 — the "regular-attention qwen35" remark further down is wrong.) +# ⚠ ggml 0.26.0 (the next -Syu brings ggml + ggml-vulkan 0.26.0-1, SOVERSION-compatible, unrebuilt): +# #30039 reports −45 % PREFILL on a GDN hybrid with b11429 binaries, TG flat → bench this preset right +# before and after that upgrade; if prefill tanks, downgrade ggml/ggml-vulkan from the pacman cache. +# REFERENCE from here: 37.1 (b11429). Every other MTP/hybrid preset needs a re-sweep on this build. +# ⚠ Needs a CURRENT llama.cpp build: first "qwen35" file HERE with ssm.*/hybrid-attn keys +# (the 9B is regular-attention qwen35). If the load fails with unknown-architecture / +# missing-tensor errors, update llama.cpp on fl before touching this preset. +# ⬇ DOWNLOAD from unsloth/Qwen3.8-27B-GGUF (NO separate MTP repo — unlike Qwen3.5/3.6, the +# head ships in the MAIN repo's ggufs for ≥ Q2_K_XL; ≤ IQ2_S need MTP/mtp-Qwen3.8-27B-Q4_0.gguf): +# Qwen3.8-27B-UD-IQ3_XXS.gguf (10.93 GB Dynamic v3 since 2026-08-19 — the 08-16 download +# is the 11.91 GB v2; RE-FETCH. UD-IQ4_XS 14.3 GB and +# UD-Q3_K_XL 13.15 = dead on arrival, no n-cpu-moe escape) +# mmproj-Qwen3.8-27B-F16.gguf ← mmproj-F16.gguf (928 MB — unchanged; rename; watch trailing spaces) +model = /home/anon/software/models/Qwen3.8-27B-UD-IQ3_XXS.gguf +mmproj = /home/anon/software/models/mmproj-Qwen3.8-27B-F16.gguf +spec-type = draft-mtp +spec-draft-n-max = 2 # ⚠ if the load log says this file has no MTP head, comment the two + # spec- lines out — and expect ~14 t/s, probably not worth keeping. +ctx-size = 24576 # RESTORED 2026-09-10 (16384 was the 08-17 gate-bench trim): matches + # the clients. KV is cheap (16 full-attn layers × 4 kv-heads × 256 + # head_dim ≈ 26 KB/token at q8/q4): 16k→24k cost +0.3 → MEASURED + # 09-10 @1.6 baseline: 14.6 used / 2.5 free. n_ctx_train 262144. +n-gpu-layers = 99 # dense: no n-cpu-moe escape — ctx/quant are the only knobs +threads = 6 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q4_0 # hybrid arch takes mixed KV like Coder-Next (GLM's same-type + # rejection was MLA-specific). If load fails at context creation: + # try v = q8_0, then delete both lines (f16 — KV small enough here). +batch-size = 2048 +ubatch-size = 256 # KEPT at 256 (512 before the 08-17 trim): prefill is GDN-bound on the + # Vulkan backend (30-34 t/s either way), so the bigger compute buffer + # buys nothing measurable and VRAM is the binding constraint here. +cache-reuse = 256 +defrag-thold = 0.1 +no-mmproj-offload = true # vision encoder on CPU → ~1 GB freed, same as the 26B +temp = 1.0 # card: thinking mode 1.0/0.95/20/0 — thinking IS the default mode +top-p = 0.95 +top-k = 20 +min-p = 0 +jinja = on +sleep-idle-seconds = 120 + +# ═══ QUANT RACE 2026-10-22 — Qwen3.8-27B third-party 3-bit quants + DFlash2 (bench-only, NOT client-wired) ═══ +# Trigger: r/LocalLLaMA 2026-09-24 "Qwen-3.8-27B is good enough that I stopped using API": a 16 GB user +# (RTX 5060 Ti, CUDA, PCIe 5.0 x8, display on the iGPU) runs ByteShape IQ4_XS + DFlash2 + Raymond's +# KV-cache streaming; a reply says "try the ISTA IQ3_S / XXS — more speed and context, couldn't tell a +# difference in quality". What survives contact with THIS box (16 GB + display, Vulkan/RADV, PCIe 4.0 x8): +# · KV-cache streaming (troed → RaymondHuang210129/llama.cpp-adaptive-kv-streaming): OUT. CUDA-only — +# the README lists Vulkan as "memory-infrastructure tests only" (no attention path), ROCm = one +# unreviewed PR for gfx1201; both authors say PCIe 5.0 is required (PCIe 4.0 users: 2–4 t/s @192k); +# no upstream PR (discussion #28216 only). And it is a 160k+ tool — clients run this model at 24k. +# · ByteShape (byteshape/Qwen3.8-27B-GGUF, proprietary "ShapeLearn" per-tensor mixed types, the IQ* +# labels are size classes; MTP head kept, quantized IQ3/IQ4 vs Q6_K/Q8_0 elsewhere): IQ4_XS-3.84bpw +# 13.08 GB → OUT (ceiling here ≈ 11 GB file); the commenter's own file is troed's 12.25 GB +# ASCII-vocab-pruned build (248320 → 129006 tokens) → OUT twice. Same size class as the incumbent: +# IQ3_S-3.23bpw 11.035 GB (vendor blog: 98.7 % of BF16 task avg vs 93.6 % for unsloth UD-IQ3_XXS — +# vendor numbers; the one independent KLD run ranks their IQ4_XS BELOW unsloth's UD-IQ4_XS, 0.050 vs +# 0.019), IQ3_XS-3.01bpw 10.353 GB, IQ3_XXS-2.88bpw 9.919 GB. Optional third runner, see below. +# · ISTA (ISTA-DASLab/Qwen3.8-27B-GSQ-RCO-GGUF: GSQ = learned per-coordinate grids, RCO = per-tensor +# type under a size budget, standard GGUF block types, imatrix ~90 % English — discussion #7 reports +# degraded Chinese; "-mtp" files carry the head, +0.35 GB, weights identical): +# IQ3_S-mtp 12.12 GB → footprint ≈ 14.2 → ~1.4 free @1.6 = UNDER THE 1.5 FLOOR. Plain IQ3_S 11.77 +# fits only WITHOUT any drafter (~3.4 free) at ~10 t/s → no. Both reddit comments measured "more +# speed and context" against a 13 GB file, not against a 3-bit one. +# IQ3_XXS-mtp 10.443 GB = 0.49 GB under the incumbent → the one ISTA file with a case here. +# Quality evidence (nobody measured it against OUR unsloth v3 file): ISTA card wiki-ppl 7.20 vs +# BF16 7.05, AIME25/GPQA-D/LCBv6 within 1–2 pts of BF16; ByteShape's blog scores it 94.4 vs 93.6 +# for UD-IQ3_XXS (= equal); Agention's KLD table puts it at 0.11, ~2× their own IQ3_XXS. Thread: +# one user "ISTA even at lower quants did better", troed "tried it, not as good for my use". +# → bench.py settles speed + VRAM only; the quality half is the user's own prompts, both files. +# · DFlash2 (z-lab/Qwen3.8-27B-DFlash2-GGUF: 1.92B block-diffusion drafter, 5 layers, 2048-token +# sliding window, no own embeddings/output head; Q4_K_M 1.143 GB; llama.cpp support since b10658 = +# already in fl's b11146): acceptance length ~5.4 vs the MTP head's 2.6 here. RDNA3/Vulkan reports +# (PR #27342 thread): 7900 XTX RADV n-max 3 = +4–12 % decode over MTP, prefill −1 to −12 %; Strix +# Halo RADV n-max 4 = 19–23 t/s vs MTP 20; R9700 n-max 4 = 52 vs 47; a net LOSS once layers spill. +# Expect +5–15 % over the incumbent (37.1 on b11429, 10-22), NOT the paper's 1.8× — every verified draft token +# re-runs the 48 GDN layers. Acceptance falls with context (5090 datum: 31–36 % at 23–63k vs MTP +# 55 %) = why the redditor says "at low context". +# VRAM: drafter 1.14 GB + (1 + n-max) × ~150 MiB recurrent-state snapshots (n-max 3 ≈ 0.6 GB) + +# drafter KV — the MTP head measured 1.5 GB against a ~0.7 estimate, so budget ~2 GB and let the +# bench.py guard decide; the ISTA file's −0.49 GB is what buys the margin. Default n-max 7 = OUT. +# Text-only: #27408 (spec + mmproj → image requests 500) still open → NO mmproj on that preset. +# #28158 (Vulkan: draft token id 248320 → HTTP 500, rare, very long prompts) still open. +# Build window: #29226 (b11132) broke drafters WITH embeddings but WITHOUT an output head (fixed by +# #30111, b11512); the z-lab drafter has neither → should not be hit. FIRST GATE regardless: +# "draft acceptance" in the server log > 0 (0.00 = that class of breakage → drop the sibling). +# ⚠ BUILD: fl = llama-cpp 0.6.0-1 (b11429) + ggml 0.25.3-2 + ggml-vulkan 0.25.3-2, CONFIRMED 10-22 (the +# b11146 → b11429 move alone took the incumbent 15.5 → 37.1, see its block). Arch extra also has +# ggml/ggml-vulkan 0.26.0 (#27952 int8 coopmat prefill, #29476 GDN tune) — the next -Syu brings them +# = another variable, bench before/after. Upstream 0.7.0 (b11669) = #30688: Vulkan +# draft-mtp decode 4× / prefill 6× SLOWER, the target compute buffer re-allocated into GTT — on this +# box that is the freeze precursor, and it hits every MTP preset on the roster. When +# `pacman -Si llama-cpp` on fl shows 0.7.0: HOLD (IgnorePkg = llama-cpp ggml ggml-vulkan) until fixed. +# Race on the current build first (one variable per run); the ggml 0.26.0 bump is a separate round. +# PLAN (clean baseline, -n 512, incumbent re-run in the SAME session — the 10-02 band was 12.5–15.5): +# 1. download (below) · 2. `sudo systemctl restart llama.service` · +# 3. ./bench.py -n 512 -m Qwen3.8-27B-UD-IQ3_XXS,Qwen3.8-27B-GSQ-RCO-IQ3_XXS,Qwen3.8-27B-GSQ-RCO-IQ3_XXS-dflash +# 4. quality: the same 3–4 real prompts (incl. non-English) against incumbent vs GSQ. +# GATE: GSQ-mtp ≥ incumbent decode (expected ~+4 %) with free ≥ 2.5 → quality is the user's call → +# if it wins, either point the incumbent section's `model =` at the GSQ file (keeps the client id, +# accepted misnomer) or rename = the seven-client-file round. DFlash sibling: acceptance > 0 AND +# decode ≥ 1.10 × the SAME-SESSION incumbent AND free ≥ 2.5 → keep as the text-only fast sibling +# (wire into clients then); else drop. Loser files: delete from ~/software/models (10.4 + 1.1 GB). +# ✦ RACE RUN 2026-10-22 03:25 @1.3 baseline, -n 512, all three in ONE session (rows in bench-history.md): +# incumbent UD-IQ3_XXS ....... 36.2 t/s / 45 pp / TTFT 8.6 / 14.5 used / 2.7 free +# GSQ-RCO-IQ3_XXS (MTP) ...... 37.5 / 44 / 7.0 / 14.0 / 3.2 → +3.6 % decode, +0.5 GB free = exactly the +# file-size prediction. Speed + VRAM half of the gate PASSED. OPEN: the quality half (same 3–4 real +# prompts, one non-English, against both; nobody has measured ISTA vs unsloth v3 at this size). +# GSQ -dflash ................ 15.4 / 32 / 18.0 / 15.3 / 1.9 → −59 % vs its own MTP row and under the +# 2.5 target → DROPPED (tombstone below). Read the acceptance line once: `journalctl -u llama.service +# --since 03:25 | grep 'draft acceptance'` — 0.00 = the #29226-window bug (fix #30111 = b11512 sits in +# 0.7.0 behind #30688 → re-probe only on a fixed 0.7.x); > 0 = block-drafting re-runs the 48 GDN +# layers per verified block and loses on this card (the RX 9070 XT datum in #25117 said the same) +# → closed for good. Either way nothing to tune: n-max 2 only shrinks the loss. +# NEXT: quality call → if GSQ wins, point the incumbent's `model =` at the GSQ file (keeps the client +# id; the section name becomes a misnomer) or do the seven-client rename round, then delete the +# unsloth file; if not, delete the GSQ file and the section. The DFlash2 drafter can go now. +# ⬇ DOWNLOAD on fl — curl straight into the models dir (the HF cache has root-owned dirs from docker): +# cd ~/software/models +# curl -L -o Qwen3.8-27B-GSQ-RCO-IQ3_XXS-mtp.gguf https://huggingface.co/ISTA-DASLab/Qwen3.8-27B-GSQ-RCO-GGUF/resolve/main/Qwen3.8-27B-GSQ-RCO-IQ3_XXS-mtp.gguf +# (dropped 10-22, only for a re-probe) curl -L -o Qwen3.8-27B-DFlash2-Q4_K_M.gguf https://huggingface.co/z-lab/Qwen3.8-27B-DFlash2-GGUF/resolve/main/Qwen3.8-27B-DFlash2-Q4_K_M.gguf +# stat -c '%s %n' Qwen3.8-27B-GSQ-RCO-IQ3_XXS-mtp.gguf Qwen3.8-27B-DFlash2-Q4_K_M.gguf # 10442827840 · 1143006816 +# (mmproj: ISTA ships the same BF16 encoder — the existing mmproj-Qwen3.8-27B-F16.gguf is reused) + +[Qwen3.8-27B-GSQ-RCO-IQ3_XXS] +# ⚗ RACE CANDIDATE 2026-10-22 — bench-only, NOT in any client file. = the incumbent preset with the ISTA +# file swapped in (MTP head Q6_K, same as unsloth's). Predicted @1.6 baseline @24k: ~14.1 used / +# ~3.0 free (incumbent 14.4 / 2.7), decode ~38–39 (incumbent 37.1 on b11429) — bandwidth × file size, nothing +# else moves. Knobs deliberately identical to the incumbent (n-max 2) for a clean A/B. +# ✓ MEASURED 2026-10-22 03:25 @1.3: 37.5 t/s / 44 pp / TTFT 7.0 / 14.0 used / 3.2 free (incumbent 36.2 / +# 2.7 in the same run). Speed + VRAM passed; QUALITY CALL PENDING — not client-wired until then. +model = /home/anon/software/models/Qwen3.8-27B-GSQ-RCO-IQ3_XXS-mtp.gguf +mmproj = /home/anon/software/models/mmproj-Qwen3.8-27B-F16.gguf +spec-type = draft-mtp +spec-draft-n-max = 2 +ctx-size = 24576 +n-gpu-layers = 99 +threads = 6 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q4_0 +batch-size = 2048 +ubatch-size = 256 +cache-reuse = 256 +defrag-thold = 0.1 +no-mmproj-offload = true +temp = 1.0 +top-p = 0.95 +top-k = 20 +min-p = 0 +jinja = on +sleep-idle-seconds = 120 + +# ─── DROPPED 2026-10-22 03:25: [Qwen3.8-27B-GSQ-RCO-IQ3_XXS-dflash] (DFlash2 text-only sibling) ───── +# 15.4 t/s / 32 pp / 15.3 used / 1.9 free vs 37.5 / 3.2 for the same file with its MTP head — the +# z-lab block drafter is a net loss on this card (see the RACE RUN entry above for the two possible +# causes and the only re-probe condition: a 0.7.x build that carries #30111 without #30688). +# Removed as a loadable section on purpose: OWUI lists every router id, and 1.9 free on a busy +# desktop is the GTT freeze. File can be deleted from the models dir: Qwen3.8-27B-DFlash2-Q4_K_M.gguf +# Keys as benched (n-max 3, no mmproj — #27408): +# model = /home/anon/software/models/Qwen3.8-27B-GSQ-RCO-IQ3_XXS-mtp.gguf +# model-draft = /home/anon/software/models/Qwen3.8-27B-DFlash2-Q4_K_M.gguf +# spec-type = draft-dflash +# spec-draft-n-max = 3 +# ctx-size = 24576 +# n-gpu-layers = 99 +# threads = 6 +# flash-attn = on +# cache-type-k = q8_0 +# cache-type-v = q4_0 +# batch-size = 2048 +# ubatch-size = 256 +# cache-reuse = 256 +# defrag-thold = 0.1 +# temp = 1.0 +# top-p = 0.95 +# top-k = 20 +# min-p = 0 +# jinja = on +# sleep-idle-seconds = 120 + +# ─── optional 3rd runner (not added — copy the GSQ section if wanted): ByteShape IQ3_S-3.23bpw ──── +# 11.035 GB = the incumbent's size, vendor-claimed best quality in the class, MTP head kept (IQ3-quantized). +# model = /home/anon/software/models/Qwen3.8-27B-IQ3_S-3.23bpw.gguf +# curl -L -o Qwen3.8-27B-IQ3_S-3.23bpw.gguf https://huggingface.co/byteshape/Qwen3.8-27B-GGUF/resolve/main/Qwen3.8-27B-IQ3_S-3.23bpw.gguf # 11035354496 B + +# ─── RETIRED 2026-07-16: [Qwen3.6-27B-Uncensored-HauhauCS-Aggressive-IQ3_M] ────────────── +# Dense: 10 t/s, 2.0 GB free (under the 2.5 target) and unfixable — bandwidth-bound, smaller +# quant would cost the quality that justified it. Removed from opencode/pi/aichat. +# File can be deleted from the models dir: Qwen3.6-27B-Uncensored-HauhauCS-Aggressive-IQ3_M.gguf + +# ───────────────────────────────────────────────────────────────────────────── +# Gemma models +# ───────────────────────────────────────────────────────────────────────────── + +[gemma-4-26B-A4B-it-UD-IQ4_XS] +# MoE (4B active) + MTP + vision. ~13.5 GB weights → tight. Projector on CPU (no-mmproj-offload). +# From unsloth/gemma-4-26B-A4B-it-qat-GGUF: mmproj-F16.gguf + mtp-gemma-4-26B-A4B-it.gguf. +# ⬇ SOURCES — local name ← upstream (PLAIN repo unsloth/gemma-4-26B-A4B-it-GGUF; the qat +# repo has NO IQ4_XS, its only main is qat-UD-Q4_K_XL 14.25 GB — see decision note below): +# gemma-4-26B-A4B-it-UD-IQ4_XS.gguf ← gemma-4-26B-A4B-it-UD-IQ4_XS.gguf (13.6 GB) +# ✓ current: the 2026-08-05 dl has the Jul 17 template +# mmproj-gemma-4-26B-A4B-it-F16.gguf ← mmproj-F16.gguf (1.19 GB) +# mtp-gemma-4-26B-A4B-it.gguf ← MTP/mtp-gemma-4-26B-A4B-it-Q8_0.gguf (462 MB) +# Keep LOCAL names stable; re-fetch the upstream names above when repos update. Pair main +# and drafter from the SAME repo — the two repos' drafters are different extractions. +# ✓ FIXED 2026-08-08 03:15: matched plain-repo sidecars cured the "Invalid input batch." +# 500s — root cause CONFIRMED as the cross-repo drafter mismatch (old qat-repo mtp under +# the new plain main). Re-benched 32.8 t/s @moe13, 12.1 used / 5.0 free, MTP ✓ — same +# speed as pre-update (32.7), template fix now in place. The *.gguf.bak sidecars are +# deletable once vision + opencode tool-calling are smoke-tested. +# (QAT quality upgrade = separate decision: main → qat-UD-Q4_K_XL, +0.7 GB, moe 13→~16, and +# a section/client id rename round. Not part of this fix.) +# ⚠ vision + MTP together is heavy — if it OOMs/freezes, add n-cpu-moe or drop MTP (keep vision). +model = /home/anon/software/models/gemma-4-26B-A4B-it-UD-IQ4_XS.gguf +mmproj = /home/anon/software/models/mmproj-gemma-4-26B-A4B-it-F16.gguf +model-draft = /home/anon/software/models/mtp-gemma-4-26B-A4B-it.gguf +spec-type = draft-mtp +spec-draft-n-max = 2 +reasoning-budget = 0 # added 2026-08-09: the Jul-17 official template makes gemma-4 DELIBERATE + # on hard prompts (probe: 700 tok = 100% reasoning_content, content + # EMPTY, finish=length) — that ate pi's 4096 maxTokens cap and returned + # truncated nothing. Same fix as the 35B daily driver. ⚠ if startup says + # option not recognized, remove; if it loads but a hard probe still emits + # reasoning_content, the gemma template ignores the budget → remove and + # raise client maxTokens to 8192 instead. +ctx-size = 24576 # MEASURED @16384/moe16: 29.6 t/s, 10.7 used / 6.5 free → sliding-window KV is + # cheap, take the ctx back (clients already assume 24576) + # n_ctx_train = 262144 (08-08 load log) — huge ctx headroom exists if a + # long-context vision need ever appears; bench stepwise, free ≥ 2.5. +n-gpu-layers = 99 +n-cpu-moe = 13 # MEASURED @16: 26.4 t/s, 11.9 used / 5.2 free → pull ~3 expert layers onto GPU for speed +threads = 6 +flash-attn = on +jinja = on # OpenAI-style tool calling (opencode build/plan default to this preset) +cache-type-k = q8_0 +cache-type-v = q4_0 +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 +defrag-thold = 0.1 +no-mmproj-offload = true # vision encoder on CPU → frees ~1 GB +temp = 1.0 +top-p = 0.95 +top-k = 64 +sleep-idle-seconds = 60 + +[gemma-4-E4B-it-UD-Q8_K_XL] +# ~5-7 GB — small/fast, lots of headroom, safe at big ctx. +# Vision: the HF repo ships mmproj-{BF16,F16,F32}.gguf — use F16 (990 MB), saved AS the exact +# path below (rename it; if the path doesn't exist the model fails to load / vision silently +# missing depending on router). Verify: startup log shows the mmproj load, and an image request +# answers instead of erroring "image input is not supported". +# NOTE: repo got Google's chat-template update ~2026-05 — if the main gguf predates that, re-download it too. +model = /home/anon/software/models/gemma-4-E4B-it-UD-Q8_K_XL.gguf +mmproj = /home/anon/software/models/mmproj-gemma-4-E4B-it.gguf +model-draft = /home/anon/software/models/mtp-gemma-4-E4B-it.gguf # ✓ MEASURED (2026-07-18): 57.3 t/s — + # +50% over 38.4 without the draft, 10.5 used / 6.6 free. Fastest model on the box. +spec-type = draft-mtp +spec-draft-n-max = 2 +reasoning-budget = 0 # added 2026-08-09, same reason as the 26B: gemma-4 deliberates on hard + # prompts since the Jul-17 template (this is what caused the 20-second + # aichat -e "think" preambles on 2026-08-05). Fast models answer NOW. + # ⚠ same caveats as the 26B — remove if not recognized / not honored. +ctx-size = 98304 # ⚗→✓ CLOSED 2026-08-08: 58.2-60.4 t/s, 10.3-10.6 used / 6.5-6.9 free + # @98304, and n_ctx_train = 131072 confirmed (upstream config.json + # max_position_embeddings) — 98304 is inside training range, no RoPE + # risk. 131072 is the hard ceiling if ever needed (~+0.5-1 GB KV). +n-gpu-layers = 99 +flash-attn = on +jinja = on # OpenAI-style tool calling (doc-writer agent defaults to this preset) +cache-type-k = q8_0 +cache-type-v = q8_0 +batch-size = 2048 +ubatch-size = 1024 +cache-reuse = 256 +defrag-thold = 0.1 +temp = 1.0 +top-p = 0.95 +top-k = 64 +sleep-idle-seconds = 30 + +# ───────────────────────────────────────────────────────────────────────────── +# Ornith (Qwen3.5-MoE derivative) +# ───────────────────────────────────────────────────────────────────────────── + +[Ornith-1.5-35B-A3B-IQ3_XXS] +# ✓ KEPT 2026-09-21 (gate passed: 32.1 t/s MTP, 13.8 used / 3.3 free @moe16) — Ornith-1.5-35B-A3B (ornith-ai / DeepReinforce, MIT, +# released ~2026-08-24): Qwen3.5-MoE architecture (qwen35moe: 40 layers, hybrid GDN 3:1, 256 +# experts / 8 active + shared, ~3B active, vision, n_ctx_train 262144), continued-pretrained and +# RL'd with a self-improvement loop. Card claims it beats Qwen3.6-35B-A3B on every coding/agentic +# bench (Terminal-Bench 2.1 67.8 vs 52.5, SWE-bench Verified 79 vs 73.4). Same shape as the daily +# driver → same recipe: MTP draft + experts on CPU. Role if it passes: AGENTIC CODER (the only +# coder here with MTP — Coder-30B 30 t/s and GLM Q3 26 t/s have none) and/or daily driver. +# MTP head VERIFIED in the gguf header 09-21 (nextn_predict_layers = 1, block_count 41 = 40+1) — +# present in bartowski's plain quants and the official Q4_K_M alike; no "-MTP" repo needed. +# Thinking is ON by default ( block; card sampling 0.6/0.95/20). Kept ON for the coder +# role; an instruct alias = same file + `reasoning-budget = 0` exactly like the daily driver. +# VRAM: file is +1.27 GB vs the daily driver's 14.07 → start at moe20 (≈ Qwen@moe16 footprint: +# predicted ~13.9 used / ~3.3 free @2.0 baseline). Until downloaded, sweep with `-x` this id. +# GATE: MTP decode ≥ ~30 t/s AND free ≥ 2.5 → keep; step moe 20→16 while free ≥ 2.5; then wire +# the six client files + README row. Anything less → retire + delete (the Qwen stays). +# ✓ LOADED + BENCHED 2026-09-21 17:31 @moe20 (2.0 baseline): 27.9 t/s / 52 pp / 12.4 used / 4.8 +# free → footprint only 10.4 GB (predicted 11.9). MTP draft active (spec column). Speed gate +# not met yet but 2.3 GB of headroom is unused → step moe 20→16 (= daily driver; the Qwen went +# 19.8→35.9 t/s over moe 24→16). Predicted @moe16: ~13.8 used / ~3.4 free @2.0. +# ✓ GATE PASSED 17:34 @moe16 (2.0 baseline): 32.1 t/s / 74 pp / TTFT 3.9 s (thinking preamble) / +# 13.8 used / 3.3 free — prediction exact. Both gate halves met → wired into the six client +# files + README 09-21. KEEP moe16 (= daily-driver envelope; moe14 ≈ +1-2 t/s for the last +# 0.8 GB of margin — not on an evening box). Draft acceptance not recorded yet (grep the log). +# Role: agentic coder with reasoning — the only coder here with MTP (Coder-30B 30, GLM Q3 26). +# Instruct alias (reasoning-budget = 0, same file) still optional — add if agent loops want +# the ~4 s thinking TTFT gone. +# ⚠ NO reasoning-budget LINE IN THIS PRESET, ON PURPOSE (2026-10-12): pi caps the think block +# PER REQUEST (`thinking_budget_tokens`, from pi settings.json > thinkingBudgets, tested on +# b11429: budget 40 → trace cut at ~40 tokens, answer still arrives, finish_reason stop) and +# llama.cpp IGNORES that field whenever the preset sets a CLI --reasoning-budget. Adding one +# here "like the Thinking preset" silently disables the pi knob and brings back pi's +# "Response was truncated before completion." (= finish_reason length: think block + answer +# > the client's 4096 max_tokens). An instruct alias (budget 0) in a SEPARATE section is fine. +# ⚠ 2026-10-22: pi's "Compacting in OVERFLOW recovery" on this preset is NOT this window filling +# up — pi clamps each request's max_tokens to contextWindow − estimate − 4096, which on +# 24k/4096 starts exactly at its compaction threshold; the first request after a compaction +# (estimate gains the system prompt + tool schemas) can leave the thinking reply ~1024 answer +# tokens → finish_reason length → pi compacts again and retries. Arithmetic + options in +# common/.pi/CLAUDE.md > Compaction tuning > max_tokens clamp. +# APPLIED 2026-10-22 (same day, unbenched): ctx-size 24576 → 32768 here + 32768 in the seven +# client files (pi contextWindow both blocks common+lw, opencode limit.context common+lw, +# aichat max_input_tokens 30000 common+lw+wm). Threshold and clamp in pi now sit at 24576, +# above anything a fresh post-compaction context reaches. Predicted cost ≈ 0.1 GB: hybrid +# GDN 3:1 = 10 attention layers with small GQA, ~8 KB/token of q8/q4 KV → ~70 MB for +8192, +# plus a few MB of FA scratch — read the "KV self size" line in the load log to confirm. +# GATE on the first load: `sudo systemctl restart llama.service`, then +# `./bench.py -m Ornith-1.5-35B-A3B-IQ3_XXS` — free ≥ 2.5 at the 2.0 baseline and decode +# ≈ 32 t/s → keep; else back to 24576 in all eight files (the router reads presets once at +# startup, and pi at 32k against a 24k server produces REAL overflow recoveries). +# ⬇ DOWNLOAD from bartowski/Ornith-1.5-35B-A3B-GGUF (imatrix; the official repo has only Q4_K_M+ +# ≥ 21.7 GB, unsloth has no 1.5 quants yet): +# Ornith-1.5-35B-A3B-IQ3_XXS.gguf 15,340,447,392 B · sha256 8918ccb9ee29abe3875efec0c3e86f0e35ef0b8a03e3f0e1c422869859a518d0 +# mmproj-Ornith-1.5-35B-A3B-f16.gguf 899,283,296 B · sha256 815c9a671991aceeef46ca1aa103b64499db8cfadf21c83005a20ed839d53c7c +model = /home/anon/software/models/Ornith-1.5-35B-A3B-IQ3_XXS.gguf +mmproj = /home/anon/software/models/mmproj-Ornith-1.5-35B-A3B-f16.gguf +spec-type = draft-mtp +spec-draft-n-max = 2 +ctx-size = 32768 # 24576 → 32768 on 2026-10-22 for pi's max_tokens clamp (⚠ note above); + # UNBENCHED until the next restart — gate free ≥ 2.5 @2.0, decode unchanged; + # n_ctx_train 262144, KV is cheap here (hybrid GDN, ~8 KB/token) +n-gpu-layers = 99 +n-cpu-moe = 16 # ✓ KEEP (09-21: 32.1 t/s, 13.8 used / 3.3 free @2.0; moe20 was 27.9 / + # 12.4 / 4.8). = daily-driver envelope; moe14 not worth the margin. +threads = 6 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q4_0 # mixed KV is fine on this arch (daily driver runs the same) +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 # inert under mmproj ("not supported by multimodal") — kept for parity +defrag-thold = 0.1 +temp = 0.6 # model card, general use: 0.6 / 0.95 / 20 (1.0 only for bench reproduction) +top-p = 0.95 +top-k = 20 +min-p = 0 +jinja = on +sleep-idle-seconds = 120 + +# ───────────────────────────────────────────────────────────────────────────── +# GLM +# ───────────────────────────────────────────────────────────────────────────── + +[GLM-4.7-Flash-UD-Q4_K_XL] +# 30B-A3B MoE, QUALITY coder. Upgraded UD-Q3_K_XL (~14 GB) → UD-Q4_K_XL (17.5 GB, unsloth's +# recommended quant) 2026-07-16, benched clean same day. 2026-09-21: the Q3 quant is BACK as the +# separate fast-coder preset [GLM-4.7-Flash-UD-Q3_K_XL] below (21.5 t/s here was too slow for +# daily agent use) — keep BOTH files; this one stays for hard reviews. +# Tuning trajectory: Q3@moe9 = 28.2 t/s → Q4@moe24 = 17.9 (measured 2026-07-16) → now moe18, +# lower stepwise toward 16 while bench keeps free ≥2.5 GB. +model = /home/anon/software/models/GLM-4.7-Flash-UD-Q4_K_XL.gguf +ctx-size = 24576 # MEASURED @16384/moe24 (Q3): 9.5 GB used, 7.6 free + # n_ctx_train = 202752 (08-08 load log) — MLA KV is compact, ctx could + # go far higher if opencode subagent sessions ever outgrow 24k. +n-gpu-layers = 99 +n-cpu-moe = 22 # lowered 24→22 on 2026-08-08: both step-down gates passed post-KV-fix — + # clean sweep @24 = 20.5 t/s, 12.0 used / 5.2 free (02:45, 1.9 baseline); + # elevated-baseline load @24 = 18.7, 13.0/4.2 (@2.9). moe22 est ~21.5 + # clean / ~19.5-20 evening, ~12.7 used clean / ~14.0 evening → inside the + # coder-proven evening envelope (14.2 loads). ✓ CLEAN VERIFIED (02:58, + # 2.0 baseline): 21.5 t/s, 12.8 used / 4.4 free — est was 21.5, exact. + # Evening observation pending; revert to 24 if an evening bench shows + # free < 2.5. moe20 stays gated (~14.4-14.7 evening = borderline vs the + # coder's 15.2 evening death). + # (08-05/07 "failures" were the mixed-KV rejection below, not VRAM.) + # Trajectory: Q3@moe9 = 28.2 → Q4@moe24 = 17.9 (07-16) → 18.7/20.5 post-KV-fix. +threads = 6 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q8_0 # was q4_0 — BROKE 2026-08-08: a llama.cpp upgrade (the one deprecating + # defrag-thold) enforces same-type K/V for this model (deepseek2/MLA + # conversion; MLA KV is compact, mixed types unsupported). Every load + # since failed at context creation regardless of VRAM. Only THIS preset + # was affected — the other k-q8/v-q4 presets are regular-attention archs. + # If q8/q8 still refuses: delete both cache-type lines (f16 default; MLA + # KV is small enough that the cost is minor at 24576 ctx). +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 +defrag-thold = 0.1 +# MTP: GLM-4.7-Flash HAS an MTP head upstream (num_nextn_predict_layers: 1) but the GGUF +# conversion (deepseek2 arch) drops those tensors and llama.cpp draft-mtp only supports +# Qwen3.5/3.6 + Gemma 4 so far (PRs #22673/#23398). No mtp-*.gguf exists to download — +# recheck when llama.cpp lands GLM MTP support. +temp = 0.6 # unsloth rec: 0.7/top-p 1.0 (tool-calling) or 1.0/0.95 (general); no repeat-penalty +top-p = 0.95 +min-p = 0.01 +jinja = on +reasoning-preserve = true # ⚗ option ACCEPTED by the build (loaded + ran 20.9 t/s, 04:11 sweep). + # BEHAVIOR flag — judge multi-turn subagent quality in opencode over the + # next days; remove if reasoning bleed ever pollutes final answers. +sleep-idle-seconds = 60 + +[GLM-4.7-Flash-UD-Q3_K_XL] +# ⚡ FAST CODER — same GLM-4.7-Flash, 3-bit. RE-ADDED 2026-09-21: the user found the Q4 preset's +# 21.5 t/s (22 expert layers in RAM) too slow for agent loops; this quant fit far more of the +# experts on the GPU and was the fastest coder this box ever ran. HISTORY (07-16, pre-KV-fix +# era): Q3@moe9 = 28.2-29.7 t/s, @moe12 = 28.1, @moe24 = 18.9 (9.5 used / 7.6 free @16k). +# Quality: UD 3-bit — "coders want ≥4-bit" (README) is why Q4 exists; pick Q3 for speed, Q4 for +# hard reviews. Same deepseek2/MLA arch → same-type KV (q8/q8) is mandatory here too. +# GATE: keep if bench ≥ ~27 t/s AND free ≥ 2.5 GB @ a ≤1.9 baseline. Start at moe12 (safe), +# step to moe9 if free allows (~+0.75 GB per 3 layers on GPU, +~1 t/s). +# ✓ BENCHED 2026-09-21 16:29 (2.0 DAYTIME baseline): 26.0 t/s / 46 pp / 13.4 used / 3.8 free → +# footprint 11.4 GB. Speed = July's 28.1 minus the usual busy-desktop tax (clean-night +# reference still to record); VRAM passes with room. +21% over the Q4's 21.5. +# Re-run 16:34 (2.1 baseline): 25.9 t/s / 65 pp / 13.5 used / 3.7 free — reproducible; the +# first run's 46 pp was CPU contention (prefill now matches the Q4's ~60). +# DECISION: KEEP moe12, do NOT step to moe9. This preset's job is EVENING agent loops, so the +# evening envelope rules: 11.4 + 3.3 evening baseline = 14.7 used / 2.5 free = exactly the +# target; moe9 would be ~15.4 used on a busy evening = the coder's old death zone, for ~+1 t/s. +# Want more speed on a QUIET desktop? A same-file alias at moe6 (~+1.5 GB, maybe ~29-30) is the +# gpt-oss-low pattern — not added; ask. +# ⬇ DOWNLOAD unsloth/GLM-4.7-Flash-GGUF (repo unchanged since 2026-02-12): +# GLM-4.7-Flash-UD-Q3_K_XL.gguf — 13,782,004,064 B (13.78 GB) +# sha256 582728c0f6931a1cf734d5a7cf60ec73522fb79811e004cbc12476dd69b033bf +model = /home/anon/software/models/GLM-4.7-Flash-UD-Q3_K_XL.gguf +ctx-size = 24576 # = clients (MLA KV is compact; n_ctx_train 202752) +n-gpu-layers = 99 +n-cpu-moe = 12 # ✓ KEEP (09-21: 26.0 t/s, 13.4 used / 3.8 free @2.0 daytime). Evening- + # safe (~14.7 used @3.3). moe9 = +~1 t/s for ~15.4 evening → no. +threads = 6 +flash-attn = on +cache-type-k = q8_0 +cache-type-v = q8_0 # MLA: mixed K/V types are rejected at context creation (see Q4 preset) +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 +defrag-thold = 0.1 +temp = 0.6 # mirrors the Q4 preset (unsloth: 0.7/top-p 1.0 tools, 1.0/0.95 general) +top-p = 0.95 +min-p = 0.01 +jinja = on +reasoning-preserve = true # mirrors the Q4 preset — same behaviour flag, same review caveat +sleep-idle-seconds = 60 + +# ───────────────────────────────────────────────────────────────────────────── +# Utility & candidates +# ───────────────────────────────────────────────────────────────────────────── + +[Qwen3-Embedding-0.6B] +# Embeddings-only, for RAG/semantic search (OWUI etc. via /v1/embeddings) — NOT a chat model, +# so it is deliberately absent from the opencode/pi/aichat chat lists. +# Qwen3-Embedding requires last-token pooling. ~0.7 GB — tiny, loads fast. +# (Q8_0 is effectively lossless for a 0.6B embedder — the f16 file is redundant, delete it.) +# CPU-ONLY on purpose: a 0.6B embeds fast on 6 cores, and 0 VRAM means it can never stack +# with a chat model into an overcommit (and never suffers/causes eviction pressure). +model = /home/anon/software/models/Qwen3-Embedding-0.6B-Q8_0.gguf +embeddings = true +pooling = last +ctx-size = 8192 +n-gpu-layers = 0 +flash-attn = on +batch-size = 8192 # embed long chunks in one pass +ubatch-size = 1024 +threads = 6 +sleep-idle-seconds = 60 + +[gpt-oss-20b] +# OpenAI gpt-oss-20b — MoE 21B / 3.6B active, reasoning + tool use (enabled 2026-07-16, NOT +# BENCHED yet). OpenAI post-trained it in MXFP4, so there is exactly ONE sensible GGUF: +# ggml-org/gpt-oss-20b-GGUF → gpt-oss-20b-mxfp4.gguf (~12.1 GB). Requants are never better — +# the old gpt-oss-20b-Q3_K_M.gguf can be deleted. +# Harmony chat template → jinja required. Default KV types kept (gpt-oss attention sinks have +# had issues with quantized KV — verify before adding cache-type lines). +model = /home/anon/software/models/gpt-oss-20b-mxfp4.gguf +ctx-size = 65536 # ⚗→✓ VERIFIED @65536 (04:11): 37.3/37.4 t/s unchanged, 14.0 used / 3.2 + # free — the fast long-context option is real (37 t/s vs Coder-Next 16). + # 131072 is OFF the table: 32k→65k cost +1.2 GB (KV slope steepens past + # the sliding window) → 131k would land under 2.5 free. Client caps + # raised 32k→64k on 2026-08-08. +n-gpu-layers = 99 +n-cpu-moe = 4 # ✓ SETTLED. MEASURED @6: 31.3 t/s · @4 (2026-07-16): 38.1 t/s, 12.7 used / + # 4.5 free — fastest model in the lineup. TTFT (~3-7 s) is the model THINKING + # (harmony reasoning streams as reasoning_content first) — not a slow load. +threads = 6 +flash-attn = on +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 +defrag-thold = 0.1 +temp = 1.0 +top-p = 1.0 +jinja = on +sleep-idle-seconds = 120 + +[gpt-oss-20b-low] +# Same GGUF, reasoning effort LOW — zero disk cost (like the 35B-Thinking alias, inverted). +# Cuts the multi-second thinking preamble for light/interactive use; keep [gpt-oss-20b] +# (default = medium effort) for hard problems. ⚠ if startup says the option is not +# recognized, the llama.cpp build predates chat-template-kwargs — comment that line out. +model = /home/anon/software/models/gpt-oss-20b-mxfp4.gguf +chat-template-kwargs = {"reasoning_effort":"low"} +ctx-size = 65536 # ⚗→✓ VERIFIED @65536 (04:11): 37.3/37.4 t/s unchanged, 14.0 used / 3.2 + # free — the fast long-context option is real (37 t/s vs Coder-Next 16). + # 131072 is OFF the table: 32k→65k cost +1.2 GB (KV slope steepens past + # the sliding window) → 131k would land under 2.5 free. Client caps + # raised 32k→64k on 2026-08-08. +n-gpu-layers = 99 +n-cpu-moe = 4 +threads = 6 +flash-attn = on +batch-size = 2048 +ubatch-size = 512 +cache-reuse = 256 +defrag-thold = 0.1 +temp = 1.0 +top-p = 1.0 +jinja = on +sleep-idle-seconds = 60 + +# ───────────────────────────────────────────────────────────────────────────── +# Notes +# ───────────────────────────────────────────────────────────────────────────── +# n-cpu-moe N : offload the first N MoE layers' experts to CPU. Higher = less VRAM (safer) but +# slower. On this display-driving GPU, a bit of offload is FAR better than a freeze. +# Only applies to MoE models (dense models ignore it — reduce ctx instead). +# override-tensor : finer control, e.g. `blk\.(1[2-9]|[2-9][0-9])\.ffn_.*_exps=CPU`. +# After ANY change: reload the server and run bench.py — keep every "VRAM free" ≥ ~2.5 GB. diff --git a/fl/.config/llamacpp/gpumon.sh b/fl/.config/llamacpp/gpumon.sh new file mode 100755 index 0000000..60e891b --- /dev/null +++ b/fl/.config/llamacpp/gpumon.sh @@ -0,0 +1,70 @@ +#!/bin/sh +# gpumon.sh — one screen of GPU state for fl (RX 7600 XT · amdgpu · Vulkan backend). +# +# watch -c -d -n 1 ~/.config/llamacpp/gpumon.sh (fish abbr `vramx`, fl/.config/fish/host.fish) +# ~/.config/llamacpp/gpumon.sh (one shot) +# +# Why not rocm-smi: `--showmemuse` gives percentages and hides GTT. The freeze mode on this box is +# VRAM overcommit spilling into GTT (system RAM) — see the config.ini header — so GTT and the +# absolute free-VRAM figure (the ≥ 2.5 GB gate) are the numbers that matter. amdgpu exposes both +# in sysfs: instant, no ROCm needed. Per-process VRAM comes from /proc//fdinfo (kernel +# drm-usage-stats), readable only for your own processes unless root. llama.service runs as the +# login user (anon), so its children show up; if they ever don't: +# systemctl show -p User llama.service and run this with sudo. +# No absolute GTT alarm on purpose: bench.py judges GTT as a delta over a per-model baseline +# (a browser-heavy desktop legitimately sits on a few GB) — `watch -d` shows the movement. +# +# GPUMON_HOST overrides the router host (default 127.0.0.1) — for a dry run from another box. + +dev=/sys/class/drm/renderD128/device +host=${GPUMON_HOST:-127.0.0.1} +port=11343 + +echo "=== GPU (amdgpu sysfs) ===" +if [ -r "$dev/mem_info_vram_used" ]; then + temp=$(cat "$dev"/hwmon/hwmon*/temp1_input 2>/dev/null | head -n 1) + awk -v u="$(cat "$dev/mem_info_vram_used")" -v t="$(cat "$dev/mem_info_vram_total")" \ + -v g="$(cat "$dev/mem_info_gtt_used" 2>/dev/null)" -v gt="$(cat "$dev/mem_info_gtt_total" 2>/dev/null)" \ + -v b="$(cat "$dev/gpu_busy_percent" 2>/dev/null)" -v m="$(cat "$dev/mem_busy_percent" 2>/dev/null)" \ + -v c="${temp:-0}" 'BEGIN { + G = 1073741824 + free = (t - u) / G + flag = free < 1.5 ? " <<< HARD FLOOR (bench.py guard)" : free < 2.5 ? " <-- below the 2.5 GB target" : "" + printf "VRAM %5.2f / %5.2f GiB free %5.2f GiB%s\n", u / G, t / G, free, flag + printf "GTT %5.2f / %5.2f GiB (VRAM spilled to RAM — must not grow while a model is resident)\n", g / G, gt / G + printf "busy gpu %3d%% mem %3d%% edge %d°C\n", b, m, c / 1000 + }' +else + echo "no amdgpu sysfs under $dev — not the fl box, or the GPU is not renderD128" +fi + +echo +echo "=== processes holding the GPU (VRAM from fdinfo · RSS · uptime; own-user only unless root) ===" +# fuser puts the PID list on stdout (the pretty table of -v goes to stderr, hence no -v here). +pids=$(fuser /dev/dri/renderD128 /dev/dri/card* 2>/dev/null | tr ' ' '\n' | grep -E '^[0-9]+$' | sort -un) +if [ -z "$pids" ]; then + echo "(nothing visible — no /dev/dri here, or the GPU users belong to another user)" +else + for p in $pids; do + [ -r "/proc/$p/fdinfo" ] || continue + # one drm client can be reachable through several fds — dedupe by drm-client-id, then sum + vram=$(awk 'FNR == 1 { cid = "" } + /^drm-client-id:/ { cid = $2 } + /^drm-(total|memory)-vram:/ { v[cid] = $2 } + END { for (k in v) s += v[k]; printf "%.2f", s / 1048576 }' /proc/"$p"/fdinfo/* 2>/dev/null) + name=$(cat /proc/"$p"/comm 2>/dev/null) + alias=$(tr '\0' '\n' < /proc/"$p"/cmdline 2>/dev/null | awk '$0 == "--alias" { getline; print; exit }') + set -- $(ps -o rss=,etime= -p "$p" 2>/dev/null | awk '{ printf "%.1f %s", $1 / 1048576, $2 }') + printf '%7s GiB %7s %-16s rss %5s GiB up %-11s %s\n' "$vram" "$p" "$name" "${1:-?}" "${2:-?}" "$alias" + done | sort -rn | head -n 15 +fi + +echo +echo "=== router $host:$port — preset status (anything not unloaded; the sysfs line above is the truth for VRAM) ===" +if out=$(curl -sf -m 1 "http://$host:$port/models" 2>/dev/null); then + printf '%s' "$out" \ + | jq -r '.data[] | select(.status.value != "unloaded") | "\(.status.value)\t\(.id)"' 2>/dev/null \ + | { grep . || echo "(nothing resident)"; } +else + echo "(router not answering — systemctl status llama.service)" +fi diff --git a/fl/.config/vllm/README.md b/fl/.config/vllm/README.md new file mode 100644 index 0000000..3fa4673 --- /dev/null +++ b/fl/.config/vllm/README.md @@ -0,0 +1,206 @@ +# vLLM on fl (docker, ROCm) — side by side with the llama.cpp router, never at the same time + +Added 2026-10-21 to answer one question: **how does vLLM compare with llama.cpp on this card, on the +same models?** It is a bench rig, not a second production endpoint. Nothing here was run on fl yet — +fl has no sshd, so every command below is for you to run there; the first run will find the rough edges. + +- **Box**: the same fl as the router — RX 7600 XT 16 GB (gfx1102, RDNA3), 5600X, 48 GB RAM. The card + drives the display. llama.cpp runs the Arch Vulkan build; vLLM needs ROCm, which comes **inside the + docker image** — nothing ROCm is installed on the host. +- **Files**: `vllm.ini` (presets, same `key = --flag` convention as `../llamacpp/config.ini`), + `vllmctl.py` (start/stop with the VRAM guards), `bench-vs.py` (one table for both engines). +- **Port 11348**. Not in the router, not in any client list (opencode/pi/aichat/OWUI) on purpose. + +## ⚠ The one rule: one engine resident at a time + +vLLM pre-allocates `gpu-memory-utilization` × 16 GiB at startup and keeps it, idle or not. The router +loads models lazily on request. So while vLLM is up, **any client request to :11343** makes the router +load a model on top of it → overcommit → GTT spill → frozen PC (the same failure `--models-max 1` +guards against). Unloading resident models is not enough; the clients on the LAN are the problem. + +`vllmctl.py up` therefore refuses while `llama.service` is active. The sequence is always: + +```fish +~/.config/vllm/vllmctl.py up --stop-router # sudo systemctl stop llama.service, then start vLLM +# … use / bench vLLM … +~/.config/vllm/vllmctl.py down # stop container, wait for VRAM to drain +sudo systemctl start llama.service # router back for the LAN +``` + +The other order is the only one that should fail safely: vLLM compares its requested budget against +free VRAM at startup and aborts when a router model is resident ("free memory … is less than desired +GPU memory utilization" — reported by users, not something verified on this card). Everything else freezes. + +## What "same models" means here, and the size surprise + +llama.cpp runs GGUF; vLLM runs Hugging Face safetensors (bf16 / AWQ / GPTQ / compressed-tensors). +The GGUF files cannot be loaded natively, so the pairs below are **the same model at a vLLM-native +quant**, not the same files (same-file GGUF loading is phase 2, see the end). + +Sizes from the HF API, 2026-10-21 — the "4-bit" vLLM checkpoints are **10–11.5 GB** because embeddings, +lm_head and the vision tower stay bf16. They are bigger than the Q6/Q8 GGUFs they pair with, so on +16 GB they are **clean-desktop only**, at `gpu-memory-utilization` ≈ 0.78 and 16k context: + +| pair | llama.cpp preset (ledger) | vLLM preset (`vllm.ini`) | vLLM weights | fits? | +|---|---|---|---|---| +| smoke | — | `Qwen3-0.6B-smoke` = `Qwen/Qwen3-0.6B` | 1.5 GB | yes — proves docker+GPU+image | +| gemma-4-E4B | `gemma-4-E4B-it-UD-Q8_K_XL` — 57 t/s **with MTP**, 96k ctx, ~7 GB | ~~`google/gemma-4-E4B-it-qat-w4a16-ct`~~ | 11.5 GB | **✗ no** (2026-10-21): vLLM needs ~16 GiB before any KV — the bf16 per-layer embedding table (262144 × 42 × 256 × 2 B = 5.6 GB) is held twice. Tombstone in the ini. | +| Qwen3.5-9B | `Qwen3.5-9B-UD-Q6_K_XL` — 32 t/s **with MTP**, 32k ctx, 9 GB | `Qwen3.5-9B-w4a16` = `RedHatAI/Qwen3.5-9B-quantized.w4a16` | 11.0 GB | the last viable pair: 0.75 on a 2.1 GB desktop, 0.78 clean; prefill batch 512 | + +**Cannot be compared on this card at all**: every 30B+ MoE (Coder-30B, GLM-4.7-Flash, Qwen3.6-35B, +Ornith, gemma-4-26B), Coder-Next 80B and Qwen3.8-27B — they only fit llama.cpp through `n-cpu-moe` +expert offload into RAM, which vLLM does not have (its MoE CPU-offload RFC died stale; the only +option is whole-weight `cpu_offload_gb`, which is slow). gpt-oss-20b (MXFP4, ~13 GB) is marginal and +its RDNA3 kernel status is unknown — not in the ini. + +**Why the "docker should just work" expectation does not hold here**: of the three first-day failures, +one was the image (no gfx1102 kernels → the override, solved) and two were memory. vLLM keeps +everything in VRAM — bf16 embeddings, fp32 logits during profiling, CUDA-graph memory — on a card that +also drives the desktop. No image changes a model's memory need; the ROCm images on Docker Hub are the +right ones. + +So the comparison is **not apples to apples** and the table says so: llama.cpp rows run Q8/Q6 with a +speculative MTP draft at a bigger context; vLLM rows run int4 without speculation at 16k. Read it as +"what each engine delivers on this card for this model", not as a kernel shoot-out. + +## Setup on fl (once) + +```fish +sudo pacman -S docker # ~20 GB free disk for the ROCm image + 25 GB for two models +sudo systemctl enable --now docker +sudo usermod -aG docker anon # then log out / in (or `newgrp docker`) +cd ~/.dots && ./install.sh # links ~/.config/vllm/* (new files are not live until re-stow) +~/.config/vllm/vllmctl.py pull # vllm/vllm-openai-rocm:v0.32.0 (ROCm 10.0; 11.6 GB download, ~25 GB on disk) +~/.config/vllm/vllmctl.py gpu-check # torch sees the card? prints device name + gfx arch +``` + +`gpu-check` must print `cuda available: True`, a `gfx1100` device (that is the override at work) and +`torch kernel: ok`. **The override is required** (found 2026-10-21): `v0.32.0` carries no gfx1102 code +objects, and a kernel launch without one aborts the process *silently* — the engine core vanishes, the +API server only says `Failed core proc(s): {}`, and even the `print`s before the abort are lost to +stdout buffering. `[global] env.HSA_OVERRIDE_GFX_VERSION = 11.0.0` presents the card as gfx1100 (RX 7900), +whose RDNA3 code runs on this chip. Nothing else on the host changes. + +Then the smoke test (tiny model, 30 % of the card, proves the whole path before any big download — +✓ passed 2026-10-21: 154.9 t/s decode, 1462 t/s prefill, TTFT 0.02 s, 7.7 GB used incl. a 2.9 GB desktop): + +```fish +~/.config/vllm/vllmctl.py up Qwen3-0.6B-smoke --stop-router +curl -s localhost:11348/v1/chat/completions -H 'content-type: application/json' \ + -d '{"model":"Qwen3-0.6B-smoke","messages":[{"role":"user","content":"hi"}],"max_tokens":20}' +~/.config/vllm/vllmctl.py down; sudo systemctl start llama.service +``` + +First start of any model compiles Triton kernels: minutes, with `vllmctl.py up` echoing the log tail +every 30 s. + +**Tags and updates.** `` is the part after the colon: `latest` = newest stable release (was +`v0.32.0` on 2026-10-18, ROCm 10.0), `nightly` = today's main branch (18 GB), `latest-rocm72` / +`nightly-rocm72` = the same on the older ROCm 7.2 stack (smaller, 12 GB), `…-base` = without vLLM +itself. The ini pins `v0.32.0` so a re-pull cannot silently change the engine under a bench run. To +update: pick the new `vX.Y.Z` on hub.docker.com/r/vllm/vllm-openai-rocm/tags, put it in `[global] image`, +`vllmctl.py pull`, then `vllmctl.py down` / `up` — the container is recreated from the image on every +`up`. Afterwards `docker image prune -f` drops the superseded layers (`docker images` shows what is kept). +`HF_TOKEN` is only needed for gated repos; none of the three presets is gated. If one ever is, +`hf auth login` on fl writes `~/.cache/huggingface/token`, which the mounted cache hands to the container. + +## Running the benchmark + +Two phases, because the engines cannot be resident together. Do both on a **clean desktop** (close the +browser; `vramx` must show ≤ ~1.5 GB used) — the vLLM presets leave ~2 GB free at 0.78 and an evening +desktop does not fit. + +```fish +# phase 1 — vLLM (router stopped by --stop-router; first run also downloads the model) +~/.config/vllm/vllmctl.py up gemma-4-E4B-it-w4a16 --stop-router +~/.config/vllm/bench-vs.py -t vllm:gemma-4-E4B-it-w4a16 --ctx 8000 --concurrency 4 +~/.config/vllm/vllmctl.py down +~/.config/vllm/vllmctl.py up Qwen3.5-9B-w4a16 # router is still stopped +~/.config/vllm/bench-vs.py -t vllm:Qwen3.5-9B-w4a16 --ctx 8000 --concurrency 4 +~/.config/vllm/vllmctl.py down + +# phase 2 — llama.cpp (vLLM down, router back) +sudo systemctl start llama.service +~/.config/vllm/bench-vs.py -t llamacpp:gemma-4-E4B-it-UD-Q8_K_XL -t llamacpp:Qwen3.5-9B-UD-Q6_K_XL --ctx 8000 --concurrency 4 +``` + +Every row lands in `bench-vs-history.md` (append) and the latest run in `bench-vs-results.md`, same +folder. The guards: a `llamacpp` target is skipped while vLLM answers `/health`; a `vllm` target is +skipped while the router has a model loaded or `llama.service` is active (`--force` overrides both). + +**How to read it** + +- `decode t/s` is usage tokens over wall time after the first token, measured the same way on both + engines; llama.cpp's own `timings` number is in parentheses so rows match `../llamacpp/bench-results.md`. +- Thinking is **off** on both (`chat_template_kwargs.enable_thinking=false`) and a reasoning delta counts + as first token, so TTFT compares the engines, not the preamble lengths. `--think` reverts that. +- `spec` shows the MTP draft on the llama.cpp side; vLLM rows have none unless the preset sets + `speculative-config`. Expect the gemma/Qwen llama.cpp rows to carry a 1.5–2× draft bonus. +- `agg t/s @N` is continuous batching's home turf — and llama-server still won it (85 vs 61 at 4 + streams): its default slot count on b11146 is evidently > 1, so no `parallel` key is needed. +- `--ctx 8000` adds decode at an 8k prompt — the number that matters for agent loops. + +## Results + +**2026-10-21, Qwen3.5-9B, same evening, same script, thinking off, 256 tok, 0.6 GB desktop:** + +| engine · checkpoint | spec | decode t/s | prefill t/s | TTFT s | decode @8k prompt | 4 streams agg t/s | VRAM used | +|---|---|---|---|---|---|---|---| +| vLLM · RedHatAI w4a16 @0.80, 16k, batch 512 | — | 29.4 | **181** | **0.17** | 16.0 | 60.6 | 12.5 GB | +| llama.cpp · UD-Q6_K_XL, 32k | MTP draft | **61.3** | 114 | 0.27 | **51.1** | **85.4** | 10.9 GB | + +What it says, for this card: + +- **Decode**: llama.cpp wins 2× single-stream and 3× at an 8k prompt. Most of the 2× is the MTP draft + (the ledger's pre-MTP Q8 number was 17 t/s in July; a no-draft Q6 today is probably ~30, i.e. parity + with vLLM). The 8k gap is not MTP: vLLM's decode halves with context here (16.0 vs 29.4) while + llama.cpp loses 17 % — on RDNA3 vLLM's attention path is the Triton generic one, llama.cpp's is a + tuned Vulkan kernel. +- **Prefill**: vLLM +59 % even with its batch capped at 512 for memory. This is its real strength on + the box, and it shows in TTFT. +- **Concurrency**: the column that was supposed to be vLLM's — it batched 4 streams to 2× its single + (60.6), but llama-server served the same 4 at 85.4. Its default slot count is evidently > 1 on this + build, so the README's "llama.cpp serializes" caveat does not hold; it does not need a `parallel` key. +- **Memory**: vLLM holds 1.6 GB more for a model with 2 GB less context, and only runs on a ≤ 0.6 GB + desktop. 0.75 was 0.11 GiB short of KV room; 0.80 is the setting. + +**Verdict**: no vLLM model earns a roster slot on fl; the bench rig stays, the router stays, llama-swap +is not needed. The one follow-up that could move the decode column is MTP in vLLM (the knob is in +the ini) — but it cannot touch the memory column or the MoE roster, so it is curiosity, not a decision. + +## When it does not start + +- **`No available memory for the cache blocks`** (seen 2026-10-21, gemma @0.73/8k on a 2.1 GB desktop): + the model loaded, but budget − weights − activation reservations left nothing for KV. What vLLM + reserved is in the log: `docker logs vllm 2>&1 | grep -iE 'profil|kv cache|weights take|peak'`. + Cheapest fixes first: text-only (`limit-mm-per-prompt` all zero — skips the image/audio encoder + warmup, now in both presets), smaller `max-num-batched-tokens` (2048, now in both presets), lower + `max-num-seqs`; then a cleaner desktop so the projection allows 0.78–0.82; last resort the smaller + GPTQ checkpoint. `--set key=val` tries any of these without editing the ini. +- **`ABORT: projected free …`**: the desktop is using more than the preset assumes. Close GPU apps or + take the suggested utilization it prints. `--force` exists; the freeze is real. +- **compressed-tensors / "no kernel" for int4 on ROCm**: both real presets use compressed-tensors + pack-quantized. If this image lacks a ROCm kernel for it, swap in the GPTQ alternative noted in the + ini (`Vishva007/gemma-4-E4B-it-W4A16-AutoRound-GPTQ`, 10.0 GB) — different kernel path. +- **Hangs / garbage output**: RDNA3 attention backend. Set `env.VLLM_ATTENTION_BACKEND = TRITON_ATTN` + explicitly; option names moved between versions — `vllmctl.py exec vllm serve --help` shows this image's. +- **GTT growing during a run** (`vramx`, the GTT line): the budget is leaking into system RAM — stop, + lower the utilization. Do not wait for the desktop to stutter. +- **Root-owned files in `~/.cache/huggingface`**: the container runs as root, so its downloads land + root-owned in anon's HF cache. Harmless for the rig; `sudo chown -R anon: ~/.cache/huggingface` if + the host-side `hf` tooling complains. +- **Container died**: `docker logs vllm` (the container is kept after a crash; `vllmctl.py up` shows + the tail and removes it on the next start). + +## Phase 2 — if the numbers justify more + +1. **Same-file GGUF in vLLM**: GGUF loading moved to an out-of-tree `vllm-gguf-plugin`; it is + "highly experimental and under-optimized" per vLLM's docs and needs a custom image layer + (`pip install vllm-gguf-plugin`), plus `--tokenizer `. Untested on ROCm. It would make the + weights identical — and show vLLM's unoptimized path, so interpret carefully. +2. **MTP in vLLM**: `RedHatAI/Qwen3.5-9B-quantized.w4a16` ships `model_mtp.safetensors`; the + commented `speculative-config` in the ini is the knob (syntax per this image's `--help`). +3. **Permanent coexistence**: replace the router's `--models-preset` mode with llama-swap (AUR + `llama-swap-bin`), which spawns llama-server *or* the vLLM container per model id, one at a time, + with a `ttl` idle unload. Same host/port/model ids for every client. Only worth it if a vLLM model + earns a place in the daily roster. diff --git a/fl/.config/vllm/bench-vs.py b/fl/.config/vllm/bench-vs.py new file mode 100755 index 0000000..2ed0c75 --- /dev/null +++ b/fl/.config/vllm/bench-vs.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +""" +bench-vs — the SAME prompt through llama.cpp (router :11343) and vLLM (:11348), one table. + +Measures per target: decode t/s, prefill t/s, TTFT, VRAM used/free (amdgpu sysfs, no root needed), +optionally decode at a long prompt (--ctx) and aggregate throughput under N parallel requests +(--concurrency). Method = ../llamacpp/bench.py (streamed chat completion, usage.completion_tokens +over wall time after the first token), applied identically to both engines; llama.cpp's own +`timings` figure is shown in parentheses so rows stay comparable with bench-results.md. + +Thinking is OFF by default on both engines (chat_template_kwargs.enable_thinking=false) and the +first reasoning_content delta counts as the first token anyway — a reasoning preamble of different +length per engine would otherwise poison TTFT. --think re-enables it. + +GUARDS (the card drives the display; two resident engines = GTT spill = frozen PC): + - a llamacpp target is refused while vLLM answers /health (stop it: ./vllmctl.py down) + - a vllm target is refused while the router reports a loaded model or llama.service is active + + ./bench-vs.py -t vllm:gemma-4-E4B-it-w4a16 # vLLM up (vllmctl.py up …), router stopped + ./bench-vs.py -t llamacpp:gemma-4-E4B-it-UD-Q8_K_XL # vLLM down, router started + ./bench-vs.py -t llamacpp:Qwen3.5-9B-UD-Q6_K_XL --ctx 8000 --concurrency 4 +Output: bench-vs-results.md (latest) + bench-vs-history.md (append), next to this script. Stdlib only. +""" +import argparse, json, os, re, subprocess, sys, threading, time, urllib.request, urllib.error +from datetime import datetime + +HERE = os.path.dirname(os.path.abspath(__file__)) +DRM = "/sys/class/drm/renderD128/device" +URLS = {"llamacpp": "http://127.0.0.1:11343/v1", "vllm": "http://127.0.0.1:11348/v1"} +TASK = "Write a Python function that merges two sorted lists, with a short docstring and one example." + + +def sysfs(name): + try: + return int(open(os.path.join(DRM, name)).read().strip()) + except (OSError, ValueError): + return None + + +def gb(b): + return f"{b / 1e9:.1f} GB" if b is not None else "-" + + +def http(url, key, payload=None, timeout=600): + data = json.dumps(payload).encode() if payload is not None else None + hdrs = {"Authorization": f"Bearer {key}"} + if data: + hdrs["Content-Type"] = "application/json" + return urllib.request.urlopen(urllib.request.Request(url, data=data, headers=hdrs), timeout=timeout) + + +def parse_ini(path): + sections, sec = {}, None + try: + lines = open(path, encoding="utf-8").read().splitlines() + except OSError: + return {} + for ln in lines: + s = ln.strip() + if not s or s.startswith("#"): + continue + if s.startswith("[") and s.endswith("]"): + sec = s[1:-1]; sections[sec] = {} + elif sec and "=" in s: + k, v = s.split("=", 1) + sections[sec][k.strip()] = v.split(" #", 1)[0].split("\t#", 1)[0].strip() + return sections + + +def run(base, key, model, prompt, n, temp, timeout, think): + payload = {"model": model, "messages": [{"role": "user", "content": prompt}], + "max_tokens": n, "temperature": temp, "stream": True, + "stream_options": {"include_usage": True}, + "timings_per_token": True} # llama.cpp extension, ignored by vLLM + if not think: + payload["chat_template_kwargs"] = {"enable_thinking": False} # both engines accept it; templates without it ignore it + t0 = time.perf_counter(); ttft = None; ntok = 0; usage = None; timings = None + for raw in http(base.rstrip("/") + "/chat/completions", key, payload, timeout): + line = raw.decode("utf-8", "ignore").strip() + if not line.startswith("data:"): + continue + body = line[5:].strip() + if body == "[DONE]": + break + try: + c = json.loads(body) + except ValueError: + continue + ch = c.get("choices") or [{}] + d = ch[0].get("delta", {}) if ch else {} + if d.get("content") or d.get("reasoning_content") or d.get("reasoning"): + if ttft is None: + ttft = time.perf_counter() - t0 + ntok += 1 + if c.get("usage"): + usage = c["usage"] + if c.get("timings"): + timings = c["timings"] + total = time.perf_counter() - t0 + comp = (usage or {}).get("completion_tokens") or ntok + ptok = (usage or {}).get("prompt_tokens") + gen_s = total - (ttft or total) + tg = comp / gen_s if gen_s > 0 else 0.0 + pp = (ptok / ttft) if (ptok and ttft) else None + srv = timings.get("predicted_per_second") if timings else None # llama.cpp's own number, for the ledger + return {"tg": tg, "pp": pp, "ttft": ttft or 0.0, "ptok": ptok or 0, "ctok": comp, "wall": total, "srv": srv, + "t0": t0, "t1": t0 + total} + + +def with_retries(fn, retries, wait, label=""): + last = None + for i in range(retries + 1): + try: + return fn() + except urllib.error.HTTPError as e: + body = e.read().decode("utf-8", "ignore")[:300] + if e.code < 500 or "failed to load" in body.lower(): + raise + last = e + except (urllib.error.URLError, ConnectionError, TimeoutError) as e: + last = e + if i < retries: + print(f" … {label}: not ready ({last}); retry in {wait}s", file=sys.stderr) + time.sleep(wait) + raise last + + +def vllm_up(url): + try: + return http(re.sub(r"/v1/?$", "", url) + "/health", "x", timeout=3).status == 200 + except Exception: + return False + + +def _status(m): + """Router /models status: newer builds send {'value': 'loaded'|'sleeping'|'unloaded'|…}, older a string.""" + st = m.get("status", "loaded") + return st.get("value", "loaded") if isinstance(st, dict) else st + + +def router_loaded(url): + try: + d = json.load(http(re.sub(r"/v1/?$", "", url) + "/models", "x", timeout=3)) + return [m["id"] for m in d.get("data", []) if _status(m) in ("loaded", "loading")] + except Exception: + return [] + + +def router_active(): + try: + r = subprocess.run(["systemctl", "is-active", "llama.service"], capture_output=True, text=True, timeout=10) + except (OSError, subprocess.TimeoutExpired): + return False + return r.stdout.strip() == "active" + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("-t", "--target", action="append", required=True, + help="engine:model, engine = llamacpp | vllm (repeatable)") + ap.add_argument("--url", action="append", default=[], help="engine=URL override, e.g. vllm=http://host:11348/v1") + ap.add_argument("-k", "--key", default="no-key-required") + ap.add_argument("-n", "--tokens", type=int, default=256) + ap.add_argument("--temp", type=float, default=0.3) + ap.add_argument("--ctx", type=int, default=0, help="also record decode at ~this many prompt tokens") + ap.add_argument("--concurrency", type=int, default=0, help="also record aggregate t/s with N parallel requests") + ap.add_argument("--think", action="store_true", help="leave the model's thinking ON (default: off on both engines)") + ap.add_argument("--timeout", type=int, default=600) + ap.add_argument("--retries", type=int, default=4); ap.add_argument("--retry-wait", type=int, default=15) + ap.add_argument("--force", action="store_true", help="skip the two-engines-resident guards") + ap.add_argument("--out", default=os.path.join(HERE, "bench-vs-results.md")) + ap.add_argument("--history", default=os.path.join(HERE, "bench-vs-history.md")) + a = ap.parse_args() + + urls = dict(URLS) + for u in a.url: + k, v = u.split("=", 1); urls[k] = v + llcfg = parse_ini(os.path.join(HERE, "..", "llamacpp", "config.ini")) + vlcfg = parse_ini(os.path.join(HERE, "vllm.ini")) + total = sysfs("mem_info_vram_total") + if total is None: + print(" (amdgpu sysfs not readable here — VRAM columns are OFF; run this ON fl for them)", file=sys.stderr) + + filler = ("The quick brown fox jumps over the lazy dog. " * max(1, a.ctx // 9)) if a.ctx else None + cols = ["engine", "model", "cfg ctx", "spec", "decode t/s", "prefill t/s", "TTFT s", "VRAM used", "VRAM free"] + if a.ctx: + cols.append(f"decode@{a.ctx // 1000}k") + if a.concurrency: + cols.append(f"agg t/s @{a.concurrency}") + + latest = open(a.out, "w", encoding="utf-8"); hist = open(a.history, "a", encoding="utf-8") + + def emit(line): + print(line); latest.write(line + "\n"); latest.flush(); hist.write(line + "\n"); hist.flush() + + latest.write("# llama.cpp vs vLLM (latest run)\n\n"); hist.write(f"\n## run {datetime.now():%Y-%m-%d %H:%M}\n\n") + emit(f"_Run {datetime.now():%Y-%m-%d %H:%M} · gen {a.tokens} tok · temp {a.temp} · thinking " + f"{'ON' if a.think else 'OFF'} · VRAM total {gb(total)} · baseline used {gb(sysfs('mem_info_vram_used'))} · " + f"decode = usage tokens / wall after first token on BOTH engines (llama.cpp's own timings in parentheses)_\n") + emit("| " + " | ".join(cols) + " |"); emit("|" + "|".join(["---"] * len(cols)) + "|") + + for t in a.target: + eng, _, model = t.partition(":") + if eng not in urls or not model: + emit(f"| {eng} | {model} | bad target — use engine:model with engine in {list(urls)} |"); continue + base = urls[eng] + # guards + if not a.force: + if eng == "llamacpp" and vllm_up(urls["vllm"]): + emit(f"| llamacpp | {model} | ⚠ SKIPPED: vLLM is up on {urls['vllm']} — loading a router model on top = freeze. " + f"`vllmctl.py down` first |"); continue + if eng == "vllm": + loaded = router_loaded(urls["llamacpp"]) + if loaded or router_active(): + emit(f"| vllm | {model} | ⚠ SKIPPED: router loaded={loaded or '-'} active={router_active()} — " + f"stop llama.service before benching vLLM |"); continue + if eng == "llamacpp": + c = llcfg.get(model, {}) + cfgctx, spec = c.get("ctx-size", "-"), (c.get("spec-type") or "-") + else: + c = vlcfg.get(model, {}) + cfgctx = c.get("max-model-len", "-") + spec = "mtp" if c.get("speculative-config") else "-" + cells = [eng, model, cfgctx, spec] + try: + with_retries(lambda: run(base, a.key, model, "hi", 8, a.temp, a.timeout, a.think), a.retries, a.retry_wait, model) + used = sysfs("mem_info_vram_used") + r = with_retries(lambda: run(base, a.key, model, TASK, a.tokens, a.temp, a.timeout, a.think), a.retries, a.retry_wait, model) + dec = f"{r['tg']:.1f}" + (f" ({r['srv']:.1f})" if r["srv"] else "") + cells += [dec, f"{r['pp']:.0f}" if r["pp"] else "-", f"{r['ttft']:.2f}", gb(used), + gb(total - used) if (total and used is not None) else "-"] + if a.ctx: + rc = run(base, a.key, model, filler + "\n\n" + TASK, a.tokens, a.temp, a.timeout, a.think) + cells.append(f"{rc['tg']:.1f}") + if a.concurrency: + res = [None] * a.concurrency + def worker(i): + res[i] = run(base, a.key, model, TASK + f" (variant {i})", a.tokens, a.temp, a.timeout, a.think) + th = [threading.Thread(target=worker, args=(i,)) for i in range(a.concurrency)] + for x in th: x.start() + for x in th: x.join() + ok = [x for x in res if x] + wall = max(x["t1"] for x in ok) - min(x["t0"] for x in ok) + cells.append(f"{sum(x['ctok'] for x in ok) / wall:.1f}" if wall > 0 else "-") + except Exception as e: + err = f"HTTP {e.code} {e.read().decode('utf-8', 'ignore')[:120]!r}" if isinstance(e, urllib.error.HTTPError) else f"ERROR {e}" + cells = cells[:4] + [err] + [""] * (len(cols) - 5) # same width whether it died early or in the --ctx/--concurrency pass + emit("| " + " | ".join(str(x) for x in cells) + " |") + + latest.write("\n_llama.cpp rows run with the preset's MTP draft when `spec` says so; vLLM rows have no speculation " + "unless `spec` = mtp. `agg t/s @N` = N parallel requests, completion tokens over the wall time of " + "the whole batch (llama-server's default slot count serves them in parallel too)._\n") + latest.close(); hist.close() + print(f"\nwrote {a.out} (+ appended {a.history})") + + +if __name__ == "__main__": + main() diff --git a/fl/.config/vllm/vllm.ini b/fl/.config/vllm/vllm.ini new file mode 100644 index 0000000..ae67c6a --- /dev/null +++ b/fl/.config/vllm/vllm.ini @@ -0,0 +1,92 @@ +# vLLM presets for fl — AMD RX 7600 XT · 16 GB · docker image vllm/vllm-openai-rocm +# Same convention as ../llamacpp/config.ini: section name = served model id, `key = value` = `--key value`. +# +# ⚠ ONE ENGINE AT A TIME. vLLM pre-allocates `gpu-memory-utilization` × 16 GiB at startup and KEEPS it. +# Any llama.cpp load on top (a client hitting :11343 is enough) overcommits → GTT spill → PC freeze. +# `vllmctl.py up` refuses to start while llama.service is active — stop the router first +# (`vllmctl.py up --stop-router`), start it again after `vllmctl.py down`. +# +# Sections: +# [global] container/runtime knobs (NOT vllm flags) — see vllmctl.py +# [] one `vllmctl.py up `: +# model HF repo id, or /models/ (models-dir is mounted at /models, read-only) +# any other key → `--key value` for `vllm serve`; `true` → bare `--key`; `false` → omitted +# served-model-name defaults to the section name (what clients and bench-vs.py use) +# x-* vllmctl-only metadata (x-weights-gb feeds the VRAM projection) +# env.NAME = value container environment (per preset; [global] env.* apply to all) +# +# VRAM MATH (vllmctl prints it before every start, aborts under reserve-gb unless --force): +# budget = gpu-memory-utilization × 17.16 GB (vLLM's total = the card's total, same as sysfs) +# budget must hold weights + activations + KV cache; everything above it + the desktop must stay +# under 16 GB with ≥ reserve-gb free. 0.75 → 12.9 GB budget → ~2.9 GB free on a 1.3 GB clean desktop. +# A busy evening desktop (3+ GB) does NOT fit any of the real models below — clean desktop only. +# Sizes measured 2026-10-21 from the HF API: the 4-bit vLLM checkpoints are 10-11.5 GB because +# embeddings, lm_head and the vision tower stay bf16 — bigger than the Q6/Q8 GGUFs they pair with. + +[global] +image = vllm/vllm-openai-rocm:v0.32.0 # = `latest` on 2026-10-18 (ROCm 10.0, 11.6 GB download); update = bump this + `vllmctl.py pull` +container = vllm +port = 11348 # whisper = 11345/11346, kokoro = 11347 +models-dir = /home/anon/software/models # mounted at /models (ro) — share the GGUF dir +hf-cache = /home/anon/.cache/huggingface # mounted at /root/.cache/huggingface (downloads + token) +router = http://127.0.0.1:11343 # llama.cpp router root (for the resident-model gate) +reserve-gb = 2.0 # abort if projected free VRAM < this (bench.py floor 1.5, target 2.5) +drain-gb = 4.0 # "card is clean" threshold before starting (same as bench.py) +health-timeout = 1800 # s — first start compiles Triton kernels, be patient +gpu-memory-utilization = 0.75 # default; presets override +# REQUIRED on this card (✓ verified 2026-10-21): v0.32.0 ships no gfx1102 code objects — without the +# override every GPU kernel launch aborts the process SILENTLY (the engine core just vanishes, the +# API server reports "Failed core proc(s): {}"). gfx1100 (RX 7900) code runs on gfx1102, same RDNA3 ISA. +env.HSA_OVERRIDE_GFX_VERSION = 11.0.0 +# Attention backend knobs (ROCm; names moved between versions — `vllmctl.py exec vllm serve --help`): +# env.VLLM_ATTENTION_BACKEND = TRITON_ATTN # the default on RDNA; set explicitly if a hang points at attention + +# ─── 1. smoke test — tiny, certain to be supported; proves docker + GPU + image + override ──── +# ✓ 2026-10-21: 154.9 t/s decode · 1462 t/s prefill · TTFT 0.02 s · 7.7 GB used incl. a 2.9 GB desktop. +[Qwen3-0.6B-smoke] +model = Qwen/Qwen3-0.6B +gpu-memory-utilization = 0.30 +max-model-len = 4096 +x-weights-gb = 1.5 + +# ─── 2. gemma-4-E4B — ✗ DOES NOT FIT vLLM ON THIS CARD (2026-10-21), tombstone kept for the math ── +# Pairs with llama.cpp [gemma-4-E4B-it-UD-Q8_K_XL] (57 t/s with MTP, 96k ctx). google/gemma-4-E4B-it-qat-w4a16-ct +# is 11.5 GB, and the second try (text-only, batch 2048, @0.73 on a 2.1 GB desktop) ended with +# "Available KV cache memory: -4.44 GiB" after an OOM on a 5,637,144,576-byte allocation. That is exactly +# Gemma 4's per-layer embedding table: 262144 vocab × 42 layers × 256 × 2 bytes (bf16). vLLM holds it +# in bf16 AND needs a second buffer of the same size → ~16 GiB before any KV block. No util, batch or +# desktop fixes that; the GPTQ/AWQ alternatives carry the same bf16 table. llama.cpp fits because the +# GGUF stores the table quantized, once. A different image changes nothing here. +# [gemma-4-E4B-it-w4a16] +# model = google/gemma-4-E4B-it-qat-w4a16-ct +# gpu-memory-utilization = 0.78 +# max-model-len = 16384 +# max-num-seqs = 4 +# max-num-batched-tokens = 2048 +# limit-mm-per-prompt = {"image": 0, "audio": 0, "video": 0} +# x-weights-gb = 11.5 + +# ─── 3. Qwen3.5-9B — pairs with llama.cpp [Qwen3.5-9B-UD-Q6_K_XL] (32 t/s with MTP, 32k ctx) ── +# Red Hat's llm-compressor int4 (compressed-tensors). 10.95 GB + a 0.49 GB MTP head file. +# Alternative (real AWQ, Triton kernels on ROCm): QuantTrio/Qwen3.5-9B-AWQ — 12.4 GB, too big for 0.78. +# The last viable "same model" pair: no per-layer table, but a 248k vocab → the fp32 logits buffer +# during profiling is max-num-batched-tokens × 248k × 4 B (2048 → 2.0 GB, 512 → 0.5 GB). Start small. +# On a 2.1 GB desktop the projection allows 0.75 (`--set gpu-memory-utilization=0.75`) → ~1.9 GB for +# activations + graphs + KV. If "No available memory for the cache blocks" again: `--set enforce-eager=true` +# (drops the CUDA-graph memory, costs decode speed), then a cleaner desktop for 0.78. +# ✓ RUNS 2026-10-21 @0.80 (0.75 was 0.11 GiB short of KV room): 29.4 t/s decode · 181 prefill · TTFT 0.17 · +# decode@8k 16.0 · 4-stream aggregate 60.6 · 12.5 GB used on a 0.6 GB desktop. Same evening, llama.cpp +# [Qwen3.5-9B-UD-Q6_K_XL] with its MTP draft: 61.3 · 114 · 0.27 · 51.1 · 85.4 · 10.9 GB. See README. +[Qwen3.5-9B-w4a16] +model = RedHatAI/Qwen3.5-9B-quantized.w4a16 +gpu-memory-utilization = 0.80 # needs a ≤ 0.6 GB desktop (projection: 2.9 GB free); 0.75 fails on KV room +max-model-len = 16384 +max-num-seqs = 4 +max-num-batched-tokens = 512 # caps the profiling logits buffer (prefill t/s cost — note it in the ledger) +limit-mm-per-prompt = {"image": 0, "video": 0} # text-only bench (Qwen3.5 has no audio input) +x-weights-gb = 11.0 +# NEXT (the one knob that could change the verdict): MTP speculative decoding — the repo ships +# model_mtp.safetensors and llama.cpp's 2× comes from exactly this. Costs ~0.5 GB weights + draft +# state → try @0.82 on a clean desktop. Syntax per `vllmctl.py exec vllm serve --help`: +# ./vllmctl.py up Qwen3.5-9B-w4a16 --set gpu-memory-utilization=0.82 --set 'speculative-config={"method": "mtp", "num_speculative_tokens": 2}' +# speculative-config = {"method": "mtp", "num_speculative_tokens": 2} diff --git a/fl/.config/vllm/vllmctl.py b/fl/.config/vllm/vllmctl.py new file mode 100755 index 0000000..5183bc5 --- /dev/null +++ b/fl/.config/vllm/vllmctl.py @@ -0,0 +1,398 @@ +#!/usr/bin/env python3 +""" +vllmctl — run vLLM (docker, ROCm) on fl WITHOUT freezing the box. + +The RX 7600 XT drives the display; VRAM overcommit spills to GTT and freezes the PC. vLLM grabs +`gpu-memory-utilization` × total VRAM at startup and keeps it, so this script gates every start: + + 1. llama.service must be STOPPED (or --stop-router): a LAN client hitting :11343 would make the + router load a model on top of vLLM = the freeze. --unsafe-keep-router skips this gate. + 2. the card must be clean (VRAM used ≤ drain-gb; resident router models are unloaded via its API). + 3. projected free VRAM = total − used − budget must be ≥ reserve-gb (else abort, --force overrides). + +Presets live in vllm.ini next to this file (same key = --flag convention as llamacpp/config.ini). + + ./vllmctl.py up [--stop-router] [--force] [--dry-run] start, wait for /health + ./vllmctl.py down stop, wait for VRAM to drain + ./vllmctl.py status | logs | pull | gpu-check | exec +Stdlib only. Run ON fl. +""" +import argparse, grp, json, os, re, shlex, subprocess, sys, time, urllib.request, urllib.error + +HERE = os.path.dirname(os.path.abspath(__file__)) +INI = os.path.join(HERE, "vllm.ini") +DRM = "/sys/class/drm/renderD128/device" + + +# ─── ini ──────────────────────────────────────────────────────────────────────────────────── +def parse_ini(path): + """{section: {key: value}} — inline `# comments` stripped, order kept.""" + sections, sec = {}, None + for ln in open(path, encoding="utf-8").read().splitlines(): + s = ln.strip() + if not s or s.startswith("#"): + continue + if s.startswith("[") and s.endswith("]"): + sec = s[1:-1]; sections[sec] = {} + elif sec and "=" in s: + k, v = s.split("=", 1) + sections[sec][k.strip()] = v.split(" #", 1)[0].split("\t#", 1)[0].strip() + return sections + + +def build_args(preset): + """vllm serve args from a preset section (x-* and env.* are not flags).""" + args = [] + for k, v in preset.items(): + if k.startswith("x-") or k.startswith("env."): + continue + if v.lower() == "false": + continue + if v.lower() == "true": + args.append(f"--{k}") + else: + args += [f"--{k}", v] + return args + + +# ─── gpu / router ─────────────────────────────────────────────────────────────────────────── +def sysfs(name): + try: + return int(open(os.path.join(DRM, name)).read().strip()) + except (OSError, ValueError): + return None + + +def vram(): + """(used, total, gtt_used) bytes from amdgpu sysfs; None where unreadable.""" + return sysfs("mem_info_vram_used"), sysfs("mem_info_vram_total"), sysfs("mem_info_gtt_used") + + +def gb(b): + return f"{b / 1e9:.1f} GB" if b is not None else "-" + + +def http(url, payload=None, timeout=10): + data = json.dumps(payload).encode() if payload is not None else None + hdrs = {"Content-Type": "application/json"} if data else {} + return urllib.request.urlopen(urllib.request.Request(url, data=data, headers=hdrs), timeout=timeout) + + +def _status(m): + """Router /models status: newer builds send {'value': 'loaded'|'sleeping'|'unloaded'|…}, older a string.""" + st = m.get("status", "loaded") + return st.get("value", "loaded") if isinstance(st, dict) else st + + +def router_loaded(root): + """ids the llama.cpp router reports as loaded ([] if unreachable).""" + try: + d = json.load(http(root.rstrip("/") + "/models", timeout=5)) + except Exception: + return [] + return [m["id"] for m in d.get("data", []) if _status(m) in ("loaded", "loading")] + + +def router_unload(root): + for m in router_loaded(root): + try: + http(root.rstrip("/") + "/models/unload", {"model": m}, timeout=30).read() + except Exception: + pass + + +def router_active(): + try: + r = subprocess.run(["systemctl", "is-active", "llama.service"], capture_output=True, text=True, timeout=10) + except (OSError, subprocess.TimeoutExpired): + return False + return r.stdout.strip() == "active" + + +def router_hint(): + return "" if router_active() else "\n (llama.service is STOPPED → sudo systemctl start llama.service to bring the router back)" + + +def wait_drain(drain_gb, window_s, label): + used, _, _ = vram() + end = time.time() + window_s + said = False + while used is not None and used > drain_gb * 1e9 and time.time() < end: + if not said: + print(f" … waiting for VRAM to drain {label} ({gb(used)} used)"); said = True + time.sleep(5) + used, _, _ = vram() + return used + + +# ─── docker ───────────────────────────────────────────────────────────────────────────────── +def docker(*args, check=True, capture=True): + return subprocess.run(["docker", *args], check=check, capture_output=capture, text=True) + + +def container_state(name): + r = docker("inspect", "-f", "{{.State.Status}}", name, check=False) + return r.stdout.strip() if r.returncode == 0 else None + + +def gpu_flags(): + flags = ["--device", "/dev/kfd", "--device", "/dev/dri", "--group-add", "video", + "--cap-add", "SYS_PTRACE", "--security-opt", "seccomp=unconfined", "--ipc=host"] + try: + flags += ["--group-add", str(grp.getgrnam("render").gr_gid)] # Arch: /dev/dri/renderD128 is group render + except KeyError: + pass + return flags + + +def run_cmd(g, name, preset, envs): + cmd = ["docker", "run", "-d", "--name", g["container"], *gpu_flags(), + "-p", f'{g["port"]}:8000', + "-v", f'{g["models-dir"]}:/models:ro', + "-v", f'{g["hf-cache"]}:/root/.cache/huggingface'] + for k, v in envs.items(): + cmd += ["-e", f"{k}={v}"] + cmd.append(g["image"]) + cmd += ["--host", "0.0.0.0", "--port", "8000", "--served-model-name", preset.get("served-model-name", name)] + cmd += build_args({k: v for k, v in preset.items() if k != "served-model-name"}) + return cmd + + +ROOT_CAUSE = re.compile(r"hipError|HSA_STATUS|code object|gfx\d+|no kernel image|EngineCore.*(ERROR|Error|error)" + r"|^\S*(ERROR|CRITICAL)|RuntimeError|ValueError|NotImplementedError|OutOfMemory|Killed|Segmentation" + r"|free memory|not supported|Unsupported|Traceback|memory profiling|kv cache memory|weights take|peak", re.I) + + +def root_cause(lines): + """The lines that explain a dead engine core: known ROCm/vLLM failure signatures, the FIRST + traceback's error line, and the last 8 lines — not the parent's 40-line stack trace.""" + out, seen = [], set() + for l in lines: + if ROOT_CAUSE.search(l) and "api_server" not in l and "core_client" not in l and "launch_core_engines" not in l: + key = l.strip()[:120] + if key not in seen: + seen.add(key); out.append(l.rstrip()) + if len(out) >= 30: + break + return out + ["…"] + [l.rstrip() for l in lines[-8:]] + + +# ─── commands ─────────────────────────────────────────────────────────────────────────────── +def cmd_up(a, cfg): + g = cfg["global"] + if a.preset not in cfg or a.preset == "global": + sys.exit(f"unknown preset {a.preset!r}; have: {', '.join(k for k in cfg if k != 'global')}") + preset = dict(cfg[a.preset]) + preset.update(dict(kv.split("=", 1) for kv in a.set)) # --set gpu-memory-utilization=0.73 --set max-model-len=8192 + preset.setdefault("gpu-memory-utilization", g.get("gpu-memory-utilization", "0.75")) + envs = {k[4:]: v for k, v in g.items() if k.startswith("env.")} + envs.update({k[4:]: v for k, v in preset.items() if k.startswith("env.")}) + envs.update(dict(e.split("=", 1) for e in a.env)) + util = float(preset["gpu-memory-utilization"]) + reserve = float(a.reserve if a.reserve is not None else g.get("reserve-gb", 2.0)) + drain = float(g.get("drain-gb", 4.0)) + + cmd = run_cmd(g, a.preset, preset, envs) + print("docker command:\n " + " ".join(shlex.quote(c) for c in cmd) + "\n") + if a.dry_run: + return + + st = container_state(g["container"]) + if st == "running": + sys.exit(f"container {g['container']} is already running — `vllmctl.py down` first") + if st: # leftover from a crash: its log is the evidence, show the tail, then clear the name + r = docker("logs", "--tail", "15", g["container"], check=False) + print(f"removing old container ({st}); its last lines were:\n" + "\n".join(" | " + l for l in (r.stdout + r.stderr).strip().splitlines()[-15:])) + docker("rm", g["container"], check=False) + + # 1. clean card — unload resident router models through its API while it is still up, then drain + if router_active(): + router_unload(g["router"]) + used = wait_drain(drain, 180, "before start") + used, total, gtt = vram() + if used is None or total is None: + if not a.force: + sys.exit(f"ABORT: cannot read {DRM}/mem_info_vram_* — no VRAM guard, not starting blind (--force overrides)") + print("⚠ FORCED without a VRAM guard (sysfs unreadable)"); used, total = 0, 1 + if used > drain * 1e9 and not a.force: + sys.exit(f"ABORT: card not clean — {gb(used)} VRAM used (> drain-gb {drain}). Leftover model / GPU apps?") + + # 2. projection — abort here costs nothing, llama.service is still running + budget = util * total + free_after = total - used - budget + weights = float(preset.get("x-weights-gb", 0) or 0) * 1e9 + print(f"VRAM: total {gb(total)} · used now {gb(used)} (GTT {gb(gtt)}) · vLLM budget {util:.2f} × total = {gb(budget)}" + f"\n → projected free {gb(free_after)} (reserve {reserve} GB)") + if weights: + room = budget - weights + print(f" budget − weights {gb(weights)} = {gb(room)} for activations + KV cache" + + (" ⚠ < 1 GB: expect 'no memory for KV cache' → raise util or lower max-model-len" if room < 1e9 else "")) + if free_after < reserve * 1e9: + suggest = max(0.0, (total - used - reserve * 1e9) / total) + msg = (f"projected free {gb(free_after)} < reserve {reserve} GB. Max safe gpu-memory-utilization right now " + f"= {suggest:.2f} (desktop is using {gb(used)}).") + if not a.force: + sys.exit("ABORT: " + msg + f"\n → free the desktop (vramx) or `--set gpu-memory-utilization={suggest:.2f}` " + f"(+ `--set max-model-len=8192` if weights leave < 1 GB); --force to start anyway.") + print("⚠ FORCED: " + msg) + + # 3. router gate — the only thing that stops a LAN client from loading a model on top of vLLM + if router_active(): + if a.stop_router: + print("stopping llama.service (sudo) …") + subprocess.run(["sudo", "systemctl", "stop", "llama.service"], check=True) + elif a.unsafe_keep_router: + print("⚠ llama.service stays ACTIVE: any client request to :11343 while vLLM runs = GTT freeze.") + else: + sys.exit("ABORT: llama.service is active. Any client request to :11343 would load a model on top " + "of vLLM and freeze the PC.\n → re-run with --stop-router (sudo systemctl stop llama.service), " + "or --unsafe-keep-router if you really know nothing will call the router.") + used2, _, _ = vram() + if used2 is not None and used2 > used + 1e9: # a client loaded something between projection and stop + print(f"⚠ VRAM grew to {gb(used2)} meanwhile — vLLM's own free-memory check should refuse; watch the start") + + # 4. start + wait + cid = subprocess.run(cmd, check=True, capture_output=True, text=True).stdout.strip() + print(f"started {cid[:12]} — waiting for http://127.0.0.1:{g['port']}/health (timeout {g.get('health-timeout', 1800)} s; " + f"first start compiles kernels)") + end = time.time() + int(g.get("health-timeout", 1800)) + last_log, shown = 0, set() + while time.time() < end: + st = container_state(g["container"]) + if st != "running": + r = docker("logs", g["container"], check=False) + print("root cause candidates (full log: docker logs " + g["container"] + "):") + for l in root_cause((r.stdout + r.stderr).splitlines()): + print(" | " + l[:200]) + sys.exit(f"ABORT: container is {st or 'gone'}. If a line names gfx1102 / 'code object' / hipErrorNoBinaryForGpu: " + f"uncomment env.HSA_OVERRIDE_GFX_VERSION = 11.0.0 in [global] and retry." + router_hint()) + try: + if http(f"http://127.0.0.1:{g['port']}/health", timeout=3).status == 200: + break + except Exception: + pass + if time.time() - last_log > 30: + r = docker("logs", "--tail", "3", g["container"], check=False) + tail = (r.stdout + r.stderr).strip().splitlines()[-3:] + for t in tail: + if t not in shown: # only lines not printed before (compile phases are quiet for minutes) + print(" | " + t[:160]); shown.add(t) + last_log = time.time() + time.sleep(3) + else: + sys.exit("ABORT: no /health within the timeout — `vllmctl.py logs`, then `vllmctl.py down`" + router_hint()) + used, total, gtt = vram() + print(f"UP. VRAM used {gb(used)} / free {gb(total - used)} · GTT {gb(gtt)}") + try: + ids = [m["id"] for m in json.load(http(f"http://127.0.0.1:{g['port']}/v1/models")).get("data", [])] + print(f"models: {', '.join(ids)} → http://192.168.0.204:{g['port']}/v1") + except Exception as e: + print(f"(/v1/models not readable yet: {e})") + print(f"next: ./bench-vs.py -t vllm:{preset.get('served-model-name', a.preset)} · when done: ./vllmctl.py down") + + +def cmd_down(a, cfg): + g = cfg["global"] + st = container_state(g["container"]) + if st: + print(f"stopping {g['container']} ({st}) …") + docker("stop", "-t", "60", g["container"], check=False) + docker("rm", g["container"], check=False) + else: + print("container not running") + used = wait_drain(float(g.get("drain-gb", 4.0)), 120, "after stop") + used, total, gtt = vram() + print(f"VRAM used {gb(used)} / free {gb(total - used) if total and used is not None else '-'} · GTT {gb(gtt)}") + if not router_active(): + print("llama.service is stopped → `sudo systemctl start llama.service` to bring the router back") + + +def cmd_status(a, cfg): + g = cfg["global"] + used, total, gtt = vram() + print(f"container {g['container']}: {container_state(g['container']) or 'not running'}") + print(f"VRAM used {gb(used)} / total {gb(total)} · GTT {gb(gtt)}") + print(f"llama.service: {'ACTIVE' if router_active() else 'stopped'} · loaded: {router_loaded(g['router']) or '-'}") + try: + ids = [m["id"] for m in json.load(http(f"http://127.0.0.1:{g['port']}/v1/models", timeout=3)).get("data", [])] + print(f"vLLM :{g['port']} serving: {', '.join(ids)}") + except Exception: + print(f"vLLM :{g['port']}: not answering") + + +def cmd_logs(a, cfg): + os.execvp("docker", ["docker", "logs", "-f", "--tail", "100", cfg["global"]["container"]]) + + +def cmd_pull(a, cfg): + os.execvp("docker", ["docker", "pull", cfg["global"]["image"]]) + + +GPU_CHECK = r""" +import os, torch +print('HSA_OVERRIDE_GFX_VERSION =', os.environ.get('HSA_OVERRIDE_GFX_VERSION', '(unset)')) +print('cuda available:', torch.cuda.is_available()) +p = torch.cuda.get_device_properties(0) +print('device:', torch.cuda.get_device_name(0) or '(no name)', p.gcnArchName, f'{p.total_memory / 1e9:.1f} GB') +print('torch kernel …', end=' ', flush=True) # a hard abort here (no code object for this arch) prints nothing more +x = torch.ones(1024, device='cuda'); torch.cuda.synchronize(); print('ok', x.sum().item()) +import vllm._C # noqa +ops = sorted({s.name.split('::', 1)[1] for s in torch._C._jit_get_all_schemas() if s.name.startswith('_C::')}) +print(f'vllm _C ops registered: {len(ops)}') +f16 = dict(device='cuda', dtype=torch.float16) +probes = {'silu_and_mul': lambda: torch.ops._C.silu_and_mul(torch.empty(4, 8, **f16), torch.randn(4, 16, **f16)), + 'gelu_fast': lambda: torch.ops._C.gelu_fast(torch.empty(4, 8, **f16), torch.randn(4, 8, **f16)), + 'rms_norm': lambda: torch.ops._C.rms_norm(torch.empty(4, 8, **f16), torch.randn(4, 8, **f16), torch.ones(8, **f16), 1e-6)} +for name, fn in probes.items(): + if name in ops: + print(f'vllm custom op {name} …', end=' ', flush=True); fn(); torch.cuda.synchronize(); print('ok -> the image has kernels for this arch') + break +else: + print('none of the probe ops exist in this build; first ops:', ops[:15]) +""" + + +def cmd_gpu_check(a, cfg): + """Does the image see the card? Prints torch's device name + arch (needs no model).""" + g = cfg["global"] + envs = [x for k, v in g.items() if k.startswith("env.") for x in ("-e", f"{k[4:]}={v}")] + envs += [x for e in a.env for x in ("-e", e)] + code = GPU_CHECK + cmd = ["docker", "run", "--rm", *gpu_flags(), *envs, "--entrypoint", "python3", g["image"], "-u", "-c", code] + print(" ".join(shlex.quote(c) for c in cmd)) + os.execvp("docker", cmd) + + +def cmd_exec(a, cfg): + g = cfg["global"] + if container_state(g["container"]) == "running": + os.execvp("docker", ["docker", "exec", "-it", g["container"], *a.cmd]) + envs = [x for k, v in g.items() if k.startswith("env.") for x in ("-e", f"{k[4:]}={v}")] + os.execvp("docker", ["docker", "run", "--rm", "-it", *gpu_flags(), *envs, "--entrypoint", a.cmd[0], g["image"], *a.cmd[1:]]) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--ini", default=INI) + sub = ap.add_subparsers(dest="cmd", required=True) + up = sub.add_parser("up"); up.add_argument("preset") + up.add_argument("--stop-router", action="store_true", help="sudo systemctl stop llama.service first") + up.add_argument("--unsafe-keep-router", action="store_true", help="leave llama.service running (freeze risk)") + up.add_argument("--force", action="store_true", help="ignore the VRAM projection / clean-card checks") + up.add_argument("--reserve", type=float, help="override reserve-gb") + up.add_argument("--dry-run", action="store_true", help="print the docker command only") + up.add_argument("--env", action="append", default=[], metavar="KEY=VAL", help="extra container env (e.g. HSA_OVERRIDE_GFX_VERSION=11.0.0)") + up.add_argument("--set", action="append", default=[], metavar="KEY=VAL", help="override a preset key for this start (e.g. gpu-memory-utilization=0.73)") + sub.add_parser("down"); sub.add_parser("status"); sub.add_parser("logs"); sub.add_parser("pull") + gc = sub.add_parser("gpu-check"); gc.add_argument("--env", action="append", default=[], metavar="KEY=VAL") + ex = sub.add_parser("exec"); ex.add_argument("cmd", nargs=argparse.REMAINDER) + a = ap.parse_args() + cfg = parse_ini(a.ini) + if "global" not in cfg: + sys.exit(f"{a.ini}: no [global] section") + {"up": cmd_up, "down": cmd_down, "status": cmd_status, "logs": cmd_logs, "pull": cmd_pull, + "gpu-check": cmd_gpu_check, "exec": cmd_exec}[a.cmd](a, cfg) + + +if __name__ == "__main__": + main() diff --git a/fl/.config/whisper/README.md b/fl/.config/whisper/README.md new file mode 100644 index 0000000..22f2d28 --- /dev/null +++ b/fl/.config/whisper/README.md @@ -0,0 +1,193 @@ +# Speech-to-text — setup & usage + +whisper.cpp serving Whisper models over an **OpenAI-compatible** transcription endpoint, so Open WebUI's +mic button works against local hardware. Added **2026-08-08**. + +- **Box**: same fl server as the LLM router — but this runs **entirely on CPU** (Ryzen 5600X, 6 cores). +- **Files here**: `whisper@.service` (one template unit) + one `.env` per model. + Models live with the GGUFs in `~/software/models/`. + +| instance | endpoint | model | speed / use | +|---|---|---|---| +| **`whisper@turbo`** | `http://$SERVER:11345/v1` | `ggml-large-v3-turbo-q5_0` (574 MB) | **default** — best accuracy, multilingual, ~15 s per request. This is what OWUI points at. | +| `whisper@small` | `http://$SERVER:11346/v1` | `ggml-small.en-q5_1` (181 MB) | English-only, ~5x lighter. Point a client here when latency beats accuracy. | + +Both run at once — together they're well under 1 GB of RAM and **zero VRAM**, so there is no reason to +stop one to use the other. Adding a third is a new `.env` file plus `systemctl enable --now whisper@`. + +## How it runs + +Template unit **`whisper@.service`** (a dedicated service user), from `/usr/bin/whisper-server` (Arch `extra/whisper-cpp`). +Each instance reads `~/.config/whisper/.env`: + +``` +WHISPER_MODEL=/home//software/models/ggml-large-v3-turbo-q5_0.bin +WHISPER_PORT=11345 +WHISPER_LANG=auto +``` + +which expands to: + +```sh +whisper-server --model $WHISPER_MODEL \ + --host 0.0.0.0 --port $WHISPER_PORT \ + --inference-path /v1/audio/transcriptions \ + --convert --tmp-dir /run/whisper- \ + --no-gpu --threads 6 --language $WHISPER_LANG +``` + +It is a template rather than N copied units on purpose: the `--tmp-dir` bug below had to be found once +and fixed once, and that only stays true while there is exactly one `ExecStart` in the repo. + +| flag | why | +|---|---| +| `--no-gpu` | **Load-bearing.** 0 VRAM — see below. | +| `--convert` | ffmpeg transcodes webm/opus/ogg → 16 kHz wav. Browsers record opus; whisper.cpp reads wav. **Requires ffmpeg on the box.** | +| `--inference-path` | `--request-path` defaults to empty, so this alone puts the route at `/v1/audio/transcriptions` — exactly where OWUI posts. | +| `--tmp-dir` | **Required.** Defaults to `"."`, i.e. the CWD — which is `/` here, and unwritable. Without it every request returns `FFmpeg conversion failed.`, plain wav included. `RuntimeDirectory=whisper-%i` creates and owns `/run/whisper-`. | +| `--language` | `auto` for multilingual models; `en` for `.en` models, where detection is pointless. | +| `--threads 6` | all cores; `Nice=5` yields to the router's CPU-offloaded experts. | +| ports `11345`/`11346` | clear of `11343` (router), **`11344` (the standalone embedding llama-server)** and `11434` (Ollama). Router *children* take random ephemeral ports (32768+), so low ports are safe from them — but run `ss -ltnp` before claiming one. | + +Keyless on the LAN, same posture as the router. If this ever leaves the trusted LAN it needs a proxy +with auth in front — whisper-server has no `--api-key`. + +**Deploying changes**: `/etc/systemd/system/whisper@.service` is a symlink to the file in the repo, so a +`git pull` edit is on disk immediately — but systemd caches unit files, so it still needs a reload. +(Copying into `/etc` instead would work, but then every repo edit silently drifts.) On the server: + +```sh +dotsync # nudges you if this dir changed +sudo systemctl daemon-reload +sudo systemctl restart whisper@turbo whisper@small +``` + +Editing only an `.env` needs no `daemon-reload` — just restart that instance. + +First install (stow does not install units): + +```sh +yay -S whisper-cpp ffmpeg +curl -L -o ~/software/models/ggml-large-v3-turbo-q5_0.bin \ + https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3-turbo-q5_0.bin +curl -L -o ~/software/models/ggml-small.en-q5_1.bin \ + https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.en-q5_1.bin + +# Point systemd at the REAL file in the repo, NOT the stowed symlink: stow already made +# ~/.config/whisper/whisper@.service a symlink, and systemctl rejects those with +# "Failed to link unit: Refusing to operate on linked unit file" +sudo systemctl link (readlink -f ~/.config/whisper/whisper@.service) # fish +sudo systemctl enable --now whisper@turbo whisper@small +``` + +## Why this is NOT a llama.cpp router preset + +The router *does* expose `POST /v1/audio/transcriptions` (it rewrites the request into a chat completion +with the prompt "Transcribe audio to text"), and `gemma-4-E4B` genuinely accepts audio input. Tempting — +but two reasons it stays a separate service. Don't re-litigate this without re-checking both: + +1. **`--models-max 1` eviction.** Every transcription would LRU-evict the resident chat model, and the + next chat message would reload it (~17.5 GB for GLM) with a cold prompt cache. Fine for a one-off + file; unusable for talking to a model. +2. **Format.** llama.cpp decodes audio via miniaudio — **wav/mp3/flac only**. OWUI's mic records + `audio/webm; codecs=opus` and its own transcode-to-mp3 step depends on ffprobe being usable inside + the OWUI AppImage; when that fails it silently forwards the opus file. `--convert` here makes the + question moot. + +Third reason, softer: an LLM asked to transcribe can paraphrase or answer the audio instead of +transcribing it, and the `gemma-4-E4B` preset samples at temp 1.0. Whisper is purpose-built and boring. + +**Still available as a fallback** for wav/mp3/flac (no config change needed), if these services are down: + +```sh +curl -F file=@clip.wav -F model=gemma-4-E4B-it-UD-Q8_K_XL \ + http://$SERVER:11343/v1/audio/transcriptions +``` + +## Open WebUI wiring + +Admin Settings → **Audio** → Speech-to-Text: + +| field | value | +|---|---| +| STT Engine | `OpenAI` | +| Base URL | `http://$SERVER:11345/v1` — no trailing path, OWUI appends `/audio/transcriptions`. Swap `11345`→`11346` for the fast instance. | +| API Key | any non-empty string (`none`) — ignored by whisper-server, but OWUI needs it set | +| STT Model | `whisper-1` — ignored by whisper-server; must not be blank | +| Request format | leave default (`multipart`) | + +OWUI sends multipart `model` + optional `language` + `file`; whisper-server reads the fields it knows +and ignores the rest. Note it joins segments with newlines, so long dictations arrive in the composer +with line breaks mid-sentence. + +## Verifying + +```sh +systemctl status whisper@turbo whisper@small +rocm-smi --showmeminfo vram # must be UNCHANGED vs before the services started + +curl -F file=@sample.wav http://$SERVER:11345/v1/audio/transcriptions # → {"text": "…"} +ffmpeg -i sample.wav -c:a libopus sample.webm # the case that actually matters: +curl -F file=@sample.webm http://$SERVER:11345/v1/audio/transcriptions # proves --convert +curl -F file=@sample.webm -F model=whisper-1 -F language=en \ + http://$SERVER:11346/v1/audio/transcriptions # OWUI's exact shape +``` + +Then: with a chat model loaded, transcribe and confirm `http://$SERVER:11343/v1/models` still +shows it `ready`/`sleeping` — **not** `unloaded`. That is the whole point of the separate service. + +**Measured 2026-08-08** (6 threads, CPU, 11 s JFK sample, `--convert` in the path): + +| model | per request | verdict | +|---|---|---| +| `large-v3-turbo-q5_0` (574 MB) | **~15.2 s** | accurate; too slow to dictate into comfortably | +| `small.en-q5_1` (181 MB) | **~2.2 s** | **~7x faster.** Word-for-word identical to turbo on the JFK sample — only punctuation differs (`And so my fellow Americans` vs turbo's `And so, my fellow Americans,`). | + +Runs were tight: small.en 2.16 / 2.16 / 2.20 s over three passes, turbo 15.1-15.2 s over three. +The webm/opus path costs nothing extra (2.19 s with `--convert` + OWUI's field shape). + +**On this evidence turbo is hard to justify as the default** — 13 seconds per utterance buys a comma on +clean audio. Where it should still win is names, jargon, accents and non-English speech, which the JFK +sample cannot show. If small.en holds up on real dictation, point OWUI at `:11346` and demote turbo to +the second instance (or just swap the ports in the two `.env` files). + +The cost is **flat** for both models: whisper pads every request to a 30 s window, so a 3 s clip costs +what a 30 s one does (turbo 15.1 s vs 15.2 s; small.en 2.08 s vs 2.20 s). It is a fixed toll per +utterance, not a rate — which is why the model is the only thing that moves it. +Flash-attention is already on by default in whisper-server, and the `parakeet-*` binaries in the package +have no server integration, so **model size is the only real dial**. + +A/B any candidate without touching a service: + +```sh +curl -LO https://github.com/ggml-org/whisper.cpp/raw/master/samples/jfk.wav # known text +time whisper-cli -m ~/software/models/ggml-small.en-q5_1.bin -f jfk.wav -t 6 -nt +time whisper-cli -m ~/software/models/ggml-base.en-q5_1.bin -f jfk.wav -t 6 -nt +``` + +## Troubleshooting + +- **Every request returns `{"error":"FFmpeg conversion failed."}`, wav included** → the temp dir is not + writable by the service user. Check `--tmp-dir /run/whisper-` is in ExecStart and that + `RuntimeDirectory=` created it (`ls -ld /run/whisper-turbo`). ffmpeg itself is fine — the startup log + says `ffmpeg is available.` either way. +- **`Failed to load environment files`** → the instance has no `.env` (`whisper@foo` needs `foo.env`), + or the repo was not re-stowed after adding it (`install.sh` links new files; `dotsync` does it for you). +- **webm/opus uploads fail, wav works** → ffmpeg missing or `--convert` dropped. `ffmpeg -version` on + the box; the journal logs the conversion command on each non-wav request. +- **VRAM moved when transcribing** → `--no-gpu` lost, or the package was rebuilt with a GPU backend. + Fix immediately; this is the freeze scenario. +- **Empty / hallucinated text on near-silence** → whisper's classic failure. Try VAD: + download `ggml-silero-v5.1.2.bin` and add `--vad --vad-model …` to the template. +- **Still too slow** → next step down is `ggml-base.en-q5_1.bin` (56 MB, ~4x lighter again) at a real + cost in accuracy on names and jargon. New `.env`, or edit `small.env`. +- **OWUI: "Server Connection Error"** → base URL has a trailing `/audio/transcriptions` (it appends that + itself), or the port is not reachable from the client host. + +## Watch list + +- `whisper-cpp` also ships **`parakeet-cli`** — NVIDIA Parakeet is much faster than Whisper on CPU for + English. No server front-end upstream yet (`examples/` has `parakeet-cli` but no server path); worth + rechecking, it would be the real fix for the 15 s toll. +- **TTS** (the other half of voice chat) is unconfigured — OWUI can drive its own, or llama.cpp can + serve OuteTTS via `--model-vocoder`. Separate job. diff --git a/fl/.config/whisper/small.env b/fl/.config/whisper/small.env new file mode 100644 index 0000000..60cf1e5 --- /dev/null +++ b/fl/.config/whisper/small.env @@ -0,0 +1,6 @@ +# FAST instance (port 11346) — English-only, ~5x lighter than turbo. +# Same API; point a client at :11346 instead of :11345 when latency matters more than accuracy. +# For a multilingual equivalent use ggml-small-q5_1.bin and set WHISPER_LANG=auto. +WHISPER_MODEL=/home/anon/software/models/ggml-small.en-q5_1.bin +WHISPER_PORT=11346 +WHISPER_LANG=en diff --git a/fl/.config/whisper/turbo.env b/fl/.config/whisper/turbo.env new file mode 100644 index 0000000..38537a2 --- /dev/null +++ b/fl/.config/whisper/turbo.env @@ -0,0 +1,6 @@ +# DEFAULT instance (port 11345) — the one Open WebUI points at. +# Best accuracy, multilingual. Measured 2026-08-08: ~15.1 s per request, FLAT (whisper pads every +# clip to a 30 s window, so a 3 s utterance costs the same as a 30 s one). +WHISPER_MODEL=/home/anon/software/models/ggml-large-v3-turbo-q5_0.bin +WHISPER_PORT=11345 +WHISPER_LANG=auto diff --git a/fl/.config/whisper/whisper@.service b/fl/.config/whisper/whisper@.service new file mode 100644 index 0000000..c121dde --- /dev/null +++ b/fl/.config/whisper/whisper@.service @@ -0,0 +1,48 @@ +[Unit] +Description=whisper.cpp STT server "%i" (CPU-only) — OpenAI-compatible /v1/audio/transcriptions +Documentation=file:///home/anon/.config/whisper/README.md +After=network-online.target +Wants=network-online.target + +[Service] +User=anon +Group=anon +WorkingDirectory=/ +# TEMPLATE UNIT — one file, N instances. `systemctl start whisper@small` reads its model/port/language +# from ~/.config/whisper/small.env. Deliberately not N copies of this unit: the --tmp-dir bug below had +# to be found once and fixed once, and that only holds if there is exactly one ExecStart in the repo. +EnvironmentFile=/home/anon/.config/whisper/%i.env +# whisper-server's --tmp-dir defaults to "." — with WorkingDirectory=/ that means it tries to write +# uploads and ffmpeg output into the filesystem root, and every request dies with +# {"error":"FFmpeg conversion failed."} (yes, even plain wav: --convert pipes everything to ffmpeg) +# RuntimeDirectory= creates /run/whisper-, owned by this user, wiped on stop. Per-instance so +# two servers can never collide on a temp filename. +RuntimeDirectory=whisper-%i +RuntimeDirectoryMode=0700 +# +# ⚠⚠ --no-gpu IS LOAD-BEARING. The GPU on this box drives the display AND holds a 13-15 GB chat model; +# ROCm does not OOM cleanly, it spills to GTT and freezes the whole PC. Whisper is CPU-only BY +# DESIGN (same rule as the Qwen3-Embedding preset): 0 VRAM means it can never stack into an +# overcommit, and it never evicts / gets evicted by the router. Do not remove. +# --convert shells out to ffmpeg (webm/opus/ogg -> 16 kHz wav). This is the whole reason the Open WebUI +# mic button works — the browser records opus, whisper.cpp reads wav. +# --inference-path puts the route exactly where OWUI posts (--request-path defaults to empty), so a +# client's base URL is http://192.168.0.204:/v1 . +ExecStart=/usr/bin/whisper-server \ + --model ${WHISPER_MODEL} \ + --host 0.0.0.0 --port ${WHISPER_PORT} \ + --inference-path /v1/audio/transcriptions \ + --convert \ + --tmp-dir /run/whisper-%i \ + --no-gpu \ + --threads 6 \ + --language ${WHISPER_LANG} +Restart=always +RestartSec=2 +# Yield to the llama.cpp router: its CPU-offloaded MoE experts (n-cpu-moe) want the same 6 cores. +Nice=5 +StandardOutput=journal +StandardError=journal + +[Install] +WantedBy=multi-user.target diff --git a/gui/.config/alacritty/alacritty.toml b/gui/.config/alacritty/alacritty.toml new file mode 100644 index 0000000..3213a2e --- /dev/null +++ b/gui/.config/alacritty/alacritty.toml @@ -0,0 +1,50 @@ +[general] +import = ["theme.toml"] + +[window] + +opacity = 0.7 + +padding.x = 25 +padding.y = 25 + +decorations = "Full" +decorations_theme_variant = "Dark" + +[font] +size = 12.0 + +[font.bold] +family = "CaskaydiaCove Nerd Font Mono" +style = "Bold" + +[font.bold_italic] +family = "CaskaydiaCove Nerd Font Mono" +style = "Bold Italic" + +[font.italic] +family = "CaskaydiaCove Nerd Font Mono" +style = "Italic" + +[font.normal] +family = "CaskaydiaCove Nerd Font Mono" +style = "Regular" +# family = "Source Code Pro" +# family = "Liberation Mono" + +[cursor] +blink_interval = 400 +blink_timeout = 15 + +[cursor.style] +shape = "Block" +blinking = "On" + +[keyboard] + +bindings = [ + { key = "J", mods = "Control|Shift", action = "ScrollLineDown" }, + { key = "K", mods = "Control|Shift", action = "ScrollLineUp" }, + { key = "D", mods = "Control|Shift", action = "ScrollPageDown" }, + { key = "U", mods = "Control|Shift", action = "ScrollPageUp" }, +] diff --git a/gui/.config/alacritty/theme.toml b/gui/.config/alacritty/theme.toml new file mode 100644 index 0000000..dc79cce --- /dev/null +++ b/gui/.config/alacritty/theme.toml @@ -0,0 +1,34 @@ +# Colours from Robb Owen's SynthWave '84 palette, arranged for this repo (yellow and magenta +# swapped). Background/foreground match kitty.conf's own colours. + +[colors.primary] +background = "#262335" +foreground = "#ffffff" + +[colors.cursor] +text = "#262335" +cursor = "#f97e72" + +[colors.selection] +text = "#262335" +background = "#f97e72" + +[colors.normal] +black = "#232530" +red = "#fe4450" +green = "#72f1b8" +yellow = "#ff7edb" +blue = "#03edf9" +magenta = "#fede5d" +cyan = "#03edf9" +white = "#ffffff" + +[colors.bright] +black = "#232530" +red = "#fe4450" +green = "#72f1b8" +yellow = "#ff7edb" +blue = "#03edf9" +magenta = "#f3e70f" +cyan = "#03edf9" +white = "#ffffff" diff --git a/gui/.config/dconf/profile/hyde_hyprland b/gui/.config/dconf/profile/hyde_hyprland new file mode 100644 index 0000000..0689bf4 --- /dev/null +++ b/gui/.config/dconf/profile/hyde_hyprland @@ -0,0 +1 @@ +user-db:hyde_hyprland diff --git a/gui/.config/dunst/dunstrc.d/50-dots-colors.conf b/gui/.config/dunst/dunstrc.d/50-dots-colors.conf new file mode 100644 index 0000000..aeb86e7 --- /dev/null +++ b/gui/.config/dunst/dunstrc.d/50-dots-colors.conf @@ -0,0 +1,53 @@ +# dunst drop-in — undo HyDE's pink critical notification, and make the progress bar visible. +# +# Why a drop-in and not the obvious files: +# ~/.config/dunst/dunstrc is GENERATED by ~/.local/share/wallbash/scripts/dunst.sh on every +# theme change, and says so in its own header. +# ~/.config/dunst/dunst.conf is HyDE's shipped source for that generator — but dunst.toml +# declares `action = "sync"` on the whole `dunst` directory, so HyDE +# overwrites it on every update. +# dunst >= 1.10 reads dunstrc.d/*.conf as drop-ins that override the base config (lexically last +# wins), and HyDE's sync copies its files in without deleting extras — so this file survives both +# a theme change and a HyDE update. Apply with `dunstctl reload`. +# +# [urgency_critical] is the pink: HyDE's generator injects background #f5e0dc (Catppuccin +# rosewater) with a #f38ba8 frame — a pale pink slab, and with `timeout = 0` it never expires, so +# one error notification sits on screen until dismissed. Note this block is NOT wallbash-driven +# (dunst.conf ships it commented out and the generator hardcodes it), so overriding it costs no +# theme coupling. Inverted here: dark base like every other surface, with the pink kept as text +# and frame so "critical" still reads as critical at a glance. +[urgency_critical] + background = "#1e1e2eF2" + foreground = "#f5e0dc" + frame_color = "#f38ba8" + +# urgency_low/normal are the everyday notifications — the volume/mute popup is `normal`, since +# volumecontrol.sh sends it with no -u. wallbash generates those as a primary colour at alpha `80` +# (#583A6B80 plum for normal, #657AA380 for low) and [global] adds `transparency = 10` on top, so +# roughly half the wallpaper shows through: on a pink-toned palette the popup reads as pink no +# matter what the base hue is. +# +# Overriding them here **decouples notifications from wallbash** — they no longer follow the +# wallpaper the way the cava bar, waybar and kitty still do. That is the deliberate trade for a +# readable popup. To hand them back to wallbash, delete these two blocks and restart dunst; the +# generated dunstrc underneath is untouched. +# +# The frames also needed fixing regardless of colour: the generator emits frame_color at alpha +# `03` (~1% opacity) and never sets `highlight`, and dunst falls back to frame_color for the +# progress bar — so the volume bar was drawing invisibly. +# +# Frame and highlight are deliberately NOT the mauve from hypr's active window border: at these +# sizes #ca9ee6 renders as a pink outline plus a pink bar, which is the thing that looked wrong in +# the first place. A neutral surface frame with a blue bar keeps the popup quiet. +[urgency_low] + background = "#1e1e2eF2" + foreground = "#cdd6f4" + frame_color = "#6c7086" + +[urgency_normal] + background = "#1e1e2eF2" + foreground = "#cdd6f4" + frame_color = "#45475a" + +[global] + highlight = "#89b4fa" diff --git a/gui/.config/environment.d/10-hyde-path.conf b/gui/.config/environment.d/10-hyde-path.conf new file mode 100644 index 0000000..3841157 --- /dev/null +++ b/gui/.config/environment.d/10-hyde-path.conf @@ -0,0 +1,12 @@ +# gui package — put HyDE's script dir on the systemd *user manager* PATH, so +# user units can resolve bare hyde script names. Nothing else on the system ever +# adds it: HyDE only self-bootstraps PATH inside its own wrappers +# (hyde-shell/app.sh), so anything a unit execs bare is "command not found" — +# hypridle's lock_cmd was the incident (TROUBLESHOOTING.md symptom 8). +# Lifecycle: the environment generator reads this at user-manager start, but the +# session-start PATH import overwrites the manager's PATH afterwards — daemon-reload +# won't re-apply this over an imported PATH; only relogin does. The fish twin +# gui/.config/fish/conf.d/hyde-path.fish is what makes that import *carry* the dir +# (it feeds the session PATH the import copies from), so both files are needed and +# together they hold in either order. +PATH=$HOME/.local/lib/hyde:$PATH diff --git a/gui/.config/fish/conf.d/00-hypr-config.fish b/gui/.config/fish/conf.d/00-hypr-config.fish new file mode 100644 index 0000000..81570aa --- /dev/null +++ b/gui/.config/fish/conf.d/00-hypr-config.fish @@ -0,0 +1,32 @@ +## gui package — pin which config Hyprland starts with. +## +## Points HYPRLAND_CONFIG at HyDE's Lua entry point, explicitly. The Lua chain +## loads HyDE's lua/ modules and then the user override +## ~/.config/hypr/hyprland.lua (repo: gui/.config/hypr/hyprland.lua, which pulls +## in the per-host host.lua). None of the old hyprlang .conf files are read in +## Lua mode. See LUA-PORT.md. +## +## Why it is set from *fish* of all places: HyDE's untracked +## ~/.config/fish/conf.d/hyde.fish exports it, and fish sources every +## conf.d/*.fish at startup. SDDM launches the session through the login shell +## (/usr/bin/start-hyprland, the `hyprland.desktop` entry — not +## `hyprland-uwsm.desktop`), so the compositor inherits whatever fish exported. +## HyDE's snippet only assigns `if test -z "$HYPRLAND_CONFIG"`, and conf.d files +## load in alphabetical order, so this file's `00-` prefix means ours is already +## set by the time hyde.fish looks — do not rename it above `hyde.fish`. +## +## The uwsm twin lives in gui/.config/uwsm/env-hyprland.d/10-dots.sh and covers +## the `hyprland-uwsm.desktop` session entry. Both are needed; neither is +## sufficient alone. Keeping the pins alive (instead of trusting HyDE's default) +## preserves the invariant that the dots repo decides the config, and makes any +## rollback a one-line edit. Takes effect at session start — relogin, not +## `hyprctl reload`. +## +## ROLLBACK to hyprlang (the chain was retired at LUA-PORT.md step 8, +## 2026-09-10): restore gui/.config/hypr, wm/.config/hypr, lw/.config/hypr and +## gui/.local/share/hyde from bddbbf3 (the last pre-step-8 commit), ./install.sh, point both +## pins back at "$HOME/.config/hypr/hyprland.conf" and relogin. d851213 is the +## last hyprlang `main` (the port merged 2026-11-09). +set -l hypr_data "$XDG_DATA_HOME" +test -n "$hypr_data"; or set hypr_data "$HOME/.local/share" +set -gx HYPRLAND_CONFIG "$hypr_data/hypr/hyde.lua" diff --git a/gui/.config/fish/conf.d/hyde-path.fish b/gui/.config/fish/conf.d/hyde-path.fish new file mode 100644 index 0000000..875ddb5 --- /dev/null +++ b/gui/.config/fish/conf.d/hyde-path.fish @@ -0,0 +1,9 @@ +## gui package — put HyDE's script dir on the *session* PATH: the compositor and +## everything it spawns directly (raw exec binds, terminals) resolve bare hyde +## script names through it. Nothing else adds it — HyDE only self-bootstraps PATH +## inside its own wrappers (hyde-shell/app.sh), so a bare script name execed +## outside that lineage is "command not found" (TROUBLESHOOTING.md symptom 8). +## The systemd-unit side is covered by the twin +## gui/.config/environment.d/10-hyde-path.conf — both are needed. +## No ordering constraint vs hyde.fish (it never touches this dir). +fish_add_path --global ~/.local/lib/hyde diff --git a/gui/.config/fish/conf.d/zz-unhyde-prompt.fish b/gui/.config/fish/conf.d/zz-unhyde-prompt.fish new file mode 100644 index 0000000..fde0293 --- /dev/null +++ b/gui/.config/fish/conf.d/zz-unhyde-prompt.fish @@ -0,0 +1,25 @@ +## gui package — undo the starship prompt that HyDE's fish snippet installs. +## +## The HyDE 26.x update dropped an untracked ~/.config/fish/conf.d/hyde.fish that +## runs `starship init fish | source`. That eagerly defines fish_prompt AND +## fish_right_prompt, which shadows our own functions/fish_prompt.fish: fish only +## autoloads a function that is not already defined, so ours never loaded and +## every new shell came up with starship's prompt. +## +## conf.d is sourced alphabetically, so this file must sort AFTER hyde.fish to +## undo it — hence zz-. +## +## Note it *sources* our prompts rather than erasing starship's: `functions --erase` +## on an autoloadable name also suppresses the autoload, which leaves the shell +## with no fish_prompt at all ("Unknown command: fish_prompt"). Defining ours over +## the top is what actually wins — for fish_right_prompt too, since common ships +## functions/fish_right_prompt.fish (the git-status right prompt). +## +## Nothing else from hyde.fish is undone here: its aliases lose to config.fish, +## which fish loads after conf.d, and its `df` wrapper is a function we do not +## otherwise define. Delete this file if you ever decide you want starship. +for f in fish_prompt fish_right_prompt fish_mode_prompt + if test -r $__fish_config_dir/functions/$f.fish + source $__fish_config_dir/functions/$f.fish + end +end diff --git a/gui/.config/fish/functions/fish_mode_prompt.fish b/gui/.config/fish/functions/fish_mode_prompt.fish new file mode 100644 index 0000000..ff0255b --- /dev/null +++ b/gui/.config/fish/functions/fish_mode_prompt.fish @@ -0,0 +1,3 @@ +function fish_mode_prompt --description "Displays the current vi mode" + fish_default_mode_prompt +end diff --git a/gui/.config/hypr/.luarc.json b/gui/.config/hypr/.luarc.json new file mode 100644 index 0000000..b7a5b18 --- /dev/null +++ b/gui/.config/hypr/.luarc.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json", + "diagnostics": { + "globals": ["hl", "hyde", "check_require"] + }, + "workspace": { + "library": ["/usr/share/hypr/stubs", "~/.local/share/hypr/lua"] + }, + "runtime": { + "version": "Lua 5.5" + } +} diff --git a/gui/.config/hypr/battery.sh b/gui/.config/hypr/battery.sh new file mode 100755 index 0000000..6a86692 --- /dev/null +++ b/gui/.config/hypr/battery.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Battery readout for the hyprlock label. Prints nothing on machines without a +# battery (wm desktop), so the label just stays empty there. +for bat in /sys/class/power_supply/BAT*; do + [ -r "$bat/capacity" ] || continue + cap=$(<"$bat/capacity") + glyph="󰁹" + [ "$(cat "$bat/status" 2>/dev/null)" = "Charging" ] && glyph="󰂄" + printf '%s %s%%' "$glyph" "$cap" + exit 0 +done diff --git a/gui/.config/hypr/dots_binds.lua b/gui/.config/hypr/dots_binds.lua new file mode 100644 index 0000000..5c88057 --- /dev/null +++ b/gui/.config/hypr/dots_binds.lua @@ -0,0 +1,263 @@ +-- gui package — the dots keybinds, split out of ./hyprland.lua. Required there +-- after the app/start overrides (the launchers read hc.app.*) and before +-- ./host.lua. + +local hc = hyde.config +local MOD = hc.modifiers.main +local home = os.getenv("HOME") or "" + +-- ── Keybinds ───────────────────────────────────────────────────────────────── +-- Policy: preserve what the dots keybindings.conf did live until the port — +-- where a dots bind and a HyDE bind share a combo, the dots action wins and +-- the displaced HyDE action is noted. Binds identical in both are not +-- repeated here (volume/media/brightness, screenshots, Super+Q/W, +-- rofi menus, Super+L lock, Super+Shift+F pin, Super+S scratchpad family, +-- Super+Z/X + mouse drag/resize, Super+J togglesplit, Super+T/E/B via the +-- app.* overrides in hyprland.lua, Super+Alt+G gamemode, Ctrl+Shift+Esc +-- sysmon). + +-- Removes every live bind on a combo regardless of flags. hl.bind's dedup only +-- replaces a bind whose flags match exactly; HyDE binds with locked/transparent/ +-- repeating flags would otherwise stay live next to ours and double-fire. +local function unbind_all(combo) + -- _active/canonicalize are HyDE-private; if an update renames them, degrade + -- to "the displaced HyDE binds double-fire" instead of erroring here and + -- silently dropping every bind registered below this line. + if not (hyde.binds and hyde.binds._active and hyde.binds.canonicalize) then + return + end + local canon = hyde.binds.canonicalize(combo) + for id, registered in pairs(hyde.binds._active) do + if id:sub(1, #canon + 1) == canon .. "|" then + hl.unbind(registered) + hyde.binds._active[id] = nil + end + end +end + +local _F + +-- Launchers (dots-only combos, no conflict) +_F = { description = "[Launcher|Apps] work session (kitty c2)" } +hl.bind(MOD .. " + CTRL + I", hl.dsp.exec_cmd("kitty --session " .. home .. "/.config/kitty/c2.conf"), _F) +_F = { description = "[Launcher|Apps] work session (kitty runners)" } +hl.bind(MOD .. " + CTRL + O", hl.dsp.exec_cmd("kitty --session " .. home .. "/.config/kitty/runners.conf"), _F) +_F = { description = "[Launcher|Apps] pyradio (kitty music)" } +hl.bind(MOD .. " + R", hl.dsp.exec_cmd("kitty --session " .. home .. "/.config/kitty/music.conf"), _F) +_F = { description = "[Launcher|Apps] ferdium" } +hl.bind(MOD .. " + Y", hl.dsp.exec_cmd("ferdium"), _F) +_F = { description = "[Launcher|Apps] betterbird" } +hl.bind(MOD .. " + M", hl.dsp.exec_cmd("betterbird"), _F) +_F = { description = "[Launcher|Apps] freetube" } +hl.bind(MOD .. " + F", hl.dsp.exec_cmd("freetube"), _F) +_F = { description = "[Launcher|Apps] web browser (librewolf)" } +hl.bind(MOD .. " + SHIFT + B", hl.dsp.exec_cmd("librewolf"), _F) +_F = { description = "[Launcher|Apps] terminal emulator (st)" } +hl.bind(MOD .. " + CTRL + T", hl.dsp.exec_cmd("st"), _F) +_F = { description = "[Launcher|Apps] terminal emulator" } +hl.bind("CTRL + ALT + T", hl.dsp.exec_cmd(hc.app.terminal), _F) + +-- Rebound fresh so the hc.app.* overrides actually apply: HyDE's binds +-- evaluated _apps.browser/_apps.explorer when key_binds.lua ran, baking in the +-- hyde-shell open wrappers. +_F = { description = "[Launcher|Apps] web browser" } +hl.bind(MOD .. " + B", hl.dsp.exec_cmd("zen-browser"), _F) +_F = { description = "[Launcher|Apps] file explorer" } +hl.bind(MOD .. " + E", hl.dsp.exec_cmd("dolphin"), _F) + +-- Conflict resolutions (dots action wins; displaced HyDE action noted) +_F = { description = "[Launcher|Apps] web browser (firefox)" } -- displaces HyDE: hide waybar +hl.bind(MOD .. " + CTRL + B", hl.dsp.exec_cmd("firefox"), _F) +_F = { description = "[Launcher|Apps] xmpp (gajim)" } -- displaces HyDE: toggle group (dots keeps it on Super+Shift+G) +hl.bind(MOD .. " + G", hl.dsp.exec_cmd("gajim"), _F) +_F = { description = "[Window Management] toggle group" } -- displaces HyDE: game launcher +hl.bind(MOD .. " + SHIFT + G", hl.dsp.group.toggle(), _F) +_F = { description = "[Launcher|Apps] terminal emulator (alacritty)" } -- displaces HyDE: theme select menu +hl.bind(MOD .. " + SHIFT + T", hl.dsp.exec_cmd("alacritty"), _F) +-- Through `wbar`, never killall: under supervision a killed waybar is back in +-- seconds, and a raw relaunch next to it means two bars. +_F = { description = "[Theming and Wallpaper] reload hyprland + waybar" } -- displaces HyDE: wallbash mode menu +hl.bind(MOD .. " + SHIFT + R", hl.dsp.exec_cmd("hyprctl reload; " .. home .. "/.local/bin/wbar restart"), _F) +_F = { description = "[Launcher|Apps] neovim" } -- displaces HyDE: code editor +hl.bind(MOD .. " + C", hl.dsp.exec_cmd("kitty nvim"), _F) + +-- Super+K keepassxc — HyDE's keyboard-layout switch carries locked=true, so a +-- plain rebind would leave both live (flags are part of a bind's identity). +unbind_all(MOD .. " + K") -- displaces HyDE: keyboard layout switch (locked) +_F = { description = "[Launcher|Apps] password manager" } +hl.bind(MOD .. " + K", hl.dsp.exec_cmd("keepassxc"), _F) + +-- Alt+Tab focus-down — HyDE ships a 4-bind alt-tab switcher (transparent/ +-- release flags); remove the whole cluster, half a switcher is worse than none. +unbind_all("ALT + TAB") -- displaces HyDE: alt-tab switcher (cycle next) +unbind_all("ALT + SHIFT + TAB") +unbind_all("ALT + ALT_L") +unbind_all("ALT + ALT_R") +_F = { description = "[Window Management|Change focus] focus down" } +hl.bind("ALT + TAB", hl.dsp.focus({ direction = "down" }), _F) + +-- Waybar toggle (custom layout; the legacy Ctrl+Alt+W). systemctl stop is a +-- deliberate stop, so Restart=always does not undo it. +_F = { description = "[Window Management] toggle waybar" } +hl.bind("CTRL + ALT + W", hl.dsp.exec_cmd(home .. "/.local/bin/wbar toggle"), _F) + +-- Fullscreen on Alt+Return (Shift+F11 stays HyDE's cycle-fullscreen). +-- Native dispatcher, not exec "hyprctl dispatch fullscreen": in Lua mode that +-- CLI arg is evaluated as hl.dispatch(fullscreen) — a nil global, dead bind. +_F = { description = "[Window Management] toggle fullscreen" } +hl.bind("ALT + RETURN", hl.dsp.window.fullscreen(), _F) + +-- No Super+Delete: HyDE's exit() ends the session on the spot, no confirm, and +-- the combo is one slipped finger from Super+Alt+Delete. Ctrl+Alt+Delete (the +-- logout menu) stays the way out. +unbind_all(MOD .. " + Delete") -- displaces HyDE: exit hyprland session + +-- ── Focus (arrows + hjkl) ──────────────────────────────────────────────────── +-- Super+Ctrl+Up/Down: movefocus — displaces HyDE: nearest-empty (Down), which +-- moves to Super+Ctrl+E below. Super+Ctrl+Left/Right move the window to r±1 +-- (Workspaces below); r±1 nav is on Super+Left/Right and Super+Ctrl+Shift. +for dir, key in pairs({ left = "LEFT", right = "RIGHT", up = "UP", down = "DOWN" }) do + _F = { description = "[Window Management|Change focus] focus " .. dir } + if key == "UP" or key == "DOWN" then + hl.bind(MOD .. " + CTRL + " .. key, hl.dsp.focus({ direction = dir }), _F) + end + hl.bind("ALT + CTRL + " .. key, hl.dsp.focus({ direction = dir }), _F) +end +for dir, key in pairs({ left = "H", right = "L", up = "K", down = "J" }) do + _F = { description = "[Window Management|Change focus] focus " .. dir } + hl.bind("ALT + CTRL + " .. key, hl.dsp.focus({ direction = dir }), _F) +end + +-- Super+Ctrl+H/L carried a deliberate double action in the hyprlang chain: +-- changegroupactive (a no-op outside a group) AND movefocus fired together. +-- Lua dedup would collapse the pair, so one function does both. +-- (Replaces HyDE's plain group-nav binds on the same combos.) Unlike the +-- arrows, they do not move the window to r±1 — that is Super+Ctrl+Alt+H/L. +_F = { description = "[Window Management|Change focus] group prev + focus left" } +hl.bind(MOD .. " + CTRL + H", function() + hl.dispatch(hl.dsp.group.prev()) + hl.dispatch(hl.dsp.focus({ direction = "left" })) +end, _F) +_F = { description = "[Window Management|Change focus] group next + focus right" } +hl.bind(MOD .. " + CTRL + L", function() + hl.dispatch(hl.dsp.group.next()) + hl.dispatch(hl.dsp.focus({ direction = "right" })) +end, _F) +_F = { description = "[Window Management|Change focus] focus up" } +hl.bind(MOD .. " + CTRL + K", hl.dsp.focus({ direction = "up" }), _F) +_F = { description = "[Window Management|Change focus] focus down" } +hl.bind(MOD .. " + CTRL + J", hl.dsp.focus({ direction = "down" }), _F) + +-- ── Resize (add hjkl to HyDE's arrow set) ──────────────────────────────────── +-- HyDE puts a flagless calculator menu on Super+Shift+K; our repeating resize +-- would double-fire next to it (flag mismatch), so drop the calculator. +unbind_all(MOD .. " + SHIFT + K") -- displaces HyDE: calculator menu +for _, m in ipairs({ { "L", 30, 0 }, { "H", -30, 0 }, { "K", 0, -30 }, { "J", 0, 30 } }) do + _F = { description = "[Window Management|Resize Active Window] resize window", repeating = true } + hl.bind(MOD .. " + SHIFT + " .. m[1], hl.dsp.window.resize({ x = m[2], y = m[3], relative = true }), _F) +end + +-- ── Move active window (Super+Alt, float-aware: moveactive / swapwindow) ───── +-- Displaces HyDE: wallpaper next/prev (Alt+Right/Left) and waybar layout +-- next/prev (Alt+Up/Down); wallpaper moves to Super+Alt+Ctrl+Shift below, +-- as in the dots chain. HyDE's binds carry no flags but ours are repeating, +-- so an explicit unbind is needed to keep them from double-firing. +unbind_all(MOD .. " + ALT + RIGHT") +unbind_all(MOD .. " + ALT + LEFT") +unbind_all(MOD .. " + ALT + UP") +unbind_all(MOD .. " + ALT + DOWN") +local function dots_move_window(dir, pix) + local lut = { l = { -1, 0 }, r = { 1, 0 }, u = { 0, -1 }, d = { 0, 1 } } + local m = lut[dir] + return function() + local w = hl.get_active_window() + if w and w.floating then + hl.dispatch(hl.dsp.window.move({ x = m[1] * pix, y = m[2] * pix, relative = true })) + else + local names = { l = "left", r = "right", u = "up", d = "down" } + hl.dispatch(hl.dsp.window.swap({ direction = names[dir] })) + end + end +end +for _, m in ipairs({ + { "LEFT", "l" }, + { "RIGHT", "r" }, + { "UP", "u" }, + { "DOWN", "d" }, + { "H", "l" }, + { "L", "r" }, + { "K", "u" }, + { "J", "d" }, +}) do + _F = { description = "[Window Management|Move active window] move " .. m[2], repeating = true } + hl.bind(MOD .. " + ALT + " .. m[1], dots_move_window(m[2], 30), _F) +end + +-- ── Wallpaper (moved off Super+Alt by the dots chain) ──────────────────────── +_F = { description = "[Theming and Wallpaper] next global wallpaper" } +hl.bind(MOD .. " + ALT + CTRL + SHIFT + RIGHT", hl.dsp.exec_cmd(hyde.sh.wallpaper("--next")), _F) +_F = { description = "[Theming and Wallpaper] previous global wallpaper" } +hl.bind(MOD .. " + ALT + CTRL + SHIFT + LEFT", hl.dsp.exec_cmd(hyde.sh.wallpaper("--prev")), _F) + +-- ── Workspaces ─────────────────────────────────────────────────────────────── +-- r~N = Nth workspace of the FOCUSED monitor — load-bearing on the 3-monitor +-- workspace sets (1-10 / 11-20 / 21-30 pinned per monitor in host.lua). +-- HyDE's own binds pass "r+1"/"empty" strings the same way; r~N is the one +-- thing to verify first in the live session. +for i = 1, 10 do + local key = (i == 10) and 0 or i + _F = { description = "[Workspaces|Navigation] navigate to workspace " .. i .. " (monitor-relative)" } + hl.bind(MOD .. " + " .. key, hl.dsp.focus({ workspace = "r~" .. i }), _F) -- displaces HyDE: absolute workspace N + _F = { description = "[Workspaces|Move window to workspace] move to workspace " .. i .. " (monitor-relative)" } + hl.bind(MOD .. " + CTRL + " .. key, hl.dsp.window.move({ workspace = "r~" .. i }), _F) + _F = { description = "[Workspaces|Move window silently] move to workspace " .. i .. " (monitor-relative)" } + hl.bind(MOD .. " + ALT + " .. key, hl.dsp.window.move({ workspace = "r~" .. i, follow = false }), _F) -- displaces HyDE: absolute silent move +end + +-- Relative workspace nav on Super+Ctrl+Shift (dots), displacing HyDE's +-- move-window-in-workspace family there (repeating flags -> explicit unbind; +-- dots does window movement on Super+Alt instead). +unbind_all(MOD .. " + SHIFT + CTRL + LEFT") +unbind_all(MOD .. " + SHIFT + CTRL + RIGHT") +unbind_all(MOD .. " + SHIFT + CTRL + UP") +unbind_all(MOD .. " + SHIFT + CTRL + DOWN") +_F = { description = "[Workspaces|Navigation|Relative workspace] change active workspace forwards" } +hl.bind(MOD .. " + CTRL + SHIFT + RIGHT", hl.dsp.focus({ workspace = "r+1" }), _F) +hl.bind(MOD .. " + CTRL + SHIFT + L", hl.dsp.focus({ workspace = "r+1" }), _F) +_F = { description = "[Workspaces|Navigation|Relative workspace] change active workspace backwards" } +hl.bind(MOD .. " + CTRL + SHIFT + LEFT", hl.dsp.focus({ workspace = "r-1" }), _F) +hl.bind(MOD .. " + CTRL + SHIFT + H", hl.dsp.focus({ workspace = "r-1" }), _F) + +_F = { description = "[Workspaces|Navigation|Relative workspace] change active workspace forwards" } +hl.bind(MOD .. " + RIGHT", hl.dsp.focus({ workspace = "r+1" }), _F) +_F = { description = "[Workspaces|Navigation|Relative workspace] change active workspace backwards" } +hl.bind(MOD .. " + LEFT", hl.dsp.focus({ workspace = "r-1" }), _F) +_F = { description = "[Workspaces|Move window to workspace|Relative workspace] move focused window to next workspace" } +hl.bind(MOD .. " + CTRL + RIGHT", hl.dsp.window.move({ workspace = "r+1" }), _F) -- displaces HyDE: workspace r+1 +_F = { + description = "[Workspaces|Move window to workspace|Relative workspace] move focused window to previous workspace", +} +hl.bind(MOD .. " + CTRL + LEFT", hl.dsp.window.move({ workspace = "r-1" }), _F) -- displaces HyDE: workspace r-1 + +-- E for "empty" — Super+Ctrl+Down is taken by movefocus above +_F = { description = "[Workspaces|Navigation] navigate to the nearest empty workspace" } +hl.bind(MOD .. " + CTRL + E", hl.dsp.focus({ workspace = "empty" }), _F) + +-- Move window to relative workspace: HyDE ships the arrow pair; add hjkl. +_F = { description = "[Workspaces|Move window to workspace|Relative workspace] move focused window to next workspace" } +hl.bind(MOD .. " + CTRL + ALT + L", hl.dsp.window.move({ workspace = "r+1" }), _F) +_F = { + description = "[Workspaces|Move window to workspace|Relative workspace] move focused window to previous workspace", +} +hl.bind(MOD .. " + CTRL + ALT + H", hl.dsp.window.move({ workspace = "r-1" }), _F) + +-- ── Hardware controls ──────────────────────────────────────────────────────── +-- HyDE binds bare F10/F11/F12 to mute / volume down / volume up (key_binds.lua, +-- locked + repeating -- a plain rebind would leave both live). That is a laptop +-- F-row assumption: the Cantor has no F-row, so F1-F12 only ever arrive from its +-- Vial layer 5 and have to reach applications instead of the mixer. The +-- XF86Audio* binds below them keep the media keys working, so nothing is lost, +-- and Shift+F11 (cycle fullscreen) canonicalizes separately and survives. +unbind_all("F10") -- displaces HyDE: un/mute output +unbind_all("F11") -- displaces HyDE: decrease volume +unbind_all("F12") -- displaces HyDE: increase volume diff --git a/gui/.config/hypr/dots_rules.lua b/gui/.config/hypr/dots_rules.lua new file mode 100644 index 0000000..4e3c957 --- /dev/null +++ b/gui/.config/hypr/dots_rules.lua @@ -0,0 +1,122 @@ +-- gui package — the dots layer + window rules, split out of ./hyprland.lua +-- (required there in their original position). Plain hl.* registrations; +-- nothing here depends on the rest of the layer. + +-- ── Layer rules ────────────────────────────────────────────────────────────── +-- waybar blur ships upstream (layer_rules.lua), but its ignore_alpha uses the +-- boolean form (default threshold), which drops the blur on low-alpha regions +-- — the cavabar background is rgba(0,0,0,0.2) and went flat. The legacy chain +-- set the threshold to 0 (blur everything) on both bars; restore that exactly. +hl.layer_rule({ + name = "dots_cavabar_blur", + match = { namespace = "cavabar" }, + blur = true, + ignore_alpha = 0, +}) +hl.layer_rule({ + name = "dots_waybar_ignore_alpha", + match = { namespace = "waybar" }, + ignore_alpha = 0, +}) + +-- ── Window rules ───────────────────────────────────────────────────────────── +-- Upstream's window_rules.lua consolidates most floats (dialogs, portals, +-- dolphin, nm-*, qt*ct, vlc, pavucontrol, …) and the PiP/modal handling. +-- Ported here: everything the repo's windowrules.conf had that upstream +-- dropped when it went global-opacity — per-app opacity, idle_inhibit, +-- jetbrains popups — plus the floats upstream does not cover. + +-- idle_inhibit while fullscreen (media players, browsers) +hl.window_rule({ + name = "dots_idle_inhibit_media", + match = { class = "^(.*celluloid.*)$|^(.*mpv.*)$|^(.*vlc.*)$|^(.*[Ss]potify.*)$" }, + idle_inhibit = "fullscreen", +}) +hl.window_rule({ + name = "dots_idle_inhibit_browsers", + match = { + class = "^(.*LibreWolf.*)$|^(.*floorp.*)$|^(.*brave-browser.*)$|^(.*firefox.*)$|^(.*chromium.*)$|^(.*zen.*)$|^(.*vivaldi.*)$", + }, + idle_inhibit = "fullscreen", +}) + +-- per-app opacity ("active inactive fullscreen", hyprlang-style value string -- +-- the Lua rule's opacity field is string-typed and takes the whole triple) +hl.window_rule({ + name = "dots_opacity_browsers", + match = { class = "^(firefox)$|^(zen)$|^(brave-browser)$" }, + opacity = "0.90 0.90 1", +}) +hl.window_rule({ + name = "dots_opacity_editors_terms", + match = { + class = "^(code-oss)$|^([Cc]ode)$|^(code-url-handler)$|^(code-insiders-url-handler)$|^(kitty)$|^(org.kde.dolphin)$|^(org.kde.ark)$|^(nwg-look)$|^(qt5ct)$|^(qt6ct)$|^(kvantummanager)$", + }, + opacity = "0.80 0.80 1", +}) +hl.window_rule({ + name = "dots_opacity_applets", + match = { + class = "^(org.pulseaudio.pavucontrol)$|^(blueman-manager)$|^(nm-applet)$|^(nm-connection-editor)$|^(hyprpolkitagent)$|^(org.freedesktop.impl.portal.desktop.gtk)$|^(org.freedesktop.impl.portal.desktop.hyprland)$", + }, + opacity = "0.80 0.70 1", +}) +hl.window_rule({ + name = "dots_opacity_spotify_class", + match = { class = "^([Ss]potify)$" }, + opacity = "0.70 0.70 1", +}) +hl.window_rule({ + name = "dots_opacity_spotify_title", + match = { initial_title = "^(Spotify Free)$|^(Spotify Premium)$" }, + opacity = "0.70 0.70 1", +}) +hl.window_rule({ + name = "dots_opacity_blender", + match = { class = "^(blender)$" }, + opacity = "1.00 1.00 1", +}) +hl.window_rule({ + name = "dots_opacity_gtk_apps", + match = { class = "^(com.github.rafostar.Clapper)$" }, + opacity = "0.90 0.90", +}) +hl.window_rule({ + name = "dots_opacity_misc_apps", + match = { + class = "^(com.github.tchx84.Flatseal)$|^(hu.kramo.Cartridges)$|^(com.obsproject.Studio)$|^(gnome-boxes)$|^(vesktop)$|^(discord)$|^(WebCord)$|^(ArmCord)$|^(app.drey.Warp)$|^(net.davidotek.pupgui2)$|^(yad)$|^(Signal)$|^(io.github.alainm23.planify)$|^(io.gitlab.theevilskeleton.Upscaler)$|^(com.github.unrud.VideoDownloader)$|^(io.gitlab.adhami3310.Impression)$|^(io.missioncenter.MissionCenter)$|^(io.github.flattool.Warehouse)$", + }, + opacity = "0.80 0.80", +}) + +-- floats upstream's consolidated list does not cover +hl.window_rule({ + name = "dots_float_class", + match = { + class = "^(Signal)$|^(com.github.rafostar.Clapper)$|^(app.drey.Warp)$|^(net.davidotek.pupgui2)$|^(yad)$|^(eog)$|^(io.github.alainm23.planify)$|^(io.gitlab.theevilskeleton.Upscaler)$|^(com.github.unrud.VideoDownloader)$|^(io.gitlab.adhami3310.Impression)$|^(io.missioncenter.MissionCenter)$", + }, + float = true, +}) +hl.window_rule({ + name = "dots_float_title", + match = { title = "^(About Mozilla Firefox)$|^(Ghidra: NO ACTIVE PROJECT.*)$" }, + float = true, +}) +hl.window_rule({ + name = "dots_float_kitty_monitors", + match = { class = "^(kitty)$", title = "^(top)$|^(btop)$|^(htop)$" }, + float = true, +}) +hl.window_rule({ + name = "dots_blender_image_editor", + match = { class = "^(blender)$", initial_title = "^(Image Editor)$" }, + float = true, + size = "(monitor_w*0.5) (monitor_h*0.5)", +}) + +-- jetbrains dropdowns/popups flicker workaround +hl.window_rule({ + name = "dots_jetbrains_popups", + match = { class = "^(.*jetbrains.*)$", title = "^(win[0-9]+)$" }, + no_initial_focus = true, +}) diff --git a/gui/.config/hypr/hypridle.conf b/gui/.config/hypr/hypridle.conf new file mode 100644 index 0000000..790dc81 --- /dev/null +++ b/gui/.config/hypr/hypridle.conf @@ -0,0 +1,61 @@ +#!   ░▒▒▒░░░▓▓          ___________ +#! ░░▒▒▒░░░░░▓▓        //___________/ +#! ░░▒▒▒░░░░░▓▓     _   _ _    _ _____ +#! ░░▒▒░░░░░▓▓▓▓▓▓ | | | | |  | |  __/ +#! ░▒▒░░░░▓▓   ▓▓ | |_| | |_/ /| |___ +#!  ░▒▒░░▓▓   ▓▓   \__  |____/ |____/ +#!    ░▒▓▓   ▓▓  //____/ + +# $LOCKSCREEN = hyprlock # preferred LOCKSCREEN e.g swaylock +# Absolute path required: the Lua chain starts hypridle as a systemd user unit +# (hyde-Hyprland-idle.service), and on the SDDM/fish session path the session PATH +# never reaches the user manager (start_up.lua's unconditional `uwsm finalize` runs +# but errors outside a uwsm session, so the import never happens) — a bare +# `lockscreen.sh` is "command not found" there — Super+L, the 240s idle lock and +# before_sleep all silently no-op. The script self-bootstraps its own env +# (hyde-shell init), so the full path alone is sufficient. +$LOCKSCREEN = ~/.local/lib/hyde/lockscreen.sh + +general { + lock_cmd = $LOCKSCREEN + unlock_cmd = #notify-send "unlock!" # same as above, but unlock + before_sleep_cmd = $LOCKSCREEN # command ran before sleep + after_sleep_cmd = # notify-send "Awake!" # command ran after sleep + ignore_dbus_inhibit = 0 +} + +# Dims the display +listener { + timeout = 120 +on-timeout = { brightnessctl -s && brightnessctl s 1% ;} + on-resume = brightnessctl -r +} + +# Lock it first before dpms off so that screen won't show for a moment after wake up. +listener { + timeout = 240 + on-timeout = $LOCKSCREEN +} + +# DPMS off +# Lua-chain form: in Lua mode `hyprctl dispatch` evaluates its argument as Lua, so the hyprlang +# `dpms off` is a syntax error and this listener silently never ran. The table form is the one +# hypridle's own sample uses (/usr/share/hypr/hypridle.conf); a bare bool/string argument acts +# like a toggle — `hl.dsp.dpms("on")` turned the display OFF. main (hyprlang) keeps `dpms off/on`. +listener { + timeout = 2300 + on-timeout = hyprctl dispatch 'hl.dsp.dpms({action = "off"})' #do not turn off display while media is playing + on-resume = hyprctl dispatch 'hl.dsp.dpms({action = "on"})' +} + +# Suspend +# listener { +# timeout = 500 +# on-timeout = systemctl suspend +# } + +# hyprlang noerror true +# Source anything from this path if you want to add your own listener +# source command actually do not exist yet +source = ~/.config/hypridle/* +# hyprlang noerror false diff --git a/gui/.config/hypr/hyprland.lua b/gui/.config/hypr/hyprland.lua new file mode 100644 index 0000000..e158712 --- /dev/null +++ b/gui/.config/hypr/hyprland.lua @@ -0,0 +1,128 @@ +-- gui package — the dots Hyprland layer, ported from the hyprlang chain +-- (hyde.conf / userprefs.conf / keybindings.conf / windowrules.conf) to +-- HyDE 26.x's Lua config. Loaded by ~/.local/share/hypr/hyde.lua second-to-last +-- (after every HyDE module, before lua_state.workflows), so plain assignments +-- here override HyDE's defaults. HyDE never overwrites this file. +-- +-- The rules and keybinds sections live in ./dots_rules.lua and +-- ./dots_binds.lua, required in place below. Host-specific config (monitors, +-- workspace pins, gaps/rounding, gpu extras) lives in ./host.lua, loaded at +-- the bottom — same layering the hyprlang chain had with +-- `source = ./host.conf`. + +-- Bootstrap: Hyprland prefers hyprland.lua as the entry point when started +-- without a config; without this block that path yields a bare cursor. hyde.lua +-- sets `hyde` on its first line, so this runs only when HyDE has not loaded. +-- The `return` matters: dofile(hyde.lua) re-enters this file through +-- check_require("hyprland"), so by the time dofile returns the body below has +-- already run once — falling through would register everything twice. +if not hyde then + local share = os.getenv("XDG_DATA_HOME") or (os.getenv("HOME") .. "/.local/share") + local entry = share .. "/hypr/hyde.lua" + local handle = io.open(entry, "r") + if not handle then + error( + "HyDE is not installed at " .. entry .. ". Run HyDE's install.sh -r, or point Hyprland at your own config." + ) + end + handle:close() + dofile(entry) + return +end + +local hc = hyde.config +local home = os.getenv("HOME") or "" + +-- ── Apps ───────────────────────────────────────────────────────────────────── +-- Named directly (not hyde-shell open --fall …) for the same reason hyde.conf +-- did: skip the wrapper, match the xdg defaults. The assignments cover lazy +-- readers of hc.app.*, but key_binds.lua already baked the defaults into its +-- Super+B/E dispatchers at bind time — hence the explicit rebinds in +-- dots_binds.lua. +hc.app.browser = "zen-browser" +hc.app.explorer = "dolphin" + +-- ── Startup ────────────────────────────────────────────────────────────────── +-- One knob suppresses HyDE's plain waybar AND launches the cava rig (was +-- $start.BAR= + a userprefs exec-once). start_up.lua captures hc.start by +-- reference and the hyprland.start event fires after this file loads, so the +-- override lands in time. `wbar` (gui/.local/bin) runs the rig as the +-- dots-waybar.service transient unit with Restart=always: waybar 0.15.0 dies on +-- every DP-2 link drop/return, and as a plain scope nothing relaunched it. +-- Absolute path: the exec env's PATH is not guaranteed to hold ~/.local/bin. +hc.start.bar = home .. "/.local/bin/wbar start" +-- Not part of the legacy session — the Lua defaults would newly launch these +-- (both binaries are installed). hyprsunset would visibly tint the screen. +-- Delete a line to adopt the HyDE default. +hc.start.blue_light_filter_daemon = "" +hc.start.clipboard_persist = "" +-- nm-applet --indicator is already the Lua default (kept deliberately: the +-- tray icon is the one place with a quick connect/disconnect menu). + +-- ── UI / icon theme ────────────────────────────────────────────────────────── +-- dots-icons = repo-tracked overlay theme (gui/.local/share/icons/dots-icons) +-- that inherits Tela-circle-dracula and swaps the tray/status icons for the +-- monochrome panel set — without it, waybar on a fractionally-scaled monitor +-- gets the colored-circle variants (the blue nm-applet blob). +hc.ui.icon_theme = "dots-icons" +-- The theme-switch pipeline regenerates lua_state/ui.lua from the theme's +-- hypr.theme and writes THAT to dconf (color/hypr.sh -> color/dconf.lua), so +-- the assignment above is not enough on its own. Top-level code re-runs on +-- every `hyprctl reload`, and both theme-switch paths end in a reload, so this +-- write lands last — the Lua-mode equivalent of the legacy $exec.dConf. +-- Upstream-sanctioned alternative if this ever races: add +-- [hyprland]\n icon_theme = "dots-icons" +-- to ~/.config/hyde/config.toml (state/hyde/hyprland.conf then overrides the +-- theme vars in theme.switch.sh:151). +hl.exec_cmd([[dconf write /org/gnome/desktop/interface/icon-theme "'dots-icons'"]]) + +-- ── Env (was userprefs.conf) ───────────────────────────────────────────────── +hl.env("SSH_AUTH_SOCK", (os.getenv("XDG_RUNTIME_DIR") or "") .. "/ssh-agent.socket") +hl.env("ELECTRON_OZONE_PLATFORM_HINT", "x11") -- disable after hyprland fixes electron flickering + +-- ── Layer + window rules (dots_rules.lua) ──────────────────────────────────── +-- Plain require, not check_require: stow --no-folding links new files one by +-- one, so a host that pulled without re-running install.sh fails loudly in +-- `hyprctl configerrors` instead of booting silently without its rules/binds. +-- The dots_ prefix matters: hyde.lua searches HyDE's own lua/ before +-- ~/.config/hypr, so a bare window_rules / key_binds would load HyDE's module. +require("dots_rules") + +-- ── Animations ─────────────────────────────────────────────────────────────── +-- The legacy chain ran $ANIMATION=theme — the hyprdots set from the theme's +-- animations.dcol. The Lua chain cannot inherit it: hyq's hyprland-lua.json +-- schema dumps decoration/borders into lua_state/hypr_theme.lua but NOT the +-- animations block (LUA-PORT.md risk 6, confirmed live), so without this the +-- session falls back to Hyprland's slower built-in defaults. Ported verbatim +-- from the generated ~/.config/hypr/animations/theme.conf. +-- Conditional so `hyde-shell animations --select` still works: a selector- +-- chosen lua_state/animations.lua loads earlier (dynamic.lua) and this block +-- steps aside for it. +local anim_state = (os.getenv("XDG_STATE_HOME") or home .. "/.local/state") .. "/hyde/lua_state/animations.lua" +local anim_f = io.open(anim_state, "r") +if anim_f then + anim_f:close() +else + hl.curve("wind", { type = "bezier", points = { { 0.05, 0.9 }, { 0.1, 1.05 } } }) + hl.curve("winIn", { type = "bezier", points = { { 0.1, 1.1 }, { 0.1, 1.1 } } }) + hl.curve("winOut", { type = "bezier", points = { { 0.3, -0.3 }, { 0, 1 } } }) + hl.curve("liner", { type = "bezier", points = { { 1, 1 }, { 1, 1 } } }) + hl.animation({ leaf = "windows", enabled = true, speed = 6, bezier = "wind", style = "slide" }) + hl.animation({ leaf = "windowsIn", enabled = true, speed = 6, bezier = "winIn", style = "slide" }) + hl.animation({ leaf = "windowsOut", enabled = true, speed = 5, bezier = "winOut", style = "slide" }) + hl.animation({ leaf = "windowsMove", enabled = true, speed = 5, bezier = "wind", style = "slide" }) + hl.animation({ leaf = "border", enabled = true, speed = 1, bezier = "liner" }) + hl.animation({ leaf = "borderangle", enabled = true, speed = 30, bezier = "liner", style = "once" }) + hl.animation({ leaf = "fade", enabled = true, speed = 10, bezier = "default" }) + hl.animation({ leaf = "workspaces", enabled = true, speed = 5, bezier = "wind" }) +end + +-- ── Keybinds (dots_binds.lua) ──────────────────────────────────────────────── +-- After the hc.app.* overrides above: the launcher binds read them. +require("dots_binds") + +-- ── Host layer ─────────────────────────────────────────────────────────────── +-- Resolves via hyde.lua's package.path (~/.config/hypr/?.lua); each host +-- overlay stows its own host.lua (wm/, lw/). check_require is HyDE's +-- missing-tolerant require — a host without one just skips it. +check_require("host") diff --git a/gui/.config/hypr/hyprlock-host.conf b/gui/.config/hypr/hyprlock-host.conf new file mode 100644 index 0000000..8d6f522 --- /dev/null +++ b/gui/.config/hypr/hyprlock-host.conf @@ -0,0 +1,9 @@ +# Default (empty) per-host hyprlock sizes — fallback shared by all GUI hosts. +# The real one comes from the per-host overlay (see lw/.config/hypr/hyprlock-host.conf). +# Present so `source = ~/.config/hypr/hyprlock-host.conf` in hyprlock.conf always resolves, +# even mid-install before the host overlay is stowed. A missing `source` target is a hard +# parse error in hyprlang — for hyprlock that means the lock screen itself fails, so this +# file must never be deleted. +# +# gui's defaults are tuned for wm (3072x1728 logical). To override, redefine any of: +# $fsClock $fsDate $fsMeta $fsSmall $fsIcon $logoSize diff --git a/gui/.config/hypr/hyprlock.conf b/gui/.config/hypr/hyprlock.conf new file mode 100644 index 0000000..e9c6832 --- /dev/null +++ b/gui/.config/hypr/hyprlock.conf @@ -0,0 +1,195 @@ +#! █░█ █▄█ █▀█ █▀█ █░░ █▀█ █▀▀ █▄▀ +#! █▀█ ░█░ █▀▀ █▀▄ █▄▄ █▄█ █▄▄ █░█ + +#* Hyprlock Configuration File + +# Everything is anchored to the CENTRE (only the two bottom-corner labels use valign), in this +# order top to bottom: uptime, greeting, logo, input field, clock, date. The offsets spread the +# content out to the top and bottom edges. Centre-anchoring is deliberate: an earlier pass used +# TOP/BOTTOM valign bands and silently reordered the clock and date, putting the date above the +# clock and the clock half off the bottom edge — don't reintroduce that. +# Every `position` and `size` is a percentage (hyprlock accepts them: both are LAYOUTCONFIG +# values), so the arrangement scales instead of being the fixed pixel offsets it once was. +# The percentages are the old pixel offsets expressed against a 1080-tall screen. +# +# `font_size` and `image:size` are plain ints in hyprlock 0.9.6 and cannot take a +# percentage, so they can't scale on their own. They're hoisted into the variables below: +# retune those few numbers for a very different screen (they are tuned for wm, 3072x1728 logical), +# or `source` a per-host file that redefines them, as kitty.conf does with host.conf. +# +# Coordinates: +x is right, +y is UP — so centre-anchored, a positive y sits above centre. +# (For the two bottom-corner labels, valign = bottom means positive y moves up from it.) + +$fontColor = rgba(255,255,255,0.5) +$fontFamily = SourceCodeVF ExtraBold +$timeFontFamily = Cantarell ExtraBold + +# Type scale — tuned for wm's 3072x1728 logical screen (this file is shared with lw — +# see ToDo.md). Since these can't be +# percentages, they are the one thing to retune on a very different display: they are +# roughly clock 13%, date 2.5%, meta 1.5% of screen height. +$fsClock = 220 +$fsDate = 44 +$fsMeta = 26 +$fsSmall = 24 +$fsIcon = 40 +$logoSize = 280 + +# Vertical positions — % of screen height from centre, + is up. Order top to bottom: uptime, +# greet, logo, input, clock, date. Deliberately pushed OUT to the edges: uptime/greet ride near +# the top, clock/date near the bottom, leaving logo + input as the only things near the middle. +# Anchored to centre rather than valign top/bottom on purpose — an earlier pass used bands and +# silently reordered the clock and date (see the header). Percentages scale, and because each +# host's font sizes are set to the same *proportion* of its screen (clock ~12.8% of height on +# both), one set of offsets gives both hosts the same layout — hence no per-host override here +# by default. Add $y* to hyprlock-host.conf if a host ever needs to differ. +$yUptime = 45% +$yGreet = 41% +$yLogo = 12% +$yInput = -5% +$yClock = -30% +$yDate = -42% + +# Per-host override for the six sizes above. They are ints, not percentages, so they are the +# one thing that cannot scale itself — a host with a different panel redefines whichever it +# needs here, and everything below picks up the new value (hyprlang expands in file order). +# Shipped empty in gui/ so this always resolves even mid-install, before a host overlay is +# stowed — same idiom, and same reason, as hypr/host.conf. +source = ~/.config/hypr/hyprlock-host.conf + +general { + ignore_empty_input = true + text_trim = true +} +# Dropped as of hyprlock 0.9.6 — it rejected all four as "config option does not exist" +# and carried on without them, so they never took effect: +# no_fade_in / fade_in_time -> fade-in is CLI-only now: lockscreen.sh --no-fade-in +# grade, disable_loading_bar -> no equivalent + +background { + monitor = + path = ~/.config/hypr/hyprlock/assets/background.jpg + # Heavier blur than you'd expect: the wallpaper has "open source" set across its + # middle, which otherwise reads as text competing with the clock sitting on top of it. + blur_passes = 3 + blur_size = 6 + contrast = 0.7 + brightness = 0.38 + vibrancy = 0.15 + vibrancy_darkness = 0.5 +} + + +# // ▀█▀ █▀█ █▀█ +# // ░█░ █▄█ █▀▀ + +# uptime +label { + monitor = + text = cmd[update:5000] echo "$(uptime -p)" + color = $fontColor + font_family = $fontFamily + font_size = $fsMeta + position = 0, $yUptime + halign = center + valign = center +} + +# greeting / weather +label { + monitor = + text = cmd[update:300000] echo "$(cat ~/.config/fish/greet.txt)" + color = $fontColor + font_family = $fontFamily + font_size = $fsSmall + position = 0, $yGreet + halign = center + valign = center +} + + +# // █▀▄▀█ █ █▀▄ █▀▄ █░░ █▀▀ +# // █░▀░█ █ █▄▀ █▄▀ █▄▄ ██▄ + +image { + monitor = + path = ~/.config/hypr/hyprlock/assets/logo.jpg + size = $logoSize + position = 0, $yLogo + halign = center + valign = center + reload_time = -1 + reload_cmd = +} + +input-field { + monitor = + size = 20%, 5% + position = 0, $yInput + halign = center + valign = center + outline_thickness = 3 + dots_size = 0.08 + dots_spacing = 0.2 + dots_center = true + outer_color = rgba(0,0,0,0.1) + inner_color = $fontColor + fade_on_empty = true +} + + +# // █▄▄ █▀█ ▀█▀ ▀█▀ █▀█ █▀▄▀█ +# // █▄█ █▄█ ░█░ ░█░ █▄█ █░▀░█ + +# date — sits BELOW the clock (-28% vs the clock's -17%), as it did before the band rewrite. +label { + monitor = + text = cmd[update:1000] echo "$(LC_TIME=en_US.UTF-8 date +'%A, %B %d')" + color = $fontColor + font_family = $fontFamily + font_size = $fsDate + position = 0, $yDate + halign = center + valign = center +} + +# clock — 17% below centre, directly under the input field, with the date below it. Centre- +# anchored, so y is the box's CENTRE and the glyphs grow both ways from it; budget for that +# when changing $fsClock, which is by far the tallest text here. +label { + monitor = + text = cmd[update:1000] echo "$(date +"%H:%M")" + color = $fontColor + font_family = $timeFontFamily + font_size = $fsClock + position = 0, $yClock + halign = center + valign = center + shadow_passes = 1 + shadow_size = 1 + shadow_color = rgba(0, 0, 0, 0.5) +} + +# power +label { + monitor = + text = cmd[] echo "⏻ " + color = $fontColor + font_size = $fsIcon + onclick = systemctl poweroff + position = 3%, 3% + halign = left + valign = bottom +} + +# battery (prints nothing on a desktop) +label { + monitor = + text = cmd[update:1000] echo -e "$(~/.config/hypr/battery.sh)" + color = $fontColor + font_family = $fontFamily + font_size = $fsSmall + position = -3%, 3% + halign = right + valign = bottom +} diff --git a/gui/.config/hypr/hyprlock/assets/background.jpg b/gui/.config/hypr/hyprlock/assets/background.jpg new file mode 100644 index 0000000..fdcb473 Binary files /dev/null and b/gui/.config/hypr/hyprlock/assets/background.jpg differ diff --git a/gui/.config/hypr/hyprlock/assets/logo.jpg b/gui/.config/hypr/hyprlock/assets/logo.jpg new file mode 100644 index 0000000..788b72a Binary files /dev/null and b/gui/.config/hypr/hyprlock/assets/logo.jpg differ diff --git a/gui/.config/kitty/host.conf b/gui/.config/kitty/host.conf new file mode 100644 index 0000000..88f4454 --- /dev/null +++ b/gui/.config/kitty/host.conf @@ -0,0 +1,2 @@ +# Per-host kitty overrides. Empty by default — a host overlay (e.g. lw/) replaces this file +# to tweak font_size/padding/opacity for that machine. kitty.conf includes it LAST. diff --git a/gui/.config/kitty/kitty.conf b/gui/.config/kitty/kitty.conf new file mode 100644 index 0000000..6008420 --- /dev/null +++ b/gui/.config/kitty/kitty.conf @@ -0,0 +1,40 @@ +# Colours: HyDE owns both includes; the repo tracks only its own colour changes below. +# - theme.conf: HyDE renders the current theme's kitty.theme here on every theme switch +# (color.set.sh, by mv, so it's always a real file and never a link into this repo). +# Untracked since 2026-11-09; a missing one is silently ignored, so kitty would fall back +# to its default palette (bin/hyde-materialize.sh recovers it on a host after the pull). +# - hyde.conf: what HyDE's wallbash kitty.sh puts at the top. Absent on most hosts; harmless. +include hyde.conf +include theme.conf + +# The repo's own colours. They come after the include, so they win (later definitions +# override) over EVERY HyDE theme, wallbash included, not just Catppuccin Mocha. +background #262335 +foreground #ffffff +# HyDE's Mocha sets #11111B; none = the tab bar uses the background above +tab_bar_background none + +font_size 12.0 +font_family CaskaydiaCove Nerd Font Mono +bold_font auto +italic_font auto +bold_italic_font auto +window_padding_width 25 +enable_audio_bell no +cursor_trail 1 +cursor_blink_interval 0.4 ease-in-out + +tab_bar_style powerline +tab_powerline_style slanted + +confirm_os_window_close 0 +# Remembering size also remembers the maximize state (~/.cache/kitty/main.json): +# close one maximized kitty and every new one opens maximized under Hyprland. +remember_window_size no +initial_window_width 100c +initial_window_height 30c +#background_opacity 0.60 +#hide_window_decorations yes + +# Per-host overrides (font_size, padding, opacity…) — included last so it wins. +include host.conf diff --git a/gui/.config/kitty/music.conf b/gui/.config/kitty/music.conf new file mode 100644 index 0000000..e4b71ec --- /dev/null +++ b/gui/.config/kitty/music.conf @@ -0,0 +1,20 @@ +# run with `kitty --session ~/.config/kitty/music.conf` + +# os_window_size 220c 64c +# create a new tab +new_tab music +layout splits + +# set the working directory for windows in the current tab +cd ~ + +# Splits are sized with --bias (a percentage of the space being split) rather +# than `resize_window taller/wider N`: that takes N *cells*, so on a small window +# N swamps the available space and the other pane collapses to nothing -- cava +# was disappearing. --bias keeps the same proportions at any window size. +# Tune: --bias here is the share the *new* pane takes; cava gets the remainder. +launch --var window=first cava +# create additional terminals +launch --location=hsplit --bias 80 pyradio +focus +launch --location=vsplit --bias 65 pipes-rs diff --git a/gui/.config/mpv/input.conf b/gui/.config/mpv/input.conf new file mode 100644 index 0000000..1c0abe1 --- /dev/null +++ b/gui/.config/mpv/input.conf @@ -0,0 +1,65 @@ +# Volume +9 add volume -5 +0 add volume 5 + +UP add volume 2 +DOWN add volume -2 + +k add volume 2 +j add volume -2 + +# Seek backward / forward +LEFT seek -5 +RIGHT seek 5 + +l seek 5 +h seek -5 + +# Bigger jumps +Shift+LEFT seek -30 +Shift+RIGHT seek 30 + +# Precise nudge (Shift+h/l): 1s exact seek +H seek -1 exact +L seek 1 exact + +# Playback speed += add speed 0.1 +- add speed -0.1 +BS set speed 1.0 # backspace resets to normal + +# Subtitle sync +z add sub-delay -0.1 # subs earlier +Z add sub-delay 0.1 # subs later + +# Chapters +> add chapter 1 +< add chapter -1 + +# A-B loop (moved off L to avoid the precise-nudge conflict) +b ab-loop + +# Audio sync (mirrors the z/Z subtitle-delay pair) +x add audio-delay -0.1 # audio earlier +X add audio-delay 0.1 # audio later + +# Playlist nav (< / > are used for chapters) +[ playlist-prev +] playlist-next + +# Track cycling +a cycle audio # next audio track +n cycle sub # next subtitle track +v cycle sub-visibility # (default) toggle subs on/off + +# Loop current file (distinct from the b A-B loop) +r cycle-values loop-file inf no + +# Screenshots +s screenshot # (default) with subs +S screenshot video # clean frame: no subs/OSD + +# Info overlays +i script-binding stats/display-stats-toggle # (default) stats HUD +o show-progress # flash progress/OSD + diff --git a/gui/.config/mpv/mpv.conf b/gui/.config/mpv/mpv.conf new file mode 100644 index 0000000..3f29d68 --- /dev/null +++ b/gui/.config/mpv/mpv.conf @@ -0,0 +1,5 @@ +[pyradio] +volume=50 + + + diff --git a/gui/.config/uwsm/env-hyprland.d/10-dots.sh b/gui/.config/uwsm/env-hyprland.d/10-dots.sh new file mode 100644 index 0000000..b5d7b79 --- /dev/null +++ b/gui/.config/uwsm/env-hyprland.d/10-dots.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env sh + +# Pin Hyprland to HyDE's Lua entry point, explicitly. +# +# HyDE's own `00-hyde.sh` (synced on every update) assigns HYPRLAND_CONFIG with +# `${HYPRLAND_CONFIG:-...}` after sourcing shell/activate; env-hyprland sources +# `env-hyprland.d/*.sh` in glob order, so this file (10 sorts after 00) wins by +# assigning unconditionally. Keeping the pin alive — rather than deleting this +# file and trusting HyDE's default — preserves the invariant that the dots repo +# decides which config Hyprland starts with, and makes any rollback a one-line +# edit here. Session-start only: relogin, not `hyprctl reload`. +# +# The Lua chain: hyde.lua loads HyDE's lua/ modules, then the user override +# ~/.config/hypr/hyprland.lua (repo: gui/.config/hypr/hyprland.lua, which pulls +# in the per-host host.lua). None of the old hyprlang .conf files are read in +# Lua mode. See LUA-PORT.md for the full map, flip-day steps and rollback. +# +# ROLLBACK to hyprlang (the chain was retired at LUA-PORT.md step 8, +# 2026-09-10): restore gui/.config/hypr, wm/.config/hypr, lw/.config/hypr and +# gui/.local/share/hyde from bddbbf3 (the last pre-step-8 commit), ./install.sh, point this and +# the fish twin (gui/.config/fish/conf.d/00-hypr-config.fish) back at +# "$HOME/.config/hypr/hyprland.conf" and relogin. d851213 is the last +# hyprlang `main` (the port merged 2026-11-09). +HYPRLAND_CONFIG="${XDG_DATA_HOME:-$HOME/.local/share}/hypr/hyde.lua" +export HYPRLAND_CONFIG diff --git a/gui/.config/waybar/cava-waybar.sh b/gui/.config/waybar/cava-waybar.sh new file mode 100755 index 0000000..96eba15 --- /dev/null +++ b/gui/.config/waybar/cava-waybar.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Self-contained waybar cava module: stream `cava` raw output as Unicode bar chars. +# No HyDE dependency — just needs `cava` installed. Usage: cava-waybar.sh [bars] +# bars = number of columns (even; ~screen_px / (font-size * 0.6)); default 94. +# +# waybar's custom/cava module uses restart-interval, so this script is relaunched +# every time it exits. Without cleanup each relaunch would leak an orphaned `cava` +# child and they'd pile up. We enforce a single instance: track cava's own PID, +# kill it on exit, and reap any stale instance left by a previous (crashed) run. +bars="${1:-94}" +chars="▁▂▃▄▅▆▇█" # cava ascii value 0..7 -> these + +conf="$(mktemp)" +pidfile="${XDG_RUNTIME_DIR:-/tmp}/cava-waybar.pid" + +cava_pid="" +cleanup() { + [[ -n "$cava_pid" ]] && kill "$cava_pid" 2>/dev/null + rm -f "$conf" "$pidfile" +} +trap cleanup EXIT INT TERM + +# Reap a stale cava from a previous run that didn't clean up (e.g. hard kill). +if [[ -f "$pidfile" ]]; then + old="$(cat "$pidfile" 2>/dev/null)" + [[ "$old" =~ ^[0-9]+$ ]] && kill "$old" 2>/dev/null +fi + +cat >"$conf" < >(sed -u "$prog") & +cava_pid=$! +echo "$cava_pid" >"$pidfile" +wait "$cava_pid" diff --git a/gui/.config/waybar/cava.width b/gui/.config/waybar/cava.width new file mode 100644 index 0000000..6529ff8 --- /dev/null +++ b/gui/.config/waybar/cava.width @@ -0,0 +1 @@ +98 diff --git a/gui/.config/waybar/layouts/custom.css b/gui/.config/waybar/layouts/custom.css new file mode 100644 index 0000000..f589e65 --- /dev/null +++ b/gui/.config/waybar/layouts/custom.css @@ -0,0 +1,212 @@ +* { + border: none; + border-radius: 0px; + font-family: "JetBrainsMono Nerd Font"; + font-weight: bold; + font-size: 10px; + min-height: 10px; +} + +@import "../theme.css"; +/* HyDE/wallbash-generated colors, one level up. FATAL if missing — + waybar exits before drawing anything. install.sh seeds it from ../theme-fallback.css on + hosts where wallbash never wrote one. */ + +window#waybar { + /* transparent so the cavabar (bottom layer, same region) shows through; module pills keep @main-bg */ + background: transparent; +} + +tooltip { + background: @main-bg; + color: @main-fg; + border-radius: 5px; + border-width: 0px; +} + +#workspaces { + border-radius: 8px; +} + +#custom-padd { + padding-left: 5px; + padding-right: 5px; +} + +#workspaces button { + box-shadow: none; + text-shadow: none; + padding: 0px; + border-radius: 5px; + margin-top: 3px; + margin-bottom: 3px; + margin-left: 0px; + padding-left: 3px; + padding-right: 3px; + margin-right: 0px; + color: @main-fg; + animation: ws_normal 20s ease-in-out 1; +} + +#workspaces button.active { + background: @wb-act-bg; + color: @wb-act-fg; + animation: ws_active 20s ease-in-out 1; + transition: all 0.4s cubic-bezier(0.55, -0.68, 0.48, 1.682); +} + +#workspaces button:hover { + background: @wb-hvr-bg; + color: @wb-hvr-fg; + animation: ws_hover 20s ease-in-out 1; + transition: all 0.3s cubic-bezier(0.55, -0.68, 0.48, 1.682); +} + +#taskbar button { + box-shadow: none; + text-shadow: none; + padding: 0px; + border-radius: 6px; + margin-top: 3px; + margin-bottom: 3px; + margin-left: 0px; + padding-left: 3px; + padding-right: 3px; + margin-right: 0px; + color: @main-fg; + animation: tb_normal 20s ease-in-out 1; +} + +#taskbar button.active { + background: @wb-act-bg; + color: @wb-act-fg; + /*animation: tb_active 20s ease-in-out 1;*/ + box-shadow: 0 0 1px 1px rgba(128, 128, 128, 0.4); + transition: all 0.4s cubic-bezier(0.55, -0.68, 0.48, 1.682); +} + +#taskbar button:hover { + background: @wb-hvr-bg; + color: @wb-hvr-fg; + opacity: 0.8; + animation: tb_hover 20s ease-in-out 1; + transition: all 0.3s cubic-bezier(0.55, -0.68, 0.48, 1.682); +} + +#tray menu * { + min-height: 16px; +} + +#tray menu separator { + min-height: 10px; +} + +#backlight, +#battery, +#bluetooth, +#custom-cava, +#custom-cliphist, +#clock, +#custom-cpuinfo, +#cpu, +#custom-gpuinfo, +#idle_inhibitor, +#custom-keybindhint, +#language, +#memory, +#mpris, +#network, +#custom-notifications, +#custom-power, +#pulseaudio, +#custom-spotify, +#taskbar, +#custom-theme, +#tray, +#custom-updates, +#custom-wallchange, +#custom-wbar, +#window, +#workspaces, +#custom-l_end, +#custom-r_end, +#custom-sl_end, +#custom-sr_end, +#custom-rl_end, +#custom-rr_end { + color: @main-fg; + /* background: @main-bg; */ + + background: transparent; + opacity: 1; + margin: 4px 0px 4px 0px; + padding-left: 4px; + padding-right: 4px; +} + +window#waybar.empty #window, +window#waybar.empty #custom-sl_end, +window#waybar.empty #custom-sr_end { + opacity: 0; +} + +#workspaces { + padding-left: 5px; + padding-right: 5px; +} + +#taskbar { + border-radius: 8px; + padding-left: 6px; + padding-right: 6px; +} + +#custom-r_end { + border-radius: 0px 8px 8px 0px; + margin-right: 3px; + padding-right: 1px; +} + +#custom-l_end { + border-radius: 8px 0px 0px 8px; + margin-left: 3px; + padding-left: 1px; +} + +#custom-sr_end { + border-top-right-radius: 6px; + border-bottom-right-radius: 6px; + margin-right: 9px; + padding-right: 3px; +} + +#custom-sl_end { + border-top-left-radius: 6px; + border-bottom-left-radius: 6px; + margin-left: 9px; + padding-left: 3px; +} + +#custom-rr_end { + border-radius: 0px 8px 8px 0px; + margin-right: 9px; + padding-right: 3px; +} + +#custom-rl_end { + border-radius: 8px 0px 0px 8px; + margin-left: 9px; + padding-left: 3px; +} + +window#waybar.cavabar { + /* background: transparent; */ + background: alpha(@main-bg, 0.1); +} + +window#waybar.cavabar #custom-cava { + font-size: 24px; + color: alpha(@main-fg, 0.5); + margin: 0px; + padding: 0px; +} diff --git a/gui/.config/waybar/layouts/custom.jsonc b/gui/.config/waybar/layouts/custom.jsonc new file mode 100644 index 0000000..66f2678 --- /dev/null +++ b/gui/.config/waybar/layouts/custom.jsonc @@ -0,0 +1,393 @@ +// --// standalone two-bar cava rig — hand-maintained, NOT HyDE-generated (see README "Waybar") //-- // + +[ +{ +// sourced from header module // + + "layer": "top", + "position": "top", + "height": 33, + "exclusive": true, + "passthrough": false, + "gtk-layer-shell": true, + "reload_style_on_change": true, + + +// positions generated based on config.ctl // + + "modules-left": ["custom/l_end","custom/power","custom/r_end","hyprland/workspaces", "custom/sl_end","hyprland/window","custom/sr_end","custom/l_end","custom/wallchange","custom/cliphist","custom/r_end"], + "modules-center": ["wlr/taskbar"], + "modules-right": ["custom/l_end","backlight","pulseaudio","pulseaudio#microphone","mpris","custom/r_end","custom/l_end","memory","cpu","custom/cpuinfo","battery","custom/r_end","custom/l_end","network","tray","custom/r_end","custom/l_end","idle_inhibitor","clock","custom/r_end"], + +// sourced from modules based on config.ctl // + + "tray": { + // exactly 22: Tela only has fixed-size monochrome icons in {16,22,24}/panel — any + // other size makes GTK fall through to scalable/devices, whose icons are colored + // circles (the blue nm-applet blob). An exact panel match keeps the tray flat/white. + "icon-size": 22, + "rotate": 0, + "spacing": 5 + }, + + // NOTE: keep in sync with modules/window.jsonc — this layout is launched standalone + // (waybar -c), so the modules/ file is NOT read here; this inline copy is what renders. + "hyprland/window": { + "format": " {}", + "rotate": 0, + "separate-outputs": true, + "max-length": 1000, + "rewrite": { + "(.*) — Kitty": " $1", + "(.*)~": " $1", + "(.*) — Mozilla Firefox": "󰈹 $1", + "(.*)Mozilla Firefox": "󰈹 Firefox", + "(.*) — LibreWolf": "󰈹 $1", + "(.*)LibreWolf": "󰈹 LibreWolf", + "(.*) — Chromium": " $1", + "(.*)Chromium": " Chromium", + "(.*) - VSCodium": "󰨞 $1", + "(.*)VSCodium": "󰨞 VSCodium", + "(.*)Code - OSS": "󰨞 $1", + "(.*) - Visual Studio Code": "󰨞 $1", + "(.*)Visual Studio Code": "󰨞 Code", + "(.*) — Dolphin": "󰉋 $1", + "(.*) - Obsidian(.*)": "󰠮 $1", + "(.*)Ferdium": "󰭻 Ferdium", + "(.*)FreeTube": " FreeTube", + "(.*) - VLC media player": "󰕼 $1", + "(.*)Neovide": " Nvim", + "(.*)Neovim": " Nvim", + "(.*)Nvim": " Nvim", + "(.*)Gajim": "󰭹 Gajim", + "(.*)KeePassXC": " KeePassXC", + "(.*)Betterbird": "󰇮 Betterbird", + // --- apps in use on this rig (glyphs verified against JetBrainsMono NF v3) --- + "nvim (.*)": " $1", + "nvim": " Nvim", + "(.*)PyRadio - Playing: (.*)": "󰐹 $2", + "(.*)PyRadio(.*)": "󰐹 PyRadio", + "(.*) - mpv": "󰿎 $1", + "(.*)mpv": "󰿎 mpv", + "(.*) — Zen Browser": "󰖟 $1", + "(.*)Zen Browser(.*)": "󰖟 Zen", + "(.*) - Thorium": " $1", + "(.*)Thorium(.*)": " Thorium", + "(.*)Ghostty(.*)": "󰊠 Ghostty", + "(.*)zellij(.*)": "󰆍 zellij", + "(.*)btop(.*)": "󰨇 btop", + "(.*)lazydocker(.*)": "󰡨 lazydocker", + "(.*)Dolphin(.*)": "󰉋 Dolphin", + "(.*)qBittorrent(.*)": "󰇚 qBittorrent", + "(.*)GIMP(.*)": "󱇣 GIMP", + "(.*)LibreOffice(.*)": "󰈙 LibreOffice", + "(.*)KiCad(.*)": "󰘚 KiCad", + "(.*)QGroundControl(.*)": "󰐴 QGroundControl", + "(.*)Foxglove(.*)": "󰚩 Foxglove", + "(.*)Bruno(.*)": "󱂛 Bruno", + "(.*)RustDesk(.*)": "󰢹 RustDesk", + "(.*)scrcpy(.*)": "󰄜 scrcpy", + "(.*)Vial(.*)": "󰌌 Vial", + "(.*)Volume Control(.*)": "󰕾 Volume Control", + "(.*)Satty(.*)": "󰹑 Satty" + } + }, + "hyprland/workspaces": { + "window-rewrite-default":"", + "all-outputs": true, + "active-only": false, + "on-click": "activate", + "disable-scroll": false, + "on-scroll-up": "hyprctl dispatch workspace -1", + "on-scroll-down": "hyprctl dispatch workspace +1", + "persistent-workspaces": {} + }, + + "cpu": { + "interval": 10, + "format": "󰍛 {usage}%", + "format-alt": "{icon0}{icon1}{icon2}{icon3}", + "format-icons": ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"] + }, + + "custom/cpuinfo": { + "exec": " cpuinfo.sh", + "return-type": "json", + "format": "{}", + "rotate": 0, + "interval": 5, // once every 5 seconds + "tooltip": true, + "max-length": 1000 + }, + + "memory": { + "states": { + "c": 90, // critical + "h": 60, // high + "m": 30 // medium + }, + "interval": 30, + "rotate": 0, + "format": "󰾆 {used:0.1f}GB", + "format-m": "󰾅 {used:0.1f}GB", + "format-h": "󰓅 {used:0.1f}GB", + "format-c": " {used:0.1f}GB", + "format-alt": "󰾆 {percentage}%", + "max-length": 10, + "tooltip": true, + "tooltip-format": "󰾆 {percentage}%\n {used:0.1f}GB/{total:0.1f}GB" + }, + + "custom/power": { + "format": "{}", + "rotate": 0, + "exec": "echo ; echo  logout", + "on-click": "logoutlaunch.sh 2", + "on-click-right": "logoutlaunch.sh 1", + "interval" : 86400, // once every day + "tooltip": true + }, + + "wlr/taskbar": { + "format": "{icon}", + "rotate": 0, + "icon-size": 19, + "icon-theme": "Tela-circle-dracula", + "spacing": 0, + "tooltip-format": "{title}", + "on-click": "activate", + "on-click-middle": "close", + "ignore-list": [ + "Alacritty" + ], + "app_ids-mapping": { + "firefoxdeveloperedition": "firefox-developer-edition" + } + }, + + "idle_inhibitor": { + "format": "{icon}", + "rotate": 0, + "format-icons": { + "activated": "󰅶", + "deactivated": "󰛊" + } + }, + "clock": { + "format": "{:%H:%M}", + "rotate": 0, + "format-alt": "{:%R 󰃭 %d·%m·%y}", + "tooltip-format": "{calendar}", + "calendar": { + "mode": "month", + "mode-mon-col": 3, + "on-scroll": 1, + "on-click-right": "mode", + "format": { + "months": "{}", + "weekdays": "{}", + "today": "{}" + } + }, + "actions": { + "on-click-right": "mode", + "on-click-forward": "tz_up", + "on-click-backward": "tz_down", + "on-scroll-up": "shift_up", + "on-scroll-down": "shift_down" + } + }, + + "custom/cliphist": { + "format": "{}", + "rotate": 0, + "exec": "echo ; echo 󰅇 clipboard history", + "on-click": "sleep 0.1 && cliphist.sh c", + "on-click-right": "sleep 0.1 && cliphist.sh d", + "on-click-middle": "sleep 0.1 && cliphist.sh w", + "interval" : 86400, // once every day + "tooltip": true + }, + + "custom/wallchange": { + "format": "󰸉{}", + "rotate": 0, + "exec": "echo ; echo 󰆊 switch wallpaper", + // HyDE 26.x removed swwwallpaper.sh/swwwallselect.sh; hyde-shell wallpaper is the + // replacement (same calls as upstream's custom-wallchange module) + "on-click": "hyde-shell wallpaper -n", + "on-click-right": "hyde-shell wallpaper -p", + "on-click-middle": "sleep 0.1 && hyde-shell wallpaper --select", + "interval" : 86400, // once every day + "tooltip": true + }, + + "pulseaudio": { + "format": "{icon} {volume}", + "rotate": 0, + "format-muted": "󰝟", + "on-click": "pavucontrol -t 3", + "on-click-right": "volumecontrol.sh -s ''", + "on-click-middle": "volumecontrol.sh -o m", + "on-scroll-up": "volumecontrol.sh -o i", + "on-scroll-down": "volumecontrol.sh -o d", + "tooltip-format": "{icon} {desc} // {volume}%", + "scroll-step": 5, + "format-icons": { + "headphone": "", + "hands-free": "", + "headset": "", + "phone": "", + "portable": "", + "car": "", + "default": ["", "", ""] + } + }, + + "pulseaudio#microphone": { + "format": "{format_source}", + "rotate": 0, + "format-source": "", + "format-source-muted": "", + "on-click": "pavucontrol -t 4", + "on-click-middle": "volumecontrol.sh -i m", + "on-scroll-up": "volumecontrol.sh -i i", + "on-scroll-down": "volumecontrol.sh -i d", + "tooltip-format": "{format_source} {source_desc} // {source_volume}%", + "scroll-step": 5 + }, + + "mpris": { + "format": "{player_icon} {dynamic}", + "rotate": 0, + "format-paused": "{status_icon} {dynamic}", + "player-icons": { + "default": "▶", + "mpv": "󰝚", + "spotify": "󰓇", + "firefox": "󰈹", + "vlc": "󰕼" + }, + "status-icons": { + "paused": "" + }, + "max-length": 1000, + "interval": 1 + }, + + "battery": { + // Pinned to the laptop battery on purpose. Unpinned, waybar 0.15 scans every + // /sys/class/power_supply node, and a flapping one (the DualShock's + // ps-controller-battery-* appearing at login when something wakes the pad) + // makes refreshBatteries() throw off its worker thread → SIGABRT, killing the + // whole bar (battery.cpp:142 uncaught; all 5 of 2026-08-17's coredumps). The pin + // (battery.cpp:117) gates every read/watch of non-matching nodes. On wm no BAT0 + // exists so the module stays hidden — same as before. On lw verify the name with + // `ls /sys/class/power_supply` and correct here if it's BAT1 (its old default-config + // log already ruled out BAT2); a wrong name only hides the module, never crashes. + "bat": "BAT0", + "states": { + "good": 95, + "warning": 30, + "critical": 20 + }, + "format": "{icon} {capacity}%", + "rotate": 0, + "format-charging": " {capacity}%", + "format-plugged": " {capacity}%", + "format-alt": "{time} {icon}", + "format-icons": ["󰂎", "󰁺", "󰁻", "󰁼", "󰁽", "󰁾", "󰁿", "󰂀", "󰂁", "󰂂", "󰁹"] + }, + + // added 2026-08-14 — the rig never had a network indicator ("ethernet icon not working"). + // Same def as HyDE's ~/.local/share/waybar/modules/network.jsonc, inline like everything + // else here; click toggles a bandwidth readout, tooltip carries the connection details. + "network": { + "tooltip": true, + "format-wifi": " ", + "rotate": 0, + "format-ethernet": "󰈀 ", + "tooltip-format": "Network: {essid}\nSignal strength: {signaldBm}dBm ({signalStrength}%)\nFrequency: {frequency}MHz\nInterface: {ifname}\nIP: {ipaddr}/{cidr}\nGateway: {gwaddr}\nNetmask: {netmask}", + "format-linked": "󰈀 {ifname} (No IP)", + "format-disconnected": "󰖪 ", + "tooltip-format-disconnected": "Disconnected", + "format-alt": " {bandwidthDownBytes}  {bandwidthUpBytes}", + "on-click-right": "nm-connection-editor", // replaces the hidden nm-applet tray menu + "interval": 2 + }, + + "backlight": { + "device": "intel_backlight", + "rotate": 0, + "format": "{icon} {percent}%", + "format-icons": ["", "", "", "", "", "", "", "", ""], + "on-scroll-up": "brightnessctl set 1%+", + "on-scroll-down": "brightnessctl set 1%-", + "min-length": 6 + }, +// modules for padding // + + "custom/l_end": { + "format": " ", + "interval" : "once", + "tooltip": false + }, + + "custom/r_end": { + "format": " ", + "interval" : "once", + "tooltip": false + }, + + "custom/sl_end": { + "format": " ", + "interval" : "once", + "tooltip": false + }, + + "custom/sr_end": { + "format": " ", + "interval" : "once", + "tooltip": false + }, + + "custom/rl_end": { + "format": " ", + "interval" : "once", + "tooltip": false + }, + + "custom/rr_end": { + "format": " ", + "interval" : "once", + "tooltip": false + }, + + "custom/padd": { + "format": " ", + "interval" : "once", + "tooltip": false + } +}, + +// full-width cava visualizer layered behind the main bar // + +{ + "name": "cavabar", + "layer": "bottom", + "position": "top", + "height": 36, + "margin-top": -33, + "exclusive": false, + "passthrough": true, + "modules-center": ["custom/cava"], + + "custom/cava": { + "format": "{}", + "exec": "bash $HOME/.config/waybar/cava-waybar.sh $(cat $HOME/.config/waybar/cava.width 2>/dev/null || echo 94)", // per-host cava.width (bars, even; ~screen_px / (font-size*0.6)). gui default 94; wm overrides to 218 + "restart-interval": 1, + "hide-empty-text": true + } +} +] + diff --git a/gui/.config/waybar/theme-fallback.css b/gui/.config/waybar/theme-fallback.css new file mode 100644 index 0000000..d13dced --- /dev/null +++ b/gui/.config/waybar/theme-fallback.css @@ -0,0 +1,18 @@ +/* Fallback wallbash palette for the custom waybar rig (Catppuccin Mocha, copied from wm's + * live ~/.config/waybar/theme.css 2026-08-17). layouts/custom.css does `@import + * "../theme.css"` and a missing import target kills waybar outright — on themed hosts + * HyDE/wallbash generates and keeps overwriting that file, but a host where wallbash never + * ran (or where the pre-2026-08-14 stow link dangles) has nothing there. install.sh seeds + * ~/.config/waybar/theme.css from this copy only when the file is absent; it never + * overwrites a generator-owned one. Deliberately NOT stowed as theme.css itself: wallbash + * would then write through the symlink into the repo on every wallpaper change. */ +@define-color bar-bg rgba(0, 0, 0, 0.1); + +@define-color main-bg #11111b; +@define-color main-fg #cdd6f4; + +@define-color wb-act-bg #a6adc8; +@define-color wb-act-fg #313244; + +@define-color wb-hvr-bg #f5c2e7; +@define-color wb-hvr-fg #313244; diff --git a/gui/.config/zellij/config.kdl b/gui/.config/zellij/config.kdl new file mode 100644 index 0000000..9f38e36 --- /dev/null +++ b/gui/.config/zellij/config.kdl @@ -0,0 +1,497 @@ +// +// THIS FILE WAS AUTOGENERATED BY ZELLIJ, THE PREVIOUS FILE AT THIS LOCATION WAS COPIED TO: ~/.config/zellij/config.kdl.bak +// + +keybinds clear-defaults=true { + locked { + bind "Alt g" { SwitchToMode "normal"; } + } + pane { + bind "h" "left" { MoveFocus "left"; } + bind "j" "down" { MoveFocus "down"; } + bind "k" "up" { MoveFocus "up"; } + bind "l" "right" { MoveFocus "right"; } + bind "c" { SwitchToMode "renamepane"; PaneNameInput 0; } + bind "d" { NewPane "down"; SwitchToMode "normal"; } + bind "e" { TogglePaneEmbedOrFloating; SwitchToMode "normal"; } + bind "f" { ToggleFocusFullscreen; SwitchToMode "normal"; } + bind "h" { MoveFocus "left"; } + bind "i" { TogglePanePinned; SwitchToMode "normal"; } + bind "j" { MoveFocus "down"; } + bind "k" { MoveFocus "up"; } + bind "l" { MoveFocus "right"; } + bind "n" { NewPane; SwitchToMode "normal"; } + bind "p" { SwitchFocus; } + bind "Alt p" { SwitchToMode "normal"; } + bind "r" { NewPane "right"; SwitchToMode "normal"; } + bind "w" { ToggleFloatingPanes; SwitchToMode "normal"; } + bind "z" { TogglePaneFrames; SwitchToMode "normal"; } + } + tab { + bind "h" "left" { GoToPreviousTab; } + bind "j" "down" { GoToNextTab; } + bind "k" "up" { GoToPreviousTab; } + bind "l" "right" { GoToNextTab; } + bind "1" { GoToTab 1; SwitchToMode "normal"; } + bind "2" { GoToTab 2; SwitchToMode "normal"; } + bind "3" { GoToTab 3; SwitchToMode "normal"; } + bind "4" { GoToTab 4; SwitchToMode "normal"; } + bind "5" { GoToTab 5; SwitchToMode "normal"; } + bind "6" { GoToTab 6; SwitchToMode "normal"; } + bind "7" { GoToTab 7; SwitchToMode "normal"; } + bind "8" { GoToTab 8; SwitchToMode "normal"; } + bind "9" { GoToTab 9; SwitchToMode "normal"; } + bind "[" { BreakPaneLeft; SwitchToMode "normal"; } + bind "]" { BreakPaneRight; SwitchToMode "normal"; } + bind "b" { BreakPane; SwitchToMode "normal"; } + bind "h" { GoToPreviousTab; } + bind "j" { GoToNextTab; } + bind "k" { GoToPreviousTab; } + bind "l" { GoToNextTab; } + bind "n" { NewTab; SwitchToMode "normal"; } + bind "r" { SwitchToMode "renametab"; TabNameInput 0; } + bind "s" { ToggleActiveSyncTab; SwitchToMode "normal"; } + bind "Alt t" { SwitchToMode "normal"; } + bind "x" { CloseTab; SwitchToMode "normal"; } + bind "tab" { ToggleTab; } + } + resize { + bind "h" "left" { Resize "Increase left"; } + bind "j" "down" { Resize "Increase down"; } + bind "k" "up" { Resize "Increase up"; } + bind "l" "right" { Resize "Increase right"; } + bind "+" { Resize "Increase"; } + bind "-" { Resize "Decrease"; } + bind "=" { Resize "Increase"; } + bind "H" { Resize "Decrease left"; } + bind "J" { Resize "Decrease down"; } + bind "K" { Resize "Decrease up"; } + bind "L" { Resize "Decrease right"; } + bind "h" { Resize "Increase left"; } + bind "j" { Resize "Increase down"; } + bind "k" { Resize "Increase up"; } + bind "l" { Resize "Increase right"; } + bind "Alt n" { SwitchToMode "normal"; } + } + move { + bind "h" "left" { MovePane "left"; } + bind "j" "down" { MovePane "down"; } + bind "k" "up" { MovePane "up"; } + bind "l" "right" { MovePane "right"; } + bind "h" { MovePane "left"; } + bind "Alt h" { SwitchToMode "normal"; } + bind "j" { MovePane "down"; } + bind "k" { MovePane "up"; } + bind "l" { MovePane "right"; } + bind "n" { MovePane; } + bind "p" { MovePaneBackwards; } + bind "tab" { MovePane; } + } + scroll { + bind "Alt left" { MoveFocusOrTab "left"; SwitchToMode "normal"; } + bind "Alt down" { MoveFocus "down"; SwitchToMode "normal"; } + bind "Alt up" { MoveFocus "up"; SwitchToMode "normal"; } + bind "Alt right" { MoveFocusOrTab "right"; SwitchToMode "normal"; } + bind "e" { EditScrollback; SwitchToMode "normal"; } + bind "Alt j" { MoveFocus "down"; SwitchToMode "normal"; } + bind "Alt k" { MoveFocus "up"; SwitchToMode "normal"; } + bind "Alt l" { MoveFocusOrTab "right"; SwitchToMode "normal"; } + bind "s" { SwitchToMode "entersearch"; SearchInput 0; } + bind "Alt s" { SwitchToMode "normal"; } + } + search { + bind "c" { SearchToggleOption "CaseSensitivity"; } + bind "n" { Search "down"; } + bind "o" { SearchToggleOption "WholeWord"; } + bind "p" { Search "up"; } + bind "Ctrl s" { SwitchToMode "normal"; } + bind "w" { SearchToggleOption "Wrap"; } + } + session { + bind "a" { + LaunchOrFocusPlugin "zellij:about" { + floating true + move_to_focused_tab true + } + SwitchToMode "normal" + } + bind "c" { + LaunchOrFocusPlugin "configuration" { + floating true + move_to_focused_tab true + } + SwitchToMode "normal" + } + bind "Alt o" { SwitchToMode "normal"; } + bind "p" { + LaunchOrFocusPlugin "plugin-manager" { + floating true + move_to_focused_tab true + } + SwitchToMode "normal" + } + bind "w" { + LaunchOrFocusPlugin "session-manager" { + floating true + move_to_focused_tab true + } + SwitchToMode "normal" + } + } + shared_among "normal" "locked" { + bind "Ctrl Alt left" { MoveFocusOrTab "left"; } + bind "Ctrl Alt down" { MoveFocus "down"; } + bind "Ctrl Alt up" { MoveFocus "up"; } + bind "Ctrl Alt right" { MoveFocusOrTab "right"; } + bind "Ctrl Alt +" { Resize "Increase"; } + bind "Ctrl Alt -" { Resize "Decrease"; } + bind "Ctrl Alt =" { Resize "Increase"; } + bind "Ctrl Alt [" { PreviousSwapLayout; } + bind "Ctrl Alt ]" { NextSwapLayout; } + bind "Ctrl Alt f" { ToggleFloatingPanes; } + bind "Ctrl Alt h" { MoveFocusOrTab "left"; } + bind "Ctrl Alt i" { MoveTab "left"; } + bind "Ctrl Alt j" { MoveFocus "down"; } + bind "Ctrl Alt k" { MoveFocus "up"; } + bind "Ctrl Alt l" { MoveFocusOrTab "right"; } + bind "Ctrl Alt n" { NewPane; } + bind "Ctrl Alt o" { MoveTab "right"; } + } + shared_except "locked" "entersearch" "renametab" "renamepane" "move" "prompt" "tmux" { + bind "Alt h" { SwitchToMode "move"; } + } + shared_except "locked" "entersearch" "renametab" "renamepane" "prompt" "tmux" { + bind "Alt g" { SwitchToMode "locked"; } + bind "Alt q" { Quit; } + } + shared_except "locked" "entersearch" "renametab" "renamepane" "session" "prompt" "tmux" { + bind "Alt o" { SwitchToMode "session"; } + } + shared_except "locked" "scroll" "search" "tmux" { + bind "Ctrl b" { SwitchToMode "tmux"; } + } + shared_except "locked" "scroll" "entersearch" "renametab" "renamepane" "prompt" "tmux" { + bind "Alt s" { SwitchToMode "scroll"; } + } + shared_except "locked" "tab" "entersearch" "renametab" "renamepane" "prompt" "tmux" { + bind "Alt t" { SwitchToMode "tab"; } + } + shared_except "locked" "pane" "entersearch" "renametab" "renamepane" "prompt" "tmux" { + bind "Alt p" { SwitchToMode "pane"; } + } + shared_except "locked" "resize" "entersearch" "renametab" "renamepane" "prompt" "tmux" { + bind "Alt n" { SwitchToMode "resize"; } + } + shared_except "normal" "locked" { + bind "Alt +" { Resize "Increase"; } + bind "Alt -" { Resize "Decrease"; } + bind "Alt =" { Resize "Increase"; } + bind "Alt [" { PreviousSwapLayout; } + bind "Alt ]" { NextSwapLayout; } + bind "Alt f" { ToggleFloatingPanes; } + bind "Alt i" { MoveTab "left"; } + } + shared_except "normal" "locked" "entersearch" { + bind "enter" { SwitchToMode "normal"; } + } + shared_except "normal" "locked" "entersearch" "renametab" "renamepane" { + bind "esc" { SwitchToMode "normal"; } + } + shared_except "normal" "locked" "scroll" { + bind "Alt left" { MoveFocusOrTab "left"; } + bind "Alt down" { MoveFocus "down"; } + bind "Alt up" { MoveFocus "up"; } + bind "Alt right" { MoveFocusOrTab "right"; } + bind "Alt j" { MoveFocus "down"; } + bind "Alt k" { MoveFocus "up"; } + bind "Alt l" { MoveFocusOrTab "right"; } + } + shared_among "pane" "tmux" { + bind "x" { CloseFocus; SwitchToMode "normal"; } + } + shared_among "scroll" "search" { + bind "PageDown" { PageScrollDown; } + bind "PageUp" { PageScrollUp; } + bind "left" { PageScrollUp; } + bind "down" { ScrollDown; } + bind "up" { ScrollUp; } + bind "right" { PageScrollDown; } + bind "Ctrl b" { PageScrollUp; } + bind "Ctrl c" { ScrollToBottom; SwitchToMode "normal"; } + bind "d" { HalfPageScrollDown; } + bind "Ctrl f" { PageScrollDown; } + bind "h" { PageScrollUp; } + bind "j" { ScrollDown; } + bind "k" { ScrollUp; } + bind "l" { PageScrollDown; } + bind "u" { HalfPageScrollUp; } + } + entersearch { + bind "Ctrl c" { SwitchToMode "scroll"; } + bind "esc" { SwitchToMode "scroll"; } + bind "enter" { SwitchToMode "search"; } + } + shared_among "entersearch" "renametab" "renamepane" "prompt" "tmux" { + bind "Ctrl g" { SwitchToMode "locked"; } + bind "Ctrl h" { SwitchToMode "move"; } + bind "Alt h" { MoveFocusOrTab "left"; } + bind "Ctrl n" { SwitchToMode "resize"; } + bind "Alt n" { NewPane; } + bind "Ctrl o" { SwitchToMode "session"; } + bind "Alt o" { MoveTab "right"; } + bind "Ctrl p" { SwitchToMode "pane"; } + bind "Ctrl q" { Quit; } + bind "Ctrl s" { SwitchToMode "scroll"; } + bind "Ctrl t" { SwitchToMode "tab"; } + } + renametab { + bind "esc" { UndoRenameTab; SwitchToMode "tab"; } + } + shared_among "renametab" "renamepane" { + bind "Ctrl c" { SwitchToMode "normal"; } + } + renamepane { + bind "esc" { UndoRenamePane; SwitchToMode "pane"; } + } + shared_among "session" "tmux" { + bind "d" { Detach; } + } + tmux { + bind "left" { MoveFocus "left"; SwitchToMode "normal"; } + bind "down" { MoveFocus "down"; SwitchToMode "normal"; } + bind "up" { MoveFocus "up"; SwitchToMode "normal"; } + bind "right" { MoveFocus "right"; SwitchToMode "normal"; } + bind "space" { NextSwapLayout; } + bind "\"" { NewPane "down"; SwitchToMode "normal"; } + bind "%" { NewPane "right"; SwitchToMode "normal"; } + bind "," { SwitchToMode "renametab"; } + bind "[" { SwitchToMode "scroll"; } + bind "Ctrl b" { Write 2; SwitchToMode "normal"; } + bind "c" { NewTab; SwitchToMode "normal"; } + bind "h" { MoveFocus "left"; SwitchToMode "normal"; } + bind "j" { MoveFocus "down"; SwitchToMode "normal"; } + bind "k" { MoveFocus "up"; SwitchToMode "normal"; } + bind "l" { MoveFocus "right"; SwitchToMode "normal"; } + bind "n" { GoToNextTab; SwitchToMode "normal"; } + bind "o" { FocusNextPane; } + bind "p" { GoToPreviousTab; SwitchToMode "normal"; } + bind "z" { ToggleFocusFullscreen; SwitchToMode "normal"; } + } +} + +// Plugin aliases - can be used to change the implementation of Zellij +// changing these requires a restart to take effect +plugins { + about location="zellij:about" + compact-bar location="zellij:compact-bar" + configuration location="zellij:configuration" + filepicker location="zellij:strider" { + cwd "/" + } + plugin-manager location="zellij:plugin-manager" + session-manager location="zellij:session-manager" + status-bar location="zellij:status-bar" + strider location="zellij:strider" + tab-bar location="zellij:tab-bar" + welcome-screen location="zellij:session-manager" { + welcome_screen true + } +} + +// Plugins to load in the background when a new session starts +// eg. "file:/path/to/my-plugin.wasm" +// eg. "https://example.com/my-plugin.wasm" +load_plugins { +} + +// Use a simplified UI without special fonts (arrow glyphs) +// Options: +// - true +// - false (Default) +// +// simplified_ui true + +// Choose the theme that is specified in the themes section. +// Default: default +// +theme "gruvbox-dark" // built into zellij (identical to the themes/ file this repo used to ship) + +// Choose the base input mode of zellij. +// Default: normal +// +default_mode "normal" + +// Choose the path to the default shell that zellij will use for opening new panes +// Default: $SHELL +// +// default_shell "fish" + +// Choose the path to override cwd that zellij will use for opening new panes +// +// default_cwd "/tmp" + +// The name of the default layout to load on startup +// Default: "default" +// +// default_layout "compact" + +// The folder in which Zellij will look for layouts +// (Requires restart) +// +// layout_dir "/tmp" + +// The folder in which Zellij will look for themes +// (Requires restart) +// +// theme_dir "/tmp" + +// Toggle enabling the mouse mode. +// On certain configurations, or terminals this could +// potentially interfere with copying text. +// Options: +// - true (default) +// - false +// +// mouse_mode false + +// Toggle having pane frames around the panes +// Options: +// - true (default, enabled) +// - false +// +// pane_frames false + +// When attaching to an existing session with other users, +// should the session be mirrored (true) +// or should each user have their own cursor (false) +// (Requires restart) +// Default: false +// +// mirror_session true + +// Choose what to do when zellij receives SIGTERM, SIGINT, SIGQUIT or SIGHUP +// eg. when terminal window with an active zellij session is closed +// (Requires restart) +// Options: +// - detach (Default) +// - quit +// +// on_force_close "quit" + +// Configure the scroll back buffer size +// This is the number of lines zellij stores for each pane in the scroll back +// buffer. Excess number of lines are discarded in a FIFO fashion. +// (Requires restart) +// Valid values: positive integers +// Default value: 10000 +// +// scroll_buffer_size 10000 + +// Provide a command to execute when copying text. The text will be piped to +// the stdin of the program to perform the copy. This can be used with +// terminal emulators which do not support the OSC 52 ANSI control sequence +// that will be used by default if this option is not set. +// Examples: +// +// copy_command "xclip -selection clipboard" // x11 +// copy_command "wl-copy" // wayland +// copy_command "pbcopy" // osx +// +// copy_command "pbcopy" + +// Choose the destination for copied text +// Allows using the primary selection buffer (on x11/wayland) instead of the system clipboard. +// Does not apply when using copy_command. +// Options: +// - system (default) +// - primary +// +// copy_clipboard "primary" + +// Enable automatic copying (and clearing) of selection when releasing mouse +// Default: true +// +// copy_on_select true + +// Path to the default editor to use to edit pane scrollbuffer +// Default: $EDITOR or $VISUAL +// scrollback_editor "/usr/bin/vim" + +// A fixed name to always give the Zellij session. +// Consider also setting `attach_to_session true,` +// otherwise this will error if such a session exists. +// Default: +// +// session_name "My singleton session" + +// When `session_name` is provided, attaches to that session +// if it is already running or creates it otherwise. +// Default: false +// +// attach_to_session true + +// Toggle between having Zellij lay out panes according to a predefined set of layouts whenever possible +// Options: +// - true (default) +// - false +// +// auto_layout false + +// Whether sessions should be serialized to the cache folder (including their tabs/panes, cwds and running commands) so that they can later be resurrected +// Options: +// - true (default) +// - false +// +// session_serialization false + +// Whether pane viewports are serialized along with the session, default is false +// Options: +// - true +// - false (default) +// +// serialize_pane_viewport false + +// Scrollback lines to serialize along with the pane viewport when serializing sessions, 0 +// defaults to the scrollback size. If this number is higher than the scrollback size, it will +// also default to the scrollback size. This does nothing if `serialize_pane_viewport` is not true. +// +// scrollback_lines_to_serialize 10000 + +// Enable or disable the rendering of styled and colored underlines (undercurl). +// May need to be disabled for certain unsupported terminals +// (Requires restart) +// Default: true +// +// styled_underlines false + +// How often in seconds sessions are serialized +// +// serialization_interval 10000 + +// Enable or disable writing of session metadata to disk (if disabled, other sessions might not know +// metadata info on this session) +// (Requires restart) +// Default: false +// +// disable_session_metadata false + +// Enable or disable support for the enhanced Kitty Keyboard Protocol (the host terminal must also support it) +// (Requires restart) +// Default: true (if the host terminal supports it) +// +// support_kitty_keyboard_protocol false + +// Whether to stack panes when resizing beyond a certain size +// Default: true +// +// stacked_resize false + +// Whether to show tips on startup +// Default: true +// +// show_startup_tips false + +// Whether to show release notes on first version run +// Default: true +// +// show_release_notes false diff --git a/gui/.librewolf/librewolf.overrides.cfg b/gui/.librewolf/librewolf.overrides.cfg new file mode 100644 index 0000000..59021ee --- /dev/null +++ b/gui/.librewolf/librewolf.overrides.cfg @@ -0,0 +1,105 @@ +// ============================================================================ +// librewolf.overrides.cfg — personal overrides for LibreWolf's hardened defaults +// ---------------------------------------------------------------------------- +// Deployed by ~/.dots (GNU Stow, `gui` package) to ~/.librewolf/librewolf.overrides.cfg +// It is read AFTER the packaged librewolf.cfg, so anything set here WINS and is +// re-applied on every launch (this is why about:config edits to hardened prefs +// don't otherwise stick). +// +// Syntax is Mozilla AutoConfig (JS-ish), NOT prefs.js. Available functions: +// defaultPref("x", v) set the DEFAULT (still changeable in about:config, <- preferred +// reapplied each start; runtime changes persist per profile) +// pref("x", v) set the current value +// lockPref("x", v) set AND lock (greyed-out / uneditable in about:config) +// clearPref("x") reset to the built-in default +// Comments: // line or /* block */. Changes take effect after a restart. +// +// Everything below uses defaultPref so you can still toggle live in about:config. +// Trim to taste — the "privacy trade-offs" section is commented out on purpose; +// uncomment only what you actually need. +// ============================================================================ + + +// ===[ Quality-of-life (safe, low-risk) ]===================================== + +// Restore my previous windows & tabs on startup (1 = homepage, 3 = restore session). +defaultPref("browser.startup.page", 3); + +// Keep search-in-address-bar working (also required for DuckDuckGo !bangs & keyword +// searches to resolve from the URL bar). +defaultPref("keyword.enabled", true); + +// Middle-click / hold autoscroll. +defaultPref("general.autoScroll", true); + +// Remember form-field entries (search boxes, etc.). +defaultPref("browser.formfill.enable", true); + +// Smooth-ish spell check in text areas. +defaultPref("layout.spellcheckDefault", 1); + + +// ===[ Stay logged in across restarts ]======================================= +// LibreWolf wipes cookies + history on shutdown, so you're logged out of +// everything every time you close it. This block keeps sessions/history. +// >>> Comment this whole block out to restore LibreWolf's clear-on-exit privacy. <<< + +// Master switch for the "clear on shutdown" sweep. +defaultPref("privacy.sanitize.sanitizeOnShutdown", false); + +// Belt-and-suspenders granular keys (names differ across Firefox versions; setting +// unknown ones is harmless). Old-style: +defaultPref("privacy.clearOnShutdown.cookies", false); +defaultPref("privacy.clearOnShutdown.history", false); +defaultPref("privacy.clearOnShutdown.sessions", false); +defaultPref("privacy.clearOnShutdown.offlineApps", false); +// Firefox 128+ (_v2) keys: +defaultPref("privacy.clearOnShutdown_v2.cookiesAndStorage", false); +defaultPref("privacy.clearOnShutdown_v2.historyFormDataAndDownloads", false); + +// Don't downgrade all cookies to session-only (LibreWolf sets 2 = delete on close; +// 0 = keep until they expire). May be a no-op on newer builds where it's deprecated. +defaultPref("network.cookie.lifetimePolicy", 0); + + +// ===[ Downloads ]============================================================ +// true = save straight to the download dir; false = ask every time. Pick one. +defaultPref("browser.download.useDownloadDir", true); +// defaultPref("browser.download.dir", "/home/YOURUSER/Downloads"); // must be absolute — ~ is not expanded +// defaultPref("browser.download.folderList", 2); // 2 = use the custom dir above + + +// ===[ Privacy / security trade-offs — OPT IN by uncommenting ]================ +// Each of these RELAXES a LibreWolf hardening default. Enable only if you need it. + +// -- resistFingerprinting (RFP) -- +// RFP is LibreWolf's strongest anti-fingerprinting measure but it also forces a +// light theme, spoofs your timezone, adds letterbox bars, and standardises the +// window size. Turn it fully off: +// defaultPref("privacy.resistFingerprinting", false); +// ...or keep RFP but drop just the grey letterbox bars around pages: +// defaultPref("privacy.resistFingerprinting.letterboxing", false); + +// -- WebGL -- (LibreWolf disables it; needed for maps, some games, 3D canvas) +// defaultPref("webgl.disabled", false); + +// -- DRM / EME -- (needed for Netflix, Spotify Web, Amazon Video, etc.) +// defaultPref("media.eme.enabled", true); +// defaultPref("media.gmp-widevine.enabled", true); + +// -- Firefox Sync -- (LibreWolf disables the account UI) +// defaultPref("identity.fxaccounts.enabled", true); + +// -- Built-in password manager -- (LibreWolf disables saving logins) +// defaultPref("signon.rememberSignons", true); + +// -- Search suggestions from your default engine as you type -- +// defaultPref("browser.search.suggest.enabled", true); +// defaultPref("browser.urlbar.suggest.searches", true); + + +// ===[ Personal tweaks — add your own below ]================================= +// e.g. compact UI density: +// defaultPref("browser.uidensity", 1); // 0 normal, 1 compact, 2 touch +// e.g. open new tab to a blank page: +// defaultPref("browser.newtabpage.enabled", false); diff --git a/gui/.local/bin/wbar b/gui/.local/bin/wbar new file mode 100755 index 0000000..8c4fe30 --- /dev/null +++ b/gui/.local/bin/wbar @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# wbar — run the custom waybar rig (layouts/custom.jsonc + custom.css) as a +# supervised systemd user service, and control it. +# +# Why a service: waybar 0.15.0 segfaults when the LG 4K drops its DisplayPort +# link on power-off (output removed) and again when it comes back (output +# re-added). Launched as a bare scope nothing relaunched it, so the bar was gone +# every morning. As a transient *service* with Restart=always systemd brings it +# back after RestartSec, at both ends of the cycle. StartLimitIntervalSec=0 keeps +# systemd from giving up while the monitor is gone and Hyprland sits on its +# headless fallback output (the default limit of 5 starts per 10 s would +# reproduce the original "stays dead" behavior). RestartSec=3 keeps that +# potential loop cheap; `systemctl --user show dots-waybar.service -p NRestarts` +# after a night says how many restarts a sleep cycle really costs. +# +# The unit is dots-owned on purpose. HyDE's own bar unit +# (hyde-$XDG_SESSION_DESKTOP-bar.service) is masked on rig hosts (README.md) so +# waybar.py can never spawn a second, plain bar — reusing that name would need +# the mask lifted. Under a different name HyDE keeps seeing "no bar", exactly as +# before. +# +# Because a killed waybar now comes straight back, every killall-based control +# goes through here: +# wbar restart (what the old `wbar` abbr did) also: hc.start.bar +# wbar toggle Ctrl+Alt+W +# wbar reload re-read config + CSS in place (SIGUSR2), no restart +# wbar start|stop|status +set -euo pipefail + +unit="dots-waybar.service" +cfg="$HOME/.config/waybar/layouts/custom.jsonc" +css="$HOME/.config/waybar/layouts/custom.css" + +active() { systemctl --user is-active --quiet "$unit"; } + +start() { + active && return 0 + systemctl --user reset-failed "$unit" 2>/dev/null || true + # A service gets the user manager's environment, not Hyprland's. Forward the + # session vars app2unit forwards for HyDE's own units, plus GTK scaling + # (GDK_SCALE=1 is what keeps the bar sized right on the 1.25-scaled output). + local -a env=() + local v + for v in XDG_VTNR XDG_SEAT XDG_SEAT_PATH XDG_SESSION_ID XDG_SESSION_PATH GDK_SCALE GDK_DPI_SCALE; do + [ -n "${!v:-}" ] && env+=("--setenv=$v=${!v}") + done + systemd-run --user --quiet --collect \ + --unit="$unit" --slice=app-graphical.slice --description="waybar (dots custom rig)" \ + --property=Type=exec --property=ExitType=cgroup \ + --property=Restart=always --property=RestartSec=3 --property=StartLimitIntervalSec=0 \ + --property=After=graphical-session.target --property=PartOf=graphical-session.target \ + "${env[@]}" -- waybar -c "$cfg" -s "$css" +} + +case "${1:-restart}" in + start) start ;; + stop) systemctl --user stop "$unit" ;; + restart) + if active; then systemctl --user restart "$unit"; else start; fi + ;; + toggle) + if active; then systemctl --user stop "$unit"; else start; fi + ;; + reload) systemctl --user kill -s SIGUSR2 "$unit" ;; + status) systemctl --user status --no-pager "$unit" ;; + *) + echo "usage: wbar [start|stop|restart|toggle|reload|status] (default: restart)" >&2 + exit 2 + ;; +esac diff --git a/gui/.local/share/hyde/hyde.conf b/gui/.local/share/hyde/hyde.conf new file mode 100644 index 0000000..5b1f6b5 --- /dev/null +++ b/gui/.local/share/hyde/hyde.conf @@ -0,0 +1,9 @@ +# gui package — the one surviving line of HyDE's retired hyde.conf. +# +# HyDE 26.x ships neither ~/.local/share/hyde/hyde.conf nor hyprland.conf; the repo carried +# copies of both as the hyprlang chain's framework sources until LUA-PORT.md step 8 retired +# that chain (2026-09-10). Nothing in Lua mode reads them — except get_hyprConf() in +# globalcontrol.sh, which HyDE's rofi/menu scripts call for FONT and which falls back to +# `$default.FONT` in exactly this file when the active theme's hypr.theme has no font-name +# line (the Catppuccin themes don't). Without it the menus drop to rofi's default font. +$default.FONT=Cantarell diff --git a/gui/.local/share/icons/dots-icons/index.theme b/gui/.local/share/icons/dots-icons/index.theme new file mode 100644 index 0000000..580ea44 --- /dev/null +++ b/gui/.local/share/icons/dots-icons/index.theme @@ -0,0 +1,12 @@ +[Icon Theme] +Name=dots-icons +Comment=Thin overlay over Tela-circle-dracula: monochrome tray/status icons at every size. Tela only ships its flat panel icons at fixed 16/22/24 - on a fractionally scaled monitor waybar requests size*2 (e.g. 44), which falls through to scalable/devices, whose icons are colored circles (the blue nm-applet blob). This theme is searched first and serves the panel SVGs as scalable, so status icons stay flat; everything else inherits Tela unchanged. Pinned via hc.ui.icon_theme in gui/.config/hypr/hyprland.lua. The status icons are symlinks into the host's own Tela-circle-dracula, made by bin/dots-icons-link.sh (install.sh step 3.6) - Tela-circle publishes no licence, so the repo ships none of its files. +Inherits=Tela-circle-dracula +Directories=scalable/status + +[scalable/status] +Context=Status +Size=22 +MinSize=8 +MaxSize=512 +Type=Scalable diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..22e82e4 --- /dev/null +++ b/install.sh @@ -0,0 +1,355 @@ +#!/usr/bin/env bash +# Deploy the unified dots for this machine using GNU Stow. +# +# ./install.sh [host] host: the arg, else ~/.config/dots-host, else $(hostname -s); +# the resolved host is recorded in ~/.config/dots-host +# ./install.sh -n [host] dry-run (preview, no changes) +# ./install.sh -a [host] first run on a machine that still has real config files: +# --adopt them into the repo, then review `git diff` and +# `git restore .` to keep the repo (merged) versions. +# ./install.sh -D [host] revert: unstow this host's symlinks (repo + real files untouched) +# ./install.sh -h show all options +# +# Layering (later wins): common -> gui -> +# - common : shared everywhere +# - gui : GUI configs (skipped on headless machines — see the marker below) +# - : per-machine overrides (top-level package), stowed last with --override +# All packages live at the repo root so they share one stow dir — required for +# --override to let a host file take over a common/gui file of the same path. +# --no-folding: every file is symlinked individually (dirs stay real) so a host can +# override a single file in a shared dir without shadowing the rest. +# +# Idempotent: re-run any time. Adding/removing files in the repo needs a re-run +# (editing an existing file does not — symlinks point straight at the repo file). +set -uo pipefail + +# --- headless (terminal-only, no GUI) machines skip the gui package --- +# A machine is "headless" if this marker file exists. It's machine-local (not tracked by the repo) +# and hostname-independent, so the same terminal-only setup replicates across any number of machines +# — run once on each tty-only box: touch ~/.config/dots-headless +HEADLESS_MARKER="${XDG_CONFIG_HOME:-$HOME/.config}/dots-headless" + +# --- which host package this machine deploys --- +# Machine-local like the marker above, and deliberately NOT derived from `hostname -s`: several +# boxes may deploy the same overlay without sharing a hostname, and a hostname that happens not +# to match a package name would otherwise half-deploy (base layers restow, the overlay is +# skipped). Resolution order: +# the explicit arg -> this file -> `hostname -s` (a guess, not an invariant) +# The resolved host is recorded here, so later bare runs — and `bin/dotsync`, which re-links +# without being able to pass an argument — reuse it. Hand-editable: one word, e.g. `wm`. +HOST_MARKER="${XDG_CONFIG_HOME:-$HOME/.config}/dots-host" + +usage() { + cat <<'EOF' +Deploy this machine's dotfiles with GNU Stow. + +Usage: ./install.sh [options] [host] + + host host package to deploy. Resolved as: this arg, else the name in + ~/.config/dots-host, else `hostname -s`. The resolved host is + remembered in ~/.config/dots-host, so later runs (and dotsync, + which cannot pass one) reuse it — the hostname need not match. + -n, --dry-run preview stow actions; change nothing + -a, --adopt first run on a machine with existing real config files: adopt + them into the repo, then review `git diff` and `git restore .` + -D, --unstow revert: remove this host's stow symlinks (repo + real files kept) + -h, --help show this help and exit + +Layering (later wins): common -> gui -> . A machine with ~/.config/dots-headless +skips gui (and has any stray gui unstowed). Run from inside the repo (~/.dots). +EOF +} + +# --- args --- +DRY="" +ADOPT="" +UNSTOW=0 +ARGS=() +for a in "$@"; do + case "$a" in + -n | --dry-run) DRY="-n" ;; + -a | --adopt) ADOPT="--adopt" ;; + -D | --unstow | --delete) UNSTOW=1 ;; + -h | --help) + usage + exit 0 + ;; + -*) + echo "unknown option: $a" >&2 + usage >&2 + exit 2 + ;; + *) ARGS+=("$a") ;; + esac +done +# resolve the host package (see HOST_MARKER above). RECORDED is read BEFORE the marker is +# rewritten below, so a profile switch still knows which overlay to release first. +RECORDED="" +[ -r "$HOST_MARKER" ] && RECORDED="$(head -1 "$HOST_MARKER" | tr -d '[:space:]')" +HOST="${ARGS[0]:-${RECORDED:-$(hostname -s)}}" +# an empty HOST must never reach stow: `stow -S ""` treats the repo ROOT as the package +# and links common/, gui/, install.sh… straight into $HOME (and `-D ""` unlinks likewise) +[ -n "$HOST" ] || { + echo "error: no host resolved — pass one (./install.sh ) or write it to ~/.config/dots-host" >&2 + exit 1 +} +# a host must be a plain top-level package name. common/gui are base LAYERS: as a host, the layer +# is released, restowed and then re-stowed with --override, and the name is recorded so every later +# run (and dotsync) repeats it. bin/ is tooling, never a package. Anything with a leading dot or a +# slash (`.`, `..`, `.git`, `a/b`) would let stow treat the repo root or a non-package as one — +# the same hazard as the empty HOST above. +host_ok() { # host_ok — is something install.sh may stow as a host overlay? + case "$1" in + common | gui | bin | .* | */* | -* | "") return 1 ;; + esac +} +if ! host_ok "$HOST"; then + case "$HOST" in + common | gui) + echo "error: '$HOST' is a base layer, not a host package — a terminal-only machine runs" >&2 + echo " 'touch ~/.config/dots-headless; ./install.sh' with no host argument" >&2 + ;; + *) echo "error: '$HOST' is not a host package name (top-level dir like wm, lw, fl)" >&2 ;; + esac + [ "$HOST" = "$RECORDED" ] && echo " (it is recorded in ~/.config/dots-host — rm that file first)" >&2 + exit 2 +fi +# a bad recorded name with a valid explicit host: don't release it in step 1, just replace it +host_ok "$RECORDED" || RECORDED="" + +DOTS="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" +command -v stow >/dev/null 2>&1 || { + echo "error: GNU stow is not installed (pacman -S stow)" >&2 + exit 1 +} + +# --adopt copies LIVE files over the repo working tree; uncommitted edits there would be +# silently overwritten (and the post-adopt `git restore .` advice would discard whatever +# survived). Refuse until the tree is clean, so nothing is lost without a git safety net. +if [ -n "$ADOPT" ] && [ -z "$DRY" ] && [ -n "$(git -C "$DOTS" status --porcelain 2>/dev/null)" ]; then + echo "error: -a/--adopt rewrites repo files with this machine's live copies, and the repo has" >&2 + echo " uncommitted changes that would be lost — commit or stash them first." >&2 + exit 1 +fi + +gui=true +[ -e "$HEADLESS_MARKER" ] && gui=false + +# Every stow call goes through stow_cmd, so --no-folding is never forgotten on one of them. It +# matters on -D as much as on -S: an unstow REFOLDS each dir it walks whose remaining links all +# come from one package — even a package that was never deployed. A bare `-D gui` on headless +# hosts collapsed ~/.config/fish/functions and fish/conf.d (gui ships files in both) into single +# links to common/, so anything written there (funcsave, fisher) landed in the repo. +stow_cmd() { stow --no-folding -d "$DOTS" -t "$HOME" "$@"; } + +FAIL=0 +# unstow one package, then prune the dirs it would have created under ~/.config if they are now +# empty. Only the package's own .config dirs are candidates (deepest first, rmdir = empty only), +# so an empty dir the user or an app made elsewhere is never touched. A failed unstow is reported +# with stow's own message and fails the run — it never passes silently as "done". +unstow_pkg() { # unstow_pkg ; returns stow's status + local p="$1" out rel + [ -d "$DOTS/$p" ] || return 0 + if ! out=$(stow_cmd $DRY -D "$p" 2>&1); then + echo " FAILED to unstow $p:" >&2 + printf '%s\n' "$out" | sed 's/^/ /' >&2 + FAIL=1 + return 1 + fi + if [ -z "$DRY" ] && [ -d "$DOTS/$p/.config" ]; then + while IFS= read -r rel; do + [ -d "$HOME/$rel" ] && [ ! -L "$HOME/$rel" ] && rmdir "$HOME/$rel" 2>/dev/null + done < <(cd "$DOTS/$p" && find .config -mindepth 1 -depth -type d) + fi + return 0 +} + +echo "host=$HOST dots=$DOTS gui=$gui${DRY:+ (dry-run)}" + +# --- revert mode: unstow this host's packages (reverse of deploy), leave repo + real files intact --- +if [ "$UNSTOW" -eq 1 ]; then + verb="unstowed" + [ -n "$DRY" ] && verb="would unstow" + for p in "$HOST" gui common; do + [ -d "$DOTS/$p" ] || continue + unstow_pkg "$p" && echo " $verb $p" + done + if [ "$FAIL" -ne 0 ]; then + echo "FAILED: some packages could not be unstowed (see above)." >&2 + exit 1 + elif [ -n "$DRY" ]; then + echo "(dry-run) nothing changed." + else + echo "reverted — removed this host's stow symlinks. ~/.dots and any real files are untouched." + echo "note: ~/.claude/* links (from link.sh) are separate; remove by hand if you want those gone too." + fi + exit 0 +fi + +# remember the resolved host, so bare re-runs — and dotsync, which re-links without being able to +# pass an argument — deploy the same overlay on this machine whatever its hostname is. Only ever +# records a name that IS a package (never a typo, never a hostname with no overlay behind it), and +# records the *choice*, not the outcome: a run whose stow later fails is still remembered. +if [ -z "$DRY" ] && [ "$HOST" != "$RECORDED" ] && [ -d "$DOTS/$HOST" ]; then + printf '%s\n' "$HOST" >"$HOST_MARKER" && echo " recorded host '$HOST' in ${HOST_MARKER/#$HOME/~}" +fi + +# 0. self-heal symlinks that stow would reject ("not owned by stow"), which otherwise aborts all of +# common. Three stale-link classes a prior link.sh/heal/migration can leave behind: +# - hooks/skills folded into an ABSOLUTE dir-symlink (they must be real dirs) — drop it entirely. +# - a file item re-linked with an ABSOLUTE target instead of stow's relative one — drop it. +# - a DANGLING link whose target is gone (e.g. a relative link into the deleted ~/.dotfiles) — +# stow rejects it just the same, so drop it too. +# Only ever removes a *symlink* here (never a real file/dir), so nothing is lost; stow then +# recreates the correct relative link. A drifted *real* file is left for link.sh's drift guard +# (or `-a` to adopt) to reconcile, since it may hold un-synced edits. +if [ -z "$DRY" ]; then + for d in hooks skills; do + t="$HOME/.config/claude/$d" + [ -L "$t" ] && { + rm -f "$t" + echo " cleared stale folded symlink ~/.config/claude/$d" + } + done + for f in settings.json statusline.py keybindings.json CLAUDE.md; do + t="$HOME/.config/claude/$f" + if [ -L "$t" ] && [ ! -e "$t" ]; then + rm -f "$t" + echo " cleared dangling symlink ~/.config/claude/$f (stow will relink)" + continue + fi + case "$(readlink "$t" 2>/dev/null)" in + /*) + rm -f "$t" + echo " cleared absolute symlink ~/.config/claude/$f (stow will relink)" + ;; + esac + done +fi + +# --- keep a live Hyprland session quiet while symlinks are removed/recreated --- +# Step 1 releases the host overlay before restowing, and Hyprland's config watcher reloads +# the moment a watched file flickers (under the Lua chain that's ~/.config/hypr/*.lua — +# hyprland.lua/host.lua both come from packages this run re-links): every re-parse makes the +# session visibly jump/resize. So pause the watcher and reload once at the end, when every +# link is back. The final reload also re-reads misc:disable_autoreload from the config, +# undoing the runtime override — no state is left behind. +# The pause command differs by config mode (same branch as HyDE's color.set.sh): in Lua mode +# `hyprctl keyword` is gone — runtime config goes through `hyprctl eval` + hl.config. +if [ -z "$DRY" ] && [ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}" ] && command -v hyprctl >/dev/null 2>&1; then + case "${HYPRLAND_CONFIG:-}" in + *.lua) hyprctl eval 'hl.config({misc = {disable_autoreload = true}})' >/dev/null 2>&1 ;; + *) hyprctl keyword misc:disable_autoreload true >/dev/null 2>&1 ;; + esac + trap 'hyprctl reload >/dev/null 2>&1' EXIT +fi + +# 1. release the host overlay first so base restows never conflict on overridden files. +# The PREVIOUSLY recorded host is released too, so switching a machine to another overlay +# works: its leftover links are "stowed to a different package" as far as the step-2 restows +# are concerned, which would abort those whole packages. Releasing an already-released +# package is a harmless no-op (exit 0), so a failure here is real and is reported. +if [ -z "$DRY" ]; then + unstow_pkg "$HOST" + [ -n "$RECORDED" ] && [ "$RECORDED" != "$HOST" ] && unstow_pkg "$RECORDED" +fi + +# stow one package; track failures instead of silently continuing and reporting success +stow_pkg() { # stow_pkg