@neuralnomads/codenomad 0.13.3 → 0.15.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.
Files changed (92) hide show
  1. package/dist/auth/manager.js +5 -1
  2. package/dist/background-processes/manager.js +164 -25
  3. package/dist/cli-upgrade.js +53 -0
  4. package/dist/cli-upgrade.test.js +31 -0
  5. package/dist/config/schema.js +1 -0
  6. package/dist/events/bus.js +4 -0
  7. package/dist/filesystem/browser.js +15 -1
  8. package/dist/index.js +79 -11
  9. package/dist/opencode-config/package-lock.json +380 -0
  10. package/dist/opencode-config/package.json +2 -2
  11. package/dist/opencode-config/plugin/lib/background-process.ts +14 -2
  12. package/dist/plugins/voice-mode.js +2 -1
  13. package/dist/server/__tests__/network-addresses.test.js +68 -0
  14. package/dist/server/__tests__/remote-proxy.test.js +204 -0
  15. package/dist/server/http-server.js +292 -47
  16. package/dist/server/network-addresses.js +43 -1
  17. package/dist/server/remote-proxy.js +466 -0
  18. package/dist/server/routes/background-processes.js +19 -1
  19. package/dist/server/routes/meta.js +0 -3
  20. package/dist/server/routes/plugin.js +5 -1
  21. package/dist/server/routes/remote-proxy.js +42 -0
  22. package/dist/server/routes/remote-servers.js +142 -0
  23. package/dist/server/routes/settings.js +1 -1
  24. package/dist/server/routes/sidecars.js +46 -0
  25. package/dist/server/routes/workspaces.js +118 -0
  26. package/dist/settings/migrate.js +5 -0
  27. package/dist/settings/service.js +64 -4
  28. package/dist/sidecars/manager.js +193 -0
  29. package/dist/workspaces/__tests__/git-worktrees.test.js +43 -0
  30. package/dist/workspaces/__tests__/spawn.test.js +140 -0
  31. package/dist/workspaces/git-mutations.js +98 -0
  32. package/dist/workspaces/git-status.js +323 -0
  33. package/dist/workspaces/git-worktrees.js +18 -1
  34. package/dist/workspaces/manager.js +11 -4
  35. package/dist/workspaces/opencode-auth.js +18 -0
  36. package/dist/workspaces/opencode-auth.test.js +34 -0
  37. package/dist/workspaces/runtime.js +56 -78
  38. package/dist/workspaces/spawn.js +219 -0
  39. package/dist/workspaces/worktree-directory.js +74 -0
  40. package/package.json +1 -1
  41. package/public/assets/ChangesTab-ovdqLHc3.js +2 -0
  42. package/public/assets/DiffToolbar-B12EfXMX.js +1 -0
  43. package/public/assets/FilesTab-nb_itEXG.js +2 -0
  44. package/public/assets/GitChangesTab-DcT_4BL2.js +2 -0
  45. package/public/assets/{SplitFilePanel-DwrJM7GQ.js → SplitFilePanel-BOHH3F--.js} +1 -1
  46. package/public/assets/StatusTab-Dyt_EG33.js +1 -0
  47. package/public/assets/align-justify-9zpyaAdy.js +1 -0
  48. package/public/assets/{bundle-full-JwmTIwMd.js → bundle-full-xFW13Lny.js} +1 -1
  49. package/public/assets/diff-viewer-xG9yjpN8.js +1 -0
  50. package/public/assets/git-diff-vendor-CSgooKT_.js +52 -0
  51. package/public/assets/index-7DpT014-.js +1 -0
  52. package/public/assets/index-BDK4V9L0.js +1 -0
  53. package/public/assets/index-Bx-Bezt2.js +1 -0
  54. package/public/assets/index-CCAZZY0l.js +1 -0
  55. package/public/assets/index-CEcZq5WB.js +1 -0
  56. package/public/assets/index-CQCmSDHL.js +1 -0
  57. package/public/assets/{index-CkYwnPl7.js → index-Cz_fl8aY.js} +1 -1
  58. package/public/assets/index-Dcgftm1m.css +1 -0
  59. package/public/assets/index-m4C3yx3J.js +1 -0
  60. package/public/assets/index-mh_z9p40.js +2 -0
  61. package/public/assets/{loading-CfqkoCbA.js → loading-HUhLEgb_.js} +1 -1
  62. package/public/assets/main-CKhfaeKI.js +48 -0
  63. package/public/assets/{markdown-D2uUJada.js → markdown-BeXU9Z-x.js} +22 -22
  64. package/public/assets/monaco-viewer-BgP6xpZ6.js +26 -0
  65. package/public/assets/{todo-i3zWdksA.js → todo-D6PVVp_f.js} +1 -1
  66. package/public/assets/tool-call-Dgn3NlA8.js +60 -0
  67. package/public/assets/unified-picker-DuNuUpLy.js +1 -0
  68. package/public/assets/wrap-text-zghCl6wN.js +1 -0
  69. package/public/index.html +5 -5
  70. package/public/loading.html +5 -5
  71. package/public/sw.js +1 -1
  72. package/public/ui-version.json +1 -1
  73. package/public/assets/ChangesTab-X8IIoIdB.js +0 -2
  74. package/public/assets/DiffToolbar-Djg0ksr_.js +0 -1
  75. package/public/assets/FilesTab-BpYPA_Zr.js +0 -2
  76. package/public/assets/GitChangesTab-DeGsV8--.js +0 -2
  77. package/public/assets/StatusTab-mT1B3wST.js +0 -1
  78. package/public/assets/diff-viewer-CKnTxbWB.js +0 -1
  79. package/public/assets/git-diff-vendor-CAv-4upN.js +0 -52
  80. package/public/assets/index-BEzx5r3P.css +0 -1
  81. package/public/assets/index-BHjkPi4D.js +0 -1
  82. package/public/assets/index-CUkIenrg.js +0 -1
  83. package/public/assets/index-D9RMxxcS.js +0 -1
  84. package/public/assets/index-DiFfJ0HM.js +0 -1
  85. package/public/assets/index-LmDdmmJP.js +0 -1
  86. package/public/assets/index-UaIyK67v.js +0 -1
  87. package/public/assets/index-lhjxIgwf.js +0 -2
  88. package/public/assets/index-xsUu1uOf.js +0 -1
  89. package/public/assets/main-B3yZBpaS.js +0 -56
  90. package/public/assets/monaco-viewer-UU9TfOpS.js +0 -15
  91. package/public/assets/tool-call-Bl3Lai68.js +0 -60
  92. package/public/assets/unified-picker-B506AoQt.js +0 -1
