dsh-starlite 0.2.0 → 0.3.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/dist/bridge.js ADDED
@@ -0,0 +1,1947 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ../agent-bridge/src/cli.ts
4
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
5
+ import { existsSync } from "node:fs";
6
+
7
+ // src/launcher.ts
8
+ import { release } from "node:os";
9
+ import { posix, win32 } from "node:path";
10
+ import { execFile, spawn } from "node:child_process";
11
+ import { lstat as lstat2, open as open2, readFile } from "node:fs/promises";
12
+ import { constants as constants2 } from "node:fs";
13
+ import { fileURLToPath } from "node:url";
14
+
15
+ // src/bootstrap.ts
16
+ import { createHash, randomUUID } from "node:crypto";
17
+ import { constants } from "node:fs";
18
+ import { lstat, mkdir, mkdtemp, open, realpath, rename, rm, writeFile } from "node:fs/promises";
19
+ import { isAbsolute, join, parse, resolve, sep } from "node:path";
20
+ var LIMIT = 64 * 1024 * 1024;
21
+ var NOTICE_LIMIT = 8 * 1024 * 1024;
22
+ var EXECUTABLE = "dsh-inochi2d-pet.exe";
23
+ var NOTICES = ["LICENSE", "THIRD_PARTY_LICENSES.txt"];
24
+ var RELEASE_REDIRECT_LIMIT = 3;
25
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
26
+ var MANIFEST_LIMIT = 256 * 1024;
27
+ var isDefaultModelId = (value) => value === "weiguang-default" || value === "bluefish-default";
28
+ async function prepareEmbeddedCompanion(options) {
29
+ options.signal?.throwIfAborted();
30
+ const assets = await realpath(options.assetDirectory);
31
+ const manifest = parseCompanionManifest(await ordinaryFile(assets, "manifest.json", MANIFEST_LIMIT), options.expectedVersion);
32
+ const executable = await ordinaryFile(assets, EXECUTABLE, LIMIT);
33
+ assertDigest(executable, manifest.executable);
34
+ assertWindowsGuiExecutable(executable);
35
+ const notices = await Promise.all(NOTICES.map((name) => ordinaryFile(assets, name, NOTICE_LIMIT)));
36
+ options.signal?.throwIfAborted();
37
+ await ensureSafeDirectory(options.cacheDirectory);
38
+ const models = manifest.schemaVersion === 2 ? [{ ...manifest.defaultModel, id: "weiguang-default", file: "default-model.vrm" }] : manifest.defaultModels.map((model) => ({ ...model, file: `${model.id}.vrm` }));
39
+ const descriptor = Buffer.from(JSON.stringify(manifest.schemaVersion === 2 ? {
40
+ schemaVersion: 2,
41
+ title: manifest.defaultModel.title,
42
+ sha256: manifest.defaultModel.sha256,
43
+ bytes: manifest.defaultModel.bytes,
44
+ file: "default-model.vrm"
45
+ } : { schemaVersion: 3, models: models.map(({ id, title, sha256, bytes, file, ...source }) => ({
46
+ id,
47
+ title,
48
+ sha256,
49
+ bytes,
50
+ file,
51
+ license: "license" in source ? source.license : void 0
52
+ })) }));
53
+ const cacheIdentity = manifest.schemaVersion === 2 ? manifest.defaultModel.sha256 : createHash("sha256").update(descriptor).digest("hex");
54
+ const cacheKey = createHash("sha256").update(`${manifest.executable.sha256}:${cacheIdentity}`).digest("hex");
55
+ const directory = join(options.cacheDirectory, `${manifest.version}-${cacheKey}`);
56
+ if (!await exists(directory)) {
57
+ const temporary = await mkdtemp(join(options.cacheDirectory, ".stage-"));
58
+ try {
59
+ await writeFile(join(temporary, EXECUTABLE), executable, { flag: "wx", mode: 448 });
60
+ for (const [index, name] of NOTICES.entries()) {
61
+ await writeFile(join(temporary, name), notices[index], { flag: "wx", mode: 384 });
62
+ }
63
+ await writeFile(join(temporary, "default-model.json"), descriptor, { flag: "wx", mode: 384 });
64
+ options.signal?.throwIfAborted();
65
+ try {
66
+ await rename(temporary, directory);
67
+ } catch (error) {
68
+ if (!await exists(directory)) throw error;
69
+ }
70
+ } finally {
71
+ await rm(temporary, { recursive: true, force: true });
72
+ }
73
+ }
74
+ await assertSafeDirectory(directory);
75
+ assertEqual(await ordinaryFile(directory, EXECUTABLE, LIMIT), executable);
76
+ for (const [index, name] of NOTICES.entries()) assertEqual(await ordinaryFile(directory, name, NOTICE_LIMIT), notices[index]);
77
+ assertEqual(await ordinaryFile(directory, "default-model.json", MANIFEST_LIMIT), descriptor);
78
+ options.signal?.throwIfAborted();
79
+ const selectedId = options.defaultModelId === void 0 ? "weiguang-default" : options.defaultModelId;
80
+ const selected = models.find((model) => model.id === selectedId);
81
+ if (!selected) return { executable: join(directory, EXECUTABLE), defaultModelReady: false };
82
+ let defaultModelReady = false;
83
+ try {
84
+ const modelFile = join(directory, selected.file);
85
+ if (await exists(modelFile)) {
86
+ const cached = await ordinaryFile(directory, selected.file, LIMIT);
87
+ try {
88
+ assertDigest(cached, selected);
89
+ defaultModelReady = true;
90
+ } catch {
91
+ }
92
+ }
93
+ if (!defaultModelReady) await downloadCharacter(selected, directory, selected.file, options.fetch ?? fetch, options.signal);
94
+ defaultModelReady = true;
95
+ } catch {
96
+ options.signal?.throwIfAborted();
97
+ }
98
+ options.signal?.throwIfAborted();
99
+ return { executable: join(directory, EXECUTABLE), defaultModelReady };
100
+ }
101
+ function parseCompanionManifest(bytes, expectedVersion) {
102
+ if (bytes.byteLength > MANIFEST_LIMIT) throw new Error("embedded companion manifest exceeds size limit");
103
+ const value = JSON.parse(Buffer.from(bytes).toString("utf8"));
104
+ if (!record(value) || ![2, 3].includes(value.schemaVersion) || !keys(value, ["schemaVersion", "version", "platform", "executable", value.schemaVersion === 2 ? "defaultModel" : "defaultModels"]) || value.platform !== "windows-x64" || typeof value.version !== "string" || value.version.length > 64 || !/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u.test(value.version) || value.version !== expectedVersion || !record(value.executable) || !keys(value.executable, ["file", "sha256", "bytes"]) || value.executable.file !== EXECUTABLE || !digest(value.executable)) {
105
+ throw new Error("invalid embedded companion manifest");
106
+ }
107
+ const models = value.schemaVersion === 2 ? [value.defaultModel] : value.defaultModels;
108
+ if (!Array.isArray(models) || models.length < 1 || models.length > 2) throw new Error("invalid default model catalog");
109
+ const ids = /* @__PURE__ */ new Set();
110
+ for (const model of models) {
111
+ validateDefaultSource(model, value.schemaVersion === 3);
112
+ if (value.schemaVersion === 3) {
113
+ const entry = model;
114
+ if (ids.has(entry.id)) throw new Error("duplicate default model identifier");
115
+ ids.add(entry.id);
116
+ }
117
+ }
118
+ if (value.schemaVersion === 3 && !ids.has("weiguang-default")) throw new Error("default catalog must retain Weiguang");
119
+ return value;
120
+ }
121
+ function validateDefaultSource(value, catalog) {
122
+ if (!record(value) || !keys(value, ["title", "url", "sha256", "bytes", ...catalog ? ["id", "license"] : []], ["localTest"]) || !validTitle(value.title) || !digest(value) || value.localTest !== void 0 && value.localTest !== true || typeof value.url !== "string" || value.url.length > 2048 || /[\p{Cc}\\]/u.test(value.url)) {
123
+ throw new Error("invalid starter character metadata");
124
+ }
125
+ if (catalog && (!isDefaultModelId(value.id) || !record(value.license) || !keys(value.license, ["title", "text"]) || !validTitle(value.license.title) || typeof value.license.text !== "string" || !value.license.text.trim() || Buffer.byteLength(value.license.text) > 100 * 1024 || value.license.text.includes("\0"))) throw new Error("invalid starter character license");
126
+ const url = new URL(value.url);
127
+ if (!url.pathname.toLowerCase().endsWith(".vrm") || url.username || url.password || url.hash || url.protocol !== "https:" && !(value.localTest === true && url.protocol === "http:" && url.hostname === "127.0.0.1" && /^http:\/\/127\.0\.0\.1(?::\d+)?\//u.test(value.url))) {
128
+ throw new Error("invalid starter character download source");
129
+ }
130
+ }
131
+ function validTitle(value) {
132
+ return typeof value === "string" && Boolean(value.trim()) && value.length <= 128 && !/[\p{Cc}]/u.test(value);
133
+ }
134
+ function assertWindowsGuiExecutable(bytes) {
135
+ if (bytes.length < 64 || bytes.readUInt16LE(0) !== 23117) throw new Error("invalid embedded Windows executable");
136
+ const pe = bytes.readUInt32LE(60);
137
+ if (pe < 64 || pe + 94 > bytes.length || bytes.readUInt32LE(pe) !== 17744 || bytes.readUInt16LE(pe + 4) !== 34404 || bytes.readUInt16LE(pe + 20) < 70 || pe + 24 + bytes.readUInt16LE(pe + 20) > bytes.length || bytes.readUInt16LE(pe + 24) !== 523 || bytes.readUInt16LE(pe + 24 + 68) !== 2) throw new Error("embedded executable must be Windows x64 GUI PE32+");
138
+ }
139
+ async function downloadCharacter(source, directory, filename, request, signal) {
140
+ const timeout = AbortSignal.timeout(3e4);
141
+ const downloadSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
142
+ const response = await characterResponse(source.url, request, downloadSignal);
143
+ if (!response.ok || response.redirected || !response.body) {
144
+ await response.body?.cancel();
145
+ throw new Error("starter character download failed");
146
+ }
147
+ const length = response.headers.get("content-length");
148
+ if (length !== null && (!/^\d+$/u.test(length) || Number(length) !== source.bytes)) {
149
+ await response.body.cancel();
150
+ throw new Error("starter character download size mismatch");
151
+ }
152
+ const temporary = join(directory, `.download-${randomUUID()}`);
153
+ let file;
154
+ const reader = response.body.getReader();
155
+ try {
156
+ file = await open(temporary, "wx", 384);
157
+ const hash = createHash("sha256");
158
+ let bytes = 0;
159
+ while (true) {
160
+ downloadSignal.throwIfAborted();
161
+ const item = await reader.read();
162
+ if (item.done) break;
163
+ bytes += item.value.byteLength;
164
+ if (bytes > source.bytes || bytes > LIMIT) throw new Error("starter character download exceeds its size limit");
165
+ hash.update(item.value);
166
+ await file.writeFile(item.value);
167
+ }
168
+ if (bytes !== source.bytes || hash.digest("hex") !== source.sha256) throw new Error("starter character download integrity mismatch");
169
+ await file.sync();
170
+ await file.close();
171
+ file = void 0;
172
+ downloadSignal.throwIfAborted();
173
+ const modelFile = join(directory, filename);
174
+ if (await exists(modelFile)) {
175
+ const cached = await ordinaryFile(directory, filename, LIMIT);
176
+ try {
177
+ assertDigest(cached, source);
178
+ return;
179
+ } catch {
180
+ }
181
+ }
182
+ await rename(temporary, modelFile);
183
+ } finally {
184
+ await reader.cancel().catch(() => void 0);
185
+ reader.releaseLock();
186
+ await file?.close();
187
+ await rm(temporary, { force: true });
188
+ }
189
+ }
190
+ async function characterResponse(source, request, signal) {
191
+ const initial = new URL(source);
192
+ const githubRelease = initial.protocol === "https:" && initial.hostname === "github.com" && !initial.port && !initial.username && !initial.password && !initial.search && !initial.hash && /^\/[a-zA-Z0-9-]+\/[a-zA-Z0-9_.-]+\/releases\/download\/[^/]+\/[^/]+\.vrm$/u.test(initial.pathname);
193
+ let current = source;
194
+ const visited = /* @__PURE__ */ new Set([current]);
195
+ for (let redirects = 0; ; ++redirects) {
196
+ signal.throwIfAborted();
197
+ const response = await request(current, { method: "GET", redirect: githubRelease ? "manual" : "error", credentials: "omit", signal });
198
+ if (!REDIRECT_STATUSES.has(response.status)) return response;
199
+ await response.body?.cancel();
200
+ const location = response.headers.get("location");
201
+ if (!githubRelease || redirects >= RELEASE_REDIRECT_LIMIT || !location) throw new Error("starter character redirect rejected");
202
+ let next;
203
+ try {
204
+ next = new URL(location, current);
205
+ } catch {
206
+ throw new Error("starter character redirect rejected");
207
+ }
208
+ if (next.protocol !== "https:" || next.hostname !== "release-assets.githubusercontent.com" || next.port || next.username || next.password || next.hash || visited.has(next.href)) {
209
+ throw new Error("starter character redirect rejected");
210
+ }
211
+ current = next.href;
212
+ visited.add(current);
213
+ }
214
+ }
215
+ async function ordinaryFile(directory, name, limit) {
216
+ await assertSafeDirectory(directory);
217
+ const path = join(directory, name), info = await lstat(path);
218
+ if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > limit) throw new Error("unsafe companion file");
219
+ const file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
220
+ try {
221
+ const opened = await file.stat();
222
+ if (!opened.isFile() || opened.size !== info.size || opened.size > limit) throw new Error("unsafe companion file");
223
+ const bytes = Buffer.alloc(info.size);
224
+ let offset = 0;
225
+ while (offset < bytes.length) {
226
+ const read = await file.read(bytes, offset, bytes.length - offset, offset);
227
+ if (read.bytesRead === 0) throw new Error("companion file changed while reading");
228
+ offset += read.bytesRead;
229
+ }
230
+ const extra = await file.read(Buffer.alloc(1), 0, 1, bytes.length);
231
+ if (extra.bytesRead !== 0) throw new Error("companion file changed while reading");
232
+ return bytes;
233
+ } finally {
234
+ await file.close();
235
+ }
236
+ }
237
+ async function ensureSafeDirectory(directory) {
238
+ if (!isAbsolute(directory)) throw new Error("companion cache must be an absolute local directory");
239
+ const absolute = resolve(directory), root = parse(absolute).root;
240
+ let current = root;
241
+ for (const component of absolute.slice(root.length).split(sep).filter(Boolean)) {
242
+ current = join(current, component);
243
+ try {
244
+ await mkdir(current, { mode: 448 });
245
+ } catch (error) {
246
+ if (!record(error) || error.code !== "EEXIST") throw error;
247
+ }
248
+ await assertSafeDirectory(current);
249
+ }
250
+ }
251
+ async function assertSafeDirectory(directory) {
252
+ const info = await lstat(directory);
253
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("unsafe companion directory");
254
+ }
255
+ async function exists(path) {
256
+ try {
257
+ await lstat(path);
258
+ return true;
259
+ } catch (error) {
260
+ if (record(error) && error.code === "ENOENT") return false;
261
+ throw error;
262
+ }
263
+ }
264
+ function assertDigest(bytes, expected) {
265
+ if (bytes.length !== expected.bytes || createHash("sha256").update(bytes).digest("hex") !== expected.sha256) throw new Error("companion file integrity mismatch");
266
+ }
267
+ function assertEqual(actual, expected) {
268
+ if (!actual.equals(expected)) throw new Error("cached companion file integrity mismatch");
269
+ }
270
+ function record(value) {
271
+ return typeof value === "object" && value !== null && !Array.isArray(value);
272
+ }
273
+ function keys(value, required, optional = []) {
274
+ return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
275
+ }
276
+ function digest(value) {
277
+ return typeof value.sha256 === "string" && /^[a-f0-9]{64}$/u.test(value.sha256) && typeof value.bytes === "number" && Number.isSafeInteger(value.bytes) && value.bytes >= 1 && value.bytes <= LIMIT;
278
+ }
279
+
280
+ // src/launcher.ts
281
+ function isWslEnvironment(environment = process.env) {
282
+ return Boolean(environment.WSL_INTEROP || environment.WSL_DISTRO_NAME) || release().toLowerCase().includes("microsoft");
283
+ }
284
+ function detectCompanionHost(platform = process.platform, architecture = process.arch, inWsl = isWslEnvironment()) {
285
+ if (architecture !== "x64") return void 0;
286
+ if (platform === "win32") return "windows";
287
+ return platform === "linux" && inWsl ? "wsl" : void 0;
288
+ }
289
+ function companionEnvironment(source) {
290
+ const result = {};
291
+ for (const name of ["PATH", "Path", "HOME", "LANG", "LC_ALL", "SYSTEMROOT", "SystemRoot", "WINDIR", "TEMP", "TMP", "LOCALAPPDATA", "APPDATA", "USERPROFILE", "WSL_INTEROP", "WSL_DISTRO_NAME"]) {
292
+ if (source[name] !== void 0) result[name] = source[name];
293
+ }
294
+ return result;
295
+ }
296
+ async function prepareWindowsExecutable(host, options = {}) {
297
+ const paths = host === "windows" ? win32 : posix;
298
+ options.signal?.throwIfAborted();
299
+ let executable = "";
300
+ const override = process.env.DSH_INOCHI2D_PET_EXE;
301
+ if (override !== void 0) {
302
+ const local = validateExecutableOverride(override);
303
+ executable = host === "windows" ? local : (await execFileText("wslpath", ["-u", local], options.signal)).trim();
304
+ } else {
305
+ const windowsDirectories = (await execFileText("powershell.exe", [
306
+ "-NoLogo",
307
+ "-NoProfile",
308
+ "-NonInteractive",
309
+ "-Command",
310
+ "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); [Environment]::GetFolderPath('LocalApplicationData'); [Environment]::GetFolderPath('ApplicationData')"
311
+ ], options.signal)).trim().split(/\r?\n/u);
312
+ if (windowsDirectories.length !== 2 || windowsDirectories.some((path) => !validWindowsDirectory(path))) throw new Error("Windows application directories are unavailable");
313
+ const windowsCache = windowsDirectories[0];
314
+ const localCache = host === "windows" ? windowsCache : (await execFileText("wslpath", ["-u", windowsCache], options.signal)).trim();
315
+ const roaming = host === "windows" ? windowsDirectories[1] : (await execFileText("wslpath", ["-u", windowsDirectories[1]], options.signal)).trim();
316
+ if (host === "wsl" && (!validPosixDirectory(localCache) || !validPosixDirectory(roaming))) throw new Error("invalid Windows application directories");
317
+ const defaultModelIds = await defaultModelsToAcquire(paths.join(roaming, "com.starcried.dsh-inochi2d-pet", "settings.json"));
318
+ const metadata = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
319
+ if (typeof metadata !== "object" || metadata === null || !("version" in metadata) || typeof metadata.version !== "string") {
320
+ throw new Error("invalid StarLite plugin package version");
321
+ }
322
+ for (const defaultModelId of defaultModelIds.length ? defaultModelIds : [null]) {
323
+ const prepared = await prepareEmbeddedCompanion({
324
+ assetDirectory: fileURLToPath(new URL("../assets/windows-x64/", import.meta.url)),
325
+ cacheDirectory: paths.join(localCache, "StarCried", "StarLite", "companions"),
326
+ expectedVersion: metadata.version,
327
+ defaultModelId,
328
+ ...options.signal ? { signal: options.signal } : {}
329
+ });
330
+ executable = prepared.executable;
331
+ if (defaultModelId && !prepared.defaultModelReady) options.onDefaultModelFailure?.();
332
+ }
333
+ }
334
+ if (host === "windows" && validateExecutableOverride(executable) !== executable || host === "wsl" && (!validPosixDirectory(executable) || posix.basename(executable).toLowerCase() !== "dsh-inochi2d-pet.exe")) {
335
+ throw new Error("StarLite for DSH executable is invalid");
336
+ }
337
+ options.signal?.throwIfAborted();
338
+ return executable;
339
+ }
340
+ function validWindowsDirectory(path) {
341
+ return /^[a-z]:[\\/]/iu.test(path) && win32.isAbsolute(path) && !/[\p{Cc}"<>|]/u.test(path) && !path.split(/[\\/]/u).some((part) => part === "." || part === "..");
342
+ }
343
+ function validPosixDirectory(path) {
344
+ return posix.isAbsolute(path) && !/[\p{Cc}]/u.test(path) && !path.split("/").some((part) => part === "." || part === "..");
345
+ }
346
+ async function defaultModelsToAcquire(path) {
347
+ const maximum = 4 * 1024 * 1024;
348
+ try {
349
+ const info = await lstat2(path);
350
+ if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > maximum) return [];
351
+ const file = await open2(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
352
+ try {
353
+ const opened = await file.stat();
354
+ if (!opened.isFile() || opened.size !== info.size) return [];
355
+ const bytes = Buffer.alloc(info.size + 1);
356
+ const result = await file.read(bytes, 0, bytes.length, 0);
357
+ if (result.bytesRead !== info.size) return [];
358
+ const value = JSON.parse(bytes.subarray(0, result.bytesRead).toString("utf8"));
359
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return [];
360
+ if (!("schemaVersion" in value)) return [];
361
+ if (value.schemaVersion === 4) {
362
+ const models = "models" in value && Array.isArray(value.models) ? value.models : [];
363
+ const installed = (id) => models.some((model) => typeof model === "object" && model !== null && !Array.isArray(model) && "id" in model && model.id === id);
364
+ const updates = "pendingModelUpdates" in value ? value.pendingModelUpdates : [];
365
+ if (!Array.isArray(updates) || updates.length > 2 || !updates.every((id) => isDefaultModelId(id) && installed(id))) return [];
366
+ const requested = new Set(updates);
367
+ if ("activeModelId" in value && isDefaultModelId(value.activeModelId) && !installed(value.activeModelId)) requested.add(value.activeModelId);
368
+ return [...requested];
369
+ }
370
+ if (![1, 2, 3].includes(value.schemaVersion)) return [];
371
+ const preferences = "preferences" in value ? value.preferences : void 0;
372
+ if (typeof preferences === "object" && preferences !== null && "modelEnabled" in preferences) return preferences.modelEnabled === true ? ["weiguang-default"] : [];
373
+ return ["weiguang-default"];
374
+ } finally {
375
+ await file.close();
376
+ }
377
+ } catch (error) {
378
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT" ? ["weiguang-default"] : [];
379
+ }
380
+ }
381
+ function validateExecutableOverride(override) {
382
+ if (!win32.isAbsolute(override) || !/^[a-z]:[\\/]/iu.test(override) || /[\p{Cc}"<>|]/u.test(override) || override.split(/[\\/]/u).some((part) => part === "." || part === "..") || win32.basename(override).toLowerCase() !== "dsh-inochi2d-pet.exe") {
383
+ throw new Error("DSH_INOCHI2D_PET_EXE must name a local Windows companion executable");
384
+ }
385
+ return override;
386
+ }
387
+ function execFileText(file, arguments_, signal) {
388
+ return new Promise((resolve2, reject) => {
389
+ execFile(file, arguments_, {
390
+ encoding: "utf8",
391
+ maxBuffer: 8192,
392
+ timeout: 3e3,
393
+ windowsHide: true,
394
+ env: companionEnvironment(process.env),
395
+ ...signal ? { signal } : {}
396
+ }, (error, stdout) => {
397
+ if (error) reject(error);
398
+ else resolve2(stdout);
399
+ });
400
+ });
401
+ }
402
+
403
+ // ../agent-bridge/src/hub-client.ts
404
+ import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
405
+ import { readdir, readFile as readFile2, stat } from "node:fs/promises";
406
+ import { release as release2 } from "node:os";
407
+ import { posix as posix2, win32 as win322 } from "node:path";
408
+
409
+ // ../protocol/src/interaction.ts
410
+ var ACTIVITIES = ["thinking", "responding", "command", "editing", "reading", "searching", "compacting", "tool", "waiting", "completed", "error", "blocked", "idle"];
411
+ function isOpaqueRef(value) {
412
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value);
413
+ }
414
+
415
+ // ../protocol/src/control.ts
416
+ var MAX_CONTROL_BYTES = 32768;
417
+ function parseControlPerform(value) {
418
+ const row = object(value, ["animation", "text", "durationMs", "stop"]), result = {};
419
+ if (row.stop !== void 0) {
420
+ if (row.stop !== true || Object.keys(row).length !== 1) throw Error("invalid stop");
421
+ return { stop: true };
422
+ }
423
+ if (row.animation !== void 0) result.animation = text(row.animation, 160);
424
+ if (row.text !== void 0) result.text = text(row.text, 1e3);
425
+ if (row.durationMs !== void 0) result.durationMs = number(row.durationMs, 1e3, 3e4);
426
+ if (!result.animation && !result.text || result.durationMs !== void 0 && !result.text) throw Error("empty performance");
427
+ return bounded(result);
428
+ }
429
+ function parseControlStage(value) {
430
+ const row = object(value, ["position", "scale", "pointerEnabled"]), result = {};
431
+ if (row.position !== void 0) {
432
+ const position = object(row.position, ["x", "y"]);
433
+ result.position = { x: number(position.x, 0, 1), y: number(position.y, 0, 1) };
434
+ }
435
+ if (row.scale !== void 0) result.scale = number(row.scale, 0.5, 1.5);
436
+ if (row.pointerEnabled !== void 0) result.pointerEnabled = boolean(row.pointerEnabled);
437
+ if (!Object.keys(result).length) throw Error("empty stage");
438
+ return result;
439
+ }
440
+ function object(value, allowed) {
441
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("invalid control object");
442
+ const row = value;
443
+ if (allowed) keys2(row, allowed);
444
+ return row;
445
+ }
446
+ function keys2(row, allowed) {
447
+ if (Object.keys(row).some((key) => !allowed.includes(key))) throw Error("unknown control field");
448
+ }
449
+ function boolean(value) {
450
+ if (typeof value !== "boolean") throw Error("invalid control flag");
451
+ return value;
452
+ }
453
+ function number(value, min, max) {
454
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) throw Error("invalid control number");
455
+ return value;
456
+ }
457
+ function text(value, max) {
458
+ if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u.test(value)) throw Error("invalid control text");
459
+ return value;
460
+ }
461
+ function bounded(value) {
462
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_CONTROL_BYTES) throw Error("control exceeds wire limit");
463
+ return value;
464
+ }
465
+
466
+ // ../protocol/src/hub.ts
467
+ var HUB_PROTOCOL_VERSION = 1;
468
+ var MAX_HUB_BYTES = 32768;
469
+ var MAX_TRANSIENT_SOURCE_TTL_MS = 6e5;
470
+ var HUB_STATES = /* @__PURE__ */ new Set([
471
+ "idle",
472
+ "thinking",
473
+ "working",
474
+ "completed",
475
+ "error",
476
+ "blocked",
477
+ "approval"
478
+ ]);
479
+ var HUB_BUBBLE_KINDS = /* @__PURE__ */ new Set([
480
+ "reasoning",
481
+ "response",
482
+ "tool",
483
+ "notice"
484
+ ]);
485
+ function parseHubRuntimeDescriptor(value) {
486
+ const row = object2(value, ["protocolVersion", "port", "token", "pid", "startedAt"]);
487
+ if (row.protocolVersion !== HUB_PROTOCOL_VERSION) {
488
+ throw new Error("unsupported hub protocol version");
489
+ }
490
+ const port = safeInt(row.port, 1, 65535);
491
+ const token = row.token;
492
+ if (typeof token !== "string" || !/^[A-Za-z0-9_-]{32,128}$/u.test(token)) {
493
+ throw new Error("invalid hub token");
494
+ }
495
+ const pid = safeInt(row.pid, 1, 2147483647);
496
+ const startedAt = safeInt(row.startedAt, 0, Number.MAX_SAFE_INTEGER);
497
+ return { protocolVersion: HUB_PROTOCOL_VERSION, port, token, pid, startedAt };
498
+ }
499
+ function parseHubSourceRegistration(value) {
500
+ const row = object2(value, [
501
+ "protocolVersion",
502
+ "sourceId",
503
+ "agent",
504
+ "name",
505
+ "persistent",
506
+ "pid",
507
+ "windowPid",
508
+ "sessionTitle"
509
+ ]);
510
+ if (row.protocolVersion !== HUB_PROTOCOL_VERSION) {
511
+ throw new Error("unsupported hub protocol version");
512
+ }
513
+ const result = {
514
+ protocolVersion: HUB_PROTOCOL_VERSION,
515
+ sourceId: ref(row.sourceId),
516
+ agent: slug(row.agent),
517
+ name: safeText(row.name, 60),
518
+ persistent: bool(row.persistent),
519
+ ...row.pid === void 0 ? {} : { pid: safeInt(row.pid, 1, 2147483647) },
520
+ ...row.windowPid === void 0 ? {} : { windowPid: safeInt(row.windowPid, 1, 2147483647) },
521
+ ...row.sessionTitle === void 0 ? {} : { sessionTitle: safeText(row.sessionTitle, 120) }
522
+ };
523
+ return bounded2(result);
524
+ }
525
+ function parseHubEventInput(value) {
526
+ const row = object2(value, [
527
+ "protocolVersion",
528
+ "sourceId",
529
+ "agent",
530
+ "name",
531
+ "state",
532
+ "activity",
533
+ "bubble",
534
+ "toolName",
535
+ "sessionTitle",
536
+ "persistent",
537
+ "pid",
538
+ "windowPid",
539
+ "ttlMs"
540
+ ]);
541
+ if (row.protocolVersion !== HUB_PROTOCOL_VERSION) {
542
+ throw new Error("unsupported hub protocol version");
543
+ }
544
+ if (typeof row.state !== "string" || !HUB_STATES.has(row.state)) {
545
+ throw new Error("invalid hub state");
546
+ }
547
+ if (row.activity !== void 0 && !ACTIVITIES.includes(row.activity)) {
548
+ throw new Error("invalid hub activity");
549
+ }
550
+ let bubble;
551
+ if (row.bubble !== void 0) {
552
+ const b = object2(row.bubble, ["kind", "text"]);
553
+ if (typeof b.kind !== "string" || !HUB_BUBBLE_KINDS.has(b.kind)) {
554
+ throw new Error("invalid hub bubble kind");
555
+ }
556
+ bubble = { kind: b.kind, text: singleLineText(b.text, 120) };
557
+ }
558
+ const result = {
559
+ protocolVersion: HUB_PROTOCOL_VERSION,
560
+ sourceId: ref(row.sourceId),
561
+ agent: slug(row.agent),
562
+ name: safeText(row.name, 60),
563
+ state: row.state,
564
+ ...row.activity === void 0 ? {} : { activity: row.activity },
565
+ ...bubble ? { bubble } : {},
566
+ ...row.toolName === void 0 ? {} : { toolName: singleLineText(row.toolName, 60) },
567
+ ...row.sessionTitle === void 0 ? {} : { sessionTitle: singleLineText(row.sessionTitle, 120) },
568
+ ...row.persistent === void 0 ? {} : { persistent: bool(row.persistent) },
569
+ ...row.pid === void 0 ? {} : { pid: safeInt(row.pid, 1, 2147483647) },
570
+ ...row.windowPid === void 0 ? {} : { windowPid: safeInt(row.windowPid, 1, 2147483647) },
571
+ ...row.ttlMs === void 0 ? {} : { ttlMs: safeInt(row.ttlMs, 1e3, MAX_TRANSIENT_SOURCE_TTL_MS) }
572
+ };
573
+ return bounded2(result);
574
+ }
575
+ function parseHubControlCommandRequest(value) {
576
+ const row = object2(value, ["protocolVersion", "sourceId", "sessionTitle", "action", "perform", "stage"]);
577
+ if (row.protocolVersion !== HUB_PROTOCOL_VERSION) {
578
+ throw new Error("unsupported hub protocol version");
579
+ }
580
+ const base = {
581
+ protocolVersion: HUB_PROTOCOL_VERSION,
582
+ sourceId: ref(row.sourceId),
583
+ ...row.sessionTitle === void 0 ? {} : { sessionTitle: safeText(row.sessionTitle, 120) }
584
+ };
585
+ if (row.action === "acquire" || row.action === "renew" || row.action === "release") {
586
+ if (row.perform !== void 0 || row.stage !== void 0) {
587
+ throw new Error("unexpected hub control payload");
588
+ }
589
+ return bounded2({ ...base, action: row.action });
590
+ }
591
+ if (row.action === "perform") {
592
+ if (row.stage !== void 0) throw new Error("unexpected stage payload");
593
+ return bounded2({ ...base, action: "perform", perform: parseControlPerform(row.perform) });
594
+ }
595
+ if (row.action === "stage") {
596
+ if (row.perform !== void 0) throw new Error("unexpected perform payload");
597
+ return bounded2({ ...base, action: "stage", stage: parseControlStage(row.stage) });
598
+ }
599
+ throw new Error("invalid hub control action");
600
+ }
601
+ function object2(value, allowed) {
602
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
603
+ throw new Error("invalid hub object");
604
+ }
605
+ const row = value;
606
+ for (const key of Object.keys(row)) {
607
+ if (!allowed.includes(key)) throw new Error("unknown hub field");
608
+ }
609
+ return row;
610
+ }
611
+ function ref(value) {
612
+ if (!isOpaqueRef(value)) throw new Error("invalid hub source reference");
613
+ return value;
614
+ }
615
+ function slug(value) {
616
+ if (typeof value !== "string" || !/^[a-z0-9][a-z0-9_-]{0,31}$/u.test(value)) {
617
+ throw new Error("invalid agent identifier");
618
+ }
619
+ return value;
620
+ }
621
+ function safeText(value, max) {
622
+ if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u.test(value)) {
623
+ throw new Error("invalid hub text");
624
+ }
625
+ return value.trim();
626
+ }
627
+ function singleLineText(value, max) {
628
+ if (typeof value !== "string") throw new Error("invalid hub text");
629
+ const normalized = value.normalize("NFC").replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/gu, " ").replace(/\s+/gu, " ").trim();
630
+ if (!normalized || normalized.length > max) {
631
+ throw new Error("invalid hub text");
632
+ }
633
+ return normalized;
634
+ }
635
+ function bool(value) {
636
+ if (typeof value !== "boolean") throw new Error("invalid hub boolean");
637
+ return value;
638
+ }
639
+ function safeInt(value, min, max) {
640
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) {
641
+ throw new Error("invalid hub integer");
642
+ }
643
+ return value;
644
+ }
645
+ function bounded2(value) {
646
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_HUB_BYTES) {
647
+ throw new Error("hub payload exceeds wire limit");
648
+ }
649
+ return value;
650
+ }
651
+
652
+ // ../protocol/src/index.ts
653
+ var DEFAULT_BUBBLE_GRAPHEMES = 120;
654
+ var MAX_SANITIZE_CODE_UNITS = 16384;
655
+ function sanitizeBubbleText(input, maximumGraphemes = DEFAULT_BUBBLE_GRAPHEMES) {
656
+ if (typeof input !== "string" || !Number.isSafeInteger(maximumGraphemes)) {
657
+ return "";
658
+ }
659
+ if (maximumGraphemes < 1 || maximumGraphemes > 500) {
660
+ return "";
661
+ }
662
+ const bounded3 = input.length > MAX_SANITIZE_CODE_UNITS ? input.slice(0, MAX_SANITIZE_CODE_UNITS) : input;
663
+ const normalized = bounded3.normalize("NFC").replace(/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\u001B\\)?|[@-_])/gu, "").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/gu, "").replace(/\s+/gu, " ").trim();
664
+ if (normalized.length === 0) {
665
+ return "";
666
+ }
667
+ const graphemes = segmentGraphemes(normalized);
668
+ const truncated = graphemes.length > maximumGraphemes || input.length > MAX_SANITIZE_CODE_UNITS;
669
+ return truncated ? `${graphemes.slice(0, maximumGraphemes - 1).join("")}\u2026` : normalized;
670
+ }
671
+ function segmentGraphemes(value) {
672
+ if (typeof Intl.Segmenter === "function") {
673
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
674
+ return [...segmenter.segment(value)].map(({ segment }) => segment);
675
+ }
676
+ return Array.from(value);
677
+ }
678
+
679
+ // ../agent-bridge/src/hub-client.ts
680
+ var DEFAULT_APP_ID = "com.starcried.dsh-inochi2d-pet";
681
+ var HEALTH_TIMEOUT_MS = 1500;
682
+ var REQUEST_TIMEOUT_MS = 5e3;
683
+ var CONTROL_TIMEOUT_MS = 4e4;
684
+ var StarLiteHubClient = class {
685
+ #options;
686
+ #fetch;
687
+ #cached;
688
+ constructor(options = {}) {
689
+ this.#options = options;
690
+ this.#fetch = options.fetch ?? fetch;
691
+ }
692
+ async resolveHubFile() {
693
+ const env = this.#options.env ?? process.env;
694
+ if (this.#options.hubFile) return this.#options.hubFile;
695
+ if (env.STARLITE_HUB_FILE?.trim()) return env.STARLITE_HUB_FILE.trim();
696
+ const platform = this.#options.platform ?? process.platform;
697
+ if (platform === "win32") {
698
+ const localAppData = env.LOCALAPPDATA?.trim();
699
+ if (!localAppData) return void 0;
700
+ return win322.join(localAppData, DEFAULT_APP_ID, "hub.json");
701
+ }
702
+ if (platform === "linux" && isWslEnvironment2(env)) {
703
+ const windowsLocal = await readWindowsLocalAppData().catch(() => void 0);
704
+ if (!windowsLocal) return void 0;
705
+ const wslLocal = await wslPathUnix(windowsLocal).catch(() => void 0);
706
+ return wslLocal ? posix2.join(wslLocal, DEFAULT_APP_ID, "hub.json") : void 0;
707
+ }
708
+ return void 0;
709
+ }
710
+ async resolveExecutable() {
711
+ const env = this.#options.env ?? process.env;
712
+ const explicit = this.#options.executable?.trim() || env.STARLITE_EXE?.trim() || env.DSH_INOCHI2D_PET_EXE?.trim();
713
+ if (explicit) {
714
+ return await isRegularFile(explicit) ? explicit : void 0;
715
+ }
716
+ const platform = this.#options.platform ?? process.platform;
717
+ const baseDir = platform === "win32" ? env.LOCALAPPDATA?.trim() : platform === "linux" && isWslEnvironment2(env) ? await readWindowsLocalAppData().then((p) => p ? wslPathUnix(p) : void 0).catch(() => void 0) : void 0;
718
+ if (!baseDir) return void 0;
719
+ const join3 = platform === "win32" ? win322.join : posix2.join;
720
+ const companionsRoot = join3(baseDir, "StarCried", "StarLite", "companions");
721
+ try {
722
+ const entries = await readdir(companionsRoot, { withFileTypes: true });
723
+ const candidates = [];
724
+ for (const entry of entries) {
725
+ if (!entry.isDirectory()) continue;
726
+ for (const exeName of ["starlite.exe", "dsh-inochi2d-pet.exe"]) {
727
+ const candidate = join3(companionsRoot, entry.name, exeName);
728
+ const info = await stat(candidate).catch(() => void 0);
729
+ if (info?.isFile()) {
730
+ candidates.push({ path: candidate, mtimeMs: info.mtimeMs });
731
+ }
732
+ }
733
+ }
734
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
735
+ return candidates[0]?.path;
736
+ } catch {
737
+ return void 0;
738
+ }
739
+ }
740
+ async discover() {
741
+ if (this.#cached && await this.checkHealth(this.#cached)) {
742
+ return this.#cached;
743
+ }
744
+ this.#cached = void 0;
745
+ const file = await this.resolveHubFile();
746
+ if (!file) return void 0;
747
+ const descriptor = await readHubDescriptor(file);
748
+ if (!descriptor) return void 0;
749
+ if (!await this.checkHealth(descriptor)) return void 0;
750
+ this.#cached = descriptor;
751
+ return descriptor;
752
+ }
753
+ async ensureRunning(options = {}) {
754
+ const live = await this.discover();
755
+ if (live) return live;
756
+ if (!options.autoLaunch) return void 0;
757
+ const executable = this.#options.prepareExecutable ? await this.#options.prepareExecutable() : await this.resolveExecutable();
758
+ if (!executable) return void 0;
759
+ try {
760
+ if (this.#options.spawnDesktop) {
761
+ await this.#options.spawnDesktop(executable);
762
+ } else {
763
+ await spawnDesktopCompanion(executable, this.#options.env ?? process.env, this.#options.platform ?? process.platform);
764
+ }
765
+ } catch {
766
+ return void 0;
767
+ }
768
+ const deadline = Date.now() + (options.waitMs ?? 8e3);
769
+ while (Date.now() < deadline) {
770
+ const ready = await this.discover();
771
+ if (ready) return ready;
772
+ await sleep(150);
773
+ }
774
+ return void 0;
775
+ }
776
+ async checkHealth(descriptor) {
777
+ try {
778
+ const response = await this.#fetch(`http://127.0.0.1:${descriptor.port}/v1/health`, {
779
+ method: "GET",
780
+ headers: { Authorization: `Bearer ${descriptor.token}` },
781
+ signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS)
782
+ });
783
+ await response.body?.cancel();
784
+ return response.status === 204;
785
+ } catch {
786
+ return false;
787
+ }
788
+ }
789
+ async registerSource(registration, options = {}) {
790
+ const payload = parseHubSourceRegistration({
791
+ protocolVersion: HUB_PROTOCOL_VERSION,
792
+ ...registration
793
+ });
794
+ const descriptor = await this.ensureRunning(options);
795
+ if (!descriptor) return false;
796
+ return this.#postNoContent(descriptor, "/v1/source/register", payload);
797
+ }
798
+ async heartbeat(sourceId) {
799
+ const descriptor = await this.discover();
800
+ if (!descriptor) return false;
801
+ return this.#postNoContent(descriptor, "/v1/source/heartbeat", {
802
+ protocolVersion: HUB_PROTOCOL_VERSION,
803
+ sourceId
804
+ });
805
+ }
806
+ async unregisterSource(sourceId) {
807
+ const descriptor = await this.discover();
808
+ if (!descriptor) return false;
809
+ return this.#postNoContent(descriptor, "/v1/source/unregister", {
810
+ protocolVersion: HUB_PROTOCOL_VERSION,
811
+ sourceId
812
+ });
813
+ }
814
+ async sendEvent(event, options = {}) {
815
+ const payload = parseHubEventInput({
816
+ protocolVersion: HUB_PROTOCOL_VERSION,
817
+ ...event
818
+ });
819
+ const descriptor = await this.ensureRunning(options);
820
+ if (!descriptor) return false;
821
+ return this.#postNoContent(descriptor, "/v1/event", payload);
822
+ }
823
+ async controlInspect(sourceId) {
824
+ const descriptor = await this.discover();
825
+ if (!descriptor) return void 0;
826
+ return this.#postJson(
827
+ descriptor,
828
+ "/v1/control/inspect",
829
+ { protocolVersion: HUB_PROTOCOL_VERSION, sourceId },
830
+ REQUEST_TIMEOUT_MS
831
+ );
832
+ }
833
+ async controlCommand(request) {
834
+ const payload = parseHubControlCommandRequest({
835
+ protocolVersion: HUB_PROTOCOL_VERSION,
836
+ ...request
837
+ });
838
+ const descriptor = await this.discover();
839
+ if (!descriptor) return void 0;
840
+ return this.#postJson(descriptor, "/v1/control/command", payload, CONTROL_TIMEOUT_MS);
841
+ }
842
+ async #postNoContent(descriptor, path, body) {
843
+ try {
844
+ const response = await this.#fetch(`http://127.0.0.1:${descriptor.port}${path}`, {
845
+ method: "POST",
846
+ headers: {
847
+ Authorization: `Bearer ${descriptor.token}`,
848
+ "Content-Type": "application/json"
849
+ },
850
+ body: JSON.stringify(body),
851
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
852
+ });
853
+ await response.body?.cancel();
854
+ if (response.status === 401) this.#cached = void 0;
855
+ return response.ok;
856
+ } catch {
857
+ this.#cached = void 0;
858
+ return false;
859
+ }
860
+ }
861
+ async #postJson(descriptor, path, body, timeoutMs) {
862
+ try {
863
+ const response = await this.#fetch(`http://127.0.0.1:${descriptor.port}${path}`, {
864
+ method: "POST",
865
+ headers: {
866
+ Authorization: `Bearer ${descriptor.token}`,
867
+ "Content-Type": "application/json"
868
+ },
869
+ body: JSON.stringify(body),
870
+ signal: AbortSignal.timeout(timeoutMs)
871
+ });
872
+ if (response.status === 401) this.#cached = void 0;
873
+ if (!response.ok) {
874
+ await response.body?.cancel();
875
+ return void 0;
876
+ }
877
+ const parsed = await response.json();
878
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
879
+ } catch {
880
+ this.#cached = void 0;
881
+ return void 0;
882
+ }
883
+ }
884
+ };
885
+ async function readHubDescriptor(filePath) {
886
+ try {
887
+ const text2 = await readFile2(filePath, "utf8");
888
+ if (Buffer.byteLength(text2, "utf8") > 4096) return void 0;
889
+ return parseHubRuntimeDescriptor(JSON.parse(text2));
890
+ } catch {
891
+ return void 0;
892
+ }
893
+ }
894
+ function sanitizedLaunchEnv(source) {
895
+ const result = {};
896
+ for (const name of [
897
+ "PATH",
898
+ "Path",
899
+ "HOME",
900
+ "LANG",
901
+ "LC_ALL",
902
+ "SYSTEMROOT",
903
+ "SystemRoot",
904
+ "WINDIR",
905
+ "TEMP",
906
+ "TMP",
907
+ "LOCALAPPDATA",
908
+ "APPDATA",
909
+ "USERPROFILE",
910
+ "WSL_INTEROP",
911
+ "WSL_DISTRO_NAME",
912
+ "STARLITE_HUB_FILE"
913
+ ]) {
914
+ if (source[name] !== void 0) result[name] = source[name];
915
+ }
916
+ return result;
917
+ }
918
+ async function spawnDesktopCompanion(executable, env, platform) {
919
+ return new Promise((resolve2, reject) => {
920
+ const child = spawn2(executable, ["--agent-launch"], {
921
+ detached: platform === "win32",
922
+ shell: false,
923
+ stdio: "ignore",
924
+ windowsHide: true,
925
+ env: sanitizedLaunchEnv(env)
926
+ });
927
+ let settled = false;
928
+ const finish = (error) => {
929
+ if (settled) return;
930
+ settled = true;
931
+ if (error) reject(error);
932
+ else resolve2();
933
+ };
934
+ child.once("error", (error) => finish(error));
935
+ child.once("spawn", () => finish());
936
+ child.unref();
937
+ });
938
+ }
939
+ function isWslEnvironment2(env) {
940
+ return Boolean(env.WSL_INTEROP || env.WSL_DISTRO_NAME) || release2().toLowerCase().includes("microsoft");
941
+ }
942
+ function execText(command, args) {
943
+ return new Promise((resolve2, reject) => {
944
+ execFile2(command, args, { timeout: 3e3 }, (error, stdout) => {
945
+ if (error) reject(error);
946
+ else resolve2(stdout.trim());
947
+ });
948
+ });
949
+ }
950
+ async function readWindowsLocalAppData() {
951
+ const out = await execText("powershell.exe", [
952
+ "-NoLogo",
953
+ "-NoProfile",
954
+ "-NonInteractive",
955
+ "-Command",
956
+ "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); [Environment]::GetFolderPath('LocalApplicationData')"
957
+ ]);
958
+ return out || void 0;
959
+ }
960
+ async function wslPathUnix(windowsPath) {
961
+ const out = await execText("wslpath", ["-u", windowsPath]);
962
+ return out || void 0;
963
+ }
964
+ async function isRegularFile(path) {
965
+ const info = await stat(path).catch(() => void 0);
966
+ return info?.isFile() === true;
967
+ }
968
+ function sleep(ms) {
969
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
970
+ }
971
+
972
+ // ../agent-bridge/src/hook.ts
973
+ import { createHash as createHash2 } from "node:crypto";
974
+ import { basename } from "node:path";
975
+ var codexActivityEvents = ["UserPromptSubmit", "PreModelRequest", "PreToolUse", "Stop", "Interrupt"];
976
+ var KNOWN_AGENT_NAMES = {
977
+ antigravity: "Antigravity",
978
+ codex: "Codex",
979
+ "claude-code": "Claude Code",
980
+ opencode: "Opencode",
981
+ workbuddy: "Workbuddy",
982
+ dsh: "DSH"
983
+ };
984
+ var VALID_STATES = /* @__PURE__ */ new Set([
985
+ "idle",
986
+ "thinking",
987
+ "working",
988
+ "completed",
989
+ "error",
990
+ "blocked",
991
+ "approval"
992
+ ]);
993
+ var VALID_ACTIVITIES = /* @__PURE__ */ new Set([
994
+ "thinking",
995
+ "responding",
996
+ "command",
997
+ "editing",
998
+ "reading",
999
+ "searching",
1000
+ "compacting",
1001
+ "tool",
1002
+ "waiting",
1003
+ "completed",
1004
+ "error",
1005
+ "blocked",
1006
+ "idle"
1007
+ ]);
1008
+ function defaultAgentDisplayName(agent) {
1009
+ return KNOWN_AGENT_NAMES[agent] ?? agent;
1010
+ }
1011
+ function deterministicSourceId(seed) {
1012
+ const digest2 = createHash2("sha256").update(seed, "utf8").digest();
1013
+ digest2[6] = digest2[6] & 15 | 64;
1014
+ digest2[8] = digest2[8] & 63 | 128;
1015
+ const hex = digest2.subarray(0, 16).toString("hex");
1016
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
1017
+ }
1018
+ function toolActivity(name) {
1019
+ if (/^(?:bash|pwsh|shell|run_command|execute_command|exec_command|terminal)$/iu.test(name)) {
1020
+ return "command";
1021
+ }
1022
+ if (/^(?:edit|write|replace_file_content|multi_replace_file_content)$/iu.test(name) || /(?:str_replace|edit_file|write_file|apply_patch|create_file|write_to_file)/iu.test(name)) {
1023
+ return "editing";
1024
+ }
1025
+ if (/^(?:read|read_image|ls|view_file|view_file_outline|view_code_item)$/iu.test(name) || /(?:read_file|list_files|list_dir|fs_read|fs_list)/iu.test(name)) {
1026
+ return "reading";
1027
+ }
1028
+ if (/^(?:glob|grep|find_by_name|grep_search|search_web)$/iu.test(name) || /(?:search|grep|find_files)/iu.test(name)) {
1029
+ return "searching";
1030
+ }
1031
+ return "tool";
1032
+ }
1033
+ function normalizeHookEvent(flags, rawPayload) {
1034
+ const agent = sanitizeSlug(flags.agent);
1035
+ const name = sanitizeBubbleText(flags.name ?? defaultAgentDisplayName(agent), 60) || agent;
1036
+ const payload = asRecord(rawPayload);
1037
+ const rawSessionKey = stringField(payload, "conversationId") ?? stringField(payload, "session_id") ?? stringField(payload, "thread-id") ?? stringField(payload, "thread_id") ?? String(flags.ppid ?? process.ppid ?? 1);
1038
+ const sourceId = deterministicSourceId(`starlite-hook:${agent}:${rawSessionKey}`);
1039
+ const sessionTitle = safeProjectTitle(flags.title, payload);
1040
+ const rawEvent = flags.event ?? stringField(payload, "hookEventName") ?? stringField(payload, "hook_event_name") ?? stringField(payload, "event") ?? stringField(payload, "type") ?? "";
1041
+ if (flags.state && VALID_STATES.has(flags.state)) {
1042
+ const state = flags.state;
1043
+ const safeTool = flags.tool ? sanitizeBubbleText(flags.tool, 60) || void 0 : void 0;
1044
+ const activity = flags.activity && VALID_ACTIVITIES.has(flags.activity) ? flags.activity : safeTool && state === "working" ? toolActivity(safeTool) : defaultActivityForState(state);
1045
+ return {
1046
+ sourceId,
1047
+ agent,
1048
+ name,
1049
+ state,
1050
+ activity,
1051
+ ...safeTool ? { toolName: safeTool } : {},
1052
+ ...sessionTitle ? { sessionTitle } : {},
1053
+ shouldLaunch: flags.autoLaunch ?? (state === "thinking" || state === "working"),
1054
+ shouldUnregister: false
1055
+ };
1056
+ }
1057
+ const mapped = mapLifecycleEvent(rawEvent, payload, flags.tool);
1058
+ return {
1059
+ sourceId,
1060
+ agent,
1061
+ name,
1062
+ state: mapped.state,
1063
+ activity: mapped.activity,
1064
+ ...mapped.toolName ? { toolName: mapped.toolName } : {},
1065
+ ...sessionTitle ? { sessionTitle } : {},
1066
+ shouldLaunch: flags.autoLaunch ?? mapped.shouldLaunch,
1067
+ shouldUnregister: mapped.shouldUnregister
1068
+ };
1069
+ }
1070
+ async function runHookCommand(client, flags, rawPayload) {
1071
+ const normalized = normalizeHookEvent(flags, rawPayload);
1072
+ if (normalized.shouldUnregister) {
1073
+ await client.unregisterSource(normalized.sourceId).catch(() => void 0);
1074
+ return normalized;
1075
+ }
1076
+ const windowPid = validPid(flags.ppid ?? process.ppid);
1077
+ await client.sendEvent(
1078
+ {
1079
+ sourceId: normalized.sourceId,
1080
+ agent: normalized.agent,
1081
+ name: normalized.name,
1082
+ state: normalized.state,
1083
+ activity: normalized.activity,
1084
+ ...normalized.toolName ? { toolName: normalized.toolName } : {},
1085
+ ...normalized.sessionTitle ? { sessionTitle: normalized.sessionTitle } : {},
1086
+ persistent: false,
1087
+ ...windowPid !== void 0 ? { windowPid } : {}
1088
+ },
1089
+ { autoLaunch: normalized.shouldLaunch, waitMs: 3e3 }
1090
+ ).catch(() => void 0);
1091
+ return normalized;
1092
+ }
1093
+ function mapLifecycleEvent(eventName, payload, cliTool) {
1094
+ const lower = eventName.trim().toLowerCase();
1095
+ const toolCall = asRecord(payload?.toolCall);
1096
+ const rawTool = cliTool ?? stringField(toolCall, "name") ?? stringField(payload, "tool_name") ?? stringField(payload, "toolName");
1097
+ const safeTool = rawTool ? sanitizeBubbleText(rawTool, 60) || void 0 : void 0;
1098
+ const hasError = Boolean(stringField(payload, "error"));
1099
+ switch (lower) {
1100
+ case "sessionstart":
1101
+ case "session_start":
1102
+ case "session-start":
1103
+ return { state: "idle", activity: "idle", shouldLaunch: true, shouldUnregister: false };
1104
+ case "sessionend":
1105
+ case "session_end":
1106
+ case "session-end":
1107
+ return { state: "idle", activity: "idle", shouldLaunch: false, shouldUnregister: true };
1108
+ case "preinvocation":
1109
+ case "userpromptsubmit":
1110
+ case "premodelrequest":
1111
+ case "turn-started":
1112
+ case "turn/start":
1113
+ case "thinking":
1114
+ return { state: "thinking", activity: "thinking", shouldLaunch: true, shouldUnregister: false };
1115
+ case "postinvocation":
1116
+ return { state: "thinking", activity: "responding", shouldLaunch: false, shouldUnregister: false };
1117
+ case "pretooluse":
1118
+ case "posttooluse":
1119
+ case "tool-start":
1120
+ case "tool/call":
1121
+ if (hasError) {
1122
+ return { state: "error", activity: "error", shouldLaunch: false, shouldUnregister: false };
1123
+ }
1124
+ return {
1125
+ state: "working",
1126
+ activity: safeTool ? toolActivity(safeTool) : "tool",
1127
+ ...safeTool ? { toolName: safeTool } : {},
1128
+ shouldLaunch: true,
1129
+ shouldUnregister: false
1130
+ };
1131
+ case "notification":
1132
+ case "approval-requested":
1133
+ case "approval":
1134
+ case "waiting":
1135
+ return {
1136
+ state: "approval",
1137
+ activity: "waiting",
1138
+ ...safeTool ? { toolName: safeTool } : {},
1139
+ shouldLaunch: false,
1140
+ shouldUnregister: false
1141
+ };
1142
+ case "stop":
1143
+ case "subagentstop":
1144
+ case "agent-turn-complete":
1145
+ case "turn-ended":
1146
+ case "turn/end": {
1147
+ const reason = (stringField(payload, "terminationReason") ?? stringField(payload, "reason") ?? "").toUpperCase();
1148
+ if (hasError || reason === "ERROR") {
1149
+ return { state: "error", activity: "error", shouldLaunch: false, shouldUnregister: false };
1150
+ }
1151
+ if (reason === "USER_CANCELED" || reason === "CANCELLED" || reason === "ABORTED") {
1152
+ return { state: "idle", activity: "idle", shouldLaunch: false, shouldUnregister: false };
1153
+ }
1154
+ if (reason === "MAX_INVOCATIONS" || reason === "MAX_FORCED_INVOCATIONS" || reason === "MAX_TOKEN_BUDGET_EXCEEDED" || reason === "BLOCKED") {
1155
+ return { state: "blocked", activity: "blocked", shouldLaunch: false, shouldUnregister: false };
1156
+ }
1157
+ return { state: "completed", activity: "completed", shouldLaunch: false, shouldUnregister: false };
1158
+ }
1159
+ case "interrupt":
1160
+ return { state: "idle", activity: "idle", shouldLaunch: false, shouldUnregister: true };
1161
+ case "error":
1162
+ case "turn-failed":
1163
+ return { state: "error", activity: "error", shouldLaunch: false, shouldUnregister: false };
1164
+ default:
1165
+ return { state: "thinking", activity: "thinking", shouldLaunch: false, shouldUnregister: false };
1166
+ }
1167
+ }
1168
+ function defaultActivityForState(state) {
1169
+ switch (state) {
1170
+ case "thinking":
1171
+ return "thinking";
1172
+ case "working":
1173
+ return "tool";
1174
+ case "approval":
1175
+ return "waiting";
1176
+ case "completed":
1177
+ return "completed";
1178
+ case "error":
1179
+ return "error";
1180
+ case "blocked":
1181
+ return "blocked";
1182
+ default:
1183
+ return "idle";
1184
+ }
1185
+ }
1186
+ function safeProjectTitle(explicitTitle, payload) {
1187
+ if (explicitTitle) {
1188
+ const clean = sanitizeBubbleText(explicitTitle, 80);
1189
+ if (clean) return clean;
1190
+ }
1191
+ const cwd = stringField(payload, "cwd");
1192
+ if (cwd) {
1193
+ const base = safePathBasename(cwd);
1194
+ if (base) return base;
1195
+ }
1196
+ const workspaces = payload?.workspacePaths;
1197
+ if (Array.isArray(workspaces) && typeof workspaces[0] === "string") {
1198
+ return safePathBasename(workspaces[0]);
1199
+ }
1200
+ return void 0;
1201
+ }
1202
+ function safePathBasename(rawPath) {
1203
+ const normalized = rawPath.replace(/\\+/gu, "/").replace(/\/+$/u, "");
1204
+ const name = basename(normalized);
1205
+ if (!name || name === "." || name === "..") return void 0;
1206
+ return sanitizeBubbleText(name, 80) || void 0;
1207
+ }
1208
+ function sanitizeSlug(raw) {
1209
+ const cleaned = raw.trim().toLowerCase().replace(/[^a-z0-9_-]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 32);
1210
+ return cleaned || "agent";
1211
+ }
1212
+ function asRecord(value) {
1213
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1214
+ }
1215
+ function stringField(row, key) {
1216
+ const value = row?.[key];
1217
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
1218
+ }
1219
+ function validPid(pid) {
1220
+ return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 && pid <= 2147483647 ? pid : void 0;
1221
+ }
1222
+
1223
+ // ../agent-bridge/src/mcp.ts
1224
+ import { randomUUID as randomUUID2 } from "node:crypto";
1225
+ import { createRequire } from "node:module";
1226
+ import { createInterface } from "node:readline";
1227
+
1228
+ // ../agent-bridge/src/codex-titles.ts
1229
+ import { open as open3, stat as stat2 } from "node:fs/promises";
1230
+ import { homedir } from "node:os";
1231
+ import { join as join2 } from "node:path";
1232
+ var MAX_TAIL_BYTES = 512 * 1024;
1233
+ var CodexTitleIndex = class {
1234
+ #codexHome;
1235
+ #cache;
1236
+ constructor(codexHome) {
1237
+ this.#codexHome = codexHome;
1238
+ }
1239
+ async lookup(sessionId) {
1240
+ if (!sessionId || sessionId.length > 128) return void 0;
1241
+ const indexPath = this.#resolveIndexPath();
1242
+ if (!indexPath) return void 0;
1243
+ try {
1244
+ const info = await stat2(indexPath);
1245
+ if (!info.isFile() || info.size <= 0) return void 0;
1246
+ if (this.#cache && this.#cache.path === indexPath && this.#cache.mtimeMs === info.mtimeMs && this.#cache.size === info.size) {
1247
+ return this.#cache.titles.get(sessionId);
1248
+ }
1249
+ const titles = await readBoundedTitles(indexPath, info.size);
1250
+ this.#cache = { path: indexPath, mtimeMs: info.mtimeMs, size: info.size, titles };
1251
+ return titles.get(sessionId);
1252
+ } catch {
1253
+ return void 0;
1254
+ }
1255
+ }
1256
+ #resolveIndexPath() {
1257
+ const base = this.#codexHome?.trim() || process.env.CODEX_HOME?.trim() || join2(homedir(), ".codex");
1258
+ return base ? join2(base, "session_index.jsonl") : void 0;
1259
+ }
1260
+ };
1261
+ async function readBoundedTitles(path, size) {
1262
+ const titles = /* @__PURE__ */ new Map();
1263
+ const readLength = Math.min(size, MAX_TAIL_BYTES);
1264
+ const offset = Math.max(0, size - readLength);
1265
+ const handle = await open3(path, "r");
1266
+ try {
1267
+ const buffer = Buffer.alloc(readLength);
1268
+ const { bytesRead } = await handle.read(buffer, 0, readLength, offset);
1269
+ if (bytesRead <= 0) return titles;
1270
+ let text2 = buffer.subarray(0, bytesRead).toString("utf8");
1271
+ if (offset > 0) {
1272
+ const firstNewline = text2.indexOf("\n");
1273
+ if (firstNewline < 0) return titles;
1274
+ text2 = text2.slice(firstNewline + 1);
1275
+ }
1276
+ for (const rawLine of text2.split(/\r?\n/u)) {
1277
+ const line = rawLine.trim();
1278
+ if (!line) continue;
1279
+ try {
1280
+ const parsed = JSON.parse(line);
1281
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
1282
+ const row = parsed;
1283
+ if (typeof row.id !== "string" || typeof row.thread_name !== "string") continue;
1284
+ const cleanTitle = sanitizeBubbleText(row.thread_name, 80);
1285
+ if (row.id && cleanTitle) {
1286
+ titles.set(row.id, cleanTitle);
1287
+ }
1288
+ } catch {
1289
+ }
1290
+ }
1291
+ } finally {
1292
+ await handle.close();
1293
+ }
1294
+ return titles;
1295
+ }
1296
+
1297
+ // ../agent-bridge/src/mcp.ts
1298
+ var SERVER_VERSION = createRequire(import.meta.url)("../package.json").version;
1299
+ var HEARTBEAT_INTERVAL_MS = 15e3;
1300
+ var SUPPORTED_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set(["2025-03-26", "2024-11-05"]);
1301
+ var MCP_INSTRUCTIONS = `Use StarLite tools only when the user asks to interact through their StarLite desktop character.
1302
+ 1. Call starlite_inspect first. If disabled, ask the user to enable Session control in StarLite settings; never edit settings files to bypass it.
1303
+ 2. Call starlite_control with action "acquire". Ownership expires after 5 minutes of inactivity. Release when done.
1304
+ 3. Use starlite_perform for one atomic animation (exact name from inspect) and/or concise plain-text bubble (1\u20131000 chars, durationMs 1000\u201330000).
1305
+ 4. Use starlite_stage sparingly for temporary current-monitor position (0\u20131), scale (0.5\u20131.5), or pointerEnabled. Changes revert on release.
1306
+ User preferences (privacy mode, bubbles hidden, drag, pause, hide) always win.`;
1307
+ var STARLITE_MCP_TOOLS = [
1308
+ {
1309
+ name: "starlite_inspect",
1310
+ description: "Inspect StarLite availability, the current model's exact animation names, preferences and session ownership. Read before acquiring or choosing animations.",
1311
+ inputSchema: {
1312
+ type: "object",
1313
+ properties: {},
1314
+ required: [],
1315
+ additionalProperties: false
1316
+ }
1317
+ },
1318
+ {
1319
+ name: "starlite_control",
1320
+ description: "Acquire, renew or release temporary exclusive control of StarLite for this Agent session. Only use for user-requested character interaction. Release when done.",
1321
+ inputSchema: {
1322
+ type: "object",
1323
+ properties: {
1324
+ action: { type: "string", enum: ["acquire", "renew", "release"] }
1325
+ },
1326
+ required: ["action"],
1327
+ additionalProperties: false
1328
+ }
1329
+ },
1330
+ {
1331
+ name: "starlite_perform",
1332
+ description: "During ownership, play one named animation and/or show short plain-text speech atomically. Await actual completion. A new performance replaces the old one. stop:true stops it. Does not override user bubble/privacy settings.",
1333
+ inputSchema: {
1334
+ type: "object",
1335
+ properties: {
1336
+ animation: { type: "string", description: "Exact catalog name (1\u2013160 characters)." },
1337
+ text: { type: "string", description: "Plain text (1\u20131000 characters)." },
1338
+ durationMs: {
1339
+ type: "number",
1340
+ description: "Bubble lifetime: 1000\u201330000 milliseconds; only with text."
1341
+ },
1342
+ stop: { type: "boolean", const: true }
1343
+ },
1344
+ required: [],
1345
+ additionalProperties: false
1346
+ }
1347
+ },
1348
+ {
1349
+ name: "starlite_stage",
1350
+ description: "During ownership, temporarily position or resize the character on its current monitor, or adjust cursor following. All changes revert on release; no OS control.",
1351
+ inputSchema: {
1352
+ type: "object",
1353
+ properties: {
1354
+ position: {
1355
+ type: "object",
1356
+ description: "Normalized current-monitor position; both axes must be between 0 and 1.",
1357
+ properties: { x: { type: "number" }, y: { type: "number" } },
1358
+ required: ["x", "y"],
1359
+ additionalProperties: false
1360
+ },
1361
+ scale: { type: "number", description: "Temporary model scale: 0.5\u20131.5." },
1362
+ pointerEnabled: { type: "boolean" }
1363
+ },
1364
+ required: [],
1365
+ additionalProperties: false
1366
+ }
1367
+ }
1368
+ ];
1369
+ var CODEX_ACTIVITY_TOOL = {
1370
+ name: "starlite_activity",
1371
+ description: "Lifecycle hook callback for automatic Codex work bubbles. Invoked by the host; omit from conversational tool calls.",
1372
+ inputSchema: {
1373
+ type: "object",
1374
+ properties: {
1375
+ event: { type: "string", enum: codexActivityEvents },
1376
+ session: { type: "string", minLength: 1, maxLength: 128 },
1377
+ tool: { type: "string", maxLength: 256 }
1378
+ },
1379
+ required: ["event", "session"],
1380
+ additionalProperties: false
1381
+ }
1382
+ };
1383
+ var StarLiteMcpHandler = class {
1384
+ sourceId;
1385
+ #client;
1386
+ #agent;
1387
+ #name;
1388
+ #sessionTitle;
1389
+ #autoLaunch;
1390
+ #pid;
1391
+ #windowPid;
1392
+ #codexTitles;
1393
+ #heartbeatTimer;
1394
+ #registering;
1395
+ #registered = false;
1396
+ #closed = false;
1397
+ constructor(client, options) {
1398
+ this.#client = client;
1399
+ this.sourceId = options.sourceId ?? randomUUID2();
1400
+ this.#agent = sanitizeSlug2(options.agent);
1401
+ this.#name = sanitizeBubbleText(options.name ?? defaultAgentDisplayName(this.#agent), 60) || this.#agent;
1402
+ this.#sessionTitle = sanitizeBubbleText(options.sessionTitle ?? this.#name, 120) || this.#name;
1403
+ this.#autoLaunch = options.autoLaunch ?? true;
1404
+ this.#pid = validPid2(options.pid ?? process.pid);
1405
+ this.#windowPid = validPid2(options.windowPid ?? process.ppid);
1406
+ this.#codexTitles = this.#agent === "codex" ? new CodexTitleIndex(options.codexHome) : void 0;
1407
+ }
1408
+ async start() {
1409
+ if (this.#closed) return;
1410
+ await this.#register(this.#autoLaunch);
1411
+ if (this.#closed || this.#heartbeatTimer) return;
1412
+ this.#heartbeatTimer = setInterval(() => {
1413
+ void this.#tickHeartbeat();
1414
+ }, HEARTBEAT_INTERVAL_MS);
1415
+ this.#heartbeatTimer.unref();
1416
+ }
1417
+ async stop() {
1418
+ if (this.#closed) return;
1419
+ this.#closed = true;
1420
+ if (this.#heartbeatTimer) {
1421
+ clearInterval(this.#heartbeatTimer);
1422
+ this.#heartbeatTimer = void 0;
1423
+ }
1424
+ if (this.#registered) {
1425
+ this.#registered = false;
1426
+ await this.#client.unregisterSource(this.sourceId).catch(() => void 0);
1427
+ }
1428
+ }
1429
+ async handleMessage(raw) {
1430
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
1431
+ return jsonRpcError(null, -32600, "Invalid Request");
1432
+ }
1433
+ const request = raw;
1434
+ const hasId = request.id !== void 0 && request.id !== null;
1435
+ const id = hasId ? request.id : null;
1436
+ if (request.jsonrpc !== "2.0" || typeof request.method !== "string") {
1437
+ return hasId ? jsonRpcError(id, -32600, "Invalid Request") : void 0;
1438
+ }
1439
+ switch (request.method) {
1440
+ case "initialize": {
1441
+ const params = asRecord2(request.params);
1442
+ const requested = typeof params?.protocolVersion === "string" ? params.protocolVersion : "";
1443
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.has(requested) ? requested : "2024-11-05";
1444
+ return jsonRpcResult(id, {
1445
+ protocolVersion,
1446
+ capabilities: { tools: {} },
1447
+ serverInfo: { name: "starlite", version: SERVER_VERSION },
1448
+ instructions: MCP_INSTRUCTIONS
1449
+ });
1450
+ }
1451
+ case "notifications/initialized":
1452
+ case "notifications/cancelled":
1453
+ return void 0;
1454
+ case "ping":
1455
+ return jsonRpcResult(id, {});
1456
+ case "tools/list": {
1457
+ const tools = this.#agent === "codex" ? [...STARLITE_MCP_TOOLS, CODEX_ACTIVITY_TOOL] : STARLITE_MCP_TOOLS;
1458
+ return jsonRpcResult(id, { tools });
1459
+ }
1460
+ case "tools/call": {
1461
+ const params = asRecord2(request.params);
1462
+ const name = typeof params?.name === "string" ? params.name : "";
1463
+ const args = asRecord2(params?.arguments) ?? {};
1464
+ const outcome = await this.#callTool(name, args);
1465
+ return jsonRpcResult(id, {
1466
+ content: [{ type: "text", text: JSON.stringify(outcome.payload) }],
1467
+ ...outcome.isError ? { isError: true } : {}
1468
+ });
1469
+ }
1470
+ default:
1471
+ return hasId ? jsonRpcError(id, -32601, `Method not found: ${request.method}`) : void 0;
1472
+ }
1473
+ }
1474
+ async #callTool(name, args) {
1475
+ if (name === CODEX_ACTIVITY_TOOL.name && this.#agent === "codex") {
1476
+ return this.#reportCodexActivity(args);
1477
+ }
1478
+ if (!this.#registered) {
1479
+ await this.#register(this.#autoLaunch);
1480
+ }
1481
+ if (name === "starlite_inspect") {
1482
+ if (Object.keys(args).length > 0) {
1483
+ return { payload: { status: "rejected", reason: "invalid-arguments" }, isError: true };
1484
+ }
1485
+ const result = await this.#client.controlInspect(this.sourceId);
1486
+ if (!result) {
1487
+ return {
1488
+ payload: {
1489
+ enabled: false,
1490
+ available: false,
1491
+ controlledBySelf: false,
1492
+ busy: false,
1493
+ reason: "unavailable"
1494
+ }
1495
+ };
1496
+ }
1497
+ return { payload: result };
1498
+ }
1499
+ if (name === "starlite_control") {
1500
+ const action = args.action;
1501
+ if (Object.keys(args).some((k) => k !== "action") || action !== "acquire" && action !== "renew" && action !== "release") {
1502
+ return { payload: { status: "rejected", reason: "invalid-arguments" }, isError: true };
1503
+ }
1504
+ const result = await this.#client.controlCommand({
1505
+ sourceId: this.sourceId,
1506
+ sessionTitle: this.#sessionTitle,
1507
+ action
1508
+ });
1509
+ return { payload: result ?? { status: "rejected", reason: "unavailable" } };
1510
+ }
1511
+ if (name === "starlite_perform") {
1512
+ let perform;
1513
+ try {
1514
+ perform = parseControlPerform(args);
1515
+ } catch {
1516
+ return { payload: { status: "rejected", reason: "invalid-arguments" }, isError: true };
1517
+ }
1518
+ const result = await this.#client.controlCommand({
1519
+ sourceId: this.sourceId,
1520
+ sessionTitle: this.#sessionTitle,
1521
+ action: "perform",
1522
+ perform
1523
+ });
1524
+ return { payload: result ?? { status: "rejected", reason: "unavailable" } };
1525
+ }
1526
+ if (name === "starlite_stage") {
1527
+ let stage;
1528
+ try {
1529
+ stage = parseControlStage(args);
1530
+ } catch {
1531
+ return { payload: { status: "rejected", reason: "invalid-arguments" }, isError: true };
1532
+ }
1533
+ const result = await this.#client.controlCommand({
1534
+ sourceId: this.sourceId,
1535
+ sessionTitle: this.#sessionTitle,
1536
+ action: "stage",
1537
+ stage
1538
+ });
1539
+ return { payload: result ?? { status: "rejected", reason: "unavailable" } };
1540
+ }
1541
+ return { payload: { status: "rejected", reason: "unknown-tool" }, isError: true };
1542
+ }
1543
+ async #reportCodexActivity(args) {
1544
+ const event = codexActivityEvents.find((value) => value === args.event);
1545
+ if (!event || typeof args.session !== "string" || !/^[\w.-]{1,128}$/u.test(args.session) || Object.keys(args).some((key) => !["event", "session", "tool"].includes(key)) || args.tool !== void 0 && (event !== "PreToolUse" || typeof args.tool !== "string" || args.tool.length > 256)) {
1546
+ return { payload: { status: "rejected", reason: "invalid-arguments" }, isError: true };
1547
+ }
1548
+ const threadTitle = await this.#codexTitles?.lookup(args.session);
1549
+ const update = normalizeHookEvent(
1550
+ {
1551
+ agent: this.#agent,
1552
+ name: this.#name,
1553
+ event,
1554
+ ...threadTitle ? { title: threadTitle } : {}
1555
+ },
1556
+ { session_id: args.session, tool_name: args.tool }
1557
+ );
1558
+ if (update.shouldUnregister) {
1559
+ await this.#client.unregisterSource(update.sourceId);
1560
+ } else {
1561
+ await this.#client.sendEvent({
1562
+ sourceId: update.sourceId,
1563
+ agent: update.agent,
1564
+ name: update.name,
1565
+ state: update.state,
1566
+ activity: update.activity,
1567
+ persistent: false,
1568
+ ...update.toolName ? { toolName: update.toolName } : {},
1569
+ ...update.sessionTitle ? { sessionTitle: update.sessionTitle } : {},
1570
+ ...this.#pid ? { pid: this.#pid } : {},
1571
+ ...this.#windowPid ? { windowPid: this.#windowPid } : {}
1572
+ });
1573
+ }
1574
+ return { payload: {} };
1575
+ }
1576
+ async #register(autoLaunch) {
1577
+ if (this.#registered || this.#closed) return;
1578
+ if (this.#registering) return this.#registering;
1579
+ const task = this.#client.registerSource(
1580
+ {
1581
+ sourceId: this.sourceId,
1582
+ agent: this.#agent,
1583
+ name: this.#name,
1584
+ persistent: true,
1585
+ ...this.#pid !== void 0 ? { pid: this.#pid } : {},
1586
+ ...this.#windowPid !== void 0 ? { windowPid: this.#windowPid } : {},
1587
+ sessionTitle: this.#sessionTitle
1588
+ },
1589
+ { autoLaunch, waitMs: 8e3 }
1590
+ ).then((ok) => {
1591
+ if (ok) this.#registered = true;
1592
+ }).catch(() => void 0).finally(() => {
1593
+ if (this.#registering === task) this.#registering = void 0;
1594
+ });
1595
+ this.#registering = task;
1596
+ return task;
1597
+ }
1598
+ async #tickHeartbeat() {
1599
+ if (this.#closed) return;
1600
+ if (!this.#registered) {
1601
+ await this.#register(false);
1602
+ return;
1603
+ }
1604
+ const ok = await this.#client.heartbeat(this.sourceId).catch(() => false);
1605
+ if (!ok) {
1606
+ this.#registered = false;
1607
+ await this.#register(false);
1608
+ }
1609
+ }
1610
+ };
1611
+ async function runMcpStdio(client, options, input = process.stdin, output = process.stdout) {
1612
+ const handler = new StarLiteMcpHandler(client, options);
1613
+ const startup = handler.start().catch(() => void 0);
1614
+ const rl = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
1615
+ let chain = Promise.resolve();
1616
+ const write = (message) => {
1617
+ output.write(`${JSON.stringify(message)}
1618
+ `);
1619
+ };
1620
+ const closePromise = new Promise((resolve2) => {
1621
+ const onDone = () => resolve2();
1622
+ rl.once("close", onDone);
1623
+ process.once("SIGINT", onDone);
1624
+ process.once("SIGTERM", onDone);
1625
+ });
1626
+ rl.on("line", (line) => {
1627
+ const trimmed = line.trim();
1628
+ if (!trimmed) return;
1629
+ chain = chain.then(async () => {
1630
+ let parsed;
1631
+ try {
1632
+ parsed = JSON.parse(trimmed);
1633
+ } catch {
1634
+ write(jsonRpcError(null, -32700, "Parse error"));
1635
+ return;
1636
+ }
1637
+ const response = await handler.handleMessage(parsed);
1638
+ if (response) write(response);
1639
+ });
1640
+ });
1641
+ await closePromise;
1642
+ rl.close();
1643
+ await Promise.allSettled([startup, chain]);
1644
+ await handler.stop();
1645
+ }
1646
+ function jsonRpcResult(id, result) {
1647
+ return { jsonrpc: "2.0", id, result };
1648
+ }
1649
+ function jsonRpcError(id, code, message) {
1650
+ return { jsonrpc: "2.0", id, error: { code, message } };
1651
+ }
1652
+ function asRecord2(value) {
1653
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1654
+ }
1655
+ function sanitizeSlug2(raw) {
1656
+ const cleaned = raw.trim().toLowerCase().replace(/[^a-z0-9_-]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 32);
1657
+ return cleaned || "agent";
1658
+ }
1659
+ function validPid2(pid) {
1660
+ return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 && pid <= 2147483647 ? pid : void 0;
1661
+ }
1662
+
1663
+ // ../agent-bridge/src/snippets.ts
1664
+ function antigravityMcpConfig(options) {
1665
+ const args = [options.cliPath, "mcp", "--agent", "antigravity"];
1666
+ if (options.executablePath) args.push("--exe", options.executablePath);
1667
+ return {
1668
+ mcpServers: {
1669
+ starlite: {
1670
+ command: options.nodePath ?? "node",
1671
+ args
1672
+ }
1673
+ }
1674
+ };
1675
+ }
1676
+ function antigravityHooksConfig(options) {
1677
+ const quoteIfNeeded = (value) => /\s/u.test(value) ? `"${value.replace(/"/gu, '\\"')}"` : value;
1678
+ const nodeBin = options.nodePath && !/\s/u.test(options.nodePath) ? options.nodePath : "node";
1679
+ const exeFlag = options.executablePath ? ` --exe ${quoteIfNeeded(options.executablePath)}` : "";
1680
+ const cmd = `${nodeBin} ${quoteIfNeeded(options.cliPath)} hook --agent antigravity${exeFlag}`;
1681
+ return {
1682
+ starlite: {
1683
+ SessionStart: [{ type: "command", command: cmd, timeout: 5 }],
1684
+ PreInvocation: [{ type: "command", command: cmd, timeout: 5 }],
1685
+ PostToolUse: [{ matcher: "*", hooks: [{ type: "command", command: cmd, timeout: 5 }] }],
1686
+ PostInvocation: [{ type: "command", command: cmd, timeout: 5 }],
1687
+ Stop: [{ type: "command", command: cmd, timeout: 5 }]
1688
+ }
1689
+ };
1690
+ }
1691
+ function codexConfigTomlSnippet(options) {
1692
+ const node = escapeTomlString(options.nodePath ?? "node");
1693
+ const cli = escapeTomlString(options.cliPath);
1694
+ const args = [`"${cli}"`, `"mcp"`, `"--agent"`, `"codex"`];
1695
+ if (options.executablePath) {
1696
+ args.push(`"--exe"`, `"${escapeTomlString(options.executablePath)}"`);
1697
+ }
1698
+ return [
1699
+ "# Add to ~/.codex/config.toml (preserves existing notify / plugins)",
1700
+ "[mcp_servers.starlite]",
1701
+ `command = "${node}"`,
1702
+ `args = [${args.join(", ")}]`
1703
+ ].join("\n");
1704
+ }
1705
+ function agentSetupPrompt(agent, options) {
1706
+ if (agent === "antigravity") {
1707
+ return [
1708
+ "\u8BF7\u5E2E\u6211\u63A5\u5165 StarLite \u684C\u9762\u89D2\u8272\u63D2\u4EF6\uFF08\u4EC5\u4FEE\u6539 Antigravity \u914D\u7F6E\uFF0C\u4E0D\u8986\u76D6\u6211\u5DF2\u6709\u914D\u7F6E\uFF09\uFF1A",
1709
+ "1. \u5728 `~/.gemini/config/mcp_config.json` \u7684 `mcpServers` \u4E2D\u5408\u5E76\u4EE5\u4E0B `starlite` \u9879\uFF1A",
1710
+ "```json",
1711
+ JSON.stringify(antigravityMcpConfig(options), null, 2),
1712
+ "```",
1713
+ "2. \u5728 `~/.gemini/config/hooks.json` \u4E2D\u5408\u5E76\u4EE5\u4E0B\u53EA\u8BFB\u72B6\u6001\u94A9\u5B50\uFF08\u4E0D\u6CE8\u518C PreToolUse\uFF0C\u4E0D\u5F71\u54CD\u5DE5\u5177\u6743\u9650\u5BA1\u6279\uFF09\uFF1A",
1714
+ "```json",
1715
+ JSON.stringify(antigravityHooksConfig(options), null, 2),
1716
+ "```"
1717
+ ].join("\n");
1718
+ }
1719
+ return [
1720
+ "\u8BF7\u5C06 StarLite \u5408\u5E76\u5230 Codex \u914D\u7F6E\u4E2D\uFF0C\u4FDD\u7559\u5DF2\u6709\u8BBE\u7F6E\u548C\u5176\u4ED6\u94A9\u5B50\uFF0C\u907F\u514D\u91CD\u590D\u6CE8\u518C\u3002",
1721
+ "\u5728 `$CODEX_HOME/config.toml` \u914D\u7F6E\u89D2\u8272\u4E92\u52A8\uFF1A",
1722
+ "```toml",
1723
+ codexConfigTomlSnippet(options),
1724
+ "```",
1725
+ "\u5728\u540C\u76EE\u5F55\u7684 hooks.json \u914D\u7F6E\u81EA\u52A8\u5DE5\u4F5C\u6C14\u6CE1\uFF0C\u7136\u540E\u63D0\u9192\u6211\u5728 Codex \u7684 /hooks \u4E2D\u5BA1\u6838 StarLite \u94A9\u5B50\uFF1A",
1726
+ "```json",
1727
+ JSON.stringify(codexHooksConfig(), null, 2),
1728
+ "```"
1729
+ ].join("\n");
1730
+ }
1731
+ function codexHooksConfig() {
1732
+ return {
1733
+ hooks: Object.fromEntries(codexActivityEvents.map((event) => [event, [{
1734
+ hooks: [{
1735
+ type: "mcp_tool",
1736
+ server: "starlite",
1737
+ tool: "starlite_activity",
1738
+ input: {
1739
+ event,
1740
+ session: "${session_id}",
1741
+ ...event === "PreToolUse" ? { tool: "${tool_name}" } : {}
1742
+ },
1743
+ timeout: 2
1744
+ }]
1745
+ }]]))
1746
+ };
1747
+ }
1748
+ function escapeTomlString(value) {
1749
+ return value.replace(/\\/gu, "\\\\").replace(/"/gu, '\\"');
1750
+ }
1751
+
1752
+ // ../agent-bridge/src/cli.ts
1753
+ async function main() {
1754
+ const args = process.argv.slice(2);
1755
+ const subcommand = args[0];
1756
+ const flags = parseFlags(args.slice(1));
1757
+ const host = detectCompanionHost();
1758
+ const bundled = host && existsSync(new URL("../assets/windows-x64/manifest.json", import.meta.url));
1759
+ const prepareExecutable = bundled && !flags.exe && !process.env.STARLITE_EXE ? () => prepareWindowsExecutable(host) : void 0;
1760
+ const client = new StarLiteHubClient({
1761
+ ...prepareExecutable ? { prepareExecutable } : {},
1762
+ ...flags.hubFile ? { hubFile: flags.hubFile } : {},
1763
+ ...flags.exe ? { executable: flags.exe } : {}
1764
+ });
1765
+ if (subcommand === "mcp") {
1766
+ await runMcpStdio(client, {
1767
+ agent: flags.agent ?? "agent",
1768
+ ...flags.name ? { name: flags.name } : {},
1769
+ ...flags.title ? { sessionTitle: flags.title } : {},
1770
+ autoLaunch: flags.noLaunch !== true
1771
+ });
1772
+ return;
1773
+ }
1774
+ if (subcommand === "hook") {
1775
+ const rawStdin = await readBoundedStdin(32768);
1776
+ let payload;
1777
+ if (rawStdin.trim()) {
1778
+ try {
1779
+ payload = JSON.parse(rawStdin);
1780
+ } catch {
1781
+ payload = void 0;
1782
+ }
1783
+ }
1784
+ await runHookCommand(
1785
+ client,
1786
+ {
1787
+ agent: flags.agent ?? "agent",
1788
+ ...flags.name ? { name: flags.name } : {},
1789
+ ...flags.event ? { event: flags.event } : {},
1790
+ ...flags.state ? { state: flags.state } : {},
1791
+ ...flags.activity ? { activity: flags.activity } : {},
1792
+ ...flags.tool ? { tool: flags.tool } : {},
1793
+ ...flags.title ? { title: flags.title } : {},
1794
+ ...flags.noLaunch ? { autoLaunch: false } : {}
1795
+ },
1796
+ payload
1797
+ );
1798
+ process.stdout.write("{}\n");
1799
+ return;
1800
+ }
1801
+ if (subcommand === "snippet") {
1802
+ const target = args[1];
1803
+ const cliPath = fileURLToPath2(import.meta.url);
1804
+ const options = {
1805
+ cliPath,
1806
+ nodePath: process.execPath,
1807
+ ...flags.exe ? { executablePath: flags.exe } : {}
1808
+ };
1809
+ if (target === "antigravity") {
1810
+ process.stdout.write(
1811
+ `=== mcp_config.json ===
1812
+ ${JSON.stringify(antigravityMcpConfig(options), null, 2)}
1813
+
1814
+ === hooks.json ===
1815
+ ${JSON.stringify(antigravityHooksConfig(options), null, 2)}
1816
+
1817
+ === Prompt ===
1818
+ ${agentSetupPrompt("antigravity", options)}
1819
+ `
1820
+ );
1821
+ return;
1822
+ }
1823
+ if (target === "codex") {
1824
+ process.stdout.write(
1825
+ `=== config.toml ===
1826
+ ${codexConfigTomlSnippet(options)}
1827
+
1828
+ === hooks.json ===
1829
+ ${JSON.stringify(codexHooksConfig(), null, 2)}
1830
+
1831
+ === Prompt ===
1832
+ ${agentSetupPrompt("codex", options)}
1833
+ `
1834
+ );
1835
+ return;
1836
+ }
1837
+ process.stderr.write("Usage: starlite-bridge snippet <antigravity|codex> [--exe <path>]\n");
1838
+ process.exitCode = 1;
1839
+ return;
1840
+ }
1841
+ if (subcommand === "doctor") {
1842
+ const hubFile = await client.resolveHubFile();
1843
+ const executable = await client.resolveExecutable();
1844
+ const live = await client.discover();
1845
+ process.stdout.write(
1846
+ `${JSON.stringify(
1847
+ {
1848
+ hubReachable: Boolean(live),
1849
+ hubPort: live?.port ?? null,
1850
+ hubFileResolved: Boolean(hubFile),
1851
+ desktopExecutableFound: Boolean(executable || prepareExecutable)
1852
+ },
1853
+ null,
1854
+ 2
1855
+ )}
1856
+ `
1857
+ );
1858
+ return;
1859
+ }
1860
+ process.stderr.write(
1861
+ [
1862
+ "StarLite universal Agent bridge",
1863
+ "Usage:",
1864
+ " starlite-bridge mcp --agent <slug> [--name <label>] [--title <title>] [--exe <path>] [--no-launch]",
1865
+ " starlite-bridge hook --agent <slug> [--event <name>] [--state <state>] [--activity <act>] [--tool <name>] [--exe <path>] [--no-launch]",
1866
+ " starlite-bridge snippet <antigravity|codex> [--exe <path>]",
1867
+ " starlite-bridge doctor"
1868
+ ].join("\n") + "\n"
1869
+ );
1870
+ process.exitCode = 1;
1871
+ }
1872
+ function parseFlags(argv) {
1873
+ const out = {};
1874
+ for (let i = 0; i < argv.length; i += 1) {
1875
+ const arg = argv[i];
1876
+ if (arg === "--no-launch") {
1877
+ out.noLaunch = true;
1878
+ continue;
1879
+ }
1880
+ const next = argv[i + 1];
1881
+ if (!next || next.startsWith("--")) continue;
1882
+ if (arg === "--agent") {
1883
+ out.agent = next;
1884
+ i += 1;
1885
+ } else if (arg === "--name") {
1886
+ out.name = next;
1887
+ i += 1;
1888
+ } else if (arg === "--title") {
1889
+ out.title = next;
1890
+ i += 1;
1891
+ } else if (arg === "--event") {
1892
+ out.event = next;
1893
+ i += 1;
1894
+ } else if (arg === "--state") {
1895
+ out.state = next;
1896
+ i += 1;
1897
+ } else if (arg === "--activity") {
1898
+ out.activity = next;
1899
+ i += 1;
1900
+ } else if (arg === "--tool") {
1901
+ out.tool = next;
1902
+ i += 1;
1903
+ } else if (arg === "--exe") {
1904
+ out.exe = next;
1905
+ i += 1;
1906
+ } else if (arg === "--hub-file") {
1907
+ out.hubFile = next;
1908
+ i += 1;
1909
+ }
1910
+ }
1911
+ return out;
1912
+ }
1913
+ function readBoundedStdin(maxBytes) {
1914
+ if (process.stdin.isTTY) return Promise.resolve("");
1915
+ return new Promise((resolve2) => {
1916
+ const chunks = [];
1917
+ let bytes = 0;
1918
+ let settled = false;
1919
+ const finish = () => {
1920
+ if (settled) return;
1921
+ settled = true;
1922
+ clearTimeout(timer);
1923
+ resolve2(Buffer.concat(chunks).toString("utf8"));
1924
+ };
1925
+ const timer = setTimeout(finish, 400);
1926
+ timer.unref();
1927
+ process.stdin.on("data", (chunk) => {
1928
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1929
+ if (bytes + buf.length > maxBytes) {
1930
+ finish();
1931
+ return;
1932
+ }
1933
+ bytes += buf.length;
1934
+ chunks.push(buf);
1935
+ });
1936
+ process.stdin.once("end", finish);
1937
+ process.stdin.once("error", finish);
1938
+ });
1939
+ }
1940
+ void main().catch(() => {
1941
+ if (process.argv[2] === "hook") {
1942
+ process.stdout.write("{}\n");
1943
+ process.exitCode = 0;
1944
+ } else {
1945
+ process.exitCode = 1;
1946
+ }
1947
+ });