@consilium108/mcp-module-devops 1.0.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 +64 -0
- package/README.md +207 -0
- package/bin/consilium-devops-mcp.js +66 -0
- package/bin/consilium-devops-orchestrator.js +172 -0
- package/bin/consilium-devops-runner.js +120 -0
- package/package.json +15 -6
- package/src/errors.js +12 -0
- package/src/groups/ops.js +125 -0
- package/src/index.js +2 -0
- package/src/orchestrator/adapters.js +158 -0
- package/src/orchestrator/api.js +86 -0
- package/src/orchestrator/config.js +164 -0
- package/src/orchestrator/daemon.js +494 -0
- package/src/orchestrator/events.js +91 -0
- package/src/orchestrator/index.js +13 -0
- package/src/orchestrator/install.js +28 -0
- package/src/orchestrator/live.js +161 -0
- package/src/orchestrator/registry.js +150 -0
- package/src/orchestrator/source.js +177 -0
- package/src/orchestrator/store.js +145 -0
- package/src/runner/client.js +42 -0
- package/src/runner/config.js +143 -0
- package/src/runner/daemon.js +162 -0
- package/src/runner/doctor.js +111 -0
- package/src/runner/index.js +12 -0
- package/src/runner/install.js +113 -0
- package/src/runner/log.js +33 -0
- package/src/runner/recipes.js +230 -0
- package/src/runner/state.js +84 -0
- package/src/runner/steps.js +196 -0
- package/src/runner/watchdog.js +113 -0
- package/src/standalone.js +227 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// generated by Claude (Opus 5.5), 2026-11-23; Konsilium: the deploy runner of @consilium108/mcp-module-devops — a SEPARATE
|
|
3
|
+
// long-running service (systemd), never inside the MCP process. It executes only requests a person approved (✅ in the bot);
|
|
4
|
+
// the commands come from this host's config, never from the server. Node built-ins only (no MCP SDK needed).
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { dirname, resolve } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import {
|
|
9
|
+
acquireLock,
|
|
10
|
+
createClient,
|
|
11
|
+
createLogger,
|
|
12
|
+
createRunner,
|
|
13
|
+
createState,
|
|
14
|
+
defaultPath,
|
|
15
|
+
doctor,
|
|
16
|
+
exampleConfig,
|
|
17
|
+
formatDoctor,
|
|
18
|
+
installSteps,
|
|
19
|
+
loadConfig,
|
|
20
|
+
tick,
|
|
21
|
+
unitText,
|
|
22
|
+
} from '../src/runner/index.js';
|
|
23
|
+
|
|
24
|
+
const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
25
|
+
const BIN = fileURLToPath(import.meta.url);
|
|
26
|
+
|
|
27
|
+
const USAGE = `consilium-devops-runner — Konsilium deploy runner (${PKG.name} ${PKG.version})
|
|
28
|
+
|
|
29
|
+
consilium-devops-runner run the service: heartbeat → claim approved requests → run → result
|
|
30
|
+
consilium-devops-runner once one tick (heartbeat, claim, run if there is an approved request)
|
|
31
|
+
consilium-devops-runner doctor [--heartbeat] [--no-docker] check this host (changes nothing; --heartbeat sends one)
|
|
32
|
+
consilium-devops-runner install --print [--user] [--repo <dir>] [--target <key>] PRINT the systemd unit and steps
|
|
33
|
+
consilium-devops-runner unit --print [--user] [--repo <dir>] PRINT only the unit
|
|
34
|
+
consilium-devops-runner config --print [--repo <dir>] [--target <key>] PRINT an example config (no secret)
|
|
35
|
+
consilium-devops-runner --version | --help
|
|
36
|
+
|
|
37
|
+
Options: --config <file>
|
|
38
|
+
|
|
39
|
+
Config (outside the repository, chmod 600): $CONSILIUM_DEVOPS_RUNNER_CONFIG, else ~/.config/consilium-devops-runner/config.json,
|
|
40
|
+
else /etc/consilium-devops-runner/config.json.
|
|
41
|
+
Environment: CONSILIUM_RUNNER_TOKEN (the target's kdr_ token, instead of tokenFile), KONSILIUM_API_URL, CONSILIUM_RUNNER_PATH,
|
|
42
|
+
CONSILIUM_RUNNER_STATE_DIR, CONSILIUM_RUNNER_LOG_FORMAT (json|text), CONSILIUM_RUNNER_TELEGRAM_TOKEN (the watchdog).
|
|
43
|
+
Nothing here installs a service: install/unit only print.`;
|
|
44
|
+
|
|
45
|
+
const argv = process.argv.slice(2);
|
|
46
|
+
const has = (f) => argv.includes(f);
|
|
47
|
+
const opt = (name) => {
|
|
48
|
+
const i = argv.indexOf(name);
|
|
49
|
+
return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : null;
|
|
50
|
+
};
|
|
51
|
+
const VALUED = new Set(['--config', '--repo', '--target']);
|
|
52
|
+
const cmd = argv.find((a, i) => !a.startsWith('-') && !VALUED.has(argv[i - 1])) ?? 'help';
|
|
53
|
+
const out = (s) => process.stdout.write(s.endsWith('\n') ? s : `${s}\n`);
|
|
54
|
+
const fail = (e, code = 1) => {
|
|
55
|
+
process.stderr.write(`consilium-devops-runner: ${e.code ? `${e.code}: ` : ''}${e.message ?? e}\n`);
|
|
56
|
+
process.exit(code);
|
|
57
|
+
};
|
|
58
|
+
const repoGuess = () => resolve(dirname(BIN), '..', '..', '..');
|
|
59
|
+
|
|
60
|
+
async function main() {
|
|
61
|
+
if (has('--version') || cmd === 'version') return out(PKG.version);
|
|
62
|
+
if (has('--help') || has('-h') || cmd === 'help') return out(USAGE);
|
|
63
|
+
const configFile = opt('--config');
|
|
64
|
+
|
|
65
|
+
if (cmd === 'config') {
|
|
66
|
+
if (!has('--print')) return fail({ message: 'config writes nothing; use: config --print > <file>' }, 2);
|
|
67
|
+
return out(JSON.stringify(exampleConfig({ repoDir: opt('--repo') ?? repoGuess(), target: opt('--target') ?? 'konsilium-prod' }), null, 2));
|
|
68
|
+
}
|
|
69
|
+
if (cmd === 'install' || cmd === 'unit') {
|
|
70
|
+
if (!has('--print')) return fail({ message: `${cmd} installs nothing; use: ${cmd} --print (and run the printed commands yourself)` }, 2);
|
|
71
|
+
const mode = has('--user') ? 'user' : 'system';
|
|
72
|
+
const repoDir = opt('--repo') ?? repoGuess();
|
|
73
|
+
if (cmd === 'unit') return out(unitText({ mode, bin: BIN, repoDir, path: defaultPath() }));
|
|
74
|
+
return out(installSteps({ mode, repoDir, target: opt('--target') ?? 'konsilium-prod', bin: BIN }));
|
|
75
|
+
}
|
|
76
|
+
if (cmd === 'doctor') {
|
|
77
|
+
const r = await doctor({ file: configFile, heartbeat: has('--heartbeat'), docker: !has('--no-docker') });
|
|
78
|
+
out(formatDoctor(r));
|
|
79
|
+
process.exit(r.ok ? 0 : 1);
|
|
80
|
+
}
|
|
81
|
+
if (cmd === 'run' || cmd === 'once') {
|
|
82
|
+
let config;
|
|
83
|
+
try {
|
|
84
|
+
config = loadConfig({ file: configFile });
|
|
85
|
+
} catch (e) {
|
|
86
|
+
return fail(e, 78); // EX_CONFIG: systemd's Restart=on-failure retries; the journal says why
|
|
87
|
+
}
|
|
88
|
+
const log = createLogger({ format: config.logFormat });
|
|
89
|
+
if (!config.token) return fail({ code: 'token_missing', message: `no runner token (CONSILIUM_RUNNER_TOKEN, "tokenFile" or "token" in ${config.file}); the owner creates a target with /deploytarget` }, 78);
|
|
90
|
+
let lock;
|
|
91
|
+
try {
|
|
92
|
+
lock = acquireLock(config.stateDir);
|
|
93
|
+
} catch (e) {
|
|
94
|
+
return fail(e, 75);
|
|
95
|
+
}
|
|
96
|
+
const client = createClient({ server: config.server, token: config.token, userAgent: `consilium-devops-runner/${PKG.version}` });
|
|
97
|
+
const state = createState(config.stateDir);
|
|
98
|
+
if (cmd === 'once') {
|
|
99
|
+
try {
|
|
100
|
+
const done = await tick(config, client, { state, log });
|
|
101
|
+
log.info(done ? 'once: done' : 'once: no approved request', done ? { deploy_id: done.id, exit: done.exitCode, health: done.health } : {});
|
|
102
|
+
} catch (e) {
|
|
103
|
+
log.error('once failed', { code: e.code ?? 'error', error: e.message });
|
|
104
|
+
process.exitCode = 1;
|
|
105
|
+
} finally {
|
|
106
|
+
lock.release();
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const runner = createRunner(config, { client, state, log, lock });
|
|
111
|
+
const onSignal = (sig) => runner.stop(sig);
|
|
112
|
+
process.on('SIGTERM', onSignal);
|
|
113
|
+
process.on('SIGINT', onSignal);
|
|
114
|
+
await runner.start();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
fail({ message: `unknown command «${cmd}» (--help)` }, 2);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
main().catch((e) => fail(e));
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@consilium108/mcp-module-devops",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "DevOps module of the Konsilium MCP (#442): Deploy requests by button and their status; debug reports of apps. Loaded by the host @consilium108/mcp;
|
|
3
|
+
"version": "1.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",
|
|
@@ -11,10 +11,20 @@
|
|
|
11
11
|
},
|
|
12
12
|
"exports": {
|
|
13
13
|
".": "./src/index.js",
|
|
14
|
-
"./
|
|
14
|
+
"./standalone": "./src/standalone.js",
|
|
15
|
+
"./runner": "./src/runner/index.js",
|
|
16
|
+
"./package.json": "./package.json",
|
|
17
|
+
"./orchestrator": "./src/orchestrator/index.js"
|
|
18
|
+
},
|
|
19
|
+
"bin": {
|
|
20
|
+
"mcp-module-devops": "bin/consilium-devops-mcp.js",
|
|
21
|
+
"consilium-devops-mcp": "bin/consilium-devops-mcp.js",
|
|
22
|
+
"consilium-devops-runner": "bin/consilium-devops-runner.js",
|
|
23
|
+
"consilium-devops-orchestrator": "bin/consilium-devops-orchestrator.js"
|
|
15
24
|
},
|
|
16
25
|
"files": [
|
|
17
26
|
"src",
|
|
27
|
+
"bin",
|
|
18
28
|
"i18n",
|
|
19
29
|
"README.md",
|
|
20
30
|
"CHANGELOG.md",
|
|
@@ -32,9 +42,8 @@
|
|
|
32
42
|
}
|
|
33
43
|
},
|
|
34
44
|
"dependencies": {
|
|
35
|
-
"@
|
|
36
|
-
|
|
37
|
-
"devDependencies": {
|
|
45
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
46
|
+
"@nativemind108/mcp": "^1.13.0",
|
|
38
47
|
"zod": "^4.6.7"
|
|
39
48
|
},
|
|
40
49
|
"publishConfig": {
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-23; Konsilium (runner in the DevOps package): the package's coded error, shared by
|
|
2
|
+
// the standalone MCP (src/standalone.js) and the deploy runner (src/runner/*). No dependencies — the runner imports it
|
|
3
|
+
// without the MCP SDK installed.
|
|
4
|
+
|
|
5
|
+
/** An error with a stable code (shown as «code: message»). */
|
|
6
|
+
export class DevopsMcpError extends Error {
|
|
7
|
+
constructor(code, message, status = null) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.status = status;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-22; Konsilium #482 (TASK-P37-482, the standalone DevOps MCP): read tools over the
|
|
2
|
+
// DevOps module API — deploy targets (with the runner's last heartbeat) and the recent deploy requests of a project.
|
|
3
|
+
// Not a group of the module definition yet (the host @consilium108/mcp and the cloud MCP keep their catalog unchanged);
|
|
4
|
+
// the standalone server (src/standalone.js) registers it. Handlers use only the host-style helpers `h`.
|
|
5
|
+
|
|
6
|
+
/** Tools of `OPS_TOOLS` (the registration order). */
|
|
7
|
+
export const OPS_TOOLS = ['list_deploy_targets', 'list_deploys', 'runner_status', 'runner_setup'];
|
|
8
|
+
|
|
9
|
+
/** A runner polls every 10 s; no heartbeat for longer than this → offline. */
|
|
10
|
+
export const RUNNER_ONLINE_SEC = 120;
|
|
11
|
+
|
|
12
|
+
/** SQLite `datetime('now')` (UTC, «YYYY-MM-DD HH:MM:SS») or ISO → ms, else null. */
|
|
13
|
+
export function parseServerTime(s) {
|
|
14
|
+
if (!s) return null;
|
|
15
|
+
const t = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : `${String(s).replace(' ', 'T')}Z`);
|
|
16
|
+
return Number.isFinite(t) ? t : null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Targets + recent deploys → the runner's status per target (pure; tested). */
|
|
20
|
+
export function runnerStatusOf(targets, deploys, { now = Date.now(), onlineSec = RUNNER_ONLINE_SEC } = {}) {
|
|
21
|
+
return (targets ?? []).map((t) => {
|
|
22
|
+
const seen = parseServerTime(t.lastSeenAt ?? t.last_seen_at);
|
|
23
|
+
const ago = seen == null ? null : Math.max(0, Math.round((now - seen) / 1000));
|
|
24
|
+
const mine = (deploys ?? []).filter((d) => d.target === t.key);
|
|
25
|
+
const running = mine.find((d) => d.status === 'running') ?? null;
|
|
26
|
+
const waiting = mine.filter((d) => d.status === 'approved' || d.status === 'pending');
|
|
27
|
+
const last = mine.find((d) => d.status === 'done' || d.status === 'failed') ?? null;
|
|
28
|
+
return {
|
|
29
|
+
key: t.key,
|
|
30
|
+
title: t.title ?? null,
|
|
31
|
+
last_seen_at: t.lastSeenAt ?? t.last_seen_at ?? null,
|
|
32
|
+
seconds_since_seen: ago,
|
|
33
|
+
online: ago != null && ago <= onlineSec,
|
|
34
|
+
state: ago == null ? 'never_seen' : ago <= onlineSec ? (running ? 'running' : 'idle') : 'offline',
|
|
35
|
+
current_job: running ? { id: running.id, kind: running.kind ?? 'deploy', started_at: running.startedAt ?? null, summary: running.summary ?? null } : null,
|
|
36
|
+
waiting: waiting.map((d) => ({ id: d.id, status: d.status, kind: d.kind ?? 'deploy' })),
|
|
37
|
+
last_finished: last ? { id: last.id, status: last.status, exit_code: last.exitCode ?? null, health: last.health ?? null, finished_at: last.finishedAt ?? null } : null,
|
|
38
|
+
};
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function registerOpsTools(server, h) {
|
|
43
|
+
if (h.shape === 'personal') return;
|
|
44
|
+
const { z, text, safe, call, P } = h;
|
|
45
|
+
const arr = (r, k) => (Array.isArray(r) ? r : (r?.[k] ?? []));
|
|
46
|
+
const ro = { readOnlyHint: true, openWorldHint: false };
|
|
47
|
+
const pid = (project_id) => project_id ?? P();
|
|
48
|
+
|
|
49
|
+
server.registerTool(
|
|
50
|
+
'list_deploy_targets',
|
|
51
|
+
{
|
|
52
|
+
title: 'Deploy targets',
|
|
53
|
+
description:
|
|
54
|
+
'Deploy targets of the project (key, title) and when the runner on the project server last called in (lastSeenAt — the runner is alive if it is recent). Only people with the deploy right of the project (owner, co-owners, granted members) see them; otherwise no_deploy_right. Targets and rights are created by a person in Konsilium (bot /deploytarget or the app), never by an AI.',
|
|
55
|
+
inputSchema: { project_id: z.number().int().positive().optional().describe('Project id; default — the active project.') },
|
|
56
|
+
annotations: ro,
|
|
57
|
+
},
|
|
58
|
+
safe(async ({ project_id }, ctx) => {
|
|
59
|
+
const id = pid(project_id);
|
|
60
|
+
const r = await call(ctx, 'GET', '/api/projects/{id}/deploy-targets', { id });
|
|
61
|
+
return text({ project_id: id, targets: Array.isArray(r) ? r : (r?.targets ?? r) });
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
server.registerTool(
|
|
65
|
+
'list_deploys',
|
|
66
|
+
{
|
|
67
|
+
title: 'Recent deploy requests',
|
|
68
|
+
description:
|
|
69
|
+
'The last deploy requests of the project (newest first, up to 20): target, status pending → approved → running → done | failed (or rejected / expired), who asked, exit code, health. Details and the log tail of one request — deploy_status.',
|
|
70
|
+
inputSchema: { project_id: z.number().int().positive().optional().describe('Project id; default — the active project.') },
|
|
71
|
+
annotations: ro,
|
|
72
|
+
},
|
|
73
|
+
safe(async ({ project_id }, ctx) => {
|
|
74
|
+
const id = pid(project_id);
|
|
75
|
+
const r = await call(ctx, 'GET', '/api/projects/{id}/deploys', { id });
|
|
76
|
+
return text({ project_id: id, deploys: Array.isArray(r) ? r : (r?.deploys ?? r) });
|
|
77
|
+
}),
|
|
78
|
+
);
|
|
79
|
+
// generated by Claude (Opus 5.5), 2026-11-23: the runner service (bin consilium-devops-runner) seen from the MCP — status and
|
|
80
|
+
// the install steps as text. The MCP never runs, installs or approves anything; the runner is a separate process.
|
|
81
|
+
server.registerTool(
|
|
82
|
+
'runner_status',
|
|
83
|
+
{
|
|
84
|
+
title: 'Deploy runner status',
|
|
85
|
+
description:
|
|
86
|
+
'Is the deploy runner of each target alive: last heartbeat (last_seen_at, seconds ago), online / offline (no heartbeat for more than 2 minutes), the job it is running now, approved requests waiting for it, the last finished one. Needs the deploy right of the project. If a target is offline, runner_setup gives the install / restart steps for a person.',
|
|
87
|
+
inputSchema: { project_id: z.number().int().positive().optional().describe('Project id; default — the active project.') },
|
|
88
|
+
annotations: ro,
|
|
89
|
+
},
|
|
90
|
+
safe(async ({ project_id }, ctx) => {
|
|
91
|
+
const id = pid(project_id);
|
|
92
|
+
const targets = arr(await call(ctx, 'GET', '/api/projects/{id}/deploy-targets', { id }), 'targets');
|
|
93
|
+
const deploys = arr(await call(ctx, 'GET', '/api/projects/{id}/deploys', { id }), 'deploys');
|
|
94
|
+
const runners = runnerStatusOf(targets, deploys);
|
|
95
|
+
return text({
|
|
96
|
+
project_id: id,
|
|
97
|
+
online_window_sec: RUNNER_ONLINE_SEC,
|
|
98
|
+
runners,
|
|
99
|
+
...(runners.some((r) => !r.online) ? { hint: 'An offline target: a person checks the service on the host (systemctl status consilium-devops-runner; journalctl -u consilium-devops-runner) — runner_setup has the steps.' } : {}),
|
|
100
|
+
...(runners.length ? {} : { hint: 'No deploy targets: the owner creates one in the bot (/deploytarget <key> <title>), never an AI.' }),
|
|
101
|
+
});
|
|
102
|
+
}),
|
|
103
|
+
);
|
|
104
|
+
server.registerTool(
|
|
105
|
+
'runner_setup',
|
|
106
|
+
{
|
|
107
|
+
title: 'Deploy runner: install steps',
|
|
108
|
+
description:
|
|
109
|
+
'The exact steps for a PERSON to bring up the deploy runner on a project host (Linux, systemd): target token via /deploytarget in the bot, the config outside the repository (chmod 600), `consilium-devops-runner doctor`, the systemd unit, a trial deploy, stop and rollback. Returns text only — it installs, starts and creates nothing (no tokens).',
|
|
110
|
+
inputSchema: {
|
|
111
|
+
target: z.string().min(2).max(41).optional().describe('Target key, default konsilium-prod.'),
|
|
112
|
+
repo_dir: z.string().max(500).optional().describe('The checkout on the host the target deploys (cwd of the steps).'),
|
|
113
|
+
user: z.string().max(64).optional().describe('The host account that runs the service (in the docker group).'),
|
|
114
|
+
mode: z.enum(['system', 'user']).optional().describe('system service with User= (default, starts at boot) or a user service.'),
|
|
115
|
+
node: z.string().max(300).optional().describe('Absolute path of node on the host (default /usr/local/bin/node).'),
|
|
116
|
+
},
|
|
117
|
+
annotations: ro,
|
|
118
|
+
},
|
|
119
|
+
safe(async ({ target, repo_dir, user, mode, node }) => {
|
|
120
|
+
const { installSteps } = await import('../runner/install.js');
|
|
121
|
+
const steps = installSteps({ target: target ?? 'konsilium-prod', repoDir: repo_dir ?? '/path/to/consilium.nativemind.net', user: user ?? 'konsilium', mode: mode ?? 'system', node: node ?? '/usr/local/bin/node' });
|
|
122
|
+
return text({ installs_nothing: true, service: 'consilium-devops-runner', steps });
|
|
123
|
+
}),
|
|
124
|
+
);
|
|
125
|
+
}
|
package/src/index.js
CHANGED
|
@@ -32,3 +32,5 @@ export default defineMcpModule({
|
|
|
32
32
|
});
|
|
33
33
|
|
|
34
34
|
export { DEBUG_TOOLS, registerDebugTools, DEPLOY_TOOLS, registerDeployTools };
|
|
35
|
+
// #482 (Claude (Opus 5.5), 2026-11-22): read tools of the standalone DevOps MCP (not a group of the host catalog yet)
|
|
36
|
+
export { OPS_TOOLS, registerOpsTools } from './groups/ops.js';
|
|
@@ -0,0 +1,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
|
+
}
|