@neuralnomads/codenomad 0.13.3 → 0.14.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 (71) hide show
  1. package/dist/auth/manager.js +5 -1
  2. package/dist/background-processes/manager.js +164 -25
  3. package/dist/config/schema.js +1 -0
  4. package/dist/events/bus.js +4 -0
  5. package/dist/index.js +56 -5
  6. package/dist/opencode-config/plugin/lib/background-process.ts +14 -2
  7. package/dist/plugins/voice-mode.js +2 -1
  8. package/dist/server/__tests__/network-addresses.test.js +68 -0
  9. package/dist/server/http-server.js +284 -15
  10. package/dist/server/network-addresses.js +43 -1
  11. package/dist/server/routes/background-processes.js +19 -1
  12. package/dist/server/routes/meta.js +0 -3
  13. package/dist/server/routes/plugin.js +5 -1
  14. package/dist/server/routes/remote-servers.js +142 -0
  15. package/dist/server/routes/sidecars.js +46 -0
  16. package/dist/settings/migrate.js +5 -0
  17. package/dist/settings/service.js +64 -4
  18. package/dist/sidecars/manager.js +193 -0
  19. package/dist/workspaces/manager.js +2 -0
  20. package/dist/workspaces/runtime.js +2 -1
  21. package/package.json +1 -1
  22. package/public/assets/ChangesTab-CFkk3tAp.js +2 -0
  23. package/public/assets/DiffToolbar-CQQLR1mp.js +1 -0
  24. package/public/assets/{FilesTab-BpYPA_Zr.js → FilesTab-CXgucPtN.js} +2 -2
  25. package/public/assets/GitChangesTab-BidSb28_.js +2 -0
  26. package/public/assets/{SplitFilePanel-DwrJM7GQ.js → SplitFilePanel-CupweEA5.js} +1 -1
  27. package/public/assets/StatusTab-C2Pl_Vce.js +1 -0
  28. package/public/assets/{bundle-full-JwmTIwMd.js → bundle-full-B-5u6Iv3.js} +1 -1
  29. package/public/assets/diff-viewer-_ehhYA-Z.js +1 -0
  30. package/public/assets/git-diff-vendor-CSgooKT_.js +52 -0
  31. package/public/assets/index-BnfDkr8C.js +1 -0
  32. package/public/assets/index-BntAaLZs.js +1 -0
  33. package/public/assets/index-BqiNjV6R.js +1 -0
  34. package/public/assets/index-BwCEJ4BE.css +1 -0
  35. package/public/assets/{index-CkYwnPl7.js → index-CxQr-wOF.js} +1 -1
  36. package/public/assets/index-DXaitXVC.js +1 -0
  37. package/public/assets/index-DzRzoTK8.js +2 -0
  38. package/public/assets/index-ShHad48G.js +1 -0
  39. package/public/assets/index-_EaXFUIj.js +1 -0
  40. package/public/assets/index-mMh5TJvW.js +1 -0
  41. package/public/assets/{loading-CfqkoCbA.js → loading-Dck2H3XH.js} +1 -1
  42. package/public/assets/main-BsIf5lOY.js +50 -0
  43. package/public/assets/{markdown-D2uUJada.js → markdown-CFV9kR80.js} +3 -3
  44. package/public/assets/monaco-viewer-CMM6n0T3.js +25 -0
  45. package/public/assets/{todo-i3zWdksA.js → todo-Ghwirj-b.js} +1 -1
  46. package/public/assets/tool-call-BC2Pv3uG.js +60 -0
  47. package/public/assets/unified-picker-Dw0kTXoT.js +1 -0
  48. package/public/assets/wrap-text-D2MJk2ad.js +1 -0
  49. package/public/index.html +5 -5
  50. package/public/loading.html +5 -5
  51. package/public/sw.js +1 -1
  52. package/public/ui-version.json +1 -1
  53. package/public/assets/ChangesTab-X8IIoIdB.js +0 -2
  54. package/public/assets/DiffToolbar-Djg0ksr_.js +0 -1
  55. package/public/assets/GitChangesTab-DeGsV8--.js +0 -2
  56. package/public/assets/StatusTab-mT1B3wST.js +0 -1
  57. package/public/assets/diff-viewer-CKnTxbWB.js +0 -1
  58. package/public/assets/git-diff-vendor-CAv-4upN.js +0 -52
  59. package/public/assets/index-BEzx5r3P.css +0 -1
  60. package/public/assets/index-BHjkPi4D.js +0 -1
  61. package/public/assets/index-CUkIenrg.js +0 -1
  62. package/public/assets/index-D9RMxxcS.js +0 -1
  63. package/public/assets/index-DiFfJ0HM.js +0 -1
  64. package/public/assets/index-LmDdmmJP.js +0 -1
  65. package/public/assets/index-UaIyK67v.js +0 -1
  66. package/public/assets/index-lhjxIgwf.js +0 -2
  67. package/public/assets/index-xsUu1uOf.js +0 -1
  68. package/public/assets/main-B3yZBpaS.js +0 -56
  69. package/public/assets/monaco-viewer-UU9TfOpS.js +0 -15
  70. package/public/assets/tool-call-Bl3Lai68.js +0 -60
  71. package/public/assets/unified-picker-B506AoQt.js +0 -1
