@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.
package/README.md CHANGED
@@ -31,6 +31,12 @@ You can run CodeNomad directly without installing it:
31
31
  npx @neuralnomads/codenomad --launch
32
32
  ```
33
33
 
34
+ To list all CLI options:
35
+
36
+ ```sh
37
+ npx @neuralnomads/codenomad --help
38
+ ```
39
+
34
40
  On startup, CodeNomad prints two URLs:
35
41
 
36
42
  - `Local Connection URL : ...` (used by desktop shells)
@@ -44,6 +50,16 @@ npm install -g @neuralnomads/codenomad
44
50
  codenomad --launch
45
51
  ```
46
52
 
53
+ ### Install Locally (per-project)
54
+ If you prefer to install CodeNomad into a project and run the local binary:
55
+
56
+ ```sh
57
+ npm install @neuralnomads/codenomad
58
+ npx codenomad --launch
59
+ ```
60
+
61
+ (`npx codenomad ...` will use `./node_modules/.bin/codenomad` when present.)
62
+
47
63
  ### Common Flags
48
64
  You can configure the server using flags or environment variables:
49
65
 
@@ -63,10 +79,30 @@ You can configure the server using flags or environment variables:
63
79
  | `--config <path>` | `CLI_CONFIG` | Config file location |
64
80
  | `--launch` | `CLI_LAUNCH` | Open the UI in a Chromium-based browser |
65
81
  | `--log-level <level>` | `CLI_LOG_LEVEL` | Logging level (trace, debug, info, warn, error) |
82
+ | `--log-destination <path>` | `CLI_LOG_DESTINATION` | Log destination file (defaults to stdout) |
66
83
  | `--username <username>` | `CODENOMAD_SERVER_USERNAME` | Username for CodeNomad's internal auth (default `codenomad`) |
67
84
  | `--password <password>` | `CODENOMAD_SERVER_PASSWORD` | Password for CodeNomad's internal auth |
68
85
  | `--generate-token` | `CODENOMAD_GENERATE_TOKEN` | Emit a one-time local bootstrap token for desktop flows |
69
86
  | `--dangerously-skip-auth` | `CODENOMAD_SKIP_AUTH` | Disable CodeNomad's internal auth (use only behind a trusted perimeter) |
87
+ | `--ui-dir <path>` | `CLI_UI_DIR` | Directory containing the built UI bundle |
88
+ | `--ui-dev-server <url>` | `CLI_UI_DEV_SERVER` | Proxy UI requests to a running dev server (requires `--https=false --http=true`) |
89
+ | `--ui-no-update` | `CLI_UI_NO_UPDATE` | Disable remote UI updates |
90
+ | `--ui-auto-update <enabled>` | `CLI_UI_AUTO_UPDATE` | Enable remote UI updates (true|false) |
91
+ | `--ui-manifest-url <url>` | `CLI_UI_MANIFEST_URL` | Remote UI manifest URL |
92
+
93
+ ### Dev Releases (Advanced)
94
+ If you want the latest bleeding-edge builds (published as GitHub pre-releases), use the dev package:
95
+
96
+ ```sh
97
+ npx @neuralnomads/codenomad-dev --launch
98
+ ```
99
+
100
+ These environment variables control how CodeNomad checks for dev updates:
101
+
102
+ | Env Variable | Description |
103
+ |-------------|-------------|
104
+ | `CODENOMAD_UPDATE_CHANNEL` | Update channel (use `dev` to enable dev build update checks) |
105
+ | `CODENOMAD_GITHUB_REPO` | GitHub repo used for dev release checks (default `NeuralNomadsAI/CodeNomad`) |
70
106
 
71
107
  ### HTTP vs HTTPS
72
108
 
