@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
@@ -75,12 +75,16 @@ export class AuthManager {
75
75
  return isLoopbackAddress(request.socket.remoteAddress);
76
76
  }
77
77
  getSessionFromRequest(request) {
78
+ return this.getSessionFromHeaders(request.headers);
79
+ }
80
+ getSessionFromHeaders(headers) {
78
81
  if (!this.authEnabled) {
79
82
  // When auth is disabled, treat all requests as authenticated.
80
83
  // We still return a stable username so callers can display it.
81
84
  return { username: this.init.username, sessionId: "auth-disabled" };
82
85
  }
83
- const cookies = parseCookies(request.headers.cookie);
86
+ const cookieHeader = Array.isArray(headers.cookie) ? headers.cookie.join("; ") : headers.cookie;
87
+ const cookies = parseCookies(cookieHeader);
84
88
  const sessionId = cookies[this.cookieName];
85
89
  const session = this.sessionManager.getSession(sessionId);
86
90
  if (!session)
@@ -19,12 +19,12 @@ export class BackgroundProcessManager {
19
19
  async list(workspaceId) {
20
20
  const records = await this.readIndex(workspaceId);
21
21
  const enriched = await Promise.all(records.map(async (record) => ({
22
- ...record,
22
+ ...this.toPublicProcess(record),
23
23
  outputSizeBytes: await this.getOutputSize(workspaceId, record.id),
24
24
  })));
25
25
  return enriched;
26
26
  }
27
- async start(workspaceId, title, command) {
27
+ async start(workspaceId, title, command, options = {}) {
28
28
  const workspace = this.deps.workspaceManager.get(workspaceId);
29
29
  if (!workspace) {
30
30
  throw new Error("Workspace not found");
@@ -53,21 +53,35 @@ export class BackgroundProcessManager {
53
53
  pid: child.pid,
54
54
  startedAt: new Date().toISOString(),
55
55
  outputSizeBytes: 0,
56
+ notify: options.notify && options.notification
57
+ ? {
58
+ sessionID: options.notification.sessionID,
59
+ directory: options.notification.directory,
60
+ }
61
+ : undefined,
62
+ };
63
+ const runningState = {
64
+ id,
65
+ child,
66
+ outputPath,
67
+ exitPromise: Promise.resolve(),
68
+ workspaceId,
56
69
  };
57
70
  const exitPromise = new Promise((resolve) => {
58
71
  child.on("close", async (code) => {
59
72
  await new Promise((resolve) => outputStream.end(resolve));
60
73
  this.running.delete(id);
61
- record.status = this.statusFromExit(code);
74
+ const completion = runningState.completion ?? this.completionFromExit(code);
75
+ record.terminalReason = completion.reason;
76
+ record.status = this.statusFromReason(completion.reason);
62
77
  record.exitCode = code === null ? undefined : code;
63
78
  record.stoppedAt = new Date().toISOString();
64
- await this.upsertIndex(workspaceId, record);
65
- record.outputSizeBytes = await this.getOutputSize(workspaceId, record.id);
66
- this.publishUpdate(workspaceId, record);
79
+ await this.finalizeRecord(workspaceId, record, completion);
67
80
  resolve();
68
81
  });
69
82
  });
70
- this.running.set(id, { id, child, outputPath, exitPromise, workspaceId });
83
+ runningState.exitPromise = exitPromise;
84
+ this.running.set(id, runningState);
71
85
  let lastPublishAt = 0;
72
86
  const maybePublishSize = () => {
73
87
  const now = Date.now();
@@ -90,7 +104,7 @@ export class BackgroundProcessManager {
90
104
  await this.upsertIndex(workspaceId, record);
91
105
  record.outputSizeBytes = await this.getOutputSize(workspaceId, record.id);
92
106
  this.publishUpdate(workspaceId, record);
93
- return record;
107
+ return this.toPublicProcess(record);
94
108
  }
95
109
  async stop(workspaceId, processId) {
96
110
  const record = await this.findProcess(workspaceId, processId);
@@ -99,17 +113,19 @@ export class BackgroundProcessManager {
99
113
  }
100
114
  const running = this.running.get(processId);
101
115
  if (running?.child && !running.child.killed) {
116
+ running.completion = { reason: "user_stopped", endContext: "normal" };
102
117
  this.killProcessTree(running.child, "SIGTERM");
103
118
  await this.waitForExit(running);
119
+ const updated = await this.findProcess(workspaceId, processId);
120
+ return updated ? this.toPublicProcess(updated) : this.toPublicProcess(record);
104
121
  }
105
122
  if (record.status === "running") {
106
123
  record.status = "stopped";
124
+ record.terminalReason = "user_stopped";
107
125
  record.stoppedAt = new Date().toISOString();
108
- await this.upsertIndex(workspaceId, record);
109
- record.outputSizeBytes = await this.getOutputSize(workspaceId, record.id);
110
- this.publishUpdate(workspaceId, record);
126
+ await this.finalizeRecord(workspaceId, record, { reason: "user_stopped", endContext: "normal" });
111
127
  }
112
- return record;
128
+ return this.toPublicProcess(record);
113
129
  }
114
130
  async terminate(workspaceId, processId) {
115
131
  const record = await this.findProcess(workspaceId, processId);
@@ -117,15 +133,18 @@ export class BackgroundProcessManager {
117
133
  return;
118
134
  const running = this.running.get(processId);
119
135
  if (running?.child && !running.child.killed) {
136
+ running.completion = { reason: "user_terminated", endContext: "normal", removeAfterFinalize: true };
120
137
  this.killProcessTree(running.child, "SIGTERM");
121
138
  await this.waitForExit(running);
139
+ return;
122
140
  }
123
- await this.removeFromIndex(workspaceId, processId);
124
- await this.removeProcessDir(workspaceId, processId);
125
- this.deps.eventBus.publish({
126
- type: "instance.event",
127
- instanceId: workspaceId,
128
- event: { type: "background.process.removed", properties: { processId } },
141
+ record.status = "stopped";
142
+ record.terminalReason = "user_terminated";
143
+ record.stoppedAt = new Date().toISOString();
144
+ await this.finalizeRecord(workspaceId, record, {
145
+ reason: "user_terminated",
146
+ endContext: "normal",
147
+ removeAfterFinalize: true,
129
148
  });
130
149
  }
131
150
  async readOutput(workspaceId, processId, options) {
@@ -204,6 +223,11 @@ export class BackgroundProcessManager {
204
223
  for (const [, running] of this.running.entries()) {
205
224
  if (running.workspaceId !== workspaceId)
206
225
  continue;
226
+ running.completion = {
227
+ reason: "user_terminated",
228
+ endContext: "workspace_cleanup",
229
+ removeAfterFinalize: true,
230
+ };
207
231
  this.killProcessTree(running.child, "SIGTERM");
208
232
  await this.waitForExit(running);
209
233
  }
@@ -287,12 +311,16 @@ export class BackgroundProcessManager {
287
311
  }
288
312
  return args;
289
313
  }
290
- statusFromExit(code) {
291
- if (code === null)
292
- return "stopped";
293
- if (code === 0)
294
- return "stopped";
295
- return "error";
314
+ completionFromExit(code) {
315
+ if (code === 0) {
316
+ return { reason: "finished", endContext: "normal" };
317
+ }
318
+ return { reason: "failed", endContext: "normal" };
319
+ }
320
+ statusFromReason(reason) {
321
+ if (reason === "failed")
322
+ return "error";
323
+ return "stopped";
296
324
  }
297
325
  async readOutputBytes(outputPath, sizeBytes, maxBytes) {
298
326
  if (maxBytes === undefined || sizeBytes <= maxBytes) {
@@ -426,8 +454,119 @@ export class BackgroundProcessManager {
426
454
  this.deps.eventBus.publish({
427
455
  type: "instance.event",
428
456
  instanceId: workspaceId,
429
- event: { type: "background.process.updated", properties: { process: record } },
457
+ event: { type: "background.process.updated", properties: { process: this.toPublicProcess(record) } },
458
+ });
459
+ }
460
+ toPublicProcess(record) {
461
+ return {
462
+ id: record.id,
463
+ workspaceId: record.workspaceId,
464
+ title: record.title,
465
+ command: record.command,
466
+ cwd: record.cwd,
467
+ status: record.status,
468
+ pid: record.pid,
469
+ startedAt: record.startedAt,
470
+ stoppedAt: record.stoppedAt,
471
+ exitCode: record.exitCode,
472
+ outputSizeBytes: record.outputSizeBytes,
473
+ terminalReason: record.terminalReason,
474
+ notifyEnabled: Boolean(record.notify),
475
+ };
476
+ }
477
+ async finalizeRecord(workspaceId, record, completion) {
478
+ if (this.shouldSendCompletionPrompt(record, completion)) {
479
+ try {
480
+ await this.sendCompletionPrompt(workspaceId, record);
481
+ if (record.notify) {
482
+ record.notify.sentAt = new Date().toISOString();
483
+ }
484
+ }
485
+ catch (error) {
486
+ this.deps.logger.warn({ err: error, workspaceId, processId: record.id }, "Failed to send background process completion prompt");
487
+ }
488
+ }
489
+ if (completion.removeAfterFinalize) {
490
+ await this.removeFromIndex(workspaceId, record.id);
491
+ await this.removeProcessDir(workspaceId, record.id);
492
+ this.deps.eventBus.publish({
493
+ type: "instance.event",
494
+ instanceId: workspaceId,
495
+ event: { type: "background.process.removed", properties: { processId: record.id } },
496
+ });
497
+ return;
498
+ }
499
+ await this.upsertIndex(workspaceId, record);
500
+ record.outputSizeBytes = await this.getOutputSize(workspaceId, record.id);
501
+ this.publishUpdate(workspaceId, record);
502
+ }
503
+ shouldSendCompletionPrompt(record, completion) {
504
+ if (completion.endContext === "workspace_cleanup")
505
+ return false;
506
+ if (!record.notify)
507
+ return false;
508
+ return !record.notify.sentAt;
509
+ }
510
+ async sendCompletionPrompt(workspaceId, record) {
511
+ const notify = record.notify;
512
+ if (!notify || !record.terminalReason)
513
+ return;
514
+ if (!this.deps.workspaceManager.get(workspaceId)) {
515
+ throw new Error("Workspace not found");
516
+ }
517
+ const port = this.deps.workspaceManager.getInstancePort(workspaceId);
518
+ if (!port) {
519
+ throw new Error("Workspace instance is not ready");
520
+ }
521
+ const targetUrl = `http://127.0.0.1:${port}/session/${encodeURIComponent(notify.sessionID)}/prompt_async`;
522
+ const headers = {
523
+ "content-type": "application/json",
524
+ "x-opencode-directory": /[^\x00-\x7F]/.test(notify.directory) ? encodeURIComponent(notify.directory) : notify.directory,
525
+ };
526
+ const authorization = this.deps.workspaceManager.getInstanceAuthorizationHeader(workspaceId);
527
+ if (authorization) {
528
+ headers.authorization = authorization;
529
+ }
530
+ const response = await fetch(targetUrl, {
531
+ method: "POST",
532
+ headers,
533
+ body: JSON.stringify({
534
+ parts: [
535
+ {
536
+ type: "text",
537
+ text: this.buildSyntheticCompletionPrompt(record),
538
+ synthetic: true,
539
+ },
540
+ ],
541
+ }),
430
542
  });
543
+ if (!response.ok) {
544
+ const message = await response.text().catch(() => "");
545
+ throw new Error(message || `Prompt request failed with ${response.status}`);
546
+ }
547
+ }
548
+ buildCompletionPrompt(record) {
549
+ const ref = `Background process "${record.title}" (${record.id})`;
550
+ switch (record.terminalReason) {
551
+ case "finished":
552
+ return `${ref} finished successfully.`;
553
+ case "failed":
554
+ return record.exitCode === undefined ? `${ref} failed.` : `${ref} failed with exit code ${record.exitCode}.`;
555
+ case "user_stopped":
556
+ return `${ref} was stopped by user.`;
557
+ case "user_terminated":
558
+ return `${ref} was terminated by user.`;
559
+ }
560
+ return `${ref} ended.`;
561
+ }
562
+ buildSyntheticCompletionPrompt(record) {
563
+ return `<system-message>${this.escapeTaggedText(this.buildCompletionPrompt(record))}</system-message>`;
564
+ }
565
+ escapeTaggedText(input) {
566
+ return input
567
+ .replace(/&/g, "&amp;")
568
+ .replace(/</g, "&lt;")
569
+ .replace(/>/g, "&gt;");
431
570
  }
432
571
  generateId() {
433
572
  const timestamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
@@ -0,0 +1,53 @@
1
+ import { spawn } from "child_process";
2
+ const CODENOMAD_PACKAGE_NAME = "@neuralnomads/codenomad";
3
+ function detectFromText(value) {
4
+ const lower = (value ?? "").toLowerCase();
5
+ if (!lower)
6
+ return null;
7
+ if (lower.includes("pnpm"))
8
+ return "pnpm";
9
+ if (lower.includes("bun"))
10
+ return "bun";
11
+ if (lower.includes("npm"))
12
+ return "npm";
13
+ return null;
14
+ }
15
+ export function detectPackageManager(env = process.env) {
16
+ return detectFromText(env.npm_config_user_agent) ?? detectFromText(env.npm_execpath) ?? "npm";
17
+ }
18
+ export function buildUpgradeCommand(version, packageManager = detectPackageManager()) {
19
+ const targetVersion = (version ?? "").trim() || "latest";
20
+ const packageSpec = `${CODENOMAD_PACKAGE_NAME}@${targetVersion}`;
21
+ const args = packageManager === "bun" ? ["add", "-g", packageSpec] : ["install", "-g", packageSpec];
22
+ return {
23
+ command: packageManager,
24
+ args,
25
+ packageSpec,
26
+ };
27
+ }
28
+ export function formatUpgradeCommand(command) {
29
+ return [command.command, ...command.args].join(" ");
30
+ }
31
+ export function runCliUpgrade(version, env = process.env) {
32
+ const upgrade = buildUpgradeCommand(version, detectPackageManager(env));
33
+ console.log(`Upgrading CodeNomad with: ${formatUpgradeCommand(upgrade)}`);
34
+ return new Promise((resolve) => {
35
+ const child = spawn(upgrade.command, upgrade.args, {
36
+ env,
37
+ shell: process.platform === "win32",
38
+ stdio: "inherit",
39
+ });
40
+ child.on("exit", (code, signal) => {
41
+ if (signal) {
42
+ console.error(`Upgrade command stopped by signal ${signal}`);
43
+ resolve(1);
44
+ return;
45
+ }
46
+ resolve(code ?? 0);
47
+ });
48
+ child.on("error", (error) => {
49
+ console.error("Failed to launch upgrade command", error);
50
+ resolve(1);
51
+ });
52
+ });
53
+ }
@@ -0,0 +1,31 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { buildUpgradeCommand, detectPackageManager, formatUpgradeCommand } from "./cli-upgrade";
4
+ describe("cli upgrade", () => {
5
+ it("defaults to npm when no package manager can be detected", () => {
6
+ assert.equal(detectPackageManager({}), "npm");
7
+ });
8
+ it("detects package managers from npm user agent", () => {
9
+ assert.equal(detectPackageManager({ npm_config_user_agent: "pnpm/9.0.0 node/v22" }), "pnpm");
10
+ assert.equal(detectPackageManager({ npm_config_user_agent: "bun/1.0.0" }), "bun");
11
+ assert.equal(detectPackageManager({ npm_config_user_agent: "npm/10.0.0 node/v22" }), "npm");
12
+ });
13
+ it("builds latest upgrade command by default", () => {
14
+ const command = buildUpgradeCommand(undefined, "npm");
15
+ assert.equal(command.packageSpec, "@neuralnomads/codenomad@latest");
16
+ assert.deepEqual(command.args, ["install", "-g", "@neuralnomads/codenomad@latest"]);
17
+ assert.equal(formatUpgradeCommand(command), "npm install -g @neuralnomads/codenomad@latest");
18
+ });
19
+ it("builds a versioned upgrade command", () => {
20
+ const command = buildUpgradeCommand("0.10.5", "pnpm");
21
+ assert.equal(command.packageSpec, "@neuralnomads/codenomad@0.10.5");
22
+ assert.deepEqual(command.args, ["install", "-g", "@neuralnomads/codenomad@0.10.5"]);
23
+ assert.equal(formatUpgradeCommand(command), "pnpm install -g @neuralnomads/codenomad@0.10.5");
24
+ });
25
+ it("uses bun add for Bun installs", () => {
26
+ const command = buildUpgradeCommand("0.10.5", "bun");
27
+ assert.equal(command.packageSpec, "@neuralnomads/codenomad@0.10.5");
28
+ assert.deepEqual(command.args, ["add", "-g", "@neuralnomads/codenomad@0.10.5"]);
29
+ assert.equal(formatUpgradeCommand(command), "bun add -g @neuralnomads/codenomad@0.10.5");
30
+ });
31
+ });
@@ -23,6 +23,7 @@ const PreferencesSchema = z
23
23
  showUsageMetrics: z.boolean().default(true),
24
24
  autoCleanupBlankSessions: z.boolean().default(true),
25
25
  listeningMode: z.enum(["local", "all"]).default("local"),
26
+ logLevel: z.enum(["DEBUG", "INFO", "WARN", "ERROR"]).default("DEBUG"),
26
27
  // OS notifications
27
28
  osNotificationsEnabled: z.boolean().default(false),
28
29
  osNotificationsAllowWhenVisible: z.boolean().default(false),
@@ -20,6 +20,8 @@ export class EventBus extends EventEmitter {
20
20
  this.on("workspace.error", handler);
21
21
  this.on("workspace.stopped", handler);
22
22
  this.on("workspace.log", handler);
23
+ this.on("sidecar.updated", handler);
24
+ this.on("sidecar.removed", handler);
23
25
  this.on("storage.configChanged", handler);
24
26
  this.on("storage.stateChanged", handler);
25
27
  this.on("instance.dataChanged", handler);
@@ -31,6 +33,8 @@ export class EventBus extends EventEmitter {
31
33
  this.off("workspace.error", handler);
32
34
  this.off("workspace.stopped", handler);
33
35
  this.off("workspace.log", handler);
36
+ this.off("sidecar.updated", handler);
37
+ this.off("sidecar.removed", handler);
34
38
  this.off("storage.configChanged", handler);
35
39
  this.off("storage.stateChanged", handler);
36
40
  this.off("instance.dataChanged", handler);
@@ -206,6 +206,17 @@ export class FileSystemBrowser {
206
206
  if (!input || input === "." || input === "./" || input === "/") {
207
207
  return ".";
208
208
  }
209
+ if (path.isAbsolute(input)) {
210
+ const resolved = path.resolve(input);
211
+ const relativeToRoot = path.relative(this.root, resolved);
212
+ if (relativeToRoot === "") {
213
+ return ".";
214
+ }
215
+ if (this.isOutsideRoot(relativeToRoot)) {
216
+ throw new Error("Access outside of root is not allowed");
217
+ }
218
+ return relativeToRoot.replace(/\\+/g, "/");
219
+ }
209
220
  let normalized = input.replace(/\\+/g, "/");
210
221
  if (normalized.startsWith("./")) {
211
222
  normalized = normalized.replace(/^\.\/+/, "");
@@ -232,11 +243,14 @@ export class FileSystemBrowser {
232
243
  const normalized = this.normalizeRelativePath(relativePath);
233
244
  const target = path.resolve(this.root, normalized);
234
245
  const relativeToRoot = path.relative(this.root, target);
235
- if (relativeToRoot.startsWith("..") || path.isAbsolute(relativeToRoot) && relativeToRoot !== "") {
246
+ if (this.isOutsideRoot(relativeToRoot)) {
236
247
  throw new Error("Access outside of root is not allowed");
237
248
  }
238
249
  return target;
239
250
  }
251
+ isOutsideRoot(relativeToRoot) {
252
+ return relativeToRoot === ".." || relativeToRoot.startsWith(`..${path.sep}`) || path.isAbsolute(relativeToRoot);
253
+ }
240
254
  resolveUnrestrictedPath(input) {
241
255
  if (!input || input === "." || input === "./") {
242
256
  return this.homeDir;
package/dist/index.js CHANGED
@@ -20,9 +20,15 @@ import { launchInBrowser } from "./launcher";
20
20
  import { resolveUi } from "./ui/remote-ui";
21
21
  import { AuthManager, BOOTSTRAP_TOKEN_STDOUT_PREFIX, DEFAULT_AUTH_COOKIE_NAME, DEFAULT_AUTH_USERNAME } from "./auth/manager";
22
22
  import { resolveHttpsOptions } from "./server/tls";
23
- import { resolveNetworkAddresses } from "./server/network-addresses";
23
+ import { RemoteProxySessionManager } from "./server/remote-proxy";
24
+ import { resolveNetworkAddresses, resolveRemoteAddresses } from "./server/network-addresses";
24
25
  import { startDevReleaseMonitor } from "./releases/dev-release-monitor";
25
26
  import { SpeechService } from "./speech/service";
27
+ import { SideCarManager } from "./sidecars/manager";
28
+ import { ClientConnectionManager } from "./clients/connection-manager";
29
+ import { PluginChannelManager } from "./plugins/channel";
30
+ import { VoiceModeManager } from "./plugins/voice-mode";
31
+ import { runCliUpgrade } from "./cli-upgrade";
26
32
  const require = createRequire(import.meta.url);
27
33
  const packageJson = require("../package.json");
28
34
  const __filename = fileURLToPath(import.meta.url);
@@ -70,9 +76,11 @@ function parseCliOptions(argv) {
70
76
  .default(false))
71
77
  .addOption(new Option("--dangerously-skip-auth", "Disable CodeNomad's internal auth. Use only behind a trusted perimeter (SSO/VPN/etc).")
72
78
  .env("CODENOMAD_SKIP_AUTH")
73
- .default(false));
79
+ .default(false))
80
+ .addOption(new Option("--upgrade [version]", "Upgrade the global CodeNomad CLI server package and exit"));
74
81
  program.parse(argv, { from: "user" });
75
82
  const parsed = program.opts();
83
+ const upgrade = parsed.upgrade;
76
84
  const parseBooleanEnv = (value) => {
77
85
  const normalized = (value ?? "").trim().toLowerCase();
78
86
  return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "y" || normalized === "on";
@@ -83,7 +91,7 @@ function parseCliOptions(argv) {
83
91
  const uiAutoUpdate = autoUpdateString === "1" || autoUpdateString === "true" || autoUpdateString === "yes";
84
92
  const httpsEnabled = parseBooleanEnv(parsed.https);
85
93
  const httpEnabled = parseBooleanEnv(parsed.http);
86
- if (!httpsEnabled && !httpEnabled) {
94
+ if (upgrade === undefined && !httpsEnabled && !httpEnabled) {
87
95
  throw new InvalidArgumentError("At least one listener must be enabled (--https or --http)");
88
96
  }
89
97
  return {
@@ -112,6 +120,7 @@ function parseCliOptions(argv) {
112
120
  authCookieName: parsed.authCookieName,
113
121
  generateToken: Boolean(parsed.generateToken),
114
122
  dangerouslySkipAuth: Boolean(parsed.dangerouslySkipAuth),
123
+ upgrade,
115
124
  };
116
125
  }
117
126
  function parsePort(input) {
@@ -138,6 +147,11 @@ function programHasArg(argv, flag) {
138
147
  }
139
148
  async function main() {
140
149
  const options = parseCliOptions(process.argv.slice(2));
150
+ if (options.upgrade !== undefined) {
151
+ const version = typeof options.upgrade === "string" ? options.upgrade : undefined;
152
+ process.exitCode = await runCliUpgrade(version);
153
+ return;
154
+ }
141
155
  const logger = createLogger({ level: options.logLevel, destination: options.logDestination, component: "app" });
142
156
  const workspaceLogger = logger.child({ component: "workspace" });
143
157
  const configLogger = logger.child({ component: "config" });
@@ -205,9 +219,17 @@ async function main() {
205
219
  getServerBaseUrl: () => serverMeta.localUrl,
206
220
  nodeExtraCaCertsPath,
207
221
  });
208
- const fileSystemBrowser = new FileSystemBrowser({ rootDir: options.rootDir, unrestricted: options.unrestrictedRoot });
222
+ const fileSystemBrowser = new FileSystemBrowser({
223
+ rootDir: options.rootDir,
224
+ unrestricted: options.unrestrictedRoot,
225
+ });
209
226
  const instanceStore = new InstanceStore(configLocation.instancesDir);
210
227
  const speechService = new SpeechService(settings, logger.child({ component: "speech" }));
228
+ const sidecarManager = new SideCarManager({
229
+ settings,
230
+ eventBus,
231
+ logger: logger.child({ component: "sidecars" }),
232
+ });
211
233
  const instanceEventBridge = new InstanceEventBridge({
212
234
  workspaceManager,
213
235
  eventBus,
@@ -253,10 +275,19 @@ async function main() {
253
275
  },
254
276
  })
255
277
  : null;
256
- if (uiResolution.uiDevServerUrl && options.https) {
257
- throw new InvalidArgumentError("UI dev proxy is only supported with --https=false --http=true");
258
- }
259
278
  const remoteAccessEnabled = options.host === "0.0.0.0" || !isLoopbackHost(options.host);
279
+ const clientConnectionManager = new ClientConnectionManager(logger.child({ component: "client-connections" }));
280
+ const pluginChannel = new PluginChannelManager(logger.child({ component: "plugin-channel" }));
281
+ const remoteProxySessionManager = new RemoteProxySessionManager({
282
+ authManager,
283
+ logger: logger.child({ component: "remote-proxy" }),
284
+ httpsOptions: tlsResolution?.httpsOptions,
285
+ });
286
+ const voiceModeManager = new VoiceModeManager({
287
+ connections: clientConnectionManager,
288
+ channel: pluginChannel,
289
+ logger: logger.child({ component: "voice-mode" }),
290
+ });
260
291
  const httpsPortExplicit = programHasArg(process.argv.slice(2), "--https-port") || Boolean(process.env.CLI_HTTPS_PORT);
261
292
  const httpPortExplicit = programHasArg(process.argv.slice(2), "--http-port") || Boolean(process.env.CLI_HTTP_PORT);
262
293
  const httpsBindPort = httpsPortExplicit ? options.httpsPort : 0;
@@ -281,7 +312,12 @@ async function main() {
281
312
  serverMeta,
282
313
  instanceStore,
283
314
  speechService,
315
+ sidecarManager,
284
316
  authManager,
317
+ clientConnectionManager,
318
+ pluginChannel,
319
+ voiceModeManager,
320
+ remoteProxySessionManager,
285
321
  uiStaticDir: uiResolution.uiStaticDir ?? DEFAULT_UI_STATIC_DIR,
286
322
  uiDevServerUrl: uiResolution.uiDevServerUrl,
287
323
  logger,
@@ -301,7 +337,12 @@ async function main() {
301
337
  serverMeta,
302
338
  instanceStore,
303
339
  speechService,
340
+ sidecarManager,
304
341
  authManager,
342
+ clientConnectionManager,
343
+ pluginChannel,
344
+ voiceModeManager,
345
+ remoteProxySessionManager,
305
346
  uiStaticDir: uiResolution.uiStaticDir ?? DEFAULT_UI_STATIC_DIR,
306
347
  uiDevServerUrl: undefined,
307
348
  logger,
@@ -328,19 +369,23 @@ async function main() {
328
369
  // which can lead clients to talk to the wrong process.
329
370
  const localUrl = `${localProtocol}://127.0.0.1:${localStart.port}`;
330
371
  let remoteUrl;
372
+ let remoteAddresses = [];
331
373
  if (remoteStart) {
332
374
  const wantsAll = options.host === "0.0.0.0" || !isLoopbackHost(options.host);
333
375
  let remoteHost = options.host;
334
376
  if (wantsAll) {
335
377
  if (options.host === "0.0.0.0") {
336
- const candidates = resolveNetworkAddresses({ host: options.host, protocol: remoteProtocol, port: remoteStart.port });
337
- remoteHost = candidates.find((addr) => addr.scope === "external")?.ip ?? "localhost";
378
+ const resolved = resolveRemoteAddresses({ host: options.host, protocol: remoteProtocol, port: remoteStart.port });
379
+ remoteAddresses = resolved.userVisible;
380
+ remoteUrl = resolved.primaryRemoteUrl ?? `${remoteProtocol}://localhost:${remoteStart.port}`;
338
381
  }
339
382
  }
340
383
  else {
341
384
  remoteHost = "localhost";
342
385
  }
343
- remoteUrl = `${remoteProtocol}://${remoteHost}:${remoteStart.port}`;
386
+ if (!remoteUrl) {
387
+ remoteUrl = `${remoteProtocol}://${remoteHost}:${remoteStart.port}`;
388
+ }
344
389
  }
345
390
  serverMeta.localUrl = localUrl;
346
391
  serverMeta.localPort = localStart.port;
@@ -349,7 +394,9 @@ async function main() {
349
394
  serverMeta.host = options.host;
350
395
  serverMeta.listeningMode = options.host === "0.0.0.0" || !isLoopbackHost(options.host) ? "all" : "local";
351
396
  if (serverMeta.remotePort && remoteUrl) {
352
- serverMeta.addresses = resolveNetworkAddresses({ host: options.host, protocol: remoteProtocol, port: serverMeta.remotePort });
397
+ serverMeta.addresses = remoteAddresses.length
398
+ ? remoteAddresses
399
+ : resolveNetworkAddresses({ host: options.host, protocol: remoteProtocol, port: serverMeta.remotePort });
353
400
  }
354
401
  else {
355
402
  serverMeta.addresses = [];
@@ -357,6 +404,15 @@ async function main() {
357
404
  console.log(`Local Connection URL : ${serverMeta.localUrl}`);
358
405
  if (serverMeta.remoteUrl) {
359
406
  console.log(`Remote Connection URL : ${serverMeta.remoteUrl}`);
407
+ const additionalRemoteUrls = serverMeta.addresses
408
+ .map((addr) => addr.remoteUrl)
409
+ .filter((url) => url !== serverMeta.remoteUrl);
410
+ if (additionalRemoteUrls.length > 0) {
411
+ console.log("Other Accessible URLs:");
412
+ for (const url of additionalRemoteUrls) {
413
+ console.log(` - ${url}`);
414
+ }
415
+ }
360
416
  }
361
417
  if (options.launch) {
362
418
  await launchInBrowser(serverMeta.localUrl, logger.child({ component: "launcher" }));
@@ -376,6 +432,18 @@ async function main() {
376
432
  catch (error) {
377
433
  logger.warn({ err: error }, "Instance event bridge shutdown failed");
378
434
  }
435
+ try {
436
+ await sidecarManager.shutdown();
437
+ }
438
+ catch (error) {
439
+ logger.error({ err: error }, "SideCar manager shutdown failed");
440
+ }
441
+ try {
442
+ clientConnectionManager.shutdown();
443
+ }
444
+ catch (error) {
445
+ logger.warn({ err: error }, "Client connection manager shutdown failed");
446
+ }
379
447
  try {
380
448
  await workspaceManager.shutdown();
381
449
  logger.info("Workspace manager shutdown complete");