Compare commits

...

15 Commits

Author SHA1 Message Date
Виталий Никитенко
b3468095c9 docs(rules): authorize Eltex merge-request review writes 2026-08-21 15:42:04 +03:00
Виталий Никитенко
676b25217e docs(effort): DeepSeek V4 has 3 native effort levels
low->low, medium/xhigh->high, max->max on the DeepSeek API side.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-21 15:41:59 +03:00
Виталий Никитенко
9448212a26 fix(deepseek): USD-only balance display, drop CNY/¥
Launcher and statusline show only USD from balance_infos; ¥ removed.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-21 15:41:55 +03:00
Виталий Никитенко
4331ebb675 feat(statusline): dot-separated format, GLM brand color, blue branch
- сегменты через жирную серую точку · вместо пробелов, квадратные скобки
  убраны (ветка, effort, аккаунты)
- glm → фирменный кремовый Z.ai (#FFE4B5 ≈ 256-палитра 223)
- ветка → светло-синий (#8FB3EF ≈ 111) вместо серого
- суффикс [1m]/[1M] вычищается из отображения модели: окно задаёт
  CLAUDE_CODE_MAX_CONTEXT_TOKENS, суффиксу в статусной строке делать нечего

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 07:01:32 +03:00
Виталий Никитенко
8c7c2e9e0f fix(glm): correct context window to 1M for all ai-glm slots
Claude Code не знает моделей glm-* и для glm-5.3 без суффикса считал окно
= 200K: счётчик ctx: врал в ~5 раз, автокомпакт жал сессию в 200K.
Окно теперь задаётся CLAUDE_CODE_MAX_CONTEXT_TOKENS=1000000 (env применяется
к не-claude моделям независимо от суффикса), поэтому [1m] у Haiku-слота
стал дублирующим и убран — все три слота пикера теперь glm-5.3.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 07:01:22 +03:00
Виталий Никитенко
60b915de5f feat(setup): add ./setup.sh update CLI mode
./setup.sh update (или --update) запускает git pull --ff-only + перегенерацию
всех ai-* лаунчеров без интерактивного меню — то же, что пункт меню 7 (логика
вынесена в общую do_update). Неизвестный аргумент печатает usage и выходит
с кодом 1, без аргументов открывается меню как раньше.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 06:00:27 +03:00
Виталий Никитенко
f61f2cde84 feat(glm): switch ai-glm to GLM 5.3
glm-5.3 доступна на api.z.ai (вышла 2026-08-14, 1M контекст): opus/sonnet =
glm-5.3, haiku = glm-5.3[1m], subagent = glm-5.3, health-check ключа тоже
на 5.3. Секция OpenRouter остаётся на z-ai/glm-5.2 — там 5.3 ещё нет.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 06:00:11 +03:00
Виталий Никитенко
7304c5c84b docs(rules): document per-project GitLab tokens
GitLab access uses project access tokens, one per project, and a token from
another project answers 404 instead of 403 - a wrong token is indistinguishable
from a missing project. Nothing described where those tokens live, so agents
either guessed or gave up.

Added section 10 with the file -> project mapping (superapp-launcher,
common-library, smart_home), a working curl example, and the note that the
generic `gitlab_token` fallback is gone: helpers such as eltex-review need an
explicit --token-file.
2026-08-12 11:24:06 +03:00
Виталий Никитенко
ee32371d30 refactor(rules): simplify global agent guidance 2026-08-08 21:02:00 +03:00
Виталий Никитенко
4723d21693 fix(codex): prevent sound hook timeouts 2026-08-08 19:20:10 +03:00
Виталий Никитенко
532d70f478 fix(add-account): unhang oauth login via fifo stdin
Логин Claude.ai подвисал навсегда: claude auth login ждёт код из браузера в stdin, а хук запускал его в фоне с </dev/null, куда код вставить невозможно. Теперь /add-account поднимает логин со stdin из fifo и печатает ссылку, а /add-account <код> отдаёт код, дожидается обмена и сохраняет новый аккаунт по email из токена. Провал логина больше не маскируется под успешное сохранение текущего аккаунта, а фоновые процессы гасятся строго по своим PID вместо широкого pkill -f. Поведение закреплено пятью тестами в tests/test_fixes.sh.
2026-08-08 19:20:10 +03:00
Виталий Никитенко
eb6a7bddad feat(rules): доступ к Redmine (red.eltex.loc) через API-ключ
Правило №6: читать задачи Redmine по персональному API-ключу из
~/.config/ai-setup/redmine_key, вытаскивать ТЗ/статус/комментарии
через /issues/<N>.json?include=journals. Ключ держать только в этом
файле, не вписывать в git.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 09:04:08 +03:00
Виталий Никитенко
57857cda4d remove bundled skills; skills now come from separate repo
Удалены все кастомные скиллы из home-configs/claude/skills и логика
их деплоя (секция 6.6 ai-setup.sh для Claude и Gemini). Из README
убраны упоминания про деплой скиллов, из test_fixes.sh — тест наличия
android-скилла. Хуки аккаунтов, команда android init, правило #5 про
reusable skills и симлинк общей папки ~/.claude/skills оставлены
нетронутыми — скиллы теперь устанавливаются из отдельного репозитория.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 11:44:05 +03:00
ekaterina soloveva
0c5057bc21 require node >=18 in ai-setup, not just presence
ai-setup.sh проверял только наличие node через command -v, поэтому системный Node v12 (Ubuntu 22.04) проходил проверку и установка NodeSource 22 не запускалась. Из-за этого хук claude-notifier падал с SyntaxError на optional chaining (?.) и nullish coalescing (??), которые поддерживаются только начиная с Node 14. Теперь скрипт извлекает мажорную версию и при значении меньше 18 ставит/обновляет Node, чтобы регенерация не возвращала сломанные хуки.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-14 11:26:49 +03:00
Виталий Никитенко
c379ee8efc feat(ai-setup): /logout для ai-glm, ai-deepseek, ai-kimi
Новый UserPromptSubmit хук logout-account-hook.sh перехватывает /logout
(провайдер по AI_LAUNCHER) и /logout-glm|/logout-deepseek|/logout-kimi
(явно), удаляет сохранённый ключ провайдера. Для ai-claude /logout
отступает — работает нативный oauth-logout.

- хук: удаляет glm_key/deepseek_key или текущий kimi_keys/<current>.key
  (+.meta) с пересчётом current; exit 2 глушит нативную /logout для
  api-key провайдеров
- 3 скилла logout-{glm,deepseek,kimi} для автокомплита
- ai-setup.sh: секция деплоя 6.7.3 + хук в копирование/регистрацию
  изолированных cfg

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-14 10:10:14 +03:00
16 changed files with 495 additions and 459 deletions

View File

@@ -13,12 +13,12 @@
## Таблица маппинга
| Claude Code `/effort` | Anthropic (`ai-claude`) | DeepSeek V4 (`ai-deepseek`) | Kimi K2.7/K2.6 (`ai-kimi`) | GLM 5.2 (`ai-glm`) | OpenRouter/GPT-5.5 (`ai-openrouter`) | OpenCode Go (`ai-opencode`) |
| Claude Code `/effort` | Anthropic (`ai-claude`) | DeepSeek V4 (`ai-deepseek`) | Kimi K2.7/K2.6 (`ai-kimi`) | GLM 5.3 (`ai-glm`) | OpenRouter/GPT-5.5 (`ai-openrouter`) | OpenCode Go (`ai-opencode`) |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| `low` | нативно `low` | провайдер поднимает до `high` | thinking on | на стороне сервера | без локального маппинга | без локального маппинга |
| `low` | нативно `low` | нативно `low` | thinking on | на стороне сервера | без локального маппинга | без локального маппинга |
| `medium` | нативно `medium` | провайдер поднимает до `high` | thinking on | на стороне сервера | без локального маппинга | без локального маппинга |
| `high` | нативно `high` | нативно `high` | thinking on | на стороне сервера | без локального маппинга | без локального маппинга |
| `xhigh` | нативно `xhigh` | провайдер поднимает до `max` | thinking on | на стороне сервера | без локального маппинга | без локального маппинга |
| `xhigh` | нативно `xhigh` | провайдер поднимает до `high` | thinking on | на стороне сервера | без локального маппинга | без локального маппинга |
| `max` | нативно `max` | нативно `max` | thinking on | на стороне сервера | без локального маппинга | без локального маппинга |
Для OpenRouter текущий лаунчер не делает локального преобразования effort и отправляет
@@ -45,12 +45,13 @@ low -> medium -> high -> xhigh -> max
### DeepSeek V4
```text
high -> max
low -> high -> max
```
- 2 реальных уровня.
- `low` и `medium` фактически поднимаются до `high`.
- `xhigh` фактически поднимается до `max`.
- 3 реальных уровня.
- `low` остаётся `low` — реально снижает thinking бюджет.
- `medium` и `xhigh` фактически поднимаются до `high`.
- `max` остаётся `max` — максимальный бюджет thinking.
- Маппинг выполняется на стороне DeepSeek API.
- Дефолт `ai-deepseek`: `high`.
@@ -65,7 +66,7 @@ on / off
- Градаций глубины reasoning нет.
- Дефолт `ai-kimi`: `high`.
### GLM 5.2 (Zhipu AI)
### GLM 5.3 (Zhipu AI)
```text
high / max
@@ -99,7 +100,7 @@ Effort не преобразуется локально — thinking budget не
| Anthropic | Не нужен | - |
| DeepSeek V4 | DeepSeek API | На стороне сервера |
| Kimi K2.7/K2.6 | Moonshot API | На стороне сервера |
| GLM 5.2 | Zhipu AI API | На стороне сервера |
| GLM 5.3 | Zhipu AI API | На стороне сервера |
| OpenRouter/GPT-5.5 | Локального маппинга нет | `ai-openrouter` отправляет значение как есть |
| OpenCode Go | Локального маппинга нет | `ai-opencode` отправляет значение через routatic-proxy |
| Legacy GPT proxy | helper-маппинг `xhigh` -> `high` | `~/bin/claude-gpt-effort-proxy.py` или `~/.local/bin/claude-gpt-effort-proxy.py` |
@@ -125,4 +126,4 @@ ai-deepseek # без флага - использовать ур
- Для повседневной работы: `high` или `xhigh`.
- `max` effort имеет реальный эффект у Anthropic и DeepSeek; у Kimi и GLM это всё тот же thinking on / маппинг на стороне сервера.
- `low`/`medium` у DeepSeek, Kimi и GLM фактически не снижают reasoning.
- `low`/`medium` у Kimi и GLM фактически не снижают reasoning; у DeepSeek `low` теперь даёт реальный уровень `low` и экономит бюджет.

View File

@@ -15,6 +15,11 @@ bash setup.sh
exec bash
```
Обновление всех AI-инструментов одной командой:
```bash
./setup.sh update
```
## 2. Настроить сеть (Amnezia + ru-bypass)
Нужно один раз на каждой машине. .ru трафик идёт напрямую,

View File

@@ -17,7 +17,6 @@ home-configs/
├── GLOBAL_RULES.md # глобальные правила для всех агентов
├── claude/
│ ├── hooks/ # хуки аккаунтов Claude Code
│ ├── skills/ # кастомные скиллы для Claude Code (и Gemini)
│ └── statusline-command.sh # статусная строка Claude Code
└── network/
└── README.md # подробная документация по сетевой настройке
@@ -57,6 +56,15 @@ bash setup.sh
exec bash
```
### Обновление одной командой
```bash
./setup.sh update # или: ./setup.sh --update
```
То же, что пункт меню `7) Обновить`: `git pull --ff-only` + перегенерация всех
`ai-*` лаунчеров через `scripts/ai-setup.sh`. Без аргументов открывается меню.
## Сеть: ru-bypass + kill switch
Полная документация: [`home-configs/network/README.md`](home-configs/network/README.md)
@@ -152,7 +160,7 @@ bash tests/test_network.sh # полные тесты
- `ai-gpt` - нативный OpenAI Codex CLI
- `ai-deepseek` - Claude Code через DeepSeek API
- `ai-kimi` - Claude Code через официальный Kimi Code API (`api.kimi.com/coding`)
- `ai-glm` - Claude Code через Zhipu AI GLM 5.2 API (`api.z.ai/api/anthropic`)
- `ai-glm` - Claude Code через Zhipu AI GLM 5.3 API (`api.z.ai/api/anthropic`)
- `ai-openrouter` - Claude Code через OpenRouter (GPT-5.5, Grok, Qwen, GLM 5.2 и др.)
- `ai-opencode` - Claude Code через OpenCode Go + routatic-proxy (DeepSeek, Kimi, Qwen, GLM, MiniMax, MiMo)
- `ai-gemini` - нативный Antigravity CLI `agy`
@@ -164,7 +172,6 @@ bash tests/test_network.sh # полные тесты
Также устанавливается:
- `~/.config/ai-setup/global_rules.md` и native rule-файлы (`~/.claude/CLAUDE.md`, `~/.codex/AGENTS.md`, `~/.kimi-code/AGENTS.md`, `~/.gemini/GEMINI.md`)
- Скиллы из `home-configs/claude/skills/` в `~/.claude/skills/` и `~/.gemini/config/plugins/local-setup/skills/`
## Android CLI
@@ -226,9 +233,9 @@ android init
## Правила агентов
В `home-configs/GLOBAL_RULES.md` - правила Карпати (Think Before Coding, Simplicity First,
Surgical Changes, Goal-Driven Execution) плюс пользовательские правила (отвечать по-русски,
не коммитить без команды, не делать git add без команды и др.).
В `home-configs/GLOBAL_RULES.md` - компактные правила о границах автономности, минимальных
изменениях, пропорциональной проверке, работе с Git и контекстом проекта, а также пользовательские
настройки: русский язык, доступ к Redmine и запрет на commit/staging без явной команды.
`scripts/ai-setup.sh` копирует их в native rule-файлы всех CLI. Лаунчеры обновляют их при каждом запуске.

View File

@@ -1,92 +1,92 @@
# Global AI Agent Rules
Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
Use these defaults across projects, then apply any more specific repository instructions. Prefer clear outcomes and proportional safeguards over process for its own sake.
**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
## 1. Resolve Intent Without Needless Blocking
## 1. Think Before Coding
- Inspect the available context before asking the user for information.
- Ask a focused question only when an ambiguity would materially change the result, create meaningful risk, or cannot be resolved from the repository or task context.
- Otherwise choose the simplest reasonable interpretation and state only assumptions that materially affect the result.
- Surface important tradeoffs and recommend a simpler or safer approach when it better serves the user's goal.
**Don't assume. Don't hide confusion. Surface tradeoffs.**
## 2. Keep Changes Minimal and Scoped
Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.
- Implement only the requested behavior and the support required to make it correct.
- Do not add speculative features, single-use abstractions, unrequested configurability, or handling for implausible scenarios.
- Preserve existing public behavior and local conventions unless the task requires changing them.
- Do not refactor, reformat, or clean up unrelated code. Mention unrelated issues only when they are relevant risks or blockers.
- Remove imports, variables, functions, files, or comments made obsolete by your own changes; leave pre-existing dead code alone unless asked.
- Every changed line should trace to the requested outcome.
## 2. Simplicity First
## 3. Act Autonomously Within the Request
**Minimum code that solves the problem. Nothing speculative.**
- For requests to answer, explain, review, diagnose, or plan, inspect the relevant materials and report the result. Do not implement changes unless the request also asks for them.
- For requests to change, build, or fix, perform safe in-scope local edits and validation without asking for routine confirmation.
- Ask before destructive or difficult-to-recover actions, external writes or publication, purchases, or a material expansion of scope.
- Exception for Eltex merge-request reviews: a bare review request or explicit `eltex-review` invocation authorizes the skill's documented GitLab writes, including inline discussions, approval, and its thank-you note. Explicit chat-only wording keeps the review read-only.
- Preserve unrelated user changes and adapt to a dirty working tree. Never discard or overwrite work you did not create.
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If you write 200 lines and it could be 50, rewrite it.
## 4. Plan and Verify Proportionally
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
- Define observable success criteria before changing code.
- For non-trivial multi-step work, keep a brief plan whose steps include their verification. Skip planning ceremony for simple tasks.
- For a bug fix, reproduce the failure first when feasible. Add a focused regression test when it provides durable value and the repository has an appropriate test layer.
- Run the smallest relevant checks first, then broader checks when the change's risk justifies them.
- Do not claim completion without fresh evidence. Report the commands run, their results, and anything that remains unverified.
## 3. Surgical Changes
## 5. Keep Git Changes Reviewable
**Touch only what you must. Clean up only your own mess.**
- Never run `git commit` unless the user explicitly asks for a commit.
- Do not stage changes unless the user explicitly asks for staging, committing, or another operation that requires it. Do not disturb changes already staged by the user.
- Leave tracked edits unstaged so they remain visible in `git diff`.
- Remember that untracked files do not appear in ordinary `git diff`. Show them with `git status --short`, list their paths in the handoff, and use `git diff --no-index -- /dev/null <path>` when a patch view is useful.
- Before handing off, inspect both `git diff` and `git status --short` and distinguish your changes from unrelated existing work.
When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.
## 6. Load Relevant Project Context
When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.
- Before acting, read the applicable agent instruction files and the project documentation directly relevant to the task.
- Follow referenced documents when they are needed to understand requirements, commands, architecture, or validation. Do not scan unrelated Markdown files indiscriminately.
- Use the repository's existing tools, conventions, and test commands unless the task requires otherwise.
The test: Every changed line should trace directly to the user's request.
## 7. Communication Style
## 4. Goal-Driven Execution
- Reply in Russian, use informal "ты", and communicate like a friendly programmer teammate.
- Lead with the outcome and keep the explanation concise while preserving evidence, material caveats, and next steps.
- Keep identifiers, commands, exact error messages, and source quotations in their original language when accuracy matters.
- Humor, irony, and swearing are welcome when they fit the conversation; clarity and respect come first.
**Define success criteria. Loop until verified.**
## 8. Reusable Skills
Transform tasks into verifiable goals:
- "Add validation" -> "Write tests for invalid inputs, then make them pass"
- "Fix the bug" -> "Write a test that reproduces it, then make it pass"
- "Refactor X" -> "Ensure tests pass before and after"
- After completing the current task, propose a focused reusable skill only when the user has repeated a workflow and reuse would clearly help.
- Do not interrupt active work to create a skill, and do not create or edit skill files without explicit user approval.
- If approved skill changes live outside the current repository, report their exact paths and how the user can inspect them.
For multi-step tasks, state a brief plan:
## 9. Redmine (red.eltex.loc)
- When the request or an Eltex branch identifies a Redmine issue, read its specification, status, and comments before implementing. Eltex branches commonly start with the issue number (for example, `485448_keyboard_opening_fix` maps to issue `485448`).
- Use the personal API key stored only in `~/.config/ai-setup/redmine_key` (mode 600):
```bash
curl -fsS -H "X-Redmine-API-Key: $(cat ~/.config/ai-setup/redmine_key)" \
"https://red.eltex.loc/issues/<N>.json?include=journals"
```
1. [Step] -> verify: [check]
2. [Step] -> verify: [check]
3. [Step] -> verify: [check]
- Read `issue.description`, `issue.status.name`, and recent non-empty `issue.journals[].notes`. If the key is missing or the request fails, report that instead of guessing the task requirements.
- Never print, log, or write the API key into repository files.
## 10. GitLab (gitlab.eltex.loc)
- GitLab access uses **per-project** tokens stored in `~/.config/ai-setup/` (mode 600). Each one is a project access token and works only for its own project:
| File | Project | id |
| :--- | :--- | :--- |
| `gitlab_token_superapp` | `voip/vp-apps/superapp-launcher` | 4928 |
| `gitlab_token_common_library` | `voip/vp-apps/common-library` | 4825 |
| `gitlab_token_smart_home` | `android_apps/smart_home` | 1409 |
- Pick the file matching the project you are working with. A token from another project returns HTTP 404, not 403, so a wrong token looks exactly like a missing project — check the token before concluding the resource does not exist.
```bash
curl -fsS -H "PRIVATE-TOKEN: $(cat ~/.config/ai-setup/gitlab_token_superapp)" \
"https://gitlab.eltex.loc/api/v4/projects/4928/merge_requests/241"
```
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
---
**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
# Global Rules for All AI Agents
The rules below are mandatory for every interaction and task. They are intentionally placed after the general coding guidelines above, but they have higher priority when a conflict exists.
1. **Communication style:**
Always reply in Russian, in a friendly peer-to-peer tone, using informal "ты". Appropriate swearing, humor, sarcasm, and irony are allowed and welcome. Communicate like a live programmer teammate, not like a dry robot.
2. **No commits without an explicit request:**
Never run `git commit` unless the user has directly and unambiguously asked for it. The final commit always remains with the user, or is made strictly by the user's command.
3. **Plain git diff visibility:**
All changes must remain visible to the user through the standard `git diff` command. Leave modified files in the working directory unstaged. Do not add files to the Git index with `git add` unless the user explicitly asks for staging, committing, or another action that requires staging, because staging hides changes from plain `git diff`.
4. **Project context:**
At the start of work, pay close attention to all provided project `.md` files, because they are provided automatically and contain the current repository's context and specifics.
5. **Reusable skills:**
When the user repeats the same instruction, output format, correction, or workflow, treat it as a candidate for a reusable skill.
Do not interrupt active work just to create a skill. Finish the current task first, then briefly propose the skill name, trigger description, and what files or tools it should contain.
Do not create or edit skill files silently. Create or update a skill only after explicit user approval.
Keep skills focused: prefer several small skills over one broad skill. A useful skill should have a precise description for when to use it, short instructions for how to act, and reusable tools, templates, references, or examples when they make the result more stable.
If skill files are outside the current git repository, clearly state the exact paths changed and how the user can inspect them, because those changes are not visible in the project `git diff`.
- There is no generic `gitlab_token` fallback any more. Tools that accept an explicit token path (for example the `eltex-review` helper) must be given `--token-file <path>`.
- `local.properties` in superapp-launcher also holds `gitlab.token` and `redmine.apiKey`; it is gitignored and must stay that way.
- Never print, log, or write these tokens into repository files.

View File

@@ -6,7 +6,7 @@ The custom statusline script renders **only ASCII-safe characters and ANSI color
- ASCII brackets `[ ]` for git branch and effort level
- ANSI 256-color escape sequences for model names, effort levels, and rate-limit percentages
- The `¥` symbol (U+00A5) for CNY balance in DeepSeek output
- The `$` symbol for the DeepSeek balance (USD only)
It does **not** use Nerd Font glyphs, powerline separators, or emoji.

View File

@@ -1,10 +1,13 @@
#!/usr/bin/env bash
# Copyright (c) 2026 Виталий Никитенко. MIT License.
# UserPromptSubmit hook: перехватывает /add-account.
# 1) сохраняет текущий аккаунт по его реальному email (account-email.sh)
# 2) запускает oauth-логин в фоне (открывает браузер)
# 3) после логина фоновый процесс сам определяет email нового аккаунта по токену
# и сохраняет его credentials + делает current
# UserPromptSubmit hook: перехватывает /add-account и /add-account <код>.
# Логин в два шага, целиком в этом же терминале (без второго окна):
# /add-account — сохраняет текущий аккаунт, поднимает фоновый
# claude auth login со stdin из fifo и печатает ссылку;
# /add-account <код> — отдаёт код из браузера в fifo, ждёт обмена, определяет
# email нового аккаунта по токену, сохраняет и делает current.
# CLI отдаёт redirect_uri на platform.claude.com и ждёт код в stdin — при
# </dev/null он висит вечно, поэтому stdin держит fifo, а не закрытый дескриптор.
input=$(cat)
prompt=$(echo "$input" | jq -r '.user_prompt // .prompt // empty' 2>/dev/null)
@@ -22,10 +25,16 @@ case "$LAUNCHER" in
ACCOUNTS_DIR="$HOME/.claude/accounts"
CURRENT_FILE="$ACCOUNTS_DIR/current"
EMAIL_HELPER="$HOME/.claude/hooks/account-email.sh"
FIFO="$HOME/.claude/add-account.fifo"
LOG="$HOME/.claude/add-account.log"
LOGIN_PID_FILE="$HOME/.claude/add-account.login.pid"
HOLDER_PID_FILE="$HOME/.claude/add-account.holder.pid"
mkdir -p "$ACCOUNTS_DIR"
# Сохраняем текущий активный аккаунт под его реальным email (по токену)
# Сохраняем текущий активный аккаунт под его реальным email (по токену),
# чтобы логин новым аккаунтом не затёр его креды безвозвратно.
cur_email=""
if [ -f "$CREDS" ]; then
cur_email=$(bash "$EMAIL_HELPER" "$CREDS" 2>/dev/null)
if [ -n "$cur_email" ]; then
@@ -35,23 +44,99 @@ case "$LAUNCHER" in
fi
fi
# Фоновый процесс: логин нового аккаунта + автосохранение после успеха.
# claude auth login ждёт авторизации в браузере и завершается после неё,
# затем определяем email нового аккаунта по токену (через API) и сохраняем.
(
claude auth login --claudeai </dev/null >/tmp/claude-add-account.log 2>&1
# Процессы гасим строго по своим PID: pkill -f "claude auth login" выкосил бы
# любой процесс, в чьей командной строке встретилась эта подстрока.
pid_of() { # $1=pid-файл, $2=ожидаемое имя процесса; печатает живой pid
[ -f "$1" ] || return 1
pid=$(cat "$1" 2>/dev/null)
[ -n "$pid" ] || return 1
[ "$(ps -p "$pid" -o comm= 2>/dev/null)" = "$2" ] || return 1
printf '%s' "$pid"
}
login_alive() { pid_of "$LOGIN_PID_FILE" claude >/dev/null; }
# Останавливаем предыдущую попытку логина, чтобы не копить висящие процессы.
stop_login() {
pid=$(pid_of "$LOGIN_PID_FILE" claude) && kill "$pid" 2>/dev/null
pid=$(pid_of "$HOLDER_PID_FILE" sleep) && kill "$pid" 2>/dev/null
rm -f "$LOGIN_PID_FILE" "$HOLDER_PID_FILE" "$FIFO"
}
code=$(echo "$normalized" | awk '{print $2}')
# ── Шаг 2: код из браузера ───────────────────────────────────────
if [ -n "$code" ]; then
if ! login_alive || [ ! -p "$FIFO" ]; then
echo "Сессия логина не запущена (или уже закрылась). Начни заново: /add-account" >&2
stop_login
exit 2
fi
printf '%s\n' "$code" > "$FIFO"
# Ждём, пока CLI обменяет код на токен и завершится.
for _ in $(seq 1 60); do
login_alive || break
sleep 0.5
done
stop_login
if grep -q "Login failed" "$LOG" 2>/dev/null; then
echo "$(grep -o 'Login failed.*' "$LOG" | tail -1)" >&2
echo "Код одноразовый и живёт недолго — начни заново: /add-account" >&2
exit 2
fi
new_email=$(bash "$EMAIL_HELPER" "$CREDS" 2>/dev/null)
if [ -n "$new_email" ] && [ -f "$CREDS" ]; then
if [ -z "$new_email" ]; then
echo "✗ Логин завершился, но email аккаунта определить не удалось. Аккаунт не сохранён." >&2
exit 2
fi
cp "$CREDS" "$ACCOUNTS_DIR/${new_email}.credentials.json"
chmod 600 "$ACCOUNTS_DIR/${new_email}.credentials.json"
echo "$new_email" > "$CURRENT_FILE"
echo "SAVED: $new_email" >> /tmp/claude-add-account.log
if [ "$new_email" = "$cur_email" ]; then
echo "⚠ Вошёл тот же аккаунт ($new_email) — новых аккаунтов не добавилось." >&2
else
echo "✓ Аккаунт $new_email добавлен и стал активным. /switch-account — переключение по кругу." >&2
fi
) &
exit 2
fi
# ── Шаг 1: запуск логина и ссылка ────────────────────────────────
stop_login
mkfifo -m 600 "$FIFO" || { echo "Не удалось создать $FIFO" >&2; exit 2; }
: > "$LOG"
# stdin из fifo: CLI ждёт код в stdin, закрытый дескриптор его подвешивает.
# Держатель fifo не даёт CLI получить EOF и задаёт таймаут попытки (15 мин).
claude auth login --claudeai < "$FIFO" > "$LOG" 2>&1 &
echo $! > "$LOGIN_PID_FILE"
disown
sleep 900 > "$FIFO" 2>/dev/null &
echo $! > "$HOLDER_PID_FILE"
disown
# exit 0: Claude загружает скилл add-account и говорит что делать
exit 0
url=""
for _ in $(seq 1 40); do
url=$(grep -o 'https://claude\.com/[^ ]*' "$LOG" 2>/dev/null | head -1)
[ -n "$url" ] && break
sleep 0.5
done
if [ -z "$url" ]; then
stop_login
echo "Не дождался ссылки для входа. Лог: $LOG" >&2
exit 2
fi
echo "Авторизуйся в браузере (ссылка ниже), скопируй код и пришли его сюда: /add-account <код>" >&2
echo "" >&2
echo "$url" >&2
exit 2
;;
kimi)

View File

@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Copyright (c) 2026 Виталий Никитенко. MIT License.
# UserPromptSubmit hook: перехватывает /logout, /logout-glm, /logout-deepseek, /logout-kimi.
# Удаляет сохранённый API-ключ провайдера, чтобы при следующем запуске лаунчер
# запросил новый.
# /logout-glm | /logout-deepseek | /logout-kimi — явно указанный провайдер.
# /logout (без суффикса) — провайдер по AI_LAUNCHER (glm/deepseek/kimi).
# Для ai-claude и прочих лаунчеров /logout отступает (exit 0) — пусть работает
# нативный oauth-logout. exit 2 после удаления: LLM не нужна, и нативная
# /logout не пытается сделать бессмысленный oauth-logout для api-key провайдеров.
input=$(cat)
prompt=$(echo "$input" | jq -r '.user_prompt // .prompt // empty' 2>/dev/null)
normalized=$(echo "$prompt" | sed 's|^[[:space:]]*/||; s|[[:space:]]*$||')
cmd=$(echo "$normalized" | awk '{print $1}')
target=""
case "$cmd" in
logout-glm) target=glm ;;
logout-deepseek) target=deepseek ;;
logout-kimi) target=kimi ;;
logout)
case "${AI_LAUNCHER:-claude}" in
glm|deepseek|kimi) target="$AI_LAUNCHER" ;;
*) exit 0 ;;
esac
;;
*) exit 0 ;;
esac
CFG="$HOME/.config/ai-setup"
case "$target" in
glm)
rm -f "$CFG/glm_key"
echo "✓ GLM ключ удалён. Перезапусти ai-glm, чтобы ввести новый." >&2
;;
deepseek)
rm -f "$CFG/deepseek_key"
echo "✓ DeepSeek ключ удалён. Перезапусти ai-deepseek, чтобы ввести новый." >&2
;;
kimi)
KEYS_DIR="$CFG/kimi_keys"
current=$(cat "$KEYS_DIR/current" 2>/dev/null || true)
if [ -n "$current" ]; then
rm -f "$KEYS_DIR/${current}.key" "$KEYS_DIR/${current}.meta"
fi
# Пересчёт current: переключаемся на первый оставшийся ключ либо сбрасываем.
mapfile -t keys < <(ls "$KEYS_DIR"/*.key 2>/dev/null | xargs -I{} basename {} .key | sort)
if [ "${#keys[@]}" -gt 0 ]; then
echo "${keys[0]}" > "$KEYS_DIR/current"
echo "✓ Kimi ключ (${current:-нет}) удалён. Активен: ${keys[0]}. Перезапусти ai-kimi." >&2
else
rm -f "$KEYS_DIR/current"
echo "✓ Kimi ключ (${current:-нет}) удалён. Других ключей нет. Перезапусти ai-kimi." >&2
fi
;;
esac
exit 2

View File

@@ -1,12 +0,0 @@
---
name: add-account
description: Add a new account or API key (handled by UserPromptSubmit hook, no LLM needed)
---
Хук уже обработал запрос. Ответь ТОЛЬКО этим текстом (без markdown, без лишних слов):
Для Claude.ai: браузер открыт — авторизуйся там. После авторизации новый аккаунт сохранится автоматически и сразу станет активным (Claude Code на Linux перечитывает токен на лету).
Для Kimi: укажи API-ключ в том же сообщении: `/add-account sk-...`. Хук проверит и сохранит ключ; ai-kimi перезапустится с ним.
/switch-account переключает между всеми сохранёнными аккаунтами/ключами по кругу.

View File

@@ -1,87 +0,0 @@
---
name: android-cli
description: Google Android CLI - официальный терминальный инструмент для Android-разработки, SDK, эмуляторов и проектов
---
# Android CLI
## Назначение
Google Android CLI (preview) - официальный инструмент от Google для Android-разработки через терминал. Он создан специально для AI-агентов, CI/CD и автоматизации. Позволяет управлять SDK, создавать проекты, запускать эмуляторы и собирать APK без необходимости вручную разбираться с `sdkmanager`, `adb` и Gradle.
## Установка и обновление
```bash
# Установка (выполняется ai-setup.sh)
curl -fsSL https://dl.google.com/android/cli/latest/linux_x86_64/install.sh | bash
# Обновление
android update
```
## Ключевые команды
| Команда | Назначение |
|---------|------------|
| `android --version` | Версия Android CLI |
| `android info` | Информация об SDK, путях, эмуляторах |
| `android sdk list` | Список доступных SDK-пакетов |
| `android sdk install <package>` | Установить пакет SDK |
| `android create --name="App" --output=./app` | Создать новый Android-проект |
| `android emulator create` | Создать виртуальное устройство |
| `android emulator start` | Запустить эмулятор |
| `android run --apks <path>` | Установить и запустить APK на устройстве/эмуляторе |
| `android init` | Развернуть skills для AI-агентов в `~/.claude/skills/` |
| `android update` | Обновить сам Android CLI |
## Workflow с Claude Code
1. **Проверь окружение**:
```bash
android info
```
2. **Установи нужные SDK-компоненты**:
```bash
android sdk install platforms/android-35 build-tools/35.0.0
```
3. **Создай проект** (если нужен новый):
```bash
android create --name="MyApp" --output=./myapp
```
4. **Собери проект**:
```bash
./gradlew assembleDebug
```
5. **Запусти на эмуляторе или устройстве**:
```bash
android emulator start
android run --apks app/build/outputs/apk/debug/app-debug.apk
```
## Когда использовать Android CLI
- Для управления SDK и установки build-tools/platforms без Android Studio.
- Для создания новых Android-проектов из терминала.
- Для запуска эмулятора и установки APK одной командой.
- Для работы в CI/CD или внутри AI-агентов.
## Когда НЕ нужен Android CLI
- Для визуального редактирования UI/Layout - используй Android Studio.
- Для отладки с breakpoints, Layout Inspector, Compose Preview - используй Android Studio.
- Для сложного рефакторинга больших проектов - используй Claude Code в паре с Android Studio.
## Ограничения
- **Preview-версия**: API и команды могут меняться. Обновляй через `android update`.
- **Windows**: `android emulator` отключён в v0.7.
- **Существующий SDK**: если уже установлен Android Studio или `sdkmanager`, Android CLI может использовать тот же SDK или создать новый в `~/.android/sdk`. Проверяй активный путь через `android info`.
## Полезные ссылки
- Официальная документация: https://d.android.com/tools/agents
- Android CLI skills: https://github.com/android/skills

View File

@@ -1,62 +0,0 @@
---
name: el-review-heavy
description: Use when пользователь запрашивает тяжелое code-review между двумя Git-ветками с диффом в стиле GitLab (от merge-base)
---
# Eltex Review Heavy
## Overview
Тяжелое ревью диффа между двумя Git-ветками в стиле GitLab Merge Request (от merge-base). Запускает полный `/code-review` с кучей агентов.
## When to Use
- Пользователь просит "поревьюй ветку feature относительно master" тщательно
- Нужен дифф как на GitLab (без лишних изменений из целевой ветки)
- Формат вызова: `/el-review-heavy <наша-ветка-с-изменениями> <целевая-ветка>`
## Workflow
1. Определи аргументы:
- `source` — первая ветка (наша, с изменениями, которую ревьюим)
- `target` — вторая ветка (целевая, в которую мерж-реквест)
2. Выполни `git fetch origin` — обнови remote refs
3. Если текущая checkout-ветка == `source`, выполни `git pull --ff-only origin source` — обнови локальную ветку
4. Построй дифф от merge-base: `git diff origin/target...origin/source > /tmp/el-review-heavy.diff` (три точки!)
5. Прочитай файл `/tmp/el-review-heavy.diff`
6. Запусти скилл `code-review` с этим файлом как аргумент
7. Полученные findings переформатируй:
- Пронумеруй проблемы
- Оставь только критические замечания
- Для каждой предложи готовый дифф с исправлением
- Объясни простым языком
## Примеры вызова
```
/el-review-heavy feature main
/el-review-heavy my-fix develop
/el-review-heavy TASK-123-payment-screen master
```
## Ошибки и крайние случаи
- Если ветка не существует на remote - сообщи пользователю и не продолжай
- Если дифф пустой - сообщи "изменений между ветками нет" и не продолжай
- Если аргументы не указаны - попроси уточнить: `/el-review-heavy <source-ветка> <target-ветка>`
## Формат вывода
```
## Проблема N: [краткое название]
**Где:** `file.kt:123`
**Что не так:** простым языком, зачем это плохо
**Исправление:**
```diff
- старая строка
+ новая строка
```
```

View File

@@ -1,63 +0,0 @@
---
name: el-review
description: Use when пользователь запрашивает легкое/быстрое code-review между двумя Git-ветками с диффом в стиле GitLab (от merge-base). Триггеры: "быстрое ревью", "легкое ревью", "/el-review".
---
# Eltex Review
## Overview
Лёгкое ревью диффа между двумя Git-ветками в стиле GitLab Merge Request (от merge-base). **Claude делает ревью сам, без multi-agent workflows** — читает дифф и выдаёт только критические проблемы с готовыми исправлениями.
## When to Use
- Пользователь просит "поревьюй ветку feature относительно master" быстро
- Пользователь говорит "быстрое ревью", "лёгкое ревью", "поверхностное ревью"
- Нужен дифф как на GitLab (без лишних изменений из целевой ветки)
- Формат вызова: `/el-review <наша-ветка-с-изменениями> <целевая-ветка>`
## Workflow
1. Определи аргументы:
- `source` — первая ветка (наша, с изменениями, которую ревьюим)
- `target` — вторая ветка (целевая, в которую мерж-реквест)
2. Выполни `git fetch origin` — обнови remote refs
3. Если текущая checkout-ветка == `source`, выполни `git pull --ff-only origin source` — обнови локальную ветку
4. Построй дифф от merge-base: `git diff origin/target...origin/source > /tmp/el-review.diff` (три точки!)
5. Прочитай файл `/tmp/el-review.diff`
6. **Сделай инлайн-ревью сам** — не запускай `/review`, не спавни multi-agent workflows, не делай deep cross-file investigations:
- Найди только критические проблемы: баги, утечки, падения, гонки, ошибки в бизнес-логике, нарушения инвариантов
- **Не репорти:** форматирование, именование переменных, стиль кода, предложения по рефакторингу (если это не баг)
- Для каждой проблемы сразу пиши готовый diff с исправлением
- Объясняй кратко, на русском, простым языком
- Если критических проблем нет — напиши **«Критических проблем не найдено»** и остановись
## Примеры вызова
```
/el-review feature main
/el-review my-fix develop
/el-review TASK-123-payment-screen master
```
## Ошибки и крайние случаи
- Если ветка не существует на remote - сообщи пользователю и не продолжай
- Если дифф пустой - сообщи "изменений между ветками нет" и не продолжай
- Если аргументы не указаны - попроси уточнить: `/el-review <source-ветка> <target-ветка>`
## Формат вывода
```
## Проблема N: [краткое название]
**Где:** `file.kt:123`
**Что не так:** простым языком, зачем это плохо
**Исправление:**
```diff
- старая строка
+ новая строка
```
```

View File

@@ -1,8 +0,0 @@
---
name: switch-account
description: Switch to next account or API key (handled by UserPromptSubmit hook, no LLM needed)
---
Переключение аккаунта/ключа уже выполнено хуком до того, как ты это читаешь.
Ответь ровно одним символом: `✓`
Никаких инструментов. Никаких объяснений. Только `✓`.

View File

@@ -4,6 +4,12 @@ input=$(cat)
cwd=$(echo "$input" | jq -r '.cwd')
model=$(echo "$input" | jq -r '.model.display_name // empty')
model_id=$(echo "$input" | jq -r '.model.id // empty')
# Суффикс [1m] в отображении не нужен: окно контекста задаётся
# CLAUDE_CODE_MAX_CONTEXT_TOKENS, а не суффиксом модели
model="${model/\[1m\]/}"
model="${model% \[1M\]}"
model="${model% (1M context)}"
model_id="${model_id/\[1m\]/}"
five_pct=$(echo "$input" | jq -r '.rate_limits.five_hour.used_percentage // empty')
five_reset=$(echo "$input" | jq -r '.rate_limits.five_hour.resets_at // empty')
week_pct=$(echo "$input" | jq -r '.rate_limits.seven_day.used_percentage // empty')
@@ -11,15 +17,18 @@ week_reset=$(echo "$input" | jq -r '.rate_limits.seven_day.resets_at // empty')
ctx_pct=$(echo "$input" | jq -r '.context_window.used_percentage // empty')
# Разделитель сегментов: жирная серая средняя точка ·
_sep() { printf " \033[1m\033[38;5;240m·\033[00m "; }
# Цвет effort: насыщенные, глубже чем пастельные (jewel tones)
_effort_color() {
case "$1" in
low) printf '\033[38;5;220m[low]\033[00m' ;; # золотой
medium) printf '\033[38;5;50m[medium]\033[00m' ;; # насыщенный teal
high) printf '\033[38;5;38m[high]\033[00m' ;; # глубокий голубой
xhigh) printf '\033[38;5;206m[xhigh]\033[00m' ;; # насыщенный фиолетовый
max) printf '\033[38;5;210m[\033[38;5;220mm\033[38;5;114ma\033[38;5;50mx\033[38;5;206m]\033[00m' ;; # радуга
*) printf '\033[38;5;252m[%s]\033[00m' "$1" ;;
low) printf '\033[38;5;220mlow\033[00m' ;; # золотой
medium) printf '\033[38;5;50mmedium\033[00m' ;; # насыщенный teal
high) printf '\033[38;5;38mhigh\033[00m' ;; # глубокий голубой
xhigh) printf '\033[38;5;206mxhigh\033[00m' ;; # насыщенный фиолетовый
max) printf '\033[38;5;220mm\033[38;5;114ma\033[38;5;50mx\033[38;5;206m\033[00m' ;; # радуга
*) printf '\033[38;5;252m%s\033[00m' "$1" ;;
esac
}
@@ -29,6 +38,7 @@ _brand_color() {
deepseek) printf '\033[38;5;69m' ;; # DeepSeek фирменный синий
claude) printf '\033[38;5;173m' ;; # Anthropic оранжевый
kimi) printf '\033[38;5;81m' ;; # Kimi голубой
glm) printf '\033[38;5;223m' ;; # Z.ai кремовый (бренд-фон z.ai, #FFE4B5)
openrouter) printf '\033[38;5;135m' ;; # OpenRouter фиолетовый
*) printf '\033[38;5;223m' ;; # кремовый (fallback)
esac
@@ -39,7 +49,7 @@ branch=$(git -C "$cwd" --no-optional-locks symbolic-ref --short HEAD 2>/dev/null
short_cwd="${cwd/#$HOME/\~}"
printf "\033[38;5;252m%s\033[00m" "$short_cwd"
[ -n "$branch" ] && printf " \033[38;5;252m[%s]\033[00m" "$branch"
[ -n "$branch" ] && { _sep; printf "\033[38;5;111m%s\033[00m" "$branch"; }
if [ -n "$model" ]; then
brand_color=$(_brand_color "${AI_LAUNCHER:-}")
effort=$(echo "$input" | jq -r ".effort.level // empty")
@@ -84,18 +94,20 @@ if [ -n "$model" ]; then
fi
fi
fi
[ -n "$account" ] && printf " %s[%s]\033[00m" "$brand_color" "$account"
[ -n "$account" ] && { _sep; printf "%s%s\033[00m" "$brand_color" "$account"; }
fi
# Аккаунт/ключ Kimi — показываем alias (account1/account2/...).
if [ "${AI_LAUNCHER:-}" = "kimi" ]; then
kimi_account=$(cat "$HOME/.config/ai-setup/kimi_keys/current" 2>/dev/null)
[ -n "$kimi_account" ] && printf " %s[%s]\033[00m" "$brand_color" "$kimi_account"
[ -n "$kimi_account" ] && { _sep; printf "%s%s\033[00m" "$brand_color" "$kimi_account"; }
fi
if [ -n "$effort" ]; then
_sep
printf "%s%s " "$brand_color" "$model"
_effort_color "$effort"
else
_sep
printf "%s%s\033[00m" "$brand_color" "$model"
fi
fi
@@ -138,7 +150,7 @@ if [[ "$model_id" == *deepseek* ]]; then
cache_file="$HOME/.cache/ai-setup/deepseek_balance"
if [ -f "$cache_file" ]; then
balance=$(head -1 "$cache_file")
[ -n "$balance" ] && printf " \033[38;5;78m%s\033[00m" "$balance"
[ -n "$balance" ] && { _sep; printf "\033[38;5;78m%s\033[00m" "$balance"; }
fi
# Фоновое обновление баланса (не чаще раза в 30 секунд)
@@ -159,13 +171,12 @@ if [[ "$model_id" == *deepseek* ]]; then
import sys, json
d = json.load(sys.stdin)
infos = d.get('balance_infos', [])
symbols = {'USD': '\$', 'CNY': '\u00a5'}
parts = []
for info in infos:
curr = info.get('currency', '')
if info.get('currency', '').upper() != 'USD':
continue
total = info.get('total_balance', '0')
sym = symbols.get(curr, curr)
parts.append(f'{sym}{total}')
parts.append(f'\${total}')
if parts:
print(' '.join(parts))
" 2>/dev/null)
@@ -182,7 +193,7 @@ elif [ "${AI_LAUNCHER:-}" = "openrouter" ]; then
cache_file="$HOME/.cache/ai-setup/openrouter_balance"
if [ -f "$cache_file" ]; then
balance=$(head -1 "$cache_file")
[ -n "$balance" ] && printf " \033[38;5;78m%s\033[00m" "$balance"
[ -n "$balance" ] && { _sep; printf "\033[38;5;78m%s\033[00m" "$balance"; }
fi
# Фоновое обновление баланса (не чаще раза в 30 секунд)
@@ -247,13 +258,13 @@ else
five_int=$(printf '%.0f' "$five_pct")
remaining=$(fmt_remaining "$five_reset")
color=$(pct_color "$five_int")
printf " %s%s:%s%%\033[00m" "$color" "$remaining" "$five_int"
_sep; printf "%s%s:%s%%\033[00m" "$color" "$remaining" "$five_int"
fi
if [ -n "$week_pct" ] && [ -n "$week_reset" ]; then
week_int=$(printf '%.0f' "$week_pct")
remaining=$(fmt_remaining "$week_reset")
color=$(pct_color "$week_int")
printf " %s%s:%s%%\033[00m" "$color" "$remaining" "$week_int"
_sep; printf "%s%s:%s%%\033[00m" "$color" "$remaining" "$week_int"
fi
fi
@@ -263,7 +274,7 @@ fi
if [ -n "$ctx_pct" ]; then
ctx_int=$(printf '%.0f' "$ctx_pct")
color=$(pct_color "$ctx_int")
printf " %sctx:%s%%\033[00m" "$color" "$ctx_int"
_sep; printf "%sctx:%s%%\033[00m" "$color" "$ctx_int"
# Звуковой сигнал при первом достижении 60%
alert_file="$HOME/.cache/ai-setup/ctx_alert_state"

View File

@@ -94,8 +94,19 @@ fi
# ── 1. Node.js ───────────────────────────────────────────────
info "Проверяю Node.js..."
if ! command -v node &>/dev/null; then
# Хуки (claude-notifier и др.) используют optional chaining (?.) и nullish
# coalescing (??) — нужен Node >=18. Проверяем не только наличие node, но и
# мажорную версию, иначе системный v12 (Ubuntu 22.04) проходит проверку, а хуки падают.
node_major=0
if command -v node &>/dev/null; then
node_major="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
fi
if [ "${node_major:-0}" -lt 18 ]; then
if [ "${node_major:-0}" -gt 0 ]; then
info "Найден Node.js v${node_major}, нужен >=18. Обновляю..."
else
info "Пытаюсь установить Node.js..."
fi
if command -v brew &>/dev/null; then
brew install node
elif command -v apt-get &>/dev/null; then
@@ -372,40 +383,6 @@ cp "$CONFIG_DIR/global_rules.md" "$HOME/.gemini/GEMINI.md"
cp "$CONFIG_DIR/global_rules.md" "$HOME/.cursorrules"
success "Native rule-файлы обновлены"
# ── 6.6. Деплой Claude и Gemini skills ───────────────────────
info "Обновляю skills для Claude и Gemini..."
SKILLS_SRC="$SCRIPT_DIR/home-configs/claude/skills"
CLAUDE_SKILLS_DST="$HOME/.claude/skills"
GEMINI_SKILLS_DST="$HOME/.gemini/config/plugins/local-setup/skills"
if [ -d "$SKILLS_SRC" ]; then
mkdir -p "$CLAUDE_SKILLS_DST" "$GEMINI_SKILLS_DST"
# Для Gemini нужен plugin.json, чтобы плагин со скилами загрузился
GEMINI_PLUGIN_DIR="$HOME/.gemini/config/plugins/local-setup"
cat <<EOF > "$GEMINI_PLUGIN_DIR/plugin.json"
{
"name": "local-setup",
"description": "Local custom skills deployed via ai-setup"
}
EOF
for skill_dir in "$SKILLS_SRC"/*; do
[ -d "$skill_dir" ] || continue
skill_name=$(basename "$skill_dir")
# Деплой для Claude
mkdir -p "$CLAUDE_SKILLS_DST/$skill_name"
cp -r "$skill_dir/"* "$CLAUDE_SKILLS_DST/$skill_name/"
# Деплой для Gemini (agy)
mkdir -p "$GEMINI_SKILLS_DST/$skill_name"
cp -r "$skill_dir/"* "$GEMINI_SKILLS_DST/$skill_name/"
done
success "Skills обновлены для Claude и Gemini"
else
info "Папка со skills не найдена, пропускаю"
fi
# ── 6.7. Статусная строка Claude Code ───────────────────────
info "Настраиваю статусную строку Claude Code..."
STATUSLINE_SRC="$SCRIPT_DIR/home-configs/claude/statusline-command.sh"
@@ -557,6 +534,41 @@ else
warn "Файл $ADD_HOOK_SRC не найден, пропускаю"
fi
# ── 6.7.3. Хук logout-account ───────────────────────────────────
info "Деплою хук logout-account..."
LOGOUT_HOOK_SRC="$SCRIPT_DIR/home-configs/claude/hooks/logout-account-hook.sh"
LOGOUT_HOOK_DST="$HOME/.claude/hooks/logout-account-hook.sh"
mkdir -p "$HOME/.claude/hooks"
if [ -f "$LOGOUT_HOOK_SRC" ]; then
cp "$LOGOUT_HOOK_SRC" "$LOGOUT_HOOK_DST"
chmod +x "$LOGOUT_HOOK_DST"
# Прописываем хук в settings.json (идемпотентно)
python3 - "$HOME/.claude/settings.json" "$LOGOUT_HOOK_DST" <<'PYEOF'
import sys, json, os
settings_path, hook_path = sys.argv[1], sys.argv[2]
data = {}
if os.path.exists(settings_path):
with open(settings_path) as f:
try: data = json.load(f)
except json.JSONDecodeError: pass
data.setdefault("hooks", {}).setdefault("UserPromptSubmit", [{"hooks": []}])
hook_cmd = f'bash "{hook_path}"'
ups = data["hooks"]["UserPromptSubmit"]
already = any(
any(h.get("command", "") == hook_cmd for h in entry.get("hooks", []))
for entry in ups
)
if not already:
ups[0]["hooks"].append({"type": "command", "command": hook_cmd})
with open(settings_path, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
f.write("\n")
PYEOF
success "Хук logout-account установлен"
else
warn "Файл $LOGOUT_HOOK_SRC не найден, пропускаю"
fi
# ── 6.8. Регистрация официального маркетплейса плагинов Claude ──
info "Настраиваю маркетплейс плагинов Claude Code..."
if ! command -v claude &>/dev/null; then
@@ -694,25 +706,24 @@ try:
d = json.load(sys.stdin)
available = d.get('is_available', False)
infos = d.get('balance_infos', [])
# Показываем только USD (CNY не выводим)
infos = [i for i in infos if i.get('currency', '').upper() == 'USD']
if not infos:
print(' \033[0;33m[БАЛАНС]\033[0m Нет данных о балансе')
sys.exit(0)
symbols = {'USD': '\$', 'CNY': '¥'}
cache_parts = []
for info in infos:
curr = info.get('currency', '???')
total = info.get('total_balance', '0')
granted = info.get('granted_balance', '0')
topped_up = info.get('topped_up_balance', '0')
sym = symbols.get(curr, curr)
status = '✅ доступен' if available else '❌ не активен'
print(f' \033[1;36m💰 Баланс DeepSeek:\033[0m {total} {curr} {status}')
print(f' \033[1;36m💰 Баланс DeepSeek:\033[0m \${total} {status}')
if float(granted) > 0:
print(f' └─ Начислено: {granted} {curr}')
print(f' └─ Начислено: \${granted}')
if float(topped_up) > 0:
print(f' └─ Пополнено: {topped_up} {curr}')
cache_parts.append(f'{sym}{total}')
# Cache all currencies with symbols for statusline
print(f' └─ Пополнено: \${topped_up}')
cache_parts.append(f'\${total}')
# Cache USD balance for statusline
if cache_parts:
cache_dir = os.path.expanduser('~/.cache/ai-setup')
os.makedirs(cache_dir, exist_ok=True)
@@ -989,16 +1000,16 @@ PYEOF
# ai-claude использует ~/.claude/hooks напрямую; остальные лаунчеры получают
# свою копию, чтобы /switch-account и /add-account работали изолированно.
mkdir -p "$cfg/hooks"
for hook in switch-account-hook.sh add-account-hook.sh account-email.sh; do
for hook in switch-account-hook.sh add-account-hook.sh logout-account-hook.sh account-email.sh; do
if [ -f "$HOME/.claude/hooks/$hook" ]; then
cp "$HOME/.claude/hooks/$hook" "$cfg/hooks/$hook"
chmod +x "$cfg/hooks/$hook"
fi
done
# Регистрируем UserPromptSubmit хуки в изолированном settings.json
python3 - "$cfg/settings.json" "$cfg/hooks/switch-account-hook.sh" "$cfg/hooks/add-account-hook.sh" <<'PYEOF'
python3 - "$cfg/settings.json" "$cfg/hooks/switch-account-hook.sh" "$cfg/hooks/add-account-hook.sh" "$cfg/hooks/logout-account-hook.sh" <<'PYEOF'
import sys, json, os
settings_path, switch_hook, add_hook = sys.argv[1:4]
settings_path = sys.argv[1]
data = {}
if os.path.exists(settings_path):
try:
@@ -1008,7 +1019,7 @@ if os.path.exists(settings_path):
pass
data.setdefault("hooks", {}).setdefault("UserPromptSubmit", [{"hooks": []}])
ups = data["hooks"]["UserPromptSubmit"]
for hook_path in (switch_hook, add_hook):
for hook_path in sys.argv[2:]:
hook_cmd = f'bash "{hook_path}"'
already = any(
any(h.get("command", "") == hook_cmd for h in entry.get("hooks", []))
@@ -1126,7 +1137,7 @@ _setup_codex_sound_hooks() {
paplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null ||
pw-play --volume=1 /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null ||
aplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null
) &
) </dev/null >/dev/null 2>&1 &
SOUNDEOF
cat > "$hooks_dir/ai-setup-sound-on-auto-compact.sh" <<'SOUNDEOF'
@@ -1137,7 +1148,7 @@ SOUNDEOF
paplay /usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga 2>/dev/null ||
pw-play --volume=1 /usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga 2>/dev/null ||
aplay /usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga 2>/dev/null
) &
) </dev/null >/dev/null 2>&1 &
SOUNDEOF
chmod +x "$hooks_dir/ai-setup-sound-on-stop.sh" "$hooks_dir/ai-setup-sound-on-auto-compact.sh"
@@ -1231,7 +1242,9 @@ fi
_build_ai_sys_prompt > /dev/null # сохраняет в ~/.codex/AGENTS.md (codex читает авто)
_setup_codex_sound_hooks
exec "$codex_bin" --dangerously-bypass-approvals-and-sandbox "$@"
exec "$codex_bin" --dangerously-bypass-approvals-and-sandbox \
-c 'tui.status_line=["model-with-reasoning","git-branch","context-used","five-hour-limit","current-dir"]' \
"$@"
GPTEOF
chmod +x "$BIN_DIR/ai-gpt"
@@ -1548,7 +1561,7 @@ chmod +x "$BIN_DIR/ai-kimi"
# === ai-glm ===
cat > "$BIN_DIR/ai-glm" << 'GLMEOF'
#!/usr/bin/env bash
# ai-glm - запуск Claude Code через Zhipu AI GLM 5.2 (Anthropic-compatible API)
# ai-glm - запуск Claude Code через Zhipu AI GLM 5.3 (Anthropic-compatible API)
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/ai-api-helpers.sh" 2>/dev/null || true
key_file="$HOME/.config/ai-setup/glm_key"
@@ -1568,7 +1581,7 @@ glm_base_url="${GLM_BASE_URL:-https://api.z.ai/api/anthropic}"
if [ -n "$api_key" ]; then
echo -n "Проверка сохранённого GLM ключа... "
_claude_test_api "$glm_base_url/v1/messages" "x-api-key: $api_key" "glm-5.2"
_claude_test_api "$glm_base_url/v1/messages" "x-api-key: $api_key" "glm-5.3"
_handle_api_response "GLM" "$_CLAUDE_TEST_CODE" "$_CLAUDE_TEST_BODY" "Пополните баланс: https://z.ai/manage-apikey/apikey-list"
ret=$_API_RET
if [ $ret -eq 401 ]; then
@@ -1609,7 +1622,7 @@ if [ -z "$api_key" ]; then
[ -z "$api_key" ] && { echo "Выход."; exit 1; }
echo -n "Проверяю ключ... "
_claude_test_api "$glm_base_url/v1/messages" "x-api-key: $api_key" "glm-5.2"
_claude_test_api "$glm_base_url/v1/messages" "x-api-key: $api_key" "glm-5.3"
_handle_api_response "GLM" "$_CLAUDE_TEST_CODE" "$_CLAUDE_TEST_BODY" "Пополните баланс: https://z.ai/manage-apikey/apikey-list"
ret=$_API_RET
if [ $ret -eq 0 ] || [ $ret -eq 429 ]; then
@@ -1632,31 +1645,37 @@ trap 'rm -f "$_PROMPT_FILE"' EXIT INT TERM
_build_ai_sys_prompt > "$_PROMPT_FILE"
export AI_LAUNCHER=glm
export CLAUDE_CONFIG_DIR="$HOME/.config/ai-setup/cfg/glm"
# Пикер: Opus/Sonnet = GLM 5.2, Haiku = GLM 5.2[1m]. availableModels НЕ задаём
# (он схлопывает пикер). Claude Code навязывает 3 слота; незаданный показал бы
# чужой Claude, поэтому opus+sonnet = glm-5.2, haiku = glm-5.2[1m].
# Пикер: все три слота = glm-5.3. availableModels НЕ задаём (он схлопывает пикер).
# Claude Code навязывает 3 слота; незаданный показал бы чужой Claude, поэтому
# opus+sonnet+haiku = glm-5.3. Окно контекста у всех слотов задаёт env
# CLAUDE_CODE_MAX_CONTEXT_TOKENS ниже — суффикс [1m] больше не нужен.
_setup_isolated_config glm opus high ''
# ai-glm стартует на /effort max. max невалиден в settings.json (там только
# low/medium/high/xhigh), поэтому задаём через CLI --effort, а не _apply_effort.
# CLAUDE_CODE_ALWAYS_ENABLE_EFFORT заставляет Claude Code отправлять effort в API
# для GLM (иначе glm-5.2 не распознан как effort-capable и параметр не уходит).
# для GLM (иначе glm-5.3 не распознан как effort-capable и параметр не уходит).
# /effort внутри сессии работает; ручной override запуска: AI_EFFORT=high ai-glm.
# CLAUDE_CODE_DISABLE_1M_CONTEXT НЕ выставляем: GLM 5.2 реально держит 1M контекста,
# CLAUDE_CODE_DISABLE_1M_CONTEXT НЕ выставляем: GLM 5.3 реально держит 1M контекста,
# а флаг заставлял бы счётчик ctx: считать окно = 200K (врал в ~5 раз). Прочие
# лаунчеры (deepseek/kimi/openrouter/opencode) флаг оставляют — у них другой контекст
# и флаг убирает [1M]-дубли из пикера; ai-claude его и так не использует.
# CLAUDE_CODE_MAX_CONTEXT_TOKENS: glm-* нет в реестре моделей Claude Code, поэтому
# окно по умолчанию считается = 200K — ctx: врал бы в ~5 раз, а автокомпакт жал бы
# сессию в 200K. Задаём реальное окно 1M явно; env применяется к не-claude моделям
# независимо от суффикса, поэтому [1m] у Haiku-слота не нужен и убран.
ANTHROPIC_BASE_URL="$glm_base_url" \
ANTHROPIC_AUTH_TOKEN="$api_key" \
ANTHROPIC_DEFAULT_OPUS_MODEL=glm-5.2 \
ANTHROPIC_DEFAULT_OPUS_MODEL_NAME="GLM 5.2" \
ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION="GLM 5.2 — флагман Zhipu AI" \
ANTHROPIC_DEFAULT_SONNET_MODEL=glm-5.2 \
ANTHROPIC_DEFAULT_SONNET_MODEL_NAME="GLM 5.2" \
ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION="GLM 5.2 — флагман Zhipu AI" \
ANTHROPIC_DEFAULT_HAIKU_MODEL='glm-5.2[1m]' \
ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME="GLM 5.2 [1M]" \
ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION="GLM 5.2 [1M] — расширенный контекст" \
CLAUDE_CODE_SUBAGENT_MODEL=glm-5.2 \
ANTHROPIC_DEFAULT_OPUS_MODEL=glm-5.3 \
ANTHROPIC_DEFAULT_OPUS_MODEL_NAME="GLM 5.3" \
ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION="GLM 5.3 — флагман Zhipu AI" \
ANTHROPIC_DEFAULT_SONNET_MODEL=glm-5.3 \
ANTHROPIC_DEFAULT_SONNET_MODEL_NAME="GLM 5.3" \
ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION="GLM 5.3 — флагман Zhipu AI" \
ANTHROPIC_DEFAULT_HAIKU_MODEL=glm-5.3 \
ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME="GLM 5.3" \
ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION="GLM 5.3 — флагман Zhipu AI" \
CLAUDE_CODE_SUBAGENT_MODEL=glm-5.3 \
CLAUDE_CODE_MAX_CONTEXT_TOKENS=1000000 \
CLAUDE_CODE_ALWAYS_ENABLE_EFFORT=1 \
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 \
claude --dangerously-skip-permissions --effort "${AI_EFFORT:-max}" --system-prompt-file "$_PROMPT_FILE" "$@"
@@ -1993,7 +2012,7 @@ echo " На базе Claude Code:"
echo -e " ${CYAN}ai-claude${NC} - Оригинальный Claude Code (Anthropic)"
echo -e " ${CYAN}ai-deepseek${NC} - DeepSeek (через Claude Code, API ключ сохраняется)"
echo -e " ${CYAN}ai-kimi${NC} - Kimi K2.7 Code (через Claude Code, API ключ сохраняется)"
echo -e " ${CYAN}ai-glm${NC} - GLM 5.2 (через Claude Code, Zhipu AI API)"
echo -e " ${CYAN}ai-glm${NC} - GLM 5.3 (через Claude Code, Zhipu AI API)"
echo -e " ${CYAN}ai-openrouter${NC} - OpenRouter (через Claude Code: GPT-5.5, Grok, Qwen, GLM 5.2 и др.)"
echo -e " ${CYAN}ai-opencode${NC} - OpenCode Go (через Claude Code + routatic-proxy: DeepSeek, Kimi, Qwen, GLM, MiniMax, MiMo)"
echo ""

View File

@@ -18,6 +18,34 @@ mkdir -p "$HOME/.config/ai-setup"
LOG="$HOME/.config/ai-setup/setup.log"
_log() { printf '%s [%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" "$2" >> "$LOG"; }
# Обновление: git pull + перегенерация всех ai-* лаунчеров (пункт меню 7)
do_update() {
local repo_dir
repo_dir="$(pwd)"
echo -e "${BLD}Обновляем репозиторий...${CLR}"
git -C "$repo_dir" pull --ff-only
echo ""
echo -e "${BLD}Перегенерация скриптов...${CLR}"
bash "$repo_dir/scripts/ai-setup.sh"
}
# CLI-режим: ./setup.sh update (или --update) — обновление без меню
case "${1:-}" in
update|--update)
_log "setup" "update (CLI) на $(hostname)"
do_update
exit $?
;;
"")
# без аргументов — интерактивное меню ниже
;;
*)
echo "Неизвестный аргумент: $1"
echo "Использование: ./setup.sh [update] — без аргументов открывается меню"
exit 1
;;
esac
if command -v whiptail >/dev/null 2>&1; then
MENU_ARGS=()
MENU_ARGS+=("1" "AI-инструменты (установить лаунчеры + ключи)")
@@ -248,12 +276,7 @@ case "$choice" in
bash tests/test_network.sh
;;
7)
REPO_DIR="$(cd "$(dirname "$0")" && pwd)"
echo -e "${BLD}Обновляем репозиторий...${CLR}"
git -C "$REPO_DIR" pull --ff-only
echo ""
echo -e "${BLD}Перегенерация скриптов...${CLR}"
bash "$REPO_DIR/scripts/ai-setup.sh"
do_update
;;
8)
bash scripts/ai-setup.sh

View File

@@ -7,6 +7,7 @@ set -euo pipefail
SCRIPT="$(cd "$(dirname "$0")/.." && pwd)/scripts/ai-setup.sh"
GLOBAL_RULES_SOURCE="$(cd "$(dirname "$0")/.." && pwd)/home-configs/GLOBAL_RULES.md"
ADD_HOOK="$(cd "$(dirname "$0")/.." && pwd)/home-configs/claude/hooks/add-account-hook.sh"
PASS=0; FAIL=0
ok() { echo "[PASS] $1"; PASS=$((PASS+1)); }
@@ -20,6 +21,7 @@ GEMINI_SECTION=$(awk '/^cat > "\$BIN_DIR\/ai-gemini"/,/^GEMINIEOF/' "$SCRIPT")
OPENCODE_SECTION=$(awk '/^cat > "\$BIN_DIR\/ai-opencode"/,/^OPENCODEEOF/' "$SCRIPT")
CURSOR_SECTION=$(awk '/^cat > "\$BIN_DIR\/ai-cursor"/,/^CURSOREOF/' "$SCRIPT")
HELPERS_SECTION=$(awk '/^cat > "\$HELPERS_FILE"/,/^HELPEREOF/' "$SCRIPT")
CODEX_SOUND_HOOKS_SECTION=$(awk '/^_setup_codex_sound_hooks\(\)/,/^}/' "$SCRIPT")
# ── ai-gpt: auto-install codex ────────────────────────────────────────────
test_gpt_autoinstall() {
@@ -39,6 +41,15 @@ test_gpt_no_proxy() {
fi
}
# ── ai-gpt: informative Codex status line ───────────────────────────────────
test_gpt_status_line() {
if echo "$GPT_SECTION" | grep -Fq 'tui.status_line=["model-with-reasoning","git-branch","context-used","five-hour-limit","current-dir"]'; then
ok "ai-gpt: shows model, branch, context usage, primary limit, and directory"
else
fail "ai-gpt: missing configured Codex status line"
fi
}
# ── ai-kimi: launches claude with Kimi backend ────────────────────────────
test_kimi_claude_launcher() {
if echo "$KIMI_SECTION" | grep -q 'claude --dangerously-skip-permissions' \
@@ -83,12 +94,13 @@ test_glm_claude_launcher() {
# ── ai-glm: uses official Zhipu AI API ────────────────────────────────────
test_glm_official_api() {
if echo "$GLM_SECTION" | grep -q 'api.z.ai/api/anthropic' \
&& echo "$GLM_SECTION" | grep -q 'ANTHROPIC_DEFAULT_OPUS_MODEL=glm-5.2' \
&& echo "$GLM_SECTION" | grep -q "ANTHROPIC_DEFAULT_HAIKU_MODEL='glm-5.2\[1m\]'" \
&& echo "$GLM_SECTION" | grep -q 'ANTHROPIC_DEFAULT_OPUS_MODEL=glm-5.3' \
&& echo "$GLM_SECTION" | grep -q 'ANTHROPIC_DEFAULT_HAIKU_MODEL=glm-5.3' \
&& echo "$GLM_SECTION" | grep -q 'CLAUDE_CODE_MAX_CONTEXT_TOKENS=1000000' \
&& echo "$GLM_SECTION" | grep -q 'x-api-key'; then
ok "ai-glm: uses official Zhipu AI API (glm-5.2 opus/sonnet, glm-5.2[1m] haiku)"
ok "ai-glm: uses official Zhipu AI API (glm-5.3 everywhere, ctx window 1M via env)"
else
fail "ai-glm: must use official Zhipu AI API with glm-5.2 and x-api-key"
fail "ai-glm: must use official Zhipu AI API with glm-5.3, 1M context window and x-api-key"
fi
}
@@ -112,20 +124,14 @@ test_cursor_native_launcher() {
fi
}
# ── global rules: Karpathy-style guidelines and native rule files ───────────
test_global_rules_include_quality_guidelines() {
karpathy_line=$(grep -n '^## 1\. Think Before Coding$' "$GLOBAL_RULES_SOURCE" | head -1 | cut -d: -f1)
global_line=$(grep -n '^# Global Rules for All AI Agents$' "$GLOBAL_RULES_SOURCE" | head -1 | cut -d: -f1)
if [ -n "$karpathy_line" ] \
&& [ -n "$global_line" ] \
&& [ "$karpathy_line" -lt "$global_line" ] \
&& grep -q 'Always reply in Russian' "$GLOBAL_RULES_SOURCE" \
&& grep -q 'Plain git diff visibility' "$GLOBAL_RULES_SOURCE" \
# ── global rules: source and native rule files ───────────────────────
test_global_rules_source_installed() {
if [ -s "$GLOBAL_RULES_SOURCE" ] \
&& grep -q 'GLOBAL_RULES_SOURCE=' "$SCRIPT" \
&& grep -q 'cp "$GLOBAL_RULES_SOURCE" "$CONFIG_DIR/global_rules.md"' "$SCRIPT"; then
ok "global rules: source file includes English Karpathy guidelines before user rules"
ok "global rules: non-empty source file is installed as global_rules.md"
else
fail "global rules: missing source file, English Karpathy guidelines, or user rules"
fail "global rules: missing source file or installation wiring"
fi
}
@@ -145,6 +151,16 @@ test_native_rule_files_generated() {
fi
}
test_codex_sound_hooks_detach_stdio() {
local detached_count
detached_count=$(printf '%s\n' "$CODEX_SOUND_HOOKS_SECTION" | grep -Fc ') </dev/null >/dev/null 2>&1 &' || true)
if [ "$detached_count" -eq 2 ]; then
ok "codex hooks: background sound players detach standard streams"
else
fail "codex hooks: background sound players can keep hook pipes open"
fi
}
# ── Fix 7: trap quotes $TMP correctly ────────────────────────────────────────
test_fix7_trap_tmp() {
if grep -q "trap 'rm -rf \"\$TMP\"' EXIT" "$SCRIPT"; then
@@ -188,15 +204,6 @@ test_android_symlink_to_bin_dir() {
fi
}
test_android_skill_exists() {
skill_file="$(cd "$(dirname "$0")/.." && pwd)/home-configs/claude/skills/android-cli/SKILL.md"
if [ -f "$skill_file" ]; then
ok "android-cli: custom skill file exists"
else
fail "android-cli: custom skill file is missing"
fi
}
# ── ai-opencode: launches claude with routatic-proxy backend ──────────────────
test_opencode_claude_launcher() {
if echo "$OPENCODE_SECTION" | grep -q 'claude --dangerously-skip-permissions' \
@@ -240,10 +247,55 @@ test_opencode_models() {
fi
}
# ── add-account: логину нужен tty, фоновый запуск висит вечно ────────────────
test_add_account_no_headless_login() {
if grep -q 'claude auth login.*</dev/null' "$ADD_HOOK"; then
fail "add-account: логин запускается с закрытым stdin — код из браузера вставить некуда"
else
ok "add-account: логин не запускается в фоне с закрытым stdin"
fi
}
test_add_account_single_terminal_flow() {
if grep -q 'mkfifo' "$ADD_HOOK" \
&& grep -q 'add-account <код>' "$ADD_HOOK" \
&& ! grep -q 'gnome-terminal' "$ADD_HOOK"; then
ok "add-account: двухшаговый флоу в одном терминале, без второго окна"
else
fail "add-account: логин должен идти через fifo в текущем терминале, без отдельного окна"
fi
}
test_add_account_kills_by_pid() {
if grep -v '^[[:space:]]*#' "$ADD_HOOK" | grep -q 'pkill'; then
fail "add-account: pkill -f выкосит любой процесс с этой подстрокой в cmdline"
else
ok "add-account: процессы гасятся по своим PID, без широкого pkill -f"
fi
}
test_add_account_checks_login_result() {
if grep -q 'Login failed' "$ADD_HOOK" \
&& ! grep -q 'SAVED:' "$ADD_HOOK"; then
ok "add-account: результат логина проверяется, провал не выдаётся за успех"
else
fail "add-account: провал логина не должен маскироваться под успешное сохранение"
fi
}
test_add_hook_syntax() {
if bash -n "$ADD_HOOK" 2>&1; then
ok "syntax: add-account-hook.sh passes 'bash -n'"
else
fail "syntax: add-account-hook.sh has syntax errors"
fi
}
# ── run all tests ─────────────────────────────────────────────────────────────
test_script_syntax
test_gpt_autoinstall
test_gpt_no_proxy
test_gpt_status_line
test_kimi_claude_launcher
test_kimi_official_api
test_kimi_no_artemox
@@ -251,17 +303,22 @@ test_glm_claude_launcher
test_glm_official_api
test_gemini_native_launcher
test_cursor_native_launcher
test_global_rules_include_quality_guidelines
test_global_rules_source_installed
test_native_rule_files_generated
test_codex_sound_hooks_detach_stdio
test_fix7_trap_tmp
test_android_cli_install_url
test_android_init_called
test_android_symlink_to_bin_dir
test_android_skill_exists
test_opencode_claude_launcher
test_opencode_routatic_proxy
test_opencode_key_management
test_opencode_models
test_add_hook_syntax
test_add_account_no_headless_login
test_add_account_single_terminal_flow
test_add_account_kills_by_pid
test_add_account_checks_login_result
echo ""
echo "Results: $PASS passed, $FAIL failed"