@openchamber/web 1.14.1 → 1.16.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 (124) hide show
  1. package/bin/cli.test.js +8 -0
  2. package/bin/lib/DOCUMENTATION.md +3 -0
  3. package/bin/lib/cli-args.js +10 -0
  4. package/bin/lib/commands-connect-url.js +169 -22
  5. package/dist/assets/{DiagramView-Cb58svCq.js → DiagramView-he_RFVx5.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-CdBIHSPZ.js +11 -0
  7. package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-B_C-tvVq.js} +1 -1
  8. package/dist/assets/OnboardingScreen-BBnTt-9w.js +1 -0
  9. package/dist/assets/SessionSwitcherDropdown-CWWrCFzr.js +1 -0
  10. package/dist/assets/SettingsWindow-CjqLdpTE.js +1 -0
  11. package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-DQcdegHp.js} +1 -1
  12. package/dist/assets/es-r0_jT91q.js +15 -0
  13. package/dist/assets/fr-Bo8rtAJ1.js +13 -0
  14. package/dist/assets/index-8J6waVO6.js +2 -0
  15. package/dist/assets/index-DEMqM4Lz.css +1 -0
  16. package/dist/assets/ja-BPWtkG-c.js +15 -0
  17. package/dist/assets/ko-Bv0k-0E3.js +15 -0
  18. package/dist/assets/main-B-GA5Tg5.js +237 -0
  19. package/dist/assets/main-Dfm-VKZ9.js +2 -0
  20. package/dist/assets/miniChat-CfmCFFfu.js +2 -0
  21. package/dist/assets/mobile-CXJqeDlm.js +2 -0
  22. package/dist/assets/pl-CiTP50bz.js +15 -0
  23. package/dist/assets/pt-BR-DadIjX5L.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-DS7Dy2ii.js +2 -0
  25. package/dist/assets/renderMobileApp-o7Fs9EBx.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-MTaPPm4F.js +167 -0
  27. package/dist/assets/uk-2RpsWGoZ.js +15 -0
  28. package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DkPuAMXD.js} +196 -133
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-BwKWaTuz.js +15 -0
  31. package/dist/assets/zh-TW--f_BqBpD.js +15 -0
  32. package/dist/index.html +4 -4
  33. package/dist/mini-chat.html +4 -4
  34. package/dist/mobile.html +4 -4
  35. package/package.json +2 -2
  36. package/server/index.js +236 -2
  37. package/server/lib/client-auth/pairing.js +308 -0
  38. package/server/lib/client-auth/pairing.test.js +142 -0
  39. package/server/lib/client-auth/remote-clients.js +65 -3
  40. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  41. package/server/lib/notifications/apns-runtime.js +11 -16
  42. package/server/lib/notifications/runtime.js +135 -33
  43. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  44. package/server/lib/opencode/agents.js +3 -0
  45. package/server/lib/opencode/bootstrap-runtime.js +15 -0
  46. package/server/lib/opencode/core-routes.js +321 -8
  47. package/server/lib/opencode/core-routes.test.js +329 -9
  48. package/server/lib/opencode/feature-routes-runtime.js +6 -0
  49. package/server/lib/opencode/network-runtime.js +14 -1
  50. package/server/lib/opencode/network-runtime.test.js +29 -9
  51. package/server/lib/opencode/proxy.js +47 -6
  52. package/server/lib/opencode/settings-helpers.js +24 -0
  53. package/server/lib/opencode/settings-helpers.test.js +25 -0
  54. package/server/lib/opencode/settings-normalization-runtime.js +21 -4
  55. package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
  56. package/server/lib/opencode/settings-runtime.js +25 -0
  57. package/server/lib/opencode/shutdown-runtime.js +2 -0
  58. package/server/lib/opencode/tunnel-auth.js +4 -9
  59. package/server/lib/package-manager.js +18 -5
  60. package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
  61. package/server/lib/permission-auto-accept/runtime.js +263 -0
  62. package/server/lib/permission-auto-accept/runtime.test.js +137 -0
  63. package/server/lib/projects/project-config.js +8 -0
  64. package/server/lib/quota/DOCUMENTATION.md +5 -2
  65. package/server/lib/quota/credentials/providers.js +43 -0
  66. package/server/lib/quota/credentials/store.js +48 -0
  67. package/server/lib/quota/credentials/store.test.js +26 -0
  68. package/server/lib/quota/opencode-go-credentials.js +11 -0
  69. package/server/lib/quota/opencode-go-credentials.test.js +32 -0
  70. package/server/lib/quota/providers/codex.js +7 -4
  71. package/server/lib/quota/providers/codex.test.js +48 -0
  72. package/server/lib/quota/providers/cursor.js +28 -39
  73. package/server/lib/quota/providers/index.js +7 -0
  74. package/server/lib/quota/providers/ollama-cloud.js +23 -42
  75. package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
  76. package/server/lib/quota/providers/opencode-go.js +70 -0
  77. package/server/lib/quota/providers/opencode-go.test.js +17 -0
  78. package/server/lib/quota/routes.js +78 -7
  79. package/server/lib/quota/routes.test.js +40 -0
  80. package/server/lib/relay/DOCUMENTATION.md +98 -0
  81. package/server/lib/relay/cross-compat.test.js +135 -0
  82. package/server/lib/relay/e2ee.js +341 -0
  83. package/server/lib/relay/e2ee.test.js +124 -0
  84. package/server/lib/relay/host-client.js +389 -0
  85. package/server/lib/relay/host-client.test.js +280 -0
  86. package/server/lib/relay/host-lock.js +101 -0
  87. package/server/lib/relay/host-lock.test.js +129 -0
  88. package/server/lib/relay/identity.js +93 -0
  89. package/server/lib/relay/identity.test.js +78 -0
  90. package/server/lib/relay/service.js +334 -0
  91. package/server/lib/relay/signing-key.js +73 -0
  92. package/server/lib/relay/tunnel-codec.js +373 -0
  93. package/server/lib/relay/tunnel-codec.test.js +58 -0
  94. package/server/lib/relay/tunnel-host.js +462 -0
  95. package/server/lib/scheduled-tasks/runtime.js +104 -0
  96. package/server/lib/session-goal/DOCUMENTATION.md +176 -0
  97. package/server/lib/session-goal/objectives.js +61 -0
  98. package/server/lib/session-goal/routes.js +36 -0
  99. package/server/lib/session-goal/runtime.js +764 -0
  100. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  101. package/server/lib/ui-auth/ui-auth.js +10 -0
  102. package/server/opencode-proxy.test.js +38 -0
  103. package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
  104. package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
  105. package/dist/assets/SessionSwitcherDropdown-4FWg9xMC.js +0 -1
  106. package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
  107. package/dist/assets/es-bWcuDy_2.js +0 -15
  108. package/dist/assets/fr-DzRs3OzV.js +0 -13
  109. package/dist/assets/index-KnWk9fmM.css +0 -1
  110. package/dist/assets/index-ZJTzZ0_U.js +0 -2
  111. package/dist/assets/ja-BqUX_UD3.js +0 -15
  112. package/dist/assets/ko-BQo10SNx.js +0 -15
  113. package/dist/assets/main-BDoqLlQB.js +0 -236
  114. package/dist/assets/main-DUGyTrDt.js +0 -2
  115. package/dist/assets/miniChat-DNDiX8GA.js +0 -2
  116. package/dist/assets/mobile-DnghtOCb.js +0 -2
  117. package/dist/assets/pl-Bgx_ATJT.js +0 -15
  118. package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
  119. package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
  120. package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
  121. package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
  122. package/dist/assets/uk-C9k8SP8q.js +0 -15
  123. package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
  124. package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
