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