@@ -0,0 +1,57 @@
1
+ import os from "os";
2
+ import path from "path";
3
+ function resolvePath(inputPath) {
4
+ if (inputPath.startsWith("~/")) {
5
+ return path.join(os.homedir(), inputPath.slice(2));
6
+ }
7
+ return path.resolve(inputPath);
8
+ }
9
+ function isYamlPath(filePath) {
10
+ const lower = filePath.toLowerCase();
11
+ return lower.endsWith(".yaml") || lower.endsWith(".yml");
12
+ }
13
+ function isJsonPath(filePath) {
14
+ return filePath.toLowerCase().endsWith(".json");
15
+ }
16
+ /**
17
+ * Resolve CodeNomad's config location into a stable base directory + derived file paths.
18
+ *
19
+ * Supported inputs:
20
+ * - Directory: "~/.config/codenomad"
21
+ * - YAML file: "~/.config/codenomad/config.yaml" (or any *.yml/*.yaml)
22
+ * - Legacy JSON file: "~/.config/codenomad/config.json"
23
+ */
24
+ export function resolveConfigLocation(raw) {
25
+ const trimmed = (raw ?? "").trim();
26
+ const fallback = "~/.config/codenomad/config.json";
27
+ const input = trimmed.length > 0 ? trimmed : fallback;
28
+ const resolvedInput = resolvePath(input);
29
+ if (isYamlPath(resolvedInput)) {
30
+ const baseDir = path.dirname(resolvedInput);
31
+ return {
32
+ baseDir,
33
+ configYamlPath: resolvedInput,
34
+ stateYamlPath: path.join(baseDir, "state.yaml"),
35
+ legacyJsonPath: path.join(baseDir, "config.json"),
36
+ instancesDir: path.join(baseDir, "instances"),
37
+ };
38
+ }
39
+ if (isJsonPath(resolvedInput)) {
40
+ const baseDir = path.dirname(resolvedInput);
41
+ return {
42
+ baseDir,
43
+ configYamlPath: path.join(baseDir, "config.yaml"),
44
+ stateYamlPath: path.join(baseDir, "state.yaml"),
45
+ legacyJsonPath: resolvedInput,
46
+ instancesDir: path.join(baseDir, "instances"),
47
+ };
48
+ }
49
+ const baseDir = resolvedInput;
50
+ return {
51
+ baseDir,
52
+ configYamlPath: path.join(baseDir, "config.yaml"),
53
+ stateYamlPath: path.join(baseDir, "state.yaml"),
54
+ legacyJsonPath: path.join(baseDir, "config.json"),
55
+ instancesDir: path.join(baseDir, "instances"),
56
+ };
57
+ }
@@ -5,7 +5,8 @@ const ModelPreferenceSchema = z.object({
5
5
  });
6
6
  const AgentModelSelectionSchema = z.record(z.string(), ModelPreferenceSchema);
7
7
  const AgentModelSelectionsSchema = z.record(z.string(), AgentModelSelectionSchema);
