@consilium108/mcp-module-devops 1.1.0 → 1.3.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 CHANGED
@@ -1,5 +1,47 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.0 — 2026-11-24
4
+
5
+ <!-- generated by Claude (Opus 5.5), 2026-11-24; Konsilium SDD-P37-160 — owner 2026-11-24 «Запускай все, добавь сразу».
6
+ 1.2.0 was never published (npm has 1.0.0, 1.1.0): its changes are folded into this section. -->
7
+
8
+ - **Deploy lifecycle from the journal (G1).** The orchestrator subscribes to `deploy.*` as well as `agent.*` and moves
9
+ the jobs that follow a deploy request by `deploy.requested / approved / rejected / running / done / failed /
10
+ rolled_back / expired` (the core's `project_events`, migration 151 `meta`; the DevOps module reports them through its
11
+ `core_outbox`). `GET /deploys/:id` stays as the fallback: every tick until the project is seen sending `deploy.*`,
12
+ then only after `deployPollFallbackMs` (default 5 min) without a fact. A `deploy.requested` of the job's target after
13
+ the assignment gives the deploy id when the agent's result line has none (IT-14).
14
+ - **Target / environment / branch / commit from the agent event (G2).** When an `agent.*` event carries `meta.target` /
15
+ `environment`, the route is chosen among the configured routes of that project (an unrouted target is ignored:
16
+ `target_not_routed`); `branch` / `commit_sha` go into the job (`konsilium.devops-job/1`) and leave `unknown`.
17
+ - **Turn-monitor state through `@consilium108/mcp/turnmonitor` (G4)** when the host package (≥ 0.11.1) is installed —
18
+ incl. `TURN_STARTED` (G3) = running; otherwise the files are read as before.
19
+ - **Live dispatch per slot (stage 3).** The global dispatch stays `dry_run`. `agents[].dispatch: "live"` (only `mode:
20
+ "headless"` + `provider: "claude"`, only in `run`) starts `claude -p <job> --output-format json --permission-mode
21
+ default --allowedTools <DevOps MCP tools + read-only git>` in the slot's workspace without a shell — one job at a time
22
+ per slot, `timeout_ms` ≤ `leaseMs` (stop + retry), only the default env names + `env_pass`, a masked per-run log in
23
+ `<stateDir>/live/`, the `ORCHESTRATOR_RESULT` → complete → agent-events report (sent although the global dispatch is
24
+ dry-run). `validateLivePlan` refuses any other shape before anything is spawned (bypass flags, another permission mode,
25
+ extra flags, tools outside the list, another binary). `agents[].dispatch: "handoff"` (only `mode: "session"`) creates a
26
+ hand-off (`POST /api/projects/:id/handoffs`, `handoff_agent` or the provider) instead of a second process; the
27
+ hand-off's result completes the job; a hand-off nobody took by the end of the lease is cancelled. A restart during a
28
+ live run retries the job at once. New exports: `createLiveDispatcher`, `validateLivePlan`, `LIVE_ALLOWED_TOOLS`,
29
+ `READ_ONLY_GIT`, `SLOT_DISPATCH`, `LIVE_ENV_DEFAULT`, `DEPLOY_EVENT_STATUS`, `resultTextOf`, `liveEnvOf`,
30
+ `maskSecrets`. `ALLOWED_ROUTES` + the three hand-off routes (create / read / cancel its own) — still no approve route.
31
+
32
+ ### Folded from 1.2.0 (never published)
33
+
34
+ - The local DevOps agent orchestrator — a SEPARATE service in the same package: bin `consilium-devops-orchestrator`
35
+ (`run`, `once`, `status`, `agents`, `check`, `config --print`, `unit --print`) and export `./orchestrator` (Node
36
+ built-ins; SSE through `subscribeSse` of `@nativemind108/mcp`). Event source = the existing delivery of #437
37
+ (`projectEvents` SSE, `get_events` catch-up / long poll, cursor saved after handling, a first start is a baseline);
38
+ agent registry = config slots + #470 turn-monitor facts (idle / running / waiting_for_user / blocked / unavailable);
39
+ durable queue with a lock per project + environment + target, coalescing, lease with renewal, retry with backoff,
40
+ restart recovery; provider adapters (claude, codex, generic) — **dry-run dispatch only**; follows the status of a
41
+ deploy an agent requested; reports through `POST /api/projects/:id/agent-events`. Never approves; plans with a
42
+ permission-bypass flag are refused; no secret in config, prompts, reports or logs.
43
+ - `acquireLock(dir, name = 'runner.lock')` — optional lock-file name (the runner is unchanged).
44
+
3
45
  ## 1.1.0 (unreleased)
