quick-acp 0.0.0-stage → 0.1.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.
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Quick gateway WebSocket transport.
3
+ *
4
+ * Reconstructed from the renderer (Wx / IZe / Gx) and the main-process proxy
5
+ * (dist/main/sncsWsProxy.js). Timing constants are the app's own:
6
+ * - WS keepalive ping every 45 s (xZe = 45e3)
7
+ * - token refresh every 900 s (PZe = 900e3)
8
+ * - protocol ping watchdog every 25 s, 2 misses -> terminate
9
+ * - inbound idle reaping at 60 s steady / 130 s during boot
10
+ *
11
+ * The transport is intentionally dumb: it frames and unframes JSON strings and
12
+ * surfaces them as events. Session semantics live in session.ts.
13
+ */
14
+ import WebSocket from 'ws';
15
+ import { DEFAULT_WS_PATH, ALT_WS_PATH } from './auth.js';
16
+ import { WORKING_PATH } from './gateway-contract.js';
17
+ import { encodeOutbound, esDrain, decodeInbound, DEFAULT_FRAMING, } from './codec.js';
18
+ // Must stay well inside the server's 95 s IDLE_TIMEOUT reap.
19
+ const WS_PING_INTERVAL_MS = 25_000;
20
+ const WS_PING_MAX_MISSED = 2;
21
+ const WS_INBOUND_IDLE_MS = 60_000;
22
+ const WS_INBOUND_IDLE_BOOT_MS = 130_000;
23
+ const WS_IDLE_CHECK_INTERVAL_MS = 15_000;
24
+ const APP_PING_INTERVAL_MS = 45_000;
25
+ const TOKEN_REFRESH_INTERVAL_MS = 900_000;
26
+ const CONNECT_TIMEOUT_MS = 30_000;
27
+ /**
28
+ * Build the WSS URL and headers.
29
+ *
30
+ * IMPORTANT 鈥?verified against the live gateway, not inferred from the binary:
31
+ * the renderer builds a `Authorization: Bearer` header (IZe), but a raw `ws`
32
+ * client sending that header is REFUSED with 401. The form that actually opens
33
+ * the socket is the token in the QUERY string together with `surfaceType`.
34
+ *
35
+ * Probe results on a social tenant:
36
+ * path /streaming/quickwork-chat-bidirectional-stream + query auth -> OPEN
37
+ * path /streaming/quickwork-chat-bidirectional-stream + header auth -> 401
38
+ * path /ws/service/.../ChatBidirectionalStream -> 404
39
+ *
40
+ * So `url` carries the auth and `headers` stays minimal. `authInHeader` exists
41
+ * only so an enterprise tenant (where the header form is what the app uses) can
42
+ * be tried without editing code.
43
+ */
44
+ export function buildHandshake(session, opts = {}) {
45
+ const path = opts.path ?? session.wsPath ?? WORKING_PATH;
46
+ const url = new URL(`wss://${session.wsHost}${path}`);
47
+ const auth = opts.auth ?? (process.env.QUICK_ACP_AUTH_IN_HEADER === '1' ? 'header' : 'query');
48
+ // surfaceType is required by the server; without it the upgrade is refused.
49
+ url.searchParams.set('surfaceType', session.surface);
50
+ const headers = {
51
+ 'X-Surface-Type': session.surface,
52
+ 'X-Agent-Service-Type': 'UNIFIED_QUICK',
53
+ };
54
+ if (auth === 'query') {
55
+ url.searchParams.set('token', session.jwt);
56
+ if (session.outpostId)
57
+ url.searchParams.set('outpostId', session.outpostId);
58
+ if (session.workingSessionId) {
59
+ url.searchParams.set('workingSessionId', session.workingSessionId);
60
+ }
61
+ // Deliberately no Authorization header: sending one makes the upgrade 401.
62
+ }
63
+ else {
64
+ headers['Authorization'] = `Bearer ${session.jwt}`;
65
+ if (session.outpostId)
66
+ headers['X-Outpost-Id'] = session.outpostId;
67
+ if (session.workingSessionId)
68
+ headers['X-Working-Session-Id'] = session.workingSessionId;
69
+ }
70
+ const channel = opts.channel ?? process.env.QUICK_ACP_CHANNEL;
71
+ if (channel === 'beta' || channel === 'prod') {
72
+ headers['X-Channel'] = channel;
73
+ url.searchParams.set('channel', channel);
74
+ }
75
+ if (opts.agentRuntimeArnOverride) {
76
+ url.searchParams.set('agentRuntimeArnOverride', opts.agentRuntimeArnOverride);
77
+ }
78
+ return { url: url.toString(), headers };
79
+ }
80
+ export class QuickTransport {
81
+ session;
82
+ opts;
83
+ ws = null;
84
+ recvBuffer = new Uint8Array(0);
85
+ listeners = new Set();
86
+ pingTimer = null;
87
+ idleTimer = null;
88
+ appPingTimer = null;
89
+ refreshTimer = null;
90
+ pendingPong = false;
91
+ missedPongs = 0;
92
+ sawInbound = false;
93
+ lastInboundAt = Date.now();
94
+ closedByUs = false;
95
+ framing;
96
+ debug;
97
+ constructor(session, opts = {}) {
98
+ this.session = session;
99
+ this.opts = opts;
100
+ this.framing = opts.framing ?? DEFAULT_FRAMING;
101
+ this.debug = opts.debug ?? process.env.QUICK_ACP_DEBUG === '1';
102
+ }
103
+ on(listener) {
104
+ this.listeners.add(listener);
105
+ return () => this.listeners.delete(listener);
106
+ }
107
+ emit(ev) {
108
+ for (const l of this.listeners) {
109
+ try {
110
+ l(ev);
111
+ }
112
+ catch (e) {
113
+ this.log('listener threw', e);
114
+ }
115
+ }
116
+ }
117
+ log(...args) {
118
+ if (this.debug)
119
+ console.error('[quick-acp:ws]', ...args);
120
+ }
121
+ /** Dial and resolve once the socket is open, or reject with the reason. */
122
+ async connect() {
123
+ const session = this.opts.pathOverride
124
+ ? { ...this.session, wsPath: this.opts.pathOverride }
125
+ : this.session;
126
+ const { url, headers } = buildHandshake(session, { framing: this.framing });
127
+ this.log('connecting to', url.replace(/(token=)[^&]*/, '$1<redacted>'));
128
+ await new Promise((resolve, reject) => {
129
+ const ws = new WebSocket(url, { headers });
130
+ this.ws = ws;
131
+ let settled = false;
132
+ const timeout = setTimeout(() => {
133
+ if (settled)
134
+ return;
135
+ settled = true;
136
+ try {
137
+ ws.terminate();
138
+ }
139
+ catch {
140
+ /* already gone */
141
+ }
142
+ reject(new Error(`connect timeout after ${CONNECT_TIMEOUT_MS}ms`));
143
+ }, CONNECT_TIMEOUT_MS);
144
+ ws.on('open', () => {
145
+ clearTimeout(timeout);
146
+ if (settled)
147
+ return;
148
+ settled = true;
149
+ this.lastInboundAt = Date.now();
150
+ this.log('open');
151
+ this.startWatchdogs();
152
+ this.emit({ type: 'open' });
153
+ resolve();
154
+ });
155
+ ws.on('message', (data) => {
156
+ this.lastInboundAt = Date.now();
157
+ this.sawInbound = true;
158
+ try {
159
+ this.handleBinary(toUint8(data));
160
+ }
161
+ catch (e) {
162
+ this.log('message handling error', e);
163
+ }
164
+ });
165
+ ws.on('pong', () => {
166
+ this.pendingPong = false;
167
+ this.missedPongs = 0;
168
+ });
169
+ ws.on('error', (err) => {
170
+ clearTimeout(timeout);
171
+ this.log('error', err.message);
172
+ if (!settled) {
173
+ settled = true;
174
+ reject(err);
175
+ return;
176
+ }
177
+ this.emit({ type: 'error', body: err.message });
178
+ });
179
+ ws.on('close', (code, reason) => {
180
+ clearTimeout(timeout);
181
+ this.stopWatchdogs();
182
+ const text = reason?.toString() ?? '';
183
+ this.log('close', code, text);
184
+ if (!settled) {
185
+ settled = true;
186
+ reject(new Error(`closed before open (code ${code}) ${text}`.trim()));
187
+ return;
188
+ }
189
+ if (!this.closedByUs)
190
+ this.emit({ type: 'close', code, reason: text });
191
+ });
192
+ });
193
+ }
194
+ handleBinary(buf) {
195
+ const combined = new Uint8Array(this.recvBuffer.length + buf.length);
196
+ combined.set(this.recvBuffer);
197
+ combined.set(buf, this.recvBuffer.length);
198
+ const { messages, consumed } = esDrain(combined, 0);
199
+ this.recvBuffer = combined.slice(consumed);
200
+ for (const msg of messages) {
201
+ const ev = decodeInbound(msg, this.framing);
202
+ if (ev.kind === 'error') {
203
+ this.log('server error frame', ev.code, ev.body);
204
+ this.emit({ type: 'error', body: ev.body });
205
+ }
206
+ else if (ev.kind === 'message') {
207
+ this.log('recv', ev.body.slice(0, 200));
208
+ this.emit({ type: 'message', body: ev.body });
209
+ }
210
+ else {
211
+ this.log('ignored frame', ev.reason);
212
+ }
213
+ }
214
+ }
215
+ /** Send one JSON message using the configured framing. */
216
+ send(obj) {
217
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
218
+ throw new Error('socket is not open');
219
+ }
220
+ const json = typeof obj === 'string' ? obj : JSON.stringify(obj);
221
+ this.log('send', json.slice(0, 200));
222
+ this.ws.send(encodeOutbound(json, this.framing));
223
+ }
224
+ /**
225
+ * Send a message as a plain text frame, bypassing the codec.
226
+ * The app does this for token_refresh (sncsWsSendRaw).
227
+ */
228
+ sendRaw(json) {
229
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
230
+ throw new Error('socket is not open');
231
+ }
232
+ this.log('sendRaw', json.slice(0, 200));
233
+ this.ws.send(json);
234
+ }
235
+ startWatchdogs() {
236
+ // WS-level liveness; two missed pongs means the path is dead.
237
+ this.pingTimer = setInterval(() => {
238
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN)
239
+ return;
240
+ if (this.pendingPong) {
241
+ this.missedPongs++;
242
+ if (this.missedPongs >= WS_PING_MAX_MISSED) {
243
+ this.log('ping timeout; terminating');
244
+ this.terminate(4002, 'ping_timeout');
245
+ return;
246
+ }
247
+ }
248
+ this.pendingPong = true;
249
+ try {
250
+ this.ws.ping();
251
+ }
252
+ catch {
253
+ /* socket died under us */
254
+ }
255
+ }, WS_PING_INTERVAL_MS);
256
+ // Inbound data liveness; distinct from the ping watchdog because a dead
257
+ // runtime still answers pings.
258
+ this.idleTimer = setInterval(() => {
259
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN)
260
+ return;
261
+ const idleMs = Date.now() - this.lastInboundAt;
262
+ const threshold = this.sawInbound ? WS_INBOUND_IDLE_MS : WS_INBOUND_IDLE_BOOT_MS;
263
+ if (idleMs >= threshold) {
264
+ this.log(`inbound idle ${Math.round(idleMs / 1000)}s; terminating`);
265
+ this.terminate(4003, 'inbound_idle');
266
+ }
267
+ }, WS_IDLE_CHECK_INTERVAL_MS);
268
+ }
269
+ /** Start application-level ping and token refresh (call after session_connect). */
270
+ startAppHeartbeat() {
271
+ if (this.appPingTimer)
272
+ return;
273
+ this.appPingTimer = setInterval(() => {
274
+ try {
275
+ this.send({ type: 'ping', payload: { timestamp: Date.now() } });
276
+ }
277
+ catch {
278
+ /* socket closed between ticks */
279
+ }
280
+ }, APP_PING_INTERVAL_MS);
281
+ const refresh = this.opts.onTokenRefreshNeeded;
282
+ if (refresh) {
283
+ this.refreshTimer = setInterval(() => {
284
+ void (async () => {
285
+ try {
286
+ const jwt = await refresh();
287
+ if (!jwt)
288
+ return;
289
+ this.sendRaw(JSON.stringify({ type: 'token_refresh', token: jwt }));
290
+ }
291
+ catch (e) {
292
+ this.log('token refresh failed', e);
293
+ }
294
+ })();
295
+ }, TOKEN_REFRESH_INTERVAL_MS);
296
+ }
297
+ }
298
+ stopWatchdogs() {
299
+ for (const t of [this.pingTimer, this.idleTimer, this.appPingTimer, this.refreshTimer]) {
300
+ if (t)
301
+ clearInterval(t);
302
+ }
303
+ this.pingTimer = null;
304
+ this.idleTimer = null;
305
+ this.appPingTimer = null;
306
+ this.refreshTimer = null;
307
+ }
308
+ terminate(code = 1000, reason = 'client_close') {
309
+ this.closedByUs = true;
310
+ this.stopWatchdogs();
311
+ try {
312
+ this.ws?.close(code, reason);
313
+ }
314
+ catch {
315
+ /* already closing */
316
+ }
317
+ this.ws = null;
318
+ }
319
+ get isOpen() {
320
+ return this.ws?.readyState === WebSocket.OPEN;
321
+ }
322
+ /** Surface id, so the session layer can repeat it in business payloads. */
323
+ get surface() {
324
+ return this.session.surface;
325
+ }
326
+ /** Outpost id, likewise. */
327
+ get outpostId() {
328
+ return this.session.outpostId;
329
+ }
330
+ /** The tenant URL, for callers that need the HTTP origin. */
331
+ get tenantUrl() {
332
+ return this.session.tenantUrl;
333
+ }
334
+ }
335
+ function toUint8(data) {
336
+ if (data instanceof ArrayBuffer)
337
+ return new Uint8Array(data);
338
+ if (Array.isArray(data))
339
+ return new Uint8Array(Buffer.concat(data));
340
+ return new Uint8Array(data);
341
+ }
342
+ export { DEFAULT_WS_PATH, ALT_WS_PATH };
343
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Regression: session ids must not collide across agent restarts.
3
+ *
4
+ * The bug this locks down: ids were `quick-1`, `quick-2`, … from a counter that
5
+ * reset to 1 on every process start. codeg binds a session id to a conversation
6
+ * and refuses to rebind it, so the second conversation ever opened got
7
+ * "agent session quick-1 is already bound to conversation 770" and could never
8
+ * send a message.
9
+ *
10
+ * Runs the REAL agent twice (two separate processes, like two app restarts) and
11
+ * asserts the ids differ.
12
+ */
13
+ import { spawn } from 'node:child_process';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { dirname, join } from 'node:path';
16
+ const here = dirname(fileURLToPath(import.meta.url));
17
+ const agentPath = join(here, 'main.js');
18
+ /** Start an agent, create one session, return its id, and stop the agent. */
19
+ async function oneRun(label) {
20
+ const child = spawn(process.execPath, [agentPath], {
21
+ stdio: ['pipe', 'pipe', 'pipe'],
22
+ env: { ...process.env, QUICK_ACP_WORKSPACE: process.cwd() },
23
+ });
24
+ child.stderr.on('data', () => { });
25
+ let buf = '';
26
+ const waiters = new Map();
27
+ child.stdout.on('data', (c) => {
28
+ buf += c.toString('utf8');
29
+ let i;
30
+ while ((i = buf.indexOf('\n')) >= 0) {
31
+ const line = buf.slice(0, i).trim();
32
+ buf = buf.slice(i + 1);
33
+ if (!line)
34
+ continue;
35
+ let msg;
36
+ try {
37
+ msg = JSON.parse(line);
38
+ }
39
+ catch {
40
+ continue;
41
+ }
42
+ if (typeof msg.id === 'number' && waiters.has(msg.id)) {
43
+ const fn = waiters.get(msg.id);
44
+ waiters.delete(msg.id);
45
+ fn(msg);
46
+ }
47
+ }
48
+ });
49
+ const send = (id, method, params) => {
50
+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);
51
+ return new Promise((res, rej) => {
52
+ waiters.set(id, res);
53
+ setTimeout(() => rej(new Error(`timeout: ${method}`)), 120_000);
54
+ });
55
+ };
56
+ await send(1, 'initialize', { protocolVersion: 1, clientCapabilities: {} });
57
+ const ns = await send(2, 'session/new', { cwd: process.cwd(), mcpServers: [] });
58
+ if (ns.error)
59
+ throw new Error(`${label}: session/new failed: ${ns.error.message}`);
60
+ const id = String(ns.result?.['sessionId'] ?? '');
61
+ child.kill();
62
+ await new Promise((r) => setTimeout(r, 400));
63
+ return id;
64
+ }
65
+ let failures = 0;
66
+ const check = (name, ok, detail = '') => {
67
+ if (ok)
68
+ console.log(` ok ${name}`);
69
+ else {
70
+ failures++;
71
+ console.log(` FAIL ${name}${detail ? ` — ${detail}` : ''}`);
72
+ }
73
+ };
74
+ console.log('quick-acp session id uniqueness');
75
+ console.log('');
76
+ const ids = [];
77
+ for (const label of ['run 1', 'run 2', 'run 3']) {
78
+ const id = await oneRun(label);
79
+ ids.push(id);
80
+ console.log(` ${label}: ${id}`);
81
+ }
82
+ console.log('');
83
+ check('every session got an id', ids.every((i) => i.length > 0));
84
+ check('ids are unique across separate agent processes', new Set(ids).size === ids.length, `got ${JSON.stringify(ids)}`);
85
+ // The old scheme produced quick-1 / quick-1 / quick-1 here.
86
+ check('ids are not the old process-local counter form', !ids.every((i) => /^quick-\d+$/.test(i)) || new Set(ids).size === ids.length);
87
+ check('ids look like Quick thread ids (UUID)', ids.every((i) => /^[0-9a-f-]{36}$/i.test(i)));
88
+ console.log('');
89
+ if (failures === 0)
90
+ console.log('all session-id checks passed');
91
+ else {
92
+ console.log(`${failures} check(s) FAILED`);
93
+ process.exitCode = 1;
94
+ }
95
+ //# sourceMappingURL=session-id-test.js.map