@neuralnomads/codenomad 0.10.3 → 0.11.4

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,96 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
4
+ import { applyMergePatch, isPlainObject } from "./merge-patch";
5
+ function ensureTrailingNewline(content) {
6
+ if (!content)
7
+ return "\n";
8
+ return content.endsWith("\n") ? content : `${content}\n`;
9
+ }
10
+ function normalizeDoc(input) {
11
+ if (!isPlainObject(input)) {
12
+ return {};
13
+ }
14
+ return input;
15
+ }
16
+ export class YamlDocStore {
17
+ constructor(filePath, logger) {
18
+ this.filePath = filePath;
19
+ this.logger = logger;
20
+ this.cache = {};
21
+ this.loaded = false;
22
+ }
23
+ load() {
24
+ if (this.loaded) {
25
+ return this.cache;
26
+ }
27
+ try {
28
+ if (!fs.existsSync(this.filePath)) {
29
+ this.cache = {};
30
+ this.loaded = true;
31
+ return this.cache;
32
+ }
33
+ const content = fs.readFileSync(this.filePath, "utf-8");
34
+ const parsed = parseYaml(content);
35
+ this.cache = normalizeDoc(parsed);
36
+ this.loaded = true;
37
+ return this.cache;
38
+ }
39
+ catch (error) {
40
+ this.logger.warn({ err: error, filePath: this.filePath }, "Failed to read YAML doc; using empty object");
41
+ this.cache = {};
42
+ this.loaded = true;
43
+ return this.cache;
44
+ }
45
+ }
46
+ get() {
47
+ return this.load();
48
+ }
49
+ replace(next) {
50
+ const normalized = normalizeDoc(next);
51
+ this.cache = normalized;
52
+ this.loaded = true;
53
+ this.persist();
54
+ return this.cache;
55
+ }
56
+ mergePatch(patch) {
57
+ if (!isPlainObject(patch)) {
58
+ throw new Error("Patch must be a JSON object");
59
+ }
60
+ const current = this.get();
61
+ const next = applyMergePatch(current, patch);
62
+ return this.replace(next);
63
+ }
64
+ getOwner(owner) {
65
+ const doc = this.get();
66
+ const value = doc?.[owner];
67
+ return normalizeDoc(value);
68
+ }
69
+ replaceOwner(owner, value) {
70
+ const doc = this.get();
71
+ const nextDoc = { ...doc, [owner]: normalizeDoc(value) };
72
+ this.replace(nextDoc);
73
+ return nextDoc[owner];
74
+ }
75
+ mergePatchOwner(owner, patch) {
76
+ if (!isPlainObject(patch)) {
77
+ throw new Error("Patch must be a JSON object");
78
+ }
79
+ const doc = this.get();
80
+ const currentOwner = normalizeDoc(doc?.[owner]);
81
+ const nextOwner = normalizeDoc(applyMergePatch(currentOwner, patch));
82
+ const nextDoc = { ...doc, [owner]: nextOwner };
83
+ this.replace(nextDoc);
84
+ return nextOwner;
85
+ }
86
+ persist() {
87
+ try {
88
+ fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
89
+ const yaml = stringifyYaml(this.cache);
90
+ fs.writeFileSync(this.filePath, ensureTrailingNewline(yaml), "utf-8");
91
+ }
92
+ catch (error) {
93
+ this.logger.warn({ err: error, filePath: this.filePath }, "Failed to persist YAML doc");
94
+ }
95
+ }
96
+ }
@@ -49,7 +49,7 @@ export class WorkspaceManager {
49
49
  }
50
50
  async create(folder, name) {
51
51
  const id = `${Date.now().toString(36)}`;
52
- const binary = this.options.binaryRegistry.resolveDefault();
52
+ const binary = this.options.binaryResolver.resolveDefault();
53
53
  const resolvedBinaryPath = this.resolveBinaryPath(binary.path);
54
54
  const workspacePath = path.isAbsolute(folder) ? folder : path.resolve(this.options.rootDir, folder);
55
55
  clearWorkspaceSearchCache(workspacePath);
@@ -67,13 +67,11 @@ export class WorkspaceManager {
67
67
  createdAt: new Date().toISOString(),
68
68
  updatedAt: new Date().toISOString(),
69
69
  };
70
- if (!descriptor.binaryVersion) {
71
- descriptor.binaryVersion = this.detectBinaryVersion(resolvedBinaryPath);
72
- }
73
70
  this.workspaces.set(id, descriptor);
74
71
  this.options.eventBus.publish({ type: "workspace.created", workspace: descriptor });
75
- const preferences = this.options.configStore.get().preferences ?? {};
76
- const userEnvironment = preferences.environmentVariables ?? {};
72
+ const serverConfig = this.options.settings.getOwner("config", "server");
73
+ const envVars = serverConfig?.environmentVariables;
74
+ const userEnvironment = envVars && typeof envVars === "object" && !Array.isArray(envVars) ? envVars : {};
77
75
  const opencodeUsername = DEFAULT_OPENCODE_USERNAME;
78
76
  const opencodePassword = generateOpencodeServerPassword();
79
77
  const authorization = buildOpencodeBasicAuthHeader({ username: opencodeUsername, password: opencodePassword });
@@ -98,7 +96,10 @@ export class WorkspaceManager {
98
96
  environment,
99
97
  onExit: (info) => this.handleProcessExit(info.workspaceId, info),
100
98
  });
