@openchamber/web 1.15.0 → 1.16.1

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 (102) hide show
  1. package/README.md +5 -5
  2. package/dist/assets/{DiagramView-HR2xZxJ8.js → DiagramView-Elkp8b4l.js} +1 -1
  3. package/dist/assets/{MarkdownRendererImpl-sm01Q7R7.js → MarkdownRendererImpl-DLhrL6oX.js} +3 -3
  4. package/dist/assets/{MultiRunWindow-DlFUaNQK.js → MultiRunWindow-DVpNCqnE.js} +1 -1
  5. package/dist/assets/{OnboardingScreen-DVRz82mJ.js → OnboardingScreen-CpcR0gyq.js} +1 -1
  6. package/dist/assets/SessionSwitcherDropdown-DHO5Je6v.js +1 -0
  7. package/dist/assets/{SettingsWindow-CkInZcj7.js → SettingsWindow-Bewo7vwh.js} +1 -1
  8. package/dist/assets/{TerminalView-D_9BAjtv.js → TerminalView-D9C7fNLm.js} +3 -3
  9. package/dist/assets/es-D9nOo8Wx.js +15 -0
  10. package/dist/assets/fr-DEF71lgt.js +13 -0
  11. package/dist/assets/index-BklNmnVr.js +2 -0
  12. package/dist/assets/index-C3uMIExE.css +1 -0
  13. package/dist/assets/ja-CpNfaEje.js +15 -0
  14. package/dist/assets/ko-DLS_rnE-.js +15 -0
  15. package/dist/assets/main-B0CxEOP5.js +237 -0
  16. package/dist/assets/{main-DzNa8r0N.js → main-Ck3ZNw8-.js} +2 -2
  17. package/dist/assets/miniChat-BAJj2Ome.js +2 -0
  18. package/dist/assets/mobile-CJoX4Cdj.js +2 -0
  19. package/dist/assets/pl-BjtFn5-n.js +15 -0
  20. package/dist/assets/pt-BR-C0_4Rnzn.js +15 -0
  21. package/dist/assets/renderElectronMiniChatApp-D4-OXCXM.js +2 -0
  22. package/dist/assets/renderMobileApp-DHWdI195.js +16 -0
  23. package/dist/assets/runtimeEndpointReset-B0P2DED1.js +167 -0
  24. package/dist/assets/uk-BDu4E0s0.js +15 -0
  25. package/dist/assets/{useAppFontEffects-DzBg8hrC.js → useAppFontEffects-9LFMCKYW.js} +195 -136
  26. package/dist/assets/zh-CN-BcwMqxIR.js +15 -0
  27. package/dist/assets/zh-TW-bNDQjKEu.js +15 -0
  28. package/dist/index.html +3 -3
  29. package/dist/mini-chat.html +3 -3
  30. package/dist/mobile.html +3 -3
  31. package/package.json +1 -1
  32. package/server/index.js +106 -1
  33. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  34. package/server/lib/notifications/apns-runtime.js +3 -1
  35. package/server/lib/notifications/runtime.js +135 -33
  36. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  37. package/server/lib/opencode/agents.js +3 -0
  38. package/server/lib/opencode/bootstrap-runtime.js +5 -0
  39. package/server/lib/opencode/core-routes.js +75 -2
  40. package/server/lib/opencode/core-routes.test.js +81 -0
  41. package/server/lib/opencode/feature-routes-runtime.js +6 -0
  42. package/server/lib/opencode/settings-helpers.js +30 -0
  43. package/server/lib/opencode/settings-helpers.test.js +14 -0
  44. package/server/lib/opencode/settings-normalization-runtime.js +19 -4
  45. package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
  46. package/server/lib/opencode/settings-runtime.js +25 -0
  47. package/server/lib/opencode/shutdown-runtime.js +2 -0
  48. package/server/lib/opencode/tunnel-auth.js +4 -9
  49. package/server/lib/package-manager.js +1 -1
  50. package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
  51. package/server/lib/permission-auto-accept/runtime.js +263 -0
  52. package/server/lib/permission-auto-accept/runtime.test.js +137 -0
  53. package/server/lib/projects/project-config.js +8 -0
  54. package/server/lib/quota/DOCUMENTATION.md +5 -2
  55. package/server/lib/quota/credentials/providers.js +43 -0
  56. package/server/lib/quota/credentials/store.js +48 -0
  57. package/server/lib/quota/credentials/store.test.js +26 -0
  58. package/server/lib/quota/opencode-go-credentials.js +11 -0
  59. package/server/lib/quota/opencode-go-credentials.test.js +32 -0
  60. package/server/lib/quota/providers/codex.js +7 -4
  61. package/server/lib/quota/providers/codex.test.js +48 -0
  62. package/server/lib/quota/providers/cursor.js +28 -39
  63. package/server/lib/quota/providers/index.js +7 -0
  64. package/server/lib/quota/providers/ollama-cloud.js +23 -42
  65. package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
  66. package/server/lib/quota/providers/opencode-go.js +70 -0
  67. package/server/lib/quota/providers/opencode-go.test.js +17 -0
  68. package/server/lib/quota/routes.js +78 -7
  69. package/server/lib/quota/routes.test.js +40 -0
  70. package/server/lib/relay/DOCUMENTATION.md +20 -0
  71. package/server/lib/relay/host-lock.js +101 -0
  72. package/server/lib/relay/host-lock.test.js +129 -0
  73. package/server/lib/relay/identity.js +24 -4
  74. package/server/lib/relay/service.js +95 -8
  75. package/server/lib/relay/signing-key.js +30 -7
  76. package/server/lib/scheduled-tasks/runtime.js +104 -0
  77. package/server/lib/session-goal/DOCUMENTATION.md +176 -0
  78. package/server/lib/session-goal/objectives.js +61 -0
  79. package/server/lib/session-goal/routes.js +36 -0
  80. package/server/lib/session-goal/runtime.js +764 -0
  81. package/server/lib/small-model/DOCUMENTATION.md +3 -1
  82. package/server/lib/small-model/call.js +45 -8
  83. package/server/lib/small-model/call.test.js +338 -0
  84. package/server/lib/small-model/index.js +1 -0
  85. package/dist/assets/SessionSwitcherDropdown-DvoOalMY.js +0 -1
  86. package/dist/assets/es-cjUissX4.js +0 -15
  87. package/dist/assets/fr-DqbXnTdK.js +0 -13
  88. package/dist/assets/index-Dg0nmvQU.css +0 -1
  89. package/dist/assets/index-ltrmNGAf.js +0 -2
  90. package/dist/assets/ja-Cetyq6Eg.js +0 -15
  91. package/dist/assets/ko-DtunWisP.js +0 -15
  92. package/dist/assets/main-BC0m8s1v.js +0 -236
  93. package/dist/assets/miniChat-BRYDE-Se.js +0 -2
  94. package/dist/assets/mobile-C3QJVA97.js +0 -2
  95. package/dist/assets/pl-DctGLgve.js +0 -15
  96. package/dist/assets/pt-BR-CXPhf78S.js +0 -15
  97. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +0 -2
  98. package/dist/assets/renderMobileApp-wkBjh5WR.js +0 -16
  99. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +0 -167
  100. package/dist/assets/uk-Bdrc-kqF.js +0 -15
  101. package/dist/assets/zh-CN-CeCVKrHP.js +0 -15
  102. package/dist/assets/zh-TW-CoqiQING.js +0 -15
