@walkhi/code-relax 0.1.0-beta.50 → 0.1.0-beta.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +105 -105
  2. package/dist/bin/cleanup-accounts.mjs +63 -63
  3. package/dist/bin/codex-remote.mjs +403 -403
  4. package/dist/bin/publish-android-release.mjs +63 -63
  5. package/dist/bin/release-upload-server.mjs +190 -190
  6. package/dist/build-platform.json +1 -1
  7. package/dist/get-shared-service-url.ps1 +14 -14
  8. package/dist/shared/code-browser.cjs +159 -159
  9. package/dist/shared/file-changes.cjs +31 -31
  10. package/dist/shared/file-citations.cjs +117 -117
  11. package/dist/shared/file-mentions.cjs +92 -92
  12. package/dist/shared/message-delivery.cjs +115 -115
  13. package/dist/shared/p2p-file-channel.cjs +87 -87
  14. package/dist/shared/server-requests.cjs +311 -311
  15. package/dist/shared/timeline-sync.cjs +173 -173
  16. package/dist/skills/code-relax/SKILL.md +22 -22
  17. package/dist/src/bounded-process-log.mjs +63 -63
  18. package/dist/src/celsius-client.mjs +107 -107
  19. package/dist/src/dots-approval-timeline.mjs +99 -99
  20. package/dist/src/dots-avatar.mjs +42 -42
  21. package/dist/src/dots-chat-projection.mjs +50 -50
  22. package/dist/src/dots-chat-server.mjs +483 -483
  23. package/dist/src/dots-message-images.mjs +319 -319
  24. package/dist/src/dots-profile.mjs +77 -77
  25. package/dist/src/dots-room-activity.mjs +172 -172
  26. package/dist/src/dots-room-client.mjs +135 -135
  27. package/dist/src/dots-room-projection.mjs +94 -94
  28. package/dist/src/dots-schedules.mjs +66 -66
  29. package/dist/src/dots-summary-tasks.mjs +32 -32
  30. package/dist/src/dots-task-catalog.mjs +430 -430
  31. package/dist/src/file-transfer-range.mjs +22 -22
  32. package/dist/src/file-upload-session.mjs +130 -130
  33. package/dist/src/hosted-history-app-server.mjs +103 -103
  34. package/dist/src/hosted-history-cache.mjs +113 -113
  35. package/dist/src/lan-socket-server.mjs +266 -266
  36. package/dist/src/managed-app-server.mjs +373 -373
  37. package/dist/src/managed-endpoint.mjs +25 -25
  38. package/dist/src/message-upload-files.mjs +109 -109
  39. package/dist/src/onboarding.mjs +12 -12
  40. package/dist/src/platform/README.md +1 -1
  41. package/dist/src/platform/codex-protocol.mjs +46 -46
  42. package/dist/src/platform/desktop-project-store.mjs +208 -208
  43. package/dist/src/platform/linux/desktop-host.mjs +87 -87
  44. package/dist/src/platform/linux/process.mjs +53 -53
  45. package/dist/src/platform/linux/system.mjs +50 -50
  46. package/dist/src/platform/linux/user-environment.mjs +9 -9
  47. package/dist/src/platform/macos/codex-runtime.mjs +125 -125
  48. package/dist/src/platform/macos/desktop-host.mjs +86 -86
  49. package/dist/src/platform/macos/user-environment.mjs +9 -9
  50. package/dist/src/platform/native-package.mjs +58 -58
  51. package/dist/src/platform/windows/activate-desktop.ps1 +49 -49
  52. package/dist/src/platform/windows/codex-runtime.mjs +215 -215
  53. package/dist/src/platform/windows/credential-store.mjs +27 -27
  54. package/dist/src/platform/windows/credential-store.ps1 +49 -49
  55. package/dist/src/platform/windows/desktop-host.mjs +65 -65
  56. package/dist/src/platform/windows/desktop-info.ps1 +38 -38
  57. package/dist/src/platform/windows/desktop-project-registration.mjs +4 -4
  58. package/dist/src/platform/windows/desktop-shortcuts.ps1 +14 -14
  59. package/dist/src/platform/windows/dots-profile.mjs +49 -49
  60. package/dist/src/platform/windows/launch-worker.mjs +41 -41
  61. package/dist/src/platform/windows/project-locations.mjs +16 -16
  62. package/dist/src/platform/windows/service-host.mjs +35 -35
  63. package/dist/src/platform/windows/user-environment.mjs +52 -52
  64. package/dist/src/project-management.mjs +58 -58
  65. package/dist/src/runtime-discovery.mjs +47 -47
  66. package/dist/src/self-relay/account-cleanup.mjs +30 -30
  67. package/dist/src/self-relay/admin-page.mjs +80 -80
  68. package/dist/src/self-relay/admin-style.mjs +14 -14
  69. package/dist/src/self-relay/connector.mjs +439 -439
  70. package/dist/src/self-relay/demo.mjs +31 -31
  71. package/dist/src/self-relay/diagnostics.mjs +54 -54
  72. package/dist/src/self-relay/email-accounts.mjs +183 -183
  73. package/dist/src/self-relay/file-wire.mjs +13 -13
  74. package/dist/src/self-relay/p2p-probe.mjs +168 -168
  75. package/dist/src/self-relay/privacy-page.mjs +26 -26
  76. package/dist/src/self-relay/public-releases.mjs +67 -67
  77. package/dist/src/self-relay/rtc-file-bridge.mjs +41 -41
  78. package/dist/src/self-relay/usage-meter.mjs +141 -141
  79. package/dist/src/server.mjs +5 -4
  80. package/dist/src/service-doctor.mjs +148 -148
  81. package/dist/src/service-install.mjs +97 -97
  82. package/dist/src/service-lifecycle.mjs +139 -139
  83. package/dist/src/shared-app-server.mjs +666 -666
  84. package/dist/src/shared-catalog.mjs +132 -132
  85. package/dist/src/shared-thread-stream.mjs +165 -165
  86. package/dist/src/usage-reset.mjs +17 -17
  87. package/dist/src/workstation-downloads.mjs +120 -120
  88. package/package.json +4 -4
  89. package/tools/postinstall.mjs +186 -186