@@ -3,7 +3,9 @@ import cors from "@fastify/cors";
3
3
  import fastifyStatic from "@fastify/static";
4
4
  import replyFrom from "@fastify/reply-from";
5
5
  import fs from "fs";
6
+ import { connect as connectTcp } from "net";
6
7
  import path from "path";
8
+ import { connect as connectTls } from "tls";
7
9
  import { fetch } from "undici";
8
10
  import { isValidWorktreeSlug, listWorktrees, resolveRepoRoot } from "../workspaces/git-worktrees";
9
11
  import { registerWorkspaceRoutes } from "./routes/workspaces";
@@ -16,12 +18,11 @@ import { registerPluginRoutes } from "./routes/plugin";
16
18
  import { registerBackgroundProcessRoutes } from "./routes/background-processes";
17
19
  import { registerWorktreeRoutes } from "./routes/worktrees";
18
20
  import { registerSpeechRoutes } from "./routes/speech";
21
+ import { registerRemoteServerRoutes } from "./routes/remote-servers";
22
+ import { registerSideCarRoutes } from "./routes/sidecars";
19
23
  import { BackgroundProcessManager } from "../background-processes/manager";
20
24
  import { registerAuthRoutes } from "./routes/auth";
21
25
  import { sendUnauthorized, wantsHtml } from "../auth/http-auth";
22
- import { ClientConnectionManager } from "../clients/connection-manager";
23
- import { PluginChannelManager } from "../plugins/channel";
24
- import { VoiceModeManager } from "../plugins/voice-mode";
25
26
  export function createHttpServer(deps) {
26
27
  // Fastify's type-level RawServer inference gets noisy when toggling HTTP vs HTTPS.
27
28
  // We keep the runtime behavior correct and cast the instance to a generic FastifyInstance.
@@ -128,13 +129,6 @@ export function createHttpServer(deps) {
128
129
  eventBus: deps.eventBus,
129
130
  logger: deps.logger.child({ component: "background-processes" }),
130
131
  });
131
- const clientConnectionManager = new ClientConnectionManager(deps.logger.child({ component: "client-connections" }));
132
- const pluginChannel = new PluginChannelManager(deps.logger.child({ component: "plugin-channel" }));
133
- const voiceModeManager = new VoiceModeManager({
134
- connections: clientConnectionManager,
135
- channel: pluginChannel,
136
- logger: deps.logger.child({ component: "voice-mode" }),
137
- });
138
132
  registerAuthRoutes(app, { authManager: deps.authManager });
