@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.
@@ -0,0 +1,91 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §3): the event contract the
2
+ // orchestrator consumes — ONLY what the server really sends today (project_events of #437 / #470), nothing assumed.
3
+ // get_events (REST) { event_id, type, project_id, ref:{type,id}, agent, actor_user_id, summary, at, entity_type?,
4
+ // entity_ref?, path?, version?, content_hash?, deleted?, via? }
5
+ // projectEvents (SSE) { cursor, type, projectId, entity, ref, path, version, contentHash, deleted, at }
6
+ // The agent events of the turn monitor (#470): type agent.<TYPE lower case>, agent = the provider, summary = «[TYPE ·
7
+ // basis …] fragment», entity_ref = the task / SDD ref, path = the agent session, content_hash = «tm:<idempotency key>».
8
+ // G2 (2026-11-24): an agent event MAY carry meta { target, environment, branch, commit_sha } (server migration 151); when
9
+ // present, the route of that target is used (only among the configured routes of the event's project — the event never
10
+ // adds a target) and branch / commit go into the job; when absent, target and environment come from the route config.
11
+ // G1 (2026-11-24): deploy.* events of the journal (requested / approved / rejected / running / done / failed /
12
+ // rolled_back / expired; ref = the deploy id, meta { deploy_id, target, kind, status, exit_code, health }) drive the jobs
13
+ // that follow a deploy request — instead of polling GET /deploys/:id (kept as a fallback).
14
+ import { OWN_KEY_PREFIX, ORCHESTRATOR_PROVIDER } from './config.js';
15
+
16
+ /** Agent event types that say something about an agent session's state (registry hints). */
17
+ export const STATE_HINTS = {
18
+ 'agent.needs_approval': 'waiting_for_user',
19
+ 'agent.user_input_required': 'waiting_for_user',
20
+ 'agent.interactive_question': 'waiting_for_user',
21
+ 'agent.open_question': 'waiting_for_user',
22
+ 'agent.needs_decision': 'waiting_for_user',
23
+ 'agent.blocked': 'blocked',
24
+ 'agent.error': 'blocked',
25
+ 'agent.turn_completed': 'idle',
26
+ 'agent.task_completed': 'idle',
27
+ };
28
+
29
+ const metaOf = (m) => (m && typeof m === 'object' && !Array.isArray(m) ? m : null);
30
+
31
+ /** One event of either shape → { cursor, type, projectId, agent, summary, entityRef, session, contentHash, at, refType, refId, meta, own } | null. */
32
+ export function normalizeBusEvent(e) {
33
+ if (!e || typeof e !== 'object') return null;
34
+ let ev;
35
+ if ('event_id' in e) {
36
+ ev = { cursor: Number(e.event_id), type: e.type ?? null, projectId: e.project_id ?? null, agent: e.agent ?? null, summary: e.summary ?? null, entityRef: e.entity_ref ?? null, session: e.path ?? null, contentHash: e.content_hash ?? null, at: e.at ?? null, refType: e.ref?.type ?? null, refId: e.ref?.id ?? null, meta: metaOf(e.meta) };
37
+ } else {
38
+ ev = { cursor: Number(e.cursor), type: e.type ?? e.kind ?? null, projectId: e.projectId ?? null, agent: e.agent ?? null, summary: e.summary ?? null, entityRef: typeof e.ref === 'string' ? e.ref : (e.entity_ref ?? null), session: e.path ?? null, contentHash: e.contentHash ?? null, at: e.at ?? null, refType: e.entity?.type ?? null, refId: e.entity?.id ?? null, meta: metaOf(e.meta) };
39
+ }
40
+ if (!Number.isFinite(ev.cursor) || !ev.type) return null;
41
+ // loop guard: the orchestrator's own reports come back through the same journal
42
+ ev.own = ev.agent === ORCHESTRATOR_PROVIDER || String(ev.contentHash ?? '').startsWith(`tm:${OWN_KEY_PREFIX}`);
43
+ return ev;
44
+ }
45
+
46
+ /** The TYPE · basis · confidence head of an agent-event summary (for diagnostics only; never trusted as a command). */
47
+ export function summaryHead(summary) {
48
+ const m = /^\[([A-Z_]+) · ([a-z+]+)(?: ([0-9.]+))?( · ждёт человека)?\]/.exec(String(summary ?? ''));
49
+ return m ? { type: m[1], basis: m[2], confidence: m[3] ? Number(m[3]) : 1, blocking: !!m[4] } : null;
50
+ }
51
+
52
+ /**
53
+ * What an event means for the orchestrator:
54
+ * { action: 'enqueue', kind, projectId, target, environment, priority, source } a route matched (DEPLOY_REQUIRED ≠ deploy:
55
+ * the job is a CHECK by an agent that may
56
+ * REQUEST a deploy; a person approves it)
57
+ * { action: 'hint', session, state, source } a session state from the bus
58
+ * { action: 'ignore', reason }
59
+ */
60
+ /** deploy.<event> → the request status it means (rolled_back: the new rollback request is approved). */
61
+ export const DEPLOY_EVENT_STATUS = { 'deploy.requested': 'pending', 'deploy.approved': 'approved', 'deploy.rejected': 'rejected', 'deploy.running': 'running', 'deploy.done': 'done', 'deploy.failed': 'failed', 'deploy.rolled_back': 'approved', 'deploy.expired': 'expired' };
62
+ const str = (v, n) => (typeof v === 'string' && v ? v.slice(0, n) : null);
63
+
64
+ export function intentOf(ev, config) {
65
+ if (!ev) return { action: 'ignore', reason: 'malformed' };
66
+ if (ev.own) return { action: 'ignore', reason: 'own_report' };
67
+ if (String(ev.type).startsWith('deploy.')) {
68
+ const deployId = Number(ev.meta?.deploy_id ?? (ev.refType === 'deploy' ? ev.refId : NaN));
69
+ const status = DEPLOY_EVENT_STATUS[ev.type] ?? null;
70
+ if (!Number.isInteger(deployId) || !status) return { action: 'ignore', reason: 'deploy_event_without_id' };
71
+ return { action: 'deploy', deployId, status: ev.meta?.status ?? status, event: ev.type, projectId: Number(ev.projectId), target: str(ev.meta?.target, 60), kind: str(ev.meta?.kind, 20), exitCode: Number.isInteger(ev.meta?.exit_code) ? ev.meta.exit_code : null, health: str(ev.meta?.health, 200), after: Number.isInteger(ev.meta?.after) ? ev.meta.after : null, at: ev.at };
72
+ }
73
+ if (!String(ev.type).startsWith('agent.')) return { action: 'ignore', reason: 'not_an_agent_event' };
74
+ const m = ev.meta ?? {};
75
+ const said = { target: str(m.target, 60), environment: str(m.environment, 40), branch: str(m.branch, 200), commit_sha: str(m.commit_sha, 64) };
76
+ const source = { event_id: ev.cursor, project_id: ev.projectId, type: ev.type, session: ev.session, task_ref: ev.entityRef, provider: ev.agent, summary: ev.summary ? String(ev.summary).slice(0, 300) : null, at: ev.at, ...(said.branch ? { branch: said.branch } : {}), ...(said.commit_sha ? { commit_sha: said.commit_sha } : {}), ...(said.target ? { said_target: said.target } : {}), ...(said.environment ? { said_environment: said.environment } : {}) };
77
+ let routes = config.routes.filter((r) => r.event === ev.type && r.projectId === Number(ev.projectId));
78
+ if (routes.length && (said.target || said.environment)) {
79
+ // G2: the agent named the target / environment — only a configured route of this project may match it
80
+ const fit = routes.filter((r) => (!said.target || r.target === said.target) && (!said.environment || config.targets[r.target].environment === said.environment));
81
+ if (!fit.length) return { action: 'ignore', reason: said.target ? 'target_not_routed' : 'environment_not_routed' };
82
+ routes = fit;
83
+ }
84
+ const route = routes.sort((a, b) => b.priority - a.priority)[0];
85
+ if (route) {
86
+ const t = config.targets[route.target];
87
+ return { action: 'enqueue', kind: route.kind, projectId: t.projectId, eventProjectId: Number(ev.projectId), target: t.key, environment: t.environment, approval: t.approval, priority: route.priority, source };
88
+ }
89
+ if (STATE_HINTS[ev.type] && ev.session) return { action: 'hint', session: ev.session, state: STATE_HINTS[ev.type], at: ev.at, source };
90
+ return { action: 'ignore', reason: ev.type === 'agent.deploy_required' ? 'no_route_for_project' : 'no_route' };
91
+ }
@@ -0,0 +1,13 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160: the local DevOps Agent Orchestrator of
2
+ // @consilium108/mcp-module-devops (export "./orchestrator"). Node built-ins only; the SSE stream uses subscribeSse of
3
+ // @nativemind108/mcp when the bin passes it. The service: bin/consilium-devops-orchestrator.js.
4
+ export { ORCHESTRATOR_NAME, ORCHESTRATOR_PROVIDER, OWN_KEY_PREFIX, JOB_KINDS, DISPATCH_MODES, SLOT_DISPATCH, LIVE_ENV_DEFAULT, AGENT_MODES, orchestratorConfigCandidates, normalizeOrchestratorConfig, loadOrchestratorConfig, exampleOrchestratorConfig } from './config.js';
5
+ export { createOrchestratorStore, JOB_STATUSES, LOCKING, FINISHED } from './store.js';
6
+ export { normalizeBusEvent, intentOf, summaryHead, STATE_HINTS, DEPLOY_EVENT_STATUS } from './events.js';
7
+ export { createRegistry, pickAgent, readTurnJournal, sessionStateOf, turnMonitorDirOf, AGENT_STATES } from './registry.js';
8
+ export { claudeAdapter, codexAdapter, genericAdapter, defaultAdapters, jobContext, promptOf, parseResult, bypassesPermissions, validateLivePlan, RESULT_MARK, DEPLOY_CHECK_TOOLS, FORBIDDEN_FLAGS, READ_ONLY_GIT, LIVE_ALLOWED_TOOLS } from './adapters.js';
9
+ export { createLiveDispatcher, resultTextOf, liveEnvOf, maskSecrets } from './live.js';
10
+ export { createOrchestratorApi, PROJECT_EVENTS_QUERY, ALLOWED_ROUTES } from './api.js';
11
+ export { createEventSource } from './source.js';
12
+ export { createOrchestrator } from './daemon.js';
13
+ export { orchestratorUnitText } from './install.js';
@@ -0,0 +1,28 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §9): the systemd USER unit of the
2
+ // orchestrator as TEXT (`consilium-devops-orchestrator unit --print`). Nothing here installs or starts anything. A user
3
+ // service: the orchestrator reads the turn-monitor state of the person's own workspaces and uses the person's sign-in.
4
+ import { ORCHESTRATOR_NAME } from './config.js';
5
+
6
+ export function orchestratorUnitText({ node = process.execPath, bin = '/usr/local/lib/node_modules/@consilium108/mcp-module-devops/bin/consilium-devops-orchestrator.js', configPath = `%h/.config/${ORCHESTRATOR_NAME}/config.json` } = {}) {
7
+ return [
8
+ '[Unit]',
9
+ 'Description=Konsilium DevOps agent orchestrator (routes DevOps events to free local AI agents; never approves a deploy)',
10
+ 'Documentation=https://www.npmjs.com/package/@consilium108/mcp-module-devops',
11
+ 'After=network-online.target',
12
+ 'Wants=network-online.target',
13
+ '',
14
+ '[Service]',
15
+ 'Type=simple',
16
+ `Environment=CONSILIUM_DEVOPS_ORCHESTRATOR_CONFIG=${configPath}`,
17
+ `ExecStart=${node} ${bin} run`,
18
+ 'Restart=on-failure',
19
+ 'RestartSec=15',
20
+ 'KillSignal=SIGTERM',
21
+ 'TimeoutStopSec=60',
22
+ 'NoNewPrivileges=true',
23
+ '',
24
+ '[Install]',
25
+ 'WantedBy=default.target',
26
+ '',
27
+ ].join('\n');
28
+ }
@@ -0,0 +1,161 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium SDD-P37-160 stage 3 (IT-13, IT-15; owner 2026-11-24 «Запускай
2
+ // все, добавь сразу»): the LIVE dispatcher — starts `claude -p` for a slot with dispatch "live" (mode headless, provider
3
+ // claude only), one job at a time per slot, in the slot's workspace, with a timeout (≤ the lease), and hands the result
4
+ // back to the orchestrator (→ complete → agent-events report). What it never does:
5
+ // • start anything validateLivePlan refuses (no bypass flag, only --permission-mode default, only the explicit
6
+ // --allowedTools list: DevOps MCP tools + read-only git; no shell: spawn without a shell, argv as given);
7
+ // • pass the service's whole environment (only LIVE_ENV_DEFAULT + the slot's env_pass names);
8
+ // • write a secret: the per-run log in <stateDir>/live/ keeps a masked tail of stdout / stderr only;
9
+ // • approve: the agent may only REQUEST a deploy (request_deploy); a person approves it with ✅.
10
+ import { spawn } from 'node:child_process';
11
+ import { mkdirSync, writeFileSync, renameSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import { LIVE_ENV_DEFAULT } from './config.js';
14
+ import { validateLivePlan } from './adapters.js';
15
+ import { redact } from '../runner/log.js';
16
+
17
+ const MAX_OUT = 1024 * 1024; // bytes of stdout kept for the result (the claude JSON); stderr: 64 KB
18
+ const LOG_TAIL = 16 * 1024;
19
+ const SECRETISH = [
20
+ /\b(ksk_[A-Za-z0-9]{4})[A-Za-z0-9_-]*/g,
21
+ /\b(sk-ant-[A-Za-z0-9]{2})[A-Za-z0-9_-]*/g,
22
+ /\b(gh[pousr]_[A-Za-z0-9]{2})[A-Za-z0-9]*/g,
23
+ /\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,
24
+ /\b((?:[A-Z][A-Z0-9_]*_)?(?:TOKEN|SECRET|PASSWORD|API_KEY)\s*[=:]\s*)\S+/g,
25
+ ];
26
+ /** The runner's redact + Konsilium keys, Anthropic keys, GitHub tokens, Bearer values, NAME_TOKEN=… assignments. */
27
+ export function maskSecrets(s) {
28
+ let out = redact(String(s ?? ''));
29
+ for (const re of SECRETISH) out = out.replace(re, (_m, keep) => `${keep}…`);
30
+ return out;
31
+ }
32
+
33
+ /** `claude -p --output-format json` prints one JSON object with `result` (the final text); anything else → the raw text. */
34
+ export function resultTextOf(stdout) {
35
+ const t = String(stdout ?? '').trim();
36
+ for (const cand of [t, t.split('\n').filter(Boolean).at(-1) ?? '']) {
37
+ try {
38
+ const j = JSON.parse(cand);
39
+ if (j && typeof j.result === 'string') return { text: j.result, isError: j.is_error === true || j.subtype === 'error', format: 'json' };
40
+ } catch {}
41
+ }
42
+ return { text: t, isError: false, format: 'text' };
43
+ }
44
+
45
+ /** The environment of a live run: only the named variables (default list + the slot's env_pass), never the whole env. */
46
+ export function liveEnvOf(env, agent, jobId) {
47
+ const names = new Set([...LIVE_ENV_DEFAULT, ...(agent?.envPass ?? [])]);
48
+ const out = {};
49
+ for (const n of names) if (env[n] != null) out[n] = env[n];
50
+ out.KONSILIUM_ORCHESTRATOR_JOB = String(jobId);
51
+ return out;
52
+ }
53
+
54
+ /**
55
+ * @param {{ onResult: (r: { jobId: string, agentId: string, attempt: number, exitCode: number|null, signal: string|null,
56
+ * timedOut: boolean, text: string, isError: boolean, error: string|null, ms: number }) => void, logDir: string,
57
+ * spawnImpl?: typeof spawn, env?: object, log?: object, now?: () => number, killGraceMs?: number }} o
58
+ */
59
+ export function createLiveDispatcher(o) {
60
+ const spawnImpl = o.spawnImpl ?? spawn;
61
+ const env = o.env ?? process.env;
62
+ const log = o.log ?? { info() {}, warn() {}, error() {} };
63
+ const now = o.now ?? Date.now;
64
+ const grace = o.killGraceMs ?? 5000;
65
+ const running = new Map(); // agentId → { jobId, attempt, child, startedAt, timer, done }
66
+
67
+ function writeLog(jobId, attempt, rec) {
68
+ try {
69
+ mkdirSync(o.logDir, { recursive: true, mode: 0o700 });
70
+ const f = join(o.logDir, `${jobId}-a${attempt}.json`);
71
+ writeFileSync(`${f}.tmp`, JSON.stringify(rec, null, 2), { mode: 0o600 });
72
+ renameSync(`${f}.tmp`, f);
73
+ } catch {
74
+ /* diagnostics only */
75
+ }
76
+ }
77
+
78
+ /** → { ok: true } | { ok: false, reason } (nothing started). */
79
+ function start({ job, agent, plan, timeoutMs }) {
80
+ if (running.has(agent.id)) return { ok: false, reason: `slot ${agent.id} already runs ${running.get(agent.id).jobId}` };
81
+ const v = validateLivePlan(plan, agent);
82
+ if (!v.ok) return v;
83
+ const attempt = job.attempts;
84
+ const startedAt = now();
85
+ let child;
86
+ try {
87
+ child = spawnImpl(plan.argv[0], plan.argv.slice(1), { cwd: plan.cwd, env: liveEnvOf(env, agent, job.id), stdio: ['ignore', 'pipe', 'pipe'], shell: false, windowsHide: true });
88
+ } catch (e) {
89
+ return { ok: false, reason: `could not start ${plan.argv[0]}: ${e?.code ?? e?.message ?? 'error'}` };
90
+ }
91
+ const r = { jobId: job.id, attempt, child, startedAt, timedOut: false, out: [], outLen: 0, err: '', settled: false };
92
+ running.set(agent.id, r);
93
+ child.stdout?.on('data', (c) => {
94
+ if (r.outLen < MAX_OUT) {
95
+ r.out.push(c);
96
+ r.outLen += c.length;
97
+ }
98
+ });
99
+ child.stderr?.on('data', (c) => {
100
+ if (r.err.length < 65536) r.err += c.toString('utf8');
101
+ });
102
+ const kill = (sig) => {
103
+ try {
104
+ child.kill(sig);
105
+ } catch {}
106
+ };
107
+ r.timer = setTimeout(() => {
108
+ r.timedOut = true;
109
+ log.warn('live run timed out — stopping it', { job: job.id, agent: agent.id, timeout_ms: timeoutMs });
110
+ kill('SIGTERM');
111
+ r.killTimer = setTimeout(() => kill('SIGKILL'), grace);
112
+ r.killTimer.unref?.();
113
+ }, timeoutMs);
114
+ r.timer.unref?.();
115
+ const finish = (exitCode, signal, error = null) => {
116
+ if (r.settled) return;
117
+ r.settled = true;
118
+ clearTimeout(r.timer);
119
+ clearTimeout(r.killTimer);
120
+ running.delete(agent.id);
121
+ const stdout = Buffer.concat(r.out).toString('utf8');
122
+ const res = resultTextOf(stdout);
123
+ const ms = now() - startedAt;
124
+ writeLog(job.id, attempt, { job: job.id, agent: agent.id, attempt, started_at: new Date(startedAt).toISOString(), ms, exit_code: exitCode, signal, timed_out: r.timedOut, error, argv: [plan.argv[0], '-p', '<prompt: konsilium.devops-job/1>', ...plan.argv.slice(3)], cwd: plan.cwd, env_names: Object.keys(liveEnvOf(env, agent, job.id)).sort(), result_tail: maskSecrets(res.text.slice(-LOG_TAIL)), stderr_tail: maskSecrets(r.err.slice(-LOG_TAIL)) });
125
+ log.info('live run finished', { job: job.id, agent: agent.id, exit_code: exitCode, signal, timed_out: r.timedOut, ms });
126
+ r.resolve?.();
127
+ try {
128
+ o.onResult({ jobId: job.id, agentId: agent.id, attempt, exitCode, signal, timedOut: r.timedOut, text: res.text, isError: res.isError, error, ms });
129
+ } catch (e) {
130
+ log.error('live result handler failed', { job: job.id, error: maskSecrets(e?.message ?? e) });
131
+ }
132
+ };
133
+ r.done = new Promise((res) => (r.resolve = res));
134
+ child.on('error', (e) => finish(null, null, `spawn ${e?.code ?? 'error'}`));
135
+ child.on('close', (code, signal) => finish(code, signal));
136
+ log.info('live run started', { job: job.id, agent: agent.id, attempt, cwd: plan.cwd, pid: child.pid ?? null, timeout_ms: timeoutMs });
137
+ return { ok: true, pid: child.pid ?? null };
138
+ }
139
+
140
+ return {
141
+ start,
142
+ busy: (agentId) => running.has(agentId),
143
+ list: () => [...running.entries()].map(([agent, r]) => ({ agent, job: r.jobId, attempt: r.attempt, pid: r.child.pid ?? null, started_at: new Date(r.startedAt).toISOString() })),
144
+ /** Graceful stop of the service: SIGTERM every run (SIGKILL after the grace), wait for them. Their leases stay. */
145
+ async stop() {
146
+ const all = [...running.values()];
147
+ for (const r of all) {
148
+ try {
149
+ r.child.kill('SIGTERM');
150
+ } catch {}
151
+ const t = setTimeout(() => {
152
+ try {
153
+ r.child.kill('SIGKILL');
154
+ } catch {}
155
+ }, grace);
156
+ t.unref?.();
157
+ }
158
+ await Promise.all(all.map((r) => r.done));
159
+ },
160
+ };
161
+ }
@@ -0,0 +1,150 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §5): the agent registry.
2
+ // Agents are the slots of the config (id, provider, mode, workspace, projects, capabilities) — a running process alone is
3
+ // never a free agent. The state of a slot comes from facts:
4
+ // 1. the orchestrator's own lease (it gave the slot a job) → running
5
+ // 2. the provider adapter says the slot cannot run here (workspace missing, provider absent) → unavailable
6
+ // 3. the turn monitor of #470 in the slot's workspace (read-only, its on-disk contract
7
+ // konsilium.agent-event/1: ~/.local/state/konsilium-mcp/<sha1(workspace)>/turnmonitor/{journal.jsonl,open.json})
8
+ // and the agent.* hints of the bus for the same session, whichever is newer:
9
+ // an open request to the person (open.json) / NEEDS_* / *_QUESTION / USER_INPUT_REQUIRED → waiting_for_user
10
+ // ERROR / BLOCKED → blocked
11
+ // RESOLVED (the person answered; the agent goes on) → running
12
+ // TURN_COMPLETED / TASK_COMPLETED / DEPLOY_REQUIRED (not blocking) within idleTtlMs → idle
13
+ // nothing seen, or the last fact is older than idleTtlMs → unavailable
14
+ // «headless» slots (a process the orchestrator itself would own) are idle unless leased.
15
+ // G4 (2026-11-24): with @consilium108/mcp ≥ 0.11.1 the facts come from its read-only export `@consilium108/mcp/turnmonitor`
16
+ // (turnMonitorState — the monitor's own reading, incl. TURN_STARTED of G3); without it (older host package, not
17
+ // installed) the files are read directly as before.
18
+ import { createHash } from 'node:crypto';
19
+ import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from 'node:fs';
20
+ import { homedir } from 'node:os';
21
+ import { join, resolve } from 'node:path';
22
+
23
+ export const AGENT_STATES = ['idle', 'running', 'waiting_for_user', 'blocked', 'unavailable'];
24
+ const TAIL_BYTES = 256 * 1024;
25
+ const WAITING = new Set(['NEEDS_APPROVAL', 'NEEDS_DECISION', 'OPEN_QUESTION', 'INTERACTIVE_QUESTION', 'USER_INPUT_REQUIRED']);
26
+ const IDLE = new Set(['TURN_COMPLETED', 'TASK_COMPLETED']);
27
+
28
+ /** = stateDirOf of @consilium108/mcp (src/sync/state.js) + /turnmonitor: where #470 keeps the state of a workspace. */
29
+ export function turnMonitorDirOf(workspace, { env = process.env, home = homedir() } = {}) {
30
+ const base = env.XDG_STATE_HOME || join(home, '.local', 'state');
31
+ return join(base, 'konsilium-mcp', createHash('sha1').update(resolve(workspace)).digest('hex'), 'turnmonitor');
32
+ }
33
+
34
+ const readJson = (f, d) => {
35
+ try {
36
+ return JSON.parse(readFileSync(f, 'utf8'));
37
+ } catch {
38
+ return d;
39
+ }
40
+ };
41
+
42
+ /** The tail of journal.jsonl → parsed events (newest last). Never reads more than TAIL_BYTES. */
43
+ export function readTurnJournal(dir) {
44
+ const f = join(dir, 'journal.jsonl');
45
+ if (!existsSync(f)) return [];
46
+ let fd;
47
+ try {
48
+ fd = openSync(f, 'r');
49
+ const size = fstatSync(fd).size;
50
+ const len = Math.min(size, TAIL_BYTES);
51
+ const buf = Buffer.alloc(len);
52
+ readSync(fd, buf, 0, len, size - len);
53
+ const lines = buf.toString('utf8').split('\n');
54
+ if (size > len) lines.shift(); // a cut first line
55
+ const out = [];
56
+ for (const l of lines) {
57
+ if (!l) continue;
58
+ try {
59
+ const e = JSON.parse(l);
60
+ if (e && (e.schema === 'konsilium.agent-event/1' || e.kind === 'resolution')) out.push(e);
61
+ } catch {}
62
+ }
63
+ return out;
64
+ } catch {
65
+ return [];
66
+ } finally {
67
+ if (fd !== undefined) closeSync(fd);
68
+ }
69
+ }
70
+
71
+ /** The state of one session from the facts of the turn monitor: { state, at, reason } | null (nothing known). */
72
+ export function sessionStateOf(events, open, sessionId) {
73
+ if (Object.values(open ?? {}).some((v) => v?.session_id === sessionId)) {
74
+ const o = Object.values(open).find((v) => v?.session_id === sessionId);
75
+ return { state: 'waiting_for_user', at: o.asked_at ?? null, reason: `turn monitor: open request (${o.type ?? o.kind ?? 'question'})` };
76
+ }
77
+ const mine = events.filter((e) => e.session_id === sessionId);
78
+ const last = mine[mine.length - 1];
79
+ if (!last) return null;
80
+ const at = last.at ?? last.detected_at ?? null;
81
+ if (last.type === 'TURN_STARTED') return { state: 'running', at, reason: `turn monitor: turn started (${last.trigger ?? 'lifecycle'})` };
82
+ if (last.type === 'RESOLVED') return { state: 'running', at, reason: 'turn monitor: the person answered; the agent goes on' };
83
+ if (last.type === 'ERROR' || last.type === 'BLOCKED') return { state: 'blocked', at, reason: `turn monitor: ${last.type}` };
84
+ if (WAITING.has(last.type) || last.blocking) return { state: 'waiting_for_user', at, reason: `turn monitor: ${last.type}${last.blocking ? ' (waits for the person)' : ''}` };
85
+ if (IDLE.has(last.type) || last.type === 'DEPLOY_REQUIRED') return { state: 'idle', at, reason: `turn monitor: ${last.type} — the turn ended` };
86
+ return { state: 'running', at, reason: `turn monitor: ${last.type}` };
87
+ }
88
+
89
+ /**
90
+ * @param {{ agents: object[], adapters: Record<string, object>, idleTtlMs: number, now?: () => number,
91
+ * readJournal?: (dir: string) => object[], readOpen?: (dir: string) => object, dirOf?: (ws: string) => string,
92
+ * turnMonitor?: { turnMonitorState: Function } | null }} o turnMonitor — the `@consilium108/mcp/turnmonitor` module (G4)
93
+ */
94
+ export function createRegistry({ agents, adapters, idleTtlMs, now = Date.now, readJournal = readTurnJournal, readOpen = (d) => readJson(join(d, 'open.json'), {}), dirOf = (ws) => turnMonitorDirOf(ws), turnMonitor = null }) {
95
+ const hints = new Map(); // session → { state, at, reason }
96
+
97
+ function stateOf(agent, leasedBy) {
98
+ if (leasedBy) return { state: 'running', reason: `orchestrator: job ${leasedBy}` };
99
+ const ad = adapters[agent.provider];
100
+ if (!ad) return { state: 'unavailable', reason: `no adapter for provider «${agent.provider}»` };
101
+ const avail = ad.available(agent);
102
+ if (!avail.ok) return { state: 'unavailable', reason: avail.reason };
103
+ if (agent.mode === 'headless') return { state: 'idle', reason: 'headless slot, not leased' };
104
+ let session = agent.sessionId;
105
+ let st = null;
106
+ let viaExport = false;
107
+ if (turnMonitor?.turnMonitorState) {
108
+ try {
109
+ const tm = turnMonitor.turnMonitorState(agent.workspace, { provider: agent.provider, sessionId: agent.sessionId ?? null });
110
+ session = session ?? tm.latest ?? null;
111
+ const one = tm.sessions.find((x) => x.session_id === session);
112
+ st = one?.state ? { state: one.state, at: one.at, reason: one.reason } : null;
113
+ viaExport = true;
114
+ } catch {
115
+ viaExport = false; // fall back to the files
116
+ }
117
+ }
118
+ if (!viaExport) {
119
+ const dir = dirOf(agent.workspace);
120
+ const events = readJournal(dir);
121
+ const open = readOpen(dir);
122
+ if (!session) {
123
+ const withSession = events.filter((e) => e.session_id && (!e.provider || e.provider === agent.provider));
124
+ session = withSession[withSession.length - 1]?.session_id ?? null;
125
+ }
126
+ if (session) st = sessionStateOf(events, open, session);
127
+ }
128
+ if (!session) return { state: 'unavailable', reason: 'turn monitor: no session seen in this workspace (is #470 on? KONSILIUM_TURN_MONITOR=on)' };
129
+ const h = hints.get(session);
130
+ if (h && (!st || Date.parse(h.at ?? 0) > Date.parse(st.at ?? 0))) st = h;
131
+ if (!st) return { state: 'unavailable', session, reason: 'turn monitor: nothing known about the session' };
132
+ if (st.state === 'idle' && st.at && now() - Date.parse(st.at) > idleTtlMs) return { state: 'unavailable', session, at: st.at, reason: `last turn ended more than ${Math.round(idleTtlMs / 60_000)} min ago — not counted as free` };
133
+ return { ...st, session };
134
+ }
135
+
136
+ return {
137
+ hint(session, state, at, reason) {
138
+ hints.set(session, { state, at: at ?? new Date(now()).toISOString(), reason: reason ?? `bus: ${state}` });
139
+ },
140
+ /** leases: Map agentId → jobId. → [{ ...agent, state, reason, session }] */
141
+ snapshot(leases = new Map()) {
142
+ return agents.map((a) => ({ id: a.id, provider: a.provider, mode: a.mode, dispatch: a.dispatch ?? 'dry_run', workspace: a.workspace, projects: a.projects, capabilities: a.capabilities, ...stateOf(a, leases.get(a.id) ?? null) }));
143
+ },
144
+ };
145
+ }
146
+
147
+ /** A free compatible agent for a job, or null. Prefers an agent that serves the target's project first, then by config order. */
148
+ export function pickAgent(snapshot, job, taken = new Set()) {
149
+ return snapshot.find((a) => a.state === 'idle' && !taken.has(a.id) && a.capabilities.includes(job.kind) && (a.projects.includes(job.projectId) || a.projects.includes(job.eventProjectId))) ?? null;
150
+ }
@@ -0,0 +1,177 @@
1
+ // generated by Claude (Opus 5.5), 2026-11-24; Konsilium TASK-P37-486, SDD-P37-160 (spec §3.3): the event source — the
2
+ // SAME delivery as the local MCP sync (#437), no new transport: per project
3
+ // • catch-up through get_events from the stored cursor (start, a heartbeat head beyond the cursor, cursor_expired);
4
+ // • then the SSE stream projectEvents (types agent.* and deploy.* — G1) via subscribeSse of @nativemind108/mcp;
5
+ // • the long poll of get_events (wait_seconds 25) when no SSE is given or the server answers 404/400 (subscriptions off).
6
+ // The cursor moves only AFTER the event was handled (at-least-once); duplicates are dropped by the caller's seen set.
7
+ // First start without a cursor: the journal (last 7 days) is read as a BASELINE — the cursor moves to its head, state
8
+ // hints are kept, nothing is enqueued (old DEPLOY_REQUIRED signals never start work).
9
+ import { normalizeBusEvent } from './events.js';
10
+
11
+ const backoff = (n) => Math.min(60_000, 1000 * 2 ** Math.min(n, 6));
12
+
13
+ /**
14
+ * @param {{ api: object, store: object, projects: number[], handle: (ev: object, o: { baseline: boolean }) => Promise<void>,
15
+ * types?: string[], log?: object, sleep?: (ms: number, signal?: AbortSignal) => Promise<void>, sse?: boolean,
16
+ * pollWaitSec?: number }} o
17
+ */
18
+ export function createEventSource(o) {
19
+ const log = o.log ?? {};
20
+ const types = o.types ?? ['agent.', 'deploy.']; // deploy.*: G1 (2026-11-24) — the deploy lifecycle instead of polling
21
+ const sleep = o.sleep ?? ((ms, signal) => new Promise((r) => {
22
+ const t = setTimeout(r, ms);
23
+ signal?.addEventListener('abort', () => (clearTimeout(t), r()), { once: true });
24
+ }));
25
+ const stop = new AbortController();
26
+ const per = new Map(); // pid → { transport, state, error, lastEventAt, events, sub }
27
+ const st = (pid) => {
28
+ if (!per.has(pid)) per.set(pid, { transport: null, state: 'stopped', error: null, lastEventAt: null, events: 0, sub: null, polling: false, notFound: 0 });
29
+ return per.get(pid);
30
+ };
31
+ const chains = new Map(); // pid → a promise chain: events of one project are handled one at a time, in order
32
+
33
+ function serial(pid, fn) {
34
+ const prev = chains.get(pid) ?? Promise.resolve();
35
+ const next = prev.then(fn, fn);
36
+ chains.set(pid, next.catch(() => {}));
37
+ return next;
38
+ }
39
+
40
+ async function handleRaw(pid, raw, baseline = false, moveCursor = true) {
41
+ const ev = normalizeBusEvent(raw);
42
+ if (!ev) return;
43
+ // an event behind the cursor (a replayed / duplicated delivery) still goes to the handler: its seen set drops it
44
+ await o.handle({ ...ev, projectId: ev.projectId ?? pid }, { baseline });
45
+ const s = st(pid);
46
+ s.lastEventAt = new Date().toISOString();
47
+ s.events++;
48
+ if (moveCursor) o.store.cursor.set(pid, ev.cursor);
49
+ }
50
+
51
+ /** An SSE event is a doorbell: the journal is read from the cursor (so a gap — a lost message — is read too). If the
52
+ * journal is unreachable, the pushed event is handled now WITHOUT moving the cursor (the next catch-up re-reads it). */
53
+ async function onPushed(pid, raw) {
54
+ try {
55
+ await catchUpNow(pid);
56
+ } catch (e) {
57
+ st(pid).error = e?.code ?? e?.message;
58
+ await serial(pid, () => handleRaw(pid, raw, false, false));
59
+ }
60
+ }
61
+
62
+ /** Read the journal after the stored cursor, in pages, oldest first. */
63
+ function catchUpNow(pid) {
64
+ return serial(pid, async () => {
65
+ const baseline = o.store.cursor.get(pid) == null;
66
+ let cursor = o.store.cursor.get(pid) ?? 0;
67
+ for (let i = 0; i < 100; i++) {
68
+ const r = await o.api.events(pid, cursor, { waitSeconds: 0, limit: 200, types });
69
+ const evs = r?.events ?? [];
70
+ for (const e of evs) await handleRaw(pid, e, baseline);
71
+ const next = Number(r?.next_cursor ?? cursor);
72
+ if (!evs.length || next <= cursor) {
73
+ if (Number.isFinite(next)) o.store.cursor.set(pid, Math.max(next, 1));
74
+ break;
75
+ }
76
+ cursor = next;
77
+ }
78
+ if (baseline && o.store.cursor.get(pid) == null) o.store.cursor.set(pid, 1);
79
+ });
80
+ }
81
+ const catchUp = catchUpNow;
82
+
83
+ async function pollLoop(pid) {
84
+ const s = st(pid);
85
+ if (s.polling) return;
86
+ s.polling = true;
87
+ s.transport = 'get_events';
88
+ let attempt = 0;
89
+ while (!stop.signal.aborted) {
90
+ try {
91
+ const got = await serial(pid, async () => {
92
+ const r = await o.api.events(pid, o.store.cursor.get(pid) ?? 0, { waitSeconds: o.pollWaitSec ?? 25, limit: 200, types });
93
+ for (const e of r?.events ?? []) {
94
+ if (stop.signal.aborted) break;
95
+ await handleRaw(pid, e);
96
+ }
97
+ if (!(r?.events ?? []).length && r?.next_cursor != null) o.store.cursor.set(pid, Number(r.next_cursor));
98
+ return (r?.events ?? []).length;
99
+ });
100
+ s.state = 'open';
101
+ s.error = null;
102
+ attempt = 0;
103
+ // an empty answer that came back at once (a server without the long poll): never spin
104
+ if (!got) await sleep(o.pollIdleMs ?? 1000, stop.signal);
105
+ } catch (e) {
106
+ s.error = e?.code ?? e?.message ?? String(e);
107
+ if (e?.status === 401 || e?.code === 'auth_required') {
108
+ s.state = 'auth_required';
109
+ log.error?.('event source: no valid credential', { project_id: pid, code: s.error });
110
+ await sleep(60_000, stop.signal);
111
+ continue;
112
+ }
113
+ s.state = 'retrying';
114
+ log.warn?.('event source: get_events failed, retrying', { project_id: pid, code: s.error });
115
+ await sleep(backoff(attempt++), stop.signal);
116
+ }
117
+ }
118
+ s.polling = false;
119
+ }
120
+
121
+ function subscribe(pid) {
122
+ const s = st(pid);
123
+ s.transport = 'sse';
124
+ s.sub = o.api.subscribe({
125
+ projectId: pid,
126
+ types,
127
+ getCursor: () => o.store.cursor.get(pid),
128
+ cursorOf: (r) => Number(r?.data?.projectEvents?.cursor ?? NaN),
129
+ onEvent: async (r) => onPushed(pid, r?.data?.projectEvents),
130
+ onHeadAhead: async () => catchUp(pid),
131
+ onCursorExpired: async () => catchUp(pid),
132
+ onState: (state, info) => {
133
+ s.state = state;
134
+ if (info?.error) s.error = info.error;
135
+ if (state === 'open') {
136
+ s.error = null;
137
+ s.notFound = 0;
138
+ }
139
+ if (state === 'retrying' && (info?.status === 404 || info?.status === 400) && ++s.notFound >= 2 && !stop.signal.aborted) {
140
+ s.sub?.close();
141
+ s.sub = null;
142
+ log.warn?.('event source: no SSE subscriptions on the server — long poll of get_events', { project_id: pid });
143
+ void pollLoop(pid);
144
+ }
145
+ },
146
+ });
147
+ }
148
+
149
+ return {
150
+ catchUp,
151
+ onPushed,
152
+ async start() {
153
+ for (const pid of o.projects) {
154
+ try {
155
+ await catchUp(pid);
156
+ } catch (e) {
157
+ st(pid).error = e?.code ?? e?.message;
158
+ log.warn?.('event source: first catch-up failed (retried by the poll / stream)', { project_id: pid, code: st(pid).error });
159
+ }
160
+ if (o.sse !== false && o.api.subscribe) subscribe(pid);
161
+ else void pollLoop(pid);
162
+ }
163
+ },
164
+ stop() {
165
+ stop.abort();
166
+ for (const s of per.values()) {
167
+ s.sub?.close();
168
+ s.sub = null;
169
+ s.state = 'stopped';
170
+ }
171
+ },
172
+ status: () => Object.fromEntries(o.projects.map((pid) => {
173
+ const s = st(pid);
174
+ return [pid, { cursor: o.store.cursor.get(pid), transport: s.transport, state: s.state, error: s.error, last_event_at: s.lastEventAt, events: s.events }];
175
+ })),
176
+ };
177
+ }