@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.
- package/README.md +48 -1
- package/dist/config/location.js +57 -0
- package/dist/config/schema.js +27 -5
- package/dist/events/bus.js +4 -4
- package/dist/index.js +30 -20
- package/dist/opencode-config/package.json +1 -1
- package/dist/releases/dev-release-monitor.js +75 -0
- package/dist/releases/release-monitor.js +9 -2
- package/dist/server/http-server.js +121 -11
- package/dist/server/routes/auth-pages/login.html +2 -1
- package/dist/server/routes/auth.js +15 -1
- package/dist/server/routes/settings.js +68 -0
- package/dist/settings/binaries.js +37 -0
- package/dist/settings/merge-patch.js +33 -0
- package/dist/settings/migrate.js +233 -0
- package/dist/settings/service.js +39 -0
- package/dist/settings/yaml-doc-store.js +96 -0
- package/dist/workspaces/manager.js +22 -41
- package/dist/workspaces/runtime.js +42 -0
- package/package.json +2 -1
- package/public/assets/index-BiJPCeIN.js +1 -0
- package/public/assets/index-YOE16xUu.css +1 -0
- package/public/assets/{loading-C4tjRBOI.js → loading-VAPQCa2j.js} +1 -1
- package/public/assets/main-BY3Fy6Si.js +250 -0
- package/public/index.html +3 -3
- package/public/loading.html +3 -3
- package/public/sw.js +1 -1
- package/public/ui-version.json +1 -1
- package/dist/config/binaries.js +0 -148
- package/dist/config/store.js +0 -69
- package/dist/server/routes/config.js +0 -44
- package/public/assets/index-ByYHPepg.css +0 -1
- package/public/assets/index-qAVOl_b1.js +0 -1
- package/public/assets/main-D-G7fZxM.js +0 -188
|
@@ -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 {
|
|
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
|
-
|
|
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 });
|
|
@@ -282,6 +282,20 @@ function registerInstanceProxyRoutes(app, deps) {
|
|
|
282
282
|
});
|
|
283
283
|
}
|
|
284
284
|
const INSTANCE_PROXY_HOST = "127.0.0.1";
|
|
285
|
+
// Special-case OpenCode directory override.
|
|
286
|
+
//
|
|
287
|
+
// UI clients may need to scope certain requests to an arbitrary directory that is not
|
|
288
|
+
// part of the Git worktree list. Since the OpenCode SDK does not reliably support
|
|
289
|
+
// injecting per-request headers, we encode an override into the *path* and strip it
|
|
290
|
+
// before proxying to the instance.
|
|
291
|
+
//
|
|
292
|
+
// Example proxied request path:
|
|
293
|
+
// /workspaces/:id/worktrees/:slug/instance/__dir/<base64url>/session/create
|
|
294
|
+
//
|
|
295
|
+
// The server will decode <base64url> -> absolute directory, validate it, then set
|
|
296
|
+
// x-opencode-directory accordingly and forward the request to /session/create.
|
|
297
|
+
const OPENCODE_DIR_OVERRIDE_PREFIX = "__dir/";
|
|
298
|
+
const OPENCODE_DIR_OVERRIDE_MAX_LEN = 4096;
|
|
285
299
|
async function proxyWorkspaceRequest(args) {
|
|
286
300
|
const { request, reply, workspaceManager, logger, worktreeSlug } = args;
|
|
287
301
|
const workspaceId = request.params.id;
|
|
@@ -357,17 +371,43 @@ async function proxyWorkspaceRequest(args) {
|
|
|
357
371
|
reply.code(400).send({ error: "Invalid worktree slug" });
|
|
358
372
|
return;
|
|
359
373
|
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
reply.code(404).send({ error: "Worktree not found" });
|
|
374
|
+
let extracted;
|
|
375
|
+
try {
|
|
376
|
+
extracted = extractOpencodeDirectoryOverride(args.pathSuffix);
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
const message = error instanceof Error ? error.message : "Invalid directory override";
|
|
380
|
+
reply.code(400).send({ error: message });
|
|
368
381
|
return;
|
|
369
382
|
}
|
|
370
|
-
|
|
383
|
+
let directory = null;
|
|
384
|
+
let forwardedSuffix = extracted.forwardedSuffix;
|
|
385
|
+
if (extracted.overrideDirectory) {
|
|
386
|
+
try {
|
|
387
|
+
directory = validateAndNormalizeOverrideDirectory({
|
|
388
|
+
overrideDirectory: extracted.overrideDirectory,
|
|
389
|
+
workspaceRoot: workspace.path,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
const message = error instanceof Error ? error.message : "Invalid directory override";
|
|
394
|
+
reply.code(400).send({ error: message });
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
else {
|
|
399
|
+
directory = await resolveWorktreeDirectory({
|
|
400
|
+
workspaceId,
|
|
401
|
+
workspacePath: workspace.path,
|
|
402
|
+
worktreeSlug,
|
|
403
|
+
logger,
|
|
404
|
+
});
|
|
405
|
+
if (!directory) {
|
|
406
|
+
reply.code(404).send({ error: "Worktree not found" });
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const normalizedSuffix = normalizeInstanceSuffix(forwardedSuffix);
|
|
371
411
|
const queryIndex = (request.raw.url ?? "").indexOf("?");
|
|
372
412
|
const search = queryIndex >= 0 ? (request.raw.url ?? "").slice(queryIndex) : "";
|
|
373
413
|
const targetUrl = `http://${INSTANCE_PROXY_HOST}:${port}${normalizedSuffix}${search}`;
|
|
@@ -418,6 +458,76 @@ async function proxyWorkspaceRequest(args) {
|
|
|
418
458
|
},
|
|
419
459
|
});
|
|
420
460
|
}
|
|
461
|
+
function extractOpencodeDirectoryOverride(pathSuffix) {
|
|
462
|
+
if (!pathSuffix) {
|
|
463
|
+
return { overrideDirectory: null, forwardedSuffix: pathSuffix };
|
|
464
|
+
}
|
|
465
|
+
// Fastify wildcard param does not include a leading slash.
|
|
466
|
+
const trimmed = pathSuffix.replace(/^\/+/, "");
|
|
467
|
+
if (!trimmed.startsWith(OPENCODE_DIR_OVERRIDE_PREFIX)) {
|
|
468
|
+
return { overrideDirectory: null, forwardedSuffix: pathSuffix };
|
|
469
|
+
}
|
|
470
|
+
const rest = trimmed.slice(OPENCODE_DIR_OVERRIDE_PREFIX.length);
|
|
471
|
+
const slashIndex = rest.indexOf("/");
|
|
472
|
+
const encoded = (slashIndex >= 0 ? rest.slice(0, slashIndex) : rest).trim();
|
|
473
|
+
const remaining = slashIndex >= 0 ? rest.slice(slashIndex + 1) : "";
|
|
474
|
+
if (!encoded) {
|
|
475
|
+
throw new Error("Missing directory override");
|
|
476
|
+
}
|
|
477
|
+
if (encoded.length > OPENCODE_DIR_OVERRIDE_MAX_LEN) {
|
|
478
|
+
throw new Error("Directory override too large");
|
|
479
|
+
}
|
|
480
|
+
let overrideDirectory = "";
|
|
481
|
+
try {
|
|
482
|
+
overrideDirectory = decodeBase64Url(encoded);
|
|
483
|
+
}
|
|
484
|
+
catch {
|
|
485
|
+
throw new Error("Invalid directory override");
|
|
486
|
+
}
|
|
487
|
+
const forwardedSuffix = remaining;
|
|
488
|
+
return { overrideDirectory, forwardedSuffix };
|
|
489
|
+
}
|
|
490
|
+
function decodeBase64Url(input) {
|
|
491
|
+
// base64url -> base64
|
|
492
|
+
const normalized = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
493
|
+
const padding = normalized.length % 4 === 0 ? "" : "=".repeat(4 - (normalized.length % 4));
|
|
494
|
+
const base64 = `${normalized}${padding}`;
|
|
495
|
+
return Buffer.from(base64, "base64").toString("utf-8");
|
|
496
|
+
}
|
|
497
|
+
function validateAndNormalizeOverrideDirectory(params) {
|
|
498
|
+
const raw = params.overrideDirectory.trim();
|
|
499
|
+
if (!raw) {
|
|
500
|
+
throw new Error("Override directory is empty");
|
|
501
|
+
}
|
|
502
|
+
if (!path.isAbsolute(raw)) {
|
|
503
|
+
throw new Error("Override directory must be an absolute path");
|
|
504
|
+
}
|
|
505
|
+
if (!fs.existsSync(raw)) {
|
|
506
|
+
throw new Error(`Override directory does not exist: ${raw}`);
|
|
507
|
+
}
|
|
508
|
+
const stats = fs.statSync(raw);
|
|
509
|
+
if (!stats.isDirectory()) {
|
|
510
|
+
throw new Error(`Override path is not a directory: ${raw}`);
|
|
511
|
+
}
|
|
512
|
+
const normalizedOverride = fs.realpathSync(raw);
|
|
513
|
+
const normalizedRoot = fs.realpathSync(params.workspaceRoot);
|
|
514
|
+
if (!isSubpath(normalizedOverride, normalizedRoot)) {
|
|
515
|
+
throw new Error("Override directory must be within the workspace root");
|
|
516
|
+
}
|
|
517
|
+
return normalizedOverride;
|
|
518
|
+
}
|
|
519
|
+
function isSubpath(candidate, root) {
|
|
520
|
+
const rel = path.relative(root, candidate);
|
|
521
|
+
if (rel === "")
|
|
522
|
+
return true;
|
|
523
|
+
if (rel === "..")
|
|
524
|
+
return false;
|
|
525
|
+
if (rel.startsWith(`..${path.sep}`))
|
|
526
|
+
return false;
|
|
527
|
+
if (path.isAbsolute(rel))
|
|
528
|
+
return false;
|
|
529
|
+
return true;
|
|
530
|
+
}
|
|
421
531
|
function normalizeInstanceSuffix(pathSuffix) {
|
|
422
532
|
if (!pathSuffix || pathSuffix === "/") {
|
|
423
533
|
return "/";
|
|
@@ -119,7 +119,8 @@
|
|
|
119
119
|
showError(message || `Login failed (${res.status})`)
|
|
120
120
|
return
|
|
121
121
|
}
|
|
122
|
-
|
|
122
|
+
// Replace history entry so Back doesn't return to /login.
|
|
123
|
+
window.location.replace("/")
|
|
123
124
|
} catch (e) {
|
|
124
125
|
showError(e && e.message ? e.message : String(e))
|
|
125
126
|
}
|
|
@@ -35,7 +35,17 @@ function getTokenHtml() {
|
|
|
35
35
|
return cachedTokenTemplate;
|
|
36
36
|
}
|
|
37
37
|
export function registerAuthRoutes(app, deps) {
|
|
38
|
-
app.get("/login", async (
|
|
38
|
+
app.get("/login", async (request, reply) => {
|
|
39
|
+
// If already authenticated, don't show the login page.
|
|
40
|
+
const session = deps.authManager.getSessionFromRequest(request);
|
|
41
|
+
if (session) {
|
|
42
|
+
reply.redirect("/");
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
// Avoid caching the login page (helps with bfcache/back behavior).
|
|
46
|
+
reply.header("Cache-Control", "no-store");
|
|
47
|
+
reply.header("Pragma", "no-cache");
|
|
48
|
+
reply.header("Expires", "0");
|
|
39
49
|
const status = deps.authManager.getStatus();
|
|
40
50
|
reply.type("text/html").send(getLoginHtml(status.username));
|
|
41
51
|
});
|
|
@@ -48,6 +58,10 @@ export function registerAuthRoutes(app, deps) {
|
|
|
48
58
|
reply.code(404).send({ error: "Not found" });
|
|
49
59
|
return;
|
|
50
60
|
}
|
|
61
|
+
// Avoid caching the token bootstrap page.
|
|
62
|
+
reply.header("Cache-Control", "no-store");
|
|
63
|
+
reply.header("Pragma", "no-cache");
|
|
64
|
+
reply.header("Expires", "0");
|
|
51
65
|
reply.type("text/html").send(getTokenHtml());
|
|
52
66
|
});
|
|
53
67
|
app.get("/api/auth/status", async (request, reply) => {
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { probeBinaryVersion } from "../../workspaces/runtime";
|
|
3
|
+
const ValidateBinarySchema = z.object({
|
|
4
|
+
path: z.string(),
|
|
5
|
+
});
|
|
6
|
+
function validateBinaryPath(binaryPath) {
|
|
7
|
+
const result = probeBinaryVersion(binaryPath);
|
|
8
|
+
return { valid: result.valid, version: result.version, error: result.error };
|
|
9
|
+
}
|
|
10
|
+
export function registerSettingsRoutes(app, deps) {
|
|
11
|
+
// Full-document access
|
|
12
|
+
app.get("/api/storage/config", async () => deps.settings.getDoc("config"));
|
|
13
|
+
app.patch("/api/storage/config", async (request, reply) => {
|
|
14
|
+
try {
|
|
15
|
+
return deps.settings.mergePatchDoc("config", request.body ?? {});
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
reply.code(400);
|
|
19
|
+
return { error: error instanceof Error ? error.message : "Invalid patch" };
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
app.get("/api/storage/config/:owner", async (request) => {
|
|
23
|
+
return deps.settings.getOwner("config", request.params.owner);
|
|
24
|
+
});
|
|
25
|
+
app.patch("/api/storage/config/:owner", async (request, reply) => {
|
|
26
|
+
try {
|
|
27
|
+
return deps.settings.mergePatchOwner("config", request.params.owner, request.body ?? {});
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
reply.code(400);
|
|
31
|
+
return { error: error instanceof Error ? error.message : "Invalid patch" };
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
app.get("/api/storage/state", async () => deps.settings.getDoc("state"));
|
|
35
|
+
app.patch("/api/storage/state", async (request, reply) => {
|
|
36
|
+
try {
|
|
37
|
+
return deps.settings.mergePatchDoc("state", request.body ?? {});
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
reply.code(400);
|
|
41
|
+
return { error: error instanceof Error ? error.message : "Invalid patch" };
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
app.get("/api/storage/state/:owner", async (request) => {
|
|
45
|
+
return deps.settings.getOwner("state", request.params.owner);
|
|
46
|
+
});
|
|
47
|
+
app.patch("/api/storage/state/:owner", async (request, reply) => {
|
|
48
|
+
try {
|
|
49
|
+
return deps.settings.mergePatchOwner("state", request.params.owner, request.body ?? {});
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
reply.code(400);
|
|
53
|
+
return { error: error instanceof Error ? error.message : "Invalid patch" };
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
// Binary validation helper (used by UI when adding binaries)
|
|
57
|
+
app.post("/api/storage/binaries/validate", async (request, reply) => {
|
|
58
|
+
try {
|
|
59
|
+
const body = ValidateBinarySchema.parse(request.body ?? {});
|
|
60
|
+
return validateBinaryPath(body.path);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
deps.logger.warn({ err: error }, "Failed to validate binary");
|
|
64
|
+
reply.code(400);
|
|
65
|
+
return { valid: false, error: error instanceof Error ? error.message : "Invalid request" };
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|