101
- await this.waitForWorkspaceReadiness({ workspaceId: id, port, exitPromise, getLastOutput });
99
+ const runtimeVersion = await this.waitForWorkspaceReadiness({ workspaceId: id, port, exitPromise, getLastOutput });
100
+ if (runtimeVersion) {
101
+ descriptor.binaryVersion = runtimeVersion;
102
+ }
102
103
  descriptor.pid = pid;
103
104
  descriptor.port = port;
104
105
  descriptor.status = "ready";
@@ -207,35 +208,6 @@ export class WorkspaceManager {
207
208
  }
208
209
  return candidates[0] ?? "";
209
210
  }
210
- detectBinaryVersion(resolvedPath) {
211
- if (!resolvedPath) {
212
- return undefined;
213
- }
214
- try {
215
- const result = spawnSync(resolvedPath, ["--version"], { encoding: "utf8" });
216
- if (result.status === 0 && result.stdout) {
217
- const line = result.stdout.split(/\r?\n/).find((entry) => entry.trim().length > 0);
218
- if (line) {
219
- const normalized = line.trim();
220
- const versionMatch = normalized.match(/([0-9]+\.[0-9]+\.[0-9A-Za-z.-]+)/);
221
- if (versionMatch) {
222
- const version = versionMatch[1];
223
- this.options.logger.debug({ binary: resolvedPath, version }, "Detected binary version");
224
- return version;
225
- }
226
- this.options.logger.debug({ binary: resolvedPath, reported: normalized }, "Binary reported version string");
227
- return normalized;
228
- }
229
- }
230
- else if (result.error) {
231
- this.options.logger.warn({ binary: resolvedPath, err: result.error }, "Failed to read binary version");
232
- }
233
- }
234
- catch (error) {
235
- this.options.logger.warn({ binary: resolvedPath, err: error }, "Failed to detect binary version");
236
- }
237
- return undefined;
238
- }
239
211
  async waitForWorkspaceReadiness(params) {
240
212
  await Promise.race([
241
213
  this.waitForPortAvailability(params.port),
@@ -243,13 +215,14 @@ export class WorkspaceManager {
243
215
  throw this.buildStartupError(params.workspaceId, "exited before becoming ready", info, params.getLastOutput());
244
216
  }),
245
217
  ]);
246
- await this.waitForInstanceHealth(params);
218
+ const version = await this.waitForInstanceHealth(params);
247
219
  await Promise.race([
248
220
  this.delay(STARTUP_STABILITY_DELAY_MS),
249
221
  params.exitPromise.then((info) => {
250
222
  throw this.buildStartupError(params.workspaceId, "exited shortly after start", info, params.getLastOutput());
251
223
  }),
252
224
  ]);
225
+ return version;
253
226
  }
254
227
  async waitForInstanceHealth(params) {
255
228
  const probeResult = await Promise.race([
@@ -259,7 +232,7 @@ export class WorkspaceManager {
259
232
  }),
260
233
  ]);
261
234
  if (probeResult.ok) {
262
- return;
235
+ return probeResult.version;
263
236
  }
264
237
  const latestOutput = params.getLastOutput().trim();