139
133
  app.addHook("preHandler", (request, reply, done) => {
140
134
  const rawUrl = request.raw.url ?? request.url;
@@ -149,7 +143,7 @@ export function createHttpServer(deps) {
149
143
  return;
150
144
  }
151
145
  const session = deps.authManager.getSessionFromRequest(request);
152
- const requiresAuthForApi = pathname.startsWith("/api/") || pathname.startsWith("/workspaces/");
146
+ const requiresAuthForApi = pathname.startsWith("/api/") || pathname.startsWith("/workspaces/") || pathname.startsWith("/sidecars/");
153
147
  if (requiresAuthForApi && !session) {
154
148
  // Allow OpenCode plugin -> CodeNomad calls with per-instance basic auth.
155
149
  const pluginMatch = pathname.match(/^\/workspaces\/([^/]+)\/plugin(?:\/|$)/);
@@ -199,7 +193,7 @@ export function createHttpServer(deps) {
199
193
  eventBus: deps.eventBus,
200
194
  registerClient: registerSseClient,
201
195
  logger: sseLogger,
202
- connectionManager: clientConnectionManager,
196
+ connectionManager: deps.clientConnectionManager,
203
197
  });
204
198
  registerWorktreeRoutes(app, { workspaceManager: deps.workspaceManager });
205
199
  registerStorageRoutes(app, {
@@ -207,13 +201,21 @@ export function createHttpServer(deps) {
207
201
  eventBus: deps.eventBus,
208
202
  workspaceManager: deps.workspaceManager,
209
203
  });
204
+ registerRemoteServerRoutes(app, { logger: apiLogger });
210
205
  registerSpeechRoutes(app, { speechService: deps.speechService });
206
+ registerSideCarRoutes(app, { sidecarManager: deps.sidecarManager });
207
+ registerSideCarProxyRoutes(app, { sidecarManager: deps.sidecarManager, logger: proxyLogger });
208
+ setupSideCarWebSocketProxy(app, {
209
+ sidecarManager: deps.sidecarManager,
210
+ authManager: deps.authManager,
211
+ logger: proxyLogger,
212
+ });
211
213
  registerPluginRoutes(app, {
212
214
  workspaceManager: deps.workspaceManager,
213
215
  eventBus: deps.eventBus,
214
216
  logger: proxyLogger,
215
- channel: pluginChannel,
216
- voiceModeManager,
217
+ channel: deps.pluginChannel,
218
+ voiceModeManager: deps.voiceModeManager,
217
219
  });
218
220
  registerBackgroundProcessRoutes(app, { backgroundProcessManager });
219
221
  registerInstanceProxyRoutes(app, { workspaceManager: deps.workspaceManager, logger: proxyLogger });
@@ -272,11 +274,52 @@ export function createHttpServer(deps) {
272
274
  },
273
275
  stop: () => {
274
276
  closeSseClients();
275
- clientConnectionManager.shutdown();
276
277
  return app.close();
277
278
  },
278
279
  };
279
280
  }
281
+ function registerSideCarProxyRoutes(app, deps) {
282
+ const proxyBaseHandler = async (request, reply) => {
283
+ await proxySideCarRequest({
284
+ request,
285
+ reply,
286
+ sidecarManager: deps.sidecarManager,
287
+ logger: deps.logger,
288
+ pathSuffix: "",
289
+ });
290
+ };
291
+ const proxyWildcardHandler = async (request, reply) => {
292
+ await proxySideCarRequest({
293
+ request,
294
+ reply,
295
+ sidecarManager: deps.sidecarManager,
296
+ logger: deps.logger,
297
+ pathSuffix: request.params["*"] ?? "",
298
+ });
299
+ };
300
+ app.all("/sidecars/:id", proxyBaseHandler);
301
+ app.all("/sidecars/:id/*", proxyWildcardHandler);
302
+ }
303
+ function setupSideCarWebSocketProxy(app, deps) {
304
+ app.server.on("upgrade", (request, socket, head) => {
305
+ const rawUrl = request.url ?? "/";
306
+ const parsed = parseSideCarUpgradePath(rawUrl);
307
+ if (!parsed) {
308
+ return;
309
+ }
310
+ void proxySideCarWebSocketUpgrade({
311
+ request,
312
+ socket: socket,
313
+ head,
314
+ sidecarId: parsed.sidecarId,
315
+ incomingPath: parsed.pathname,
316
+ search: parsed.search,
317
+ sidecarManager: deps.sidecarManager,
318
+ authManager: deps.authManager,
319
+ logger: deps.logger,
320
+ });
321
+ });
322
+ }
280
323
  function registerInstanceProxyRoutes(app, deps) {
281
324
  app.register(async (instance) => {
282
325
  instance.removeAllContentTypeParsers();
@@ -679,3 +722,229 @@ function buildProxyHeaders(headers) {
679
722
  }
680
723
  return result;
681
724
  }
725
+ async function proxySideCarRequest(args) {
726
+ const sidecarId = args.request.params.id ?? "";
727
+ const sidecar = await args.sidecarManager.get(sidecarId);
728
+ if (!sidecar) {
729
+ args.reply.code(404).send({ error: "SideCar not found" });
730
+ return;
731
+ }
732
+ const pathname = (args.request.raw.url ?? args.request.url ?? "").split("?")[0] ?? "";
733
+ const queryIndex = (args.request.raw.url ?? args.request.url ?? "").indexOf("?");
734
+ const search = queryIndex >= 0 ? (args.request.raw.url ?? args.request.url ?? "").slice(queryIndex) : "";
735
+ const pathSuffix = args.pathSuffix ?? "";
736
+ const requestPath = pathSuffix ? `${args.sidecarManager.buildProxyBasePath(sidecarId)}/${pathSuffix.replace(/^\/+/, "")}` : args.sidecarManager.buildProxyBasePath(sidecarId);
737
+ const targetPath = args.sidecarManager.buildTargetPath(sidecarId, requestPath, search);
738
+ const targetOrigin = args.sidecarManager.buildTargetOrigin(sidecar);
739
+ const targetUrl = `${targetOrigin}${targetPath}`;
740
+ args.logger.debug({ sidecarId: sidecar.id, targetUrl, pathname, prefixMode: sidecar.prefixMode }, "Proxying request to SideCar");
741
+ await args.reply.from(targetUrl, {
742
+ rewriteRequestHeaders: (_originalRequest, headers) => sanitizeSideCarProxyRequestHeaders(headers, targetOrigin),
743
+ rewriteHeaders: (headers) => rewriteSideCarResponseHeaders(headers, sidecarId, targetOrigin, sidecar.prefixMode),
744
+ onError: (reply, { error }) => {
745
+ args.logger.error({ sidecarId: sidecar.id, err: error, targetUrl }, "Failed to proxy SideCar request");
746
+ if (!reply.sent) {
747
+ reply.code(502).send({ error: "SideCar proxy failed" });
748
+ }
749
+ },
750
+ });
751
+ }
752
+ function parseSideCarUpgradePath(rawUrl) {
753
+ let parsed;
754
+ try {
755
+ parsed = new URL(rawUrl, "http://localhost");
756
+ }
757
+ catch {
758
+ return null;
759
+ }
760
+ const match = parsed.pathname.match(/^\/sidecars\/([^/]+)(?:\/.*)?$/);
761
+ if (!match) {
762
+ return null;
763
+ }
764
+ try {
765
+ return {
766
+ sidecarId: decodeURIComponent(match[1] ?? ""),
767
+ pathname: parsed.pathname,
768
+ search: parsed.search,
769
+ };
770
+ }
771
+ catch {
772
+ return null;
773
+ }
774
+ }
775
+ async function proxySideCarWebSocketUpgrade(args) {
776
+ const { request, socket, head, sidecarId, incomingPath, search, sidecarManager, authManager, logger } = args;
777
+ if (!isWebSocketUpgradeRequest(request)) {
778
+ rejectUpgrade(socket, 400, "Bad Request");
779
+ return;
780
+ }
781
+ const session = authManager.getSessionFromHeaders(request.headers);
782
+ if (!session) {
783
+ rejectUpgrade(socket, 401, "Unauthorized");
784
+ return;
785
+ }
786
+ const sidecar = await sidecarManager.get(sidecarId);
787
+ if (!sidecar) {
788
+ rejectUpgrade(socket, 404, "Not Found");
789
+ return;
790
+ }
791
+ const targetOrigin = sidecarManager.buildTargetOrigin(sidecar);
792
+ const targetPath = sidecarManager.buildTargetPath(sidecarId, incomingPath, search);
793
+ const targetUrl = new URL(`${targetOrigin}${targetPath}`);
794
+ logger.debug({ sidecarId, targetUrl: targetUrl.toString(), prefixMode: sidecar.prefixMode }, "Proxying websocket to SideCar");
795
+ const { socket: upstream, readyEvent } = createSideCarUpstreamSocket(targetUrl);
796
+ const closeBoth = () => {
797
+ if (!socket.destroyed) {
798
+ socket.destroy();
799
+ }
800
+ if (!upstream.destroyed) {
801
+ upstream.destroy();
802
+ }
803
+ };
804
+ upstream.once("error", (error) => {
805
+ logger.error({ sidecarId, err: error, targetUrl: targetUrl.toString() }, "Failed to proxy SideCar websocket");
806
+ rejectUpgrade(socket, 502, "Bad Gateway");
807
+ if (!upstream.destroyed) {
808
+ upstream.destroy();
809
+ }
810
+ });
811
+ socket.once("error", (error) => {
812
+ logger.debug({ sidecarId, err: error }, "SideCar websocket client socket errored");
813
+ if (!upstream.destroyed) {
814
+ upstream.destroy();
815
+ }
816
+ });
817
+ upstream.once(readyEvent, () => {
818
+ try {
819
+ upstream.write(buildSideCarWebSocketRequest(request, targetUrl));
820
+ if (head.length > 0) {
821
+ upstream.write(head);
822
+ }
823
+ upstream.pipe(socket);
824
+ socket.pipe(upstream);
825
+ }
826
+ catch (error) {
827
+ logger.error({ sidecarId, err: error, targetUrl: targetUrl.toString() }, "Failed to forward SideCar websocket upgrade");
828
+ closeBoth();
829
+ }
830
+ });
831
+ upstream.once("close", () => {
832
+ if (!socket.destroyed) {
833
+ socket.end();
834
+ }
835
+ });
836
+ socket.once("close", () => {
837
+ if (!upstream.destroyed) {
838
+ upstream.end();
839
+ }
840
+ });
841
+ }
842
+ function createSideCarUpstreamSocket(targetUrl) {
843
+ const port = Number(targetUrl.port || (targetUrl.protocol === "https:" ? 443 : 80));
844
+ if (targetUrl.protocol === "https:") {
845
+ return {
846
+ socket: connectTls({
847
+ host: targetUrl.hostname,
848
+ port,
849
+ servername: targetUrl.hostname,
850
+ }),
851
+ readyEvent: "secureConnect",
852
+ };
853
+ }
854
+ return {
855
+ socket: connectTcp(port, targetUrl.hostname),
856
+ readyEvent: "connect",
857
+ };
858
+ }
859
+ function buildSideCarWebSocketRequest(request, targetUrl) {
860
+ const pathWithQuery = `${targetUrl.pathname}${targetUrl.search}`;
861
+ const requestLine = `${request.method ?? "GET"} ${pathWithQuery} HTTP/${request.httpVersion}\r\n`;
862
+ const headerLines = [];
863
+ const rawHeaders = request.rawHeaders ?? [];
864
+ const blockedHeaders = getBlockedSideCarRequestHeaders();
865
+ for (let index = 0; index < rawHeaders.length; index += 2) {
866
+ const key = rawHeaders[index];
867
+ const value = rawHeaders[index + 1];
868
+ if (!key || value === undefined)
869
+ continue;
870
+ const lower = key.toLowerCase();
871
+ if (blockedHeaders.has(lower))
872
+ continue;
873
+ if (lower === "origin") {
874
+ headerLines.push(`Origin: ${targetUrl.origin}\r\n`);
875
+ continue;
876
+ }
877
+ headerLines.push(`${key}: ${value}\r\n`);
878
+ }
879
+ const hostValue = targetUrl.port ? `${targetUrl.hostname}:${targetUrl.port}` : targetUrl.hostname;
880
+ headerLines.push(`Host: ${hostValue}\r\n`);
881
+ headerLines.push("\r\n");
882
+ return requestLine + headerLines.join("");
883
+ }
884
+ function isWebSocketUpgradeRequest(request) {
885
+ const upgrade = request.headers.upgrade;
886
+ if (typeof upgrade !== "string" || upgrade.toLowerCase() !== "websocket") {
887
+ return false;
888
+ }
889
+ const connection = request.headers.connection;
890
+ const connectionValue = Array.isArray(connection) ? connection.join(",") : connection ?? "";
891
+ return connectionValue.toLowerCase().split(",").map((part) => part.trim()).includes("upgrade");
892
+ }
893
+ function rejectUpgrade(socket, statusCode, statusText) {
894
+ if (socket.destroyed) {
895
+ return;
896
+ }
897
+ socket.write(`HTTP/1.1 ${statusCode} ${statusText}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
898
+ socket.destroy();
899
+ }
900
+ function rewriteSideCarResponseHeaders(headers, sidecarId, targetOrigin, prefixMode) {
901
+ if (prefixMode === "preserve") {
902
+ return headers;
903
+ }
904
+ const next = { ...headers };
905
+ const locationHeader = next.location;
906
+ const location = Array.isArray(locationHeader) ? locationHeader[0] : locationHeader;
907
+ if (!location) {
908
+ return next;
909
+ }
910
+ const publicBase = `/sidecars/${encodeURIComponent(sidecarId)}`;
911
+ if (location.startsWith("/")) {
912
+ next.location = `${publicBase}${location}`;
913
+ return next;
914
+ }
915
+ try {
916
+ const parsed = new URL(location);
917
+ if (parsed.origin === targetOrigin) {
918
+ next.location = `${publicBase}${parsed.pathname}${parsed.search}${parsed.hash}`;
919
+ }
920
+ }
921
+ catch {
922
+ // Relative redirects should continue to resolve against the public sidecar path.
923
+ }
924
+ return next;
925
+ }
926
+ function sanitizeSideCarProxyRequestHeaders(headers, targetOrigin) {
927
+ const blockedHeaders = getBlockedSideCarRequestHeaders();
928
+ const next = {};
929
+ for (const [key, value] of Object.entries(headers)) {
930
+ if (!value)
931
+ continue;
932
+ if (blockedHeaders.has(key.toLowerCase()))
933
+ continue;
934
+ next[key] = value;
935
+ }
936
+ next.origin = targetOrigin;
937
+ return next;
938
+ }
939
+ function getBlockedSideCarRequestHeaders() {
940
+ return new Set([
941
+ "host",
942
+ "authorization",
943
+ "proxy-authorization",
944
+ "forwarded",
945
+ "x-forwarded-for",
946
+ "x-forwarded-host",
947
+ "x-forwarded-port",
948
+ "x-forwarded-proto",
949
+ ]);
950
+ }
@@ -52,9 +52,51 @@ export function resolveNetworkAddresses(args) {
52
52
  const scopeDelta = scopeWeight[a.scope] - scopeWeight[b.scope];
53
53
  if (scopeDelta !== 0)
54
54
  return scopeDelta;
55
- return a.ip.localeCompare(b.ip);
55
+ return 0;
56
56
  });
57
57
  }
58
+ export function resolveRemoteAddresses(args) {
59
+ const all = resolveNetworkAddresses(args);
60
+ const userVisible = sortUserVisibleAddresses(all.filter((address) => address.scope === "external"));
61
+ return {
62
+ all,
63
+ userVisible,
64
+ primaryRemoteUrl: userVisible[0]?.remoteUrl,
65
+ };
66
+ }
67
+ function sortUserVisibleAddresses(addresses) {
68
+ return [...addresses].sort((left, right) => getUserVisiblePriority(left.ip) - getUserVisiblePriority(right.ip));
69
+ }
70
+ function getUserVisiblePriority(ip) {
71
+ if (isPrivateIPv4(ip))
72
+ return 0;
73
+ if (isLinkLocalIPv4(ip))
74
+ return 2;
75
+ return 1;
76
+ }
77
+ function isLinkLocalIPv4(ip) {
78
+ const octets = parseIPv4(ip);
79
+ if (!octets)
80
+ return false;
81
+ const [first, second] = octets;
82
+ return first === 169 && second === 254;
83
+ }
84
+ function isPrivateIPv4(ip) {
85
+ const octets = parseIPv4(ip);
86
+ if (!octets)
87
+ return false;
88
+ const [first, second] = octets;
89
+ if (first === 10)
90
+ return true;
91
+ if (first === 192 && second === 168)
92
+ return true;
93
+ return first === 172 && second >= 16 && second <= 31;
94
+ }
95
+ function parseIPv4(value) {
96
+ if (!isIPv4Address(value))
97
+ return null;
98
+ return value.split(".").map((part) => Number(part));
99
+ }
58
100
  function isIPv4Address(value) {
59
101
  if (!value)
60
102
  return false;
@@ -2,6 +2,21 @@ import { z } from "zod";
2
2
  const StartSchema = z.object({
3
3
  title: z.string().trim().min(1),
4
4
  command: z.string().trim().min(1),
5
+ notify: z.boolean().optional(),
6
+ notification: z
7
+ .object({
8
+ sessionID: z.string().trim().min(1),
9
+ directory: z.string().trim().min(1),
10
+ })
11
+ .optional(),
12
+ }).superRefine((value, ctx) => {
13
+ if (value.notify && !value.notification) {
14
+ ctx.addIssue({
15
+ code: z.ZodIssueCode.custom,
16
+ message: "Notification metadata is required when notify is enabled",
17
+ path: ["notification"],
18
+ });
19
+ }
5
20
  });
6
21
  const OutputQuerySchema = z.object({
7
22
  method: z.enum(["full", "tail", "head", "grep"]).optional(),
@@ -17,7 +32,10 @@ export function registerBackgroundProcessRoutes(app, deps) {
17
32
  });
18
33
  app.post("/workspaces/:id/plugin/background-processes", async (request, reply) => {
19
34
  const payload = StartSchema.parse(request.body ?? {});
20
- const process = await deps.backgroundProcessManager.start(request.params.id, payload.title, payload.command);
35
+ const process = await deps.backgroundProcessManager.start(request.params.id, payload.title, payload.command, {
36
+ notify: payload.notify,
37
+ notification: payload.notification,
38
+ });
21
39
  reply.code(201);
22
40
  return process;
23
41
  });
@@ -1,17 +1,14 @@
1
- import { resolveNetworkAddresses } from "../network-addresses";
2
1
  export function registerMetaRoutes(app, deps) {
3
2
  app.get("/api/meta", async () => buildMetaResponse(deps.serverMeta));
4
3
  }
5
4
  function buildMetaResponse(meta) {
6
5
  const localPort = resolveLocalPort(meta);
7
6
  const remote = resolveRemote(meta);
8
- const addresses = remote && remote.port > 0 ? resolveNetworkAddresses({ host: meta.host, protocol: remote.protocol, port: remote.port }) : [];
9
7
  return {
10
8
  ...meta,
11
9
  localPort,
12
10
  remotePort: remote?.port,
13
11
  listeningMode: meta.host === "0.0.0.0" || !isLoopbackHost(meta.host) ? "all" : "local",
14
- addresses,
15
12
  };
16
13
  }
17
14
  function resolveLocalPort(meta) {
@@ -41,7 +41,11 @@ export function registerPluginRoutes(app, deps) {
41
41
  return;
42
42
  }
43
43
  const payload = VoiceModeStateSchema.parse(request.body ?? {});
44
- deps.voiceModeManager.setEnabled(request.params.id, { clientId: payload.clientId, connectionId: payload.connectionId }, payload.enabled);
44
+ const applied = deps.voiceModeManager.setEnabled(request.params.id, { clientId: payload.clientId, connectionId: payload.connectionId }, payload.enabled);
45
+ if (payload.enabled && !applied) {
46
+ reply.code(409).send({ error: "Client connection not active for voice mode enable" });
47
+ return;
48
+ }
45
49
  return { enabled: payload.enabled };
46
50
  });
47
51
  const handleWildcard = async (request, reply) => {
@@ -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
+ }
@@ -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
+ }
@@ -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",