package/dist/index.html CHANGED
@@ -515,11 +515,11 @@
515
515
  pointer-events: none;
516
516
  }
517
517
  </style>
518
- <script type="module" crossorigin src="/assets/main-DUGyTrDt.js"></script>
519
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
520
- <link rel="modulepreload" crossorigin href="/assets/index-ZJTzZ0_U.js">
518
+ <script type="module" crossorigin src="/assets/main-Dfm-VKZ9.js"></script>
519
+ <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-BE757pvp.js">
520
+ <link rel="modulepreload" crossorigin href="/assets/index-8J6waVO6.js">
521
521
  <link rel="modulepreload" crossorigin href="/assets/mobileLayoutPreference-Dio-WWkI.js">
522
- <link rel="stylesheet" crossorigin href="/assets/index-KnWk9fmM.css">
522
+ <link rel="stylesheet" crossorigin href="/assets/index-DEMqM4Lz.css">
523
523
  </head>
524
524
  <body class="h-full bg-background text-foreground">
525
525
  <div id="root" class="h-full">
@@ -74,10 +74,10 @@
74
74
  }
75
75
  </style>
76
76
 
77
- <script type="module" crossorigin src="/assets/miniChat-DNDiX8GA.js"></script>
78
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
79
- <link rel="modulepreload" crossorigin href="/assets/index-ZJTzZ0_U.js">
80
- <link rel="stylesheet" crossorigin href="/assets/index-KnWk9fmM.css">
77
+ <script type="module" crossorigin src="/assets/miniChat-CfmCFFfu.js"></script>
78
+ <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-BE757pvp.js">
79
+ <link rel="modulepreload" crossorigin href="/assets/index-8J6waVO6.js">
80
+ <link rel="stylesheet" crossorigin href="/assets/index-DEMqM4Lz.css">
81
81
  </head>
