@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
@@ -0,0 +1,462 @@
1
+ // Host side of the tunnel mux (Layer 3): consumes decrypted tunnel frames for
2
+ // ONE relay connection and dispatches them to the local loopback origin.
3
+ // HTTP streams -> fetch http://127.0.0.1:<port> with streamed duplex bodies;
4
+ // WS streams -> `ws` client to the loopback WebSocket endpoints.
5
+ // The dispatcher NEVER injects credentials: tunneled requests authenticate
6
+ // exactly like any remote client (bearer oc_client_* header, oc_url_token query).
7
+ // Spec: .opencode/plans/private-relay/01-protocol-spec.md (Layer 3).
8
+
9
+ import { WebSocket } from 'ws';
10
+
11
+ import {
12
+ MAX_TUNNEL_PAYLOAD_BYTES,
13
+ TunnelFrameType,
14
+ chunkPayload,
15
+ createFragmentAssembler,
16
+ decodeJsonPayload,
17
+ decodeTunnelFrame,
18
+ encodeFragmentedMessage,
19
+ encodeJsonPayload,
20
+ encodeTunnelFrame,
21
+ } from './tunnel-codec.js';
22
+
23
+ // Path allowlists (defense in depth; same families realtime-proxy.js allows).
24
+ const isAllowedHttpPath = (pathname) =>
25
+ pathname === '/health'
26
+ || pathname === '/api'
27
+ || pathname.startsWith('/api/')
28
+ || pathname === '/auth'
29
+ || pathname.startsWith('/auth/');
30
+
31
+ const ALLOWED_WS_PATHS = new Set([
32
+ '/api/global/event/ws',
33
+ '/api/event/ws',
34
+ '/api/terminal/ws',
35
+ '/api/dictation/ws',
36
+ ]);
37
+
38
+ // Hop-by-hop headers stripped from tunneled requests; `host` is set by fetch
39
+ // to the loopback origin. content-length is dropped too because the body is
40
+ // re-chunked through the tunnel and undici computes framing itself.
41
+ const STRIPPED_REQUEST_HEADERS = new Set([
42
+ 'connection',
43
+ 'keep-alive',
44
+ 'transfer-encoding',
45
+ 'upgrade',
46
+ 'host',
47
+ 'content-length',
48
+ ]);
49
+
50
+ // Response framing headers that no longer apply once the body crosses the
51
+ // tunnel as HttpBody chunks (loopback fetch already decoded content-encoding).
52
+ const STRIPPED_RESPONSE_HEADERS = new Set([
53
+ 'connection',
54
+ 'keep-alive',
55
+ 'transfer-encoding',
56
+ 'content-length',
57
+ 'content-encoding',
58
+ ]);
59
+
60
+ // v1 backpressure rule: pause reading the loopback source while the outbound
61
+ // relay socket has more than this buffered.
62
+ const BACKPRESSURE_LIMIT_BYTES = 4 * 1024 * 1024;
63
+ const BACKPRESSURE_POLL_MS = 20;
64
+
65
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
66
+
67
+ const isHttpRequestPayload = (parsed) =>
68
+ Boolean(parsed && typeof parsed === 'object'
69
+ && typeof parsed.method === 'string'
70
+ && typeof parsed.path === 'string'
71
+ && typeof parsed.query === 'string'
72
+ && parsed.headers && typeof parsed.headers === 'object');
73
+
74
+ const isWsOpenPayload = (parsed) =>
75
+ Boolean(parsed && typeof parsed === 'object'
76
+ && typeof parsed.path === 'string'
77
+ && typeof parsed.query === 'string'
78
+ && (parsed.protocols === undefined || Array.isArray(parsed.protocols)));
79
+
80
+ const isWsClosePayload = (parsed) => Boolean(parsed && typeof parsed === 'object');
81
+
82
+ /**
83
+ * @param {{
84
+ * connectionId: string,
85
+ * getLocalPort: () => number,
86
+ * sendFrame: (plaintextFrame: Uint8Array) => void | Promise<void>,
87
+ * getBufferedAmount: () => number,
88
+ * }} deps
89
+ */
90
+ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBufferedAmount }) => {
91
+ /** @type {Map<number, { kind: 'http', abort: AbortController, body: ReadableStreamDefaultController | null } | { kind: 'ws', socket: WebSocket, opened: boolean }>} */
92
+ const streams = new Map();
93
+ const assembler = createFragmentAssembler();
94
+ let closed = false;
95
+
96
+ const send = async (frame) => {
97
+ if (closed) return;
98
+ await sendFrame(frame);
99
+ };
100
+
101
+ const sendJson = (frameType, streamId, payload) =>
102
+ send(encodeTunnelFrame(frameType, streamId, encodeJsonPayload(payload)));
103
+
104
+ const sendAbort = async (streamId, reason) => {
105
+ await sendJson(TunnelFrameType.StreamAbort, streamId, { reason: String(reason ?? 'stream error') });
106
+ };
107
+
108
+ const dropStream = (streamId) => {
109
+ streams.delete(streamId);
110
+ assembler.dropStream(streamId);
111
+ };
112
+
113
+ const abortLocalStream = (streamId, reason) => {
114
+ const stream = streams.get(streamId);
115
+ if (!stream) return;
116
+ dropStream(streamId);
117
+ if (stream.kind === 'http') {
118
+ try {
119
+ stream.body?.error(new Error(String(reason ?? 'aborted')));
120
+ } catch {
121
+ // body already closed
122
+ }
123
+ stream.abort.abort();
124
+ } else {
125
+ try {
126
+ stream.socket.terminate();
127
+ } catch {
128
+ // socket already gone
129
+ }
130
+ }
131
+ };
132
+
133
+ const waitForBackpressure = async (signal) => {
134
+ while (!closed && getBufferedAmount() > BACKPRESSURE_LIMIT_BYTES) {
135
+ if (signal?.aborted) return;
136
+ await sleep(BACKPRESSURE_POLL_MS);
137
+ }
138
+ };
139
+
140
+ // -------------------------------------------------------------------------
141
+ // HTTP
142
+ // -------------------------------------------------------------------------
143
+
144
+ const buildRequestHeaders = (rawHeaders) => {
145
+ const headers = {};
146
+ for (const [name, value] of Object.entries(rawHeaders)) {
147
+ if (typeof name !== 'string' || typeof value !== 'string') continue;
148
+ const lower = name.toLowerCase();
149
+ if (STRIPPED_REQUEST_HEADERS.has(lower)) continue;
150
+ if (/[\r\n]/.test(name) || /[\r\n]/.test(value)) continue;
151
+ headers[lower] = value;
152
+ }
153
+ headers['x-openchamber-relay-connection'] = connectionId;
154
+ return headers;
155
+ };
156
+
157
+ // Synthetic responses never ship an empty body: `reason` states explicitly
158
+ // that the relay host (not the upstream server) produced this response.
159
+ const syntheticResponse = async (streamId, status, message) => {
160
+ await sendJson(TunnelFrameType.HttpResponse, streamId, {
161
+ status,
162
+ headers: { 'content-type': 'application/json' },
163
+ });
164
+ await send(encodeTunnelFrame(TunnelFrameType.HttpBody, streamId, encodeJsonPayload({ error: message, reason: message, source: 'relay-tunnel-host' })));
165
+ await send(encodeTunnelFrame(TunnelFrameType.StreamEnd, streamId, new Uint8Array(0)));
166
+ };
167
+
168
+ const runHttpStream = async (streamId, request) => {
169
+ const method = request.method.toUpperCase();
170
+ if (!isAllowedHttpPath(request.path)) {
171
+ dropStream(streamId);
172
+ await syntheticResponse(streamId, 403, 'Path is not allowed through the relay');
173
+ return;
174
+ }
175
+
176
+ const stream = streams.get(streamId);
177
+ if (!stream || stream.kind !== 'http') return;
178
+
179
+ const hasBody = method !== 'GET' && method !== 'HEAD';
180
+ let requestBody;
181
+ if (hasBody) {
182
+ requestBody = new ReadableStream({
183
+ start(controller) {
184
+ stream.body = controller;
185
+ },
186
+ });
187
+ } else {
188
+ stream.body = null;
189
+ stream.noBody = true;
190
+ }
191
+
192
+ const url = `http://127.0.0.1:${getLocalPort()}${request.path}${request.query ? `?${request.query}` : ''}`;
193
+ let response;
194
+ try {
195
+ response = await fetch(url, {
196
+ method,
197
+ headers: buildRequestHeaders(request.headers),
198
+ body: requestBody,
199
+ duplex: hasBody ? 'half' : undefined,
200
+ signal: stream.abort.signal,
201
+ });
202
+ } catch (error) {
203
+ if (streams.get(streamId) === stream) {
204
+ dropStream(streamId);
205
+ await sendAbort(streamId, error?.message ?? 'loopback request failed');
206
+ }
207
+ return;
208
+ }
209
+
210
+ const responseHeaders = {};
211
+ for (const [name, value] of response.headers.entries()) {
212
+ if (STRIPPED_RESPONSE_HEADERS.has(name)) continue;
213
+ responseHeaders[name] = value;
214
+ }
215
+ await sendJson(TunnelFrameType.HttpResponse, streamId, { status: response.status, headers: responseHeaders });
216
+
217
+ try {
218
+ if (response.body) {
219
+ for await (const chunk of response.body) {
220
+ if (closed || stream.abort.signal.aborted) return;
221
+ const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
222
+ for (const piece of chunkPayload(bytes, MAX_TUNNEL_PAYLOAD_BYTES)) {
223
+ await waitForBackpressure(stream.abort.signal);
224
+ if (closed || stream.abort.signal.aborted) return;
225
+ await send(encodeTunnelFrame(TunnelFrameType.HttpBody, streamId, piece));
226
+ }
227
+ }
228
+ }
229
+ if (streams.get(streamId) === stream) {
230
+ dropStream(streamId);
231
+ await send(encodeTunnelFrame(TunnelFrameType.StreamEnd, streamId, new Uint8Array(0)));
232
+ }
233
+ } catch (error) {
234
+ if (streams.get(streamId) === stream) {
235
+ dropStream(streamId);
236
+ await sendAbort(streamId, error?.message ?? 'loopback response failed');
237
+ }
238
+ }
239
+ };
240
+
241
+ const handleHttpRequest = (streamId, payload) => {
242
+ if (streams.has(streamId)) {
243
+ abortLocalStream(streamId, 'duplicate stream id');
244
+ void sendAbort(streamId, 'duplicate stream id');
245
+ return;
246
+ }
247
+ let request;
248
+ try {
249
+ request = decodeJsonPayload(payload, isHttpRequestPayload);
250
+ } catch (error) {
251
+ void sendAbort(streamId, error?.message ?? 'malformed request');
252
+ return;
253
+ }
254
+ const stream = { kind: 'http', abort: new AbortController(), body: null, noBody: false };
255
+ streams.set(streamId, stream);
256
+ void runHttpStream(streamId, request);
257
+ };
258
+
259
+ const handleHttpBody = (streamId, payload) => {
260
+ const stream = streams.get(streamId);
261
+ if (!stream || stream.kind !== 'http' || stream.noBody) return;
262
+ // The body controller attaches synchronously in runHttpStream before any
263
+ // await, so by the time body frames arrive it is set for body-carrying
264
+ // methods; drop stray body bytes otherwise.
265
+ try {
266
+ stream.body?.enqueue(payload);
267
+ } catch {
268
+ // stream already errored/closed
269
+ }
270
+ };
271
+
272
+ const handleStreamEnd = (streamId) => {
273
+ const stream = streams.get(streamId);
274
+ if (!stream || stream.kind !== 'http') return;
275
+ try {
276
+ stream.body?.close();
277
+ } catch {
278
+ // stream already errored/closed
279
+ }
280
+ // Response side keeps running; only the request body is half-closed.
281
+ };
282
+
283
+ // -------------------------------------------------------------------------
284
+ // WebSocket
285
+ // -------------------------------------------------------------------------
286
+
287
+ const handleWsOpen = (streamId, payload) => {
288
+ if (streams.has(streamId)) {
289
+ abortLocalStream(streamId, 'duplicate stream id');
290
+ void sendAbort(streamId, 'duplicate stream id');
291
+ return;
292
+ }
293
+ let open;
294
+ try {
295
+ open = decodeJsonPayload(payload, isWsOpenPayload);
296
+ } catch (error) {
297
+ void sendAbort(streamId, error?.message ?? 'malformed ws open');
298
+ return;
299
+ }
300
+ if (!ALLOWED_WS_PATHS.has(open.path)) {
301
+ void sendAbort(streamId, 'Path is not allowed through the relay');
302
+ return;
303
+ }
304
+
305
+ const url = `ws://127.0.0.1:${getLocalPort()}${open.path}${open.query ? `?${open.query}` : ''}`;
306
+ // Present the loopback origin we're actually dialing. The server derives this
307
+ // as a trusted same-origin candidate from the Host header (127.0.0.1:<port>),
308
+ // so the WS origin check passes reliably for every client platform. We do NOT
309
+ // use the client's window.location.origin: it's unreliable in WKWebView (empty
310
+ // or "null" for custom schemes), and the `ws` client sends no Origin at all
311
+ // otherwise — a no-origin upgrade is rejected 403. The request itself is still
312
+ // authenticated by the tunneled oc_url_token, not by this origin.
313
+ const dialHeaders = {
314
+ 'x-openchamber-relay-connection': connectionId,
315
+ origin: `http://127.0.0.1:${getLocalPort()}`,
316
+ };
317
+ let socket;
318
+ try {
319
+ socket = new WebSocket(url, open.protocols, {
320
+ headers: dialHeaders,
321
+ });
322
+ } catch (error) {
323
+ void sendAbort(streamId, error?.message ?? 'ws dial failed');
324
+ return;
325
+ }
326
+ const stream = { kind: 'ws', socket, opened: false };
327
+ streams.set(streamId, stream);
328
+
329
+ socket.on('open', () => {
330
+ if (streams.get(streamId) !== stream) return;
331
+ stream.opened = true;
332
+ void sendJson(TunnelFrameType.WsOpened, streamId, socket.protocol ? { protocol: socket.protocol } : {});
333
+ });
334
+ socket.on('message', (data, isBinary) => {
335
+ if (streams.get(streamId) !== stream || closed) return;
336
+ const bytes = Buffer.isBuffer(data) ? new Uint8Array(data) : new Uint8Array(Buffer.concat(data));
337
+ const frameType = isBinary ? TunnelFrameType.WsBinary : TunnelFrameType.WsText;
338
+ void (async () => {
339
+ for (const frame of encodeFragmentedMessage(frameType, streamId, bytes)) {
340
+ await waitForBackpressure(null);
341
+ if (streams.get(streamId) !== stream || closed) return;
342
+ await send(frame);
343
+ }
344
+ })();
345
+ });
346
+ socket.on('close', (code, reasonBuffer) => {
347
+ if (streams.get(streamId) !== stream) return;
348
+ dropStream(streamId);
349
+ const reason = reasonBuffer ? reasonBuffer.toString('utf8') : '';
350
+ if (stream.opened) {
351
+ void sendJson(TunnelFrameType.WsClose, streamId, { code: code || 1000, reason });
352
+ } else {
353
+ void sendAbort(streamId, reason || `upstream ws closed (${code || 'no code'})`);
354
+ }
355
+ });
356
+ socket.on('error', (error) => {
357
+ if (streams.get(streamId) !== stream) return;
358
+ if (!stream.opened) {
359
+ dropStream(streamId);
360
+ try {
361
+ socket.terminate();
362
+ } catch {
363
+ // already gone
364
+ }
365
+ void sendAbort(streamId, error?.message ?? 'upstream ws error');
366
+ }
367
+ // Post-open errors are followed by 'close', handled above.
368
+ });
369
+ };
370
+
371
+ const handleWsMessage = (streamId, frameType, message) => {
372
+ const stream = streams.get(streamId);
373
+ if (!stream || stream.kind !== 'ws' || stream.socket.readyState !== WebSocket.OPEN) return;
374
+ if (frameType === TunnelFrameType.WsText) {
375
+ stream.socket.send(Buffer.from(message).toString('utf8'));
376
+ } else {
377
+ stream.socket.send(message, { binary: true });
378
+ }
379
+ };
380
+
381
+ const handleWsClose = (streamId, payload) => {
382
+ const stream = streams.get(streamId);
383
+ if (!stream || stream.kind !== 'ws') return;
384
+ dropStream(streamId);
385
+ let close = { code: 1000, reason: '' };
386
+ try {
387
+ close = decodeJsonPayload(payload, isWsClosePayload);
388
+ } catch {
389
+ // fall through with defaults
390
+ }
391
+ const code = Number.isInteger(close.code) && close.code >= 1000 && close.code <= 4999 ? close.code : 1000;
392
+ try {
393
+ stream.socket.close(code, typeof close.reason === 'string' ? close.reason : '');
394
+ } catch {
395
+ stream.socket.terminate();
396
+ }
397
+ };
398
+
399
+ // -------------------------------------------------------------------------
400
+ // Frame entrypoint
401
+ // -------------------------------------------------------------------------
402
+
403
+ /** @param {Uint8Array} plaintextFrame one decrypted tunnel frame */
404
+ const handleFrame = async (plaintextFrame) => {
405
+ if (closed) return;
406
+ const frame = decodeTunnelFrame(plaintextFrame);
407
+
408
+ // WS message frames can be fragmented; everything else arrives whole.
409
+ if (frame.frameType === TunnelFrameType.WsText || frame.frameType === TunnelFrameType.WsBinary) {
410
+ const message = assembler.push(frame);
411
+ if (message === null) return;
412
+ handleWsMessage(frame.streamId, frame.frameType, message);
413
+ return;
414
+ }
415
+
416
+ switch (frame.frameType) {
417
+ case TunnelFrameType.HttpRequest:
418
+ handleHttpRequest(frame.streamId, frame.payload);
419
+ return;
420
+ case TunnelFrameType.HttpBody:
421
+ handleHttpBody(frame.streamId, frame.payload);
422
+ return;
423
+ case TunnelFrameType.StreamEnd:
424
+ handleStreamEnd(frame.streamId);
425
+ return;
426
+ case TunnelFrameType.StreamAbort:
427
+ abortLocalStream(frame.streamId, 'aborted by client');
428
+ return;
429
+ case TunnelFrameType.WsOpen:
430
+ handleWsOpen(frame.streamId, frame.payload);
431
+ return;
432
+ case TunnelFrameType.WsClose:
433
+ handleWsClose(frame.streamId, frame.payload);
434
+ return;
435
+ case TunnelFrameType.Ping:
436
+ await send(encodeTunnelFrame(TunnelFrameType.Pong, frame.streamId, new Uint8Array(0)));
437
+ return;
438
+ case TunnelFrameType.Pong:
439
+ return;
440
+ default:
441
+ // Host never receives HttpResponse/WsOpened; ignore rather than tear down.
442
+ return;
443
+ }
444
+ };
445
+
446
+ const close = () => {
447
+ if (closed) return;
448
+ closed = true;
449
+ for (const streamId of [...streams.keys()]) {
450
+ abortLocalStream(streamId, 'connection closed');
451
+ }
452
+ streams.clear();
453
+ };
454
+
455
+ return {
456
+ handleFrame,
457
+ close,
458
+ get streamCount() {
459
+ return streams.size;
460
+ },
461
+ };
462
+ };
@@ -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,