engine7 7.1.133 → 7.1.136
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 +1 -0
- package/dist/auth-server.mjs +632 -0
- package/dist/bg-worker.mjs +31660 -28486
- package/dist/cc-desktop.mjs +951 -0
- package/dist/cli.mjs +41446 -30183
- package/dist/engine-startup.mjs +59137 -46007
- package/dist/main.mjs +50062 -36930
- package/dist/recall-worker.mjs +20443 -0
- package/dist/sqlite-maintenance-worker.mjs +1163 -124
- package/dist/stop-history-worker.mjs +180 -0
- package/dist/topics-worker.mjs +3350 -1078
- package/dist/travel-authority.mjs +1068 -0
- package/dist/travel-console.mjs +2205 -0
- package/dist/travel-controller.mjs +1883 -0
- package/dist/travel-data.mjs +7250 -0
- package/dist/travel-gateway.mjs +3258 -0
- package/dist/travel-key-service.mjs +483 -0
- package/dist/travel-node-data.mjs +4930 -0
- package/dist/travel-node.mjs +21233 -0
- package/dist/travel-retire.mjs +1094 -0
- package/dist/web-console.mjs +2425 -0
- package/package.json +32 -17
- package/templates/config.template.json +45 -0
- package/templates/skills/auth-connect/SKILL.md +22 -0
- package/templates/skills/email/SKILL.md +119 -115
- package/templates/skills/email/scripts/email-config-path.test.js +52 -0
- package/templates/skills/email/scripts/email-config.d.ts +4 -0
- package/templates/skills/email/scripts/email-config.js +6 -3
- package/templates/skills/pptx/SKILL.md +5 -0
- package/templates/skills/pptx/assets/engine7-aurora/field.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/hero.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/wordmark.png +0 -0
- package/templates/skills/pptx/examples/engine7-aurora.cjs +190 -0
- package/templates/skills/pptx/package-lock.json +171 -0
- package/templates/skills/pptx/package.json +12 -0
- package/templates/skills/pptx/scripts/engine7-aurora.cjs +132 -0
- package/templates/skills/pptx/styles/engine7-aurora.md +136 -0
- package/templates/skills/pptx/tests/engine7-aurora.test.cjs +116 -0
- package/templates/workspace/AGENTS.md +2 -9
- package/templates/workspace/RULES.md +22 -0
- package/templates/workspace/hooks/loop-detector.mjs +37 -0
- package/templates/workspace/souls/unnamed.md +10 -0
|
@@ -0,0 +1,951 @@
|
|
|
1
|
+
const require=(await import('node:module')).createRequire(import.meta.url)
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __esm = (fn, res) => function __init() {
|
|
4
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
// src/cc-driver/desktop.ts
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
12
|
+
import { createServer } from "node:http";
|
|
13
|
+
function normalizeDesktopTitle(value) {
|
|
14
|
+
if (typeof value !== "string" || /[\x00-\x1f\x7f-\x9f]/.test(value) || Array.from(value.trim()).length > 120) {
|
|
15
|
+
throw failure("title must be a single line of at most 120 characters without control characters", 400);
|
|
16
|
+
}
|
|
17
|
+
return value.trim();
|
|
18
|
+
}
|
|
19
|
+
function nativeSessionOwners(sessionId) {
|
|
20
|
+
const dir = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"), "sessions");
|
|
21
|
+
let files;
|
|
22
|
+
try {
|
|
23
|
+
files = fs.readdirSync(dir);
|
|
24
|
+
} catch {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
const owners = [];
|
|
28
|
+
for (const file of files.filter((f) => /^\d+\.json$/.test(f))) {
|
|
29
|
+
try {
|
|
30
|
+
const info = JSON.parse(fs.readFileSync(path.join(dir, file), "utf8"));
|
|
31
|
+
if (info.sessionId === sessionId && Number.isInteger(info.pid) && info.pid > 0 && alive(info.pid)) owners.push(info.pid);
|
|
32
|
+
} catch {
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return owners;
|
|
36
|
+
}
|
|
37
|
+
async function findDesktopTargets(workDir, sessionId) {
|
|
38
|
+
let files;
|
|
39
|
+
try {
|
|
40
|
+
files = fs.readdirSync(registryDir());
|
|
41
|
+
} catch {
|
|
42
|
+
return [];
|
|
43
|
+
}
|
|
44
|
+
const targets = [];
|
|
45
|
+
for (const file of files.filter((f) => /^\d+-[\da-f-]+\.json$/.test(f))) {
|
|
46
|
+
let saved;
|
|
47
|
+
try {
|
|
48
|
+
saved = JSON.parse(fs.readFileSync(path.join(registryDir(), file), "utf8"));
|
|
49
|
+
} catch {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (!Number.isInteger(saved.pid) || saved.pid < 1 || !alive(saved.pid) || !Number.isInteger(saved.port) || saved.port < 1 || saved.port > 65535 || typeof saved.token !== "string" || typeof saved.instance !== "string" || typeof saved.sessionId !== "string" || typeof saved.workDir !== "string") continue;
|
|
53
|
+
if (workDir && canonical(workDir) !== canonical(saved.workDir) || sessionId && sessionId !== saved.sessionId) continue;
|
|
54
|
+
const response = await fetch(`http://127.0.0.1:${saved.port}/status`, {
|
|
55
|
+
headers: { authorization: `Bearer ${saved.token}` },
|
|
56
|
+
signal: AbortSignal.timeout(2e3)
|
|
57
|
+
});
|
|
58
|
+
if (!response.ok) throw failure(`Desktop CC ${saved.port} unavailable (HTTP ${response.status})`);
|
|
59
|
+
const current = await response.json();
|
|
60
|
+
if (current.pid !== saved.pid || current.instance !== saved.instance || current.sessionId !== saved.sessionId || canonical(current.workDir || "") !== canonical(saved.workDir)) throw failure("Desktop CC identity/session changed");
|
|
61
|
+
targets.push({ ...current, token: saved.token });
|
|
62
|
+
}
|
|
63
|
+
return targets;
|
|
64
|
+
}
|
|
65
|
+
async function renameDesktop(target, title) {
|
|
66
|
+
const normalized = normalizeDesktopTitle(title);
|
|
67
|
+
const response = await fetch(`http://127.0.0.1:${target.port}/title`, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers: { authorization: `Bearer ${target.token}`, "content-type": "application/json" },
|
|
70
|
+
body: JSON.stringify({ title: normalized, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir }),
|
|
71
|
+
signal: AbortSignal.timeout(2e3)
|
|
72
|
+
});
|
|
73
|
+
const result = await response.json();
|
|
74
|
+
if (!response.ok) throw failure(result.error || `Desktop CC HTTP ${response.status}`, response.status);
|
|
75
|
+
if (result.sessionId !== target.sessionId || result.instance !== target.instance || result.title !== normalized) {
|
|
76
|
+
throw failure("Desktop CC returned an invalid rename result");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function readBody(req) {
|
|
80
|
+
const chunks = [];
|
|
81
|
+
let bytes = 0;
|
|
82
|
+
for await (const part of req) {
|
|
83
|
+
const chunk = Buffer.isBuffer(part) ? part : Buffer.from(part);
|
|
84
|
+
bytes += chunk.length;
|
|
85
|
+
if (bytes > 1e6) throw failure("Request too large", 413);
|
|
86
|
+
chunks.push(chunk);
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
90
|
+
} catch {
|
|
91
|
+
throw failure("Invalid JSON", 400);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async function startDesktopBridge(options) {
|
|
95
|
+
const title = normalizeDesktopTitle(options.title ?? "");
|
|
96
|
+
const dir = registryDir();
|
|
97
|
+
fs.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
98
|
+
const endpoint = {
|
|
99
|
+
pid: process.pid,
|
|
100
|
+
instance: randomUUID(),
|
|
101
|
+
token: randomBytes(32).toString("hex"),
|
|
102
|
+
port: 0,
|
|
103
|
+
sessionId: options.sessionId,
|
|
104
|
+
workDir: canonical(options.workDir),
|
|
105
|
+
title,
|
|
106
|
+
key: `desktop:${options.sessionId}`,
|
|
107
|
+
ready: false,
|
|
108
|
+
busy: false
|
|
109
|
+
};
|
|
110
|
+
const file = path.join(dir, `${process.pid}-${endpoint.instance}.json`);
|
|
111
|
+
let closed = false, draft = false, suspended = false, pasting = false;
|
|
112
|
+
let humanBuffer = "", active;
|
|
113
|
+
const queue = [];
|
|
114
|
+
let enterTimer;
|
|
115
|
+
let ackTimer;
|
|
116
|
+
const save = () => {
|
|
117
|
+
if (closed) return;
|
|
118
|
+
fs.writeFileSync(`${file}.tmp`, JSON.stringify(endpoint), { mode: 384 });
|
|
119
|
+
fs.renameSync(`${file}.tmp`, file);
|
|
120
|
+
};
|
|
121
|
+
const rejectAll = (message) => {
|
|
122
|
+
clearTimeout(enterTimer);
|
|
123
|
+
clearTimeout(ackTimer);
|
|
124
|
+
active?.reject(failure(message));
|
|
125
|
+
active = void 0;
|
|
126
|
+
for (const job of queue.splice(0)) job.reject(failure(message));
|
|
127
|
+
};
|
|
128
|
+
const humanInput = (data) => {
|
|
129
|
+
if (closed) return;
|
|
130
|
+
if (/^\x1b\[(?:[?>]?[\d;]*[cR]|[IO])$/.test(data)) {
|
|
131
|
+
options.writeInput(data);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (pasting) {
|
|
135
|
+
humanBuffer += data;
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (data === "\x1B" || data.includes("")) {
|
|
139
|
+
if (active) {
|
|
140
|
+
active.reject(failure("Desktop turn interrupted by its user"));
|
|
141
|
+
active = void 0;
|
|
142
|
+
}
|
|
143
|
+
suspended = true;
|
|
144
|
+
endpoint.busy = true;
|
|
145
|
+
draft = false;
|
|
146
|
+
} else if (data.includes("\r") || data.includes("\n")) {
|
|
147
|
+
draft = false;
|
|
148
|
+
endpoint.busy = true;
|
|
149
|
+
} else if (data === "") {
|
|
150
|
+
draft = false;
|
|
151
|
+
} else if (data) {
|
|
152
|
+
draft = true;
|
|
153
|
+
}
|
|
154
|
+
options.writeInput(data);
|
|
155
|
+
if (data === "") queueMicrotask(pump);
|
|
156
|
+
};
|
|
157
|
+
const unlockInput = () => {
|
|
158
|
+
pasting = false;
|
|
159
|
+
const data = humanBuffer;
|
|
160
|
+
humanBuffer = "";
|
|
161
|
+
if (data) humanInput(data);
|
|
162
|
+
};
|
|
163
|
+
const pump = () => {
|
|
164
|
+
if (closed || !endpoint.ready || endpoint.busy || suspended || draft || pasting || active || !queue.length) return;
|
|
165
|
+
const job = queue.shift();
|
|
166
|
+
if (job.sessionId !== endpoint.sessionId) {
|
|
167
|
+
job.reject(failure("Desktop session changed"));
|
|
168
|
+
pump();
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
active = job;
|
|
172
|
+
endpoint.busy = true;
|
|
173
|
+
pasting = true;
|
|
174
|
+
const prompt = `[engine7_cc_ask:${job.id}] [from ${terminalText(job.source).replace(/\n/g, " ").slice(0, 160)}]
|
|
175
|
+
${terminalText(job.prompt)}`;
|
|
176
|
+
try {
|
|
177
|
+
options.writeInput(`\x1B[200~${prompt}\x1B[201~`);
|
|
178
|
+
enterTimer = setTimeout(() => {
|
|
179
|
+
if (closed || active !== job) return;
|
|
180
|
+
try {
|
|
181
|
+
options.writeInput("\r");
|
|
182
|
+
} catch (e) {
|
|
183
|
+
job.reject(e);
|
|
184
|
+
suspended = true;
|
|
185
|
+
unlockInput();
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
ackTimer = setTimeout(() => {
|
|
189
|
+
if (active !== job || job.submitted) return;
|
|
190
|
+
suspended = true;
|
|
191
|
+
job.reject(failure("Desktop input was sent but UserPromptSubmit hook did not acknowledge it; inspect the terminal before retrying", 503));
|
|
192
|
+
unlockInput();
|
|
193
|
+
}, 1e4);
|
|
194
|
+
}, 100);
|
|
195
|
+
} catch (error) {
|
|
196
|
+
job.reject(error);
|
|
197
|
+
suspended = true;
|
|
198
|
+
unlockInput();
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
const onHook = (input) => {
|
|
202
|
+
if (!input || typeof input.hook_event_name !== "string" || typeof input.session_id !== "string" || typeof input.cwd !== "string" || canonical(input.cwd) !== endpoint.workDir) throw failure("Invalid desktop hook identity", 400);
|
|
203
|
+
const event = input.hook_event_name;
|
|
204
|
+
if (event === "SessionStart") {
|
|
205
|
+
if (input.source === "compact" && endpoint.ready && input.session_id === endpoint.sessionId) return;
|
|
206
|
+
const changed = input.session_id !== endpoint.sessionId;
|
|
207
|
+
if (changed) rejectAll("Desktop session changed while request was pending");
|
|
208
|
+
endpoint.sessionId = input.session_id;
|
|
209
|
+
endpoint.key = `desktop:${input.session_id}`;
|
|
210
|
+
endpoint.ready = true;
|
|
211
|
+
endpoint.busy = false;
|
|
212
|
+
suspended = false;
|
|
213
|
+
if (changed) unlockInput();
|
|
214
|
+
save();
|
|
215
|
+
pump();
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (input.session_id !== endpoint.sessionId) throw failure("Desktop hook session changed");
|
|
219
|
+
if (event === "UserPromptSubmit") {
|
|
220
|
+
endpoint.busy = true;
|
|
221
|
+
if (active && typeof input.prompt === "string" && input.prompt.startsWith(`[engine7_cc_ask:${active.id}] `)) {
|
|
222
|
+
active.submitted = true;
|
|
223
|
+
clearTimeout(ackTimer);
|
|
224
|
+
unlockInput();
|
|
225
|
+
} else if (active) {
|
|
226
|
+
active.reject(failure("Desktop user changed the active turn"));
|
|
227
|
+
active = void 0;
|
|
228
|
+
clearTimeout(enterTimer);
|
|
229
|
+
clearTimeout(ackTimer);
|
|
230
|
+
unlockInput();
|
|
231
|
+
}
|
|
232
|
+
} else if (event === "Stop" || event === "StopFailure") {
|
|
233
|
+
if (active?.submitted) {
|
|
234
|
+
const text = typeof input.last_assistant_message === "string" ? input.last_assistant_message : "";
|
|
235
|
+
active.resolve({
|
|
236
|
+
sessionId: endpoint.sessionId,
|
|
237
|
+
text: text || String(input.error || "CC stopped without a text answer"),
|
|
238
|
+
isError: event === "StopFailure" || !text.trim()
|
|
239
|
+
});
|
|
240
|
+
active = void 0;
|
|
241
|
+
}
|
|
242
|
+
endpoint.busy = false;
|
|
243
|
+
suspended = false;
|
|
244
|
+
pump();
|
|
245
|
+
} else if (event === "PermissionRequest" || event === "Notification" && input.notification_type === "permission_prompt") {
|
|
246
|
+
endpoint.busy = true;
|
|
247
|
+
} else if (event === "Notification" && input.notification_type === "idle_prompt" && !active) {
|
|
248
|
+
endpoint.busy = false;
|
|
249
|
+
suspended = false;
|
|
250
|
+
pump();
|
|
251
|
+
} else if (event === "SessionEnd") {
|
|
252
|
+
endpoint.ready = false;
|
|
253
|
+
rejectAll("Desktop session ended");
|
|
254
|
+
save();
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
const server = createServer(async (req, res) => {
|
|
258
|
+
const reply = (status, value) => {
|
|
259
|
+
if (res.destroyed || res.writableEnded) return;
|
|
260
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
261
|
+
res.end(JSON.stringify(value));
|
|
262
|
+
};
|
|
263
|
+
const auth = String(req.headers.authorization || "");
|
|
264
|
+
const expected = `Bearer ${endpoint.token}`;
|
|
265
|
+
if (req.headers.origin || !/^127\.0\.0\.1:\d+$/.test(req.headers.host || "") || !["127.0.0.1", "::ffff:127.0.0.1"].includes(req.socket.remoteAddress || "") || Buffer.byteLength(auth) !== Buffer.byteLength(expected) || !timingSafeEqual(Buffer.from(auth), Buffer.from(expected))) {
|
|
266
|
+
reply(403, { error: "Local desktop authentication required" });
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (req.url === "/status" && req.method === "GET") {
|
|
270
|
+
const { token: _token, ...status } = endpoint;
|
|
271
|
+
reply(200, { ...status, suspended, draft, queued: queue.length });
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (req.method !== "POST" || !["/ask", "/hook", "/title"].includes(req.url || "")) {
|
|
275
|
+
reply(404, { error: "Not found" });
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
let job;
|
|
279
|
+
const disconnect = () => {
|
|
280
|
+
if (!job || res.writableEnded) return;
|
|
281
|
+
const index = queue.indexOf(job);
|
|
282
|
+
if (index >= 0) queue.splice(index, 1);
|
|
283
|
+
job.reject(failure("Caller disconnected; any submitted desktop turn continues", 499));
|
|
284
|
+
};
|
|
285
|
+
res.on("close", disconnect);
|
|
286
|
+
try {
|
|
287
|
+
const input = await readBody(req);
|
|
288
|
+
if (req.url === "/hook") {
|
|
289
|
+
onHook(input);
|
|
290
|
+
reply(200, { ok: true });
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (input?.instance !== endpoint.instance || input.sessionId !== endpoint.sessionId || typeof input.workDir !== "string" || canonical(input.workDir) !== endpoint.workDir) throw failure("Desktop identity/session changed");
|
|
294
|
+
if (req.url === "/title") {
|
|
295
|
+
const title2 = normalizeDesktopTitle(input.title);
|
|
296
|
+
const previous = endpoint.title;
|
|
297
|
+
endpoint.title = title2;
|
|
298
|
+
try {
|
|
299
|
+
save();
|
|
300
|
+
} catch (error) {
|
|
301
|
+
endpoint.title = previous;
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
reply(200, { title: title2, sessionId: endpoint.sessionId, instance: endpoint.instance });
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (!endpoint.ready || suspended || closed) throw failure("Desktop not ready; check its hooks and terminal", 503);
|
|
308
|
+
if (typeof input.prompt !== "string" || !input.prompt.trim() || typeof input.source !== "string" || !input.source.trim()) {
|
|
309
|
+
throw failure("prompt and source required", 400);
|
|
310
|
+
}
|
|
311
|
+
if (queue.length >= 32) throw failure("Desktop queue full", 429);
|
|
312
|
+
const result = new Promise((resolve, reject) => {
|
|
313
|
+
job = { id: randomUUID(), prompt: input.prompt, source: input.source, sessionId: input.sessionId, submitted: false, resolve, reject };
|
|
314
|
+
queue.push(job);
|
|
315
|
+
});
|
|
316
|
+
if (res.destroyed) disconnect();
|
|
317
|
+
else pump();
|
|
318
|
+
reply(200, await result);
|
|
319
|
+
} catch (error) {
|
|
320
|
+
reply(error.status || 500, { error: error.message || String(error) });
|
|
321
|
+
} finally {
|
|
322
|
+
res.off("close", disconnect);
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
await new Promise((resolve, reject) => {
|
|
326
|
+
server.once("error", reject);
|
|
327
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
328
|
+
});
|
|
329
|
+
endpoint.port = server.address().port;
|
|
330
|
+
save();
|
|
331
|
+
return { endpoint, humanInput, async close() {
|
|
332
|
+
if (closed) return;
|
|
333
|
+
closed = true;
|
|
334
|
+
rejectAll("Desktop process closed");
|
|
335
|
+
try {
|
|
336
|
+
fs.unlinkSync(file);
|
|
337
|
+
} catch {
|
|
338
|
+
}
|
|
339
|
+
await new Promise((resolve) => {
|
|
340
|
+
server.close(() => resolve());
|
|
341
|
+
server.closeAllConnections();
|
|
342
|
+
});
|
|
343
|
+
} };
|
|
344
|
+
}
|
|
345
|
+
var registryDir, canonical, failure, alive, terminalText;
|
|
346
|
+
var init_desktop = __esm({
|
|
347
|
+
"src/cc-driver/desktop.ts"() {
|
|
348
|
+
"use strict";
|
|
349
|
+
registryDir = () => process.env.CC_DESKTOP_REGISTRY_DIR || path.join(os.homedir(), ".engine7", "cc-driver", "desktops");
|
|
350
|
+
canonical = (dir) => {
|
|
351
|
+
try {
|
|
352
|
+
return fs.realpathSync(dir);
|
|
353
|
+
} catch {
|
|
354
|
+
return path.resolve(dir);
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
failure = (message, status = 409) => Object.assign(new Error(message), { status });
|
|
358
|
+
alive = (pid) => {
|
|
359
|
+
try {
|
|
360
|
+
process.kill(pid, 0);
|
|
361
|
+
return true;
|
|
362
|
+
} catch (e) {
|
|
363
|
+
return e.code === "EPERM";
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
terminalText = (text) => text.replace(/\r\n?/g, "\n").replace(
|
|
367
|
+
/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,
|
|
368
|
+
(c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
// src/config/writer.ts
|
|
374
|
+
import fs2 from "node:fs";
|
|
375
|
+
import path2 from "node:path";
|
|
376
|
+
function isNormalized(text) {
|
|
377
|
+
if (text === "") return true;
|
|
378
|
+
if (text.includes("\r")) return false;
|
|
379
|
+
let minIndent = Infinity;
|
|
380
|
+
for (const line of text.split("\n")) {
|
|
381
|
+
const m = /^( +)\S/.exec(line);
|
|
382
|
+
if (!m) continue;
|
|
383
|
+
const width = m[1].length;
|
|
384
|
+
if (width % 2 !== 0) return false;
|
|
385
|
+
if (width < minIndent) minIndent = width;
|
|
386
|
+
}
|
|
387
|
+
return minIndent === 2 || minIndent === Infinity;
|
|
388
|
+
}
|
|
389
|
+
function rotateBaks(filePath) {
|
|
390
|
+
const dir = path2.dirname(filePath);
|
|
391
|
+
const base = path2.basename(filePath);
|
|
392
|
+
const baks = fs2.readdirSync(dir).filter((n) => n.startsWith(base + ".bak-")).sort();
|
|
393
|
+
while (baks.length >= KEEP_BAKS) {
|
|
394
|
+
const victim = baks.shift();
|
|
395
|
+
try {
|
|
396
|
+
fs2.unlinkSync(path2.join(dir, victim));
|
|
397
|
+
} catch {
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
function sleepSync(ms) {
|
|
402
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
403
|
+
}
|
|
404
|
+
function errCode(err) {
|
|
405
|
+
return err?.code ?? "";
|
|
406
|
+
}
|
|
407
|
+
function writeFailure(filePath, primary, extra) {
|
|
408
|
+
const code = errCode(primary);
|
|
409
|
+
const reason = RETRYABLE_CODES.has(code) ? `\u76EE\u6807\u6587\u4EF6\u88AB\u5360\u7528\u6216\u4E0D\u53EF\u5199\uFF08${code}\uFF09\u2014\u2014\u8BF7\u5173\u95ED\u6B63\u5728\u4F7F\u7528\u5B83\u7684\u7A0B\u5E8F\uFF08\u7F16\u8F91\u5668\u3001\u6740\u6BD2\u3001\u540C\u6B65\u76D8\u7B49\uFF09\u540E\u91CD\u8BD5` : `\u5199\u5165\u5931\u8D25${code ? `\uFF08${code}\uFF09` : ""}\uFF1A${primary?.message ?? String(primary)}`;
|
|
410
|
+
return new ConfigWriteError(`\u65E0\u6CD5\u5199\u5165 ${filePath}\uFF1A${reason}${extra ? `\uFF1B${extra}` : ""}`, code, primary);
|
|
411
|
+
}
|
|
412
|
+
function renameWithRetry(from, to) {
|
|
413
|
+
for (let attempt = 1; ; attempt++) {
|
|
414
|
+
try {
|
|
415
|
+
fs2.renameSync(from, to);
|
|
416
|
+
return;
|
|
417
|
+
} catch (err) {
|
|
418
|
+
if (attempt >= RENAME_ATTEMPTS || !RETRYABLE_CODES.has(errCode(err))) throw err;
|
|
419
|
+
sleepSync(RENAME_RETRY_MS);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
function commitFile(tmp, filePath) {
|
|
424
|
+
try {
|
|
425
|
+
renameWithRetry(tmp, filePath);
|
|
426
|
+
return;
|
|
427
|
+
} catch (primaryErr) {
|
|
428
|
+
const old = `${filePath}.old`;
|
|
429
|
+
try {
|
|
430
|
+
fs2.renameSync(filePath, old);
|
|
431
|
+
} catch (err) {
|
|
432
|
+
throw writeFailure(filePath, primaryErr, `\u6539\u540D .old \u5907\u4EFD\u4E5F\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
|
|
433
|
+
}
|
|
434
|
+
try {
|
|
435
|
+
fs2.renameSync(tmp, filePath);
|
|
436
|
+
} catch (err) {
|
|
437
|
+
try {
|
|
438
|
+
fs2.renameSync(old, filePath);
|
|
439
|
+
} catch {
|
|
440
|
+
throw writeFailure(filePath, primaryErr, `\u65B0\u5185\u5BB9\u843D\u76D8\u4E0E\u56DE\u6EDA\u90FD\u5931\u8D25\uFF0C\u65E7\u5185\u5BB9\u7559\u5728 ${old}`);
|
|
441
|
+
}
|
|
442
|
+
throw writeFailure(filePath, primaryErr, `\u6362\u540D\u843D\u76D8\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
|
|
443
|
+
}
|
|
444
|
+
try {
|
|
445
|
+
fs2.unlinkSync(old);
|
|
446
|
+
} catch {
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function writeConfigAtomic(filePath, obj) {
|
|
451
|
+
const existed = fs2.existsSync(filePath);
|
|
452
|
+
let prevText = "";
|
|
453
|
+
let fileMode;
|
|
454
|
+
if (existed) {
|
|
455
|
+
try {
|
|
456
|
+
prevText = fs2.readFileSync(filePath, "utf-8");
|
|
457
|
+
fileMode = fs2.statSync(filePath).mode & 511;
|
|
458
|
+
} catch (err) {
|
|
459
|
+
throw writeFailure(filePath, err);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const normalized = !existed || !isNormalized(prevText);
|
|
463
|
+
if (prevText) {
|
|
464
|
+
try {
|
|
465
|
+
fs2.copyFileSync(filePath, `${filePath}.bak-${Date.now()}`);
|
|
466
|
+
} catch {
|
|
467
|
+
}
|
|
468
|
+
rotateBaks(filePath);
|
|
469
|
+
}
|
|
470
|
+
const content = JSON.stringify(obj, null, 2) + "\n";
|
|
471
|
+
const tmp = path2.join(path2.dirname(filePath), `.${path2.basename(filePath)}.tmp-${process.pid}`);
|
|
472
|
+
try {
|
|
473
|
+
const fd = fs2.openSync(tmp, "w", fileMode);
|
|
474
|
+
try {
|
|
475
|
+
if (fileMode !== void 0) fs2.fchmodSync(fd, fileMode);
|
|
476
|
+
fs2.writeFileSync(fd, content, "utf-8");
|
|
477
|
+
fs2.fsyncSync(fd);
|
|
478
|
+
} finally {
|
|
479
|
+
fs2.closeSync(fd);
|
|
480
|
+
}
|
|
481
|
+
commitFile(tmp, filePath);
|
|
482
|
+
} catch (err) {
|
|
483
|
+
throw err instanceof ConfigWriteError ? err : writeFailure(filePath, err);
|
|
484
|
+
} finally {
|
|
485
|
+
try {
|
|
486
|
+
fs2.unlinkSync(tmp);
|
|
487
|
+
} catch {
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return { normalized };
|
|
491
|
+
}
|
|
492
|
+
var KEEP_BAKS, RENAME_ATTEMPTS, RENAME_RETRY_MS, RETRYABLE_CODES, ConfigWriteError;
|
|
493
|
+
var init_writer = __esm({
|
|
494
|
+
"src/config/writer.ts"() {
|
|
495
|
+
"use strict";
|
|
496
|
+
KEEP_BAKS = 3;
|
|
497
|
+
RENAME_ATTEMPTS = 5;
|
|
498
|
+
RENAME_RETRY_MS = 50;
|
|
499
|
+
RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
|
|
500
|
+
ConfigWriteError = class extends Error {
|
|
501
|
+
code;
|
|
502
|
+
constructor(message, code, cause) {
|
|
503
|
+
super(message, { cause });
|
|
504
|
+
this.name = "ConfigWriteError";
|
|
505
|
+
this.code = code;
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
// src/config/live.ts
|
|
512
|
+
function markSelfWrite() {
|
|
513
|
+
selfWrite.pending = true;
|
|
514
|
+
}
|
|
515
|
+
var LiveConfigClass, liveConfig, selfWrite;
|
|
516
|
+
var init_live = __esm({
|
|
517
|
+
"src/config/live.ts"() {
|
|
518
|
+
"use strict";
|
|
519
|
+
init_writer();
|
|
520
|
+
LiveConfigClass = class {
|
|
521
|
+
current = null;
|
|
522
|
+
/** 启动时注入(替代 registry.config = config) */
|
|
523
|
+
init(config) {
|
|
524
|
+
this.current = config;
|
|
525
|
+
}
|
|
526
|
+
/** 取整个 config 对象(只读引用,不要缓存) */
|
|
527
|
+
all() {
|
|
528
|
+
if (!this.current) {
|
|
529
|
+
throw new Error("[liveConfig] not initialized \u2014 call liveConfig.init() first");
|
|
530
|
+
}
|
|
531
|
+
return this.current;
|
|
532
|
+
}
|
|
533
|
+
/** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
|
|
534
|
+
get(dotPath) {
|
|
535
|
+
if (!this.current) return void 0;
|
|
536
|
+
return dotPath.split(".").reduce((acc, key) => {
|
|
537
|
+
if (acc == null) return void 0;
|
|
538
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") return void 0;
|
|
539
|
+
return acc[key];
|
|
540
|
+
}, this.current);
|
|
541
|
+
}
|
|
542
|
+
/** reload 时原地更新(Object.assign 保持引用不变)
|
|
543
|
+
* ⚠️ 0908 立法(浅层 assign 陷阱,见 docs/hot-reload-architecture.md):
|
|
544
|
+
* 这是**浅层** assign——顶层 key 被整体换新引用,构造期捕获嵌套子对象
|
|
545
|
+
* (如 config.cron、deps.everosCfg、adapter 的 config 段)的模块 reload 后
|
|
546
|
+
* 拿着的是旧对象。两条出路:(a) 使用时 liveConfig.get() 现读;(b) 注册为
|
|
547
|
+
* reloadOrchestrator entry,key 变化驱动 stop→start 重建。禁止新增"构造期
|
|
548
|
+
* 固化嵌套 config 引用"的代码。(不做 deep-merge:会破坏"删 key"语义。) */
|
|
549
|
+
assign(newConfig) {
|
|
550
|
+
if (!this.current) {
|
|
551
|
+
this.current = newConfig;
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
Object.assign(this.current, newConfig);
|
|
555
|
+
}
|
|
556
|
+
/** 改活树上的值;文件承载路径同步持久化(read-modify-write 回 config 文件) */
|
|
557
|
+
/**
|
|
558
|
+
* 改活树 + 落盘。
|
|
559
|
+
*
|
|
560
|
+
* 返回值 = **落盘**是否成功(活树无论成败都已同步——它是先改的)。绝大多数调用点照旧
|
|
561
|
+
* `void liveConfig.set(...)` 不理它;但**要打成功日志的调用点必须 await 这个布尔值**。
|
|
562
|
+
*
|
|
563
|
+
* 为什么把这个信号交出去(1001 审查捞回):本方法本来是 fire-and-forget,落盘失败只在
|
|
564
|
+
* `persistToFile` 里 warn 一行;而启动早段的调用点(两个免费档 fixup)紧接着打了句
|
|
565
|
+
* "免费档补齐 xxx" 的成功日志 ⇒ 配置**没写进文件**却被读成"写好了":进程内生效、托盘
|
|
566
|
+
* 读文件还是旧值、下次启动重放同一句——正是本仓最恨的假信号。
|
|
567
|
+
*/
|
|
568
|
+
async set(dotPath, val, options) {
|
|
569
|
+
if (!this.current) throw new Error("[liveConfig] not initialized \u2014 call liveConfig.init() first");
|
|
570
|
+
const keys = dotPath.split(".");
|
|
571
|
+
const dangerous = keys.find((k) => k === "__proto__" || k === "constructor" || k === "prototype");
|
|
572
|
+
if (dangerous) throw new Error(`[liveConfig] set: \u8DEF\u5F84\u6BB5\u300C${dangerous}\u300D\u662F\u4FDD\u7559\u540D\uFF0C\u62D2\u7EDD\u5199\u5165\uFF08${dotPath}\uFF09`);
|
|
573
|
+
let obj = this.current;
|
|
574
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
575
|
+
if (obj[keys[i]] == null) obj[keys[i]] = {};
|
|
576
|
+
obj = obj[keys[i]];
|
|
577
|
+
}
|
|
578
|
+
obj[keys[keys.length - 1]] = val;
|
|
579
|
+
return this.persistToFile(dotPath, val, options?.atomic === true);
|
|
580
|
+
}
|
|
581
|
+
/** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
|
|
582
|
+
async persistToFile(dotPath, val, atomic = false) {
|
|
583
|
+
const fs6 = await import("node:fs");
|
|
584
|
+
const cfgPath = this.current?._configFilePath;
|
|
585
|
+
if (!cfgPath || !fs6.existsSync(cfgPath)) {
|
|
586
|
+
console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
try {
|
|
590
|
+
const raw = JSON.parse(fs6.readFileSync(cfgPath, "utf-8"));
|
|
591
|
+
const keys = dotPath.split(".");
|
|
592
|
+
let o = raw;
|
|
593
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
594
|
+
if (o[keys[i]] == null) o[keys[i]] = {};
|
|
595
|
+
o = o[keys[i]];
|
|
596
|
+
}
|
|
597
|
+
o[keys[keys.length - 1]] = val;
|
|
598
|
+
if (atomic) {
|
|
599
|
+
writeConfigAtomic(cfgPath, raw);
|
|
600
|
+
} else fs6.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
|
|
601
|
+
const lastKey = keys[keys.length - 1].toLowerCase();
|
|
602
|
+
const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
|
|
603
|
+
const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
|
|
604
|
+
console.log(`[liveConfig] persisted ${dotPath} = ${shown} to ${cfgPath}`);
|
|
605
|
+
markSelfWrite();
|
|
606
|
+
return true;
|
|
607
|
+
} catch (e) {
|
|
608
|
+
console.warn(`[liveConfig] persist failed (${dotPath}): ${e.message}`);
|
|
609
|
+
return false;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
/** 是否已初始化 */
|
|
613
|
+
isReady() {
|
|
614
|
+
return this.current !== null;
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
liveConfig = new LiveConfigClass();
|
|
618
|
+
selfWrite = { pending: false };
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
// src/cc-driver/project-sessions.ts
|
|
623
|
+
import fs3 from "node:fs";
|
|
624
|
+
import os2 from "node:os";
|
|
625
|
+
import path3 from "node:path";
|
|
626
|
+
function mungeProjectKey(absPath) {
|
|
627
|
+
const normalized = absPath.replaceAll("\\", "/");
|
|
628
|
+
let out = "";
|
|
629
|
+
for (const ch of normalized) {
|
|
630
|
+
const code = ch.charCodeAt(0);
|
|
631
|
+
if (ch === "/" || ch === ":" || ch === "_" || ch === " " || ch === "~" || code > 127) out += "-";
|
|
632
|
+
else out += ch;
|
|
633
|
+
}
|
|
634
|
+
return out;
|
|
635
|
+
}
|
|
636
|
+
function projectsBase(homeDir) {
|
|
637
|
+
return path3.join(homeDir ?? os2.homedir(), ".claude", "projects");
|
|
638
|
+
}
|
|
639
|
+
function projectDirFor(workDir, homeDir) {
|
|
640
|
+
let abs = path3.resolve(workDir);
|
|
641
|
+
try {
|
|
642
|
+
abs = fs3.realpathSync(abs);
|
|
643
|
+
} catch {
|
|
644
|
+
}
|
|
645
|
+
return path3.join(projectsBase(homeDir), mungeProjectKey(abs));
|
|
646
|
+
}
|
|
647
|
+
var init_project_sessions = __esm({
|
|
648
|
+
"src/cc-driver/project-sessions.ts"() {
|
|
649
|
+
"use strict";
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
// src/cc-driver/router.ts
|
|
654
|
+
var BIND_TTL;
|
|
655
|
+
var init_router = __esm({
|
|
656
|
+
"src/cc-driver/router.ts"() {
|
|
657
|
+
"use strict";
|
|
658
|
+
init_live();
|
|
659
|
+
init_project_sessions();
|
|
660
|
+
BIND_TTL = 10 * 60 * 1e3;
|
|
661
|
+
}
|
|
662
|
+
});
|
|
663
|
+
|
|
664
|
+
// src/cc-driver/handoff.ts
|
|
665
|
+
import fs4 from "node:fs";
|
|
666
|
+
import os3 from "node:os";
|
|
667
|
+
import path4 from "node:path";
|
|
668
|
+
function registryDir2() {
|
|
669
|
+
return process.env.CC_DRIVER_REGISTRY_DIR || path4.join(os3.homedir(), ".engine7", "cc-driver", "hubs");
|
|
670
|
+
}
|
|
671
|
+
function canonical2(dir) {
|
|
672
|
+
try {
|
|
673
|
+
return fs4.realpathSync(dir);
|
|
674
|
+
} catch {
|
|
675
|
+
return path4.resolve(dir);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
function live(pid) {
|
|
679
|
+
try {
|
|
680
|
+
process.kill(pid, 0);
|
|
681
|
+
return true;
|
|
682
|
+
} catch (error) {
|
|
683
|
+
return error?.code === "EPERM";
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
async function findBoundCcTargets(workDir, key) {
|
|
687
|
+
let files;
|
|
688
|
+
try {
|
|
689
|
+
files = fs4.readdirSync(registryDir2());
|
|
690
|
+
} catch {
|
|
691
|
+
return [];
|
|
692
|
+
}
|
|
693
|
+
const endpoints = [];
|
|
694
|
+
for (const file of files.filter((f) => /^\d+\.json$/.test(f))) {
|
|
695
|
+
try {
|
|
696
|
+
const e = JSON.parse(fs4.readFileSync(path4.join(registryDir2(), file), "utf8"));
|
|
697
|
+
if (!Number.isInteger(e.pid) || e.pid <= 0 || !Number.isInteger(e.port) || e.port <= 0 || e.port > 65535 || typeof e.stateDir !== "string" || !Array.isArray(e.bindings) || !live(e.pid)) continue;
|
|
698
|
+
if (e.bindings.some((b) => typeof b.key === "string" && typeof b.workDir === "string" && (!key || b.key === key) && (!workDir || canonical2(b.workDir) === canonical2(workDir)))) endpoints.push(e);
|
|
699
|
+
} catch {
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
const lists = await Promise.all(endpoints.map(async (endpoint) => {
|
|
703
|
+
const response = await fetch(`http://127.0.0.1:${endpoint.port}/api/cc-driver/bindings`, {
|
|
704
|
+
headers: { "x-engine-console": "1" },
|
|
705
|
+
signal: AbortSignal.timeout(2e3)
|
|
706
|
+
});
|
|
707
|
+
if (!response.ok) throw new Error(`CC hub ${endpoint.port} cannot expose bindings (HTTP ${response.status}); update/restart this hub`);
|
|
708
|
+
const body = await response.json();
|
|
709
|
+
if (body.pid !== endpoint.pid || body.stateDir !== endpoint.stateDir || !Array.isArray(body.bindings)) {
|
|
710
|
+
throw new Error(`CC hub ${endpoint.port} identity changed; refusing to use another engine`);
|
|
711
|
+
}
|
|
712
|
+
return body.bindings.filter((b) => typeof b.key === "string" && typeof b.workDir === "string" && (b.sessionId === null || typeof b.sessionId === "string") && (!key || b.key === key) && (!workDir || canonical2(b.workDir) === canonical2(workDir))).map((b) => ({ ...b, endpoint }));
|
|
713
|
+
}));
|
|
714
|
+
return lists.flat();
|
|
715
|
+
}
|
|
716
|
+
var init_handoff = __esm({
|
|
717
|
+
"src/cc-driver/handoff.ts"() {
|
|
718
|
+
"use strict";
|
|
719
|
+
init_router();
|
|
720
|
+
}
|
|
721
|
+
});
|
|
722
|
+
|
|
723
|
+
// src/cc-driver/desktop-cli.ts
|
|
724
|
+
init_desktop();
|
|
725
|
+
init_handoff();
|
|
726
|
+
init_project_sessions();
|
|
727
|
+
import fs5 from "node:fs";
|
|
728
|
+
import os4 from "node:os";
|
|
729
|
+
import path5 from "node:path";
|
|
730
|
+
import { fileURLToPath } from "node:url";
|
|
731
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
732
|
+
import { createRequire } from "node:module";
|
|
733
|
+
var UUID = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
|
|
734
|
+
var shellQuote = (s) => `'${s.replace(/'/g, `'"'"'`)}'`;
|
|
735
|
+
async function loadDesktopPty() {
|
|
736
|
+
if (process.platform === "darwin") {
|
|
737
|
+
const require2 = createRequire(import.meta.url);
|
|
738
|
+
const native = require2("node-pty/lib/utils.js").loadNativeModule("pty");
|
|
739
|
+
const helper = path5.resolve(path5.dirname(require2.resolve("node-pty")), native.dir, "spawn-helper").replace("app.asar", "app.asar.unpacked").replace("node_modules.asar", "node_modules.asar.unpacked");
|
|
740
|
+
const mode = fs5.statSync(helper).mode;
|
|
741
|
+
if (!(mode & 64)) fs5.chmodSync(helper, mode | 64);
|
|
742
|
+
}
|
|
743
|
+
return import("node-pty");
|
|
744
|
+
}
|
|
745
|
+
function parseDesktopArgs(args) {
|
|
746
|
+
let resume, workDir = process.cwd(), help = false;
|
|
747
|
+
let title;
|
|
748
|
+
let claudeArgs = [];
|
|
749
|
+
for (let i = 0; i < args.length; i++) {
|
|
750
|
+
if (args[i] === "--") {
|
|
751
|
+
claudeArgs = args.slice(i + 1);
|
|
752
|
+
break;
|
|
753
|
+
}
|
|
754
|
+
if (args[i] === "--help" || args[i] === "-h") {
|
|
755
|
+
help = true;
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
if (args[i] === "--resume" || args[i] === "-r") {
|
|
759
|
+
resume = args[++i];
|
|
760
|
+
if (!resume || !UUID.test(resume)) throw new Error("--resume requires a full session UUID");
|
|
761
|
+
} else if (args[i] === "--title") {
|
|
762
|
+
title = normalizeDesktopTitle(args[++i]);
|
|
763
|
+
} else if (args[i] === "--work-dir") {
|
|
764
|
+
if (!args[i + 1]) throw new Error("--work-dir requires a directory");
|
|
765
|
+
workDir = path5.resolve(args[++i]);
|
|
766
|
+
} else throw new Error(`Unknown option ${args[i]}; use -- before Claude options`);
|
|
767
|
+
}
|
|
768
|
+
for (const arg of claudeArgs) {
|
|
769
|
+
const flag = arg.split("=")[0];
|
|
770
|
+
if (["--resume", "-r", "--continue", "-c", "--session-id", "--fork-session", "--no-session-persistence", "--worktree", "-w"].includes(flag)) {
|
|
771
|
+
throw new Error("Use the launcher --resume UUID; Claude session/worktree options cannot override the desktop identity");
|
|
772
|
+
}
|
|
773
|
+
if (["--print", "-p", "--input-format", "--output-format", "--bare"].includes(flag)) throw new Error("cc-desktop requires interactive Claude with hooks enabled");
|
|
774
|
+
}
|
|
775
|
+
return { resume, workDir, claudeArgs, help, ...title === void 0 ? {} : { title } };
|
|
776
|
+
}
|
|
777
|
+
async function runDesktopRename(args) {
|
|
778
|
+
let sessionId, title, workDir;
|
|
779
|
+
for (let i = 0; i < args.length; i++) {
|
|
780
|
+
if (args[i] === "--help" || args[i] === "-h") {
|
|
781
|
+
console.log("Usage: engine7 cc-desktop rename --session <UUID> --title <text> [--work-dir <directory>]\nAn empty title restores the directory-name display.");
|
|
782
|
+
return 0;
|
|
783
|
+
}
|
|
784
|
+
if (args[i] === "--session") {
|
|
785
|
+
sessionId = args[++i];
|
|
786
|
+
if (!sessionId || !UUID.test(sessionId)) throw new Error("--session requires a full session UUID");
|
|
787
|
+
} else if (args[i] === "--title") title = normalizeDesktopTitle(args[++i]);
|
|
788
|
+
else if (args[i] === "--work-dir") {
|
|
789
|
+
if (!args[i + 1]) throw new Error("--work-dir requires a directory");
|
|
790
|
+
workDir = path5.resolve(args[++i]);
|
|
791
|
+
} else throw new Error(`Unknown rename option ${args[i]}`);
|
|
792
|
+
}
|
|
793
|
+
if (!sessionId) throw new Error("rename requires --session UUID");
|
|
794
|
+
if (title === void 0) throw new Error("rename requires --title (use an empty string to clear it)");
|
|
795
|
+
const targets = await findDesktopTargets(workDir, sessionId);
|
|
796
|
+
if (targets.length !== 1) throw new Error(`Expected one connected desktop for ${sessionId}; found ${targets.length}`);
|
|
797
|
+
await renameDesktop(targets[0], title);
|
|
798
|
+
console.log(`Renamed desktop:${sessionId} \u2192 ${title || path5.basename(targets[0].workDir)}`);
|
|
799
|
+
return 0;
|
|
800
|
+
}
|
|
801
|
+
function desktopSettings(args, node, entry, descriptor) {
|
|
802
|
+
const remaining = [];
|
|
803
|
+
let settings = {};
|
|
804
|
+
for (let i = 0; i < args.length; i++) {
|
|
805
|
+
const arg = args[i];
|
|
806
|
+
if (arg === "--settings" || arg.startsWith("--settings=")) {
|
|
807
|
+
const value = arg === "--settings" ? args[++i] : arg.slice("--settings=".length);
|
|
808
|
+
if (!value) throw new Error("--settings requires a file or JSON object");
|
|
809
|
+
const parsed = JSON.parse(value.trim().startsWith("{") ? value : fs5.readFileSync(value, "utf8"));
|
|
810
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Invalid Claude settings");
|
|
811
|
+
settings = { ...settings, ...parsed, hooks: { ...settings.hooks, ...parsed.hooks } };
|
|
812
|
+
} else remaining.push(arg);
|
|
813
|
+
}
|
|
814
|
+
if (settings.disableAllHooks) throw new Error("cc-desktop needs native hooks; disableAllHooks cannot be enabled");
|
|
815
|
+
const command = [node, ...entry.endsWith(".ts") ? ["--import", import.meta.resolve("tsx")] : [], entry, "hook", descriptor].map(shellQuote).join(" ");
|
|
816
|
+
const hooks = { ...settings.hooks };
|
|
817
|
+
for (const event of ["SessionStart", "UserPromptSubmit", "Stop", "StopFailure", "SessionEnd", "PermissionRequest", "Notification"]) {
|
|
818
|
+
hooks[event] = [...hooks[event] || [], { hooks: [{ type: "command", command, timeout: 5 }] }];
|
|
819
|
+
}
|
|
820
|
+
return { args: remaining, settings: { ...settings, hooks } };
|
|
821
|
+
}
|
|
822
|
+
function claudeExecutable() {
|
|
823
|
+
for (const dir of (process.env.PATH || "").split(path5.delimiter)) {
|
|
824
|
+
for (const name of process.platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"]) {
|
|
825
|
+
const file = path5.join(dir, name);
|
|
826
|
+
if (!fs5.existsSync(file)) continue;
|
|
827
|
+
if (name.endsWith(".cmd")) {
|
|
828
|
+
const script = path5.join(dir, "node_modules", "@anthropic-ai", "claude-code", "cli.js");
|
|
829
|
+
if (fs5.existsSync(script)) return { command: process.execPath, args: [script] };
|
|
830
|
+
} else return { command: file, args: [] };
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
throw new Error("Cannot find the installed claude executable in PATH");
|
|
834
|
+
}
|
|
835
|
+
async function runHook(file) {
|
|
836
|
+
const descriptor = JSON.parse(fs5.readFileSync(file, "utf8"));
|
|
837
|
+
if (!Number.isInteger(descriptor.port) || descriptor.port < 1 || descriptor.port > 65535 || typeof descriptor.token !== "string") {
|
|
838
|
+
throw new Error("Invalid desktop hook endpoint");
|
|
839
|
+
}
|
|
840
|
+
const chunks = [];
|
|
841
|
+
let length = 0;
|
|
842
|
+
for await (const chunk of process.stdin) {
|
|
843
|
+
const b = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
844
|
+
length += b.length;
|
|
845
|
+
if (length > 1e6) throw new Error("Desktop hook input too large");
|
|
846
|
+
chunks.push(b);
|
|
847
|
+
}
|
|
848
|
+
const response = await fetch(`http://127.0.0.1:${descriptor.port}/hook`, {
|
|
849
|
+
method: "POST",
|
|
850
|
+
headers: { authorization: `Bearer ${descriptor.token}`, "content-type": "application/json" },
|
|
851
|
+
body: Buffer.concat(chunks),
|
|
852
|
+
signal: AbortSignal.timeout(2e3)
|
|
853
|
+
});
|
|
854
|
+
if (!response.ok) throw new Error(`Desktop hook rejected: ${response.status} ${await response.text()}`);
|
|
855
|
+
return 0;
|
|
856
|
+
}
|
|
857
|
+
async function runDesktopCli(args) {
|
|
858
|
+
if (args[0] === "hook") return runHook(args[1]);
|
|
859
|
+
if (args[0] === "rename") return runDesktopRename(args.slice(1));
|
|
860
|
+
const parsed = parseDesktopArgs(args);
|
|
861
|
+
if (parsed.help) {
|
|
862
|
+
console.log("Usage: engine7 cc-desktop [--resume <UUID>] [--title <text>] [--work-dir <directory>] [-- <Claude options>]\nOpens the installed interactive Claude Code with an Engine7 input bridge.\nUse cc_ask({prompt, sessionId: UUID}) to contact this open terminal.\nRename: engine7 cc-desktop rename --session <UUID> --title <text>");
|
|
863
|
+
return 0;
|
|
864
|
+
}
|
|
865
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("cc-desktop needs an interactive terminal (TTY)");
|
|
866
|
+
const sessionId = parsed.resume || randomUUID2();
|
|
867
|
+
if (parsed.resume) {
|
|
868
|
+
if (nativeSessionOwners(sessionId).length) throw new Error("This session is already open in Claude Code. Exit that window before opening it with cc-desktop.");
|
|
869
|
+
if (!fs5.existsSync(path5.join(projectDirFor(parsed.workDir), `${sessionId}.jsonl`))) throw new Error("Resume UUID not found in this project");
|
|
870
|
+
}
|
|
871
|
+
const command = claudeExecutable();
|
|
872
|
+
const pty = await loadDesktopPty();
|
|
873
|
+
const folder = fs5.mkdtempSync(path5.join(os4.tmpdir(), "engine7-cc-desktop-"));
|
|
874
|
+
fs5.chmodSync(folder, 448);
|
|
875
|
+
let terminal;
|
|
876
|
+
const bridge = await startDesktopBridge({ workDir: parsed.workDir, sessionId, title: parsed.title, writeInput: (data2) => {
|
|
877
|
+
if (!terminal) throw new Error("Desktop terminal has not started");
|
|
878
|
+
terminal.write(data2);
|
|
879
|
+
} });
|
|
880
|
+
const data = (value) => bridge.humanInput(value.toString());
|
|
881
|
+
const resize = () => {
|
|
882
|
+
try {
|
|
883
|
+
terminal?.resize(Math.max(1, process.stdout.columns || 80), Math.max(1, process.stdout.rows || 24));
|
|
884
|
+
} catch {
|
|
885
|
+
}
|
|
886
|
+
};
|
|
887
|
+
const terminate = () => {
|
|
888
|
+
try {
|
|
889
|
+
terminal?.kill();
|
|
890
|
+
} catch {
|
|
891
|
+
}
|
|
892
|
+
};
|
|
893
|
+
const previousRaw = !!process.stdin.isRaw;
|
|
894
|
+
try {
|
|
895
|
+
const desktops = await findDesktopTargets(parsed.workDir, sessionId);
|
|
896
|
+
if (desktops.some((d) => d.instance !== bridge.endpoint.instance) || nativeSessionOwners(sessionId).length) {
|
|
897
|
+
throw new Error("Another desktop already owns this session");
|
|
898
|
+
}
|
|
899
|
+
if (parsed.resume && (await findBoundCcTargets(parsed.workDir)).some((t) => t.sessionId === sessionId && t.busy)) {
|
|
900
|
+
throw new Error("The bound CC hub is still executing this session; wait for it to finish before opening the desktop");
|
|
901
|
+
}
|
|
902
|
+
const descriptor = path5.join(folder, "endpoint.json");
|
|
903
|
+
fs5.writeFileSync(descriptor, JSON.stringify(bridge.endpoint), { mode: 384 });
|
|
904
|
+
const here = path5.dirname(fileURLToPath(import.meta.url));
|
|
905
|
+
const entry = path5.join(here, import.meta.url.endsWith(".ts") ? "desktop-entry.ts" : "cc-desktop.mjs");
|
|
906
|
+
const merged = desktopSettings(parsed.claudeArgs, process.execPath, entry, descriptor);
|
|
907
|
+
const settings = path5.join(folder, "settings.json");
|
|
908
|
+
fs5.writeFileSync(settings, JSON.stringify(merged.settings), { mode: 384 });
|
|
909
|
+
process.stderr.write(`[cc-desktop] target=desktop:${sessionId}
|
|
910
|
+
`);
|
|
911
|
+
terminal = pty.spawn(command.command, [
|
|
912
|
+
...command.args,
|
|
913
|
+
...parsed.resume ? ["--resume", sessionId] : ["--session-id", sessionId],
|
|
914
|
+
...merged.args,
|
|
915
|
+
"--settings",
|
|
916
|
+
settings
|
|
917
|
+
], {
|
|
918
|
+
name: process.env.TERM || "xterm-256color",
|
|
919
|
+
cwd: parsed.workDir,
|
|
920
|
+
cols: process.stdout.columns || 80,
|
|
921
|
+
rows: process.stdout.rows || 24,
|
|
922
|
+
env: { ...process.env, CC_ASK_DEPTH: "1" }
|
|
923
|
+
});
|
|
924
|
+
terminal.onData((value) => process.stdout.write(value));
|
|
925
|
+
process.stdin.setEncoding("utf8");
|
|
926
|
+
process.stdin.setRawMode(true);
|
|
927
|
+
process.stdin.resume();
|
|
928
|
+
process.stdin.on("data", data);
|
|
929
|
+
process.stdout.on("resize", resize);
|
|
930
|
+
process.on("SIGTERM", terminate);
|
|
931
|
+
process.on("SIGHUP", terminate);
|
|
932
|
+
return await new Promise((resolve) => terminal.onExit(({ exitCode }) => resolve(exitCode)));
|
|
933
|
+
} finally {
|
|
934
|
+
process.stdin.off("data", data);
|
|
935
|
+
process.stdout.off("resize", resize);
|
|
936
|
+
process.off("SIGTERM", terminate);
|
|
937
|
+
process.off("SIGHUP", terminate);
|
|
938
|
+
process.stdin.setRawMode(previousRaw);
|
|
939
|
+
process.stdin.pause();
|
|
940
|
+
await bridge.close();
|
|
941
|
+
fs5.rmSync(folder, { recursive: true, force: true });
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// src/cc-driver/desktop-entry.ts
|
|
946
|
+
try {
|
|
947
|
+
process.exitCode = await runDesktopCli(process.argv.slice(2));
|
|
948
|
+
} catch (error) {
|
|
949
|
+
console.error(`[cc-desktop] ${error.message || error}`);
|
|
950
|
+
process.exitCode = 1;
|
|
951
|
+
}
|