acryl 0.2.7 → 0.2.8

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/launcher.js CHANGED
@@ -8,7 +8,7 @@ import { basename, dirname, join, resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { EventEmitter } from "events";
10
10
  import * as fs from "node:fs";
11
- import { existsSync, readFileSync, readdirSync } from "node:fs";
11
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
12
12
  // node_modules/.pnpm/marked@18.0.11/node_modules/marked/lib/marked.esm.js
13
13
  /**
14
14
  * marked v18.0.11 - a markdown parser
@@ -7066,9 +7066,94 @@ var TuiMainScreen = class extends TuiBase {
7066
7066
  else this.terminal.hideCursor();
7067
7067
  }
7068
7068
  };
7069
- // plugins/acryl-launcher/node-context.js
7069
+ // plugins/acryl-launcher/apps-registry.js
7070
7070
  /** What makes a folder an app: the Blend manifest create-acrylblends writes at its root. */
7071
7071
  const APP_MARKER = "blend.yaml";
7072
+ const REGISTRY_FILE = "apps.json";
7073
+ const MADE_BY = Object.freeze(["person", "agent"]);
7074
+ /** The three kinds of app (spec 050 D10). An entry without one is a web app, which is what every app made before the field existed is. */
7075
+ const SURFACES = Object.freeze([
7076
+ "web",
7077
+ "desktop",
7078
+ "tui"
7079
+ ]);
7080
+ const slug = (name) => name.toLowerCase().replace(/[^a-z0-9-]+/gu, "-").replace(/^-+|-+$/gu, "") || "app";
7081
+ /** The Blend id a folder's blend.yaml names (`metadata.id`, else a top-level `id:`, else `name:`), or '' when it names none. */
7082
+ function blendOf(folder) {
7083
+ try {
7084
+ const text = readFileSync(join(folder, APP_MARKER), "utf8");
7085
+ return /^metadata:[^\S\n]*\n(?:[ \t]+\S.*\n|[ \t]*\n)*?[ \t]+id:\s*["']?([^\s"'#]+)/mu.exec(text)?.[1] ?? /^id:\s*["']?([^\s"']+)/mu.exec(text)?.[1] ?? /^name:\s*["']?([^\s"']+)/mu.exec(text)?.[1] ?? "";
7086
+ } catch {
7087
+ return "";
7088
+ }
7089
+ }
7090
+ const valid = (entry) => entry && typeof entry.id === "string" && typeof entry.path === "string";
7091
+ /** Every app in the list, oldest first; an empty list when the file is missing or not readable as a list (a broken file never stops the launcher). */
7092
+ function readApps(home) {
7093
+ try {
7094
+ const parsed = JSON.parse(readFileSync(join(home, REGISTRY_FILE), "utf8"));
7095
+ return (Array.isArray(parsed?.apps) ? parsed.apps : []).filter(valid).map((entry) => Object.freeze({
7096
+ id: entry.id,
7097
+ path: entry.path,
7098
+ blend: entry.blend ?? "",
7099
+ madeBy: MADE_BY.includes(entry.madeBy) ? entry.madeBy : "person",
7100
+ surface: SURFACES.includes(entry.surface) ? entry.surface : "web",
7101
+ added: entry.added ?? ""
7102
+ }));
7103
+ } catch {
7104
+ return [];
7105
+ }
7106
+ }
7107
+ function write(home, apps) {
7108
+ mkdirSync(home, { recursive: true });
7109
+ const file = join(home, REGISTRY_FILE);
7110
+ const temporary = `${file}.${String(process.pid)}.tmp`;
7111
+ writeFileSync(temporary, `${JSON.stringify({ apps }, null, 2)}\n`);
7112
+ renameSync(temporary, file);
7113
+ }
7114
+ /**
7115
+ * Put an app's folder in the list. A folder already listed stays as it is (`added: false`). A folder without a blend.yaml is not an app: this throws
7116
+ * a sentence a person can act on.
7117
+ */
7118
+ function addApp(home, { path, madeBy = "person", surface = "web" }, { now = () => (/* @__PURE__ */ new Date()).toISOString() } = {}) {
7119
+ const folder = resolve(path);
7120
+ if (!existsSync(join(folder, "blend.yaml"))) throw new Error(`${folder} is not an ACRYL app: it has no ${APP_MARKER}`);
7121
+ const apps = readApps(home);
7122
+ const existing = apps.find((entry) => resolve(entry.path) === folder);
7123
+ if (existing) return {
7124
+ entry: existing,
7125
+ added: false
7126
+ };
7127
+ const taken = new Set(apps.map((entry) => entry.id));
7128
+ const base = slug(basename(folder));
7129
+ let id = base;
7130
+ for (let n = 2; taken.has(id); n += 1) id = `${base}-${String(n)}`;
7131
+ const entry = Object.freeze({
7132
+ id,
7133
+ path: folder,
7134
+ blend: blendOf(folder),
7135
+ madeBy: MADE_BY.includes(madeBy) ? madeBy : "person",
7136
+ surface: SURFACES.includes(surface) ? surface : "web",
7137
+ added: now()
7138
+ });
7139
+ write(home, [...apps, entry]);
7140
+ return {
7141
+ entry,
7142
+ added: true
7143
+ };
7144
+ }
7145
+ /** Take an app out of the list (its folder is not touched). Returns whether it was listed. */
7146
+ function removeApp(home, id) {
7147
+ const apps = readApps(home);
7148
+ if (!apps.some((entry) => entry.id === id)) return false;
7149
+ write(home, apps.filter((entry) => entry.id !== id));
7150
+ return true;
7151
+ }
7152
+ /** What is true of a listed app now: its folder is there or it is not ('ready' | 'missing'). */
7153
+ function inspectApp(entry) {
7154
+ return Object.freeze({ state: existsSync(join(entry.path, "blend.yaml")) ? "ready" : "missing" });
7155
+ }
7156
+ // plugins/acryl-launcher/node-context.js
7072
7157
  /** The public registry's index (create-acrylblends PUBLIC_REGISTRY). */
7073
7158
  const REGISTRY_INDEX = "https://acrylblends.github.io/registry/index.json";
7074
7159
  const isApp = (dir) => existsSync(join(dir, APP_MARKER));
@@ -7093,9 +7178,23 @@ function listApps(cwd) {
7093
7178
  });