4
46
 
5
47
  <!-- generated by Claude (Opus 5.5), 2026-11-22; Konsilium #482 (TASK-P37-482) -->
package/README.md CHANGED
@@ -69,6 +69,69 @@ 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
+ ## Оркестратор агентов (1.2.0 → 1.3.0, #486, SDD-P37-160)
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
+ Переключить один слот на живой запуск (пример):
114
+
115
+ ```json
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
+ ```
120
+
121
+ затем `check` (покажет `claude-headless (live)`) и перезапуск службы; в workspace слота должен быть подключён DevOps
122
+ MCP под именем `consilium-devops` (инструменты `mcp__consilium-devops__*`), а `claude` — доступен по `claude_bin`.
123
+
124
+ ```
125
+ consilium-devops-orchestrator config --print --repo <dir> --project <id> > ~/.config/consilium-devops-orchestrator/config.json
126
+ consilium-devops-orchestrator check # проверить конфиг
127
+ consilium-devops-orchestrator agents # слоты агентов и их состояние сейчас
128
+ consilium-devops-orchestrator once # догнать события, один такт, напечатать статус
129
+ consilium-devops-orchestrator unit --print # юнит systemd (ничего не ставит)
130
+ consilium-devops-orchestrator status # последний status.json службы
131
+ ```
132
+
133
+ Учётные данные: `KONSILIUM_API_KEY` (ksk_… с `tasks:work`) или вход `npx @consilium108/mcp login`; в конфиге секретов нет.
134
+
72
135
  ## Runner
73
136
 
