@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
@@ -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,93 @@
1
+ const STALE_CONNECTION_TIMEOUT_MS = 45000;
2
+ const STALE_SWEEP_INTERVAL_MS = 5000;
3
+ export class ClientConnectionManager {
4
+ constructor(logger) {
5
+ this.logger = logger;
6
+ this.connections = new Map();
7
+ this.subscribers = new Set();
8
+ this.sweepTimer = setInterval(() => this.sweepStaleConnections(), STALE_SWEEP_INTERVAL_MS);
9
+ this.sweepTimer.unref?.();
10
+ }
11
+ shutdown() {
12
+ clearInterval(this.sweepTimer);
13
+ for (const connection of Array.from(this.connections.values())) {
14
+ this.disconnect(connection.key, "shutdown", false);
15
+ }
16
+ }
17
+ subscribe(listener) {
18
+ this.subscribers.add(listener);
19
+ return () => this.subscribers.delete(listener);
20
+ }
21
+ register(input) {
22
+ const key = getConnectionKey(input);
23
+ const now = Date.now();
24
+ const existing = this.connections.get(key);
25
+ if (existing) {
26
+ this.logger.debug({ clientId: input.clientId, connectionId: input.connectionId }, "Replacing existing client connection");
27
+ this.disconnect(key, "replaced");
28
+ }
29
+ const connection = {
30
+ key,
31
+ clientId: input.clientId,
32
+ connectionId: input.connectionId,
33
+ connectedAt: now,
34
+ lastSeenAt: now,
35
+ close: input.close,
36
+ };
37
+ this.connections.set(key, connection);
38
+ this.logger.debug({ clientId: input.clientId, connectionId: input.connectionId }, "Client connected");
39
+ this.notify({ type: "connected", connection });
40
+ return () => this.disconnect(key, "closed");
41
+ }
42
+ pong(input) {
43
+ const key = getConnectionKey(input);
44
+ const connection = this.connections.get(key);
45
+ if (!connection) {
46
+ this.logger.debug({ clientId: input.clientId, connectionId: input.connectionId }, "Ignoring pong for unknown client connection");
47
+ return false;
48
+ }
49
+ connection.lastSeenAt = Date.now();
50
+ return true;
51
+ }
52
+ isConnected(input) {
53
+ return this.connections.has(getConnectionKey(input));
54
+ }
55
+ sweepStaleConnections() {
56
+ const cutoff = Date.now() - STALE_CONNECTION_TIMEOUT_MS;
57
+ for (const connection of Array.from(this.connections.values())) {
58
+ if (connection.lastSeenAt > cutoff)
59
+ continue;
60
+ this.logger.debug({ clientId: connection.clientId, connectionId: connection.connectionId }, "Client connection timed out");
61
+ this.disconnect(connection.key, "timeout");
62
+ }
63
+ }
64
+ disconnect(key, reason, invokeClose = true) {
65
+ const connection = this.connections.get(key);
66
+ if (!connection)
67
+ return;
68
+ this.connections.delete(key);
69
+ this.logger.debug({ clientId: connection.clientId, connectionId: connection.connectionId, reason }, "Client disconnected");
70
+ if (invokeClose) {
71
+ try {
72
+ connection.close();
73
+ }
74
+ catch (error) {
75
+ this.logger.warn({ err: error, clientId: connection.clientId, connectionId: connection.connectionId }, "Failed to close stale client connection");
76
+ }
77
+ }
78
+ this.notify({ type: "disconnected", connection, reason });
79
+ }
80
+ notify(event) {
81
+ for (const subscriber of this.subscribers) {
82
+ try {
83
+ subscriber(event);
84
+ }
85
+ catch (error) {
86
+ this.logger.warn({ err: error, eventType: event.type }, "Client connection subscriber failed");
87
+ }
88
+ }
89
+ }
90
+ }
91
+ function getConnectionKey(input) {
92
+ return `${input.clientId}:${input.connectionId}`;
93
+ }
@@ -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);
@@ -50,6 +50,13 @@ export class FileSystemBrowser {
50
50
  fs.mkdirSync(absolutePath);
51
51
  return { path: relativePath, absolutePath };
52
52
  }
