acryl 0.1.16 → 0.1.18

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/bin.js CHANGED
@@ -4,14 +4,13 @@ import { fileURLToPath } from "node:url";
4
4
  import { existsSync, realpathSync, writeFileSync } from "node:fs";
5
5
  import { dirname, join, relative, resolve } from "node:path";
6
6
  import { execFile, spawn } from "node:child_process";
7
- import { createHash, randomBytes, randomUUID } from "node:crypto";
7
+ import { randomUUID } from "node:crypto";
8
8
  import { BlockAssembler, createUserMessage } from "@deepseek-ai/dsh-llm";
9
9
  import { SessionId } from "@deepseek-ai/dsh-session";
10
10
  import { DEFAULT_PROFILE_BUNDLES, boot, composeEntries, healProfilesModuleFallback, initProfile, loadProfile, resolveProfileDir } from "@deepseek-ai/dsh-app-boot";
11
11
  import { diffLines } from "diff";
12
12
  import { Container, Editor, HStack, Key, KeybindingsManager, ProcessTerminal, ScrollView, TUI_KEYBINDINGS, Text, TuiAltScreen, VStack, matchesKey, setKeybindings, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
13
13
  import { readdir } from "node:fs/promises";
14
- import { createServer } from "node:http";
15
14
  import { ManualCompactionError } from "@deepseek-ai/dsh-compaction";
16
15
  import { GoalError } from "@deepseek-ai/dsh-goal";
17
16
  //#region src/cli/node-launcher.ts
@@ -71,6 +70,55 @@ function provideCmdline(ctx, host) {
71
70
  process.stdout, process.stderr;
72
71
  //#endregion
73
72
  //#region ../acryl-harness-runtime/lib/index.mjs
73
+ const shippedPresetsDir = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "deepseek-harness", "packages", "preset", "agent-presets", "presets");
74
+ const authorizationCapabilityPatches = [{
75
+ id: "system-prompt",
76
+ name: "@deepseek-ai/dsh-system-prompt",
77
+ config: { persona: "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}." }
78
+ }, { insert: [
79
+ {
80
+ id: "agent-presets",
81
+ name: "@deepseek-ai/dsh-agent-presets",
82
+ config: {
83
+ default: "standard",
84
+ roots: existsSync(shippedPresetsDir) ? [{
85
+ path: shippedPresetsDir,
86
+ trust: "system"
87
+ }] : [],
88
+ includeShippedRoot: false,
89
+ includeUserRoot: true
90
+ }
91
+ },
92
+ {
93
+ id: "session-stats",
94
+ name: "@deepseek-ai/dsh-session-stats"
95
+ },
96
+ {
97
+ id: "authorization",
98
+ name: "@deepseek-ai/dsh-authorization"
99
+ }
100
+ ] }];
101
+ const NON_TUI_SHARED_ROW_IDS = /* @__PURE__ */ new Set(["authorization"]);
102
+ function selectNonTuiCapabilityPatches(patches) {
103
+ return patches.flatMap((patch) => {
104
+ if (!("insert" in patch) || !Array.isArray(patch.insert)) return [];
105
+ const insert = patch.insert.filter((row) => NON_TUI_SHARED_ROW_IDS.has(row.id));
106
+ return insert.length === 0 ? [] : [{ insert }];
107
+ });
108
+ }
109
+ const ACRYL_CODING_CAPABILITIES = [{
110
+ id: "authorization",
111
+ surfaces: [
112
+ "tui",
113
+ "web",
114
+ "desktop"
115
+ ],
116
+ loaderPatches: authorizationCapabilityPatches
117
+ }];
118
+ function createAcrylCodingCapabilityPatches(surfaces) {
119
+ const includeSharedCodingRows = surfaces.has("tui");
120
+ return structuredClone(ACRYL_CODING_CAPABILITIES.filter((capability) => capability.surfaces.some((surface) => surfaces.has(surface))).flatMap((capability) => includeSharedCodingRows ? capability.loaderPatches : selectNonTuiCapabilityPatches(capability.loaderPatches)));
121
+ }
74
122
  function contentText(content) {
75
123
  return content.filter((block) => {
76
124
  return block.type === "text" && typeof block.text === "string";
@@ -272,27 +320,6 @@ function createAcrylSessionBridge(ctx, options) {
272
320
  }
273
321
  const dshInstallAnchor = createRequire(import.meta.url).resolve("@deepseek-ai/dsh/package.json");
274
322
  const profileRoot = "[]\n";
275
- const shippedPresetsDir = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "deepseek-harness", "packages", "preset", "agent-presets", "presets");
276
- const ACRYL_RUNTIME_ROWS = [{
277
- id: "system-prompt",
278
- name: "@deepseek-ai/dsh-system-prompt",
279
- config: { persona: "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}." }
280
- }, { insert: [{
281
- id: "agent-presets",
282
- name: "@deepseek-ai/dsh-agent-presets",
283
- config: {
284
- default: "standard",
285
- roots: existsSync(shippedPresetsDir) ? [{
286
- path: shippedPresetsDir,
287
- trust: "system"
288
- }] : [],
289
- includeShippedRoot: false,
290
- includeUserRoot: true
291
- }
292
- }, {
293
- id: "session-stats",
294
- name: "@deepseek-ai/dsh-session-stats"
295
- }] }];
296
323
  /** Boot one normal pinned-Harness ACRYL profile in a single Cordis root. */
297
324
  async function bootAcrylHarnessProfile(options) {
298
325
  if (options.profile.trim() === "") throw new Error("ACRYL Harness profile must not be empty");
@@ -303,7 +330,7 @@ async function bootAcrylHarnessProfile(options) {
303
330
  writeFileSync(rootConfig, profileRoot);
304
331
  const patches = structuredClone([
305
332
  ...profile.layers.flatMap((layer) => layer.patches),
306
- ...ACRYL_RUNTIME_ROWS,
333
+ ...createAcrylCodingCapabilityPatches(/* @__PURE__ */ new Set(["tui"])),
307
334
  ...profile.patches
308
335
  ]);
309
336
  if (composeEntries([patches]).find((entry) => entry.id === "hmr")?.disabled !== true && !process.execArgv.includes("--expose-internals")) throw new Error("ACRYL profile enables Cordis HMR and must be launched with Node --expose-internals");
@@ -322,9 +349,9 @@ async function bootAcrylHarnessProfile(options) {
322
349
  /**
323
350
  * Boot the DSH browser surface (the `web` profile: `dsh-base` + `dsh-web-app`)
324
351
  * as one normal ACRYL runtime, so `pnpm acryl-web` serves the same DSH
325
- * HTTP/WebSocket seam the web surface always uses. The web profile already
326
- * composes the persona/agent rows ACRYL's terminal surface adds, so no
327
- * ACRYL_RUNTIME_ROWS are re-inserted (that would duplicate `system-prompt`).
352
+ * HTTP/WebSocket seam the web surface always uses. The shipped Web profile
353
+ * already owns its system prompt, agent-preset roster, and session stats, so
354
+ * the shared factory contributes only the missing authorization seam here.
328
355
  */
329
356
  async function bootAcrylWebProfile(options = {}) {
330
357
  const profileName = "web";
@@ -333,7 +360,11 @@ async function bootAcrylWebProfile(options = {}) {
333
360
  const profile = loadProfile("web", profileName, dshInstallAnchor);
334
361
  const rootConfig = join(profile.dir, "cordis.yml");
335
362
  writeFileSync(rootConfig, profileRoot);
336
- const patches = structuredClone([...profile.layers.flatMap((layer) => layer.patches), ...profile.patches]);
363
+ const patches = structuredClone([
364
+ ...profile.layers.flatMap((layer) => layer.patches),
365
+ ...createAcrylCodingCapabilityPatches(/* @__PURE__ */ new Set(["web"])),
366
+ ...profile.patches
367
+ ]);
337
368
  const cmdlineArgs = options.cmdlineArgs ?? [];
338
369
  const ctx = await boot("web", rootConfig, patches, (hostCtx) => {
339
370
  provideCmdline(hostCtx, {
@@ -440,7 +471,7 @@ const ESC = "\x1B[";
440
471
  const dim$2 = fg(theme.muted);
441
472
  const cyan$1 = fg(theme.secondary);
442
473
  const primary = fg(theme.primary);
443
- const bold$10 = (s) => `${ESC}1m${s}${ESC}0m`;
474
+ const bold$11 = (s) => `${ESC}1m${s}${ESC}0m`;
444
475
  const italic = (s) => `${ESC}3m${s}${ESC}0m`;
445
476
  const strike = (s) => `${ESC}9m${s}${ESC}0m`;
446
477
  const underline = (s) => `${ESC}4m${s}${ESC}0m`;
@@ -484,7 +515,7 @@ function looksLikeMarkdown(text) {
484
515
  /** Style links, bold, strikethrough, and emphasis in a span already known to contain no inline code. */
485
516
  function applyNonCodeInline(text) {
486
517
  let working = text.replaceAll(LINK_RE_G, (_match, label, url) => hyperlink(url, underline(primary(label))));
487
- working = working.replaceAll(BOLD_RE_G, (_match, a, b) => bold$10(a ?? b ?? ""));
518
+ working = working.replaceAll(BOLD_RE_G, (_match, a, b) => bold$11(a ?? b ?? ""));
488
519
  working = working.replaceAll(STRIKE_RE_G, (_match, t) => strike(t));
489
520
  return working.replaceAll(ITALIC_RE_G, (_match, a, b) => italic(a ?? b ?? ""));
490
521
  }
@@ -550,7 +581,7 @@ function padCell(styled, width, align) {
550
581
  }
551
582
  /** Pad one row of already-styled cells (header or body) to a single column-aligned line. */
552
583
  function formatTableRow(styledCells, widths, aligns, isHeader) {
553
- return widths.map((width, i) => padCell(isHeader ? bold$10(styledCells[i] ?? "") : styledCells[i] ?? "", width, aligns[i] ?? "left")).join(dim$2(" │ "));
584
+ return widths.map((width, i) => padCell(isHeader ? bold$11(styledCells[i] ?? "") : styledCells[i] ?? "", width, aligns[i] ?? "left")).join(dim$2(" │ "));
554
585
  }
555
586
  /** A dim horizontal rule under the header row, with a cross at each column boundary. */
556
587
  function formatTableRule(widths) {
@@ -607,7 +638,7 @@ function renderMarkdown(text) {
607
638
  if (header !== null) {
608
639
  const level = header[1].length;
609
640
  const content = applyInline(header[2]);
610
- out.push(level === 1 ? bold$10(primary(content)) : level === 2 ? bold$10(cyan$1(content)) : bold$10(content));
641
+ out.push(level === 1 ? bold$11(primary(content)) : level === 2 ? bold$11(cyan$1(content)) : bold$11(content));
611
642
  continue;
612
643
  }
613
644
  if (HR_RE.test(line)) {
@@ -1232,6 +1263,31 @@ var TuiStore = class {
1232
1263
  }
1233
1264
  } });
1234
1265
  }
1266
+ /** Open the `/login` sign-in overlay to a fresh, loading flow list. */
1267
+ openLogin() {
1268
+ this.set({ overlay: {
1269
+ kind: "login",
1270
+ login: {
1271
+ flows: void 0,
1272
+ selected: 0,
1273
+ signingIn: void 0,
1274
+ prompt: void 0,
1275
+ busy: true,
1276
+ error: void 0
1277
+ }
1278
+ } });
1279
+ }
1280
+ /** Patch the open `/login` overlay's sub-state; a no-op once it's closed. */
1281
+ updateLogin(patch) {
1282
+ if (this.state.overlay.kind !== "login") return;
1283
+ this.set({ overlay: {
1284
+ kind: "login",
1285
+ login: {
1286
+ ...this.state.overlay.login,
1287
+ ...patch
1288
+ }
1289
+ } });
1290
+ }
1235
1291
  /** Open the `/trajectory` ledger overlay. */
1236
1292
  openTrajectory() {
1237
1293
  this.set({ overlay: { kind: "trajectory" } });
@@ -1783,10 +1839,10 @@ function runSlashCommand(command, actions) {
1783
1839
  }
1784
1840
  //#endregion
1785
1841
  //#region src/tui/piTheme.ts
1786
- const bold$9 = (s) => `\x1b[1m${s}\x1b[0m`;
1842
+ const bold$10 = (s) => `\x1b[1m${s}\x1b[0m`;
1787
1843
  const selectListTheme = {
1788
1844
  selectedPrefix: fg(theme.primary),
1789
- selectedText: (s) => bold$9(fg(theme.primary)(s)),
1845
+ selectedText: (s) => bold$10(fg(theme.primary)(s)),
1790
1846
  description: fg(theme.muted),
1791
1847
  scrollInfo: fg(theme.muted),
1792
1848
  noMatch: fg(theme.muted)
@@ -2111,6 +2167,68 @@ var Spinner = class {
2111
2167
  }
2112
2168
  };
2113
2169
  //#endregion
2170
+ //#region src/tui/clipboard.ts
2171
+ /**
2172
+ * System-clipboard read, used for right-click paste. Node has no built-in
2173
+ * clipboard API, so this shells out to the platform's clipboard tool via
2174
+ * `execFile` (the same `node:child_process` approach used elsewhere for
2175
+ * platform launchers like `open`/`xdg-open`).
2176
+ * @module @tomowang/dsh-tui/tui/clipboard
2177
+ */
2178
+ function clipboardCommands() {
2179
+ switch (process.platform) {
2180
+ case "darwin": return [["pbpaste", []]];
2181
+ case "win32": return [["powershell.exe", [
2182
+ "-NoProfile",
2183
+ "-NonInteractive",
2184
+ "-Command",
2185
+ "Get-Clipboard"
2186
+ ]]];
2187
+ default: return [
2188
+ ["xclip", [
2189
+ "-selection",
2190
+ "clipboard",
2191
+ "-o"
2192
+ ]],
2193
+ ["xsel", ["--clipboard", "--output"]],
2194
+ ["wl-paste", ["--no-newline"]]
2195
+ ];
2196
+ }
2197
+ }
2198
+ /**
2199
+ * Read the system clipboard. Resolves with the clipboard text (possibly empty).
2200
+ * Rejects when no supported clipboard tool is available on this host.
2201
+ *
2202
+ * A single trailing newline is stripped: `pbpaste` prints the clipboard verbatim,
2203
+ * while `xclip`/`xsel`/`Get-Clipboard` append one, so this keeps the result
2204
+ * consistent with a native terminal paste (which inserts exactly what was copied).
2205
+ */
2206
+ function readClipboard() {
2207
+ return new Promise((resolve, reject) => {
2208
+ const commands = clipboardCommands();
2209
+ let index = 0;
2210
+ const attempt = () => {
2211
+ if (index >= commands.length) {
2212
+ reject(/* @__PURE__ */ new Error("no clipboard tool available"));
2213
+ return;
2214
+ }
2215
+ const [command, args] = commands[index];
2216
+ index += 1;
2217
+ execFile(command, args, {
2218
+ encoding: "utf8",
2219
+ maxBuffer: 10 * 1024 * 1024
2220
+ }, (error, stdout) => {
2221
+ if (error) {
2222
+ attempt();
2223
+ return;
2224
+ }
2225
+ resolve(stdout.replace(/\r?\n$/, ""));
2226
+ });
2227
+ };
2228
+ attempt();
2229
+ });
2230
+ }
2231
+ //#endregion
2114
2232
  //#region src/yly/yly-frames.generated.ts
2115
2233
  const YLY_FRAMES = {
2116
2234
  "small": [
@@ -3030,6 +3148,15 @@ var YlyPet = class {
3030
3148
  * delegate keystrokes to a field nested inside a larger custom overlay.
3031
3149
  * @module @tomowang/dsh-tui/tui/miniTextField
3032
3150
  */
3151
+ const BRACKETED_PASTE_START = "\x1B[200~";
3152
+ const BRACKETED_PASTE_END = "\x1B[201~";
3153
+ /** Extract the content of one bracketed-paste sequence, or `undefined` if `data` is not one. */
3154
+ function extractBracketedPaste(data) {
3155
+ if (!data.startsWith(BRACKETED_PASTE_START)) return void 0;
3156
+ const end = data.indexOf(BRACKETED_PASTE_END);
3157
+ if (end === -1) return void 0;
3158
+ return data.slice(6, end);
3159
+ }
3033
3160
  function emptyMiniTextField(value = "") {
3034
3161
  return {
3035
3162
  value,
@@ -3068,6 +3195,15 @@ function miniTextFieldInput(state, data) {
3068
3195
  cursor: state.cursor
3069
3196
  };
3070
3197
  }
3198
+ const paste = extractBracketedPaste(data);
3199
+ if (paste !== void 0) {
3200
+ const text = paste.replace(/[\r\n]+/g, "");
3201
+ if (text.length === 0) return state;
3202
+ return {
3203
+ value: state.value.slice(0, state.cursor) + text + state.value.slice(state.cursor),
3204
+ cursor: state.cursor + text.length
3205
+ };
3206
+ }
3071
3207
  if (data.length > 0 && !data.startsWith("\x1B") && data !== "\r" && data !== "\n" && data !== " ") return {
3072
3208
  value: state.value.slice(0, state.cursor) + data + state.value.slice(state.cursor),
3073
3209
  cursor: state.cursor + data.length
@@ -3081,11 +3217,11 @@ function renderMiniTextField(state, cursorVisible, mask) {
3081
3217
  }
3082
3218
  //#endregion
3083
3219
  //#region src/tui/modelProfile/ModelProfileOverlay.ts
3084
- const bold$8 = (s) => `\x1b[1m${s}\x1b[0m`;
3085
- const secondary$8 = fg(theme.secondary);
3086
- const muted$9 = fg(theme.muted);
3087
- const errorColor$4 = fg(theme.error);
3088
- const invert$4 = (s) => `\x1b[7m${s}\x1b[0m`;
3220
+ const bold$9 = (s) => `\x1b[1m${s}\x1b[0m`;
3221
+ const secondary$9 = fg(theme.secondary);
3222
+ const muted$10 = fg(theme.muted);
3223
+ const errorColor$5 = fg(theme.error);
3224
+ const invert$5 = (s) => `\x1b[7m${s}\x1b[0m`;
3089
3225
  var ModelProfileOverlay = class {
3090
3226
  store;
3091
3227
  actions;
@@ -3162,21 +3298,19 @@ var ModelProfileOverlay = class {
3162
3298
  }
3163
3299
  renderList(mp) {
3164
3300
  const { providers, selected, busy, error } = mp;
3165
- const lines = [bold$8(secondary$8("Model providers"))];
3166
- if (error !== void 0) lines.push(errorColor$4(error));
3167
- if (busy && providers === void 0) lines.push(muted$9("Loading…"));
3301
+ const lines = [bold$9(secondary$9("Model providers"))];
3302
+ if (error !== void 0) lines.push(errorColor$5(error));
3303
+ if (busy && providers === void 0) lines.push(muted$10("Loading…"));
3168
3304
  providers?.forEach((row, index) => {
3169
3305
  const marker = row.configured ? "● " : "○ ";
3170
3306
  const active = row.live ? " (active)" : "";
3171
3307
  const noKey = row.apiKeyConfigured ? "" : " [no api key]";
3172
- const oauthStatus = row.oauth === void 0 ? "" : row.grantConfigured ? " [oauth ✓]" : " [oauth]";
3173
3308
  const confirm = this.confirmDelete === index ? " — press d again to delete" : "";
3174
- const text = `${index === selected ? "› " : " "}${marker}${row.displayName}${active}${noKey}${oauthStatus}${confirm}`;
3175
- lines.push(index === selected ? invert$4(text) : text);
3309
+ const text = `${index === selected ? "› " : " "}${marker}${row.displayName}${active}${noKey}${confirm}`;
3310
+ lines.push(index === selected ? invert$5(text) : text);
3176
3311
  });
3177
- if (providers?.length === 0) lines.push(muted$9("No providers configured yet — press a to add one."));
3178
- const hasOauth = providers?.some((row) => row.oauth !== void 0) ?? false;
3179
- lines.push(muted$9(`↑↓ select · enter edit · a add · d delete · s set active model${hasOauth ? " · o login with oauth" : ""} · esc close`));
3312
+ if (providers?.length === 0) lines.push(muted$10("No providers configured yet — press a to add one."));
3313
+ lines.push(muted$10("↑↓ select · enter edit · a add · d delete · s set active model · esc close"));
3180
3314
  return lines;
3181
3315
  }
3182
3316
  handleListInput(data, mp) {
@@ -3213,11 +3347,6 @@ var ModelProfileOverlay = class {
3213
3347
  if (model !== void 0) this.actions.setActiveModel(row.route, model.id);
3214
3348
  return;
3215
3349
  }
3216
- if (data === "o") {
3217
- const row = providers[selected];
3218
- if (row.oauth !== void 0) this.actions.loginWithOAuth(row.route);
3219
- return;
3220
- }
3221
3350
  if (data === "d") {
3222
3351
  if (this.confirmDelete === selected) {
3223
3352
  this.confirmDelete = void 0;
@@ -3245,8 +3374,8 @@ var ModelProfileOverlay = class {
3245
3374
  baseURL: "Base URL",
3246
3375
  apiKey: draft.apiKeyConfigured ? "API key (set — leave blank to keep)" : "API key"
3247
3376
  };
3248
- const lines = [bold$8(secondary$8(draft.isNew ? "Add provider" : `Edit ${draft.displayName || draft.route}`))];
3249
- if (mp.error !== void 0) lines.push(errorColor$4(mp.error));
3377
+ const lines = [bold$9(secondary$9(draft.isNew ? "Add provider" : `Edit ${draft.displayName || draft.route}`))];
3378
+ if (mp.error !== void 0) lines.push(errorColor$5(mp.error));
3250
3379
  textFields.forEach((field, index) => {
3251
3380
  const isFocused = this.focused === index;
3252
3381
  const mask = field === "apiKey" ? "*" : void 0;
@@ -3254,10 +3383,10 @@ var ModelProfileOverlay = class {
3254
3383
  lines.push(`${prefix}${renderMiniTextField(fieldState[field], isFocused, mask)}`);
3255
3384
  });
3256
3385
  const modelsText = `${this.focused === modelsRow ? "› " : " "}Models (${this.models.length}) — enter to edit`;
3257
- lines.push(this.focused === modelsRow ? invert$4(modelsText) : modelsText);
3386
+ lines.push(this.focused === modelsRow ? invert$5(modelsText) : modelsText);
3258
3387
  const saveText = `${this.focused === saveRow ? "› " : " "}${mp.busy ? "Saving…" : "Save"}`;
3259
- lines.push(this.focused === saveRow ? invert$4(saveText) : saveText);
3260
- lines.push(muted$9("tab/shift+tab move · enter confirm field / activate row · esc cancel"));
3388
+ lines.push(this.focused === saveRow ? invert$5(saveText) : saveText);
3389
+ lines.push(muted$10("tab/shift+tab move · enter confirm field / activate row · esc cancel"));
3261
3390
  return lines;
3262
3391
  }
3263
3392
  handleFormInput(data, draft) {
@@ -3307,21 +3436,21 @@ var ModelProfileOverlay = class {
3307
3436
  }
3308
3437
  }
3309
3438
  renderModelListEditor(mp) {
3310
- const lines = [bold$8(secondary$8("Models"))];
3439
+ const lines = [bold$9(secondary$9("Models"))];
3311
3440
  this.models.forEach((model, index) => {
3312
3441
  const isSelected = !this.modelInputFocused && index === this.modelSelected;
3313
3442
  const text = `${isSelected ? "› " : " "}${model.id}${model.name === void 0 ? "" : ` — ${model.name}`}`;
3314
- lines.push(isSelected ? invert$4(text) : text);
3443
+ lines.push(isSelected ? invert$5(text) : text);
3315
3444
  });
3316
- if (this.models.length === 0) lines.push(muted$9("No models yet."));
3445
+ if (this.models.length === 0) lines.push(muted$10("No models yet."));
3317
3446
  lines.push(`${this.modelInputFocused ? "› " : " "}Add id: ${renderMiniTextField(this.modelDraftId, this.modelInputFocused)}`);
3318
- if (mp.busy) lines.push(muted$9("Discovering…"));
3319
- if (mp.discovered !== void 0) if (mp.discovered.length === 0) lines.push(muted$9("No models discovered."));
3447
+ if (mp.busy) lines.push(muted$10("Discovering…"));
3448
+ if (mp.discovered !== void 0) if (mp.discovered.length === 0) lines.push(muted$10("No models discovered."));
3320
3449
  else {
3321
- lines.push(muted$9("Discovered — tab to the id field and type one to adopt it:"));
3322
- for (const model of mp.discovered) lines.push(muted$9(` ${model.id}${model.name === void 0 ? "" : ` — ${model.name}`}`));
3450
+ lines.push(muted$10("Discovered — tab to the id field and type one to adopt it:"));
3451
+ for (const model of mp.discovered) lines.push(muted$10(` ${model.id}${model.name === void 0 ? "" : ` — ${model.name}`}`));
3323
3452
  }
3324
- lines.push(muted$9("tab toggle list/input · ↑↓ select · x remove · g discover · esc back"));
3453
+ lines.push(muted$10("tab toggle list/input · ↑↓ select · x remove · g discover · esc back"));
3325
3454
  return lines;
3326
3455
  }
3327
3456
  addModel(id) {
@@ -3382,6 +3511,111 @@ var ModelProfileOverlay = class {
3382
3511
  }
3383
3512
  };
3384
3513
  //#endregion
3514
+ //#region src/tui/login/LoginOverlay.ts
3515
+ const bold$8 = (s) => `\x1b[1m${s}\x1b[0m`;
3516
+ const secondary$8 = fg(theme.secondary);
3517
+ const muted$9 = fg(theme.muted);
3518
+ const errorColor$4 = fg(theme.error);
3519
+ const invert$4 = (s) => `\x1b[7m${s}\x1b[0m`;
3520
+ var LoginOverlay = class {
3521
+ store;
3522
+ actions;
3523
+ promptField = emptyMiniTextField();
3524
+ promptCursor = 0;
3525
+ constructor(store, actions) {
3526
+ this.store = store;
3527
+ this.actions = actions;
3528
+ }
3529
+ invalidate() {}
3530
+ renderList(login) {
3531
+ const lines = [bold$8(secondary$8("Sign in"))];
3532
+ if (login.error !== void 0) lines.push(errorColor$4(login.error));
3533
+ if (login.busy && login.flows === void 0) lines.push(muted$9("Loading…"));
3534
+ login.flows?.forEach((flow, index) => {
3535
+ const marker = flow.inFlight ? "· " : "○ ";
3536
+ const signingIn = login.signingIn === flow.key ? " — signing in…" : "";
3537
+ const text = `${index === login.selected ? "› " : " "}${marker}${flow.label}${signingIn}`;
3538
+ lines.push(index === login.selected ? invert$4(text) : text);
3539
+ });
3540
+ if (login.flows?.length === 0) lines.push(muted$9("No sign-in providers are available in this profile."));
3541
+ lines.push(muted$9("↑↓ select · enter sign in · esc close"));
3542
+ return lines;
3543
+ }
3544
+ renderPrompt(prompt) {
3545
+ const lines = [bold$8(secondary$8("Sign in"))];
3546
+ lines.push(prompt.message);
3547
+ if (prompt.kind === "select") {
3548
+ prompt.options.forEach((option, index) => {
3549
+ const row = `${index === this.promptCursor ? "› " : " "}${option.label}`;
3550
+ lines.push(index === this.promptCursor ? invert$4(row) : row);
3551
+ if (option.description !== void 0) lines.push(muted$9(` ${option.description}`));
3552
+ });
3553
+ lines.push(muted$9("↑↓ choose · enter select · esc cancel"));
3554
+ } else {
3555
+ const mask = prompt.kind === "secret" ? "•" : void 0;
3556
+ const placeholder = prompt.placeholder ?? (prompt.kind === "secret" ? "API key" : "code");
3557
+ const field = this.promptField.value === "" ? `(${placeholder})` : renderMiniTextField(this.promptField, true, mask);
3558
+ lines.push(`> ${field}`);
3559
+ lines.push(muted$9("type + enter submit · esc cancel"));
3560
+ }
3561
+ return lines;
3562
+ }
3563
+ render(_width) {
3564
+ const overlay = this.store.getSnapshot().overlay;
3565
+ if (overlay.kind !== "login") return [];
3566
+ const { prompt } = overlay.login;
3567
+ return prompt === void 0 ? this.renderList(overlay.login) : this.renderPrompt(prompt);
3568
+ }
3569
+ handleInput(data) {
3570
+ const overlay = this.store.getSnapshot().overlay;
3571
+ if (overlay.kind !== "login") return;
3572
+ const { prompt } = overlay.login;
3573
+ if (prompt !== void 0) this.handlePromptInput(data, prompt);
3574
+ else this.handleListInput(data, overlay.login);
3575
+ }
3576
+ handlePromptInput(data, prompt) {
3577
+ if (matchesKey(data, Key.escape)) {
3578
+ this.actions.answerAuthorizationPrompt("");
3579
+ return;
3580
+ }
3581
+ if (prompt.kind === "select") {
3582
+ if (matchesKey(data, Key.up)) {
3583
+ this.promptCursor = Math.max(0, this.promptCursor - 1);
3584
+ return;
3585
+ }
3586
+ if (matchesKey(data, Key.down)) {
3587
+ this.promptCursor = Math.min(prompt.options.length - 1, this.promptCursor + 1);
3588
+ return;
3589
+ }
3590
+ if (matchesKey(data, Key.enter)) this.actions.answerAuthorizationPrompt(prompt.options[this.promptCursor].id);
3591
+ return;
3592
+ }
3593
+ if (matchesKey(data, Key.enter)) {
3594
+ this.actions.answerAuthorizationPrompt(this.promptField.value.trim());
3595
+ return;
3596
+ }
3597
+ const next = miniTextFieldInput(this.promptField, data);
3598
+ if (next !== void 0) this.promptField = next;
3599
+ }
3600
+ handleListInput(data, login) {
3601
+ if (matchesKey(data, Key.escape)) {
3602
+ this.actions.closeLogin();
3603
+ return;
3604
+ }
3605
+ const flows = login.flows;
3606
+ if (flows === void 0 || flows.length === 0) return;
3607
+ if (matchesKey(data, Key.up)) {
3608
+ this.actions.selectLoginFlow(Math.max(0, login.selected - 1));
3609
+ return;
3610
+ }
3611
+ if (matchesKey(data, Key.down)) {
3612
+ this.actions.selectLoginFlow(Math.min(flows.length - 1, login.selected + 1));
3613
+ return;
3614
+ }
3615
+ if (matchesKey(data, Key.enter)) this.actions.beginAuthorization(flows[login.selected].key);
3616
+ }
3617
+ };
3618
+ //#endregion
3385
3619
  //#region src/tui/trajectory/layout.ts
3386
3620
  const LABEL_LIMIT = 100;
3387
3621
  function prettyJson(raw) {
@@ -4621,7 +4855,12 @@ var TuiApp = class {
4621
4855
  this.options = options;
4622
4856
  const { store, actions } = options;
4623
4857
  const terminal = new ProcessTerminal();
4624
- this.tui = new TuiAltScreen(terminal, true, void 0, { mouse: true });
4858
+ this.tui = new TuiAltScreen(terminal, true, void 0, {
4859
+ mouse: true,
4860
+ onRightClickPaste: () => {
4861
+ readClipboard().then((text) => this.tui.getFocusedComponent()?.handleInput?.(`\x1b[200~${text}\x1b[201~`)).catch(() => {});
4862
+ }
4863
+ });
4625
4864
  this.spinner = new Spinner(this.tui);
4626
4865
  this.pet = new YlyPet(this.tui);
4627
4866
  const transcriptScrollView = new ScrollView(this.documentContainer, {
@@ -4809,6 +5048,7 @@ var TuiApp = class {
4809
5048
  switch (overlay.kind) {
4810
5049
  case "none": return;
4811
5050
  case "modelProfile": return new ModelProfileOverlay(store, actions);
5051
+ case "login": return new LoginOverlay(store, actions);
4812
5052
  case "trajectory": return new TrajectoryOverlay(this.tui, store, actions, getTool);
4813
5053
  case "toolCards": return new ToolCardsOverlay(this.tui, store, actions, getTool, getToolCall);
4814
5054
  case "context": return new ContextOverlay(store, actions);
@@ -4939,170 +5179,6 @@ function logoutSuccessMessage(provider) {
4939
5179
  function logoutNoneMessage() {
4940
5180
  return "No active provider is selected; nothing to log out.";
4941
5181
  }
4942
- /** The DSH credential-key segment grammar: lowercase hyphenated identifier. */
4943
- const KEY_SEGMENT_PATTERN = /^[a-z][a-z0-9-]*$/;
4944
- /**
4945
- * Build the `<scope>/<id>` CredentialKey address for one provider's grant
4946
- * record. Mirrors the DSH `credentialKey` grammar so the record space stays
4947
- * valid without a runtime dependency on `@deepseek-ai/dsh-credentials`.
4948
- */
4949
- function grantKey(meta) {
4950
- const scope = meta.ownerScope ?? "acryl-tui";
4951
- for (const segment of [scope, meta.route]) if (!KEY_SEGMENT_PATTERN.test(segment)) throw new TypeError(`credential key segment "${segment}" must be a lowercase hyphenated identifier`);
4952
- return `${scope}/${meta.route}`;
4953
- }
4954
- /** The OAuth-capable providers shipped with ACRYL. Empty until a real provider is wired. */
4955
- const OAUTH_PROVIDERS = [];
4956
- /** Resolve metadata for a provider route, or undefined when it is not OAuth-capable. */
4957
- function oauthProviderFor(route) {
4958
- return OAUTH_PROVIDERS.find((entry) => entry.route === route);
4959
- }
4960
- //#endregion
4961
- //#region src/tui/oauth/flow.ts
4962
- /**
4963
- * OAuth authorization-code flow (L010 + L011): PKCE, a one-shot loopback
4964
- * redirect listener, the code→token exchange, and grant persistence through
4965
- * the `credentials` record seam (`modifyRecord`/`readRecord`/`deleteRecord`).
4966
- *
4967
- * The flow owns exactly one transient resource — an `http.Server` bound to
4968
- * `127.0.0.1:0` — which is opened and closed inside `runOAuthLogin`. The PKCE
4969
- * verifier and `state` are in-memory only and never surface to a transcript.
4970
- * @module @tomowang/dsh-tui/tui/oauth/flow
4971
- */
4972
- function base64Url(input) {
4973
- return input.toString("base64url");
4974
- }
4975
- function makePkce() {
4976
- const verifier = base64Url(randomBytes(32));
4977
- return {
4978
- verifier,
4979
- challenge: base64Url(createHash("sha256").update(verifier).digest()),
4980
- state: base64Url(randomBytes(16))
4981
- };
4982
- }
4983
- function toGrantPayload(tokens) {
4984
- return {
4985
- accessToken: tokens.access_token,
4986
- refreshToken: tokens.refresh_token,
4987
- tokenType: tokens.token_type,
4988
- expiresAt: tokens.expires_in !== void 0 ? Date.now() + tokens.expires_in * 1e3 : void 0
4989
- };
4990
- }
4991
- function buildAuthorizeUrl(meta, redirectUri, pkce) {
4992
- const params = new URLSearchParams({
4993
- response_type: "code",
4994
- client_id: meta.clientId,
4995
- redirect_uri: redirectUri,
4996
- scope: meta.scopes.join(" "),
4997
- state: pkce.state
4998
- });
4999
- if (meta.pkce) {
5000
- params.set("code_challenge", pkce.challenge);
5001
- params.set("code_challenge_method", "S256");
5002
- }
5003
- if (meta.audience !== void 0) params.set("audience", meta.audience);
5004
- return `${meta.authorizeUrl}?${params.toString()}`;
5005
- }
5006
- /** Attach the one-shot callback handler and return a promise for the code. */
5007
- function awaitCallback(server, state, timeoutMs) {
5008
- return new Promise((resolve, reject) => {
5009
- const timer = setTimeout(() => {
5010
- reject(/* @__PURE__ */ new Error("OAuth login timed out waiting for the redirect."));
5011
- server.close();
5012
- }, timeoutMs);
5013
- server.on("request", (request, response) => {
5014
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
5015
- if (url.pathname !== "/callback") {
5016
- response.writeHead(404).end();
5017
- return;
5018
- }
5019
- clearTimeout(timer);
5020
- response.writeHead(200, { "content-type": "text/plain" }).end("Authorization complete. You can return to ACRYL.");
5021
- const code = url.searchParams.get("code");
5022
- const returnedState = url.searchParams.get("state");
5023
- server.close();
5024
- if (returnedState !== state) reject(/* @__PURE__ */ new Error("OAuth state mismatch."));
5025
- else if (code === null) reject(/* @__PURE__ */ new Error("OAuth redirect did not include an authorization code."));
5026
- else resolve(code);
5027
- });
5028
- });
5029
- }
5030
- /** Open the authorize URL in the platform's default browser. */
5031
- function defaultOpenUrl(url) {
5032
- const platform = process.platform;
5033
- const command = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["cmd", [
5034
- "/c",
5035
- "start",
5036
- "",
5037
- url
5038
- ]] : ["xdg-open", [url]];
5039
- return new Promise((resolve) => {
5040
- execFile(command[0], command[1], () => resolve());
5041
- });
5042
- }
5043
- /** POST the authorization code to the token endpoint and normalize the body. */
5044
- async function exchangeCode(meta, code, redirectUri, pkce) {
5045
- const body = new URLSearchParams({
5046
- grant_type: "authorization_code",
5047
- code,
5048
- redirect_uri: redirectUri,
5049
- client_id: meta.clientId
5050
- });
5051
- if (meta.pkce) body.set("code_verifier", pkce.verifier);
5052
- return postToken(meta, body);
5053
- }
5054
- /** POST to the token endpoint; shared by the code and refresh exchanges. */
5055
- async function postToken(meta, body) {
5056
- const response = await fetch(meta.tokenUrl, {
5057
- method: "POST",
5058
- headers: { "content-type": "application/x-www-form-urlencoded" },
5059
- body: body.toString()
5060
- });
5061
- if (!response.ok) {
5062
- const text = await response.text().catch(() => "");
5063
- throw new Error(`token request failed (${response.status}): ${text}`);
5064
- }
5065
- return await response.json();
5066
- }
5067
- /** Run the full authorization-code flow and persist the resulting grant. */
5068
- async function runOAuthLogin(meta, credentials, options = {}) {
5069
- const server = createServer();
5070
- try {
5071
- const pkce = makePkce();
5072
- await new Promise((resolve, reject) => {
5073
- server.once("error", reject);
5074
- server.listen(0, "127.0.0.1", resolve);
5075
- });
5076
- const { port } = server.address();
5077
- const redirectUri = `http://127.0.0.1:${port}/callback`;
5078
- const authorizeUrl = buildAuthorizeUrl(meta, redirectUri, pkce);
5079
- const codePromise = awaitCallback(server, pkce.state, options.timeoutMs ?? 3e5);
5080
- codePromise.catch(() => {});
5081
- await (options.openUrl ?? defaultOpenUrl)(authorizeUrl);
5082
- const tokens = await exchangeCode(meta, await codePromise, redirectUri, pkce);
5083
- await credentials.modifyRecord(grantKey(meta), async () => ({
5084
- kind: "grant",
5085
- payload: toGrantPayload(tokens)
5086
- }));
5087
- return { ok: true };
5088
- } catch (error) {
5089
- return {
5090
- ok: false,
5091
- error: error instanceof Error ? error.message : String(error)
5092
- };
5093
- } finally {
5094
- if (server.listening) server.close();
5095
- }
5096
- }
5097
- /** Read the stored grant for a provider, or undefined when none is stored. */
5098
- async function readOAuthGrant(meta, credentials) {
5099
- const record = await credentials.readRecord(grantKey(meta));
5100
- return record?.kind === "grant" ? record.payload : void 0;
5101
- }
5102
- /** Revoke (delete) a provider's stored grant. Removing an absent record is a no-op. */
5103
- async function revokeOAuthGrant(meta, credentials) {
5104
- await credentials.deleteRecord(grantKey(meta));
5105
- }
5106
5182
  /** Canonical ACRYL version string used by the CLI and the release smoke checks. */
5107
5183
  const ACRYL_VERSION = createRequire(import.meta.url)("../package.json").version;
5108
5184
  //#endregion
@@ -5163,6 +5239,19 @@ function deriveApiKeyRef(route) {
5163
5239
  const upper = route.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
5164
5240
  return `${/^[A-Z_]/.test(upper) ? upper : `P_${upper}`}_API_KEY`;
5165
5241
  }
5242
+ /** Open a URL in the platform's default browser (fire-and-forget). */
5243
+ function openBrowser(url) {
5244
+ const platform = process.platform;
5245
+ const command = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["cmd", [
5246
+ "/c",
5247
+ "start",
5248
+ "",
5249
+ url
5250
+ ]] : ["xdg-open", [url]];
5251
+ return new Promise((resolve) => {
5252
+ execFile(command[0], command[1], () => resolve());
5253
+ });
5254
+ }
5166
5255
  /** Nest a provider settings section at its path, e.g. `['providers','deepseek']` -> `{ providers: { deepseek: section } }`. */
5167
5256
  function nestAtPath(path, section) {
5168
5257
  let patch = section;
@@ -5236,8 +5325,6 @@ async function attachSession(host, resumeId) {
5236
5325
  const userValue = descriptor === void 0 ? void 0 : getAtPath(descriptor.user, entry.settingsPath);
5237
5326
  const apiKeyRef = value?.apiKeyEnv ?? deriveApiKeyRef(entry.provider);
5238
5327
  const info = await credentialsSvc.describe(apiKeyRef);
5239
- const oauth = oauthProviderFor(entry.provider);
5240
- const grant = oauth === void 0 ? void 0 : await readOAuthGrant(oauth, credentialsSvc);
5241
5328
  rows.push({
5242
5329
  route: entry.provider,
5243
5330
  displayName: value?.displayName ?? entry.displayName,
@@ -5249,8 +5336,6 @@ async function attachSession(host, resumeId) {
5249
5336
  baseURL: value?.baseURL,
5250
5337
  apiKeyRef,
5251
5338
  apiKeyConfigured: info.configured,
5252
- oauth,
5253
- grantConfigured: grant !== void 0,
5254
5339
  models: value?.models ?? [],
5255
5340
  revision: descriptor?.revision
5256
5341
  });
@@ -5262,6 +5347,30 @@ async function attachSession(host, resumeId) {
5262
5347
  selected: 0
5263
5348
  });
5264
5349
  }
5350
+ async function loadAuthorizationFlows() {
5351
+ const authSvc = host.ctx.get("authorization");
5352
+ if (authSvc === void 0) {
5353
+ store.updateLogin({
5354
+ flows: [],
5355
+ busy: false,
5356
+ error: "Sign-in is not available in this profile."
5357
+ });
5358
+ return;
5359
+ }
5360
+ try {
5361
+ const list = authSvc.list();
5362
+ store.updateLogin({
5363
+ flows: list,
5364
+ busy: false,
5365
+ error: void 0
5366
+ });
5367
+ } catch (error) {
5368
+ store.updateLogin({
5369
+ busy: false,
5370
+ error: error instanceof Error ? error.message : String(error)
5371
+ });
5372
+ }
5373
+ }
5265
5374
  async function loadAgentPresets() {
5266
5375
  const presetsSvc = host.ctx.get("agentPresets");
5267
5376
  if (presetsSvc === void 0) {
@@ -5292,6 +5401,7 @@ async function attachSession(host, resumeId) {
5292
5401
  });
5293
5402
  }
5294
5403
  }
5404
+ let pendingPromptResolve;
5295
5405
  const actions = {
5296
5406
  send(text) {
5297
5407
  store.setNotice(void 0);
@@ -5410,29 +5520,84 @@ async function attachSession(host, resumeId) {
5410
5520
  loadProviders();
5411
5521
  },
5412
5522
  login() {
5413
- store.openModelProfile();
5414
- loadProviders();
5523
+ store.openLogin();
5524
+ loadAuthorizationFlows();
5525
+ },
5526
+ closeLogin() {
5527
+ store.closeOverlay();
5528
+ },
5529
+ selectLoginFlow(index) {
5530
+ store.updateLogin({ selected: index });
5415
5531
  },
5416
- loginWithOAuth(route) {
5532
+ beginAuthorization(key) {
5417
5533
  (async () => {
5418
- const credentialsSvc = host.ctx.get("credentials");
5419
- if (credentialsSvc === void 0) {
5420
- store.setNotice("Credentials are not available in this profile.");
5534
+ const authSvc = host.ctx.get("authorization");
5535
+ if (authSvc === void 0) {
5536
+ store.setNotice("Sign-in is not available in this profile.");
5421
5537
  return;
5422
5538
  }
5423
- const meta = oauthProviderFor(route);
5424
- if (meta === void 0) {
5425
- store.setNotice("OAuth is not available for this provider.");
5426
- return;
5539
+ const overlay = store.getSnapshot().overlay;
5540
+ const flow = overlay.kind === "login" ? overlay.login.flows?.find((entry) => entry.key === key) : void 0;
5541
+ if (flow === void 0) return;
5542
+ store.updateLogin({ signingIn: key });
5543
+ const interaction = {
5544
+ notify(notice) {
5545
+ if (notice.url !== void 0) openBrowser(notice.url);
5546
+ const parts = [notice.message];
5547
+ if (notice.url !== void 0) parts.push(notice.url);
5548
+ if (notice.code !== void 0) parts.push(`Code: ${notice.code}`);
5549
+ store.setNotice(parts.join("\n"));
5550
+ },
5551
+ async prompt(prompt) {
5552
+ return await new Promise((resolve, reject) => {
5553
+ if (prompt.signal?.aborted) {
5554
+ reject(/* @__PURE__ */ new Error("authorization prompt withdrawn"));
5555
+ return;
5556
+ }
5557
+ pendingPromptResolve = resolve;
5558
+ const state = prompt.kind === "select" ? {
5559
+ kind: "select",
5560
+ message: prompt.message,
5561
+ options: (prompt.options ?? []).map((option) => ({
5562
+ id: option.id,
5563
+ label: option.label,
5564
+ description: option.description
5565
+ }))
5566
+ } : {
5567
+ kind: prompt.kind,
5568
+ message: prompt.message,
5569
+ placeholder: prompt.placeholder
5570
+ };
5571
+ store.updateLogin({ prompt: state });
5572
+ prompt.signal?.addEventListener("abort", () => {
5573
+ if (pendingPromptResolve === resolve) pendingPromptResolve = void 0;
5574
+ store.updateLogin({ prompt: void 0 });
5575
+ reject(/* @__PURE__ */ new Error("authorization prompt withdrawn"));
5576
+ }, { once: true });
5577
+ });
5578
+ }
5579
+ };
5580
+ try {
5581
+ if ((await authSvc.begin({
5582
+ key,
5583
+ interaction
5584
+ })).status === "authorized") {
5585
+ store.setNotice(`Signed in to ${flow.label}.`);
5586
+ loadAuthorizationFlows();
5587
+ } else store.setNotice("Sign-in cancelled.");
5588
+ } catch (error) {
5589
+ store.setNotice(`Sign-in failed: ${error instanceof Error ? error.message : String(error)}`);
5590
+ } finally {
5591
+ store.updateLogin({ signingIn: void 0 });
5427
5592
  }
5428
- store.setNotice(`Opening ${meta.route} OAuth login…`);
5429
- const result = await runOAuthLogin(meta, credentialsSvc);
5430
- if (result.ok) {
5431
- store.setNotice(`OAuth login complete for ${meta.route}.`);
5432
- loadProviders();
5433
- } else store.setNotice(`OAuth login failed: ${result.error}`);
5434
5593
  })();
5435
5594
  },
5595
+ answerAuthorizationPrompt(value) {
5596
+ const resolve = pendingPromptResolve;
5597
+ pendingPromptResolve = void 0;
5598
+ store.updateLogin({ prompt: void 0 });
5599
+ if (resolve !== void 0) resolve(value);
5600
+ },
5436
5601
  logout() {
5437
5602
  (async () => {
5438
5603
  const credentialsSvc = host.ctx.get("credentials");
@@ -5449,8 +5614,6 @@ async function attachSession(host, resumeId) {
5449
5614
  return;
5450
5615
  }
5451
5616
  try {
5452
- const oauth = oauthProviderFor(row.route);
5453
- if (oauth !== void 0) await revokeOAuthGrant(oauth, credentialsSvc);
5454
5617
  await credentialsSvc.unset(row.apiKeyRef);
5455
5618
  store.setNotice(logoutSuccessMessage(row.displayName));
5456
5619
  loadProviders();