@walkhi/code-relax 0.1.0-beta.26 → 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 -0
  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 +463 -148
  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
@@ -1,124 +1,130 @@
1
- import crypto from 'node:crypto';
2
- import fs from 'node:fs/promises';
3
- import path from 'node:path';
4
-
5
- export const MAX_FILE_BYTES = 20 * 1024 * 1024;
6
- export const MAX_FILE_COUNT = 4;
7
- export const MAX_TOTAL_BYTES = 40 * 1024 * 1024;
8
- export const FILE_CHUNK_BYTES = 256 * 1024;
9
-
10
- function validName(value) {
11
- return typeof value === 'string' && value.length > 0 && value.length <= 180 &&
12
- value !== '.' && value !== '..' && !/[\\/:*?"<>|\x00-\x1f]/.test(value) && !/[. ]$/.test(value) &&
13
- !/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(value);
14
- }
15
-
16
- async function uniqueDestination(directory, name, partial) {
17
- const dot = name.lastIndexOf('.');
18
- const stem = dot > 0 ? name.slice(0, dot) : name;
19
- const extension = dot > 0 ? name.slice(dot) : '';
20
- for (let index = 0; ; index++) {
21
- const suffix = index ? ` (${index})` : '';
22
- const candidate = index ? `${stem.slice(0, 180 - extension.length - suffix.length)}${suffix}${extension}` : name;
23
- if (!candidate || candidate.length > 180) throw new Error('同名文件过多,文件名无法继续编号');
24
- const destination = path.join(directory, candidate);
25
- try {
26
- await fs.link(partial, destination);
27
- await fs.unlink(partial);
28
- return { name: candidate, path: destination };
29
- } catch (error) {
30
- if (error.code !== 'EEXIST') throw error;
31
- }
32
- }
33
- }
34
-
35
- export function createFileUploadSession(root) {
36
- let upload;
37
- const completed = new Map();
38
- let completedBytes = 0;
39
- const directory = path.join(root, 'incoming');
40
- const clearActive = async () => {
41
- const current = upload;
42
- upload = undefined;
43
- if (!current) return;
44
- await current.handle.close().catch(() => {});
45
- await fs.unlink(current.partial).catch(() => {});
46
- };
47
- const clear = async () => {
48
- await clearActive();
49
- for (const file of completed.values()) await fs.unlink(file.path).catch(() => {});
50
- completed.clear(); completedBytes = 0;
51
- };
52
- return {
53
- async receive(message) {
54
- if (!message || typeof message !== 'object') throw new Error('无效的文件上传请求');
55
- if (message.type === 'cancel') { await clear(); return { type: 'cancelled' }; }
56
- if (message.type === 'commit') {
57
- if (upload) throw new Error('文件尚未上传完成');
58
- completed.clear(); completedBytes = 0;
59
- return { type: 'committed' };
60
- }
61
- if (message.type === 'remove') {
62
- if (upload) throw new Error('请等待当前文件上传完成');
63
- const file = completed.get(message.id);
64
- if (!file) throw new Error('文件上传会话已失效');
65
- await fs.unlink(file.path);
66
- completed.delete(message.id); completedBytes -= file.size;
67
- return { type: 'removed', id: message.id };
68
- }
69
- if (message.type === 'start') {
70
- if (upload) throw new Error('已有文件正在上传');
71
- if (!validName(message.name)) throw new Error('文件名无效');
72
- if (!Number.isSafeInteger(message.size) || message.size < 1 || message.size > MAX_FILE_BYTES) {
73
- throw new Error('单个文件不得超过 20 MiB');
74
- }
75
- if (completed.size >= MAX_FILE_COUNT || completedBytes + message.size > MAX_TOTAL_BYTES) {
76
- throw new Error('每条消息最多 4 个文件,合计不超过 40 MiB');
77
- }
78
- if (!/^[a-f0-9]{64}$/i.test(message.sha256 || '')) throw new Error('文件校验值无效');
79
- const id = crypto.randomUUID();
80
- await fs.mkdir(directory, { recursive: true });
81
- const partial = path.join(directory, `.upload-${id}`);
82
- const handle = await fs.open(partial, 'wx');
83
- upload = { id, partial, handle, name: message.name, size: message.size,
84
- expected: message.sha256.toLowerCase(), hash: crypto.createHash('sha256'), offset: 0 };
85
- return { type: 'started', id, offset: 0, chunkBytes: FILE_CHUNK_BYTES };
86
- }
87
- const current = upload;
88
- if (!current || message.id !== current.id) throw new Error('文件上传会话已失效');
89
- if (message.type === 'chunk') {
90
- if (!Number.isSafeInteger(message.offset) || message.offset !== current.offset) {
91
- return { type: 'offset', id: current.id, offset: current.offset };
92
- }
93
- if (typeof message.data !== 'string' || message.data.length > Math.ceil(FILE_CHUNK_BYTES / 3) * 4 + 4 ||
94
- !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(message.data)) {
95
- throw new Error('文件分片格式无效');
96
- }
97
- const bytes = Buffer.from(message.data, 'base64');
98
- if (!bytes.length || bytes.length > FILE_CHUNK_BYTES || current.offset + bytes.length > current.size) {
99
- throw new Error('文件分片大小无效');
100
- }
101
- await current.handle.writeFile(bytes);
102
- current.hash.update(bytes);
103
- current.offset += bytes.length;
104
- return { type: 'offset', id: current.id, offset: current.offset };
105
- }
106
- if (message.type === 'finish') {
107
- if (current.offset !== current.size || current.hash.digest('hex') !== current.expected) {
108
- await clear(); throw new Error('文件大小或 SHA-256 校验失败');
109
- }
110
- await current.handle.sync();
111
- await current.handle.close();
112
- upload = undefined;
113
- let saved;
114
- try { saved = await uniqueDestination(directory, current.name, current.partial); }
115
- catch (error) { await fs.unlink(current.partial).catch(() => {}); throw error; }
116
- const result = { type: 'completed', id: current.id, ...saved, size: current.size };
117
- completed.set(current.id, result); completedBytes += current.size;
118
- return result;
119
- }
120
- throw new Error('不支持的文件上传操作');
121
- },
122
- close: clear,
123
- };
124
- }
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ export const MAX_FILE_BYTES = 20 * 1024 * 1024;
6
+ export const MAX_FILE_COUNT = 4;
7
+ export const MAX_TOTAL_BYTES = 40 * 1024 * 1024;
8
+ export const FILE_CHUNK_BYTES = 256 * 1024;
9
+
10
+ function validName(value) {
11
+ return typeof value === 'string' && value.length > 0 && value.length <= 180 &&
12
+ value !== '.' && value !== '..' && !/[\\/:*?"<>|\x00-\x1f]/.test(value) && !/[. ]$/.test(value) &&
13
+ !/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(value);
14
+ }
15
+
16
+ async function uniqueDestination(directory, name, partial) {
17
+ const dot = name.lastIndexOf('.');
18
+ const stem = dot > 0 ? name.slice(0, dot) : name;
19
+ const extension = dot > 0 ? name.slice(dot) : '';
20
+ for (let index = 0; ; index++) {
21
+ const suffix = index ? ` (${index})` : '';
22
+ const candidate = index ? `${stem.slice(0, 180 - extension.length - suffix.length)}${suffix}${extension}` : name;
23
+ if (!candidate || candidate.length > 180) throw new Error('同名文件过多,文件名无法继续编号');
24
+ const destination = path.join(directory, candidate);
25
+ try {
26
+ await fs.link(partial, destination);
27
+ await fs.unlink(partial);
28
+ return { name: candidate, path: destination };
29
+ } catch (error) {
30
+ if (error.code !== 'EEXIST') throw error;
31
+ }
32
+ }
33
+ }
34
+
35
+ export function createFileUploadSession(root) {
36
+ let upload;
37
+ const completed = new Map();
38
+ let completedBytes = 0;
39
+ const directory = path.join(root, 'incoming');
40
+ const clearActive = async () => {
41
+ const current = upload;
42
+ upload = undefined;
43
+ if (!current) return;
44
+ await current.handle.close().catch(() => {});
45
+ await fs.unlink(current.partial).catch(() => {});
46
+ };
47
+ const clear = async () => {
48
+ await clearActive();
49
+ for (const file of completed.values()) {
50
+ await fs.unlink(file.path).catch(() => {});
51
+ if (file.preview) await fs.unlink(file.preview.path).catch(() => {});
52
+ }
53
+ completed.clear(); completedBytes = 0;
54
+ };
55
+ return {
56
+ async receive(message) {
57
+ if (!message || typeof message !== 'object') throw new Error('无效的文件上传请求');
58
+ if (message.type === 'cancel') { await clear(); return { type: 'cancelled' }; }
59
+ if (message.type === 'commit') {
60
+ if (upload) throw new Error('文件尚未上传完成');
61
+ completed.clear(); completedBytes = 0;
62
+ return { type: 'committed' };
63
+ }
64
+ if (message.type === 'remove') {
65
+ if (upload) throw new Error('请等待当前文件上传完成');
66
+ const file = completed.get(message.id);
67
+ if (!file) throw new Error('文件上传会话已失效');
68
+ await fs.unlink(file.path);
69
+ if (file.preview) await fs.unlink(file.preview.path);
70
+ completed.delete(message.id); completedBytes -= file.size;
71
+ return { type: 'removed', id: message.id };
72
+ }
73
+ if (message.type === 'start') {
74
+ if (upload) throw new Error('已有文件正在上传');
75
+ if (!validName(message.name)) throw new Error('文件名无效');
76
+ if (!Number.isSafeInteger(message.size) || message.size < 1 || message.size > MAX_FILE_BYTES) {
77
+ throw new Error('单个文件不得超过 20 MiB');
78
+ }
79
+ const parent = message.previewOf ? completed.get(message.previewOf) : null;
80
+ if (message.previewOf && (!parent || parent.preview || message.size > FILE_CHUNK_BYTES)) throw new Error('预览图关联无效或超过 256 KiB');
81
+ if (!parent && (completed.size >= MAX_FILE_COUNT || completedBytes + message.size > MAX_TOTAL_BYTES)) {
82
+ throw new Error('每条消息最多 4 个文件,合计不超过 40 MiB');
83
+ }
84
+ if (!/^[a-f0-9]{64}$/i.test(message.sha256 || '')) throw new Error('文件校验值无效');
85
+ const id = crypto.randomUUID();
86
+ await fs.mkdir(directory, { recursive: true });
87
+ const partial = path.join(directory, `.upload-${id}`);
88
+ const handle = await fs.open(partial, 'wx');
89
+ upload = { id, partial, handle, name: parent ? `${id}.preview.jpg` : message.name, size: message.size, parent,
90
+ expected: message.sha256.toLowerCase(), hash: crypto.createHash('sha256'), offset: 0 };
91
+ return { type: 'started', id, offset: 0, chunkBytes: FILE_CHUNK_BYTES };
92
+ }
93
+ const current = upload;
94
+ if (!current || message.id !== current.id) throw new Error('文件上传会话已失效');
95
+ if (message.type === 'chunk') {
96
+ if (!Number.isSafeInteger(message.offset) || message.offset !== current.offset) {
97
+ return { type: 'offset', id: current.id, offset: current.offset };
98
+ }
99
+ if (!Buffer.isBuffer(message.data)) {
100
+ throw new Error('文件分片格式无效');
101
+ }
102
+ const bytes = message.data;
103
+ if (!bytes.length || bytes.length > FILE_CHUNK_BYTES || current.offset + bytes.length > current.size) {
104
+ throw new Error('文件分片大小无效');
105
+ }
106
+ await current.handle.writeFile(bytes);
107
+ current.hash.update(bytes);
108
+ current.offset += bytes.length;
109
+ return { type: 'offset', id: current.id, offset: current.offset };
110
+ }
111
+ if (message.type === 'finish') {
112
+ if (current.offset !== current.size || current.hash.digest('hex') !== current.expected) {
113
+ await clear(); throw new Error('文件大小或 SHA-256 校验失败');
114
+ }
115
+ await current.handle.sync();
116
+ await current.handle.close();
117
+ upload = undefined;
118
+ let saved;
119
+ try { saved = await uniqueDestination(directory, current.name, current.partial); }
120
+ catch (error) { await fs.unlink(current.partial).catch(() => {}); throw error; }
121
+ const result = { type: 'completed', id: current.id, ...saved, size: current.size, sha256: current.expected };
122
+ if (current.parent) current.parent.preview = result;
123
+ else { completed.set(current.id, result); completedBytes += current.size; }
124
+ return result;
125
+ }
126
+ throw new Error('不支持的文件上传操作');
127
+ },
128
+ close: clear,
129
+ };
130
+ }
@@ -0,0 +1,103 @@
1
+ import { SharedAppServer } from './shared-app-server.mjs';
2
+ import { historyCacheScope, completedHistory, turnMetadata } from './hosted-history-cache.mjs';
3
+
4
+ // Hosted history uses a disk range cache; local kernel history retains its own storage.
5
+ export class HostedHistoryAppServer extends SharedAppServer {
6
+ constructor(url, historyCache) {
7
+ super(url);
8
+ this.historyCache = historyCache;
9
+ this.historyHeadKey = 'latest';
10
+ this.diskHeads = new Map(); this.invalidatedTurns = new Set(); this.windowSaves = new Map();
11
+ this.historyVersions = new Map();
12
+ this.on('disconnected', () => { this.diskHeads.clear(); this.invalidatedTurns.clear(); this.historyVersions.clear(); });
13
+ }
14
+
15
+ historyScope(threadId) { return historyCacheScope(this.historyIdentity, this.historySource, threadId); }
16
+ historyVersion(threadId) { return `${this.epoch}:${this.historyVersions.get(threadId) || 0}`; }
17
+
18
+ async restoreHistoryHead(threadId) {
19
+ const scope = this.historyScope(threadId);
20
+ const result = await this.historyCache?.get(scope, this.historyHeadKey);
21
+ if (scope !== this.historyScope(threadId)) throw new Error('云端账号连接已变化,请重新读取历史。');
22
+ return result;
23
+ }
24
+
25
+ saveHistoryWindow(threadId, immediate = false) {
26
+ const record = this.threads.get(threadId), scope = this.historyScope(threadId);
27
+ if (!this.historyCache || !scope || !record || record.hydrating || record.needsReload
28
+ || record.historyTrimmed || record.metadataOnly || record.readOnly || !completedHistory(record.thread.turns)) return;
29
+ const value = structuredClone({ updatedAt: record.thread.updatedAt, turns: record.thread.turns,
30
+ nextCursor: record.nextCursor, revision: record.thread.chatRevision,
31
+ ...(record.approvalBeforeMs !== undefined ? { approvalBeforeMs: record.approvalBeforeMs } : {}) });
32
+ const pending = this.windowSaves.get(scope);
33
+ if (pending) { clearTimeout(pending); this.windowSaves.delete(scope); }
34
+ const save = () => { this.windowSaves.delete(scope); return this.historyCache.put(scope, this.historyHeadKey, value); };
35
+ if (immediate) return save();
36
+ const timer = setTimeout(save, 200); timer.unref(); this.windowSaves.set(scope, timer);
37
+ }
38
+
39
+ invalidateHistory(method, params) {
40
+ const id = params.threadId || params.thread?.id, scope = this.historyScope(id);
41
+ if (!scope || !this.historyCache) return;
42
+ const turnId = params.turnId || params.turn?.id;
43
+ const whole = ['thread/deleted', 'thread/compacted'].includes(method);
44
+ if (!whole && (!turnId || !/^(?:item\/|turn\/)/.test(method))) return;
45
+ this.historyVersions.set(id, (this.historyVersions.get(id) || 0) + 1);
46
+ clearTimeout(this.windowSaves.get(scope)); this.windowSaves.delete(scope);
47
+ const key = `${scope}:${turnId}`;
48
+ if (whole || !this.invalidatedTurns.has(key)) {
49
+ this.invalidatedTurns.add(key); this.diskHeads.delete(id);
50
+ void this.historyCache.invalidate(scope, whole ? undefined : turnId);
51
+ }
52
+ if (whole) {
53
+ const record = this.threads.get(id);
54
+ if (record) record.needsReload = true;
55
+ this.emit('history-invalidated', id);
56
+ }
57
+ if (method === 'turn/completed') this.invalidatedTurns.delete(key);
58
+ }
59
+
60
+ async compactTurn(threadId, turn, cursor = null, apply, limit = 100) {
61
+ const scope = this.historyScope(threadId), candidate = this.diskHeads.get(threadId);
62
+ const version = this.historyVersion(threadId);
63
+ if (cursor && !turn.status && this.historyCache) {
64
+ const final = await this.historyCache.get(scope, `turn:${turn.id}`);
65
+ if (scope !== this.historyScope(threadId)) throw new Error('云端账号连接已变化,请重新读取历史。');
66
+ if (final) turn = { ...final.turns[0], ...turn };
67
+ }
68
+ const saved = !cursor && candidate?.head?.turns.find(value => value.id === turn.id);
69
+ if (scope && this.historyCache && saved && candidate.scope === scope && candidate.updatedAt != null
70
+ && candidate.head.updatedAt === candidate.updatedAt && completedHistory([saved])
71
+ && turnMetadata(saved) === turnMetadata(turn)) {
72
+ const result = { ...saved, ...turn, items: saved.items, itemPage: saved.itemPage };
73
+ apply?.(result); return result;
74
+ }
75
+ const result = await super.compactTurn(threadId, turn, cursor, apply, limit);
76
+ if (this.historyCache && scope === this.historyScope(threadId) && version === this.historyVersion(threadId)
77
+ && completedHistory([{ ...turn, items: [] }])) {
78
+ const { items, itemPage, ...metadata } = turn;
79
+ await this.historyCache.put(scope, `turn:${turn.id}`, { turns: [metadata] });
80
+ }
81
+ return result;
82
+ }
83
+
84
+ async history(threadId, cursor, options = {}) {
85
+ await this.connect();
86
+ let position;
87
+ try { position = JSON.parse(cursor); } catch { position = null; }
88
+ if (position?.threadId !== threadId) return super.history(threadId, cursor, options);
89
+ const scope = this.historyScope(threadId);
90
+ const version = this.historyVersion(threadId);
91
+ const key = JSON.stringify(['history', position.turnId, position.itemCursor, position.turnCursor, options.itemLimit ?? 100]);
92
+ const cached = await this.historyCache?.get(scope, key);
93
+ if (scope !== this.historyScope(threadId)) throw new Error('云端账号连接已变化,请重新读取历史。');
94
+ if (cached && version === this.historyVersion(threadId)) return { thread: { id: threadId, turns: cached.turns },
95
+ nextCursor: cached.position ? JSON.stringify(cached.position) : null };
96
+ const result = await super.history(threadId, cursor, options);
97
+ if (scope === this.historyScope(threadId) && version === this.historyVersion(threadId) && completedHistory(result.thread.turns)) {
98
+ const next = result.nextCursor ? JSON.parse(result.nextCursor) : null;
99
+ await this.historyCache?.put(scope, key, { turns: result.thread.turns, position: next });
100
+ }
101
+ return result;
102
+ }
103
+ }
@@ -0,0 +1,113 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+
5
+ const threadBudget = 8 * 1024 * 1024;
6
+ const totalBudget = 128 * 1024 * 1024;
7
+ const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
8
+
9
+ // Store confirmed ranges, not connection tokens, execution context or image bytes.
10
+ export function historyCacheScope(identity, source, threadId) {
11
+ return identity?.accountId && threadId ? digest([identity.accountId, identity.userId || '', source, threadId]) : null;
12
+ }
13
+
14
+ export function completedHistory(turns) {
15
+ if (!turns?.length || turns.some(turn => !['completed', 'failed', 'interrupted'].includes(turn.status)
16
+ || turn.cacheStub || turn.items?.some(item => item.dotsStreaming
17
+ || item.type === 'imageGeneration' && !item.savedPath && item.result))) return false;
18
+ // Signed media addresses and embedded bytes must be reread/refreshed, not replayed from disk.
19
+ const media = value => value && typeof value === 'object' && Object.entries(value).some(([key, part]) =>
20
+ typeof part === 'string' && (/^data:/.test(part) || /[?&](?:X-Amz-|X-Goog-|signature=|sig=|token=)/i.test(part))
21
+ || key === 'imageBytes' || media(part));
22
+ return !media(turns);
23
+ }
24
+
25
+ export function turnMetadata(turn) {
26
+ return digest(Object.entries(turn || {}).filter(([key]) => !['items', 'itemPage', 'cacheStub'].includes(key))
27
+ .sort(([a], [b]) => a.localeCompare(b)));
28
+ }
29
+
30
+ export class HostedHistoryCache {
31
+ constructor(stateRoot, { report = error => console.error(`托管历史缓存失败:${error.message}`), maxThreadBytes = threadBudget, maxTotalBytes = totalBudget } = {}) {
32
+ this.directory = path.join(stateRoot, 'hosted-history');
33
+ this.report = report; this.maxThreadBytes = maxThreadBytes; this.maxTotalBytes = maxTotalBytes;
34
+ this.tail = Promise.resolve();
35
+ }
36
+
37
+ async record(scope) {
38
+ try {
39
+ const record = JSON.parse(await fs.readFile(path.join(this.directory, `${scope}.json`), 'utf8'));
40
+ if (record.version !== 1 || !record.entries || Array.isArray(record.entries) || typeof record.entries !== 'object') {
41
+ throw new Error('历史缓存结构无效,需重新读取云端历史。');
42
+ }
43
+ if (Object.values(record.entries).some(entry => !Number.isFinite(entry.at) || !entry.value
44
+ || !Array.isArray(entry.value.turns) && !Array.isArray(entry.value.data))) {
45
+ throw new Error('历史缓存页结构无效,需重新读取云端历史。');
46
+ }
47
+ return record;
48
+ } catch (error) { if (error.code !== 'ENOENT') this.report(error); return { version: 1, entries: {} }; }
49
+ }
50
+
51
+ run(operation, fallback) {
52
+ const work = this.tail.then(operation).catch(error => { this.report(error); return fallback; });
53
+ this.tail = work.then(() => {}); return work;
54
+ }
55
+
56
+ get(scope, key) {
57
+ if (!scope) return Promise.resolve(null);
58
+ return this.run(async () => (await this.record(scope)).entries?.[key]?.value ?? null, null);
59
+ }
60
+
61
+ put(scope, key, value) {
62
+ if (!scope) return Promise.resolve();
63
+ // Freeze before queuing; live events may mutate the source window during disk I/O.
64
+ const snapshot = structuredClone(value);
65
+ return this.run(async () => {
66
+ const record = await this.record(scope);
67
+ record.entries ||= {};
68
+ record.entries[key] = { at: Date.now(), value: snapshot };
69
+ let text = JSON.stringify(record);
70
+ for (const [oldKey] of Object.entries(record.entries).sort((a, b) => a[1].at - b[1].at)) {
71
+ if (Buffer.byteLength(text) <= this.maxThreadBytes) break;
72
+ delete record.entries[oldKey]; text = JSON.stringify(record);
73
+ }
74
+ await this.write(scope, text);
75
+ await this.prune(scope);
76
+ });
77
+ }
78
+
79
+ invalidate(scope, turnId) {
80
+ if (!scope) return Promise.resolve();
81
+ return this.run(async () => {
82
+ const record = await this.record(scope);
83
+ for (const [key, entry] of Object.entries(record.entries || {})) {
84
+ if (!turnId || entry.value.turnIds?.includes(turnId) || entry.value.turns?.some(turn => turn.id === turnId)
85
+ || entry.value.thread?.turns?.some(turn => turn.id === turnId)) delete record.entries[key];
86
+ }
87
+ await this.write(scope, JSON.stringify(record));
88
+ });
89
+ }
90
+
91
+ async write(scope, text) {
92
+ if (!/^[a-f0-9]{64}$/.test(scope)) throw new Error('历史缓存身份无效');
93
+ await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });
94
+ const file = path.join(this.directory, `${scope}.json`), temporary = `${file}.tmp`;
95
+ try {
96
+ await fs.writeFile(temporary, text, { mode: 0o600 });
97
+ await fs.rename(temporary, file);
98
+ } finally {
99
+ try { await fs.unlink(temporary); } catch (error) { if (error.code !== 'ENOENT') this.report(error); }
100
+ }
101
+ }
102
+
103
+ async prune(current) {
104
+ const files = await Promise.all((await fs.readdir(this.directory)).filter(name => /^[a-f0-9]{64}\.json$/.test(name))
105
+ .map(async name => ({ name, ...await fs.stat(path.join(this.directory, name)) })));
106
+ let bytes = files.reduce((sum, file) => sum + file.size, 0);
107
+ for (const file of files.sort((a, b) => a.mtimeMs - b.mtimeMs)) {
108
+ if (bytes <= this.maxTotalBytes) break;
109
+ if (file.name === `${current}.json`) continue;
110
+ await fs.unlink(path.join(this.directory, file.name)); bytes -= file.size;
111
+ }
112
+ }
113
+ }