@walkhi/code-relax 0.1.0-beta.27 → 0.1.0-beta.28

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 (63) hide show
  1. package/README.md +80 -67
  2. package/dist/bin/codex-remote.mjs +286 -239
  3. package/dist/shared/app-server-events.cjs +102 -16
  4. package/dist/shared/code-browser.cjs +159 -0
  5. package/dist/shared/file-changes.cjs +31 -0
  6. package/dist/shared/file-citations.cjs +117 -82
  7. package/dist/shared/file-mentions.cjs +80 -35
  8. package/dist/shared/message-delivery.cjs +38 -0
  9. package/dist/shared/p2p-file-channel.cjs +74 -0
  10. package/dist/shared/server-requests.cjs +149 -41
  11. package/dist/shared/service-endpoints.cjs +11 -11
  12. package/dist/shared/timeline-sync.cjs +173 -156
  13. package/dist/skills/code-relax/SKILL.md +2 -1
  14. package/dist/src/bounded-process-log.mjs +63 -0
  15. package/dist/src/celsius-client.mjs +107 -0
  16. package/dist/src/code-browser.mjs +101 -0
  17. package/dist/src/desktop-launcher.mjs +30 -30
  18. package/dist/src/dots-approval-timeline.mjs +99 -0
  19. package/dist/src/dots-avatar.mjs +42 -0
  20. package/dist/src/dots-chat-projection.mjs +50 -0
  21. package/dist/src/dots-chat-server.mjs +412 -0
  22. package/dist/src/dots-message-images.mjs +319 -0
  23. package/dist/src/dots-profile.mjs +77 -0
  24. package/dist/src/dots-room-activity.mjs +94 -0
  25. package/dist/src/dots-room-client.mjs +135 -0
  26. package/dist/src/dots-room-projection.mjs +94 -0
  27. package/dist/src/dots-schedules.mjs +66 -0
  28. package/dist/src/dots-summary-tasks.mjs +32 -0
  29. package/dist/src/dots-task-catalog.mjs +411 -0
  30. package/dist/src/file-transfer-range.mjs +22 -0
  31. package/dist/src/file-upload-session.mjs +130 -124
  32. package/dist/src/hosted-history-app-server.mjs +103 -0
  33. package/dist/src/hosted-history-cache.mjs +113 -0
  34. package/dist/src/lan-socket-server.mjs +205 -160
  35. package/dist/src/managed-app-server.mjs +241 -238
  36. package/dist/src/message-upload-files.mjs +74 -0
  37. package/dist/src/platform/windows/activate-desktop.ps1 +48 -0
  38. package/dist/src/platform/windows/codex-runtime.mjs +253 -251
  39. package/dist/src/platform/windows/desktop-host.mjs +38 -32
  40. package/dist/src/platform/windows/desktop-info.ps1 +2 -2
  41. package/dist/src/platform/windows/desktop-project-registration.mjs +153 -0
  42. package/dist/src/platform/windows/dots-profile.mjs +49 -0
  43. package/dist/src/platform/windows/launch-worker.mjs +41 -42
  44. package/dist/src/platform/windows/project-locations.mjs +16 -0
  45. package/dist/src/project-create.mjs +119 -0
  46. package/dist/src/project-management.mjs +69 -0
  47. package/dist/src/self-relay/account-connections.mjs +52 -0
  48. package/dist/src/self-relay/admin-page.mjs +80 -80
  49. package/dist/src/self-relay/admin-style.mjs +14 -9
  50. package/dist/src/self-relay/connector.mjs +22 -4
  51. package/dist/src/self-relay/file-wire.mjs +13 -0
  52. package/dist/src/self-relay/p2p-probe.mjs +152 -123
  53. package/dist/src/self-relay/rtc-file-bridge.mjs +41 -0
  54. package/dist/src/self-relay/server.mjs +894 -849
  55. package/dist/src/server.mjs +471 -199
  56. package/dist/src/service-doctor.mjs +72 -61
  57. package/dist/src/service-lifecycle.mjs +51 -43
  58. package/dist/src/shared-app-server.mjs +166 -107
  59. package/dist/src/shared-catalog.mjs +132 -40
  60. package/dist/src/shared-thread-stream.mjs +103 -25
  61. package/dist/src/usage-reset.mjs +17 -0
  62. package/dist/src/workstation-downloads.mjs +120 -0
  63. package/package.json +1 -1
