@neuralnomads/codenomad 0.13.1 → 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 (81) hide show
  1. package/dist/auth/manager.js +5 -1
  2. package/dist/background-processes/manager.js +164 -25
  3. package/dist/clients/connection-manager.js +93 -0
  4. package/dist/config/schema.js +1 -0
  5. package/dist/events/bus.js +4 -0
  6. package/dist/filesystem/browser.js +7 -0
  7. package/dist/index.js +56 -5
  8. package/dist/opencode-config/package.json +1 -1
  9. package/dist/opencode-config/plugin/codenomad.ts +30 -0
  10. package/dist/opencode-config/plugin/lib/background-process.ts +14 -2
  11. package/dist/plugins/voice-mode.js +78 -0
  12. package/dist/server/__tests__/network-addresses.test.js +68 -0
  13. package/dist/server/http-server.js +294 -3
  14. package/dist/server/network-addresses.js +43 -1
  15. package/dist/server/routes/background-processes.js +19 -1
  16. package/dist/server/routes/events.js +24 -1
  17. package/dist/server/routes/meta.js +0 -3
  18. package/dist/server/routes/plugin.js +22 -4
  19. package/dist/server/routes/remote-servers.js +142 -0
  20. package/dist/server/routes/sidecars.js +46 -0
  21. package/dist/server/routes/workspaces.js +14 -0
  22. package/dist/settings/migrate.js +5 -0
  23. package/dist/settings/service.js +64 -4
  24. package/dist/sidecars/manager.js +193 -0
  25. package/dist/speech/providers/openai-compatible.js +32 -11
  26. package/dist/ui/__tests__/remote-ui.test.js +21 -0
  27. package/dist/ui/remote-ui.js +2 -2
  28. package/dist/workspaces/manager.js +7 -0
  29. package/dist/workspaces/runtime.js +2 -1
  30. package/package.json +1 -1
  31. package/public/assets/ChangesTab-CFkk3tAp.js +2 -0
  32. package/public/assets/DiffToolbar-CQQLR1mp.js +1 -0
  33. package/public/assets/FilesTab-CXgucPtN.js +2 -0
  34. package/public/assets/GitChangesTab-BidSb28_.js +2 -0
  35. package/public/assets/{SplitFilePanel-DbTPpm8n.js → SplitFilePanel-CupweEA5.js} +1 -1
  36. package/public/assets/StatusTab-C2Pl_Vce.js +1 -0
  37. package/public/assets/{bundle-full-UinVq7HP.js → bundle-full-B-5u6Iv3.js} +1 -1
  38. package/public/assets/diff-viewer-_ehhYA-Z.js +1 -0
  39. package/public/assets/git-diff-vendor-CSgooKT_.js +52 -0
  40. package/public/assets/index-BnfDkr8C.js +1 -0
  41. package/public/assets/index-BntAaLZs.js +1 -0
  42. package/public/assets/index-BqiNjV6R.js +1 -0
  43. package/public/assets/index-BwCEJ4BE.css +1 -0
  44. package/public/assets/{index-CdoHjzfy.js → index-CxQr-wOF.js} +1 -1
  45. package/public/assets/index-DXaitXVC.js +1 -0
  46. package/public/assets/index-DzRzoTK8.js +2 -0
  47. package/public/assets/index-ShHad48G.js +1 -0
  48. package/public/assets/index-_EaXFUIj.js +1 -0
  49. package/public/assets/index-mMh5TJvW.js +1 -0
  50. package/public/assets/{loading-D8mHQfQ7.js → loading-Dck2H3XH.js} +1 -1
  51. package/public/assets/main-BsIf5lOY.js +50 -0
  52. package/public/assets/{markdown-pqPmydDQ.js → markdown-CFV9kR80.js} +20 -20
  53. package/public/assets/monaco-viewer-CMM6n0T3.js +25 -0
  54. package/public/assets/{todo-BbZMcvOc.js → todo-Ghwirj-b.js} +1 -1
  55. package/public/assets/tool-call-BC2Pv3uG.js +60 -0
  56. package/public/assets/unified-picker-Dw0kTXoT.js +1 -0
  57. package/public/assets/wrap-text-D2MJk2ad.js +1 -0
  58. package/public/index.html +5 -5
  59. package/public/loading.html +5 -5
  60. package/public/sw.js +1 -1
  61. package/public/ui-version.json +1 -1
  62. package/public/assets/ChangesTab-DdswQ3Ok.js +0 -2
  63. package/public/assets/DiffToolbar-Yldqxvj8.js +0 -1
  64. package/public/assets/FilesTab-7agluNpw.js +0 -2
  65. package/public/assets/GitChangesTab-BZ5PaHzK.js +0 -2
  66. package/public/assets/StatusTab-CKBp3O9-.js +0 -1
  67. package/public/assets/diff-viewer-D9gxUZHP.js +0 -1
  68. package/public/assets/git-diff-vendor-CAv-4upN.js +0 -52
  69. package/public/assets/index-0Gk1-9Cd.js +0 -1
  70. package/public/assets/index-BEO8r15M.js +0 -1
  71. package/public/assets/index-BH7b9sVx.js +0 -1
  72. package/public/assets/index-CHPcUby9.js +0 -2
  73. package/public/assets/index-Cjpfqqyq.js +0 -1
  74. package/public/assets/index-D7Ta2Qha.js +0 -1
  75. package/public/assets/index-DxTSRG2o.js +0 -1
  76. package/public/assets/index-ENvu-xYE.css +0 -1
  77. package/public/assets/index-YR_aK97-.js +0 -1
  78. package/public/assets/main-DnH_qzWG.js +0 -56
  79. package/public/assets/monaco-viewer-BSBw02bx.js +0 -15
  80. package/public/assets/tool-call-BBzW7Hvr.js +0 -60
  81. package/public/assets/unified-picker-DcafxZRV.js +0 -1