74
137
  <!-- Раздел составлен ассистентом (Claude Opus 5.5), 2026-11-23. -->
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env node
2
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160: the local DevOps agent orchestrator of
3
+ // @consilium108/mcp-module-devops — a SEPARATE long-running service (a systemd user unit), not the MCP and not the runner.
4
+ // It listens to the project's agent events (#437 SSE + get_events), keeps a durable queue with a lock per target, picks a
5
+ // free compatible local agent (#470 turn-monitor facts) and dispatches a structured job — dry-run by default; per slot
6
+ // (2026-11-24, stage 3) "live" starts `claude -p` (headless claude slots, `run` only) and "handoff" hands the job to a
7
+ // person's session (create_handoff). It never approves a deploy. Credential: KONSILIUM_API_KEY or the
8
+ // `npx @consilium108/mcp login` sign-in.
9
+ import { readFileSync, existsSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { acquireLock, createLogger } from '../src/runner/index.js';
13
+ import {
14
+ createEventSource,
15
+ createOrchestrator,
16
+ createOrchestratorApi,
17
+ createOrchestratorStore,
18
+ createRegistry,
19
+ createLiveDispatcher,
20
+ defaultAdapters,
21
+ exampleOrchestratorConfig,
22
+ loadOrchestratorConfig,
23
+ orchestratorUnitText,
24
+ } from '../src/orchestrator/index.js';
25
+
26
+ const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
27
+ const BIN = fileURLToPath(import.meta.url);
28
+
29
+ const USAGE = `consilium-devops-orchestrator — Konsilium DevOps agent orchestrator (${PKG.name} ${PKG.version})
30
+
31
+ consilium-devops-orchestrator run the service: events → queue (lock per target) → free agent → dispatch
32
+ consilium-devops-orchestrator once catch up the events once, one tick, print the status (dry-run dispatch)
33
+ consilium-devops-orchestrator status the last status.json of the service (jobs, agents, cursors, metrics)
34
+ consilium-devops-orchestrator agents the agent slots and their state now (turn-monitor facts; changes nothing)
35
+ consilium-devops-orchestrator check validate the config (changes nothing)
36
+ consilium-devops-orchestrator config --print [--repo <dir>] [--project <id>] [--target <key>] PRINT an example config
37
+ consilium-devops-orchestrator unit --print PRINT the systemd user unit (installs nothing)
38
+ consilium-devops-orchestrator --version | --help
39
+
40
+ Options: --config <file>
41
+ Config (no secret inside): $CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG, else ~/.config/consilium-devops-orchestrator/config.json.
42
+ Environment: KONSILIUM_API_KEY (ksk_… with tasks:work, or an OAuth token) or the sign-in of \`npx @consilium108/mcp login\`;
43
+ KONSILIUM_API_URL, CONSILIUM_ORCHESTRATOR_STATE_DIR, CONSILIUM_ORCHESTRATOR_LOG_FORMAT (json|text), KONSILIUM_KEYCHAIN=off.
44
+ Dispatch is dry-run by default (the plan is recorded, nothing is started). Per agent slot: "dispatch": "live" (mode
45
+ headless, provider claude — \`claude -p\` with --permission-mode default and an explicit --allowedTools list, one job at a
46
+ time, timeout_ms ≤ leaseMs; only in \`run\`) or "handoff" (mode session — create_handoff into that session).
47
+ A deploy is approved only by a person with the deploy right (✅ in the bot); the orchestrator never approves.`;
48
+
49
+ const argv = process.argv.slice(2);
50
+ const has = (f) => argv.includes(f);
51
+ const opt = (name) => {
52
+ const i = argv.indexOf(name);
53
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : null;
54
+ };
55
+ const VALUED = new Set(['--config', '--repo', '--project', '--target']);
56
+ const cmd = argv.find((a, i) => !a.startsWith('-') && !VALUED.has(argv[i - 1])) ?? 'help';
57
+ const out = (s) => process.stdout.write(s.endsWith('\n') ? s : `${s}\n`);
58
+ const fail = (e, code = 1) => {
59
+ process.stderr.write(`consilium-devops-orchestrator: ${e.code ? `${e.code}: ` : ''}${e.message ?? e}\n`);
60
+ process.exit(code);
61
+ };
62
+
63
+ async function credentialsOf(env, apiUrl) {
64
+ if (env.KONSILIUM_API_KEY) return { bearer: async () => env.KONSILIUM_API_KEY, source: () => 'KONSILIUM_API_KEY' };
65
+ if (env.KONSILIUM_KEYCHAIN !== 'off') {
66
+ try {
67
+ const auth = await import('@consilium108/mcp/auth');
68
+ const store = await auth.openStore({ env, apiUrl });
69
+ const c = await auth.createCredentialProvider({ apiUrl, store, envKey: null }).init();
70
+ return { bearer: () => c.bearer(), source: () => `sign-in (${store.backend})` };
71
+ } catch {
72
+ /* no host package / no sign-in */
73
+ }
74
+ }
75
+ return { bearer: async () => null, source: () => 'none' };
76
+ }
77
+
78
+ /** G4: the read-only turn-monitor state of @consilium108/mcp ≥ 0.11.1, or null (the registry reads the files). */
79
+ async function turnMonitorOrNull() {
80
+ try {
81
+ const m = await import('@consilium108/mcp/turnmonitor');
82
+ return typeof m.turnMonitorState === 'function' ? m : null;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ async function subscribeSseOrNull() {
89
+ try {
90
+ return (await import('@nativemind108/mcp')).subscribeSse ?? null;
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ function build(config, { log, credentials, subscribeSse, turnMonitor, live = false }) {
97
+ const store = createOrchestratorStore({ dir: config.stateDir });
98
+ const adapters = defaultAdapters(config.agents.map((a) => a.provider));
99
+ const registry = createRegistry({ agents: config.agents, adapters, idleTtlMs: config.idleTtlMs, turnMonitor });
100
+ const api = createOrchestratorApi({ server: config.server, credentials, userAgent: `consilium-devops-orchestrator/${PKG.version}`, subscribeSse: config.sse ? subscribeSse : null });
101
+ const deps = { api, store, registry, adapters, log };
102
+ // stage 3: the live dispatcher only for `run` and only when a slot asks for it
103
+ if (live && config.agents.some((a) => a.dispatch === 'live')) deps.dispatcher = createLiveDispatcher({ logDir: join(config.stateDir, 'live'), log, onResult: (r) => deps.orc.onLiveResult(r) });
104
+ const orc = createOrchestrator(config, deps);
105
+ deps.orc = orc;
106
+ deps.source = createEventSource({ api, store, projects: config.projects, handle: orc.handle, log, sse: config.sse });
107
+ return { orc, store, registry, source: deps.source };
108
+ }
109
+
110
+ async function main() {
111
+ if (has('--version') || cmd === 'version') return out(PKG.version);
112
+ if (has('--help') || has('-h') || cmd === 'help') return out(USAGE);
113
+ if (cmd === 'config') {
114
+ if (!has('--print')) return fail({ message: 'config writes nothing; use: config --print > <file>' }, 2);
115
+ return out(JSON.stringify(exampleOrchestratorConfig({ repoDir: opt('--repo') ?? '/path/to/consilium.nativemind.net', projectId: Number(opt('--project')) || 1, target: opt('--target') ?? 'konsilium-prod' }), null, 2));
116
+ }
117
+ if (cmd === 'unit') {
118
+ if (!has('--print')) return fail({ message: 'unit installs nothing; use: unit --print' }, 2);
119
+ return out(orchestratorUnitText({ bin: BIN }));
120
+ }
121
+ let config;
122
+ try {
123
+ config = loadOrchestratorConfig({ file: opt('--config') });
124
+ } catch (e) {
125
+ return fail(e, 78);
126
+ }
127
+ if (cmd === 'check') return out(`ok: ${config.file}; projects ${config.projects.join(', ')}; targets ${Object.keys(config.targets).join(', ') || '—'}; agents ${config.agents.map((a) => `${a.id}${a.dispatch !== 'dry_run' ? ` (${a.dispatch})` : ''}`).join(', ') || '—'}; dispatch ${config.dispatch}`);
128
+ if (cmd === 'status') {
129
+ const f = join(config.stateDir, 'status.json');
130
+ if (!existsSync(f)) return fail({ code: 'no_status', message: `${f} does not exist (the service has not run yet)` });
131
+ return out(readFileSync(f, 'utf8'));
132
+ }
133
+ const log = createLogger({ format: config.logFormat, out: cmd === 'run' ? process.stdout : process.stderr });
134
+ if (cmd === 'agents') {
135
+ const adapters = defaultAdapters(config.agents.map((a) => a.provider));
136
+ const registry = createRegistry({ agents: config.agents, adapters, idleTtlMs: config.idleTtlMs, turnMonitor: await turnMonitorOrNull() });
137
+ return out(JSON.stringify(registry.snapshot(), null, 2));
138
+ }
139
+ if (cmd === 'run' || cmd === 'once') {
140
+ let lock;
141
+ try {
142
+ lock = acquireLock(config.stateDir, 'orchestrator.lock');
143
+ } catch (e) {
144
+ return fail(e, 75);
145
+ }
146
+ const credentials = await credentialsOf(process.env, config.server);
147
+ log.info('credential', { source: credentials.source() });
148
+ const { orc, source } = build(config, { log, credentials, subscribeSse: cmd === 'run' ? await subscribeSseOrNull() : null, turnMonitor: await turnMonitorOrNull(), live: cmd === 'run' });
149
+ if (cmd === 'once') {
150
+ try {
151
+ for (const pid of config.projects) await source.catchUp(pid);
152
+ await orc.tick();
153
+ out(JSON.stringify(orc.status(), null, 2));
154
+ } catch (e) {
155
+ log.error('once failed', { code: e.code ?? 'error', error: e.message });
156
+ process.exitCode = 1;
157
+ } finally {
158
+ lock.release();
159
+ }
160
+ return;
161
+ }
162
+ const onSignal = (sig) => orc.stop(sig);
163
+ process.on('SIGTERM', onSignal);
164
+ process.on('SIGINT', onSignal);
165
+ await orc.start();
166
+ lock.release();
167
+ return;
168
+ }
169
+ fail({ message: `unknown command «${cmd}» (--help)` }, 2);
170
+ }
171
+
172
+ main().catch((e) => fail(e));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@consilium108/mcp-module-devops",
3
- "version": "1.1.0",
4
- "description": "DevOps module of the Konsilium MCP (#442): Deploy requests by button and their status; debug reports of apps. Loaded by the host @consilium108/mcp; also runs on its own (bin consilium-devops-mcp, #482); the deploy runner service (bin consilium-devops-runner).",
3
+ "version": "1.3.0",
4
+ "description": "DevOps module of the Konsilium MCP (#442): Deploy requests by button and their status; debug reports of apps. Loaded by the host @consilium108/mcp; also runs on its own (bin consilium-devops-mcp, #482); the deploy runner service (bin consilium-devops-runner); the local agent orchestrator (bin consilium-devops-orchestrator, #486).",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "NativeMind",
7
7
  "homepage": "https://konsilium.nativemind.net",
@@ -13,12 +13,14 @@
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",
20
21
  "consilium-devops-mcp": "bin/consilium-devops-mcp.js",
21
- "consilium-devops-runner": "bin/consilium-devops-runner.js"
22
+ "consilium-devops-runner": "bin/consilium-devops-runner.js",
23
+ "consilium-devops-orchestrator": "bin/consilium-devops-orchestrator.js"
22
24
  },
23
25
  "files": [
24
26
  "src",
@@ -0,0 +1,158 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §7): provider adapters. One
2
+ // interface for every provider — available(agent), plan(job, agent) → the exact launch it WOULD make (argv, cwd, names of
3
+ // env variables, the structured job) — so the orchestrator is not tied to Claude Code. The plan is recorded (dry-run) or,
4
+ // for a slot with dispatch "live" (stage 3: headless claude only), checked by validateLivePlan and started by live.js;
5
+ // a session slot with dispatch "handoff" gets a create_handoff instead. Rules baked into every plan:
6
+ // • the agent may only analyse and REQUEST a deploy (request_deploy of the DevOps MCP); a person approves it (✅);
7
+ // • no permission bypass flag is ever added (no --dangerously-skip-permissions / bypassPermissions / --yolo);
8
+ // • an interactive («session») slot is never driven by a second process: its plan is a hand-off for that session;
9
+ // • no secret in the prompt: only refs, ids, the target key and the environment.
10
+ import { existsSync, statSync } from 'node:fs';
11
+ import { basename } from 'node:path';
12
+
13
+ export const RESULT_MARK = 'ORCHESTRATOR_RESULT';
14
+ /** DevOps MCP tools a deploy_check may use (read + request; there is no approve tool and none is allowed). */
15
+ export const DEPLOY_CHECK_TOOLS = ['request_deploy', 'deploy_status', 'list_deploys', 'list_deploy_targets', 'runner_status'];
16
+ export const FORBIDDEN_FLAGS = ['--dangerously-skip-permissions', 'bypassPermissions', '--yolo', '--full-auto', '--dangerously-bypass-approvals-and-sandbox'];
17
+ /** Read-only git a deploy_check may run (Claude Code permission rules). Nothing else from Bash. */
18
+ export const READ_ONLY_GIT = ['Bash(git log:*)', 'Bash(git status:*)', 'Bash(git diff:*)', 'Bash(git show:*)', 'Bash(git rev-parse:*)'];
19
+
20
+ /** The structured job handed to an agent: only verified fields; unknown ones are named as unknown. */
21
+ export function jobContext(job) {
22
+ const src = job.sources ?? [];
23
+ // G2: what the agents said about the deploy (branch / commit) — given when every signal agrees, else still unknown
24
+ const one = (k) => {
25
+ const v = [...new Set(src.map((s) => s[k]).filter(Boolean))];
26
+ return v.length === 1 && src.every((s) => s[k]) ? v[0] : null;
27
+ };
28
+ const branch = one('branch');
29
+ const commit = one('commit_sha');
30
+ return {
31
+ schema: 'konsilium.devops-job/1',
32
+ job_id: job.id,
33
+ kind: job.kind,
34
+ project_id: job.projectId,
35
+ target: job.target,
36
+ environment: job.environment,
37
+ approval: { required: true, by: 'a person with the deploy right (✅ in the Konsilium bot)', orchestrator_may_approve: false, agent_may_approve: false },
38
+ 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 } : {}) })),
39
+ ...(branch ? { branch } : {}),
40
+ ...(commit ? { commit_sha: commit } : {}),
41
+ unknown: [...(branch ? [] : ['repository branch']), ...(commit ? [] : ['commit SHA']), 'what changed since the last deploy'],
42
+ attempt: job.attempts,
43
+ };
44
+ }
45
+
46
+ export function promptOf(job) {
47
+ const ctx = jobContext(job);
48
+ return [
49
+ `Konsilium DevOps job ${job.id} (${job.kind}) for the deploy target «${job.target}» (${job.environment}).`,
50
+ 'An agent turn said a deploy may be needed (DEPLOY_REQUIRED). That is a signal, NOT a command to deploy.',
51
+ '1. Check what changed (git log / git status in this workspace) and whether those changes are committed and tested.',
52
+ `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. Never approve, never run the deploy steps yourself, never edit the runner config.`,
53
+ '3. If it is not warranted or you are unsure, do not request; say why.',
54
+ `Finish with ONE line: ${RESULT_MARK} {"job":"${job.id}","outcome":"requested|not_needed|blocked","deploy_id":<id or null>,"note":"<short>"}`,
55
+ '',
56
+ 'Job (JSON):',
57
+ JSON.stringify(ctx),
58
+ ].join('\n');
59
+ }
60
+
61
+ /** The last ORCHESTRATOR_RESULT line of an agent's output → { job, outcome, deploy_id, note } | null. */
62
+ export function parseResult(text) {
63
+ const lines = String(text ?? '').split('\n').filter((l) => l.includes(RESULT_MARK));
64
+ for (const l of lines.reverse()) {
65
+ try {
66
+ const r = JSON.parse(l.slice(l.indexOf(RESULT_MARK) + RESULT_MARK.length).trim());
67
+ if (r && typeof r.job === 'string' && ['requested', 'not_needed', 'blocked'].includes(r.outcome)) return { job: r.job, outcome: r.outcome, deploy_id: Number.isInteger(r.deploy_id) ? r.deploy_id : null, note: r.note ? String(r.note).slice(0, 300) : null };
68
+ } catch {}
69
+ }
70
+ return null;
71
+ }
72
+
73
+ const dirOk = (p) => {
74
+ try {
75
+ return existsSync(p) && statSync(p).isDirectory();
76
+ } catch {
77
+ return false;
78
+ }
79
+ };
80
+
81
+ function baseAdapter(provider, build) {
82
+ return {
83
+ provider,
84
+ available(agent) {
85
+ return dirOk(agent.workspace) ? { ok: true } : { ok: false, reason: `workspace ${agent.workspace} does not exist on this host` };
86
+ },
87
+ plan(job, agent) {
88
+ const prompt = promptOf(job);
89
+ const built = (p) => build(p, job, agent);
90
+ if (agent.mode === 'session') {
91
+ // an interactive session is never driven by a second process: the job is handed to THAT session
92
+ return { provider, mode: 'handoff_to_session', cwd: agent.workspace, session: agent.session ?? agent.sessionId ?? null, argv: null, env: [], prompt, job: jobContext(job) };
93
+ }
94
+ return { provider, mode: 'headless', cwd: agent.workspace, ...built(prompt), prompt, job: jobContext(job) };
95
+ },
96
+ };
97
+ }
98
+
99
+ const mcpTool = (name) => `mcp__consilium-devops__${name}`;
100
+
101
+ /** The exact --allowedTools of a live deploy_check: the DevOps MCP tools (read + request; no approve exists) and read-only git. */
102
+ export const LIVE_ALLOWED_TOOLS = [...DEPLOY_CHECK_TOOLS.map(mcpTool), ...READ_ONLY_GIT];
103
+
104
+ /** Claude Code: `claude -p` headless with an explicit tool allow-list and the default permission mode. */
105
+ export const claudeAdapter = baseAdapter('claude', (prompt, _job, agent) => ({
106
+ argv: [agent?.claudeBin ?? 'claude', '-p', prompt, '--output-format', 'json', '--permission-mode', 'default', '--allowedTools', LIVE_ALLOWED_TOOLS.join(',')],
107
+ env: ['KONSILIUM_API_KEY (from the service environment; never in the prompt)'],
108
+ }));
109
+
110
+ /** Codex CLI: `codex exec` in its default sandbox and approval policy (no bypass). */
111
+ export const codexAdapter = baseAdapter('codex', (prompt) => ({ argv: ['codex', 'exec', prompt], env: ['KONSILIUM_API_KEY'] }));
112
+
113
+ /** Any other client: the plan carries the prompt; a person or a wrapper starts it. */
114
+ export const genericAdapter = (provider) => baseAdapter(provider, () => ({ argv: null, env: [] }));
115
+
116
+ export function defaultAdapters(providers = []) {
117
+ const out = { claude: claudeAdapter, codex: codexAdapter };
118
+ for (const p of providers) if (!out[p]) out[p] = genericAdapter(p);
119
+ return out;
120
+ }
121
+
122
+ /** True if a plan would bypass a permission gate (refused by the dispatcher). */
123
+ export function bypassesPermissions(plan) {
124
+ const flat = [...(plan.argv ?? [])].join(' ');
125
+ return FORBIDDEN_FLAGS.some((f) => flat.includes(f)) || /--dangerously|--permission-mode[= ](?!default\b)/.test(flat);
126
+ }
127
+
128
+ const LIVE_FLAGS = new Set(['--output-format', '--permission-mode', '--allowedTools']);
129
+ /**
130
+ * Stage 3: may this plan be STARTED as a process? Strict — the exact shape claudeAdapter builds and nothing more:
131
+ * claude (…/claude) -p <prompt> [--output-format json] --permission-mode default --allowedTools <subset of LIVE_ALLOWED_TOOLS>
132
+ * no other flag (no bypass, no extra MCP config, no permission-prompt tool, no shell), a headless claude plan in a workspace.
133
+ * → { ok: true } | { ok: false, reason }
134
+ */
135
+ export function validateLivePlan(plan, agent = null) {
136
+ const no = (reason) => ({ ok: false, reason });
137
+ if (!plan || plan.provider !== 'claude' || plan.mode !== 'headless') return no('live dispatch is only for a headless claude plan');
138
+ if (agent && (agent.mode !== 'headless' || agent.provider !== 'claude')) return no('live dispatch is only for a headless claude slot');
139
+ const a = plan.argv;
140
+ if (!Array.isArray(a) || a.length < 3 || a.some((x) => typeof x !== 'string')) return no('no argv');
141
+ if (bypassesPermissions(plan)) return no('the plan would bypass a permission gate');
142
+ if (basename(a[0]) !== 'claude' || (agent?.claudeBin && a[0] !== agent.claudeBin)) return no(`not the configured claude binary: ${basename(a[0])}`);
143
+ if (a[1] !== '-p' || !a[2] || a[2].startsWith('-')) return no('claude must run as `claude -p <prompt>`');
144
+ const seen = {};
145
+ for (let i = 3; i < a.length; i += 2) {
146
+ const f = a[i];
147
+ if (!LIVE_FLAGS.has(f) || seen[f] !== undefined || a[i + 1] === undefined) return no(`flag not allowed in a live run: ${String(f).slice(0, 40)}`);
148
+ seen[f] = a[i + 1];
149
+ }
150
+ if (seen['--permission-mode'] !== 'default') return no('--permission-mode must be «default»');
151
+ if (seen['--output-format'] !== undefined && seen['--output-format'] !== 'json') return no('--output-format must be json');
152
+ const tools = String(seen['--allowedTools'] ?? '').split(',').map((t) => t.trim()).filter(Boolean);
153
+ if (!tools.length) return no('an explicit --allowedTools list is required');
154
+ const bad = tools.find((t) => !LIVE_ALLOWED_TOOLS.includes(t));
155
+ if (bad) return no(`tool not allowed in a live run: ${bad.slice(0, 60)}`);
156
+ if (!plan.cwd || !dirOk(plan.cwd)) return no(`workspace ${plan.cwd} does not exist`);
157
+ return { ok: true };
158
+ }
@@ -0,0 +1,86 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §8): the orchestrator's calls
2
+ // to EXISTING Konsilium routes with the person's credential (a scoped key ksk_… with tasks:work, or the OAuth sign-in) —
3
+ // GET /api/projects/:id/events (#437 journal: catch-up and the long-poll fallback)
4
+ // GET /api/projects/:id/deploys/:deployId (DevOps module via the core: the status of a request an agent made)
5
+ // POST /api/projects/:id/agent-events (#470 route: the orchestrator's status reports; idempotent; notifies nobody)
6
+ // POST /api/projects/:id/handoffs (#F73 create_handoff: a job for a «session» slot with dispatch "handoff" —
7
+ // GET /api/projects/:id/handoffs/:handoffId the person's own agent session takes it; its result comes back here;
8
+ // POST /api/projects/:id/handoffs/:handoffId/status only «cancelled» of the orchestrator's own pending hand-off)
9
+ // and the SSE stream /api/graphql/stream (projectEvents of #437) through subscribeSse of @nativemind108/mcp when it is
10
+ // given. There is no approve call here and none can be added through this client: approvals are a person's ✅.
11
+ import { DevopsMcpError } from '../errors.js';
12
+
13
+ export const PROJECT_EVENTS_QUERY = 'subscription E($p: Int!, $after: Cursor, $t: [String!]) { projectEvents(projectId: $p, after: $after, types: $t) { cursor type projectId entity ref path version contentHash deleted at } }';
14
+ export const ALLOWED_ROUTES = ['GET /api/projects/{id}/events', 'GET /api/projects/{id}/deploys/{deployId}', 'POST /api/projects/{id}/agent-events', 'POST /api/projects/{id}/handoffs', 'GET /api/projects/{id}/handoffs/{handoffId}', 'POST /api/projects/{id}/handoffs/{handoffId}/status'];
15
+
16
+ /**
17
+ * @param {{ server: string, credentials: { bearer: () => Promise<string|null> }, fetchImpl?: typeof fetch, userAgent?: string,
18
+ * timeoutMs?: number, subscribeSse?: Function }} o
19
+ */
20
+ export function createOrchestratorApi({ server, credentials, fetchImpl = fetch, userAgent = 'consilium-devops-orchestrator', timeoutMs = 70_000, subscribeSse = null }) {
21
+ const base = String(server).replace(/\/+$/, '');
22
+ async function call(method, path, params = {}, body = null) {
23
+ if (!ALLOWED_ROUTES.includes(`${method} ${path}`)) throw new DevopsMcpError('route_not_allowed', `${method} ${path} is not a route of the orchestrator`);
24
+ const bearer = await credentials.bearer();
25
+ if (!bearer) throw new DevopsMcpError('auth_required', 'no Konsilium credential (KONSILIUM_API_KEY or `npx @consilium108/mcp login`)', 401);
26
+ const rest = { ...params };
27
+ const p = path.replace(/\{(\w+)\}/g, (_m, k) => {
28
+ const v = rest[k];
29
+ delete rest[k];
30
+ return encodeURIComponent(String(v));
31
+ });
32
+ const qs = method === 'GET' ? new URLSearchParams(Object.entries(rest).filter(([, v]) => v !== undefined && v !== null).map(([k, v]) => [k, Array.isArray(v) ? v.join(',') : String(v)])).toString() : '';
33
+ let r;
34
+ try {
35
+ r = await fetchImpl(`${base}${p}${qs ? `?${qs}` : ''}`, {
36
+ method,
37
+ headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json', 'user-agent': userAgent, 'x-nm-client': 'mcp', 'x-nm-mcp-local': '1' },
38
+ ...(body ? { body: JSON.stringify(body) } : {}),
39
+ signal: AbortSignal.timeout(timeoutMs),
40
+ });
41
+ } catch (e) {
42
+ throw new DevopsMcpError('network_unavailable', `${method} ${path}: ${e?.cause?.code ?? e?.name ?? 'network error'}`, 0);
43
+ }
44
+ if (!r.ok) {
45
+ const code = r.status === 401 ? 'auth_invalid' : r.status === 403 ? 'forbidden' : r.status === 404 ? 'not_found' : r.status === 503 ? 'module_unavailable' : `http_${r.status}`;
46
+ throw new DevopsMcpError(code, `${method} ${path}: HTTP ${r.status}`, r.status);
47
+ }
48
+ const j = await r.json();
49
+ return j?.data ?? j;
50
+ }
51
+ return {
52
+ events: (projectId, cursor, { waitSeconds = 0, limit = 200, types = null } = {}) => call('GET', '/api/projects/{id}/events', { id: projectId, cursor: cursor ?? 0, wait_seconds: waitSeconds, limit, types: types?.length ? types : undefined }),
53
+ deploy: async (projectId, deployId) => {
54
+ const r = await call('GET', '/api/projects/{id}/deploys/{deployId}', { id: projectId, deployId });
55
+ return r?.deploy ?? r?.request ?? r;
56
+ },
57
+ report: (projectId, body) => call('POST', '/api/projects/{id}/agent-events', { id: projectId }, body),
58
+ /** Stage 3: a job handed to a person's agent session (create_handoff). → { id, status, … } */
59
+ handoff: async (projectId, { target_agent, title, context, idempotency_key }) => {
60
+ const r = await call('POST', '/api/projects/{id}/handoffs', { id: projectId }, { target_agent, title, context, idempotency_key });
61
+ return r?.handoff ?? r;
62
+ },
63
+ getHandoff: async (projectId, handoffId) => {
64
+ const r = await call('GET', '/api/projects/{id}/handoffs/{handoffId}', { id: projectId, handoffId });
65
+ return r?.handoff ?? r;
66
+ },
67
+ /** Only cancelling the orchestrator's own hand-off (a lease that expired while it was still pending). */
68
+ cancelHandoff: async (projectId, handoffId) => {
69
+ const r = await call('POST', '/api/projects/{id}/handoffs/{handoffId}/status', { id: projectId, handoffId }, { status: 'cancelled' });
70
+ return r?.handoff ?? r;
71
+ },
72
+ /** projectEvents over SSE, or null when no subscribeSse was given. */
73
+ subscribe: subscribeSse
74
+ ? (o) =>
75
+ subscribeSse({
76
+ url: `${base}/api/graphql/stream`,
77
+ query: PROJECT_EVENTS_QUERY,
78
+ variables: { p: o.projectId, t: o.types ?? ['agent.', 'deploy.'] },
79
+ bearer: async () => credentials.bearer().catch(() => null),
80
+ headers: { 'X-NM-Client': 'mcp', 'X-NM-MCP-Local': '1' },
81
+ ...(fetchImpl !== fetch ? { fetch: fetchImpl } : {}),
82
+ ...o,
83
+ })
84
+ : null,
85
+ };
86
+ }