@hjd-hitsz/claudex-web 4.1.5 → 4.2.0
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/.env.example +2 -0
- package/CHANGELOG.md +31 -0
- package/README.md +13 -1
- package/bin/auth.mjs +86 -0
- package/bin/claudex-web.mjs +20 -0
- package/bin/p2p.mjs +134 -0
- package/build-info.json +4 -4
- package/client/dist/app.js +104 -104
- package/client/dist/code-highlight-style.js +1 -1
- package/client/dist/document-editor.js +54 -54
- package/client/dist/file-panel.js +5 -5
- package/client/dist/notification-worker.js +2 -1
- package/client/dist/p2p-sw.js +162 -0
- package/client/dist/style.css +1 -1
- package/client/dist/terminal-panel.js +11 -11
- package/docs/architecture/backends.md +8 -1
- package/docs/architecture/behavior.md +159 -53
- package/docs/architecture.md +36 -339
- package/docs/background-tasks.md +30 -26
- package/docs/deployment.md +47 -6
- package/docs/development.md +107 -151
- package/docs/images/desktop-dark.png +0 -0
- package/docs/images/desktop-light.png +0 -0
- package/docs/images/mobile-sidebar.png +0 -0
- package/docs/images/mobile.png +0 -0
- package/docs/releases/v4.2.0.md +13 -0
- package/docs/versioning.md +13 -3
- package/package.json +9 -2
- package/packages/background-terminal/LICENSE +674 -0
- package/packages/background-terminal/README.md +17 -0
- package/packages/background-terminal/background-jobs.mjs +457 -0
- package/packages/background-terminal/background-mcp.mjs +79 -0
- package/packages/background-terminal/background-protocol.mjs +80 -0
- package/packages/background-terminal/cli.mjs +14 -0
- package/packages/background-terminal/client.mjs +61 -0
- package/packages/background-terminal/codex.mjs +88 -0
- package/packages/background-terminal/delivery.mjs +192 -0
- package/packages/background-terminal/log.mjs +25 -0
- package/packages/background-terminal/native-watches.mjs +160 -0
- package/packages/background-terminal/package.json +15 -0
- package/packages/background-terminal/service.mjs +126 -0
- package/packages/translation-engine/package.json +1 -1
- package/server/src/application.mjs +82 -10
- package/server/src/auth-http.mjs +187 -0
- package/server/src/auth-login.mjs +144 -0
- package/server/src/auth-totp.mjs +233 -0
- package/server/src/auth.mjs +169 -220
- package/server/src/backends/claude/background-tasks.mjs +88 -35
- package/server/src/backends/claude/messages.mjs +1 -1
- package/server/src/backends/claude/worker-client.mjs +47 -35
- package/server/src/backends/claude/worker-lines.mjs +17 -0
- package/server/src/backends/claude/worker-server.mjs +49 -69
- package/server/src/backends/codex/adapter.mjs +46 -5
- package/server/src/backends/codex/background-service.mjs +85 -0
- package/server/src/backends/codex/background-task-views.mjs +87 -0
- package/server/src/backends/codex/background-terminals.mjs +91 -0
- package/server/src/backends/codex/events.mjs +11 -0
- package/server/src/backends/codex/methods.mjs +1 -0
- package/server/src/backends/codex/native-background-handoff.mjs +72 -0
- package/server/src/backends/codex/requests.mjs +51 -38
- package/server/src/backends/codex/subscriptions.mjs +34 -4
- package/server/src/backends/configuration.mjs +8 -0
- package/server/src/backends/manager.mjs +34 -32
- package/server/src/backends/storage.mjs +3 -14
- package/server/src/config.mjs +13 -0
- package/server/src/http/business.mjs +21 -0
- package/server/src/http/router.mjs +12 -25
- package/server/src/p2p/http.mjs +136 -0
- package/server/src/p2p/peers.mjs +132 -0
- package/server/src/p2p/service.mjs +229 -0
- package/server/src/p2p/storage.mjs +45 -0
- package/server/src/p2p/tunnel.mjs +95 -0
- package/server/src/p2p-http.mjs +149 -0
- package/server/src/p2p-peer.mjs +135 -0
- package/server/src/private-file.mjs +14 -0
- package/server/src/summary-translation.mjs +1 -1
- package/server/src/thread-folders.mjs +3 -13
- package/server/src/translation-service.mjs +3 -8
- package/shared/codex-preferences.mjs +9 -0
- package/shared/p2p-wire.mjs +157 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { setTimeout as wait } from "node:timers/promises";
|
|
3
|
+
import { tunnelStorage } from "./storage.mjs";
|
|
4
|
+
|
|
5
|
+
const profile = "claudex-web";
|
|
6
|
+
const route = "@";
|
|
7
|
+
|
|
8
|
+
export async function runPublicTunnel({
|
|
9
|
+
directory,
|
|
10
|
+
port,
|
|
11
|
+
signal,
|
|
12
|
+
onOrigin,
|
|
13
|
+
onState,
|
|
14
|
+
}) {
|
|
15
|
+
const endpoint = new URL(
|
|
16
|
+
process.env.OPENTUNNEL_API || "https://opentunnel.xyz",
|
|
17
|
+
);
|
|
18
|
+
if (endpoint.protocol !== "https:" || endpoint.href !== `${endpoint.origin}/`)
|
|
19
|
+
throw new Error("OPENTUNNEL_API 须为 HTTPS 来源地址");
|
|
20
|
+
const { create } = await import("@opentunnel/client");
|
|
21
|
+
const store = await tunnelStorage(
|
|
22
|
+
join(directory, "tunnel.json"),
|
|
23
|
+
endpoint.origin,
|
|
24
|
+
profile,
|
|
25
|
+
);
|
|
26
|
+
const client = create({ api: endpoint, store });
|
|
27
|
+
let retry = 1000;
|
|
28
|
+
|
|
29
|
+
async function attach(connection, activeSignal) {
|
|
30
|
+
let accepted = false;
|
|
31
|
+
const events = (async () => {
|
|
32
|
+
for await (const { type } of connection.events) {
|
|
33
|
+
if (!accepted || activeSignal.aborted) continue;
|
|
34
|
+
if (type === "connected") onState("online");
|
|
35
|
+
if (type === "disconnected" || type === "reconnecting")
|
|
36
|
+
onState("connecting");
|
|
37
|
+
}
|
|
38
|
+
})();
|
|
39
|
+
const closed = Promise.all([connection.closed, events]);
|
|
40
|
+
void closed.catch(() => {});
|
|
41
|
+
try {
|
|
42
|
+
if (!activeSignal.aborted) {
|
|
43
|
+
await onOrigin(connection.urls[route]);
|
|
44
|
+
accepted = true;
|
|
45
|
+
onState(
|
|
46
|
+
connection.status().state === "connected" ? "online" : "connecting",
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
await closed;
|
|
50
|
+
} finally {
|
|
51
|
+
await connection.close();
|
|
52
|
+
await closed.catch(() => {});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
while (!signal.aborted) {
|
|
58
|
+
onState("connecting");
|
|
59
|
+
const timeout = new AbortController();
|
|
60
|
+
const activeSignal = AbortSignal.any([signal, timeout.signal]);
|
|
61
|
+
const timer = setTimeout(() => timeout.abort(), 90000);
|
|
62
|
+
timer.unref();
|
|
63
|
+
let routeConflict = false;
|
|
64
|
+
try {
|
|
65
|
+
const connection = await client.tunnel.connect({
|
|
66
|
+
profile,
|
|
67
|
+
routes: { [route]: `127.0.0.1:${port}` },
|
|
68
|
+
signal: activeSignal,
|
|
69
|
+
onRouteConflict: "fail",
|
|
70
|
+
onEvent(event) {
|
|
71
|
+
if (event.type === "route-conflict") routeConflict = true;
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
retry = 1000;
|
|
76
|
+
await attach(connection, activeSignal);
|
|
77
|
+
} catch {
|
|
78
|
+
if (!signal.aborted)
|
|
79
|
+
onState(
|
|
80
|
+
"error",
|
|
81
|
+
routeConflict
|
|
82
|
+
? "OpenTunnel 域名被另一进程占用,正在重试"
|
|
83
|
+
: "OpenTunnel 暂不可用,正在重试",
|
|
84
|
+
);
|
|
85
|
+
} finally {
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
}
|
|
88
|
+
if (signal.aborted) break;
|
|
89
|
+
await wait(retry, undefined, { signal }).catch(() => {});
|
|
90
|
+
retry = Math.min(retry * 2, 30000);
|
|
91
|
+
}
|
|
92
|
+
} finally {
|
|
93
|
+
await client.dispose();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { Readable, Writable } from "node:stream";
|
|
2
|
+
import { P2P_STREAM_CHUNK_BYTES } from "../../shared/p2p-wire.mjs";
|
|
3
|
+
|
|
4
|
+
class PeerResponse extends Writable {
|
|
5
|
+
constructor(send, id, method) {
|
|
6
|
+
super();
|
|
7
|
+
this.send = send;
|
|
8
|
+
this.id = id;
|
|
9
|
+
this.method = method;
|
|
10
|
+
this.headers = {};
|
|
11
|
+
this.headersSent = false;
|
|
12
|
+
this.statusCode = 200;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
setHeader(name, value) {
|
|
16
|
+
this.headers[name.toLowerCase()] = String(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
writeHead(status, headers = {}) {
|
|
20
|
+
if (this.headersSent || this.destroyed) return this;
|
|
21
|
+
for (const [name, value] of Object.entries(headers))
|
|
22
|
+
this.setHeader(name, value);
|
|
23
|
+
this.statusCode = status;
|
|
24
|
+
this.headersSent = true;
|
|
25
|
+
this.headerSent = this.send({
|
|
26
|
+
type: "response",
|
|
27
|
+
id: this.id,
|
|
28
|
+
status,
|
|
29
|
+
headers: this.headers,
|
|
30
|
+
});
|
|
31
|
+
this.headerSent.catch(() => this.destroy());
|
|
32
|
+
return this;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
pull() {
|
|
36
|
+
if (this.destroyed || this.credit) return;
|
|
37
|
+
this.credit = true;
|
|
38
|
+
this.resumeWrite?.();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async _write(chunk, encoding, callback) {
|
|
42
|
+
try {
|
|
43
|
+
this.writeHead(this.statusCode);
|
|
44
|
+
await this.headerSent;
|
|
45
|
+
if (this.method !== "HEAD") {
|
|
46
|
+
for (
|
|
47
|
+
let offset = 0;
|
|
48
|
+
offset < chunk.length;
|
|
49
|
+
offset += P2P_STREAM_CHUNK_BYTES
|
|
50
|
+
) {
|
|
51
|
+
if (!this.credit && !this.destroyed)
|
|
52
|
+
await new Promise((resolve) => {
|
|
53
|
+
this.resumeWrite = resolve;
|
|
54
|
+
});
|
|
55
|
+
this.resumeWrite = null;
|
|
56
|
+
if (this.destroyed) break;
|
|
57
|
+
this.credit = false;
|
|
58
|
+
await this.send(
|
|
59
|
+
{ type: "data", id: this.id },
|
|
60
|
+
chunk.subarray(offset, offset + P2P_STREAM_CHUNK_BYTES),
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
callback();
|
|
65
|
+
} catch (error) {
|
|
66
|
+
callback(error);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
_final(callback) {
|
|
71
|
+
this.writeHead(this.statusCode);
|
|
72
|
+
this.send({ type: "end", id: this.id }).then(() => callback(), callback);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
_destroy(error, callback) {
|
|
76
|
+
this.resumeWrite?.();
|
|
77
|
+
callback(error);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function createPeerHttp(handle, wire) {
|
|
82
|
+
const active = new Map();
|
|
83
|
+
|
|
84
|
+
return {
|
|
85
|
+
receive(message, bytes) {
|
|
86
|
+
const { type, id, method, url, headers } = message;
|
|
87
|
+
if (!Number.isSafeInteger(id) || id < 1) throw new Error("无效请求编号");
|
|
88
|
+
const running = active.get(id);
|
|
89
|
+
if (type === "pull") {
|
|
90
|
+
running?.pull();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (type === "cancel") {
|
|
94
|
+
running?.destroy();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (type !== "request" || running) throw new Error("无效直连请求");
|
|
98
|
+
const fail = (message) => {
|
|
99
|
+
wire.send({ type: "error", id, message }).catch(() => {});
|
|
100
|
+
};
|
|
101
|
+
if (
|
|
102
|
+
active.size >= 32 ||
|
|
103
|
+
!["GET", "HEAD", "POST", "PUT"].includes(method) ||
|
|
104
|
+
typeof url !== "string" ||
|
|
105
|
+
!url.startsWith("/api/") ||
|
|
106
|
+
url.length > 16384
|
|
107
|
+
) {
|
|
108
|
+
fail("直连 HTTP 请求无效或过多");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const parsed = new URL(url, "https://localhost");
|
|
112
|
+
if (parsed.origin !== "https://localhost") {
|
|
113
|
+
fail("直连 HTTP 地址无效");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const request = Readable.from(bytes.length ? [Buffer.from(bytes)] : []);
|
|
117
|
+
request.method = method;
|
|
118
|
+
request.url = parsed.pathname + parsed.search;
|
|
119
|
+
request.headers = {};
|
|
120
|
+
for (const name of ["range", "content-type"])
|
|
121
|
+
if (typeof headers?.[name] === "string" && headers[name].length <= 1024)
|
|
122
|
+
request.headers[name] = headers[name];
|
|
123
|
+
const response = new PeerResponse(wire.send, id, method);
|
|
124
|
+
active.set(id, response);
|
|
125
|
+
response.on("close", () => {
|
|
126
|
+
active.delete(id);
|
|
127
|
+
request.destroy();
|
|
128
|
+
});
|
|
129
|
+
response.on("error", () => fail("直连响应传输中断"));
|
|
130
|
+
Promise.resolve()
|
|
131
|
+
.then(() => {
|
|
132
|
+
if (response.destroyed) return;
|
|
133
|
+
return (
|
|
134
|
+
handle(request, response, parsed.pathname) ||
|
|
135
|
+
response.writeHead(404).end()
|
|
136
|
+
);
|
|
137
|
+
})
|
|
138
|
+
.catch(() => {
|
|
139
|
+
if (response.destroyed) return;
|
|
140
|
+
if (response.headersSent) response.destroy(new Error("请求处理失败"));
|
|
141
|
+
else response.writeHead(500).end();
|
|
142
|
+
});
|
|
143
|
+
},
|
|
144
|
+
close() {
|
|
145
|
+
for (const response of active.values()) response.destroy();
|
|
146
|
+
active.clear();
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { createP2pWire } from "../../shared/p2p-wire.mjs";
|
|
3
|
+
import { createPeerHttp } from "./p2p-http.mjs";
|
|
4
|
+
|
|
5
|
+
export function createPeerClient(
|
|
6
|
+
channel,
|
|
7
|
+
handleBusiness,
|
|
8
|
+
{ authentication, linkId, onAuthenticated, onLogout },
|
|
9
|
+
) {
|
|
10
|
+
const peer = new EventEmitter();
|
|
11
|
+
const lifetime = new AbortController();
|
|
12
|
+
const authorized = () =>
|
|
13
|
+
peer.authSessionId && authentication.valid(peer.authSessionId, linkId);
|
|
14
|
+
let untrack, pendingToken;
|
|
15
|
+
let authenticating = false;
|
|
16
|
+
peer.authLinkId = linkId;
|
|
17
|
+
peer.readyState = 1;
|
|
18
|
+
peer.detach = () => {
|
|
19
|
+
if (peer.readyState === 3) return;
|
|
20
|
+
peer.readyState = 3;
|
|
21
|
+
lifetime.abort();
|
|
22
|
+
authentication.cancelPeer(pendingToken, peer);
|
|
23
|
+
wire.close();
|
|
24
|
+
http.close();
|
|
25
|
+
peer.emit("close");
|
|
26
|
+
};
|
|
27
|
+
peer.close = () => {
|
|
28
|
+
peer.detach();
|
|
29
|
+
channel.close();
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
async function authorize(message) {
|
|
33
|
+
if (authenticating) {
|
|
34
|
+
peer.close();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
authenticating = true;
|
|
38
|
+
try {
|
|
39
|
+
if (message.action === "logout") {
|
|
40
|
+
authentication.cancelPeer(pendingToken, peer);
|
|
41
|
+
pendingToken = undefined;
|
|
42
|
+
const id = peer.authSessionId;
|
|
43
|
+
untrack?.();
|
|
44
|
+
untrack = undefined;
|
|
45
|
+
peer.authSessionId = undefined;
|
|
46
|
+
http.close();
|
|
47
|
+
if (id) onLogout(peer);
|
|
48
|
+
await authentication.logoutPeer(linkId, id);
|
|
49
|
+
await wire.send({
|
|
50
|
+
type: "auth-result",
|
|
51
|
+
session: { authenticated: false },
|
|
52
|
+
});
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const current = authorized();
|
|
56
|
+
if (message.action === "status") {
|
|
57
|
+
await wire.send({
|
|
58
|
+
type: "auth-result",
|
|
59
|
+
session: current
|
|
60
|
+
? authentication.describe(current)
|
|
61
|
+
: (authentication.pendingPeer(pendingToken, peer) ?? {
|
|
62
|
+
authenticated: false,
|
|
63
|
+
}),
|
|
64
|
+
});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (current || !["login", "resume", "totp"].includes(message.action))
|
|
68
|
+
throw new Error("当前连接无法执行此登录操作。", { cause: 400 });
|
|
69
|
+
const options = { scope: peer, pendingToken, signal: lifetime.signal };
|
|
70
|
+
const {
|
|
71
|
+
id,
|
|
72
|
+
token,
|
|
73
|
+
session,
|
|
74
|
+
pendingToken: nextPending,
|
|
75
|
+
} = message.action === "login"
|
|
76
|
+
? await authentication.loginPeer(linkId, message, options)
|
|
77
|
+
: message.action === "totp"
|
|
78
|
+
? await authentication.verifyPeer(linkId, message, options)
|
|
79
|
+
: authentication.resumePeer(linkId, message.token);
|
|
80
|
+
if (message.action === "resume")
|
|
81
|
+
authentication.cancelPeer(pendingToken, peer);
|
|
82
|
+
pendingToken = nextPending;
|
|
83
|
+
lifetime.signal.throwIfAborted();
|
|
84
|
+
if (id) untrack = authentication.attach(peer, id, linkId);
|
|
85
|
+
await wire.send({
|
|
86
|
+
type: "auth-result",
|
|
87
|
+
session,
|
|
88
|
+
...(token && { token }),
|
|
89
|
+
});
|
|
90
|
+
if (id && authorized()) onAuthenticated(peer);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error.cause === 410) pendingToken = undefined;
|
|
93
|
+
if (!lifetime.signal.aborted)
|
|
94
|
+
await wire
|
|
95
|
+
.send({
|
|
96
|
+
type: "auth-result",
|
|
97
|
+
status: typeof error.cause === "number" ? error.cause : 503,
|
|
98
|
+
error:
|
|
99
|
+
typeof error.cause === "number"
|
|
100
|
+
? error.message
|
|
101
|
+
: "登录暂不可用,请稍后重试。",
|
|
102
|
+
})
|
|
103
|
+
.catch(() => {});
|
|
104
|
+
} finally {
|
|
105
|
+
authenticating = false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const wire = createP2pWire({
|
|
110
|
+
sendFrame: (frame) =>
|
|
111
|
+
channel.sendMessageBinary(
|
|
112
|
+
Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength),
|
|
113
|
+
),
|
|
114
|
+
bufferedAmount: () => channel.bufferedAmount(),
|
|
115
|
+
maxInboundBytes: () => (peer.authSessionId ? undefined : 8192),
|
|
116
|
+
receive(message, bytes) {
|
|
117
|
+
if (message.type === "auth") {
|
|
118
|
+
if (bytes.length) peer.close();
|
|
119
|
+
else void authorize(message);
|
|
120
|
+
} else if (message.type === "rpc") {
|
|
121
|
+
if (authorized()) peer.emit("message", message.text);
|
|
122
|
+
} else http.receive(message, bytes);
|
|
123
|
+
},
|
|
124
|
+
close: peer.close,
|
|
125
|
+
});
|
|
126
|
+
const http = createPeerHttp((request, response, path) => {
|
|
127
|
+
if (!authorized()) return response.writeHead(401).end();
|
|
128
|
+
return handleBusiness(request, response, path);
|
|
129
|
+
}, wire);
|
|
130
|
+
peer.send = (text) => {
|
|
131
|
+
if (authorized()) wire.send({ type: "rpc", text }).catch(() => {});
|
|
132
|
+
};
|
|
133
|
+
channel.onMessage(wire.frame);
|
|
134
|
+
return peer;
|
|
135
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
|
|
5
|
+
export async function writePrivateFile(path, content) {
|
|
6
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
7
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
8
|
+
try {
|
|
9
|
+
await writeFile(temporary, content, { mode: 0o600, flag: "wx" });
|
|
10
|
+
await rename(temporary, path);
|
|
11
|
+
} finally {
|
|
12
|
+
await rm(temporary, { force: true });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
2
|
import { isAbsolute, join } from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { writePrivateFile } from "./private-file.mjs";
|
|
4
4
|
|
|
5
5
|
// 网页项目归属与待应用目录由桥接保存;原生会话在下次恢复或开始轮次时应用目录。
|
|
6
6
|
export function createThreadFolders(directory) {
|
|
@@ -36,17 +36,7 @@ export function createThreadFolders(directory) {
|
|
|
36
36
|
folderRevision: (previous?.folderRevision || 0) + 1,
|
|
37
37
|
};
|
|
38
38
|
const next = { ...entries, [thread.id]: entry };
|
|
39
|
-
await
|
|
40
|
-
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
41
|
-
try {
|
|
42
|
-
await writeFile(temporary, JSON.stringify(next, null, 2) + "\n", {
|
|
43
|
-
mode: 0o600,
|
|
44
|
-
flag: "wx",
|
|
45
|
-
});
|
|
46
|
-
await rename(temporary, path);
|
|
47
|
-
} finally {
|
|
48
|
-
await rm(temporary, { force: true });
|
|
49
|
-
}
|
|
39
|
+
await writePrivateFile(path, JSON.stringify(next, null, 2) + "\n");
|
|
50
40
|
entries = next;
|
|
51
41
|
return { ...thread, ...entry };
|
|
52
42
|
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { writePrivateFile } from "./private-file.mjs";
|
|
4
4
|
import {
|
|
5
5
|
createTranslationEngine,
|
|
6
6
|
ModelStore,
|
|
@@ -83,12 +83,7 @@ export function createTranslationService(
|
|
|
83
83
|
setEnabled(enabled) {
|
|
84
84
|
const operation = mutations.then(async () => {
|
|
85
85
|
await initialize();
|
|
86
|
-
await
|
|
87
|
-
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
88
|
-
await writeFile(temporary, JSON.stringify({ enabled }), {
|
|
89
|
-
mode: 0o600,
|
|
90
|
-
});
|
|
91
|
-
await rename(temporary, file);
|
|
86
|
+
await writePrivateFile(file, JSON.stringify({ enabled }));
|
|
92
87
|
state = { ...state, enabled, error: "" };
|
|
93
88
|
if (!enabled) {
|
|
94
89
|
state = { ...state, state: "disabled", progress: null };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function isCodexPreference(input) {
|
|
2
|
+
return (
|
|
3
|
+
input.id === "codex" &&
|
|
4
|
+
("backgroundTerminalEnabled" in input || "hiddenModels" in input) &&
|
|
5
|
+
Object.keys(input).every((key) =>
|
|
6
|
+
["id", "type", "backgroundTerminalEnabled", "hiddenModels"].includes(key),
|
|
7
|
+
)
|
|
8
|
+
);
|
|
9
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { MAX_RPC_MESSAGE_BYTES } from "./rpc-limits.mjs";
|
|
2
|
+
|
|
3
|
+
const frameSize = 16 * 1024;
|
|
4
|
+
const maxJsonBytes = 64 * 1024;
|
|
5
|
+
export const MAX_P2P_BODY_BYTES = 512 * 1024;
|
|
6
|
+
export const P2P_STREAM_CHUNK_BYTES = 64 * 1024;
|
|
7
|
+
const bufferLimit = 256 * 1024;
|
|
8
|
+
const maxQueueBytes = 2 * MAX_RPC_MESSAGE_BYTES;
|
|
9
|
+
const encoder = new TextEncoder();
|
|
10
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
11
|
+
|
|
12
|
+
export function createP2pWire({
|
|
13
|
+
sendFrame,
|
|
14
|
+
bufferedAmount,
|
|
15
|
+
receive,
|
|
16
|
+
close,
|
|
17
|
+
maxInboundBytes,
|
|
18
|
+
}) {
|
|
19
|
+
let closed = false;
|
|
20
|
+
let pending = Promise.resolve();
|
|
21
|
+
let queuedBytes = 0;
|
|
22
|
+
let incoming;
|
|
23
|
+
let deadline;
|
|
24
|
+
|
|
25
|
+
function shutdown() {
|
|
26
|
+
closed = true;
|
|
27
|
+
incoming = null;
|
|
28
|
+
clearTimeout(deadline);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function fail(error) {
|
|
32
|
+
if (closed) return;
|
|
33
|
+
shutdown();
|
|
34
|
+
close(error);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function send(message, binary = new Uint8Array()) {
|
|
38
|
+
if (closed) return Promise.reject(new Error("直连已断开"));
|
|
39
|
+
const rpc = message.type === "rpc";
|
|
40
|
+
if (rpc) binary = encoder.encode(message.text);
|
|
41
|
+
const json = encoder.encode(
|
|
42
|
+
JSON.stringify(rpc ? { type: "rpc" } : message),
|
|
43
|
+
);
|
|
44
|
+
const size = json.length + binary.byteLength + 8;
|
|
45
|
+
if (
|
|
46
|
+
json.length > maxJsonBytes ||
|
|
47
|
+
binary.byteLength > (rpc ? MAX_RPC_MESSAGE_BYTES : MAX_P2P_BODY_BYTES) ||
|
|
48
|
+
queuedBytes + size > maxQueueBytes
|
|
49
|
+
) {
|
|
50
|
+
const error = new Error("直连消息超过传输限制");
|
|
51
|
+
fail(error);
|
|
52
|
+
return Promise.reject(error);
|
|
53
|
+
}
|
|
54
|
+
queuedBytes += size;
|
|
55
|
+
const operation = pending.then(async () => {
|
|
56
|
+
const prefix = new Uint8Array(8 + json.length);
|
|
57
|
+
const header = new DataView(prefix.buffer);
|
|
58
|
+
header.setUint32(0, json.length);
|
|
59
|
+
header.setUint32(4, binary.byteLength);
|
|
60
|
+
prefix.set(json, 8);
|
|
61
|
+
for (let offset = 0; offset < size; offset += frameSize - 1) {
|
|
62
|
+
const end = Math.min(offset + frameSize - 1, size);
|
|
63
|
+
const packet = new Uint8Array(end - offset + 1);
|
|
64
|
+
packet[0] = (offset === 0 ? 1 : 0) | (end === size ? 2 : 0);
|
|
65
|
+
if (offset < prefix.length) packet.set(prefix.subarray(offset, end), 1);
|
|
66
|
+
if (end > prefix.length)
|
|
67
|
+
packet.set(
|
|
68
|
+
binary.subarray(
|
|
69
|
+
Math.max(0, offset - prefix.length),
|
|
70
|
+
end - prefix.length,
|
|
71
|
+
),
|
|
72
|
+
1 + Math.max(0, prefix.length - offset),
|
|
73
|
+
);
|
|
74
|
+
const waitStarted = Date.now();
|
|
75
|
+
while (!closed && bufferedAmount() > bufferLimit) {
|
|
76
|
+
if (Date.now() - waitStarted >= 30000)
|
|
77
|
+
throw new Error("直连发送超时");
|
|
78
|
+
await new Promise((resolve) => setTimeout(resolve, 8));
|
|
79
|
+
}
|
|
80
|
+
if (closed) throw new Error("直连已断开");
|
|
81
|
+
sendFrame(packet);
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
pending = operation.catch(fail).finally(() => {
|
|
85
|
+
queuedBytes -= size;
|
|
86
|
+
});
|
|
87
|
+
return operation;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function frame(input) {
|
|
91
|
+
if (closed) return;
|
|
92
|
+
try {
|
|
93
|
+
if (!(input instanceof ArrayBuffer) && !ArrayBuffer.isView(input))
|
|
94
|
+
throw new Error("直连需要二进制帧");
|
|
95
|
+
const packet = ArrayBuffer.isView(input)
|
|
96
|
+
? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
|
|
97
|
+
: new Uint8Array(input);
|
|
98
|
+
const flags = packet[0];
|
|
99
|
+
if (
|
|
100
|
+
packet.length < 2 ||
|
|
101
|
+
packet.length > frameSize ||
|
|
102
|
+
flags > 3 ||
|
|
103
|
+
Boolean(flags & 1) === Boolean(incoming)
|
|
104
|
+
)
|
|
105
|
+
throw new Error("无效的直连帧顺序");
|
|
106
|
+
let body = packet.subarray(1);
|
|
107
|
+
if (flags & 1) {
|
|
108
|
+
const header = new DataView(body.buffer, body.byteOffset, body.length);
|
|
109
|
+
const jsonLength = header.getUint32(0);
|
|
110
|
+
const binaryLength = header.getUint32(4);
|
|
111
|
+
if (
|
|
112
|
+
jsonLength < 2 ||
|
|
113
|
+
jsonLength > maxJsonBytes ||
|
|
114
|
+
binaryLength > MAX_RPC_MESSAGE_BYTES ||
|
|
115
|
+
jsonLength + binaryLength > (maxInboundBytes?.() ?? Infinity)
|
|
116
|
+
)
|
|
117
|
+
throw new Error("无效的直连消息长度");
|
|
118
|
+
incoming = {
|
|
119
|
+
payload: new Uint8Array(jsonLength + binaryLength),
|
|
120
|
+
offset: 0,
|
|
121
|
+
jsonLength,
|
|
122
|
+
};
|
|
123
|
+
deadline = setTimeout(() => fail(new Error("直连接收超时")), 120000);
|
|
124
|
+
body = body.subarray(8);
|
|
125
|
+
}
|
|
126
|
+
const { payload, offset, jsonLength } = incoming;
|
|
127
|
+
if (
|
|
128
|
+
offset + body.length > payload.length ||
|
|
129
|
+
Boolean(flags & 2) !== (offset + body.length === payload.length)
|
|
130
|
+
)
|
|
131
|
+
throw new Error("无效的直连消息边界");
|
|
132
|
+
payload.set(body, offset);
|
|
133
|
+
incoming.offset += body.length;
|
|
134
|
+
if (flags & 2) {
|
|
135
|
+
incoming = null;
|
|
136
|
+
clearTimeout(deadline);
|
|
137
|
+
const message = JSON.parse(
|
|
138
|
+
decoder.decode(payload.subarray(0, jsonLength)),
|
|
139
|
+
);
|
|
140
|
+
if (!message || typeof message.type !== "string")
|
|
141
|
+
throw new Error("无效的直连消息类型");
|
|
142
|
+
const binary = payload.subarray(jsonLength);
|
|
143
|
+
if (message.type === "rpc")
|
|
144
|
+
receive({ type: "rpc", text: decoder.decode(binary) });
|
|
145
|
+
else {
|
|
146
|
+
if (binary.length > MAX_P2P_BODY_BYTES)
|
|
147
|
+
throw new Error("直连请求超过大小限制");
|
|
148
|
+
receive(message, binary);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
} catch (error) {
|
|
152
|
+
fail(error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return { send, frame, close: shutdown };
|
|
157
|
+
}
|