@walkhi/code-relax 0.1.0-beta.30 → 0.1.0-beta.31
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/README.md +95 -89
- package/dist/bin/cleanup-accounts.mjs +63 -63
- package/dist/bin/codex-remote.mjs +374 -367
- package/dist/bin/manage-relay-admin.mjs +20 -20
- package/dist/bin/migrate-relay-db.mjs +109 -109
- package/dist/bin/publish-android-release.mjs +62 -58
- package/dist/bin/self-relay-admin.mjs +8 -8
- package/dist/bin/self-relay-demo.mjs +33 -33
- package/dist/bin/self-relay-server.mjs +66 -66
- package/dist/build-platform.json +1 -1
- package/dist/get-lan-networks.ps1 +40 -40
- package/dist/get-shared-service-url.ps1 +6 -6
- package/dist/shared/app-server-events.cjs +422 -412
- package/dist/shared/code-browser.cjs +159 -159
- package/dist/shared/file-changes.cjs +31 -31
- package/dist/shared/file-citations.cjs +117 -117
- package/dist/shared/file-mentions.cjs +92 -92
- package/dist/shared/message-delivery.cjs +54 -54
- package/dist/shared/p2p-data-channel.cjs +72 -72
- package/dist/shared/p2p-diagnostics.cjs +28 -28
- package/dist/shared/p2p-file-channel.cjs +74 -74
- package/dist/shared/plan-pricing.cjs +32 -32
- package/dist/shared/question-attention.cjs +40 -0
- package/dist/shared/server-requests.cjs +219 -219
- package/dist/shared/timeline-sync.cjs +173 -173
- package/dist/skills/code-relax/SKILL.md +22 -22
- package/dist/src/archived-threads.mjs +22 -0
- package/dist/src/background-process.mjs +18 -18
- package/dist/src/bounded-process-log.mjs +63 -63
- package/dist/src/celsius-client.mjs +107 -107
- package/dist/src/code-browser.mjs +100 -100
- package/dist/src/desktop-launcher.mjs +46 -46
- package/dist/src/dots-approval-timeline.mjs +99 -99
- package/dist/src/dots-avatar.mjs +42 -42
- package/dist/src/dots-chat-projection.mjs +50 -50
- package/dist/src/dots-chat-server.mjs +461 -461
- package/dist/src/dots-message-images.mjs +319 -319
- package/dist/src/dots-profile.mjs +77 -77
- package/dist/src/dots-room-activity.mjs +94 -94
- package/dist/src/dots-room-client.mjs +135 -135
- package/dist/src/dots-room-projection.mjs +94 -94
- package/dist/src/dots-schedules.mjs +66 -66
- package/dist/src/dots-summary-tasks.mjs +32 -32
- package/dist/src/dots-task-catalog.mjs +430 -430
- package/dist/src/dots-task-files.mjs +52 -52
- package/dist/src/execution-health.mjs +26 -26
- package/dist/src/file-transfer-range.mjs +22 -22
- package/dist/src/file-upload-session.mjs +130 -130
- package/dist/src/hosted-history-app-server.mjs +103 -103
- package/dist/src/hosted-history-cache.mjs +113 -113
- package/dist/src/lan-socket-server.mjs +265 -263
- package/dist/src/managed-app-server.mjs +244 -244
- package/dist/src/message-images.mjs +9 -9
- package/dist/src/message-upload-files.mjs +74 -74
- package/dist/src/onboarding.mjs +12 -12
- package/dist/src/plan-pricing.mjs +47 -47
- package/dist/src/platform/README.md +12 -12
- package/dist/src/platform/codex-protocol.mjs +46 -46
- package/dist/src/platform/codex-runtime.mjs +3 -3
- package/dist/src/platform/credential-store.mjs +3 -3
- package/dist/src/platform/desktop-host.mjs +3 -3
- package/dist/src/platform/desktop-project-registration.mjs +3 -3
- package/dist/src/platform/desktop-project-store.mjs +208 -149
- package/dist/src/platform/file-opener.mjs +9 -0
- package/dist/src/platform/linux/README.md +3 -3
- package/dist/src/platform/linux/codex-runtime.mjs +56 -0
- package/dist/src/platform/linux/credential-store.mjs +28 -0
- package/dist/src/platform/linux/desktop-host.mjs +83 -0
- package/dist/src/platform/linux/desktop-installation.mjs +36 -0
- package/dist/src/platform/linux/desktop-project-registration.mjs +11 -0
- package/dist/src/platform/linux/network-info.mjs +11 -0
- package/dist/src/platform/linux/process.mjs +42 -0
- package/dist/src/platform/linux/project-locations.mjs +17 -0
- package/dist/src/platform/linux/resident-startup.mjs +52 -0
- package/dist/src/platform/linux/retained-runtime.mjs +76 -0
- package/dist/src/platform/linux/service-host.mjs +18 -0
- package/dist/src/platform/linux/system.mjs +49 -0
- package/dist/src/platform/linux/user-environment.mjs +7 -0
- package/dist/src/platform/macos/README.md +3 -3
- package/dist/src/platform/macos/codex-runtime.mjs +125 -125
- package/dist/src/platform/macos/credential-store.mjs +10 -10
- package/dist/src/platform/macos/desktop-host.mjs +82 -82
- package/dist/src/platform/macos/desktop-project-registration.mjs +11 -10
- package/dist/src/platform/macos/network-info.mjs +8 -28
- package/dist/src/platform/macos/project-locations.mjs +8 -8
- package/dist/src/platform/macos/resident-startup.mjs +84 -84
- package/dist/src/platform/macos/retained-runtime.mjs +127 -127
- package/dist/src/platform/macos/service-host.mjs +18 -18
- package/dist/src/platform/macos/system.mjs +29 -29
- package/dist/src/platform/macos/user-environment.mjs +7 -7
- package/dist/src/platform/native-package.mjs +58 -46
- package/dist/src/platform/network-info.mjs +3 -3
- package/dist/src/platform/path-identity.mjs +5 -5
- package/dist/src/platform/posix/network-candidates.mjs +23 -0
- package/dist/src/platform/posix/runtime-paths.mjs +25 -25
- package/dist/src/platform/project-locations.mjs +3 -3
- package/dist/src/platform/runtime-paths.mjs +8 -8
- package/dist/src/platform/select.mjs +5 -5
- package/dist/src/platform/service-host.mjs +3 -3
- package/dist/src/platform/user-environment.mjs +3 -3
- package/dist/src/platform/windows/IsolatedProcess.cs +79 -79
- package/dist/src/platform/windows/activate-desktop.ps1 +48 -48
- package/dist/src/platform/windows/background-process.mjs +30 -30
- package/dist/src/platform/windows/codex-runtime.mjs +215 -215
- package/dist/src/platform/windows/credential-store.mjs +27 -27
- package/dist/src/platform/windows/credential-store.ps1 +49 -49
- package/dist/src/platform/windows/desktop-helper.mjs +179 -179
- package/dist/src/platform/windows/desktop-host.mjs +58 -58
- package/dist/src/platform/windows/desktop-info.ps1 +14 -14
- package/dist/src/platform/windows/desktop-project-registration.mjs +4 -4
- package/dist/src/platform/windows/desktop-runtime.ps1 +10 -10
- package/dist/src/platform/windows/desktop-shortcuts.ps1 +21 -21
- package/dist/src/platform/windows/dots-profile.mjs +49 -49
- package/dist/src/platform/windows/launch-worker.mjs +41 -41
- package/dist/src/platform/windows/network-info.mjs +34 -34
- package/dist/src/platform/windows/project-locations.mjs +16 -16
- package/dist/src/platform/windows/resident-start.js +20 -20
- package/dist/src/platform/windows/resident-start.ps1 +7 -7
- package/dist/src/platform/windows/resident-startup.ps1 +83 -83
- package/dist/src/platform/windows/resolve-state-root.ps1 +14 -14
- package/dist/src/platform/windows/runtime-paths.mjs +20 -20
- package/dist/src/platform/windows/rustdesk-video-probe.mjs +167 -167
- package/dist/src/platform/windows/service-host.mjs +31 -31
- package/dist/src/platform/windows/start-hidden-console.ps1 +49 -49
- package/dist/src/platform/windows/stop-desktop.ps1 +22 -22
- package/dist/src/platform/windows/user-environment.mjs +50 -50
- package/dist/src/platform/windows/user-environment.ps1 +41 -41
- package/dist/src/project-archive.mjs +30 -0
- package/dist/src/project-create.mjs +121 -119
- package/dist/src/project-management.mjs +59 -69
- package/dist/src/project-remove.mjs +55 -0
- package/dist/src/project-update.mjs +56 -0
- package/dist/src/runtime-discovery.mjs +47 -47
- package/dist/src/self-relay/account-cleanup.mjs +30 -30
- package/dist/src/self-relay/account-connections.mjs +52 -52
- package/dist/src/self-relay/admin-cloud.mjs +101 -101
- package/dist/src/self-relay/admin-page.mjs +80 -80
- package/dist/src/self-relay/admin-server.mjs +74 -74
- package/dist/src/self-relay/admin-state.mjs +127 -127
- package/dist/src/self-relay/admin-style.mjs +14 -14
- package/dist/src/self-relay/android-releases.mjs +61 -61
- package/dist/src/self-relay/client.mjs +61 -61
- package/dist/src/self-relay/connector.mjs +439 -438
- package/dist/src/self-relay/debug-allowlist.mjs +33 -33
- package/dist/src/self-relay/demo.mjs +37 -37
- package/dist/src/self-relay/device-info.mjs +27 -0
- package/dist/src/self-relay/device-store.mjs +92 -84
- package/dist/src/self-relay/diagnostics.mjs +54 -54
- package/dist/src/self-relay/email-accounts.mjs +183 -183
- package/dist/src/self-relay/file-wire.mjs +13 -13
- package/dist/src/self-relay/lan-authorizations.mjs +71 -42
- package/dist/src/self-relay/lifecycle.mjs +264 -250
- package/dist/src/self-relay/long-pairing.mjs +40 -40
- package/dist/src/self-relay/mysql-state.mjs +118 -105
- package/dist/src/self-relay/p2p-probe.mjs +159 -159
- package/dist/src/self-relay/privacy-page.mjs +26 -26
- package/dist/src/self-relay/public-releases.mjs +34 -0
- package/dist/src/self-relay/rtc-file-bridge.mjs +41 -41
- package/dist/src/self-relay/server.mjs +1006 -932
- package/dist/src/self-relay/usage-daily.mjs +55 -55
- package/dist/src/self-relay/usage-meter.mjs +141 -141
- package/dist/src/self-relay/windows-route-helper.mjs +75 -75
- package/dist/src/self-relay/wire.mjs +36 -36
- package/dist/src/server.mjs +1861 -1778
- package/dist/src/service-control.mjs +82 -82
- package/dist/src/service-doctor.mjs +110 -110
- package/dist/src/service-health.mjs +33 -33
- package/dist/src/service-install.mjs +91 -91
- package/dist/src/service-lifecycle.mjs +138 -138
- package/dist/src/service-restart.mjs +81 -81
- package/dist/src/shared-app-server.mjs +615 -611
- package/dist/src/shared-catalog.mjs +132 -132
- package/dist/src/shared-recovery.mjs +146 -146
- package/dist/src/shared-thread-stream.mjs +164 -164
- package/dist/src/skill-install.mjs +51 -51
- package/dist/src/thread-title-generation.mjs +150 -150
- package/dist/src/turn-model-history.mjs +47 -47
- package/dist/src/usage-reset.mjs +17 -17
- package/dist/src/workstation-downloads.mjs +120 -120
- package/dist/tools/rtc-route-helper.ps1 +99 -99
- package/dist/tools/start-rtc-route-helper.ps1 +15 -15
- package/dist/web/vendor/markdown-it.LICENSE.txt +22 -22
- package/dist/web/vendor/markdown-it.umd.min.js +13 -13
- package/package.json +7 -6
- package/tools/postinstall.mjs +127 -127
|
@@ -1,77 +1,77 @@
|
|
|
1
|
-
import http2 from 'node:http2';
|
|
2
|
-
|
|
3
|
-
const colors = new Set(['black', 'blue', 'green', 'orange', 'pink', 'purple', 'red', 'yellow']);
|
|
4
|
-
export function dotsProfile(profile) {
|
|
5
|
-
const name = typeof profile?.display_name === 'string' ? profile.display_name.trim() : '';
|
|
6
|
-
const pointer = profile?.avatar_manifest?.snapshot?.asset_pointer;
|
|
7
|
-
return { profileId: profile.id, activeRootThreadId: profile.active_root_thread_id || '',
|
|
8
|
-
messagingRoomId: typeof profile.messaging_room_id === 'string' ? profile.messaging_room_id : '',
|
|
9
|
-
name: name && !['O', 'o', 'Orbit', 'orbit', 'dot'].includes(name) ? name : 'Dots',
|
|
10
|
-
avatarFileId: typeof pointer === 'string' && /^sediment:\/\/file_[a-f0-9]+$/.test(pointer)
|
|
11
|
-
? pointer.slice('sediment://'.length) : '', color: colors.has(profile.color) ? profile.color : '' };
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// Desktop 26.930.7945.0 discovers roots through /tbo and its thread attachments.
|
|
15
|
-
// Hosted thread/list can omit every aeon root while thread/read still resolves it.
|
|
16
|
-
export async function readDotsCatalog(localServer, identity) {
|
|
17
|
-
const auth = await localServer.request('getAuthStatus', { includeToken: true, refreshToken: false });
|
|
18
|
-
const principal = JSON.parse(Buffer.from(auth.authToken.split('.')[1], 'base64url'))['https://api.openai.com/auth'];
|
|
19
|
-
if (!identity || principal?.chatgpt_account_id !== identity.accountId || principal.chatgpt_user_id !== identity.userId) {
|
|
20
|
-
throw new Error('点点账号已变化,请重新连接。');
|
|
21
|
-
}
|
|
22
|
-
const session = http2.connect('https://chatgpt.com');
|
|
23
|
-
session.on('error', () => {}); // Individual requests report the transport error.
|
|
24
|
-
try {
|
|
25
|
-
const get = route => new Promise((resolve, reject) => {
|
|
26
|
-
const request = session.request({ ':method': 'GET', ':path': `/backend-api${route}`,
|
|
27
|
-
authorization: `Bearer ${auth.authToken}`, 'chatgpt-account-id': identity.accountId,
|
|
28
|
-
'user-agent': 'Code-Relax/0.1.0', accept: 'application/json' });
|
|
29
|
-
let status, body = '', size = 0;
|
|
30
|
-
const timer = setTimeout(() => request.destroy(new Error('读取点点资料超时。')), 15000);
|
|
31
|
-
request.setEncoding('utf8');
|
|
32
|
-
request.on('response', headers => { status = headers[':status']; });
|
|
33
|
-
request.on('data', chunk => {
|
|
34
|
-
size += Buffer.byteLength(chunk);
|
|
35
|
-
if (size > 1024 * 1024) request.destroy(new Error('点点资料响应过大。'));
|
|
36
|
-
else body += chunk;
|
|
37
|
-
});
|
|
38
|
-
request.on('error', reject);
|
|
39
|
-
request.on('close', () => clearTimeout(timer));
|
|
40
|
-
request.on('end', () => {
|
|
41
|
-
try {
|
|
42
|
-
if (status !== 200) throw new Error(`读取点点目录失败(HTTP ${status})。`);
|
|
43
|
-
resolve(JSON.parse(body));
|
|
44
|
-
} catch (error) { reject(error); }
|
|
45
|
-
});
|
|
46
|
-
request.end();
|
|
47
|
-
});
|
|
48
|
-
const profiles = new Map(), rootThreadIds = new Set();
|
|
49
|
-
let cursor;
|
|
50
|
-
do {
|
|
51
|
-
const query = new URLSearchParams({ limit: '25', ...(cursor ? { cursor } : {}) });
|
|
52
|
-
const page = await get(`/tbo?${query}`);
|
|
53
|
-
for (const value of page.items) {
|
|
54
|
-
if (typeof value.id !== 'string' || !value.id
|
|
55
|
-
|| value.active_root_thread_id != null && typeof value.active_root_thread_id !== 'string') {
|
|
56
|
-
throw new Error('点点资料缺少有效身份。');
|
|
57
|
-
}
|
|
58
|
-
const profile = dotsProfile(value);
|
|
59
|
-
let threadCursor;
|
|
60
|
-
do {
|
|
61
|
-
const threadQuery = new URLSearchParams({ limit: '100', include_hidden: 'true',
|
|
62
|
-
...(threadCursor ? { cursor: threadCursor } : {}) });
|
|
63
|
-
const attachments = await get(`/tbo/${encodeURIComponent(value.id)}/threads?${threadQuery}`);
|
|
64
|
-
for (const attachment of attachments.items) {
|
|
65
|
-
const id = attachment.thread_id;
|
|
66
|
-
profiles.set(id, profile);
|
|
67
|
-
if (value.status !== 'deleting' && (!profile.activeRootThreadId || profile.activeRootThreadId === id)
|
|
68
|
-
&& (attachment.parent_thread_id === null || attachment.parent_thread_id === id)) rootThreadIds.add(id);
|
|
69
|
-
}
|
|
70
|
-
threadCursor = attachments.cursor;
|
|
71
|
-
} while (threadCursor);
|
|
72
|
-
}
|
|
73
|
-
cursor = page.cursor;
|
|
74
|
-
} while (cursor);
|
|
75
|
-
return { profiles, rootThreadIds };
|
|
76
|
-
} finally { session.destroy(); }
|
|
77
|
-
}
|
|
1
|
+
import http2 from 'node:http2';
|
|
2
|
+
|
|
3
|
+
const colors = new Set(['black', 'blue', 'green', 'orange', 'pink', 'purple', 'red', 'yellow']);
|
|
4
|
+
export function dotsProfile(profile) {
|
|
5
|
+
const name = typeof profile?.display_name === 'string' ? profile.display_name.trim() : '';
|
|
6
|
+
const pointer = profile?.avatar_manifest?.snapshot?.asset_pointer;
|
|
7
|
+
return { profileId: profile.id, activeRootThreadId: profile.active_root_thread_id || '',
|
|
8
|
+
messagingRoomId: typeof profile.messaging_room_id === 'string' ? profile.messaging_room_id : '',
|
|
9
|
+
name: name && !['O', 'o', 'Orbit', 'orbit', 'dot'].includes(name) ? name : 'Dots',
|
|
10
|
+
avatarFileId: typeof pointer === 'string' && /^sediment:\/\/file_[a-f0-9]+$/.test(pointer)
|
|
11
|
+
? pointer.slice('sediment://'.length) : '', color: colors.has(profile.color) ? profile.color : '' };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Desktop 26.930.7945.0 discovers roots through /tbo and its thread attachments.
|
|
15
|
+
// Hosted thread/list can omit every aeon root while thread/read still resolves it.
|
|
16
|
+
export async function readDotsCatalog(localServer, identity) {
|
|
17
|
+
const auth = await localServer.request('getAuthStatus', { includeToken: true, refreshToken: false });
|
|
18
|
+
const principal = JSON.parse(Buffer.from(auth.authToken.split('.')[1], 'base64url'))['https://api.openai.com/auth'];
|
|
19
|
+
if (!identity || principal?.chatgpt_account_id !== identity.accountId || principal.chatgpt_user_id !== identity.userId) {
|
|
20
|
+
throw new Error('点点账号已变化,请重新连接。');
|
|
21
|
+
}
|
|
22
|
+
const session = http2.connect('https://chatgpt.com');
|
|
23
|
+
session.on('error', () => {}); // Individual requests report the transport error.
|
|
24
|
+
try {
|
|
25
|
+
const get = route => new Promise((resolve, reject) => {
|
|
26
|
+
const request = session.request({ ':method': 'GET', ':path': `/backend-api${route}`,
|
|
27
|
+
authorization: `Bearer ${auth.authToken}`, 'chatgpt-account-id': identity.accountId,
|
|
28
|
+
'user-agent': 'Code-Relax/0.1.0', accept: 'application/json' });
|
|
29
|
+
let status, body = '', size = 0;
|
|
30
|
+
const timer = setTimeout(() => request.destroy(new Error('读取点点资料超时。')), 15000);
|
|
31
|
+
request.setEncoding('utf8');
|
|
32
|
+
request.on('response', headers => { status = headers[':status']; });
|
|
33
|
+
request.on('data', chunk => {
|
|
34
|
+
size += Buffer.byteLength(chunk);
|
|
35
|
+
if (size > 1024 * 1024) request.destroy(new Error('点点资料响应过大。'));
|
|
36
|
+
else body += chunk;
|
|
37
|
+
});
|
|
38
|
+
request.on('error', reject);
|
|
39
|
+
request.on('close', () => clearTimeout(timer));
|
|
40
|
+
request.on('end', () => {
|
|
41
|
+
try {
|
|
42
|
+
if (status !== 200) throw new Error(`读取点点目录失败(HTTP ${status})。`);
|
|
43
|
+
resolve(JSON.parse(body));
|
|
44
|
+
} catch (error) { reject(error); }
|
|
45
|
+
});
|
|
46
|
+
request.end();
|
|
47
|
+
});
|
|
48
|
+
const profiles = new Map(), rootThreadIds = new Set();
|
|
49
|
+
let cursor;
|
|
50
|
+
do {
|
|
51
|
+
const query = new URLSearchParams({ limit: '25', ...(cursor ? { cursor } : {}) });
|
|
52
|
+
const page = await get(`/tbo?${query}`);
|
|
53
|
+
for (const value of page.items) {
|
|
54
|
+
if (typeof value.id !== 'string' || !value.id
|
|
55
|
+
|| value.active_root_thread_id != null && typeof value.active_root_thread_id !== 'string') {
|
|
56
|
+
throw new Error('点点资料缺少有效身份。');
|
|
57
|
+
}
|
|
58
|
+
const profile = dotsProfile(value);
|
|
59
|
+
let threadCursor;
|
|
60
|
+
do {
|
|
61
|
+
const threadQuery = new URLSearchParams({ limit: '100', include_hidden: 'true',
|
|
62
|
+
...(threadCursor ? { cursor: threadCursor } : {}) });
|
|
63
|
+
const attachments = await get(`/tbo/${encodeURIComponent(value.id)}/threads?${threadQuery}`);
|
|
64
|
+
for (const attachment of attachments.items) {
|
|
65
|
+
const id = attachment.thread_id;
|
|
66
|
+
profiles.set(id, profile);
|
|
67
|
+
if (value.status !== 'deleting' && (!profile.activeRootThreadId || profile.activeRootThreadId === id)
|
|
68
|
+
&& (attachment.parent_thread_id === null || attachment.parent_thread_id === id)) rootThreadIds.add(id);
|
|
69
|
+
}
|
|
70
|
+
threadCursor = attachments.cursor;
|
|
71
|
+
} while (threadCursor);
|
|
72
|
+
}
|
|
73
|
+
cursor = page.cursor;
|
|
74
|
+
} while (cursor);
|
|
75
|
+
return { profiles, rootThreadIds };
|
|
76
|
+
} finally { session.destroy(); }
|
|
77
|
+
}
|
|
@@ -1,94 +1,94 @@
|
|
|
1
|
-
import { EventEmitter } from 'node:events';
|
|
2
|
-
|
|
3
|
-
// Desktop's room-live SSE owns the watch; Celsius carries its revisioned state.
|
|
4
|
-
export class DotsRoomActivity extends EventEmitter {
|
|
5
|
-
constructor(server) {
|
|
6
|
-
super(); this.server = server; this.watches = new Map();
|
|
7
|
-
this.message = (topic, event) => {
|
|
8
|
-
if (event?.type !== 'calpico-room-live') return;
|
|
9
|
-
for (const watch of this.watches.values()) {
|
|
10
|
-
const value = event.payload;
|
|
11
|
-
if (watch.topic !== topic || watch.roomId !== value?.room_id || value.version !== 1) continue;
|
|
12
|
-
if (!watch.subscriptionId) {
|
|
13
|
-
if (watch.pending.size >= 4) watch.pending.delete(watch.pending.keys().next().value);
|
|
14
|
-
const old = watch.pending.get(value.subscription_id);
|
|
15
|
-
if (!old || value.revision > old.revision) watch.pending.set(value.subscription_id, value);
|
|
16
|
-
} else this.apply(watch, value);
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
server.rooms.on('message', this.message);
|
|
20
|
-
}
|
|
21
|
-
acquire(threadId, listener) {
|
|
22
|
-
let watch = this.watches.get(threadId);
|
|
23
|
-
if (!watch) {
|
|
24
|
-
watch = { threadId, listeners: new Set(), activity: null, generation: 0, attempts: 0 };
|
|
25
|
-
this.watches.set(threadId, watch);
|
|
26
|
-
}
|
|
27
|
-
watch.listeners.add(listener); listener({ threadId, activity: watch.activity });
|
|
28
|
-
if (!watch.controller && !watch.timer) void this.start(watch);
|
|
29
|
-
let released = false;
|
|
30
|
-
return () => {
|
|
31
|
-
if (released) return; released = true; watch.listeners.delete(listener);
|
|
32
|
-
if (!watch.listeners.size) { this.watches.delete(threadId); this.stop(watch); }
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
publish(watch, activity) {
|
|
36
|
-
if (JSON.stringify(watch.activity) === JSON.stringify(activity)) return;
|
|
37
|
-
watch.activity = activity;
|
|
38
|
-
for (const listener of watch.listeners) listener({ threadId: watch.threadId, activity });
|
|
39
|
-
}
|
|
40
|
-
apply(watch, value) {
|
|
41
|
-
if (value.subscription_id !== watch.subscriptionId || !Number.isSafeInteger(value.revision) || value.revision <= watch.revision) return;
|
|
42
|
-
watch.revision = value.revision;
|
|
43
|
-
if (value.type === 'calpico-room-live-error') {
|
|
44
|
-
this.fail(watch, new Error('点点活动暂不可用。'), value.code === 'temporarily_unavailable'); return;
|
|
45
|
-
}
|
|
46
|
-
if (value.type !== 'calpico-room-live-state' || !Array.isArray(value.threads)) return;
|
|
47
|
-
const current = value.threads[0];
|
|
48
|
-
if (current?.stream_state !== 'attached' || current.turn_status !== 'in_progress') { this.publish(watch, null); return; }
|
|
49
|
-
watch.attempts = 0;
|
|
50
|
-
const label = current.activity_status?.status_label;
|
|
51
|
-
this.publish(watch, { kind: 'thinking', label: typeof label === 'string' && label.trim() ? label : '正在思考…' });
|
|
52
|
-
}
|
|
53
|
-
async start(watch) {
|
|
54
|
-
const generation = ++watch.generation, controller = new AbortController();
|
|
55
|
-
watch.controller = controller; watch.pending = new Map(); watch.subscriptionId = null; watch.revision = -1;
|
|
56
|
-
const current = () => this.watches.get(watch.threadId) === watch && generation === watch.generation && !controller.signal.aborted;
|
|
57
|
-
try {
|
|
58
|
-
await this.server.connect();
|
|
59
|
-
const room = this.server.bindings.get(watch.threadId) || await this.server.room(watch.threadId);
|
|
60
|
-
if (!current()) return;
|
|
61
|
-
watch.roomId = room.id; watch.topic = `calpico-room-live:${room.id}`;
|
|
62
|
-
await this.server.rooms.subscribe(watch.topic);
|
|
63
|
-
if (!current()) { if (!this.watches.has(watch.threadId)) await this.server.rooms.unsubscribe(watch.topic); return; }
|
|
64
|
-
await this.server.rooms.request(`/messaging/rooms/${encodeURIComponent(room.id)}/live`, {
|
|
65
|
-
method: 'POST', signal: controller.signal, onEvent: value => {
|
|
66
|
-
if (!current()) return;
|
|
67
|
-
if (value?.type !== 'calpico-room-live-ready' || value.version !== 1 || value.room_id !== room.id
|
|
68
|
-
|| typeof value.subscription_id !== 'string' || watch.subscriptionId && watch.subscriptionId !== value.subscription_id) {
|
|
69
|
-
throw new Error('点点活动订阅身份无效。');
|
|
70
|
-
}
|
|
71
|
-
watch.subscriptionId = value.subscription_id;
|
|
72
|
-
const pending = watch.pending.get(value.subscription_id); watch.pending.clear();
|
|
73
|
-
if (pending) this.apply(watch, pending);
|
|
74
|
-
},
|
|
75
|
-
});
|
|
76
|
-
if (current()) this.fail(watch, new Error('点点活动连接已结束。'), true);
|
|
77
|
-
} catch (error) { if (current()) this.fail(watch, error, ![401, 403, 404].includes(error.status)); }
|
|
78
|
-
}
|
|
79
|
-
fail(watch, error, retry) {
|
|
80
|
-
this.stop(watch); this.emit('unavailable', error);
|
|
81
|
-
if (retry && watch.listeners.size && this.server.ready && watch.attempts < 5) {
|
|
82
|
-
watch.timer = setTimeout(() => { watch.timer = null; void this.start(watch); }, Math.min(30000, 1000 * 2 ** watch.attempts++));
|
|
83
|
-
watch.timer.unref();
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
stop(watch) {
|
|
87
|
-
watch.generation++; clearTimeout(watch.timer); watch.timer = null;
|
|
88
|
-
watch.controller?.abort(); watch.controller = null; watch.pending?.clear(); this.publish(watch, null);
|
|
89
|
-
// The SSE cancellation ends the server watch. The shared topic remains
|
|
90
|
-
// subscribed while this account socket lives, avoiding unsubscribe races.
|
|
91
|
-
}
|
|
92
|
-
close() { for (const watch of this.watches.values()) this.stop(watch); this.watches.clear(); }
|
|
93
|
-
dispose() { this.close(); this.server.rooms.off('message', this.message); }
|
|
94
|
-
}
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
|
|
3
|
+
// Desktop's room-live SSE owns the watch; Celsius carries its revisioned state.
|
|
4
|
+
export class DotsRoomActivity extends EventEmitter {
|
|
5
|
+
constructor(server) {
|
|
6
|
+
super(); this.server = server; this.watches = new Map();
|
|
7
|
+
this.message = (topic, event) => {
|
|
8
|
+
if (event?.type !== 'calpico-room-live') return;
|
|
9
|
+
for (const watch of this.watches.values()) {
|
|
10
|
+
const value = event.payload;
|
|
11
|
+
if (watch.topic !== topic || watch.roomId !== value?.room_id || value.version !== 1) continue;
|
|
12
|
+
if (!watch.subscriptionId) {
|
|
13
|
+
if (watch.pending.size >= 4) watch.pending.delete(watch.pending.keys().next().value);
|
|
14
|
+
const old = watch.pending.get(value.subscription_id);
|
|
15
|
+
if (!old || value.revision > old.revision) watch.pending.set(value.subscription_id, value);
|
|
16
|
+
} else this.apply(watch, value);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
server.rooms.on('message', this.message);
|
|
20
|
+
}
|
|
21
|
+
acquire(threadId, listener) {
|
|
22
|
+
let watch = this.watches.get(threadId);
|
|
23
|
+
if (!watch) {
|
|
24
|
+
watch = { threadId, listeners: new Set(), activity: null, generation: 0, attempts: 0 };
|
|
25
|
+
this.watches.set(threadId, watch);
|
|
26
|
+
}
|
|
27
|
+
watch.listeners.add(listener); listener({ threadId, activity: watch.activity });
|
|
28
|
+
if (!watch.controller && !watch.timer) void this.start(watch);
|
|
29
|
+
let released = false;
|
|
30
|
+
return () => {
|
|
31
|
+
if (released) return; released = true; watch.listeners.delete(listener);
|
|
32
|
+
if (!watch.listeners.size) { this.watches.delete(threadId); this.stop(watch); }
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
publish(watch, activity) {
|
|
36
|
+
if (JSON.stringify(watch.activity) === JSON.stringify(activity)) return;
|
|
37
|
+
watch.activity = activity;
|
|
38
|
+
for (const listener of watch.listeners) listener({ threadId: watch.threadId, activity });
|
|
39
|
+
}
|
|
40
|
+
apply(watch, value) {
|
|
41
|
+
if (value.subscription_id !== watch.subscriptionId || !Number.isSafeInteger(value.revision) || value.revision <= watch.revision) return;
|
|
42
|
+
watch.revision = value.revision;
|
|
43
|
+
if (value.type === 'calpico-room-live-error') {
|
|
44
|
+
this.fail(watch, new Error('点点活动暂不可用。'), value.code === 'temporarily_unavailable'); return;
|
|
45
|
+
}
|
|
46
|
+
if (value.type !== 'calpico-room-live-state' || !Array.isArray(value.threads)) return;
|
|
47
|
+
const current = value.threads[0];
|
|
48
|
+
if (current?.stream_state !== 'attached' || current.turn_status !== 'in_progress') { this.publish(watch, null); return; }
|
|
49
|
+
watch.attempts = 0;
|
|
50
|
+
const label = current.activity_status?.status_label;
|
|
51
|
+
this.publish(watch, { kind: 'thinking', label: typeof label === 'string' && label.trim() ? label : '正在思考…' });
|
|
52
|
+
}
|
|
53
|
+
async start(watch) {
|
|
54
|
+
const generation = ++watch.generation, controller = new AbortController();
|
|
55
|
+
watch.controller = controller; watch.pending = new Map(); watch.subscriptionId = null; watch.revision = -1;
|
|
56
|
+
const current = () => this.watches.get(watch.threadId) === watch && generation === watch.generation && !controller.signal.aborted;
|
|
57
|
+
try {
|
|
58
|
+
await this.server.connect();
|
|
59
|
+
const room = this.server.bindings.get(watch.threadId) || await this.server.room(watch.threadId);
|
|
60
|
+
if (!current()) return;
|
|
61
|
+
watch.roomId = room.id; watch.topic = `calpico-room-live:${room.id}`;
|
|
62
|
+
await this.server.rooms.subscribe(watch.topic);
|
|
63
|
+
if (!current()) { if (!this.watches.has(watch.threadId)) await this.server.rooms.unsubscribe(watch.topic); return; }
|
|
64
|
+
await this.server.rooms.request(`/messaging/rooms/${encodeURIComponent(room.id)}/live`, {
|
|
65
|
+
method: 'POST', signal: controller.signal, onEvent: value => {
|
|
66
|
+
if (!current()) return;
|
|
67
|
+
if (value?.type !== 'calpico-room-live-ready' || value.version !== 1 || value.room_id !== room.id
|
|
68
|
+
|| typeof value.subscription_id !== 'string' || watch.subscriptionId && watch.subscriptionId !== value.subscription_id) {
|
|
69
|
+
throw new Error('点点活动订阅身份无效。');
|
|
70
|
+
}
|
|
71
|
+
watch.subscriptionId = value.subscription_id;
|
|
72
|
+
const pending = watch.pending.get(value.subscription_id); watch.pending.clear();
|
|
73
|
+
if (pending) this.apply(watch, pending);
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
if (current()) this.fail(watch, new Error('点点活动连接已结束。'), true);
|
|
77
|
+
} catch (error) { if (current()) this.fail(watch, error, ![401, 403, 404].includes(error.status)); }
|
|
78
|
+
}
|
|
79
|
+
fail(watch, error, retry) {
|
|
80
|
+
this.stop(watch); this.emit('unavailable', error);
|
|
81
|
+
if (retry && watch.listeners.size && this.server.ready && watch.attempts < 5) {
|
|
82
|
+
watch.timer = setTimeout(() => { watch.timer = null; void this.start(watch); }, Math.min(30000, 1000 * 2 ** watch.attempts++));
|
|
83
|
+
watch.timer.unref();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
stop(watch) {
|
|
87
|
+
watch.generation++; clearTimeout(watch.timer); watch.timer = null;
|
|
88
|
+
watch.controller?.abort(); watch.controller = null; watch.pending?.clear(); this.publish(watch, null);
|
|
89
|
+
// The SSE cancellation ends the server watch. The shared topic remains
|
|
90
|
+
// subscribed while this account socket lives, avoiding unsubscribe races.
|
|
91
|
+
}
|
|
92
|
+
close() { for (const watch of this.watches.values()) this.stop(watch); this.watches.clear(); }
|
|
93
|
+
dispose() { this.close(); this.server.rooms.off('message', this.message); }
|
|
94
|
+
}
|
|
@@ -1,135 +1,135 @@
|
|
|
1
|
-
import http2 from 'node:http2';
|
|
2
|
-
import { CelsiusClient } from './celsius-client.mjs';
|
|
3
|
-
|
|
4
|
-
const topic = 'calpico-chatgpt-messaging';
|
|
5
|
-
const identityKey = identity => JSON.stringify([identity?.accountId, identity?.userId]);
|
|
6
|
-
|
|
7
|
-
// Desktop 26.1002.7124.0: the DM API and Celsius share the kernel account,
|
|
8
|
-
// but are independent of the hosted execution socket. Never replay a POST.
|
|
9
|
-
export class DotsRoomClient extends CelsiusClient {
|
|
10
|
-
constructor(transport) {
|
|
11
|
-
super({ topics: [topic] }); this.transport = transport;
|
|
12
|
-
this.getConnection = () => this.request('/celsius/ws/user');
|
|
13
|
-
this.controllers = new Set(); this.routes = new Map();
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
async authorization() {
|
|
17
|
-
const identity = this.transport.profileIdentity, generation = this.generation;
|
|
18
|
-
const auth = await this.transport.localServer.request('getAuthStatus', { includeToken: true, refreshToken: false });
|
|
19
|
-
const principal = auth.authToken && JSON.parse(Buffer.from(auth.authToken.split('.')[1], 'base64url'))['https://api.openai.com/auth'];
|
|
20
|
-
if (!identity?.accountId || principal?.chatgpt_account_id !== identity.accountId
|
|
21
|
-
|| principal.chatgpt_user_id !== identity.userId || generation !== this.generation
|
|
22
|
-
|| identityKey(identity) !== identityKey(this.transport.profileIdentity)) throw new Error('点点账号已变化,请重新连接。');
|
|
23
|
-
return { identity, generation, headers: { authorization: `Bearer ${auth.authToken}`,
|
|
24
|
-
'chatgpt-account-id': identity.accountId, 'user-agent': 'Code-Relax/0.1.0' } };
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
async request(route, { method = 'GET', body, contentType, signal, onEvent, rawResponse = false } = {}) {
|
|
28
|
-
const auth = await this.authorization();
|
|
29
|
-
const controller = new AbortController(); this.controllers.add(controller);
|
|
30
|
-
const cancelled = () => controller.abort(signal.reason);
|
|
31
|
-
signal?.addEventListener('abort', cancelled, { once: true });
|
|
32
|
-
if (signal?.aborted) cancelled();
|
|
33
|
-
let sent = false, status, timer;
|
|
34
|
-
try {
|
|
35
|
-
return await new Promise((resolve, reject) => {
|
|
36
|
-
const session = http2.connect('https://chatgpt.com');
|
|
37
|
-
let request, settled = false, bytes = 0, text = '';
|
|
38
|
-
const current = () => auth.generation === this.generation
|
|
39
|
-
&& identityKey(auth.identity) === identityKey(this.transport.profileIdentity);
|
|
40
|
-
const finish = (error, value) => {
|
|
41
|
-
if (settled) return; settled = true;
|
|
42
|
-
clearTimeout(timer); controller.signal.removeEventListener('abort', abort);
|
|
43
|
-
request?.destroy(); session.destroy();
|
|
44
|
-
if (error) {
|
|
45
|
-
if (method !== 'GET' && !onEvent) error.deliveryUnknown = sent && !(status >= 400 && status < 500 && status !== 408);
|
|
46
|
-
reject(error);
|
|
47
|
-
} else resolve(value);
|
|
48
|
-
};
|
|
49
|
-
const abort = () => finish(controller.signal.reason || new Error('点点请求已取消。'));
|
|
50
|
-
controller.signal.addEventListener('abort', abort, { once: true });
|
|
51
|
-
session.on('error', error => finish(error));
|
|
52
|
-
if (controller.signal.aborted) { abort(); return; }
|
|
53
|
-
const roomRoute = /^\/messaging\/rooms\/([^/]+)\/messages$/.exec(route)?.[1];
|
|
54
|
-
request = session.request({ ':method': method, ':path': `/backend-api${route}`, ...auth.headers,
|
|
55
|
-
accept: onEvent ? 'text/event-stream' : 'application/json',
|
|
56
|
-
...(body != null ? { 'content-type': contentType || 'application/json' } : {}),
|
|
57
|
-
...(roomRoute && this.routes.has(roomRoute) ? { 'x-openai-thread-route': this.routes.get(roomRoute) } : {}) });
|
|
58
|
-
timer = setTimeout(() => finish(new Error('点点请求超时,请重新核对状态。')), 30000);
|
|
59
|
-
request.setEncoding('utf8');
|
|
60
|
-
request.on('response', headers => {
|
|
61
|
-
status = headers[':status'];
|
|
62
|
-
if (roomRoute && typeof headers['x-openai-thread-route'] === 'string' && headers['x-openai-thread-route'].length <= 1024 && current()) this.routes.set(roomRoute, headers['x-openai-thread-route']);
|
|
63
|
-
if (status < 200 || status >= 300) {
|
|
64
|
-
console.error(JSON.stringify({ event: 'dots-room-request', method, status, route: route.split('?')[0] }));
|
|
65
|
-
const message = status === 401 ? '点点登录状态需要恢复,请重新连接。'
|
|
66
|
-
: status === 403 || status === 404 ? '点点消息暂不可用,请稍后重新同步。'
|
|
67
|
-
: status === 429 ? '点点暂时繁忙,请稍后再试。' : '点点请求尚未完成,请稍后核对。';
|
|
68
|
-
finish(Object.assign(new Error(message), { status }));
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
request.on('data', chunk => {
|
|
72
|
-
if (!current()) { finish(new Error('点点账号已变化,请重新连接。')); return; }
|
|
73
|
-
bytes += Buffer.byteLength(chunk); text += chunk;
|
|
74
|
-
if (onEvent) {
|
|
75
|
-
text = text.replace(/\r\n/g, '\n');
|
|
76
|
-
let end;
|
|
77
|
-
while ((end = text.indexOf('\n\n')) >= 0) {
|
|
78
|
-
const frame = text.slice(0, end); text = text.slice(end + 2);
|
|
79
|
-
const data = frame.split('\n').filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');
|
|
80
|
-
if (data) try { onEvent(JSON.parse(data)); clearTimeout(timer); } catch (error) { finish(error); return; }
|
|
81
|
-
}
|
|
82
|
-
bytes = Buffer.byteLength(text);
|
|
83
|
-
}
|
|
84
|
-
if (bytes > 8 * 1024 * 1024) finish(new Error('点点响应超出单次读取上限。'));
|
|
85
|
-
});
|
|
86
|
-
request.on('error', error => finish(error));
|
|
87
|
-
request.on('end', () => {
|
|
88
|
-
if (!current()) { finish(new Error('点点账号已变化,请重新连接。')); return; }
|
|
89
|
-
try { finish(null, onEvent ? null : rawResponse ? text : text ? JSON.parse(text) : null); } catch (error) { finish(error); }
|
|
90
|
-
});
|
|
91
|
-
request.on('close', () => { if (!settled) finish(new Error('点点请求连接已断开。')); });
|
|
92
|
-
// end() can queue data before TLS connects. Only a ready HTTP/2 stream
|
|
93
|
-
// has been assigned an ID and may have submitted the request.
|
|
94
|
-
sent = !request.pending;
|
|
95
|
-
request.once('ready', () => { sent = true; });
|
|
96
|
-
request.end(body == null ? undefined : Buffer.isBuffer(body) ? body : JSON.stringify(body));
|
|
97
|
-
});
|
|
98
|
-
} finally { this.controllers.delete(controller); signal?.removeEventListener('abort', cancelled); }
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
async roomId(threadId) {
|
|
102
|
-
let profile = this.transport.liveProfiles.get(threadId);
|
|
103
|
-
if (!profile?.messagingRoomId) {
|
|
104
|
-
const value = await this.request(`/tbo/by-thread/${encodeURIComponent(threadId)}`);
|
|
105
|
-
profile = { messagingRoomId: value?.messaging_room_id };
|
|
106
|
-
}
|
|
107
|
-
if (typeof profile.messagingRoomId !== 'string' || !profile.messagingRoomId) throw new Error('点点消息房间暂不可用。');
|
|
108
|
-
return profile.messagingRoomId;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
async room(id) {
|
|
112
|
-
const room = await this.request(`/messaging/rooms/${encodeURIComponent(id)}`);
|
|
113
|
-
if (room?.id !== id || room.type !== 'DM' || room.app_source !== 'chatgpt:messaging' || !Array.isArray(room.members)) {
|
|
114
|
-
throw new Error('点点消息房间身份不匹配。');
|
|
115
|
-
}
|
|
116
|
-
return room;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
async messages(roomId, { before, after, around, limit = 20 } = {}) {
|
|
120
|
-
const query = new URLSearchParams({ limit: String(limit), ...(before ? { before } : {}),
|
|
121
|
-
...(after ? { after } : {}), ...(around ? { around } : {}) });
|
|
122
|
-
const page = await this.request(`/messaging/rooms/${encodeURIComponent(roomId)}/messages?${query}`);
|
|
123
|
-
if (!Array.isArray(page?.items) || page.items.some(message => typeof message.id !== 'string' || !message.id)) throw new Error('点点消息页格式无效。');
|
|
124
|
-
// Null prev_cursor is also returned for nonempty middle pages. Desktop uses
|
|
125
|
-
// the first message ID; only an empty page proves that history is exhausted.
|
|
126
|
-
return { items: page.items, before: page.prev_cursor ?? page.items[0]?.id ?? null,
|
|
127
|
-
after: page.next_cursor ?? (after && page.items.length >= limit ? page.items.at(-1)?.id : null) };
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
close() {
|
|
131
|
-
super.close();
|
|
132
|
-
for (const controller of this.controllers) controller.abort(new Error('点点连接已结束。'));
|
|
133
|
-
this.controllers.clear(); this.routes.clear();
|
|
134
|
-
}
|
|
135
|
-
}
|
|
1
|
+
import http2 from 'node:http2';
|
|
2
|
+
import { CelsiusClient } from './celsius-client.mjs';
|
|
3
|
+
|
|
4
|
+
const topic = 'calpico-chatgpt-messaging';
|
|
5
|
+
const identityKey = identity => JSON.stringify([identity?.accountId, identity?.userId]);
|
|
6
|
+
|
|
7
|
+
// Desktop 26.1002.7124.0: the DM API and Celsius share the kernel account,
|
|
8
|
+
// but are independent of the hosted execution socket. Never replay a POST.
|
|
9
|
+
export class DotsRoomClient extends CelsiusClient {
|
|
10
|
+
constructor(transport) {
|
|
11
|
+
super({ topics: [topic] }); this.transport = transport;
|
|
12
|
+
this.getConnection = () => this.request('/celsius/ws/user');
|
|
13
|
+
this.controllers = new Set(); this.routes = new Map();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async authorization() {
|
|
17
|
+
const identity = this.transport.profileIdentity, generation = this.generation;
|
|
18
|
+
const auth = await this.transport.localServer.request('getAuthStatus', { includeToken: true, refreshToken: false });
|
|
19
|
+
const principal = auth.authToken && JSON.parse(Buffer.from(auth.authToken.split('.')[1], 'base64url'))['https://api.openai.com/auth'];
|
|
20
|
+
if (!identity?.accountId || principal?.chatgpt_account_id !== identity.accountId
|
|
21
|
+
|| principal.chatgpt_user_id !== identity.userId || generation !== this.generation
|
|
22
|
+
|| identityKey(identity) !== identityKey(this.transport.profileIdentity)) throw new Error('点点账号已变化,请重新连接。');
|
|
23
|
+
return { identity, generation, headers: { authorization: `Bearer ${auth.authToken}`,
|
|
24
|
+
'chatgpt-account-id': identity.accountId, 'user-agent': 'Code-Relax/0.1.0' } };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async request(route, { method = 'GET', body, contentType, signal, onEvent, rawResponse = false } = {}) {
|
|
28
|
+
const auth = await this.authorization();
|
|
29
|
+
const controller = new AbortController(); this.controllers.add(controller);
|
|
30
|
+
const cancelled = () => controller.abort(signal.reason);
|
|
31
|
+
signal?.addEventListener('abort', cancelled, { once: true });
|
|
32
|
+
if (signal?.aborted) cancelled();
|
|
33
|
+
let sent = false, status, timer;
|
|
34
|
+
try {
|
|
35
|
+
return await new Promise((resolve, reject) => {
|
|
36
|
+
const session = http2.connect('https://chatgpt.com');
|
|
37
|
+
let request, settled = false, bytes = 0, text = '';
|
|
38
|
+
const current = () => auth.generation === this.generation
|
|
39
|
+
&& identityKey(auth.identity) === identityKey(this.transport.profileIdentity);
|
|
40
|
+
const finish = (error, value) => {
|
|
41
|
+
if (settled) return; settled = true;
|
|
42
|
+
clearTimeout(timer); controller.signal.removeEventListener('abort', abort);
|
|
43
|
+
request?.destroy(); session.destroy();
|
|
44
|
+
if (error) {
|
|
45
|
+
if (method !== 'GET' && !onEvent) error.deliveryUnknown = sent && !(status >= 400 && status < 500 && status !== 408);
|
|
46
|
+
reject(error);
|
|
47
|
+
} else resolve(value);
|
|
48
|
+
};
|
|
49
|
+
const abort = () => finish(controller.signal.reason || new Error('点点请求已取消。'));
|
|
50
|
+
controller.signal.addEventListener('abort', abort, { once: true });
|
|
51
|
+
session.on('error', error => finish(error));
|
|
52
|
+
if (controller.signal.aborted) { abort(); return; }
|
|
53
|
+
const roomRoute = /^\/messaging\/rooms\/([^/]+)\/messages$/.exec(route)?.[1];
|
|
54
|
+
request = session.request({ ':method': method, ':path': `/backend-api${route}`, ...auth.headers,
|
|
55
|
+
accept: onEvent ? 'text/event-stream' : 'application/json',
|
|
56
|
+
...(body != null ? { 'content-type': contentType || 'application/json' } : {}),
|
|
57
|
+
...(roomRoute && this.routes.has(roomRoute) ? { 'x-openai-thread-route': this.routes.get(roomRoute) } : {}) });
|
|
58
|
+
timer = setTimeout(() => finish(new Error('点点请求超时,请重新核对状态。')), 30000);
|
|
59
|
+
request.setEncoding('utf8');
|
|
60
|
+
request.on('response', headers => {
|
|
61
|
+
status = headers[':status'];
|
|
62
|
+
if (roomRoute && typeof headers['x-openai-thread-route'] === 'string' && headers['x-openai-thread-route'].length <= 1024 && current()) this.routes.set(roomRoute, headers['x-openai-thread-route']);
|
|
63
|
+
if (status < 200 || status >= 300) {
|
|
64
|
+
console.error(JSON.stringify({ event: 'dots-room-request', method, status, route: route.split('?')[0] }));
|
|
65
|
+
const message = status === 401 ? '点点登录状态需要恢复,请重新连接。'
|
|
66
|
+
: status === 403 || status === 404 ? '点点消息暂不可用,请稍后重新同步。'
|
|
67
|
+
: status === 429 ? '点点暂时繁忙,请稍后再试。' : '点点请求尚未完成,请稍后核对。';
|
|
68
|
+
finish(Object.assign(new Error(message), { status }));
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
request.on('data', chunk => {
|
|
72
|
+
if (!current()) { finish(new Error('点点账号已变化,请重新连接。')); return; }
|
|
73
|
+
bytes += Buffer.byteLength(chunk); text += chunk;
|
|
74
|
+
if (onEvent) {
|
|
75
|
+
text = text.replace(/\r\n/g, '\n');
|
|
76
|
+
let end;
|
|
77
|
+
while ((end = text.indexOf('\n\n')) >= 0) {
|
|
78
|
+
const frame = text.slice(0, end); text = text.slice(end + 2);
|
|
79
|
+
const data = frame.split('\n').filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');
|
|
80
|
+
if (data) try { onEvent(JSON.parse(data)); clearTimeout(timer); } catch (error) { finish(error); return; }
|
|
81
|
+
}
|
|
82
|
+
bytes = Buffer.byteLength(text);
|
|
83
|
+
}
|
|
84
|
+
if (bytes > 8 * 1024 * 1024) finish(new Error('点点响应超出单次读取上限。'));
|
|
85
|
+
});
|
|
86
|
+
request.on('error', error => finish(error));
|
|
87
|
+
request.on('end', () => {
|
|
88
|
+
if (!current()) { finish(new Error('点点账号已变化,请重新连接。')); return; }
|
|
89
|
+
try { finish(null, onEvent ? null : rawResponse ? text : text ? JSON.parse(text) : null); } catch (error) { finish(error); }
|
|
90
|
+
});
|
|
91
|
+
request.on('close', () => { if (!settled) finish(new Error('点点请求连接已断开。')); });
|
|
92
|
+
// end() can queue data before TLS connects. Only a ready HTTP/2 stream
|
|
93
|
+
// has been assigned an ID and may have submitted the request.
|
|
94
|
+
sent = !request.pending;
|
|
95
|
+
request.once('ready', () => { sent = true; });
|
|
96
|
+
request.end(body == null ? undefined : Buffer.isBuffer(body) ? body : JSON.stringify(body));
|
|
97
|
+
});
|
|
98
|
+
} finally { this.controllers.delete(controller); signal?.removeEventListener('abort', cancelled); }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async roomId(threadId) {
|
|
102
|
+
let profile = this.transport.liveProfiles.get(threadId);
|
|
103
|
+
if (!profile?.messagingRoomId) {
|
|
104
|
+
const value = await this.request(`/tbo/by-thread/${encodeURIComponent(threadId)}`);
|
|
105
|
+
profile = { messagingRoomId: value?.messaging_room_id };
|
|
106
|
+
}
|
|
107
|
+
if (typeof profile.messagingRoomId !== 'string' || !profile.messagingRoomId) throw new Error('点点消息房间暂不可用。');
|
|
108
|
+
return profile.messagingRoomId;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async room(id) {
|
|
112
|
+
const room = await this.request(`/messaging/rooms/${encodeURIComponent(id)}`);
|
|
113
|
+
if (room?.id !== id || room.type !== 'DM' || room.app_source !== 'chatgpt:messaging' || !Array.isArray(room.members)) {
|
|
114
|
+
throw new Error('点点消息房间身份不匹配。');
|
|
115
|
+
}
|
|
116
|
+
return room;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async messages(roomId, { before, after, around, limit = 20 } = {}) {
|
|
120
|
+
const query = new URLSearchParams({ limit: String(limit), ...(before ? { before } : {}),
|
|
121
|
+
...(after ? { after } : {}), ...(around ? { around } : {}) });
|
|
122
|
+
const page = await this.request(`/messaging/rooms/${encodeURIComponent(roomId)}/messages?${query}`);
|
|
123
|
+
if (!Array.isArray(page?.items) || page.items.some(message => typeof message.id !== 'string' || !message.id)) throw new Error('点点消息页格式无效。');
|
|
124
|
+
// Null prev_cursor is also returned for nonempty middle pages. Desktop uses
|
|
125
|
+
// the first message ID; only an empty page proves that history is exhausted.
|
|
126
|
+
return { items: page.items, before: page.prev_cursor ?? page.items[0]?.id ?? null,
|
|
127
|
+
after: page.next_cursor ?? (after && page.items.length >= limit ? page.items.at(-1)?.id : null) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
close() {
|
|
131
|
+
super.close();
|
|
132
|
+
for (const controller of this.controllers) controller.abort(new Error('点点连接已结束。'));
|
|
133
|
+
this.controllers.clear(); this.routes.clear();
|
|
134
|
+
}
|
|
135
|
+
}
|