8
- const PreferencesSchema = z.object({
8
+ const PreferencesSchema = z
9
+ .object({
9
10
  showThinkingBlocks: z.boolean().default(false),
10
11
  thinkingBlocksExpansion: z.enum(["expanded", "collapsed"]).default("expanded"),
11
12
  showTimelineTools: z.boolean().default(true),
@@ -27,7 +28,9 @@ const PreferencesSchema = z.object({
27
28
  osNotificationsAllowWhenVisible: z.boolean().default(false),
28
29
  notifyOnNeedsInput: z.boolean().default(true),
29
30
  notifyOnIdle: z.boolean().default(true),
30
- });
31
+ })
32
+ // Preserve unknown preference keys so newer configs survive older binaries.
33
+ .passthrough();
31
34
  const RecentFolderSchema = z.object({
32
35
  path: z.string(),
33
36
  lastAccessed: z.number().nonnegative(),
@@ -38,11 +41,30 @@ const OpenCodeBinarySchema = z.object({
38
41
  lastUsed: z.number().nonnegative(),
39
42
  label: z.string().optional(),
40
43
  });
41
- const ConfigFileSchema = z.object({
44
+ const ConfigFileSchema = z
45
+ .object({
42
46
  preferences: PreferencesSchema.default({}),
43
47
  recentFolders: z.array(RecentFolderSchema).default([]),
44
48
  opencodeBinaries: z.array(OpenCodeBinarySchema).default([]),
45
49
  theme: z.enum(["light", "dark", "system"]).optional(),
46
- });
50
+ })
51
+ // Preserve unknown top-level keys so optional future features survive downgrades.
52
+ .passthrough();
53
+ // On-disk config.yaml only stores stable configuration (not volatile state like recent folders).
54
+ const ConfigYamlSchema = z
55
+ .object({
56
+ preferences: PreferencesSchema.default({}),
57
+ opencodeBinaries: z.array(OpenCodeBinarySchema).default([]),
58
+ theme: z.enum(["light", "dark", "system"]).optional(),
59
+ })
60
+ .passthrough();
61
+ // On-disk state.yaml stores server-scoped mutable state (per-server, not per-client).
62
+ const StateFileSchema = z
63
+ .object({
64
+ recentFolders: z.array(RecentFolderSchema).default([]),
65
+ })
66
+ .passthrough();
47
67
  const DEFAULT_CONFIG = ConfigFileSchema.parse({});
48
- export { ModelPreferenceSchema, AgentModelSelectionSchema, AgentModelSelectionsSchema, PreferencesSchema, RecentFolderSchema, OpenCodeBinarySchema, ConfigFileSchema, DEFAULT_CONFIG, };
68
+ const DEFAULT_CONFIG_YAML = ConfigYamlSchema.parse({});
69
+ const DEFAULT_STATE = StateFileSchema.parse({});
70
+ export { ModelPreferenceSchema, AgentModelSelectionSchema, AgentModelSelectionsSchema, PreferencesSchema, RecentFolderSchema, OpenCodeBinarySchema, ConfigFileSchema, ConfigYamlSchema, StateFileSchema, DEFAULT_CONFIG, DEFAULT_CONFIG_YAML, DEFAULT_STATE, };
@@ -20,8 +20,8 @@ export class EventBus extends EventEmitter {
20
20
  this.on("workspace.error", handler);
21
21
  this.on("workspace.stopped", handler);
22
22
  this.on("workspace.log", handler);
23
- this.on("config.appChanged", handler);
24
- this.on("config.binariesChanged", handler);
23
+ this.on("storage.configChanged", handler);
24
+ this.on("storage.stateChanged", handler);
25
25
  this.on("instance.dataChanged", handler);
26
26
  this.on("instance.event", handler);
27
27
  this.on("instance.eventStatus", handler);
@@ -31,8 +31,8 @@ export class EventBus extends EventEmitter {
31
31
  this.off("workspace.error", handler);
32
32
  this.off("workspace.stopped", handler);
33
33
  this.off("workspace.log", handler);
34
- this.off("config.appChanged", handler);
35
- this.off("config.binariesChanged", handler);
34
+ this.off("storage.configChanged", handler);
35
+ this.off("storage.stateChanged", handler);
36
36
  this.off("instance.dataChanged", handler);
37
37
  this.off("instance.event", handler);
38
38
  this.off("instance.eventStatus", handler);
package/dist/index.js CHANGED
@@ -8,8 +8,9 @@ import { fileURLToPath } from "url";
8
8
  import { createRequire } from "module";
9
9
  import { createHttpServer } from "./server/http-server";
10
10
  import { WorkspaceManager } from "./workspaces/manager";
11
- import { ConfigStore } from "./config/store";
12
- import { BinaryRegistry } from "./config/binaries";
11
+ import { resolveConfigLocation } from "./config/location";
12
+ import { SettingsService } from "./settings/service";
13
+ import { BinaryResolver } from "./settings/binaries";
13
14
  import { FileSystemBrowser } from "./filesystem/browser";
14
15
  import { EventBus } from "./events/bus";
15
16
  import { InstanceStore } from "./storage/instance-store";
@@ -20,6 +21,7 @@ import { resolveUi } from "./ui/remote-ui";
20
21
  import { AuthManager, BOOTSTRAP_TOKEN_STDOUT_PREFIX, DEFAULT_AUTH_USERNAME } from "./auth/manager";
21
22
  import { resolveHttpsOptions } from "./server/tls";
22
23
  import { resolveNetworkAddresses } from "./server/network-addresses";
24
+ import { startDevReleaseMonitor } from "./releases/dev-release-monitor";
23
25
  const require = createRequire(import.meta.url);
24
26
  const packageJson = require("../package.json");
25
27
  const __filename = fileURLToPath(import.meta.url);
@@ -126,12 +128,6 @@ function resolveHost(input) {
126
128
  }
127
129
  return trimmed;
128
130
  }
129
- function resolvePath(filePath) {
130
- if (filePath.startsWith("~/")) {
131
- return path.join(process.env.HOME ?? "", filePath.slice(2));
132
- }
133
- return path.resolve(filePath);
134
- }
135
131
  function programHasArg(argv, flag) {
136
132
  return argv.includes(flag);
137
133
  }
@@ -151,7 +147,8 @@ async function main() {
151
147
  }
152
148
  const eventBus = new EventBus(eventLogger);
153
149
  const isLoopbackHost = (host) => host === "127.0.0.1" || host === "::1" || host.startsWith("127.");
154
- const configDir = path.dirname(resolvePath(options.configPath));
150
+ const configLocation = resolveConfigLocation(options.configPath);
151
+ const configDir = configLocation.baseDir;
155
152
  if ((options.tlsKeyPath && !options.tlsCertPath) || (!options.tlsKeyPath && options.tlsCertPath)) {
156
153
  throw new InvalidArgumentError("--tls-key and --tls-cert must be provided together");
157
154
  }
@@ -168,7 +165,7 @@ async function main() {
168
165
  addresses: [],
169
166
  };
170
167
  const authManager = new AuthManager({
171
- configPath: options.configPath,
168
+ configPath: configLocation.configYamlPath,
172
169
  username: options.authUsername,
173
170
  password: options.authPassword,
174
171
  generateToken: options.generateToken,
@@ -191,19 +188,19 @@ async function main() {
191
188
  logger: logger.child({ component: "tls" }),
192
189
  });
193
190
  const nodeExtraCaCertsPath = !options.http ? tlsResolution?.caCertPath : undefined;
194
- const configStore = new ConfigStore(options.configPath, eventBus, configLogger);
195
- const binaryRegistry = new BinaryRegistry(configStore, eventBus, configLogger);
191
+ const settings = new SettingsService(configLocation, eventBus, configLogger);
192
+ const binaryResolver = new BinaryResolver(settings);
196
193
  const workspaceManager = new WorkspaceManager({
197
194
  rootDir: options.rootDir,
198
- configStore,
199
- binaryRegistry,
195
+ settings,
196
+ binaryResolver,
200
197
  eventBus,
201
198
  logger: workspaceLogger,
202
199
  getServerBaseUrl: () => serverMeta.localUrl,
203
200
  nodeExtraCaCertsPath,
204
201
  });
205
202
  const fileSystemBrowser = new FileSystemBrowser({ rootDir: options.rootDir, unrestricted: options.unrestrictedRoot });
206
- const instanceStore = new InstanceStore();
203
+ const instanceStore = new InstanceStore(configLocation.instancesDir);
207
204
  const instanceEventBridge = new InstanceEventBridge({
208
205
  workspaceManager,
209
206
  eventBus,
@@ -235,6 +232,20 @@ async function main() {
235
232
  latestServerUrl: uiResolution.latestServerUrl,
236
233
  minServerVersion: uiResolution.minServerVersion,
237
234
  };
235
+ const updateChannel = (process.env.CODENOMAD_UPDATE_CHANNEL ?? "").trim().toLowerCase();
236
+ const githubRepo = (process.env.CODENOMAD_GITHUB_REPO ?? "NeuralNomadsAI/CodeNomad").trim();
237
+ const isDevVersion = packageJson.version.includes("-dev.") || packageJson.version.includes("-dev-");
238
+ const enableDevUpdateChecks = updateChannel === "dev" || (updateChannel === "" && isDevVersion);
239
+ const devReleaseMonitor = enableDevUpdateChecks
240
+ ? startDevReleaseMonitor({
241
+ currentVersion: packageJson.version,
242
+ repo: githubRepo,
243
+ logger: logger.child({ component: "updates" }),
244
+ onUpdate: (release) => {
245
+ serverMeta.update = release;
246
+ },
247
+ })
248
+ : null;
238
249
  if (uiResolution.uiDevServerUrl && options.https) {
239
250
  throw new InvalidArgumentError("UI dev proxy is only supported with --https=false --http=true");
240
251
  }
@@ -257,8 +268,7 @@ async function main() {
257
268
  defaultPort: options.httpPort,
258
269
  protocol: "http",
259
270
  workspaceManager,
260
- configStore,
261
- binaryRegistry,
271
+ settings,
262
272
  fileSystemBrowser,
263
273
  eventBus,
264
274
  serverMeta,
@@ -277,8 +287,7 @@ async function main() {
277
287
  protocol: "https",
278
288
  httpsOptions: tlsResolution?.httpsOptions,
279
289
  workspaceManager,
280
- configStore,
281
- binaryRegistry,
290
+ settings,
282
291
  fileSystemBrowser,
283
292
  eventBus,
284
293
  serverMeta,
@@ -377,6 +386,7 @@ async function main() {
377
386
  })();
378
387
  await Promise.allSettled([shutdownWorkspaces, shutdownHttp]);
379
388
  // no-op: remote UI manifest replaces GitHub release monitor
389
+ devReleaseMonitor?.stop();
380
390
  logger.info("Exiting process");
381
391
  process.exit(0);
382
392
  };
@@ -4,6 +4,6 @@
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "dependencies": {
7
- "@opencode-ai/plugin": "1.1.53"
7
+ "@opencode-ai/plugin": "1.2.4"
8
8
  }
9
- }
9
+ }
@@ -0,0 +1,75 @@
1
+ import { fetch } from "undici";
2
+ import { compareVersionStrings, stripTagPrefix } from "./release-monitor";
3
+ const DEFAULT_POLL_INTERVAL_MS = 15 * 60 * 1000;
4
+ export function startDevReleaseMonitor(options) {
5
+ let stopped = false;
6
+ let timer = null;
7
+ const pollIntervalMs = Number.isFinite(options.pollIntervalMs) && (options.pollIntervalMs ?? 0) > 0
8
+ ? options.pollIntervalMs
9
+ : DEFAULT_POLL_INTERVAL_MS;
10
+ const refresh = async () => {
11
+ if (stopped)
12
+ return;
13
+ try {
14
+ const release = await fetchLatestPrerelease({
15
+ repo: options.repo,
16
+ currentVersion: options.currentVersion,
17
+ });
18
+ options.onUpdate(release);
19
+ }
20
+ catch (error) {
21
+ options.logger.debug({ err: error }, "Failed to refresh dev prerelease information");
22
+ }
23
+ };
24
+ void refresh();
25
+ timer = setInterval(() => void refresh(), pollIntervalMs);
26
+ return {
27
+ stop() {
28
+ stopped = true;
29
+ if (timer) {
30
+ clearInterval(timer);
31
+ timer = null;
32
+ }
33
+ },
34
+ };
35
+ }
36
+ async function fetchLatestPrerelease(args) {
37
+ const normalizedRepo = args.repo.trim();
38
+ if (!/^[^/\s]+\/[^/\s]+$/.test(normalizedRepo)) {
39
+ throw new Error(`Invalid GitHub repo: ${args.repo}`);
40
+ }
41
+ const apiUrl = `https://api.github.com/repos/${normalizedRepo}/releases?per_page=20`;
42
+ const response = await fetch(apiUrl, {
43
+ headers: {
44
+ Accept: "application/vnd.github+json",
45
+ "User-Agent": "CodeNomad-CLI",
46
+ },
47
+ });
48
+ if (!response.ok) {
49
+ throw new Error(`GitHub releases API responded with ${response.status}`);
50
+ }
51
+ const list = (await response.json());
52
+ const latest = list.find((r) => r && r.prerelease === true && r.draft !== true);
53
+ if (!latest) {
54
+ return null;
55
+ }
56
+ const tag = latest.tag_name || latest.name;
57
+ if (!tag) {
58
+ return null;
59
+ }
60
+ const normalizedVersion = stripTagPrefix(tag);
61
+ if (!normalizedVersion) {
62
+ return null;
63
+ }
64
+ if (compareVersionStrings(normalizedVersion, args.currentVersion) <= 0) {
65
+ return null;
66
+ }
67
+ return {
68
+ version: normalizedVersion,
69
+ tag,
70
+ url: latest.html_url ?? `https://github.com/${normalizedRepo}/releases/tag/${encodeURIComponent(tag)}`,
71
+ channel: "dev",
72
+ publishedAt: latest.published_at ?? latest.created_at,
73
+ notes: latest.body,
74
+ };
75
+ }
@@ -20,6 +20,11 @@ export function startReleaseMonitor(options) {
20
20
  },
21
21
  };
22
22
  }
23
+ export function compareVersionStrings(a, b) {
24
+ const left = parseVersion(a);
25
+ const right = parseVersion(b);
26
+ return compareVersions(left, right);
27
+ }
23
28
  async function fetchLatestRelease(options) {
24
29
  const response = await fetch(RELEASES_API_URL, {
25
30
  headers: {
@@ -53,7 +58,7 @@ async function fetchLatestRelease(options) {
53
58
  notes: json.body,
54
59
  };
55
60
  }
56
- function stripTagPrefix(tag) {
61
+ export function stripTagPrefix(tag) {
57
62
  if (!tag)
58
63
  return null;
59
64
  const trimmed = tag.trim();
@@ -63,7 +68,9 @@ function stripTagPrefix(tag) {
63
68
  }
64
69
  function parseVersion(value) {
65
70
  const normalized = stripTagPrefix(value) ?? "0.0.0";
66
- const [core, prerelease = null] = normalized.split("-", 2);
71
+ const dashIndex = normalized.indexOf("-");
72
+ const core = dashIndex >= 0 ? normalized.slice(0, dashIndex) : normalized;
73
+ const prerelease = dashIndex >= 0 ? normalized.slice(dashIndex + 1) : null;
67
74
  const [major = 0, minor = 0, patch = 0] = core.split(".").map((segment) => {
68
75
  const parsed = Number.parseInt(segment, 10);
69
76
  return Number.isFinite(parsed) ? parsed : 0;
@@ -7,7 +7,7 @@ import path from "path";
7
7
  import { fetch } from "undici";
8
8
  import { isValidWorktreeSlug, listWorktrees, resolveRepoRoot } from "../workspaces/git-worktrees";
9
9
  import { registerWorkspaceRoutes } from "./routes/workspaces";
10
- import { registerConfigRoutes } from "./routes/config";
10
+ import { registerSettingsRoutes } from "./routes/settings";
11
11
  import { registerFilesystemRoutes } from "./routes/filesystem";
12
12
  import { registerMetaRoutes } from "./routes/meta";
13
13
  import { registerEventRoutes } from "./routes/events";
@@ -181,7 +181,7 @@ export function createHttpServer(deps) {
181
181
  reply.code(404).send({ message: "UI bundle missing" });
182
182
  });
183
183
  registerWorkspaceRoutes(app, { workspaceManager: deps.workspaceManager });
184
- registerConfigRoutes(app, { configStore: deps.configStore, binaryRegistry: deps.binaryRegistry });
184
+ registerSettingsRoutes(app, { settings: deps.settings, logger: apiLogger });
185
185
  registerFilesystemRoutes(app, { fileSystemBrowser: deps.fileSystemBrowser });
186
186
  registerMetaRoutes(app, { serverMeta: deps.serverMeta });
187
187
  registerEventRoutes(app, { eventBus: deps.eventBus, registerClient: registerSseClient, logger: sseLogger });
@@ -0,0 +1,96 @@
1
+ import { z } from "zod";
2
+ import { spawnSync } from "child_process";
3
+ import { buildSpawnSpec } from "../../workspaces/runtime";
4
+ const ValidateBinarySchema = z.object({
5
+ path: z.string(),
6
+ });
7
+ function validateBinaryPath(binaryPath) {
8
+ if (!binaryPath) {
9
+ return { valid: false, error: "Missing binary path" };
10
+ }
11
+ const spec = buildSpawnSpec(binaryPath, ["--version"]);
12
+ try {
13
+ const result = spawnSync(spec.command, spec.args, {
14
+ encoding: "utf8",
15
+ windowsVerbatimArguments: Boolean(spec.options.windowsVerbatimArguments),
16
+ });
17
+ if (result.error) {
18
+ return { valid: false, error: result.error.message };
19
+ }
20
+ if (result.status !== 0) {
21
+ const stderr = result.stderr?.trim();
22
+ const stdout = result.stdout?.trim();
23
+ const combined = stderr || stdout;
24
+ const error = combined ? `Exited with code ${result.status}: ${combined}` : `Exited with code ${result.status}`;
25
+ return { valid: false, error };
26
+ }
27
+ const stdout = (result.stdout ?? "").trim();
28
+ const firstLine = stdout.split(/\r?\n/).find((line) => line.trim().length > 0);
29
+ const normalized = firstLine?.trim();
30
+ const versionMatch = normalized?.match(/([0-9]+\.[0-9]+\.[0-9A-Za-z.-]+)/);
31
+ const version = versionMatch?.[1];
32
+ return { valid: true, version };
33
+ }
34
+ catch (error) {
35
+ return { valid: false, error: error instanceof Error ? error.message : String(error) };
36
+ }
37
+ }
38
+ export function registerSettingsRoutes(app, deps) {
39
+ // Full-document access
40
+ app.get("/api/storage/config", async () => deps.settings.getDoc("config"));
41
+ app.patch("/api/storage/config", async (request, reply) => {
42
+ try {
43
+ return deps.settings.mergePatchDoc("config", request.body ?? {});
44
+ }
45
+ catch (error) {
46
+ reply.code(400);
47
+ return { error: error instanceof Error ? error.message : "Invalid patch" };
48
+ }
49
+ });
50
+ app.get("/api/storage/config/:owner", async (request) => {
51
+ return deps.settings.getOwner("config", request.params.owner);
52
+ });
53
+ app.patch("/api/storage/config/:owner", async (request, reply) => {
54
+ try {
55
+ return deps.settings.mergePatchOwner("config", request.params.owner, request.body ?? {});
56
+ }
57
+ catch (error) {
58
+ reply.code(400);
59
+ return { error: error instanceof Error ? error.message : "Invalid patch" };
60
+ }
61
+ });
62
+ app.get("/api/storage/state", async () => deps.settings.getDoc("state"));
63
+ app.patch("/api/storage/state", async (request, reply) => {
64
+ try {
65
+ return deps.settings.mergePatchDoc("state", request.body ?? {});
66
+ }
67
+ catch (error) {
68
+ reply.code(400);
69
+ return { error: error instanceof Error ? error.message : "Invalid patch" };
70
+ }
71
+ });
72
+ app.get("/api/storage/state/:owner", async (request) => {
73
+ return deps.settings.getOwner("state", request.params.owner);
74
+ });
75
+ app.patch("/api/storage/state/:owner", async (request, reply) => {
76
+ try {
77
+ return deps.settings.mergePatchOwner("state", request.params.owner, request.body ?? {});
78
+ }
79
+ catch (error) {
80
+ reply.code(400);
81
+ return { error: error instanceof Error ? error.message : "Invalid patch" };
82
+ }
83
+ });
84
+ // Binary validation helper (used by UI when adding binaries)
85
+ app.post("/api/storage/binaries/validate", async (request, reply) => {
86
+ try {
87
+ const body = ValidateBinarySchema.parse(request.body ?? {});
88
+ return validateBinaryPath(body.path);
89
+ }
90
+ catch (error) {
91
+ deps.logger.warn({ err: error }, "Failed to validate binary");
92
+ reply.code(400);
93
+ return { valid: false, error: error instanceof Error ? error.message : "Invalid request" };
94
+ }
95
+ });
96
+ }
@@ -0,0 +1,37 @@
1
+ function prettyLabel(p) {
2
+ const parts = p.split(/[\\/]/);
3
+ const last = parts[parts.length - 1] || p;
4
+ return last || p;
5
+ }
6
+ function readUiBinaries(settings) {
7
+ const ui = settings.getOwner("state", "ui");
8
+ const list = ui?.opencodeBinaries;
9
+ if (!Array.isArray(list))
10
+ return [];
11
+ return list.filter((item) => item && typeof item === "object" && typeof item.path === "string");
12
+ }
13
+ function readDefaultBinaryPath(settings) {
14
+ const server = settings.getOwner("config", "server");
15
+ const value = server?.opencodeBinary;
16
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
17
+ }
18
+ export class BinaryResolver {
19
+ constructor(settings) {
20
+ this.settings = settings;
21
+ }
22
+ list() {
23
+ return readUiBinaries(this.settings);
24
+ }
25
+ resolveDefault() {
26
+ const binaries = this.list();
27
+ const configuredDefault = readDefaultBinaryPath(this.settings);
28
+ const fallback = binaries[0]?.path;
29
+ const path = configuredDefault ?? fallback ?? "opencode";
30
+ const entry = binaries.find((b) => b.path === path);
31
+ return {
32
+ path,
33
+ label: entry?.label ?? prettyLabel(path),
34
+ version: entry?.version,
35
+ };
36
+ }
37
+ }
@@ -0,0 +1,33 @@
1
+ export function isPlainObject(value) {
2
+ if (!value || typeof value !== "object")
3
+ return false;
4
+ if (Array.isArray(value))
5
+ return false;
6
+ const proto = Object.getPrototypeOf(value);
7
+ return proto === Object.prototype || proto === null;
8
+ }
9
+ /**
10
+ * RFC 7396-ish merge patch with explicit null deletes.
11
+ * - Objects merge recursively
12
+ * - Arrays/scalars replace
13
+ * - null deletes keys
14
+ */
15
+ export function applyMergePatch(current, patch) {
16
+ if (!isPlainObject(patch)) {
17
+ return patch;
18
+ }
19
+ const base = isPlainObject(current) ? { ...current } : {};
20
+ for (const [key, value] of Object.entries(patch)) {
21
+ if (value === null) {
22
+ delete base[key];
23
+ continue;
24
+ }
25
+ const existing = base[key];
26
+ if (isPlainObject(value) && isPlainObject(existing)) {
27
+ base[key] = applyMergePatch(existing, value);
28
+ continue;
29
+ }
30
+ base[key] = value;
31
+ }
32
+ return base;
33
+ }