@@ -0,0 +1,129 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+
3
+ import { createRelayHostLock } from './host-lock.js';
4
+
5
+ // In-memory fs standing in for the shared data dir.
6
+ const makeFakeFs = () => {
7
+ const files = new Map();
8
+ return {
9
+ readFileSync: (p) => {
10
+ if (!files.has(p)) {
11
+ const error = new Error('ENOENT');
12
+ error.code = 'ENOENT';
13
+ throw error;
14
+ }
15
+ return files.get(p);
16
+ },
17
+ writeFileSync: (p, data) => {
18
+ files.set(p, data);
19
+ },
20
+ unlinkSync: (p) => {
21
+ files.delete(p);
22
+ },
23
+ peek: (p) => files.get(p),
24
+ };
25
+ };
26
+
27
+ // Fake process: `alive` is the set of pids that respond to kill(pid, 0).
28
+ const makeFakeProcess = (pid, alive = new Set([pid])) => ({
29
+ pid,
30
+ kill: (target) => {
31
+ if (!alive.has(target)) {
32
+ const error = new Error('ESRCH');
33
+ error.code = 'ESRCH';
34
+ throw error;
35
+ }
36
+ return true;
37
+ },
38
+ });
39
+
40
+ const LOCK = '/data/relay-host.lock';
41
+ const silentLogger = { warn: () => {} };
42
+
43
+ describe('relay host lock', () => {
44
+ it('claims a free lock and reports holding it', () => {
45
+ const fs = makeFakeFs();
46
+ const lock = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(100), logger: silentLogger });
47
+
48
+ expect(lock.tryClaim()).toBe(true);
49
+ expect(lock.holdsClaim()).toBe(true);
50
+ expect(JSON.parse(fs.peek(LOCK)).pid).toBe(100);
51
+ });
52
+
53
+ it('refuses to claim while another LIVE process holds it', () => {
54
+ const fs = makeFakeFs();
55
+ const alive = new Set([100, 200]);
56
+ const first = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(100, alive), logger: silentLogger });
57
+ const second = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(200, alive), logger: silentLogger });
58
+
59
+ expect(first.tryClaim()).toBe(true);
60
+ expect(second.tryClaim()).toBe(false);
61
+ expect(second.holdsClaim()).toBe(false);
62
+ expect(second.liveClaimantPid()).toBe(100);
63
+ });
64
+
65
+ it('treats a dead claimant as free (stale claim takeover)', () => {
66
+ const fs = makeFakeFs();
67
+ const alive = new Set([200]); // pid 100 is gone
68
+ fs.writeFileSync(LOCK, JSON.stringify({ pid: 100 }));
69
+ const lock = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(200, alive), logger: silentLogger });
70
+
71
+ expect(lock.liveClaimantPid()).toBe(null);
72
+ expect(lock.tryClaim()).toBe(true);
73
+ expect(lock.holdsClaim()).toBe(true);
74
+ });
75
+
76
+ it('forceClaim overrides a live holder; the loser sees the takeover', () => {
77
+ const fs = makeFakeFs();
78
+ const alive = new Set([100, 200]);
79
+ const first = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(100, alive), logger: silentLogger });
80
+ const second = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(200, alive), logger: silentLogger });
81
+
82
+ expect(first.tryClaim()).toBe(true);
83
+ expect(second.forceClaim()).toBe(true);
84
+ expect(second.holdsClaim()).toBe(true);
85
+ expect(first.holdsClaim()).toBe(false);
86
+ expect(first.liveClaimantPid()).toBe(200);
87
+ });
88
+
89
+ it('release removes only its own claim', () => {
90
+ const fs = makeFakeFs();
91
+ const alive = new Set([100, 200]);
92
+ const first = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(100, alive), logger: silentLogger });
93
+ const second = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(200, alive), logger: silentLogger });
94
+
95
+ expect(first.tryClaim()).toBe(true);
96
+ second.release(); // not the holder — must be a no-op
97
+ expect(first.holdsClaim()).toBe(true);
98
+
99
+ first.release();
100
+ expect(fs.peek(LOCK)).toBeUndefined();
101
+ expect(first.liveClaimantPid()).toBe(null);
102
+ });
103
+
104
+ it('treats an unparsable claim file as free', () => {
105
+ const fs = makeFakeFs();
106
+ fs.writeFileSync(LOCK, 'not-json');
107
+ const lock = createRelayHostLock({ lockFilePath: LOCK, fs, process: makeFakeProcess(100), logger: silentLogger });
108
+
109
+ expect(lock.liveClaimantPid()).toBe(null);
110
+ expect(lock.tryClaim()).toBe(true);
111
+ });
112
+
113
+ it('an EPERM kill probe still counts as a live holder', () => {
114
+ const fs = makeFakeFs();
115
+ fs.writeFileSync(LOCK, JSON.stringify({ pid: 100 }));
116
+ const proc = {
117
+ pid: 200,
118
+ kill: () => {
119
+ const error = new Error('EPERM');
120
+ error.code = 'EPERM';
121
+ throw error;
122
+ },
123
+ };
124
+ const lock = createRelayHostLock({ lockFilePath: LOCK, fs, process: proc, logger: silentLogger });
125
+
126
+ expect(lock.liveClaimantPid()).toBe(100);
127
+ expect(lock.tryClaim()).toBe(false);
128
+ });
129
+ });
@@ -16,10 +16,15 @@ import { exportPublicKeyJwk, generateEcdhKeyPair, importEcdhPrivateKey } from '.
16
16
  const isJwkPair = (value) => Boolean(value && typeof value === 'object' && value.privateJwk && value.publicJwk);
