@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.
- package/README.md +80 -67
- package/dist/bin/codex-remote.mjs +286 -239
- package/dist/shared/app-server-events.cjs +102 -16
- package/dist/shared/code-browser.cjs +159 -0
- package/dist/shared/file-changes.cjs +31 -0
- package/dist/shared/file-citations.cjs +117 -0
- package/dist/shared/file-mentions.cjs +80 -35
- package/dist/shared/message-delivery.cjs +38 -0
- package/dist/shared/p2p-file-channel.cjs +74 -0
- package/dist/shared/server-requests.cjs +149 -41
- package/dist/shared/service-endpoints.cjs +11 -11
- package/dist/shared/timeline-sync.cjs +173 -156
- package/dist/skills/code-relax/SKILL.md +2 -1
- package/dist/src/bounded-process-log.mjs +63 -0
- package/dist/src/celsius-client.mjs +107 -0
- package/dist/src/code-browser.mjs +101 -0
- package/dist/src/desktop-launcher.mjs +30 -30
- package/dist/src/dots-approval-timeline.mjs +99 -0
- package/dist/src/dots-avatar.mjs +42 -0
- package/dist/src/dots-chat-projection.mjs +50 -0
- package/dist/src/dots-chat-server.mjs +412 -0
- package/dist/src/dots-message-images.mjs +319 -0
- package/dist/src/dots-profile.mjs +77 -0
- package/dist/src/dots-room-activity.mjs +94 -0
- package/dist/src/dots-room-client.mjs +135 -0
- package/dist/src/dots-room-projection.mjs +94 -0
- package/dist/src/dots-schedules.mjs +66 -0
- package/dist/src/dots-summary-tasks.mjs +32 -0
- package/dist/src/dots-task-catalog.mjs +411 -0
- package/dist/src/file-transfer-range.mjs +22 -0
- package/dist/src/file-upload-session.mjs +130 -124
- package/dist/src/hosted-history-app-server.mjs +103 -0
- package/dist/src/hosted-history-cache.mjs +113 -0
- package/dist/src/lan-socket-server.mjs +205 -160
- package/dist/src/managed-app-server.mjs +241 -238
- package/dist/src/message-upload-files.mjs +74 -0
- package/dist/src/platform/windows/activate-desktop.ps1 +48 -0
- package/dist/src/platform/windows/codex-runtime.mjs +253 -251
- package/dist/src/platform/windows/desktop-host.mjs +38 -32
- package/dist/src/platform/windows/desktop-info.ps1 +2 -2
- package/dist/src/platform/windows/desktop-project-registration.mjs +153 -0
- package/dist/src/platform/windows/dots-profile.mjs +49 -0
- package/dist/src/platform/windows/launch-worker.mjs +41 -42
- package/dist/src/platform/windows/project-locations.mjs +16 -0
- package/dist/src/project-create.mjs +119 -0
- package/dist/src/project-management.mjs +69 -0
- package/dist/src/self-relay/account-connections.mjs +52 -0
- package/dist/src/self-relay/admin-page.mjs +80 -80
- package/dist/src/self-relay/admin-style.mjs +14 -9
- package/dist/src/self-relay/connector.mjs +22 -4
- package/dist/src/self-relay/file-wire.mjs +13 -0
- package/dist/src/self-relay/p2p-probe.mjs +152 -123
- package/dist/src/self-relay/rtc-file-bridge.mjs +41 -0
- package/dist/src/self-relay/server.mjs +894 -849
- package/dist/src/server.mjs +463 -148
- package/dist/src/service-doctor.mjs +72 -61
- package/dist/src/service-lifecycle.mjs +51 -43
- package/dist/src/shared-app-server.mjs +166 -107
- package/dist/src/shared-catalog.mjs +132 -40
- package/dist/src/shared-thread-stream.mjs +103 -25
- package/dist/src/usage-reset.mjs +17 -0
- package/dist/src/workstation-downloads.mjs +120 -0
- package/package.json +1 -1
|
@@ -1,238 +1,241 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import net from 'node:net';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { EventEmitter } from 'node:events';
|
|
5
|
-
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
-
import { readRecord, writeRecord } from './service-lifecycle.mjs';
|
|
7
|
-
import { SharedAppServer } from './shared-app-server.mjs';
|
|
8
|
-
import { pruneRetainedDesktopRuntimes, resolveCodexRuntime, runtimeFilesAvailable } from './platform/windows/codex-runtime.mjs';
|
|
9
|
-
|
|
10
|
-
export const managedAppServerUrl = 'ws://127.0.0.1:45839';
|
|
11
|
-
export const managedAppServerReadyUrl = 'http://127.0.0.1:45839/readyz';
|
|
12
|
-
export const managedAppServerLauncherRevision =
|
|
13
|
-
const retryDelays = [1_000, 2_000, 5_000, 10_000, 20_000];
|
|
14
|
-
|
|
15
|
-
export function managedPortAvailable() {
|
|
16
|
-
return new Promise(resolve => {
|
|
17
|
-
const server = net.createServer();
|
|
18
|
-
server.once('error', () => resolve(false));
|
|
19
|
-
server.listen(45839, '127.0.0.1', () => server.close(() => resolve(true)));
|
|
20
|
-
});
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export class ManagedAppServer extends EventEmitter {
|
|
24
|
-
constructor({ stateRoot, host, environment = process.env, available = managedPortAvailable,
|
|
25
|
-
wait = delay, timeout = 30_000, now = Date.now, client = new SharedAppServer(managedAppServerUrl) }) {
|
|
26
|
-
super();
|
|
27
|
-
this.stateRoot = stateRoot;
|
|
28
|
-
this.host = host;
|
|
29
|
-
this.environment = environment;
|
|
30
|
-
this.available = available;
|
|
31
|
-
this.wait = wait;
|
|
32
|
-
this.timeout = timeout;
|
|
33
|
-
this.now = now;
|
|
34
|
-
this.recordPath = path.join(stateRoot, 'managed-app-server.json');
|
|
35
|
-
this.client = client;
|
|
36
|
-
this.state = { state: 'absent', ready: false, error: null };
|
|
37
|
-
this.restartStatus = null;
|
|
38
|
-
this.stopped = true;
|
|
39
|
-
this.restarting = false;
|
|
40
|
-
this.retryAttempt = 0;
|
|
41
|
-
this.retryAfter = 0;
|
|
42
|
-
this.client.on('disconnected', () => {
|
|
43
|
-
if (!this.stopped && !this.restarting) this.failed('Codex 内核连接断开。');
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
snapshot() {
|
|
48
|
-
return { ...this.state,
|
|
49
|
-
version: this.state.ready && this.client.ready ? this.client.serverVersion || null : null,
|
|
50
|
-
...(this.restartStatus ? { restart: { ...this.restartStatus } } : {}) };
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async start() {
|
|
54
|
-
this.stopped = false;
|
|
55
|
-
return this.ensure();
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
async ensure() {
|
|
59
|
-
if (this.stopped) return false;
|
|
60
|
-
if (this.restarting) return false;
|
|
61
|
-
if (this.work) return this.work;
|
|
62
|
-
if (this.now() < this.retryAfter) return false;
|
|
63
|
-
this.work = this.ensureNow().finally(() => { this.work = null; });
|
|
64
|
-
return this.work;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async ensureNow() {
|
|
68
|
-
// Keep an already verified instance available while the periodic identity
|
|
69
|
-
// check runs; publishing "starting" every three seconds makes health flicker.
|
|
70
|
-
if (!this.state.ready) this.publish({ state: 'starting', ready: false, error: null });
|
|
71
|
-
try {
|
|
72
|
-
fs.mkdirSync(this.stateRoot, { recursive: true });
|
|
73
|
-
let record = null, actual = null;
|
|
74
|
-
const candidate = readRecord(this.recordPath);
|
|
75
|
-
const process = candidate?.pid ? await this.host.process(candidate.pid) : null;
|
|
76
|
-
if (sameManagedProcess(candidate, process)) { record = candidate; actual = process; }
|
|
77
|
-
const startedHere = !actual;
|
|
78
|
-
const savedRuntime = actual ? readRecord(path.join(this.stateRoot, 'codex-runtime.json')) : null;
|
|
79
|
-
const runtime = actual && savedRuntime?.executable && runtimeFilesAvailable(savedRuntime.executable)
|
|
80
|
-
? savedRuntime
|
|
81
|
-
: await resolveCodexRuntime(this.stateRoot, { refresh: !actual, environment: this.environment });
|
|
82
|
-
if (actual && !runtimeFilesAvailable(actual.executable)) {
|
|
83
|
-
throw new Error(`运行中的 Codex 内核目录已被移除或缺少 codex-code-mode-host.exe:${actual.executable};已找到可用内核 ${runtime.executable},请确认重启内核。`);
|
|
84
|
-
}
|
|
85
|
-
if (!actual) {
|
|
86
|
-
if (!await this.available()) throw new Error('45839 被未识别进程占用,未启动或结束任何进程。');
|
|
87
|
-
const childEnvironment = { ...this.environment };
|
|
88
|
-
childEnvironment.CODEX_HOME = runtime.codexHome;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
record = { ...
|
|
102
|
-
writeRecord(this.recordPath, record);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
return
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
this.
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
if (
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
this.
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
this.
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
this.
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
await this.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import net from 'node:net';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { EventEmitter } from 'node:events';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { readRecord, writeRecord } from './service-lifecycle.mjs';
|
|
7
|
+
import { SharedAppServer } from './shared-app-server.mjs';
|
|
8
|
+
import { pruneRetainedDesktopRuntimes, resolveCodexRuntime, runtimeFilesAvailable } from './platform/windows/codex-runtime.mjs';
|
|
9
|
+
|
|
10
|
+
export const managedAppServerUrl = 'ws://127.0.0.1:45839';
|
|
11
|
+
export const managedAppServerReadyUrl = 'http://127.0.0.1:45839/readyz';
|
|
12
|
+
export const managedAppServerLauncherRevision = 3;
|
|
13
|
+
const retryDelays = [1_000, 2_000, 5_000, 10_000, 20_000];
|
|
14
|
+
|
|
15
|
+
export function managedPortAvailable() {
|
|
16
|
+
return new Promise(resolve => {
|
|
17
|
+
const server = net.createServer();
|
|
18
|
+
server.once('error', () => resolve(false));
|
|
19
|
+
server.listen(45839, '127.0.0.1', () => server.close(() => resolve(true)));
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class ManagedAppServer extends EventEmitter {
|
|
24
|
+
constructor({ stateRoot, host, environment = process.env, available = managedPortAvailable,
|
|
25
|
+
wait = delay, timeout = 30_000, now = Date.now, client = new SharedAppServer(managedAppServerUrl) }) {
|
|
26
|
+
super();
|
|
27
|
+
this.stateRoot = stateRoot;
|
|
28
|
+
this.host = host;
|
|
29
|
+
this.environment = environment;
|
|
30
|
+
this.available = available;
|
|
31
|
+
this.wait = wait;
|
|
32
|
+
this.timeout = timeout;
|
|
33
|
+
this.now = now;
|
|
34
|
+
this.recordPath = path.join(stateRoot, 'managed-app-server.json');
|
|
35
|
+
this.client = client;
|
|
36
|
+
this.state = { state: 'absent', ready: false, error: null };
|
|
37
|
+
this.restartStatus = null;
|
|
38
|
+
this.stopped = true;
|
|
39
|
+
this.restarting = false;
|
|
40
|
+
this.retryAttempt = 0;
|
|
41
|
+
this.retryAfter = 0;
|
|
42
|
+
this.client.on('disconnected', () => {
|
|
43
|
+
if (!this.stopped && !this.restarting) this.failed('Codex 内核连接断开。');
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
snapshot() {
|
|
48
|
+
return { ...this.state,
|
|
49
|
+
version: this.state.ready && this.client.ready ? this.client.serverVersion || null : null,
|
|
50
|
+
...(this.restartStatus ? { restart: { ...this.restartStatus } } : {}) };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async start() {
|
|
54
|
+
this.stopped = false;
|
|
55
|
+
return this.ensure();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async ensure() {
|
|
59
|
+
if (this.stopped) return false;
|
|
60
|
+
if (this.restarting) return false;
|
|
61
|
+
if (this.work) return this.work;
|
|
62
|
+
if (this.now() < this.retryAfter) return false;
|
|
63
|
+
this.work = this.ensureNow().finally(() => { this.work = null; });
|
|
64
|
+
return this.work;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async ensureNow() {
|
|
68
|
+
// Keep an already verified instance available while the periodic identity
|
|
69
|
+
// check runs; publishing "starting" every three seconds makes health flicker.
|
|
70
|
+
if (!this.state.ready) this.publish({ state: 'starting', ready: false, error: null });
|
|
71
|
+
try {
|
|
72
|
+
fs.mkdirSync(this.stateRoot, { recursive: true });
|
|
73
|
+
let record = null, actual = null;
|
|
74
|
+
const candidate = readRecord(this.recordPath);
|
|
75
|
+
const process = candidate?.pid ? await this.host.process(candidate.pid) : null;
|
|
76
|
+
if (sameManagedProcess(candidate, process)) { record = candidate; actual = process; }
|
|
77
|
+
const startedHere = !actual;
|
|
78
|
+
const savedRuntime = actual ? readRecord(path.join(this.stateRoot, 'codex-runtime.json')) : null;
|
|
79
|
+
const runtime = actual && savedRuntime?.executable && runtimeFilesAvailable(savedRuntime.executable)
|
|
80
|
+
? savedRuntime
|
|
81
|
+
: await resolveCodexRuntime(this.stateRoot, { refresh: !actual, environment: this.environment });
|
|
82
|
+
if (actual && !runtimeFilesAvailable(actual.executable)) {
|
|
83
|
+
throw new Error(`运行中的 Codex 内核目录已被移除或缺少 codex-code-mode-host.exe:${actual.executable};已找到可用内核 ${runtime.executable},请确认重启内核。`);
|
|
84
|
+
}
|
|
85
|
+
if (!actual) {
|
|
86
|
+
if (!await this.available()) throw new Error('45839 被未识别进程占用,未启动或结束任何进程。');
|
|
87
|
+
const childEnvironment = { ...this.environment };
|
|
88
|
+
childEnvironment.CODEX_HOME = runtime.codexHome;
|
|
89
|
+
// Desktop's inherited INFO tracing can emit enter/exit on every poll.
|
|
90
|
+
// The managed background kernel retains warnings and errors only.
|
|
91
|
+
childEnvironment.RUST_LOG = 'warn';
|
|
92
|
+
for (const key of ['CODEX_APP_SERVER_WS_URL', 'CODEX_APP_SERVER_FORCE_CLI', 'CODEX_APP_TOOLS_PIPE_PATH']) delete childEnvironment[key];
|
|
93
|
+
for (const key of Object.keys(childEnvironment)) {
|
|
94
|
+
if (/^npm_/iu.test(key) || key.toUpperCase() === 'INIT_CWD') delete childEnvironment[key];
|
|
95
|
+
}
|
|
96
|
+
const pid = await this.host.start(runtime.executable, ['app-server', '--listen', managedAppServerUrl], childEnvironment,
|
|
97
|
+
[path.join(this.stateRoot, 'managed-app-server.stdout.log'), path.join(this.stateRoot, 'managed-app-server.stderr.log')]);
|
|
98
|
+
const started = await this.host.process(pid);
|
|
99
|
+
if (!sameManagedProcess(started, started)) throw new Error('Codex 内核启动后进程身份无法确认。');
|
|
100
|
+
actual = started;
|
|
101
|
+
record = { ...started, launcherRevision: managedAppServerLauncherRevision };
|
|
102
|
+
writeRecord(this.recordPath, record);
|
|
103
|
+
} else if (!readRecord(this.recordPath)) {
|
|
104
|
+
record = { ...actual, launcherRevision: Number.isSafeInteger(record?.launcherRevision) ? record.launcherRevision : 0 };
|
|
105
|
+
writeRecord(this.recordPath, record);
|
|
106
|
+
}
|
|
107
|
+
await this.waitUntilReady(actual);
|
|
108
|
+
await this.client.connect();
|
|
109
|
+
if (!this.client.ready) throw new Error('Codex 内核协议初始化未完成。');
|
|
110
|
+
if (startedHere) {
|
|
111
|
+
try { pruneRetainedDesktopRuntimes(this.stateRoot, actual.executable); }
|
|
112
|
+
catch (error) { console.error('旧版 Codex 内核文件清理失败:', error); }
|
|
113
|
+
}
|
|
114
|
+
const preferredExecutable = path.resolve(runtime.executable);
|
|
115
|
+
const updatePending = path.resolve(actual.executable).toLowerCase() !== preferredExecutable.toLowerCase();
|
|
116
|
+
const launcherRevision = Number.isSafeInteger(record?.launcherRevision) ? record.launcherRevision : 0;
|
|
117
|
+
this.retryAttempt = 0;
|
|
118
|
+
this.retryAfter = 0;
|
|
119
|
+
this.publish({ state: 'ready', ready: true, error: null, pid: actual.pid,
|
|
120
|
+
created: actual.created, executable: actual.executable, preferredExecutable,
|
|
121
|
+
updatePending, launcherRevision, selectedVersion: runtime.version, source: runtime.source,
|
|
122
|
+
launcherRestartRequired: launcherRevision !== managedAppServerLauncherRevision,
|
|
123
|
+
url: managedAppServerUrl });
|
|
124
|
+
return true;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
this.failed(error instanceof Error ? error.message : String(error));
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async waitUntilReady(expected) {
|
|
132
|
+
const deadline = this.now() + this.timeout;
|
|
133
|
+
while (true) {
|
|
134
|
+
const actual = await this.host.process(expected.pid);
|
|
135
|
+
if (!sameManagedProcess(expected, actual)) throw new Error('Codex 内核在就绪前退出。');
|
|
136
|
+
if (await this.host.ready(managedAppServerReadyUrl)) return;
|
|
137
|
+
if (this.now() >= deadline) throw new Error('Codex 内核未在 30 秒内就绪,请查看工作站诊断日志。');
|
|
138
|
+
await this.wait(250);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
restart(operationId) {
|
|
143
|
+
if (this.stopped) throw new Error('工作站服务正在停止,不能重启 Codex 内核。');
|
|
144
|
+
if (this.restartWork) {
|
|
145
|
+
if (this.restartStatus?.operationId === operationId) return this.snapshot();
|
|
146
|
+
const error = new Error('Codex 内核已经在重启,请等待当前操作完成。');
|
|
147
|
+
error.code = 'managed_app_server_restarting';
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
this.restartStatus = { operationId, status: 'running', stage: 'checking', error: null,
|
|
151
|
+
startedAt: new Date(this.now()).toISOString() };
|
|
152
|
+
this.emit('state', this.snapshot());
|
|
153
|
+
this.restartWork = this.restartNow().finally(() => { this.restartWork = null; });
|
|
154
|
+
return this.snapshot();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async restartNow() {
|
|
158
|
+
this.restarting = true;
|
|
159
|
+
const previous = this.state;
|
|
160
|
+
this.publish({ ...previous, state: 'restarting', ready: false, error: null });
|
|
161
|
+
try {
|
|
162
|
+
const record = readRecord(this.recordPath);
|
|
163
|
+
const actual = record?.pid ? await this.host.process(record.pid) : null;
|
|
164
|
+
if (actual && !sameManagedProcess(record, actual)) {
|
|
165
|
+
throw new Error('Codex 内核进程身份已经变化,未结束任何进程。');
|
|
166
|
+
}
|
|
167
|
+
if (!actual && !await this.available()) throw new Error('45839 被未识别进程占用,未结束任何进程。');
|
|
168
|
+
this.restartStage('stopping');
|
|
169
|
+
// Resolve the replacement before stopping the current working process.
|
|
170
|
+
const runtime = await resolveCodexRuntime(this.stateRoot, { refresh: true, environment: this.environment });
|
|
171
|
+
const desktop = await this.host.prepareKernelRestart?.();
|
|
172
|
+
this.client.close();
|
|
173
|
+
if (actual) {
|
|
174
|
+
await this.host.stop(actual.pid);
|
|
175
|
+
await this.waitUntilStopped(actual);
|
|
176
|
+
} else if (!await this.available()) {
|
|
177
|
+
throw new Error('45839 被未识别进程占用,未结束任何进程。');
|
|
178
|
+
}
|
|
179
|
+
fs.rmSync(this.recordPath, { force: true });
|
|
180
|
+
this.retryAttempt = 0;
|
|
181
|
+
this.retryAfter = 0;
|
|
182
|
+
this.restartStage('starting');
|
|
183
|
+
const ready = await this.ensureNow();
|
|
184
|
+
if (!ready) throw new Error(this.state.error || 'Codex 内核未能重新启动。');
|
|
185
|
+
const desktopEnvironment = { ...this.environment, CODEX_HOME: runtime.codexHome, CODEX_APP_SERVER_WS_URL: managedAppServerUrl };
|
|
186
|
+
delete desktopEnvironment.CODEX_APP_SERVER_FORCE_CLI;
|
|
187
|
+
delete desktopEnvironment.CODEX_APP_TOOLS_PIPE_PATH;
|
|
188
|
+
await this.host.resumeAfterKernelRestart?.(desktop, desktopEnvironment);
|
|
189
|
+
this.restartStatus = { ...this.restartStatus, status: 'completed', stage: 'ready',
|
|
190
|
+
completedAt: new Date(this.now()).toISOString() };
|
|
191
|
+
this.emit('state', this.snapshot());
|
|
192
|
+
} catch (error) {
|
|
193
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
194
|
+
if (this.state.state === 'restarting') this.failed(message);
|
|
195
|
+
this.restartStatus = { ...this.restartStatus, status: 'failed', stage: 'failed', error: message,
|
|
196
|
+
completedAt: new Date(this.now()).toISOString() };
|
|
197
|
+
this.emit('state', this.snapshot());
|
|
198
|
+
} finally {
|
|
199
|
+
this.restarting = false;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
restartStage(stage) {
|
|
204
|
+
this.restartStatus = { ...this.restartStatus, stage };
|
|
205
|
+
this.emit('state', this.snapshot());
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async waitUntilStopped(expected) {
|
|
209
|
+
const deadline = this.now() + 10_000;
|
|
210
|
+
while (true) {
|
|
211
|
+
const actual = await this.host.process(expected.pid);
|
|
212
|
+
if (!sameManagedProcess(expected, actual) && await this.available()) return;
|
|
213
|
+
if (this.now() >= deadline) throw new Error('Codex 内核未在 10 秒内退出;不会启动第二个实例。');
|
|
214
|
+
await this.wait(100);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
failed(message) {
|
|
219
|
+
const retryMs = retryDelays[Math.min(this.retryAttempt++, retryDelays.length - 1)];
|
|
220
|
+
this.retryAfter = this.now() + retryMs;
|
|
221
|
+
this.publish({ state: 'failed', ready: false, error: message, retryAt: new Date(this.retryAfter).toISOString() });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
publish(value) {
|
|
225
|
+
const changed = JSON.stringify(value) !== JSON.stringify(this.state);
|
|
226
|
+
this.state = value;
|
|
227
|
+
if (changed) this.emit('state', this.snapshot());
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
close() {
|
|
231
|
+
this.stopped = true;
|
|
232
|
+
this.client.close();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function sameManagedProcess(record, actual) {
|
|
237
|
+
if (!record || !actual || record.pid !== actual.pid || record.created !== actual.created) return false;
|
|
238
|
+
if (String(record.executable || '').toLowerCase() !== String(actual.executable || '').toLowerCase()) return false;
|
|
239
|
+
const command = String(actual.command || '').toLowerCase();
|
|
240
|
+
return command.includes('app-server') && command.includes(managedAppServerUrl);
|
|
241
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import sharp from 'sharp';
|
|
4
|
+
import media from '../shared/code-browser.cjs';
|
|
5
|
+
import { validateInlineImage } from './message-images.mjs';
|
|
6
|
+
import { MAX_FILE_BYTES, MAX_FILE_COUNT, MAX_TOTAL_BYTES } from './file-upload-session.mjs';
|
|
7
|
+
|
|
8
|
+
const mimeTypes = { pdf: 'application/pdf', txt: 'text/plain', md: 'text/markdown', csv: 'text/csv',
|
|
9
|
+
json: 'application/json', zip: 'application/zip', doc: 'application/msword',
|
|
10
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
11
|
+
xls: 'application/vnd.ms-excel', xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
12
|
+
ppt: 'application/vnd.ms-powerpoint', pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' };
|
|
13
|
+
|
|
14
|
+
async function localFile(file, directory) {
|
|
15
|
+
if (typeof file?.path !== 'string' || typeof file.name !== 'string' || !file.name || /[\r\n\0]/.test(file.name)) {
|
|
16
|
+
throw new Error('附件信息无效,请重新选择。');
|
|
17
|
+
}
|
|
18
|
+
const root = await fs.realpath(directory), resolved = await fs.realpath(file.path);
|
|
19
|
+
if (path.relative(root, path.dirname(resolved)) !== '') throw new Error('附件必须来自本次工作站上传目录。');
|
|
20
|
+
const handle = await fs.open(resolved, 'r');
|
|
21
|
+
try {
|
|
22
|
+
const stat = await handle.stat();
|
|
23
|
+
if (!stat.isFile() || stat.size < 1 || stat.size > MAX_FILE_BYTES) throw new Error('附件为空或超过 20 MiB。');
|
|
24
|
+
const bytes = await handle.readFile();
|
|
25
|
+
if (bytes.length !== stat.size) throw new Error('附件在读取时发生变化,请重新上传。');
|
|
26
|
+
const mimeType = media.mediaMime(file) || mimeTypes[path.extname(file.name).slice(1).toLowerCase()] || 'application/octet-stream';
|
|
27
|
+
if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(mimeType)) throw new Error('附件类型无效。');
|
|
28
|
+
return { name: file.name, mimeType, bytes };
|
|
29
|
+
} finally { await handle.close(); }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function readMessageUploads(body, uploadsRoot) {
|
|
33
|
+
const images = body.images ?? [], originals = body.originalImages ?? [], files = body.files ?? [];
|
|
34
|
+
if (![images, originals, files].every(Array.isArray) || images.length + originals.length > 4 || files.length + originals.length > MAX_FILE_COUNT) {
|
|
35
|
+
throw new Error('每条消息最多 4 张图片、4 个文件。');
|
|
36
|
+
}
|
|
37
|
+
const uploads = [];
|
|
38
|
+
let imageBytes = 0, fileBytes = 0;
|
|
39
|
+
for (const image of images) {
|
|
40
|
+
let file;
|
|
41
|
+
if (typeof image === 'string' && image.startsWith('data:')) {
|
|
42
|
+
validateInlineImage(image);
|
|
43
|
+
const mimeType = image.slice(5, image.indexOf(';'));
|
|
44
|
+
file = { name: `image.${mimeType.split('/')[1]}`, mimeType, bytes: Buffer.from(image.slice(image.indexOf(',') + 1), 'base64') };
|
|
45
|
+
} else {
|
|
46
|
+
if (typeof image !== 'string' || !/^[a-f0-9]{64}$/.test(image)) throw new Error('图片标识无效。');
|
|
47
|
+
let extension = 'webp';
|
|
48
|
+
try { await fs.access(path.join(uploadsRoot, `${image}.webp`)); }
|
|
49
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; extension = 'png'; }
|
|
50
|
+
file = await localFile({ path: path.join(uploadsRoot, `${image}.${extension}`), name: `image.${extension}` }, uploadsRoot);
|
|
51
|
+
}
|
|
52
|
+
imageBytes += file.bytes.length;
|
|
53
|
+
if (imageBytes > 8 * 1024 * 1024) throw new Error('压缩图片合计不能超过 8 MiB。');
|
|
54
|
+
uploads.push(file);
|
|
55
|
+
}
|
|
56
|
+
for (const original of originals) {
|
|
57
|
+
if (typeof original !== 'string' || !/\.(png|jpe?g|webp|gif)$/i.test(original)) throw new Error('原图路径无效。');
|
|
58
|
+
}
|
|
59
|
+
for (const file of [...originals.map(value => ({ path: value, name: path.basename(value) })), ...files]) {
|
|
60
|
+
const uploaded = await localFile(file, path.join(uploadsRoot, 'incoming'));
|
|
61
|
+
fileBytes += uploaded.bytes.length;
|
|
62
|
+
if (fileBytes > MAX_TOTAL_BYTES) throw new Error('文件合计不能超过 40 MiB。');
|
|
63
|
+
uploads.push(uploaded);
|
|
64
|
+
}
|
|
65
|
+
for (const file of uploads) {
|
|
66
|
+
if (/^image\/(?:png|jpeg|webp|gif)$/.test(file.mimeType)) {
|
|
67
|
+
const metadata = await sharp(file.bytes).metadata();
|
|
68
|
+
file.width = metadata.width; file.height = metadata.height;
|
|
69
|
+
if (!file.width || !file.height) throw new Error('无法读取 图片尺寸。');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (uploads.filter(file => file.width).length > 4) throw new Error('每条消息最多 4 张图片。');
|
|
73
|
+
return uploads;
|
|
74
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[Parameter(Mandatory=$true)][string]$Executable,
|
|
3
|
+
[Parameter(Mandatory=$true)][string]$AppServerUrl
|
|
4
|
+
)
|
|
5
|
+
$ErrorActionPreference = 'Stop'
|
|
6
|
+
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
7
|
+
$package = Get-AppxPackage OpenAI.Codex | Select-Object -First 1
|
|
8
|
+
if (-not $package -or $Executable -ne (Join-Path $package.InstallLocation 'app/ChatGPT.exe')) {
|
|
9
|
+
throw 'Desktop executable identity changed; activation stopped.'
|
|
10
|
+
}
|
|
11
|
+
# Packaged activation uses the user's environment, not the worker's env block.
|
|
12
|
+
# Installation already owns and broadcasts this setting. Do not silently launch
|
|
13
|
+
# a separate app-server if it has been removed or changed since installation.
|
|
14
|
+
if ([Environment]::GetEnvironmentVariable('CODEX_APP_SERVER_WS_URL', 'User') -ne $AppServerUrl) {
|
|
15
|
+
throw 'Desktop app-server environment differs from the workstation; run relax setup to repair it.'
|
|
16
|
+
}
|
|
17
|
+
if ([Environment]::GetEnvironmentVariable('CODEX_APP_SERVER_FORCE_CLI', 'User') -eq '1' -or
|
|
18
|
+
[Environment]::GetEnvironmentVariable('CODEX_APP_SERVER_FORCE_CLI', 'Machine') -eq '1') {
|
|
19
|
+
throw 'CODEX_APP_SERVER_FORCE_CLI=1 prevents Desktop from connecting to the workstation.'
|
|
20
|
+
}
|
|
21
|
+
# Activate the registered application so Windows supplies its MSIX identity.
|
|
22
|
+
# Never spawn ChatGPT.exe through the hidden-console broker: a bootstrap failure
|
|
23
|
+
# can leave a windowless Electron singleton blocking subsequent taskbar launches.
|
|
24
|
+
Add-Type -TypeDefinition @'
|
|
25
|
+
using System;
|
|
26
|
+
using System.Runtime.InteropServices;
|
|
27
|
+
namespace CodeRelax {
|
|
28
|
+
[ComImport, Guid("2e941141-7f97-4756-ba1d-9decde894a3d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
|
29
|
+
interface IApplicationActivationManager {
|
|
30
|
+
void ActivateApplication([MarshalAs(UnmanagedType.LPWStr)] string appId,
|
|
31
|
+
[MarshalAs(UnmanagedType.LPWStr)] string arguments, uint options, out uint processId);
|
|
32
|
+
void ActivateForFile([MarshalAs(UnmanagedType.LPWStr)] string appId, IntPtr items,
|
|
33
|
+
[MarshalAs(UnmanagedType.LPWStr)] string verb, out uint processId);
|
|
34
|
+
void ActivateForProtocol([MarshalAs(UnmanagedType.LPWStr)] string appId, IntPtr items, out uint processId);
|
|
35
|
+
}
|
|
36
|
+
public static class DesktopActivation {
|
|
37
|
+
public static uint Activate(string appId) {
|
|
38
|
+
object instance = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C")));
|
|
39
|
+
try {
|
|
40
|
+
uint processId;
|
|
41
|
+
((IApplicationActivationManager)instance).ActivateApplication(appId, "", 2, out processId);
|
|
42
|
+
return processId;
|
|
43
|
+
} finally { Marshal.ReleaseComObject(instance); }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
'@
|
|
48
|
+
[CodeRelax.DesktopActivation]::Activate($package.PackageFamilyName + '!App')
|