7094
7179
  return apps;
7095
7180
  }
7181
+ /**
7182
+ * Every app a person can choose: the ones in the list (value = the app's whole path, so any command runs in the right folder) and the ones in the
7183
+ * folder the launcher started in that are not listed yet.
7184
+ */
7185
+ function listAllApps(cwd, home) {
7186
+ const listed = home ? readApps(home).filter((entry) => inspectApp(entry).state === "ready").map((entry) => ({
7187
+ value: entry.path,
7188
+ label: entry.id,
7189
+ description: `${entry.blend || blendOf(entry.path) || "Blend"} ${entry.path}`
7190
+ })) : [];
7191
+ const known = new Set(listed.map((entry) => resolve(entry.value)));
7192
+ const local = listApps(cwd).filter((entry) => !known.has(resolve(cwd, entry.value)));
7193
+ return [...listed, ...local];
7194
+ }
7096
7195
  /** An app's own plugins: its plugin folders that the library (plugins/library.lock.json) did not put there. */
7097
7196
  function listPlugins(cwd, app) {
7098
- const root = join(cwd, app, "plugins");
7197
+ const root = join(resolve(cwd, app), "plugins");
7099
7198
  let library = {};
7100
7199
  try {
7101
7200
  library = JSON.parse(readFileSync(join(root, "library.lock.json"), "utf8")).plugins ?? {};
@@ -7123,70 +7222,21 @@ async function listBlends({ fetch = globalThis.fetch, url = REGISTRY_INDEX, time
7123
7222
  /** The context a session needs, for the folder the launcher started in. */
7124
7223
  function nodeContext(cwd = process.cwd(), options = {}) {
7125
7224
  let blends;
7225
+ const { home } = options;
7126
7226
  return {
7127
7227
  exists: (path) => existsSync(resolve(cwd, path)),
7128
- listApps: () => listApps(cwd),
7228
+ listApps: () => listAllApps(cwd, home),
7229
+ registeredApps: () => home ? readApps(home).map((entry) => ({
7230
+ ...entry,
7231
+ blend: entry.blend || blendOf(entry.path),
7232
+ ...inspectApp(entry)
7233
+ })) : [],
7234
+ defaultAppsFolder: () => options.appsFolder ?? ".",
7235
+ home,
7129
7236
  listPlugins: (app) => listPlugins(cwd, app),
7130
7237
  listBlends: () => blends ??= listBlends(options)
7131
7238
  };
7132
7239
  }
7133
- /** Terminal palettes by background: `dark` for a dark terminal (the default), `light` for a light one. */
7134
- const palettes = {
7135
- dark: {
7136
- primary: "#4F6BFE",
7137
- secondary: "#38BDF8",
7138
- accent: "#818CF8",
7139
- reasoning: "#A855F7",
7140
- success: "#34D399",
7141
- warning: "#FBBF24",
7142
- error: "#F87171",
7143
- info: "#4F6BFE",
7144
- muted: "#94A3B8"
7145
- },
7146
- light: {
7147
- primary: "#3652D9",
7148
- secondary: "#0369A1",
7149
- accent: "#4F46E5",
7150
- reasoning: "#7E22CE",
7151
- success: "#047857",
7152
- warning: "#B45309",
7153
- error: "#DC2626",
7154
- info: "#3652D9",
7155
- muted: "#64748B"
7156
- }
7157
- };
7158
- // plugins/acryl-ui-tui/scheme.js
7159
- const ESC$1 = "\x1B";
7160
- const paint$1 = (hex) => {
7161
- const n = Number.parseInt(hex.slice(1), 16);
7162
- return (text) => `${ESC$1}[38;2;${n >> 16 & 255};${n >> 8 & 255};${n & 255}m${text}${ESC$1}[0m`;
7163
- };
7164
- /** The theme for a palette mode (`dark` or `light`), in the shape `createTuiUi` takes. */
7165
- function paletteTheme(mode = "dark") {
7166
- const palette = palettes[mode] ?? palettes.dark;
7167
- return Object.freeze({
7168
- mode: palettes[mode] ? mode : "dark",
7169
- color: (role) => paint$1(palette[role] ?? palette.muted)
7170
- });
7171
- }
7172
- /** True when the person chose a palette (`ACRYL_TUI_THEME`), so the terminal's own report is not followed. */
7173
- const isPaletteForced = (env = process.env) => ["dark", "light"].includes(env.ACRYL_TUI_THEME?.trim().toLowerCase() ?? "");
7174
- /** The palette before the terminal answers: `ACRYL_TUI_THEME`, then the background index in `COLORFGBG`, then dark. */
7175
- function paletteModeFromEnv(env = process.env) {
7176
- const forced = env.ACRYL_TUI_THEME?.trim().toLowerCase();
7177
- if (forced === "dark" || forced === "light") return forced;
7178
- const background = env.COLORFGBG?.split(";").pop();
7179
- if (background !== void 0 && /^\d+$/u.test(background)) {
7180
- const index = Number(background);
7181
- return index === 7 || index >= 9 && index <= 15 ? "light" : "dark";
7182
- }
7183
- return "dark";
7184
- }
7185
- /** Light or dark from the background a terminal reports (0-255 channels), by relative luminance (ITU-R BT.709); undefined when none was reported. */
7186
- function schemeOfBackground(background) {
7187
- if (background === void 0) return void 0;
7188
- return (.2126 * background.r + .7152 * background.g + .0722 * background.b) / 255 >= .5 ? "light" : "dark";
7189
- }
7190
7240
  // plugins/acryl-launcher/journeys.js
7191
7241
  /** The starters `acryl new` makes (create-acrylblends TEMPLATES, same order and words). */
7192
7242
  const STARTERS = Object.freeze([
@@ -7221,12 +7271,36 @@ const STARTERS = Object.freeze([
7221
7271
  description: "the blank app with an agent that builds plugins into the running app"
7222
7272
  }
7223
7273
  ]);
7274
+ /** Where `acryl ade` opens ACRYL ADE (spec 050 D14); the first run makes it in ~/.acryl/ade. */
7275
+ const ADE_SURFACES = Object.freeze([
7276
+ {
7277
+ value: "web",
7278
+ label: "Browser",
7279
+ description: "ACRYL ADE in your browser (the first run installs it, about a minute)"
7280
+ },
7281
+ {
7282
+ value: "gui",
7283
+ label: "Window",
7284
+ description: "ACRYL ADE in its own desktop window"
7285
+ },
7286
+ {
7287
+ value: "tui",
7288
+ label: "Terminal",
7289
+ description: "the ACRYL coding agent in this terminal (a one-time download of about 450 MB)"
7290
+ }
7291
+ ]);
7224
7292
  /** The rule create-acrylblends applies to a new app's name. */
7225
7293
  const APP_NAME = /^[a-z][a-z0-9-]*$/u;
7226
- /** Why `name` cannot be a new app's name here, or undefined when it can. */
7227
- function appNameProblem(name, context) {
7294
+ /** Why `name` cannot be a new app's name (in the folder the `where` answer names, else here), or undefined when it can. */
7295
+ function appNameProblem(name, context, answers = {}) {
7228
7296
  if (!APP_NAME.test(name)) return "lower case letters, digits and dashes, starting with a letter";
7229
- if (context.exists(name)) return `there is already a folder named ${name} here`;
7297
+ const path = answers.where && answers.where !== "." ? `${answers.where}/${name}` : name;
7298
+ if (context.exists(path)) return `there is already a folder named ${name} ${answers.where && answers.where !== "." ? `in ${answers.where}` : "here"}`;
7299
+ }
7300
+ /** Why `folder` cannot hold new apps, or undefined when it can (it need not exist yet: the launcher makes it). */
7301
+ function whereProblem(folder) {
7302
+ if (folder.startsWith("~")) return "type the whole folder path (the default shown is one), not one starting with ~";
7303
+ return folder === "" ? "say which folder the app goes in" : void 0;
7230
7304
  }
7231
7305
  /** A name for an app made from a registry id: its last part (`acrylblends.notes-desktop` gives `notes-desktop`). */
7232
7306
  const nameFromId = (id) => id.split(".").at(-1).replace(/[^a-z0-9-]/gu, "-").replace(/^[^a-z]+/u, "") || "my-app";
@@ -7258,30 +7332,52 @@ const JOURNEYS = Object.freeze([
7258
7332
  id: "create",
7259
7333
  title: "Create an app",
7260
7334
  summary: "a new app, installed and started",
7261
- steps: [text("name", "Name of the app", {
7262
- initial: () => "my-app",
7263
- check: appNameProblem
7264
- }), choose("starter", "Start from", () => STARTERS)],
7265
- command: (answers) => acryl([
7266
- "new",
7267
- answers.name,
7268
- answers.starter
7269
- ])
7335
+ steps: [
7336
+ text("where", "Which folder should it live in", {
7337
+ initial: (_answers, context) => context.defaultAppsFolder?.() ?? ".",
7338
+ hint: "a new folder is made if needed; Enter keeps the suggestion",
7339
+ check: whereProblem
7340
+ }),
7341
+ text("name", "Name of the app", {
7342
+ initial: () => "my-app",
7343
+ check: appNameProblem
7344
+ }),
7345
+ choose("starter", "Start from", () => STARTERS)
7346
+ ],
7347
+ command: (answers) => ({
7348
+ ...acryl([
7349
+ "new",
7350
+ answers.name,
7351
+ answers.starter
7352
+ ], answers.where),
7353
+ ensureCwd: answers.where !== "."
7354
+ })
7270
7355
  },
7271
7356
  {
7272
7357
  id: "blend",
7273
7358
  title: "Install a Blend",
7274
7359
  summary: "a ready app from the registry",
7275
- steps: [choose("blend", "Which Blend", (context) => context.listBlends(), { empty: "The registry could not be read. Check the network and try again." }), text("name", "Name of the app", {
7276
- initial: (answers) => nameFromId(answers.blend),
7277
- check: appNameProblem
7278
- })],
7279
- command: (answers) => acryl([
7280
- "new",
7281
- answers.name,
7282
- "--from",
7283
- answers.blend
7284
- ])
7360
+ steps: [
7361
+ choose("blend", "Which Blend", (context) => context.listBlends(), { empty: "The registry could not be read. Check the network and try again." }),
7362
+ text("where", "Which folder should it live in", {
7363
+ initial: (_answers, context) => context.defaultAppsFolder?.() ?? ".",
7364
+ hint: "a new folder is made if needed; Enter keeps the suggestion",
7365
+ check: whereProblem
7366
+ }),
7367
+ text("name", "Name of the app", {
7368
+ initial: (answers) => nameFromId(answers.blend),
7369
+ check: appNameProblem
7370
+ })
7371
+ ],
7372
+ command: (answers) => ({
7373
+ ...acryl([
7374
+ "new",
7375
+ answers.name,
7376
+ "--from",
7377
+ answers.blend
7378
+ ], answers.where),
7379
+ ensureCwd: answers.where !== "."
7380
+ })
7285
7381
  },
7286
7382
  {
7287
7383
  id: "open",
@@ -7326,6 +7422,31 @@ const JOURNEYS = Object.freeze([
7326
7422
  steps: [chooseApp],
7327
7423
  command: (answers) => acryl(["update"], answers.app)
7328
7424
  },
7425
+ {
7426
+ id: "add",
7427
+ title: "Add an app folder",
7428
+ summary: "put an app you already have in the list",
7429
+ steps: [text("folder", "The app's folder", {
7430
+ hint: "a folder with a blend.yaml in it",
7431
+ check: (folder, context) => folder.trim() === "" ? "say which folder" : context.exists(`${folder}/blend.yaml`) ? void 0 : `no blend.yaml in ${folder}: this is not an app folder`
7432
+ })],
7433
+ command: (answers) => acryl([
7434
+ "apps",
7435
+ "add",
7436
+ answers.folder
7437
+ ])
7438
+ },
7439
+ {
7440
+ id: "model",
7441
+ title: "Set up a model",
7442
+ summary: "your DeepSeek key, once, for every app",
7443
+ steps: [],
7444
+ command: () => acryl([
7445
+ "model",
7446
+ "set",
7447
+ "deepseek"
7448
+ ])
7449
+ },
7329
7450
  {
7330
7451
  id: "check",
7331
7452
  title: "Check this machine",
@@ -7334,11 +7455,11 @@ const JOURNEYS = Object.freeze([
7334
7455
  command: () => acryl(["blends", "preflight"])
7335
7456
  },
7336
7457
  {
7337
- id: "code",
7338
- title: "Open ACRYL Code",
7339
- summary: "the coding IDE, in this terminal",
7340
- steps: [],
7341
- command: () => acryl(["code"])
7458
+ id: "ade",
7459
+ title: "Open ACRYL ADE",
7460
+ summary: "the agent development environment: browser, window or terminal",
7461
+ steps: [choose("surface", "Open it in", () => ADE_SURFACES)],
7462
+ command: (answers) => acryl(answers.surface === "web" ? ["ade"] : ["ade", `--${answers.surface}`])
7342
7463
  }
7343
7464
  ]);
7344
7465
  /** The journey with this id; throws for an unknown one, which is a bug in the face that asked. */
@@ -7353,17 +7474,60 @@ function commandLine(command) {
7353
7474
  const line = [command.program, ...command.args].map(quote).join(" ");
7354
7475
  return command.cwd === "." ? line : `cd ${quote(command.cwd)} && ${line}`;
7355
7476
  }
7477
+ // plugins/acryl-launcher/apps-command.js
7478
+ /** Run it; `out` and `err` get lines. Returns the exit code. */
7479
+ function runAppsCommand(argv, { home, cwd, out = () => {}, err = () => {} }) {
7480
+ const [verb = "list", ...rest] = argv;
7481
+ try {
7482
+ if (verb === "list") {
7483
+ const apps = readApps(home);
7484
+ if (apps.length === 0) out("No apps yet. Make one with: acryl new <name> or add a folder: acryl apps add <folder>");
7485
+ for (const app of apps) out(`${app.id} ${inspectApp(app).state} ${app.blend || "-"} ${app.path}`);
7486
+ return 0;
7487
+ }
7488
+ if (verb === "add") {
7489
+ if (rest.length === 0) {
7490
+ err("acryl apps add needs the app folder, for example: acryl apps add ./shop");
7491
+ return 2;
7492
+ }
7493
+ const { entry, added } = addApp(home, { path: rest[0].startsWith("/") || /^[a-z]:[\\/]/iu.test(rest[0]) ? rest[0] : `${cwd}/${rest[0]}` });
7494
+ out(added ? `Added ${entry.id}: ${entry.path}` : `${entry.id} is already in the list: ${entry.path}`);
7495
+ return 0;
7496
+ }
7497
+ if (verb === "remove") {
7498
+ if (rest.length === 0) {
7499
+ err("acryl apps remove needs the app id (see: acryl apps)");
7500
+ return 2;
7501
+ }
7502
+ if (!removeApp(home, rest[0])) {
7503
+ err(`no app "${rest[0]}" in the list (see: acryl apps)`);
7504
+ return 1;
7505
+ }
7506
+ out(`Removed ${rest[0]} from the list. Its folder is untouched.`);
7507
+ return 0;
7508
+ }
7509
+ err(`acryl apps: unknown "${verb}". Use: acryl apps [add <folder> | remove <id>]`);
7510
+ return 2;
7511
+ } catch (cause) {
7512
+ err(`acryl apps: ${cause instanceof Error ? cause.message : String(cause)}`);
7513
+ return 1;
7514
+ }
7515
+ }
7356
7516
  // plugins/acryl-launcher/session.js
7357
7517
  /**
7358
7518
  * @param {string} journeyId one of JOURNEYS
7359
7519
  * @param {{ exists(path: string): boolean, listApps(): Promise<object[]> | object[], listBlends(): Promise<object[]> | object[],
7360
7520
  * listPlugins(app: string): Promise<object[]> | object[] }} context where the lists come from (node-context.js, or a fake)
7361
7521
  */
7362
- function createSession(journeyId, context) {
7522
+ function createSession(journeyId, context, preset = {}) {
7363
7523
  const { steps, command, title } = journey(journeyId);
7364
7524
  const answers = {};
7365
7525
  let state;
7366
- async function enter(index, error) {
7526
+ async function enter(index, error, backwards = false) {
7527
+ while (index < steps.length && steps[index].id in preset && !error && !backwards) {
7528
+ answers[steps[index].id] = preset[steps[index].id];
7529
+ index += 1;
7530
+ }
7367
7531
  if (index >= steps.length) {
7368
7532
  const next = command({ ...answers });
7369
7533
  state = Object.freeze({
@@ -7391,7 +7555,7 @@ function createSession(journeyId, context) {
7391
7555
  ...options.length === 0 ? { empty: step.empty ?? "Nothing to choose from." } : {}
7392
7556
  });
7393
7557
  } else {
7394
- const initial = answers[step.id] ?? step.initial?.({ ...answers }) ?? "";
7558
+ const initial = answers[step.id] ?? step.initial?.({ ...answers }, context) ?? "";
7395
7559
  state = Object.freeze({
7396
7560
  ...base,
7397
7561
  initial
@@ -7422,12 +7586,198 @@ function createSession(journeyId, context) {
7422
7586
  },
7423
7587
  /** One step back; undefined when already at the first step (the face goes back to the list of journeys). */
7424
7588
  async back() {
7425
- const index = state?.kind === "ready" ? steps.length - 1 : (state?.index ?? 0) - 1;
7589
+ let index = state?.kind === "ready" ? steps.length - 1 : (state?.index ?? 0) - 1;
7590
+ while (index >= 0 && steps[index].id in preset) index -= 1;
7426
7591
  if (index < 0) return void 0;
7427
- return enter(index);
7592
+ return enter(index, void 0, true);
7428
7593
  }
7429
7594
  };
7430
7595
  }
7596
+ // plugins/acryl-launcher/model-key.js
7597
+ const MODEL_FILE = "model.json";
7598
+ const PROVIDERS = Object.freeze(["deepseek", "orcarouter"]);
7599
+ /** ACRYL's referral link at OrcaRouter: ACRYL earns a share of what a person who signs up through it spends, who pays nothing extra. */
7600
+ const ORCAROUTER_REFERRAL_URL = "https://www.orcarouter.ai/ref/ref_2bfa348e557d434a67c1";
7601
+ const PROVIDER = Object.freeze({
7602
+ deepseek: {
7603
+ label: "DeepSeek",
7604
+ env: "DEEPSEEK_API_KEY",
7605
+ problem: (key) => (!key.startsWith("sk-") || key.length < 20) && "a DeepSeek key starts with sk- and is longer than this"
7606
+ },
7607
+ orcarouter: {
7608
+ label: "OrcaRouter",
7609
+ env: "ORCA_KEY",
7610
+ problem: (key) => (!key.startsWith("sk-orca-") || key.length < 20) && "an OrcaRouter key starts with sk-orca- and is longer than this"
7611
+ }
7612
+ });
7613
+ /** Where a person gets a key: said whenever the key is missing or about to be asked for. */
7614
+ const getKeyText = (provider) => provider === "orcarouter" ? `Get an OrcaRouter key at ${ORCAROUTER_REFERRAL_URL} (a referral link: ACRYL earns a share of what you spend there, you pay nothing extra).` : void 0;
7615
+ /** Why `key` cannot be a key for `provider`, or undefined when it looks like one (a typo is caught here, not on the first failed answer). */
7616
+ function keyProblem(key, provider = "deepseek") {
7617
+ if (key === "") return "the key is empty";
7618
+ if (/\s/u.test(key)) return "the key has spaces or line breaks in it: paste only the key";
7619
+ return PROVIDER[provider].problem(key) || void 0;
7620
+ }
7621
+ function readAll(home) {
7622
+ try {
7623
+ const value = JSON.parse(readFileSync(join(home, MODEL_FILE), "utf8"));
7624
+ return value !== null && typeof value === "object" ? value : {};
7625
+ } catch {
7626
+ return {};
7627
+ }
7628
+ }
7629
+ /** The stored key, or undefined. */
7630
+ function readModelKey(home, provider = "deepseek") {
7631
+ const value = readAll(home)[provider];
7632
+ return typeof value === "string" && value !== "" ? value : void 0;
7633
+ }
7634
+ function writeAll(home, keys) {
7635
+ mkdirSync(home, { recursive: true });
7636
+ const file = join(home, MODEL_FILE);
7637
+ const temporary = `${file}.${String(process.pid)}.tmp`;
7638
+ writeFileSync(temporary, `${JSON.stringify(keys)}\n`, { mode: 384 });
7639
+ chmodSync(temporary, 384);
7640
+ renameSync(temporary, file);
7641
+ }
7642
+ /** Store the key beside the other providers' keys (owner-only file, written whole or not at all). */
7643
+ function saveModelKey(home, key, provider = "deepseek") {
7644
+ const problem = keyProblem(key, provider);
7645
+ if (problem) throw new Error(problem);
7646
+ writeAll(home, {
7647
+ ...readAll(home),
7648
+ [provider]: key
7649
+ });
7650
+ }
7651
+ /** Forget one provider's key, or every key when no provider is named; returns whether there was one. */
7652
+ function clearModelKey(home, provider) {
7653
+ if (provider === void 0) {
7654
+ const had = PROVIDERS.some((name) => readModelKey(home, name) !== void 0);
7655
+ rmSync(join(home, MODEL_FILE), { force: true });
7656
+ return had;
7657
+ }
7658
+ const keys = readAll(home);
7659
+ const had = readModelKey(home, provider) !== void 0;
7660
+ delete keys[provider];
7661
+ if (had) writeAll(home, keys);
7662
+ return had;
7663
+ }
7664
+ /** `sk-...1234`: enough to tell two keys apart, never enough to use one. */
7665
+ const maskKey = (key) => `${key.slice(0, 3)}...${key.slice(-4)}`;
7666
+ /**
7667
+ * What a started app should have in its environment: each stored key, unless the environment already names one (an explicit
7668
+ * DEEPSEEK_API_KEY or ORCA_KEY wins, so a person's own export is never overridden by the stored one).
7669
+ */
7670
+ function modelEnv(home, env = {}) {
7671
+ const extra = {};
7672
+ for (const provider of PROVIDERS) {
7673
+ const name = PROVIDER[provider].env;
7674
+ const key = env[name] ? void 0 : readModelKey(home, provider);
7675
+ if (key) extra[name] = key;
7676
+ }
7677
+ return extra;
7678
+ }
7679
+ const USAGE = "acryl model [set deepseek | set orcarouter | clear [deepseek | orcarouter]]";
7680
+ /** `acryl model ...`. `readSecret()` asks for the key without echoing it. Returns the exit code. */
7681
+ async function runModelCommand(argv, { home, env = {}, out = () => {}, err = () => {}, readSecret }) {
7682
+ const [verb = "status", named, ...rest] = argv;
7683
+ try {
7684
+ if (verb === "status") {
7685
+ for (const provider of PROVIDERS) {
7686
+ const { label, env: name } = PROVIDER[provider];
7687
+ const key = readModelKey(home, provider);
7688
+ out(key ? `${label} key: set (${maskKey(key)}). Every app that acryl starts gets it.` : `${label} key: not set. Set it with: acryl model set ${provider}`);
7689
+ if (!key && getKeyText(provider)) out(getKeyText(provider));
7690
+ if (env[name]) out(`${name} is also set in this environment and wins over the stored key.`);
7691
+ }
7692
+ return 0;
7693
+ }
7694
+ if (verb === "clear") {
7695
+ if (named !== void 0 && !PROVIDERS.includes(named)) {
7696
+ err(`acryl model clear: unknown provider "${named}". Use: ${USAGE}`);
7697
+ return 2;
7698
+ }
7699
+ const label = named === void 0 ? "model" : PROVIDER[named].label;
7700
+ out(clearModelKey(home, named) ? `The stored ${label} key is removed.` : `There was no stored ${label} key.`);
7701
+ return 0;
7702
+ }
7703
+ if (verb === "set") {
7704
+ const provider = named ?? "deepseek";
7705
+ if (!PROVIDERS.includes(provider)) {
7706
+ err(`acryl model set: only ${PROVIDERS.join(" and ")} are supported, not "${provider}"`);
7707
+ return 2;
7708
+ }
7709
+ const { label, env: name } = PROVIDER[provider];
7710
+ if (getKeyText(provider)) out(getKeyText(provider));
7711
+ const key = (await readSecret(`${label} API key (typing is hidden): `)).trim();
7712
+ saveModelKey(home, key, provider);
7713
+ out(`Saved (${maskKey(key)}). Every app that acryl starts now gets it as ${name}.`);
7714
+ if (provider === "orcarouter") out("Apps do not send their model requests through OrcaRouter yet; for now the key is stored and handed to apps.");
7715
+ return 0;
7716
+ }
7717
+ err(`acryl model: unknown "${verb}". Use: ${USAGE}`);
7718
+ return 2;
7719
+ } catch (cause) {
7720
+ err(`acryl model: ${cause instanceof Error ? cause.message : String(cause)}`);
7721
+ return 1;
7722
+ }
7723
+ }
7724
+ /** Terminal palettes by background: `dark` for a dark terminal (the default), `light` for a light one. */
7725
+ const palettes = {
7726
+ dark: {
7727
+ primary: "#4F6BFE",
7728
+ secondary: "#38BDF8",
7729
+ accent: "#818CF8",
7730
+ reasoning: "#A855F7",
7731
+ success: "#34D399",
7732
+ warning: "#FBBF24",
7733
+ error: "#F87171",
7734
+ info: "#4F6BFE",
7735
+ muted: "#94A3B8"
7736
+ },
7737
+ light: {
7738
+ primary: "#3652D9",
7739
+ secondary: "#0369A1",
7740
+ accent: "#4F46E5",
7741
+ reasoning: "#7E22CE",
7742
+ success: "#047857",
7743
+ warning: "#B45309",
7744
+ error: "#DC2626",
7745
+ info: "#3652D9",
7746
+ muted: "#64748B"
7747
+ }
7748
+ };
7749
+ // plugins/acryl-ui-tui/scheme.js
7750
+ const ESC$1 = "\x1B";
7751
+ const paint$1 = (hex) => {
7752
+ const n = Number.parseInt(hex.slice(1), 16);
7753
+ return (text) => `${ESC$1}[38;2;${n >> 16 & 255};${n >> 8 & 255};${n & 255}m${text}${ESC$1}[0m`;
7754
+ };
7755
+ /** The theme for a palette mode (`dark` or `light`), in the shape `createTuiUi` takes. */
7756
+ function paletteTheme(mode = "dark") {
7757
+ const palette = palettes[mode] ?? palettes.dark;
7758
+ return Object.freeze({
7759
+ mode: palettes[mode] ? mode : "dark",
7760
+ color: (role) => paint$1(palette[role] ?? palette.muted)
7761
+ });
7762
+ }
7763
+ /** True when the person chose a palette (`ACRYL_TUI_THEME`), so the terminal's own report is not followed. */
7764
+ const isPaletteForced = (env = process.env) => ["dark", "light"].includes(env.ACRYL_TUI_THEME?.trim().toLowerCase() ?? "");
7765
+ /** The palette before the terminal answers: `ACRYL_TUI_THEME`, then the background index in `COLORFGBG`, then dark. */
7766
+ function paletteModeFromEnv(env = process.env) {
7767
+ const forced = env.ACRYL_TUI_THEME?.trim().toLowerCase();
7768
+ if (forced === "dark" || forced === "light") return forced;
7769
+ const background = env.COLORFGBG?.split(";").pop();
7770
+ if (background !== void 0 && /^\d+$/u.test(background)) {
7771
+ const index = Number(background);
7772
+ return index === 7 || index >= 9 && index <= 15 ? "light" : "dark";
7773
+ }
7774
+ return "dark";
7775
+ }
7776
+ /** Light or dark from the background a terminal reports (0-255 channels), by relative luminance (ITU-R BT.709); undefined when none was reported. */
7777
+ function schemeOfBackground(background) {
7778
+ if (background === void 0) return void 0;
7779
+ return (.2126 * background.r + .7152 * background.g + .0722 * background.b) / 255 >= .5 ? "light" : "dark";
7780
+ }
7431
7781
  // plugins/acryl-ui-tui/index.js
7432
7782
  const ESC = "\x1B";
7433
7783
  const paint = (hex) => {
@@ -7716,6 +8066,51 @@ const { Stack, Card, Field, SettingsRow, SelectField, Segmented, Tabs, SwitchFie
7716
8066
  // apps/acryl-launcher-tui/view.js
7717
8067
  const bold = (text) => `\x1b[1m${text}\x1b[22m`;
7718
8068
  const MENU_ROWS = JOURNEYS.length;
8069
+ const HOME_ROWS = 12;
8070
+ /** The three kinds of app (spec 050 D10), in the words the desktop screen uses; CLI (TUI) is listed but not yet made. */
8071
+ const SURFACE_LABEL = {
8072
+ web: "Web",
8073
+ desktop: "Desktop",
8074
+ tui: "CLI (TUI)"
8075
+ };
8076
+ /** The rows of the home list after the apps (the mockup's footer: + New app, Blends store, Health), each opening one journey. */
8077
+ const ACTIONS = Object.freeze([
8078
+ {
8079
+ value: "journey:create",
8080
+ label: "+ New app",
8081
+ description: "asks where it goes, suggests ~/ACRYL"
8082
+ },
8083
+ {
8084
+ value: "journey:blend",
8085
+ label: "Blends store",
8086
+ description: "install a ready app from the registry"
8087
+ },
8088
+ {
8089
+ value: "journey:add",
8090
+ label: "Add an app folder",
8091
+ description: "an app you already have"
8092
+ },
8093
+ {
8094
+ value: "journey:model",
8095
+ label: "Set up a model",
8096
+ description: "your DeepSeek key, once, for every app"
8097
+ },
8098
+ {
8099
+ value: "journey:check",
8100
+ label: "Health",
8101
+ description: "Node, npm, git, an agent, a free port"
8102
+ },
8103
+ {
8104
+ value: "journey:ade",
8105
+ label: "ACRYL ADE",
8106
+ description: "the agentic development environment, in this terminal"
8107
+ },
8108
+ {
8109
+ value: "more",
8110
+ label: "All things to do",
8111
+ description: "every journey, including pull and share a plugin"
8112
+ }
8113
+ ]);
7719
8114
  function createLauncherView({ context, theme, requestRender = () => {}, finish }) {
7720
8115
  const ui = createTuiUi(theme);
7721
8116
  const c = (role) => theme.color(role);
@@ -7736,16 +8131,43 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7736
8131
  done = true;
7737
8132
  finish(result);
7738
8133
  };
7739
- function showMenu(selected) {
8134
+ const apps = () => context.registeredApps?.() ?? [];
8135
+ const begin = (journeyId, preset) => follow(createSession(journeyId, context, preset), (session) => session.begin());
8136
+ /** The first screen (spec 050 D6): the apps on this machine, then the things to do. Enter opens an app; u updates it; p pulls a plugin into it. */
8137
+ function showHome(selected) {
8138
+ const listed = apps();
8139
+ const rows = [...listed.map((app) => ({
8140
+ value: `app:${app.path}`,
8141
+ label: app.id,
8142
+ description: `${app.state} ${SURFACE_LABEL[app.surface] ?? "Web"} ${app.blend || "Blend"}`,
8143
+ detail: app.state === "missing" ? `${app.path} - the folder is gone` : app.path
8144
+ })), ...ACTIONS];
8145
+ list = new SelectList(rows, Math.min(HOME_ROWS, rows.length), listTheme);
8146
+ list.setSelectedIndex(Math.max(0, rows.findIndex((row) => row.value === selected)));
8147
+ list.onSelect = (item) => {
8148
+ if (item.value === "more") return showMore();
8149
+ if (item.value.startsWith("journey:")) return begin(item.value.slice(8));
8150
+ const app = listed.find((entry) => `app:${entry.path}` === item.value);
8151
+ if (app?.state === "missing") return void 0;
8152
+ return begin("open", { app: app.path });
8153
+ };
8154
+ field = void 0;
8155
+ screen = {
8156
+ kind: "home",
8157
+ apps: listed
8158
+ };
8159
+ }
8160
+ /** Every journey, for the ones the home list does not name. */
8161
+ function showMore(selected) {
7740
8162
  list = new SelectList(JOURNEYS.map((entry) => ({
7741
8163
  value: entry.id,
7742
8164
  label: entry.title,
7743
8165
  description: entry.summary
7744
8166
  })), MENU_ROWS, listTheme);
7745
8167
  if (selected) list.setSelectedIndex(Math.max(0, JOURNEYS.findIndex((entry) => entry.id === selected)));
7746
- list.onSelect = (item) => follow(createSession(item.value, context), (session) => session.begin());
8168
+ list.onSelect = (item) => begin(item.value);
7747
8169
  field = void 0;
7748
- screen = { kind: "menu" };
8170
+ screen = { kind: "more" };
7749
8171
  }
7750
8172
  /** Wait for the session's next state, showing that something is happening meanwhile; undefined (back from the first step) is the menu. */
7751
8173
  function follow(session, step) {
@@ -7755,7 +8177,7 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7755
8177
  };
7756
8178
  requestRender();
7757
8179
  pending = Promise.resolve(step(session)).then((state) => {
7758
- if (state === void 0) showMenu(session.id);
8180
+ if (state === void 0) showHome();
7759
8181
  else present(session, state);
7760
8182
  }, (cause) => {
7761
8183
  screen = {
@@ -7789,7 +8211,14 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7789
8211
  };
7790
8212
  }
7791
8213
  function body() {
7792
- if (screen.kind === "menu") return [ui.Card({
8214
+ if (screen.kind === "home") {
8215
+ const title = screen.apps.length === 0 ? "No apps yet - start one" : `Your apps (${String(screen.apps.length)})`;
8216
+ return [ui.Card({
8217
+ title,
8218
+ body: [list, highlighted(list, "detail")]
8219
+ })];
8220
+ }
8221
+ if (screen.kind === "more") return [ui.Card({
7793
8222
  title: "What do you want to do?",
7794
8223
  body: [list]
7795
8224
  })];
@@ -7808,7 +8237,7 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7808
8237
  body: [
7809
8238
  "This runs now:",
7810
8239
  "",
7811
- c("primary")(bold(state.line)),
8240
+ wrapped(c("primary")(bold(state.line))),
7812
8241
  "",
7813
8242
  c("muted")("Next time you can type it yourself.")
7814
8243
  ]
@@ -7826,10 +8255,18 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7826
8255
  body: parts
7827
8256
  })];
7828
8257
  }
7829
- function highlighted(from) {
8258
+ /** A line that wraps at the card's width instead of being cut: the command shown must be the whole command, however long the folder. */
8259
+ function wrapped(text) {
8260
+ return {
8261
+ render: (width) => wrapTextWithAnsi(text, width),
8262
+ invalidate() {}
8263
+ };
8264
+ }
8265
+ function highlighted(from, key = "description") {
7830
8266
  return {
7831
8267
  render(width) {
7832
- const description = from.getSelectedItem()?.description;
8268
+ const item = from.getSelectedItem();
8269
+ const description = key === "detail" ? item?.detail : item?.description;
7833
8270
  if (!description) return [];
7834
8271
  const wrapped = wrapTextWithAnsi(c("muted")(description), width);
7835
8272
  const shown = wrapped.slice(0, 3);
@@ -7840,19 +8277,20 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7840
8277
  };
7841
8278
  }
7842
8279
  function keysHint() {
7843
- if (screen.kind === "menu") return "Up/Down choose Enter go Esc quit";
8280
+ if (screen.kind === "home") return "Up/Down choose Enter open u update p pull a plugin Esc quit";
8281
+ if (screen.kind === "more") return "Up/Down choose Enter go Esc back";
7844
8282
  if (screen.kind === "session" && screen.state.kind === "ready") return "Enter run Esc back Ctrl-C quit";
7845
8283
  if (screen.kind === "session" && screen.state.step?.kind === "text") return "Enter next Esc back Ctrl-C quit";
7846
8284
  return "Up/Down choose Enter next Esc back Ctrl-C quit";
7847
8285
  }
7848
- showMenu();
8286
+ showHome();
7849
8287
  return {
7850
8288
  /** Settles when the last answer has been handled (tests wait on it; the terminal just re-renders). */
7851
8289
  get settled() {
7852
8290
  return pending;
7853
8291
  },
7854
8292
  render(width) {
7855
- const header = `${c("primary")(bold("ACRYL"))} ${c("muted")("every step offered, no commands to remember")}`;
8293
+ const header = `${c("primary")(bold("ACRYL"))} ${c("muted")("every app on this machine, every step offered")}`;
7856
8294
  return ui.Stack({
7857
8295
  children: [
7858
8296
  header,
@@ -7868,7 +8306,8 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7868
8306
  if (matchesKey(data, "ctrl+c")) return close(void 0);
7869
8307
  if (screen.kind === "busy") return;
7870
8308
  if (matchesKey(data, "escape")) {
7871
- if (screen.kind === "menu") return close(void 0);
8309
+ if (screen.kind === "home") return close(void 0);
8310
+ if (screen.kind === "more") return showHome("more");
7872
8311
  return follow(screen.session, (session) => session.back());
7873
8312
  }
7874
8313
  if (screen.kind === "session" && screen.state.kind === "ready") {
@@ -7878,6 +8317,10 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7878
8317
  });
7879
8318
  return;
7880
8319
  }
8320
+ if (screen.kind === "home" && (data === "u" || data === "p")) {
8321
+ const row = list.getSelectedItem();
8322
+ if (row?.value.startsWith("app:")) return begin(data === "u" ? "update" : "pull", { app: row.value.slice(4) });
8323
+ }
7881
8324
  (field ?? list)?.handleInput(data);
7882
8325
  requestRender();
7883
8326
  },
@@ -7888,7 +8331,8 @@ function createLauncherView({ context, theme, requestRender = () => {}, finish }
7888
8331
  };
7889
8332
  }
7890
8333
  // apps/acryl-launcher-tui/run.js
7891
- function runLauncher({ cwd = process.cwd(), env = process.env, terminal = new ProcessTerminal() } = {}) {
8334
+ /** `home` is ACRYL's own folder (~/.acryl) and `appsFolder` where new apps are suggested (~/ACRYL): the selector decides both, this face only passes them on. */
8335
+ function runLauncher({ cwd = process.cwd(), env = process.env, terminal = new ProcessTerminal(), home, appsFolder } = {}) {
7892
8336
  const tui = new TuiMainScreen(terminal);
7893
8337
  let mode = paletteModeFromEnv(env);
7894
8338
  const theme = {
@@ -7905,7 +8349,10 @@ function runLauncher({ cwd = process.cwd(), env = process.env, terminal = new Pr
7905
8349
  };
7906
8350
  return new Promise((resolve) => {
7907
8351
  const view = createLauncherView({
7908
- context: nodeContext(cwd),
8352
+ context: nodeContext(cwd, {
8353
+ home,
8354
+ appsFolder
8355
+ }),
7909
8356
  theme,
7910
8357
  requestRender: () => tui.requestRender(),
7911
8358
  finish: (result) => {
@@ -7930,4 +8377,4 @@ function runLauncher({ cwd = process.cwd(), env = process.env, terminal = new Pr
7930
8377
  }
7931
8378
  });
7932
8379
  }
7933
- export { runLauncher };
8380
+ export { addApp, modelEnv, runAppsCommand, runLauncher, runModelCommand };