@powerhousedao/clint 6.3.0-dev.9 → 6.4.0-next.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/dist/build-DZIv63eB.mjs +77 -0
- package/dist/build-DZIv63eB.mjs.map +1 -0
- package/dist/{build-skills-BnqGyuCH.mjs → build-skills-BNEOn-cl.mjs} +15 -6
- package/dist/build-skills-BNEOn-cl.mjs.map +1 -0
- package/dist/dist--xzirmg-.mjs +655 -0
- package/dist/dist--xzirmg-.mjs.map +1 -0
- package/dist/glob-CGjvhxgW.mjs +48 -0
- package/dist/glob-CGjvhxgW.mjs.map +1 -0
- package/dist/index-C3-HSfKb.d.mts +389 -0
- package/dist/index-C3-HSfKb.d.mts.map +1 -0
- package/dist/index.d.mts +55 -303
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -8
- package/dist/integrations/mastra/index.d.mts +248 -0
- package/dist/integrations/mastra/index.d.mts.map +1 -0
- package/dist/integrations/mastra/index.mjs +509 -0
- package/dist/integrations/mastra/index.mjs.map +1 -0
- package/dist/integrations/powerhouse/index.d.mts +4 -0
- package/dist/integrations/powerhouse/index.mjs +3 -0
- package/dist/markdown-BUeGwhbR.mjs +1588 -0
- package/dist/markdown-BUeGwhbR.mjs.map +1 -0
- package/dist/powerhouse-BDnj7kqd.mjs +1922 -0
- package/dist/powerhouse-BDnj7kqd.mjs.map +1 -0
- package/dist/{proxy-BFR8GScT.mjs → proxy-ji3EHzLn.mjs} +128 -28
- package/dist/proxy-ji3EHzLn.mjs.map +1 -0
- package/dist/remote-reactor-BQzq4yfO.mjs +69 -0
- package/dist/remote-reactor-BQzq4yfO.mjs.map +1 -0
- package/dist/{start-b7Mn2cxB.mjs → repl-Czb7u0x_.mjs} +6 -29
- package/dist/repl-Czb7u0x_.mjs.map +1 -0
- package/dist/runners/cli-runner.d.mts +339 -0
- package/dist/runners/cli-runner.d.mts.map +1 -0
- package/dist/runners/cli-runner.mjs +324 -0
- package/dist/runners/cli-runner.mjs.map +1 -0
- package/dist/runners/mastra-runner.d.mts +5 -3
- package/dist/runners/mastra-runner.d.mts.map +1 -1
- package/dist/runners/mastra-runner.mjs +10 -60
- package/dist/runners/mastra-runner.mjs.map +1 -1
- package/dist/runners/proxy-runner.d.mts +281 -0
- package/dist/runners/proxy-runner.d.mts.map +1 -0
- package/dist/runners/proxy-runner.mjs +91 -0
- package/dist/runners/proxy-runner.mjs.map +1 -0
- package/dist/schema-BEKAZGyT.mjs +47 -0
- package/dist/schema-BEKAZGyT.mjs.map +1 -0
- package/dist/{src-BebNN3xc.mjs → src-BehwgLP6.mjs} +395 -1481
- package/dist/src-BehwgLP6.mjs.map +1 -0
- package/dist/start-BHn9LIyX.mjs +37 -0
- package/dist/start-BHn9LIyX.mjs.map +1 -0
- package/dist/store-CxqB-OrX.mjs +101 -0
- package/dist/store-CxqB-OrX.mjs.map +1 -0
- package/dist/{stream-DVuufwIj.mjs → stream-BguHx7vC.mjs} +4 -2
- package/dist/{stream-DVuufwIj.mjs.map → stream-BguHx7vC.mjs.map} +1 -1
- package/dist/testing/index.d.mts +81 -0
- package/dist/testing/index.d.mts.map +1 -0
- package/dist/testing/index.mjs +131 -0
- package/dist/testing/index.mjs.map +1 -0
- package/dist/{types-CRkoD-Mm.d.mts → types-CF6GuPJd.d.mts} +241 -261
- package/dist/types-CF6GuPJd.d.mts.map +1 -0
- package/dist/types-CbHJ-ZnH.d.mts +60 -0
- package/dist/types-CbHJ-ZnH.d.mts.map +1 -0
- package/package.json +44 -25
- package/dist/build-skills-BnqGyuCH.mjs.map +0 -1
- package/dist/dist-CUltriBW.mjs +0 -1628
- package/dist/dist-CUltriBW.mjs.map +0 -1
- package/dist/drive-Bu9zoFrO.mjs +0 -85
- package/dist/drive-Bu9zoFrO.mjs.map +0 -1
- package/dist/esm-C1DOsF1a.mjs +0 -13140
- package/dist/esm-C1DOsF1a.mjs.map +0 -1
- package/dist/events-BnwGFTjv.mjs +0 -237
- package/dist/events-BnwGFTjv.mjs.map +0 -1
- package/dist/folders-BYO1Wqqb.mjs +0 -256
- package/dist/folders-BYO1Wqqb.mjs.map +0 -1
- package/dist/local-signer-EFzJV3bn.mjs +0 -128
- package/dist/local-signer-EFzJV3bn.mjs.map +0 -1
- package/dist/markdown-D-sP2zw_.mjs +0 -275
- package/dist/markdown-D-sP2zw_.mjs.map +0 -1
- package/dist/proxy-BFR8GScT.mjs.map +0 -1
- package/dist/proxy-routes-DP3ztsnS.mjs +0 -215
- package/dist/proxy-routes-DP3ztsnS.mjs.map +0 -1
- package/dist/reactor-C9VIUX1H.mjs +0 -51
- package/dist/reactor-C9VIUX1H.mjs.map +0 -1
- package/dist/runners/clint-runner.d.mts +0 -398
- package/dist/runners/clint-runner.d.mts.map +0 -1
- package/dist/runners/clint-runner.mjs +0 -519
- package/dist/runners/clint-runner.mjs.map +0 -1
- package/dist/services-9E-r0nWl.mjs +0 -999
- package/dist/services-9E-r0nWl.mjs.map +0 -1
- package/dist/src-BebNN3xc.mjs.map +0 -1
- package/dist/start-b7Mn2cxB.mjs.map +0 -1
- package/dist/subscriptions-CfiflAsI.mjs +0 -38
- package/dist/subscriptions-CfiflAsI.mjs.map +0 -1
- package/dist/switchboard-CyvOavqL.mjs +0 -57
- package/dist/switchboard-CyvOavqL.mjs.map +0 -1
- package/dist/types-CRkoD-Mm.d.mts.map +0 -1
|
@@ -1,999 +0,0 @@
|
|
|
1
|
-
import { d as resolveServiceProxyContext } from "./proxy-routes-DP3ztsnS.mjs";
|
|
2
|
-
import fs from "node:fs";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { z } from "zod";
|
|
5
|
-
import { execSync, spawn, spawnSync } from "node:child_process";
|
|
6
|
-
import net from "node:net";
|
|
7
|
-
import crypto from "node:crypto";
|
|
8
|
-
//#region src/core/schema.ts
|
|
9
|
-
const WRAPPER_TYPES = /* @__PURE__ */ new Set([
|
|
10
|
-
"default",
|
|
11
|
-
"optional",
|
|
12
|
-
"nullable"
|
|
13
|
-
]);
|
|
14
|
-
/**
|
|
15
|
-
* Extract field entries from a ZodObject schema's shape.
|
|
16
|
-
* Returns an empty array for non-object schemas.
|
|
17
|
-
*
|
|
18
|
-
* When `sensitiveKeys` is provided, those fields are marked `sensitive: true`.
|
|
19
|
-
*/
|
|
20
|
-
function getSchemaFields(schema, sensitiveKeys) {
|
|
21
|
-
if (!(schema instanceof z.ZodObject)) return [];
|
|
22
|
-
const fields = [];
|
|
23
|
-
for (const [key, field] of Object.entries(schema.shape)) fields.push({
|
|
24
|
-
key,
|
|
25
|
-
description: field.description,
|
|
26
|
-
isOptional: field.isOptional(),
|
|
27
|
-
hasDefault: field instanceof z.ZodDefault,
|
|
28
|
-
defaultValue: field instanceof z.ZodDefault ? field.def.defaultValue : void 0,
|
|
29
|
-
baseType: resolveBaseType(field),
|
|
30
|
-
sensitive: sensitiveKeys?.has(key) ?? false
|
|
31
|
-
});
|
|
32
|
-
return fields;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Resolve the base type name by unwrapping Default/Optional/Nullable wrappers.
|
|
36
|
-
* Uses .type and .def.innerType (both public Zod v4 API).
|
|
37
|
-
*/
|
|
38
|
-
function resolveBaseType(schema) {
|
|
39
|
-
let current = schema;
|
|
40
|
-
while (WRAPPER_TYPES.has(current.type) && current.def.innerType) current = current.def.innerType;
|
|
41
|
-
return current.type;
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Convert a kebab-case slug to a Title Case string.
|
|
45
|
-
* E.g. 'document-modeling' → 'Document Modeling'
|
|
46
|
-
*/
|
|
47
|
-
function slugToTitle(slug) {
|
|
48
|
-
return slug.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
|
|
49
|
-
}
|
|
50
|
-
//#endregion
|
|
51
|
-
//#region src/core/preflight.ts
|
|
52
|
-
/**
|
|
53
|
-
* Check if a TCP port is free by attempting to bind to it.
|
|
54
|
-
*/
|
|
55
|
-
function isPortFree(port) {
|
|
56
|
-
return new Promise((resolve) => {
|
|
57
|
-
const server = net.createServer();
|
|
58
|
-
server.once("error", () => resolve(false));
|
|
59
|
-
server.once("listening", () => {
|
|
60
|
-
server.close(() => resolve(true));
|
|
61
|
-
});
|
|
62
|
-
server.listen(port, "127.0.0.1");
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Check that the working directory satisfies a condition.
|
|
67
|
-
*
|
|
68
|
-
* @param test A function that receives the cwd and returns true if valid.
|
|
69
|
-
* @param message Error message on failure.
|
|
70
|
-
* @param hint Optional guidance.
|
|
71
|
-
*/
|
|
72
|
-
function checkWorkdir(test, message, hint) {
|
|
73
|
-
return (ctx) => {
|
|
74
|
-
if (test(ctx.cwd)) return { ok: true };
|
|
75
|
-
return {
|
|
76
|
-
ok: false,
|
|
77
|
-
message: `${message} (cwd: ${ctx.cwd})`,
|
|
78
|
-
hint
|
|
79
|
-
};
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* Check that a command is available on PATH, optionally matching a version.
|
|
84
|
-
*
|
|
85
|
-
* @param binary Binary name (e.g. 'ph', 'node', 'pnpm').
|
|
86
|
-
* @param options Optional version flag, version predicate, and hint.
|
|
87
|
-
*/
|
|
88
|
-
function checkCommand(binary, options) {
|
|
89
|
-
return (ctx) => {
|
|
90
|
-
try {
|
|
91
|
-
const output = execSync(`${binary} ${options?.versionFlag ?? "--version"}`, {
|
|
92
|
-
cwd: ctx.cwd,
|
|
93
|
-
timeout: 5e3,
|
|
94
|
-
stdio: [
|
|
95
|
-
"ignore",
|
|
96
|
-
"pipe",
|
|
97
|
-
"pipe"
|
|
98
|
-
],
|
|
99
|
-
env: { ...process.env }
|
|
100
|
-
}).toString().trim();
|
|
101
|
-
if (options?.versionTest && !options.versionTest(output)) return {
|
|
102
|
-
ok: false,
|
|
103
|
-
message: `${binary} version mismatch: ${output}`,
|
|
104
|
-
hint: options.hint
|
|
105
|
-
};
|
|
106
|
-
return { ok: true };
|
|
107
|
-
} catch {
|
|
108
|
-
return {
|
|
109
|
-
ok: false,
|
|
110
|
-
message: `'${binary}' not found`,
|
|
111
|
-
hint: options?.hint ?? `Install ${binary} or check your PATH`
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Check that a TCP port is available.
|
|
118
|
-
*
|
|
119
|
-
* @param port Port number, or a function that extracts it from the preflight context.
|
|
120
|
-
* @param label Human-readable name for the port (e.g. 'Connect Studio').
|
|
121
|
-
*/
|
|
122
|
-
function checkPort(port, label) {
|
|
123
|
-
return async (ctx) => {
|
|
124
|
-
const p = typeof port === "function" ? port(ctx) : port;
|
|
125
|
-
if (p === void 0) return { ok: true };
|
|
126
|
-
if (await isPortFree(p)) return { ok: true };
|
|
127
|
-
return {
|
|
128
|
-
ok: false,
|
|
129
|
-
message: `${label ? `${label} port` : "Port"} ${p} is already in use`,
|
|
130
|
-
hint: `Stop the process using port ${p}, or use a different port`
|
|
131
|
-
};
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
//#endregion
|
|
135
|
-
//#region src/core/process-platform.ts
|
|
136
|
-
/**
|
|
137
|
-
* NOTE(port): the ph-clint repo was POSIX-only. Its supervision model —
|
|
138
|
-
* `detached: true` to create a process GROUP, then `process.kill(-pid)` to
|
|
139
|
-
* fell the whole tree — does not exist on Windows: negative-pid kills throw,
|
|
140
|
-
* and `detached` forces a new console per child that even `windowsHide`
|
|
141
|
-
* cannot suppress (libuv allocates one for a detached shell). The split:
|
|
142
|
-
*
|
|
143
|
-
* - POSIX: keep the group model exactly as ported.
|
|
144
|
-
* - Windows: spawn attached + hidden; kill trees with `taskkill /T /F`,
|
|
145
|
-
* which walks the child tree the way the group kill does on POSIX.
|
|
146
|
-
*/
|
|
147
|
-
const isWindows = process.platform === "win32";
|
|
148
|
-
/** Spawn options fragment for a supervised child. */
|
|
149
|
-
function supervisedSpawnOptions() {
|
|
150
|
-
return {
|
|
151
|
-
detached: !isWindows,
|
|
152
|
-
windowsHide: true
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
/** Kill a supervised child's whole tree. `signal` only applies on POSIX;
|
|
156
|
-
* Windows tree-kill is always forceful (there are no signals to deliver). */
|
|
157
|
-
function killTree(pid, signal = "SIGTERM") {
|
|
158
|
-
if (isWindows) {
|
|
159
|
-
spawnSync("taskkill", [
|
|
160
|
-
"/PID",
|
|
161
|
-
String(pid),
|
|
162
|
-
"/T",
|
|
163
|
-
"/F"
|
|
164
|
-
], {
|
|
165
|
-
stdio: "ignore",
|
|
166
|
-
windowsHide: true
|
|
167
|
-
});
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
170
|
-
process.kill(-pid, signal);
|
|
171
|
-
}
|
|
172
|
-
//#endregion
|
|
173
|
-
//#region src/core/project-scanner.ts
|
|
174
|
-
/**
|
|
175
|
-
* Common project indicator files/dirs. When any of these exist in a folder
|
|
176
|
-
* that isn't matched by the scanner, the folder is treated as a foreign
|
|
177
|
-
* project and its subtree is pruned from the search.
|
|
178
|
-
*/
|
|
179
|
-
const PROJECT_INDICATORS = [
|
|
180
|
-
".git",
|
|
181
|
-
"package.json",
|
|
182
|
-
"node_modules",
|
|
183
|
-
"pyproject.toml",
|
|
184
|
-
"setup.py",
|
|
185
|
-
"Cargo.toml",
|
|
186
|
-
"go.mod",
|
|
187
|
-
"pom.xml",
|
|
188
|
-
"build.gradle",
|
|
189
|
-
"build.gradle.kts",
|
|
190
|
-
".sln",
|
|
191
|
-
"Gemfile",
|
|
192
|
-
"composer.json"
|
|
193
|
-
];
|
|
194
|
-
function detectType(folderPath, scanner) {
|
|
195
|
-
if (scanner.isProjectFolder(folderPath)) return "match";
|
|
196
|
-
for (const indicator of PROJECT_INDICATORS) if (fs.existsSync(path.join(folderPath, indicator))) return "mismatch";
|
|
197
|
-
return "non-project";
|
|
198
|
-
}
|
|
199
|
-
function enqueueSubdirs(dir, queue) {
|
|
200
|
-
let entries;
|
|
201
|
-
try {
|
|
202
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
203
|
-
} catch {
|
|
204
|
-
return;
|
|
205
|
-
}
|
|
206
|
-
for (const entry of entries) if (entry.isDirectory() && !entry.name.startsWith(".")) queue.push(path.join(dir, entry.name));
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* Breadth-first search for project folders starting from `rootDir`.
|
|
210
|
-
*
|
|
211
|
-
* - If root itself matches, returns it immediately.
|
|
212
|
-
* - Otherwise searches subfolders breadth-first:
|
|
213
|
-
* - Match → added to results, subtree pruned
|
|
214
|
-
* - Mismatch (foreign project) → subtree pruned
|
|
215
|
-
* - Non-project → subfolders enqueued for further search
|
|
216
|
-
*
|
|
217
|
-
* Uses `scanner.getProjectName` for the result name (default: `path.basename`),
|
|
218
|
-
* and `scanner.getProjectConfig` when provided.
|
|
219
|
-
*/
|
|
220
|
-
function scanProjects(rootDir, scanner) {
|
|
221
|
-
const getName = (p) => scanner.getProjectName ? scanner.getProjectName(p) : path.basename(p);
|
|
222
|
-
const getConfig = (p) => scanner.getProjectConfig ? scanner.getProjectConfig(p) : void 0;
|
|
223
|
-
function toResult(folderPath) {
|
|
224
|
-
const result = {
|
|
225
|
-
name: getName(folderPath),
|
|
226
|
-
path: folderPath,
|
|
227
|
-
config: getConfig(folderPath)
|
|
228
|
-
};
|
|
229
|
-
if (scanner.getDocumentLink) {
|
|
230
|
-
const link = scanner.getDocumentLink(folderPath);
|
|
231
|
-
if (link) {
|
|
232
|
-
result.documentId = link.documentId;
|
|
233
|
-
result.documentType = link.documentType;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
return result;
|
|
237
|
-
}
|
|
238
|
-
if (detectType(rootDir, scanner) === "match") return [toResult(rootDir)];
|
|
239
|
-
const results = [];
|
|
240
|
-
const queue = [];
|
|
241
|
-
enqueueSubdirs(rootDir, queue);
|
|
242
|
-
while (queue.length > 0) {
|
|
243
|
-
const dir = queue.shift();
|
|
244
|
-
switch (detectType(dir, scanner)) {
|
|
245
|
-
case "match":
|
|
246
|
-
results.push(toResult(dir));
|
|
247
|
-
break;
|
|
248
|
-
case "mismatch": break;
|
|
249
|
-
case "non-project": enqueueSubdirs(dir, queue);
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
return results;
|
|
253
|
-
}
|
|
254
|
-
//#endregion
|
|
255
|
-
//#region src/core/services.ts
|
|
256
|
-
/**
|
|
257
|
-
* Resolve the display name for a service definition.
|
|
258
|
-
* Uses `def.name` if provided, otherwise auto-generates from `def.id`.
|
|
259
|
-
*/
|
|
260
|
-
function resolveServiceName(def) {
|
|
261
|
-
return def.name ?? slugToTitle(def.id);
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* Identity wrapper for service definitions — provides type checking and IDE support.
|
|
265
|
-
*/
|
|
266
|
-
function defineService(opts) {
|
|
267
|
-
return opts;
|
|
268
|
-
}
|
|
269
|
-
/**
|
|
270
|
-
* Get the directory for a service's instance state files.
|
|
271
|
-
*/
|
|
272
|
-
function serviceDir(servicesDir, serviceId) {
|
|
273
|
-
return path.join(servicesDir, serviceId);
|
|
274
|
-
}
|
|
275
|
-
/**
|
|
276
|
-
* NOTE(port): instance ids are `{serviceId}:{name|hash}` — and a COLON in a
|
|
277
|
-
* filename is not a filename on NTFS: it silently writes an Alternate Data
|
|
278
|
-
* Stream (invisible to readdir), so state files vanished on Windows. Encode
|
|
279
|
-
* ids for FILENAMES only; the logical id (parsed on ':' elsewhere, stored
|
|
280
|
-
* inside the state JSON) is untouched.
|
|
281
|
-
*/
|
|
282
|
-
function fileSafeId(instanceId) {
|
|
283
|
-
return instanceId.replace(/[<>:"/\\|?*]/g, "+");
|
|
284
|
-
}
|
|
285
|
-
function stateFilePath(servicesDir, serviceId, instanceId) {
|
|
286
|
-
return path.join(serviceDir(servicesDir, serviceId), `${fileSafeId(instanceId)}.json`);
|
|
287
|
-
}
|
|
288
|
-
/** Base (run-less) log name, kept as a final fallback for older state. */
|
|
289
|
-
function logFilePath(servicesDir, serviceId, instanceId) {
|
|
290
|
-
return path.join(serviceDir(servicesDir, serviceId), `${fileSafeId(instanceId)}.log`);
|
|
291
|
-
}
|
|
292
|
-
/** Number of per-run log files kept per instance. */
|
|
293
|
-
const MAX_RUN_LOGS = 5;
|
|
294
|
-
/** Match a per-run log file for an instance: `<fileSafeId>.<runId>.log`. */
|
|
295
|
-
function runLogPattern(instanceId) {
|
|
296
|
-
const safe = fileSafeId(instanceId);
|
|
297
|
-
return new RegExp(`^${safe.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.(\\d+)\\.log$`);
|
|
298
|
-
}
|
|
299
|
-
/** Allocate a fresh per-run log file name for an instance, unique within the dir. */
|
|
300
|
-
function newRunLogFile(servicesDir, serviceId, instanceId) {
|
|
301
|
-
const dir = serviceDir(servicesDir, serviceId);
|
|
302
|
-
const safe = fileSafeId(instanceId);
|
|
303
|
-
let runId = Date.now();
|
|
304
|
-
let name = `${safe}.${runId}.log`;
|
|
305
|
-
while (fs.existsSync(path.join(dir, name))) {
|
|
306
|
-
runId += 1;
|
|
307
|
-
name = `${safe}.${runId}.log`;
|
|
308
|
-
}
|
|
309
|
-
return name;
|
|
310
|
-
}
|
|
311
|
-
/** List an instance's per-run log files, newest first by runId. */
|
|
312
|
-
function listRunLogs(servicesDir, serviceId, instanceId) {
|
|
313
|
-
const dir = serviceDir(servicesDir, serviceId);
|
|
314
|
-
const re = runLogPattern(instanceId);
|
|
315
|
-
try {
|
|
316
|
-
return fs.readdirSync(dir).filter((f) => re.test(f)).sort((a, b) => Number(re.exec(b)[1]) - Number(re.exec(a)[1]));
|
|
317
|
-
} catch {
|
|
318
|
-
return [];
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
/**
|
|
322
|
-
* Resolve the active log path for an instance: the run recorded in the state
|
|
323
|
-
* file, else the newest per-run log, else the base log name.
|
|
324
|
-
*/
|
|
325
|
-
function activeLogPath(servicesDir, serviceId, instanceId) {
|
|
326
|
-
const dir = serviceDir(servicesDir, serviceId);
|
|
327
|
-
const state = readStateFile(stateFilePath(servicesDir, serviceId, instanceId));
|
|
328
|
-
if (state?.logFile && fs.existsSync(path.join(dir, state.logFile))) return path.join(dir, state.logFile);
|
|
329
|
-
const runs = listRunLogs(servicesDir, serviceId, instanceId);
|
|
330
|
-
if (runs.length > 0) return path.join(dir, runs[0]);
|
|
331
|
-
return logFilePath(servicesDir, serviceId, instanceId);
|
|
332
|
-
}
|
|
333
|
-
/** Keep only the newest `MAX_RUN_LOGS` per-run logs for an instance. */
|
|
334
|
-
function pruneRunLogs(servicesDir, serviceId, instanceId) {
|
|
335
|
-
const dir = serviceDir(servicesDir, serviceId);
|
|
336
|
-
const runs = listRunLogs(servicesDir, serviceId, instanceId);
|
|
337
|
-
for (const f of runs.slice(MAX_RUN_LOGS)) try {
|
|
338
|
-
fs.unlinkSync(path.join(dir, f));
|
|
339
|
-
} catch {}
|
|
340
|
-
}
|
|
341
|
-
const MAX_LINE_CHARS = 2e3;
|
|
342
|
-
const MAX_TOTAL_CHARS = 16e3;
|
|
343
|
-
/**
|
|
344
|
-
* Strip NUL bytes and non-printable control chars (keeping \n and \t), then
|
|
345
|
-
* cap each line and the total length. Keeps the tail when over the total cap,
|
|
346
|
-
* since recent log lines matter most. Guards against truncate-while-open gaps
|
|
347
|
-
* that fill the file with NUL runs containing no newlines.
|
|
348
|
-
*/
|
|
349
|
-
function sanitizeLogText(text, maxTotal = MAX_TOTAL_CHARS) {
|
|
350
|
-
let out = text.replace(/[\x00-\x08\x0B-\x1F\x7F]/g, "").split("\n").map((line) => {
|
|
351
|
-
if (line.length <= MAX_LINE_CHARS) return line;
|
|
352
|
-
const dropped = line.length - MAX_LINE_CHARS;
|
|
353
|
-
return line.slice(0, MAX_LINE_CHARS) + `…[truncated ${dropped} chars]`;
|
|
354
|
-
}).join("\n");
|
|
355
|
-
if (out.length > maxTotal) out = `…[truncated ${out.length - maxTotal} chars]\n` + out.slice(out.length - maxTotal);
|
|
356
|
-
return out;
|
|
357
|
-
}
|
|
358
|
-
/**
|
|
359
|
-
* Read the last N lines from a log file, returning an empty string if unavailable.
|
|
360
|
-
*/
|
|
361
|
-
function tailLogFile(filePath, lines = 20) {
|
|
362
|
-
try {
|
|
363
|
-
return sanitizeLogText(fs.readFileSync(filePath, "utf-8")).split("\n").filter((l) => l.length > 0).slice(-lines).join("\n");
|
|
364
|
-
} catch {
|
|
365
|
-
return "";
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
function readStateFile(filePath) {
|
|
369
|
-
try {
|
|
370
|
-
const raw = fs.readFileSync(filePath, "utf-8");
|
|
371
|
-
return JSON.parse(raw);
|
|
372
|
-
} catch {
|
|
373
|
-
return null;
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
function writeStateFile(filePath, state) {
|
|
377
|
-
fs.writeFileSync(filePath, JSON.stringify(state, null, 2));
|
|
378
|
-
}
|
|
379
|
-
function removeStateFile(filePath) {
|
|
380
|
-
try {
|
|
381
|
-
fs.unlinkSync(filePath);
|
|
382
|
-
} catch {}
|
|
383
|
-
}
|
|
384
|
-
function isPidAlive(pid) {
|
|
385
|
-
try {
|
|
386
|
-
process.kill(pid, 0);
|
|
387
|
-
return true;
|
|
388
|
-
} catch {
|
|
389
|
-
return false;
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
/**
|
|
393
|
-
* Wait for a PID to exit, polling with kill(pid, 0).
|
|
394
|
-
* Returns true if the process exited, false on timeout.
|
|
395
|
-
*/
|
|
396
|
-
function waitForExit(pid, timeout, interval = 100) {
|
|
397
|
-
return new Promise((resolve) => {
|
|
398
|
-
const deadline = Date.now() + timeout;
|
|
399
|
-
const check = () => {
|
|
400
|
-
if (!isPidAlive(pid)) {
|
|
401
|
-
resolve(true);
|
|
402
|
-
return;
|
|
403
|
-
}
|
|
404
|
-
if (Date.now() >= deadline) {
|
|
405
|
-
resolve(false);
|
|
406
|
-
return;
|
|
407
|
-
}
|
|
408
|
-
setTimeout(check, interval);
|
|
409
|
-
};
|
|
410
|
-
check();
|
|
411
|
-
});
|
|
412
|
-
}
|
|
413
|
-
/**
|
|
414
|
-
* Generate an instance ID from start options.
|
|
415
|
-
* - Default (no name, no workdir) → serviceId
|
|
416
|
-
* - Named → serviceId:name
|
|
417
|
-
* - Workdir-derived → serviceId:hash8
|
|
418
|
-
*/
|
|
419
|
-
function resolveInstanceId(serviceId, opts) {
|
|
420
|
-
if (opts?.name) return `${serviceId}:${opts.name}`;
|
|
421
|
-
if (opts?.workdir) return `${serviceId}:${crypto.createHash("sha256").update(opts.workdir).digest("hex").slice(0, 8)}`;
|
|
422
|
-
return serviceId;
|
|
423
|
-
}
|
|
424
|
-
/**
|
|
425
|
-
* Resolve a service command — supports static string or dynamic function.
|
|
426
|
-
*/
|
|
427
|
-
function resolveCommand(def, ctx) {
|
|
428
|
-
return typeof def.command === "function" ? def.command(ctx) : def.command;
|
|
429
|
-
}
|
|
430
|
-
/**
|
|
431
|
-
* Scan a service's instance directory for all state files.
|
|
432
|
-
*/
|
|
433
|
-
function scanInstances(servicesDir, serviceId) {
|
|
434
|
-
const dir = serviceDir(servicesDir, serviceId);
|
|
435
|
-
try {
|
|
436
|
-
return fs.readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => readStateFile(path.join(dir, f))).filter((s) => s !== null);
|
|
437
|
-
} catch {
|
|
438
|
-
return [];
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
/**
|
|
442
|
-
* Strip the `.<runId>.log` or `.log` suffix from a log file name to get its
|
|
443
|
-
* instance ID. The runId is a `Date.now()` millisecond timestamp (see
|
|
444
|
-
* newRunLogFile), so we only treat a timestamp-width digit run (>=10) as a
|
|
445
|
-
* runId — otherwise a legacy `<instanceId>.log` whose instance name ends in
|
|
446
|
-
* `.<digits>` (e.g. `svc:agent.1`) would have that suffix wrongly stripped.
|
|
447
|
-
*/
|
|
448
|
-
function instanceIdFromLogFile(name) {
|
|
449
|
-
return name.replace(/(?:\.\d{10,})?\.log$/, "");
|
|
450
|
-
}
|
|
451
|
-
/**
|
|
452
|
-
* Find the instance ID of the most recently modified .log file in a service directory.
|
|
453
|
-
* Used as a fallback when no .json state files exist (e.g. after stop).
|
|
454
|
-
*/
|
|
455
|
-
function mostRecentLogInstance(servicesDir, serviceId) {
|
|
456
|
-
const dir = serviceDir(servicesDir, serviceId);
|
|
457
|
-
try {
|
|
458
|
-
const logFiles = fs.readdirSync(dir).filter((f) => f.endsWith(".log"));
|
|
459
|
-
if (logFiles.length === 0) return void 0;
|
|
460
|
-
let best;
|
|
461
|
-
for (const f of logFiles) {
|
|
462
|
-
const stat = fs.statSync(path.join(dir, f));
|
|
463
|
-
if (!best || stat.mtimeMs > best.mtime) best = {
|
|
464
|
-
name: f,
|
|
465
|
-
mtime: stat.mtimeMs
|
|
466
|
-
};
|
|
467
|
-
}
|
|
468
|
-
return best ? instanceIdFromLogFile(best.name) : void 0;
|
|
469
|
-
} catch {
|
|
470
|
-
return;
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
/**
|
|
474
|
-
* Create a ServiceManager for managing long-running detached services.
|
|
475
|
-
*/
|
|
476
|
-
function createServiceManager(definitions, opts) {
|
|
477
|
-
const { config, servicesDir, eventBus } = opts;
|
|
478
|
-
const defMap = /* @__PURE__ */ new Map();
|
|
479
|
-
for (const def of definitions) defMap.set(def.id, def);
|
|
480
|
-
function ensureServiceDir(serviceId) {
|
|
481
|
-
fs.mkdirSync(serviceDir(servicesDir, serviceId), { recursive: true });
|
|
482
|
-
}
|
|
483
|
-
function buildContext(params) {
|
|
484
|
-
return {
|
|
485
|
-
params,
|
|
486
|
-
config,
|
|
487
|
-
proxy: resolveServiceProxyContext(config.proxyPublicUrl)
|
|
488
|
-
};
|
|
489
|
-
}
|
|
490
|
-
async function start(id, startOpts) {
|
|
491
|
-
const def = defMap.get(id);
|
|
492
|
-
if (!def) throw new Error(`Unknown service: ${id}`);
|
|
493
|
-
const instanceId = resolveInstanceId(id, startOpts);
|
|
494
|
-
const maxInstances = def.maxInstances ?? 1;
|
|
495
|
-
const existingState = readStateFile(stateFilePath(servicesDir, id, instanceId));
|
|
496
|
-
if (existingState && existingState.status === "stopped") removeStateFile(stateFilePath(servicesDir, id, instanceId));
|
|
497
|
-
else if (existingState && existingState.pid && isPidAlive(existingState.pid)) {
|
|
498
|
-
if (existingState.status === "ready" || existingState.status === "starting") throw new Error(`Service ${id} is already running (pid ${existingState.pid})`);
|
|
499
|
-
}
|
|
500
|
-
if (scanInstances(servicesDir, id).filter((s) => s.instanceId !== instanceId && s.status !== "stopped" && s.pid && isPidAlive(s.pid)).length >= maxInstances) throw new Error(`Service ${id} has reached max instances (${maxInstances})`);
|
|
501
|
-
ensureServiceDir(id);
|
|
502
|
-
const params = startOpts?.params;
|
|
503
|
-
const buildCtx = buildContext(params);
|
|
504
|
-
const commandStr = resolveCommand(def, buildCtx);
|
|
505
|
-
const spawnCwd = startOpts?.cwd ?? startOpts?.workdir;
|
|
506
|
-
if (def.preflight?.length) {
|
|
507
|
-
const preflightCtx = {
|
|
508
|
-
cwd: spawnCwd ?? process.cwd(),
|
|
509
|
-
config,
|
|
510
|
-
params,
|
|
511
|
-
command: commandStr
|
|
512
|
-
};
|
|
513
|
-
for (const check of def.preflight) {
|
|
514
|
-
const result = await check(preflightCtx);
|
|
515
|
-
if (!result.ok) {
|
|
516
|
-
const parts = [`${resolveServiceName(def)}: ${result.message}`];
|
|
517
|
-
if (result.hint) parts.push(` Hint: ${result.hint}`);
|
|
518
|
-
throw new Error(parts.join("\n"));
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
const logFile = newRunLogFile(servicesDir, id, instanceId);
|
|
523
|
-
const logPath = path.join(serviceDir(servicesDir, id), logFile);
|
|
524
|
-
const logFd = fs.openSync(logPath, "w");
|
|
525
|
-
pruneRunLogs(servicesDir, id, instanceId);
|
|
526
|
-
const env = {
|
|
527
|
-
...process.env,
|
|
528
|
-
...def.env ? def.env(buildCtx) : {}
|
|
529
|
-
};
|
|
530
|
-
const child = spawn(commandStr, {
|
|
531
|
-
shell: true,
|
|
532
|
-
...supervisedSpawnOptions(),
|
|
533
|
-
stdio: [
|
|
534
|
-
"ignore",
|
|
535
|
-
logFd,
|
|
536
|
-
logFd
|
|
537
|
-
],
|
|
538
|
-
env,
|
|
539
|
-
cwd: spawnCwd
|
|
540
|
-
});
|
|
541
|
-
child.unref();
|
|
542
|
-
fs.closeSync(logFd);
|
|
543
|
-
const pid = child.pid;
|
|
544
|
-
const restartAttempt = existingState?.restartAttempt ?? 0;
|
|
545
|
-
const state = {
|
|
546
|
-
serviceId: id,
|
|
547
|
-
instanceId,
|
|
548
|
-
name: resolveServiceName(def),
|
|
549
|
-
pid,
|
|
550
|
-
status: "starting",
|
|
551
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
552
|
-
command: commandStr,
|
|
553
|
-
restartAttempt,
|
|
554
|
-
workdir: startOpts?.workdir,
|
|
555
|
-
params,
|
|
556
|
-
logFile
|
|
557
|
-
};
|
|
558
|
-
writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
|
|
559
|
-
/* istanbul ignore next -- defensive guard */
|
|
560
|
-
child.on("error", () => {
|
|
561
|
-
state.status = "failed";
|
|
562
|
-
state.error = "Failed to spawn process";
|
|
563
|
-
writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
|
|
564
|
-
eventBus?.emit("service:failed", {
|
|
565
|
-
id,
|
|
566
|
-
instanceId,
|
|
567
|
-
name: resolveServiceName(def),
|
|
568
|
-
error: state.error
|
|
569
|
-
});
|
|
570
|
-
});
|
|
571
|
-
if (!def.readiness || def.readiness.wait === false) {
|
|
572
|
-
state.status = "ready";
|
|
573
|
-
writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
|
|
574
|
-
eventBus?.emit("service:ready", {
|
|
575
|
-
id,
|
|
576
|
-
instanceId,
|
|
577
|
-
name: resolveServiceName(def),
|
|
578
|
-
endpoints: state.endpoints
|
|
579
|
-
});
|
|
580
|
-
return instanceId;
|
|
581
|
-
}
|
|
582
|
-
const readinessPatterns = def.readiness.patterns ? def.readiness.patterns : [{
|
|
583
|
-
name: "_default",
|
|
584
|
-
pattern: def.readiness.pattern,
|
|
585
|
-
captures: def.readiness.captures
|
|
586
|
-
}];
|
|
587
|
-
const { timeout } = def.readiness;
|
|
588
|
-
const startTime = Date.now();
|
|
589
|
-
let lastPos = 0;
|
|
590
|
-
const matched = /* @__PURE__ */ new Set();
|
|
591
|
-
state.endpoints = {};
|
|
592
|
-
state.endpointTypes = {};
|
|
593
|
-
await new Promise((resolve, reject) => {
|
|
594
|
-
const pollInterval = setInterval(() => {
|
|
595
|
-
if (!isPidAlive(pid)) {
|
|
596
|
-
clearInterval(pollInterval);
|
|
597
|
-
state.status = "failed";
|
|
598
|
-
state.error = "Process exited before becoming ready";
|
|
599
|
-
writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
|
|
600
|
-
eventBus?.emit("service:failed", {
|
|
601
|
-
id,
|
|
602
|
-
instanceId,
|
|
603
|
-
name: resolveServiceName(def),
|
|
604
|
-
error: state.error
|
|
605
|
-
});
|
|
606
|
-
const tail = tailLogFile(logPath);
|
|
607
|
-
const hint = `Check the workdir and run '${id}-logs' for the full log.`;
|
|
608
|
-
const lines = [state.error];
|
|
609
|
-
lines.push("");
|
|
610
|
-
lines.push(` workdir: ${spawnCwd}`);
|
|
611
|
-
lines.push(` command: ${commandStr}`);
|
|
612
|
-
if (tail) {
|
|
613
|
-
lines.push("");
|
|
614
|
-
lines.push(" Recent log output:");
|
|
615
|
-
lines.push(...tail.split("\n").map((l) => " " + l));
|
|
616
|
-
}
|
|
617
|
-
lines.push("");
|
|
618
|
-
lines.push(` ${hint}`);
|
|
619
|
-
reject(new Error(lines.join("\n")));
|
|
620
|
-
return;
|
|
621
|
-
}
|
|
622
|
-
try {
|
|
623
|
-
const logContent = fs.readFileSync(logPath, "utf-8");
|
|
624
|
-
const newContent = logContent.slice(lastPos);
|
|
625
|
-
lastPos = logContent.length;
|
|
626
|
-
if (newContent) {
|
|
627
|
-
for (const rp of readinessPatterns) {
|
|
628
|
-
if (matched.has(rp.name)) continue;
|
|
629
|
-
const match = rp.pattern.exec(newContent);
|
|
630
|
-
if (match) {
|
|
631
|
-
matched.add(rp.name);
|
|
632
|
-
if (rp.captures) for (const [name, captureDef] of Object.entries(rp.captures)) {
|
|
633
|
-
const groupIdx = typeof captureDef === "number" ? captureDef : captureDef.group;
|
|
634
|
-
if (match[groupIdx]) {
|
|
635
|
-
state.endpoints[name] = match[groupIdx];
|
|
636
|
-
if (typeof captureDef !== "number" && captureDef.type) state.endpointTypes[name] = captureDef.type;
|
|
637
|
-
}
|
|
638
|
-
}
|
|
639
|
-
eventBus?.emit("service:pattern-matched", {
|
|
640
|
-
id,
|
|
641
|
-
instanceId,
|
|
642
|
-
name: resolveServiceName(def),
|
|
643
|
-
patternName: rp.name,
|
|
644
|
-
endpoints: state.endpoints,
|
|
645
|
-
endpointTypes: state.endpointTypes,
|
|
646
|
-
remaining: readinessPatterns.length - matched.size
|
|
647
|
-
});
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
if (matched.size === readinessPatterns.length) {
|
|
651
|
-
clearInterval(pollInterval);
|
|
652
|
-
state.status = "ready";
|
|
653
|
-
state.restartAttempt = 0;
|
|
654
|
-
writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
|
|
655
|
-
eventBus?.emit("service:ready", {
|
|
656
|
-
id,
|
|
657
|
-
instanceId,
|
|
658
|
-
name: resolveServiceName(def),
|
|
659
|
-
endpoints: state.endpoints,
|
|
660
|
-
endpointTypes: state.endpointTypes
|
|
661
|
-
});
|
|
662
|
-
resolve();
|
|
663
|
-
return;
|
|
664
|
-
}
|
|
665
|
-
}
|
|
666
|
-
} catch {}
|
|
667
|
-
if (Date.now() - startTime > timeout) {
|
|
668
|
-
clearInterval(pollInterval);
|
|
669
|
-
try {
|
|
670
|
-
killTree(pid, "SIGKILL");
|
|
671
|
-
} catch {}
|
|
672
|
-
const unmatched = readinessPatterns.filter((rp) => !matched.has(rp.name)).map((rp) => rp.name);
|
|
673
|
-
state.status = "failed";
|
|
674
|
-
state.error = `Readiness timeout exceeded (unmatched: ${unmatched.join(", ")})`;
|
|
675
|
-
writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
|
|
676
|
-
eventBus?.emit("service:failed", {
|
|
677
|
-
id,
|
|
678
|
-
instanceId,
|
|
679
|
-
name: resolveServiceName(def),
|
|
680
|
-
error: state.error
|
|
681
|
-
});
|
|
682
|
-
const tail = tailLogFile(logPath);
|
|
683
|
-
const hint = `Check the workdir and run '${id}-logs' for the full log.`;
|
|
684
|
-
const tLines = [state.error];
|
|
685
|
-
tLines.push("");
|
|
686
|
-
tLines.push(` workdir: ${spawnCwd}`);
|
|
687
|
-
tLines.push(` command: ${commandStr}`);
|
|
688
|
-
if (tail) {
|
|
689
|
-
tLines.push("");
|
|
690
|
-
tLines.push(" Recent log output:");
|
|
691
|
-
tLines.push(...tail.split("\n").map((l) => " " + l));
|
|
692
|
-
}
|
|
693
|
-
tLines.push("");
|
|
694
|
-
tLines.push(` ${hint}`);
|
|
695
|
-
const detail = tLines.join("\n");
|
|
696
|
-
reject(new Error(detail));
|
|
697
|
-
}
|
|
698
|
-
}, 100);
|
|
699
|
-
});
|
|
700
|
-
return instanceId;
|
|
701
|
-
}
|
|
702
|
-
/**
|
|
703
|
-
* Send a signal to a process, trying the process group first, then direct PID.
|
|
704
|
-
*/
|
|
705
|
-
/* istanbul ignore next -- kill fallbacks depend on OS process group behavior */
|
|
706
|
-
function killProcess(pid, signal) {
|
|
707
|
-
try {
|
|
708
|
-
killTree(pid, signal);
|
|
709
|
-
} catch {
|
|
710
|
-
try {
|
|
711
|
-
process.kill(pid, signal);
|
|
712
|
-
} catch {}
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
/**
|
|
716
|
-
* Force-kill a process with SIGKILL, then wait for it to exit.
|
|
717
|
-
*/
|
|
718
|
-
/* istanbul ignore next -- force-kill path requires processes that resist SIGTERM */
|
|
719
|
-
async function forceKill(pid) {
|
|
720
|
-
killProcess(pid, "SIGKILL");
|
|
721
|
-
await waitForExit(pid, 2e3);
|
|
722
|
-
}
|
|
723
|
-
async function stopInstance(def, serviceId, instanceId) {
|
|
724
|
-
const statePath = stateFilePath(servicesDir, serviceId, instanceId);
|
|
725
|
-
const state = readStateFile(statePath);
|
|
726
|
-
if (!state || !state.pid) {
|
|
727
|
-
if (state?.status === "stopped") return;
|
|
728
|
-
throw new Error(`Service ${serviceId} is not running`);
|
|
729
|
-
}
|
|
730
|
-
if (!isPidAlive(state.pid)) {
|
|
731
|
-
state.status = "stopped";
|
|
732
|
-
state.pid = 0;
|
|
733
|
-
state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
734
|
-
writeStateFile(statePath, state);
|
|
735
|
-
return;
|
|
736
|
-
}
|
|
737
|
-
const signal = def.shutdown?.signal ?? "SIGTERM";
|
|
738
|
-
const timeout = def.shutdown?.timeout ?? 5e3;
|
|
739
|
-
killProcess(state.pid, signal);
|
|
740
|
-
if (!await waitForExit(state.pid, timeout)) await forceKill(state.pid);
|
|
741
|
-
if (state.endpoints?.port) {
|
|
742
|
-
const port = parseInt(state.endpoints.port, 10);
|
|
743
|
-
if (!isNaN(port)) {
|
|
744
|
-
let portFree = false;
|
|
745
|
-
for (let i = 0; i < 10; i++) {
|
|
746
|
-
portFree = await isPortFree(port);
|
|
747
|
-
if (portFree) break;
|
|
748
|
-
await new Promise((r) => setTimeout(r, 100));
|
|
749
|
-
}
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
state.status = "stopped";
|
|
753
|
-
state.pid = 0;
|
|
754
|
-
state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
755
|
-
writeStateFile(statePath, state);
|
|
756
|
-
eventBus?.emit("service:stopped", {
|
|
757
|
-
id: serviceId,
|
|
758
|
-
instanceId,
|
|
759
|
-
name: resolveServiceName(def)
|
|
760
|
-
});
|
|
761
|
-
}
|
|
762
|
-
async function stop(id, instanceId) {
|
|
763
|
-
const def = defMap.get(id);
|
|
764
|
-
if (!def) throw new Error(`Unknown service: ${id}`);
|
|
765
|
-
if (instanceId) return stopInstance(def, id, instanceId);
|
|
766
|
-
const instances = scanInstances(servicesDir, id);
|
|
767
|
-
if (instances.length === 0) throw new Error(`Service ${id} is not running`);
|
|
768
|
-
for (const inst of instances) try {
|
|
769
|
-
await stopInstance(def, id, inst.instanceId);
|
|
770
|
-
} catch {}
|
|
771
|
-
}
|
|
772
|
-
function list(serviceId) {
|
|
773
|
-
const results = [];
|
|
774
|
-
const defs = serviceId ? [defMap.get(serviceId)].filter(Boolean) : definitions;
|
|
775
|
-
for (const def of defs) {
|
|
776
|
-
const instances = scanInstances(servicesDir, def.id);
|
|
777
|
-
if (instances.length === 0) {
|
|
778
|
-
results.push({
|
|
779
|
-
serviceId: def.id,
|
|
780
|
-
instanceId: def.id,
|
|
781
|
-
name: resolveServiceName(def),
|
|
782
|
-
status: "idle"
|
|
783
|
-
});
|
|
784
|
-
continue;
|
|
785
|
-
}
|
|
786
|
-
for (const state of instances) {
|
|
787
|
-
if (state.status === "stopped") {
|
|
788
|
-
results.push({
|
|
789
|
-
serviceId: def.id,
|
|
790
|
-
instanceId: state.instanceId,
|
|
791
|
-
name: state.name,
|
|
792
|
-
status: "stopped",
|
|
793
|
-
workdir: state.workdir,
|
|
794
|
-
params: state.params
|
|
795
|
-
});
|
|
796
|
-
continue;
|
|
797
|
-
}
|
|
798
|
-
if (!state.pid || !isPidAlive(state.pid)) {
|
|
799
|
-
const statePath = stateFilePath(servicesDir, def.id, state.instanceId);
|
|
800
|
-
if (def.restart?.enabled && (state.restartAttempt ?? 0) < def.restart.maxRetries && state.status === "ready") {
|
|
801
|
-
const attempt = (state.restartAttempt ?? 0) + 1;
|
|
802
|
-
eventBus?.emit("service:restarting", {
|
|
803
|
-
id: def.id,
|
|
804
|
-
instanceId: state.instanceId,
|
|
805
|
-
name: resolveServiceName(def),
|
|
806
|
-
attempt,
|
|
807
|
-
maxRetries: def.restart.maxRetries
|
|
808
|
-
});
|
|
809
|
-
state.status = "starting";
|
|
810
|
-
state.restartAttempt = attempt;
|
|
811
|
-
writeStateFile(statePath, state);
|
|
812
|
-
const restartParams = state.params;
|
|
813
|
-
const restartWorkdir = state.workdir;
|
|
814
|
-
const restartName = state.instanceId.includes(":") ? state.instanceId.split(":")[1] : void 0;
|
|
815
|
-
setTimeout(async () => {
|
|
816
|
-
try {
|
|
817
|
-
removeStateFile(statePath);
|
|
818
|
-
ensureServiceDir(def.id);
|
|
819
|
-
const commandStr = resolveCommand(def, buildContext(restartParams));
|
|
820
|
-
const tempState = {
|
|
821
|
-
serviceId: def.id,
|
|
822
|
-
instanceId: state.instanceId,
|
|
823
|
-
name: resolveServiceName(def),
|
|
824
|
-
pid: 0,
|
|
825
|
-
status: "failed",
|
|
826
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
827
|
-
command: commandStr,
|
|
828
|
-
restartAttempt: attempt,
|
|
829
|
-
params: restartParams,
|
|
830
|
-
workdir: restartWorkdir
|
|
831
|
-
};
|
|
832
|
-
writeStateFile(statePath, tempState);
|
|
833
|
-
await start(def.id, {
|
|
834
|
-
params: restartParams,
|
|
835
|
-
workdir: restartWorkdir,
|
|
836
|
-
name: restartName
|
|
837
|
-
});
|
|
838
|
-
} catch {}
|
|
839
|
-
}, def.restart.delay);
|
|
840
|
-
results.push({
|
|
841
|
-
serviceId: def.id,
|
|
842
|
-
instanceId: state.instanceId,
|
|
843
|
-
name: resolveServiceName(def),
|
|
844
|
-
status: "starting",
|
|
845
|
-
restartAttempt: attempt,
|
|
846
|
-
params: state.params,
|
|
847
|
-
workdir: state.workdir
|
|
848
|
-
});
|
|
849
|
-
} else {
|
|
850
|
-
const isFailed = state.status === "failed" || def.restart?.enabled && (state.restartAttempt ?? 0) >= def.restart.maxRetries;
|
|
851
|
-
if (def.restart?.enabled && (state.restartAttempt ?? 0) >= def.restart.maxRetries) eventBus?.emit("service:failed", {
|
|
852
|
-
id: def.id,
|
|
853
|
-
instanceId: state.instanceId,
|
|
854
|
-
name: resolveServiceName(def),
|
|
855
|
-
error: "Max restart retries exceeded"
|
|
856
|
-
});
|
|
857
|
-
if (isFailed) {
|
|
858
|
-
removeStateFile(statePath);
|
|
859
|
-
results.push({
|
|
860
|
-
serviceId: def.id,
|
|
861
|
-
instanceId: state.instanceId,
|
|
862
|
-
name: resolveServiceName(def),
|
|
863
|
-
status: "failed",
|
|
864
|
-
error: state.error ?? "Process exited unexpectedly",
|
|
865
|
-
restartAttempt: state.restartAttempt
|
|
866
|
-
});
|
|
867
|
-
} else {
|
|
868
|
-
state.status = "stopped";
|
|
869
|
-
state.pid = 0;
|
|
870
|
-
state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
871
|
-
writeStateFile(statePath, state);
|
|
872
|
-
results.push({
|
|
873
|
-
serviceId: def.id,
|
|
874
|
-
instanceId: state.instanceId,
|
|
875
|
-
name: state.name,
|
|
876
|
-
status: "stopped",
|
|
877
|
-
workdir: state.workdir,
|
|
878
|
-
params: state.params
|
|
879
|
-
});
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
continue;
|
|
883
|
-
}
|
|
884
|
-
results.push({
|
|
885
|
-
serviceId: def.id,
|
|
886
|
-
instanceId: state.instanceId,
|
|
887
|
-
name: resolveServiceName(def),
|
|
888
|
-
status: state.status,
|
|
889
|
-
pid: state.pid,
|
|
890
|
-
endpoints: state.endpoints,
|
|
891
|
-
endpointTypes: state.endpointTypes,
|
|
892
|
-
restartAttempt: state.restartAttempt,
|
|
893
|
-
params: state.params,
|
|
894
|
-
workdir: state.workdir
|
|
895
|
-
});
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
|
-
return results;
|
|
899
|
-
}
|
|
900
|
-
function logs(id, instanceId, lines = 50) {
|
|
901
|
-
const def = defMap.get(id);
|
|
902
|
-
if (!def) throw new Error(`Unknown service: ${id}`);
|
|
903
|
-
let resolvedInstanceId = instanceId;
|
|
904
|
-
let warning = "";
|
|
905
|
-
if (!resolvedInstanceId) {
|
|
906
|
-
const instances = scanInstances(servicesDir, id);
|
|
907
|
-
const running = instances.filter((s) => s.status === "ready" || s.status === "starting");
|
|
908
|
-
if (running.length === 1) resolvedInstanceId = running[0].instanceId;
|
|
909
|
-
else if (running.length > 1) {
|
|
910
|
-
warning = `⚠ Multiple running instances — showing logs for ${running[0].instanceId}. Use --instance to specify: ${running.map((r) => r.instanceId).join(", ")}\n`;
|
|
911
|
-
resolvedInstanceId = running[0].instanceId;
|
|
912
|
-
} else if (instances.length > 0) resolvedInstanceId = mostRecentLogInstance(servicesDir, id) ?? instances[instances.length - 1].instanceId;
|
|
913
|
-
else resolvedInstanceId = mostRecentLogInstance(servicesDir, id) ?? id;
|
|
914
|
-
}
|
|
915
|
-
const logPath = activeLogPath(servicesDir, id, resolvedInstanceId);
|
|
916
|
-
const instanceState = (instanceId ? null : scanInstances(servicesDir, id))?.find((s) => s.instanceId === resolvedInstanceId);
|
|
917
|
-
const statusTag = instanceState ? ` [${instanceState.status}]` : "";
|
|
918
|
-
const instanceTag = resolvedInstanceId !== id ? ` (${resolvedInstanceId})` : "";
|
|
919
|
-
const workdirLine = instanceState?.workdir ? `\n (dir: ${instanceState.workdir})` : "";
|
|
920
|
-
const footer = `\n— ${resolveServiceName(def)}${instanceTag}${statusTag} log${workdirLine}`;
|
|
921
|
-
try {
|
|
922
|
-
const body = sanitizeLogText(sanitizeLogText(fs.readFileSync(logPath, "utf-8")).split("\n").slice(-lines).join("\n"));
|
|
923
|
-
return warning + body + footer;
|
|
924
|
-
} catch {
|
|
925
|
-
return warning;
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
function watchLogs(id, instanceId, onLine) {
|
|
929
|
-
if (!defMap.get(id)) throw new Error(`Unknown service: ${id}`);
|
|
930
|
-
const logPath = activeLogPath(servicesDir, id, instanceId);
|
|
931
|
-
let lastPos = 0;
|
|
932
|
-
try {
|
|
933
|
-
lastPos = fs.statSync(logPath).size;
|
|
934
|
-
} catch {}
|
|
935
|
-
let watcher;
|
|
936
|
-
try {
|
|
937
|
-
watcher = fs.watch(logPath, () => {
|
|
938
|
-
try {
|
|
939
|
-
const buf = fs.readFileSync(logPath);
|
|
940
|
-
if (buf.length < lastPos) lastPos = 0;
|
|
941
|
-
const newContent = buf.toString("utf-8", lastPos);
|
|
942
|
-
lastPos = buf.length;
|
|
943
|
-
if (newContent) {
|
|
944
|
-
const lines = newContent.split("\n").filter((l) => l.length > 0);
|
|
945
|
-
for (const line of lines) onLine(line);
|
|
946
|
-
}
|
|
947
|
-
} catch {}
|
|
948
|
-
});
|
|
949
|
-
} catch {
|
|
950
|
-
onLine("Log file not found");
|
|
951
|
-
return () => {};
|
|
952
|
-
}
|
|
953
|
-
return () => {
|
|
954
|
-
watcher.close();
|
|
955
|
-
};
|
|
956
|
-
}
|
|
957
|
-
function getDefinition(id) {
|
|
958
|
-
return defMap.get(id);
|
|
959
|
-
}
|
|
960
|
-
function scanProjectsForService(id, rootDir) {
|
|
961
|
-
const def = defMap.get(id);
|
|
962
|
-
if (!def) throw new Error(`Unknown service: ${id}`);
|
|
963
|
-
if (!def.projectScanner) return [];
|
|
964
|
-
return scanProjects(rootDir, def.projectScanner);
|
|
965
|
-
}
|
|
966
|
-
function purgeStoppedInstances(id) {
|
|
967
|
-
if (!defMap.get(id)) throw new Error(`Unknown service: ${id}`);
|
|
968
|
-
const instances = scanInstances(servicesDir, id);
|
|
969
|
-
for (const state of instances) if (state.status === "stopped") {
|
|
970
|
-
removeStateFile(stateFilePath(servicesDir, id, state.instanceId));
|
|
971
|
-
const dir = serviceDir(servicesDir, id);
|
|
972
|
-
try {
|
|
973
|
-
fs.unlinkSync(logFilePath(servicesDir, id, state.instanceId));
|
|
974
|
-
} catch {}
|
|
975
|
-
for (const f of listRunLogs(servicesDir, id, state.instanceId)) try {
|
|
976
|
-
fs.unlinkSync(path.join(dir, f));
|
|
977
|
-
} catch {}
|
|
978
|
-
}
|
|
979
|
-
}
|
|
980
|
-
function watchChunks(_id, _instanceId, _onChunk) {
|
|
981
|
-
if (!defMap.get(_id)) throw new Error(`Unknown service: ${_id}`);
|
|
982
|
-
return () => {};
|
|
983
|
-
}
|
|
984
|
-
return {
|
|
985
|
-
start,
|
|
986
|
-
stop,
|
|
987
|
-
list,
|
|
988
|
-
getDefinition,
|
|
989
|
-
logs,
|
|
990
|
-
watchLogs,
|
|
991
|
-
watchChunks,
|
|
992
|
-
scanProjects: scanProjectsForService,
|
|
993
|
-
purgeStoppedInstances
|
|
994
|
-
};
|
|
995
|
-
}
|
|
996
|
-
//#endregion
|
|
997
|
-
export { scanProjects as a, checkCommand as c, isPortFree as d, getSchemaFields as f, PROJECT_INDICATORS as i, checkPort as l, defineService as n, killTree as o, slugToTitle as p, resolveServiceName as r, supervisedSpawnOptions as s, createServiceManager as t, checkWorkdir as u };
|
|
998
|
-
|
|
999
|
-
//# sourceMappingURL=services-9E-r0nWl.mjs.map
|