@openchamber/web 1.14.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.test.js +8 -0
- package/bin/lib/DOCUMENTATION.md +3 -0
- package/bin/lib/cli-args.js +10 -0
- package/bin/lib/commands-connect-url.js +169 -22
- package/dist/assets/{DiagramView-CIaZCGUT.js → DiagramView-HR2xZxJ8.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
- package/dist/assets/{MultiRunWindow-Bsbr3i8y.js → MultiRunWindow-DlFUaNQK.js} +1 -1
- package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
- package/dist/assets/{SessionSwitcherDropdown-CLm6tF5n.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
- package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
- package/dist/assets/{TerminalView-DF7-jlam.js → TerminalView-D_9BAjtv.js} +3 -3
- package/dist/assets/es-cjUissX4.js +15 -0
- package/dist/assets/fr-DqbXnTdK.js +13 -0
- package/dist/assets/index-Dg0nmvQU.css +1 -0
- package/dist/assets/index-ltrmNGAf.js +2 -0
- package/dist/assets/ja-Cetyq6Eg.js +15 -0
- package/dist/assets/ko-DtunWisP.js +15 -0
- package/dist/assets/main-BC0m8s1v.js +236 -0
- package/dist/assets/main-DzNa8r0N.js +2 -0
- package/dist/assets/miniChat-BRYDE-Se.js +2 -0
- package/dist/assets/mobile-C3QJVA97.js +2 -0
- package/dist/assets/pl-DctGLgve.js +15 -0
- package/dist/assets/pt-BR-CXPhf78S.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
- package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
- package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
- package/dist/assets/uk-Bdrc-kqF.js +15 -0
- package/dist/assets/{useAppFontEffects-DTO332li.js → useAppFontEffects-DzBg8hrC.js} +132 -116
- package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
- package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
- package/dist/assets/zh-TW-CoqiQING.js +15 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +2 -2
- package/server/index.js +157 -6
- package/server/lib/client-auth/pairing.js +308 -0
- package/server/lib/client-auth/pairing.test.js +142 -0
- package/server/lib/client-auth/remote-clients.js +65 -3
- package/server/lib/notifications/apns-runtime.js +9 -16
- package/server/lib/opencode/bootstrap-runtime.js +10 -0
- package/server/lib/opencode/core-routes.js +247 -6
- package/server/lib/opencode/core-routes.test.js +248 -9
- package/server/lib/opencode/feature-routes-runtime.js +10 -0
- package/server/lib/opencode/models-metadata.js +61 -0
- package/server/lib/opencode/network-runtime.js +14 -1
- package/server/lib/opencode/network-runtime.test.js +29 -9
- package/server/lib/opencode/openchamber-routes.js +7 -40
- package/server/lib/opencode/proxy.js +47 -6
- package/server/lib/opencode/settings-helpers.js +16 -0
- package/server/lib/opencode/settings-helpers.test.js +11 -0
- package/server/lib/opencode/settings-normalization-runtime.js +2 -0
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/package-manager.js +18 -5
- package/server/lib/relay/DOCUMENTATION.md +78 -0
- package/server/lib/relay/cross-compat.test.js +135 -0
- package/server/lib/relay/e2ee.js +341 -0
- package/server/lib/relay/e2ee.test.js +124 -0
- package/server/lib/relay/host-client.js +389 -0
- package/server/lib/relay/host-client.test.js +280 -0
- package/server/lib/relay/identity.js +73 -0
- package/server/lib/relay/identity.test.js +78 -0
- package/server/lib/relay/service.js +247 -0
- package/server/lib/relay/signing-key.js +50 -0
- package/server/lib/relay/tunnel-codec.js +373 -0
- package/server/lib/relay/tunnel-codec.test.js +58 -0
- package/server/lib/relay/tunnel-host.js +462 -0
- package/server/lib/session-assist/DOCUMENTATION.md +66 -0
- package/server/lib/session-assist/runtime.js +394 -0
- package/server/lib/small-model/DOCUMENTATION.md +78 -0
- package/server/lib/small-model/call.js +380 -0
- package/server/lib/small-model/catalog.js +13 -0
- package/server/lib/small-model/index.js +167 -0
- package/server/lib/small-model/resolve.js +131 -0
- package/server/lib/small-model/resolve.test.js +197 -0
- package/server/lib/small-model/routes.js +44 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
- package/server/lib/ui-auth/ui-auth.js +10 -0
- package/server/opencode-proxy.test.js +38 -0
- package/dist/assets/MarkdownRendererImpl-DWgOeIpO.js +0 -7
- package/dist/assets/OnboardingScreen-3IAKkM5k.js +0 -1
- package/dist/assets/SettingsWindow-K-ErjehP.js +0 -1
- package/dist/assets/es-DQIFCjC2.js +0 -15
- package/dist/assets/fr-CJRav0LS.js +0 -13
- package/dist/assets/index-5eUDDB6w.js +0 -2
- package/dist/assets/index-CgpE7F8T.css +0 -1
- package/dist/assets/ja-CjAaqvHO.js +0 -15
- package/dist/assets/ko-BEbFxvrd.js +0 -15
- package/dist/assets/main-C2put7uQ.js +0 -2
- package/dist/assets/main-DuQEoz31.js +0 -214
- package/dist/assets/miniChat-o3AAQ-8r.js +0 -2
- package/dist/assets/mobile-X0421aWz.js +0 -2
- package/dist/assets/pl-D4kzai5T.js +0 -15
- package/dist/assets/pt-BR-9Sk3esQZ.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-CdDj0ms1.js +0 -2
- package/dist/assets/renderMobileApp-cZ_HZKSe.js +0 -16
- package/dist/assets/runtimeEndpointReset-BYLVW9e7.js +0 -167
- package/dist/assets/uk-DW_dTfoO.js +0 -15
- package/dist/assets/zh-CN-r2_euV7U.js +0 -15
- package/dist/assets/zh-TW-BdPx3NWh.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
|
+
};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Session Assist
|
|
2
|
+
|
|
3
|
+
Server-side watcher that generates a short recap of the agent's last reply
|
|
4
|
+
and one suggested user follow-up with the small model
|
|
5
|
+
(`lib/small-model`), storing both on the session's metadata under
|
|
6
|
+
`metadata.openchamber.assist`.
|
|
7
|
+
|
|
8
|
+
## Flow
|
|
9
|
+
|
|
10
|
+
1. `createSessionAssistRuntime` is a consumer of the server's global SSE
|
|
11
|
+
fan-out (`index.js` → `onPayload`), riding the same upstream connection as
|
|
12
|
+
notifications. Purely event-driven — dormant sessions never generate
|
|
13
|
+
anything, there is no backfill and no session scanning.
|
|
14
|
+
2. `session.status: idle` arms a 60-second per-session timer; any `busy`/
|
|
15
|
+
`retry` status or a user `message.updated` clears it (the "1 minute of
|
|
16
|
+
quiet" rule).
|
|
17
|
+
3. On fire: fetch the session (skip sub-agent sessions with `parentID`),
|
|
18
|
+
take the LAST exchange only — the final assistant reply plus the user
|
|
19
|
+
message it answered (assistant `parentID` → user id) — and call
|
|
20
|
+
`generateSmallModelText` with the
|
|
21
|
+
session's own provider/model taken from the last assistant message — so
|
|
22
|
+
the utility call spends the same subscription as the conversation.
|
|
23
|
+
`restrictToPreferredProvider` forbids the resolver's global fallback:
|
|
24
|
+
conversation content never goes to a provider the user didn't pick for
|
|
25
|
+
the session, unless the small model was chosen explicitly (settings
|
|
26
|
+
override or opencode config). A resolver 404 is silently skipped.
|
|
27
|
+
4. The requested JSON fields (`recap`, `suggestion`, or both) are clamped and
|
|
28
|
+
PATCHed onto the session metadata together with `forMessageID` (the last
|
|
29
|
+
assistant message id) and `generatedAt`. Before writing, the session tail is
|
|
30
|
+
re-checked (a stale result is dropped) and the metadata is merged from a
|
|
31
|
+
fresh session read so concurrent metadata writes made during generation are
|
|
32
|
+
preserved.
|
|
33
|
+
|
|
34
|
+
## Settings gate
|
|
35
|
+
|
|
36
|
+
`sessionRecapEnabled` and `sessionSuggestionEnabled` in OpenChamber settings
|
|
37
|
+
(Settings → Chat, default on) are hard generation switches checked at fire
|
|
38
|
+
time. When both are off, no small-model calls run and nothing is written. When
|
|
39
|
+
one is on, the runtime still makes at most one small-model call and asks only
|
|
40
|
+
for that field. The UI also hides disabled payload types immediately.
|
|
41
|
+
|
|
42
|
+
## Freshness contract (no clearing writes)
|
|
43
|
+
|
|
44
|
+
Clients do not need the payload to be deleted: they render it only while
|
|
45
|
+
`assist.forMessageID` still equals the session's last assistant message id
|
|
46
|
+
(and the session is idle). Any new message invalidates the payload
|
|
47
|
+
everywhere instantly and offline; the next idle cycle overwrites it.
|
|
48
|
+
|
|
49
|
+
## UI consumers (packages/ui)
|
|
50
|
+
|
|
51
|
+
- `lib/sessionAssistMetadata.ts` — payload parsing.
|
|
52
|
+
- `hooks/useSessionAssist.ts` — freshness gating + the 1-minute quiet window
|
|
53
|
+
for the recap (single timeout to the boundary, no polling).
|
|
54
|
+
- `components/chat/SessionRecapSpacer.tsx` — renders the recap inside the
|
|
55
|
+
fixed-height reserved gap under the last message (height never changes).
|
|
56
|
+
- `components/chat/SessionSuggestionChip.tsx` — one tappable suggestion chip
|
|
57
|
+
near the composer (desktop chips row + above the mobile pill); hidden as
|
|
58
|
+
soon as the composer has any content. Tap fills the input, never sends.
|
|
59
|
+
|
|
60
|
+
## Limitations
|
|
61
|
+
|
|
62
|
+
- The watcher lives in the web server, so VS Code (extension-only, no web
|
|
63
|
+
server) does not generate assists; it still renders payloads produced by a
|
|
64
|
+
web/desktop instance of the same OpenCode server via `session.updated`.
|
|
65
|
+
- Metadata payloads ride every `session.updated` event — keep the clamps
|
|
66
|
+
(`RECAP_CHAR_LIMIT`, `SUGGESTION_CHAR_LIMIT`) small.
|