@@ -0,0 +1,78 @@
1
+ export class VoiceModeManager {
2
+ constructor(options) {
3
+ this.options = options;
4
+ this.enabledConnectionsByInstance = new Map();
5
+ this.aggregateByInstance = new Map();
6
+ this.options.connections.subscribe((event) => {
7
+ if (event.type !== "disconnected")
8
+ return;
9
+ this.clearConnection(event.connection);
10
+ });
11
+ }
12
+ setEnabled(instanceId, connection, enabled) {
13
+ if (enabled && !this.options.connections.isConnected(connection)) {
14
+ this.options.logger.debug({ instanceId, clientId: connection.clientId, connectionId: connection.connectionId }, "Ignoring voice mode enable for disconnected client connection");
15
+ return false;
16
+ }
17
+ const key = getConnectionKey(connection);
18
+ const current = this.enabledConnectionsByInstance.get(instanceId) ?? new Set();
19
+ if (enabled) {
20
+ current.add(key);
21
+ this.enabledConnectionsByInstance.set(instanceId, current);
22
+ }
23
+ else if (current.delete(key)) {
24
+ if (current.size === 0) {
25
+ this.enabledConnectionsByInstance.delete(instanceId);
26
+ }
27
+ else {
28
+ this.enabledConnectionsByInstance.set(instanceId, current);
29
+ }
30
+ }
31
+ this.options.logger.debug({ instanceId, clientId: connection.clientId, connectionId: connection.connectionId, enabled }, "Voice mode updated for client connection");
32
+ this.publishIfChanged(instanceId);
33
+ return true;
34
+ }
35
+ syncInstance(instanceId) {
36
+ this.options.channel.send(instanceId, buildVoiceModeEvent(this.isEnabled(instanceId)));
37
+ }
38
+ isEnabled(instanceId) {
39
+ return this.aggregateByInstance.get(instanceId) === true;
40
+ }
41
+ clearConnection(connection) {
42
+ const key = getConnectionKey(connection);
43
+ for (const [instanceId, enabledConnections] of Array.from(this.enabledConnectionsByInstance.entries())) {
44
+ if (!enabledConnections.delete(key))
45
+ continue;
46
+ if (enabledConnections.size === 0) {
47
+ this.enabledConnectionsByInstance.delete(instanceId);
48
+ }
49
+ this.publishIfChanged(instanceId);
50
+ }
51
+ }
52
+ publishIfChanged(instanceId) {
53
+ const enabled = (this.enabledConnectionsByInstance.get(instanceId)?.size ?? 0) > 0;
54
+ const previous = this.aggregateByInstance.get(instanceId) === true;
55
+ if (enabled === previous)
56
+ return;
57
+ if (enabled) {
58
+ this.aggregateByInstance.set(instanceId, true);
59
+ }
60
+ else {
61
+ this.aggregateByInstance.delete(instanceId);
62
+ }
63
+ this.options.logger.debug({ instanceId, enabled }, "Broadcasting aggregate voice mode");
64
+ this.options.channel.send(instanceId, buildVoiceModeEvent(enabled));
65
+ }
66
+ }
67
+ function buildVoiceModeEvent(enabled) {
68
+ return {
69
+ type: "codenomad.voiceMode",
70
+ properties: {
71
+ enabled,
72
+ formatVersion: "v1",
73
+ },
74
+ };
75
+ }
76
+ function getConnectionKey(connection) {
77
+ return `${connection.clientId}:${connection.connectionId}`;
78
+ }
@@ -0,0 +1,68 @@
1
+ import assert from "node:assert/strict";
2
+ import os from "node:os";
3
+ import { describe, it } from "node:test";
4
+ import { resolveNetworkAddresses, resolveRemoteAddresses } from "../network-addresses";
5
+ describe("resolveNetworkAddresses", () => {
6
+ it("preserves interface order among external addresses", () => {
7
+ const addresses = [
8
+ { address: "172.24.0.1", family: "IPv4", internal: false },
9
+ { address: "192.168.1.128", family: "IPv4", internal: false },
10
+ { address: "10.0.0.8", family: 4, internal: false },
11
+ { address: "127.0.0.1", family: "IPv4", internal: true },
12
+ { address: "169.254.10.20", family: "IPv4", internal: false },
13
+ ];
14
+ usingMockedNetworkInterfaces(addresses, () => {
15
+ const result = resolveNetworkAddresses({ host: "0.0.0.0", protocol: "https", port: 9898 });
16
+ assert.deepEqual(result.map((entry) => entry.ip), ["172.24.0.1", "192.168.1.128", "10.0.0.8", "169.254.10.20", "127.0.0.1"]);
17
+ });
18
+ });
19
+ });
20
+ describe("resolveRemoteAddresses", () => {
21
+ it("keeps all external addresses user-visible while preferring non-link-local addresses for the primary URL", () => {
22
+ const addresses = [
23
+ { address: "169.254.10.20", family: "IPv4", internal: false },
24
+ { address: "192.168.1.128", family: "IPv4", internal: false },
25
+ { address: "172.24.0.1", family: "IPv4", internal: false },
26
+ ];
27
+ usingMockedNetworkInterfaces(addresses, () => {
28
+ const result = resolveRemoteAddresses({ host: "0.0.0.0", protocol: "https", port: 9898 });
29
+ assert.deepEqual(result.userVisible.map((entry) => entry.ip), ["192.168.1.128", "172.24.0.1", "169.254.10.20"]);
30
+ assert.equal(result.primaryRemoteUrl, "https://192.168.1.128:9898");
31
+ });
32
+ });
33
+ it("prefers private LAN addresses over public addresses", () => {
34
+ const addresses = [
35
+ { address: "203.0.113.40", family: "IPv4", internal: false },
36
+ { address: "192.168.1.128", family: "IPv4", internal: false },
37
+ { address: "8.8.8.8", family: "IPv4", internal: false },
38
+ ];
39
+ usingMockedNetworkInterfaces(addresses, () => {
40
+ const result = resolveRemoteAddresses({ host: "0.0.0.0", protocol: "https", port: 9898 });
41
+ assert.deepEqual(result.userVisible.map((entry) => entry.ip), ["192.168.1.128", "203.0.113.40", "8.8.8.8"]);
42
+ assert.equal(result.primaryRemoteUrl, "https://192.168.1.128:9898");
43
+ });
44
+ });
45
+ it("uses a public address when no private LAN address is available", () => {
46
+ const addresses = [
47
+ { address: "169.254.10.20", family: "IPv4", internal: false },
48
+ { address: "203.0.113.40", family: "IPv4", internal: false },
49
+ ];
50
+ usingMockedNetworkInterfaces(addresses, () => {
51
+ const result = resolveRemoteAddresses({ host: "0.0.0.0", protocol: "https", port: 9898 });
52
+ assert.deepEqual(result.userVisible.map((entry) => entry.ip), ["203.0.113.40", "169.254.10.20"]);
53
+ assert.equal(result.primaryRemoteUrl, "https://203.0.113.40:9898");
54
+ });
55
+ });
56
+ });
57
+ function usingMockedNetworkInterfaces(addresses, callback) {
58
+ const original = os.networkInterfaces;
59
+ os.networkInterfaces = (() => ({
60
+ ethernet0: addresses,
61
+ }));
62
+ try {
63
+ callback();
64
+ }
65
+ finally {
66
+ os.networkInterfaces = original;
67
+ }
68
+ }
@@ -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,6 +18,8 @@ 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";
@@ -139,7 +143,7 @@ export function createHttpServer(deps) {
139
143
  return;
140
144
  }
