@consilium108/mcp-module-devops 1.0.0 → 1.1.0
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/CHANGELOG.md +22 -0
- package/README.md +144 -0
- package/bin/consilium-devops-mcp.js +66 -0
- package/bin/consilium-devops-runner.js +120 -0
- package/package.json +12 -5
- package/src/errors.js +12 -0
- package/src/groups/ops.js +125 -0
- package/src/index.js +2 -0
- package/src/runner/client.js +42 -0
- package/src/runner/config.js +143 -0
- package/src/runner/daemon.js +162 -0
- package/src/runner/doctor.js +111 -0
- package/src/runner/index.js +12 -0
- package/src/runner/install.js +113 -0
- package/src/runner/log.js +33 -0
- package/src/runner/recipes.js +230 -0
- package/src/runner/state.js +84 -0
- package/src/runner/steps.js +196 -0
- package/src/runner/watchdog.js +113 -0
- package/src/standalone.js +227 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.1.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
<!-- generated by Claude (Opus 5.5), 2026-11-22; Konsilium #482 (TASK-P37-482) -->
|
|
6
|
+
|
|
7
|
+
- The DevOps MCP on its own: `bin` `consilium-devops-mcp` (stdio) and `./standalone` (`createDevopsMcp`) — the module's
|
|
8
|
+
`deploy` and `debug` groups unchanged, plus `devops_session`, `select_project`, `list_deploy_targets`, `list_deploys`.
|
|
9
|
+
Credential: `KONSILIUM_API_KEY` or the `@consilium108/mcp login` sign-in; project: `--project` /
|
|
10
|
+
`KONSILIUM_PROJECT_ID` / `select_project` / the connection default; calls go to the core (it proxies to the DevOps
|
|
11
|
+
module) or with `--devops-api` straight to the module API. Stable error codes. No approval tools.
|
|
12
|
+
- The module definition (groups, tools of the host catalog) is unchanged — `@consilium108/mcp` and the cloud MCP keep
|
|
13
|
+
their tool lists. Dependencies: + `@modelcontextprotocol/sdk`, `zod` (runtime).
|
|
14
|
+
- `list_deploy_targets` / `list_deploys` need the core with the key routes of #482 (older core → `key_not_allowed`).
|
|
15
|
+
- The deploy runner joins the package as a SEPARATE service (2026-11-23, by the assistant's recommendation): bin
|
|
16
|
+
`consilium-devops-runner` (`run`, `once`, `doctor`, `install --print`, `unit --print`, `config --print`) and export
|
|
17
|
+
`./runner` (Node built-ins only). Ported from the monorepo's `deploy-runner/`: config outside the repository (mode 600
|
|
18
|
+
enforced, `tokenFile` / env overrides), explicit PATH with a preflight (`command_not_found` instead of «spawn docker
|
|
19
|
+
ENOENT»), recipe `konsilium-linux` (tests → web build → DB backup → `:prev` → `up -d --build app mcp` → healthy → checks;
|
|
20
|
+
rollback to `:prev`), JSON logs, heartbeat during a job, one deploy at a time, idempotent claim, graceful stop, systemd
|
|
21
|
+
unit printed (never installed). The watchdog no longer reads the core's `.env`. MCP tools `runner_status`,
|
|
22
|
+
`runner_setup` (standalone server only; the host catalog is unchanged). Extra bin `mcp-module-devops` keeps
|
|
23
|
+
`npx -y @consilium108/mcp-module-devops` starting the MCP now that the package has two commands.
|
|
24
|
+
|
|
3
25
|
## 1.0.0 (unreleased)
|
|
4
26
|
|
|
5
27
|
<!-- generated by Claude (Opus 5.5), 2026-11-20; Konsilium #442, SDD flows/sdd-consilium-mcp-modules -->
|
package/README.md
CHANGED
|
@@ -25,4 +25,148 @@ mod.id; // 'devops'
|
|
|
25
25
|
Object.keys(mod.groups);
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
+
## Отдельный MCP DevOps (1.1.0, #482)
|
|
29
|
+
|
|
30
|
+
<!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-22. -->
|
|
31
|
+
|
|
32
|
+
Тот же пакет запускается сам, без хоста и без остальных модулей: `bin` **`consilium-devops-mcp`** (stdio).
|
|
33
|
+
Инструменты (11): `devops_session` (кто, проекты и права, активный проект, включён ли модуль), `select_project`,
|
|
34
|
+
`request_deploy`, `deploy_status`, `list_deploy_targets` (цели и когда runner последний раз выходил на связь),
|
|
35
|
+
`list_deploys` (последние запросы), `runner_status` (runner каждой цели: на связи / нет, текущая выкатка, ожидающие),
|
|
36
|
+
`runner_setup` (шаги установки runner'а текстом — сам ничего не ставит), `list_debug_reports`, `get_debug_report`,
|
|
37
|
+
`attach_debug_capture`.
|
|
38
|
+
Одобрить, отклонить, откатить, создать цель или выдать право MCP **не может** — это делает человек с правом выкатки
|
|
39
|
+
(✅ в мессенджере / приложение). Бизнес-логики в MCP нет: каждый вызов — REST API Консилиума с ключом человека.
|
|
40
|
+
|
|
41
|
+
Куда идут вызовы: ядро Консилиума (`KONSILIUM_API_URL`, по умолчанию `https://konsilium.nativemind.net`); ядро
|
|
42
|
+
проверяет права и модуль и проксирует DevOps-маршруты в API модуля (`MODULE_DEVOPS=remote`). `--devops-api <url>` /
|
|
43
|
+
`DEVOPS_API_URL` — прямо в API модуля (те же пути; модуль сам проверяет ключ через ядро) — только когда он доступен
|
|
44
|
+
снаружи (сейчас нет: модуль слушает только сеть ядра).
|
|
45
|
+
|
|
46
|
+
Вход: ключ Консилиума в `KONSILIUM_API_KEY` (Аккаунт → API: нужный проект и право `tasks:work`) или OAuth-токен;
|
|
47
|
+
без него — вход `npx @consilium108/mcp login`, если этот пакет установлен. Никаких токенов модуля, секретов
|
|
48
|
+
сервера или runner здесь нет и не нужно.
|
|
49
|
+
|
|
50
|
+
Подключение (Claude Code, `.mcp.json`):
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"mcpServers": {
|
|
55
|
+
"consilium-devops": {
|
|
56
|
+
"command": "npx",
|
|
57
|
+
"args": ["-y", "@consilium108/mcp-module-devops", "--project", "37"],
|
|
58
|
+
"env": { "KONSILIUM_API_KEY": "${KONSILIUM_API_KEY}" }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Или `claude mcp add consilium-devops -e KONSILIUM_API_KEY=… -- npx -y @consilium108/mcp-module-devops --project 37`.
|
|
65
|
+
Удалённо (облачный MCP Консилиума, OAuth в клиенте): `https://konsilium.nativemind.net/mcp/p/<project_id>` —
|
|
66
|
+
там те же `request_deploy`, `deploy_status` и отчёты (модуль DevOps включается в «Подключённых приложениях»).
|
|
67
|
+
|
|
68
|
+
Ошибки — `code: message` и `structuredContent.error.code`: `auth_required`, `auth_invalid`, `project_not_chosen`,
|
|
69
|
+
`forbidden_project`, `no_deploy_right`, `module_disabled`, `module_unavailable`, `network_unavailable`,
|
|
70
|
+
`key_not_allowed` (ядро старше 1.1.0 — `list_deploy_targets` / `list_deploys` ещё не открыты для ключей), `rate_limited`.
|
|
71
|
+
|
|
72
|
+
## Runner
|
|
73
|
+
|
|
74
|
+
<!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-23. -->
|
|
75
|
+
|
|
76
|
+
Тот же пакет — вторая точка входа: **`consilium-devops-runner`**, долгоживущая служба на сервере проекта (systemd).
|
|
77
|
+
Это **не** процесс MCP: MCP только просит выкатку (`request_deploy`) и смотрит статус (`runner_status`); одобряет
|
|
78
|
+
человек (✅ в боте); runner берёт у ядра только одобренные запросы своей цели и выполняет команды **из своего
|
|
79
|
+
локального конфига** — сервер команд не присылает. Код runner'а — только встроенные модули Node (`./runner`,
|
|
80
|
+
`src/runner/*`), MCP SDK ему не нужен.
|
|
81
|
+
|
|
82
|
+
| Что | Как |
|
|
83
|
+
|---|---|
|
|
84
|
+
| Точки входа | `consilium-devops-mcp` (stdio MCP, агентам), `consilium-devops-runner` (служба); `mcp-module-devops` = MCP (для `npx -y @consilium108/mcp-module-devops`) |
|
|
85
|
+
| Вход в ядро | токен цели `kdr_…` (создаёт владелец: `/deploytarget <ключ> <название>` в боте, показывается один раз); не ключ человека |
|
|
86
|
+
| API | `POST /api/deploy/runner/heartbeat`, `/claim`, `/:id/result` ядра (ядро проксирует в API модуля, `MODULE_DEVOPS=remote`) |
|
|
87
|
+
| Конфиг | вне репозитория: `$CONSILIUM_DEVOPS_RUNNER_CONFIG` → `~/.config/consilium-devops-runner/config.json` → `/etc/consilium-devops-runner/config.json`; права 600 (иначе отказ `config_perms`); токен — `tokenFile` (600), `token` или `CONSILIUM_RUNNER_TOKEN` |
|
|
88
|
+
| Переопределения | `KONSILIUM_API_URL`, `CONSILIUM_RUNNER_PATH`, `CONSILIUM_RUNNER_STATE_DIR`, `CONSILIUM_RUNNER_LOG_FORMAT` (`json`/`text`), `CONSILIUM_RUNNER_TELEGRAM_TOKEN` |
|
|
89
|
+
| PATH | явный (`path` в конфиге; по умолчанию `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin` + `~/development/flutter/bin`, если есть); перед выкаткой проверяется, что все команды на месте — иначе ничего не запускается, ошибка `command_not_found: «docker» not on PATH (PATH=…)` (11.11 было «spawn docker ENOENT») |
|
|
90
|
+
| Надёжность | одна выкатка за раз (lock-файл), heartbeat и во время выкатки, идемпотентный claim (`state.json`: запрос не выполняется дважды, недоставленный итог досылается, прерванный — сообщается как `interrupted`), полный лог каждой выкатки — `<stateDir>/logs/D<id>.log`, в ядро — хвост 4096 символов |
|
|
91
|
+
| Остановка | SIGTERM ждёт конца текущей выкатки (`stopTimeoutMs`, по умолчанию 20 мин; юнит `KillMode=mixed`, `TimeoutStopSec=1500`); повторный сигнал прерывает шаг, откат всё равно выполняется |
|
|
92
|
+
| Логи | JSON по строке в stdout (journald); токены маскируются |
|
|
93
|
+
| Сторож (`watch`) | диск и health раз в минуту; в Telegram — только с токеном из **своего** файла runner'а (`watch.envFile`, например `~/.config/consilium-devops-runner/runner.env`) или `CONSILIUM_RUNNER_TELEGRAM_TOKEN`; файлы `.env*` (окружение ядра) не читаются; без токена — только журнал |
|
|
94
|
+
|
|
95
|
+
Команды (ничего не устанавливают и не запускают, кроме `run` / `once`):
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
consilium-devops-runner config --print --repo /path/to/consilium.nativemind.net > ~/.config/consilium-devops-runner/config.json
|
|
99
|
+
consilium-devops-runner doctor [--heartbeat] [--no-docker] # docker/git/node/flutter на PATH, compose-файлы, репозиторий, права, токен (без значения), доступность ядра
|
|
100
|
+
consilium-devops-runner install --print [--user] # печатает юнит systemd и все шаги установки
|
|
101
|
+
consilium-devops-runner unit --print [--user] # только юнит
|
|
102
|
+
consilium-devops-runner run # служба
|
|
103
|
+
consilium-devops-runner once # один цикл (heartbeat, claim, выполнить одобренное)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Из рабочей копии без установки: `node packages/mcp-module-devops/bin/consilium-devops-runner.js …`; из npm (после
|
|
107
|
+
публикации): `npx -y -p @consilium108/mcp-module-devops consilium-devops-runner …`.
|
|
108
|
+
|
|
109
|
+
### Цель и рецепт `konsilium-linux`
|
|
110
|
+
|
|
111
|
+
```json
|
|
112
|
+
{
|
|
113
|
+
"server": "https://konsilium.nativemind.net",
|
|
114
|
+
"tokenFile": "~/.config/consilium-devops-runner/token",
|
|
115
|
+
"path": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/anton/development/flutter/bin",
|
|
116
|
+
"targets": {
|
|
117
|
+
"konsilium-prod": {
|
|
118
|
+
"recipe": "konsilium-linux",
|
|
119
|
+
"repoDir": "/path/to/consilium.nativemind.net",
|
|
120
|
+
"composeFiles": null,
|
|
121
|
+
"composeProfiles": [],
|
|
122
|
+
"services": ["app", "mcp"],
|
|
123
|
+
"tests": { "server": true, "flutter": true },
|
|
124
|
+
"buildWeb": true,
|
|
125
|
+
"backup": true,
|
|
126
|
+
"appUrl": "http://127.0.0.1:8090",
|
|
127
|
+
"mcpUrl": "http://127.0.0.1:8091"
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
"watch": { "diskPath": "/", "minFreeGb": 30, "health": "http://127.0.0.1:8090/api/health", "chatIds": [], "envFile": "~/.config/consilium-devops-runner/runner.env" }
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Шаги рецепта (процедура ведущего на Linux-проде):
|
|
135
|
+
|
|
136
|
+
1. **до выкатки** (сбой → ничего не менялось, отката нет): `preSteps` (свои команды) → тесты сервера (vitest в
|
|
137
|
+
`node:22-bookworm` на копии `server/` + `packages/` в `<stateDir>/test-tree`, `npm ci` только при смене lock) →
|
|
138
|
+
`flutter analyze --no-fatal-infos` и `flutter test` в `app/konsilium_flutter` → `bash scripts/build-web.sh` →
|
|
139
|
+
`docker compose exec -T app node --no-deprecation scripts/db-backup.js`;
|
|
140
|
+
2. **выкатка**: образ запущенного контейнера каждого сервиса → `konsilium-<svc>:prev`; `user_version` до;
|
|
141
|
+
`GIT_SHA=$(git rev-parse HEAD) docker compose up -d --build app mcp`; ожидание healthy (`healthyTimeoutMs`, 5 мин);
|
|
142
|
+
3. **проверки**: `GET /api/health` 200, `POST /mcp` 401 без ключа, `POST /line/webhook` и `/max/webhook` 401,
|
|
143
|
+
`user_version` через node + better-sqlite3 внутри контейнера app (не меньше, чем до), ошибок в логах app/mcp с
|
|
144
|
+
начала выкатки 0 (`logErrorPattern`);
|
|
145
|
+
4. **откат** при сбое шага 2–3 (и по кнопке «↩ Откатить»): `docker tag konsilium-<svc>:prev konsilium-<svc>:latest`,
|
|
146
|
+
`docker compose up -d --no-build app mcp`, ожидание healthy.
|
|
147
|
+
|
|
148
|
+
Настраивается: `composeFiles` (список `-f`; `null` — обычный `docker compose`, он сам берёт
|
|
149
|
+
`docker-compose.override.yml` и `COMPOSE_FILE` из `.env` проекта; на проде с профилем ИИ —
|
|
150
|
+
`["docker-compose.yml", "docker-compose.override.yml", "docker-compose.ai.yml"]` и `composeProfiles: ["ai"]`, если
|
|
151
|
+
`COMPOSE_FILE` в `.env` не задан), `services`, `imagePrefix`, `tests` (`false` — без тестов), `testImage`,
|
|
152
|
+
`flutterAnalyzeArgs`, `flutterTestArgs`, `buildWeb`, `backup`, `preSteps`, `httpChecks` (`[{ method, url, expect }]`),
|
|
153
|
+
`userVersion`, `logErrors`, `logErrorPattern`, `healthyTimeoutMs`, `stepTimeoutMs`, `health`. Цель без `recipe` со
|
|
154
|
+
своими `deploy` / `rollback` / `health` (формат старого `deploy-runner/config.json`) работает как раньше. `git pull`
|
|
155
|
+
runner не делает: выкатывается то, что лежит в рабочей копии (HEAD).
|
|
156
|
+
|
|
157
|
+
### Установка на сервере (делает человек)
|
|
158
|
+
|
|
159
|
+
`consilium-devops-runner install --print` (или MCP `runner_setup`) печатает точные команды: токен цели через
|
|
160
|
+
`/deploytarget` → конфиг и `token` в `~/.config/consilium-devops-runner/` (700/600) → `doctor` → `doctor --heartbeat` →
|
|
161
|
+
юнит `/etc/systemd/system/consilium-devops-runner.service` (`User=` с доступом к docker, `KillMode=mixed`) →
|
|
162
|
+
`sudo systemctl enable --now consilium-devops-runner` → `journalctl -u consilium-devops-runner -f` → пробная выкатка
|
|
163
|
+
(`request_deploy` / `/deploy` → ✅). Остановить: `sudo systemctl stop consilium-devops-runner`; убрать:
|
|
164
|
+
`disable --now` и удалить юнит.
|
|
165
|
+
|
|
166
|
+
Старый каталог `deploy-runner/` монорепо — тонкая обёртка над `src/runner` (для прежнего запуска
|
|
167
|
+
`node deploy-runner/runner.js` с `deploy-runner/config.json` и тестов ядра).
|
|
168
|
+
|
|
169
|
+
Сборка и проверка: `npm install && npm test` (модуль + stdio-тест с поддельным ядром + runner с поддельным ядром и `docker`); `npm pack` — пакет;
|
|
170
|
+
публикация — `npm publish` (владелец/ведущий по «публикуй»).
|
|
171
|
+
|
|
28
172
|
Лицензия: NativeMindNONC (см. LICENSE).
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// generated by Claude (Opus 5.5), 2026-11-22; Konsilium #482 (TASK-P37-482): the standalone DevOps MCP on stdio.
|
|
3
|
+
// stdout is JSON-RPC only; every log line goes to stderr. No module or service secret is read here — only the person's
|
|
4
|
+
// Konsilium credential (KONSILIUM_API_KEY, or the sign-in of `npx @consilium108/mcp login` when that package is installed).
|
|
5
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
6
|
+
import { createDevopsMcp, DEFAULT_API_URL } from '../src/standalone.js';
|
|
7
|
+
import mod from '../src/index.js';
|
|
8
|
+
|
|
9
|
+
const USAGE = `consilium-devops-mcp — Konsilium DevOps MCP (stdio): deploy requests and their status, deploy targets, debug reports
|
|
10
|
+
|
|
11
|
+
npx -y @consilium108/mcp-module-devops [--project <id>] [--api <url>] [--devops-api <url>]
|
|
12
|
+
|
|
13
|
+
--project <id> active project (a choice, not a right; select_project changes it); default — the connection's default
|
|
14
|
+
--api <url> Konsilium core (default ${DEFAULT_API_URL})
|
|
15
|
+
--devops-api <url> the DevOps module API, only when it is reachable directly (default: through the core)
|
|
16
|
+
|
|
17
|
+
Environment:
|
|
18
|
+
KONSILIUM_API_KEY a Konsilium key (ksk_… from «Account → API»: the project + the right tasks:work) or an OAuth
|
|
19
|
+
access token; without it the sign-in of \`npx @consilium108/mcp login\` is used when available
|
|
20
|
+
KONSILIUM_PROJECT_ID the project (instead of --project)
|
|
21
|
+
KONSILIUM_API_URL the core (instead of --api)
|
|
22
|
+
DEVOPS_API_URL the module API (instead of --devops-api)
|
|
23
|
+
KONSILIUM_KEYCHAIN=off do not look into the OS credential store
|
|
24
|
+
|
|
25
|
+
Deploys are approved only by a person with the deploy right (✅ in the messenger); this MCP requests and watches.`;
|
|
26
|
+
|
|
27
|
+
const argv = process.argv.slice(2);
|
|
28
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
29
|
+
process.stdout.write(`${USAGE}\n`);
|
|
30
|
+
process.exit(0);
|
|
31
|
+
}
|
|
32
|
+
if (argv.includes('--version')) {
|
|
33
|
+
process.stdout.write(`${mod.version}\n`);
|
|
34
|
+
process.exit(0);
|
|
35
|
+
}
|
|
36
|
+
const opt = (name) => {
|
|
37
|
+
const i = argv.indexOf(name);
|
|
38
|
+
return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : null;
|
|
39
|
+
};
|
|
40
|
+
const log = (m) => process.stderr.write(`[consilium-devops-mcp] ${m}\n`);
|
|
41
|
+
const env = process.env;
|
|
42
|
+
const apiUrl = (opt('--api') ?? env.KONSILIUM_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
|
43
|
+
const devopsUrl = opt('--devops-api') ?? env.DEVOPS_API_URL ?? null;
|
|
44
|
+
const projectId = Number(opt('--project') ?? env.KONSILIUM_PROJECT_ID) || null;
|
|
45
|
+
const envKey = env.KONSILIUM_API_KEY || null;
|
|
46
|
+
|
|
47
|
+
/** The credential: the key from the environment, else the stored sign-in of @consilium108/mcp (optional peer). */
|
|
48
|
+
async function credentialsOf() {
|
|
49
|
+
if (envKey) return { bearer: async () => envKey, source: () => 'KONSILIUM_API_KEY' };
|
|
50
|
+
if (env.KONSILIUM_KEYCHAIN !== 'off') {
|
|
51
|
+
try {
|
|
52
|
+
const auth = await import('@consilium108/mcp/auth');
|
|
53
|
+
const store = await auth.openStore({ env, apiUrl });
|
|
54
|
+
const c = await auth.createCredentialProvider({ apiUrl, store, envKey: null }).init();
|
|
55
|
+
return { bearer: () => c.bearer(), ...(c.kind?.() === 'oauth' ? { refresh: (failed) => c.refresh(failed) } : {}), source: () => `sign-in (${store.backend})` };
|
|
56
|
+
} catch {
|
|
57
|
+
/* the host package is not installed or no store: tools answer auth_required */
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return { bearer: async () => null, source: () => 'none' };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const credentials = await credentialsOf();
|
|
64
|
+
const { server } = createDevopsMcp({ apiUrl, devopsUrl, credentials, projectId });
|
|
65
|
+
await server.connect(new StdioServerTransport());
|
|
66
|
+
log(`${mod.name} ${mod.version}; core ${apiUrl}${devopsUrl ? `; module ${devopsUrl}` : ''}; project ${projectId ?? 'default of the connection'}; credential: ${credentials.source()}`);
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// generated by Claude (Opus 5.5), 2026-11-23; Konsilium: the deploy runner of @consilium108/mcp-module-devops — a SEPARATE
|
|
3
|
+
// long-running service (systemd), never inside the MCP process. It executes only requests a person approved (✅ in the bot);
|
|
4
|
+
// the commands come from this host's config, never from the server. Node built-ins only (no MCP SDK needed).
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { dirname, resolve } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import {
|
|
9
|
+
acquireLock,
|
|
10
|
+
createClient,
|
|
11
|
+
createLogger,
|
|
12
|
+
createRunner,
|
|
13
|
+
createState,
|
|
14
|
+
defaultPath,
|
|
15
|
+
doctor,
|
|
16
|
+
exampleConfig,
|
|
17
|
+
formatDoctor,
|
|
18
|
+
installSteps,
|
|
19
|
+
loadConfig,
|
|
20
|
+
tick,
|
|
21
|
+
unitText,
|
|
22
|
+
} from '../src/runner/index.js';
|
|
23
|
+
|
|
24
|
+
const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
25
|
+
const BIN = fileURLToPath(import.meta.url);
|
|
26
|
+
|
|
27
|
+
const USAGE = `consilium-devops-runner — Konsilium deploy runner (${PKG.name} ${PKG.version})
|
|
28
|
+
|
|
29
|
+
consilium-devops-runner run the service: heartbeat → claim approved requests → run → result
|
|
30
|
+
consilium-devops-runner once one tick (heartbeat, claim, run if there is an approved request)
|
|
31
|
+
consilium-devops-runner doctor [--heartbeat] [--no-docker] check this host (changes nothing; --heartbeat sends one)
|
|
32
|
+
consilium-devops-runner install --print [--user] [--repo <dir>] [--target <key>] PRINT the systemd unit and steps
|
|
33
|
+
consilium-devops-runner unit --print [--user] [--repo <dir>] PRINT only the unit
|
|
34
|
+
consilium-devops-runner config --print [--repo <dir>] [--target <key>] PRINT an example config (no secret)
|
|
35
|
+
consilium-devops-runner --version | --help
|
|
36
|
+
|
|
37
|
+
Options: --config <file>
|
|
38
|
+
|
|
39
|
+
Config (outside the repository, chmod 600): $CONSILIUM_DEVOPS_RUNNER_CONFIG, else ~/.config/consilium-devops-runner/config.json,
|
|
40
|
+
else /etc/consilium-devops-runner/config.json.
|
|
41
|
+
Environment: CONSILIUM_RUNNER_TOKEN (the target's kdr_ token, instead of tokenFile), KONSILIUM_API_URL, CONSILIUM_RUNNER_PATH,
|
|
42
|
+
CONSILIUM_RUNNER_STATE_DIR, CONSILIUM_RUNNER_LOG_FORMAT (json|text), CONSILIUM_RUNNER_TELEGRAM_TOKEN (the watchdog).
|
|
43
|
+
Nothing here installs a service: install/unit only print.`;
|
|
44
|
+
|
|
45
|
+
const argv = process.argv.slice(2);
|
|
46
|
+
const has = (f) => argv.includes(f);
|
|
47
|
+
const opt = (name) => {
|
|
48
|
+
const i = argv.indexOf(name);
|
|
49
|
+
return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : null;
|
|
50
|
+
};
|
|
51
|
+
const VALUED = new Set(['--config', '--repo', '--target']);
|
|
52
|
+
const cmd = argv.find((a, i) => !a.startsWith('-') && !VALUED.has(argv[i - 1])) ?? 'help';
|
|
53
|
+
const out = (s) => process.stdout.write(s.endsWith('\n') ? s : `${s}\n`);
|
|
54
|
+
const fail = (e, code = 1) => {
|
|
55
|
+
process.stderr.write(`consilium-devops-runner: ${e.code ? `${e.code}: ` : ''}${e.message ?? e}\n`);
|
|
56
|
+
process.exit(code);
|
|
57
|
+
};
|
|
58
|
+
const repoGuess = () => resolve(dirname(BIN), '..', '..', '..');
|
|
59
|
+
|
|
60
|
+
async function main() {
|
|
61
|
+
if (has('--version') || cmd === 'version') return out(PKG.version);
|
|
62
|
+
if (has('--help') || has('-h') || cmd === 'help') return out(USAGE);
|
|
63
|
+
const configFile = opt('--config');
|
|
64
|
+
|
|
65
|
+
if (cmd === 'config') {
|
|
66
|
+
if (!has('--print')) return fail({ message: 'config writes nothing; use: config --print > <file>' }, 2);
|
|
67
|
+
return out(JSON.stringify(exampleConfig({ repoDir: opt('--repo') ?? repoGuess(), target: opt('--target') ?? 'konsilium-prod' }), null, 2));
|
|
68
|
+
}
|
|
69
|
+
if (cmd === 'install' || cmd === 'unit') {
|
|
70
|
+
if (!has('--print')) return fail({ message: `${cmd} installs nothing; use: ${cmd} --print (and run the printed commands yourself)` }, 2);
|
|
71
|
+
const mode = has('--user') ? 'user' : 'system';
|
|
72
|
+
const repoDir = opt('--repo') ?? repoGuess();
|
|
73
|
+
if (cmd === 'unit') return out(unitText({ mode, bin: BIN, repoDir, path: defaultPath() }));
|
|
74
|
+
return out(installSteps({ mode, repoDir, target: opt('--target') ?? 'konsilium-prod', bin: BIN }));
|
|
75
|
+
}
|
|
76
|
+
if (cmd === 'doctor') {
|
|
77
|
+
const r = await doctor({ file: configFile, heartbeat: has('--heartbeat'), docker: !has('--no-docker') });
|
|
78
|
+
out(formatDoctor(r));
|
|
79
|
+
process.exit(r.ok ? 0 : 1);
|
|
80
|
+
}
|
|
81
|
+
if (cmd === 'run' || cmd === 'once') {
|
|
82
|
+
let config;
|
|
83
|
+
try {
|
|
84
|
+
config = loadConfig({ file: configFile });
|
|
85
|
+
} catch (e) {
|
|
86
|
+
return fail(e, 78); // EX_CONFIG: systemd's Restart=on-failure retries; the journal says why
|
|
87
|
+
}
|
|
88
|
+
const log = createLogger({ format: config.logFormat });
|
|
89
|
+
if (!config.token) return fail({ code: 'token_missing', message: `no runner token (CONSILIUM_RUNNER_TOKEN, "tokenFile" or "token" in ${config.file}); the owner creates a target with /deploytarget` }, 78);
|
|
90
|
+
let lock;
|
|
91
|
+
try {
|
|
92
|
+
lock = acquireLock(config.stateDir);
|
|
93
|
+
} catch (e) {
|
|
94
|
+
return fail(e, 75);
|
|
95
|
+
}
|
|
96
|
+
const client = createClient({ server: config.server, token: config.token, userAgent: `consilium-devops-runner/${PKG.version}` });
|
|
97
|
+
const state = createState(config.stateDir);
|
|
98
|
+
if (cmd === 'once') {
|
|
99
|
+
try {
|
|
100
|
+
const done = await tick(config, client, { state, log });
|
|
101
|
+
log.info(done ? 'once: done' : 'once: no approved request', done ? { deploy_id: done.id, exit: done.exitCode, health: done.health } : {});
|
|
102
|
+
} catch (e) {
|
|
103
|
+
log.error('once failed', { code: e.code ?? 'error', error: e.message });
|
|
104
|
+
process.exitCode = 1;
|
|
105
|
+
} finally {
|
|
106
|
+
lock.release();
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const runner = createRunner(config, { client, state, log, lock });
|
|
111
|
+
const onSignal = (sig) => runner.stop(sig);
|
|
112
|
+
process.on('SIGTERM', onSignal);
|
|
113
|
+
process.on('SIGINT', onSignal);
|
|
114
|
+
await runner.start();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
fail({ message: `unknown command «${cmd}» (--help)` }, 2);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
main().catch((e) => fail(e));
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@consilium108/mcp-module-devops",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "DevOps module of the Konsilium MCP (#442): Deploy requests by button and their status; debug reports of apps. Loaded by the host @consilium108/mcp;
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "DevOps module of the Konsilium MCP (#442): Deploy requests by button and their status; debug reports of apps. Loaded by the host @consilium108/mcp; also runs on its own (bin consilium-devops-mcp, #482); the deploy runner service (bin consilium-devops-runner).",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"author": "NativeMind",
|
|
7
7
|
"homepage": "https://konsilium.nativemind.net",
|
|
@@ -11,10 +11,18 @@
|
|
|
11
11
|
},
|
|
12
12
|
"exports": {
|
|
13
13
|
".": "./src/index.js",
|
|
14
|
+
"./standalone": "./src/standalone.js",
|
|
15
|
+
"./runner": "./src/runner/index.js",
|
|
14
16
|
"./package.json": "./package.json"
|
|
15
17
|
},
|
|
18
|
+
"bin": {
|
|
19
|
+
"mcp-module-devops": "bin/consilium-devops-mcp.js",
|
|
20
|
+
"consilium-devops-mcp": "bin/consilium-devops-mcp.js",
|
|
21
|
+
"consilium-devops-runner": "bin/consilium-devops-runner.js"
|
|
22
|
+
},
|
|
16
23
|
"files": [
|
|
17
24
|
"src",
|
|
25
|
+
"bin",
|
|
18
26
|
"i18n",
|
|
19
27
|
"README.md",
|
|
20
28
|
"CHANGELOG.md",
|
|
@@ -32,9 +40,8 @@
|
|
|
32
40
|
}
|
|
33
41
|
},
|
|
34
42
|
"dependencies": {
|
|
35
|
-
"@
|
|
36
|
-
|
|
37
|
-
"devDependencies": {
|
|
43
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
44
|
+
"@nativemind108/mcp": "^1.13.0",
|
|
38
45
|
"zod": "^4.6.7"
|
|
39
46
|
},
|
|
40
47
|
"publishConfig": {
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-23; Konsilium (runner in the DevOps package): the package's coded error, shared by
|
|
2
|
+
// the standalone MCP (src/standalone.js) and the deploy runner (src/runner/*). No dependencies — the runner imports it
|
|
3
|
+
// without the MCP SDK installed.
|
|
4
|
+
|
|
5
|
+
/** An error with a stable code (shown as «code: message»). */
|
|
6
|
+
export class DevopsMcpError extends Error {
|
|
7
|
+
constructor(code, message, status = null) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.status = status;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-22; Konsilium #482 (TASK-P37-482, the standalone DevOps MCP): read tools over the
|
|
2
|
+
// DevOps module API — deploy targets (with the runner's last heartbeat) and the recent deploy requests of a project.
|
|
3
|
+
// Not a group of the module definition yet (the host @consilium108/mcp and the cloud MCP keep their catalog unchanged);
|
|
4
|
+
// the standalone server (src/standalone.js) registers it. Handlers use only the host-style helpers `h`.
|
|
5
|
+
|
|
6
|
+
/** Tools of `OPS_TOOLS` (the registration order). */
|
|
7
|
+
export const OPS_TOOLS = ['list_deploy_targets', 'list_deploys', 'runner_status', 'runner_setup'];
|
|
8
|
+
|
|
9
|
+
/** A runner polls every 10 s; no heartbeat for longer than this → offline. */
|
|
10
|
+
export const RUNNER_ONLINE_SEC = 120;
|
|
11
|
+
|
|
12
|
+
/** SQLite `datetime('now')` (UTC, «YYYY-MM-DD HH:MM:SS») or ISO → ms, else null. */
|
|
13
|
+
export function parseServerTime(s) {
|
|
14
|
+
if (!s) return null;
|
|
15
|
+
const t = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : `${String(s).replace(' ', 'T')}Z`);
|
|
16
|
+
return Number.isFinite(t) ? t : null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Targets + recent deploys → the runner's status per target (pure; tested). */
|
|
20
|
+
export function runnerStatusOf(targets, deploys, { now = Date.now(), onlineSec = RUNNER_ONLINE_SEC } = {}) {
|
|
21
|
+
return (targets ?? []).map((t) => {
|
|
22
|
+
const seen = parseServerTime(t.lastSeenAt ?? t.last_seen_at);
|
|
23
|
+
const ago = seen == null ? null : Math.max(0, Math.round((now - seen) / 1000));
|
|
24
|
+
const mine = (deploys ?? []).filter((d) => d.target === t.key);
|
|
25
|
+
const running = mine.find((d) => d.status === 'running') ?? null;
|
|
26
|
+
const waiting = mine.filter((d) => d.status === 'approved' || d.status === 'pending');
|
|
27
|
+
const last = mine.find((d) => d.status === 'done' || d.status === 'failed') ?? null;
|
|
28
|
+
return {
|
|
29
|
+
key: t.key,
|
|
30
|
+
title: t.title ?? null,
|
|
31
|
+
last_seen_at: t.lastSeenAt ?? t.last_seen_at ?? null,
|
|
32
|
+
seconds_since_seen: ago,
|
|
33
|
+
online: ago != null && ago <= onlineSec,
|
|
34
|
+
state: ago == null ? 'never_seen' : ago <= onlineSec ? (running ? 'running' : 'idle') : 'offline',
|
|
35
|
+
current_job: running ? { id: running.id, kind: running.kind ?? 'deploy', started_at: running.startedAt ?? null, summary: running.summary ?? null } : null,
|
|
36
|
+
waiting: waiting.map((d) => ({ id: d.id, status: d.status, kind: d.kind ?? 'deploy' })),
|
|
37
|
+
last_finished: last ? { id: last.id, status: last.status, exit_code: last.exitCode ?? null, health: last.health ?? null, finished_at: last.finishedAt ?? null } : null,
|
|
38
|
+
};
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function registerOpsTools(server, h) {
|
|
43
|
+
if (h.shape === 'personal') return;
|
|
44
|
+
const { z, text, safe, call, P } = h;
|
|
45
|
+
const arr = (r, k) => (Array.isArray(r) ? r : (r?.[k] ?? []));
|
|
46
|
+
const ro = { readOnlyHint: true, openWorldHint: false };
|
|
47
|
+
const pid = (project_id) => project_id ?? P();
|
|
48
|
+
|
|
49
|
+
server.registerTool(
|
|
50
|
+
'list_deploy_targets',
|
|
51
|
+
{
|
|
52
|
+
title: 'Deploy targets',
|
|
53
|
+
description:
|
|
54
|
+
'Deploy targets of the project (key, title) and when the runner on the project server last called in (lastSeenAt — the runner is alive if it is recent). Only people with the deploy right of the project (owner, co-owners, granted members) see them; otherwise no_deploy_right. Targets and rights are created by a person in Konsilium (bot /deploytarget or the app), never by an AI.',
|
|
55
|
+
inputSchema: { project_id: z.number().int().positive().optional().describe('Project id; default — the active project.') },
|
|
56
|
+
annotations: ro,
|
|
57
|
+
},
|
|
58
|
+
safe(async ({ project_id }, ctx) => {
|
|
59
|
+
const id = pid(project_id);
|
|
60
|
+
const r = await call(ctx, 'GET', '/api/projects/{id}/deploy-targets', { id });
|
|
61
|
+
return text({ project_id: id, targets: Array.isArray(r) ? r : (r?.targets ?? r) });
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
server.registerTool(
|
|
65
|
+
'list_deploys',
|
|
66
|
+
{
|
|
67
|
+
title: 'Recent deploy requests',
|
|
68
|
+
description:
|
|
69
|
+
'The last deploy requests of the project (newest first, up to 20): target, status pending → approved → running → done | failed (or rejected / expired), who asked, exit code, health. Details and the log tail of one request — deploy_status.',
|
|
70
|
+
inputSchema: { project_id: z.number().int().positive().optional().describe('Project id; default — the active project.') },
|
|
71
|
+
annotations: ro,
|
|
72
|
+
},
|
|
73
|
+
safe(async ({ project_id }, ctx) => {
|
|
74
|
+
const id = pid(project_id);
|
|
75
|
+
const r = await call(ctx, 'GET', '/api/projects/{id}/deploys', { id });
|
|
76
|
+
return text({ project_id: id, deploys: Array.isArray(r) ? r : (r?.deploys ?? r) });
|
|
77
|
+
}),
|
|
78
|
+
);
|
|
79
|
+
// generated by Claude (Opus 5.5), 2026-11-23: the runner service (bin consilium-devops-runner) seen from the MCP — status and
|
|
80
|
+
// the install steps as text. The MCP never runs, installs or approves anything; the runner is a separate process.
|
|
81
|
+
server.registerTool(
|
|
82
|
+
'runner_status',
|
|
83
|
+
{
|
|
84
|
+
title: 'Deploy runner status',
|
|
85
|
+
description:
|
|
86
|
+
'Is the deploy runner of each target alive: last heartbeat (last_seen_at, seconds ago), online / offline (no heartbeat for more than 2 minutes), the job it is running now, approved requests waiting for it, the last finished one. Needs the deploy right of the project. If a target is offline, runner_setup gives the install / restart steps for a person.',
|
|
87
|
+
inputSchema: { project_id: z.number().int().positive().optional().describe('Project id; default — the active project.') },
|
|
88
|
+
annotations: ro,
|
|
89
|
+
},
|
|
90
|
+
safe(async ({ project_id }, ctx) => {
|
|
91
|
+
const id = pid(project_id);
|
|
92
|
+
const targets = arr(await call(ctx, 'GET', '/api/projects/{id}/deploy-targets', { id }), 'targets');
|
|
93
|
+
const deploys = arr(await call(ctx, 'GET', '/api/projects/{id}/deploys', { id }), 'deploys');
|
|
94
|
+
const runners = runnerStatusOf(targets, deploys);
|
|
95
|
+
return text({
|
|
96
|
+
project_id: id,
|
|
97
|
+
online_window_sec: RUNNER_ONLINE_SEC,
|
|
98
|
+
runners,
|
|
99
|
+
...(runners.some((r) => !r.online) ? { hint: 'An offline target: a person checks the service on the host (systemctl status consilium-devops-runner; journalctl -u consilium-devops-runner) — runner_setup has the steps.' } : {}),
|
|
100
|
+
...(runners.length ? {} : { hint: 'No deploy targets: the owner creates one in the bot (/deploytarget <key> <title>), never an AI.' }),
|
|
101
|
+
});
|
|
102
|
+
}),
|
|
103
|
+
);
|
|
104
|
+
server.registerTool(
|
|
105
|
+
'runner_setup',
|
|
106
|
+
{
|
|
107
|
+
title: 'Deploy runner: install steps',
|
|
108
|
+
description:
|
|
109
|
+
'The exact steps for a PERSON to bring up the deploy runner on a project host (Linux, systemd): target token via /deploytarget in the bot, the config outside the repository (chmod 600), `consilium-devops-runner doctor`, the systemd unit, a trial deploy, stop and rollback. Returns text only — it installs, starts and creates nothing (no tokens).',
|
|
110
|
+
inputSchema: {
|
|
111
|
+
target: z.string().min(2).max(41).optional().describe('Target key, default konsilium-prod.'),
|
|
112
|
+
repo_dir: z.string().max(500).optional().describe('The checkout on the host the target deploys (cwd of the steps).'),
|
|
113
|
+
user: z.string().max(64).optional().describe('The host account that runs the service (in the docker group).'),
|
|
114
|
+
mode: z.enum(['system', 'user']).optional().describe('system service with User= (default, starts at boot) or a user service.'),
|
|
115
|
+
node: z.string().max(300).optional().describe('Absolute path of node on the host (default /usr/local/bin/node).'),
|
|
116
|
+
},
|
|
117
|
+
annotations: ro,
|
|
118
|
+
},
|
|
119
|
+
safe(async ({ target, repo_dir, user, mode, node }) => {
|
|
120
|
+
const { installSteps } = await import('../runner/install.js');
|
|
121
|
+
const steps = installSteps({ target: target ?? 'konsilium-prod', repoDir: repo_dir ?? '/path/to/consilium.nativemind.net', user: user ?? 'konsilium', mode: mode ?? 'system', node: node ?? '/usr/local/bin/node' });
|
|
122
|
+
return text({ installs_nothing: true, service: 'consilium-devops-runner', steps });
|
|
123
|
+
}),
|
|
124
|
+
);
|
|
125
|
+
}
|
package/src/index.js
CHANGED
|
@@ -32,3 +32,5 @@ export default defineMcpModule({
|
|
|
32
32
|
});
|
|
33
33
|
|
|
34
34
|
export { DEBUG_TOOLS, registerDebugTools, DEPLOY_TOOLS, registerDeployTools };
|
|
35
|
+
// #482 (Claude (Opus 5.5), 2026-11-22): read tools of the standalone DevOps MCP (not a group of the host catalog yet)
|
|
36
|
+
export { OPS_TOOLS, registerOpsTools } from './groups/ops.js';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-23; Konsilium (deploy runner in @consilium108/mcp-module-devops). Ported from
|
|
2
|
+
// deploy-runner/runner.js: the runner's API client — POST /api/deploy/runner/{heartbeat,claim,:id/result} of the core with
|
|
3
|
+
// the target's runner token (kdr_…, never a person's key). The core proxies these to the DevOps module (MODULE_DEVOPS=remote).
|
|
4
|
+
// Errors are the package's coded DevopsMcpError; the token never appears in a message.
|
|
5
|
+
import { DevopsMcpError } from '../errors.js';
|
|
6
|
+
|
|
7
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
8
|
+
|
|
9
|
+
export function createClient({ server, token, fetchImpl = fetch, userAgent = 'consilium-devops-runner', timeoutMs = 30_000 }) {
|
|
10
|
+
const base = String(server ?? '').replace(/\/+$/, '');
|
|
11
|
+
const call = async (path, body) => {
|
|
12
|
+
let r;
|
|
13
|
+
try {
|
|
14
|
+
r = await fetchImpl(`${base}/api/deploy/runner${path}`, {
|
|
15
|
+
method: 'POST',
|
|
16
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': userAgent },
|
|
17
|
+
body: JSON.stringify(body ?? {}),
|
|
18
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
19
|
+
});
|
|
20
|
+
} catch (e) {
|
|
21
|
+
throw new DevopsMcpError('network_unavailable', `${path}: ${e?.cause?.code ?? e?.name ?? 'network error'}`, 0);
|
|
22
|
+
}
|
|
23
|
+
if (!r.ok) {
|
|
24
|
+
const code = r.status === 401 ? 'bad_runner_token' : r.status === 404 ? 'not_found' : r.status === 503 ? 'module_unavailable' : `http_${r.status}`;
|
|
25
|
+
throw new DevopsMcpError(code, `${path}: HTTP ${r.status}${r.status === 401 ? ' (the runner token is wrong or the target was deleted — the owner creates a target with /deploytarget)' : ''}`, r.status);
|
|
26
|
+
}
|
|
27
|
+
return r.json();
|
|
28
|
+
};
|
|
29
|
+
// #140: the app restarts during a deploy (or a rollback) — the result must survive a few 502s, else the request hangs in «running»
|
|
30
|
+
const result = async (id, res, { tries = 20, delayMs = 6000 } = {}) => {
|
|
31
|
+
const body = { exitCode: res.exitCode, logTail: res.logTail, health: res.health ?? null };
|
|
32
|
+
for (let i = 0; ; i++) {
|
|
33
|
+
try {
|
|
34
|
+
return await call(`/${id}/result`, body);
|
|
35
|
+
} catch (e) {
|
|
36
|
+
if (e.status === 404 || e.status === 401 || i >= tries - 1) throw e;
|
|
37
|
+
await sleep(delayMs);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
return { heartbeat: () => call('/heartbeat'), claim: async () => (await call('/claim')).request, result };
|
|
42
|
+
}
|