82
82
  <body class="h-full bg-background text-foreground">
83
83
  <div id="root" class="h-full">
package/dist/mobile.html CHANGED
@@ -63,10 +63,10 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-DnghtOCb.js"></script>
67
- <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-C6iL44L9.js">
68
- <link rel="modulepreload" crossorigin href="/assets/index-ZJTzZ0_U.js">
69
- <link rel="stylesheet" crossorigin href="/assets/index-KnWk9fmM.css">
66
+ <script type="module" crossorigin src="/assets/mobile-CXJqeDlm.js"></script>
67
+ <link rel="modulepreload" crossorigin href="/assets/vendor-.bun-BE757pvp.js">
68
+ <link rel="modulepreload" crossorigin href="/assets/index-8J6waVO6.js">
69
+ <link rel="stylesheet" crossorigin href="/assets/index-DEMqM4Lz.css">
70
70
  </head>
71
71
  <body class="h-full bg-background text-foreground">
72
72
  <div id="root" class="h-full"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openchamber/web",
3
- "version": "1.14.1",
3
+ "version": "1.16.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./server/index.js",
@@ -25,7 +25,7 @@
25
25
  "dependencies": {
26
26
  "@clack/prompts": "^1.1.0",
27
27
  "@octokit/rest": "^22.0.1",
28
- "@opencode-ai/sdk": "1.17.12",
28
+ "@opencode-ai/sdk": "1.17.18",
29
29
  "@simplewebauthn/server": "13.3.1",
30
30
  "adm-zip": "^0.5.16",
31
31
  "better-sqlite3": "^12.10.0",
package/server/index.js CHANGED
@@ -73,6 +73,7 @@ import { createBootstrapRuntime } from './lib/opencode/bootstrap-runtime.js';
73
73
  import { createSessionRuntime } from './lib/opencode/session-runtime.js';
74
74
  import { createOpenCodeWatcherRuntime } from './lib/opencode/watcher.js';
75
75
  import { createSessionAssistRuntime } from './lib/session-assist/runtime.js';
76
+ import { createSessionGoalRuntime } from './lib/session-goal/runtime.js';
76
77
  import { createScheduledTasksRuntime } from './lib/scheduled-tasks/runtime.js';
77
78
  import { createServerStartupRuntime } from './lib/opencode/server-startup-runtime.js';
78
79
  import { createTunnelWiringRuntime } from './lib/opencode/tunnel-wiring-runtime.js';
@@ -84,11 +85,15 @@ import { createNotificationTriggerRuntime } from './lib/notifications/runtime.js
84
85
  import { createPushRuntime } from './lib/notifications/push-runtime.js';
85
86
  import { createApnsRuntime } from './lib/notifications/apns-runtime.js';
86
87
  import { createNotificationTemplateRuntime } from './lib/notifications/template-runtime.js';
88
+ import { createPermissionAutoAcceptRuntime } from './lib/permission-auto-accept/runtime.js';
87
89
  import { createGracefulShutdownRuntime } from './lib/opencode/shutdown-runtime.js';
88
90
  import { createProjectConfigRuntime } from './lib/projects/project-config.js';
89
91
  import { createRemoteClientAuthRuntime } from './lib/client-auth/remote-clients.js';
92
+ import { createClientPairingRuntime } from './lib/client-auth/pairing.js';
90
93
  import { createPreviewProxyRuntime } from './lib/preview/proxy-runtime.js';
91
94
  import { attachRealtimeProxy } from './lib/realtime-proxy.js';
95
+ import { createRelayService } from './lib/relay/service.js';
96
+ import { createRelayHostLock } from './lib/relay/host-lock.js';
92
97
  import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
93
98
  import webPush from 'web-push';
94
99
 
@@ -281,6 +286,7 @@ const SETTINGS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'settings.json');
281
286
  const PUSH_SUBSCRIPTIONS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'push-subscriptions.json');