17
17
 
18
18
  /**
19
- * @param {{ crypto: typeof import('node:crypto'), readSettingsFromDiskMigrated: () => Promise<object>, writeSettingsToDisk: (settings: object) => Promise<void> }} deps
19
+ * @param {{
20
+ * crypto: typeof import('node:crypto'),
21
+ * readSettingsFromDiskMigrated: () => Promise<object>,
22
+ * writeSettingsToDisk: (settings: object) => Promise<void>,
23
+ * readSettingsStrict?: () => Promise<object>,
24
+ * }} deps
20
25
  */
21
26
  export const createRelayIdentityRuntime = (deps) => {
22
- const { crypto, readSettingsFromDiskMigrated, writeSettingsToDisk } = deps;
27
+ const { crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict } = deps;
23
28
 
24
29
  let cachedIdentity = null;
25
30
 
@@ -29,10 +34,25 @@ export const createRelayIdentityRuntime = (deps) => {
29
34
  if (isJwkPair(existing)) {
30
35
  return existing;
31
36
  }
37
+ // Same regeneration gate as the signing key: never mint a replacement
38
+ // identity key off a swallowed read failure — a new encryption key breaks
39
+ // the E2EE trust anchor pinned by every paired device. Verify "missing" via
40
+ // the strict reader (throws on corrupt/unreadable) before generating.
41
+ let verifiedSettings = settings;
42
+ if (readSettingsStrict) {
43
+ verifiedSettings = await readSettingsStrict();
44
+ const verified = verifiedSettings?.relayEncryptionKey;
45
+ if (isJwkPair(verified)) {
46
+ return verified;
47
+ }
48
+ }
49
+ // Loud on purpose: a new encryption key invalidates the E2EE trust anchor of
50
+ // every paired device. Expected exactly once, on first relay use.
51
+ console.warn('[relay-identity] Generating NEW relay encryption keypair (E2EE trust anchor changes; previously paired devices must re-pair)');
32
52
  const keyPair = await generateEcdhKeyPair();
33
53
  const privateJwk = await globalThis.crypto.subtle.exportKey('jwk', keyPair.privateKey);
34
54
  const publicJwk = await exportPublicKeyJwk(keyPair.publicKey);
35
- await writeSettingsToDisk({ ...settings, relayEncryptionKey: { privateJwk, publicJwk } });
55
+ await writeSettingsToDisk({ ...settings, ...(verifiedSettings || {}), relayEncryptionKey: { privateJwk, publicJwk } });
36
56
  return { privateJwk, publicJwk };
37
57
  };
38
58
 
@@ -46,7 +66,7 @@ export const createRelayIdentityRuntime = (deps) => {
46
66
  */
47
67
  const getRelayIdentity = async () => {
48
68
  if (cachedIdentity) return cachedIdentity;
49
- const signing = await getOrCreateRelaySigningKeypair({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk });
69
+ const signing = await getOrCreateRelaySigningKeypair({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict });
50
70
  const serverId = deriveServerId({ crypto }, signing.publicJwk);
51
71
  const encryption = await getOrCreateEncryptionKeypair();
52
72
  const hostEncPrivateKey = await importEcdhPrivateKey(encryption.privateJwk);
@@ -58,16 +58,28 @@ export const createRelayService = ({
58
58
  crypto,
59
59
  readSettingsFromDiskMigrated,
60
60
  writeSettingsToDisk,
61
+ // Strict settings reader (throws on corrupt/unreadable) gating identity
62
+ // regeneration — see identity.js/signing-key.js.
63
+ readSettingsStrict,
61
64
  getLocalPort,
62
65
  // Returns true when any paired device or pending pairing session uses the
63
66
  // relay transport. The relay lifecycle is driven purely by this demand.
64
67
  hasRelayDemand = async () => false,
68
+ // Per-machine claim (host-lock.js): all local instances share the same
69
+ // serverId, so only ONE process may run the relay host at a time or they
70
+ // evict each other at the relay worker ("Control replaced") and devices land
71
+ // on a random instance. Optional: without it, behavior is pre-lock.
72
+ hostLock = null,
65
73
  logger = console,
66
74
  }) => {
67
- const identityRuntime = createRelayIdentityRuntime({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk });
75
+ const identityRuntime = createRelayIdentityRuntime({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict });
68
76
 
69
77
  let hostClient = null;
70
78
  let status = { state: 'disabled', lastError: null, connectedClients: 0 };
79
+ // Re-checks the claim while enabled: a standby instance takes over when the
80
+ // claimant dies; a running host stands down when another process claims.
81
+ let claimWatchTimer = null;
82
+ const CLAIM_WATCH_INTERVAL_MS = 30_000;
71
83
 
72
84
  const readConfig = async () => {
73
85
  const settings = await readSettingsFromDiskMigrated();
@@ -90,8 +102,65 @@ export const createRelayService = ({
90
102
  });
91
103
  };
92
104
 
93
- const start = async (relayUrl) => {
105
+ const stopHostClient = () => {
106
+ if (!hostClient) return;
107
+ hostClient.stop();
108
+ hostClient = null;
109
+ };
110
+
111
+ const standbyStatus = (holderPid) => ({
112
+ state: 'standby',
113
+ lastError: `relay host is owned by another local OpenChamber process (pid ${holderPid})`,
114
+ connectedClients: 0,
115
+ });
116
+
117
+ // Claim watcher, active while the relay is enabled:
118
+ // - standby → claimant died → take over (start our host);
119
+ // - running → another live process claimed → stand down (stop, standby).
120
+ // This back-off is what actually ends the mutual-eviction fight: the loser
121
+ // must STOP reconnecting, otherwise both keep replacing each other forever.
122
+ const ensureClaimWatch = (relayUrl) => {
123
+ if (!hostLock || claimWatchTimer) return;
124
+ claimWatchTimer = setInterval(() => {
125
+ void (async () => {
126
+ try {
127
+ if (hostClient) {
128
+ if (!hostLock.holdsClaim() && hostLock.liveClaimantPid() !== null) {
129
+ logger.warn('[Relay] host claim taken by another local instance — standing down');
130
+ const holder = hostLock.liveClaimantPid();
131
+ stopHostClient();
132
+ status = standbyStatus(holder);
133
+ }
134
+ return;
135
+ }
136
+ if (status.state === 'standby' && hostLock.tryClaim()) {
137
+ logger.warn('[Relay] host claim is free — taking over the relay host');
138
+ await start(relayUrl);
139
+ }
140
+ } catch (error) {
141
+ logger.warn(`[Relay] claim watch failed: ${error?.message ?? error}`);
142
+ }
143
+ })();
144
+ }, CLAIM_WATCH_INTERVAL_MS);
145
+ if (typeof claimWatchTimer.unref === 'function') claimWatchTimer.unref();
146
+ };
147
+
148
+ const stopClaimWatch = () => {
149
+ if (!claimWatchTimer) return;
150
+ clearInterval(claimWatchTimer);
151
+ claimWatchTimer = null;
152
+ };
153
+
154
+ const start = async (relayUrl, { claim = 'try' } = {}) => {
94
155
  if (hostClient) return;
156
+ if (hostLock) {
157
+ const claimed = claim === 'force' ? hostLock.forceClaim() : hostLock.tryClaim();
158
+ if (!claimed) {
159
+ status = standbyStatus(hostLock.liveClaimantPid());
160
+ ensureClaimWatch(relayUrl);
161
+ return;
162
+ }
163
+ }
95
164
  const identity = await identityRuntime.getRelayIdentity();
96
165
  hostClient = startRelayHost({
97
166
  relayUrl,
@@ -103,12 +172,13 @@ export const createRelayService = ({
103
172
  },
104
173
  });
105
174
  status = hostClient.getStatus();
175
+ ensureClaimWatch(relayUrl);
106
176
  };
107
177
 
108
178
  const stop = () => {
109
- if (!hostClient) return;
110
- hostClient.stop();
111
- hostClient = null;
179
+ stopClaimWatch();
180
+ stopHostClient();
181
+ if (hostLock) hostLock.release();
112
182
  status = { state: 'disabled', lastError: null, connectedClients: 0 };
113
183
  };
114
184
 
@@ -145,13 +215,24 @@ export const createRelayService = ({
145
215
  }
146
216
  };
147
217
 
218
+ // Stable server identity (base64url SHA-256 of the canonical public signing
219
+ // JWK). Derived from a public key, so it is not a secret; clients use it to
220
+ // verify that a learned/probed address belongs to this server before trusting
221
+ // it. Independent of whether the relay host is currently enabled.
222
+ const getServerId = async () => {
223
+ const identity = await identityRuntime.getRelayIdentity();
224
+ return identity.serverId;
225
+ };
226
+
148
227
  const getStatus = async () => {
149
228
  const config = await readConfig();
150
229
  const identity = await identityRuntime.getRelayIdentity();
151
230
  const live = hostClient ? hostClient.getStatus() : status;
152
231
  return {
153
232
  enabled: config.enabled,
154
- state: hostClient ? live.state : 'disabled',
233
+ // Without a host client the service is either off or standing by while
234
+ // another local process owns the machine's relay host claim.
235
+ state: hostClient ? live.state : (status.state === 'standby' ? 'standby' : 'disabled'),
155
236
  serverId: identity.serverId,
156
237
  connectedClients: live.connectedClients,
157
238
  relayUrl: config.relayUrl,
@@ -195,7 +276,11 @@ export const createRelayService = ({
195
276
  }
196
277
  if (!hostClient) {
197
278
  const next = await readConfig();
198
- await start(next.relayUrl);
279
+ // Force-claim: creating a pairing link is explicit user intent — the
280
+ // instance the user is pairing against MUST be the one devices reach,
281
+ // even if another local process currently holds the machine's claim
282
+ // (its claim watcher sees the takeover and stands down).
283
+ await start(next.relayUrl, { claim: 'force' });
199
284
  }
200
285
  return buildPairingCandidate();
201
286
  };
@@ -215,7 +300,8 @@ export const createRelayService = ({
215
300
  const relayUrl = typeof req.body?.relayUrl === 'string' ? normalizeRelayUrl(req.body.relayUrl) : current.relayUrl;
216
301
  await writeConfig({ enabled: true, relayUrl });
217
302
  if (hostClient) stop();
218
- await start(relayUrl);
303
+ // Explicit user action: take the machine's host claim like pairing does.
304
+ await start(relayUrl, { claim: 'force' });
219
305
  res.json(await getStatus());
220
306
  } catch (error) {
221
307
  res.status(500).json({ error: error?.message ?? 'Failed to enable relay' });
@@ -241,6 +327,7 @@ export const createRelayService = ({
241
327
  reconcile,
242
328
  stop,
243
329
  getStatus,
330
+ getServerId,
244
331
  getPairingCandidate,
245
332
  ensureEnabledForPairing,
246
333
  };
@@ -6,22 +6,45 @@
6
6
  // serverId must stay stable because push token binding depends on it.
7
7
 
8
8
  /**
9
- * @param {{ crypto: typeof import('node:crypto'), readSettingsFromDiskMigrated: () => Promise<object>, writeSettingsToDisk: (settings: object) => Promise<void> }} deps
9
+ * @param {{
10
+ * crypto: typeof import('node:crypto'),
11
+ * readSettingsFromDiskMigrated: () => Promise<object>,
12
+ * writeSettingsToDisk: (settings: object) => Promise<void>,
13
+ * readSettingsStrict?: () => Promise<object>,
14
+ * }} deps
10
15
  * @returns {Promise<{ privateKey: import('node:crypto').KeyObject, publicJwk: JsonWebKey }>}
11
16
  */
12
- export const getOrCreateRelaySigningKeypair = async ({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk }) => {
17
+ export const getOrCreateRelaySigningKeypair = async ({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict }) => {
18
+ const toKeypair = (stored) => ({
19
+ privateKey: crypto.createPrivateKey({ key: stored.privateJwk, format: 'jwk' }),
20
+ publicJwk: stored.publicJwk,
21
+ });
13
22
  const settings = await readSettingsFromDiskMigrated();
14
23
  const existing = settings?.relaySigningKey;
15
24
  if (existing && existing.privateJwk && existing.publicJwk) {
16
- return {
17
- privateKey: crypto.createPrivateKey({ key: existing.privateJwk, format: 'jwk' }),
18
- publicJwk: existing.publicJwk,
19
- };
25
+ return toKeypair(existing);
20
26
  }
27
+ // Regeneration gate: the lenient settings reader maps read failures to `{}`,
28
+ // indistinguishable from "first run". Minting a new keypair changes serverId,
29
+ // which orphans every paired device and push binding AND the write below would
30
+ // clobber the settings file with the empty spread. Re-verify with the strict
31
+ // reader (throws on corrupt/unreadable) before generating; if it finds the
32
+ // key the lenient read lost, use it and generate nothing.
33
+ let verifiedSettings = settings;
34
+ if (readSettingsStrict) {
35
+ verifiedSettings = await readSettingsStrict();
36
+ const verified = verifiedSettings?.relaySigningKey;
37
+ if (verified && verified.privateJwk && verified.publicJwk) {
38
+ return toKeypair(verified);
39
+ }
40
+ }
41
+ // Loud on purpose: a new signing key means a new serverId — every previously
42
+ // paired device and push binding is orphaned. Expected exactly once, on first run.
43
+ console.warn('[relay-identity] Generating NEW relay signing keypair (serverId changes; previously paired devices must re-pair)');
21
44
  const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
22
45
  const privateJwk = privateKey.export({ format: 'jwk' });
23
46
  const publicJwk = publicKey.export({ format: 'jwk' });
24
- await writeSettingsToDisk({ ...settings, relaySigningKey: { privateJwk, publicJwk } });
47
+ await writeSettingsToDisk({ ...settings, ...(verifiedSettings || {}), relaySigningKey: { privateJwk, publicJwk } });
25
48
  return { privateKey, publicJwk };
26
49
  };
27
50
 
@@ -406,6 +406,21 @@ export const createScheduledTasksRuntime = (deps) => {
406
406
  return projectRunning < maxProjectConcurrency;
407
407
  };
408
408
 
409
+ // Same instruction the composer attaches on an armed goal send: the agent
410
+ // must know goal mode is on from turn one, and each turn has to end with a
411
+ // factual report for the independent audit.
412
+ const buildGoalIntroText = (tokenBudget) => {
413
+ const budgetLine = tokenBudget
414
+ ? ` A token budget of ${tokenBudget} tokens applies to this goal.`
415
+ : '';
416
+ return '<system-reminder>\n'
417
+ + 'Goal mode is active for this session. The user message above defines the goal objective. '
418
+ + 'Work toward it across turns; whenever you stop before the objective is verifiably complete, the system will automatically prompt you to continue. '
419
+ + 'Progress is evaluated independently after each turn, so end every turn with a clear, factual statement of what is done, what was verified, and what remains.'
420
+ + budgetLine
421
+ + '\n</system-reminder>';
422
+ };
423
+
409
424
  const buildPromptAsyncPayload = (task, projectPath) => ({
410
425
  model: {
411
426
  providerID: task.execution.providerID,
@@ -418,9 +433,94 @@ export const createScheduledTasksRuntime = (deps) => {
418
433
  type: 'text',
419
434
  text: expandSnippets(task.execution.prompt, projectPath),
420
435
  },
436
+ ...(task.execution.goalEnabled
437
+ ? [{ type: 'text', text: buildGoalIntroText(task.execution.goalTokenBudget), synthetic: true }]
438
+ : []),
421
439
  ],
422
440
  });
423
441
 
442
+ // Scheduled goal runs: stamp the goal onto the fresh session's metadata
443
+ // before the prompt goes out; the session-goal runtime picks the loop up
444
+ // from session events like any other goal.
445
+ const createTaskGoal = async ({ baseUrl, authHeaders, sessionID, projectPath, task }) => {
446
+ const now = Date.now();
447
+ // File-backed objective keyed by session id: metadata stays light, the
448
+ // full expanded prompt lives under the OpenChamber data dir. If the file
449
+ // write fails, fall back to an inline (clamped) objective.
450
+ // Oversized prompts are distilled into audit criteria by the small model
451
+ // (the working agent gets the full prompt in chat anyway); on distill
452
+ // failure a head+tail excerpt keeps intent and acceptance criteria.
453
+ let objectiveText = expandSnippets(task.execution.prompt, projectPath);
454
+ if (objectiveText.length > 5000) {
455
+ let distilled = null;
456
+ try {
457
+ const { generateSmallModelText } = await import('../small-model/index.js');
458
+ const generated = await generateSmallModelText({
459
+ restrictToPreferredProvider: true,
460
+ prompt: objectiveText,
461
+ system: [
462
+ 'You distill a large task description into the COMPLETION CRITERIA a progress auditor will judge against.',
463
+ 'Return ONLY the criteria text — no preamble, no headers, no markdown fences.',
464
+ 'Capture: the end goals, what must exist and work when the task is fully done, and how each major part is verified. Omit implementation steps.',
465
+ 'Preserve verbatim any file paths, commands, and identifiers that define the task.',
466
+ 'Stay under 4000 characters.',
467
+ 'Write in the same language as the task text.',
468
+ ].join('\n'),
469
+ directory: projectPath,
470
+ preferredProviderID: task.execution.providerID,
471
+ preferredModelID: task.execution.modelID,
472
+ });
473
+ distilled = typeof generated?.text === 'string' ? generated.text.trim() : null;
474
+ } catch (error) {
475
+ console.warn('[scheduled-tasks] goal objective distillation failed:', error?.message || error);
476
+ }
477
+ if (distilled) {
478
+ objectiveText = distilled;
479
+ } else {
480
+ const marker = '\n\n[… objective trimmed for the auditor — the full prompt was delivered in the chat message …]\n\n';
481
+ const half = Math.max(0, Math.floor((5000 - marker.length) / 2));
482
+ objectiveText = `${objectiveText.slice(0, half)}${marker}${objectiveText.slice(-half)}`;
483
+ }
484
+ }
485
+ let objectiveFile = false;
486
+ try {
487
+ const { writeObjective } = await import('../session-goal/objectives.js');
488
+ await writeObjective(sessionID, objectiveText);
489
+ objectiveFile = true;
490
+ } catch (error) {
491
+ console.warn('[scheduled-tasks] goal objective file write failed, falling back to inline:', error?.message || error);
492
+ }
493
+ const goal = {
494
+ id: `${now.toString(36)}${Math.random().toString(36).slice(2, 8)}`,
495
+ objective: objectiveFile ? '' : objectiveText.slice(0, 5000),
496
+ objectiveFile,
497
+ status: 'active',
498
+ tokenBudget: task.execution.goalTokenBudget || null,
499
+ tokensUsed: 0,
500
+ turnsUsed: 0,
501
+ blockedStreak: 0,
502
+ note: '',
503
+ statusReason: '',
504
+ lastAccountedMessageID: '',
505
+ createdAt: now,
506
+ updatedAt: now,
507
+ };
508
+ const url = new URL(`${baseUrl}/session/${encodeURIComponent(sessionID)}`);
509
+ url.searchParams.set('directory', projectPath);
510
+ const response = await fetch(url.toString(), {
511
+ method: 'PATCH',
512
+ headers: {
513
+ ...authHeaders,
514
+ 'content-type': 'application/json',
515
+ accept: 'application/json',
516
+ },
517
+ body: JSON.stringify({ metadata: { openchamber: { goal } } }),
518
+ });
519
+ if (!response.ok) {
520
+ throw new Error(`goal metadata patch failed (${response.status})`);
521
+ }
522
+ };
523
+
424
524
  const runPromptAsync = async ({ baseUrl, authHeaders, sessionID, projectPath, task }) => {
425
525
  const promptUrl = new URL(`${baseUrl}/session/${encodeURIComponent(sessionID)}/prompt_async`);
426
526
  promptUrl.searchParams.set('directory', projectPath);
@@ -511,6 +611,10 @@ export const createScheduledTasksRuntime = (deps) => {
511
611
  } catch {
512
612
  }
513
613
 
614
+ if (task.execution.goalEnabled) {
615
+ await createTaskGoal({ baseUrl, authHeaders, sessionID, projectPath, task });
616
+ }
617
+
514
618
  const executedAsCommand = await runScheduledCommandIfApplicable({
515
619
  client,
516
620
  projectPath,