141
145
  const session = deps.authManager.getSessionFromRequest(request);
142
- const requiresAuthForApi = pathname.startsWith("/api/") || pathname.startsWith("/workspaces/");
146
+ const requiresAuthForApi = pathname.startsWith("/api/") || pathname.startsWith("/workspaces/") || pathname.startsWith("/sidecars/");
143
147
  if (requiresAuthForApi && !session) {
144
148
  // Allow OpenCode plugin -> CodeNomad calls with per-instance basic auth.
145
149
  const pluginMatch = pathname.match(/^\/workspaces\/([^/]+)\/plugin(?:\/|$)/);
@@ -185,15 +189,34 @@ export function createHttpServer(deps) {
185
189
  registerSettingsRoutes(app, { settings: deps.settings, logger: apiLogger });
186
190
  registerFilesystemRoutes(app, { fileSystemBrowser: deps.fileSystemBrowser });
187
191
  registerMetaRoutes(app, { serverMeta: deps.serverMeta });
188
- registerEventRoutes(app, { eventBus: deps.eventBus, registerClient: registerSseClient, logger: sseLogger });
192
+ registerEventRoutes(app, {
193
+ eventBus: deps.eventBus,
194
+ registerClient: registerSseClient,
195
+ logger: sseLogger,
196
+ connectionManager: deps.clientConnectionManager,
197
+ });
189
198
  registerWorktreeRoutes(app, { workspaceManager: deps.workspaceManager });
190
199
  registerStorageRoutes(app, {
191
200
  instanceStore: deps.instanceStore,
192
201
  eventBus: deps.eventBus,
193
202
  workspaceManager: deps.workspaceManager,
194
203
  });
204
+ registerRemoteServerRoutes(app, { logger: apiLogger });
195
205
  registerSpeechRoutes(app, { speechService: deps.speechService });
196
- registerPluginRoutes(app, { workspaceManager: deps.workspaceManager, eventBus: deps.eventBus, logger: proxyLogger });
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
+ });
213
+ registerPluginRoutes(app, {
214
+ workspaceManager: deps.workspaceManager,
215
+ eventBus: deps.eventBus,
216
+ logger: proxyLogger,
217
+ channel: deps.pluginChannel,
218
+ voiceModeManager: deps.voiceModeManager,
219
+ });
197
220
  registerBackgroundProcessRoutes(app, { backgroundProcessManager });
