@compivia/engine-host 0.0.0-placeholder.0 → 0.0.1128

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,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Compivia</title>
7
+ </head>
8
+ <body>
9
+ <h1>Compivia</h1>
10
+ <p>Dashboard UI is on its way. The read-model API is served under <code>/api</code>.</p>
11
+ </body>
12
+ </html>
@@ -0,0 +1,192 @@
1
+ // SPDX-License-Identifier: FSL-1.1-ALv2
2
+ // Plain-JS ESM entry плагина-хоста (child процесс): грузит вклад только из
3
+ // --dir, говорит с runner'ом по IPC process.send (спека #410 §4.8).
4
+
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { pathToFileURL } from "node:url";
8
+
9
+ const SUPPORTED_API_VERSIONS = [1]; // дубликат SUPPORTED_PLUGIN_API_VERSIONS (@compivia/plugin-sdk)
10
+
11
+ function fail(message) {
12
+ process.stderr.write(`${message}\n`);
13
+ process.exit(1);
14
+ }
15
+
16
+ function parseArgv(argv) {
17
+ let dir;
18
+ let contribution;
19
+ for (let i = 0; i < argv.length; i += 1) {
20
+ if (argv[i] === "--dir") { dir = argv[i + 1]; i += 1; }
21
+ else if (argv[i] === "--contribution") { contribution = argv[i + 1]; i += 1; }
22
+ else fail(`unknown argument ${argv[i] ?? "(missing)"}`);
23
+ }
24
+ if (typeof dir !== "string" || dir === "") fail("missing --dir");
25
+ if (typeof contribution !== "string" || !/^[a-z]+:[a-z][a-z0-9-]{0,31}$/.test(contribution)) fail("missing or invalid --contribution");
26
+ return { dir, contribution };
27
+ }
28
+
29
+ const { dir, contribution } = parseArgv(process.argv.slice(2));
30
+ const sep = contribution.indexOf(":");
31
+ const kind = contribution.slice(0, sep);
32
+ const id = contribution.slice(sep + 1);
33
+ if (kind !== "harness" && kind !== "reporter") fail(`unsupported kind ${kind}`);
34
+
35
+ const manifestPath = join(dir, "package.json");
36
+ if (!existsSync(manifestPath)) fail(`package.json not found in ${dir}`);
37
+ let manifest;
38
+ let pkgVersion = "";
39
+ let pkgName = "";
40
+ try {
41
+ const pkg = JSON.parse(readFileSync(manifestPath, "utf8"));
42
+ manifest = pkg.compivia.plugin;
43
+ pkgVersion = String(pkg.version ?? "");
44
+ pkgName = String(pkg.name ?? "");
45
+ } catch (error) {
46
+ fail(`invalid plugin package: ${error && typeof error === "object" ? String(error.message) : "read error"}`);
47
+ }
48
+ if (manifest === null || typeof manifest !== "object") fail("missing compivia.plugin manifest");
49
+ if (!SUPPORTED_API_VERSIONS.includes(manifest.apiVersion)) fail(`unsupported plugin apiVersion ${JSON.stringify(manifest.apiVersion)}; supported: [${SUPPORTED_API_VERSIONS.join(", ")}]`);
50
+ const entry = (manifest.contributions ?? []).find((c) => c && c.kind === kind && c.id === id);
51
+ if (entry === undefined) fail(`contribution ${contribution} not found in manifest`);
52
+ if (typeof entry.module !== "string" || entry.module === "") fail("manifest contribution.module: expected a string");
53
+
54
+ let def;
55
+ try {
56
+ const module = await import(pathToFileURL(join(dir, entry.module)).href);
57
+ def = module.default;
58
+ } catch (error) {
59
+ fail(`module load failed: ${error && typeof error === "object" ? String(error.message).split("\n")[0] : "unknown"}`);
60
+ }
61
+ if (def === null || typeof def !== "object" || Array.isArray(def)) fail("default export: not an object");
62
+ if (def.id !== id) fail("default export: id mismatch");
63
+
64
+ const secrets = kind === "reporter" && Array.isArray(entry.secrets) ? entry.secrets : [];
65
+ function mask(text) {
66
+ let out = String(text);
67
+ for (const name of secrets) {
68
+ const value = process.env[name];
69
+ if (value !== undefined && value !== "") out = out.split(value).join("***");
70
+ }
71
+ return out;
72
+ }
73
+
74
+ function send(message) {
75
+ if (process.send === undefined || process.channel === null) return;
76
+ process.send(message);
77
+ }
78
+
79
+ send({ type: "ready", contribution: { kind, id, package: pkgName, version: process.env.COMPIVIA_PLUGIN_VERSION ?? pkgVersion, apiVersion: manifest.apiVersion } });
80
+
81
+ let initOptions = {};
82
+ let disposed = false;
83
+
84
+ function makeLogger() {
85
+ return {
86
+ debug: (msg, fields) => send({ type: "log", level: "debug", msg: mask(msg), ...(fields !== undefined ? { fields } : {}) }),
87
+ info: (msg, fields) => send({ type: "log", level: "info", msg: mask(msg), ...(fields !== undefined ? { fields } : {}) }),
88
+ warn: (msg, fields) => send({ type: "log", level: "warn", msg: mask(msg), ...(fields !== undefined ? { fields } : {}) }),
89
+ error: (msg, fields) => send({ type: "log", level: "error", msg: mask(msg), ...(fields !== undefined ? { fields } : {}) }),
90
+ };
91
+ }
92
+
93
+ async function initReporter() {
94
+ const env = Object.fromEntries(secrets.map((name) => [name, typeof process.env[name] === "string" ? process.env[name] : ""]));
95
+ const ctx = { subscription: `plugin:${kind}:${id}`, options: initOptions, env, logger: makeLogger() };
96
+ if (typeof def.init === "function") await def.init(ctx);
97
+ }
98
+
99
+ process.on("message", (message) => {
100
+ if (message === null || typeof message !== "object") {
101
+ fail("protocol violation");
102
+ return;
103
+ }
104
+ if (disposed) return;
105
+ if (message.type === "dispose") {
106
+ void (async () => {
107
+ disposed = true;
108
+ try {
109
+ if (kind === "reporter" && typeof def.dispose === "function") {
110
+ const timer = setTimeout(() => process.exit(0), 5000);
111
+ timer.unref?.();
112
+ await def.dispose();
113
+ }
114
+ } catch { /* dispose не должен валить хост */ }
115
+ process.exit(0);
116
+ })().catch(() => {});
117
+ return;
118
+ }
119
+ // FIFO: init полностью завершается до первого call — плагин с async init
120
+ // никогда не вызывается в неинициализированном состоянии.
121
+ messageQueue = messageQueue.then(() => handleMessage(message)).catch(() => fail("dispatcher failure"));
122
+ });
123
+
124
+ let messageQueue = Promise.resolve();
125
+
126
+ async function handleMessage(parsed) {
127
+ if (parsed.type === "init") {
128
+ try {
129
+ initOptions = parsed.options ?? {};
130
+ if (kind === "reporter") await initReporter();
131
+ return;
132
+ } catch (error) {
133
+ send({ type: "failure", requestId: null, class: "plugin_error", message: mask(String(error?.message ?? error)) });
134
+ return;
135
+ }
136
+ }
137
+ if (parsed.type !== "call") fail(`unknown message type ${String(parsed.type)}`);
138
+ const { requestId, method, timeoutMs } = parsed;
139
+ const harnessMethods = ["detect", "launch", "classifyLine", "locateSession", "finalOf", "checksOf", "normalizeLine", "classify", "finalFromOutput"];
140
+ const reporterMethods = ["probe"];
141
+ const allowed = kind === "harness" ? harnessMethods : reporterMethods;
142
+ if (!allowed.includes(method)) {
143
+ send({ type: "failure", requestId, class: "method_unknown", message: `method ${method} is not implemented by ${kind} contributions` });
144
+ return;
145
+ }
146
+ // Abort-таймеры собираются и снимаются по завершении вызова.
147
+ const timers = [];
148
+ const abortSignalAfter = (ms) => {
149
+ const controller = new AbortController();
150
+ const timer = setTimeout(() => controller.abort(), ms ?? 30_000);
151
+ timer.unref?.();
152
+ timers.push(timer);
153
+ return controller.signal;
154
+ };
155
+ const dispatch = async () => {
156
+ switch (method) {
157
+ case "detect": return def.detect({ logger: makeLogger(), signal: abortSignalAfter(timeoutMs) });
158
+ case "launch": return def.launch(parsed.params);
159
+ case "classifyLine": return def.classifyLine(parsed.params);
160
+ case "locateSession": return def.locateSession(parsed.params);
161
+ case "finalOf": return def.finalOf(parsed.params?.location, parsed.params?.turn);
162
+ case "checksOf": {
163
+ if (typeof def.checksOf !== "function") return [];
164
+ return def.checksOf(parsed.params?.location ?? parsed.params);
165
+ }
166
+ case "normalizeLine": return def.normalizeLine(parsed.params?.sessionId, parsed.params?.line);
167
+ case "classify": return def.classify(parsed.params);
168
+ case "finalFromOutput": return def.finalFromOutput(parsed.params);
169
+ case "probe": return def.probe({ subscription: `plugin:${kind}:${id}`, options: initOptions, env: reporterEnv(), logger: makeLogger() }, abortSignalAfter(timeoutMs));
170
+ default: return { __unknownMethod: true };
171
+ }
172
+ };
173
+ try {
174
+ const result = await dispatch();
175
+ if (result !== undefined && result !== null && typeof result === "object" && result.__unknownMethod === true) {
176
+ send({ type: "failure", requestId, class: "method_unknown", message: `method ${method} is not implemented by this contribution` });
177
+ return;
178
+ }
179
+ send({ type: "result", requestId, result });
180
+ } catch (error) {
181
+ send({ type: "failure", requestId, class: "plugin_error", message: mask(String(error?.message ?? error).split("\n")[0]) });
182
+ } finally {
183
+ for (const timer of timers.splice(0)) clearTimeout(timer);
184
+ }
185
+ }
186
+
187
+ function reporterEnv() {
188
+ return Object.fromEntries(secrets.map((name) => [name, typeof process.env[name] === "string" ? process.env[name] : ""]));
189
+ }
190
+
191
+ process.on("disconnect", () => process.exit(0));
192
+ process.on("SIGTERM", () => process.exit(0));
@@ -0,0 +1,79 @@
1
+ // SPDX-License-Identifier: FSL-1.1-ALv2
2
+ // Старт-время клайма обязано делить базу с пробой хоста: сверка личности
3
+ // сравнивает клайм с пробой через допуск ±2 c, а оценка `Date.now() − uptime()`
4
+ // расходится с ядерной базой Linux-пробы (btime + starttime/CLK_TCK) при
5
+ // ступеньках часов (NTP на pi-раннерах, паузы VM) — тогда stop не признаёт
6
+ // живой процесс и чистит запись, оставляя агента-сироту (регрессия R2, CI
7
+ // ubuntu 2026-10-23). Вне /proc клайм строится из ps etime — той же базы,
8
+ // что у macOS-пробы.
9
+ import { spawnSync } from "node:child_process";
10
+ import { readFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+
13
+ let clockTicksCache = null;
14
+
15
+ // getconf может зависнуть — таймаут уводит в fallback (100), не блокируя bootstrap.
16
+ function clockTicks() {
17
+ if (clockTicksCache !== null) return clockTicksCache;
18
+ try {
19
+ const { stdout } = spawnSync("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 1000 });
20
+ const value = Number(stdout?.trim());
21
+ clockTicksCache = Number.isSafeInteger(value) && value > 0 ? value : 100;
22
+ } catch {
23
+ clockTicksCache = 100;
24
+ }
25
+ return clockTicksCache;
26
+ }
27
+
28
+ function tryRead(path) {
29
+ try {
30
+ return readFileSync(path, "utf8");
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ // /proc-база: starttime — поле 22, после state это fields[19]; comm может
37
+ // содержать пробелы и скобки — отсчёт от последней ')'. Тики ленивые:
38
+ // getconf спавнится только когда чтение /proc удалось и нужен пересчёт.
39
+ function procStartedAt(pid, root, ticksOf) {
40
+ const raw = tryRead(join(root, "proc", String(pid), "stat"));
41
+ if (raw === null) return null;
42
+ const close = raw.lastIndexOf(")");
43
+ if (close < 0) return null;
44
+ const fields = raw.slice(close + 2).split(" ");
45
+ const startTicks = Number(fields[19]);
46
+ const btime = /^btime\s+(\d+)$/m.exec(tryRead(join(root, "proc", "stat")) ?? "");
47
+ if (!Number.isSafeInteger(startTicks) || btime === null) return null;
48
+ return new Date((Number(btime[1]) + startTicks / ticksOf()) * 1000).toISOString();
49
+ }
50
+
51
+ // etime ps ([[DD-]hh:]mm:ss) — локале-независимо.
52
+ function etimeSeconds(raw) {
53
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(raw.trim());
54
+ if (match === null) return null;
55
+ const days = match[1] !== undefined ? Number(match[1]) : 0;
56
+ const hours = match[2] !== undefined ? Number(match[2]) : 0;
57
+ const minutes = Number(match[3]);
58
+ const seconds = Number(match[4]);
59
+ if ([days, hours, minutes, seconds].some((value) => !Number.isSafeInteger(value) || value < 0)) return null;
60
+ return ((days * 24 + hours) * 60 + minutes) * 60 + seconds;
61
+ }
62
+
63
+ // ps etime — та же now-база, что у macOS-пробы; ps недоступен — null.
64
+ function psStartedAt(pid) {
65
+ const run = spawnSync("ps", ["-o", "etime=", "-p", String(pid)], { encoding: "utf8", timeout: 1000 });
66
+ const seconds = run.status === 0 ? etimeSeconds(run.stdout ?? "") : null;
67
+ return seconds === null ? null : new Date(Date.now() - seconds * 1000).toISOString();
68
+ }
69
+
70
+ /** Старт-время процесса в ISO: /proc-база (Linux), иначе ps etime (та же база,
71
+ * что у macOS-пробы); null — вывел не удалось, вызывающий падает на оценку.
72
+ * Явный root выключает ps-fallback: так проверяется семантика /proc в тестах. */
73
+ export function kernelStartedAt(pid, opts = {}) {
74
+ const root = opts.root ?? "/";
75
+ const fromProc = procStartedAt(pid, root, () => opts.clockTicks ?? clockTicks());
76
+ if (fromProc !== null) return fromProc;
77
+ if (opts.root !== undefined) return null;
78
+ return psStartedAt(pid);
79
+ }
@@ -0,0 +1,194 @@
1
+ // SPDX-License-Identifier: FSL-1.1-ALv2
2
+ // Commit our identity before exec replaces this process (same PID/session).
3
+ // No parent-owned pipe or environment serialization: survives parent SIGKILL.
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import { accessSync, constants, openSync, readSync, closeSync, writeSync } from "node:fs";
6
+ import { basename } from "node:path";
7
+ import { kernelStartedAt } from "./proc/claim-started-at.mjs";
8
+
9
+ // Sidecar-лог (#601 spec §5.6): launcher спавнится со stdio 'ignore', поэтому
10
+ // записи нельзя доставить stdout'ом; pipe-альтернатива отклонена (fds
11
+ // наследуются через execve — риск EPIPE/блокировки агента). JSONL, O_APPEND,
12
+ // один writeSync на запись; падение sidecar не меняет exit-код. Редакции
13
+ // секретов здесь нет — в записи идут только безопасные поля каталога
14
+ // (run_id, process_id, mode, file — basename, err {name, message, code});
15
+ // intent.token, значения env и содержимое реестра — никогда.
16
+ function openSidecarLog(registryPath) {
17
+ try { return openSync(`${registryPath}.launcher.log`, "a", 0o600); } catch { return null; }
18
+ }
19
+
20
+ function log(sidecar, level, msg, fields) {
21
+ if (sidecar === null) return;
22
+ const entry = { ts: new Date().toISOString(), level, msg, component: "runner.launcher", ...fields };
23
+ try { writeSync(sidecar, `${JSON.stringify(entry)}\n`); } catch { /* sidecar не влияет на exit-код */ }
24
+ }
25
+
26
+ function errorFields(error, includeMessage = true) {
27
+ // Формат err как у единого логгера: {name, message, code}. message ошибок
28
+ // node:sqlite/fs не содержит transcript, но сообщение SyntaxError от
29
+ // JSON.parse(rawArgs) может включить фрагмент сырых аргументов — поэтому
30
+ // на пути битых args message не пишется вовсе.
31
+ return {
32
+ name: error instanceof Error ? error.constructor.name : typeof error,
33
+ ...(includeMessage ? { message: error instanceof Error ? error.message : String(error) } : {}),
34
+ code: typeof error?.code === "string" ? error.code : null,
35
+ };
36
+ }
37
+
38
+ function terminateExit(sidecar, code) {
39
+ try { closeSync(sidecar); } catch { /* очистка перед exit */ }
40
+ process.exit(code);
41
+ }
42
+
43
+ const [rawIntent, mode, file, rawArgs, bootstrapPrefix] = process.argv.slice(2);
44
+ // intent разбирается первым: без него неизвестен registryPath — sidecar не
45
+ // открывается, и этот путь (как раньше) не логирует ничего: только exit.
46
+ let intent;
47
+ try {
48
+ intent = JSON.parse(rawIntent);
49
+ } catch {
50
+ process.exit(1);
51
+ }
52
+ const intentFields = { run_id: intent.runId, process_id: intent.processId, mode };
53
+ const sidecar = openSidecarLog(intent.registryPath);
54
+
55
+ // TSV 121: битые args — отказ ввода; содержимое rawArgs не логируется.
56
+ let args;
57
+ try {
58
+ args = JSON.parse(rawArgs);
59
+ } catch (error) {
60
+ log(sidecar, "error", "launcher.invalid_argv", { ...intentFields, field: "args", err: errorFields(error, false) });
61
+ terminateExit(sidecar, 1);
62
+ }
63
+ void args;
64
+
65
+ let db;
66
+ const claimStartedAt = Date.now();
67
+ try {
68
+ db = new DatabaseSync(intent.registryPath);
69
+ } catch (error) {
70
+ // TSV 122: открытие реестра — внешняя операция; причина — в sidecar.
71
+ log(sidecar, "error", "launcher.registry_open_failed", { ...intentFields, err: errorFields(error) });
72
+ terminateExit(sidecar, 1);
73
+ }
74
+ db.exec("PRAGMA busy_timeout = 3000");
75
+ // Клайм до транзакции: значение зависит только от ядра/часов, а spawnSync
76
+ // внутри BEGIN IMMEDIATE удлинял бы write-лок реестра на латентность subprocess.
77
+ const startedAt = kernelStartedAt(process.pid)
78
+ ?? new Date(Date.now() - process.uptime() * 1000).toISOString();
79
+ try {
80
+ db.exec("BEGIN IMMEDIATE");
81
+ } catch (error) {
82
+ // TSV 123: транзакция не открылась — ROLLBACK не нужен.
83
+ log(sidecar, "error", "launcher.claim_failed", { ...intentFields, err: errorFields(error), duration_ms: Date.now() - claimStartedAt, rollback_ok: false });
84
+ terminateExit(sidecar, 1);
85
+ }
86
+ let registeredHarness = null;
87
+ let registeredPending = false;
88
+ try {
89
+ // База пробы, не оценка: расхождение клайма с /proc-базой при ступеньках
90
+ // часов валило сверку личности (±2 c) — stop не признавал живой процесс
91
+ // (регрессия R2, CI ubuntu 2026-10-23). Оценка — fallback без /proc и ps.
92
+ if (mode === "agent") {
93
+ const result = db.prepare("UPDATE agent_processes SET agent_pid = ?, agent_started_at = ?, launch_pending = 0 WHERE process_id = ? AND run_id = ? AND launch_pending = 1 AND agent_pid IS NULL")
94
+ .run(process.pid, startedAt, intent.processId, intent.runId);
95
+ if (result.changes === 0) {
96
+ db.exec("ROLLBACK");
97
+ db.close();
98
+ // TSV 124: клейм утерян конкурентному запуску — WARN + прежний exit(0).
99
+ log(sidecar, "warn", "launcher.agent_claim_lost", { ...intentFields });
100
+ terminateExit(sidecar, 0);
101
+ }
102
+ } else {
103
+ const reservation = db.prepare("SELECT * FROM run_reservations WHERE run_id = ? AND launch_token = ? AND process_id = ? AND phase = 'reserved'")
104
+ .get(intent.runId, intent.token, intent.processId);
105
+ if (!reservation) {
106
+ db.exec("ROLLBACK");
107
+ db.close();
108
+ // TSV 125: резервация не найдена (не наш запуск или уже снята) —
109
+ // WARN + прежний exit(0).
110
+ log(sidecar, "warn", "launcher.reservation_missing", { ...intentFields });
111
+ terminateExit(sidecar, 0);
112
+ }
113
+ const wrapper = JSON.stringify({ pid: process.pid, pgid: process.pid, cwd: process.cwd(), startedAt });
114
+ registeredPending = mode === "wrapper-pty";
115
+ db.prepare(`INSERT INTO agent_processes
116
+ (process_id, run_id, harness, wrapper_json, agent_pid, agent_started_at, started_at, session_id, transcript_path, transcript_offset, log_file, state, transcript_boundary, launch_pending, external, external_dir)
117
+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, 'running', ?, ?, ?, ?)`)
118
+ .run(intent.processId, intent.runId, reservation.harness, wrapper, registeredPending ? null : process.pid, registeredPending ? null : startedAt,
119
+ reservation.created_at, reservation.transcript_path, reservation.transcript_offset ?? 0, reservation.log_file, reservation.transcript_boundary, registeredPending ? 1 : 0,
120
+ reservation.external ? 1 : 0, reservation.external_dir ?? null);
121
+ db.prepare("UPDATE run_reservations SET phase = 'spawned', agent_pid = ?, agent_started_at = ?, wrapper_json = ? WHERE run_id = ? AND launch_token = ?")
122
+ .run(process.pid, startedAt, wrapper, intent.runId, intent.token);
123
+ registeredHarness = reservation.harness;
124
+ }
125
+ db.exec("COMMIT");
126
+ // TSV 126: клейм/регистрация зафиксированы — INFO после COMMIT.
127
+ log(sidecar, "info", "launcher.registered", {
128
+ ...intentFields,
129
+ harness: registeredHarness,
130
+ launch_pending: registeredPending,
131
+ wrapper_pid: process.pid,
132
+ duration_ms: Date.now() - claimStartedAt,
133
+ });
134
+ } catch (error) {
135
+ try {
136
+ db.exec("ROLLBACK");
137
+ } catch (rollbackError) {
138
+ // ROLLBACK над уже-откатившейся транзакцией: причина фиксируется, прежний
139
+ // исход (незапланированный throw → exit 1) не меняется.
140
+ log(sidecar, "warn", "launcher.claim_failed", { ...intentFields, err: errorFields(rollbackError), reason: "rollback_failed", duration_ms: Date.now() - claimStartedAt, rollback_ok: false });
141
+ terminateExit(sidecar, 1);
142
+ }
143
+ log(sidecar, "error", "launcher.claim_failed", { ...intentFields, err: errorFields(error), duration_ms: Date.now() - claimStartedAt, rollback_ok: true });
144
+ terminateExit(sidecar, 1);
145
+ } finally {
146
+ db.close();
147
+ }
148
+ try {
149
+ // Node24 aborts rather than throws on exec failure. Detect a missing script
150
+ // interpreter before attempting exec; other abrupt deaths stay ambiguous.
151
+ let descriptor;
152
+ try {
153
+ descriptor = openSync(file, "r");
154
+ const header = Buffer.alloc(1024);
155
+ const size = readSync(descriptor, header, 0, header.length, 0);
156
+ const interpreter = /^#!\s*(\S+)/.exec(header.subarray(0,size).toString("utf8"))?.[1];
157
+ if (interpreter) accessSync(interpreter, constants.X_OK);
158
+ } catch (error) {
159
+ if (error.code !== "EACCES" || descriptor !== undefined) throw error;
160
+ // TSV 128: файл не читается (EACCES) — проверка интерпретатора
161
+ // пропускается, фактический исход покажет exec.
162
+ log(sidecar, "debug", "launcher.interpreter_check_skipped", { ...intentFields, file: basename(file), code: error.code });
163
+ } finally {if (descriptor !== undefined) closeSync(descriptor);}
164
+ let restoredKeys = 0;
165
+ if (mode !== "wrapper-pty" && bootstrapPrefix) {
166
+ for (const key of Object.keys(process.env)) {
167
+ if (!key.startsWith(bootstrapPrefix)) continue;
168
+ process.env[key.slice(bootstrapPrefix.length)] = process.env[key];
169
+ delete process.env[key];
170
+ restoredKeys += 1;
171
+ }
172
+ }
173
+ // TSV 129: восстановленные ключи считаются; значения env не логируются (секреты).
174
+ log(sidecar, "debug", "launcher.bootstrap_env_restored", { ...intentFields, keys_count: restoredKeys });
175
+ // TSV 130: execve заменяет образ процесса — последняя запись этого инстанса.
176
+ log(sidecar, "info", "launcher.exec", { ...intentFields, file: basename(file) });
177
+ process.execve(file, [file, ...args], process.env);
178
+ } catch (error) {
179
+ // TSV 131: exec/подготовка упали — причина в sidecar и launch_failed=1 в
180
+ // реестре (корреляция по process_id; поведение прежнее).
181
+ log(sidecar, "error", "launcher.exec_failed", { ...intentFields, file: basename(file), err: errorFields(error) });
182
+ try {
183
+ const failureDb = new DatabaseSync(intent.registryPath);
184
+ try {
185
+ failureDb.exec("PRAGMA busy_timeout = 3000");
186
+ failureDb.prepare("UPDATE agent_processes SET launch_failed = 1 WHERE process_id = ? AND run_id = ?")
187
+ .run(intent.processId, intent.runId);
188
+ } finally {failureDb.close();}
189
+ } catch (failureError) {
190
+ // Отказ записи launch_failed не меняет exit-код, но причина не теряется.
191
+ log(sidecar, "warn", "launcher.launch_failed_write_failed", { ...intentFields, err: errorFields(failureError) });
192
+ }
193
+ terminateExit(sidecar, 1);
194
+ }
package/package.json CHANGED
@@ -1,12 +1,75 @@
1
1
  {
2
2
  "name": "@compivia/engine-host",
3
- "version": "0.0.0-placeholder.0",
4
- "description": "Placeholder release; the engine component for the compivia CLI is coming soon.",
5
- "license": "UNLICENSED",
3
+ "version": "0.0.1128",
4
+ "description": "Self-host Compivia engine with its runner as an installable component",
5
+ "keywords": [
6
+ "compivia",
7
+ "engine",
8
+ "engine-host",
9
+ "self-host"
10
+ ],
11
+ "engines": {
12
+ "node": ">=24"
13
+ },
6
14
  "repository": {
7
15
  "type": "git",
8
- "url": "git+https://github.com/compivia/compivia-core-dev.git"
16
+ "url": "git+https://github.com/compivia/compivia-core-dev.git",
17
+ "directory": "packages/engine-host"
18
+ },
19
+ "type": "module",
20
+ "license": "FSL-1.1-ALv2",
21
+ "bin": {
22
+ "compivia-engine-host": "bin/engine-host.mjs"
23
+ },
24
+ "files": [
25
+ "bin/",
26
+ "dist/"
27
+ ],
28
+ "compivia": {
29
+ "mode": "engine",
30
+ "wrapperCompat": ">=0.0.0",
31
+ "description": "Self-host engine with its runner",
32
+ "commands": [
33
+ {
34
+ "name": "status",
35
+ "description": "show engine status"
36
+ },
37
+ {
38
+ "name": "runs",
39
+ "description": "show active and recent runs"
40
+ },
41
+ {
42
+ "name": "queue",
43
+ "description": "show the task queue and wait reasons"
44
+ },
45
+ {
46
+ "name": "task show",
47
+ "description": "show a task or feature"
48
+ },
49
+ {
50
+ "name": "settings reload",
51
+ "description": "reload settings of a running engine"
52
+ },
53
+ {
54
+ "name": "limits enable-route",
55
+ "description": "enable a route in the user limits ledger"
56
+ },
57
+ {
58
+ "name": "runner",
59
+ "description": "run a standalone self-host runner process"
60
+ }
61
+ ]
62
+ },
63
+ "exports": {
64
+ "./compose-local": "./src/compose-local.ts"
65
+ },
66
+ "scripts": {
67
+ "build": "node build.mjs",
68
+ "test": "vitest run",
69
+ "typecheck": "tsc --noEmit"
9
70
  },
71
+ "dependencies": {},
72
+ "devDependencies": {},
10
73
  "publishConfig": {
11
74
  "registry": "https://registry.npmjs.org/",
12
75
  "access": "public"