@acryldev/launcher-desktop 0.0.0-stage → 0.1.2

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/lib/index.js ADDED
@@ -0,0 +1,1440 @@
1
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { APP_MARKER, APP_NAME, STARTERS, addApp, appNameProblem, blendOf, blendVersionOf, clearGithub, githubClientId, githubEnv, inspectApp, maskKey, modelEnv, pollGithubSignIn, prepareTools, readApps, readGithub, readModelKey, removeApp, setBlendVisibility, startGithubSignIn, toolsEnv, whereProblem } from "@acryldev/launcher";
4
+ import { defineAcrylTool } from "@acryldev/control";
5
+ import { Acryl } from "@acryldev/blends";
6
+ import { error } from "@acryldev/loopback-http";
7
+ import { INVALID_JSON, jsonBody, jsonContent, ownPage, privateApi, readJson } from "@acryldev/loopback-http/router";
8
+ import { spawn, spawnSync } from "node:child_process";
9
+ //#region src/contract.ts
10
+ /** The wire contract of the ACRYL screen's routes (the desktop face of the launcher, spec 050 T012). The screen is the client of these routes. */
11
+ /** Every launcher route lives under this prefix, the one the Host's Web adapter mounts for this plugin. */
12
+ const LAUNCHER_API_PREFIX = "/api/acryl-launcher";
13
+ const LAUNCHER_STATE_PATH = `${LAUNCHER_API_PREFIX}/state`;
14
+ const LAUNCHER_HEALTH_PATH = `${LAUNCHER_API_PREFIX}/health`;
15
+ const LAUNCHER_ADD_PATH = `${LAUNCHER_API_PREFIX}/add`;
16
+ const LAUNCHER_REMOVE_PATH = `${LAUNCHER_API_PREFIX}/remove`;
17
+ const LAUNCHER_NEW_PATH = `${LAUNCHER_API_PREFIX}/new`;
18
+ const LAUNCHER_START_PATH = `${LAUNCHER_API_PREFIX}/start`;
19
+ const LAUNCHER_STOP_PATH = `${LAUNCHER_API_PREFIX}/stop`;
20
+ const LAUNCHER_UPDATE_PATH = `${LAUNCHER_API_PREFIX}/update`;
21
+ /** Open ACRYL ADE (the Blend `acryl.ade` in `<home>/ade`, the folder `acryl ade` uses), made on first use, in a window or the browser. */
22
+ const LAUNCHER_ADE_PATH = `${LAUNCHER_API_PREFIX}/ade`;
23
+ const LAUNCHER_BLENDS_PATH = `${LAUNCHER_API_PREFIX}/blends`;
24
+ const LAUNCHER_ASSISTANT_FOLDER_PATH = `${LAUNCHER_API_PREFIX}/assistant-folder`;
25
+ const LAUNCHER_PLUGINS_PATH = `${LAUNCHER_API_PREFIX}/plugins`;
26
+ const LAUNCHER_PLUGIN_PULL_PATH = `${LAUNCHER_API_PREFIX}/plugin-pull`;
27
+ const LAUNCHER_PUBLISH_PLAN_PATH = `${LAUNCHER_API_PREFIX}/publish-plan`;
28
+ const LAUNCHER_PUBLISH_PATH = `${LAUNCHER_API_PREFIX}/publish`;
29
+ const LAUNCHER_SHARE_PLAN_PATH = `${LAUNCHER_API_PREFIX}/share-plan`;
30
+ const LAUNCHER_SHARE_PATH = `${LAUNCHER_API_PREFIX}/share`;
31
+ const LAUNCHER_GITHUB_PATH = `${LAUNCHER_API_PREFIX}/github`;
32
+ const LAUNCHER_GITHUB_START_PATH = `${LAUNCHER_API_PREFIX}/github-start`;
33
+ const LAUNCHER_GITHUB_POLL_PATH = `${LAUNCHER_API_PREFIX}/github-poll`;
34
+ const LAUNCHER_GITHUB_DISCONNECT_PATH = `${LAUNCHER_API_PREFIX}/github-disconnect`;
35
+ const SURFACES = [
36
+ "web",
37
+ "desktop",
38
+ "tui"
39
+ ];
40
+ /** Surfaces a person can choose for a new app today. */
41
+ const MAKEABLE_SURFACES = ["web", "desktop"];
42
+ /** A Blend id as `acryl new --from` takes it: it starts with a letter or digit, so it can never read as an option. */
43
+ const BLEND_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
44
+ /** A Blend released on GitHub, as `--from` takes it (create-acrylblends `github:owner/repo#ref`): what a community Blend is made from. */
45
+ const BLEND_SOURCE = /^github:[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}(?:#[A-Za-z0-9._/-]{1,100})?$/u;
46
+ /** A plugin name, a GitHub account and a license id as the door takes them: nothing that could read as an option or a path. */
47
+ const PLUGIN_NAME = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
48
+ const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u;
49
+ const LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]{0,39}$/u;
50
+ //#endregion
51
+ //#region src/door.ts
52
+ /**
53
+ * The running app's door, reached the way the app's own `acryl` command reaches it: `<app>/.acryl/door.json` names the loopback address and the secret of the
54
+ * app that is running now. The screen is a person's surface, so it may do what the terminal's prompt does: send a publish the person confirmed. Only
55
+ * loopback addresses are used, and a missing or stale file means the app is not running.
56
+ */
57
+ var DoorUnavailable = class extends Error {};
58
+ const TIMEOUT_MS$1 = 6e4;
59
+ const LOOPBACK = /* @__PURE__ */ new Set([
60
+ "127.0.0.1",
61
+ "localhost",
62
+ "[::1]"
63
+ ]);
64
+ const NOT_RUNNING = "the app is not running: start it from this screen, then try again";
65
+ function readDoorFile(folder, read) {
66
+ let parsed;
67
+ try {
68
+ parsed = JSON.parse(read(join(folder, ".acryl", "door.json")));
69
+ } catch {
70
+ throw new DoorUnavailable(NOT_RUNNING);
71
+ }
72
+ const file = parsed;
73
+ if (typeof file?.url !== "string" || typeof file.secret !== "string") throw new DoorUnavailable(NOT_RUNNING);
74
+ let url;
75
+ try {
76
+ url = new URL(file.url);
77
+ } catch {
78
+ throw new DoorUnavailable(NOT_RUNNING);
79
+ }
80
+ if (url.protocol !== "http:" || !LOOPBACK.has(url.hostname)) throw new DoorUnavailable(NOT_RUNNING);
81
+ return {
82
+ url: url.origin,
83
+ secret: file.secret
84
+ };
85
+ }
86
+ function fileDoor(fetchImpl = (input, init) => fetch(input, init), read = (path) => readFileSync(path, "utf8")) {
87
+ const post = async (folder, path, body) => {
88
+ const file = readDoorFile(folder, read);
89
+ try {
90
+ const answer = await (await fetchImpl(`${file.url}${path}`, {
91
+ method: "POST",
92
+ headers: {
93
+ authorization: `Bearer ${file.secret}`,
94
+ "content-type": "application/json"
95
+ },
96
+ body: JSON.stringify(body),
97
+ signal: AbortSignal.timeout(TIMEOUT_MS$1)
98
+ })).json();
99
+ if (answer === null || typeof answer !== "object") throw new DoorUnavailable("the app answered with nothing readable");
100
+ return answer;
101
+ } catch (cause) {
102
+ if (cause instanceof DoorUnavailable) throw cause;
103
+ throw new DoorUnavailable(NOT_RUNNING);
104
+ }
105
+ };
106
+ return {
107
+ call: (folder, verb, args) => post(folder, "/api/acryl-door/call", {
108
+ verb,
109
+ args
110
+ }),
111
+ confirmPublish: (folder, body) => post(folder, "/api/acryl-door/publish-confirmed", body)
112
+ };
113
+ }
114
+ //#endregion
115
+ //#region src/registry.ts
116
+ /** The public Blend registry as the screen's store lists it: only reads (the same index `acryl new --from` and the terminal's "Install a Blend" use). */
117
+ const REGISTRY_INDEX = "https://acrylblends.github.io/registry/index.json";
118
+ /** Blends released by people outside the ACRYL project and found on GitHub by the registry's hourly sync (origin `community`, each with its `source`). */
119
+ const REGISTRY_DISCOVERED = "https://acrylblends.github.io/registry/discovered.json";
120
+ const TIMEOUT_MS = 1e4;
121
+ var RegistryUnavailable = class extends Error {};
122
+ const record$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
123
+ const text$2 = (value) => typeof value === "string" ? value : "";
124
+ /** The `entries` of one registry list; `RegistryUnavailable` in words a person can act on. */
125
+ async function entriesOf(fetchImpl, url) {
126
+ let body;
127
+ try {
128
+ const response = await fetchImpl(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
129
+ if (!response.ok) throw new RegistryUnavailable(`The registry answered HTTP ${String(response.status)}.`);
130
+ body = await response.json();
131
+ } catch (cause) {
132
+ if (cause instanceof RegistryUnavailable) throw cause;
133
+ throw new RegistryUnavailable("The registry could not be read. Check the network and try again.");
134
+ }
135
+ const entries = record$1(body)?.entries;
136
+ if (!Array.isArray(entries)) throw new RegistryUnavailable("The registry answered, but its list could not be read.");
137
+ return entries;
138
+ }
139
+ /**
140
+ * The Blends an ACRYL app can be made from (registry entries whose runtime is `acrylblends`), by name: the public registry's, and the community ones
141
+ * the registry found on GitHub (made from their `source`). The community list is optional: when it cannot be read, the store still lists the rest.
142
+ */
143
+ async function readBlends(fetchImpl = (input, init) => fetch(input, init), url = REGISTRY_INDEX, discovered = REGISTRY_DISCOVERED) {
144
+ const blends = [];
145
+ const ids = /* @__PURE__ */ new Set();
146
+ for (const raw of await entriesOf(fetchImpl, url)) {
147
+ const entry = record$1(raw);
148
+ if (entry === void 0 || entry.runtime !== "acrylblends" || typeof entry.id !== "string" || entry.id === "") continue;
149
+ ids.add(entry.id);
150
+ blends.push({
151
+ id: entry.id,
152
+ name: text$2(entry.name) || entry.id,
153
+ version: text$2(entry.version),
154
+ category: text$2(entry.category),
155
+ description: text$2(entry.description),
156
+ origin: entry.origin === "official" ? "official" : "community"
157
+ });
158
+ }
159
+ const community = discovered === void 0 ? [] : await entriesOf(fetchImpl, discovered).catch(() => []);
160
+ for (const raw of community) {
161
+ const entry = record$1(raw);
162
+ if (entry === void 0 || entry.runtime !== "acrylblends" || typeof entry.id !== "string" || entry.id === "" || ids.has(entry.id)) continue;
163
+ const source = text$2(entry.source);
164
+ if (!BLEND_SOURCE.test(source)) continue;
165
+ ids.add(entry.id);
166
+ blends.push({
167
+ id: entry.id,
168
+ name: text$2(entry.name) || entry.id,
169
+ version: text$2(entry.version),
170
+ category: text$2(entry.category),
171
+ description: text$2(entry.description),
172
+ origin: "community",
173
+ source
174
+ });
175
+ }
176
+ return blends.sort((a, b) => a.name.localeCompare(b.name));
177
+ }
178
+ //#endregion
179
+ //#region src/tools.ts
180
+ const LAUNCHER_HELP = `The ACRYL launcher is the first screen of ACRYL (Web and Desktop). Where things are:
181
+ - My apps (left nav): every app made with ACRYL on this machine, as cards with a state (running, stopped), a surface (Web = served at an address, Desktop = a window of its own) and a Blend name. Select a card for its panel: Start or Stop, Open, Remove from list, its folder, and, while it runs, its Plugins.
182
+ - + New app (top): asks where, a name, a starter (Blank, Node.js, Notes, Chat, To-do, Agent) and a surface; it runs "acryl new <name> <starter>" and installs the app (about a minute), then starts it.
183
+ - Blends store (left nav): the public registry of ready-made apps (acrylblends.github.io/blends); "Make an app" on a card runs "acryl new <name> --from <id>".
184
+ - Add a folder (top): puts an app you already have in the list ("acryl apps add <folder>").
185
+ - Plugins of a running app (its card's panel): "Pull a plugin" takes github:owner/repo@version; "Share plugin" shows exactly what would be published and sends nothing until the person clicks "Yes, publish". An agent never publishes: it can only prepare the plan.
186
+ - Running, Made by agents, Updates (not built yet), WebBoxes.ai (deploy is coming), Health (Node, npm and the model key), Settings (the look: ACRYL ADE or acryl.dev).
187
+ - Assistant (left nav): this panel. ACRYL ADE (the agentic development environment) opens from its card on My apps.
188
+ Tools: acryl_launcher_apps lists the apps; acryl_launcher_new_app, _start_app and _stop_app change them; acryl_launcher_blends searches the registry; acryl_launcher_plugins and _pull_plugin work on a running app; acryl_launcher_publish_plan prepares a publish for the person to confirm.`;
189
+ /** An app as an agent reads it: the address without its launch token (the token is a secret of the person's session). */
190
+ const describeApp = (app) => ({
191
+ id: app.id,
192
+ name: app.name,
193
+ folder: app.path,
194
+ blend: app.blend,
195
+ surface: app.surface,
196
+ state: app.state,
197
+ madeBy: app.madeBy,
198
+ ...app.address === void 0 ? {} : { address: app.address.replace(/\?.*$/u, "") },
199
+ ...app.failure === void 0 ? {} : { failure: app.failure }
200
+ });
201
+ const text$1 = (value) => [{
202
+ type: "text",
203
+ text: value
204
+ }];
205
+ /** Every tool's value is the text an agent reads (JSON where it is data): a typed object output would need a schema per tool and gains nothing here. */
206
+ const asText = (value) => JSON.stringify(value, null, 2);
207
+ const STRING = { type: "string" };
208
+ /** The tool definitions over one service; separate from registering them so a test can call each. */
209
+ function launcherTools(service) {
210
+ return [
211
+ defineAcrylTool({
212
+ name: "acryl_launcher_help",
213
+ description: "How to use the ACRYL launcher and where to find what: its screens, buttons and the other launcher tools. Call it first when asked about the launcher.",
214
+ parameters: {},
215
+ output: {
216
+ schema: STRING,
217
+ render: (_args, value) => text$1(value)
218
+ },
219
+ execute: () => LAUNCHER_HELP
220
+ }),
221
+ defineAcrylTool({
222
+ name: "acryl_launcher_apps",
223
+ description: "The apps in the launcher's list: id, folder, Blend, surface (web or desktop), state (running, starting, stopped, missing) and address when running; and the app being made, if any.",
224
+ parameters: {},
225
+ output: {
226
+ schema: STRING,
227
+ render: (_args, value) => text$1(value)
228
+ },
229
+ execute: () => {
230
+ const state = service.state();
231
+ return asText({
232
+ apps: state.apps.map(describeApp),
233
+ making: state.job,
234
+ newAppsGoIn: state.appsFolder
235
+ });
236
+ }
237
+ }),
238
+ defineAcrylTool({
239
+ name: "acryl_launcher_blends",
240
+ description: "Blends in the public registry that an app can be made from (id, name, category, description). Give a query to narrow it; at most 25 are returned.",
241
+ parameters: { query: {
242
+ type: "string",
243
+ description: "words to look for in the name, id, category or description"
244
+ } },
245
+ output: {
246
+ schema: STRING,
247
+ render: (_args, value) => text$1(value)
248
+ },
249
+ execute: async (args) => {
250
+ const needle = (args.query ?? "").trim().toLowerCase();
251
+ const found = (await service.blends()).filter((blend) => needle === "" || `${blend.name} ${blend.id} ${blend.category} ${blend.description}`.toLowerCase().includes(needle));
252
+ return asText({
253
+ total: found.length,
254
+ blends: found.slice(0, 25).map((blend) => ({
255
+ id: blend.id,
256
+ name: blend.name,
257
+ category: blend.category,
258
+ description: blend.description
259
+ }))
260
+ });
261
+ }
262
+ }),
263
+ defineAcrylTool({
264
+ name: "acryl_launcher_new_app",
265
+ description: "Make a new app, as the launcher's + New app does: from a starter (blank, nodejs, notes, chat, todo, agent) or from a registry Blend id (acrylblends_launcher_blends), as a web or desktop app. It installs the app (about a minute) and starts it; watch with acryl_launcher_apps.",
266
+ parameters: {
267
+ name: {
268
+ type: "string",
269
+ required: true,
270
+ description: "lower case letters, digits and dashes"
271
+ },
272
+ starter: {
273
+ type: "string",
274
+ description: "a starter; default blank. Not with blend."
275
+ },
276
+ blend: {
277
+ type: "string",
278
+ description: "a registry Blend id such as acrylblends.csv-explorer. Not with starter."
279
+ },
280
+ surface: {
281
+ type: "string",
282
+ description: "web (default) or desktop"
283
+ },
284
+ where: {
285
+ type: "string",
286
+ description: "the folder to make it in; default the launcher's apps folder"
287
+ }
288
+ },
289
+ output: {
290
+ schema: STRING,
291
+ render: (_args, value) => text$1(value)
292
+ },
293
+ execute: (args) => {
294
+ const surface = args.surface === "desktop" ? "desktop" : args.surface === void 0 || args.surface === "web" ? "web" : void 0;
295
+ if (surface === void 0) throw new Error("surface must be web or desktop");
296
+ const where = args.where ?? service.state().appsFolder;
297
+ service.create({
298
+ where,
299
+ name: args.name,
300
+ surface,
301
+ ...args.blend === void 0 ? { starter: args.starter ?? "blank" } : {
302
+ blend: args.blend,
303
+ ...args.starter === void 0 ? {} : { starter: args.starter }
304
+ }
305
+ });
306
+ return asText({
307
+ making: args.name,
308
+ where,
309
+ note: "It is being made and installed (about a minute), then started. Call acryl_launcher_apps to watch."
310
+ });
311
+ }
312
+ }),
313
+ defineAcrylTool({
314
+ name: "acryl_launcher_start_app",
315
+ description: "Start an app from the launcher's list (a desktop app opens its own window); installs its dependencies first if it has none.",
316
+ parameters: { app: {
317
+ type: "string",
318
+ required: true,
319
+ description: "the app's id from acryl_launcher_apps"
320
+ } },
321
+ output: {
322
+ schema: STRING,
323
+ render: (_args, value) => text$1(value)
324
+ },
325
+ execute: (args) => {
326
+ service.start(args.app);
327
+ return asText({ starting: args.app });
328
+ }
329
+ }),
330
+ defineAcrylTool({
331
+ name: "acryl_launcher_stop_app",
332
+ description: "Stop an app the launcher started.",
333
+ parameters: { app: {
334
+ type: "string",
335
+ required: true,
336
+ description: "the app's id from acryl_launcher_apps"
337
+ } },
338
+ output: {
339
+ schema: STRING,
340
+ render: (_args, value) => text$1(value)
341
+ },
342
+ execute: (args) => {
343
+ service.stop(args.app);
344
+ return asText({ stopped: args.app });
345
+ }
346
+ }),
347
+ defineAcrylTool({
348
+ name: "acryl_launcher_plugins",
349
+ description: "The plugins of a RUNNING app: the ones made in it (shareable) and the ones pulled from a registry, with their source.",
350
+ parameters: { app: {
351
+ type: "string",
352
+ required: true,
353
+ description: "the app's id"
354
+ } },
355
+ output: {
356
+ schema: STRING,
357
+ render: (_args, value) => text$1(value)
358
+ },
359
+ execute: async (args) => asText({ plugins: await service.plugins(args.app) })
360
+ }),
361
+ defineAcrylTool({
362
+ name: "acryl_launcher_pull_plugin",
363
+ description: "Pull a plugin from a registry source into a RUNNING app, as the launcher's Pull a plugin does. The source is github:owner/repo@version.",
364
+ parameters: {
365
+ app: {
366
+ type: "string",
367
+ required: true,
368
+ description: "the app's id"
369
+ },
370
+ source: {
371
+ type: "string",
372
+ required: true,
373
+ description: "github:owner/repo@version"
374
+ }
375
+ },
376
+ output: {
377
+ schema: STRING,
378
+ render: (_args, value) => text$1(value)
379
+ },
380
+ execute: async (args) => asText(await service.pullPlugin(args.app, args.source))
381
+ }),
382
+ defineAcrylTool({
383
+ name: "acryl_launcher_publish_plan",
384
+ description: "Prepare publishing a plugin made in a RUNNING app: what would be sent (account, repository, version, license, files) and the line a friend pulls it with. Sends NOTHING: the person presses Share plugin on the app's card in the launcher and says yes.",
385
+ parameters: {
386
+ app: {
387
+ type: "string",
388
+ required: true,
389
+ description: "the app's id"
390
+ },
391
+ plugin: {
392
+ type: "string",
393
+ required: true,
394
+ description: "a plugin made in the app"
395
+ },
396
+ owner: {
397
+ type: "string",
398
+ description: "the GitHub account that would own the repository; default the signed-in one"
399
+ }
400
+ },
401
+ output: {
402
+ schema: STRING,
403
+ render: (_args, value) => text$1(value)
404
+ },
405
+ execute: async (args) => asText({
406
+ plan: await service.publishPlan({
407
+ id: args.app,
408
+ plugin: args.plugin,
409
+ ...args.owner === void 0 ? {} : { owner: args.owner }
410
+ }),
411
+ nextStep: "Nothing was sent. Tell the person to press Share plugin on the app's card and confirm."
412
+ })
413
+ })
414
+ ];
415
+ }
416
+ /** Register the tools in the registry; the disposer removes them. @returns disposer. */
417
+ function registerLauncherTools(ctx, service) {
418
+ const disposers = launcherTools(service).map((definition) => ctx.acrylTools.register(definition));
419
+ return () => {
420
+ for (const dispose of disposers.reverse()) dispose();
421
+ };
422
+ }
423
+ //#endregion
424
+ //#region src/runner.ts
425
+ /**
426
+ * The one place this plugin starts processes. A `Runner` hands back a `Run` the service watches; the real one spawns the command through the
427
+ * machine's own Node and npm (the desktop app carries no Node of its own yet, spec 050 T005) and stops a whole tree, not only its first process
428
+ * (`npm run dev` starts a server below npm).
429
+ */
430
+ /** Keys the desktop app set for itself; a started app must choose its own (a shared one would put the new app in this app's home and port). */
431
+ const OWN_KEYS = /^(ACRYL_|ACRYLBLENDS_|DSH_|ELECTRON_|npm_|PORT$|WATCH_REPORT_DEPENDENCIES$)/u;
432
+ /** The environment a started app gets: this process's, without the keys above, plus the places Node usually lives (a Dock launch has a short PATH). */
433
+ function appEnvironment(base, platform = process.platform) {
434
+ const env = {};
435
+ for (const [key, value] of Object.entries(base)) if (!OWN_KEYS.test(key)) env[key] = value;
436
+ if (platform !== "win32") {
437
+ const extra = ["/opt/homebrew/bin", "/usr/local/bin"];
438
+ const have = (env.PATH ?? "").split(":");
439
+ env.PATH = [...have, ...extra.filter((dir) => !have.includes(dir))].filter((dir) => dir !== "").join(":");
440
+ }
441
+ return env;
442
+ }
443
+ /** Stop a command and everything it started: a process group on Unix, `taskkill /t` on Windows. */
444
+ function stopTree(pid, platform) {
445
+ try {
446
+ if (platform === "win32") spawnSync("taskkill", [
447
+ "/pid",
448
+ String(pid),
449
+ "/t",
450
+ "/f"
451
+ ], { windowsHide: true });
452
+ else process.kill(-pid, "SIGTERM");
453
+ } catch {}
454
+ }
455
+ const spawnRunner = (command) => {
456
+ const win = process.platform === "win32";
457
+ const child = spawn(command.program, [...command.args], {
458
+ cwd: command.cwd,
459
+ env: command.env,
460
+ shell: win,
461
+ detached: !win,
462
+ windowsHide: true,
463
+ stdio: [
464
+ "ignore",
465
+ "pipe",
466
+ "pipe"
467
+ ]
468
+ });
469
+ const outputs = [];
470
+ const ends = [];
471
+ let ended = false;
472
+ const finish = (end) => {
473
+ if (ended) return;
474
+ ended = true;
475
+ for (const listener of ends) listener(end);
476
+ };
477
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", (chunk) => {
478
+ for (const listener of outputs) listener(chunk.toString("utf8"));
479
+ });
480
+ child.on("error", (cause) => {
481
+ finish({
482
+ code: null,
483
+ notFound: cause.code === "ENOENT",
484
+ error: cause.message
485
+ });
486
+ });
487
+ child.on("close", (code) => {
488
+ finish({
489
+ code,
490
+ notFound: code === 127
491
+ });
492
+ });
493
+ return {
494
+ onOutput: (listener) => {
495
+ outputs.push(listener);
496
+ },
497
+ onEnd: (listener) => {
498
+ ends.push(listener);
499
+ },
500
+ stop: () => {
501
+ if (!ended && child.pid !== void 0) stopTree(child.pid, process.platform);
502
+ }
503
+ };
504
+ };
505
+ //#endregion
506
+ //#region src/service.ts
507
+ /**
508
+ * What the ACRYL screen does, as one service with ports (Clean Architecture: the routes and the Cordis plugin are the edge; this holds the rules).
509
+ * The list is the registry `<home>/apps.json` (`acryl-launcher`, the same file `acryl apps` and the terminal read); what runs is held here, in
510
+ * memory, because the launcher records no port: an app is "running" when this service started it and it has not ended.
511
+ */
512
+ /** A request the service cannot honour, in a sentence a person can act on. The route answers it as 409. */
513
+ var LauncherRefusal = class extends Error {};
514
+ /** The address an app prints, with the token it needs: `http://127.0.0.1:3999/?token=...`. */
515
+ const ADDRESS = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+[^\s'")\]]*/u;
516
+ const BLENDS_FRESH_MS = 6e4;
517
+ /** The package `acryl new` runs (`distribution/acryl-npm-launcher/forward.js` CREATE_SPEC). */
518
+ const CREATE_SPEC = "create-acrylblends@latest";
519
+ /** The command that updates an app from its Blend's newer release (`acrylblends update`, in the acrylblends package). */
520
+ const UPDATE_SPEC = "acrylblends@latest";
521
+ /** The app's own share command, from its folder (the `save` plugin of acrylblends). */
522
+ const SHARE_COMMAND = join("plugins", "save", "share-cli.ts");
523
+ /** ACRYL ADE: the Blend and the folder in the home that `acryl ade` makes and opens (`distribution/acryl-npm-launcher/managed.js` MANAGED.ade). */
524
+ const ADE_BLEND = "acryl.ade";
525
+ const ADE_FOLDER = "ade";
526
+ const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/gu;
527
+ const tail = (text) => {
528
+ const lines = text.replace(ANSI, "").split(/\r?\n/u).map((line) => line.trim()).filter((line) => line !== "").slice(-12).join("\n");
529
+ return lines !== "" && /\n\s*$/u.test(text) ? `${lines}\n` : lines;
530
+ };
531
+ var LauncherService = class {
532
+ #ports;
533
+ #started = /* @__PURE__ */ new Map();
534
+ /** Why an app last ended without being stopped, until it is started again. */
535
+ #failures = /* @__PURE__ */ new Map();
536
+ #job;
537
+ #blends;
538
+ #signIn;
539
+ /** The tools apps need: being fetched (the first start on a computer without them), ready, or not had (apps then try the computer's own). */
540
+ #tools = { state: "ready" };
541
+ constructor(ports) {
542
+ this.#ports = ports;
543
+ }
544
+ /** Start fetching what this computer lacks of Node.js and gh; apps wait for it (`#toolsReady`). Called once, when the launcher starts. */
545
+ prepareTools() {
546
+ const prepare = this.#ports.prepareTools;
547
+ if (prepare === void 0) return Promise.resolve();
548
+ this.#tools = { state: "preparing" };
549
+ return prepare().then(() => {
550
+ this.#tools = { state: "ready" };
551
+ }, (cause) => {
552
+ this.#tools = {
553
+ state: "failed",
554
+ reason: cause instanceof Error ? cause.message : String(cause)
555
+ };
556
+ });
557
+ }
558
+ /** Refuse, in words, to start anything while the tools are still being fetched; a failed fetch lets apps try the computer's own tools. */
559
+ #toolsReady() {
560
+ if (this.#tools.state === "preparing") throw new LauncherRefusal("Getting Node.js and GitHub's tool ready for your apps (only on the first start on this computer, about a minute). Try again in a moment.");
561
+ }
562
+ state() {
563
+ if (this.#blends === void 0 || Date.now() - this.#blends.at >= BLENDS_FRESH_MS) this.blends().catch(() => void 0);
564
+ const apps = readApps(this.#ports.home).map((entry) => this.#view(entry));
565
+ const at = this.#job;
566
+ const job = at === void 0 ? null : {
567
+ name: at.name,
568
+ kind: at.kind,
569
+ line: at.line,
570
+ status: at.status,
571
+ step: at.step,
572
+ since: at.since,
573
+ output: at.output.trimEnd(),
574
+ ...at.message === void 0 ? {} : { message: at.message }
575
+ };
576
+ return {
577
+ apps,
578
+ appsFolder: this.#ports.appsFolder,
579
+ starters: STARTERS,
580
+ job
581
+ };
582
+ }
583
+ #view(entry) {
584
+ const started = this.#started.get(entry.id);
585
+ const missing = inspectApp(entry).state === "missing";
586
+ const state = missing ? "missing" : started === void 0 ? "stopped" : started.address === void 0 ? "starting" : "running";
587
+ const failure = this.#failures.get(entry.id);
588
+ const blend = entry.blend === "" ? blendOf(entry.path) : entry.blend;
589
+ const version = missing ? "" : blendVersionOf(entry.path);
590
+ const latest = this.#blends?.list.find((listed) => listed.id === blend)?.version;
591
+ return {
592
+ id: entry.id,
593
+ name: basename(entry.path),
594
+ path: entry.path,
595
+ blend,
596
+ madeBy: entry.madeBy,
597
+ surface: entry.surface,
598
+ state,
599
+ ...version === "" ? {} : { version },
600
+ ...version !== "" && latest !== void 0 && newerVersion(latest, version) ? { update: latest } : {},
601
+ ...started?.address === void 0 ? {} : { address: started.address },
602
+ ...started === void 0 || started.address !== void 0 || started.output === "" ? {} : { output: started.output.trimEnd() },
603
+ ...failure === void 0 || state !== "stopped" ? {} : { failure }
604
+ };
605
+ }
606
+ add(path) {
607
+ try {
608
+ return this.#view(addApp(this.#ports.home, { path }).entry);
609
+ } catch (cause) {
610
+ throw new LauncherRefusal(cause instanceof Error ? cause.message : String(cause));
611
+ }
612
+ }
613
+ remove(id) {
614
+ this.stop(id);
615
+ if (!removeApp(this.#ports.home, id)) throw new LauncherRefusal(`there is no app "${id}" in the list`);
616
+ }
617
+ /**
618
+ * Start an app the way the terminal's "Open an app" does, with the saved model key: a Web app with `npm run dev` in its folder (its address opens in the
619
+ * browser), a Desktop app with `npm run desktop`, which starts the same app and opens it in its own window (Electron is fetched the first time).
620
+ */
621
+ start(id, surface) {
622
+ this.#toolsReady();
623
+ const entry = readApps(this.#ports.home).find((app) => app.id === id);
624
+ if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
625
+ if (inspectApp(entry).state === "missing") throw new LauncherRefusal(`the folder ${entry.path} is gone: remove it from the list, or put it back`);
626
+ if (this.#started.has(id)) return;
627
+ this.#failures.delete(id);
628
+ if (!this.#ports.exists(join(entry.path, "node_modules"))) {
629
+ this.#installThenStart(id, entry.path, surface);
630
+ return;
631
+ }
632
+ const run = this.#ports.runner({
633
+ program: "npm",
634
+ args: ["run", (surface ?? entry.surface) === "desktop" ? "desktop" : "dev"],
635
+ cwd: entry.path,
636
+ env: this.#environment()
637
+ });
638
+ this.#watch(id, run, void 0);
639
+ }
640
+ #installThenStart(id, folder, surface) {
641
+ const run = this.#ports.runner({
642
+ program: "npm",
643
+ args: [
644
+ "install",
645
+ "--loglevel",
646
+ "http"
647
+ ],
648
+ cwd: folder,
649
+ env: this.#environment()
650
+ });
651
+ const started = {
652
+ run,
653
+ address: void 0,
654
+ output: ""
655
+ };
656
+ this.#started.set(id, started);
657
+ run.onOutput((text) => {
658
+ started.output = tail(`${started.output}${text}`);
659
+ });
660
+ run.onEnd((end) => {
661
+ if (this.#started.get(id) !== started) return;
662
+ this.#started.delete(id);
663
+ if (end.notFound) this.#failures.set(id, "Node.js and npm were not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.");
664
+ else if (end.code === 0) try {
665
+ this.start(id, surface);
666
+ } catch (cause) {
667
+ this.#failures.set(id, cause instanceof Error ? cause.message : String(cause));
668
+ }
669
+ else if (end.code !== null) this.#failures.set(id, started.output === "" ? end.error ?? "npm install ended before the app could run." : started.output.trimEnd());
670
+ });
671
+ }
672
+ /**
673
+ * ACRYL ADE, the way `acryl ade` (`--gui`) opens it: the Blend `acryl.ade` in `<home>/ade`, made from the registry the first time (listed, installed and
674
+ * started as any app made here is), then started in a window or the browser. Already running, it is left as it is.
675
+ */
676
+ openAde(surface) {
677
+ const folder = join(this.#ports.home, ADE_FOLDER);
678
+ if (!this.#ports.exists(join(folder, APP_MARKER))) {
679
+ this.create({
680
+ name: ADE_FOLDER,
681
+ where: this.#ports.home,
682
+ blend: ADE_BLEND,
683
+ surface
684
+ });
685
+ return;
686
+ }
687
+ this.start(addApp(this.#ports.home, {
688
+ path: folder,
689
+ surface
690
+ }).entry.id, surface);
691
+ }
692
+ stop(id) {
693
+ this.#started.get(id)?.run.stop();
694
+ }
695
+ /**
696
+ * Bring the newer registry release of the app's Blend into it: `acrylblends update` in its folder (a git merge that keeps the person's changes, then npm
697
+ * install). A running app is stopped first and started again after.
698
+ */
699
+ update(id) {
700
+ this.#toolsReady();
701
+ if (this.#job?.status === "running") throw new LauncherRefusal(`${this.#job.name} is still being worked on: wait for it to finish`);
702
+ const entry = readApps(this.#ports.home).find((app) => app.id === id);
703
+ if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
704
+ const view = this.#view(entry);
705
+ if (view.update === void 0) throw new LauncherRefusal(`${view.name} is on the latest release of ${view.blend}`);
706
+ const restart = this.#started.has(id);
707
+ this.stop(id);
708
+ const run = this.#ports.runner({
709
+ program: "npm",
710
+ args: [
711
+ "exec",
712
+ "--yes",
713
+ UPDATE_SPEC,
714
+ "--",
715
+ "update"
716
+ ],
717
+ cwd: entry.path,
718
+ env: this.#environment()
719
+ });
720
+ const job = {
721
+ name: view.name,
722
+ kind: "update",
723
+ line: `cd ${entry.path} && npx ${UPDATE_SPEC} update`,
724
+ status: "running",
725
+ run,
726
+ since: Date.now(),
727
+ output: "",
728
+ step: `Updating ${view.name} from ${view.blend} ${view.version ?? ""} to ${view.update}: getting the release and merging it in, your changes are kept, then npm install. Next: ${restart ? "starting it again" : "done"}.`
729
+ };
730
+ this.#job = job;
731
+ let output = "";
732
+ run.onOutput((text) => {
733
+ output = tail(`${output}${text}`);
734
+ job.output = output;
735
+ });
736
+ run.onEnd((end) => {
737
+ if (job.run !== run) return;
738
+ if (end.notFound) {
739
+ job.status = "failed";
740
+ job.message = "Node.js and npm were not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.";
741
+ return;
742
+ }
743
+ if (end.code !== 0) {
744
+ job.status = "failed";
745
+ job.message = output === "" ? end.error ?? "The update ended before it was done; the app is unchanged." : output.trimEnd();
746
+ return;
747
+ }
748
+ job.status = "done";
749
+ job.step = `Updated ${view.name} to ${view.blend} ${view.update}.${restart ? " Starting it again: its progress shows on its card below." : ""}`;
750
+ job.output = "";
751
+ if (restart) try {
752
+ this.start(id);
753
+ } catch (cause) {
754
+ this.#failures.set(id, cause instanceof Error ? cause.message : String(cause));
755
+ }
756
+ });
757
+ }
758
+ stopAll() {
759
+ for (const started of this.#started.values()) started.run.stop();
760
+ this.#job?.run.stop();
761
+ }
762
+ /**
763
+ * Make an app: the same `acryl new <name> <starter>` the terminal runs, in the folder the person chose. `acryl new` goes on to install and start the app,
764
+ * so the process it began is the app's running process: when its blend.yaml appears the app is listed and that process is adopted as the app's.
765
+ */
766
+ create(request) {
767
+ this.#toolsReady();
768
+ if (this.#job?.status === "running") throw new LauncherRefusal(`${this.#job.name} is still being made: wait for it to finish`);
769
+ const problem = whereProblem(request.where) ?? (APP_NAME.test(request.name) ? void 0 : appNameProblem(request.name, this.#ports));
770
+ if (problem !== void 0) throw new LauncherRefusal(problem);
771
+ if (request.starter === void 0 === (request.blend === void 0)) throw new LauncherRefusal("choose a starter or a Blend, not both");
772
+ if (request.starter !== void 0 && !STARTERS.some((starter) => starter.value === request.starter)) throw new LauncherRefusal(`there is no starter "${request.starter}"`);
773
+ if (request.blend !== void 0 && !BLEND_ID.test(request.blend) && !BLEND_SOURCE.test(request.blend)) throw new LauncherRefusal(`"${request.blend}" is not a Blend id (for example acrylblends.notes) or a Blend on GitHub (github:owner/repo#tag)`);
774
+ if (!MAKEABLE_SURFACES.includes(request.surface)) throw new LauncherRefusal("CLI (TUI) apps are coming: choose Web or Desktop");
775
+ const folder = join(request.where, request.name);
776
+ if (this.#ports.exists(folder)) throw new LauncherRefusal(`there is already a folder named ${request.name} in ${request.where}`);
777
+ this.#ports.makeFolder(request.where);
778
+ const source = request.blend === void 0 ? [request.starter ?? ""] : ["--from", request.blend];
779
+ const args = [
780
+ "exec",
781
+ "--yes",
782
+ CREATE_SPEC,
783
+ "--",
784
+ request.name,
785
+ ...source
786
+ ];
787
+ const line = `cd ${request.where} && acryl new ${request.name} ${source.join(" ")}`;
788
+ const run = this.#ports.runner({
789
+ program: "npm",
790
+ args,
791
+ cwd: request.where,
792
+ env: {
793
+ ...this.#environment(),
794
+ npm_config_loglevel: "http"
795
+ }
796
+ });
797
+ const step = request.blend === void 0 ? `Step 1 of 2: getting ${request.name} and installing its dependencies (${CREATE_SPEC}, about a minute). Next: starting it.` : `Step 1 of 3: getting ${request.name} (${CREATE_SPEC}). Next: installing its dependencies, then starting it.`;
798
+ const job = {
799
+ name: request.name,
800
+ kind: "make",
801
+ line,
802
+ status: "running",
803
+ run,
804
+ step,
805
+ since: Date.now(),
806
+ output: ""
807
+ };
808
+ this.#job = job;
809
+ this.#watch(void 0, run, {
810
+ folder,
811
+ surface: request.surface,
812
+ job
813
+ });
814
+ }
815
+ /** The registry's Blends, read again at most once a minute: the store is opened and closed often, and the registry is a public file. */
816
+ async blends() {
817
+ if (this.#blends !== void 0 && Date.now() - this.#blends.at < BLENDS_FRESH_MS) return this.#blends.list;
818
+ const list = await this.#ports.blends();
819
+ this.#blends = {
820
+ at: Date.now(),
821
+ list
822
+ };
823
+ return list;
824
+ }
825
+ /** The apps folder, made when it is not there yet: the assistant's agent works in it, and a folder that does not exist cannot be worked in. */
826
+ assistantFolder() {
827
+ this.#ports.makeFolder(this.#ports.appsFolder);
828
+ return this.#ports.appsFolder;
829
+ }
830
+ #entry(id) {
831
+ const entry = readApps(this.#ports.home).find((app) => app.id === id);
832
+ if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
833
+ return entry;
834
+ }
835
+ /** A door call, with "the app is not running" and a refusal as the sentence a person can act on. */
836
+ async #door(id, run) {
837
+ const entry = this.#entry(id);
838
+ let answer;
839
+ try {
840
+ answer = await run(this.#ports.door, entry.path);
841
+ } catch (cause) {
842
+ if (cause instanceof DoorUnavailable) throw new LauncherRefusal(cause.message);
843
+ throw cause;
844
+ }
845
+ if (!answer.ok) throw new LauncherRefusal(answer.message ?? "the app refused");
846
+ return answer;
847
+ }
848
+ /** The plugins of a running app: the ones its people made (shareable) and the ones pulled from a registry. */
849
+ async plugins(id) {
850
+ const answer = await this.#door(id, (door, folder) => door.call(folder, "plugin-list", {}));
851
+ return (Array.isArray(answer.value) ? answer.value : []).filter((plugin) => typeof plugin.name === "string").map((plugin) => ({
852
+ name: String(plugin.name),
853
+ version: typeof plugin.version === "string" ? plugin.version : "",
854
+ state: typeof plugin.state === "string" ? plugin.state : "",
855
+ ...typeof plugin.pulledFrom === "string" ? { pulledFrom: plugin.pulledFrom } : {},
856
+ ...typeof plugin.author === "string" ? { author: plugin.author } : {}
857
+ }));
858
+ }
859
+ /** Pull a plugin into a running app from a registry source (`github:owner/repo@version`), the way `acryl plugin pull` does. */
860
+ async pullPlugin(id, source) {
861
+ if (source.trim() === "" || source.startsWith("-") || source.length > 1024) throw new LauncherRefusal("say where the plugin is, for example github:someone/pomodoro@0.1.0");
862
+ return {
863
+ text: (await this.#door(id, (door, folder) => door.call(folder, "plugin-pull", { source: source.trim() }))).text ?? "Pulled.",
864
+ plugins: await this.plugins(id)
865
+ };
866
+ }
867
+ #checkPublish(request) {
868
+ if (!PLUGIN_NAME.test(request.plugin)) throw new LauncherRefusal(`"${request.plugin}" is not a plugin name`);
869
+ if (request.owner !== void 0 && !ACCOUNT_NAME.test(request.owner)) throw new LauncherRefusal(`"${request.owner}" is not a GitHub account name`);
870
+ if (request.license !== void 0 && !LICENSE_ID.test(request.license)) throw new LauncherRefusal(`"${request.license}" is not a license id`);
871
+ }
872
+ #options(request) {
873
+ return {
874
+ ...request.owner === void 0 ? {} : { owner: request.owner },
875
+ ...request.license === void 0 ? {} : { license: request.license }
876
+ };
877
+ }
878
+ /** What publishing a plugin would send (the account, repository, version, license and files). Sends nothing. */
879
+ async publishPlan(request) {
880
+ this.#checkPublish(request);
881
+ const plan = (await this.#door(request.id, (door, folder) => door.call(folder, "plugin-publish", {
882
+ name: request.plugin,
883
+ ...this.#options(request)
884
+ }))).value;
885
+ if (plan === null || typeof plan !== "object" || typeof plan.owner !== "string" || typeof plan.repo !== "string" || typeof plan.version !== "string") throw new LauncherRefusal("the app did not give a publish plan");
886
+ return {
887
+ owner: plan.owner,
888
+ repo: plan.repo,
889
+ version: plan.version,
890
+ visibility: String(plan.visibility ?? ""),
891
+ license: String(plan.license ?? ""),
892
+ createsRepository: plan.createsRepository === true,
893
+ files: Array.isArray(plan.files) ? plan.files.map(String) : [],
894
+ integrity: String(plan.integrity ?? ""),
895
+ digest: String(plan.digest ?? ""),
896
+ pullLine: String(plan.pullLine ?? "")
897
+ };
898
+ }
899
+ /** The person's yes: publish exactly the plan they read. The app sends it only if the plugin still matches that plan. */
900
+ async publish(request) {
901
+ this.#checkPublish(request);
902
+ const result = (await this.#door(request.id, (door, folder) => door.confirmPublish(folder, {
903
+ name: request.plugin,
904
+ ...this.#options(request),
905
+ confirm: request.plan
906
+ }))).value;
907
+ if (result?.ok !== true) throw new LauncherRefusal(`Not published: ${result?.reason ?? "the app did not answer"}${result?.next === void 0 ? "" : `. ${result.next}`}`);
908
+ return {
909
+ releaseUrl: result.releaseUrl ?? "",
910
+ pullLine: result.pullLine ?? ""
911
+ };
912
+ }
913
+ /**
914
+ * The app's own share command (`plugins/save/share-cli.ts`, acrylblends 1.5.5), run in its folder: it prints one JSON line, the plan or the result.
915
+ * The app need not be running. An app made before that command has none, and is told how to get it.
916
+ */
917
+ async #shareCommand(request, confirm) {
918
+ this.#toolsReady();
919
+ const entry = this.#entry(request.id);
920
+ if (request.owner !== void 0 && !ACCOUNT_NAME.test(request.owner)) throw new LauncherRefusal(`"${request.owner}" is not a GitHub account name`);
921
+ if (!this.#ports.exists(join(entry.path, SHARE_COMMAND))) throw new LauncherRefusal(`This app was made before apps could share themselves. In ${entry.path} run "npx acrylblends@latest upgrade", then try again.`);
922
+ if (request.visibility !== void 0 && confirm === void 0) try {
923
+ setBlendVisibility(entry.path, request.visibility);
924
+ } catch (cause) {
925
+ throw new LauncherRefusal(`Could not set who may see it: ${cause instanceof Error ? cause.message : String(cause)}`);
926
+ }
927
+ const args = [
928
+ SHARE_COMMAND,
929
+ "--json",
930
+ ...request.owner === void 0 ? [] : ["--owner", request.owner],
931
+ ...confirm === void 0 ? [] : ["--confirm", Buffer.from(JSON.stringify(confirm), "utf8").toString("base64url")]
932
+ ];
933
+ const run = this.#ports.runner({
934
+ program: "node",
935
+ args,
936
+ cwd: entry.path,
937
+ env: this.#environment()
938
+ });
939
+ let output = "";
940
+ run.onOutput((text) => {
941
+ output += text;
942
+ });
943
+ if ((await new Promise((resolve) => {
944
+ run.onEnd(resolve);
945
+ })).notFound) throw new LauncherRefusal("Node.js was not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.");
946
+ const line = output.split(/\r?\n/u).map((text) => text.trim()).findLast((text) => text.startsWith("{"));
947
+ let answer;
948
+ try {
949
+ answer = line === void 0 ? void 0 : JSON.parse(line);
950
+ } catch {
951
+ answer = void 0;
952
+ }
953
+ if (answer === null || typeof answer !== "object") throw new LauncherRefusal(tail(output) === "" ? "the app did not answer" : tail(output));
954
+ const value = answer;
955
+ if (value.ok === false) throw new LauncherRefusal(`Not shared: ${typeof value.reason === "string" ? value.reason : "the app refused"}`);
956
+ return value;
957
+ }
958
+ /** What sharing the app would send: the repository (a new one, or the remote it has), its visibility and how many changed files are saved first. Sends nothing. */
959
+ async sharePlan(request) {
960
+ const plan = await this.#shareCommand(request, void 0);
961
+ if (typeof plan.repository !== "string" || typeof plan.create !== "boolean" || plan.visibility !== "private" && plan.visibility !== "public" || typeof plan.changes !== "number") throw new LauncherRefusal("the app did not give a share plan");
962
+ return {
963
+ repository: plan.repository,
964
+ create: plan.create,
965
+ visibility: plan.visibility,
966
+ changes: plan.changes
967
+ };
968
+ }
969
+ /** The person's yes: share exactly the plan they read. The app sends it only if it still matches that plan. */
970
+ async share(request) {
971
+ const result = await this.#shareCommand(request, request.plan);
972
+ if (result.ok !== true || typeof result.remote !== "string") throw new LauncherRefusal("Not shared: the app did not answer");
973
+ return {
974
+ remote: result.remote,
975
+ created: result.created === true
976
+ };
977
+ }
978
+ async health(probe = this.#ports.runner) {
979
+ const version = (program) => new Promise((resolve) => {
980
+ const run = probe({
981
+ program,
982
+ args: ["--version"],
983
+ cwd: this.#ports.home,
984
+ env: this.#environment()
985
+ });
986
+ let text = "";
987
+ run.onOutput((chunk) => {
988
+ text += chunk;
989
+ });
990
+ run.onEnd((end) => {
991
+ resolve(end.code === 0 && !end.notFound ? text.trim().split(/\s+/u)[0]?.replace(/^v/u, "") : void 0);
992
+ });
993
+ });
994
+ const [node, npm] = await Promise.all([version("node"), version("npm")]);
995
+ return {
996
+ ...node === void 0 ? {} : { node },
997
+ ...npm === void 0 ? {} : { npm },
998
+ modelKey: readModelKey(this.#ports.home) !== void 0,
999
+ home: this.#ports.home
1000
+ };
1001
+ }
1002
+ /** The saved key, masked, for the screen's Settings and Health; never the key itself. */
1003
+ maskedModelKey() {
1004
+ const key = readModelKey(this.#ports.home);
1005
+ return key === void 0 ? void 0 : maskKey(key);
1006
+ }
1007
+ #environment() {
1008
+ const inherited = this.#ports.environment();
1009
+ return appEnvironment(toolsEnv(this.#ports.home, {
1010
+ ...inherited,
1011
+ ...modelEnv(this.#ports.home, inherited),
1012
+ ...githubEnv(this.#ports.home, inherited)
1013
+ }));
1014
+ }
1015
+ /** Who is signed in to GitHub here (the token apps get as GH_TOKEN), never the token. */
1016
+ github() {
1017
+ return {
1018
+ available: githubClientId(this.#ports.environment()) !== void 0,
1019
+ login: readGithub(this.#ports.home)?.login ?? null
1020
+ };
1021
+ }
1022
+ /** Start GitHub's device sign-in: the code for the person; the device code stays here until it is approved, refused or expires. */
1023
+ async githubStart() {
1024
+ const clientId = githubClientId(this.#ports.environment());
1025
+ if (clientId === void 0) throw new LauncherRefusal("this build of Control Center has no GitHub app to sign in with");
1026
+ try {
1027
+ const started = await startGithubSignIn(clientId);
1028
+ this.#signIn = {
1029
+ clientId,
1030
+ deviceCode: started.deviceCode,
1031
+ until: Date.now() + started.expiresIn * 1e3
1032
+ };
1033
+ return {
1034
+ userCode: started.userCode,
1035
+ verificationUri: started.verificationUri,
1036
+ interval: started.interval
1037
+ };
1038
+ } catch (cause) {
1039
+ throw new LauncherRefusal(`GitHub sign-in could not start: ${cause instanceof Error ? cause.message : String(cause)}. Check the network and try again.`);
1040
+ }
1041
+ }
1042
+ /** One poll of the sign-in under way: pending, connected (the token is saved and every app started from now on gets it), or failed. */
1043
+ async githubPoll() {
1044
+ const signIn = this.#signIn;
1045
+ if (signIn === void 0) return {
1046
+ state: "failed",
1047
+ reason: "no GitHub sign-in is under way: start it again"
1048
+ };
1049
+ if (Date.now() > signIn.until) {
1050
+ this.#signIn = void 0;
1051
+ return {
1052
+ state: "failed",
1053
+ reason: "the code expired: start the sign-in again"
1054
+ };
1055
+ }
1056
+ try {
1057
+ const answer = await pollGithubSignIn(this.#ports.home, signIn.clientId, signIn.deviceCode);
1058
+ if (answer.state !== "pending") this.#signIn = void 0;
1059
+ return answer;
1060
+ } catch {
1061
+ return { state: "pending" };
1062
+ }
1063
+ }
1064
+ /** Forget the GitHub connection on this machine. Apps started from now on no longer get the token. */
1065
+ githubDisconnect() {
1066
+ this.#signIn = void 0;
1067
+ clearGithub(this.#ports.home);
1068
+ return this.github();
1069
+ }
1070
+ /**
1071
+ * Follow one process. For an app being started, `id` is known; for one being made it is not until the folder has its blend.yaml, which is when the app
1072
+ * is listed and the process becomes that app's.
1073
+ */
1074
+ #watch(id, run, making) {
1075
+ const started = {
1076
+ run,
1077
+ address: void 0,
1078
+ output: ""
1079
+ };
1080
+ let appId = id;
1081
+ if (appId !== void 0) this.#started.set(appId, started);
1082
+ run.onOutput((text) => {
1083
+ started.output = tail(`${started.output}${text}`);
1084
+ if (making !== void 0 && making.job.run === run) making.job.output = started.output;
1085
+ started.address ??= ADDRESS.exec(text)?.[0];
1086
+ if (making !== void 0 && appId === void 0 && this.#ports.exists(join(making.folder, APP_MARKER))) {
1087
+ appId = addApp(this.#ports.home, {
1088
+ path: making.folder,
1089
+ surface: making.surface
1090
+ }).entry.id;
1091
+ this.#started.set(appId, started);
1092
+ }
1093
+ if (making !== void 0 && started.address !== void 0 && making.job.status === "running") making.job.status = "done";
1094
+ });
1095
+ run.onEnd((end) => {
1096
+ if (appId !== void 0 && this.#started.get(appId) === started) {
1097
+ this.#started.delete(appId);
1098
+ const closed = started.address !== void 0 && readApps(this.#ports.home).find((entry) => entry.id === appId)?.surface === "desktop";
1099
+ if (end.code !== 0 && end.code !== null && !end.notFound && !closed) this.#failures.set(appId, started.output.trimEnd());
1100
+ }
1101
+ if (end.notFound) this.#note(making, "failed", "Node.js and npm were not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.", id);
1102
+ else if (making !== void 0 && making.job.status === "running") if (end.code === 0 && appId !== void 0) if (this.#ports.exists(join(making.folder, "node_modules"))) this.#finish(appId, making.job);
1103
+ else this.#install(appId, making.folder, making.job);
1104
+ else making.job.status = "failed";
1105
+ if (making !== void 0 && making.job.status === "failed" && making.job.message === void 0) making.job.message = started.output === "" ? end.error ?? "The command ended before the app was made." : started.output.trimEnd();
1106
+ });
1107
+ }
1108
+ /** The job's last step: the app is made, so it is started (a Desktop app opens its window). */
1109
+ #finish(appId, job) {
1110
+ job.status = "done";
1111
+ job.step = `Made. Starting ${job.name} now: its progress shows on its card below.`;
1112
+ job.output = "";
1113
+ delete job.message;
1114
+ try {
1115
+ this.start(appId);
1116
+ } catch (cause) {
1117
+ this.#failures.set(appId, cause instanceof Error ? cause.message : String(cause));
1118
+ }
1119
+ }
1120
+ /** `npm install` in the new app's folder, as the job's second step; the job is still running while it does, and says so. */
1121
+ #install(appId, folder, job) {
1122
+ job.step = "Step 2 of 3: installing its dependencies (npm install, about a minute). Next: starting it.";
1123
+ job.output = "";
1124
+ const run = this.#ports.runner({
1125
+ program: "npm",
1126
+ args: [
1127
+ "install",
1128
+ "--loglevel",
1129
+ "http"
1130
+ ],
1131
+ cwd: folder,
1132
+ env: this.#environment()
1133
+ });
1134
+ job.run = run;
1135
+ let output = "";
1136
+ run.onOutput((text) => {
1137
+ output = tail(`${output}${text}`);
1138
+ job.output = output;
1139
+ });
1140
+ run.onEnd((end) => {
1141
+ if (job.run !== run) return;
1142
+ if (end.notFound) {
1143
+ job.status = "failed";
1144
+ job.message = "Node.js and npm were not found on this machine. Install Node.js 22.19 or later from nodejs.org, then try again.";
1145
+ } else if (end.code === 0) this.#finish(appId, job);
1146
+ else {
1147
+ job.status = "failed";
1148
+ job.message = output === "" ? end.error ?? "npm install ended before the app could run." : output.trimEnd();
1149
+ }
1150
+ });
1151
+ }
1152
+ #note(making, status, message, id) {
1153
+ if (making !== void 0) {
1154
+ making.job.status = status;
1155
+ making.job.message = message;
1156
+ } else if (id !== void 0) this.#failures.set(id, message);
1157
+ }
1158
+ };
1159
+ /** `0.2.0` is newer than `0.1.9`; anything that is not three numbers is never newer. */
1160
+ function newerVersion(candidate, current) {
1161
+ const parse = (text) => /^(\d+)\.(\d+)\.(\d+)$/u.exec(text)?.slice(1).map(Number);
1162
+ const a = parse(candidate);
1163
+ const b = parse(current);
1164
+ if (a === void 0 || b === void 0) return false;
1165
+ for (let index = 0; index < 3; index += 1) if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0);
1166
+ return false;
1167
+ }
1168
+ //#endregion
1169
+ //#region src/route.ts
1170
+ /** Strict same-origin loopback routes for the ACRYL screen. Reads need the app's own page; a change needs the exact `Origin` and a small JSON body. */
1171
+ const MAX_FIELD = 1024;
1172
+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1173
+ const text = (value) => typeof value === "string" && value.trim() !== "" && value.length <= MAX_FIELD ? value.trim() : void 0;
1174
+ const onlyKeys = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
1175
+ function parseOne(field) {
1176
+ return (value) => {
1177
+ const body = record(value);
1178
+ return body === void 0 || !onlyKeys(body, [field]) ? void 0 : text(body[field]);
1179
+ };
1180
+ }
1181
+ function parseNew(value) {
1182
+ const body = record(value);
1183
+ if (body === void 0 || !onlyKeys(body, [
1184
+ "where",
1185
+ "name",
1186
+ "starter",
1187
+ "blend",
1188
+ "surface"
1189
+ ])) return void 0;
1190
+ const where = text(body.where);
1191
+ const name = text(body.name);
1192
+ const starter = text(body.starter);
1193
+ const blend = text(body.blend);
1194
+ const surface = SURFACES.find((known) => known === body.surface);
1195
+ if (where === void 0 || name === void 0 || surface === void 0 || starter === void 0 === (blend === void 0)) return void 0;
1196
+ return {
1197
+ where,
1198
+ name,
1199
+ surface,
1200
+ ...starter === void 0 ? {} : { starter },
1201
+ ...blend === void 0 ? {} : { blend }
1202
+ };
1203
+ }
1204
+ const optional = (value) => value === void 0 ? void 0 : text(value) ?? null;
1205
+ function parsePublishPlan(value) {
1206
+ const body = record(value);
1207
+ if (body === void 0 || !onlyKeys(body, [
1208
+ "id",
1209
+ "plugin",
1210
+ "owner",
1211
+ "license"
1212
+ ])) return void 0;
1213
+ const id = text(body.id);
1214
+ const plugin = text(body.plugin);
1215
+ const owner = optional(body.owner);
1216
+ const license = optional(body.license);
1217
+ if (id === void 0 || plugin === void 0 || owner === null || license === null) return void 0;
1218
+ return {
1219
+ id,
1220
+ plugin,
1221
+ ...owner === void 0 ? {} : { owner },
1222
+ ...license === void 0 ? {} : { license }
1223
+ };
1224
+ }
1225
+ function parsePlan(value) {
1226
+ const plan = record(value);
1227
+ if (plan === void 0 || !Array.isArray(plan.files) || !plan.files.every((file) => typeof file === "string")) return void 0;
1228
+ if (![
1229
+ "owner",
1230
+ "repo",
1231
+ "version",
1232
+ "visibility",
1233
+ "license",
1234
+ "integrity",
1235
+ "digest",
1236
+ "pullLine"
1237
+ ].every((field) => typeof plan[field] === "string") || typeof plan.createsRepository !== "boolean") return void 0;
1238
+ return plan;
1239
+ }
1240
+ function parsePublish(value) {
1241
+ const body = record(value);
1242
+ if (body === void 0) return void 0;
1243
+ const { plan, ...rest } = body;
1244
+ const request = parsePublishPlan(rest);
1245
+ const confirmed = parsePlan(plan);
1246
+ return request === void 0 || confirmed === void 0 ? void 0 : {
1247
+ ...request,
1248
+ plan: confirmed
1249
+ };
1250
+ }
1251
+ function parseSharePlan(value) {
1252
+ const body = record(value);
1253
+ if (body === void 0 || !onlyKeys(body, [
1254
+ "id",
1255
+ "owner",
1256
+ "visibility"
1257
+ ])) return void 0;
1258
+ const id = text(body.id);
1259
+ const owner = optional(body.owner);
1260
+ if (body.visibility !== void 0 && body.visibility !== "private" && body.visibility !== "public") return void 0;
1261
+ const visibility = body.visibility;
1262
+ return id === void 0 || owner === null ? void 0 : {
1263
+ id,
1264
+ ...owner === void 0 ? {} : { owner },
1265
+ ...visibility === void 0 ? {} : { visibility }
1266
+ };
1267
+ }
1268
+ const nothing = (value) => record(value) !== void 0 && Object.keys(value).length === 0 ? {} : void 0;
1269
+ function parseShare(value) {
1270
+ const body = record(value);
1271
+ if (body === void 0) return void 0;
1272
+ const { plan, ...rest } = body;
1273
+ const request = parseSharePlan(rest);
1274
+ const read = record(plan);
1275
+ if (request === void 0 || read === void 0 || !onlyKeys(read, [
1276
+ "repository",
1277
+ "create",
1278
+ "visibility",
1279
+ "changes"
1280
+ ])) return void 0;
1281
+ const repository = text(read.repository);
1282
+ if (repository === void 0 || typeof read.create !== "boolean" || read.visibility !== "private" && read.visibility !== "public") return void 0;
1283
+ if (typeof read.changes !== "number" || !Number.isSafeInteger(read.changes) || read.changes < 0) return void 0;
1284
+ const confirmed = {
1285
+ repository,
1286
+ create: read.create,
1287
+ visibility: read.visibility,
1288
+ changes: read.changes
1289
+ };
1290
+ return {
1291
+ ...request,
1292
+ plan: confirmed
1293
+ };
1294
+ }
1295
+ function launcherRoutes(service, report = () => {}) {
1296
+ const app = new Acryl();
1297
+ app.get(LAUNCHER_STATE_PATH, ownPage, (c) => c.json(service.state()));
1298
+ app.get(LAUNCHER_HEALTH_PATH, ownPage, async (c) => {
1299
+ try {
1300
+ return c.json({
1301
+ ...await service.health(),
1302
+ keyMask: service.maskedModelKey() ?? null
1303
+ });
1304
+ } catch (cause) {
1305
+ report("check this machine", cause);
1306
+ return c.json(error("the launcher is unavailable"), 500);
1307
+ }
1308
+ });
1309
+ app.get(LAUNCHER_BLENDS_PATH, ownPage, async (c) => {
1310
+ try {
1311
+ return c.json({ blends: await service.blends() });
1312
+ } catch (cause) {
1313
+ if (cause instanceof RegistryUnavailable) return c.json(error(cause.message), 502);
1314
+ report("read the registry", cause);
1315
+ return c.json(error("the launcher is unavailable"), 500);
1316
+ }
1317
+ });
1318
+ /** A question or an action on a running app's door: same-origin JSON in, the answer out. A refusal is 409 with its reason. */
1319
+ const ask = (path, parse, run, operation) => {
1320
+ app.post(path, ownPage, jsonContent, jsonBody(), async (c) => {
1321
+ const value = await readJson(c);
1322
+ if (value === INVALID_JSON) return c.json(error("invalid JSON request"), 400);
1323
+ const request = parse(value);
1324
+ if (request === void 0) return c.json(error(`invalid ${operation} request`), 400);
1325
+ try {
1326
+ return c.json(await run(request));
1327
+ } catch (cause) {
1328
+ if (cause instanceof LauncherRefusal) return c.json(error(cause.message), 409);
1329
+ report(operation, cause);
1330
+ return c.json(error("the launcher is unavailable"), 500);
1331
+ }
1332
+ });
1333
+ };
1334
+ ask(LAUNCHER_ASSISTANT_FOLDER_PATH, (value) => record(value) !== void 0 && Object.keys(value).length === 0 ? {} : void 0, () => Promise.resolve({ folder: service.assistantFolder() }), "prepare the assistant's folder");
1335
+ ask(LAUNCHER_PLUGINS_PATH, parseOne("id"), async (id) => ({ plugins: await service.plugins(id) }), "list plugins");
1336
+ ask(LAUNCHER_PLUGIN_PULL_PATH, (value) => {
1337
+ const body = record(value);
1338
+ const id = body === void 0 || !onlyKeys(body, ["id", "source"]) ? void 0 : text(body.id);
1339
+ const source = body === void 0 ? void 0 : text(body.source);
1340
+ return id === void 0 || source === void 0 ? void 0 : {
1341
+ id,
1342
+ source
1343
+ };
1344
+ }, (request) => service.pullPlugin(request.id, request.source), "pull a plugin");
1345
+ ask(LAUNCHER_PUBLISH_PLAN_PATH, parsePublishPlan, (request) => service.publishPlan(request), "plan a publish");
1346
+ ask(LAUNCHER_PUBLISH_PATH, parsePublish, (request) => service.publish(request), "publish a plugin");
1347
+ ask(LAUNCHER_SHARE_PLAN_PATH, parseSharePlan, (request) => service.sharePlan(request), "plan a share");
1348
+ ask(LAUNCHER_SHARE_PATH, parseShare, (request) => service.share(request), "share an app");
1349
+ ask(LAUNCHER_GITHUB_PATH, nothing, () => Promise.resolve(service.github()), "read the GitHub connection");
1350
+ ask(LAUNCHER_GITHUB_START_PATH, nothing, () => service.githubStart(), "start the GitHub sign-in");
1351
+ ask(LAUNCHER_GITHUB_POLL_PATH, nothing, () => service.githubPoll(), "check the GitHub sign-in");
1352
+ ask(LAUNCHER_GITHUB_DISCONNECT_PATH, nothing, () => Promise.resolve(service.githubDisconnect()), "disconnect GitHub");
1353
+ /** A change: same-origin JSON in, the new state out. A refusal is 409 with its reason; anything else is reported and 500. */
1354
+ const change = (path, parse, run, operation) => {
1355
+ app.post(path, ownPage, jsonContent, jsonBody(), async (c) => {
1356
+ const value = await readJson(c);
1357
+ if (value === INVALID_JSON) return c.json(error("invalid JSON request"), 400);
1358
+ const request = parse(value);
1359
+ if (request === void 0) return c.json(error(`invalid ${operation} request`), 400);
1360
+ try {
1361
+ run(request);
1362
+ return c.json(service.state());
1363
+ } catch (cause) {
1364
+ if (cause instanceof LauncherRefusal) return c.json(error(cause.message), 409);
1365
+ report(operation, cause);
1366
+ return c.json(error("the launcher is unavailable"), 500);
1367
+ }
1368
+ });
1369
+ };
1370
+ change(LAUNCHER_ADD_PATH, parseOne("path"), (path) => {
1371
+ service.add(path);
1372
+ }, "add an app");
1373
+ change(LAUNCHER_REMOVE_PATH, parseOne("id"), (id) => {
1374
+ service.remove(id);
1375
+ }, "remove an app");
1376
+ change(LAUNCHER_NEW_PATH, parseNew, (request) => {
1377
+ service.create(request);
1378
+ }, "make an app");
1379
+ change(LAUNCHER_START_PATH, parseOne("id"), (id) => {
1380
+ service.start(id);
1381
+ }, "start an app");
1382
+ change(LAUNCHER_STOP_PATH, parseOne("id"), (id) => {
1383
+ service.stop(id);
1384
+ }, "stop an app");
1385
+ change(LAUNCHER_UPDATE_PATH, parseOne("id"), (id) => {
1386
+ service.update(id);
1387
+ }, "update an app");
1388
+ change(LAUNCHER_ADE_PATH, (value) => {
1389
+ const surface = parseOne("surface")(value);
1390
+ return surface === "web" || surface === "desktop" ? surface : void 0;
1391
+ }, (surface) => {
1392
+ service.openAde(surface);
1393
+ }, "open ACRYL ADE");
1394
+ return privateApi(LAUNCHER_API_PREFIX, app);
1395
+ }
1396
+ //#endregion
1397
+ //#region src/index.ts
1398
+ /**
1399
+ * Cordis Host plugin: the routes behind the ACRYL screen, the first screen of the desktop app (spec 050 T012). It lists the apps in the ACRYL home's
1400
+ * `apps.json`, adds, removes, makes, starts and stops them, and stops everything it started when it unloads.
1401
+ * Capability boundary: the list and what runs on this machine (one service, `LauncherService`); the drawing is the Client half.
1402
+ */
1403
+ const name = "acryl-launcher-desktop";
1404
+ const inject = [
1405
+ "router",
1406
+ "routerHttp",
1407
+ "appInstance"
1408
+ ];
1409
+ function apply(ctx) {
1410
+ const home = ctx.appInstance.home;
1411
+ const service = new LauncherService({
1412
+ home,
1413
+ appsFolder: join(dirname(home), "ACRYL"),
1414
+ runner: spawnRunner,
1415
+ environment: () => process.env,
1416
+ exists: (path) => existsSync(path),
1417
+ makeFolder: (path) => {
1418
+ mkdirSync(path, { recursive: true });
1419
+ },
1420
+ blends: () => readBlends(),
1421
+ door: fileDoor(),
1422
+ prepareTools: () => prepareTools(home, process.env)
1423
+ });
1424
+ service.prepareTools();
1425
+ const report = (operation, cause) => {
1426
+ ctx.logger.error(`@acryldev/launcher-desktop: failed to ${operation}: ${cause instanceof Error ? cause.message : String(cause)}`);
1427
+ };
1428
+ ctx.effect(() => () => {
1429
+ service.stopAll();
1430
+ }, "@acryldev/launcher-desktop: apps it started");
1431
+ ctx.inject(["acrylTools"], (child) => {
1432
+ child.effect(() => registerLauncherTools(child, service), "@acryldev/launcher-desktop: launcher tools");
1433
+ });
1434
+ ctx.router.route("/", launcherRoutes(service, report));
1435
+ ctx.routerHttp.mount(LAUNCHER_API_PREFIX);
1436
+ }
1437
+ //#endregion
1438
+ export { ACCOUNT_NAME, BLEND_ID, BLEND_SOURCE, LAUNCHER_ADD_PATH, LAUNCHER_ADE_PATH, LAUNCHER_API_PREFIX, LAUNCHER_ASSISTANT_FOLDER_PATH, LAUNCHER_BLENDS_PATH, LAUNCHER_GITHUB_DISCONNECT_PATH, LAUNCHER_GITHUB_PATH, LAUNCHER_GITHUB_POLL_PATH, LAUNCHER_GITHUB_START_PATH, LAUNCHER_HEALTH_PATH, LAUNCHER_NEW_PATH, LAUNCHER_PLUGINS_PATH, LAUNCHER_PLUGIN_PULL_PATH, LAUNCHER_PUBLISH_PATH, LAUNCHER_PUBLISH_PLAN_PATH, LAUNCHER_REMOVE_PATH, LAUNCHER_SHARE_PATH, LAUNCHER_SHARE_PLAN_PATH, LAUNCHER_START_PATH, LAUNCHER_STATE_PATH, LAUNCHER_STOP_PATH, LAUNCHER_UPDATE_PATH, LICENSE_ID, LauncherRefusal, LauncherService, MAKEABLE_SURFACES, PLUGIN_NAME, SURFACES, apply, inject, name };
1439
+
1440
+ //# sourceMappingURL=index.js.map