@consilium108/mcp-module-devops 1.3.0 → 1.4.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 +36 -0
- package/README.md +58 -56
- package/bin/consilium-devops-mcp.js +47 -3
- package/package.json +4 -4
- package/src/orchestrator/brief.js +46 -0
- package/src/orchestrator/config.js +29 -78
- package/src/orchestrator/events.js +5 -12
- package/src/orchestrator/index.js +9 -12
- package/src/orchestrator/producer.js +193 -0
- package/src/orchestrator/registry.js +16 -4
- package/src/standalone.js +9 -3
- package/bin/consilium-devops-orchestrator.js +0 -172
- package/src/orchestrator/adapters.js +0 -158
- package/src/orchestrator/api.js +0 -86
- package/src/orchestrator/daemon.js +0 -494
- package/src/orchestrator/install.js +0 -28
- package/src/orchestrator/live.js +0 -161
- package/src/orchestrator/source.js +0 -177
- package/src/orchestrator/store.js +0 -145
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,41 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.4.0 — 2026-11-24
|
|
4
|
+
|
|
5
|
+
<!-- generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2, SDD-P37-160 IT-160-1 … IT-160-7 — owner
|
|
6
|
+
2026-11-24: the orchestrator works INSIDE the running JS MCP; the separate daemon / systemd unit / CLI are cancelled. -->
|
|
7
|
+
|
|
8
|
+
- **The DevOps Orchestrator runs inside `consilium-devops-mcp`** (one process, one lifecycle): the event listener (#437
|
|
9
|
+
SSE `projectEvents` + `get_events` from the cursor, long poll fallback, first start = baseline) starts after the
|
|
10
|
+
transport is connected and stops with it (transport closed, stdin ended, SIGTERM / SIGINT); cursor, jobs and leases
|
|
11
|
+
stay on disk and the next start replays from the cursor. One listener per workspace (leader lock): a second DevOps MCP
|
|
12
|
+
of the same workspace (another session) serves the tools only and takes over when the leader exits.
|
|
13
|
+
- **Jobs instead of dispatch.** `agent.deploy_required` of a routed project → a job `devops.deploy_check` in the shared
|
|
14
|
+
job inbox of `@consilium108/mcp-agent-jobs` 0.1.0 (new dependency; envelope `konsilium.agent-job/1`, the same as the
|
|
15
|
+
Developer MCP's jobs). New tools `jobs_inbox`, `jobs_claim`, `jobs_ack`, `jobs_status`, `jobs_result`,
|
|
16
|
+
`jobs_release` (+ resource `konsilium-jobs://inbox`, `notifications/resources/updated` and a log message on change):
|
|
17
|
+
the session's main agent claims a job and starts its own built-in subagent (Agent tool) with the returned prompt; the
|
|
18
|
+
subagent acks (lease), may `request_deploy`, and reports. Kept rules: one active job per project + environment +
|
|
19
|
+
target, coalescing, lease / retry with backoff / max attempts, stale results ignored, deploy followed by `deploy.*`
|
|
20
|
+
(poll fallback only in the listener's process), the deploy id from `deploy.requested` (IT-14), reports through
|
|
21
|
+
`agent-events` (`orc:` keys; own events ignored), G2 routing by the named target, #470 session state (now shown in
|
|
22
|
+
`jobs_inbox` / `jobs_status`, never a gate). New options of the bin: `--orchestrator-config`, `--workspace`,
|
|
23
|
+
`--no-jobs` (`KONSILIUM_JOBS=off`).
|
|
24
|
+
- **Removed** (the separate service of 1.2.0 / 1.3.0): bin `consilium-devops-orchestrator` (run / once / status / agents /
|
|
25
|
+
check / config --print / unit --print), the systemd unit text, the daemon loop, agent slots, provider adapters,
|
|
26
|
+
dry-run / live (`claude -p`) / hand-off dispatch and their exports (`createOrchestrator`, `createLiveDispatcher`,
|
|
27
|
+
`validateLivePlan`, `orchestratorUnitText`, `createOrchestratorStore`, `createEventSource`, `createOrchestratorApi`, …).
|
|
28
|
+
Moved to `@consilium108/mcp-agent-jobs`: the listener, the store (now the inbox), the API client. The config keeps
|
|
29
|
+
`projects / targets / routes / leaseMs / maxAttempts / backoffMs / deployPollFallbackMs / idleTtlMs / report`; old keys
|
|
30
|
+
(`agents`, `dispatch`, `reportDryRun`, `pollMs`, `stateDir`, `sse`, `logFormat`, `stopTimeoutMs`) are ignored with a
|
|
31
|
+
warning. The deploy runner (`consilium-devops-runner`, #482) is unchanged — it is a different thing.
|
|
32
|
+
- Exports of `./orchestrator`: `createDevopsProducer`, `createSessionRegistry`, `findOrchestratorConfig`, `jobContext`,
|
|
33
|
+
`promptOf`, `DEPLOY_CHECK_TOOLS`, `LEGACY_KEYS` and the kept event / registry / config helpers.
|
|
34
|
+
- Tests: `test/orchestrator.test.js` rewritten (12, through the real MCP tools on an in-memory transport: hand-off flow,
|
|
35
|
+
replay / duplicates, MCP restart, busy session + several subagents + lease expiry, approval-required + conflicting
|
|
36
|
+
deploys + IT-14, runner failure, reporting retry, two MCP processes, diagnostics + #470, one inbox with Developer jobs);
|
|
37
|
+
`orchestrator-live.test.js` removed; `standalone.test.js` lists the job tools.
|
|
38
|
+
|
|
3
39
|
## 1.3.0 — 2026-11-24
|
|
4
40
|
|
|
5
41
|
<!-- generated by Claude (Opus 5.5), 2026-11-24; Konsilium SDD-P37-160 — owner 2026-11-24 «Запускай все, добавь сразу».
|
package/README.md
CHANGED
|
@@ -69,68 +69,70 @@ Object.keys(mod.groups);
|
|
|
69
69
|
`forbidden_project`, `no_deploy_right`, `module_disabled`, `module_unavailable`, `network_unavailable`,
|
|
70
70
|
`key_not_allowed` (ядро старше 1.1.0 — `list_deploy_targets` / `list_deploys` ещё не открыты для ключей), `rate_limited`.
|
|
71
71
|
|
|
72
|
-
## Оркестратор
|
|
73
|
-
|
|
74
|
-
`consilium-devops-orchestrator` — третья команда пакета и **отдельная** долгоживущая служба (systemd user unit), не
|
|
75
|
-
процесс MCP и не runner. Слушает события агентов проекта (SSE `projectEvents` из #437 + `get_events` для догонки и
|
|
76
|
-
как запасной long poll), ведёт устойчивую очередь (`state.json` вне репозитория: курсоры, дедупликация, задания, lease,
|
|
77
|
-
outbox отчётов) с блокировкой на проект + окружение + цель, выбирает **действительно свободного** совместимого агента
|
|
78
|
-
(слоты из конфига + факты монитора ходов #470 из `~/.local/state/konsilium-mcp/<sha1>/turnmonitor/`; запущенный процесс
|
|
79
|
-
сам по себе свободным не считается) и передаёт ему структурированное задание через адаптер провайдера (Claude Code,
|
|
80
|
-
Codex, generic). `DEPLOY_REQUIRED` — сигнал на **проверку**: агент может только *запросить* выкатку (`request_deploy`),
|
|
81
|
-
одобряет человек ✅; оркестратор ничего не одобряет и не обходит permission gate. После запроса задание следит за
|
|
82
|
-
статусом выкатки на сервере (pending → `waiting_for_user`, approved/running → `running`, done → `succeeded`, failed →
|
|
83
|
-
`failed` (runner), rejected/expired → `cancelled`) и держит блокировку цели. Отчёты — в журнал событий проекта через
|
|
84
|
-
существующий маршрут `POST /api/projects/:id/agent-events` (идемпотентно, никого не уведомляет; свои события не
|
|
85
|
-
перечитываются).
|
|
86
|
-
|
|
87
|
-
<!-- Обновлено ассистентом (Claude Opus 5.5), 2026-11-24: 1.3.0 — G1–G4 и этап 3 (решение владельца «Запускай все»). -->
|
|
88
|
-
|
|
89
|
-
**1.3.0 — события выкаток, маршрутизация по цели, живой запуск по слоту.**
|
|
90
|
-
- *События выкаток (G1)*: ядро (и модуль DevOps в режиме `remote` через свой `core_outbox`) пишет в журнал проекта
|
|
91
|
-
`deploy.requested / approved / rejected / running / done / failed / rolled_back / expired` (`meta`: id, ключ цели,
|
|
92
|
-
вид, статус, exit/health; без хвоста лога). Оркестратор подписан на `agent.*` и `deploy.*` и двигает задания по
|
|
93
|
-
ним; опрос `GET /deploys/:id` остаётся запасным — каждый такт, пока сервер не прислал ни одного `deploy.*` по
|
|
94
|
-
проекту, затем только после `deployPollFallbackMs` (5 мин) тишины. `deploy.requested` своей цели после назначения
|
|
95
|
-
даёт номер выкатки, если агент его не назвал.
|
|
96
|
-
- *Цель из события (G2)*: событие агента может нести `target / environment / branch / commit_sha`; маршрут выбирается
|
|
97
|
-
среди настроенных маршрутов проекта события (событие цель не добавляет: чужая цель → `target_not_routed`), ветка и
|
|
98
|
-
коммит попадают в задание.
|
|
99
|
-
- *Монитор ходов (G3/G4)*: с `@consilium108/mcp` ≥ 0.11.1 состояние сессий читается через её экспорт
|
|
100
|
-
`@consilium108/mcp/turnmonitor` (в т. ч. `TURN_STARTED` — начало хода), без неё — из файлов, как раньше.
|
|
101
|
-
- *Запуск (этап 3)*: глобально по-прежнему `dry_run`; включается **по слоту**:
|
|
102
|
-
|
|
103
|
-
| `agents[].dispatch` | Где можно | Что делает |
|
|
104
|
-
|---|---|---|
|
|
105
|
-
| `dry_run` (по умолчанию) | любой слот | план записывается, ничего не запускается |
|
|
106
|
-
| `live` | только `mode: "headless"` + `provider: "claude"`; только в `run` | `claude -p <задание> --output-format json --permission-mode default --allowedTools <DevOps MCP: request_deploy, deploy_status, list_deploys, list_deploy_targets, runner_status; git log/status/diff/show/rev-parse>` в `workspace` слота, без оболочки; один процесс на слот; таймаут `timeout_ms` (≤ `leaseMs`, по умолчанию = lease) → остановка и повтор; окружение — только имена из списка по умолчанию + `env_pass` слота; лог запуска (маскированный хвост) — `<stateDir>/live/J<n>-a<попытка>.json`; итог (`ORCHESTRATOR_RESULT`) → отчёт agent-events |
|
|
107
|
-
| `handoff` | только `mode: "session"` | `create_handoff` (#F73) в сессию человека (`handoff_agent` — id агента из `list_agents`, иначе провайдер); второй процесс в сессию не запускается; результат передачи с `ORCHESTRATOR_RESULT` завершает задание; невзятая к концу lease передача отменяется |
|
|
108
|
-
|
|
109
|
-
Любой план с флагом обхода (`--dangerously-skip-permissions`, `bypassPermissions`, иной `--permission-mode`, `--yolo`…),
|
|
110
|
-
лишним флагом (`--mcp-config` и т. п.), инструментом вне списка или чужим бинарником отклоняется **до** запуска
|
|
111
|
-
(`failed`). Одобрить выкатку оркестратор и запущенный агент не могут: такого вызова нет, одобряет человек ✅.
|
|
112
|
-
|
|
113
|
-
Переключить один слот на живой запуск (пример):
|
|
72
|
+
## Оркестратор внутри MCP (1.4.0, #486 v2, SDD-P37-160)
|
|
114
73
|
|
|
115
|
-
|
|
116
|
-
{ "id": "claude-headless", "provider": "claude", "mode": "headless", "dispatch": "live",
|
|
117
|
-
"workspace": "~/proj/nativemind.net/consilium.nativemind.net", "projects": [37],
|
|
118
|
-
"claude_bin": "~/.local/bin/claude", "timeout_ms": 900000, "capabilities": ["deploy_check"] }
|
|
119
|
-
```
|
|
74
|
+
<!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-24, по решению владельца: никакой отдельной службы. -->
|
|
120
75
|
|
|
121
|
-
|
|
122
|
-
|
|
76
|
+
DevOps Orchestrator работает **внутри уже запущенного процесса** `consilium-devops-mcp` — того, что Claude Code (или
|
|
77
|
+
другой клиент) стартует для сессии. Отдельной службы, systemd-юнита, команды `consilium-devops-orchestrator` и второго
|
|
78
|
+
процесса агента больше нет (1.2.0 / 1.3.0 удалены из пакета). Жизненный цикл один: MCP стартовал — слушатель событий
|
|
79
|
+
поднялся; MCP закрыт (клиент закрыл транспорт, stdin кончился, SIGTERM/SIGINT) — подписка закрыта, курсор и очередь
|
|
80
|
+
остались на диске; следующий старт MCP дочитывает журнал от курсора.
|
|
123
81
|
|
|
124
82
|
```
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
83
|
+
Консилиум ── project_events (#437: SSE projectEvents + get_events от курсора) ──► consilium-devops-mcp (один процесс)
|
|
84
|
+
├ слушатель (лидер рабочей папки)
|
|
85
|
+
├ inbox заданий (общий для MCP папки)
|
|
86
|
+
└ jobs_inbox / jobs_claim / jobs_ack /
|
|
87
|
+
jobs_status / jobs_result / jobs_release
|
|
88
|
+
основной агент сессии ── jobs_claim ──► встроенный субагент (Agent tool, та же сессия) ── request_deploy ──► ✅ человека
|
|
89
|
+
──► существующий runner #482 (выкатка)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
- **События → задания.** `agent.deploy_required` проекта с маршрутом → задание `devops.deploy_check` (конверт
|
|
93
|
+
`konsilium.agent-job/1` пакета `@consilium108/mcp-agent-jobs`). `DEPLOY_REQUIRED` — сигнал на **проверку**, не на
|
|
94
|
+
выкатку. Одна цель (`проект:окружение:цель` = `lock_key`) — одно активное задание; сигналы цели в очереди сливаются;
|
|
95
|
+
во время активного — один следующий, ждёт. Повторная доставка (SSE + догонка, повтор после рестарта) задание не
|
|
96
|
+
дублирует (ключ идемпотентности — проект + id события).
|
|
97
|
+
- **Кто выполняет.** MCP агента не запускает. Основной агент в безопасный момент смотрит `jobs_inbox`, берёт задание
|
|
98
|
+
`jobs_claim` (атомарно — одно выполнение на задание, даже при нескольких процессах MCP и сессиях в одной папке) и
|
|
99
|
+
запускает **своего** субагента штатным Agent tool с `subagent_prompt` (в фоне). Субагент: `jobs_ack` (старт и пульс
|
|
100
|
+
аренды), проверка изменений, при необходимости `request_deploy`, затем `jobs_result` (`requested` + `deploy_id`,
|
|
101
|
+
`not_needed`, `blocked`). Аренда (по умолчанию из конфига, `leaseMs`) без пульса истекает → задание в очередь с
|
|
102
|
+
отсрочкой, после `maxAttempts` — `failed`; поздний результат прежнего запуска (`stale_run`) ничего не меняет.
|
|
103
|
+
- **Выкатка.** После `requested` задание ждёт ✅ человека (`waiting_for_user`, держит цель, не истекает) и следует за
|
|
104
|
+
выкаткой по событиям `deploy.*` (`approved/running` → `running`, `done` → `succeeded`, `failed` → `failed`,
|
|
105
|
+
`rejected/expired` → `cancelled`); опрос `GET /deploys/:id` — запасной (только в процессе-слушателе, только при
|
|
106
|
+
тишине журнала). `deploy.requested` своей цели после взятия даёт номер выкатки, если субагент его не назвал.
|
|
107
|
+
Одобрить не может никто из MCP: такого инструмента и маршрута нет. Runner (#482) — отдельная служба на сервере
|
|
108
|
+
выкатки, исполняет только одобренное.
|
|
109
|
+
- **Отчёты в Консилиум** — `POST /api/projects/:id/agent-events` (идемпотентно, `provider: devops-orchestrator`):
|
|
110
|
+
ожидание ✅ → `NEEDS_APPROVAL` (blocking), `blocked` → `BLOCKED`, `failed` → `ERROR` (exit/health, без хвоста лога),
|
|
111
|
+
`succeeded/cancelled` → `TASK_COMPLETED`. При недоступности сервера — повтор с отсрочкой (на диске).
|
|
112
|
+
- **Состояние сессии (#470)** — `jobs_inbox.session` / `jobs_status.session`: idle / running / waiting_for_user /
|
|
113
|
+
blocked / unavailable по фактам монитора ходов рабочей папки; брать задание не мешает (субагенты идут параллельно).
|
|
114
|
+
- **Диагностика** — `jobs_status` без аргументов: слушатель каждого модуля (этот процесс / другой), проекты, транспорт,
|
|
115
|
+
курсор, счётчики, метрики, последняя ошибка.
|
|
116
|
+
|
|
117
|
+
Как занятая сессия узнаёт о задании (проверено 24.11, TASK-P36-531 и документация Claude Code): уведомления MCP
|
|
118
|
+
(`resources/updated`, лог) Claude Code хода не начинают — поэтому (1) основной агент смотрит `jobs_inbox` между
|
|
119
|
+
своими шагами (это сказано в instructions MCP), (2) по желанию человека — хук `konsilium-jobs-hook` пакета
|
|
120
|
+
`@consilium108/mcp-agent-jobs` на `UserPromptSubmit` / `SessionStart` / `PostToolUse` (добавляет в контекст «есть
|
|
121
|
+
задания»), или `konsilium-jobs-hook watch` в инструменте Monitor. Второй сессии / `claude -p` нет.
|
|
122
|
+
|
|
123
|
+
Конфиг (без секретов; без файла DevOps-заданий нет, инструменты inbox работают): `--orchestrator-config <file>`,
|
|
124
|
+
`$CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG` или `~/.config/consilium-devops-orchestrator/config.json`:
|
|
125
|
+
|
|
126
|
+
```json
|
|
127
|
+
{ "projects": [37],
|
|
128
|
+
"targets": { "konsilium-prod": { "project_id": 1, "environment": "production", "approval": "human" } },
|
|
129
|
+
"routes": [{ "event": "agent.deploy_required", "project_id": 37, "target": "konsilium-prod" }],
|
|
130
|
+
"leaseMs": 1800000, "maxAttempts": 3, "backoffMs": 60000, "report": "agent-events" }
|
|
131
131
|
```
|
|
132
132
|
|
|
133
|
-
|
|
133
|
+
Ключи прежней службы (`agents`, `dispatch`, `reportDryRun`, `pollMs`, `stateDir`, `sse`, `logFormat`, `stopTimeoutMs`)
|
|
134
|
+
игнорируются с предупреждением в stderr. Inbox — `$XDG_STATE_HOME/konsilium-mcp/<sha1(папки)>/jobs/` (общий с Developer
|
|
135
|
+
MCP той же папки; `KONSILIUM_JOBS_DIR` — иначе); выключить — `--no-jobs` / `KONSILIUM_JOBS=off`.
|
|
134
136
|
|
|
135
137
|
## Runner
|
|
136
138
|
|
|
@@ -3,7 +3,10 @@
|
|
|
3
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
4
|
// Konsilium credential (KONSILIUM_API_KEY, or the sign-in of `npx @consilium108/mcp login` when that package is installed).
|
|
5
5
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
6
|
+
import { createJobRuntime, createKonsiliumApi, ROUTES, jobsDirOf, bindToProcess } from '@consilium108/mcp-agent-jobs';
|
|
6
7
|
import { createDevopsMcp, DEFAULT_API_URL } from '../src/standalone.js';
|
|
8
|
+
import { findOrchestratorConfig, createDevopsProducer, createSessionRegistry } from '../src/orchestrator/index.js';
|
|
9
|
+
import { redact } from '../src/runner/log.js';
|
|
7
10
|
import mod from '../src/index.js';
|
|
8
11
|
|
|
9
12
|
const USAGE = `consilium-devops-mcp — Konsilium DevOps MCP (stdio): deploy requests and their status, deploy targets, debug reports
|
|
@@ -13,6 +16,10 @@ const USAGE = `consilium-devops-mcp — Konsilium DevOps MCP (stdio): deploy req
|
|
|
13
16
|
--project <id> active project (a choice, not a right; select_project changes it); default — the connection's default
|
|
14
17
|
--api <url> Konsilium core (default ${DEFAULT_API_URL})
|
|
15
18
|
--devops-api <url> the DevOps module API, only when it is reachable directly (default: through the core)
|
|
19
|
+
--orchestrator-config <file> the DevOps Orchestrator's targets / routes (default: $CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG,
|
|
20
|
+
~/.config/consilium-devops-orchestrator/config.json); without it no DevOps jobs are made
|
|
21
|
+
--workspace <dir> the workspace of the job inbox (default: the working directory = the repository of the session)
|
|
22
|
+
--no-jobs no job inbox (KONSILIUM_JOBS=off)
|
|
16
23
|
|
|
17
24
|
Environment:
|
|
18
25
|
KONSILIUM_API_KEY a Konsilium key (ksk_… from «Account → API»: the project + the right tasks:work) or an OAuth
|
|
@@ -22,7 +29,10 @@ Environment:
|
|
|
22
29
|
DEVOPS_API_URL the module API (instead of --devops-api)
|
|
23
30
|
KONSILIUM_KEYCHAIN=off do not look into the OS credential store
|
|
24
31
|
|
|
25
|
-
|
|
32
|
+
The DevOps Orchestrator runs INSIDE this process (TASK-P37-486 v2): it listens to the Konsilium journal (#437), turns
|
|
33
|
+
agent.deploy_required of a routed project into a job of the workspace's job inbox and follows the deploy; the main agent
|
|
34
|
+
of the session claims the job (jobs_claim) and starts its own built-in subagent. No separate service, no second agent
|
|
35
|
+
process. Deploys are approved only by a person with the deploy right (✅ in the messenger); this MCP requests and watches.`;
|
|
26
36
|
|
|
27
37
|
const argv = process.argv.slice(2);
|
|
28
38
|
if (argv.includes('--help') || argv.includes('-h')) {
|
|
@@ -61,6 +71,40 @@ async function credentialsOf() {
|
|
|
61
71
|
}
|
|
62
72
|
|
|
63
73
|
const credentials = await credentialsOf();
|
|
64
|
-
const
|
|
74
|
+
const optional = async (name, pick) => {
|
|
75
|
+
try {
|
|
76
|
+
return pick(await import(name));
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** TASK-P37-486 v2: the job inbox + the DevOps Orchestrator in THIS process (off: --no-jobs / KONSILIUM_JOBS=off). */
|
|
83
|
+
async function jobRuntime() {
|
|
84
|
+
if (argv.includes('--no-jobs') || env.KONSILIUM_JOBS === 'off') return null;
|
|
85
|
+
const logger = { info: (m, f) => log(`${m}${f ? ` ${JSON.stringify(f)}` : ''}`), warn: (m, f) => log(`warn: ${m}${f ? ` ${JSON.stringify(f)}` : ''}`), error: (m, f) => log(`error: ${m}${f ? ` ${JSON.stringify(f)}` : ''}`) };
|
|
86
|
+
try {
|
|
87
|
+
const workspace = opt('--workspace') ?? env.KONSILIUM_WORKSPACE ?? process.cwd();
|
|
88
|
+
const found = findOrchestratorConfig({ file: opt('--orchestrator-config') });
|
|
89
|
+
if (found.error) log(`orchestrator config ${found.error.file}: ${found.error.code}: ${found.error.message} — no DevOps jobs`);
|
|
90
|
+
const cfg = found.config;
|
|
91
|
+
for (const w of cfg?.warnings ?? []) log(`orchestrator config: ${w}`);
|
|
92
|
+
const signedIn = credentials.source() !== 'none';
|
|
93
|
+
const api = signedIn ? createKonsiliumApi({ server: cfg?.server ?? apiUrl, credentials, routes: [ROUTES.events, ROUTES.deploy, ROUTES.report], subscribeSse: await optional('@nativemind108/mcp', (m) => m.subscribeSse ?? null), userAgent: `consilium-devops-mcp/${mod.version}` }) : null;
|
|
94
|
+
const registry = createSessionRegistry({ workspace, idleTtlMs: cfg?.idleTtlMs, turnMonitor: await optional('@consilium108/mcp/turnmonitor', (m) => m) });
|
|
95
|
+
const producer = cfg ? createDevopsProducer({ config: cfg, api, log: logger, registry, redact }) : null;
|
|
96
|
+
return createJobRuntime({ dir: jobsDirOf(workspace), workspace, producers: producer ? [producer] : [], api, log: logger, leaseMs: cfg?.leaseMs, maxAttempts: cfg?.maxAttempts, backoffMs: cfg?.backoffMs, sessionState: () => registry.state() });
|
|
97
|
+
} catch (e) {
|
|
98
|
+
log(`job inbox off: ${e.code ?? 'error'}: ${e.message}`);
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const jobs = await jobRuntime();
|
|
104
|
+
const { server } = createDevopsMcp({ apiUrl, devopsUrl, credentials, projectId, jobs });
|
|
65
105
|
await server.connect(new StdioServerTransport());
|
|
66
|
-
|
|
106
|
+
if (jobs) {
|
|
107
|
+
bindToProcess(jobs, { server, log });
|
|
108
|
+
await jobs.start();
|
|
109
|
+
}
|
|
110
|
+
log(`${mod.name} ${mod.version}; core ${apiUrl}${devopsUrl ? `; module ${devopsUrl}` : ''}; project ${projectId ?? 'default of the connection'}; credential: ${credentials.source()}; jobs: ${jobs ? `${jobs.dir} (DevOps jobs: ${jobs.modules().includes('devops') ? 'on' : 'off — no orchestrator config'})` : 'off'}`);
|
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; also runs on its own (bin consilium-devops-mcp, #482)
|
|
3
|
+
"version": "1.4.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) — with the DevOps Orchestrator inside that process (#486 v2: Konsilium events → jobs of the workspace's job inbox, claimed by the session's own subagents); 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",
|
|
@@ -19,8 +19,7 @@
|
|
|
19
19
|
"bin": {
|
|
20
20
|
"mcp-module-devops": "bin/consilium-devops-mcp.js",
|
|
21
21
|
"consilium-devops-mcp": "bin/consilium-devops-mcp.js",
|
|
22
|
-
"consilium-devops-runner": "bin/consilium-devops-runner.js"
|
|
23
|
-
"consilium-devops-orchestrator": "bin/consilium-devops-orchestrator.js"
|
|
22
|
+
"consilium-devops-runner": "bin/consilium-devops-runner.js"
|
|
24
23
|
},
|
|
25
24
|
"files": [
|
|
26
25
|
"src",
|
|
@@ -42,6 +41,7 @@
|
|
|
42
41
|
}
|
|
43
42
|
},
|
|
44
43
|
"dependencies": {
|
|
44
|
+
"@consilium108/mcp-agent-jobs": "^0.1.0",
|
|
45
45
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
46
46
|
"@nativemind108/mcp": "^1.13.0",
|
|
47
47
|
"zod": "^4.6.7"
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2 (SDD-P37-160, IT-160-5 / IT-160-6): what a
|
|
2
|
+
// subagent gets for a DevOps job — the job context (only verified fields; unknown ones named as unknown) and the brief.
|
|
3
|
+
// Kept from adapters.js of 1.2.0 / 1.3.0 (jobContext, promptOf, DEPLOY_CHECK_TOOLS); the provider adapters, the live
|
|
4
|
+
// `claude -p` plans and the ORCHESTRATOR_RESULT line are gone: the result now comes through jobs_result (or the
|
|
5
|
+
// AGENT_JOB_RESULT line of @consilium108/mcp-agent-jobs). Rules: the subagent may only analyse and REQUEST a deploy
|
|
6
|
+
// (request_deploy); a person approves it (✅); no secret in the brief — only refs, ids, the target key, the environment.
|
|
7
|
+
|
|
8
|
+
/** DevOps MCP tools a deploy_check may use (read + request; there is no approve tool and none is allowed). */
|
|
9
|
+
export const DEPLOY_CHECK_TOOLS = ['request_deploy', 'deploy_status', 'list_deploys', 'list_deploy_targets', 'runner_status'];
|
|
10
|
+
|
|
11
|
+
/** The structured job context: only verified fields; what is not known is listed in `unknown`. */
|
|
12
|
+
export function jobContext(job) {
|
|
13
|
+
const src = job.sources ?? [];
|
|
14
|
+
// G2: what the agents said about the deploy (branch / commit) — given when every signal agrees, else still unknown
|
|
15
|
+
const one = (k) => {
|
|
16
|
+
const v = [...new Set(src.map((s) => s[k]).filter(Boolean))];
|
|
17
|
+
return v.length === 1 && src.every((s) => s[k]) ? v[0] : null;
|
|
18
|
+
};
|
|
19
|
+
const branch = one('branch');
|
|
20
|
+
const commit = one('commit_sha');
|
|
21
|
+
return {
|
|
22
|
+
schema: 'konsilium.devops-job/2',
|
|
23
|
+
kind: job.kind,
|
|
24
|
+
project_id: job.projectId,
|
|
25
|
+
target: job.target,
|
|
26
|
+
environment: job.environment,
|
|
27
|
+
approval: { required: true, by: 'a person with the deploy right (✅ in the Konsilium bot)', orchestrator_may_approve: false, agent_may_approve: false },
|
|
28
|
+
signals: src.map((s) => ({ event_id: s.event_id, project_id: s.project_id, type: s.type, task_ref: s.task_ref ?? null, session: s.session ?? null, summary: s.summary ?? null, at: s.at ?? null, ...(s.branch ? { branch: s.branch } : {}), ...(s.commit_sha ? { commit_sha: s.commit_sha } : {}) })),
|
|
29
|
+
...(branch ? { branch } : {}),
|
|
30
|
+
...(commit ? { commit_sha: commit } : {}),
|
|
31
|
+
unknown: [...(branch ? [] : ['repository branch']), ...(commit ? [] : ['commit SHA']), 'what changed since the last deploy'],
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function promptOf(job) {
|
|
36
|
+
return [
|
|
37
|
+
`DevOps deploy check for the deploy target «${job.target}» (${job.environment}), Konsilium project ${job.projectId}.`,
|
|
38
|
+
'An agent turn said a deploy may be needed (DEPLOY_REQUIRED). That is a signal, NOT a command to deploy.',
|
|
39
|
+
'1. Check what changed (git log / git status in this workspace) and whether those changes are committed and tested.',
|
|
40
|
+
`2. If a deploy is warranted, call the DevOps MCP tool request_deploy with target «${job.target}» and a one-line summary. That only creates a request: a person with the deploy right approves it with ✅ in the bot; the deploy runner then executes it. Never approve, never run the deploy steps yourself, never edit the runner config.`,
|
|
41
|
+
'3. If it is not warranted or you are unsure, do not request; say why.',
|
|
42
|
+
'Report: outcome «requested» with deploy_id (the request id request_deploy returned), «not_needed», or «blocked» with the reason.',
|
|
43
|
+
'The job context (JSON):',
|
|
44
|
+
JSON.stringify(jobContext(job)),
|
|
45
|
+
].join('\n');
|
|
46
|
+
}
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §4): the orchestrator's config.
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
2
|
+
// v2 (owner, 2026-11-24): the orchestrator runs INSIDE the DevOps MCP (bin consilium-devops-mcp) — this file only says
|
|
3
|
+
// which projects it listens to and which targets / routes make jobs. It holds NO secret: the Konsilium credential is
|
|
4
|
+
// the MCP's (KONSILIUM_API_KEY or the `@consilium108/mcp login` sign-in). Location: --orchestrator-config <file>,
|
|
5
|
+
// $CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG, ~/.config/consilium-devops-orchestrator/config.json,
|
|
6
|
+
// /etc/consilium-devops-orchestrator/config.json; no file = the MCP makes no DevOps jobs (the inbox tools still work).
|
|
7
|
+
// Keys of the removed service (agents, dispatch, reportDryRun, pollMs, stateDir, sse, logFormat, stopTimeoutMs) are
|
|
8
|
+
// ignored with a warning: jobs go to the running session's own subagents through jobs_claim; nothing is started.
|
|
8
9
|
import { existsSync, readFileSync } from 'node:fs';
|
|
9
10
|
import { homedir } from 'node:os';
|
|
10
|
-
import {
|
|
11
|
+
import { join } from 'node:path';
|
|
11
12
|
import { DevopsMcpError } from '../errors.js';
|
|
12
13
|
import { DEFAULT_SERVER } from '../runner/config.js';
|
|
13
14
|
|
|
@@ -17,14 +18,6 @@ export const ORCHESTRATOR_PROVIDER = 'devops-orchestrator';
|
|
|
17
18
|
/** Idempotency-key prefix of its own reports; the server stores it as content_hash «tm:orc:…». */
|
|
18
19
|
export const OWN_KEY_PREFIX = 'orc:';
|
|
19
20
|
export const JOB_KINDS = ['deploy_check'];
|
|
20
|
-
export const DISPATCH_MODES = ['dry_run'];
|
|
21
|
-
/** Per agent slot (stage 3): dry_run (default) · live (headless claude only) · handoff (session slots only). */
|
|
22
|
-
export const SLOT_DISPATCH = ['dry_run', 'live', 'handoff'];
|
|
23
|
-
/** Environment variables a live run inherits by default (names only; values never logged). Anything else is dropped. */
|
|
24
|
-
export const LIVE_ENV_DEFAULT = ['PATH', 'HOME', 'USER', 'LOGNAME', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'TMPDIR', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'XDG_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR', 'ANTHROPIC_API_KEY', 'KONSILIUM_API_KEY', 'KONSILIUM_API_URL'];
|
|
25
|
-
export const AGENT_MODES = ['session', 'headless'];
|
|
26
|
-
|
|
27
|
-
const expandHome = (p, home) => (p && p.startsWith('~/') ? join(home, p.slice(2)) : p);
|
|
28
21
|
|
|
29
22
|
export function orchestratorConfigCandidates(env = process.env, home = homedir()) {
|
|
30
23
|
if (env.CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG) return [env.CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG];
|
|
@@ -32,19 +25,20 @@ export function orchestratorConfigCandidates(env = process.env, home = homedir()
|
|
|
32
25
|
return [join(xdg, ORCHESTRATOR_NAME, 'config.json'), `/etc/${ORCHESTRATOR_NAME}/config.json`];
|
|
33
26
|
}
|
|
34
27
|
|
|
28
|
+
/** Keys of the removed separate service (1.2.0 / 1.3.0) — ignored with a warning. */
|
|
29
|
+
export const LEGACY_KEYS = ['agents', 'dispatch', 'reportDryRun', 'pollMs', 'stateDir', 'sse', 'logFormat', 'stopTimeoutMs'];
|
|
30
|
+
|
|
35
31
|
const bad = (msg) => new DevopsMcpError('config_invalid', msg);
|
|
36
32
|
|
|
37
33
|
/**
|
|
38
34
|
* Normalizes and validates a raw config object (already parsed). Throws config_invalid with the reason.
|
|
39
|
-
* → { file, server, projects,
|
|
40
|
-
*
|
|
35
|
+
* → { file, server, projects, leaseMs, deployPollFallbackMs, maxAttempts, backoffMs, idleTtlMs, report, targets, routes,
|
|
36
|
+
* warnings }
|
|
41
37
|
*/
|
|
42
38
|
export function normalizeOrchestratorConfig(raw, { file = null, env = process.env, home = homedir() } = {}) {
|
|
43
39
|
if (!raw || typeof raw !== 'object') throw bad('the config must be a JSON object');
|
|
44
|
-
const base = file ? dirname(file) : process.cwd();
|
|
45
40
|
if ('token' in raw || 'apiKey' in raw || 'tokenFile' in raw) throw bad('the orchestrator config holds no credential: use KONSILIUM_API_KEY or `npx @consilium108/mcp login`');
|
|
46
|
-
const
|
|
47
|
-
if (!DISPATCH_MODES.includes(dispatch)) throw bad(`dispatch «${dispatch}» is not available globally (the global dispatch stays ${DISPATCH_MODES.join(', ')}); start agents per slot: agents[].dispatch "live" (mode headless, provider claude) or "handoff" (mode session)`);
|
|
41
|
+
const warnings = LEGACY_KEYS.filter((k) => k in raw).map((k) => `«${k}» is ignored: the orchestrator runs inside the DevOps MCP and hands jobs to the session's own subagents (jobs_claim); nothing is started or dispatched by it`);
|
|
48
42
|
const leaseMs = Number(raw.leaseMs) || 30 * 60_000;
|
|
49
43
|
const targets = {};
|
|
50
44
|
for (const [key, t] of Object.entries(raw.targets ?? {})) {
|
|
@@ -65,75 +59,27 @@ export function normalizeOrchestratorConfig(raw, { file = null, env = process.en
|
|
|
65
59
|
if (!JOB_KINDS.includes(kind)) throw bad(`routes[${i}].kind «${kind}»: one of ${JOB_KINDS.join(', ')}`);
|
|
66
60
|
return { event, projectId, target: r.target, kind, priority: Number(r.priority) || 0 };
|
|
67
61
|
});
|
|
68
|
-
const ids = new Set();
|
|
69
|
-
const agents = (raw.agents ?? []).map((a, i) => {
|
|
70
|
-
const id = String(a?.id ?? '');
|
|
71
|
-
if (!/^[a-z0-9][a-z0-9._-]{0,59}$/i.test(id)) throw bad(`agents[${i}].id: letters, digits, . _ - only`);
|
|
72
|
-
if (ids.has(id)) throw bad(`agents: id «${id}» twice`);
|
|
73
|
-
ids.add(id);
|
|
74
|
-
const mode = a.mode ?? 'session';
|
|
75
|
-
if (!AGENT_MODES.includes(mode)) throw bad(`agents[${i}].mode: ${AGENT_MODES.join(' | ')}`);
|
|
76
|
-
if (!a.workspace) throw bad(`agents[${i}].workspace (the repository the agent works in) is required`);
|
|
77
|
-
const projects = [].concat(a.projects ?? []).map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
|
78
|
-
if (!projects.length) throw bad(`agents[${i}].projects: at least one Konsilium project id`);
|
|
79
|
-
const provider = String(a.provider ?? 'claude');
|
|
80
|
-
// stage 3: starting an agent is per slot and narrow — never a second process in a person's session
|
|
81
|
-
const slotDispatch = a.dispatch ?? 'dry_run';
|
|
82
|
-
if (!SLOT_DISPATCH.includes(slotDispatch)) throw bad(`agents[${i}].dispatch: ${SLOT_DISPATCH.join(' | ')}`);
|
|
83
|
-
if (slotDispatch === 'live' && (mode !== 'headless' || provider !== 'claude')) throw bad(`agents[${i}].dispatch "live" is allowed only for mode "headless" with provider "claude" (a session slot gets "handoff")`);
|
|
84
|
-
if (slotDispatch === 'handoff' && mode !== 'session') throw bad(`agents[${i}].dispatch "handoff" is for mode "session" slots (a headless claude slot may be "live")`);
|
|
85
|
-
const timeoutMs = a.timeout_ms == null ? leaseMs : Number(a.timeout_ms);
|
|
86
|
-
if (!Number.isFinite(timeoutMs) || timeoutMs < 1000 || timeoutMs > leaseMs) throw bad(`agents[${i}].timeout_ms: 1000 … leaseMs (${leaseMs}) — a live run never outlives its lease`);
|
|
87
|
-
const claudeBin = a.claude_bin == null ? 'claude' : String(a.claude_bin);
|
|
88
|
-
if (!/(^|\/)claude$/.test(claudeBin)) throw bad(`agents[${i}].claude_bin: a path to the \`claude\` binary (…/claude)`);
|
|
89
|
-
const envPass = [].concat(a.env_pass ?? []).map(String);
|
|
90
|
-
for (const n of envPass) if (!/^[A-Z_][A-Z0-9_]{0,63}$/.test(n)) throw bad(`agents[${i}].env_pass: variable names only (${n})`);
|
|
91
|
-
const handoffAgent = a.handoff_agent == null ? null : String(a.handoff_agent);
|
|
92
|
-
if (handoffAgent && !/^[a-z0-9][a-z0-9._-]{1,39}$/i.test(handoffAgent)) throw bad(`agents[${i}].handoff_agent: an agent id from list_agents (e.g. claude-1a2b3c) or a provider`);
|
|
93
|
-
return {
|
|
94
|
-
id,
|
|
95
|
-
provider,
|
|
96
|
-
mode,
|
|
97
|
-
dispatch: slotDispatch,
|
|
98
|
-
timeoutMs,
|
|
99
|
-
claudeBin: claudeBin.startsWith('~/') || claudeBin.includes('/') ? resolve(base, expandHome(claudeBin, home)) : claudeBin,
|
|
100
|
-
envPass,
|
|
101
|
-
handoffAgent,
|
|
102
|
-
workspace: resolve(base, expandHome(String(a.workspace), home)),
|
|
103
|
-
projects,
|
|
104
|
-
capabilities: [].concat(a.capabilities ?? JOB_KINDS).map(String),
|
|
105
|
-
sessionId: a.session_id ? String(a.session_id).slice(0, 120) : null,
|
|
106
|
-
};
|
|
107
|
-
});
|
|
108
62
|
const projects = [...new Set([...(raw.projects ?? []).map(Number), ...routes.map((r) => r.projectId)])].filter((n) => Number.isInteger(n) && n > 0);
|
|
109
63
|
if (!projects.length) throw bad('projects: at least one project id to listen to (or a route)');
|
|
110
|
-
const stateDir = resolve(base, expandHome(env.CONSILIUM_ORCHESTRATOR_STATE_DIR ?? raw.stateDir ?? join(env.XDG_STATE_HOME || join(home, '.local', 'state'), ORCHESTRATOR_NAME), home));
|
|
111
64
|
return {
|
|
112
65
|
file,
|
|
113
66
|
server: String(env.KONSILIUM_API_URL ?? raw.server ?? DEFAULT_SERVER).replace(/\/+$/, ''),
|
|
114
67
|
projects,
|
|
115
|
-
stateDir,
|
|
116
|
-
pollMs: Number(raw.pollMs) || 5_000,
|
|
117
68
|
leaseMs,
|
|
118
69
|
deployPollFallbackMs: Number(raw.deployPollFallbackMs) || 5 * 60_000,
|
|
119
70
|
maxAttempts: Number(raw.maxAttempts) || 3,
|
|
120
71
|
backoffMs: Number(raw.backoffMs) || 60_000,
|
|
121
72
|
idleTtlMs: Number(raw.idleTtlMs) || 6 * 3600_000,
|
|
122
|
-
stopTimeoutMs: Number(raw.stopTimeoutMs) || 30_000,
|
|
123
|
-
dispatch,
|
|
124
73
|
report: raw.report === 'off' ? 'off' : 'agent-events',
|
|
125
|
-
reportDryRun: raw.reportDryRun === true,
|
|
126
|
-
sse: raw.sse !== false,
|
|
127
|
-
logFormat: env.CONSILIUM_ORCHESTRATOR_LOG_FORMAT ?? raw.logFormat ?? 'json',
|
|
128
74
|
targets,
|
|
129
75
|
routes,
|
|
130
|
-
|
|
76
|
+
warnings,
|
|
131
77
|
};
|
|
132
78
|
}
|
|
133
79
|
|
|
134
80
|
export function loadOrchestratorConfig({ file = null, env = process.env, home = homedir() } = {}) {
|
|
135
81
|
const f = file ?? orchestratorConfigCandidates(env, home).find((p) => existsSync(p)) ?? null;
|
|
136
|
-
if (!f || !existsSync(f)) throw new DevopsMcpError('config_missing', `no orchestrator config (looked at ${orchestratorConfigCandidates(env, home).join(', ')}).
|
|
82
|
+
if (!f || !existsSync(f)) throw new DevopsMcpError('config_missing', `no orchestrator config (looked at ${orchestratorConfigCandidates(env, home).join(', ')}). see README «Orchestrator inside the MCP»`);
|
|
137
83
|
let raw;
|
|
138
84
|
try {
|
|
139
85
|
raw = JSON.parse(readFileSync(f, 'utf8'));
|
|
@@ -143,22 +89,27 @@ export function loadOrchestratorConfig({ file = null, env = process.env, home =
|
|
|
143
89
|
return normalizeOrchestratorConfig(raw, { file: f, env, home });
|
|
144
90
|
}
|
|
145
91
|
|
|
146
|
-
/** An example config (
|
|
147
|
-
export function exampleOrchestratorConfig({
|
|
92
|
+
/** An example config (README «Orchestrator inside the MCP»). No secret inside. */
|
|
93
|
+
export function exampleOrchestratorConfig({ projectId = 1, target = 'konsilium-prod' } = {}) {
|
|
148
94
|
return {
|
|
149
95
|
server: DEFAULT_SERVER,
|
|
150
96
|
projects: [projectId],
|
|
151
|
-
stateDir: `~/.local/state/${ORCHESTRATOR_NAME}`,
|
|
152
|
-
dispatch: 'dry_run',
|
|
153
97
|
report: 'agent-events',
|
|
154
|
-
pollMs: 5000,
|
|
155
98
|
leaseMs: 1800000,
|
|
156
99
|
maxAttempts: 3,
|
|
157
100
|
backoffMs: 60000,
|
|
158
101
|
targets: { [target]: { project_id: projectId, environment: 'production', approval: 'human', title: 'Консилиум (прод)' } },
|
|
159
102
|
routes: [{ event: 'agent.deploy_required', project_id: projectId, target, kind: 'deploy_check' }],
|
|
160
|
-
// dispatch per slot: "dry_run" (default) · "handoff" (a session slot: create_handoff into it) · "live" (mode
|
|
161
|
-
// "headless" + provider "claude" only: `claude -p`, timeout_ms ≤ leaseMs)
|
|
162
|
-
agents: [{ id: 'claude-main', provider: 'claude', mode: 'session', dispatch: 'dry_run', workspace: repoDir, projects: [projectId], capabilities: ['deploy_check'] }],
|
|
163
103
|
};
|
|
164
104
|
}
|
|
105
|
+
|
|
106
|
+
/** The config file of the MCP start, or { config: null } when there is none (no DevOps jobs; never an MCP failure). */
|
|
107
|
+
export function findOrchestratorConfig({ file = null, env = process.env, home = homedir() } = {}) {
|
|
108
|
+
const f = file ?? orchestratorConfigCandidates(env, home).find((p) => existsSync(p)) ?? null;
|
|
109
|
+
if (!f) return { config: null, error: null, looked: orchestratorConfigCandidates(env, home) };
|
|
110
|
+
try {
|
|
111
|
+
return { config: loadOrchestratorConfig({ file: f, env, home }), error: null };
|
|
112
|
+
} catch (e) {
|
|
113
|
+
return { config: null, error: { code: e.code ?? 'config_invalid', message: e.message, file: f } };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §3): the event contract the
|
|
2
|
-
// orchestrator consumes — ONLY what the server really sends today (project_events of #437 / #470), nothing assumed.
|
|
2
|
+
// orchestrator consumes (v2: inside the DevOps MCP — producer.js; unchanged rules) — ONLY what the server really sends today (project_events of #437 / #470), nothing assumed.
|
|
3
3
|
// get_events (REST) { event_id, type, project_id, ref:{type,id}, agent, actor_user_id, summary, at, entity_type?,
|
|
4
4
|
// entity_ref?, path?, version?, content_hash?, deleted?, via? }
|
|
5
5
|
// projectEvents (SSE) { cursor, type, projectId, entity, ref, path, version, contentHash, deleted, at }
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// G1 (2026-11-24): deploy.* events of the journal (requested / approved / rejected / running / done / failed /
|
|
12
12
|
// rolled_back / expired; ref = the deploy id, meta { deploy_id, target, kind, status, exit_code, health }) drive the jobs
|
|
13
13
|
// that follow a deploy request — instead of polling GET /deploys/:id (kept as a fallback).
|
|
14
|
+
import { normalizeBusEvent as normalizeGeneric } from '@consilium108/mcp-agent-jobs';
|
|
14
15
|
import { OWN_KEY_PREFIX, ORCHESTRATOR_PROVIDER } from './config.js';
|
|
15
16
|
|
|
16
17
|
/** Agent event types that say something about an agent session's state (registry hints). */
|
|
@@ -26,18 +27,10 @@ export const STATE_HINTS = {
|
|
|
26
27
|
'agent.task_completed': 'idle',
|
|
27
28
|
};
|
|
28
29
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
/** One event of either shape → { cursor, type, projectId, agent, summary, entityRef, session, contentHash, at, refType, refId, meta, own } | null. */
|
|
30
|
+
/** One event of either shape (normalizeBusEvent of @consilium108/mcp-agent-jobs) + `own`: the orchestrator's own report. */
|
|
32
31
|
export function normalizeBusEvent(e) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
if ('event_id' in e) {
|
|
36
|
-
ev = { cursor: Number(e.event_id), type: e.type ?? null, projectId: e.project_id ?? null, agent: e.agent ?? null, summary: e.summary ?? null, entityRef: e.entity_ref ?? null, session: e.path ?? null, contentHash: e.content_hash ?? null, at: e.at ?? null, refType: e.ref?.type ?? null, refId: e.ref?.id ?? null, meta: metaOf(e.meta) };
|
|
37
|
-
} else {
|
|
38
|
-
ev = { cursor: Number(e.cursor), type: e.type ?? e.kind ?? null, projectId: e.projectId ?? null, agent: e.agent ?? null, summary: e.summary ?? null, entityRef: typeof e.ref === 'string' ? e.ref : (e.entity_ref ?? null), session: e.path ?? null, contentHash: e.contentHash ?? null, at: e.at ?? null, refType: e.entity?.type ?? null, refId: e.entity?.id ?? null, meta: metaOf(e.meta) };
|
|
39
|
-
}
|
|
40
|
-
if (!Number.isFinite(ev.cursor) || !ev.type) return null;
|
|
32
|
+
const ev = normalizeGeneric(e);
|
|
33
|
+
if (!ev) return null;
|
|
41
34
|
// loop guard: the orchestrator's own reports come back through the same journal
|
|
42
35
|
ev.own = ev.agent === ORCHESTRATOR_PROVIDER || String(ev.contentHash ?? '').startsWith(`tm:${OWN_KEY_PREFIX}`);
|
|
43
36
|
return ev;
|
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160: the
|
|
2
|
-
// @consilium108/mcp-module-devops (export "./orchestrator")
|
|
3
|
-
// @
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2, SDD-P37-160: the DevOps Orchestrator of
|
|
2
|
+
// @consilium108/mcp-module-devops (export "./orchestrator") — INSIDE the DevOps MCP since 1.4.0: the producer of DevOps
|
|
3
|
+
// jobs for the shared job inbox of @consilium108/mcp-agent-jobs; the MCP bin starts and stops it with the process.
|
|
4
|
+
// The separate service of 1.2.0 / 1.3.0 (bin consilium-devops-orchestrator, systemd unit, agent slots, dry-run / live /
|
|
5
|
+
// hand-off dispatch) is removed.
|
|
6
|
+
export { ORCHESTRATOR_NAME, ORCHESTRATOR_PROVIDER, OWN_KEY_PREFIX, JOB_KINDS, LEGACY_KEYS, orchestratorConfigCandidates, normalizeOrchestratorConfig, loadOrchestratorConfig, findOrchestratorConfig, exampleOrchestratorConfig } from './config.js';
|
|
6
7
|
export { normalizeBusEvent, intentOf, summaryHead, STATE_HINTS, DEPLOY_EVENT_STATUS } from './events.js';
|
|
7
|
-
export { createRegistry,
|
|
8
|
-
export {
|
|
9
|
-
export {
|
|
10
|
-
export { createOrchestratorApi, PROJECT_EVENTS_QUERY, ALLOWED_ROUTES } from './api.js';
|
|
11
|
-
export { createEventSource } from './source.js';
|
|
12
|
-
export { createOrchestrator } from './daemon.js';
|
|
13
|
-
export { orchestratorUnitText } from './install.js';
|
|
8
|
+
export { createRegistry, createSessionRegistry, readTurnJournal, sessionStateOf, turnMonitorDirOf, AGENT_STATES } from './registry.js';
|
|
9
|
+
export { DEPLOY_CHECK_TOOLS, jobContext, promptOf } from './brief.js';
|
|
10
|
+
export { createDevopsProducer, isOwnEvent, DEVOPS_MCP, DEVOPS_KINDS, DEVOPS_EVENT_TYPES } from './producer.js';
|