@consilium108/mcp-module-devops 1.1.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 +78 -0
- package/README.md +65 -0
- package/bin/consilium-devops-mcp.js +47 -3
- package/package.json +5 -3
- package/src/orchestrator/brief.js +46 -0
- package/src/orchestrator/config.js +115 -0
- package/src/orchestrator/events.js +84 -0
- package/src/orchestrator/index.js +10 -0
- package/src/orchestrator/producer.js +193 -0
- package/src/orchestrator/registry.js +162 -0
- package/src/runner/state.js +4 -4
- package/src/standalone.js +9 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,83 @@
|
|
|
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
|
+
|
|
39
|
+
## 1.3.0 — 2026-11-24
|
|
40
|
+
|
|
41
|
+
<!-- generated by Claude (Opus 5.5), 2026-11-24; Konsilium SDD-P37-160 — owner 2026-11-24 «Запускай все, добавь сразу».
|
|
42
|
+
1.2.0 was never published (npm has 1.0.0, 1.1.0): its changes are folded into this section. -->
|
|
43
|
+
|
|
44
|
+
- **Deploy lifecycle from the journal (G1).** The orchestrator subscribes to `deploy.*` as well as `agent.*` and moves
|
|
45
|
+
the jobs that follow a deploy request by `deploy.requested / approved / rejected / running / done / failed /
|
|
46
|
+
rolled_back / expired` (the core's `project_events`, migration 151 `meta`; the DevOps module reports them through its
|
|
47
|
+
`core_outbox`). `GET /deploys/:id` stays as the fallback: every tick until the project is seen sending `deploy.*`,
|
|
48
|
+
then only after `deployPollFallbackMs` (default 5 min) without a fact. A `deploy.requested` of the job's target after
|
|
49
|
+
the assignment gives the deploy id when the agent's result line has none (IT-14).
|
|
50
|
+
- **Target / environment / branch / commit from the agent event (G2).** When an `agent.*` event carries `meta.target` /
|
|
51
|
+
`environment`, the route is chosen among the configured routes of that project (an unrouted target is ignored:
|
|
52
|
+
`target_not_routed`); `branch` / `commit_sha` go into the job (`konsilium.devops-job/1`) and leave `unknown`.
|
|
53
|
+
- **Turn-monitor state through `@consilium108/mcp/turnmonitor` (G4)** when the host package (≥ 0.11.1) is installed —
|
|
54
|
+
incl. `TURN_STARTED` (G3) = running; otherwise the files are read as before.
|
|
55
|
+
- **Live dispatch per slot (stage 3).** The global dispatch stays `dry_run`. `agents[].dispatch: "live"` (only `mode:
|
|
56
|
+
"headless"` + `provider: "claude"`, only in `run`) starts `claude -p <job> --output-format json --permission-mode
|
|
57
|
+
default --allowedTools <DevOps MCP tools + read-only git>` in the slot's workspace without a shell — one job at a time
|
|
58
|
+
per slot, `timeout_ms` ≤ `leaseMs` (stop + retry), only the default env names + `env_pass`, a masked per-run log in
|
|
59
|
+
`<stateDir>/live/`, the `ORCHESTRATOR_RESULT` → complete → agent-events report (sent although the global dispatch is
|
|
60
|
+
dry-run). `validateLivePlan` refuses any other shape before anything is spawned (bypass flags, another permission mode,
|
|
61
|
+
extra flags, tools outside the list, another binary). `agents[].dispatch: "handoff"` (only `mode: "session"`) creates a
|
|
62
|
+
hand-off (`POST /api/projects/:id/handoffs`, `handoff_agent` or the provider) instead of a second process; the
|
|
63
|
+
hand-off's result completes the job; a hand-off nobody took by the end of the lease is cancelled. A restart during a
|
|
64
|
+
live run retries the job at once. New exports: `createLiveDispatcher`, `validateLivePlan`, `LIVE_ALLOWED_TOOLS`,
|
|
65
|
+
`READ_ONLY_GIT`, `SLOT_DISPATCH`, `LIVE_ENV_DEFAULT`, `DEPLOY_EVENT_STATUS`, `resultTextOf`, `liveEnvOf`,
|
|
66
|
+
`maskSecrets`. `ALLOWED_ROUTES` + the three hand-off routes (create / read / cancel its own) — still no approve route.
|
|
67
|
+
|
|
68
|
+
### Folded from 1.2.0 (never published)
|
|
69
|
+
|
|
70
|
+
- The local DevOps agent orchestrator — a SEPARATE service in the same package: bin `consilium-devops-orchestrator`
|
|
71
|
+
(`run`, `once`, `status`, `agents`, `check`, `config --print`, `unit --print`) and export `./orchestrator` (Node
|
|
72
|
+
built-ins; SSE through `subscribeSse` of `@nativemind108/mcp`). Event source = the existing delivery of #437
|
|
73
|
+
(`projectEvents` SSE, `get_events` catch-up / long poll, cursor saved after handling, a first start is a baseline);
|
|
74
|
+
agent registry = config slots + #470 turn-monitor facts (idle / running / waiting_for_user / blocked / unavailable);
|
|
75
|
+
durable queue with a lock per project + environment + target, coalescing, lease with renewal, retry with backoff,
|
|
76
|
+
restart recovery; provider adapters (claude, codex, generic) — **dry-run dispatch only**; follows the status of a
|
|
77
|
+
deploy an agent requested; reports through `POST /api/projects/:id/agent-events`. Never approves; plans with a
|
|
78
|
+
permission-bypass flag are refused; no secret in config, prompts, reports or logs.
|
|
79
|
+
- `acquireLock(dir, name = 'runner.lock')` — optional lock-file name (the runner is unchanged).
|
|
80
|
+
|
|
3
81
|
## 1.1.0 (unreleased)
|
|
4
82
|
|
|
5
83
|
<!-- generated by Claude (Opus 5.5), 2026-11-22; Konsilium #482 (TASK-P37-482) -->
|
package/README.md
CHANGED
|
@@ -69,6 +69,71 @@ 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
|
+
## Оркестратор внутри MCP (1.4.0, #486 v2, SDD-P37-160)
|
|
73
|
+
|
|
74
|
+
<!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-24, по решению владельца: никакой отдельной службы. -->
|
|
75
|
+
|
|
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 дочитывает журнал от курсора.
|
|
81
|
+
|
|
82
|
+
```
|
|
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
|
+
```
|
|
132
|
+
|
|
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`.
|
|
136
|
+
|
|
72
137
|
## Runner
|
|
73
138
|
|
|
74
139
|
<!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-23. -->
|
|
@@ -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); the deploy runner service (bin consilium-devops-runner).",
|
|
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",
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
".": "./src/index.js",
|
|
14
14
|
"./standalone": "./src/standalone.js",
|
|
15
15
|
"./runner": "./src/runner/index.js",
|
|
16
|
-
"./package.json": "./package.json"
|
|
16
|
+
"./package.json": "./package.json",
|
|
17
|
+
"./orchestrator": "./src/orchestrator/index.js"
|
|
17
18
|
},
|
|
18
19
|
"bin": {
|
|
19
20
|
"mcp-module-devops": "bin/consilium-devops-mcp.js",
|
|
@@ -40,6 +41,7 @@
|
|
|
40
41
|
}
|
|
41
42
|
},
|
|
42
43
|
"dependencies": {
|
|
44
|
+
"@consilium108/mcp-agent-jobs": "^0.1.0",
|
|
43
45
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
44
46
|
"@nativemind108/mcp": "^1.13.0",
|
|
45
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
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §4): the orchestrator's config.
|
|
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.
|
|
9
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { DevopsMcpError } from '../errors.js';
|
|
13
|
+
import { DEFAULT_SERVER } from '../runner/config.js';
|
|
14
|
+
|
|
15
|
+
export const ORCHESTRATOR_NAME = 'consilium-devops-orchestrator';
|
|
16
|
+
/** The provider name of the orchestrator's own reports (agent events); its own events are never consumed again. */
|
|
17
|
+
export const ORCHESTRATOR_PROVIDER = 'devops-orchestrator';
|
|
18
|
+
/** Idempotency-key prefix of its own reports; the server stores it as content_hash «tm:orc:…». */
|
|
19
|
+
export const OWN_KEY_PREFIX = 'orc:';
|
|
20
|
+
export const JOB_KINDS = ['deploy_check'];
|
|
21
|
+
|
|
22
|
+
export function orchestratorConfigCandidates(env = process.env, home = homedir()) {
|
|
23
|
+
if (env.CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG) return [env.CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG];
|
|
24
|
+
const xdg = env.XDG_CONFIG_HOME || join(home, '.config');
|
|
25
|
+
return [join(xdg, ORCHESTRATOR_NAME, 'config.json'), `/etc/${ORCHESTRATOR_NAME}/config.json`];
|
|
26
|
+
}
|
|
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
|
+
|
|
31
|
+
const bad = (msg) => new DevopsMcpError('config_invalid', msg);
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Normalizes and validates a raw config object (already parsed). Throws config_invalid with the reason.
|
|
35
|
+
* → { file, server, projects, leaseMs, deployPollFallbackMs, maxAttempts, backoffMs, idleTtlMs, report, targets, routes,
|
|
36
|
+
* warnings }
|
|
37
|
+
*/
|
|
38
|
+
export function normalizeOrchestratorConfig(raw, { file = null, env = process.env, home = homedir() } = {}) {
|
|
39
|
+
if (!raw || typeof raw !== 'object') throw bad('the config must be a JSON object');
|
|
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`');
|
|
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`);
|
|
42
|
+
const leaseMs = Number(raw.leaseMs) || 30 * 60_000;
|
|
43
|
+
const targets = {};
|
|
44
|
+
for (const [key, t] of Object.entries(raw.targets ?? {})) {
|
|
45
|
+
if (!/^[a-z0-9][a-z0-9._-]{0,59}$/i.test(key)) throw bad(`target key «${key}»: letters, digits, . _ - only`);
|
|
46
|
+
const projectId = Number(t?.project_id);
|
|
47
|
+
if (!Number.isInteger(projectId) || projectId <= 0) throw bad(`target «${key}»: project_id (the Konsilium project of the deploy target) is required`);
|
|
48
|
+
const environment = String(t.environment ?? 'production');
|
|
49
|
+
if (t.approval && t.approval !== 'human') throw bad(`target «${key}»: approval is always «human» (✅ of a person with the deploy right); the orchestrator never approves`);
|
|
50
|
+
targets[key] = { key, projectId, environment, approval: 'human', title: t.title ? String(t.title).slice(0, 100) : null };
|
|
51
|
+
}
|
|
52
|
+
const routes = (raw.routes ?? []).map((r, i) => {
|
|
53
|
+
const event = String(r?.event ?? '');
|
|
54
|
+
if (!/^agent\.[a-z_]+$/.test(event)) throw bad(`routes[${i}].event: an agent event type such as agent.deploy_required`);
|
|
55
|
+
const projectId = Number(r.project_id);
|
|
56
|
+
if (!Number.isInteger(projectId) || projectId <= 0) throw bad(`routes[${i}].project_id is required (the project whose events start the job)`);
|
|
57
|
+
if (!targets[r.target]) throw bad(`routes[${i}].target «${r.target}» is not in targets`);
|
|
58
|
+
const kind = r.kind ?? 'deploy_check';
|
|
59
|
+
if (!JOB_KINDS.includes(kind)) throw bad(`routes[${i}].kind «${kind}»: one of ${JOB_KINDS.join(', ')}`);
|
|
60
|
+
return { event, projectId, target: r.target, kind, priority: Number(r.priority) || 0 };
|
|
61
|
+
});
|
|
62
|
+
const projects = [...new Set([...(raw.projects ?? []).map(Number), ...routes.map((r) => r.projectId)])].filter((n) => Number.isInteger(n) && n > 0);
|
|
63
|
+
if (!projects.length) throw bad('projects: at least one project id to listen to (or a route)');
|
|
64
|
+
return {
|
|
65
|
+
file,
|
|
66
|
+
server: String(env.KONSILIUM_API_URL ?? raw.server ?? DEFAULT_SERVER).replace(/\/+$/, ''),
|
|
67
|
+
projects,
|
|
68
|
+
leaseMs,
|
|
69
|
+
deployPollFallbackMs: Number(raw.deployPollFallbackMs) || 5 * 60_000,
|
|
70
|
+
maxAttempts: Number(raw.maxAttempts) || 3,
|
|
71
|
+
backoffMs: Number(raw.backoffMs) || 60_000,
|
|
72
|
+
idleTtlMs: Number(raw.idleTtlMs) || 6 * 3600_000,
|
|
73
|
+
report: raw.report === 'off' ? 'off' : 'agent-events',
|
|
74
|
+
targets,
|
|
75
|
+
routes,
|
|
76
|
+
warnings,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function loadOrchestratorConfig({ file = null, env = process.env, home = homedir() } = {}) {
|
|
81
|
+
const f = file ?? orchestratorConfigCandidates(env, home).find((p) => existsSync(p)) ?? null;
|
|
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»`);
|
|
83
|
+
let raw;
|
|
84
|
+
try {
|
|
85
|
+
raw = JSON.parse(readFileSync(f, 'utf8'));
|
|
86
|
+
} catch (e) {
|
|
87
|
+
throw bad(`${f}: not valid JSON (${e.message})`);
|
|
88
|
+
}
|
|
89
|
+
return normalizeOrchestratorConfig(raw, { file: f, env, home });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** An example config (README «Orchestrator inside the MCP»). No secret inside. */
|
|
93
|
+
export function exampleOrchestratorConfig({ projectId = 1, target = 'konsilium-prod' } = {}) {
|
|
94
|
+
return {
|
|
95
|
+
server: DEFAULT_SERVER,
|
|
96
|
+
projects: [projectId],
|
|
97
|
+
report: 'agent-events',
|
|
98
|
+
leaseMs: 1800000,
|
|
99
|
+
maxAttempts: 3,
|
|
100
|
+
backoffMs: 60000,
|
|
101
|
+
targets: { [target]: { project_id: projectId, environment: 'production', approval: 'human', title: 'Консилиум (прод)' } },
|
|
102
|
+
routes: [{ event: 'agent.deploy_required', project_id: projectId, target, kind: 'deploy_check' }],
|
|
103
|
+
};
|
|
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
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
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 (v2: inside the DevOps MCP — producer.js; unchanged rules) — ONLY what the server really sends today (project_events of #437 / #470), nothing assumed.
|
|
3
|
+
// get_events (REST) { event_id, type, project_id, ref:{type,id}, agent, actor_user_id, summary, at, entity_type?,
|
|
4
|
+
// entity_ref?, path?, version?, content_hash?, deleted?, via? }
|
|
5
|
+
// projectEvents (SSE) { cursor, type, projectId, entity, ref, path, version, contentHash, deleted, at }
|
|
6
|
+
// The agent events of the turn monitor (#470): type agent.<TYPE lower case>, agent = the provider, summary = «[TYPE ·
|
|
7
|
+
// basis …] fragment», entity_ref = the task / SDD ref, path = the agent session, content_hash = «tm:<idempotency key>».
|
|
8
|
+
// G2 (2026-11-24): an agent event MAY carry meta { target, environment, branch, commit_sha } (server migration 151); when
|
|
9
|
+
// present, the route of that target is used (only among the configured routes of the event's project — the event never
|
|
10
|
+
// adds a target) and branch / commit go into the job; when absent, target and environment come from the route config.
|
|
11
|
+
// G1 (2026-11-24): deploy.* events of the journal (requested / approved / rejected / running / done / failed /
|
|
12
|
+
// rolled_back / expired; ref = the deploy id, meta { deploy_id, target, kind, status, exit_code, health }) drive the jobs
|
|
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';
|
|
15
|
+
import { OWN_KEY_PREFIX, ORCHESTRATOR_PROVIDER } from './config.js';
|
|
16
|
+
|
|
17
|
+
/** Agent event types that say something about an agent session's state (registry hints). */
|
|
18
|
+
export const STATE_HINTS = {
|
|
19
|
+
'agent.needs_approval': 'waiting_for_user',
|
|
20
|
+
'agent.user_input_required': 'waiting_for_user',
|
|
21
|
+
'agent.interactive_question': 'waiting_for_user',
|
|
22
|
+
'agent.open_question': 'waiting_for_user',
|
|
23
|
+
'agent.needs_decision': 'waiting_for_user',
|
|
24
|
+
'agent.blocked': 'blocked',
|
|
25
|
+
'agent.error': 'blocked',
|
|
26
|
+
'agent.turn_completed': 'idle',
|
|
27
|
+
'agent.task_completed': 'idle',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** One event of either shape (normalizeBusEvent of @consilium108/mcp-agent-jobs) + `own`: the orchestrator's own report. */
|
|
31
|
+
export function normalizeBusEvent(e) {
|
|
32
|
+
const ev = normalizeGeneric(e);
|
|
33
|
+
if (!ev) return null;
|
|
34
|
+
// loop guard: the orchestrator's own reports come back through the same journal
|
|
35
|
+
ev.own = ev.agent === ORCHESTRATOR_PROVIDER || String(ev.contentHash ?? '').startsWith(`tm:${OWN_KEY_PREFIX}`);
|
|
36
|
+
return ev;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The TYPE · basis · confidence head of an agent-event summary (for diagnostics only; never trusted as a command). */
|
|
40
|
+
export function summaryHead(summary) {
|
|
41
|
+
const m = /^\[([A-Z_]+) · ([a-z+]+)(?: ([0-9.]+))?( · ждёт человека)?\]/.exec(String(summary ?? ''));
|
|
42
|
+
return m ? { type: m[1], basis: m[2], confidence: m[3] ? Number(m[3]) : 1, blocking: !!m[4] } : null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* What an event means for the orchestrator:
|
|
47
|
+
* { action: 'enqueue', kind, projectId, target, environment, priority, source } a route matched (DEPLOY_REQUIRED ≠ deploy:
|
|
48
|
+
* the job is a CHECK by an agent that may
|
|
49
|
+
* REQUEST a deploy; a person approves it)
|
|
50
|
+
* { action: 'hint', session, state, source } a session state from the bus
|
|
51
|
+
* { action: 'ignore', reason }
|
|
52
|
+
*/
|
|
53
|
+
/** deploy.<event> → the request status it means (rolled_back: the new rollback request is approved). */
|
|
54
|
+
export const DEPLOY_EVENT_STATUS = { 'deploy.requested': 'pending', 'deploy.approved': 'approved', 'deploy.rejected': 'rejected', 'deploy.running': 'running', 'deploy.done': 'done', 'deploy.failed': 'failed', 'deploy.rolled_back': 'approved', 'deploy.expired': 'expired' };
|
|
55
|
+
const str = (v, n) => (typeof v === 'string' && v ? v.slice(0, n) : null);
|
|
56
|
+
|
|
57
|
+
export function intentOf(ev, config) {
|
|
58
|
+
if (!ev) return { action: 'ignore', reason: 'malformed' };
|
|
59
|
+
if (ev.own) return { action: 'ignore', reason: 'own_report' };
|
|
60
|
+
if (String(ev.type).startsWith('deploy.')) {
|
|
61
|
+
const deployId = Number(ev.meta?.deploy_id ?? (ev.refType === 'deploy' ? ev.refId : NaN));
|
|
62
|
+
const status = DEPLOY_EVENT_STATUS[ev.type] ?? null;
|
|
63
|
+
if (!Number.isInteger(deployId) || !status) return { action: 'ignore', reason: 'deploy_event_without_id' };
|
|
64
|
+
return { action: 'deploy', deployId, status: ev.meta?.status ?? status, event: ev.type, projectId: Number(ev.projectId), target: str(ev.meta?.target, 60), kind: str(ev.meta?.kind, 20), exitCode: Number.isInteger(ev.meta?.exit_code) ? ev.meta.exit_code : null, health: str(ev.meta?.health, 200), after: Number.isInteger(ev.meta?.after) ? ev.meta.after : null, at: ev.at };
|
|
65
|
+
}
|
|
66
|
+
if (!String(ev.type).startsWith('agent.')) return { action: 'ignore', reason: 'not_an_agent_event' };
|
|
67
|
+
const m = ev.meta ?? {};
|
|
68
|
+
const said = { target: str(m.target, 60), environment: str(m.environment, 40), branch: str(m.branch, 200), commit_sha: str(m.commit_sha, 64) };
|
|
69
|
+
const source = { event_id: ev.cursor, project_id: ev.projectId, type: ev.type, session: ev.session, task_ref: ev.entityRef, provider: ev.agent, summary: ev.summary ? String(ev.summary).slice(0, 300) : null, at: ev.at, ...(said.branch ? { branch: said.branch } : {}), ...(said.commit_sha ? { commit_sha: said.commit_sha } : {}), ...(said.target ? { said_target: said.target } : {}), ...(said.environment ? { said_environment: said.environment } : {}) };
|
|
70
|
+
let routes = config.routes.filter((r) => r.event === ev.type && r.projectId === Number(ev.projectId));
|
|
71
|
+
if (routes.length && (said.target || said.environment)) {
|
|
72
|
+
// G2: the agent named the target / environment — only a configured route of this project may match it
|
|
73
|
+
const fit = routes.filter((r) => (!said.target || r.target === said.target) && (!said.environment || config.targets[r.target].environment === said.environment));
|
|
74
|
+
if (!fit.length) return { action: 'ignore', reason: said.target ? 'target_not_routed' : 'environment_not_routed' };
|
|
75
|
+
routes = fit;
|
|
76
|
+
}
|
|
77
|
+
const route = routes.sort((a, b) => b.priority - a.priority)[0];
|
|
78
|
+
if (route) {
|
|
79
|
+
const t = config.targets[route.target];
|
|
80
|
+
return { action: 'enqueue', kind: route.kind, projectId: t.projectId, eventProjectId: Number(ev.projectId), target: t.key, environment: t.environment, approval: t.approval, priority: route.priority, source };
|
|
81
|
+
}
|
|
82
|
+
if (STATE_HINTS[ev.type] && ev.session) return { action: 'hint', session: ev.session, state: STATE_HINTS[ev.type], at: ev.at, source };
|
|
83
|
+
return { action: 'ignore', reason: ev.type === 'agent.deploy_required' ? 'no_route_for_project' : 'no_route' };
|
|
84
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
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';
|
|
7
|
+
export { normalizeBusEvent, intentOf, summaryHead, STATE_HINTS, DEPLOY_EVENT_STATUS } from './events.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';
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2 (SDD-P37-160, IT-160-2 … IT-160-6): the DevOps
|
|
2
|
+
// Orchestrator INSIDE the DevOps MCP process — the producer of DevOps jobs for the shared job inbox of
|
|
3
|
+
// @consilium108/mcp-agent-jobs (envelope konsilium.agent-job/1). It replaces the separate service of 1.2.0 / 1.3.0
|
|
4
|
+
// (daemon loop, agent slots, dry-run / live / hand-off dispatch, systemd unit, CLI): what stayed is the logic —
|
|
5
|
+
// events (events.js intents, unchanged) agent.deploy_required of a routed project → a job devops.deploy_check for the
|
|
6
|
+
// target (DEPLOY_REQUIRED is a signal, not a deploy); state hints → the registry
|
|
7
|
+
// queue rules (now the inbox) one active job per project + environment + target (lock_key), signals of a
|
|
8
|
+
// target coalesce into its queued job, lease / retry / backoff / max attempts
|
|
9
|
+
// deploy lifecycle (G1) deploy.* of the journal move the job that follows a request; GET /deploys/:id
|
|
10
|
+
// as the fallback (only the leader, only when the journal is silent)
|
|
11
|
+
// correlation (IT-14) a deploy.requested of the job's target after the claim gives the deploy id
|
|
12
|
+
// when the subagent's result has none
|
|
13
|
+
// reports (#470 route) waiting_for_user → NEEDS_APPROVAL (blocking), blocked → BLOCKED, failed →
|
|
14
|
+
// ERROR, succeeded / cancelled → TASK_COMPLETED; idempotent keys «orc:…» (the
|
|
15
|
+
// loop guard ignores them when they come back)
|
|
16
|
+
// Who runs a job: the main agent of the running session claims it (jobs_claim) and starts its own built-in subagent
|
|
17
|
+
// (Agent tool); the subagent may call request_deploy — a person approves it (✅); the existing runner of #482 executes
|
|
18
|
+
// only the approved deploy. Nothing here can approve, start an agent or a process.
|
|
19
|
+
import { intentOf, DEPLOY_EVENT_STATUS } from './events.js';
|
|
20
|
+
import { ORCHESTRATOR_PROVIDER, OWN_KEY_PREFIX } from './config.js';
|
|
21
|
+
import { DEPLOY_CHECK_TOOLS, jobContext, promptOf } from './brief.js';
|
|
22
|
+
|
|
23
|
+
export const DEVOPS_MCP = 'consilium-devops';
|
|
24
|
+
export const DEVOPS_KINDS = ['devops.deploy_check'];
|
|
25
|
+
export const DEVOPS_EVENT_TYPES = ['agent.', 'deploy.'];
|
|
26
|
+
/** deploy request status → job status (the job holds the target's lock until the deploy is final). */
|
|
27
|
+
const DEPLOY_STATUS = { pending: 'waiting_for_user', approved: 'running', running: 'running', done: 'succeeded', failed: 'failed', rejected: 'cancelled', expired: 'cancelled' };
|
|
28
|
+
const FOLLOWING = new Set(['waiting_for_user', 'running', 'claimed']);
|
|
29
|
+
const REPORT_TYPE = { waiting_for_user: 'NEEDS_APPROVAL', blocked: 'BLOCKED', failed: 'ERROR', succeeded: 'TASK_COMPLETED', cancelled: 'TASK_COMPLETED' };
|
|
30
|
+
const serverTime = (s) => (s ? Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : `${String(s).replace(' ', 'T')}Z`) : NaN);
|
|
31
|
+
const clip = (s, n) => (s == null ? null : String(s).length > n ? `${String(s).slice(0, n - 1)}…` : String(s));
|
|
32
|
+
/** The loop guard: the orchestrator's own reports come back through the same journal. */
|
|
33
|
+
export const isOwnEvent = (ev) => ev.agent === ORCHESTRATOR_PROVIDER || String(ev.contentHash ?? '').startsWith(`tm:${OWN_KEY_PREFIX}`);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {{ config: object, api: object|null, log?: object, now?: () => number, registry?: object|null, redact?: (s: string) => string }} o
|
|
37
|
+
* config — normalizeOrchestratorConfig (targets, routes, projects, report, deployPollFallbackMs, idleTtlMs)
|
|
38
|
+
*/
|
|
39
|
+
export function createDevopsProducer({ config, api, log = { info() {}, warn() {}, error() {} }, now = Date.now, registry = null, redact = (s) => s }) {
|
|
40
|
+
const metrics = { events: 0, ignored: 0, own_ignored: 0, baseline_skipped: 0, hints: 0, enqueued: 0, coalesced: 0, duplicates: 0, deploy_events: 0, deploy_polls: 0, deploy_poll_errors: 0, reports_sent: 0, reports_suppressed: 0 };
|
|
41
|
+
const deployEventProjects = new Set(); // projects whose journal is seen sending deploy.* (G1) — polling becomes a fallback
|
|
42
|
+
const DEPLOY_NOTE = (id, s, d = {}) =>
|
|
43
|
+
({
|
|
44
|
+
pending: `deploy request #${id} waits for a person's ✅`,
|
|
45
|
+
approved: `deploy #${id} approved by a person; waiting for the runner`,
|
|
46
|
+
running: `deploy #${id} is running on the runner`,
|
|
47
|
+
done: `deploy #${id} done (health ${d.health ?? '—'})`,
|
|
48
|
+
failed: `deploy #${id} failed on the runner (exit ${d.exitCode ?? '?'}, health ${d.health ?? '—'}); see deploy_status`,
|
|
49
|
+
rejected: `deploy request #${id} rejected by a person`,
|
|
50
|
+
expired: `deploy request #${id} expired without an approval`,
|
|
51
|
+
})[s] ?? `deploy #${id}: ${s}`;
|
|
52
|
+
|
|
53
|
+
function jobInput(intent) {
|
|
54
|
+
const src = intent.source;
|
|
55
|
+
const sources = [src];
|
|
56
|
+
const ctxJob = { id: '(this job)', kind: 'deploy_check', projectId: intent.projectId, target: intent.target, environment: intent.environment, sources, attempts: 1 };
|
|
57
|
+
return {
|
|
58
|
+
module: 'devops',
|
|
59
|
+
kind: 'devops.deploy_check',
|
|
60
|
+
mcp: DEVOPS_MCP,
|
|
61
|
+
project_id: intent.projectId,
|
|
62
|
+
title: `Deploy check: ${intent.target} (${intent.environment})`,
|
|
63
|
+
brief: promptOf(ctxJob),
|
|
64
|
+
context: jobContext(ctxJob),
|
|
65
|
+
correlation: { idempotency_key: `deploy_check:${src.project_id}:${src.event_id}`, events: [{ project_id: src.project_id, event_id: src.event_id, type: src.type }], task_ref: src.task_ref ?? null },
|
|
66
|
+
priority: intent.priority,
|
|
67
|
+
lock_key: `${intent.projectId}:${intent.environment}:${intent.target}`,
|
|
68
|
+
delegation: { mode: 'subagent', isolation: 'none', reason: 'an independent check; one deploy-related job per target at a time (lock_key)' },
|
|
69
|
+
approval: { required: true, by: 'a person with the deploy right (✅ in the Konsilium bot)' },
|
|
70
|
+
tools: DEPLOY_CHECK_TOOLS,
|
|
71
|
+
meta: { target: intent.target, environment: intent.environment, event_project_id: intent.eventProjectId },
|
|
72
|
+
note: `signal ${src.type} #${src.event_id}`,
|
|
73
|
+
// a later signal for the same queued job: its context lists every signal
|
|
74
|
+
mergeContext: (ctx, add) => ({ ...ctx, signals: [...(ctx?.signals ?? []), ...(add?.signals ?? [])].slice(-20) }),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Move the job that follows a deploy to the status the deploy now has (event or poll). */
|
|
79
|
+
function followDeploy(inbox, j, s, d = {}) {
|
|
80
|
+
const want = DEPLOY_STATUS[s];
|
|
81
|
+
const meta = { ...j.meta, deployFactAt: now() };
|
|
82
|
+
if (!want || (want === j.status && s === j.meta?.deployStatus)) return inbox.update(j.id, { meta });
|
|
83
|
+
return inbox.update(j.id, { status: want, lease: null, meta: { ...meta, deployStatus: s } }, DEPLOY_NOTE(j.correlation.deploy_id, s, d));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function applyDeployEvent(inbox, it) {
|
|
87
|
+
deployEventProjects.add(it.projectId);
|
|
88
|
+
const jobs = inbox.list({ module: 'devops' });
|
|
89
|
+
const j = jobs.find((x) => x.correlation.deploy_id === it.deployId && x.projectId === it.projectId && FOLLOWING.has(x.status));
|
|
90
|
+
if (j) return followDeploy(inbox, j, it.status, { health: it.health, exitCode: it.exitCode });
|
|
91
|
+
// IT-14: a request of the job's target made after the claim, before the subagent's result names it
|
|
92
|
+
if (it.event === 'deploy.requested' && it.target) {
|
|
93
|
+
const at = serverTime(it.at);
|
|
94
|
+
const c = jobs.find((x) => !x.correlation.deploy_id && x.lease && ['claimed', 'running'].includes(x.status) && x.projectId === it.projectId && x.meta?.target === it.target && (!Number.isFinite(at) || at >= Date.parse(x.claimedAt ?? 0) - 60_000));
|
|
95
|
+
if (c) inbox.update(c.id, { meta: { ...c.meta, candidateDeployId: it.deployId } }, `deploy request #${it.deployId} of ${it.target} seen in the journal`);
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
module: 'devops',
|
|
102
|
+
mcp: DEVOPS_MCP,
|
|
103
|
+
kinds: DEVOPS_KINDS,
|
|
104
|
+
types: DEVOPS_EVENT_TYPES,
|
|
105
|
+
projects: () => config.projects,
|
|
106
|
+
metrics: () => ({ ...metrics }),
|
|
107
|
+
|
|
108
|
+
async handle(ev, { baseline = false, inbox }) {
|
|
109
|
+
metrics.events++;
|
|
110
|
+
const intent = intentOf({ ...ev, own: isOwnEvent(ev) }, config);
|
|
111
|
+
if (intent.action === 'deploy') {
|
|
112
|
+
metrics.deploy_events++;
|
|
113
|
+
applyDeployEvent(inbox, intent);
|
|
114
|
+
} else if (intent.action === 'hint') {
|
|
115
|
+
const at = serverTime(ev.at);
|
|
116
|
+
registry?.hint(intent.session, intent.state, Number.isFinite(at) ? new Date(at).toISOString() : null, `bus: ${ev.type}`);
|
|
117
|
+
metrics.hints++;
|
|
118
|
+
} else if (intent.action === 'enqueue') {
|
|
119
|
+
if (baseline) metrics.baseline_skipped++;
|
|
120
|
+
else {
|
|
121
|
+
const r = inbox.enqueue(jobInput(intent), { coalesce: true });
|
|
122
|
+
if (r.duplicate) metrics.duplicates++;
|
|
123
|
+
else if (r.coalesced) metrics.coalesced++;
|
|
124
|
+
else {
|
|
125
|
+
metrics.enqueued++;
|
|
126
|
+
log.info?.('devops job queued', { job: r.job.id, target: intent.target, environment: intent.environment, event_id: intent.source.event_id });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} else if (intent.reason === 'own_report') metrics.own_ignored++;
|
|
130
|
+
else metrics.ignored++;
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
/** The subagent's result → the job status: a requested deploy is followed until it is final (holds the target). */
|
|
134
|
+
decide(job, result) {
|
|
135
|
+
if (result.outcome !== 'requested') return null; // the inbox default
|
|
136
|
+
const id = result.deploy_id ?? (Number.isInteger(job.meta?.candidateDeployId) ? job.meta.candidateDeployId : null);
|
|
137
|
+
if (!id) return { status: 'blocked', note: 'the subagent said «requested» but gave no deploy id (and none of this target was seen in the journal)' };
|
|
138
|
+
return { status: 'waiting_for_user', patch: { correlation: { ...job.correlation, deploy_id: id }, meta: { ...job.meta, deployStatus: 'pending', deployFactAt: now() } }, note: `deploy request #${id} waits for a person's ✅${result.deploy_id ? '' : ' (id from the journal)'}` };
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
/** G1 fallback: GET /deploys/:id of followed deploys — only the listener's process, only when the journal is silent. */
|
|
142
|
+
async tick({ leader, inbox }) {
|
|
143
|
+
if (!leader || !api?.deploy) return;
|
|
144
|
+
for (const j of inbox.list({ module: 'devops' })) {
|
|
145
|
+
const id = j.correlation.deploy_id;
|
|
146
|
+
if (!id || !FOLLOWING.has(j.status)) continue;
|
|
147
|
+
if (deployEventProjects.has(j.projectId) && now() - (j.meta?.deployFactAt ?? 0) < config.deployPollFallbackMs) continue;
|
|
148
|
+
let d;
|
|
149
|
+
try {
|
|
150
|
+
metrics.deploy_polls++;
|
|
151
|
+
d = await api.deploy(j.projectId, id);
|
|
152
|
+
} catch (e) {
|
|
153
|
+
metrics.deploy_poll_errors++;
|
|
154
|
+
log.warn?.('deploy status unavailable', { job: j.id, deploy_id: id, code: e.code ?? 'error' });
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
followDeploy(inbox, j, d?.status, { health: d?.health, exitCode: d?.exitCode });
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
/** Server effects: status reports through the #470 agent-event route (idempotent; nobody is notified by it). */
|
|
162
|
+
async effect(job, name, ef = {}) {
|
|
163
|
+
const status = name === 'result' ? (ef.status ?? job.status) : name;
|
|
164
|
+
const type = REPORT_TYPE[status];
|
|
165
|
+
if (!type || !api?.report) return;
|
|
166
|
+
if (config.report === 'off') {
|
|
167
|
+
metrics.reports_suppressed++;
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const deployId = job.correlation.deploy_id ?? 0;
|
|
171
|
+
const text = job.result?.summary ?? job.history?.at(-1)?.note ?? null;
|
|
172
|
+
await api.report(job.meta?.event_project_id ?? job.projectId, {
|
|
173
|
+
idempotency_key: `${OWN_KEY_PREFIX}${job.id}:${status}:${ef.attempt ?? job.attempts}:${deployId}`,
|
|
174
|
+
type,
|
|
175
|
+
basis: 'lifecycle',
|
|
176
|
+
confidence: 1,
|
|
177
|
+
provider: ORCHESTRATOR_PROVIDER,
|
|
178
|
+
via: DEVOPS_MCP,
|
|
179
|
+
session_id: `orc-${job.id}`,
|
|
180
|
+
blocking: status === 'waiting_for_user',
|
|
181
|
+
reason: clip(`DevOps job ${job.id} (${job.kind} ${job.meta?.target}/${job.meta?.environment}) → ${status}`, 500),
|
|
182
|
+
...(text ? { text: clip(redact(text), 500) } : {}),
|
|
183
|
+
...(job.correlation.task_ref ? { task_ref: clip(job.correlation.task_ref, 120) } : {}),
|
|
184
|
+
at: new Date(now()).toISOString(),
|
|
185
|
+
});
|
|
186
|
+
metrics.reports_sent++;
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
status: () => ({ targets: Object.keys(config.targets), routes: config.routes.length, deploy_event_projects: [...deployEventProjects], report: config.report, warnings: config.warnings ?? [], metrics: { ...metrics } }),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export { DEPLOY_EVENT_STATUS };
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §5): the agent registry.
|
|
2
|
+
// Agents are the slots of the config (id, provider, mode, workspace, projects, capabilities) — a running process alone is
|
|
3
|
+
// never a free agent. The state of a slot comes from facts:
|
|
4
|
+
// 1. the orchestrator's own lease (it gave the slot a job) → running
|
|
5
|
+
// 2. the provider adapter says the slot cannot run here (workspace missing, provider absent) → unavailable
|
|
6
|
+
// 3. the turn monitor of #470 in the slot's workspace (read-only, its on-disk contract
|
|
7
|
+
// konsilium.agent-event/1: ~/.local/state/konsilium-mcp/<sha1(workspace)>/turnmonitor/{journal.jsonl,open.json})
|
|
8
|
+
// and the agent.* hints of the bus for the same session, whichever is newer:
|
|
9
|
+
// an open request to the person (open.json) / NEEDS_* / *_QUESTION / USER_INPUT_REQUIRED → waiting_for_user
|
|
10
|
+
// ERROR / BLOCKED → blocked
|
|
11
|
+
// RESOLVED (the person answered; the agent goes on) → running
|
|
12
|
+
// TURN_COMPLETED / TASK_COMPLETED / DEPLOY_REQUIRED (not blocking) within idleTtlMs → idle
|
|
13
|
+
// nothing seen, or the last fact is older than idleTtlMs → unavailable
|
|
14
|
+
// (v2: one slot = the workspace of the running session — createSessionRegistry; «headless» slots are gone.)
|
|
15
|
+
// G4 (2026-11-24): with @consilium108/mcp ≥ 0.11.1 the facts come from its read-only export `@consilium108/mcp/turnmonitor`
|
|
16
|
+
// (turnMonitorState — the monitor's own reading, incl. TURN_STARTED of G3); without it (older host package, not
|
|
17
|
+
// installed) the files are read directly as before.
|
|
18
|
+
import { createHash } from 'node:crypto';
|
|
19
|
+
import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from 'node:fs';
|
|
20
|
+
import { homedir } from 'node:os';
|
|
21
|
+
import { join, resolve } from 'node:path';
|
|
22
|
+
|
|
23
|
+
export const AGENT_STATES = ['idle', 'running', 'waiting_for_user', 'blocked', 'unavailable'];
|
|
24
|
+
const TAIL_BYTES = 256 * 1024;
|
|
25
|
+
const WAITING = new Set(['NEEDS_APPROVAL', 'NEEDS_DECISION', 'OPEN_QUESTION', 'INTERACTIVE_QUESTION', 'USER_INPUT_REQUIRED']);
|
|
26
|
+
const IDLE = new Set(['TURN_COMPLETED', 'TASK_COMPLETED']);
|
|
27
|
+
|
|
28
|
+
/** = stateDirOf of @consilium108/mcp (src/sync/state.js) + /turnmonitor: where #470 keeps the state of a workspace. */
|
|
29
|
+
export function turnMonitorDirOf(workspace, { env = process.env, home = homedir() } = {}) {
|
|
30
|
+
const base = env.XDG_STATE_HOME || join(home, '.local', 'state');
|
|
31
|
+
return join(base, 'konsilium-mcp', createHash('sha1').update(resolve(workspace)).digest('hex'), 'turnmonitor');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const readJson = (f, d) => {
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(readFileSync(f, 'utf8'));
|
|
37
|
+
} catch {
|
|
38
|
+
return d;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** The tail of journal.jsonl → parsed events (newest last). Never reads more than TAIL_BYTES. */
|
|
43
|
+
export function readTurnJournal(dir) {
|
|
44
|
+
const f = join(dir, 'journal.jsonl');
|
|
45
|
+
if (!existsSync(f)) return [];
|
|
46
|
+
let fd;
|
|
47
|
+
try {
|
|
48
|
+
fd = openSync(f, 'r');
|
|
49
|
+
const size = fstatSync(fd).size;
|
|
50
|
+
const len = Math.min(size, TAIL_BYTES);
|
|
51
|
+
const buf = Buffer.alloc(len);
|
|
52
|
+
readSync(fd, buf, 0, len, size - len);
|
|
53
|
+
const lines = buf.toString('utf8').split('\n');
|
|
54
|
+
if (size > len) lines.shift(); // a cut first line
|
|
55
|
+
const out = [];
|
|
56
|
+
for (const l of lines) {
|
|
57
|
+
if (!l) continue;
|
|
58
|
+
try {
|
|
59
|
+
const e = JSON.parse(l);
|
|
60
|
+
if (e && (e.schema === 'konsilium.agent-event/1' || e.kind === 'resolution')) out.push(e);
|
|
61
|
+
} catch {}
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
} catch {
|
|
65
|
+
return [];
|
|
66
|
+
} finally {
|
|
67
|
+
if (fd !== undefined) closeSync(fd);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The state of one session from the facts of the turn monitor: { state, at, reason } | null (nothing known). */
|
|
72
|
+
export function sessionStateOf(events, open, sessionId) {
|
|
73
|
+
if (Object.values(open ?? {}).some((v) => v?.session_id === sessionId)) {
|
|
74
|
+
const o = Object.values(open).find((v) => v?.session_id === sessionId);
|
|
75
|
+
return { state: 'waiting_for_user', at: o.asked_at ?? null, reason: `turn monitor: open request (${o.type ?? o.kind ?? 'question'})` };
|
|
76
|
+
}
|
|
77
|
+
const mine = events.filter((e) => e.session_id === sessionId);
|
|
78
|
+
const last = mine[mine.length - 1];
|
|
79
|
+
if (!last) return null;
|
|
80
|
+
const at = last.at ?? last.detected_at ?? null;
|
|
81
|
+
if (last.type === 'TURN_STARTED') return { state: 'running', at, reason: `turn monitor: turn started (${last.trigger ?? 'lifecycle'})` };
|
|
82
|
+
if (last.type === 'RESOLVED') return { state: 'running', at, reason: 'turn monitor: the person answered; the agent goes on' };
|
|
83
|
+
if (last.type === 'ERROR' || last.type === 'BLOCKED') return { state: 'blocked', at, reason: `turn monitor: ${last.type}` };
|
|
84
|
+
if (WAITING.has(last.type) || last.blocking) return { state: 'waiting_for_user', at, reason: `turn monitor: ${last.type}${last.blocking ? ' (waits for the person)' : ''}` };
|
|
85
|
+
if (IDLE.has(last.type) || last.type === 'DEPLOY_REQUIRED') return { state: 'idle', at, reason: `turn monitor: ${last.type} — the turn ended` };
|
|
86
|
+
return { state: 'running', at, reason: `turn monitor: ${last.type}` };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @param {{ agents: object[], adapters: Record<string, object>, idleTtlMs: number, now?: () => number,
|
|
91
|
+
* readJournal?: (dir: string) => object[], readOpen?: (dir: string) => object, dirOf?: (ws: string) => string,
|
|
92
|
+
* turnMonitor?: { turnMonitorState: Function } | null }} o turnMonitor — the `@consilium108/mcp/turnmonitor` module (G4)
|
|
93
|
+
*/
|
|
94
|
+
export function createRegistry({ agents, adapters, idleTtlMs, now = Date.now, readJournal = readTurnJournal, readOpen = (d) => readJson(join(d, 'open.json'), {}), dirOf = (ws) => turnMonitorDirOf(ws), turnMonitor = null }) {
|
|
95
|
+
const hints = new Map(); // session → { state, at, reason }
|
|
96
|
+
|
|
97
|
+
function stateOf(agent, leasedBy) {
|
|
98
|
+
if (leasedBy) return { state: 'running', reason: `orchestrator: job ${leasedBy}` };
|
|
99
|
+
const ad = adapters[agent.provider];
|
|
100
|
+
if (!ad) return { state: 'unavailable', reason: `no adapter for provider «${agent.provider}»` };
|
|
101
|
+
const avail = ad.available(agent);
|
|
102
|
+
if (!avail.ok) return { state: 'unavailable', reason: avail.reason };
|
|
103
|
+
if (agent.mode === 'headless') return { state: 'idle', reason: 'headless slot, not leased' };
|
|
104
|
+
let session = agent.sessionId;
|
|
105
|
+
let st = null;
|
|
106
|
+
let viaExport = false;
|
|
107
|
+
if (turnMonitor?.turnMonitorState) {
|
|
108
|
+
try {
|
|
109
|
+
const tm = turnMonitor.turnMonitorState(agent.workspace, { provider: agent.provider, sessionId: agent.sessionId ?? null });
|
|
110
|
+
session = session ?? tm.latest ?? null;
|
|
111
|
+
const one = tm.sessions.find((x) => x.session_id === session);
|
|
112
|
+
st = one?.state ? { state: one.state, at: one.at, reason: one.reason } : null;
|
|
113
|
+
viaExport = true;
|
|
114
|
+
} catch {
|
|
115
|
+
viaExport = false; // fall back to the files
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (!viaExport) {
|
|
119
|
+
const dir = dirOf(agent.workspace);
|
|
120
|
+
const events = readJournal(dir);
|
|
121
|
+
const open = readOpen(dir);
|
|
122
|
+
if (!session) {
|
|
123
|
+
const withSession = events.filter((e) => e.session_id && (!e.provider || e.provider === agent.provider));
|
|
124
|
+
session = withSession[withSession.length - 1]?.session_id ?? null;
|
|
125
|
+
}
|
|
126
|
+
if (session) st = sessionStateOf(events, open, session);
|
|
127
|
+
}
|
|
128
|
+
if (!session) return { state: 'unavailable', reason: 'turn monitor: no session seen in this workspace (is #470 on? KONSILIUM_TURN_MONITOR=on)' };
|
|
129
|
+
const h = hints.get(session);
|
|
130
|
+
if (h && (!st || Date.parse(h.at ?? 0) > Date.parse(st.at ?? 0))) st = h;
|
|
131
|
+
if (!st) return { state: 'unavailable', session, reason: 'turn monitor: nothing known about the session' };
|
|
132
|
+
if (st.state === 'idle' && st.at && now() - Date.parse(st.at) > idleTtlMs) return { state: 'unavailable', session, at: st.at, reason: `last turn ended more than ${Math.round(idleTtlMs / 60_000)} min ago — not counted as free` };
|
|
133
|
+
return { ...st, session };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
hint(session, state, at, reason) {
|
|
138
|
+
hints.set(session, { state, at: at ?? new Date(now()).toISOString(), reason: reason ?? `bus: ${state}` });
|
|
139
|
+
},
|
|
140
|
+
/** leases: Map agentId → jobId. → [{ ...agent, state, reason, session }] */
|
|
141
|
+
snapshot(leases = new Map()) {
|
|
142
|
+
return agents.map((a) => ({ id: a.id, provider: a.provider, mode: a.mode, dispatch: a.dispatch ?? 'dry_run', workspace: a.workspace, projects: a.projects, capabilities: a.capabilities, ...stateOf(a, leases.get(a.id) ?? null) }));
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* v2 (inside the MCP, 2026-11-24): the state of THIS session's workspace — shown by jobs_inbox / jobs_status so the main
|
|
149
|
+
* agent sees whether it is waiting for a person or blocked. It never gates a claim: subagents of the session run in
|
|
150
|
+
* parallel with the main agent; the registry keeps its facts (#470) and the bus hints of the listener.
|
|
151
|
+
*/
|
|
152
|
+
export function createSessionRegistry({ workspace, provider = 'claude', idleTtlMs = 6 * 3600_000, now = Date.now, turnMonitor = null, readJournal, readOpen, dirOf } = {}) {
|
|
153
|
+
const slot = { id: 'this-session', provider, mode: 'session', workspace, projects: [], capabilities: [] };
|
|
154
|
+
const reg = createRegistry({ agents: [slot], adapters: { [provider]: { available: () => ({ ok: true }) } }, idleTtlMs, now, turnMonitor, ...(readJournal ? { readJournal } : {}), ...(readOpen ? { readOpen } : {}), ...(dirOf ? { dirOf } : {}) });
|
|
155
|
+
return {
|
|
156
|
+
hint: (...a) => reg.hint(...a),
|
|
157
|
+
state() {
|
|
158
|
+
const s = reg.snapshot()[0];
|
|
159
|
+
return { workspace, state: s.state, reason: s.reason, session: s.session ?? null, at: s.at ?? null };
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
package/src/runner/state.js
CHANGED
|
@@ -17,10 +17,10 @@ const alive = (pid) => {
|
|
|
17
17
|
}
|
|
18
18
|
};
|
|
19
19
|
|
|
20
|
-
/** A lock file with our pid (O_EXCL); a stale lock of a dead process is taken over. */
|
|
21
|
-
export function acquireLock(dir) {
|
|
20
|
+
/** A lock file with our pid (O_EXCL); a stale lock of a dead process is taken over. `name`: the orchestrator uses its own. */
|
|
21
|
+
export function acquireLock(dir, name = 'runner.lock') {
|
|
22
22
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
23
|
-
const file = join(dir,
|
|
23
|
+
const file = join(dir, name);
|
|
24
24
|
for (let i = 0; i < 2; i++) {
|
|
25
25
|
try {
|
|
26
26
|
const fd = openSync(file, 'wx', 0o600);
|
|
@@ -30,7 +30,7 @@ export function acquireLock(dir) {
|
|
|
30
30
|
} catch (e) {
|
|
31
31
|
if (e.code !== 'EEXIST') throw e;
|
|
32
32
|
const pid = Number(readFileSync(file, 'utf8').trim());
|
|
33
|
-
if (pid && pid !== process.pid && alive(pid)) throw new DevopsMcpError('already_running', `another runner (pid ${pid}) holds ${file} — one deploy at a time`);
|
|
33
|
+
if (pid && pid !== process.pid && alive(pid)) throw new DevopsMcpError('already_running', `another ${name === 'runner.lock' ? 'runner' : 'process'} (pid ${pid}) holds ${file}${name === 'runner.lock' ? ' — one deploy at a time' : ''}`);
|
|
34
34
|
rmSync(file, { force: true });
|
|
35
35
|
}
|
|
36
36
|
}
|
package/src/standalone.js
CHANGED
|
@@ -12,11 +12,14 @@ import { z } from 'zod';
|
|
|
12
12
|
import mod from './index.js';
|
|
13
13
|
import { OPS_TOOLS, registerOpsTools } from './groups/ops.js';
|
|
14
14
|
import { DevopsMcpError } from './errors.js';
|
|
15
|
+
import { registerJobTools, JOB_TOOLS, JOBS_INSTRUCTIONS } from '@consilium108/mcp-agent-jobs';
|
|
15
16
|
|
|
16
17
|
export const DEFAULT_API_URL = 'https://konsilium.nativemind.net';
|
|
17
18
|
export const SESSION_TOOLS = ['devops_session', 'select_project'];
|
|
18
19
|
/** Every tool of the standalone server, in registration order. */
|
|
19
20
|
export const STANDALONE_TOOLS = [...SESSION_TOOLS, ...Object.values(mod.groups).flatMap((g) => g.tools), ...OPS_TOOLS];
|
|
21
|
+
/** + the job inbox tools when the job runtime runs (the default of the bin; TASK-P37-486 v2). */
|
|
22
|
+
export { JOB_TOOLS };
|
|
20
23
|
|
|
21
24
|
export { DevopsMcpError }; // src/errors.js — shared with the deploy runner
|
|
22
25
|
|
|
@@ -68,8 +71,10 @@ export function fillPath(path, args = {}) {
|
|
|
68
71
|
* @param {number|null} [o.projectId] the project chosen at start (--project / KONSILIUM_PROJECT_ID)
|
|
69
72
|
* @param {string} [o.version] the client version for User-Agent
|
|
70
73
|
* @param {typeof fetch} [o.fetch]
|
|
74
|
+
* @param {object|null} [o.jobs] the job runtime of @consilium108/mcp-agent-jobs (TASK-P37-486 v2: the DevOps
|
|
75
|
+
* Orchestrator inside this MCP) → the six jobs_* tools, the inbox resource and change notifications
|
|
71
76
|
*/
|
|
72
|
-
export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, credentials = null, projectId = null, version = mod.version, fetch: f = globalThis.fetch, timeoutMs = 60_000 } = {}) {
|
|
77
|
+
export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, credentials = null, projectId = null, version = mod.version, fetch: f = globalThis.fetch, timeoutMs = 60_000, jobs = null } = {}) {
|
|
73
78
|
const core = String(apiUrl).replace(/\/+$/, '');
|
|
74
79
|
const direct = devopsUrl ? String(devopsUrl).replace(/\/+$/, '') : null;
|
|
75
80
|
let active = Number(projectId) || null;
|
|
@@ -170,7 +175,7 @@ export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, cr
|
|
|
170
175
|
client: () => 'MCP',
|
|
171
176
|
};
|
|
172
177
|
|
|
173
|
-
const server = new McpServer({ name: 'consilium-devops', version }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
178
|
+
const server = new McpServer({ name: 'consilium-devops', version }, { capabilities: { tools: {}, ...(jobs ? { resources: {}, logging: {} } : {}) }, instructions: jobs ? `${INSTRUCTIONS}\n${JOBS_INSTRUCTIONS}` : INSTRUCTIONS });
|
|
174
179
|
const ro = { readOnlyHint: true, openWorldHint: false };
|
|
175
180
|
|
|
176
181
|
server.registerTool(
|
|
@@ -216,12 +221,13 @@ export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, cr
|
|
|
216
221
|
);
|
|
217
222
|
for (const g of Object.values(mod.groups)) g.register(server, h);
|
|
218
223
|
registerOpsTools(server, h);
|
|
224
|
+
if (jobs) registerJobTools(server, { runtime: jobs, z, mcp: 'consilium-devops' });
|
|
219
225
|
|
|
220
226
|
return { server, helpers: h, activeProject: () => active, loadSession };
|
|
221
227
|
}
|
|
222
228
|
|
|
223
229
|
export const INSTRUCTIONS = `Konsilium DevOps MCP (${mod.name} ${mod.version}): deploy requests by button and their status, deploy targets and the runner's heartbeat, Job Copilot debug reports — for the projects of your Konsilium sign-in.
|
|
224
230
|
Start with devops_session (who, projects, rights, active project); select_project switches the project.
|
|
225
|
-
runner_status shows whether the deploy runner of each target is online and what it runs; runner_setup gives a person the steps to install it (text only — the runner is a separate service, bin consilium-devops-runner).
|
|
231
|
+
runner_status shows whether the deploy runner of each target is online and what it runs; runner_setup gives a person the steps to install it (text only — the runner is a separate service on the deploy host, bin consilium-devops-runner; it executes only approved deploys).
|
|
226
232
|
request_deploy asks the people with the deploy right to approve (✅ in the messenger); you cannot approve, reject or roll back — a person does. Then poll deploy_status(deploy_id): pending → approved → running → done | failed (rejected / expired), exit code, health, log tail.
|
|
227
233
|
Errors come as «code: message» (auth_required, auth_invalid, project_not_chosen, no_deploy_right, module_disabled, module_unavailable, network_unavailable …).`;
|