dsh-agentic-pet 0.0.0-stage → 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/README.i18n.yaml +4 -0
- package/README.md +49 -2
- package/README.zh.md +50 -0
- package/carrier/dist-renderer/assets/index-BHG2MI7t.css +1 -0
- package/carrier/dist-renderer/assets/index-C61Q_dyJ.js +1 -0
- package/carrier/dist-renderer/index.html +19 -0
- package/carrier/lib/host-child.js +49 -0
- package/carrier/lib/main.js +1038 -0
- package/carrier/lib/preload.js +63 -0
- package/carrier/package.json +8 -0
- package/client/pet-settings.js +261 -0
- package/cordis.patch.yml +11 -0
- package/lib/index.js +589 -0
- package/lib/service-Vj-lLpIv.js +6258 -0
- package/lib/tools.js +41 -0
- package/lib/types/actions.d.ts +42 -0
- package/lib/types/driver.d.ts +57 -0
- package/lib/types/index.d.ts +64 -0
- package/lib/types/inner-voice.d.ts +103 -0
- package/lib/types/registry.d.ts +54 -0
- package/lib/types/service.d.ts +159 -0
- package/lib/types/settings-page.d.ts +22 -0
- package/lib/types/tools.d.ts +29 -0
- package/package.json +58 -3
- package/presets/pet-inner-voice.patch.yml +53 -0
- package/presets/pet.patch.yml +142 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
import { i as installPetDriver, n as installPetService } from "./service-Vj-lLpIv.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { dirname, extname, join, normalize, resolve, sep } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
//#region lib/types/settings-page.js
|
|
11
|
+
/**
|
|
12
|
+
* The settings page's host half: local HTTP routes backing the desktop
|
|
13
|
+
* sidebar "桌宠" page (the client half lives in ./client/pet-settings.js and
|
|
14
|
+
* registers through the web GUI's slot system, per the dsh-qqbot precedent).
|
|
15
|
+
* Settings persist in their own JSON file in the dsh home — the platform
|
|
16
|
+
* settings service derives namespaces from profile entry config schemas,
|
|
17
|
+
* which this bundle does not declare; a file keeps the surface honest.
|
|
18
|
+
* Routes use the raw handler form (resource routes postdate rc.3) behind a
|
|
19
|
+
* same-origin loopback fence, one registration per path with internal method
|
|
20
|
+
* dispatch — the webserver throws on duplicate path registration.
|
|
21
|
+
* @module dsh-agentic-pet/settings-page
|
|
22
|
+
*/
|
|
23
|
+
const DEFAULT_SETTINGS = {
|
|
24
|
+
proactivity: {
|
|
25
|
+
enabled: false,
|
|
26
|
+
cooldownMinutes: 10,
|
|
27
|
+
idleThresholdMinutes: 5,
|
|
28
|
+
idleAnimation: true,
|
|
29
|
+
idleAnimationGapMinutes: 10
|
|
30
|
+
},
|
|
31
|
+
innerVoice: {
|
|
32
|
+
enabled: true,
|
|
33
|
+
preset: "pet-inner-voice",
|
|
34
|
+
wakeIntervalMinutes: 2,
|
|
35
|
+
speakProbability: .5,
|
|
36
|
+
touchReplyProbability: .3,
|
|
37
|
+
touchReplyCooldownSeconds: 30,
|
|
38
|
+
boundSessions: {}
|
|
39
|
+
},
|
|
40
|
+
debug: { cdp: false }
|
|
41
|
+
};
|
|
42
|
+
/** The touch ledger the driver owns; reset writes the driver's empty shape. */
|
|
43
|
+
const EMPTY_LEDGER = {
|
|
44
|
+
affection: 0,
|
|
45
|
+
total: 0,
|
|
46
|
+
byPart: {},
|
|
47
|
+
recent: []
|
|
48
|
+
};
|
|
49
|
+
/** Same-origin loopback fence (dsh-qqbot precedent): local host only, no
|
|
50
|
+
* cross-site fetches, and an Origin header — when present — must be this
|
|
51
|
+
* server's own host. */
|
|
52
|
+
function isTrusted(req) {
|
|
53
|
+
const host = req.headers.host;
|
|
54
|
+
if (typeof host !== "string") return false;
|
|
55
|
+
let hostname;
|
|
56
|
+
try {
|
|
57
|
+
hostname = new URL(`http://${host}`).hostname;
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
if (!/^(\[::1\]|localhost|127(\.\d{1,3}){3})$/.test(hostname)) return false;
|
|
62
|
+
if (req.headers["sec-fetch-site"] === "cross-site") return false;
|
|
63
|
+
const origin = req.headers.origin;
|
|
64
|
+
if (origin === void 0) return true;
|
|
65
|
+
try {
|
|
66
|
+
return new URL(origin).host === host;
|
|
67
|
+
} catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function writeJson(res, status, body) {
|
|
72
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
73
|
+
res.end(JSON.stringify(body));
|
|
74
|
+
}
|
|
75
|
+
async function readJsonBody(req) {
|
|
76
|
+
const chunks = [];
|
|
77
|
+
let size = 0;
|
|
78
|
+
for await (const chunk of req) {
|
|
79
|
+
size += chunk.length;
|
|
80
|
+
if (size > 1024 * 1024) return void 0;
|
|
81
|
+
chunks.push(chunk);
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
85
|
+
return typeof parsed === "object" && parsed !== null ? parsed : void 0;
|
|
86
|
+
} catch {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Clamp a number into [min, max]; undefined passthrough for absent input. */
|
|
91
|
+
function clampNumber(value, min, max) {
|
|
92
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
|
|
93
|
+
return Math.min(max, Math.max(min, Math.round(value)));
|
|
94
|
+
}
|
|
95
|
+
/** Merge a patch into the settings, accepting only the known keys. */
|
|
96
|
+
function mergeSettings(current, patch) {
|
|
97
|
+
const proactivity = {
|
|
98
|
+
...DEFAULT_SETTINGS.proactivity,
|
|
99
|
+
...current.proactivity
|
|
100
|
+
};
|
|
101
|
+
const innerVoice = {
|
|
102
|
+
...DEFAULT_SETTINGS.innerVoice,
|
|
103
|
+
...current.innerVoice
|
|
104
|
+
};
|
|
105
|
+
const debug = {
|
|
106
|
+
...DEFAULT_SETTINGS.debug,
|
|
107
|
+
...current.debug
|
|
108
|
+
};
|
|
109
|
+
const patchProactivity = patch.proactivity;
|
|
110
|
+
if (typeof patchProactivity === "object" && patchProactivity !== null) {
|
|
111
|
+
const p = patchProactivity;
|
|
112
|
+
if (typeof p.enabled === "boolean") proactivity.enabled = p.enabled;
|
|
113
|
+
const cooldown = clampNumber(p.cooldownMinutes, 1, 240);
|
|
114
|
+
if (cooldown !== void 0) proactivity.cooldownMinutes = cooldown;
|
|
115
|
+
const idle = clampNumber(p.idleThresholdMinutes, 1, 240);
|
|
116
|
+
if (idle !== void 0) proactivity.idleThresholdMinutes = idle;
|
|
117
|
+
if (typeof p.idleAnimation === "boolean") proactivity.idleAnimation = p.idleAnimation;
|
|
118
|
+
const gap = clampNumber(p.idleAnimationGapMinutes, 1, 120);
|
|
119
|
+
if (gap !== void 0) proactivity.idleAnimationGapMinutes = gap;
|
|
120
|
+
}
|
|
121
|
+
const patchInnerVoice = patch.innerVoice;
|
|
122
|
+
if (typeof patchInnerVoice === "object" && patchInnerVoice !== null) {
|
|
123
|
+
const v = patchInnerVoice;
|
|
124
|
+
if (typeof v.enabled === "boolean") innerVoice.enabled = v.enabled;
|
|
125
|
+
if (typeof v.preset === "string" && v.preset !== "") innerVoice.preset = v.preset;
|
|
126
|
+
const wake = clampNumber(v.wakeIntervalMinutes, 1, 60);
|
|
127
|
+
if (wake !== void 0) innerVoice.wakeIntervalMinutes = wake;
|
|
128
|
+
if (typeof v.speakProbability === "number" && Number.isFinite(v.speakProbability)) innerVoice.speakProbability = Math.min(1, Math.max(0, v.speakProbability));
|
|
129
|
+
if (typeof v.touchReplyProbability === "number" && Number.isFinite(v.touchReplyProbability)) innerVoice.touchReplyProbability = Math.min(1, Math.max(0, v.touchReplyProbability));
|
|
130
|
+
const replyCooldown = clampNumber(v.touchReplyCooldownSeconds, 0, 600);
|
|
131
|
+
if (replyCooldown !== void 0) innerVoice.touchReplyCooldownSeconds = replyCooldown;
|
|
132
|
+
const bound = v.boundSessions;
|
|
133
|
+
if (typeof bound === "object" && bound !== null) {
|
|
134
|
+
const record = {};
|
|
135
|
+
for (const [petId, sessionId] of Object.entries(bound)) if (petId !== "" && typeof sessionId === "string" && sessionId !== "") record[petId] = sessionId;
|
|
136
|
+
innerVoice.boundSessions = record;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const patchDebug = patch.debug;
|
|
140
|
+
if (typeof patchDebug === "object" && patchDebug !== null) {
|
|
141
|
+
const d = patchDebug;
|
|
142
|
+
if (typeof d.cdp === "boolean") debug.cdp = d.cdp;
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
...current,
|
|
146
|
+
proactivity,
|
|
147
|
+
innerVoice,
|
|
148
|
+
debug
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function openPathInFileManager(path) {
|
|
152
|
+
if (process.platform === "win32") {
|
|
153
|
+
spawn("explorer.exe", [path], {
|
|
154
|
+
detached: true,
|
|
155
|
+
stdio: "ignore"
|
|
156
|
+
}).unref();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
spawn(process.platform === "darwin" ? "open" : "xdg-open", [path], {
|
|
160
|
+
detached: true,
|
|
161
|
+
stdio: "ignore"
|
|
162
|
+
}).unref();
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Register the settings page's routes. One registration per exact path with
|
|
166
|
+
* internal method dispatch; every handler runs behind the fence.
|
|
167
|
+
* @param ctx - plugin context inside the runtime.
|
|
168
|
+
* @param home - the dsh home holding the settings/ledger/manifest files.
|
|
169
|
+
*/
|
|
170
|
+
function installSettingsPage(ctx, home, pet) {
|
|
171
|
+
const settingsPath = join(home, "pet-settings.json");
|
|
172
|
+
const ledgerPath = join(home, "pet-affection.json");
|
|
173
|
+
const windowPath = join(home, "pet-window.json");
|
|
174
|
+
/** Summarize EVERY live pet (id, online flag, normalized /status). */
|
|
175
|
+
const petStatus = async () => {
|
|
176
|
+
return { pets: (await Promise.all((await pet.list()).map((entry) => pet.snapshot(entry)))).map(({ id, online, ...rest }) => ({
|
|
177
|
+
id,
|
|
178
|
+
online,
|
|
179
|
+
...rest
|
|
180
|
+
})) };
|
|
181
|
+
};
|
|
182
|
+
const readSettings = async () => {
|
|
183
|
+
try {
|
|
184
|
+
return mergeSettings(JSON.parse(await readFile(settingsPath, "utf8")), {});
|
|
185
|
+
} catch {
|
|
186
|
+
return mergeSettings({}, {});
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
const routeByPath = /* @__PURE__ */ new Map();
|
|
190
|
+
const route = (method, path, handler) => {
|
|
191
|
+
let handlers = routeByPath.get(path);
|
|
192
|
+
if (handlers === void 0) {
|
|
193
|
+
handlers = /* @__PURE__ */ new Map();
|
|
194
|
+
routeByPath.set(path, handlers);
|
|
195
|
+
ctx.effect(() => ctx.webServer.register({
|
|
196
|
+
kind: "exact",
|
|
197
|
+
path,
|
|
198
|
+
handler: async (req, res) => {
|
|
199
|
+
const httpReq = req;
|
|
200
|
+
const httpRes = res;
|
|
201
|
+
if (!isTrusted(httpReq)) {
|
|
202
|
+
writeJson(httpRes, 403, { error: "refused: same-origin loopback only" });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const registered = handlers?.get(String(httpReq.method ?? "").toUpperCase());
|
|
206
|
+
if (registered === void 0) {
|
|
207
|
+
writeJson(httpRes, 405, { error: "method not allowed" });
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
await registered(httpReq, httpRes);
|
|
212
|
+
} catch (error) {
|
|
213
|
+
writeJson(httpRes, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}), `pet-surface: settings ${path}`);
|
|
217
|
+
}
|
|
218
|
+
handlers.set(method, handler);
|
|
219
|
+
};
|
|
220
|
+
route("GET", "/api/pet-settings/read", async (_req, res) => {
|
|
221
|
+
const [settings, windowPosition, status] = await Promise.all([
|
|
222
|
+
readSettings(),
|
|
223
|
+
readFile(windowPath, "utf8").then((raw) => JSON.parse(raw), () => null),
|
|
224
|
+
petStatus()
|
|
225
|
+
]);
|
|
226
|
+
const affection = {};
|
|
227
|
+
const legacyBook = await readFile(ledgerPath, "utf8").then((raw) => JSON.parse(raw), () => null);
|
|
228
|
+
const bookIds = new Set(status.pets.map((pet) => String(pet.id)));
|
|
229
|
+
bookIds.add("electron");
|
|
230
|
+
for (const id of bookIds) {
|
|
231
|
+
const book = await readFile(id === "electron" && legacyBook !== null ? ledgerPath : join(home, "pet-affection.d", `${id}.json`), "utf8").then((raw) => JSON.parse(raw), () => null);
|
|
232
|
+
if (book !== null) affection[id] = book;
|
|
233
|
+
}
|
|
234
|
+
writeJson(res, 200, {
|
|
235
|
+
settings,
|
|
236
|
+
affection,
|
|
237
|
+
windowPosition,
|
|
238
|
+
pets: status.pets
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
route("POST", "/api/pet-settings/update", async (req, res) => {
|
|
242
|
+
const body = await readJsonBody(req);
|
|
243
|
+
const patch = body === void 0 ? void 0 : body.patch;
|
|
244
|
+
if (typeof patch !== "object" || patch === null) {
|
|
245
|
+
writeJson(res, 400, { error: "body must be {patch:{...}}" });
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const next = mergeSettings(await readSettings(), patch);
|
|
249
|
+
await writeFile(settingsPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
|
|
250
|
+
ctx.emit("pet-settings/changed");
|
|
251
|
+
writeJson(res, 200, {
|
|
252
|
+
ok: true,
|
|
253
|
+
settings: next
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
route("POST", "/api/pet-settings/reset-affection", async (_req, res) => {
|
|
257
|
+
await writeFile(ledgerPath, `${JSON.stringify(EMPTY_LEDGER)}\n`, "utf8");
|
|
258
|
+
writeJson(res, 200, {
|
|
259
|
+
ok: true,
|
|
260
|
+
affection: EMPTY_LEDGER
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
route("POST", "/api/pet-settings/reset-position", async (_req, res) => {
|
|
264
|
+
if (existsSync(windowPath)) await unlink(windowPath);
|
|
265
|
+
writeJson(res, 200, { ok: true });
|
|
266
|
+
});
|
|
267
|
+
route("POST", "/api/pet-settings/open-logs", async (_req, res) => {
|
|
268
|
+
const logsDir = join(home, "logs");
|
|
269
|
+
const target = existsSync(logsDir) ? logsDir : home;
|
|
270
|
+
openPathInFileManager(target);
|
|
271
|
+
writeJson(res, 200, {
|
|
272
|
+
ok: true,
|
|
273
|
+
opened: target
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region lib/types/index.js
|
|
279
|
+
/**
|
|
280
|
+
* dsh-agentic-pet — the pet-surface bundle's runtime glue plugin plus
|
|
281
|
+
* the bundle patch (`cordis.patch.yml`, declared by the `dsh.bundle.patch`
|
|
282
|
+
* manifest field). The plugin owns the pet-surface glue: it resolves the built
|
|
283
|
+
* pet renderer dist (workspace knowledge of this bundle, never user config)
|
|
284
|
+
* and registers the `/pet` prefix route over the web composition, serving the
|
|
285
|
+
* desktop pet's page through Connection's browser authentication — the same
|
|
286
|
+
* token/cookie chain the Web GUI uses, so the desktop pet attaches to dsh as
|
|
287
|
+
* an authenticated client (`interactions=answer`) rather than a file-bridge
|
|
288
|
+
* observer. The route registers in the raw `handler` form and adapts to Fetch
|
|
289
|
+
* at the edge, because resource-typed routes postdate the installed 0.2.1-rc.3
|
|
290
|
+
* desktop webserver; Connection's authorizeIndex has the same version split
|
|
291
|
+
* and is branched on a webserver capability probe. The dist location follows
|
|
292
|
+
* the `@deepseek-ai/dsh-web-frontend` precedent: anchored on the app package
|
|
293
|
+
* manifest, never configured.
|
|
294
|
+
* @module dsh-agentic-pet
|
|
295
|
+
*/
|
|
296
|
+
/** Stable Cordis plugin name. */
|
|
297
|
+
const name = "pet-surface";
|
|
298
|
+
/**
|
|
299
|
+
* Services required before the `/pet` route can register. `sessionController`
|
|
300
|
+
* is a SIBLING plugin row's service (the api-session-controller row in the
|
|
301
|
+
* same composition): a command-style ctx.get from this row's fiber never sees
|
|
302
|
+
* it (the petTools/petService precedent), while static inject is resolved by
|
|
303
|
+
* the Loader ACROSS rows and waits for that row to mount — the webServer
|
|
304
|
+
* precedent. Every profile mounting this bundle mounts the web-app rows too,
|
|
305
|
+
* so the dependency is always satisfiable.
|
|
306
|
+
*/
|
|
307
|
+
const inject = [
|
|
308
|
+
"webServer",
|
|
309
|
+
"connection",
|
|
310
|
+
"sessionController",
|
|
311
|
+
"workspaceController"
|
|
312
|
+
];
|
|
313
|
+
/** The URL path prefix the pet renderer is served under. No trailing slash. */
|
|
314
|
+
const PET_PATH_PREFIX = "/pet";
|
|
315
|
+
/**
|
|
316
|
+
* Locator file naming this runtime's authenticated root for the pet carrier.
|
|
317
|
+
* The desktop shell keeps its authenticated URL in process memory only, so a
|
|
318
|
+
* bundle inside that runtime is the only component positioned to publish it.
|
|
319
|
+
* The carrier prefers the env override, then this file's freshest live
|
|
320
|
+
* publisher, then falls back to spawning its own profile.
|
|
321
|
+
*/
|
|
322
|
+
function petLocatorPath() {
|
|
323
|
+
return join(process.env.DSH_HOME ?? join(homedir(), ".dsh"), "pet-surface-url.json");
|
|
324
|
+
}
|
|
325
|
+
const HTML_MIME = "text/html; charset=utf-8";
|
|
326
|
+
const MIME = {
|
|
327
|
+
".html": HTML_MIME,
|
|
328
|
+
".js": "text/javascript; charset=utf-8",
|
|
329
|
+
".css": "text/css; charset=utf-8",
|
|
330
|
+
".png": "image/png",
|
|
331
|
+
".svg": "image/svg+xml",
|
|
332
|
+
".webp": "image/webp",
|
|
333
|
+
".ico": "image/x-icon",
|
|
334
|
+
".json": "application/json",
|
|
335
|
+
".map": "application/json",
|
|
336
|
+
".webmanifest": "application/manifest+json",
|
|
337
|
+
".woff2": "font/woff2"
|
|
338
|
+
};
|
|
339
|
+
const STATIC_MISS_CODES = new Set([
|
|
340
|
+
"ENOENT",
|
|
341
|
+
"EISDIR",
|
|
342
|
+
"ENOTDIR"
|
|
343
|
+
]);
|
|
344
|
+
/**
|
|
345
|
+
* Dist location is workspace knowledge of this bundle: anchored on the pet app
|
|
346
|
+
* package manifest, not configured. Existence is a request-time concern — the
|
|
347
|
+
* route reads files per request, so a composition whose pet page is never
|
|
348
|
+
* visited boots without the dist being built.
|
|
349
|
+
*/
|
|
350
|
+
function resolveDistIndex() {
|
|
351
|
+
const require = createRequire(import.meta.url);
|
|
352
|
+
try {
|
|
353
|
+
return join(dirname(require.resolve("@deepseek-ai/dsh-pet/package.json")), "dist-renderer", "index.html");
|
|
354
|
+
} catch {
|
|
355
|
+
const shipped = join(dirname(fileURLToPath(import.meta.url)), "..", "carrier", "dist-renderer", "index.html");
|
|
356
|
+
if (existsSync(shipped)) return shipped;
|
|
357
|
+
throw new Error("pet-app: the pet renderer dist is not resolvable from this composition (neither @deepseek-ai/dsh-pet nor the shipped carrier dist)");
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/** A Response body that is `bytes` itself, without the copy a buffer body gets. */
|
|
361
|
+
function bytesBody(bytes) {
|
|
362
|
+
return new ReadableStream({ start(controller) {
|
|
363
|
+
controller.enqueue(bytes);
|
|
364
|
+
controller.close();
|
|
365
|
+
} });
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Answer one GET or HEAD `/pet` request. The URL path is the full server
|
|
369
|
+
* pathname (`/pet` prefix included); it must be exactly the prefix or stay
|
|
370
|
+
* under it. The index entry (`/pet`, `/pet/`, `/pet/index.html`) passes
|
|
371
|
+
* Connection's browser authentication; every other file is public with a weak
|
|
372
|
+
* ETag and `cache-control: no-cache`, answering a matching `If-None-Match`
|
|
373
|
+
* with 304. Traversal outside the dist root is 403, missing paths are 404, a
|
|
374
|
+
* malformed percent-escape rejects (the adapter answers 400 over HTTP), and
|
|
375
|
+
* non-GET/HEAD is 405. The index serves raw, deliberately NOT through
|
|
376
|
+
* webServer.renderIndex: the web boot injections (opaque boot background,
|
|
377
|
+
* module-system bootstrap) are Web-GUI concerns that would paint the
|
|
378
|
+
* transparent pet window opaque.
|
|
379
|
+
*/
|
|
380
|
+
async function servePetStatic(request, distRoot, distIndex, authorizeIndex) {
|
|
381
|
+
const pathname = decodeURIComponent(new URL(request.url).pathname);
|
|
382
|
+
const target = resolve(normalize(join(distRoot, pathname === "/pet" || pathname === `/pet/` ? "/" : pathname.slice(4))));
|
|
383
|
+
if (target !== distRoot && !target.startsWith(distRoot + sep)) return new Response(null, { status: 403 });
|
|
384
|
+
let body;
|
|
385
|
+
let headers;
|
|
386
|
+
try {
|
|
387
|
+
if (target === distRoot || target === distIndex) {
|
|
388
|
+
const refusal = authorizeIndex();
|
|
389
|
+
if (refusal !== void 0) return refusal;
|
|
390
|
+
body = await readFile(distIndex, "utf8");
|
|
391
|
+
headers = { "content-type": HTML_MIME };
|
|
392
|
+
} else {
|
|
393
|
+
body = await readFile(target);
|
|
394
|
+
const cache = {
|
|
395
|
+
"cache-control": "no-cache",
|
|
396
|
+
etag: `W/"${createHash("sha1").update(body).digest("base64url")}"`
|
|
397
|
+
};
|
|
398
|
+
if (request.headers.get("if-none-match") === cache.etag) return new Response(null, {
|
|
399
|
+
status: 304,
|
|
400
|
+
headers: cache
|
|
401
|
+
});
|
|
402
|
+
headers = {
|
|
403
|
+
"content-type": MIME[extname(target)] ?? "application/octet-stream",
|
|
404
|
+
...cache
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
} catch (error) {
|
|
408
|
+
if (!STATIC_MISS_CODES.has(error.code)) throw error;
|
|
409
|
+
return new Response(null, { status: 404 });
|
|
410
|
+
}
|
|
411
|
+
if (request.method === "HEAD") return new Response(null, {
|
|
412
|
+
status: 200,
|
|
413
|
+
headers
|
|
414
|
+
});
|
|
415
|
+
return new Response(typeof body === "string" ? body : bytesBody(body), {
|
|
416
|
+
status: 200,
|
|
417
|
+
headers
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
/** The environment minus Electron's Node-mode flag, so a spawned GUI child is a GUI child. */
|
|
421
|
+
function stripRunAsNode(env) {
|
|
422
|
+
const clean = { ...env };
|
|
423
|
+
delete clean.ELECTRON_RUN_AS_NODE;
|
|
424
|
+
return clean;
|
|
425
|
+
}
|
|
426
|
+
/** One raw webserver handler request's absolute URL. */
|
|
427
|
+
function absoluteUrl(req) {
|
|
428
|
+
return `http://${req.headers.host ?? "127.0.0.1"}${req.url ?? "/"}`;
|
|
429
|
+
}
|
|
430
|
+
/** Normalize a node header value (string | string[] | undefined) for Fetch. */
|
|
431
|
+
function headerValue(value) {
|
|
432
|
+
return Array.isArray(value) ? value.join(", ") : value;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Register the `/pet` prefix route with a raw handler serving the pet renderer
|
|
436
|
+
* dist, and publish the locator. The handler form predates resource-typed
|
|
437
|
+
* routes, so one code path serves both the installed 0.2.1-rc.3 desktop
|
|
438
|
+
* webserver and current builds; authorizeIndex branches on whether the
|
|
439
|
+
* webserver carries the resource API (`readResource` arrived with it).
|
|
440
|
+
* @param ctx - plugin context carrying the webServer and connection services.
|
|
441
|
+
*/
|
|
442
|
+
function apply(ctx) {
|
|
443
|
+
const distIndex = resolveDistIndex();
|
|
444
|
+
const distRoot = dirname(distIndex);
|
|
445
|
+
const authorizeIndex = ctx.connection;
|
|
446
|
+
const supportsResourceApi = typeof ctx.webServer.readResource === "function";
|
|
447
|
+
const authorizeToResponse = (req) => {
|
|
448
|
+
if (supportsResourceApi) {
|
|
449
|
+
let status = 401;
|
|
450
|
+
let headers = {};
|
|
451
|
+
let body;
|
|
452
|
+
const requestHeaders = {};
|
|
453
|
+
const host = headerValue(req.headers.host);
|
|
454
|
+
if (host !== void 0) requestHeaders.host = host;
|
|
455
|
+
const cookie = headerValue(req.headers.cookie);
|
|
456
|
+
if (cookie !== void 0) requestHeaders.cookie = cookie;
|
|
457
|
+
return authorizeIndex.authorizeIndex(new Request(absoluteUrl(req), { headers: requestHeaders }), {
|
|
458
|
+
writeHead(nextStatus, nextHeaders) {
|
|
459
|
+
status = nextStatus;
|
|
460
|
+
headers = nextHeaders;
|
|
461
|
+
},
|
|
462
|
+
end(text) {
|
|
463
|
+
body = text;
|
|
464
|
+
}
|
|
465
|
+
}) ? void 0 : new Response(body ?? "", {
|
|
466
|
+
status,
|
|
467
|
+
headers
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
let status = 401;
|
|
471
|
+
let headers = {};
|
|
472
|
+
let body;
|
|
473
|
+
return authorizeIndex.authorizeIndex(req, {
|
|
474
|
+
writeHead(nextStatus, nextHeaders) {
|
|
475
|
+
status = nextStatus;
|
|
476
|
+
headers = nextHeaders ?? {};
|
|
477
|
+
},
|
|
478
|
+
setHeader(name, value) {
|
|
479
|
+
headers[name] = String(value);
|
|
480
|
+
},
|
|
481
|
+
end(text) {
|
|
482
|
+
if (text !== void 0) body = String(text);
|
|
483
|
+
}
|
|
484
|
+
}) ? void 0 : new Response(body ?? "", {
|
|
485
|
+
status,
|
|
486
|
+
headers
|
|
487
|
+
});
|
|
488
|
+
};
|
|
489
|
+
ctx.effect(() => ctx.webServer.register({
|
|
490
|
+
kind: "prefix",
|
|
491
|
+
path: PET_PATH_PREFIX,
|
|
492
|
+
handler: async (req, res) => {
|
|
493
|
+
const ifNoneMatch = headerValue(req.headers["if-none-match"]);
|
|
494
|
+
const response = await servePetStatic(new Request(absoluteUrl(req), {
|
|
495
|
+
method: req.method ?? "GET",
|
|
496
|
+
...ifNoneMatch === void 0 ? {} : { headers: { "if-none-match": ifNoneMatch } }
|
|
497
|
+
}), distRoot, distIndex, () => authorizeToResponse(req));
|
|
498
|
+
res.writeHead(response.status, Object.fromEntries(response.headers.entries()));
|
|
499
|
+
if (req.method === "HEAD" || response.body === null) {
|
|
500
|
+
res.end();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
504
|
+
}
|
|
505
|
+
}), "pet-surface: /pet route");
|
|
506
|
+
const authenticatedRoot = () => {
|
|
507
|
+
if (ctx.get("webServer") === void 0 || ctx.get("connection") === void 0) return void 0;
|
|
508
|
+
return ctx.connection.authenticatedUrl(`${ctx.webServer.protocol}//127.0.0.1:${String(ctx.webServer.port)}`);
|
|
509
|
+
};
|
|
510
|
+
const publishLocator = (url) => {
|
|
511
|
+
const record = `${JSON.stringify({
|
|
512
|
+
url,
|
|
513
|
+
since: Date.now(),
|
|
514
|
+
pid: process.pid
|
|
515
|
+
})}\n`;
|
|
516
|
+
mkdir(dirname(petLocatorPath()), { recursive: true }).then(() => writeFile(petLocatorPath(), record, "utf8")).catch((error) => {
|
|
517
|
+
console.error(`pet-surface: could not write the locator file: ${error instanceof Error ? error.message : String(error)}`);
|
|
518
|
+
});
|
|
519
|
+
};
|
|
520
|
+
/**
|
|
521
|
+
* Auto-start the pet window. A bare Electron binary runs any app directory
|
|
522
|
+
* (`electron.exe <dir>`), but a PACKAGED one (the installed desktop) loads
|
|
523
|
+
* its own app and dies on its single-instance lock instead — so the host's
|
|
524
|
+
* `process.execPath` is only a last resort and the resolution order is an
|
|
525
|
+
* explicit env override, a binary staged beside this package, then the
|
|
526
|
+
* `electron` npm dependency (its module resolves to the binary path).
|
|
527
|
+
* The carrier's single-instance lock collapses duplicates.
|
|
528
|
+
*/
|
|
529
|
+
const resolveElectronBinary = () => {
|
|
530
|
+
if (process.env.DSH_PET_ELECTRON !== void 0 && process.env.DSH_PET_ELECTRON !== "") return process.env.DSH_PET_ELECTRON;
|
|
531
|
+
const staged = join(resolve(join(dirname(fileURLToPath(import.meta.url)), "..")), "electron-bin", process.platform === "win32" ? "electron.exe" : process.platform === "darwin" ? join("Electron.app", "Contents", "MacOS", "Electron") : "electron");
|
|
532
|
+
if (existsSync(staged)) return staged;
|
|
533
|
+
try {
|
|
534
|
+
const require = createRequire(import.meta.url);
|
|
535
|
+
const candidate = String(require("electron"));
|
|
536
|
+
if (existsSync(candidate)) return candidate;
|
|
537
|
+
} catch {}
|
|
538
|
+
return process.versions.electron !== void 0 ? process.execPath : void 0;
|
|
539
|
+
};
|
|
540
|
+
const spawnPetCarrier = (url) => {
|
|
541
|
+
const carrierDir = resolve(join(dirname(fileURLToPath(import.meta.url)), "..", "carrier"));
|
|
542
|
+
const electronBinary = resolveElectronBinary();
|
|
543
|
+
if (process.env.DSH_PET_NO_SPAWN === "1" || electronBinary === void 0 || !existsSync(join(carrierDir, "package.json"))) return;
|
|
544
|
+
const child = spawn(electronBinary, [carrierDir], {
|
|
545
|
+
env: {
|
|
546
|
+
...stripRunAsNode(process.env),
|
|
547
|
+
DSH_PET_URL: url,
|
|
548
|
+
DSH_PET_RUNTIME_PID: String(process.pid)
|
|
549
|
+
},
|
|
550
|
+
detached: true,
|
|
551
|
+
stdio: [
|
|
552
|
+
"ignore",
|
|
553
|
+
"pipe",
|
|
554
|
+
"pipe"
|
|
555
|
+
]
|
|
556
|
+
});
|
|
557
|
+
child.stdout?.setEncoding("utf8");
|
|
558
|
+
child.stdout?.on("data", (chunk) => {
|
|
559
|
+
process.stdout.write(`[pet-carrier] ${chunk}`);
|
|
560
|
+
});
|
|
561
|
+
child.stderr?.setEncoding("utf8");
|
|
562
|
+
child.stderr?.on("data", (chunk) => {
|
|
563
|
+
process.stderr.write(`[pet-carrier] ${chunk}`);
|
|
564
|
+
});
|
|
565
|
+
child.unref();
|
|
566
|
+
ctx.effect(() => () => {
|
|
567
|
+
child.kill();
|
|
568
|
+
}, "pet-surface: carrier shutdown");
|
|
569
|
+
};
|
|
570
|
+
const settledReady = () => {
|
|
571
|
+
const url = authenticatedRoot();
|
|
572
|
+
if (url === void 0) return;
|
|
573
|
+
publishLocator(url);
|
|
574
|
+
spawnPetCarrier(url);
|
|
575
|
+
};
|
|
576
|
+
const settled = ctx.get("loader")?.await();
|
|
577
|
+
if (settled === void 0) settledReady();
|
|
578
|
+
else settled.then(settledReady).catch(() => {});
|
|
579
|
+
const pet = installPetService(ctx, dirname(petLocatorPath()));
|
|
580
|
+
installPetDriver(ctx, dirname(petLocatorPath()), pet);
|
|
581
|
+
installSettingsPage(ctx, dirname(petLocatorPath()), pet);
|
|
582
|
+
ctx.effect(() => () => {
|
|
583
|
+
readFile(petLocatorPath(), "utf8").then((raw) => {
|
|
584
|
+
if (JSON.parse(raw).pid === process.pid) return unlink(petLocatorPath());
|
|
585
|
+
}).catch(() => {});
|
|
586
|
+
}, "pet-surface: locator withdrawal");
|
|
587
|
+
}
|
|
588
|
+
//#endregion
|
|
589
|
+
export { PET_PATH_PREFIX, apply, inject, name, petLocatorPath, servePetStatic };
|