@@ -0,0 +1,142 @@
1
+ import { Agent, fetch } from "undici";
2
+ import { z } from "zod";
3
+ const ProbeSchema = z.object({
4
+ baseUrl: z.string().min(1),
5
+ skipTlsVerify: z.boolean().optional(),
6
+ });
7
+ const PROBE_TIMEOUT_MS = 8000;
8
+ export function registerRemoteServerRoutes(app, deps) {
9
+ app.post("/api/remote-servers/probe", async (request, reply) => {
10
+ try {
11
+ const body = ProbeSchema.parse(request.body ?? {});
12
+ return await probeRemoteServer(body.baseUrl, Boolean(body.skipTlsVerify));
13
+ }
14
+ catch (error) {
15
+ deps.logger.warn({ err: error }, "Failed to probe remote server");
16
+ reply.code(400);
17
+ return { error: error instanceof Error ? error.message : "Invalid request" };
18
+ }
19
+ });
20
+ }
21
+ async function probeRemoteServer(baseUrl, skipTlsVerify) {
22
+ const normalizedUrl = normalizeBaseUrl(baseUrl);
23
+ const probeUrl = new URL("./api/auth/status", `${normalizedUrl}/`);
24
+ const controller = new AbortController();
25
+ const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
26
+ const dispatcher = skipTlsVerify ? new Agent({ connect: { rejectUnauthorized: false } }) : undefined;
27
+ try {
28
+ const response = await fetch(probeUrl, {
29
+ method: "GET",
30
+ dispatcher,
31
+ signal: controller.signal,
32
+ headers: {
33
+ Accept: "application/json",
34
+ },
35
+ });
36
+ if (!response.ok) {
37
+ return {
38
+ ok: false,
39
+ reachable: true,
40
+ normalizedUrl,
41
+ skipTlsVerify,
42
+ requiresAuth: false,
43
+ authenticated: false,
44
+ error: `Remote server returned HTTP ${response.status}`,
45
+ errorCode: "http_error",
46
+ };
47
+ }
48
+ const payload = (await response.json());
49
+ if (typeof payload?.authenticated !== "boolean") {
50
+ return {
51
+ ok: false,
52
+ reachable: true,
53
+ normalizedUrl,
54
+ skipTlsVerify,
55
+ requiresAuth: false,
56
+ authenticated: false,
57
+ error: "Remote server did not return a valid CodeNomad auth response",
58
+ errorCode: "invalid_server",
59
+ };
60
+ }
61
+ return {
62
+ ok: true,
63
+ reachable: true,
64
+ normalizedUrl,
65
+ skipTlsVerify,
66
+ requiresAuth: !payload.authenticated,
67
+ authenticated: payload.authenticated,
68
+ };
69
+ }
70
+ catch (error) {
71
+ const message = describeProbeError(error);
72
+ return {
73
+ ok: false,
74
+ reachable: false,
75
+ normalizedUrl,
76
+ skipTlsVerify,
77
+ requiresAuth: false,
78
+ authenticated: false,
79
+ error: message.message,
80
+ errorCode: message.code,
81
+ };
82
+ }
83
+ finally {
84
+ clearTimeout(timeout);
85
+ await dispatcher?.close().catch(() => { });
86
+ }
87
+ }
88
+ function normalizeBaseUrl(input) {
89
+ const parsed = new URL(input.trim());
90
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
91
+ throw new Error("Server URL must use http:// or https://");
92
+ }
93
+ parsed.hash = "";
94
+ parsed.search = "";
95
+ parsed.pathname = parsed.pathname === "/" ? "/" : parsed.pathname.replace(/\/+$/, "") || "/";
96
+ const value = parsed.toString();
97
+ return parsed.pathname === "/" ? value.replace(/\/$/, "") : value.replace(/\/$/, "");
98
+ }
99
+ function describeProbeError(error) {
100
+ const chain = unwrapErrorChain(error);
101
+ const detailed = chain.find((entry) => {
102
+ const code = (entry?.code ?? "").toString();
103
+ return Boolean(code) && code !== "UND_ERR_RESPONSE_STATUS_CODE";
104
+ }) ?? chain[0];
105
+ const code = (detailed?.code ?? "").toString();
106
+ const exactMessage = detailed?.message?.trim() || chain.find((entry) => entry.message?.trim())?.message?.trim();
107
+ if (code === "DEPTH_ZERO_SELF_SIGNED_CERT" || code === "SELF_SIGNED_CERT_IN_CHAIN" || code === "CERT_HAS_EXPIRED") {
108
+ return {
109
+ code: "tls_error",
110
+ message: "Certificate check failed while connecting to the remote server.",
111
+ };
112
+ }
113
+ return {
114
+ code: code === "ERR_INVALID_URL"
115
+ ? "invalid_url"
116
+ : code === "ECONNREFUSED"
117
+ ? "connection_refused"
118
+ : code === "ENOTFOUND"
119
+ ? "dns_error"
120
+ : code === "UND_ERR_CONNECT_TIMEOUT" || code === "ABORT_ERR"
121
+ ? "timeout"
122
+ : code
123
+ ? code.toLowerCase()
124
+ : "probe_failed",
125
+ message: exactMessage || "Failed to connect to the remote server.",
126
+ };
127
+ }
128
+ function unwrapErrorChain(error) {
129
+ const results = [];
130
+ let current = error;
131
+ const seen = new Set();
132
+ while (current && typeof current === "object" && !seen.has(current)) {
133
+ seen.add(current);
134
+ const entry = current;
135
+ results.push({ code: entry.code, message: entry.message });
136
+ current = entry.cause;
137
+ }
138
+ if (results.length === 0 && error instanceof Error) {
139
+ results.push({ message: error.message });
140
+ }
141
+ return results;
142
+ }
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { probeBinaryVersion } from "../../workspaces/runtime";
2
+ import { probeBinaryVersion } from "../../workspaces/spawn";
3
3
  import { sanitizeConfigDoc, sanitizeConfigOwner } from "../../settings/public-config";