198
221
  registerInstanceProxyRoutes(app, { workspaceManager: deps.workspaceManager, logger: proxyLogger });
199
222
  if (deps.uiDevServerUrl) {
@@ -255,6 +278,48 @@ export function createHttpServer(deps) {
255
278
  },
256
279
  };
257
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
+ }
258
323
  function registerInstanceProxyRoutes(app, deps) {
259
324
  app.register(async (instance) => {
260
325
  instance.removeAllContentTypeParsers();
@@ -657,3 +722,229 @@ function buildProxyHeaders(headers) {
657
722
  }
658
723
  return result;
659
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,7 +1,16 @@
1
+ import { z } from "zod";
1
2
  let nextClientId = 0;
3
+ const ConnectionQuerySchema = z.object({
4
+ clientId: z.string().trim().min(1),
5
+ connectionId: z.string().trim().min(1),
6
+ });
7
+ const PongBodySchema = ConnectionQuerySchema.extend({
8
+ pingTs: z.number().optional(),
9
+ });
2
10
  export function registerEventRoutes(app, deps) {
3
11
  app.get("/api/events", (request, reply) => {
4
12
  const clientId = ++nextClientId;
13
+ const connection = ConnectionQuerySchema.parse(request.query ?? {});
5
14
  deps.logger.debug({ clientId }, "SSE client connected");
6
15
  const origin = request.headers.origin ?? "*";
7
16
  reply.raw.setHeader("Access-Control-Allow-Origin", origin);
@@ -20,7 +29,8 @@ export function registerEventRoutes(app, deps) {
20
29
  };
21
30
  const unsubscribe = deps.eventBus.onEvent(send);
22
31
  const heartbeat = setInterval(() => {
23
- reply.raw.write(`:hb ${Date.now()}\n\n`);
32
+ const ping = { ts: Date.now() };
33
+ reply.raw.write(`event: codenomad.client.ping\ndata: ${JSON.stringify(ping)}\n\n`);
24
34
  }, 15000);
25
35
  let closed = false;
26
36
  const close = () => {
@@ -33,11 +43,24 @@ export function registerEventRoutes(app, deps) {
33
43
  deps.logger.debug({ clientId }, "SSE client disconnected");
34
44
  };
35
45
  const unregister = deps.registerClient(close);
46
+ const unregisterConnection = deps.connectionManager.register({
47
+ ...connection,
48
+ close,
49
+ });
36
50
  const handleClose = () => {
37
51
  close();
38
52
  unregister();
53
+ unregisterConnection();
39
54
  };
40
55
  request.raw.on("close", handleClose);
41
56
  request.raw.on("error", handleClose);
42
57
  });
58
+ app.post("/api/client-connections/pong", (request, reply) => {
59
+ const body = PongBodySchema.parse(request.body ?? {});
60
+ if (!deps.connectionManager.pong(body)) {
61
+ reply.code(404).send({ error: "Client connection not found" });
62
+ return;
63
+ }
64
+ reply.code(204).send();
65
+ });
43
66
  }
@@ -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) {