@jakerdy/agentica 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +291 -0
- package/dist/cli.js +64 -0
- package/dist/cli.js.map +27 -0
- package/globals/anti-spaghetti.md +65 -0
- package/globals/lang-python.md +105 -0
- package/globals/lang-typescript.md +61 -0
- package/globals/use-agentica.md +127 -0
- package/package.json +55 -0
- package/prompts/architect.prompt.md +302 -0
- package/prompts/change.prompt.md +915 -0
- package/prompts/create.prompt.md +953 -0
- package/prompts/implement.prompt.md +389 -0
- package/prompts/init.prompt.md +123 -0
- package/prompts/readme.prompt.md +355 -0
- package/prompts/refactor.prompt.md +712 -0
- package/prompts/reverse.prompt.md +777 -0
- package/prompts/tasks.prompt.md +1041 -0
- package/prompts/validate.prompt.md +480 -0
- package/stacks/python/cli/product.md +41 -0
- package/stacks/python/cli/structure.md +40 -0
- package/stacks/python/cli/tech.md +29 -0
- package/stacks/python/gui/product.md +41 -0
- package/stacks/python/gui/structure.md +41 -0
- package/stacks/python/gui/tech.md +29 -0
- package/stacks/python/lib/product.md +41 -0
- package/stacks/python/lib/structure.md +34 -0
- package/stacks/python/lib/tech.md +30 -0
- package/stacks/python/monorepo/product.md +41 -0
- package/stacks/python/monorepo/structure.md +29 -0
- package/stacks/python/monorepo/tech.md +30 -0
- package/stacks/typescript/cli/product.md +41 -0
- package/stacks/typescript/cli/structure.md +34 -0
- package/stacks/typescript/cli/tech.md +31 -0
- package/stacks/typescript/lib/product.md +41 -0
- package/stacks/typescript/lib/structure.md +33 -0
- package/stacks/typescript/lib/tech.md +31 -0
- package/stacks/typescript/monorepo/product.md +41 -0
- package/stacks/typescript/monorepo/structure.md +34 -0
- package/stacks/typescript/monorepo/tech.md +47 -0
- package/stacks/typescript/server/product.md +41 -0
- package/stacks/typescript/server/structure.md +35 -0
- package/stacks/typescript/server/tech.md +30 -0
- package/stacks/typescript/spa/product.md +41 -0
- package/stacks/typescript/spa/structure.md +36 -0
- package/stacks/typescript/spa/tech.md +29 -0
- package/templates/architecture/AR-0000 - /320/220/321/200/321/205/320/270/321/202/320/265/320/272/321/202/321/203/321/200/320/260 /321/204/320/270/321/207/320/270 /320/270/320/273/320/270 /320/274/320/276/320/264/321/203/320/273/321/217 XXX.md" +136 -0
- package/templates/change/CH-0000 - /320/230/320/267/320/274/320/265/320/275/320/265/320/275/320/270/320/265 /320/262 /321/204/320/270/321/207/320/265 /320/270/320/273/320/270 /320/274/320/276/320/264/321/203/320/273/320/265 XXX.md" +33 -0
- package/templates/feature/FT-0000 - /320/235/320/260/320/267/320/262/320/260/320/275/320/270/320/265 /321/204/320/270/321/207/320/270 /320/270/320/273/320/270 /320/274/320/276/320/264/321/203/320/273/321/217 XXX/product.md" +121 -0
- package/templates/feature/FT-0000 - /320/235/320/260/320/267/320/262/320/260/320/275/320/270/320/265 /321/204/320/270/321/207/320/270 /320/270/320/273/320/270 /320/274/320/276/320/264/321/203/320/273/321/217 XXX/tasks.md" +38 -0
- package/templates/feature/FT-0000 - /320/235/320/260/320/267/320/262/320/260/320/275/320/270/320/265 /321/204/320/270/321/207/320/270 /320/270/320/273/320/270 /320/274/320/276/320/264/321/203/320/273/321/217 XXX/tech.md" +155 -0
- package/templates/feature/FT-0000 - /320/235/320/260/320/267/320/262/320/260/320/275/320/270/320/265 /321/204/320/270/321/207/320/270 /320/270/320/273/320/270 /320/274/320/276/320/264/321/203/320/273/321/217 XXX/validation.md" +31 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jak Erdy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
# Agentica
|
|
2
|
+
|
|
3
|
+
[](https://github.com/jakerdy/agentica/releases/tag/v0.1.0)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](https://bun.sh)
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
**Spec Driven фреймворк для агентного кодинга.**
|
|
10
|
+
Вдохновлен [SpecKit](https://github.com/github/spec-kit), но исповедует Developer-first подход.
|
|
11
|
+
|
|
12
|
+
В то время как другие инструменты работают в пространстве "продукта" (User Stories, Vibe Coding), Agentica работает в пространстве "архитектора", предоставляя разработчику полный контроль над структурой и качеством кода до того, как AI напишет первую строчку.
|
|
13
|
+
|
|
14
|
+
## Prerequisites
|
|
15
|
+
|
|
16
|
+
- VSCode 1.109.0+
|
|
17
|
+
- GitHub Copilot
|
|
18
|
+
- Bun 1.3+ / Node.js 18+ (для запуска CLI)
|
|
19
|
+
- Context7 (`Upstash.context7-mcp`) — опционально
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# Установка глобально
|
|
25
|
+
bun install -g @jakerdy/agentica
|
|
26
|
+
|
|
27
|
+
# Инициализация (работает и в пустой папке, и в существующем проекте)
|
|
28
|
+
agentica init typescript/cli MyProject
|
|
29
|
+
|
|
30
|
+
# Открытие в VSCode
|
|
31
|
+
cd MyProject
|
|
32
|
+
code .
|
|
33
|
+
```
|
|
34
|
+
После `init` Agentica автоматически:
|
|
35
|
+
- копирует в проект `.agentica/prompts`, `.agentica/templates` и `.agentica/skills`;
|
|
36
|
+
- обновляет `.vscode/settings.json`, добавляя пути в `chat.promptFilesLocations` и `chat.agentSkillsLocations`.
|
|
37
|
+
- добавит context7 в рекомендованные расширения, чтобы агенты сами могли искать документацию по библиотекам
|
|
38
|
+
|
|
39
|
+
Открой AI-чат (`Ctrl + Shift + I`) и запустите инициализационный промпт:
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
/agentica.init
|
|
43
|
+
|
|
44
|
+
Опишите тут свой проект
|
|
45
|
+
- Стек технологий
|
|
46
|
+
- Основную функциональность
|
|
47
|
+
- Прочие важные детали
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Мотивация
|
|
51
|
+
|
|
52
|
+
Agentica был создан в ходе мучительного поиска "идеального" инструмента для работы с агентными системами.
|
|
53
|
+
|
|
54
|
+
На момент начала 2026 года существует множество инструментов, чтобы держать агента в рамках. Но большинство из них исходит из непростительно оптимистичного предположения, что агентная система:
|
|
55
|
+
1. Достаточно умна, чтобы писать качественный код.
|
|
56
|
+
2. Может самостоятельно построить адекватную архитектуру.
|
|
57
|
+
3. Позволяет пользователю быть "менеджером", который вообще не думает про структуру кода.
|
|
58
|
+
|
|
59
|
+
Однако практика показывает, что это ложь. Агентный кодинг обычно представляет собой одно из двух:
|
|
60
|
+
- **Цикл бесконечной борьбы**, в котором вы раз за разом затыкаете дыры в реализации, получая в итоге качество кода "ниже среднего".
|
|
61
|
+
- **Адская бюрократия**, требующая составления спецификации на пару тысяч строк Markdown с постоянной вычиткой и невозможностью вернуться назад без переписывания половины текста.
|
|
62
|
+
|
|
63
|
+
Но у агентов есть одно свойство, которое сложно игнорировать - они способны выдавать **очень много кода за единицу времени**. Чтобы это было полезно, им нужна правильная спека.
|
|
64
|
+
Agentica - это конструктор таких спек. Она заполняет расстояние между вашими архитектурными решениями и финальным кодом.
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
### Всадники апокалипсиса агентного кодинга
|
|
68
|
+
|
|
69
|
+
Фреймворк спроектирован для обхода четырех главных ограничений LLM:
|
|
70
|
+
|
|
71
|
+
1. **Контекст модели ограничен.** То, что помнит модель - это 1/10 или 1/20 часть проекта. Наша задача - сделать так, чтобы в контекст попало только то, что действительно важно для задачи, и ссылки на то, куда нужно "сходить".
|
|
72
|
+
2. **Context Rot (Гниение контекста).** Чем больше данных, тем глупее модель (на 5-15%). Поэтому чем уже скоуп спецификации и "общих файлов", тем лучше результат.
|
|
73
|
+
3. **Context Compaction.** При переполнении агент начинает сжимать информацию, выкидывая детали. Проблема в том, что он может выкинуть важное. Мы должны либо помещаться в одну сессию, либо заставлять модель перечитывать важное.
|
|
74
|
+
4. **Говнокод.** Модели обучались на GitHub. Беда в том, что в среднем люди пишут спагетти-код.
|
|
75
|
+
- Молодой разработчик неопытен, пишет переусложненный код и радостно выкладывает его в OpenSource - это идеальный корм для обучения моделей.
|
|
76
|
+
- Дядьки с опытом 15+ лет сидят в своих уютненьких банках, страховых и FAANG'ах. Им давно не нужно ничего контрибутить в OpenSource.
|
|
77
|
+
- **Итог:** Есть явный bias модели в сторону кода сомнительного качества. Агент скорее напишет 100 строк 10-этажных вложенных конструкций, чем разделит это на плоские функции.
|
|
78
|
+
|
|
79
|
+
## Философия подхода
|
|
80
|
+
|
|
81
|
+
### 0. Вся ответственность за принятые решения лежит на тебе
|
|
82
|
+
|
|
83
|
+
Прелесть агентов заключается в том, что они мультиплицируют твои возможности по написанию кода в разы, а то и в десятки раз. Но не весь тот код, что написал агент, следует сразу лить в прод.
|
|
84
|
+
|
|
85
|
+
В идеале, вся та работа по "продумыванию" проекта должна быть сделана человеком. И только после того, как человек удостоверился в том что:
|
|
86
|
+
- Все структуры данных и интерфейсы правильные
|
|
87
|
+
- Ответственность между элементами распределена верно
|
|
88
|
+
- Будут использоваться именно те библиотеки которые вы выбрали при планировании проекта
|
|
89
|
+
- Не добавится сущностей, которые уже были реализованы
|
|
90
|
+
- Изменение органично встроится в существующую систему
|
|
91
|
+
Можно давать агенту возможность написать несколько тысяч строк кода. Другими словами, когда вы "всё понимаете" и "неопределённость ожиданий сведена к минимуму".
|
|
92
|
+
|
|
93
|
+
### 1. Тех-Задание + Продукт = Баланс
|
|
94
|
+
|
|
95
|
+
Все Spec-Driven фреймворки (которые я видел) исходят из того, что продукт первичен ("Vibe Coding"). Мы опираемся на "ощущения", а не на техническую красоту.
|
|
96
|
+
|
|
97
|
+
- Думать только о продукте = коллекционирование тех-долга с первого дня.
|
|
98
|
+
- Думать только о технике = постройка никому не нужного космолета.
|
|
99
|
+
|
|
100
|
+
Нужно приземлиться посередине. Агент через 100k токенов всё забудет, а код, который он написал, станет **вашей проблемой**. Поэтому ответственность должна начинаться до того, как агент начнет писать. Вы должны придумать архитектуру. Агенту останется только "заполнить тело методов".
|
|
101
|
+
|
|
102
|
+
В Agentica мы работаем сразу над "продуктовой" и "технической" частью. Например, в базовых структурах (кеши, фабрики) продукта нет - там чистая инженерия. А в новой панели GUI техничка простая, но важен UX.
|
|
103
|
+
|
|
104
|
+
### 2. Узкий Scope и Модульность
|
|
105
|
+
Вместо одного огромного контекста Agentica внедряет директорию `.agentica/` в каждый пакет монорепозитория. Это позволяет:
|
|
106
|
+
- Держать в контексте LLM только правила конкретного модуля.
|
|
107
|
+
- Использовать 20 файлов по 40 строк вместо одного на 1000.
|
|
108
|
+
|
|
109
|
+
### 3. Anti-Spaghetti Метод
|
|
110
|
+
В файле `AGENTS.md` и промптах мы перечисляем всё то, что нам *не нравится* в коде агента, и дополняем это "хорошими практиками". Мы редактируем этот список до тех пор, пока код не станет "совсем хорошим".
|
|
111
|
+
|
|
112
|
+
### 4. Семантическая валидация
|
|
113
|
+
Review'ить код, написанный AI - то ещё удовольствие.
|
|
114
|
+
Для этого нужен отдельный процесс: **Семантическая Валидация**.
|
|
115
|
+
|
|
116
|
+
Агент сам ходит по коду и сверяет его с продуктовыми и техническими требованиями, выступая в роли придирчивого сеньора.
|
|
117
|
+
|
|
118
|
+
И в конце выдаёт вам отчёт. И уже вы решаете, что с этим всё делать:
|
|
119
|
+
- Збить
|
|
120
|
+
- Попросить агента поправить критические проблемы
|
|
121
|
+
- Адаптировать требования к новой информации полученной из реализации, и начать сначала, но уже с более продуманной спекой
|
|
122
|
+
|
|
123
|
+
Главное помнить: сгенерированный код — ваша проблема, агент всё забудет, как только вы начнёте новый чат, и "обвинять" в плохих решениях будет уже некого...
|
|
124
|
+
|
|
125
|
+
## Структура проекта
|
|
126
|
+
|
|
127
|
+
Agentica строго разделяет уровни ответственности.
|
|
128
|
+
|
|
129
|
+
### Топология файлов
|
|
130
|
+
|
|
131
|
+
- **Root проекта:** Шаблоны, промпты, глобальный контекст.
|
|
132
|
+
- **Package root:** Фичи, изменения, архитектура пакета.
|
|
133
|
+
|
|
134
|
+
```text
|
|
135
|
+
.
|
|
136
|
+
├── .agentica/ # GLOBAL SCOPE (Конфигурация и общие знания)
|
|
137
|
+
│ ├── templates/ # Шаблоны (feature, arch, change)
|
|
138
|
+
│ ├── prompts/ # Промпты (init, create, implement...)
|
|
139
|
+
│ ├── skills/ # Skills для Copilot Agent (например frontend-design)
|
|
140
|
+
│ ├── product.md # Глобальный продукт
|
|
141
|
+
│ ├── structure.md # Структура репозитория
|
|
142
|
+
│ ├── tech.md # Глобальный стек и стандарты
|
|
143
|
+
│ └── status.md # Статус интеграции в корне
|
|
144
|
+
├── packages/
|
|
145
|
+
│ ├── package1/
|
|
146
|
+
│ │ ├── .agentica/ # PACKAGE SCOPE (Спецификации и локальный контекст)
|
|
147
|
+
│ │ │ ├── architecture/ # AR-XXXX (Архитектурные решения)
|
|
148
|
+
│ │ │ ├── changes/ # CH-XXXX (Изменения существующего)
|
|
149
|
+
│ │ │ ├── features/ # FT-XXXX (Новые фичи)
|
|
150
|
+
│ │ │ ├── product.md # Контекст пакета
|
|
151
|
+
│ │ │ ├── structure.md # Структура пакета
|
|
152
|
+
│ │ │ ├── tech.md # Стек пакета
|
|
153
|
+
│ │ │ └── status.md # Статус интеграции пакета
|
|
154
|
+
│ │ ├── src/
|
|
155
|
+
│ │ └── ...
|
|
156
|
+
└── ...
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
**Важно:** В Single-project структуре списки объединяются в одной корневой `.agentica/`.
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
## Справочник команд
|
|
163
|
+
|
|
164
|
+
Все команды вызываются через `/agentica.<command>`. Аргументы опциональны - агент постарается вывести их из контекста, но явное указание надежнее.
|
|
165
|
+
|
|
166
|
+
| Команда | Аргументы | Назначение |
|
|
167
|
+
| :---------- | :-------- | :---------------------------------------------------- |
|
|
168
|
+
| `init` | `--lang`, | Инициализация и настройка проекта |
|
|
169
|
+
| `architect` | `--name` | Архитектурная спецификация (`AR-XXXX`) |
|
|
170
|
+
| `reverse` | `--name` | Reverse Engineering по существующему коду (`AR-XXXX`) |
|
|
171
|
+
| `create` | `--name` | Спецификация новой фичи (`FT-XXXX`) |
|
|
172
|
+
| `change` | `--name` | Спецификация изменений (`CH-XXXX`) |
|
|
173
|
+
| `tasks` | `--id` | Декомпозиция спеки на задачи |
|
|
174
|
+
| `implement` | `--id` | Написание кода по задачам |
|
|
175
|
+
| `validate` | `--id` | Семантическая и техническая приемка |
|
|
176
|
+
| `readme` | `--id` | Генерация документации |
|
|
177
|
+
| `refactor` | --- | Улучшение кода без смены API |
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## Рабочие процессы (Workflows)
|
|
182
|
+
|
|
183
|
+
Ниже описаны типовые циклы разработки (Loops).
|
|
184
|
+
|
|
185
|
+
### Общие советы (Pain-killers)
|
|
186
|
+
|
|
187
|
+
- **Новая фича - новый чат.** Нам нужен максимально пустой и чистый контекст.
|
|
188
|
+
- **Не спасайте спеку.** Если что-то не получилось и вы хотите всё поменять в середине - удаляйте спеку, создавайте новый чат. Не пытайтесь "вылечить" текущую сессию. Вы потратите в 3 раза больше времени, а результат будет хуже. Выбрасывайте смелее.
|
|
189
|
+
- **Учитесь писать на русском.** Если вы не можете чётко сформулировать мысли текстом так, чтобы понял ваш товарищ, агент вас точно не поймёт. "Ну это же очевидно" для агента не работает. Спросите у LLM, как писать хорошие технические тексты - это прокачает ваш скилл промптинга.
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
### 1. Zero-to-Hero (Инициализация)
|
|
193
|
+
|
|
194
|
+
```text
|
|
195
|
+
/agentica.init --lang TypeScript
|
|
196
|
+
Сделай CLI для импорта CSV. Нужны команды import, validate.
|
|
197
|
+
Используй commander и chalk.
|
|
198
|
+
```
|
|
199
|
+
*Что происходит:* Агент создает структуру `.agentica/`, заполняет `tech.md` и `structure.md` под ваш запрос, готовит промпты.
|
|
200
|
+
|
|
201
|
+
### 2. Разработка новой фичи (Feature Loop)
|
|
202
|
+
|
|
203
|
+
Цикл: **Spec → Tasks → Implement → Validate**.
|
|
204
|
+
|
|
205
|
+
1. **Создание спецификации:**
|
|
206
|
+
```text
|
|
207
|
+
/agentica.create --name Пакетная загрузка
|
|
208
|
+
Нужна загрузка CSV из папки, фильтр по маске и отчет об ошибках.
|
|
209
|
+
Добавь ограничение файла до 100MB и retry при ошибках сети.
|
|
210
|
+
```
|
|
211
|
+
*Агент задаст уточняющие вопросы в процессе создания спеки для получения полной картины.*
|
|
212
|
+
|
|
213
|
+
2. **План работ:**
|
|
214
|
+
```text
|
|
215
|
+
/agentica.tasks --id FT-0012
|
|
216
|
+
```
|
|
217
|
+
3. **Кодинг:**
|
|
218
|
+
```text
|
|
219
|
+
/agentica.implement --id FT-0012
|
|
220
|
+
```
|
|
221
|
+
4. **Приемка:**
|
|
222
|
+
```text
|
|
223
|
+
/agentica.validate --id FT-0012
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
### 3. Изменение существующего (Change Loop)
|
|
227
|
+
|
|
228
|
+
Используйте, когда нужно аккуратно поменять логику, не сломав остальное.
|
|
229
|
+
|
|
230
|
+
```text
|
|
231
|
+
/agentica.change --name Формат ошибок
|
|
232
|
+
Нужно перевести ошибки с string на JSON объект {code, msg}.
|
|
233
|
+
Важно: сохранить exit-codes для CLI, чтобы не сломать CI.
|
|
234
|
+
```
|
|
235
|
+
*Агент создаст `CH-XXXX`, проанализирует риски (Breaking Changes), предложит план миграции и только потом перейдет к коду.*
|
|
236
|
+
|
|
237
|
+
### 4. Архитектурное проектирование
|
|
238
|
+
|
|
239
|
+
Когда нужно описать новые идеи, принципы и подходы **до** начала реализации. Это не про код, а про структуру, границы модулей и контракты.
|
|
240
|
+
|
|
241
|
+
```text
|
|
242
|
+
/agentica.architect --name Система плагинов
|
|
243
|
+
Нужно спроектировать событийно-ориентированную систему плагинов.
|
|
244
|
+
Опиши интерфейсы ядра, жизненный цикл плагина и шину событий.
|
|
245
|
+
```
|
|
246
|
+
*Агент создаст `AR-XXXX`, опишет диаграммы, потоки данных и принятые компромиссы (Trade-offs).*
|
|
247
|
+
|
|
248
|
+
### 5. Реверс-инжиниринг (Legacy Analysis)
|
|
249
|
+
|
|
250
|
+
Когда документация умерла (или не рождалась), и нужно понять "как оно работает сейчас", чтобы не выстрелить себе в ногу.
|
|
251
|
+
|
|
252
|
+
```text
|
|
253
|
+
/agentica.reverse --name Анализ текущего монорепо
|
|
254
|
+
Восстанови карту модулей, просканируй entry-points.
|
|
255
|
+
Найди циклические зависимости и узкие места в текущей реализации.
|
|
256
|
+
```
|
|
257
|
+
*Агент просканирует кодовую базу и создаст описание системы "As-Is", подсветив зоны риска и архитектурный долг.*
|
|
258
|
+
|
|
259
|
+
### 6. Документация
|
|
260
|
+
```text
|
|
261
|
+
/agentica.readme --id FT-0012
|
|
262
|
+
Сделай короткую доку для разработчиков с примерами.
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
## CLI
|
|
266
|
+
|
|
267
|
+
Чтобы было проще интегрировать Agentica в ваш проект, был создан небольшой, но удобный CLI.
|
|
268
|
+
|
|
269
|
+
Agentica CLI поддерживает два формата запуска `init`:
|
|
270
|
+
- **Позиционный (основной):** `agentica init <stack> [targetPath]`
|
|
271
|
+
- **Через опции (совместимость):** `agentica init --stack <type> [--out <path>]`
|
|
272
|
+
|
|
273
|
+
### Основные команды
|
|
274
|
+
|
|
275
|
+
```bash
|
|
276
|
+
# Инициализация Agentica в текущей папке
|
|
277
|
+
agentica init typescript/cli
|
|
278
|
+
|
|
279
|
+
# Инициализация с созданием новой папки проекта
|
|
280
|
+
agentica init typescript/spa MyProject
|
|
281
|
+
|
|
282
|
+
# То же через опции (режим совместимости)
|
|
283
|
+
agentica init --stack typescript/spa --out MyProject
|
|
284
|
+
|
|
285
|
+
# Показать доступные шаблоны стеков
|
|
286
|
+
agentica stacks
|
|
287
|
+
|
|
288
|
+
# Справка по CLI
|
|
289
|
+
agentica --help
|
|
290
|
+
agentica init --help
|
|
291
|
+
```
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import{createRequire as eq}from"node:module";var rq=Object.create;var{getPrototypeOf:nq,defineProperty:qq,getOwnPropertyNames:aq}=Object;var tq=Object.prototype.hasOwnProperty;var oq=(q,z,J)=>{J=q!=null?rq(nq(q)):{};let Z=z||!q||!q.__esModule?qq(J,"default",{value:q,enumerable:!0}):J;for(let $ of aq(q))if(!tq.call(Z,$))qq(Z,$,{get:()=>q[$],enumerable:!0});return Z};var I=(q,z)=>()=>(z||q((z={exports:{}}).exports,z),z.exports);var _=eq(import.meta.url);var A=I((q1)=>{class u extends Error{constructor(q,z,J){super(J);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=z,this.exitCode=q,this.nestedError=void 0}}class zq extends u{constructor(q){super(1,"commander.invalidArgument",q);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}q1.CommanderError=u;q1.InvalidArgumentError=zq});var C=I((Q1)=>{var{InvalidArgumentError:Z1}=A();class Jq{constructor(q,z){switch(this.description=z||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,q[0]){case"<":this.required=!0,this._name=q.slice(1,-1);break;case"[":this.required=!1,this._name=q.slice(1,-1);break;default:this.required=!0,this._name=q;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(q,z){if(z===this.defaultValue||!Array.isArray(z))return[q];return z.push(q),z}default(q,z){return this.defaultValue=q,this.defaultValueDescription=z,this}argParser(q){return this.parseArg=q,this}choices(q){return this.argChoices=q.slice(),this.parseArg=(z,J)=>{if(!this.argChoices.includes(z))throw new Z1(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(z,J);return z},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function $1(q){let z=q.name()+(q.variadic===!0?"...":"");return q.required?"<"+z+">":"["+z+"]"}Q1.Argument=Jq;Q1.humanReadableArgName=$1});var g=I((H1)=>{var{humanReadableArgName:B1}=C();class Zq{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(q){this.helpWidth=this.helpWidth??q.helpWidth??80}visibleCommands(q){let z=q.commands.filter((Z)=>!Z._hidden),J=q._getHelpCommand();if(J&&!J._hidden)z.push(J);if(this.sortSubcommands)z.sort((Z,$)=>{return Z.name().localeCompare($.name())});return z}compareOptions(q,z){let J=(Z)=>{return Z.short?Z.short.replace(/^-/,""):Z.long.replace(/^--/,"")};return J(q).localeCompare(J(z))}visibleOptions(q){let z=q.options.filter((Z)=>!Z.hidden),J=q._getHelpOption();if(J&&!J.hidden){let Z=J.short&&q._findOption(J.short),$=J.long&&q._findOption(J.long);if(!Z&&!$)z.push(J);else if(J.long&&!$)z.push(q.createOption(J.long,J.description));else if(J.short&&!Z)z.push(q.createOption(J.short,J.description))}if(this.sortOptions)z.sort(this.compareOptions);return z}visibleGlobalOptions(q){if(!this.showGlobalOptions)return[];let z=[];for(let J=q.parent;J;J=J.parent){let Z=J.options.filter(($)=>!$.hidden);z.push(...Z)}if(this.sortOptions)z.sort(this.compareOptions);return z}visibleArguments(q){if(q._argsDescription)q.registeredArguments.forEach((z)=>{z.description=z.description||q._argsDescription[z.name()]||""});if(q.registeredArguments.find((z)=>z.description))return q.registeredArguments;return[]}subcommandTerm(q){let z=q.registeredArguments.map((J)=>B1(J)).join(" ");return q._name+(q._aliases[0]?"|"+q._aliases[0]:"")+(q.options.length?" [options]":"")+(z?" "+z:"")}optionTerm(q){return q.flags}argumentTerm(q){return q.name()}longestSubcommandTermLength(q,z){return z.visibleCommands(q).reduce((J,Z)=>{return Math.max(J,this.displayWidth(z.styleSubcommandTerm(z.subcommandTerm(Z))))},0)}longestOptionTermLength(q,z){return z.visibleOptions(q).reduce((J,Z)=>{return Math.max(J,this.displayWidth(z.styleOptionTerm(z.optionTerm(Z))))},0)}longestGlobalOptionTermLength(q,z){return z.visibleGlobalOptions(q).reduce((J,Z)=>{return Math.max(J,this.displayWidth(z.styleOptionTerm(z.optionTerm(Z))))},0)}longestArgumentTermLength(q,z){return z.visibleArguments(q).reduce((J,Z)=>{return Math.max(J,this.displayWidth(z.styleArgumentTerm(z.argumentTerm(Z))))},0)}commandUsage(q){let z=q._name;if(q._aliases[0])z=z+"|"+q._aliases[0];let J="";for(let Z=q.parent;Z;Z=Z.parent)J=Z.name()+" "+J;return J+z+" "+q.usage()}commandDescription(q){return q.description()}subcommandDescription(q){return q.summary()||q.description()}optionDescription(q){let z=[];if(q.argChoices)z.push(`choices: ${q.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if(q.defaultValue!==void 0){if(q.required||q.optional||q.isBoolean()&&typeof q.defaultValue==="boolean")z.push(`default: ${q.defaultValueDescription||JSON.stringify(q.defaultValue)}`)}if(q.presetArg!==void 0&&q.optional)z.push(`preset: ${JSON.stringify(q.presetArg)}`);if(q.envVar!==void 0)z.push(`env: ${q.envVar}`);if(z.length>0){let J=`(${z.join(", ")})`;if(q.description)return`${q.description} ${J}`;return J}return q.description}argumentDescription(q){let z=[];if(q.argChoices)z.push(`choices: ${q.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if(q.defaultValue!==void 0)z.push(`default: ${q.defaultValueDescription||JSON.stringify(q.defaultValue)}`);if(z.length>0){let J=`(${z.join(", ")})`;if(q.description)return`${q.description} ${J}`;return J}return q.description}formatItemList(q,z,J){if(z.length===0)return[];return[J.styleTitle(q),...z,""]}groupItems(q,z,J){let Z=new Map;return q.forEach(($)=>{let Q=J($);if(!Z.has(Q))Z.set(Q,[])}),z.forEach(($)=>{let Q=J($);if(!Z.has(Q))Z.set(Q,[]);Z.get(Q).push($)}),Z}formatHelp(q,z){let J=z.padWidth(q,z),Z=z.helpWidth??80;function $(H,G){return z.formatItem(H,J,G,z)}let Q=[`${z.styleTitle("Usage:")} ${z.styleUsage(z.commandUsage(q))}`,""],X=z.commandDescription(q);if(X.length>0)Q=Q.concat([z.boxWrap(z.styleCommandDescription(X),Z),""]);let Y=z.visibleArguments(q).map((H)=>{return $(z.styleArgumentTerm(z.argumentTerm(H)),z.styleArgumentDescription(z.argumentDescription(H)))});if(Q=Q.concat(this.formatItemList("Arguments:",Y,z)),this.groupItems(q.options,z.visibleOptions(q),(H)=>H.helpGroupHeading??"Options:").forEach((H,G)=>{let F=H.map((N)=>{return $(z.styleOptionTerm(z.optionTerm(N)),z.styleOptionDescription(z.optionDescription(N)))});Q=Q.concat(this.formatItemList(G,F,z))}),z.showGlobalOptions){let H=z.visibleGlobalOptions(q).map((G)=>{return $(z.styleOptionTerm(z.optionTerm(G)),z.styleOptionDescription(z.optionDescription(G)))});Q=Q.concat(this.formatItemList("Global Options:",H,z))}return this.groupItems(q.commands,z.visibleCommands(q),(H)=>H.helpGroup()||"Commands:").forEach((H,G)=>{let F=H.map((N)=>{return $(z.styleSubcommandTerm(z.subcommandTerm(N)),z.styleSubcommandDescription(z.subcommandDescription(N)))});Q=Q.concat(this.formatItemList(G,F,z))}),Q.join(`
|
|
3
|
+
`)}displayWidth(q){return $q(q).length}styleTitle(q){return q}styleUsage(q){return q.split(" ").map((z)=>{if(z==="[options]")return this.styleOptionText(z);if(z==="[command]")return this.styleSubcommandText(z);if(z[0]==="["||z[0]==="<")return this.styleArgumentText(z);return this.styleCommandText(z)}).join(" ")}styleCommandDescription(q){return this.styleDescriptionText(q)}styleOptionDescription(q){return this.styleDescriptionText(q)}styleSubcommandDescription(q){return this.styleDescriptionText(q)}styleArgumentDescription(q){return this.styleDescriptionText(q)}styleDescriptionText(q){return q}styleOptionTerm(q){return this.styleOptionText(q)}styleSubcommandTerm(q){return q.split(" ").map((z)=>{if(z==="[options]")return this.styleOptionText(z);if(z[0]==="["||z[0]==="<")return this.styleArgumentText(z);return this.styleSubcommandText(z)}).join(" ")}styleArgumentTerm(q){return this.styleArgumentText(q)}styleOptionText(q){return q}styleArgumentText(q){return q}styleSubcommandText(q){return q}styleCommandText(q){return q}padWidth(q,z){return Math.max(z.longestOptionTermLength(q,z),z.longestGlobalOptionTermLength(q,z),z.longestSubcommandTermLength(q,z),z.longestArgumentTermLength(q,z))}preformatted(q){return/\n[^\S\r\n]/.test(q)}formatItem(q,z,J,Z){let Q=" ".repeat(2);if(!J)return Q+q;let X=q.padEnd(z+q.length-Z.displayWidth(q)),Y=2,B=(this.helpWidth??80)-z-Y-2,H;if(B<this.minWidthToWrap||Z.preformatted(J))H=J;else H=Z.boxWrap(J,B).replace(/\n/g,`
|
|
4
|
+
`+" ".repeat(z+Y));return Q+X+" ".repeat(Y)+H.replace(/\n/g,`
|
|
5
|
+
${Q}`)}boxWrap(q,z){if(z<this.minWidthToWrap)return q;let J=q.split(/\r\n|\n/),Z=/[\s]*[^\s]+/g,$=[];return J.forEach((Q)=>{let X=Q.match(Z);if(X===null){$.push("");return}let Y=[X.shift()],U=this.displayWidth(Y[0]);X.forEach((B)=>{let H=this.displayWidth(B);if(U+H<=z){Y.push(B),U+=H;return}$.push(Y.join(""));let G=B.trimStart();Y=[G],U=this.displayWidth(G)}),$.push(Y.join(""))}),$.join(`
|
|
6
|
+
`)}}function $q(q){let z=/\x1b\[\d*(;\d*)*m/g;return q.replace(z,"")}H1.Help=Zq;H1.stripColor=$q});var m=I((M1)=>{var{InvalidArgumentError:K1}=A();class Xq{constructor(q,z){this.flags=q,this.description=z||"",this.required=q.includes("<"),this.optional=q.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(q),this.mandatory=!1;let J=W1(q);if(this.short=J.shortFlag,this.long=J.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(q,z){return this.defaultValue=q,this.defaultValueDescription=z,this}preset(q){return this.presetArg=q,this}conflicts(q){return this.conflictsWith=this.conflictsWith.concat(q),this}implies(q){let z=q;if(typeof q==="string")z={[q]:!0};return this.implied=Object.assign(this.implied||{},z),this}env(q){return this.envVar=q,this}argParser(q){return this.parseArg=q,this}makeOptionMandatory(q=!0){return this.mandatory=!!q,this}hideHelp(q=!0){return this.hidden=!!q,this}_collectValue(q,z){if(z===this.defaultValue||!Array.isArray(z))return[q];return z.push(q),z}choices(q){return this.argChoices=q.slice(),this.parseArg=(z,J)=>{if(!this.argChoices.includes(z))throw new K1(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(z,J);return z},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return Qq(this.name().replace(/^no-/,""));return Qq(this.name())}helpGroup(q){return this.helpGroupHeading=q,this}is(q){return this.short===q||this.long===q}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class Yq{constructor(q){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,q.forEach((z)=>{if(z.negate)this.negativeOptions.set(z.attributeName(),z);else this.positiveOptions.set(z.attributeName(),z)}),this.negativeOptions.forEach((z,J)=>{if(this.positiveOptions.has(J))this.dualOptions.add(J)})}valueFromOption(q,z){let J=z.attributeName();if(!this.dualOptions.has(J))return!0;let Z=this.negativeOptions.get(J).presetArg,$=Z!==void 0?Z:!1;return z.negate===($===q)}}function Qq(q){return q.split("-").reduce((z,J)=>{return z+J[0].toUpperCase()+J.slice(1)})}function W1(q){let z,J,Z=/^-[^-]$/,$=/^--[^-]/,Q=q.split(/[ |,]+/).concat("guard");if(Z.test(Q[0]))z=Q.shift();if($.test(Q[0]))J=Q.shift();if(!z&&Z.test(Q[0]))z=Q.shift();if(!z&&$.test(Q[0]))z=J,J=Q.shift();if(Q[0].startsWith("-")){let X=Q[0],Y=`option creation failed due to '${X}' in option flags '${q}'`;if(/^-[^-][^-]/.test(X))throw Error(`${Y}
|
|
7
|
+
- a short flag is a single dash and a single character
|
|
8
|
+
- either use a single dash and a single character (for a short flag)
|
|
9
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Z.test(X))throw Error(`${Y}
|
|
10
|
+
- too many short flags`);if($.test(X))throw Error(`${Y}
|
|
11
|
+
- too many long flags`);throw Error(`${Y}
|
|
12
|
+
- unrecognised flag format`)}if(z===void 0&&J===void 0)throw Error(`option creation failed due to no flags found in '${q}'.`);return{shortFlag:z,longFlag:J}}M1.Option=Xq;M1.DualOptions=Yq});var Bq=I((T1)=>{function R1(q,z){if(Math.abs(q.length-z.length)>3)return Math.max(q.length,z.length);let J=[];for(let Z=0;Z<=q.length;Z++)J[Z]=[Z];for(let Z=0;Z<=z.length;Z++)J[0][Z]=Z;for(let Z=1;Z<=z.length;Z++)for(let $=1;$<=q.length;$++){let Q=1;if(q[$-1]===z[Z-1])Q=0;else Q=1;if(J[$][Z]=Math.min(J[$-1][Z]+1,J[$][Z-1]+1,J[$-1][Z-1]+Q),$>1&&Z>1&&q[$-1]===z[Z-2]&&q[$-2]===z[Z-1])J[$][Z]=Math.min(J[$][Z],J[$-2][Z-2]+1)}return J[q.length][z.length]}function P1(q,z){if(!z||z.length===0)return"";z=Array.from(new Set(z));let J=q.startsWith("--");if(J)q=q.slice(2),z=z.map((X)=>X.slice(2));let Z=[],$=3,Q=0.4;if(z.forEach((X)=>{if(X.length<=1)return;let Y=R1(q,X),U=Math.max(q.length,X.length);if((U-Y)/U>Q){if(Y<$)$=Y,Z=[X];else if(Y===$)Z.push(X)}}),Z.sort((X,Y)=>X.localeCompare(Y)),J)Z=Z.map((X)=>`--${X}`);if(Z.length>1)return`
|
|
13
|
+
(Did you mean one of ${Z.join(", ")}?)`;if(Z.length===1)return`
|
|
14
|
+
(Did you mean ${Z[0]}?)`;return""}T1.suggestSimilar=P1});var Kq=I((S1)=>{var N1=_("node:events").EventEmitter,c=_("node:child_process"),T=_("node:path"),b=_("node:fs"),K=_("node:process"),{Argument:I1,humanReadableArgName:D1}=C(),{CommanderError:d}=A(),{Help:E1,stripColor:F1}=g(),{Option:Hq,DualOptions:w1}=m(),{suggestSimilar:Uq}=Bq();class p extends N1{constructor(q){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=q||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(z)=>K.stdout.write(z),writeErr:(z)=>K.stderr.write(z),outputError:(z,J)=>J(z),getOutHelpWidth:()=>K.stdout.isTTY?K.stdout.columns:void 0,getErrHelpWidth:()=>K.stderr.isTTY?K.stderr.columns:void 0,getOutHasColors:()=>l()??(K.stdout.isTTY&&K.stdout.hasColors?.()),getErrHasColors:()=>l()??(K.stderr.isTTY&&K.stderr.hasColors?.()),stripColor:(z)=>F1(z)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(q){return this._outputConfiguration=q._outputConfiguration,this._helpOption=q._helpOption,this._helpCommand=q._helpCommand,this._helpConfiguration=q._helpConfiguration,this._exitCallback=q._exitCallback,this._storeOptionsAsProperties=q._storeOptionsAsProperties,this._combineFlagAndOptionalValue=q._combineFlagAndOptionalValue,this._allowExcessArguments=q._allowExcessArguments,this._enablePositionalOptions=q._enablePositionalOptions,this._showHelpAfterError=q._showHelpAfterError,this._showSuggestionAfterError=q._showSuggestionAfterError,this}_getCommandAndAncestors(){let q=[];for(let z=this;z;z=z.parent)q.push(z);return q}command(q,z,J){let Z=z,$=J;if(typeof Z==="object"&&Z!==null)$=Z,Z=null;$=$||{};let[,Q,X]=q.match(/([^ ]+) *(.*)/),Y=this.createCommand(Q);if(Z)Y.description(Z),Y._executableHandler=!0;if($.isDefault)this._defaultCommandName=Y._name;if(Y._hidden=!!($.noHelp||$.hidden),Y._executableFile=$.executableFile||null,X)Y.arguments(X);if(this._registerCommand(Y),Y.parent=this,Y.copyInheritedSettings(this),Z)return this;return Y}createCommand(q){return new p(q)}createHelp(){return Object.assign(new E1,this.configureHelp())}configureHelp(q){if(q===void 0)return this._helpConfiguration;return this._helpConfiguration=q,this}configureOutput(q){if(q===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...q},this}showHelpAfterError(q=!0){if(typeof q!=="string")q=!!q;return this._showHelpAfterError=q,this}showSuggestionAfterError(q=!0){return this._showSuggestionAfterError=!!q,this}addCommand(q,z){if(!q._name)throw Error(`Command passed to .addCommand() must have a name
|
|
15
|
+
- specify the name in Command constructor or using .name()`);if(z=z||{},z.isDefault)this._defaultCommandName=q._name;if(z.noHelp||z.hidden)q._hidden=!0;return this._registerCommand(q),q.parent=this,q._checkForBrokenPassThrough(),this}createArgument(q,z){return new I1(q,z)}argument(q,z,J,Z){let $=this.createArgument(q,z);if(typeof J==="function")$.default(Z).argParser(J);else $.default(J);return this.addArgument($),this}arguments(q){return q.trim().split(/ +/).forEach((z)=>{this.argument(z)}),this}addArgument(q){let z=this.registeredArguments.slice(-1)[0];if(z?.variadic)throw Error(`only the last argument can be variadic '${z.name()}'`);if(q.required&&q.defaultValue!==void 0&&q.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${q.name()}'`);return this.registeredArguments.push(q),this}helpCommand(q,z){if(typeof q==="boolean"){if(this._addImplicitHelpCommand=q,q&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let J=q??"help [command]",[,Z,$]=J.match(/([^ ]+) *(.*)/),Q=z??"display help for command",X=this.createCommand(Z);if(X.helpOption(!1),$)X.arguments($);if(Q)X.description(Q);if(this._addImplicitHelpCommand=!0,this._helpCommand=X,q||z)this._initCommandGroup(X);return this}addHelpCommand(q,z){if(typeof q!=="object")return this.helpCommand(q,z),this;return this._addImplicitHelpCommand=!0,this._helpCommand=q,this._initCommandGroup(q),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(q,z){let J=["preSubcommand","preAction","postAction"];if(!J.includes(q))throw Error(`Unexpected value for event passed to hook : '${q}'.
|
|
16
|
+
Expecting one of '${J.join("', '")}'`);if(this._lifeCycleHooks[q])this._lifeCycleHooks[q].push(z);else this._lifeCycleHooks[q]=[z];return this}exitOverride(q){if(q)this._exitCallback=q;else this._exitCallback=(z)=>{if(z.code!=="commander.executeSubCommandAsync")throw z};return this}_exit(q,z,J){if(this._exitCallback)this._exitCallback(new d(q,z,J));K.exit(q)}action(q){let z=(J)=>{let Z=this.registeredArguments.length,$=J.slice(0,Z);if(this._storeOptionsAsProperties)$[Z]=this;else $[Z]=this.opts();return $.push(this),q.apply(this,$)};return this._actionHandler=z,this}createOption(q,z){return new Hq(q,z)}_callParseArg(q,z,J,Z){try{return q.parseArg(z,J)}catch($){if($.code==="commander.invalidArgument"){let Q=`${Z} ${$.message}`;this.error(Q,{exitCode:$.exitCode,code:$.code})}throw $}}_registerOption(q){let z=q.short&&this._findOption(q.short)||q.long&&this._findOption(q.long);if(z){let J=q.long&&this._findOption(q.long)?q.long:q.short;throw Error(`Cannot add option '${q.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${J}'
|
|
17
|
+
- already used by option '${z.flags}'`)}this._initOptionGroup(q),this.options.push(q)}_registerCommand(q){let z=(Z)=>{return[Z.name()].concat(Z.aliases())},J=z(q).find((Z)=>this._findCommand(Z));if(J){let Z=z(this._findCommand(J)).join("|"),$=z(q).join("|");throw Error(`cannot add command '${$}' as already have command '${Z}'`)}this._initCommandGroup(q),this.commands.push(q)}addOption(q){this._registerOption(q);let z=q.name(),J=q.attributeName();if(q.negate){let $=q.long.replace(/^--no-/,"--");if(!this._findOption($))this.setOptionValueWithSource(J,q.defaultValue===void 0?!0:q.defaultValue,"default")}else if(q.defaultValue!==void 0)this.setOptionValueWithSource(J,q.defaultValue,"default");let Z=($,Q,X)=>{if($==null&&q.presetArg!==void 0)$=q.presetArg;let Y=this.getOptionValue(J);if($!==null&&q.parseArg)$=this._callParseArg(q,$,Y,Q);else if($!==null&&q.variadic)$=q._collectValue($,Y);if($==null)if(q.negate)$=!1;else if(q.isBoolean()||q.optional)$=!0;else $="";this.setOptionValueWithSource(J,$,X)};if(this.on("option:"+z,($)=>{let Q=`error: option '${q.flags}' argument '${$}' is invalid.`;Z($,Q,"cli")}),q.envVar)this.on("optionEnv:"+z,($)=>{let Q=`error: option '${q.flags}' value '${$}' from env '${q.envVar}' is invalid.`;Z($,Q,"env")});return this}_optionEx(q,z,J,Z,$){if(typeof z==="object"&&z instanceof Hq)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Q=this.createOption(z,J);if(Q.makeOptionMandatory(!!q.mandatory),typeof Z==="function")Q.default($).argParser(Z);else if(Z instanceof RegExp){let X=Z;Z=(Y,U)=>{let B=X.exec(Y);return B?B[0]:U},Q.default($).argParser(Z)}else Q.default(Z);return this.addOption(Q)}option(q,z,J,Z){return this._optionEx({},q,z,J,Z)}requiredOption(q,z,J,Z){return this._optionEx({mandatory:!0},q,z,J,Z)}combineFlagAndOptionalValue(q=!0){return this._combineFlagAndOptionalValue=!!q,this}allowUnknownOption(q=!0){return this._allowUnknownOption=!!q,this}allowExcessArguments(q=!0){return this._allowExcessArguments=!!q,this}enablePositionalOptions(q=!0){return this._enablePositionalOptions=!!q,this}passThroughOptions(q=!0){return this._passThroughOptions=!!q,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(q=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!q,this}getOptionValue(q){if(this._storeOptionsAsProperties)return this[q];return this._optionValues[q]}setOptionValue(q,z){return this.setOptionValueWithSource(q,z,void 0)}setOptionValueWithSource(q,z,J){if(this._storeOptionsAsProperties)this[q]=z;else this._optionValues[q]=z;return this._optionValueSources[q]=J,this}getOptionValueSource(q){return this._optionValueSources[q]}getOptionValueSourceWithGlobals(q){let z;return this._getCommandAndAncestors().forEach((J)=>{if(J.getOptionValueSource(q)!==void 0)z=J.getOptionValueSource(q)}),z}_prepareUserArgs(q,z){if(q!==void 0&&!Array.isArray(q))throw Error("first parameter to parse must be array or undefined");if(z=z||{},q===void 0&&z.from===void 0){if(K.versions?.electron)z.from="electron";let Z=K.execArgv??[];if(Z.includes("-e")||Z.includes("--eval")||Z.includes("-p")||Z.includes("--print"))z.from="eval"}if(q===void 0)q=K.argv;this.rawArgs=q.slice();let J;switch(z.from){case void 0:case"node":this._scriptPath=q[1],J=q.slice(2);break;case"electron":if(K.defaultApp)this._scriptPath=q[1],J=q.slice(2);else J=q.slice(1);break;case"user":J=q.slice(0);break;case"eval":J=q.slice(1);break;default:throw Error(`unexpected parse option { from: '${z.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",J}parse(q,z){this._prepareForParse();let J=this._prepareUserArgs(q,z);return this._parseCommand([],J),this}async parseAsync(q,z){this._prepareForParse();let J=this._prepareUserArgs(q,z);return await this._parseCommand([],J),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(q,z,J){if(b.existsSync(q))return;let Z=z?`searched for local subcommand relative to directory '${z}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",$=`'${q}' does not exist
|
|
19
|
+
- if '${J}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
+
- ${Z}`;throw Error($)}_executeSubCommand(q,z){z=z.slice();let J=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function $(B,H){let G=T.resolve(B,H);if(b.existsSync(G))return G;if(Z.includes(T.extname(H)))return;let F=Z.find((N)=>b.existsSync(`${G}${N}`));if(F)return`${G}${F}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Q=q._executableFile||`${this._name}-${q._name}`,X=this._executableDir||"";if(this._scriptPath){let B;try{B=b.realpathSync(this._scriptPath)}catch{B=this._scriptPath}X=T.resolve(T.dirname(B),X)}if(X){let B=$(X,Q);if(!B&&!q._executableFile&&this._scriptPath){let H=T.basename(this._scriptPath,T.extname(this._scriptPath));if(H!==this._name)B=$(X,`${H}-${q._name}`)}Q=B||Q}J=Z.includes(T.extname(Q));let Y;if(K.platform!=="win32")if(J)z.unshift(Q),z=Gq(K.execArgv).concat(z),Y=c.spawn(K.argv[0],z,{stdio:"inherit"});else Y=c.spawn(Q,z,{stdio:"inherit"});else this._checkForMissingExecutable(Q,X,q._name),z.unshift(Q),z=Gq(K.execArgv).concat(z),Y=c.spawn(K.execPath,z,{stdio:"inherit"});if(!Y.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((H)=>{K.on(H,()=>{if(Y.killed===!1&&Y.exitCode===null)Y.kill(H)})});let U=this._exitCallback;Y.on("close",(B)=>{if(B=B??1,!U)K.exit(B);else U(new d(B,"commander.executeSubCommandAsync","(close)"))}),Y.on("error",(B)=>{if(B.code==="ENOENT")this._checkForMissingExecutable(Q,X,q._name);else if(B.code==="EACCES")throw Error(`'${Q}' not executable`);if(!U)K.exit(1);else{let H=new d(1,"commander.executeSubCommandAsync","(error)");H.nestedError=B,U(H)}}),this.runningCommand=Y}_dispatchSubcommand(q,z,J){let Z=this._findCommand(q);if(!Z)this.help({error:!0});Z._prepareForParse();let $;return $=this._chainOrCallSubCommandHook($,Z,"preSubcommand"),$=this._chainOrCall($,()=>{if(Z._executableHandler)this._executeSubCommand(Z,z.concat(J));else return Z._parseCommand(z,J)}),$}_dispatchHelpCommand(q){if(!q)this.help();let z=this._findCommand(q);if(z&&!z._executableHandler)z.help();return this._dispatchSubcommand(q,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((q,z)=>{if(q.required&&this.args[z]==null)this.missingArgument(q.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let q=(J,Z,$)=>{let Q=Z;if(Z!==null&&J.parseArg){let X=`error: command-argument value '${Z}' is invalid for argument '${J.name()}'.`;Q=this._callParseArg(J,Z,$,X)}return Q};this._checkNumberOfArguments();let z=[];this.registeredArguments.forEach((J,Z)=>{let $=J.defaultValue;if(J.variadic){if(Z<this.args.length){if($=this.args.slice(Z),J.parseArg)$=$.reduce((Q,X)=>{return q(J,X,Q)},J.defaultValue)}else if($===void 0)$=[]}else if(Z<this.args.length){if($=this.args[Z],J.parseArg)$=q(J,$,J.defaultValue)}z[Z]=$}),this.processedArgs=z}_chainOrCall(q,z){if(q?.then&&typeof q.then==="function")return q.then(()=>z());return z()}_chainOrCallHooks(q,z){let J=q,Z=[];if(this._getCommandAndAncestors().reverse().filter(($)=>$._lifeCycleHooks[z]!==void 0).forEach(($)=>{$._lifeCycleHooks[z].forEach((Q)=>{Z.push({hookedCommand:$,callback:Q})})}),z==="postAction")Z.reverse();return Z.forEach(($)=>{J=this._chainOrCall(J,()=>{return $.callback($.hookedCommand,this)})}),J}_chainOrCallSubCommandHook(q,z,J){let Z=q;if(this._lifeCycleHooks[J]!==void 0)this._lifeCycleHooks[J].forEach(($)=>{Z=this._chainOrCall(Z,()=>{return $(this,z)})});return Z}_parseCommand(q,z){let J=this.parseOptions(z);if(this._parseOptionsEnv(),this._parseOptionsImplied(),q=q.concat(J.operands),z=J.unknown,this.args=q.concat(z),q&&this._findCommand(q[0]))return this._dispatchSubcommand(q[0],q.slice(1),z);if(this._getHelpCommand()&&q[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(q[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(z),this._dispatchSubcommand(this._defaultCommandName,q,z);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(J.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Z=()=>{if(J.unknown.length>0)this.unknownOption(J.unknown[0])},$=`command:${this.name()}`;if(this._actionHandler){Z(),this._processArguments();let Q;if(Q=this._chainOrCallHooks(Q,"preAction"),Q=this._chainOrCall(Q,()=>this._actionHandler(this.processedArgs)),this.parent)Q=this._chainOrCall(Q,()=>{this.parent.emit($,q,z)});return Q=this._chainOrCallHooks(Q,"postAction"),Q}if(this.parent?.listenerCount($))Z(),this._processArguments(),this.parent.emit($,q,z);else if(q.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",q,z);if(this.listenerCount("command:*"))this.emit("command:*",q,z);else if(this.commands.length)this.unknownCommand();else Z(),this._processArguments()}else if(this.commands.length)Z(),this.help({error:!0});else Z(),this._processArguments()}_findCommand(q){if(!q)return;return this.commands.find((z)=>z._name===q||z._aliases.includes(q))}_findOption(q){return this.options.find((z)=>z.is(q))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((q)=>{q.options.forEach((z)=>{if(z.mandatory&&q.getOptionValue(z.attributeName())===void 0)q.missingMandatoryOptionValue(z)})})}_checkForConflictingLocalOptions(){let q=this.options.filter((J)=>{let Z=J.attributeName();if(this.getOptionValue(Z)===void 0)return!1;return this.getOptionValueSource(Z)!=="default"});q.filter((J)=>J.conflictsWith.length>0).forEach((J)=>{let Z=q.find(($)=>J.conflictsWith.includes($.attributeName()));if(Z)this._conflictingOption(J,Z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((q)=>{q._checkForConflictingLocalOptions()})}parseOptions(q){let z=[],J=[],Z=z;function $(B){return B.length>1&&B[0]==="-"}let Q=(B)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(B))return!1;return!this._getCommandAndAncestors().some((H)=>H.options.map((G)=>G.short).some((G)=>/^-\d$/.test(G)))},X=null,Y=null,U=0;while(U<q.length||Y){let B=Y??q[U++];if(Y=null,B==="--"){if(Z===J)Z.push(B);Z.push(...q.slice(U));break}if(X&&(!$(B)||Q(B))){this.emit(`option:${X.name()}`,B);continue}if(X=null,$(B)){let H=this._findOption(B);if(H){if(H.required){let G=q[U++];if(G===void 0)this.optionMissingArgument(H);this.emit(`option:${H.name()}`,G)}else if(H.optional){let G=null;if(U<q.length&&(!$(q[U])||Q(q[U])))G=q[U++];this.emit(`option:${H.name()}`,G)}else this.emit(`option:${H.name()}`);X=H.variadic?H:null;continue}}if(B.length>2&&B[0]==="-"&&B[1]!=="-"){let H=this._findOption(`-${B[1]}`);if(H){if(H.required||H.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${H.name()}`,B.slice(2));else this.emit(`option:${H.name()}`),Y=`-${B.slice(2)}`;continue}}if(/^--[^=]+=/.test(B)){let H=B.indexOf("="),G=this._findOption(B.slice(0,H));if(G&&(G.required||G.optional)){this.emit(`option:${G.name()}`,B.slice(H+1));continue}}if(Z===z&&$(B)&&!(this.commands.length===0&&Q(B)))Z=J;if((this._enablePositionalOptions||this._passThroughOptions)&&z.length===0&&J.length===0){if(this._findCommand(B)){z.push(B),J.push(...q.slice(U));break}else if(this._getHelpCommand()&&B===this._getHelpCommand().name()){z.push(B,...q.slice(U));break}else if(this._defaultCommandName){J.push(B,...q.slice(U));break}}if(this._passThroughOptions){Z.push(B,...q.slice(U));break}Z.push(B)}return{operands:z,unknown:J}}opts(){if(this._storeOptionsAsProperties){let q={},z=this.options.length;for(let J=0;J<z;J++){let Z=this.options[J].attributeName();q[Z]=Z===this._versionOptionName?this._version:this[Z]}return q}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((q,z)=>Object.assign(q,z.opts()),{})}error(q,z){if(this._outputConfiguration.outputError(`${q}
|
|
22
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
|
+
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
24
|
+
`),this.outputHelp({error:!0});let J=z||{},Z=J.exitCode||1,$=J.code||"commander.error";this._exit(Z,$,q)}_parseOptionsEnv(){this.options.forEach((q)=>{if(q.envVar&&q.envVar in K.env){let z=q.attributeName();if(this.getOptionValue(z)===void 0||["default","config","env"].includes(this.getOptionValueSource(z)))if(q.required||q.optional)this.emit(`optionEnv:${q.name()}`,K.env[q.envVar]);else this.emit(`optionEnv:${q.name()}`)}})}_parseOptionsImplied(){let q=new w1(this.options),z=(J)=>{return this.getOptionValue(J)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(J))};this.options.filter((J)=>J.implied!==void 0&&z(J.attributeName())&&q.valueFromOption(this.getOptionValue(J.attributeName()),J)).forEach((J)=>{Object.keys(J.implied).filter((Z)=>!z(Z)).forEach((Z)=>{this.setOptionValueWithSource(Z,J.implied[Z],"implied")})})}missingArgument(q){let z=`error: missing required argument '${q}'`;this.error(z,{code:"commander.missingArgument"})}optionMissingArgument(q){let z=`error: option '${q.flags}' argument missing`;this.error(z,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(q){let z=`error: required option '${q.flags}' not specified`;this.error(z,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(q,z){let J=(Q)=>{let X=Q.attributeName(),Y=this.getOptionValue(X),U=this.options.find((H)=>H.negate&&X===H.attributeName()),B=this.options.find((H)=>!H.negate&&X===H.attributeName());if(U&&(U.presetArg===void 0&&Y===!1||U.presetArg!==void 0&&Y===U.presetArg))return U;return B||Q},Z=(Q)=>{let X=J(Q),Y=X.attributeName();if(this.getOptionValueSource(Y)==="env")return`environment variable '${X.envVar}'`;return`option '${X.flags}'`},$=`error: ${Z(q)} cannot be used with ${Z(z)}`;this.error($,{code:"commander.conflictingOption"})}unknownOption(q){if(this._allowUnknownOption)return;let z="";if(q.startsWith("--")&&this._showSuggestionAfterError){let Z=[],$=this;do{let Q=$.createHelp().visibleOptions($).filter((X)=>X.long).map((X)=>X.long);Z=Z.concat(Q),$=$.parent}while($&&!$._enablePositionalOptions);z=Uq(q,Z)}let J=`error: unknown option '${q}'${z}`;this.error(J,{code:"commander.unknownOption"})}_excessArguments(q){if(this._allowExcessArguments)return;let z=this.registeredArguments.length,J=z===1?"":"s",$=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${z} argument${J} but got ${q.length}.`;this.error($,{code:"commander.excessArguments"})}unknownCommand(){let q=this.args[0],z="";if(this._showSuggestionAfterError){let Z=[];this.createHelp().visibleCommands(this).forEach(($)=>{if(Z.push($.name()),$.alias())Z.push($.alias())}),z=Uq(q,Z)}let J=`error: unknown command '${q}'${z}`;this.error(J,{code:"commander.unknownCommand"})}version(q,z,J){if(q===void 0)return this._version;this._version=q,z=z||"-V, --version",J=J||"output the version number";let Z=this.createOption(z,J);return this._versionOptionName=Z.attributeName(),this._registerOption(Z),this.on("option:"+Z.name(),()=>{this._outputConfiguration.writeOut(`${q}
|
|
25
|
+
`),this._exit(0,"commander.version",q)}),this}description(q,z){if(q===void 0&&z===void 0)return this._description;if(this._description=q,z)this._argsDescription=z;return this}summary(q){if(q===void 0)return this._summary;return this._summary=q,this}alias(q){if(q===void 0)return this._aliases[0];let z=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)z=this.commands[this.commands.length-1];if(q===z._name)throw Error("Command alias can't be the same as its name");let J=this.parent?._findCommand(q);if(J){let Z=[J.name()].concat(J.aliases()).join("|");throw Error(`cannot add alias '${q}' to command '${this.name()}' as already have command '${Z}'`)}return z._aliases.push(q),this}aliases(q){if(q===void 0)return this._aliases;return q.forEach((z)=>this.alias(z)),this}usage(q){if(q===void 0){if(this._usage)return this._usage;let z=this.registeredArguments.map((J)=>{return D1(J)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?z:[]).join(" ")}return this._usage=q,this}name(q){if(q===void 0)return this._name;return this._name=q,this}helpGroup(q){if(q===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=q,this}commandsGroup(q){if(q===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=q,this}optionsGroup(q){if(q===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=q,this}_initOptionGroup(q){if(this._defaultOptionGroup&&!q.helpGroupHeading)q.helpGroup(this._defaultOptionGroup)}_initCommandGroup(q){if(this._defaultCommandGroup&&!q.helpGroup())q.helpGroup(this._defaultCommandGroup)}nameFromFilename(q){return this._name=T.basename(q,T.extname(q)),this}executableDir(q){if(q===void 0)return this._executableDir;return this._executableDir=q,this}helpInformation(q){let z=this.createHelp(),J=this._getOutputContext(q);z.prepareContext({error:J.error,helpWidth:J.helpWidth,outputHasColors:J.hasColors});let Z=z.formatHelp(this,z);if(J.hasColors)return Z;return this._outputConfiguration.stripColor(Z)}_getOutputContext(q){q=q||{};let z=!!q.error,J,Z,$;if(z)J=(X)=>this._outputConfiguration.writeErr(X),Z=this._outputConfiguration.getErrHasColors(),$=this._outputConfiguration.getErrHelpWidth();else J=(X)=>this._outputConfiguration.writeOut(X),Z=this._outputConfiguration.getOutHasColors(),$=this._outputConfiguration.getOutHelpWidth();return{error:z,write:(X)=>{if(!Z)X=this._outputConfiguration.stripColor(X);return J(X)},hasColors:Z,helpWidth:$}}outputHelp(q){let z;if(typeof q==="function")z=q,q=void 0;let J=this._getOutputContext(q),Z={error:J.error,write:J.write,command:this};this._getCommandAndAncestors().reverse().forEach((Q)=>Q.emit("beforeAllHelp",Z)),this.emit("beforeHelp",Z);let $=this.helpInformation({error:J.error});if(z){if($=z($),typeof $!=="string"&&!Buffer.isBuffer($))throw Error("outputHelp callback must return a string or a Buffer")}if(J.write($),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",Z),this._getCommandAndAncestors().forEach((Q)=>Q.emit("afterAllHelp",Z))}helpOption(q,z){if(typeof q==="boolean"){if(q){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(q??"-h, --help",z??"display help for command"),q||z)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(q){return this._helpOption=q,this._initOptionGroup(q),this}help(q){this.outputHelp(q);let z=Number(K.exitCode??0);if(z===0&&q&&typeof q!=="function"&&q.error)z=1;this._exit(z,"commander.help","(outputHelp)")}addHelpText(q,z){let J=["beforeAll","before","after","afterAll"];if(!J.includes(q))throw Error(`Unexpected value for position to addHelpText.
|
|
26
|
+
Expecting one of '${J.join("', '")}'`);let Z=`${q}Help`;return this.on(Z,($)=>{let Q;if(typeof z==="function")Q=z({error:$.error,command:$.command});else Q=z;if(Q)$.write(`${Q}
|
|
27
|
+
`)}),this}_outputHelpIfRequested(q){let z=this._getHelpOption();if(z&&q.find((Z)=>z.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Gq(q){return q.map((z)=>{if(!z.startsWith("--inspect"))return z;let J,Z="127.0.0.1",$="9229",Q;if((Q=z.match(/^(--inspect(-brk)?)$/))!==null)J=Q[1];else if((Q=z.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(J=Q[1],/^\d+$/.test(Q[3]))$=Q[3];else Z=Q[3];else if((Q=z.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)J=Q[1],Z=Q[3],$=Q[4];if(J&&$!=="0")return`${J}=${Z}:${parseInt($)+1}`;return z})}function l(){if(K.env.NO_COLOR||K.env.FORCE_COLOR==="0"||K.env.FORCE_COLOR==="false")return!1;if(K.env.FORCE_COLOR||K.env.CLICOLOR_FORCE!==void 0)return!0;return}S1.Command=p;S1.useColor=l});var Vq=I((k1)=>{var{Argument:Wq}=C(),{Command:i}=Kq(),{CommanderError:O1,InvalidArgumentError:Mq}=A(),{Help:x1}=g(),{Option:Lq}=m();k1.program=new i;k1.createCommand=(q)=>new i(q);k1.createOption=(q,z)=>new Lq(q,z);k1.createArgument=(q,z)=>new Wq(q,z);k1.Command=i;k1.Option=Lq;k1.Argument=Wq;k1.Help=x1;k1.CommanderError=O1;k1.InvalidArgumentError=Mq;k1.InvalidOptionArgumentError=Mq});var Rq=oq(Vq(),1),{program:sz,createCommand:rz,createArgument:nz,createOption:az,CommanderError:tz,InvalidArgumentError:oz,InvalidOptionArgumentError:ez,Command:Pq,Argument:qJ,Option:zJ,Help:JJ}=Rq.default;import{join as R,resolve as cq}from"path";import{writeFileSync as Iz}from"fs";var Tq=(q=0)=>(z)=>`\x1B[${z+q}m`,jq=(q=0)=>(z)=>`\x1B[${38+q};5;${z}m`,Nq=(q=0)=>(z,J,Z)=>`\x1B[${38+q};2;${z};${J};${Z}m`,M={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},$J=Object.keys(M.modifier),l1=Object.keys(M.color),p1=Object.keys(M.bgColor),QJ=[...l1,...p1];function i1(){let q=new Map;for(let[z,J]of Object.entries(M)){for(let[Z,$]of Object.entries(J))M[Z]={open:`\x1B[${$[0]}m`,close:`\x1B[${$[1]}m`},J[Z]=M[Z],q.set($[0],$[1]);Object.defineProperty(M,z,{value:J,enumerable:!1})}return Object.defineProperty(M,"codes",{value:q,enumerable:!1}),M.color.close="\x1B[39m",M.bgColor.close="\x1B[49m",M.color.ansi=Tq(),M.color.ansi256=jq(),M.color.ansi16m=Nq(),M.bgColor.ansi=Tq(10),M.bgColor.ansi256=jq(10),M.bgColor.ansi16m=Nq(10),Object.defineProperties(M,{rgbToAnsi256:{value(z,J,Z){if(z===J&&J===Z){if(z<8)return 16;if(z>248)return 231;return Math.round((z-8)/247*24)+232}return 16+36*Math.round(z/255*5)+6*Math.round(J/255*5)+Math.round(Z/255*5)},enumerable:!1},hexToRgb:{value(z){let J=/[a-f\d]{6}|[a-f\d]{3}/i.exec(z.toString(16));if(!J)return[0,0,0];let[Z]=J;if(Z.length===3)Z=[...Z].map((Q)=>Q+Q).join("");let $=Number.parseInt(Z,16);return[$>>16&255,$>>8&255,$&255]},enumerable:!1},hexToAnsi256:{value:(z)=>M.rgbToAnsi256(...M.hexToRgb(z)),enumerable:!1},ansi256ToAnsi:{value(z){if(z<8)return 30+z;if(z<16)return 90+(z-8);let J,Z,$;if(z>=232)J=((z-232)*10+8)/255,Z=J,$=J;else{z-=16;let Y=z%36;J=Math.floor(z/36)/5,Z=Math.floor(Y/6)/5,$=Y%6/5}let Q=Math.max(J,Z,$)*2;if(Q===0)return 30;let X=30+(Math.round($)<<2|Math.round(Z)<<1|Math.round(J));if(Q===2)X+=60;return X},enumerable:!1},rgbToAnsi:{value:(z,J,Z)=>M.ansi256ToAnsi(M.rgbToAnsi256(z,J,Z)),enumerable:!1},hexToAnsi:{value:(z)=>M.ansi256ToAnsi(M.hexToAnsi256(z)),enumerable:!1}}),M}var s1=i1(),P=s1;import s from"node:process";import r1 from"node:os";import Iq from"node:tty";function V(q,z=globalThis.Deno?globalThis.Deno.args:s.argv){let J=q.startsWith("-")?"":q.length===1?"-":"--",Z=z.indexOf(J+q),$=z.indexOf("--");return Z!==-1&&($===-1||Z<$)}var{env:L}=s,y;if(V("no-color")||V("no-colors")||V("color=false")||V("color=never"))y=0;else if(V("color")||V("colors")||V("color=true")||V("color=always"))y=1;function n1(){if("FORCE_COLOR"in L){if(L.FORCE_COLOR==="true")return 1;if(L.FORCE_COLOR==="false")return 0;return L.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(L.FORCE_COLOR,10),3)}}function a1(q){if(q===0)return!1;return{level:q,hasBasic:!0,has256:q>=2,has16m:q>=3}}function t1(q,{streamIsTTY:z,sniffFlags:J=!0}={}){let Z=n1();if(Z!==void 0)y=Z;let $=J?y:Z;if($===0)return 0;if(J){if(V("color=16m")||V("color=full")||V("color=truecolor"))return 3;if(V("color=256"))return 2}if("TF_BUILD"in L&&"AGENT_NAME"in L)return 1;if(q&&!z&&$===void 0)return 0;let Q=$||0;if(L.TERM==="dumb")return Q;if(s.platform==="win32"){let X=r1.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in L){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((X)=>(X in L)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((X)=>(X in L))||L.CI_NAME==="codeship")return 1;return Q}if("TEAMCITY_VERSION"in L)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(L.TEAMCITY_VERSION)?1:0;if(L.COLORTERM==="truecolor")return 3;if(L.TERM==="xterm-kitty")return 3;if(L.TERM==="xterm-ghostty")return 3;if(L.TERM==="wezterm")return 3;if("TERM_PROGRAM"in L){let X=Number.parseInt((L.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(L.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(L.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(L.TERM))return 1;if("COLORTERM"in L)return 1;return Q}function Dq(q,z={}){let J=t1(q,{streamIsTTY:q&&q.isTTY,...z});return a1(J)}var o1={stdout:Dq({isTTY:Iq.isatty(1)}),stderr:Dq({isTTY:Iq.isatty(2)})},Eq=o1;function Fq(q,z,J){let Z=q.indexOf(z);if(Z===-1)return q;let $=z.length,Q=0,X="";do X+=q.slice(Q,Z)+z+J,Q=Z+$,Z=q.indexOf(z,Q);while(Z!==-1);return X+=q.slice(Q),X}function wq(q,z,J,Z){let $=0,Q="";do{let X=q[Z-1]==="\r";Q+=q.slice($,X?Z-1:Z)+z+(X?`\r
|
|
28
|
+
`:`
|
|
29
|
+
`)+J,$=Z+1,Z=q.indexOf(`
|
|
30
|
+
`,$)}while(Z!==-1);return Q+=q.slice($),Q}var{stdout:Sq,stderr:_q}=Eq,r=Symbol("GENERATOR"),w=Symbol("STYLER"),O=Symbol("IS_EMPTY"),Aq=["ansi","ansi","ansi256","ansi16m"],S=Object.create(null),e1=(q,z={})=>{if(z.level&&!(Number.isInteger(z.level)&&z.level>=0&&z.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let J=Sq?Sq.level:0;q.level=z.level===void 0?J:z.level};var qz=(q)=>{let z=(...J)=>J.join(" ");return e1(z,q),Object.setPrototypeOf(z,x.prototype),z};function x(q){return qz(q)}Object.setPrototypeOf(x.prototype,Function.prototype);for(let[q,z]of Object.entries(P))S[q]={get(){let J=f(this,a(z.open,z.close,this[w]),this[O]);return Object.defineProperty(this,q,{value:J}),J}};S.visible={get(){let q=f(this,this[w],!0);return Object.defineProperty(this,"visible",{value:q}),q}};var n=(q,z,J,...Z)=>{if(q==="rgb"){if(z==="ansi16m")return P[J].ansi16m(...Z);if(z==="ansi256")return P[J].ansi256(P.rgbToAnsi256(...Z));return P[J].ansi(P.rgbToAnsi(...Z))}if(q==="hex")return n("rgb",z,J,...P.hexToRgb(...Z));return P[J][q](...Z)},zz=["rgb","hex","ansi256"];for(let q of zz){S[q]={get(){let{level:J}=this;return function(...Z){let $=a(n(q,Aq[J],"color",...Z),P.color.close,this[w]);return f(this,$,this[O])}}};let z="bg"+q[0].toUpperCase()+q.slice(1);S[z]={get(){let{level:J}=this;return function(...Z){let $=a(n(q,Aq[J],"bgColor",...Z),P.bgColor.close,this[w]);return f(this,$,this[O])}}}}var Jz=Object.defineProperties(()=>{},{...S,level:{enumerable:!0,get(){return this[r].level},set(q){this[r].level=q}}}),a=(q,z,J)=>{let Z,$;if(J===void 0)Z=q,$=z;else Z=J.openAll+q,$=z+J.closeAll;return{open:q,close:z,openAll:Z,closeAll:$,parent:J}},f=(q,z,J)=>{let Z=(...$)=>Zz(Z,$.length===1?""+$[0]:$.join(" "));return Object.setPrototypeOf(Z,Jz),Z[r]=q,Z[w]=z,Z[O]=J,Z},Zz=(q,z)=>{if(q.level<=0||!z)return q[O]?"":z;let J=q[w];if(J===void 0)return z;let{openAll:Z,closeAll:$}=J;if(z.includes("\x1B"))while(J!==void 0)z=Fq(z,J.close,J.open),J=J.parent;let Q=z.indexOf(`
|
|
31
|
+
`);if(Q!==-1)z=wq(z,$,Z,Q);return Z+z+$};Object.defineProperties(x.prototype,S);var $z=x(),LJ=x({level:_q?_q.level:0});var W=$z;import{mkdirSync as Qz,existsSync as xq,readdirSync as Xz,statSync as Yz,copyFileSync as Bz}from"fs";import{join as Oq,dirname as Hz}from"path";function j(q){if(!xq(q))Qz(q,{recursive:!0})}function D(q){return xq(q)}function t(q,z){j(Hz(z)),Bz(q,z)}function k(q,z){j(z);let J=Xz(q);for(let Z of J){let $=Oq(q,Z),Q=Oq(z,Z);if(Yz($).isDirectory())k($,Q);else t($,Q)}}import{readFileSync as Cq,writeFileSync as bq}from"fs";import{join as v}from"path";var yq=".vscode",Uz="settings.json",Gz="extensions.json",Kz=".agentica/prompts",Wz=".agentica/skills",kq="Upstash.context7-mcp";function fq(q){let z=v(q,yq),J=v(z,Uz);j(z);let Z={};if(D(J)){let Q=Cq(J,"utf-8");try{Z=JSON.parse(Q)}catch(X){throw Error(`Invalid JSON in ${J}: ${X}`)}}Z["chat.promptFilesLocations"]??={},Z["chat.promptFilesLocations"][Kz]=!0,Z["chat.agentSkillsLocations"]??={},Z["chat.agentSkillsLocations"][Wz]=!0;let $=JSON.stringify(Z,null,2);bq(J,$,"utf-8")}function vq(q){let z=v(q,yq),J=v(z,Gz);j(z);let Z={};if(D(J)){let X=Cq(J,"utf-8");try{Z=JSON.parse(X)}catch(Y){throw Error(`Invalid JSON in ${J}: ${Y}`)}}let $=Array.isArray(Z.recommendations)?Z.recommendations:[];if(!$.includes(kq))$.push(kq);Z.recommendations=$;let Q=JSON.stringify(Z,null,2);bq(J,Q,"utf-8")}import{readFileSync as o,writeFileSync as Mz,renameSync as Lz}from"fs";import{join as E}from"path";var Vz="AGENTS.md",Rz="AGENTS.old.md",Pz=`
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
`,Tz="globals",jz="anti-spaghetti.md",Nz="use-agentica.md";function hq(q,z,J){let Z=E(z,".agentica"),$=E(Z,Vz),Q=E(Z,Rz);if(D($))Lz($,Q);let X=E(q,Tz),Y=`lang-${J}.md`,U=o(E(X,Y),"utf-8"),B=o(E(X,jz),"utf-8"),H=o(E(X,Nz),"utf-8"),G=[U,B,H].join(Pz);Mz($,G,"utf-8")}var __dirname="E:\\Dev\\2026-02-15 - Agentica\\src\\commands",Dz=".agentica",uq="prompts",gq="templates",mq="skills",Ez="stacks",Fz="status.md",dq=1,wz=["prompts","templates","architecture","changes","features"],Sz=["product.md","structure.md","tech.md"];async function lq(q){console.log(W.blue(`
|
|
36
|
+
\uD83D\uDE80 Инициализация Agentica...
|
|
37
|
+
`));let z=Az(q.stack);if(!z)_z(q.stack);await new pq(q,z).execute()}class pq{options;stack;repoRoot;targetDir;stackDir;agenticaDir;constructor(q,z){this.options=q;this.stack=z;this.repoRoot=Oz(),this.targetDir=this.options.name?cq(process.cwd(),this.options.name):process.cwd(),this.stackDir=R(this.repoRoot,Ez,this.stack.lang,this.stack.type),this.agenticaDir=R(this.targetDir,Dz)}async execute(){this.ensureStackExists(),this.createProjectDirIfNeeded(),this.createAgenticaDirectories(),this.copyPrompts(),this.copyTemplates(),this.copySkills(),this.copyStackTemplateFiles(),this.createStatusFile(),this.composeAgentsFile(),this.updateVSCodeConfiguration(),this.printSuccessMessage()}ensureStackExists(){if(D(this.stackDir))return;console.error(W.red(`❌ Стек не найден: ${this.stack.lang}/${this.stack.type}`)),console.error(W.yellow(` Путь проверки: ${this.stackDir}`)),process.exit(dq)}createProjectDirIfNeeded(){if(!this.options.name)return;j(this.targetDir),console.log(W.green(`✓ Создана директория: ${this.options.name}`))}createAgenticaDirectories(){j(this.agenticaDir),console.log(W.green("✓ Создана .agentica/"));for(let q of wz)j(R(this.agenticaDir,q))}copyPrompts(){let q=R(this.repoRoot,uq),z=R(this.agenticaDir,uq);k(q,z),console.log(W.green("✓ Скопирована prompts/"))}copyTemplates(){let q=R(this.repoRoot,gq),z=R(this.agenticaDir,gq);k(q,z),console.log(W.green("✓ Скопирована templates/"))}copySkills(){let q=R(this.repoRoot,mq),z=R(this.agenticaDir,mq);k(q,z),console.log(W.green("✓ Скопирована skills/"))}copyStackTemplateFiles(){for(let q of Sz){let z=R(this.stackDir,q),J=R(this.agenticaDir,q);t(z,J)}console.log(W.green(`✓ Скопирован шаблон стека: ${this.stack.lang}/${this.stack.type}`))}createStatusFile(){let q=xz(this.stack),z=R(this.agenticaDir,Fz);Iz(z,q,"utf-8"),console.log(W.green("✓ Создан status.md"))}composeAgentsFile(){hq(this.repoRoot,this.targetDir,this.stack.lang),console.log(W.green("✓ Сформирован AGENTS.md"))}updateVSCodeConfiguration(){try{fq(this.targetDir),vq(this.targetDir),console.log(W.green("✓ Обновлён .vscode/settings.json")),console.log(W.green("✓ Обновлён .vscode/extensions.json"))}catch(q){console.warn(W.yellow(`⚠ Предупреждение: не удалось обновить настройки VSCode: ${q}`))}}printSuccessMessage(){if(console.log(W.green.bold(`
|
|
38
|
+
✨ Agentica успешно инициализирована!
|
|
39
|
+
`)),console.log(W.cyan("Следующие шаги:")),this.options.name)console.log(W.white(` 1. cd ${this.options.name}`));console.log(W.white(" 2. Открой проект в VSCode: code .")),console.log(W.white(` 3. Начни с промпта /agentica.init d чате Copilot:
|
|
40
|
+
- Опиши свой проект, и стек технологий (после команды)
|
|
41
|
+
- Agentica подстроится под твои нужды
|
|
42
|
+
- А дальще можно запускать /agentica.create или /agentica.change
|
|
43
|
+
- И обязательно прочитай и донастрой AGENTS.md
|
|
44
|
+
`))}}function _z(q){console.error(W.red(`❌ Неверный формат стека: ${q}`)),console.error(W.yellow(" Ожидаемый формат: <lang>/<type>")),console.error(W.yellow(" Примеры: typescript/cli, python/gui")),process.exit(dq)}function Az(q){let z=q.split("/");if(z.length!==2)return null;let[J,Z]=z;if(!J||!Z)return null;return{lang:J,type:Z}}function Oz(){return cq(__dirname,"../..")}function xz(q){return`# Статус Agentica
|
|
45
|
+
|
|
46
|
+
## Инициализация
|
|
47
|
+
|
|
48
|
+
- **Дата:** ${new Date().toISOString().split("T")[0]}
|
|
49
|
+
- **Стек:** ${q.lang}/${q.type}
|
|
50
|
+
- **Статус:** Инициализировано
|
|
51
|
+
|
|
52
|
+
## Статус интеграции
|
|
53
|
+
|
|
54
|
+
- [ ] Структура проекта приведена к шаблону стека
|
|
55
|
+
- [ ] Рабочее пространство VSCode настроено
|
|
56
|
+
- [ ] Создана первая спецификация фичи
|
|
57
|
+
- [ ] Завершена первая реализация
|
|
58
|
+
|
|
59
|
+
## Заметки
|
|
60
|
+
|
|
61
|
+
Добавьте здесь заметки о процессе интеграции.
|
|
62
|
+
`}import{readdirSync as kz,statSync as Cz}from"fs";import{join as e,resolve as bz}from"path";var __dirname="E:\\Dev\\2026-02-15 - Agentica\\src\\commands",yz="stacks";function sq(){let q=fz();if(q.length===0){console.log(W.yellow("Доступные шаблоны стеков не найдены."));return}console.log(W.green(`
|
|
63
|
+
Доступные шаблоны стеков [${q.length}]:
|
|
64
|
+
`));for(let z of q)console.log(` ${z}`);console.log(),console.log("Используй один из этих шаблонов чтобы проинициализировать проект:"),console.log(" agentica init typescript/cli")}function fz(){let q=vz(),z=e(q,yz),J=iq(z),Z=[];for(let $ of J){let Q=e(z,$),X=iq(Q);for(let Y of X)Z.push(`${$}/${Y}`)}return Z.sort()}function iq(q){let z=kz(q,{withFileTypes:!0}),J=[];for(let Z of z){if(!Z.isDirectory())continue;let $=e(q,Z.name);if(!Cz($).isDirectory())continue;J.push(Z.name)}return J}function vz(){return bz(__dirname,"../..")}var h=new Pq;h.name("agentica").description("Фреймворк для агентной разработки по спецификациям").version("0.1.0");h.command("init").description("Инициализировать Agentica в проекте").argument("[stack]","Шаблон стека (например, typescript/cli)").argument("[targetPath]","Путь проекта (по умолчанию текущая директория)").option("--stack <type>","Шаблон стека (альтернатива позиционному аргументу)").option("--out <path>","Путь проекта (альтернатива targetPath)").action(async(q,z,J)=>{let Z=q??J.stack,$=z??J.out;if(!Z)console.error("Ошибка: не указан stack. Используйте init <stack> или --stack <type>."),process.exit(1);let Q={stack:Z,name:$};try{await lq(Q)}catch(X){console.error("Ошибка:",X),process.exit(1)}});h.command("stacks").description("Показать доступные шаблоны проектов").action(sq);h.parse();
|