compivia 0.0.0-stage → 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,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));
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "compivia",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1128",
4
+ "description": "Compivia CLI wrapper: installs and proxies self-host engine components",
5
+ "keywords": [
6
+ "compivia",
7
+ "cli",
8
+ "engine",
9
+ "self-host"
10
+ ],
11
+ "engines": {
12
+ "node": ">=24"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/compivia/compivia-core-dev.git",
17
+ "directory": "packages/cli"
18
+ },
19
+ "type": "module",
20
+ "license": "FSL-1.1-ALv2",
21
+ "bin": {
22
+ "compivia": "bin/compivia.mjs"
23
+ },
24
+ "files": [
25
+ "bin/",
26
+ "dist/"
27
+ ],
28
+ "scripts": {
29
+ "build": "node build.mjs",
30
+ "test": "vitest run",
31
+ "typecheck": "tsc --noEmit"
32
+ },
33
+ "devDependencies": {},
34
+ "dependencies": {},
35
+ "publishConfig": {
36
+ "registry": "https://registry.npmjs.org/",
37
+ "access": "public"
38
+ }
39
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.