282
287
  const APNS_TOKENS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'apns-tokens.json');
283
288
  const REMOTE_CLIENTS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'remote-clients.json');
289
+ const CLIENT_PAIRING_SESSIONS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'client-pairing-sessions.json');
284
290
  const CLOUDFLARE_MANAGED_REMOTE_TUNNELS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'cloudflare-managed-remote-tunnels.json');
285
291
  const CLOUDFLARE_LEGACY_NAMED_TUNNELS_FILE_PATH = path.join(OPENCHAMBER_DATA_DIR, 'cloudflare-named-tunnels.json');
286
292
  const CLOUDFLARE_MANAGED_REMOTE_TUNNELS_VERSION = 1;
@@ -360,6 +366,7 @@ const settingsRuntime = createSettingsRuntime({
360
366
 
361
367
  const readSettingsFromDiskMigrated = (...args) => settingsRuntime.readSettingsFromDiskMigrated(...args);
362
368
  const readSettingsFromDisk = (...args) => settingsRuntime.readSettingsFromDisk(...args);
369
+ const readSettingsFromDiskStrict = (...args) => settingsRuntime.readSettingsFromDiskStrict(...args);
363
370
  const writeSettingsToDisk = (...args) => settingsRuntime.writeSettingsToDisk(...args);
364
371
  const persistSettings = (...args) => settingsRuntime.persistSettings(...args);
365
372
 
@@ -404,6 +411,7 @@ const apnsRuntime = createApnsRuntime({
404
411
  APNS_TOKENS_FILE_PATH,
405
412
  readSettingsFromDiskMigrated,
406
413
  writeSettingsToDisk,
414
+ readSettingsStrict: readSettingsFromDiskStrict,
407
415
  });
408
416
 
409
417
  const addOrUpdateApnsToken = (...args) => apnsRuntime.addOrUpdateApnsToken(...args);
@@ -602,6 +610,7 @@ Object.defineProperties(openCodeNetworkState, {
602
610
  const openCodeNetworkRuntime = createOpenCodeNetworkRuntime({
603
611
  state: openCodeNetworkState,
604
612
  getOpenCodeAuthHeaders,
613
+ configuredOpenCodeHostname: ENV_CONFIGURED_OPENCODE_HOSTNAME,
605
614
  });
606
615
 
607
616
  const waitForReady = (...args) => openCodeNetworkRuntime.waitForReady(...args);
@@ -711,7 +720,7 @@ const notificationTriggerRuntime = createNotificationTriggerRuntime({
711
720
  });
712
721
 
713
722
  const maybeSendPushForTrigger = (...args) => notificationTriggerRuntime.maybeSendPushForTrigger(...args);
714
- const setAutoAcceptSession = (...args) => notificationTriggerRuntime.setAutoAcceptSession(...args);
723
+ const setAutoAcceptSession = (sessionId, enabled) => permissionAutoAcceptRuntime.setSessionPolicy(sessionId, enabled);
715
724
  clearPendingPushBadge = () => notificationTriggerRuntime.clearPendingPushBadge();
716
725
 
717
726
  const sessionAssistRuntime = createSessionAssistRuntime({
@@ -720,12 +729,65 @@ const sessionAssistRuntime = createSessionAssistRuntime({
720
729
  getSmallModelService: async () => import('./lib/small-model/index.js'),
721
730
  });
722
731
 
732
+ const sessionGoalRuntime = createSessionGoalRuntime({
733
+ buildOpenCodeUrl,
734
+ getOpenCodeAuthHeaders,
735
+ getSmallModelService: async () => import('./lib/small-model/index.js'),
736
+ emitGoalNotification: async ({ sessionId, directory, status, goal }) => {
737
+ // The goal settle notification replaces the per-turn ready notifications
738
+ // (suppressed while the goal is active) — so it obeys the same toggle.
739
+ const settings = await readSettingsFromDisk();
740
+ if (settings.notifyOnCompletion === false) {
741
+ return;
742
+ }
743
+ const title = status === 'complete'
744
+ ? 'Goal complete'
745
+ : (status === 'budgetLimited' ? 'Goal reached its token budget' : 'Goal blocked');
746
+ const detail = goal?.statusReason && goal.statusReason !== 'verified by audit' && goal.statusReason !== 'reported by agent'
747
+ ? goal.statusReason
748
+ : (goal?.note || '');
749
+ const objective = typeof goal?.objective === 'string' ? goal.objective.slice(0, 140) : '';
750
+ const notificationPayload = {
751
+ title,
752
+ body: [objective, detail].filter(Boolean).join(' — ').slice(0, 240),
753
+ tag: `goal-${sessionId}`,
754
+ kind: 'goal',
755
+ sessionId,
756
+ directory,
757
+ };
758
+ const desktopNotificationDelivered = emitDesktopNotification(notificationPayload);
759
+ broadcastUiNotification(notificationPayload, { desktopNotificationDelivered });
760
+ void notificationTriggerRuntime.sendGoalSettlePush({
761
+ sessionId,
762
+ directory,
763
+ status,
764
+ title,
765
+ body: notificationPayload.body,
766
+ }).catch((error) => {
767
+ console.warn('[session-goal] push fanout failed:', error?.message || error);
768
+ });
769
+ },
770
+ });
771
+
723
772
  const globalMessageStreamHub = createGlobalMessageStreamHub({
724
773
  buildOpenCodeUrl,
725
774
  getOpenCodeAuthHeaders,
726
775
  upstreamStallTimeoutMs: getUpstreamStallTimeoutMs,
727
776
  });
728
777
 
778
+ const permissionAutoAcceptRuntime = createPermissionAutoAcceptRuntime({
779
+ globalEventHub: globalMessageStreamHub,
780
+ buildOpenCodeUrl,
781
+ getOpenCodeAuthHeaders,
782
+ readSettingsFromDiskMigrated,
783
+ persistSettings,
784
+ broadcastGlobalUiEvent,
785
+ });
786
+ permissionAutoAcceptRuntime.start();
787
+ notificationTriggerRuntime.setGetIsSessionAutoAccepting(
788
+ (sessionId, directory) => permissionAutoAcceptRuntime.isSessionAutoAccepting(sessionId, directory),
789
+ );
790
+
729
791
  const openCodeWatcherRuntime = createOpenCodeWatcherRuntime({
730
792
  waitForOpenCodePort: (...args) => waitForOpenCodePort(...args),
731
793
  buildOpenCodeUrl,
@@ -750,6 +812,7 @@ globalMessageStreamHub.subscribeEvent((event) => {
750
812
  ? event.directory
751
813
  : '';
752
814
  sessionAssistRuntime.processPayload(payload, directory);
815
+ sessionGoalRuntime.processPayload(payload, directory);
753
816
  });
754
817
 
755
818
  const processForwardedEventPayload = (payload, emitSyntheticEvent) => {
@@ -871,6 +934,13 @@ const remoteClientAuthRuntime = createRemoteClientAuthRuntime({
871
934
  crypto,
872
935
  storePath: REMOTE_CLIENTS_FILE_PATH,
873
936
  });
937
+ const clientPairingRuntime = createClientPairingRuntime({
938
+ fsPromises,
939
+ path,
940
+ crypto,
941
+ storePath: CLIENT_PAIRING_SESSIONS_FILE_PATH,
942
+ remoteClientAuthRuntime,
943
+ });
874
944
  const featureRoutesRuntime = createFeatureRoutesRuntime({
875
945
  clientReloadDelayMs: CLIENT_RELOAD_DELAY_MS,
876
946
  });
@@ -1059,6 +1129,7 @@ const gracefulShutdownRuntime = createGracefulShutdownRuntime({
1059
1129
  syncToHmrState,
1060
1130
  openCodeWatcherRuntime,
1061
1131
  sessionAssistRuntime,
1132
+ sessionGoalRuntime,
1062
1133
  sessionRuntime,
1063
1134
  getHealthCheckInterval: () => healthCheckInterval,
1064
1135
  clearHealthCheckInterval: (value) => clearInterval(value),
@@ -1100,6 +1171,83 @@ async function main(options = {}) {
1100
1171
  || (typeof process.env.OPENCHAMBER_HOST === 'string' && process.env.OPENCHAMBER_HOST.trim().length > 0
1101
1172
  ? process.env.OPENCHAMBER_HOST.trim()
1102
1173
  : '127.0.0.1');
1174
+
1175
+ // Pairing transports advertised to the create-device dialog. LAN reachability is
1176
+ // derived from the SERVER's actual bind (a wildcard bind → the machine's LAN IP;
1177
+ // a specific non-loopback host → that host), NOT from how the UI was opened — so
1178
+ // "Local network" works even when the UI is opened on localhost, and is absent
1179
+ // when the server is only bound to loopback (a LAN link would not connect).
1180
+ // The IPv4 the requesting client actually reached this server on (if any).
1181
+ // Strips the IPv6-mapped prefix; loopback means "not a LAN path".
1182
+ const requestReachedLanAddress = (req) => {
1183
+ const raw = typeof req?.socket?.localAddress === 'string' ? req.socket.localAddress : '';
1184
+ const address = raw.startsWith('::ffff:') ? raw.slice(7) : raw;
1185
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(address)) return null;
1186
+ if (address.startsWith('127.')) return null;
1187
+ return address;
1188
+ };
1189
+ const resolvePairingTransports = (req) => {
1190
+ const activePort = tunnelRuntimeContext.getActivePort() || port;
1191
+ const local = `http://127.0.0.1:${activePort}`;
1192
+ let lanHost = null;
1193
+ if (isNetworkExposedBindHost(effectiveBindHost)) {
1194
+ // Prefer the address the client is ALREADY talking to us on — it is the
1195
+ // one interface guaranteed to be routable from that client's network.
1196
+ // Interface scanning is only a fallback: on servers with virtual bridges
1197
+ // (docker0 etc.) the first non-internal IPv4 can be an address no other
1198
+ // machine can reach, which produced pairing links whose LAN candidate
1199
+ // silently failed and forced devices onto the relay.
1200
+ lanHost = requestReachedLanAddress(req);
1201
+ try {
1202
+ if (!lanHost) {
1203
+ for (const list of Object.values(os.networkInterfaces())) {
1204
+ for (const entry of (list || [])) {
1205
+ if (entry.family === 'IPv4' && !entry.internal) { lanHost = entry.address; break; }
1206
+ }
1207
+ if (lanHost) break;
1208
+ }
1209
+ }
1210
+ } catch {
1211
+ lanHost = null;
1212
+ }
1213
+ } else {
1214
+ const h = String(effectiveBindHost || '').toLowerCase();
1215
+ if (h && h !== '127.0.0.1' && h !== 'localhost' && h !== '::1') lanHost = effectiveBindHost;
1216
+ }
1217
+ const lan = lanHost ? `http://${lanHost.includes(':') ? `[${lanHost}]` : lanHost}:${activePort}` : null;
1218
+ return { local, lan, relayAvailable: true };
1219
+ };
1220
+ // ALL direct LAN URLs this server is currently reachable on, for the
1221
+ // candidates-refresh endpoint: the address the requesting client already
1222
+ // reached us on first (guaranteed routable from its network — over the relay
1223
+ // tunnel this is loopback and yields nothing), then every non-internal IPv4
1224
+ // interface. A client that paired while the machine had a different DHCP
1225
+ // lease uses this to replace its stale LAN candidate.
1226
+ const resolveDirectLanUrls = (req) => {
1227
+ const activePort = tunnelRuntimeContext.getActivePort() || port;
1228
+ const urls = [];
1229
+ const push = (host) => {
1230
+ if (typeof host !== 'string' || !host) return;
1231
+ const url = `http://${host.includes(':') ? `[${host}]` : host}:${activePort}`;
1232
+ if (!urls.includes(url)) urls.push(url);
1233
+ };
1234
+ if (isNetworkExposedBindHost(effectiveBindHost)) {
1235
+ push(requestReachedLanAddress(req));
1236
+ try {
1237
+ for (const list of Object.values(os.networkInterfaces())) {
1238
+ for (const entry of (list || [])) {
1239
+ if (entry.family === 'IPv4' && !entry.internal) push(entry.address);
1240
+ }
1241
+ }
1242
+ } catch {
1243
+ // interface scan failure → whatever we already collected
1244
+ }
1245
+ } else {
1246
+ const h = String(effectiveBindHost || '').toLowerCase();
1247
+ if (h && h !== '127.0.0.1' && h !== 'localhost' && h !== '::1') push(effectiveBindHost);
1248
+ }
1249
+ return urls;
1250
+ };
1103
1251
  const uiPassword = typeof options.uiPassword === 'string'
1104
1252
  ? options.uiPassword
1105
1253
  : (typeof process.env.OPENCHAMBER_UI_PASSWORD === 'string' ? process.env.OPENCHAMBER_UI_PASSWORD : null);
@@ -1181,7 +1329,7 @@ async function main(options = {}) {
1181
1329
  res.setHeader('Access-Control-Allow-Origin', origin);
1182
1330
  res.setHeader('Access-Control-Allow-Credentials', 'true');
1183
1331
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
1184
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory');
1332
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory,X-OpenCode-Directory-Encoding');
1185
1333
  res.setHeader('Access-Control-Expose-Headers', 'x-next-cursor');
1186
1334
  res.setHeader('Vary', 'Origin');
1187
1335
  if (req.method === 'OPTIONS') {
@@ -1202,6 +1350,11 @@ async function main(options = {}) {
1202
1350
  server = http.createServer(app);
1203
1351
  let realtimeProxyRuntime = { stop: () => {} };
1204
1352
 
1353
+ // The relay service is constructed further below (it depends on the tunnel
1354
+ // runtime's active port). The pairing routes registered here only read the
1355
+ // relay candidate lazily at request time, so a late-bound holder is enough.
1356
+ let relayServiceInstance = null;
1357
+
1205
1358
  const bootstrapResult = bootstrapRuntime.setupBaseRoutes(app, {
1206
1359
  process,
1207
1360
  openchamberVersion: OPENCHAMBER_VERSION,
@@ -1242,6 +1395,34 @@ async function main(options = {}) {
1242
1395
  uiPassword,
1243
1396
  tunnelAuthController,
1244
1397
  remoteClientAuthRuntime,
1398
+ clientPairingRuntime,
1399
+ getRelayPairingCandidate: (options) => {
1400
+ if (!relayServiceInstance) return null;
1401
+ // A relay pairing link enables the relay on demand; a plain link only
1402
+ // advertises relay when it is already on.
1403
+ return options?.ensureEnabled
1404
+ ? relayServiceInstance.ensureEnabledForPairing()
1405
+ : relayServiceInstance.getPairingCandidate();
1406
+ },
1407
+ // Re-evaluate the relay lifecycle after pairing/device changes (a revoked or
1408
+ // redeemed device can flip relay demand on or off).
1409
+ reconcileRelay: () => (relayServiceInstance ? relayServiceInstance.reconcile() : Promise.resolve()),
1410
+ getPairingTransports: resolvePairingTransports,
1411
+ getDirectCandidateUrls: resolveDirectLanUrls,
1412
+ // Stable server identity for client-side verification of learned addresses.
1413
+ // Lazily resolved: the relay service is constructed after these routes.
1414
+ getServerId: () => (relayServiceInstance ? relayServiceInstance.getServerId() : Promise.resolve(null)),
1415
+ // The display name a paired device shows for THIS server. Devices name the
1416
+ // connection by the issuing machine's hostname, not the per-device pairing
1417
+ // label typed by the operator.
1418
+ getServerLabel: () => {
1419
+ try {
1420
+ const name = os.hostname();
1421
+ return typeof name === 'string' && name.trim().length > 0 ? name.trim() : 'OpenChamber';
1422
+ } catch {
1423
+ return 'OpenChamber';
1424
+ }
1425
+ },
1245
1426
  readSettingsFromDiskMigrated,
1246
1427
  normalizeTunnelSessionTtlMs,
1247
1428
  sayTTSCapability,
@@ -1285,6 +1466,38 @@ async function main(options = {}) {
1285
1466
  const tunnelRuntimeContext = tunnelWiringRuntime.initialize(app, port);
1286
1467
  const { tunnelService, startTunnelWithNormalizedRequest } = tunnelRuntimeContext;
1287
1468
 
1469
+ // Private relay host service: config + management routes + host client
1470
+ // lifecycle. Loopback port comes from the same source the tunnel uses so
1471
+ // relay-tunneled requests hit the local Express app on 127.0.0.1.
1472
+ const relayService = createRelayService({
1473
+ crypto,
1474
+ os,
1475
+ readSettingsFromDiskMigrated,
1476
+ writeSettingsToDisk,
1477
+ readSettingsStrict: readSettingsFromDiskStrict,
1478
+ remoteClientAuthRuntime,
1479
+ getLocalPort: () => tunnelRuntimeContext.getActivePort(),
1480
+ // One relay host per machine: every instance sharing this data dir shares
1481
+ // the relay identity (serverId), so concurrent hosts evict each other at
1482
+ // the relay worker and devices land on a random local instance.
1483
+ hostLock: createRelayHostLock({
1484
+ lockFilePath: path.join(OPENCHAMBER_DATA_DIR, 'relay-host.lock'),
1485
+ fs,
1486
+ process,
1487
+ }),
1488
+ // Relay demand = any paired device or pending pairing session that uses the
1489
+ // relay transport. Drives the auto on/off lifecycle.
1490
+ hasRelayDemand: async () => {
1491
+ const [pendingRelay, deviceRelay] = await Promise.all([
1492
+ clientPairingRuntime.hasActiveRelaySession().catch(() => false),
1493
+ remoteClientAuthRuntime.hasActiveRelayClients().catch(() => false),
1494
+ ]);
1495
+ return pendingRelay || deviceRelay;
1496
+ },
1497
+ });
1498
+ relayServiceInstance = relayService;
1499
+ relayService.registerRoutes(app);
1500
+
1288
1501
  await featureRoutesRuntime.registerRoutes(app, {
1289
1502
  crypto,
1290
1503
  fs,
@@ -1318,6 +1531,7 @@ async function main(options = {}) {
1318
1531
  scheduledTasksRuntime,
1319
1532
  getOpenChamberEventClients: () => uiOpenChamberEventClients,
1320
1533
  writeSseEvent,
1534
+ permissionAutoAcceptRuntime,
1321
1535
  });
1322
1536
 
1323
1537
  const previewProxyRuntime = createPreviewProxyRuntime({
@@ -1394,6 +1608,20 @@ async function main(options = {}) {
1394
1608
  console.warn('[ScheduledTasks] Failed to start runtime:', error?.message || error);
1395
1609
  }
1396
1610
 
1611
+ // Only opens a relay control socket when the user opted in (config enabled).
1612
+ // Reconcile the relay lifecycle from demand on startup: run it if any relay
1613
+ // device/session exists, stop it (and clear a stale enabled flag) otherwise.
1614
+ void relayService.reconcile();
1615
+
1616
+ // Relay demand can change outside our routes: `openchamber connect-url
1617
+ // --relay` writes a pending relay session straight to the on-disk store, and
1618
+ // pending sessions expire without any request hitting us. Poll reconcile so a
1619
+ // headless instance picks the relay up (or drops it) within a minute.
1620
+ const relayReconcileTimer = setInterval(() => {
1621
+ void relayService.reconcile();
1622
+ }, 60_000);
1623
+ relayReconcileTimer.unref?.();
1624
+
1397
1625
  return {
1398
1626
  expressApp: app,
1399
1627
  httpServer: server,
@@ -1424,6 +1652,12 @@ async function main(options = {}) {
1424
1652
  },
1425
1653
  stop: (shutdownOptions = {}) => {
1426
1654
  realtimeProxyRuntime.stop();
1655
+ clearInterval(relayReconcileTimer);
1656
+ try {
1657
+ relayService.stop();
1658
+ } catch {
1659
+ // best-effort teardown of the relay host client
1660
+ }
1427
1661
  try {
1428
1662
  dictationRuntime?.stop?.();
1429
1663
  } catch {