@consilium108/mcp-module-devops 1.3.0 → 1.5.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 +48 -0
- package/README.md +74 -58
- package/bin/consilium-devops-mcp.js +47 -3
- package/bin/consilium-devops-runner.js +16 -0
- package/package.json +4 -4
- package/src/orchestrator/brief.js +46 -0
- package/src/orchestrator/config.js +29 -78
- package/src/orchestrator/events.js +5 -12
- package/src/orchestrator/index.js +9 -12
- package/src/orchestrator/producer.js +193 -0
- package/src/orchestrator/registry.js +16 -4
- package/src/runner/config.js +1 -1
- package/src/runner/index.js +1 -0
- package/src/runner/recipes.js +3 -1
- package/src/runner/record.js +140 -0
- package/src/standalone.js +9 -3
- package/bin/consilium-devops-orchestrator.js +0 -172
- package/src/orchestrator/adapters.js +0 -158
- package/src/orchestrator/api.js +0 -86
- package/src/orchestrator/daemon.js +0 -494
- package/src/orchestrator/install.js +0 -28
- package/src/orchestrator/live.js +0 -161
- package/src/orchestrator/source.js +0 -177
- package/src/orchestrator/store.js +0 -145
|
@@ -1,172 +0,0 @@
|
|
|
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));
|
|
@@ -1,158 +0,0 @@
|
|
|
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
|
-
}
|
package/src/orchestrator/api.js
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
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
|
-
}
|