@@ -0,0 +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
+ }
@@ -0,0 +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
+ }
@@ -0,0 +1,32 @@
1
+ import events from '../shared/app-server-events.cjs';
2
+
3
+ export async function readDotsSummaryTasks(dotsServer, threadId) {
4
+ await dotsServer.source(threadId, 'aeon');
5
+ const catalog = await dotsServer.taskCatalog(false);
6
+ // Use the existing account-scoped local profile map, without a remote profile
7
+ // request. A Dot keeps its identity when its active root thread changes.
8
+ await dotsServer.refreshProfiles();
9
+ const identity = dotsServer.profileIdentity;
10
+ const profileId = dotsServer.profileNames.get(threadId)?.profileId;
11
+ const tasks = await Promise.all(catalog.filter(thread => thread.threadSource === 'aeon_child').map(async thread => {
12
+ const page = await dotsServer.nativeRequest('thread/items/list', {
13
+ threadId: thread.id, limit: 1, sortDirection: 'asc',
14
+ });
15
+ if (!Array.isArray(page.data)) throw new Error('点点任务未返回委派来源。');
16
+ const item = page.data[0]?.item;
17
+ if (item?.type !== 'userMessage' || !Array.isArray(item.content)
18
+ || !item.content.some(part => {
19
+ const sourceId = part.type === 'text' && events.parseCodexDelegation(part.text)?.sourceThreadId;
20
+ return sourceId && (sourceId === threadId || profileId
21
+ && dotsServer.profileNames.get(sourceId)?.profileId === profileId);
22
+ })) return null;
23
+
24
+ return {
25
+ id: thread.id, hostId: 'durable', threadSource: 'aeon_child',
26
+ title: thread.name?.trim() || '未命名任务', cwd: thread.cwd,
27
+ recencyAt: thread.recencyAt ?? thread.updatedAt,
28
+ };
29
+ }));
30
+ if (identity !== dotsServer.profileIdentity) throw new Error('点点账号已变化,请重新读取任务。');
31
+ return { threadId, tasks: tasks.filter(task => task !== null) };
32
+ }
@@ -0,0 +1,411 @@
1
+ import WebSocket from 'ws';
2
+ import { HostedHistoryAppServer } from './hosted-history-app-server.mjs';
3
+ import { createDotsAvatarReader } from './dots-avatar.mjs';
4
+ import { readDotsCatalog } from './dots-profile.mjs';
5
+
6
+ const hostedAppServerUrl = 'wss://codex-cloud-backend.chatgpt.com/';
7
+ export const dotsTaskRevision = turn => turn ? JSON.stringify([turn.id, turn.status]) : '';
8
+
9
+ // Dots delegated tasks live in Desktop's durable host. Reuse the app-server
10
+ // protocol client; only the authenticated transport differs from the local host.
11
+ export class DotsAppServer extends HostedHistoryAppServer {
12
+ constructor(localServer, readProfiles = async () => new Map(), historyCache = null) {
13
+ super(localServer.url, historyCache);
14
+ this.historySource = 'aeon_child';
15
+ this.localServer = localServer;
16
+ this.url = hostedAppServerUrl;
17
+ this.threadSources = new Map();
18
+ this.catalogWatches = new Map();
19
+ this.readProfiles = readProfiles;
20
+ this.readAvatar = createDotsAvatarReader(localServer);
21
+ this.profileNames = new Map();
22
+ this.liveProfiles = new Map();
23
+ this.liveRoots = new Map();
24
+ this.rootIdentity = null;
25
+ this.catalogPages = new Map();
26
+ this.profileRefresh = null;
27
+ this.profileAttemptAt = 0;
28
+ this.on('turn', ({ thread }) => {
29
+ thread.chatRevision = dotsTaskRevision(thread.turns.at(-1));
30
+ this.saveHistoryWindow(thread.id);
31
+ });
32
+ this.on('disconnected', () => {
33
+ this.profileIdentity = null;
34
+ this.catalogPages.clear(); this.profileRefresh = null; this.profileAttemptAt = 0;
35
+ this.catalogWatches.clear();
36
+ });
37
+ }
38
+
39
+ get historyIdentity() { return this.profileIdentity; }
40
+
41
+ async connect() {
42
+ if (this.resetting) await this.resetting;
43
+ if (this.connecting) return this.connecting;
44
+ return super.connect();
45
+ }
46
+
47
+ async open() {
48
+ await super.open();
49
+ const socket = this.socket, identity = this.profileIdentity;
50
+ // Load confirmed display metadata before chat snapshots can publish a name
51
+ // or avatar. This reads local state, not the slow live profile request.
52
+ await this.refreshProfiles().catch(error => this.emit('profile-error', error));
53
+ if (!this.ready || this.socket !== socket || this.profileIdentity !== identity) throw new Error('点点连接已变化,请重新连接。');
54
+ this.emit('connected');
55
+ }
56
+
57
+ setProfileIdentity(identity) {
58
+ const key = JSON.stringify([identity.accountId, identity.userId]);
59
+ if (this.rootIdentity !== key) {
60
+ this.liveRoots.clear(); this.profileNames.clear(); this.liveProfiles.clear();
61
+ }
62
+ this.profileIdentity = identity; this.rootIdentity = key;
63
+ }
64
+
65
+ async openSocket() {
66
+ await this.localServer.connect();
67
+ const auth = await this.localServer.request('getAuthStatus', { includeToken: true, refreshToken: false });
68
+ if (!['chatgpt', 'chatgptAuthTokens'].includes(auth.authMethod) || !auth.authToken) {
69
+ throw new Error('读取 Dots 任务需要 Codex 内核已登录 ChatGPT。');
70
+ }
71
+ const identity = JSON.parse(Buffer.from(auth.authToken.split('.')[1], 'base64url').toString('utf8'));
72
+ const accountId = identity['https://api.openai.com/auth']?.chatgpt_account_id;
73
+ if (!accountId) throw new Error('Codex 内核没有可用于读取 Dots 任务的 ChatGPT 账号身份。');
74
+ this.setProfileIdentity({ accountId, userId: identity['https://api.openai.com/auth']?.chatgpt_user_id });
75
+ // Credentials stay in this process and go only to the fixed official host.
76
+ return new WebSocket(hostedAppServerUrl,
77
+ ['codex-app-server', 'codex-client.desktop', `openai-bearer.${auth.authToken}`], {
78
+ headers: { 'ChatGPT-Account-Id': accountId, 'X-OpenAI-Product-Sku': 'codex' },
79
+ handshakeTimeout: 15000,
80
+ });
81
+ }
82
+
83
+ request(method, params, transform = value => value) {
84
+ return this.nativeRequest(method, params, value => {
85
+ if (method === 'thread/read' || method === 'thread/resume') {
86
+ if (value.thread.threadSource !== 'aeon_child') throw new Error('该会话不是 Dots 委派任务。');
87
+ value.thread = { ...value.thread, hostId: 'durable', cwd: dotsTaskCwd(value.thread) };
88
+ if (method === 'thread/resume') value.cwd = value.thread.cwd;
89
+ }
90
+ return transform(value);
91
+ });
92
+ }
93
+
94
+ nativeRequest(method, params, transform) {
95
+ const socket = this.socket;
96
+ return super.request(method, params, transform).catch(error => {
97
+ if (error.code === 'app_server_request_timeout' && this.ready && this.socket === socket && !this.resetting) {
98
+ // An OPEN hosted socket can stop answering RPCs while still delivering
99
+ // notifications. Invalidate it once; reconnect through the existing
100
+ // observer lifecycle, never replay the request whose outcome is unknown.
101
+ this.ready = false;
102
+ const resetting = new Promise(resolve => socket.once('close', resolve)).finally(() => {
103
+ if (this.resetting === resetting) this.resetting = null;
104
+ });
105
+ this.resetting = resetting;
106
+ console.warn(JSON.stringify({ time: new Date().toISOString(), event: 'dots-connection-reset',
107
+ reason: error.code, method, threadId: params?.threadId }));
108
+ socket.terminate();
109
+ }
110
+ throw error;
111
+ });
112
+ }
113
+
114
+ watchCatalogTask(threadId) {
115
+ return this.watchExecution(threadId, 'aeon_child');
116
+ }
117
+
118
+ watchExecution(threadId, expectedSource) {
119
+ const current = this.catalogWatches.get(threadId);
120
+ if (current) return current;
121
+ // Hosted thread/list does not subscribe to task notifications. Resume only
122
+ // metadata, with no settings overrides or history window, to register a watch.
123
+ // A slow background watch does not prove the shared socket has stalled.
124
+ // Keep foreground history/streams alive; this read reports its own failure.
125
+ const work = super.request('thread/resume', { threadId, excludeTurns: true }).then(result => {
126
+ if (result.thread.threadSource !== expectedSource) throw new Error('执行订阅返回了不同来源的对话。');
127
+ }).catch(error => {
128
+ if (this.catalogWatches.get(threadId) === work) this.catalogWatches.delete(threadId);
129
+ throw error;
130
+ });
131
+ this.catalogWatches.set(threadId, work);
132
+ return work;
133
+ }
134
+
135
+ async latestTaskState(threadId, refresh = false) {
136
+ const record = this.threads.get(threadId);
137
+ const epoch = this.epoch, sequence = record?.sequence;
138
+ let turn;
139
+ if (!refresh && record && !record.needsReload && !record.hydrating && !record.historyTrimmed) {
140
+ turn = record.thread.turns.at(-1);
141
+ } else {
142
+ const page = await this.initialTurnsPage(threadId);
143
+ if (epoch !== this.epoch) throw new Error('云端连接已变化,请重新核对任务状态。');
144
+ const current = this.threads.get(threadId);
145
+ // Live events received during the metadata read outrank its older result.
146
+ turn = current && current.sequence !== sequence ? current.thread.turns.at(-1) : page.data[0];
147
+ if (current && !current.hydrating && dotsTaskRevision(current.thread.turns.at(-1)) !== dotsTaskRevision(turn)) {
148
+ current.needsReload = true;
149
+ }
150
+ }
151
+ return { chatRevision: dotsTaskRevision(turn), lastTurnStatus: turn?.status || null };
152
+ }
153
+
154
+ async timeline(threadId, pageOptions = {}, knownSync) {
155
+ const result = await super.timeline(threadId, { ...pageOptions, maxTurns: 1 }, knownSync);
156
+ result.thread.chatRevision = dotsTaskRevision(this.threads.get(threadId)?.thread.turns.at(-1));
157
+ await this.saveHistoryWindow(threadId, true);
158
+ return result;
159
+ }
160
+
161
+ async source(threadId, expected) {
162
+ let source = this.threadSources.get(threadId);
163
+ if (!source) {
164
+ await this.connect();
165
+ const { thread } = await this.nativeRequest('thread/read', { threadId, includeTurns: false });
166
+ source = thread.threadSource; this.threadSources.set(threadId, source);
167
+ }
168
+ if (!['aeon', 'aeon_child'].includes(source) || expected && source !== expected) throw new Error('该会话不是对应的 Dots 对话。');
169
+ return source;
170
+ }
171
+
172
+ notification(method, params) {
173
+ if (['thread/started', 'thread/archived', 'thread/unarchived', 'thread/deleted',
174
+ 'thread/name/updated', 'thread/status/changed', 'thread/project/updated', 'turn/started', 'turn/completed'].includes(method)) {
175
+ this.catalogPages.clear();
176
+ }
177
+ if (this.threadSources.get(params.threadId) === 'aeon') this.serverRequests.notification(method, params);
178
+ if (params.thread?.threadSource) this.threadSources.set(params.thread.id, params.thread.threadSource);
179
+ this.emit('host-notification', { method, params });
180
+ if (this.threadSources.get(params.threadId || params.thread?.id) !== 'aeon') {
181
+ this.invalidateHistory(method, params);
182
+ super.notification(method, params);
183
+ }
184
+ }
185
+
186
+ async unsubscribeThread() {
187
+ // Page interest is local; the hosted watch/window last until socket disconnect.
188
+ // Do not turn page closure into thread/stop or another execution command.
189
+ }
190
+
191
+ keepThreadLoaded(_threadId, record) {
192
+ // Hosted watches last for the socket, independently of phone snapshot tokens.
193
+ return this.ready && Boolean(record && !record.readOnly);
194
+ }
195
+
196
+ isThreadObserved(threadId, record) { return this.keepThreadLoaded(threadId, record); }
197
+
198
+ async resumeTimeline(threadId, apply, options = {}) {
199
+ // The hosted protocol loads history separately. Register the resumed thread
200
+ // before requesting its page so notifications can update the hydrating record.
201
+ const scope = this.historyScope(threadId), head = options.reconcileObserved ? null : await this.restoreHistoryHead(threadId);
202
+ return this.request('thread/resume', { threadId, excludeTurns: true }, value => {
203
+ if (scope !== this.historyScope(threadId)) throw new Error('云端账号连接已变化,请重新读取历史。');
204
+ this.diskHeads.set(threadId, { head, updatedAt: value.thread.updatedAt, scope });
205
+ return apply({ ...value, initialTurnsPage: { data: [], nextCursor: null } });
206
+ });
207
+ }
208
+
209
+ async history(threadId, cursor, options = {}) {
210
+ await this.connect(); await this.source(threadId, 'aeon_child');
211
+ return super.history(threadId, cursor, options);
212
+ }
213
+
214
+ initialTurnsPage(threadId) {
215
+ return this.request('thread/turns/list', {
216
+ threadId, limit: 1, sortDirection: 'desc', itemsView: 'notLoaded',
217
+ });
218
+ }
219
+
220
+ async models() {
221
+ await this.connect();
222
+ const models = []; let cursor;
223
+ do {
224
+ const result = await this.request('model/list', { limit: 100, ...(cursor ? { cursor } : {}) });
225
+ models.push(...result.data); cursor = result.nextCursor;
226
+ } while (cursor);
227
+ // Hosted app-server has model/list but no local config/read.
228
+ return { models: models.filter(model => !model.hidden), enabledReasoningEfforts: null };
229
+ }
230
+
231
+ async readContext(threadId, refreshSettings = false) {
232
+ if (refreshSettings) {
233
+ await this.connect();
234
+ const previous = this.settingsNotifications.get(threadId);
235
+ // Hosted thread/read can report stored defaults even after a turn override.
236
+ // Resume without overrides reads the live settings, as Desktop does.
237
+ const settings = await this.request('thread/resume', { threadId, excludeTurns: true });
238
+ if (settings.model && this.settingsNotifications.get(threadId) === previous) {
239
+ this.contexts.set(threadId, { ...this.contexts.get(threadId), model: settings.model,
240
+ thinking: settings.reasoningEffort, serviceTier: settings.serviceTier ?? null });
241
+ }
242
+ }
243
+ return this.context(threadId);
244
+ }
245
+
246
+ async send(args) {
247
+ try {
248
+ await this.connect();
249
+ const record = this.threads.get(args.threadId);
250
+ if (!record || record.needsReload) await this.timeline(args.threadId);
251
+ } catch (error) { error.deliveryUnknown = false; throw error; }
252
+ return super.send(args);
253
+ }
254
+
255
+ async interrupt(threadId) {
256
+ await this.connect();
257
+ this.requireWritable(threadId);
258
+ const result = await this.request('thread/stop', { threadId });
259
+ const record = this.threads.get(threadId);
260
+ if (record) record.needsReload = true;
261
+ return result;
262
+ }
263
+
264
+ async taskCatalog(archived = false, refresh = false) {
265
+ await this.connect();
266
+ const cached = this.catalogPages.get(archived);
267
+ if (cached?.work) return cached.work;
268
+ if (!refresh && cached?.tasks && Date.now() - cached.at < 30000) return cached.tasks;
269
+ const identity = this.profileIdentity;
270
+ const entry = {};
271
+ const work = this.readTaskCatalog(archived).then(tasks => {
272
+ if (identity !== this.profileIdentity) throw new Error('点点账号已变化,请重新读取目录。');
273
+ entry.tasks = tasks; entry.at = Date.now();
274
+ return tasks;
275
+ }).finally(() => { entry.work = null; });
276
+ entry.work = work;
277
+ this.catalogPages.set(archived, entry);
278
+ return work;
279
+ }
280
+
281
+ async readTaskCatalog(archived) {
282
+ const tasks = [];
283
+ let cursor;
284
+ do {
285
+ const page = await this.request('thread/list', {
286
+ // Hosted recency_at can omit existing delegated threads with no cursor.
287
+ // Fetch by updated_at; the merged catalog still uses each thread's recency.
288
+ limit: 100, sortKey: 'updated_at', sortDirection: 'desc', archived,
289
+ ...(cursor ? { cursor } : {}),
290
+ });
291
+ for (const thread of page.data) this.threadSources.set(thread.id, thread.threadSource);
292
+ tasks.push(...page.data.filter(thread => ['aeon', 'aeon_child'].includes(thread.threadSource))
293
+ .map(thread => ({ ...thread, cwd: dotsTaskCwd(thread) })));
294
+ cursor = page.nextCursor;
295
+ } while (cursor);
296
+ return tasks;
297
+ }
298
+
299
+ async catalog(archived = false, refresh = false) {
300
+ const tasks = await this.taskCatalog(archived, refresh);
301
+ await this.refreshProfiles();
302
+ this.refreshLiveProfiles();
303
+ // Subscription failure must not discard an authoritative catalog snapshot.
304
+ // Watches continue independently; failed watches are retried by the next catalog read.
305
+ if (!archived) for (const thread of tasks.filter(thread => thread.threadSource === 'aeon_child')) {
306
+ void this.watchCatalogTask(thread.id).catch(error => {
307
+ console.error('Dots 任务订阅失败:', thread.id, error.message);
308
+ });
309
+ }
310
+ return [...tasks.filter(thread => thread.threadSource === 'aeon_child'),
311
+ ...(archived ? [] : this.liveRoots.values())].map(thread => thread.threadSource === 'aeon' ? { ...thread,
312
+ name: this.profileName(thread.id), avatar: this.profileAvatar(thread.id), color: this.profileColor(thread.id) } : thread);
313
+ }
314
+
315
+ async tasks(archived = false) { return (await this.taskCatalog(archived)).filter(thread => thread.threadSource === 'aeon_child'); }
316
+
317
+ async refreshProfiles() {
318
+ const identity = this.profileIdentity;
319
+ const names = identity ? await this.readProfiles(identity) : new Map();
320
+ if (identity !== this.profileIdentity) throw new Error('点点账号已变化,请重新读取目录。');
321
+ const byProfile = new Map([...this.liveProfiles.values()].map(profile => [profile.profileId, profile]));
322
+ for (const [id, profile] of names) {
323
+ if (byProfile.has(profile.profileId)) names.set(id, byProfile.get(profile.profileId));
324
+ }
325
+ for (const [id, profile] of this.liveProfiles) names.set(id, byProfile.get(profile.profileId));
326
+ for (const [id, profile] of names) {
327
+ const previous = this.profileNames.get(id);
328
+ if (previous?.avatar && previous.avatarFileId === profile.avatarFileId) profile.avatar = previous.avatar;
329
+ }
330
+ if (identity === this.profileIdentity) this.profileNames = names;
331
+ }
332
+
333
+ refreshLiveProfiles() {
334
+ if (this.profileRefresh || Date.now() - this.profileAttemptAt < 60000) return;
335
+ const identity = this.profileIdentity;
336
+ this.profileAttemptAt = Date.now();
337
+ const snapshot = () => JSON.stringify([[...this.profileNames], [...this.liveRoots]]);
338
+ let published = snapshot();
339
+ const publish = () => {
340
+ const next = snapshot();
341
+ if (identity !== this.profileIdentity || published === next) return;
342
+ published = next;
343
+ this.emit('notification', { method: 'thread/name/updated', params: {} });
344
+ };
345
+ const work = (async () => {
346
+ try {
347
+ const { profiles: live, rootThreadIds } = await readDotsCatalog(this.localServer, identity);
348
+ if (identity !== this.profileIdentity) return;
349
+ const roots = new Map();
350
+ for (const threadId of rootThreadIds) {
351
+ const { thread } = await this.nativeRequest('thread/read', { threadId, includeTurns: false });
352
+ if (identity !== this.profileIdentity) return;
353
+ if (thread.id !== threadId || thread.threadSource !== 'aeon') throw new Error('点点目录返回了非主线程。');
354
+ roots.set(threadId, { ...thread, cwd: dotsTaskCwd(thread) });
355
+ }
356
+ if (identity !== this.profileIdentity) return;
357
+ this.liveProfiles = live;
358
+ this.liveRoots = roots;
359
+ for (const id of roots.keys()) this.threadSources.set(id, 'aeon');
360
+ await this.refreshProfiles();
361
+ publish();
362
+ } catch (error) {
363
+ if (identity !== this.profileIdentity) return;
364
+ this.emit('profile-error', error);
365
+ }
366
+ await Promise.all([...new Set(this.profileNames.values())].map(async profile => {
367
+ try { profile.avatar = await this.readAvatar(profile, identity); }
368
+ catch (error) { this.emit('profile-error', error); }
369
+ }));
370
+ publish();
371
+ if (identity === this.profileIdentity && this.liveProfiles.size) await this.readProfiles.save?.(identity, this.liveProfiles);
372
+ })().catch(error => this.emit('profile-error', error))
373
+ .finally(() => { if (this.profileRefresh === work) this.profileRefresh = null; });
374
+ this.profileRefresh = work;
375
+ }
376
+
377
+ profileName(threadId) { return this.profileNames.get(threadId)?.name || 'Dots'; }
378
+ profileAvatar(threadId) { return this.profileNames.get(threadId)?.avatar || ''; }
379
+ profileColor(threadId) { return this.profileNames.get(threadId)?.color || ''; }
380
+ }
381
+
382
+ function dotsTaskCwd(thread) {
383
+ return thread.environments?.[0]?.cwd || thread.cwd;
384
+ }
385
+
386
+ export async function readDotsTasks(localAppServerUrl) {
387
+ const local = new SharedAppServer(localAppServerUrl);
388
+ const cloud = new DotsAppServer(local);
389
+ try {
390
+ const tasks = await cloud.tasks();
391
+ const summaries = await Promise.all(tasks.map(async thread => {
392
+ const turns = await cloud.request('thread/turns/list', {
393
+ threadId: thread.id, limit: 1, sortDirection: 'desc', itemsView: 'notLoaded',
394
+ });
395
+ const latest = turns.data[0];
396
+ return {
397
+ id: thread.id, hostId: 'durable', threadSource: thread.threadSource,
398
+ title: thread.name || thread.preview || '', model: thread.model,
399
+ cwd: thread.environments?.[0]?.cwd || thread.cwd,
400
+ environments: thread.environments, createdAt: thread.createdAt, updatedAt: thread.updatedAt,
401
+ recencyAt: thread.recencyAt ?? thread.updatedAt, status: thread.status?.type,
402
+ latestTurn: latest ? { id: latest.id, status: latest.status,
403
+ startedAt: latest.startedAt, completedAt: latest.completedAt, error: latest.error } : null,
404
+ };
405
+ }));
406
+ return { source: 'codex-cloud-app-server', readAt: new Date().toISOString(), tasks: summaries };
407
+ } finally {
408
+ cloud.close();
409
+ local.close();
410
+ }
411
+ }
@@ -0,0 +1,22 @@
1
+ export const FILE_READ_LIMIT = 20 * 1024 * 1024;
2
+ export const FILE_PART_BYTES = 256 * 1024;
3
+ export class FileRangeError extends Error {
4
+ constructor(statusCode, message) { super(message); this.statusCode = statusCode; }
5
+ }
6
+
7
+ export function fileRange(query, size, revision) {
8
+ const offset = Number(query.get('offset') || 0);
9
+ const length = Number(query.get('length') || FILE_PART_BYTES);
10
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= size ||
11
+ !Number.isSafeInteger(length) || length < 1 || length > FILE_PART_BYTES) {
12
+ throw new FileRangeError(400, '无效的文件读取范围。');
13
+ }
14
+ if ((offset && !query.get('revision')) || (query.has('revision') && query.get('revision') !== revision)) {
15
+ throw new FileRangeError(409, '文件已变化,请重新打开。');
16
+ }
17
+ return { offset, length: Math.min(length, size - offset) };
18
+ }
19
+
20
+ export function fileRevision(stat) {
21
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
22
+ }