53
+ writeFile(relativePath, contents) {
54
+ if (this.unrestricted) {
55
+ throw new Error("writeFile is not available in unrestricted mode");
56
+ }
57
+ const resolved = this.toRestrictedAbsolute(relativePath);
58
+ fs.writeFileSync(resolved, contents, "utf-8");
59
+ }
53
60
  readFile(relativePath) {
54
61
  if (this.unrestricted) {
55
62
  throw new Error("readFile is not available in unrestricted mode");
package/dist/index.js CHANGED
@@ -20,9 +20,13 @@ 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 { resolveNetworkAddresses, resolveRemoteAddresses } from "./server/network-addresses";
24
24
  import { startDevReleaseMonitor } from "./releases/dev-release-monitor";
25
25
  import { SpeechService } from "./speech/service";
26
+ import { SideCarManager } from "./sidecars/manager";
27
+ import { ClientConnectionManager } from "./clients/connection-manager";
28
+ import { PluginChannelManager } from "./plugins/channel";
29
+ import { VoiceModeManager } from "./plugins/voice-mode";
26
30
  const require = createRequire(import.meta.url);
27
31
  const packageJson = require("../package.json");
28
32
  const __filename = fileURLToPath(import.meta.url);
@@ -208,6 +212,11 @@ async function main() {
208
212
  const fileSystemBrowser = new FileSystemBrowser({ rootDir: options.rootDir, unrestricted: options.unrestrictedRoot });
209
213
  const instanceStore = new InstanceStore(configLocation.instancesDir);
210
214
  const speechService = new SpeechService(settings, logger.child({ component: "speech" }));
215
+ const sidecarManager = new SideCarManager({
216
+ settings,
217
+ eventBus,
218
+ logger: logger.child({ component: "sidecars" }),
219
+ });
211
220
  const instanceEventBridge = new InstanceEventBridge({
212
221
  workspaceManager,
213
222
  eventBus,
@@ -257,6 +266,13 @@ async function main() {
257
266
  throw new InvalidArgumentError("UI dev proxy is only supported with --https=false --http=true");
258
267
  }
259
268
  const remoteAccessEnabled = options.host === "0.0.0.0" || !isLoopbackHost(options.host);
269
+ const clientConnectionManager = new ClientConnectionManager(logger.child({ component: "client-connections" }));
270
+ const pluginChannel = new PluginChannelManager(logger.child({ component: "plugin-channel" }));
271
+ const voiceModeManager = new VoiceModeManager({
272
+ connections: clientConnectionManager,
273
+ channel: pluginChannel,
274
+ logger: logger.child({ component: "voice-mode" }),
275
+ });
260
276
  const httpsPortExplicit = programHasArg(process.argv.slice(2), "--https-port") || Boolean(process.env.CLI_HTTPS_PORT);
261
277
  const httpPortExplicit = programHasArg(process.argv.slice(2), "--http-port") || Boolean(process.env.CLI_HTTP_PORT);
262
278
  const httpsBindPort = httpsPortExplicit ? options.httpsPort : 0;
@@ -281,7 +297,11 @@ async function main() {
281
297
  serverMeta,
282
298
  instanceStore,
283
299
  speechService,
300
+ sidecarManager,
284
301
  authManager,
302
+ clientConnectionManager,
303
+ pluginChannel,
304
+ voiceModeManager,
285
305
  uiStaticDir: uiResolution.uiStaticDir ?? DEFAULT_UI_STATIC_DIR,
286
306
  uiDevServerUrl: uiResolution.uiDevServerUrl,
287
307
  logger,
@@ -301,7 +321,11 @@ async function main() {
301
321
  serverMeta,
302
322
  instanceStore,
303
323
  speechService,
324
+ sidecarManager,
304
325
  authManager,
326
+ clientConnectionManager,
327
+ pluginChannel,
328
+ voiceModeManager,
305
329
  uiStaticDir: uiResolution.uiStaticDir ?? DEFAULT_UI_STATIC_DIR,
306
330
  uiDevServerUrl: undefined,
307
331
  logger,
@@ -328,19 +352,23 @@ async function main() {
328
352
  // which can lead clients to talk to the wrong process.
329
353
  const localUrl = `${localProtocol}://127.0.0.1:${localStart.port}`;
330
354
  let remoteUrl;
355
+ let remoteAddresses = [];
331
356
  if (remoteStart) {
332
357
  const wantsAll = options.host === "0.0.0.0" || !isLoopbackHost(options.host);
333
358
  let remoteHost = options.host;
334
359
  if (wantsAll) {
335
360
  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";
361
+ const resolved = resolveRemoteAddresses({ host: options.host, protocol: remoteProtocol, port: remoteStart.port });
362
+ remoteAddresses = resolved.userVisible;
363
+ remoteUrl = resolved.primaryRemoteUrl ?? `${remoteProtocol}://localhost:${remoteStart.port}`;
338
364
  }
339
365
  }
340
366
  else {
341
367
  remoteHost = "localhost";
342
368
  }
343
- remoteUrl = `${remoteProtocol}://${remoteHost}:${remoteStart.port}`;
369
+ if (!remoteUrl) {
370
+ remoteUrl = `${remoteProtocol}://${remoteHost}:${remoteStart.port}`;
371
+ }
344
372
  }
345
373
  serverMeta.localUrl = localUrl;
346
374
  serverMeta.localPort = localStart.port;
@@ -349,7 +377,9 @@ async function main() {
349
377
  serverMeta.host = options.host;
350
378
  serverMeta.listeningMode = options.host === "0.0.0.0" || !isLoopbackHost(options.host) ? "all" : "local";
351
379
  if (serverMeta.remotePort && remoteUrl) {
352
- serverMeta.addresses = resolveNetworkAddresses({ host: options.host, protocol: remoteProtocol, port: serverMeta.remotePort });
380
+ serverMeta.addresses = remoteAddresses.length
381
+ ? remoteAddresses
382
+ : resolveNetworkAddresses({ host: options.host, protocol: remoteProtocol, port: serverMeta.remotePort });
353
383
  }
354
384
  else {
355
385
  serverMeta.addresses = [];
@@ -357,6 +387,15 @@ async function main() {
357
387
  console.log(`Local Connection URL : ${serverMeta.localUrl}`);
358
388
  if (serverMeta.remoteUrl) {
359
389
  console.log(`Remote Connection URL : ${serverMeta.remoteUrl}`);
390
+ const additionalRemoteUrls = serverMeta.addresses
391
+ .map((addr) => addr.remoteUrl)
392
+ .filter((url) => url !== serverMeta.remoteUrl);
393
+ if (additionalRemoteUrls.length > 0) {
394
+ console.log("Other Accessible URLs:");
395
+ for (const url of additionalRemoteUrls) {
396
+ console.log(` - ${url}`);
397
+ }
398
+ }
360
399
  }
361
400
  if (options.launch) {
362
401
  await launchInBrowser(serverMeta.localUrl, logger.child({ component: "launcher" }));
@@ -376,6 +415,18 @@ async function main() {
376
415
  catch (error) {
377
416
  logger.warn({ err: error }, "Instance event bridge shutdown failed");
378
417
  }
418
+ try {
419
+ await sidecarManager.shutdown();
420
+ }
421
+ catch (error) {
422
+ logger.error({ err: error }, "SideCar manager shutdown failed");
423
+ }
424
+ try {
425
+ clientConnectionManager.shutdown();
426
+ }
427
+ catch (error) {
428
+ logger.warn({ err: error }, "Client connection manager shutdown failed");
429
+ }
379
430
  try {
380
431
  await workspaceManager.shutdown();
381
432
  logger.info("Workspace manager shutdown complete");
@@ -4,6 +4,6 @@
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "dependencies": {
7
- "@opencode-ai/plugin": "1.3.2"
7
+ "@opencode-ai/plugin": "1.3.7"
8
8
  }
9
9
  }
@@ -2,6 +2,8 @@ import type { PluginInput } from "@opencode-ai/plugin"
2
2
  import { createCodeNomadClient, getCodeNomadConfig } from "./lib/client"
3
3
  import { createBackgroundProcessTools } from "./lib/background-process"
4
4
 
5
+ let voiceModeEnabled = false
6
+
5
7
  export async function CodeNomadPlugin(input: PluginInput) {
6
8
  const config = getCodeNomadConfig()
7
9
  const client = createCodeNomadClient(config)
@@ -16,6 +18,11 @@ export async function CodeNomadPlugin(input: PluginInput) {
16
18
  pingTs: (event.properties as any)?.ts,
17
19
  },
18
20
  }).catch(() => {})
21
+ return
22
+ }
23
+
24
+ if (event.type === "codenomad.voiceMode") {
25
+ voiceModeEnabled = Boolean((event.properties as { enabled?: unknown } | undefined)?.enabled)
19
26
  }
20
27
  })
21
28
 
@@ -23,6 +30,13 @@ export async function CodeNomadPlugin(input: PluginInput) {
23
30
  tool: {
24
31
  ...backgroundProcessTools,
25
32
  },
33
+ async "chat.message"(_input: { sessionID: string }, output: { message: { system?: string } }) {
34
+ if (!voiceModeEnabled) {
35
+ return
36
+ }
37
+
38
+ output.message.system = [output.message.system, buildVoiceModePrompt()].filter(Boolean).join("\n\n")
39
+ },
26
40
  async event(input: { event: any }) {
27
41
  const opencodeEvent = input?.event
28
42
  if (!opencodeEvent || typeof opencodeEvent !== "object") return
@@ -30,3 +44,19 @@ export async function CodeNomadPlugin(input: PluginInput) {
30
44
  },
31
45
  }
32
46
  }
47
+
48
+ function buildVoiceModePrompt(): string {
49
+ return [
50
+ "Voice conversation mode is enabled.",
51
+ "Prepend your reply with a fenced code block using language `spoken`.",
52
+ "The `spoken` block should be the natural conversational reply you would say out loud to the user. It should be a concise spoken gist of the full response in 2 to 4 natural sentences.",
53
+ "In the spoken block, summarize the main outcome, recommendation, or next step. Sound conversational and natural, not like a document summary.",
54
+ "Do not include code, bullet lists, markdown formatting, or long technical detail in the spoken block.",
55
+ "Do not add generic phrases about whether the user should read more.",
56
+ "Only mention additional written detail when there is something specific that may matter for the user's next response, such as a tradeoff, caveat, risk, open question, exact diff, or test result.",
57
+ "When referring to that written detail, say `below` or `in the message` rather than `detailed section`.",
58
+ "After the `spoken` block, continue with your normal detailed response.",
59
+ "Example:",
60
+ "```spoken\nI implemented the relay-based voice-mode flow and it works with the current plugin bridge. The reconnect caveat is explained below.\n```",
61
+ ].join("\n\n")
62
+ }
@@ -13,6 +13,11 @@ type BackgroundProcess = {
13
13
  outputSizeBytes?: number
14
14
  }
15
15
 
16
+ type BackgroundProcessNotificationRequest = {
17
+ sessionID: string
18
+ directory: string
19
+ }
20
+
16
21
  type BackgroundProcessOptions = {
17
22
  baseDir: string
18
23
  }
@@ -36,12 +41,19 @@ export function createBackgroundProcessTools(config: CodeNomadConfig, options: B
36
41
  args: {
37
42
  title: tool.schema.string().describe("Short label for the process (e.g. Dev server, DB server)"),
38
43
  command: tool.schema.string().describe("Shell command to run in the workspace"),
44
+ notify: tool.schema.boolean().optional().describe("Notify the current session when the process ends"),
39
45
  },
40
- async execute(args) {
46
+ async execute(args, context) {
41
47
  assertCommandWithinBase(args.command, options.baseDir)
48
+ const notification: BackgroundProcessNotificationRequest | undefined = args.notify
49
+ ? {
50
+ sessionID: context.sessionID,
51
+ directory: context.directory,
52
+ }
53
+ : undefined
42
54
  const process = await request<BackgroundProcess>("", {
43
55
  method: "POST",
44
- body: JSON.stringify({ title: args.title, command: args.command }),
56
+ body: JSON.stringify({ title: args.title, command: args.command, notify: args.notify, notification }),
45
57
  })
46
58
 
47
59
  return `Started background process ${process.id} (${process.title})\nStatus: ${process.status}\nCommand: ${process.command}`