265
238
  if (latestOutput) {
@@ -269,7 +242,7 @@ export class WorkspaceManager {
269
242
  throw new Error(`Workspace ${params.workspaceId} failed health check: ${reason}.`);
270
243
  }
271
244
  async probeInstance(workspaceId, port) {
272
- const url = `http://127.0.0.1:${port}/project/current`;
245
+ const url = `http://127.0.0.1:${port}/global/health`;
273
246
  try {
274
247
  const headers = {};
275
248
  const authHeader = this.opencodeAuth.get(workspaceId)?.authorization;
@@ -278,11 +251,19 @@ export class WorkspaceManager {
278
251
  }
279
252
  const response = await fetch(url, { headers });
280
253
  if (!response.ok) {
281
- const reason = `health probe returned HTTP ${response.status}`;
254
+ const reason = `/global/health returned HTTP ${response.status}`;
282
255
  this.options.logger.debug({ workspaceId, status: response.status }, "Health probe returned server error");
283
256
  return { ok: false, reason };
284
257
  }
285
- return { ok: true };
258
+ const payload = (await response.json().catch(() => null));
259
+ const healthy = payload?.healthy === true;
260
+ const version = typeof payload?.version === "string" ? payload.version.trim() : undefined;
261
+ if (!healthy) {
262
+ const reason = "Instance reported unhealthy";
263
+ this.options.logger.debug({ workspaceId, payload }, "Health probe returned unhealthy response");
264
+ return { ok: false, reason };
265
+ }
266
+ return { ok: true, version: version || undefined };
286
267
  }
287
268
  catch (error) {
288
269
  const reason = error instanceof Error ? error.message : String(error);
@@ -3,6 +3,7 @@ import { existsSync, statSync } from "fs";
3
3
  import path from "path";
4
4
  export const WINDOWS_CMD_EXTENSIONS = new Set([".cmd", ".bat"]);
5
5
  export const WINDOWS_POWERSHELL_EXTENSIONS = new Set([".ps1"]);
6
+ const VERSION_REGEX = /([0-9]+\.[0-9]+\.[0-9A-Za-z.-]+)/;
6
7
  export function buildSpawnSpec(binaryPath, args) {
7
8
  if (process.platform !== "win32") {
8
9
  return { command: binaryPath, args, options: {} };
@@ -29,6 +30,47 @@ export function buildSpawnSpec(binaryPath, args) {
29
30
  }
30
31
  return { command: binaryPath, args, options: {} };
31
32
  }
33
+ export function probeBinaryVersion(binaryPath) {
34
+ if (!binaryPath) {
35
+ return { valid: false, error: "Missing binary path" };
36
+ }
37
+ const spec = buildSpawnSpec(binaryPath, ["--version"]);
38
+ try {
39
+ const result = spawnSync(spec.command, spec.args, {
40
+ encoding: "utf8",
41
+ windowsVerbatimArguments: Boolean(spec.options.windowsVerbatimArguments),
42
+ });
43
+ if (result.error) {
44
+ return { valid: false, error: result.error.message };
45
+ }
46
+ if (result.status !== 0) {
47
+ const stderr = result.stderr?.trim();
48
+ const stdout = result.stdout?.trim();
49
+ const combined = stderr || stdout;
50
+ const error = combined ? `Exited with code ${result.status}: ${combined}` : `Exited with code ${result.status}`;
51
+ return { valid: false, error };
52
+ }
53
+ const stdoutLines = String(result.stdout ?? "")
54
+ .split(/\r?\n/)
55
+ .map((line) => line.trim())
56
+ .filter((line) => line.length > 0);
57
+ const stderrLines = String(result.stderr ?? "")
58
+ .split(/\r?\n/)
59
+ .map((line) => line.trim())
60
+ .filter((line) => line.length > 0);
61
+ // Prefer stdout; fall back to stderr (some tools report version there).
62
+ const reported = stdoutLines[0] ?? stderrLines[0];
63
+ if (!reported) {
64
+ return { valid: true };
65
+ }
66
+ const versionMatch = reported.match(VERSION_REGEX);
67
+ const version = versionMatch?.[1];
68
+ return { valid: true, version, reported };
69
+ }
70
+ catch (error) {
71
+ return { valid: false, error: error instanceof Error ? error.message : String(error) };
72
+ }
73
+ }
32
74
  const SENSITIVE_ENV_KEY = /(PASSWORD|TOKEN|SECRET)/i;
33
75
  function redactEnvironment(env) {
34
76
  const redacted = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neuralnomads/codenomad",
3
- "version": "0.10.3",
3
+ "version": "0.11.4",
4
4
  "description": "CodeNomad Server",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -34,6 +34,7 @@
34
34
  "node-forge": "^1.3.3",
35
35
  "pino": "^9.4.0",
36
36
  "undici": "^6.19.8",
37
+ "yaml": "^2.4.2",
37
38
  "yauzl": "^2.10.0",
38
39
  "zod": "^3.23.8"
39
40
  },