@consilium108/mcp-module-devops 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +58 -56
- package/bin/consilium-devops-mcp.js +47 -3
- package/package.json +4 -4
- package/src/orchestrator/brief.js +46 -0
- package/src/orchestrator/config.js +29 -78
- package/src/orchestrator/events.js +5 -12
- package/src/orchestrator/index.js +9 -12
- package/src/orchestrator/producer.js +193 -0
- package/src/orchestrator/registry.js +16 -4
- package/src/standalone.js +9 -3
- package/bin/consilium-devops-orchestrator.js +0 -172
- package/src/orchestrator/adapters.js +0 -158
- package/src/orchestrator/api.js +0 -86
- package/src/orchestrator/daemon.js +0 -494
- package/src/orchestrator/install.js +0 -28
- package/src/orchestrator/live.js +0 -161
- package/src/orchestrator/source.js +0 -177
- package/src/orchestrator/store.js +0 -145
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486 v2 (SDD-P37-160, IT-160-2 … IT-160-6): the DevOps
|
|
2
|
+
// Orchestrator INSIDE the DevOps MCP process — the producer of DevOps jobs for the shared job inbox of
|
|
3
|
+
// @consilium108/mcp-agent-jobs (envelope konsilium.agent-job/1). It replaces the separate service of 1.2.0 / 1.3.0
|
|
4
|
+
// (daemon loop, agent slots, dry-run / live / hand-off dispatch, systemd unit, CLI): what stayed is the logic —
|
|
5
|
+
// events (events.js intents, unchanged) agent.deploy_required of a routed project → a job devops.deploy_check for the
|
|
6
|
+
// target (DEPLOY_REQUIRED is a signal, not a deploy); state hints → the registry
|
|
7
|
+
// queue rules (now the inbox) one active job per project + environment + target (lock_key), signals of a
|
|
8
|
+
// target coalesce into its queued job, lease / retry / backoff / max attempts
|
|
9
|
+
// deploy lifecycle (G1) deploy.* of the journal move the job that follows a request; GET /deploys/:id
|
|
10
|
+
// as the fallback (only the leader, only when the journal is silent)
|
|
11
|
+
// correlation (IT-14) a deploy.requested of the job's target after the claim gives the deploy id
|
|
12
|
+
// when the subagent's result has none
|
|
13
|
+
// reports (#470 route) waiting_for_user → NEEDS_APPROVAL (blocking), blocked → BLOCKED, failed →
|
|
14
|
+
// ERROR, succeeded / cancelled → TASK_COMPLETED; idempotent keys «orc:…» (the
|
|
15
|
+
// loop guard ignores them when they come back)
|
|
16
|
+
// Who runs a job: the main agent of the running session claims it (jobs_claim) and starts its own built-in subagent
|
|
17
|
+
// (Agent tool); the subagent may call request_deploy — a person approves it (✅); the existing runner of #482 executes
|
|
18
|
+
// only the approved deploy. Nothing here can approve, start an agent or a process.
|
|
19
|
+
import { intentOf, DEPLOY_EVENT_STATUS } from './events.js';
|
|
20
|
+
import { ORCHESTRATOR_PROVIDER, OWN_KEY_PREFIX } from './config.js';
|
|
21
|
+
import { DEPLOY_CHECK_TOOLS, jobContext, promptOf } from './brief.js';
|
|
22
|
+
|
|
23
|
+
export const DEVOPS_MCP = 'consilium-devops';
|
|
24
|
+
export const DEVOPS_KINDS = ['devops.deploy_check'];
|
|
25
|
+
export const DEVOPS_EVENT_TYPES = ['agent.', 'deploy.'];
|
|
26
|
+
/** deploy request status → job status (the job holds the target's lock until the deploy is final). */
|
|
27
|
+
const DEPLOY_STATUS = { pending: 'waiting_for_user', approved: 'running', running: 'running', done: 'succeeded', failed: 'failed', rejected: 'cancelled', expired: 'cancelled' };
|
|
28
|
+
const FOLLOWING = new Set(['waiting_for_user', 'running', 'claimed']);
|
|
29
|
+
const REPORT_TYPE = { waiting_for_user: 'NEEDS_APPROVAL', blocked: 'BLOCKED', failed: 'ERROR', succeeded: 'TASK_COMPLETED', cancelled: 'TASK_COMPLETED' };
|
|
30
|
+
const serverTime = (s) => (s ? Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : `${String(s).replace(' ', 'T')}Z`) : NaN);
|
|
31
|
+
const clip = (s, n) => (s == null ? null : String(s).length > n ? `${String(s).slice(0, n - 1)}…` : String(s));
|
|
32
|
+
/** The loop guard: the orchestrator's own reports come back through the same journal. */
|
|
33
|
+
export const isOwnEvent = (ev) => ev.agent === ORCHESTRATOR_PROVIDER || String(ev.contentHash ?? '').startsWith(`tm:${OWN_KEY_PREFIX}`);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {{ config: object, api: object|null, log?: object, now?: () => number, registry?: object|null, redact?: (s: string) => string }} o
|
|
37
|
+
* config — normalizeOrchestratorConfig (targets, routes, projects, report, deployPollFallbackMs, idleTtlMs)
|
|
38
|
+
*/
|
|
39
|
+
export function createDevopsProducer({ config, api, log = { info() {}, warn() {}, error() {} }, now = Date.now, registry = null, redact = (s) => s }) {
|
|
40
|
+
const metrics = { events: 0, ignored: 0, own_ignored: 0, baseline_skipped: 0, hints: 0, enqueued: 0, coalesced: 0, duplicates: 0, deploy_events: 0, deploy_polls: 0, deploy_poll_errors: 0, reports_sent: 0, reports_suppressed: 0 };
|
|
41
|
+
const deployEventProjects = new Set(); // projects whose journal is seen sending deploy.* (G1) — polling becomes a fallback
|
|
42
|
+
const DEPLOY_NOTE = (id, s, d = {}) =>
|
|
43
|
+
({
|
|
44
|
+
pending: `deploy request #${id} waits for a person's ✅`,
|
|
45
|
+
approved: `deploy #${id} approved by a person; waiting for the runner`,
|
|
46
|
+
running: `deploy #${id} is running on the runner`,
|
|
47
|
+
done: `deploy #${id} done (health ${d.health ?? '—'})`,
|
|
48
|
+
failed: `deploy #${id} failed on the runner (exit ${d.exitCode ?? '?'}, health ${d.health ?? '—'}); see deploy_status`,
|
|
49
|
+
rejected: `deploy request #${id} rejected by a person`,
|
|
50
|
+
expired: `deploy request #${id} expired without an approval`,
|
|
51
|
+
})[s] ?? `deploy #${id}: ${s}`;
|
|
52
|
+
|
|
53
|
+
function jobInput(intent) {
|
|
54
|
+
const src = intent.source;
|
|
55
|
+
const sources = [src];
|
|
56
|
+
const ctxJob = { id: '(this job)', kind: 'deploy_check', projectId: intent.projectId, target: intent.target, environment: intent.environment, sources, attempts: 1 };
|
|
57
|
+
return {
|
|
58
|
+
module: 'devops',
|
|
59
|
+
kind: 'devops.deploy_check',
|
|
60
|
+
mcp: DEVOPS_MCP,
|
|
61
|
+
project_id: intent.projectId,
|
|
62
|
+
title: `Deploy check: ${intent.target} (${intent.environment})`,
|
|
63
|
+
brief: promptOf(ctxJob),
|
|
64
|
+
context: jobContext(ctxJob),
|
|
65
|
+
correlation: { idempotency_key: `deploy_check:${src.project_id}:${src.event_id}`, events: [{ project_id: src.project_id, event_id: src.event_id, type: src.type }], task_ref: src.task_ref ?? null },
|
|
66
|
+
priority: intent.priority,
|
|
67
|
+
lock_key: `${intent.projectId}:${intent.environment}:${intent.target}`,
|
|
68
|
+
delegation: { mode: 'subagent', isolation: 'none', reason: 'an independent check; one deploy-related job per target at a time (lock_key)' },
|
|
69
|
+
approval: { required: true, by: 'a person with the deploy right (✅ in the Konsilium bot)' },
|
|
70
|
+
tools: DEPLOY_CHECK_TOOLS,
|
|
71
|
+
meta: { target: intent.target, environment: intent.environment, event_project_id: intent.eventProjectId },
|
|
72
|
+
note: `signal ${src.type} #${src.event_id}`,
|
|
73
|
+
// a later signal for the same queued job: its context lists every signal
|
|
74
|
+
mergeContext: (ctx, add) => ({ ...ctx, signals: [...(ctx?.signals ?? []), ...(add?.signals ?? [])].slice(-20) }),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Move the job that follows a deploy to the status the deploy now has (event or poll). */
|
|
79
|
+
function followDeploy(inbox, j, s, d = {}) {
|
|
80
|
+
const want = DEPLOY_STATUS[s];
|
|
81
|
+
const meta = { ...j.meta, deployFactAt: now() };
|
|
82
|
+
if (!want || (want === j.status && s === j.meta?.deployStatus)) return inbox.update(j.id, { meta });
|
|
83
|
+
return inbox.update(j.id, { status: want, lease: null, meta: { ...meta, deployStatus: s } }, DEPLOY_NOTE(j.correlation.deploy_id, s, d));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function applyDeployEvent(inbox, it) {
|
|
87
|
+
deployEventProjects.add(it.projectId);
|
|
88
|
+
const jobs = inbox.list({ module: 'devops' });
|
|
89
|
+
const j = jobs.find((x) => x.correlation.deploy_id === it.deployId && x.projectId === it.projectId && FOLLOWING.has(x.status));
|
|
90
|
+
if (j) return followDeploy(inbox, j, it.status, { health: it.health, exitCode: it.exitCode });
|
|
91
|
+
// IT-14: a request of the job's target made after the claim, before the subagent's result names it
|
|
92
|
+
if (it.event === 'deploy.requested' && it.target) {
|
|
93
|
+
const at = serverTime(it.at);
|
|
94
|
+
const c = jobs.find((x) => !x.correlation.deploy_id && x.lease && ['claimed', 'running'].includes(x.status) && x.projectId === it.projectId && x.meta?.target === it.target && (!Number.isFinite(at) || at >= Date.parse(x.claimedAt ?? 0) - 60_000));
|
|
95
|
+
if (c) inbox.update(c.id, { meta: { ...c.meta, candidateDeployId: it.deployId } }, `deploy request #${it.deployId} of ${it.target} seen in the journal`);
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
module: 'devops',
|
|
102
|
+
mcp: DEVOPS_MCP,
|
|
103
|
+
kinds: DEVOPS_KINDS,
|
|
104
|
+
types: DEVOPS_EVENT_TYPES,
|
|
105
|
+
projects: () => config.projects,
|
|
106
|
+
metrics: () => ({ ...metrics }),
|
|
107
|
+
|
|
108
|
+
async handle(ev, { baseline = false, inbox }) {
|
|
109
|
+
metrics.events++;
|
|
110
|
+
const intent = intentOf({ ...ev, own: isOwnEvent(ev) }, config);
|
|
111
|
+
if (intent.action === 'deploy') {
|
|
112
|
+
metrics.deploy_events++;
|
|
113
|
+
applyDeployEvent(inbox, intent);
|
|
114
|
+
} else if (intent.action === 'hint') {
|
|
115
|
+
const at = serverTime(ev.at);
|
|
116
|
+
registry?.hint(intent.session, intent.state, Number.isFinite(at) ? new Date(at).toISOString() : null, `bus: ${ev.type}`);
|
|
117
|
+
metrics.hints++;
|
|
118
|
+
} else if (intent.action === 'enqueue') {
|
|
119
|
+
if (baseline) metrics.baseline_skipped++;
|
|
120
|
+
else {
|
|
121
|
+
const r = inbox.enqueue(jobInput(intent), { coalesce: true });
|
|
122
|
+
if (r.duplicate) metrics.duplicates++;
|
|
123
|
+
else if (r.coalesced) metrics.coalesced++;
|
|
124
|
+
else {
|
|
125
|
+
metrics.enqueued++;
|
|
126
|
+
log.info?.('devops job queued', { job: r.job.id, target: intent.target, environment: intent.environment, event_id: intent.source.event_id });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} else if (intent.reason === 'own_report') metrics.own_ignored++;
|
|
130
|
+
else metrics.ignored++;
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
/** The subagent's result → the job status: a requested deploy is followed until it is final (holds the target). */
|
|
134
|
+
decide(job, result) {
|
|
135
|
+
if (result.outcome !== 'requested') return null; // the inbox default
|
|
136
|
+
const id = result.deploy_id ?? (Number.isInteger(job.meta?.candidateDeployId) ? job.meta.candidateDeployId : null);
|
|
137
|
+
if (!id) return { status: 'blocked', note: 'the subagent said «requested» but gave no deploy id (and none of this target was seen in the journal)' };
|
|
138
|
+
return { status: 'waiting_for_user', patch: { correlation: { ...job.correlation, deploy_id: id }, meta: { ...job.meta, deployStatus: 'pending', deployFactAt: now() } }, note: `deploy request #${id} waits for a person's ✅${result.deploy_id ? '' : ' (id from the journal)'}` };
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
/** G1 fallback: GET /deploys/:id of followed deploys — only the listener's process, only when the journal is silent. */
|
|
142
|
+
async tick({ leader, inbox }) {
|
|
143
|
+
if (!leader || !api?.deploy) return;
|
|
144
|
+
for (const j of inbox.list({ module: 'devops' })) {
|
|
145
|
+
const id = j.correlation.deploy_id;
|
|
146
|
+
if (!id || !FOLLOWING.has(j.status)) continue;
|
|
147
|
+
if (deployEventProjects.has(j.projectId) && now() - (j.meta?.deployFactAt ?? 0) < config.deployPollFallbackMs) continue;
|
|
148
|
+
let d;
|
|
149
|
+
try {
|
|
150
|
+
metrics.deploy_polls++;
|
|
151
|
+
d = await api.deploy(j.projectId, id);
|
|
152
|
+
} catch (e) {
|
|
153
|
+
metrics.deploy_poll_errors++;
|
|
154
|
+
log.warn?.('deploy status unavailable', { job: j.id, deploy_id: id, code: e.code ?? 'error' });
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
followDeploy(inbox, j, d?.status, { health: d?.health, exitCode: d?.exitCode });
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
/** Server effects: status reports through the #470 agent-event route (idempotent; nobody is notified by it). */
|
|
162
|
+
async effect(job, name, ef = {}) {
|
|
163
|
+
const status = name === 'result' ? (ef.status ?? job.status) : name;
|
|
164
|
+
const type = REPORT_TYPE[status];
|
|
165
|
+
if (!type || !api?.report) return;
|
|
166
|
+
if (config.report === 'off') {
|
|
167
|
+
metrics.reports_suppressed++;
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const deployId = job.correlation.deploy_id ?? 0;
|
|
171
|
+
const text = job.result?.summary ?? job.history?.at(-1)?.note ?? null;
|
|
172
|
+
await api.report(job.meta?.event_project_id ?? job.projectId, {
|
|
173
|
+
idempotency_key: `${OWN_KEY_PREFIX}${job.id}:${status}:${ef.attempt ?? job.attempts}:${deployId}`,
|
|
174
|
+
type,
|
|
175
|
+
basis: 'lifecycle',
|
|
176
|
+
confidence: 1,
|
|
177
|
+
provider: ORCHESTRATOR_PROVIDER,
|
|
178
|
+
via: DEVOPS_MCP,
|
|
179
|
+
session_id: `orc-${job.id}`,
|
|
180
|
+
blocking: status === 'waiting_for_user',
|
|
181
|
+
reason: clip(`DevOps job ${job.id} (${job.kind} ${job.meta?.target}/${job.meta?.environment}) → ${status}`, 500),
|
|
182
|
+
...(text ? { text: clip(redact(text), 500) } : {}),
|
|
183
|
+
...(job.correlation.task_ref ? { task_ref: clip(job.correlation.task_ref, 120) } : {}),
|
|
184
|
+
at: new Date(now()).toISOString(),
|
|
185
|
+
});
|
|
186
|
+
metrics.reports_sent++;
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
status: () => ({ targets: Object.keys(config.targets), routes: config.routes.length, deploy_event_projects: [...deployEventProjects], report: config.report, warnings: config.warnings ?? [], metrics: { ...metrics } }),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export { DEPLOY_EVENT_STATUS };
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// RESOLVED (the person answered; the agent goes on) → running
|
|
12
12
|
// TURN_COMPLETED / TASK_COMPLETED / DEPLOY_REQUIRED (not blocking) within idleTtlMs → idle
|
|
13
13
|
// nothing seen, or the last fact is older than idleTtlMs → unavailable
|
|
14
|
-
//
|
|
14
|
+
// (v2: one slot = the workspace of the running session — createSessionRegistry; «headless» slots are gone.)
|
|
15
15
|
// G4 (2026-11-24): with @consilium108/mcp ≥ 0.11.1 the facts come from its read-only export `@consilium108/mcp/turnmonitor`
|
|
16
16
|
// (turnMonitorState — the monitor's own reading, incl. TURN_STARTED of G3); without it (older host package, not
|
|
17
17
|
// installed) the files are read directly as before.
|
|
@@ -144,7 +144,19 @@ export function createRegistry({ agents, adapters, idleTtlMs, now = Date.now, re
|
|
|
144
144
|
};
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
-
/**
|
|
148
|
-
|
|
149
|
-
|
|
147
|
+
/**
|
|
148
|
+
* v2 (inside the MCP, 2026-11-24): the state of THIS session's workspace — shown by jobs_inbox / jobs_status so the main
|
|
149
|
+
* agent sees whether it is waiting for a person or blocked. It never gates a claim: subagents of the session run in
|
|
150
|
+
* parallel with the main agent; the registry keeps its facts (#470) and the bus hints of the listener.
|
|
151
|
+
*/
|
|
152
|
+
export function createSessionRegistry({ workspace, provider = 'claude', idleTtlMs = 6 * 3600_000, now = Date.now, turnMonitor = null, readJournal, readOpen, dirOf } = {}) {
|
|
153
|
+
const slot = { id: 'this-session', provider, mode: 'session', workspace, projects: [], capabilities: [] };
|
|
154
|
+
const reg = createRegistry({ agents: [slot], adapters: { [provider]: { available: () => ({ ok: true }) } }, idleTtlMs, now, turnMonitor, ...(readJournal ? { readJournal } : {}), ...(readOpen ? { readOpen } : {}), ...(dirOf ? { dirOf } : {}) });
|
|
155
|
+
return {
|
|
156
|
+
hint: (...a) => reg.hint(...a),
|
|
157
|
+
state() {
|
|
158
|
+
const s = reg.snapshot()[0];
|
|
159
|
+
return { workspace, state: s.state, reason: s.reason, session: s.session ?? null, at: s.at ?? null };
|
|
160
|
+
},
|
|
161
|
+
};
|
|
150
162
|
}
|
package/src/standalone.js
CHANGED
|
@@ -12,11 +12,14 @@ import { z } from 'zod';
|
|
|
12
12
|
import mod from './index.js';
|
|
13
13
|
import { OPS_TOOLS, registerOpsTools } from './groups/ops.js';
|
|
14
14
|
import { DevopsMcpError } from './errors.js';
|
|
15
|
+
import { registerJobTools, JOB_TOOLS, JOBS_INSTRUCTIONS } from '@consilium108/mcp-agent-jobs';
|
|
15
16
|
|
|
16
17
|
export const DEFAULT_API_URL = 'https://konsilium.nativemind.net';
|
|
17
18
|
export const SESSION_TOOLS = ['devops_session', 'select_project'];
|
|
18
19
|
/** Every tool of the standalone server, in registration order. */
|
|
19
20
|
export const STANDALONE_TOOLS = [...SESSION_TOOLS, ...Object.values(mod.groups).flatMap((g) => g.tools), ...OPS_TOOLS];
|
|
21
|
+
/** + the job inbox tools when the job runtime runs (the default of the bin; TASK-P37-486 v2). */
|
|
22
|
+
export { JOB_TOOLS };
|
|
20
23
|
|
|
21
24
|
export { DevopsMcpError }; // src/errors.js — shared with the deploy runner
|
|
22
25
|
|
|
@@ -68,8 +71,10 @@ export function fillPath(path, args = {}) {
|
|
|
68
71
|
* @param {number|null} [o.projectId] the project chosen at start (--project / KONSILIUM_PROJECT_ID)
|
|
69
72
|
* @param {string} [o.version] the client version for User-Agent
|
|
70
73
|
* @param {typeof fetch} [o.fetch]
|
|
74
|
+
* @param {object|null} [o.jobs] the job runtime of @consilium108/mcp-agent-jobs (TASK-P37-486 v2: the DevOps
|
|
75
|
+
* Orchestrator inside this MCP) → the six jobs_* tools, the inbox resource and change notifications
|
|
71
76
|
*/
|
|
72
|
-
export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, credentials = null, projectId = null, version = mod.version, fetch: f = globalThis.fetch, timeoutMs = 60_000 } = {}) {
|
|
77
|
+
export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, credentials = null, projectId = null, version = mod.version, fetch: f = globalThis.fetch, timeoutMs = 60_000, jobs = null } = {}) {
|
|
73
78
|
const core = String(apiUrl).replace(/\/+$/, '');
|
|
74
79
|
const direct = devopsUrl ? String(devopsUrl).replace(/\/+$/, '') : null;
|
|
75
80
|
let active = Number(projectId) || null;
|
|
@@ -170,7 +175,7 @@ export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, cr
|
|
|
170
175
|
client: () => 'MCP',
|
|
171
176
|
};
|
|
172
177
|
|
|
173
|
-
const server = new McpServer({ name: 'consilium-devops', version }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
178
|
+
const server = new McpServer({ name: 'consilium-devops', version }, { capabilities: { tools: {}, ...(jobs ? { resources: {}, logging: {} } : {}) }, instructions: jobs ? `${INSTRUCTIONS}\n${JOBS_INSTRUCTIONS}` : INSTRUCTIONS });
|
|
174
179
|
const ro = { readOnlyHint: true, openWorldHint: false };
|
|
175
180
|
|
|
176
181
|
server.registerTool(
|
|
@@ -216,12 +221,13 @@ export function createDevopsMcp({ apiUrl = DEFAULT_API_URL, devopsUrl = null, cr
|
|
|
216
221
|
);
|
|
217
222
|
for (const g of Object.values(mod.groups)) g.register(server, h);
|
|
218
223
|
registerOpsTools(server, h);
|
|
224
|
+
if (jobs) registerJobTools(server, { runtime: jobs, z, mcp: 'consilium-devops' });
|
|
219
225
|
|
|
220
226
|
return { server, helpers: h, activeProject: () => active, loadSession };
|
|
221
227
|
}
|
|
222
228
|
|
|
223
229
|
export const INSTRUCTIONS = `Konsilium DevOps MCP (${mod.name} ${mod.version}): deploy requests by button and their status, deploy targets and the runner's heartbeat, Job Copilot debug reports — for the projects of your Konsilium sign-in.
|
|
224
230
|
Start with devops_session (who, projects, rights, active project); select_project switches the project.
|
|
225
|
-
runner_status shows whether the deploy runner of each target is online and what it runs; runner_setup gives a person the steps to install it (text only — the runner is a separate service, bin consilium-devops-runner).
|
|
231
|
+
runner_status shows whether the deploy runner of each target is online and what it runs; runner_setup gives a person the steps to install it (text only — the runner is a separate service on the deploy host, bin consilium-devops-runner; it executes only approved deploys).
|
|
226
232
|
request_deploy asks the people with the deploy right to approve (✅ in the messenger); you cannot approve, reject or roll back — a person does. Then poll deploy_status(deploy_id): pending → approved → running → done | failed (rejected / expired), exit code, health, log tail.
|
|
227
233
|
Errors come as «code: message» (auth_required, auth_invalid, project_not_chosen, no_deploy_right, module_disabled, module_unavailable, network_unavailable …).`;
|
|
@@ -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
|
-
}
|