@@ -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
+ }
@@ -1,94 +1,94 @@
1
- // Desktop 26.1002.7124.0 hides appshot context before the visible request.
2
- // Presentation recognizes the format, never an application's routing contract.
3
- function appshotMessageBody(text) {
4
- if (typeof text !== 'string' || !text.trimStart().startsWith('# Applications mentioned by the user:')) return text;
5
- const request = /\r?\n## My request(?: for Codex)?:\r?\n/.exec(text);
6
- if (!request) return text;
7
- const context = text.slice(0, request.index);
8
- for (const [, attributes, content] of context.matchAll(/<appshot\b([^>]*)>([\s\S]*?)<\/appshot>/g)) {
9
- const attrs = new Map([...attributes.matchAll(/([A-Za-z][A-Za-z0-9-]*)="([^"]*)"/g)].map(([, key, value]) => [key, value]));
10
- if (attrs.get('app')?.trim() && attrs.get('bundle-identifier')?.trim()
11
- && (content.trim() || attrs.get('image')?.trim())) return text.slice(request.index + request[0].length);
12
- }
13
- return text;
14
- }
15
-
16
- // Desktop 26.1007.2314.0 X8o/Z8o: suggestions are a native widget, not text.
17
- // Use its supplied web setup entry on mobile; never invent an OAuth URL.
18
- function pluginSetupLinks(attachments) {
19
- const links = new Map();
20
- for (const attachment of attachments) {
21
- if (attachment.type !== 'widget' || attachment.product_sku !== 'aeon'
22
- || attachment.messages?.length !== 2) continue;
23
- const [call, reply] = attachment.messages;
24
- if (call.author?.role !== 'assistant' || reply.author?.role !== 'tool'
25
- || call.id !== attachment.original_message_id || reply.metadata?.is_visually_hidden_from_conversation === true
26
- || reply.metadata?.is_error === true) continue;
27
- const first = call.metadata?.chatgpt_sdk, second = reply.metadata?.chatgpt_sdk;
28
- const connector = first?.resource_name === 'plugin_management.suggest_plugins' ? 'connector_openai_plugin_management'
29
- : first?.resource_name === 'openai_settings.suggest_plugins' ? 'connector_openai_openai_settings' : null;
30
- if (!connector || [first, second].some(sdk => !sdk || sdk.resource_name !== first.resource_name
31
- || sdk.html_asset_pointer !== 'internal://plugin-management-suggestions' || sdk.distribution_channel !== 'openai'
32
- || sdk.attribution_id !== connector || sdk.resolved_pineapple_uri !== `connectors://${connector}`
33
- || sdk.is_error === true || sdk.is_widget_closed === true)) continue;
34
- const result = second.tool_response_metadata?.call_tool_result, data = result?.structuredContent;
35
- if (result?.isError === true || data?.kind !== 'plugin_suggestions' || data.version !== 1
36
- || typeof data.setup_url !== 'string' || !Array.isArray(data.suggestions) || !data.suggestions.length
37
- || data.suggestions.some(plugin => typeof plugin?.plugin_id !== 'string' || !plugin.plugin_id
38
- || typeof plugin.display_name !== 'string' || !plugin.display_name.trim())) continue;
39
- let url;
40
- try { url = new URL(data.setup_url); } catch { continue; }
41
- if (url.origin !== 'https://chatgpt.com' || url.pathname !== '/plugin-suggestions'
42
- || url.username || url.password || url.hash || url.searchParams.getAll('bundle').length !== 1
43
- || !url.searchParams.get('bundle')) continue;
44
- const names = [...new Map(data.suggestions.map(plugin => [plugin.plugin_id, plugin.display_name])).values()];
45
- const label = names.join('、').replace(/[\r\n]+/g, ' ').replace(/[\\`*_[\]<>]/g, '\\$&');
46
- links.set(data.setup_url, `[设置 ${label} 连接](<${url.href.replace(/</g, '%3C').replace(/>/g, '%3E')}>)`);
47
- }
48
- return [...links.values()];
49
- }
50
-
51
- // Message role alone is insufficient: Dot is also a user-shaped room member.
52
- export function dotsRoomTurns(room, messages) {
53
- return messages.map(message => {
54
- const member = room.members.find(value => value.account_user_id === message.account_user_id);
55
- const assistant = Array.isArray(message.raw_messages) || Boolean(member?.aeon_id);
56
- const time = Date.parse(message.created_at);
57
- const common = { id: message.id, startedAtMs: Number.isFinite(time) ? time : undefined,
58
- completedAtMs: Number.isFinite(time) ? time : undefined };
59
- const rawText = Array.isArray(message.raw_messages) ? message.raw_messages
60
- .filter(raw => raw.author?.role === 'assistant' && raw.channel !== 'analysis'
61
- && !raw.metadata?.is_hidden && !raw.metadata?.hidden && ['text', 'multimodal_text'].includes(raw.content?.content_type))
62
- .flatMap(raw => (raw.content.parts || []).filter(part => typeof part === 'string')).join('\n\n')
63
- : message.content?.text || '';
64
- const sourceAttachments = message.content?.attachments || message.attachments || [];
65
- const text = assistant ? [rawText, ...pluginSetupLinks(sourceAttachments)].filter(Boolean).join('\n\n')
66
- : member ? appshotMessageBody(rawText) : rawText;
67
- const attachments = sourceAttachments.flatMap(attachment => {
68
- if (attachment.type !== 'file' || typeof attachment.file_id !== 'string') return [];
69
- const file = attachment.file || {};
70
- return [{ type: /^image\//.test(file.mime_type || '') ? 'image' : 'file',
71
- roomId: room.id, fileId: attachment.file_id, name: file.name || file.file_name || '附件',
72
- mimeType: file.mime_type || '', size: file.size_bytes }];
73
- });
74
- let item;
75
- if (!message.deleted_at && message.content?.type !== 'message_error') {
76
- if (assistant) item = { ...common, type: 'agentMessage', text, attachments, phase: 'final', delivery: 'async',
77
- ...(message.generation?.status === 'in_progress' ? { dotsStreaming: true, completedAtMs: null } : {}) };
78
- else if (member) item = { ...common, type: 'userMessage', clientId: message.request_id?.replace(/-/g, ''),
79
- content: [...(text ? [{ type: 'text', text }] : []), ...attachments] };
80
- }
81
- const request = message.content?.elicitation;
82
- const approval = !message.deleted_at && request && typeof request.request_id === 'string' && request.request_id
83
- && typeof request.thread_id === 'string' && request.thread_id && request.params?.threadId === request.thread_id
84
- && ['pending', 'resolved', 'expired'].includes(request.status)
85
- ? { type: 'approval', id: `approval:string:${request.request_id}`, requestId: request.request_id,
86
- method: 'mcpServer/elicitation/request', params: request.params, status: request.status, result: null,
87
- sourceThreadId: request.thread_id, turnId: request.turn_id ?? null, receivedAtMs: time,
88
- completedAtMs: null, roomMessageId: message.id } : null;
89
- return { id: message.id, status: item?.dotsStreaming ? 'inProgress' : 'completed',
90
- roomMessage: true, deleted: Boolean(message.deleted_at), createdAt: message.created_at,
91
- updatedAt: message.deleted_at || message.updated_at || message.created_at,
92
- items: [...(item && (text || attachments.length) ? [item] : []), ...(approval ? [approval] : [])] };
93
- });
94
- }
1
+ // Desktop 26.1002.7124.0 hides appshot context before the visible request.
2
+ // Presentation recognizes the format, never an application's routing contract.
3
+ function appshotMessageBody(text) {
4
+ if (typeof text !== 'string' || !text.trimStart().startsWith('# Applications mentioned by the user:')) return text;
5
+ const request = /\r?\n## My request(?: for Codex)?:\r?\n/.exec(text);
6
+ if (!request) return text;
7
+ const context = text.slice(0, request.index);
8
+ for (const [, attributes, content] of context.matchAll(/<appshot\b([^>]*)>([\s\S]*?)<\/appshot>/g)) {
9
+ const attrs = new Map([...attributes.matchAll(/([A-Za-z][A-Za-z0-9-]*)="([^"]*)"/g)].map(([, key, value]) => [key, value]));
10
+ if (attrs.get('app')?.trim() && attrs.get('bundle-identifier')?.trim()
11
+ && (content.trim() || attrs.get('image')?.trim())) return text.slice(request.index + request[0].length);
12
+ }
13
+ return text;
14
+ }
15
+
16
+ // Desktop 26.1007.2314.0 X8o/Z8o: suggestions are a native widget, not text.
17
+ // Use its supplied web setup entry on mobile; never invent an OAuth URL.
18
+ function pluginSetupLinks(attachments) {
19
+ const links = new Map();
20
+ for (const attachment of attachments) {
21
+ if (attachment.type !== 'widget' || attachment.product_sku !== 'aeon'
22
+ || attachment.messages?.length !== 2) continue;
23
+ const [call, reply] = attachment.messages;
24
+ if (call.author?.role !== 'assistant' || reply.author?.role !== 'tool'
25
+ || call.id !== attachment.original_message_id || reply.metadata?.is_visually_hidden_from_conversation === true
26
+ || reply.metadata?.is_error === true) continue;
27
+ const first = call.metadata?.chatgpt_sdk, second = reply.metadata?.chatgpt_sdk;
28
+ const connector = first?.resource_name === 'plugin_management.suggest_plugins' ? 'connector_openai_plugin_management'
29
+ : first?.resource_name === 'openai_settings.suggest_plugins' ? 'connector_openai_openai_settings' : null;
30
+ if (!connector || [first, second].some(sdk => !sdk || sdk.resource_name !== first.resource_name
31
+ || sdk.html_asset_pointer !== 'internal://plugin-management-suggestions' || sdk.distribution_channel !== 'openai'
32
+ || sdk.attribution_id !== connector || sdk.resolved_pineapple_uri !== `connectors://${connector}`
33
+ || sdk.is_error === true || sdk.is_widget_closed === true)) continue;
34
+ const result = second.tool_response_metadata?.call_tool_result, data = result?.structuredContent;
35
+ if (result?.isError === true || data?.kind !== 'plugin_suggestions' || data.version !== 1
36
+ || typeof data.setup_url !== 'string' || !Array.isArray(data.suggestions) || !data.suggestions.length
37
+ || data.suggestions.some(plugin => typeof plugin?.plugin_id !== 'string' || !plugin.plugin_id
38
+ || typeof plugin.display_name !== 'string' || !plugin.display_name.trim())) continue;
39
+ let url;
40
+ try { url = new URL(data.setup_url); } catch { continue; }
41
+ if (url.origin !== 'https://chatgpt.com' || url.pathname !== '/plugin-suggestions'
42
+ || url.username || url.password || url.hash || url.searchParams.getAll('bundle').length !== 1
43
+ || !url.searchParams.get('bundle')) continue;
44
+ const names = [...new Map(data.suggestions.map(plugin => [plugin.plugin_id, plugin.display_name])).values()];
45
+ const label = names.join('、').replace(/[\r\n]+/g, ' ').replace(/[\\`*_[\]<>]/g, '\\$&');
46
+ links.set(data.setup_url, `[设置 ${label} 连接](<${url.href.replace(/</g, '%3C').replace(/>/g, '%3E')}>)`);
47
+ }
48
+ return [...links.values()];
49
+ }
50
+
51
+ // Message role alone is insufficient: Dot is also a user-shaped room member.
52
+ export function dotsRoomTurns(room, messages) {
53
+ return messages.map(message => {
54
+ const member = room.members.find(value => value.account_user_id === message.account_user_id);
55
+ const assistant = Array.isArray(message.raw_messages) || Boolean(member?.aeon_id);
56
+ const time = Date.parse(message.created_at);
57
+ const common = { id: message.id, startedAtMs: Number.isFinite(time) ? time : undefined,
58
+ completedAtMs: Number.isFinite(time) ? time : undefined };
59
+ const rawText = Array.isArray(message.raw_messages) ? message.raw_messages
60
+ .filter(raw => raw.author?.role === 'assistant' && raw.channel !== 'analysis'
61
+ && !raw.metadata?.is_hidden && !raw.metadata?.hidden && ['text', 'multimodal_text'].includes(raw.content?.content_type))
62
+ .flatMap(raw => (raw.content.parts || []).filter(part => typeof part === 'string')).join('\n\n')
63
+ : message.content?.text || '';
64
+ const sourceAttachments = message.content?.attachments || message.attachments || [];
65
+ const text = assistant ? [rawText, ...pluginSetupLinks(sourceAttachments)].filter(Boolean).join('\n\n')
66
+ : member ? appshotMessageBody(rawText) : rawText;
67
+ const attachments = sourceAttachments.flatMap(attachment => {
68
+ if (attachment.type !== 'file' || typeof attachment.file_id !== 'string') return [];
69
+ const file = attachment.file || {};
70
+ return [{ type: /^image\//.test(file.mime_type || '') ? 'image' : 'file',
71
+ roomId: room.id, fileId: attachment.file_id, name: file.name || file.file_name || '附件',
72
+ mimeType: file.mime_type || '', size: file.size_bytes }];
73
+ });
74
+ let item;
75
+ if (!message.deleted_at && message.content?.type !== 'message_error') {
76
+ if (assistant) item = { ...common, type: 'agentMessage', text, attachments, phase: 'final', delivery: 'async',
77
+ ...(message.generation?.status === 'in_progress' ? { dotsStreaming: true, completedAtMs: null } : {}) };
78
+ else if (member) item = { ...common, type: 'userMessage', clientId: message.request_id?.replace(/-/g, ''),
79
+ content: [...(text ? [{ type: 'text', text }] : []), ...attachments] };
80
+ }
81
+ const request = message.content?.elicitation;
82
+ const approval = !message.deleted_at && request && typeof request.request_id === 'string' && request.request_id
83
+ && typeof request.thread_id === 'string' && request.thread_id && request.params?.threadId === request.thread_id
84
+ && ['pending', 'resolved', 'expired'].includes(request.status)
85
+ ? { type: 'approval', id: `approval:string:${request.request_id}`, requestId: request.request_id,
86
+ method: 'mcpServer/elicitation/request', params: request.params, status: request.status, result: null,
87
+ sourceThreadId: request.thread_id, turnId: request.turn_id ?? null, receivedAtMs: time,
88
+ completedAtMs: null, roomMessageId: message.id } : null;
89
+ return { id: message.id, status: item?.dotsStreaming ? 'inProgress' : 'completed',
90
+ roomMessage: true, deleted: Boolean(message.deleted_at), createdAt: message.created_at,
91
+ updatedAt: message.deleted_at || message.updated_at || message.created_at,
92
+ items: [...(item && (text || attachments.length) ? [item] : []), ...(approval ? [approval] : [])] };
93
+ });
94
+ }
@@ -1,66 +1,66 @@
1
- import http2 from 'node:http2';
2
-
3
- // Desktop 26.930.3748.0: state-42dba351d73f lists this Dot's automations,
4
- // and F8 excludes finished schedules while retaining condition watches.
5
- export async function readDotsSchedules(dotsServer, threadId) {
6
- await dotsServer.connect();
7
- await dotsServer.source(threadId, 'aeon');
8
- const identity = dotsServer.profileIdentity;
9
- const auth = await dotsServer.localServer.request('getAuthStatus', { includeToken: true, refreshToken: false });
10
- const principal = JSON.parse(Buffer.from(auth.authToken.split('.')[1], 'base64url').toString('utf8'))['https://api.openai.com/auth'];
11
- if (!identity || identity.accountId !== principal?.chatgpt_account_id || identity.userId !== principal?.chatgpt_user_id) {
12
- throw new Error('点点账号已变化,请重新连接。');
13
- }
14
- const session = http2.connect('https://chatgpt.com');
15
- // Stream errors carry failures to the caller; consume the corresponding
16
- // session event so a failed connection does not crash the workstation.
17
- session.on('error', () => {});
18
- const get = path => new Promise((resolve, reject) => {
19
- const request = session.request({ ':method': 'GET', ':path': '/backend-api' + path,
20
- authorization: `Bearer ${auth.authToken}`, 'chatgpt-account-id': identity.accountId,
21
- 'user-agent': 'Code-Relax/0.1.0', accept: 'application/json' });
22
- let status, contentType, body = '', size = 0;
23
- const timeout = setTimeout(() => request.destroy(new Error('读取点点定时任务超时。')), 60000);
24
- request.setEncoding('utf8');
25
- request.on('response', headers => { status = headers[':status']; contentType = headers['content-type']; });
26
- request.on('data', chunk => {
27
- size += Buffer.byteLength(chunk);
28
- if (size > 8 * 1024 * 1024) request.destroy(new Error('点点定时任务响应过大。'));
29
- else body += chunk;
30
- });
31
- request.on('error', reject);
32
- request.on('close', () => clearTimeout(timeout));
33
- request.on('end', () => {
34
- try {
35
- if (status !== 200) throw new Error(`读取点点定时任务失败(HTTP ${status})。`);
36
- if (!contentType?.includes('application/json')) throw new Error('点点定时任务返回了非 JSON 响应。');
37
- resolve(JSON.parse(body));
38
- } catch (error) { reject(error); }
39
- });
40
- request.end();
41
- });
42
- try {
43
- const profile = await get(`/tbo/by-thread/${encodeURIComponent(threadId)}`);
44
- if (typeof profile.id !== 'string' || !profile.id) throw new Error('点点资料缺少身份。');
45
- const schedules = [];
46
- let cursor;
47
- do {
48
- const query = new URLSearchParams({ limit: '100', ...(cursor ? { cursor } : {}) });
49
- const page = await get(`/tbo/${encodeURIComponent(profile.id)}/automations?${query}`);
50
- if (!Array.isArray(page.items) || page.cursor != null && typeof page.cursor !== 'string') throw new Error('点点定时任务列表格式无效。');
51
- for (const item of page.items) {
52
- if (typeof item.id !== 'string' || typeof item.title !== 'string' || typeof item.is_enabled !== 'boolean'
53
- || !Array.isArray(item.next_run_times)) throw new Error('点点定时任务信息不完整。');
54
- const watching = item.timing_mode === 'condition_watch';
55
- if (item.executor !== 'local' && !watching && item.next_run_times.length === 0) continue;
56
- schedules.push({ id: item.id, title: item.display_title?.trim() || item.title.trim(),
57
- status: !item.is_enabled ? 'paused' : watching ? 'monitoring' : 'scheduled',
58
- schedule: watching ? '' : item.display_schedule || '',
59
- nextRunAt: item.is_enabled && !watching ? item.next_run_times[0] || null : null });
60
- }
61
- cursor = page.cursor;
62
- } while (cursor);
63
- if (dotsServer.profileIdentity !== identity) throw new Error('点点连接已变化,请重新读取。');
64
- return { threadId, schedules };
65
- } finally { session.destroy(); }
66
- }
1
+ import http2 from 'node:http2';
2
+
3
+ // Desktop 26.930.3748.0: state-42dba351d73f lists this Dot's automations,
4
+ // and F8 excludes finished schedules while retaining condition watches.
5
+ export async function readDotsSchedules(dotsServer, threadId) {
6
+ await dotsServer.connect();
7
+ await dotsServer.source(threadId, 'aeon');
8
+ const identity = dotsServer.profileIdentity;
9
+ const auth = await dotsServer.localServer.request('getAuthStatus', { includeToken: true, refreshToken: false });
10
+ const principal = JSON.parse(Buffer.from(auth.authToken.split('.')[1], 'base64url').toString('utf8'))['https://api.openai.com/auth'];
11
+ if (!identity || identity.accountId !== principal?.chatgpt_account_id || identity.userId !== principal?.chatgpt_user_id) {
12
+ throw new Error('点点账号已变化,请重新连接。');
13
+ }
14
+ const session = http2.connect('https://chatgpt.com');
15
+ // Stream errors carry failures to the caller; consume the corresponding
16
+ // session event so a failed connection does not crash the workstation.
17
+ session.on('error', () => {});
18
+ const get = path => new Promise((resolve, reject) => {
19
+ const request = session.request({ ':method': 'GET', ':path': '/backend-api' + path,
20
+ authorization: `Bearer ${auth.authToken}`, 'chatgpt-account-id': identity.accountId,
21
+ 'user-agent': 'Code-Relax/0.1.0', accept: 'application/json' });
22
+ let status, contentType, body = '', size = 0;
23
+ const timeout = setTimeout(() => request.destroy(new Error('读取点点定时任务超时。')), 60000);
24
+ request.setEncoding('utf8');
25
+ request.on('response', headers => { status = headers[':status']; contentType = headers['content-type']; });
26
+ request.on('data', chunk => {
27
+ size += Buffer.byteLength(chunk);
28
+ if (size > 8 * 1024 * 1024) request.destroy(new Error('点点定时任务响应过大。'));
29
+ else body += chunk;
30
+ });
31
+ request.on('error', reject);
32
+ request.on('close', () => clearTimeout(timeout));
33
+ request.on('end', () => {
34
+ try {
35
+ if (status !== 200) throw new Error(`读取点点定时任务失败(HTTP ${status})。`);
36
+ if (!contentType?.includes('application/json')) throw new Error('点点定时任务返回了非 JSON 响应。');
37
+ resolve(JSON.parse(body));
38
+ } catch (error) { reject(error); }
39
+ });
40
+ request.end();
41
+ });
42
+ try {
43
+ const profile = await get(`/tbo/by-thread/${encodeURIComponent(threadId)}`);
44
+ if (typeof profile.id !== 'string' || !profile.id) throw new Error('点点资料缺少身份。');
45
+ const schedules = [];
46
+ let cursor;
47
+ do {
48
+ const query = new URLSearchParams({ limit: '100', ...(cursor ? { cursor } : {}) });
49
+ const page = await get(`/tbo/${encodeURIComponent(profile.id)}/automations?${query}`);
50
+ if (!Array.isArray(page.items) || page.cursor != null && typeof page.cursor !== 'string') throw new Error('点点定时任务列表格式无效。');
51
+ for (const item of page.items) {
52
+ if (typeof item.id !== 'string' || typeof item.title !== 'string' || typeof item.is_enabled !== 'boolean'
53
+ || !Array.isArray(item.next_run_times)) throw new Error('点点定时任务信息不完整。');
54
+ const watching = item.timing_mode === 'condition_watch';
55
+ if (item.executor !== 'local' && !watching && item.next_run_times.length === 0) continue;
56
+ schedules.push({ id: item.id, title: item.display_title?.trim() || item.title.trim(),
57
+ status: !item.is_enabled ? 'paused' : watching ? 'monitoring' : 'scheduled',
58
+ schedule: watching ? '' : item.display_schedule || '',
59
+ nextRunAt: item.is_enabled && !watching ? item.next_run_times[0] || null : null });
60
+ }
61
+ cursor = page.cursor;
62
+ } while (cursor);
63
+ if (dotsServer.profileIdentity !== identity) throw new Error('点点连接已变化,请重新读取。');
64
+ return { threadId, schedules };
65
+ } finally { session.destroy(); }
66
+ }