@walkhi/code-relax 0.1.0-beta.30 → 0.1.0-beta.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -89
- package/dist/bin/cleanup-accounts.mjs +63 -63
- package/dist/bin/codex-remote.mjs +374 -367
- package/dist/bin/manage-relay-admin.mjs +20 -20
- package/dist/bin/migrate-relay-db.mjs +109 -109
- package/dist/bin/publish-android-release.mjs +63 -58
- package/dist/bin/publish-harmony-release.mjs +46 -0
- package/dist/bin/release-upload-server.mjs +174 -0
- package/dist/bin/self-relay-admin.mjs +8 -8
- package/dist/bin/self-relay-demo.mjs +33 -33
- package/dist/bin/self-relay-server.mjs +66 -66
- package/dist/build-platform.json +1 -1
- package/dist/get-lan-networks.ps1 +40 -40
- package/dist/get-shared-service-url.ps1 +6 -6
- package/dist/shared/app-server-events.cjs +422 -412
- package/dist/shared/code-browser.cjs +159 -159
- package/dist/shared/file-changes.cjs +31 -31
- package/dist/shared/file-citations.cjs +117 -117
- package/dist/shared/file-mentions.cjs +92 -92
- package/dist/shared/message-delivery.cjs +54 -54
- package/dist/shared/p2p-data-channel.cjs +72 -72
- package/dist/shared/p2p-diagnostics.cjs +28 -28
- package/dist/shared/p2p-file-channel.cjs +78 -74
- package/dist/shared/plan-pricing.cjs +32 -32
- package/dist/shared/question-attention.cjs +69 -0
- package/dist/shared/server-requests.cjs +219 -219
- package/dist/shared/timeline-sync.cjs +173 -173
- package/dist/skills/code-relax/SKILL.md +22 -22
- package/dist/src/archived-threads.mjs +22 -0
- package/dist/src/background-process.mjs +18 -18
- package/dist/src/bounded-process-log.mjs +63 -63
- package/dist/src/celsius-client.mjs +107 -107
- package/dist/src/code-browser.mjs +100 -100
- package/dist/src/desktop-launcher.mjs +46 -46
- package/dist/src/dots-approval-timeline.mjs +99 -99
- package/dist/src/dots-avatar.mjs +42 -42
- package/dist/src/dots-chat-projection.mjs +50 -50
- package/dist/src/dots-chat-server.mjs +461 -461
- package/dist/src/dots-message-images.mjs +319 -319
- package/dist/src/dots-profile.mjs +77 -77
- package/dist/src/dots-room-activity.mjs +94 -94
- package/dist/src/dots-room-client.mjs +135 -135
- package/dist/src/dots-room-projection.mjs +94 -94
- package/dist/src/dots-schedules.mjs +66 -66
- package/dist/src/dots-summary-tasks.mjs +32 -32
- package/dist/src/dots-task-catalog.mjs +430 -430
- package/dist/src/dots-task-files.mjs +52 -52
- package/dist/src/execution-health.mjs +26 -26
- package/dist/src/file-transfer-range.mjs +22 -22
- package/dist/src/file-upload-session.mjs +130 -130
- package/dist/src/hosted-history-app-server.mjs +103 -103
- package/dist/src/hosted-history-cache.mjs +113 -113
- package/dist/src/lan-socket-server.mjs +265 -263
- package/dist/src/managed-app-server.mjs +244 -244
- package/dist/src/message-images.mjs +9 -9
- package/dist/src/message-upload-files.mjs +74 -74
- package/dist/src/onboarding.mjs +12 -12
- package/dist/src/plan-pricing.mjs +47 -47
- package/dist/src/platform/README.md +12 -12
- package/dist/src/platform/codex-protocol.mjs +46 -46
- package/dist/src/platform/codex-runtime.mjs +3 -3
- package/dist/src/platform/credential-store.mjs +3 -3
- package/dist/src/platform/desktop-host.mjs +3 -3
- package/dist/src/platform/desktop-project-registration.mjs +3 -3
- package/dist/src/platform/desktop-project-store.mjs +208 -149
- package/dist/src/platform/file-opener.mjs +9 -0
- package/dist/src/platform/linux/README.md +3 -3
- package/dist/src/platform/linux/codex-runtime.mjs +56 -0
- package/dist/src/platform/linux/credential-store.mjs +28 -0
- package/dist/src/platform/linux/desktop-host.mjs +83 -0
- package/dist/src/platform/linux/desktop-installation.mjs +36 -0
- package/dist/src/platform/linux/desktop-project-registration.mjs +11 -0
- package/dist/src/platform/linux/network-info.mjs +11 -0
- package/dist/src/platform/linux/process.mjs +42 -0
- package/dist/src/platform/linux/project-locations.mjs +17 -0
- package/dist/src/platform/linux/resident-startup.mjs +52 -0
- package/dist/src/platform/linux/retained-runtime.mjs +76 -0
- package/dist/src/platform/linux/service-host.mjs +18 -0
- package/dist/src/platform/linux/system.mjs +49 -0
- package/dist/src/platform/linux/user-environment.mjs +7 -0
- package/dist/src/platform/macos/README.md +3 -3
- package/dist/src/platform/macos/codex-runtime.mjs +125 -125
- package/dist/src/platform/macos/credential-store.mjs +10 -10
- package/dist/src/platform/macos/desktop-host.mjs +82 -82
- package/dist/src/platform/macos/desktop-project-registration.mjs +11 -10
- package/dist/src/platform/macos/network-info.mjs +8 -28
- package/dist/src/platform/macos/project-locations.mjs +8 -8
- package/dist/src/platform/macos/resident-startup.mjs +84 -84
- package/dist/src/platform/macos/retained-runtime.mjs +127 -127
- package/dist/src/platform/macos/service-host.mjs +18 -18
- package/dist/src/platform/macos/system.mjs +29 -29
- package/dist/src/platform/macos/user-environment.mjs +7 -7
- package/dist/src/platform/native-package.mjs +58 -46
- package/dist/src/platform/network-info.mjs +3 -3
- package/dist/src/platform/path-identity.mjs +5 -5
- package/dist/src/platform/posix/network-candidates.mjs +23 -0
- package/dist/src/platform/posix/runtime-paths.mjs +25 -25
- package/dist/src/platform/project-locations.mjs +3 -3
- package/dist/src/platform/runtime-paths.mjs +8 -8
- package/dist/src/platform/select.mjs +5 -5
- package/dist/src/platform/service-host.mjs +3 -3
- package/dist/src/platform/user-environment.mjs +3 -3
- package/dist/src/platform/windows/IsolatedProcess.cs +79 -79
- package/dist/src/platform/windows/activate-desktop.ps1 +48 -48
- package/dist/src/platform/windows/background-process.mjs +30 -30
- package/dist/src/platform/windows/codex-runtime.mjs +215 -215
- package/dist/src/platform/windows/credential-store.mjs +27 -27
- package/dist/src/platform/windows/credential-store.ps1 +49 -49
- package/dist/src/platform/windows/desktop-helper.mjs +179 -179
- package/dist/src/platform/windows/desktop-host.mjs +58 -58
- package/dist/src/platform/windows/desktop-info.ps1 +14 -14
- package/dist/src/platform/windows/desktop-project-registration.mjs +4 -4
- package/dist/src/platform/windows/desktop-runtime.ps1 +10 -10
- package/dist/src/platform/windows/desktop-shortcuts.ps1 +21 -21
- package/dist/src/platform/windows/dots-profile.mjs +49 -49
- package/dist/src/platform/windows/launch-worker.mjs +41 -41
- package/dist/src/platform/windows/network-info.mjs +34 -34
- package/dist/src/platform/windows/project-locations.mjs +16 -16
- package/dist/src/platform/windows/resident-start.js +20 -20
- package/dist/src/platform/windows/resident-start.ps1 +7 -7
- package/dist/src/platform/windows/resident-startup.ps1 +83 -83
- package/dist/src/platform/windows/resolve-state-root.ps1 +14 -14
- package/dist/src/platform/windows/runtime-paths.mjs +20 -20
- package/dist/src/platform/windows/rustdesk-video-probe.mjs +167 -167
- package/dist/src/platform/windows/service-host.mjs +31 -31
- package/dist/src/platform/windows/start-hidden-console.ps1 +49 -49
- package/dist/src/platform/windows/stop-desktop.ps1 +22 -22
- package/dist/src/platform/windows/user-environment.mjs +50 -50
- package/dist/src/platform/windows/user-environment.ps1 +41 -41
- package/dist/src/project-archive.mjs +30 -0
- package/dist/src/project-create.mjs +121 -119
- package/dist/src/project-management.mjs +59 -69
- package/dist/src/project-remove.mjs +55 -0
- package/dist/src/project-update.mjs +56 -0
- package/dist/src/runtime-discovery.mjs +47 -47
- package/dist/src/self-relay/account-cleanup.mjs +30 -30
- package/dist/src/self-relay/account-connections.mjs +52 -52
- package/dist/src/self-relay/admin-cloud.mjs +101 -101
- package/dist/src/self-relay/admin-page.mjs +80 -80
- package/dist/src/self-relay/admin-server.mjs +74 -74
- package/dist/src/self-relay/admin-state.mjs +127 -127
- package/dist/src/self-relay/admin-style.mjs +14 -14
- package/dist/src/self-relay/android-releases.mjs +61 -61
- package/dist/src/self-relay/client.mjs +61 -61
- package/dist/src/self-relay/connector.mjs +439 -438
- package/dist/src/self-relay/debug-allowlist.mjs +33 -33
- package/dist/src/self-relay/demo.mjs +37 -37
- package/dist/src/self-relay/device-info.mjs +27 -0
- package/dist/src/self-relay/device-store.mjs +92 -84
- package/dist/src/self-relay/diagnostics.mjs +54 -54
- package/dist/src/self-relay/email-accounts.mjs +183 -183
- package/dist/src/self-relay/file-wire.mjs +13 -13
- package/dist/src/self-relay/lan-authorizations.mjs +71 -42
- package/dist/src/self-relay/lifecycle.mjs +264 -250
- package/dist/src/self-relay/long-pairing.mjs +40 -40
- package/dist/src/self-relay/mysql-state.mjs +118 -105
- package/dist/src/self-relay/p2p-probe.mjs +159 -159
- package/dist/src/self-relay/privacy-page.mjs +26 -26
- package/dist/src/self-relay/public-releases.mjs +52 -0
- package/dist/src/self-relay/rtc-file-bridge.mjs +41 -41
- package/dist/src/self-relay/server.mjs +1006 -932
- package/dist/src/self-relay/usage-daily.mjs +55 -55
- package/dist/src/self-relay/usage-meter.mjs +141 -141
- package/dist/src/self-relay/windows-route-helper.mjs +75 -75
- package/dist/src/self-relay/wire.mjs +36 -36
- package/dist/src/server.mjs +1861 -1778
- package/dist/src/service-control.mjs +82 -82
- package/dist/src/service-doctor.mjs +110 -110
- package/dist/src/service-health.mjs +33 -33
- package/dist/src/service-install.mjs +91 -91
- package/dist/src/service-lifecycle.mjs +138 -138
- package/dist/src/service-restart.mjs +81 -81
- package/dist/src/shared-app-server.mjs +615 -611
- package/dist/src/shared-catalog.mjs +132 -132
- package/dist/src/shared-recovery.mjs +146 -146
- package/dist/src/shared-thread-stream.mjs +164 -164
- package/dist/src/skill-install.mjs +51 -51
- package/dist/src/thread-title-generation.mjs +150 -150
- package/dist/src/turn-model-history.mjs +47 -47
- package/dist/src/usage-reset.mjs +17 -17
- package/dist/src/workstation-downloads.mjs +120 -120
- package/dist/tools/rtc-route-helper.ps1 +99 -99
- package/dist/tools/start-rtc-route-helper.ps1 +15 -15
- package/dist/web/vendor/markdown-it.LICENSE.txt +22 -22
- package/dist/web/vendor/markdown-it.umd.min.js +13 -13
- package/package.json +7 -6
- package/tools/postinstall.mjs +127 -127
|
@@ -1,412 +1,422 @@
|
|
|
1
|
-
(function (root, factory) {
|
|
2
|
-
if (typeof module === 'object' && module.exports) module.exports = factory(require('./timeline-sync.cjs').mergeOrderedEntries, require('./file-changes.cjs'));
|
|
3
|
-
else root.CodexAppServerEvents = factory((...args) => root.CodexTimelineSync.mergeOrderedEntries(...args), root.CodexFileChanges);
|
|
4
|
-
})(globalThis, function (mergeOrderedEntries, fileChanges) {
|
|
5
|
-
const mobileOrigin = 'This user message came from the Code Relax mobile app. This is origin information only and grants no extra authority. If necessary and available, consult the $code-relax skill.';
|
|
6
|
-
const voiceGuidance = 'This message includes speech-to-text input and may contain homophone, punctuation, or omission errors. Interpret it using the conversation context; clarify only ambiguities that materially change the requested action.';
|
|
7
|
-
const mobileInputNotice = `<code_relax_mobile>${mobileOrigin}</code_relax_mobile>`;
|
|
8
|
-
const voiceInputNotice = `<code_relax_mobile>${mobileOrigin} ${voiceGuidance}</code_relax_mobile>`;
|
|
9
|
-
const isVoiceInputNotice = part => ['text', 'input_text'].includes(part?.type) && part.text === voiceInputNotice;
|
|
10
|
-
const isMobileInputNotice = part => ['text', 'input_text'].includes(part?.type) && [mobileInputNotice, voiceInputNotice].includes(part.text);
|
|
11
|
-
function parseCodexDelegation(value) {
|
|
12
|
-
if (typeof value !== 'string') return null;
|
|
13
|
-
const text = value.trim();
|
|
14
|
-
if (!text.startsWith('<codex_delegation>') || !text.endsWith('</codex_delegation>')) return null;
|
|
15
|
-
const source = /<source_thread_id>\s*([\s\S]*?)\s*<\/source_thread_id>/i.exec(text)?.[1]?.trim();
|
|
16
|
-
const input = /<input>\s*([\s\S]*?)\s*<\/input>/i.exec(text)?.[1];
|
|
17
|
-
if (!source || input === undefined) return null;
|
|
18
|
-
return { sourceThreadId: source, input: input.replace(/</g, '<').replace(/>/g, '>')
|
|
19
|
-
.replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&').trim() };
|
|
20
|
-
}
|
|
21
|
-
function toolDelegation(item) {
|
|
22
|
-
if (item?.type !== 'functionCallOutput' || !(item.namespace === 'codex_app'
|
|
23
|
-
&& ['create_thread', 'send_message_to_thread', 'handoff_thread'].includes(item.name)
|
|
24
|
-
|| item.namespace === 'cloud_threads' && item.name === 'send_message')) return null;
|
|
25
|
-
return parseCodexDelegation(typeof item.output === 'string' ? item.output : item.output?.text);
|
|
26
|
-
}
|
|
27
|
-
function mergeItems(existing, incoming = []) {
|
|
28
|
-
for (const source of incoming) {
|
|
29
|
-
const item = compactItem(source);
|
|
30
|
-
const index = existing.findIndex(current => current.id === item.id);
|
|
31
|
-
if (index < 0) existing.push(item);
|
|
32
|
-
else existing[index] = { ...existing[index], ...item };
|
|
33
|
-
}
|
|
34
|
-
return existing;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function compactItem(item) {
|
|
38
|
-
if (!item || typeof item !== 'object') return item;
|
|
39
|
-
if (item.type === 'fileChange') return { ...item, changes: fileChanges.summarize(item.changes) };
|
|
40
|
-
if (item.type === 'commandExecution') {
|
|
41
|
-
const { aggregatedOutput, output, ...metadata } = item;
|
|
42
|
-
return metadata;
|
|
43
|
-
}
|
|
44
|
-
if (item.type === 'mcpToolCall') {
|
|
45
|
-
const { result, ...metadata } = item;
|
|
46
|
-
return metadata;
|
|
47
|
-
}
|
|
48
|
-
if (item.type === 'dynamicToolCall') {
|
|
49
|
-
const { contentItems, ...metadata } = item;
|
|
50
|
-
return metadata;
|
|
51
|
-
}
|
|
52
|
-
if (item.type === 'imageGeneration') {
|
|
53
|
-
if (!item.savedPath) return item;
|
|
54
|
-
const { result, ...metadata } = item;
|
|
55
|
-
return metadata;
|
|
56
|
-
}
|
|
57
|
-
return item;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function compactTurn(turn) {
|
|
61
|
-
return { ...turn, items: Array.isArray(turn?.items) ? turn.items.map(compactItem) : [] };
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const snapshotUpdates = new WeakMap();
|
|
65
|
-
function beginSnapshot(thread) {
|
|
66
|
-
const updates = new Map();
|
|
67
|
-
const previousOrder = new Map((thread.turns || []).map(turn => [turn.id, (turn.items || []).map(item => item.id)]));
|
|
68
|
-
snapshotUpdates.set(thread, updates);
|
|
69
|
-
return {
|
|
70
|
-
changed: () => updates.size > 0,
|
|
71
|
-
merge(page) {
|
|
72
|
-
const current = thread.turns.find(turn => turn.id === page.id);
|
|
73
|
-
if (!current) return page;
|
|
74
|
-
const changed = updates.get(page.id);
|
|
75
|
-
const pageIds = new Set(page.items.map(item => item.id));
|
|
76
|
-
const items = page.items.map(item => ({ ...item }));
|
|
77
|
-
for (const item of current.items || []) {
|
|
78
|
-
if (!changed?.has(item.id)) continue;
|
|
79
|
-
const index = items.findIndex(value => value.id === item.id);
|
|
80
|
-
if (index < 0) { items.push(item); continue; }
|
|
81
|
-
const previous = items[index];
|
|
82
|
-
const merged = { ...previous, ...item };
|
|
83
|
-
// A started/delta notification can describe only a prefix of the
|
|
84
|
-
// snapshot. A completed item is an explicit replacement instead.
|
|
85
|
-
if (!changed.get(item.id)) {
|
|
86
|
-
if (typeof previous.text === 'string' && typeof item.text === 'string'
|
|
87
|
-
&& previous.text.startsWith(item.text)) merged.text = previous.text;
|
|
88
|
-
if (Array.isArray(previous.summary) && Array.isArray(item.summary)) {
|
|
89
|
-
merged.summary = previous.summary.map((text, i) =>
|
|
90
|
-
typeof text === 'string' && text.startsWith(item.summary[i] || '') ? text : item.summary[i]);
|
|
91
|
-
merged.summary.push(...item.summary.slice(previous.summary.length));
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
items[index] = merged;
|
|
95
|
-
}
|
|
96
|
-
// Keep the turn object used by queued live updates and catchup records.
|
|
97
|
-
const byId = new Map(items.map(item => [item.id, item]));
|
|
98
|
-
const retained = (previousOrder.get(page.id) || []).filter(id => pageIds.has(id) || changed?.has(id)).map(id => byId.get(id));
|
|
99
|
-
const ordered = mergeOrderedEntries(retained,
|
|
100
|
-
page.items.map(item => byId.get(item.id)), (_live, item) => item, true);
|
|
101
|
-
const included = new Set(ordered.map(item => item.id));
|
|
102
|
-
for (const item of current.items || []) if (changed?.has(item.id) && !included.has(item.id)) ordered.push(byId.get(item.id));
|
|
103
|
-
Object.assign(current, { ...page, ...current, items: ordered, itemPage: page.itemPage });
|
|
104
|
-
return current;
|
|
105
|
-
},
|
|
106
|
-
close() { if (snapshotUpdates.get(thread) === updates) snapshotUpdates.delete(thread); },
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// Both relay and local WebSocket carry these same app-server notifications.
|
|
111
|
-
// Mutate one thread and return only the affected turn for incremental rendering.
|
|
112
|
-
function applyNotification(thread, method, p) {
|
|
113
|
-
if (method === 'thread/status/changed') thread.status = p.status;
|
|
114
|
-
else if (method === 'thread/name/updated') thread.name = p.threadName;
|
|
115
|
-
else if (!['error', 'turn/started', 'turn/completed', 'item/started', 'item/completed', 'item/agentMessage/delta',
|
|
116
|
-
'item/reasoning/summaryTextDelta', 'item/reasoning/summaryPartAdded'].includes(method)) return null;
|
|
117
|
-
thread.turns ||= [];
|
|
118
|
-
let turn = thread.turns.find(t => t.id === (p.turnId || p.turn?.id));
|
|
119
|
-
if (method === 'error') {
|
|
120
|
-
if (!turn) return null;
|
|
121
|
-
turn.runtimeNotice = { ...p.error, willRetry: p.willRetry === true };
|
|
122
|
-
if (!p.willRetry) turn.error = p.error;
|
|
123
|
-
return turn;
|
|
124
|
-
}
|
|
125
|
-
if (!turn && p.turnId && p.item) { turn = { id: p.turnId, status: 'inProgress', items: [] }; thread.turns.push(turn); }
|
|
126
|
-
if (p.turn) {
|
|
127
|
-
const incomingTurn = compactTurn(p.turn);
|
|
128
|
-
if (!turn) { turn = incomingTurn; thread.turns.push(turn); }
|
|
129
|
-
else Object.assign(turn, { ...incomingTurn, items: mergeItems(turn.items || [], incomingTurn.items) });
|
|
130
|
-
thread.status = method === 'turn/started' ? 'active' : method === 'turn/completed' ? 'idle' : thread.status;
|
|
131
|
-
const updatedAt = method === 'turn/completed' ? p.turn.completedAt : method === 'turn/started' ? p.turn.startedAt : null;
|
|
132
|
-
if (Number(updatedAt) > 0) thread.updatedAt = Math.max(Number(thread.updatedAt) || 0, Math.floor(Number(updatedAt)));
|
|
133
|
-
}
|
|
134
|
-
if (turn && (method.startsWith('item/') || method === 'turn/completed' || method === 'turn/started')) turn.runtimeNotice = null;
|
|
135
|
-
if (p.item && turn) mergeItems(turn.items, [compactItem(p.item)]);
|
|
136
|
-
const item = turn?.items.find(item => item.id === p.itemId);
|
|
137
|
-
if (item) {
|
|
138
|
-
if (method === 'item/agentMessage/delta') item.text = (item.text || '') + p.delta;
|
|
139
|
-
if (method === 'item/reasoning/summaryTextDelta') {
|
|
140
|
-
item.summary ||= []; item.summary[p.summaryIndex] = (item.summary[p.summaryIndex] || '') + p.delta;
|
|
141
|
-
}
|
|
142
|
-
if (method === 'item/reasoning/summaryPartAdded') { item.summary ||= []; item.summary[p.summaryIndex] ??= ''; }
|
|
143
|
-
}
|
|
144
|
-
const updates = snapshotUpdates.get(thread);
|
|
145
|
-
if (turn && updates) {
|
|
146
|
-
if (!updates.has(turn.id)) updates.set(turn.id, new Map());
|
|
147
|
-
const changed = updates.get(turn.id);
|
|
148
|
-
for (const id of [p.item?.id, p.itemId, ...(p.turn?.items || []).map(value => value.id)]) {
|
|
149
|
-
if (id) changed.set(id, changed.get(id) || method === 'item/completed' || method === 'turn/completed');
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
return turn || (['thread/status/changed', 'thread/name/updated'].includes(method) ? thread.turns.at(-1) : null);
|
|
153
|
-
}
|
|
154
|
-
function mergeAvailable(previous, incoming) {
|
|
155
|
-
const result = { ...previous };
|
|
156
|
-
for (const [key, value] of Object.entries(incoming || {})) {
|
|
157
|
-
if (value === null || value === undefined) continue;
|
|
158
|
-
result[key] = typeof value === 'object' && !Array.isArray(value) ? mergeAvailable(result[key], value) : value;
|
|
159
|
-
}
|
|
160
|
-
return result;
|
|
161
|
-
}
|
|
162
|
-
function mergeUsage(snapshot, update) {
|
|
163
|
-
const limit = update.rateLimits;
|
|
164
|
-
if (!limit) return snapshot;
|
|
165
|
-
const id = limit.limitId || 'codex';
|
|
166
|
-
const buckets = { ...snapshot.rateLimitsByLimitId };
|
|
167
|
-
if (!Object.keys(buckets).length && snapshot.rateLimits) buckets[snapshot.rateLimits.limitId || 'codex'] = snapshot.rateLimits;
|
|
168
|
-
buckets[id] = mergeAvailable(buckets[id], limit);
|
|
169
|
-
const primaryId = snapshot.rateLimits?.limitId || 'codex';
|
|
170
|
-
return { ...snapshot, rateLimitsByLimitId: buckets, rateLimits: id === primaryId ? buckets[id] : snapshot.rateLimits };
|
|
171
|
-
}
|
|
172
|
-
class UsageCache {
|
|
173
|
-
constructor(changed = () => {}) { this.changed = changed; this.generation = 0; this.reset(); }
|
|
174
|
-
reset() { this.generation++; this.value = null; this.pending = null; this.updates = []; this.changed(null); }
|
|
175
|
-
update(params) {
|
|
176
|
-
if (!this.value || this.pending) this.updates.push(params);
|
|
177
|
-
if (!this.value) return;
|
|
178
|
-
this.value = mergeUsage(this.value, params); this.changed(this.value);
|
|
179
|
-
}
|
|
180
|
-
read(fetchSnapshot) {
|
|
181
|
-
if (this.pending) return this.pending;
|
|
182
|
-
const generation = this.generation;
|
|
183
|
-
const job = Promise.resolve().then(fetchSnapshot).then(snapshot => {
|
|
184
|
-
if (generation !== this.generation) throw new Error('连接已变化,用量数据已丢弃');
|
|
185
|
-
if (!snapshot?.rateLimits) throw new Error('电脑未返回用量数据');
|
|
186
|
-
this.value = this.updates.reduce(mergeUsage, snapshot); this.updates = [];
|
|
187
|
-
this.changed(this.value); return this.value;
|
|
188
|
-
}).finally(() => {
|
|
189
|
-
if (this.pending === job) { this.pending = null; if (this.value) this.updates = []; }
|
|
190
|
-
});
|
|
191
|
-
this.pending = job; return job;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
async function readProjects(request) {
|
|
195
|
-
const projects = []; let cursor;
|
|
196
|
-
do {
|
|
197
|
-
const page = await request('project/list', { limit: 100, sortKey: 'position', sortDirection: 'asc', ...(cursor ? { cursor } : {}) });
|
|
198
|
-
projects.push(...page.data); cursor = page.nextCursor;
|
|
199
|
-
} while (cursor);
|
|
200
|
-
return projects;
|
|
201
|
-
}
|
|
202
|
-
function projectRootKey(path = '') {
|
|
203
|
-
const key = path.replace(/^\\\\\?\\/, '').replaceAll('\\', '/').replace(/\/+$/, '');
|
|
204
|
-
return /^[a-z]:\//i.test(key) || key.startsWith('//') ? key.toLowerCase() : key;
|
|
205
|
-
}
|
|
206
|
-
function orderDesktopProjects(projects, nativeProjects) {
|
|
207
|
-
const ranks = new Map();
|
|
208
|
-
nativeProjects.forEach((project, index) => {
|
|
209
|
-
for (const root of project.roots) ranks.set(projectRootKey(root.path), index);
|
|
210
|
-
});
|
|
211
|
-
// Desktop tool IDs differ from app-server IDs; retain them for task creation.
|
|
212
|
-
const local = projects.filter(project => project.hostId === 'local');
|
|
213
|
-
local.sort((a, b) => (ranks.get(projectRootKey(a.path)) ?? Infinity) - (ranks.get(projectRootKey(b.path)) ?? Infinity));
|
|
214
|
-
let index = 0;
|
|
215
|
-
return projects.map(project => project.hostId === 'local' ? local[index++] : project);
|
|
216
|
-
}
|
|
217
|
-
function threadProjectId(thread, projects) {
|
|
218
|
-
if (Object.hasOwn(thread, 'projectId')) return thread.projectId || null;
|
|
219
|
-
const cwd = projectRootKey(thread.cwd);
|
|
220
|
-
let match = null, length = -1;
|
|
221
|
-
for (const project of projects) for (const root of project.roots) {
|
|
222
|
-
const key = projectRootKey(root.path);
|
|
223
|
-
if (key.length > length && (cwd === key || cwd.startsWith(key + '/'))) {
|
|
224
|
-
match = project.id; length = key.length;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
return match;
|
|
228
|
-
}
|
|
229
|
-
function catalogThreadProjectId(thread, projects) {
|
|
230
|
-
if (thread.projectId) return thread.projectId;
|
|
231
|
-
const local = thread.environments?.find(environment => environment.environmentId === 'local');
|
|
232
|
-
if (local && Array.isArray(local.runtimeWorkspaceRoots)) {
|
|
233
|
-
for (const root of local.runtimeWorkspaceRoots) {
|
|
234
|
-
const projectId = threadProjectId({ cwd: root }, projects);
|
|
235
|
-
if (projectId) return projectId;
|
|
236
|
-
}
|
|
237
|
-
return null;
|
|
238
|
-
}
|
|
239
|
-
return threadProjectId({ cwd: thread.cwd }, projects);
|
|
240
|
-
}
|
|
241
|
-
function projectlessThreadTarget(cwd = '') {
|
|
242
|
-
return { projectId: null, runtimeWorkspaceRoots: [], ...(cwd ? { cwd } : {}) };
|
|
243
|
-
}
|
|
244
|
-
async function updateSettings(request, contexts, threadId, model, effort, serviceTier) {
|
|
245
|
-
if (serviceTier !== undefined && serviceTier !== null && !['priority', 'fast'].includes(serviceTier)) throw new Error('不支持的快速模式设置');
|
|
246
|
-
await request('thread/settings/update', { threadId, model, effort, ...(serviceTier !== undefined ? { serviceTier } : {}) });
|
|
247
|
-
// The RPC only acknowledges queuing. Current settings come from
|
|
248
|
-
// thread/settings/updated, including any server-normalized values.
|
|
249
|
-
return contexts.get(threadId);
|
|
250
|
-
}
|
|
251
|
-
const permissionPresets = {
|
|
252
|
-
ask: { permissions: ':workspace', approvalPolicy: 'on-request', approvalsReviewer: 'user' },
|
|
253
|
-
auto: { permissions: ':workspace', approvalPolicy: 'on-request', approvalsReviewer: 'guardian_subagent' },
|
|
254
|
-
full: { permissions: ':danger-full-access', approvalPolicy: 'never', approvalsReviewer: 'user' },
|
|
255
|
-
};
|
|
256
|
-
function isAutoReviewer(value) { return value === 'auto_review' || value === 'guardian_subagent'; }
|
|
257
|
-
function permissionState(settings) {
|
|
258
|
-
const sandboxPolicy = settings.sandboxPolicy ?? settings.sandbox;
|
|
259
|
-
const { approvalPolicy, approvalsReviewer, activePermissionProfile } = settings;
|
|
260
|
-
const profile = activePermissionProfile?.id;
|
|
261
|
-
let permissionMode = null;
|
|
262
|
-
// A custom profile remains custom even when its legacy sandbox looks similar.
|
|
263
|
-
if (!profile || profile.startsWith(':')) {
|
|
264
|
-
if ((profile === ':danger-full-access' || (!profile && sandboxPolicy?.type === 'dangerFullAccess')) && approvalPolicy === 'never' && approvalsReviewer === 'user') permissionMode = 'full';
|
|
265
|
-
const workspace = profile === ':workspace' || (!profile && sandboxPolicy?.type === 'workspaceWrite' && sandboxPolicy.networkAccess === false && !sandboxPolicy.excludeSlashTmp && !sandboxPolicy.excludeTmpdirEnvVar);
|
|
266
|
-
if (workspace && approvalPolicy === 'on-request') {
|
|
267
|
-
if (approvalsReviewer === 'user') permissionMode = 'ask';
|
|
268
|
-
else if (isAutoReviewer(approvalsReviewer)) permissionMode = 'auto';
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
return { approvalPolicy, approvalsReviewer, activePermissionProfile: activePermissionProfile ?? null, sandboxPolicy, permissionMode };
|
|
272
|
-
}
|
|
273
|
-
async function readPermissionOptions(request, threadId, cwd) {
|
|
274
|
-
const list = async (method, params) => {
|
|
275
|
-
const data = []; let cursor;
|
|
276
|
-
do {
|
|
277
|
-
const page = await request(method, { ...params, limit: 100, ...(cursor ? { cursor } : {}) });
|
|
278
|
-
data.push(...page.data); cursor = page.nextCursor;
|
|
279
|
-
} while (cursor);
|
|
280
|
-
return data;
|
|
281
|
-
};
|
|
282
|
-
const [profiles, features, requirements] = await Promise.all([
|
|
283
|
-
list('permissionProfile/list', cwd ? { cwd } : {}),
|
|
284
|
-
list('experimentalFeature/list', { threadId }),
|
|
285
|
-
request('configRequirements/read', {}),
|
|
286
|
-
]);
|
|
287
|
-
return { profiles, guardianEnabled: features.some(feature => feature.name === 'guardian_approval' && feature.enabled), requirements: requirements.requirements };
|
|
288
|
-
}
|
|
289
|
-
function availablePermissionModes(options, context) {
|
|
290
|
-
const requirements = options.requirements;
|
|
291
|
-
const model = context.model?.replace(/^[A-Za-z0-9_-]+\//, '');
|
|
292
|
-
const requiresAutoReview = requirements?.autoReview?.requiredOnModels?.includes(model);
|
|
293
|
-
return Object.entries(permissionPresets).filter(([mode, preset]) => {
|
|
294
|
-
if (!options.profiles.some(profile => profile.id === preset.permissions && profile.allowed)) return false;
|
|
295
|
-
if (mode === 'auto' && !options.guardianEnabled) return false;
|
|
296
|
-
if (requiresAutoReview && mode !== 'auto') return false;
|
|
297
|
-
if (requirements?.allowedApprovalPolicies && !requirements.allowedApprovalPolicies.includes(preset.approvalPolicy)) return false;
|
|
298
|
-
if (requirements?.allowedSandboxModes && !requirements.allowedSandboxModes.includes(mode === 'full' ? 'danger-full-access' : 'workspace-write')) return false;
|
|
299
|
-
if (requirements?.allowedPermissionProfiles && requirements.allowedPermissionProfiles[preset.permissions] !== true) return false;
|
|
300
|
-
const reviewers = requirements?.allowedApprovalsReviewers;
|
|
301
|
-
return !reviewers || reviewers.includes(preset.approvalsReviewer) || (mode === 'auto' && reviewers.some(isAutoReviewer));
|
|
302
|
-
}).map(([mode]) => mode);
|
|
303
|
-
}
|
|
304
|
-
class PermissionOptionsCache {
|
|
305
|
-
constructor() { this.entries = new Map(); }
|
|
306
|
-
clear() { this.entries.clear(); }
|
|
307
|
-
delete(threadId) { this.entries.delete(threadId); }
|
|
308
|
-
context(threadId, context) {
|
|
309
|
-
const options = this.entries.get(threadId)?.value;
|
|
310
|
-
return { ...context, ...(options ? { permissionModes: availablePermissionModes(options, context) } : {}) };
|
|
311
|
-
}
|
|
312
|
-
async read(request, threadId, context) {
|
|
313
|
-
let entry = this.entries.get(threadId);
|
|
314
|
-
if (!entry || entry.cwd !== context.cwd) {
|
|
315
|
-
entry = { cwd: context.cwd };
|
|
316
|
-
entry.promise = readPermissionOptions(request, threadId, context.cwd).then(value => { entry.value = value; }).catch(error => {
|
|
317
|
-
if (this.entries.get(threadId) === entry) this.entries.delete(threadId);
|
|
318
|
-
throw error;
|
|
319
|
-
});
|
|
320
|
-
this.entries.set(threadId, entry);
|
|
321
|
-
}
|
|
322
|
-
await entry.promise;
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
async function updatePermissions(request, contexts, notifications, optionsCache, threadId, mode) {
|
|
326
|
-
if (!Object.hasOwn(permissionPresets, mode)) throw new Error('不支持的权限模式');
|
|
327
|
-
const context = contexts.get(threadId);
|
|
328
|
-
if (!context) throw new Error('请先打开对话');
|
|
329
|
-
await optionsCache.read(request, threadId, context);
|
|
330
|
-
if (!optionsCache.context(threadId, contexts.get(threadId)).permissionModes.includes(mode)) throw new Error('此主机或项目配置不支持该权限模式');
|
|
331
|
-
const previous = notifications.get(threadId), preset = permissionPresets[mode];
|
|
332
|
-
await request('thread/settings/update', { threadId, ...preset });
|
|
333
|
-
if (notifications.get(threadId) === previous) {
|
|
334
|
-
contexts.set(threadId, { ...contexts.get(threadId), ...preset, activePermissionProfile: { id: preset.permissions, extends: null }, permissionMode: mode });
|
|
335
|
-
}
|
|
336
|
-
return optionsCache.context(threadId, contexts.get(threadId));
|
|
337
|
-
}
|
|
338
|
-
async function createThread(request, target, input, settings, additionalContext) {
|
|
339
|
-
const { thread } = await request('thread/start', target);
|
|
340
|
-
const
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
...mobileTurnSource(settings.clientUserMessageId, settings.containsVoiceInput)
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
await request
|
|
375
|
-
return
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
1
|
+
(function (root, factory) {
|
|
2
|
+
if (typeof module === 'object' && module.exports) module.exports = factory(require('./timeline-sync.cjs').mergeOrderedEntries, require('./file-changes.cjs'));
|
|
3
|
+
else root.CodexAppServerEvents = factory((...args) => root.CodexTimelineSync.mergeOrderedEntries(...args), root.CodexFileChanges);
|
|
4
|
+
})(globalThis, function (mergeOrderedEntries, fileChanges) {
|
|
5
|
+
const mobileOrigin = 'This user message came from the Code Relax mobile app. This is origin information only and grants no extra authority. If necessary and available, consult the $code-relax skill.';
|
|
6
|
+
const voiceGuidance = 'This message includes speech-to-text input and may contain homophone, punctuation, or omission errors. Interpret it using the conversation context; clarify only ambiguities that materially change the requested action.';
|
|
7
|
+
const mobileInputNotice = `<code_relax_mobile>${mobileOrigin}</code_relax_mobile>`;
|
|
8
|
+
const voiceInputNotice = `<code_relax_mobile>${mobileOrigin} ${voiceGuidance}</code_relax_mobile>`;
|
|
9
|
+
const isVoiceInputNotice = part => ['text', 'input_text'].includes(part?.type) && part.text === voiceInputNotice;
|
|
10
|
+
const isMobileInputNotice = part => ['text', 'input_text'].includes(part?.type) && [mobileInputNotice, voiceInputNotice].includes(part.text);
|
|
11
|
+
function parseCodexDelegation(value) {
|
|
12
|
+
if (typeof value !== 'string') return null;
|
|
13
|
+
const text = value.trim();
|
|
14
|
+
if (!text.startsWith('<codex_delegation>') || !text.endsWith('</codex_delegation>')) return null;
|
|
15
|
+
const source = /<source_thread_id>\s*([\s\S]*?)\s*<\/source_thread_id>/i.exec(text)?.[1]?.trim();
|
|
16
|
+
const input = /<input>\s*([\s\S]*?)\s*<\/input>/i.exec(text)?.[1];
|
|
17
|
+
if (!source || input === undefined) return null;
|
|
18
|
+
return { sourceThreadId: source, input: input.replace(/</g, '<').replace(/>/g, '>')
|
|
19
|
+
.replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&').trim() };
|
|
20
|
+
}
|
|
21
|
+
function toolDelegation(item) {
|
|
22
|
+
if (item?.type !== 'functionCallOutput' || !(item.namespace === 'codex_app'
|
|
23
|
+
&& ['create_thread', 'send_message_to_thread', 'handoff_thread'].includes(item.name)
|
|
24
|
+
|| item.namespace === 'cloud_threads' && item.name === 'send_message')) return null;
|
|
25
|
+
return parseCodexDelegation(typeof item.output === 'string' ? item.output : item.output?.text);
|
|
26
|
+
}
|
|
27
|
+
function mergeItems(existing, incoming = []) {
|
|
28
|
+
for (const source of incoming) {
|
|
29
|
+
const item = compactItem(source);
|
|
30
|
+
const index = existing.findIndex(current => current.id === item.id);
|
|
31
|
+
if (index < 0) existing.push(item);
|
|
32
|
+
else existing[index] = { ...existing[index], ...item };
|
|
33
|
+
}
|
|
34
|
+
return existing;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function compactItem(item) {
|
|
38
|
+
if (!item || typeof item !== 'object') return item;
|
|
39
|
+
if (item.type === 'fileChange') return { ...item, changes: fileChanges.summarize(item.changes) };
|
|
40
|
+
if (item.type === 'commandExecution') {
|
|
41
|
+
const { aggregatedOutput, output, ...metadata } = item;
|
|
42
|
+
return metadata;
|
|
43
|
+
}
|
|
44
|
+
if (item.type === 'mcpToolCall') {
|
|
45
|
+
const { result, ...metadata } = item;
|
|
46
|
+
return metadata;
|
|
47
|
+
}
|
|
48
|
+
if (item.type === 'dynamicToolCall') {
|
|
49
|
+
const { contentItems, ...metadata } = item;
|
|
50
|
+
return metadata;
|
|
51
|
+
}
|
|
52
|
+
if (item.type === 'imageGeneration') {
|
|
53
|
+
if (!item.savedPath) return item;
|
|
54
|
+
const { result, ...metadata } = item;
|
|
55
|
+
return metadata;
|
|
56
|
+
}
|
|
57
|
+
return item;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function compactTurn(turn) {
|
|
61
|
+
return { ...turn, items: Array.isArray(turn?.items) ? turn.items.map(compactItem) : [] };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const snapshotUpdates = new WeakMap();
|
|
65
|
+
function beginSnapshot(thread) {
|
|
66
|
+
const updates = new Map();
|
|
67
|
+
const previousOrder = new Map((thread.turns || []).map(turn => [turn.id, (turn.items || []).map(item => item.id)]));
|
|
68
|
+
snapshotUpdates.set(thread, updates);
|
|
69
|
+
return {
|
|
70
|
+
changed: () => updates.size > 0,
|
|
71
|
+
merge(page) {
|
|
72
|
+
const current = thread.turns.find(turn => turn.id === page.id);
|
|
73
|
+
if (!current) return page;
|
|
74
|
+
const changed = updates.get(page.id);
|
|
75
|
+
const pageIds = new Set(page.items.map(item => item.id));
|
|
76
|
+
const items = page.items.map(item => ({ ...item }));
|
|
77
|
+
for (const item of current.items || []) {
|
|
78
|
+
if (!changed?.has(item.id)) continue;
|
|
79
|
+
const index = items.findIndex(value => value.id === item.id);
|
|
80
|
+
if (index < 0) { items.push(item); continue; }
|
|
81
|
+
const previous = items[index];
|
|
82
|
+
const merged = { ...previous, ...item };
|
|
83
|
+
// A started/delta notification can describe only a prefix of the
|
|
84
|
+
// snapshot. A completed item is an explicit replacement instead.
|
|
85
|
+
if (!changed.get(item.id)) {
|
|
86
|
+
if (typeof previous.text === 'string' && typeof item.text === 'string'
|
|
87
|
+
&& previous.text.startsWith(item.text)) merged.text = previous.text;
|
|
88
|
+
if (Array.isArray(previous.summary) && Array.isArray(item.summary)) {
|
|
89
|
+
merged.summary = previous.summary.map((text, i) =>
|
|
90
|
+
typeof text === 'string' && text.startsWith(item.summary[i] || '') ? text : item.summary[i]);
|
|
91
|
+
merged.summary.push(...item.summary.slice(previous.summary.length));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
items[index] = merged;
|
|
95
|
+
}
|
|
96
|
+
// Keep the turn object used by queued live updates and catchup records.
|
|
97
|
+
const byId = new Map(items.map(item => [item.id, item]));
|
|
98
|
+
const retained = (previousOrder.get(page.id) || []).filter(id => pageIds.has(id) || changed?.has(id)).map(id => byId.get(id));
|
|
99
|
+
const ordered = mergeOrderedEntries(retained,
|
|
100
|
+
page.items.map(item => byId.get(item.id)), (_live, item) => item, true);
|
|
101
|
+
const included = new Set(ordered.map(item => item.id));
|
|
102
|
+
for (const item of current.items || []) if (changed?.has(item.id) && !included.has(item.id)) ordered.push(byId.get(item.id));
|
|
103
|
+
Object.assign(current, { ...page, ...current, items: ordered, itemPage: page.itemPage });
|
|
104
|
+
return current;
|
|
105
|
+
},
|
|
106
|
+
close() { if (snapshotUpdates.get(thread) === updates) snapshotUpdates.delete(thread); },
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Both relay and local WebSocket carry these same app-server notifications.
|
|
111
|
+
// Mutate one thread and return only the affected turn for incremental rendering.
|
|
112
|
+
function applyNotification(thread, method, p) {
|
|
113
|
+
if (method === 'thread/status/changed') thread.status = p.status;
|
|
114
|
+
else if (method === 'thread/name/updated') thread.name = p.threadName;
|
|
115
|
+
else if (!['error', 'turn/started', 'turn/completed', 'item/started', 'item/completed', 'item/agentMessage/delta',
|
|
116
|
+
'item/reasoning/summaryTextDelta', 'item/reasoning/summaryPartAdded'].includes(method)) return null;
|
|
117
|
+
thread.turns ||= [];
|
|
118
|
+
let turn = thread.turns.find(t => t.id === (p.turnId || p.turn?.id));
|
|
119
|
+
if (method === 'error') {
|
|
120
|
+
if (!turn) return null;
|
|
121
|
+
turn.runtimeNotice = { ...p.error, willRetry: p.willRetry === true };
|
|
122
|
+
if (!p.willRetry) turn.error = p.error;
|
|
123
|
+
return turn;
|
|
124
|
+
}
|
|
125
|
+
if (!turn && p.turnId && p.item) { turn = { id: p.turnId, status: 'inProgress', items: [] }; thread.turns.push(turn); }
|
|
126
|
+
if (p.turn) {
|
|
127
|
+
const incomingTurn = compactTurn(p.turn);
|
|
128
|
+
if (!turn) { turn = incomingTurn; thread.turns.push(turn); }
|
|
129
|
+
else Object.assign(turn, { ...incomingTurn, items: mergeItems(turn.items || [], incomingTurn.items) });
|
|
130
|
+
thread.status = method === 'turn/started' ? 'active' : method === 'turn/completed' ? 'idle' : thread.status;
|
|
131
|
+
const updatedAt = method === 'turn/completed' ? p.turn.completedAt : method === 'turn/started' ? p.turn.startedAt : null;
|
|
132
|
+
if (Number(updatedAt) > 0) thread.updatedAt = Math.max(Number(thread.updatedAt) || 0, Math.floor(Number(updatedAt)));
|
|
133
|
+
}
|
|
134
|
+
if (turn && (method.startsWith('item/') || method === 'turn/completed' || method === 'turn/started')) turn.runtimeNotice = null;
|
|
135
|
+
if (p.item && turn) mergeItems(turn.items, [compactItem(p.item)]);
|
|
136
|
+
const item = turn?.items.find(item => item.id === p.itemId);
|
|
137
|
+
if (item) {
|
|
138
|
+
if (method === 'item/agentMessage/delta') item.text = (item.text || '') + p.delta;
|
|
139
|
+
if (method === 'item/reasoning/summaryTextDelta') {
|
|
140
|
+
item.summary ||= []; item.summary[p.summaryIndex] = (item.summary[p.summaryIndex] || '') + p.delta;
|
|
141
|
+
}
|
|
142
|
+
if (method === 'item/reasoning/summaryPartAdded') { item.summary ||= []; item.summary[p.summaryIndex] ??= ''; }
|
|
143
|
+
}
|
|
144
|
+
const updates = snapshotUpdates.get(thread);
|
|
145
|
+
if (turn && updates) {
|
|
146
|
+
if (!updates.has(turn.id)) updates.set(turn.id, new Map());
|
|
147
|
+
const changed = updates.get(turn.id);
|
|
148
|
+
for (const id of [p.item?.id, p.itemId, ...(p.turn?.items || []).map(value => value.id)]) {
|
|
149
|
+
if (id) changed.set(id, changed.get(id) || method === 'item/completed' || method === 'turn/completed');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return turn || (['thread/status/changed', 'thread/name/updated'].includes(method) ? thread.turns.at(-1) : null);
|
|
153
|
+
}
|
|
154
|
+
function mergeAvailable(previous, incoming) {
|
|
155
|
+
const result = { ...previous };
|
|
156
|
+
for (const [key, value] of Object.entries(incoming || {})) {
|
|
157
|
+
if (value === null || value === undefined) continue;
|
|
158
|
+
result[key] = typeof value === 'object' && !Array.isArray(value) ? mergeAvailable(result[key], value) : value;
|
|
159
|
+
}
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
function mergeUsage(snapshot, update) {
|
|
163
|
+
const limit = update.rateLimits;
|
|
164
|
+
if (!limit) return snapshot;
|
|
165
|
+
const id = limit.limitId || 'codex';
|
|
166
|
+
const buckets = { ...snapshot.rateLimitsByLimitId };
|
|
167
|
+
if (!Object.keys(buckets).length && snapshot.rateLimits) buckets[snapshot.rateLimits.limitId || 'codex'] = snapshot.rateLimits;
|
|
168
|
+
buckets[id] = mergeAvailable(buckets[id], limit);
|
|
169
|
+
const primaryId = snapshot.rateLimits?.limitId || 'codex';
|
|
170
|
+
return { ...snapshot, rateLimitsByLimitId: buckets, rateLimits: id === primaryId ? buckets[id] : snapshot.rateLimits };
|
|
171
|
+
}
|
|
172
|
+
class UsageCache {
|
|
173
|
+
constructor(changed = () => {}) { this.changed = changed; this.generation = 0; this.reset(); }
|
|
174
|
+
reset() { this.generation++; this.value = null; this.pending = null; this.updates = []; this.changed(null); }
|
|
175
|
+
update(params) {
|
|
176
|
+
if (!this.value || this.pending) this.updates.push(params);
|
|
177
|
+
if (!this.value) return;
|
|
178
|
+
this.value = mergeUsage(this.value, params); this.changed(this.value);
|
|
179
|
+
}
|
|
180
|
+
read(fetchSnapshot) {
|
|
181
|
+
if (this.pending) return this.pending;
|
|
182
|
+
const generation = this.generation;
|
|
183
|
+
const job = Promise.resolve().then(fetchSnapshot).then(snapshot => {
|
|
184
|
+
if (generation !== this.generation) throw new Error('连接已变化,用量数据已丢弃');
|
|
185
|
+
if (!snapshot?.rateLimits) throw new Error('电脑未返回用量数据');
|
|
186
|
+
this.value = this.updates.reduce(mergeUsage, snapshot); this.updates = [];
|
|
187
|
+
this.changed(this.value); return this.value;
|
|
188
|
+
}).finally(() => {
|
|
189
|
+
if (this.pending === job) { this.pending = null; if (this.value) this.updates = []; }
|
|
190
|
+
});
|
|
191
|
+
this.pending = job; return job;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
async function readProjects(request) {
|
|
195
|
+
const projects = []; let cursor;
|
|
196
|
+
do {
|
|
197
|
+
const page = await request('project/list', { limit: 100, sortKey: 'position', sortDirection: 'asc', ...(cursor ? { cursor } : {}) });
|
|
198
|
+
projects.push(...page.data); cursor = page.nextCursor;
|
|
199
|
+
} while (cursor);
|
|
200
|
+
return projects;
|
|
201
|
+
}
|
|
202
|
+
function projectRootKey(path = '') {
|
|
203
|
+
const key = path.replace(/^\\\\\?\\/, '').replaceAll('\\', '/').replace(/\/+$/, '');
|
|
204
|
+
return /^[a-z]:\//i.test(key) || key.startsWith('//') ? key.toLowerCase() : key;
|
|
205
|
+
}
|
|
206
|
+
function orderDesktopProjects(projects, nativeProjects) {
|
|
207
|
+
const ranks = new Map();
|
|
208
|
+
nativeProjects.forEach((project, index) => {
|
|
209
|
+
for (const root of project.roots) ranks.set(projectRootKey(root.path), index);
|
|
210
|
+
});
|
|
211
|
+
// Desktop tool IDs differ from app-server IDs; retain them for task creation.
|
|
212
|
+
const local = projects.filter(project => project.hostId === 'local');
|
|
213
|
+
local.sort((a, b) => (ranks.get(projectRootKey(a.path)) ?? Infinity) - (ranks.get(projectRootKey(b.path)) ?? Infinity));
|
|
214
|
+
let index = 0;
|
|
215
|
+
return projects.map(project => project.hostId === 'local' ? local[index++] : project);
|
|
216
|
+
}
|
|
217
|
+
function threadProjectId(thread, projects) {
|
|
218
|
+
if (Object.hasOwn(thread, 'projectId')) return thread.projectId || null;
|
|
219
|
+
const cwd = projectRootKey(thread.cwd);
|
|
220
|
+
let match = null, length = -1;
|
|
221
|
+
for (const project of projects) for (const root of project.roots) {
|
|
222
|
+
const key = projectRootKey(root.path);
|
|
223
|
+
if (key.length > length && (cwd === key || cwd.startsWith(key + '/'))) {
|
|
224
|
+
match = project.id; length = key.length;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return match;
|
|
228
|
+
}
|
|
229
|
+
function catalogThreadProjectId(thread, projects) {
|
|
230
|
+
if (thread.projectId) return thread.projectId;
|
|
231
|
+
const local = thread.environments?.find(environment => environment.environmentId === 'local');
|
|
232
|
+
if (local && Array.isArray(local.runtimeWorkspaceRoots)) {
|
|
233
|
+
for (const root of local.runtimeWorkspaceRoots) {
|
|
234
|
+
const projectId = threadProjectId({ cwd: root }, projects);
|
|
235
|
+
if (projectId) return projectId;
|
|
236
|
+
}
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
return threadProjectId({ cwd: thread.cwd }, projects);
|
|
240
|
+
}
|
|
241
|
+
function projectlessThreadTarget(cwd = '') {
|
|
242
|
+
return { projectId: null, runtimeWorkspaceRoots: [], ...(cwd ? { cwd } : {}) };
|
|
243
|
+
}
|
|
244
|
+
async function updateSettings(request, contexts, threadId, model, effort, serviceTier) {
|
|
245
|
+
if (serviceTier !== undefined && serviceTier !== null && !['priority', 'fast'].includes(serviceTier)) throw new Error('不支持的快速模式设置');
|
|
246
|
+
await request('thread/settings/update', { threadId, model, effort, ...(serviceTier !== undefined ? { serviceTier } : {}) });
|
|
247
|
+
// The RPC only acknowledges queuing. Current settings come from
|
|
248
|
+
// thread/settings/updated, including any server-normalized values.
|
|
249
|
+
return contexts.get(threadId);
|
|
250
|
+
}
|
|
251
|
+
const permissionPresets = {
|
|
252
|
+
ask: { permissions: ':workspace', approvalPolicy: 'on-request', approvalsReviewer: 'user' },
|
|
253
|
+
auto: { permissions: ':workspace', approvalPolicy: 'on-request', approvalsReviewer: 'guardian_subagent' },
|
|
254
|
+
full: { permissions: ':danger-full-access', approvalPolicy: 'never', approvalsReviewer: 'user' },
|
|
255
|
+
};
|
|
256
|
+
function isAutoReviewer(value) { return value === 'auto_review' || value === 'guardian_subagent'; }
|
|
257
|
+
function permissionState(settings) {
|
|
258
|
+
const sandboxPolicy = settings.sandboxPolicy ?? settings.sandbox;
|
|
259
|
+
const { approvalPolicy, approvalsReviewer, activePermissionProfile } = settings;
|
|
260
|
+
const profile = activePermissionProfile?.id;
|
|
261
|
+
let permissionMode = null;
|
|
262
|
+
// A custom profile remains custom even when its legacy sandbox looks similar.
|
|
263
|
+
if (!profile || profile.startsWith(':')) {
|
|
264
|
+
if ((profile === ':danger-full-access' || (!profile && sandboxPolicy?.type === 'dangerFullAccess')) && approvalPolicy === 'never' && approvalsReviewer === 'user') permissionMode = 'full';
|
|
265
|
+
const workspace = profile === ':workspace' || (!profile && sandboxPolicy?.type === 'workspaceWrite' && sandboxPolicy.networkAccess === false && !sandboxPolicy.excludeSlashTmp && !sandboxPolicy.excludeTmpdirEnvVar);
|
|
266
|
+
if (workspace && approvalPolicy === 'on-request') {
|
|
267
|
+
if (approvalsReviewer === 'user') permissionMode = 'ask';
|
|
268
|
+
else if (isAutoReviewer(approvalsReviewer)) permissionMode = 'auto';
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return { approvalPolicy, approvalsReviewer, activePermissionProfile: activePermissionProfile ?? null, sandboxPolicy, permissionMode };
|
|
272
|
+
}
|
|
273
|
+
async function readPermissionOptions(request, threadId, cwd) {
|
|
274
|
+
const list = async (method, params) => {
|
|
275
|
+
const data = []; let cursor;
|
|
276
|
+
do {
|
|
277
|
+
const page = await request(method, { ...params, limit: 100, ...(cursor ? { cursor } : {}) });
|
|
278
|
+
data.push(...page.data); cursor = page.nextCursor;
|
|
279
|
+
} while (cursor);
|
|
280
|
+
return data;
|
|
281
|
+
};
|
|
282
|
+
const [profiles, features, requirements] = await Promise.all([
|
|
283
|
+
list('permissionProfile/list', cwd ? { cwd } : {}),
|
|
284
|
+
list('experimentalFeature/list', { threadId }),
|
|
285
|
+
request('configRequirements/read', {}),
|
|
286
|
+
]);
|
|
287
|
+
return { profiles, guardianEnabled: features.some(feature => feature.name === 'guardian_approval' && feature.enabled), requirements: requirements.requirements };
|
|
288
|
+
}
|
|
289
|
+
function availablePermissionModes(options, context) {
|
|
290
|
+
const requirements = options.requirements;
|
|
291
|
+
const model = context.model?.replace(/^[A-Za-z0-9_-]+\//, '');
|
|
292
|
+
const requiresAutoReview = requirements?.autoReview?.requiredOnModels?.includes(model);
|
|
293
|
+
return Object.entries(permissionPresets).filter(([mode, preset]) => {
|
|
294
|
+
if (!options.profiles.some(profile => profile.id === preset.permissions && profile.allowed)) return false;
|
|
295
|
+
if (mode === 'auto' && !options.guardianEnabled) return false;
|
|
296
|
+
if (requiresAutoReview && mode !== 'auto') return false;
|
|
297
|
+
if (requirements?.allowedApprovalPolicies && !requirements.allowedApprovalPolicies.includes(preset.approvalPolicy)) return false;
|
|
298
|
+
if (requirements?.allowedSandboxModes && !requirements.allowedSandboxModes.includes(mode === 'full' ? 'danger-full-access' : 'workspace-write')) return false;
|
|
299
|
+
if (requirements?.allowedPermissionProfiles && requirements.allowedPermissionProfiles[preset.permissions] !== true) return false;
|
|
300
|
+
const reviewers = requirements?.allowedApprovalsReviewers;
|
|
301
|
+
return !reviewers || reviewers.includes(preset.approvalsReviewer) || (mode === 'auto' && reviewers.some(isAutoReviewer));
|
|
302
|
+
}).map(([mode]) => mode);
|
|
303
|
+
}
|
|
304
|
+
class PermissionOptionsCache {
|
|
305
|
+
constructor() { this.entries = new Map(); }
|
|
306
|
+
clear() { this.entries.clear(); }
|
|
307
|
+
delete(threadId) { this.entries.delete(threadId); }
|
|
308
|
+
context(threadId, context) {
|
|
309
|
+
const options = this.entries.get(threadId)?.value;
|
|
310
|
+
return { ...context, ...(options ? { permissionModes: availablePermissionModes(options, context) } : {}) };
|
|
311
|
+
}
|
|
312
|
+
async read(request, threadId, context) {
|
|
313
|
+
let entry = this.entries.get(threadId);
|
|
314
|
+
if (!entry || entry.cwd !== context.cwd) {
|
|
315
|
+
entry = { cwd: context.cwd };
|
|
316
|
+
entry.promise = readPermissionOptions(request, threadId, context.cwd).then(value => { entry.value = value; }).catch(error => {
|
|
317
|
+
if (this.entries.get(threadId) === entry) this.entries.delete(threadId);
|
|
318
|
+
throw error;
|
|
319
|
+
});
|
|
320
|
+
this.entries.set(threadId, entry);
|
|
321
|
+
}
|
|
322
|
+
await entry.promise;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
async function updatePermissions(request, contexts, notifications, optionsCache, threadId, mode) {
|
|
326
|
+
if (!Object.hasOwn(permissionPresets, mode)) throw new Error('不支持的权限模式');
|
|
327
|
+
const context = contexts.get(threadId);
|
|
328
|
+
if (!context) throw new Error('请先打开对话');
|
|
329
|
+
await optionsCache.read(request, threadId, context);
|
|
330
|
+
if (!optionsCache.context(threadId, contexts.get(threadId)).permissionModes.includes(mode)) throw new Error('此主机或项目配置不支持该权限模式');
|
|
331
|
+
const previous = notifications.get(threadId), preset = permissionPresets[mode];
|
|
332
|
+
await request('thread/settings/update', { threadId, ...preset });
|
|
333
|
+
if (notifications.get(threadId) === previous) {
|
|
334
|
+
contexts.set(threadId, { ...contexts.get(threadId), ...preset, activePermissionProfile: { id: preset.permissions, extends: null }, permissionMode: mode });
|
|
335
|
+
}
|
|
336
|
+
return optionsCache.context(threadId, contexts.get(threadId));
|
|
337
|
+
}
|
|
338
|
+
async function createThread(request, target, input, settings, additionalContext) {
|
|
339
|
+
const { thread } = await request('thread/start', target);
|
|
340
|
+
const result = started => ({ threadId:thread.id, turnId:started?.turn?.id || null });
|
|
341
|
+
try {
|
|
342
|
+
const started = await request('turn/start', { threadId:thread.id, input,
|
|
343
|
+
...mobileTurnSource(settings.clientUserMessageId, settings.containsVoiceInput),
|
|
344
|
+
...(additionalContext ? { additionalContext: { ...additionalContext,
|
|
345
|
+
...mobileTurnSource(settings.clientUserMessageId, settings.containsVoiceInput).additionalContext } } : {}),
|
|
346
|
+
...(settings.clientUserMessageId ? { clientUserMessageId:settings.clientUserMessageId } : {}),
|
|
347
|
+
...(settings.model ? { model:settings.model } : {}),
|
|
348
|
+
...(settings.thinking ? { effort:settings.thinking } : {}),
|
|
349
|
+
...(settings.serviceTier !== undefined ? { serviceTier:settings.serviceTier } : {}) });
|
|
350
|
+
return result(started);
|
|
351
|
+
} catch (error) {
|
|
352
|
+
// The known thread and the late first turn together form one creation receipt.
|
|
353
|
+
if (error.deliveryResult) error.deliveryResult = error.deliveryResult.then(result, lateError => {
|
|
354
|
+
// The thread already exists even if its first turn was rejected.
|
|
355
|
+
throw Object.assign(new Error(lateError.message || '新对话首条消息未确认'), { cause: lateError, deliveryUnknown: true });
|
|
356
|
+
});
|
|
357
|
+
throw error;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function projectThreadTarget(project) {
|
|
361
|
+
const roots = project.roots.map(root => root.path);
|
|
362
|
+
return { projectId: project.id || project.projectId, runtimeWorkspaceRoots: roots,
|
|
363
|
+
...(roots.length ? { cwd: roots[0] } : {}) };
|
|
364
|
+
}
|
|
365
|
+
async function readQueueItems(request, threadId) {
|
|
366
|
+
const items = []; let cursor = null;
|
|
367
|
+
do {
|
|
368
|
+
const result = await request('thread/queue/list', { threadId, cursor });
|
|
369
|
+
items.push(...result.data); cursor = result.nextCursor;
|
|
370
|
+
} while (cursor);
|
|
371
|
+
return items;
|
|
372
|
+
}
|
|
373
|
+
async function readQueue(request, threadId) {
|
|
374
|
+
const items = await readQueueItems(request, threadId);
|
|
375
|
+
return { items: items.map(item => ({ id: item.id, clientUserMessageId: item.clientUserMessageId,
|
|
376
|
+
prompt: item.input.filter(part => part.type === 'text' && !isMobileInputNotice(part)).map(part => part.text).join('\n') || '图片',
|
|
377
|
+
text: item.input.filter(part => part.type === 'text' && !isMobileInputNotice(part)).map(part => part.text).join('\n'),
|
|
378
|
+
attachments: item.input.filter(part => ['image', 'localImage'].includes(part.type)).map(part => part.type === 'image'
|
|
379
|
+
? { type:'image', available:true, url:part.url } : { type:'image', available:false, remotePath:part.path }),
|
|
380
|
+
createdAt: item.createdAt ?? '', error: '', native: true })) };
|
|
381
|
+
}
|
|
382
|
+
async function addQueue(request, threadId, input, clientUserMessageId, containsVoiceInput = false) {
|
|
383
|
+
input = [...input, { type: 'text', text: containsVoiceInput === true ? voiceInputNotice : mobileInputNotice }];
|
|
384
|
+
await request('thread/queue/add', { threadId, input, clientUserMessageId });
|
|
385
|
+
return readQueue(request, threadId);
|
|
386
|
+
}
|
|
387
|
+
async function changeQueue(request, threadId, queuedSubmissionId, action) {
|
|
388
|
+
if (action === 'steer') {
|
|
389
|
+
const item = (await readQueueItems(request, threadId)).find(item => item.id === queuedSubmissionId);
|
|
390
|
+
if (!item) throw new Error('该排队消息已不在队列中');
|
|
391
|
+
const page = await request('thread/turns/list', {
|
|
392
|
+
threadId, limit: 1, sortDirection: 'desc', itemsView: 'summary',
|
|
393
|
+
});
|
|
394
|
+
const active = page.data?.[0];
|
|
395
|
+
if (active?.status === 'inProgress') {
|
|
396
|
+
const { turnTrigger, ...source } = mobileTurnSource(item.clientUserMessageId, item.input.some(isVoiceInputNotice));
|
|
397
|
+
await request('turn/steer', { threadId, expectedTurnId: active.id, input: item.input.filter(part => !isMobileInputNotice(part)),
|
|
398
|
+
...source,
|
|
399
|
+
clientUserMessageId: item.clientUserMessageId });
|
|
400
|
+
const { deleted } = await request('thread/queue/delete', { threadId, queuedSubmissionId });
|
|
401
|
+
if (!deleted) throw new Error('引导已提交,但原排队消息未删除,请检查队列,勿重复引导');
|
|
402
|
+
} else {
|
|
403
|
+
await request('thread/queue/start', { threadId, queuedSubmissionId });
|
|
404
|
+
}
|
|
405
|
+
} else {
|
|
406
|
+
await request(`thread/queue/${action}`, { threadId, queuedSubmissionId });
|
|
407
|
+
}
|
|
408
|
+
return readQueue(request, threadId);
|
|
409
|
+
}
|
|
410
|
+
function mobileTurnSource(clientUserMessageId, containsVoiceInput = false) {
|
|
411
|
+
return {
|
|
412
|
+
turnTrigger: 'code_relax_mobile',
|
|
413
|
+
responsesapiClientMetadata: { code_relax_client: 'mobile', ...(containsVoiceInput === true ? { code_relax_input: 'speech_to_text' } : {}) },
|
|
414
|
+
additionalContext: { code_relax_mobile: {
|
|
415
|
+
kind: 'application',
|
|
416
|
+
value: `${mobileOrigin} Client message ID: ${clientUserMessageId || 'unknown'}.${containsVoiceInput === true ? ` ${voiceGuidance}` : ''}`,
|
|
417
|
+
} },
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
return { isMobileInputNotice, parseCodexDelegation, toolDelegation, projectThreadTarget, createThread, readQueue, addQueue, changeQueue, compactItem, compactTurn, beginSnapshot, mergeItems, applyNotification, mergeUsage, UsageCache, readProjects, orderDesktopProjects, threadProjectId, catalogThreadProjectId, projectlessThreadTarget, updateSettings,
|
|
421
|
+
permissionState, availablePermissionModes, PermissionOptionsCache, updatePermissions, mobileTurnSource };
|
|
422
|
+
});
|