@neuralnomads/codenomad 0.10.3 → 0.11.1

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,233 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
4
+ import { 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 safeReadYaml(filePath, logger) {
11
+ try {
12
+ const content = fs.readFileSync(filePath, "utf-8");
13
+ return parseYaml(content);
14
+ }
15
+ catch (error) {
16
+ logger.warn({ err: error, filePath }, "Failed to read YAML file during migration");
17
+ return null;
18
+ }
19
+ }
20
+ function safeReadJson(filePath, logger) {
21
+ try {
22
+ const content = fs.readFileSync(filePath, "utf-8");
23
+ return JSON.parse(content);
24
+ }
25
+ catch (error) {
26
+ logger.warn({ err: error, filePath }, "Failed to read JSON file during migration");
27
+ return null;
28
+ }
29
+ }
30
+ function writeYaml(filePath, doc, logger) {
31
+ try {
32
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
33
+ const yaml = stringifyYaml(doc);
34
+ fs.writeFileSync(filePath, ensureTrailingNewline(yaml), "utf-8");
35
+ }
36
+ catch (error) {
37
+ logger.warn({ err: error, filePath }, "Failed to write YAML file during migration");
38
+ }
39
+ }
40
+ function pickBackupPath(filePath) {
41
+ const preferred = `${filePath}.bak`;
42
+ if (!fs.existsSync(preferred)) {
43
+ return preferred;
44
+ }
45
+ return `${filePath}.bak.${Date.now()}`;
46
+ }
47
+ function normalizeDoc(value) {
48
+ return isPlainObject(value) ? value : {};
49
+ }
50
+ function looksLikeNewOwnerDoc(value) {
51
+ const doc = normalizeDoc(value);
52
+ // Heuristic: owner-bucket docs have at least one of these roots.
53
+ return Boolean(doc.ui || doc.server || doc.app || doc.legacy);
54
+ }
55
+ function looksLikeLegacyConfig(value) {
56
+ const doc = normalizeDoc(value);
57
+ return Boolean(doc.preferences || doc.opencodeBinaries || doc.theme || doc.recentFolders);
58
+ }
59
+ function looksLikeLegacyState(value) {
60
+ const doc = normalizeDoc(value);
61
+ return Boolean(doc.recentFolders);
62
+ }
63
+ function omitKeys(source, keys) {
64
+ const out = {};
65
+ for (const [k, v] of Object.entries(source)) {
66
+ if (keys.has(k))
67
+ continue;
68
+ out[k] = v;
69
+ }
70
+ return out;
71
+ }
72
+ function mapLegacyToOwnerDocs(legacyConfig, legacyState) {
73
+ const cfg = normalizeDoc(legacyConfig);
74
+ const st = normalizeDoc(legacyState);
75
+ const outConfig = {};
76
+ const outState = {};
77
+ const uiConfig = {};
78
+ const uiSettings = {};
79
+ const serverConfig = {};
80
+ const uiState = {};
81
+ // theme -> config.ui.theme
82
+ if (typeof cfg.theme === "string") {
83
+ uiConfig.theme = cfg.theme;
84
+ }
85
+ const preferences = normalizeDoc(cfg.preferences);
86
+ if (Object.keys(preferences).length > 0) {
87
+ // Server-owned stable keys
88
+ const envVars = preferences.environmentVariables;
89
+ if (isPlainObject(envVars)) {
90
+ serverConfig.environmentVariables = envVars;
91
+ }
92
+ const listeningMode = preferences.listeningMode;
93
+ if (typeof listeningMode === "string") {
94
+ serverConfig.listeningMode = listeningMode;
95
+ }
96
+ const lastUsedBinary = preferences.lastUsedBinary;
97
+ if (typeof lastUsedBinary === "string") {
98
+ serverConfig.opencodeBinary = lastUsedBinary;
99
+ }
100
+ // UI-owned state keys (drop preferences)
101
+ const modelRecents = preferences.modelRecents;
102
+ const modelFavorites = preferences.modelFavorites;
103
+ const modelThinkingSelections = preferences.modelThinkingSelections;
104
+ const models = {};
105
+ if (Array.isArray(modelRecents)) {
106
+ models.recents = modelRecents;
107
+ }
108
+ if (Array.isArray(modelFavorites)) {
109
+ models.favorites = modelFavorites;
110
+ }
111
+ if (isPlainObject(modelThinkingSelections)) {
112
+ models.thinkingSelections = modelThinkingSelections;
113
+ }
114
+ if (Object.keys(models).length > 0) {
115
+ uiState.models = models;
116
+ }
117
+ // Remaining preferences are treated as stable UI settings.
118
+ const moved = new Set([
119
+ "environmentVariables",
120
+ "listeningMode",
121
+ "lastUsedBinary",
122
+ "modelRecents",
123
+ "modelFavorites",
124
+ "modelThinkingSelections",
125
+ ]);
126
+ Object.assign(uiSettings, omitKeys(preferences, moved));
127
+ }
128
+ // recentFolders lives in legacy state (yaml) or legacy config.json
129
+ const recentFolders = (st.recentFolders ?? cfg.recentFolders);
130
+ if (Array.isArray(recentFolders)) {
131
+ uiState.recentFolders = recentFolders;
132
+ }
133
+ // opencodeBinaries -> state.ui.opencodeBinaries
134
+ if (Array.isArray(cfg.opencodeBinaries)) {
135
+ uiState.opencodeBinaries = cfg.opencodeBinaries;
136
+ }
137
+ if (Object.keys(uiSettings).length > 0) {
138
+ uiConfig.settings = uiSettings;
139
+ }
140
+ if (Object.keys(uiConfig).length > 0) {
141
+ outConfig.ui = uiConfig;
142
+ }
143
+ if (Object.keys(serverConfig).length > 0) {
144
+ outConfig.server = serverConfig;
145
+ }
146
+ if (Object.keys(uiState).length > 0) {
147
+ outState.ui = uiState;
148
+ }
149
+ // Unknown top-level keys -> legacy.unknown
150
+ const knownConfigKeys = new Set(["preferences", "opencodeBinaries", "theme", "recentFolders"]);
151
+ const unknownConfig = omitKeys(cfg, knownConfigKeys);
152
+ if (Object.keys(unknownConfig).length > 0) {
153
+ outConfig.legacy = { unknown: unknownConfig };
154
+ }
155
+ const knownStateKeys = new Set(["recentFolders"]);
156
+ const unknownState = omitKeys(st, knownStateKeys);
157
+ if (Object.keys(unknownState).length > 0) {
158
+ outState.legacy = { unknown: unknownState };
159
+ }
160
+ return { config: outConfig, state: outState };
161
+ }
162
+ /**
163
+ * Migrate older config/state layouts into owner-bucket YAML docs.
164
+ *
165
+ * Legacy inputs supported:
166
+ * - config.yaml with { preferences, opencodeBinaries, theme }
167
+ * - state.yaml with { recentFolders }
168
+ * - legacy config.json with full ConfigFile schema
169
+ */
170
+ export function migrateSettingsLayout(location, logger) {
171
+ const configYamlPath = location.configYamlPath;
172
+ const stateYamlPath = location.stateYamlPath;
173
+ const legacyJsonPath = location.legacyJsonPath;
174
+ const configExists = fs.existsSync(configYamlPath);
175
+ const stateExists = fs.existsSync(stateYamlPath);
176
+ const configDoc = configExists ? safeReadYaml(configYamlPath, logger) : null;
177
+ const stateDoc = stateExists ? safeReadYaml(stateYamlPath, logger) : null;
178
+ const configIsNew = configExists && looksLikeNewOwnerDoc(configDoc) && !looksLikeLegacyConfig(configDoc);
179
+ const stateIsNew = stateExists && looksLikeNewOwnerDoc(stateDoc) && !looksLikeLegacyState(stateDoc);
180
+ if (configIsNew && stateIsNew) {
181
+ return;
182
+ }
183
+ const legacyJsonExists = fs.existsSync(legacyJsonPath);
184
+ const hasLegacyYaml = (configExists && looksLikeLegacyConfig(configDoc)) || (stateExists && looksLikeLegacyState(stateDoc));
185
+ const shouldMigrateFromJson = !configExists && legacyJsonExists;
186
+ if (!hasLegacyYaml && !shouldMigrateFromJson) {
187
+ // Either fresh install or partially written docs; let stores create on first write.
188
+ return;
189
+ }
190
+ const sourceConfig = shouldMigrateFromJson ? safeReadJson(legacyJsonPath, logger) : configDoc;
191
+ const sourceState = shouldMigrateFromJson ? sourceConfig : stateDoc;
192
+ const { config, state } = mapLegacyToOwnerDocs(sourceConfig, sourceState);
193
+ try {
194
+ fs.mkdirSync(location.baseDir, { recursive: true });
195
+ }
196
+ catch (error) {
197
+ logger.warn({ err: error, baseDir: location.baseDir }, "Failed to create base directory during migration");
198
+ }
199
+ // Backup legacy files before rewriting.
200
+ if (configExists) {
201
+ try {
202
+ const bak = pickBackupPath(configYamlPath);
203
+ fs.renameSync(configYamlPath, bak);
204
+ logger.info({ configYamlPath, bak }, "Backed up legacy config.yaml");
205
+ }
206
+ catch (error) {
207
+ logger.warn({ err: error, configYamlPath }, "Failed to backup legacy config.yaml");
208
+ }
209
+ }
210
+ if (stateExists) {
211
+ try {
212
+ const bak = pickBackupPath(stateYamlPath);
213
+ fs.renameSync(stateYamlPath, bak);
214
+ logger.info({ stateYamlPath, bak }, "Backed up legacy state.yaml");
215
+ }
216
+ catch (error) {
217
+ logger.warn({ err: error, stateYamlPath }, "Failed to backup legacy state.yaml");
218
+ }
219
+ }
220
+ if (shouldMigrateFromJson) {
221
+ try {
222
+ const bak = pickBackupPath(legacyJsonPath);
223
+ fs.renameSync(legacyJsonPath, bak);
224
+ logger.info({ legacyJsonPath, bak }, "Moved legacy config.json to backup");
225
+ }
226
+ catch (error) {
227
+ logger.warn({ err: error, legacyJsonPath }, "Failed to move legacy config.json to backup");
228
+ }
229
+ }
230
+ writeYaml(configYamlPath, config, logger);
231
+ writeYaml(stateYamlPath, state, logger);
232
+ logger.info({ configYamlPath, stateYamlPath }, "Migrated settings docs to owner-bucket layout");
233
+ }
@@ -0,0 +1,39 @@
1
+ import { YamlDocStore } from "./yaml-doc-store";
2
+ import { migrateSettingsLayout } from "./migrate";
3
+ export class SettingsService {
4
+ constructor(location, eventBus, logger) {
5
+ this.location = location;
6
+ this.eventBus = eventBus;
7
+ this.logger = logger;
8
+ migrateSettingsLayout(location, logger);
9
+ this.configStore = new YamlDocStore(location.configYamlPath, logger.child({ component: "settings-config" }));
10
+ this.stateStore = new YamlDocStore(location.stateYamlPath, logger.child({ component: "settings-state" }));
11
+ }
12
+ getDoc(kind) {
13
+ return kind === "config" ? this.configStore.get() : this.stateStore.get();
14
+ }
15
+ mergePatchDoc(kind, patch) {
16
+ const updated = kind === "config" ? this.configStore.mergePatch(patch) : this.stateStore.mergePatch(patch);
17
+ this.publish(kind, "*");
18
+ return updated;
19
+ }
20
+ getOwner(kind, owner) {
21
+ return kind === "config" ? this.configStore.getOwner(owner) : this.stateStore.getOwner(owner);
22
+ }
23
+ mergePatchOwner(kind, owner, patch) {
24
+ const updated = kind === "config" ? this.configStore.mergePatchOwner(owner, patch) : this.stateStore.mergePatchOwner(owner, patch);
25
+ this.publish(kind, owner, updated);
26
+ return updated;
27
+ }
28
+ publish(kind, owner, value) {
29
+ if (!this.eventBus)
30
+ return;
31
+ const type = kind === "config" ? "storage.configChanged" : "storage.stateChanged";
32
+ const payload = {
33
+ type,
34
+ owner,
35
+ value: value ?? this.getOwner(kind, owner),
36
+ };
37
+ this.eventBus.publish(payload);
38
+ }
39
+ }
@@ -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);
@@ -72,8 +72,9 @@ export class WorkspaceManager {
72
72
  }
73
73
  this.workspaces.set(id, descriptor);
74
74
  this.options.eventBus.publish({ type: "workspace.created", workspace: descriptor });
75
- const preferences = this.options.configStore.get().preferences ?? {};
76
- const userEnvironment = preferences.environmentVariables ?? {};
75
+ const serverConfig = this.options.settings.getOwner("config", "server");
76
+ const envVars = serverConfig?.environmentVariables;
77
+ const userEnvironment = envVars && typeof envVars === "object" && !Array.isArray(envVars) ? envVars : {};
77
78
  const opencodeUsername = DEFAULT_OPENCODE_USERNAME;
78
79
  const opencodePassword = generateOpencodeServerPassword();
79
80
  const authorization = buildOpencodeBasicAuthHeader({ username: opencodeUsername, password: opencodePassword });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neuralnomads/codenomad",
3
- "version": "0.10.3",
3
+ "version": "0.11.1",
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
  },