4
4
  const ValidateBinarySchema = z.object({
5
5
  path: z.string(),
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ const SideCarCreateSchema = z.object({
3
+ kind: z.literal("port").default("port"),
4
+ name: z.string().trim().min(1),
5
+ port: z.number().int().min(1).max(65535),
6
+ insecure: z.boolean().default(false),
7
+ prefixMode: z.enum(["strip", "preserve"]).default("strip"),
8
+ });
9
+ const SideCarUpdateSchema = SideCarCreateSchema.omit({ kind: true }).partial().refine((value) => Object.keys(value).length > 0, {
10
+ message: "At least one field is required",
11
+ });
12
+ export function registerSideCarRoutes(app, deps) {
13
+ app.get("/api/sidecars", async () => {
14
+ return { sidecars: await deps.sidecarManager.list() };
15
+ });
16
+ app.post("/api/sidecars", async (request, reply) => {
17
+ try {
18
+ const body = SideCarCreateSchema.parse(request.body ?? {});
19
+ const sidecar = await deps.sidecarManager.create(body);
20
+ reply.code(201);
21
+ return sidecar;
22
+ }
23
+ catch (error) {
24
+ reply.code(400);
25
+ return { error: error instanceof Error ? error.message : "Failed to create SideCar" };
26
+ }
27
+ });
28
+ app.put("/api/sidecars/:id", async (request, reply) => {
29
+ try {
30
+ const body = SideCarUpdateSchema.parse(request.body ?? {});
31
+ return await deps.sidecarManager.update(request.params.id, body);
32
+ }
33
+ catch (error) {
34
+ reply.code(400);
35
+ return { error: error instanceof Error ? error.message : "Failed to update SideCar" };
36
+ }
37
+ });
38
+ app.delete("/api/sidecars/:id", async (request, reply) => {
39
+ const removed = await deps.sidecarManager.delete(request.params.id);
40
+ if (!removed) {
41
+ reply.code(404);
42
+ return { error: "SideCar not found" };
43
+ }
44
+ reply.code(204);
45
+ });
46
+ }
@@ -1,4 +1,8 @@
1
1
  import { z } from "zod";
2
+ import { getWorktreeGitDiff, getWorktreeGitStatus } from "../../workspaces/git-status";
3
+ import { commitWorktreeChanges, isGitMutationError, stageWorktreePaths, unstageWorktreePaths } from "../../workspaces/git-mutations";
4
+ import { isGitAvailable, resolveRepoRoot } from "../../workspaces/git-worktrees";
5
+ import { resolveWorktreeDirectory } from "../../workspaces/worktree-directory";
2
6
  const WorkspaceCreateSchema = z.object({
3
7
  path: z.string(),
4
8
  name: z.string().optional(),
@@ -12,6 +16,17 @@ const WorkspaceFileContentQuerySchema = z.object({
12
16
  const WorkspaceFileContentBodySchema = z.object({
13
17
  contents: z.string(),
14
18
  });
19
+ const WorktreeGitDiffQuerySchema = z.object({
20
+ path: z.string().trim().min(1, "Path is required"),
21
+ originalPath: z.string().trim().optional(),
22
+ scope: z.enum(["staged", "unstaged"]),
23
+ });
24
+ const WorktreeGitPathsBodySchema = z.object({
25
+ paths: z.array(z.string().trim().min(1, "Path is required")).min(1, "At least one path is required"),
26
+ });
27
+ const WorktreeGitCommitBodySchema = z.object({
28
+ message: z.string().trim().min(1, "Commit message is required"),
29
+ });
15
30
  const WorkspaceFileSearchQuerySchema = z.object({
16
31
  q: z.string().trim().min(1, "Query is required"),
17
32
  limit: z.coerce.number().int().positive().max(200).optional(),
@@ -92,8 +107,111 @@ export function registerWorkspaceRoutes(app, deps) {
92
107
  return handleWorkspaceError(error, reply);
93
108
  }
94
109
  });
110
+ app.get("/api/workspaces/:id/worktrees/:slug/git-status", async (request, reply) => {
111
+ try {
112
+ const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
113
+ if (!directory)
114
+ return;
115
+ return await getWorktreeGitStatus({ workspaceFolder: directory, logger: request.log });
116
+ }
117
+ catch (error) {
118
+ return handleWorkspaceError(error, reply);
119
+ }
120
+ });
121
+ app.get("/api/workspaces/:id/worktrees/:slug/git-diff", async (request, reply) => {
122
+ try {
123
+ const query = WorktreeGitDiffQuerySchema.parse(request.query ?? {});
124
+ const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
125
+ if (!directory)
126
+ return;
127
+ return await getWorktreeGitDiff({
128
+ workspaceFolder: directory,
129
+ path: query.path,
130
+ originalPath: query.originalPath,
131
+ scope: query.scope,
132
+ });
133
+ }
134
+ catch (error) {
135
+ return handleWorkspaceError(error, reply);
136
+ }
137
+ });
138
+ app.post("/api/workspaces/:id/worktrees/:slug/git-stage", async (request, reply) => {
139
+ try {
140
+ const body = WorktreeGitPathsBodySchema.parse(request.body ?? {});
141
+ const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
142
+ if (!directory)
143
+ return;
144
+ await stageWorktreePaths({ workspaceFolder: directory, paths: body.paths });
145
+ return { ok: true };
146
+ }
147
+ catch (error) {
148
+ return handleWorkspaceError(error, reply);
149
+ }
150
+ });
151
+ app.post("/api/workspaces/:id/worktrees/:slug/git-unstage", async (request, reply) => {
152
+ try {
153
+ const body = WorktreeGitPathsBodySchema.parse(request.body ?? {});
154
+ const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
155
+ if (!directory)
156
+ return;
157
+ await unstageWorktreePaths({ workspaceFolder: directory, paths: body.paths });
158
+ return { ok: true };
159
+ }
160
+ catch (error) {
161
+ return handleWorkspaceError(error, reply);
162
+ }
163
+ });
164
+ app.post("/api/workspaces/:id/worktrees/:slug/git-commit", async (request, reply) => {
165
+ try {
166
+ const body = WorktreeGitCommitBodySchema.parse(request.body ?? {});
167
+ const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply);
168
+ if (!directory)
169
+ return;
170
+ const result = await commitWorktreeChanges({ workspaceFolder: directory, message: body.message });
171
+ return { ok: true, ...result };
172
+ }
173
+ catch (error) {
174
+ return handleWorkspaceError(error, reply);
175
+ }
176
+ });
177
+ }
178
+ async function resolveGitWorktreeDirectory(workspaceManager, workspaceId, worktreeSlug, logger, reply) {
179
+ const workspace = workspaceManager.get(workspaceId);
180
+ if (!workspace) {
181
+ reply.code(404);
182
+ reply.send({ error: "Workspace not found" });
183
+ return null;
184
+ }
185
+ const gitAvailable = await isGitAvailable(workspace.path);
186
+ if (!gitAvailable) {
187
+ reply.code(503);
188
+ reply.send({ error: "Git is not installed or not available in PATH" });
189
+ return null;
190
+ }
191
+ const { isGitRepo } = await resolveRepoRoot(workspace.path, logger);
192
+ if (!isGitRepo) {
193
+ reply.code(400);
194
+ reply.send({ error: "Workspace is not a Git repository" });
195
+ return null;
196
+ }
197
+ const directory = await resolveWorktreeDirectory({
198
+ workspaceId: workspace.id,
199
+ workspacePath: workspace.path,
200
+ worktreeSlug,
201
+ logger,
202
+ });
203
+ if (!directory) {
204
+ reply.code(404);
205
+ reply.send({ error: "Worktree not found" });
206
+ return null;
207
+ }
208
+ return directory;
95
209
  }
96
210
  function handleWorkspaceError(error, reply) {
211
+ if (isGitMutationError(error)) {
212
+ reply.code(error.statusCode);
213
+ return { error: error.message };
214
+ }
97
215
  if (error instanceof Error && error.message === "Workspace not found") {
98
216
  reply.code(404);
99
217
  return { error: "Workspace not found" };
@@ -93,6 +93,10 @@ function mapLegacyToOwnerDocs(legacyConfig, legacyState) {
93
93
  if (typeof listeningMode === "string") {
94
94
  serverConfig.listeningMode = listeningMode;
95
95
  }
96
+ const logLevel = preferences.logLevel;
97
+ if (typeof logLevel === "string") {
98
+ serverConfig.logLevel = logLevel;
99
+ }
96
100
  const lastUsedBinary = preferences.lastUsedBinary;
97
101
  if (typeof lastUsedBinary === "string") {
98
102
  serverConfig.opencodeBinary = lastUsedBinary;
@@ -118,6 +122,7 @@ function mapLegacyToOwnerDocs(legacyConfig, legacyState) {
118
122
  const moved = new Set([
119
123
  "environmentVariables",
120
124
  "listeningMode",
125
+ "logLevel",
121
126
  "lastUsedBinary",
122
127
  "modelRecents",
123
128
  "modelFavorites",
@@ -1,6 +1,47 @@
1
+ import { z } from "zod";
1
2
  import { YamlDocStore } from "./yaml-doc-store";
2
3
  import { migrateSettingsLayout } from "./migrate";
3
4
  import { sanitizeConfigOwner } from "./public-config";
5
+ const CanonicalLogLevelSchema = z.preprocess((value) => (typeof value === "string" ? value.trim().toUpperCase() : value), z.enum(["DEBUG", "INFO", "WARN", "ERROR"]));
6
+ function isPlainObject(value) {
7
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8
+ }
9
+ function isDeepEqual(a, b) {
10
+ if (a === b)
11
+ return true;
12
+ try {
13
+ return JSON.stringify(a) === JSON.stringify(b);
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ function normalizeServerConfigOwner(value) {
20
+ if (!isPlainObject(value)) {
21
+ return {};
22
+ }
23
+ const next = { ...value };
24
+ const parsedLogLevel = CanonicalLogLevelSchema.safeParse(next.logLevel);
25
+ if (parsedLogLevel.success) {
26
+ next.logLevel = parsedLogLevel.data;
27
+ }
28
+ else if (next.logLevel !== undefined) {
29
+ next.logLevel = "DEBUG";
30
+ }
31
+ return next;
32
+ }
33
+ function normalizeConfigDoc(doc) {
34
+ if (!isPlainObject(doc)) {
35
+ return {};
36
+ }
37
+ if (!isPlainObject(doc.server)) {
38
+ return doc;
39
+ }
40
+ return {
41
+ ...doc,
42
+ server: normalizeServerConfigOwner(doc.server),
43
+ };
44
+ }
4
45
  export class SettingsService {
5
46
  constructor(location, eventBus, logger) {
6
47
  this.location = location;
@@ -11,18 +52,37 @@ export class SettingsService {
11
52
  this.stateStore = new YamlDocStore(location.stateYamlPath, logger.child({ component: "settings-state" }));
12
53
  }
13
54
  getDoc(kind) {
14
- return kind === "config" ? this.configStore.get() : this.stateStore.get();
55
+ if (kind !== "config") {
56
+ return this.stateStore.get();
57
+ }
58
+ const current = this.configStore.get();
59
+ const normalized = normalizeConfigDoc(current);
60
+ if (!isDeepEqual(current, normalized)) {
61
+ this.configStore.replace(normalized);
62
+ }
63
+ return normalized;
15
64
  }
16
65
  mergePatchDoc(kind, patch) {
17
- const updated = kind === "config" ? this.configStore.mergePatch(patch) : this.stateStore.mergePatch(patch);
66
+ const updated = kind === "config"
67
+ ? this.configStore.replace(normalizeConfigDoc(this.configStore.mergePatch(patch)))
68
+ : this.stateStore.mergePatch(patch);
18
69
  this.publish(kind, "*");
19
70
  return updated;
20
71
  }
21
72
  getOwner(kind, owner) {
22
- return kind === "config" ? this.configStore.getOwner(owner) : this.stateStore.getOwner(owner);
73
+ if (kind !== "config") {
74
+ return this.stateStore.getOwner(owner);
75
+ }
76
+ return owner === "server"
77
+ ? normalizeServerConfigOwner(this.getDoc("config").server)
78
+ : this.getDoc("config")[owner];
23
79
  }
24
80
  mergePatchOwner(kind, owner, patch) {
25
- const updated = kind === "config" ? this.configStore.mergePatchOwner(owner, patch) : this.stateStore.mergePatchOwner(owner, patch);
81
+ const updated = kind === "config"
82
+ ? owner === "server"
83
+ ? this.configStore.replaceOwner(owner, normalizeServerConfigOwner(this.configStore.mergePatchOwner(owner, patch)))
84
+ : this.configStore.mergePatchOwner(owner, patch)
85
+ : this.stateStore.mergePatchOwner(owner, patch);
26
86
  this.publish(kind, owner, updated);
27
87
  return updated;
28
88
  }
@@ -0,0 +1,193 @@
1
+ import { connect } from "net";
2
+ export class SideCarManager {
3
+ constructor(options) {
4
+ this.options = options;
5
+ this.configs = new Map();
6
+ this.runtime = new Map();
7
+ for (const record of this.loadConfiguredSideCars()) {
8
+ this.configs.set(record.id, record);
9
+ this.runtime.set(record.id, { status: "stopped" });
10
+ }
11
+ queueMicrotask(() => {
12
+ for (const record of this.configs.values()) {
13
+ void this.refreshPortSideCar(record.id).catch((error) => {
14
+ this.options.logger.warn({ sidecarId: record.id, err: error }, "Failed to probe sidecar port");
15
+ });
16
+ }
17
+ });
18
+ }
19
+ async list() {
20
+ await this.refreshPortStatuses();
21
+ return Array.from(this.configs.values()).map((record) => this.toSideCar(record));
22
+ }
23
+ async get(id) {
24
+ if (!this.configs.has(id))
25
+ return undefined;
26
+ await this.refreshPortSideCar(id);
27
+ return this.toSideCar(this.requireConfig(id));
28
+ }
29
+ async create(input) {
30
+ const normalizedName = input.name.trim();
31
+ const id = this.buildSideCarId(normalizedName);
32
+ if (this.configs.has(id)) {
33
+ throw new Error(`SideCar '${id}' already exists`);
34
+ }
35
+ const now = new Date().toISOString();
36
+ const record = {
37
+ id,
38
+ kind: input.kind,
39
+ name: normalizedName,
40
+ port: input.port,
41
+ insecure: input.insecure,
42
+ prefixMode: input.prefixMode,
43
+ createdAt: now,
44
+ updatedAt: now,
45
+ };
46
+ this.configs.set(record.id, record);
47
+ this.runtime.set(record.id, { status: "stopped" });
48
+ this.persistConfigs();
49
+ await this.refreshPortSideCar(record.id);
50
+ return this.toSideCar(record);
51
+ }
52
+ async update(id, input) {
53
+ const record = this.requireConfig(id);
54
+ record.name = typeof input.name === "string" ? input.name.trim() : record.name;
55
+ record.port = typeof input.port === "number" ? input.port : record.port;
56
+ record.insecure = typeof input.insecure === "boolean" ? input.insecure : record.insecure;
57
+ record.prefixMode = typeof input.prefixMode === "string" ? input.prefixMode : record.prefixMode;
58
+ record.updatedAt = new Date().toISOString();
59
+ this.persistConfigs();
60
+ await this.refreshPortSideCar(id);
61
+ return this.toSideCar(record);
62
+ }
63
+ async delete(id) {
64
+ const record = this.configs.get(id);
65
+ if (!record)
66
+ return false;
67
+ this.configs.delete(id);
68
+ this.runtime.delete(id);
69
+ this.persistConfigs();
70
+ this.options.eventBus.publish({ type: "sidecar.removed", sidecarId: id });
71
+ return true;
72
+ }
73
+ async shutdown() {
74
+ return;
75
+ }
76
+ buildTargetOrigin(sidecar) {
77
+ const protocol = sidecar.insecure ? "http" : "https";
78
+ return `${protocol}://127.0.0.1:${sidecar.port}`;
79
+ }
80
+ buildProxyBasePath(id) {
81
+ return `/sidecars/${encodeURIComponent(id)}`;
82
+ }
83
+ buildTargetPath(id, incomingPath, search = "") {
84
+ const record = this.requireConfig(id);
85
+ const publicBase = this.buildProxyBasePath(id);
86
+ const normalizedPath = incomingPath || publicBase;
87
+ if (record.prefixMode === "preserve") {
88
+ return `${normalizedPath}${search}`;
89
+ }
90
+ let stripped = normalizedPath.startsWith(publicBase) ? normalizedPath.slice(publicBase.length) : normalizedPath;
91
+ if (!stripped || stripped === "/") {
92
+ stripped = "/";
93
+ }
94
+ else if (!stripped.startsWith("/")) {
95
+ stripped = `/${stripped}`;
96
+ }
97
+ return `${stripped}${search}`;
98
+ }
99
+ async refreshPortStatuses() {
100
+ await Promise.all(Array.from(this.configs.values()).map((record) => this.refreshPortSideCar(record.id)));
101
+ }
102
+ async refreshPortSideCar(id) {
103
+ const record = this.configs.get(id);
104
+ if (!record)
105
+ return;
106
+ const isAvailable = await this.isPortAvailable(record.port);
107
+ const current = this.runtime.get(id);
108
+ const nextStatus = isAvailable ? "running" : "stopped";
109
+ if (current?.status === nextStatus) {
110
+ return;
111
+ }
112
+ this.runtime.set(id, { status: nextStatus });
113
+ record.updatedAt = new Date().toISOString();
114
+ this.publish(id);
115
+ }
116
+ publish(id) {
117
+ const record = this.configs.get(id);
118
+ if (!record)
119
+ return;
120
+ this.options.eventBus.publish({ type: "sidecar.updated", sidecar: this.toSideCar(record) });
121
+ }
122
+ toSideCar(record) {
123
+ const runtime = this.runtime.get(record.id);
124
+ return {
125
+ id: record.id,
126
+ kind: record.kind,
127
+ name: record.name,
128
+ port: record.port,
129
+ insecure: record.insecure,
130
+ prefixMode: record.prefixMode,
131
+ status: runtime?.status ?? "stopped",
132
+ createdAt: record.createdAt,
133
+ updatedAt: record.updatedAt,
134
+ };
135
+ }
136
+ requireConfig(id) {
137
+ const record = this.configs.get(id);
138
+ if (!record) {
139
+ throw new Error("SideCar not found");
140
+ }
141
+ return record;
142
+ }
143
+ persistConfigs() {
144
+ const sidecars = Array.from(this.configs.values()).map((record) => ({ ...record }));
145
+ this.options.settings.mergePatchOwner("config", "server", { sidecars });
146
+ }
147
+ loadConfiguredSideCars() {
148
+ const serverConfig = this.options.settings.getOwner("config", "server");
149
+ const list = Array.isArray(serverConfig?.sidecars) ? serverConfig.sidecars : [];
150
+ const records = [];
151
+ for (const item of list) {
152
+ if (!item || typeof item !== "object")
153
+ continue;
154
+ const record = item;
155
+ const kind = record.kind === "port" ? "port" : null;
156
+ const id = typeof record.id === "string" && record.id.trim() ? record.id.trim() : null;
157
+ const name = typeof record.name === "string" && record.name.trim() ? record.name.trim() : null;
158
+ const port = typeof record.port === "number" && Number.isInteger(record.port) ? record.port : null;
159
+ if (!kind || !id || !name || !port)
160
+ continue;
161
+ const insecure = record.insecure === true;
162
+ const prefixMode = record.prefixMode === "preserve" ? "preserve" : "strip";
163
+ const createdAt = typeof record.createdAt === "string" && record.createdAt ? record.createdAt : new Date().toISOString();
164
+ const updatedAt = typeof record.updatedAt === "string" && record.updatedAt ? record.updatedAt : createdAt;
165
+ records.push({ id, kind, name, port, insecure, prefixMode, createdAt, updatedAt });
166
+ }
167
+ return records;
168
+ }
169
+ isPortAvailable(port) {
170
+ return new Promise((resolve) => {
171
+ const socket = connect({ port, host: "127.0.0.1" }, () => {
172
+ socket.end();
173
+ resolve(true);
174
+ });
175
+ socket.once("error", () => {
176
+ socket.destroy();
177
+ resolve(false);
178
+ });
179
+ });
180
+ }
181
+ buildSideCarId(name) {
182
+ const normalized = name
183
+ .trim()
184
+ .toLowerCase()
185
+ .replace(/[^a-z0-9]+/g, "-")
186
+ .replace(/-{2,}/g, "-")
187
+ .replace(/^-|-$/g, "");
188
+ if (!normalized) {
189
+ throw new Error("SideCar name must include letters or numbers");
190
+ }
191
+ return normalized;
192
+ }
193
+ }
@@ -0,0 +1,43 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { describe, it } from "node:test";
6
+ import { listWorktrees } from "../git-worktrees";
7
+ describe("listWorktrees", () => {
8
+ it("uses the selected workspace folder for the root worktree directory", async () => {
9
+ const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-worktrees-"));
10
+ const binDir = path.join(temp, "bin");
11
+ const repoRoot = path.join(temp, "repo");
12
+ const workspaceFolder = path.join(repoRoot, "proj-1");
13
+ const originalPath = process.env.PATH;
14
+ try {
15
+ mkdirSync(binDir, { recursive: true });
16
+ mkdirSync(workspaceFolder, { recursive: true });
17
+ const gitPath = path.join(binDir, process.platform === "win32" ? "git.cmd" : "git");
18
+ const porcelain = [
19
+ `worktree ${repoRoot}`,
20
+ "HEAD 1111111",
21
+ "branch refs/heads/main",
22
+ "",
23
+ ].join("\n");
24
+ if (process.platform === "win32") {
25
+ writeFileSync(gitPath, `@echo off\r\nif "%1"=="worktree" if "%2"=="list" if "%3"=="--porcelain" (\r\necho ${porcelain.replace(/\n/g, "\r\necho ")}\r\nexit /b 0\r\n)\r\nexit /b 1\r\n`);
26
+ }
27
+ else {
28
+ writeFileSync(gitPath, `#!/bin/sh\nif [ "$1" = "worktree" ] && [ "$2" = "list" ] && [ "$3" = "--porcelain" ]; then\nprintf '%s\n' '${porcelain.replace(/'/g, "'\\''")}'\nexit 0\nfi\nexit 1\n`, { mode: 0o755 });
29
+ }
30
+ process.env.PATH = `${binDir}${path.delimiter}${originalPath ?? ""}`;
31
+ const worktrees = await listWorktrees({ repoRoot, workspaceFolder });
32
+ assert.equal(worktrees[0]?.slug, "root");
33
+ assert.equal(worktrees[0]?.directory, workspaceFolder);
34
+ assert.equal(worktrees[0]?.kind, "root");
35
+ assert.equal(worktrees[0]?.branch, "main");
36
+ assert.notEqual(worktrees[0]?.directory, repoRoot);
37
+ }
38
+ finally {
39
+ process.env.PATH = originalPath;
40
+ rmSync(temp, { recursive: true, force: true });
41
+ }
42
+ });
43
+ });