acryl 0.1.14 → 0.1.16

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { randomUUID } from "node:crypto";
2
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
3
3
  import { BlockAssembler, createUserMessage } from "@deepseek-ai/dsh-llm";
4
4
  import { SessionId } from "@deepseek-ai/dsh-session";
5
5
  import { existsSync, writeFileSync } from "node:fs";
@@ -8,8 +8,9 @@ import { fileURLToPath } from "node:url";
8
8
  import { DEFAULT_PROFILE_BUNDLES, boot, composeEntries, healProfilesModuleFallback, initProfile, loadProfile, resolveProfileDir } from "@deepseek-ai/dsh-app-boot";
9
9
  import { diffLines } from "diff";
10
10
  import { Container, Editor, HStack, Key, KeybindingsManager, ProcessTerminal, ScrollView, TUI_KEYBINDINGS, Text, TuiAltScreen, VStack, matchesKey, setKeybindings, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
11
- import { spawn } from "node:child_process";
11
+ import { execFile, spawn } from "node:child_process";
12
12
  import { readdir } from "node:fs/promises";
13
+ import { createServer } from "node:http";
13
14
  import { ManualCompactionError } from "@deepseek-ai/dsh-compaction";
14
15
  import { GoalError } from "@deepseek-ai/dsh-goal";
15
16
  //#region src/cli/grammar.ts
@@ -1609,6 +1610,14 @@ const SLASH_COMMANDS = [
1609
1610
  command: "/help",
1610
1611
  description: "Show help and available commands"
1611
1612
  },
1613
+ {
1614
+ command: "/login",
1615
+ description: "Configure provider authentication (API key)"
1616
+ },
1617
+ {
1618
+ command: "/logout",
1619
+ description: "Remove provider authentication"
1620
+ },
1612
1621
  {
1613
1622
  command: "/model",
1614
1623
  description: "Manage LLM provider profiles"
@@ -1727,6 +1736,12 @@ function runSlashCommand(command, actions) {
1727
1736
  case "/model":
1728
1737
  actions.openModelProfile();
1729
1738
  return;
1739
+ case "/login":
1740
+ actions.login();
1741
+ return;
1742
+ case "/logout":
1743
+ actions.logout();
1744
+ return;
1730
1745
  case "/trajectory":
1731
1746
  actions.openTrajectory();
1732
1747
  return;
@@ -3135,12 +3150,14 @@ var ModelProfileOverlay = class {
3135
3150
  const marker = row.configured ? "● " : "○ ";
3136
3151
  const active = row.live ? " (active)" : "";
3137
3152
  const noKey = row.apiKeyConfigured ? "" : " [no api key]";
3153
+ const oauthStatus = row.oauth === void 0 ? "" : row.grantConfigured ? " [oauth ✓]" : " [oauth]";
3138
3154
  const confirm = this.confirmDelete === index ? " — press d again to delete" : "";
3139
- const text = `${index === selected ? "› " : " "}${marker}${row.displayName}${active}${noKey}${confirm}`;
3155
+ const text = `${index === selected ? "› " : " "}${marker}${row.displayName}${active}${noKey}${oauthStatus}${confirm}`;
3140
3156
  lines.push(index === selected ? invert$4(text) : text);
3141
3157
  });
3142
3158
  if (providers?.length === 0) lines.push(muted$9("No providers configured yet — press a to add one."));
3143
- lines.push(muted$9("↑↓ select · enter edit · a add · d delete · s set active model · esc close"));
3159
+ const hasOauth = providers?.some((row) => row.oauth !== void 0) ?? false;
3160
+ lines.push(muted$9(`↑↓ select · enter edit · a add · d delete · s set active model${hasOauth ? " · o login with oauth" : ""} · esc close`));
3144
3161
  return lines;
3145
3162
  }
3146
3163
  handleListInput(data, mp) {
@@ -3177,6 +3194,11 @@ var ModelProfileOverlay = class {
3177
3194
  if (model !== void 0) this.actions.setActiveModel(row.route, model.id);
3178
3195
  return;
3179
3196
  }
3197
+ if (data === "o") {
3198
+ const row = providers[selected];
3199
+ if (row.oauth !== void 0) this.actions.loginWithOAuth(row.route);
3200
+ return;
3201
+ }
3180
3202
  if (data === "d") {
3181
3203
  if (this.confirmDelete === selected) {
3182
3204
  this.confirmDelete = void 0;
@@ -4891,6 +4913,178 @@ async function walkDirectory(cwd) {
4891
4913
  return results;
4892
4914
  }
4893
4915
  //#endregion
4916
+ //#region src/tui/auth-guidance.ts
4917
+ function logoutSuccessMessage(provider) {
4918
+ return `Removed stored authentication for ${provider.trim() === "" ? "provider" : provider}.`;
4919
+ }
4920
+ function logoutNoneMessage() {
4921
+ return "No active provider is selected; nothing to log out.";
4922
+ }
4923
+ /** The DSH credential-key segment grammar: lowercase hyphenated identifier. */
4924
+ const KEY_SEGMENT_PATTERN = /^[a-z][a-z0-9-]*$/;
4925
+ /**
4926
+ * Build the `<scope>/<id>` CredentialKey address for one provider's grant
4927
+ * record. Mirrors the DSH `credentialKey` grammar so the record space stays
4928
+ * valid without a runtime dependency on `@deepseek-ai/dsh-credentials`.
4929
+ */
4930
+ function grantKey(meta) {
4931
+ const scope = meta.ownerScope ?? "acryl-tui";
4932
+ 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`);
4933
+ return `${scope}/${meta.route}`;
4934
+ }
4935
+ /** The OAuth-capable providers shipped with ACRYL. Empty until a real provider is wired. */
4936
+ const OAUTH_PROVIDERS = [];
4937
+ /** Resolve metadata for a provider route, or undefined when it is not OAuth-capable. */
4938
+ function oauthProviderFor(route) {
4939
+ return OAUTH_PROVIDERS.find((entry) => entry.route === route);
4940
+ }
4941
+ //#endregion
4942
+ //#region src/tui/oauth/flow.ts
4943
+ /**
4944
+ * OAuth authorization-code flow (L010 + L011): PKCE, a one-shot loopback
4945
+ * redirect listener, the code→token exchange, and grant persistence through
4946
+ * the `credentials` record seam (`modifyRecord`/`readRecord`/`deleteRecord`).
4947
+ *
4948
+ * The flow owns exactly one transient resource — an `http.Server` bound to
4949
+ * `127.0.0.1:0` — which is opened and closed inside `runOAuthLogin`. The PKCE
4950
+ * verifier and `state` are in-memory only and never surface to a transcript.
4951
+ * @module @tomowang/dsh-tui/tui/oauth/flow
4952
+ */
4953
+ function base64Url(input) {
4954
+ return input.toString("base64url");
4955
+ }
4956
+ function makePkce() {
4957
+ const verifier = base64Url(randomBytes(32));
4958
+ return {
4959
+ verifier,
4960
+ challenge: base64Url(createHash("sha256").update(verifier).digest()),
4961
+ state: base64Url(randomBytes(16))
4962
+ };
4963
+ }
4964
+ function toGrantPayload(tokens) {
4965
+ return {
4966
+ accessToken: tokens.access_token,
4967
+ refreshToken: tokens.refresh_token,
4968
+ tokenType: tokens.token_type,
4969
+ expiresAt: tokens.expires_in !== void 0 ? Date.now() + tokens.expires_in * 1e3 : void 0
4970
+ };
4971
+ }
4972
+ function buildAuthorizeUrl(meta, redirectUri, pkce) {
4973
+ const params = new URLSearchParams({
4974
+ response_type: "code",
4975
+ client_id: meta.clientId,
4976
+ redirect_uri: redirectUri,
4977
+ scope: meta.scopes.join(" "),
4978
+ state: pkce.state
4979
+ });
4980
+ if (meta.pkce) {
4981
+ params.set("code_challenge", pkce.challenge);
4982
+ params.set("code_challenge_method", "S256");
4983
+ }
4984
+ if (meta.audience !== void 0) params.set("audience", meta.audience);
4985
+ return `${meta.authorizeUrl}?${params.toString()}`;
4986
+ }
4987
+ /** Attach the one-shot callback handler and return a promise for the code. */
4988
+ function awaitCallback(server, state, timeoutMs) {
4989
+ return new Promise((resolve, reject) => {
4990
+ const timer = setTimeout(() => {
4991
+ reject(/* @__PURE__ */ new Error("OAuth login timed out waiting for the redirect."));
4992
+ server.close();
4993
+ }, timeoutMs);
4994
+ server.on("request", (request, response) => {
4995
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
4996
+ if (url.pathname !== "/callback") {
4997
+ response.writeHead(404).end();
4998
+ return;
4999
+ }
5000
+ clearTimeout(timer);
5001
+ response.writeHead(200, { "content-type": "text/plain" }).end("Authorization complete. You can return to ACRYL.");
5002
+ const code = url.searchParams.get("code");
5003
+ const returnedState = url.searchParams.get("state");
5004
+ server.close();
5005
+ if (returnedState !== state) reject(/* @__PURE__ */ new Error("OAuth state mismatch."));
5006
+ else if (code === null) reject(/* @__PURE__ */ new Error("OAuth redirect did not include an authorization code."));
5007
+ else resolve(code);
5008
+ });
5009
+ });
5010
+ }
5011
+ /** Open the authorize URL in the platform's default browser. */
5012
+ function defaultOpenUrl(url) {
5013
+ const platform = process.platform;
5014
+ const command = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["cmd", [
5015
+ "/c",
5016
+ "start",
5017
+ "",
5018
+ url
5019
+ ]] : ["xdg-open", [url]];
5020
+ return new Promise((resolve) => {
5021
+ execFile(command[0], command[1], () => resolve());
5022
+ });
5023
+ }
5024
+ /** POST the authorization code to the token endpoint and normalize the body. */
5025
+ async function exchangeCode(meta, code, redirectUri, pkce) {
5026
+ const body = new URLSearchParams({
5027
+ grant_type: "authorization_code",
5028
+ code,
5029
+ redirect_uri: redirectUri,
5030
+ client_id: meta.clientId
5031
+ });
5032
+ if (meta.pkce) body.set("code_verifier", pkce.verifier);
5033
+ return postToken(meta, body);
5034
+ }
5035
+ /** POST to the token endpoint; shared by the code and refresh exchanges. */
5036
+ async function postToken(meta, body) {
5037
+ const response = await fetch(meta.tokenUrl, {
5038
+ method: "POST",
5039
+ headers: { "content-type": "application/x-www-form-urlencoded" },
5040
+ body: body.toString()
5041
+ });
5042
+ if (!response.ok) {
5043
+ const text = await response.text().catch(() => "");
5044
+ throw new Error(`token request failed (${response.status}): ${text}`);
5045
+ }
5046
+ return await response.json();
5047
+ }
5048
+ /** Run the full authorization-code flow and persist the resulting grant. */
5049
+ async function runOAuthLogin(meta, credentials, options = {}) {
5050
+ const server = createServer();
5051
+ try {
5052
+ const pkce = makePkce();
5053
+ await new Promise((resolve, reject) => {
5054
+ server.once("error", reject);
5055
+ server.listen(0, "127.0.0.1", resolve);
5056
+ });
5057
+ const { port } = server.address();
5058
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
5059
+ const authorizeUrl = buildAuthorizeUrl(meta, redirectUri, pkce);
5060
+ const codePromise = awaitCallback(server, pkce.state, options.timeoutMs ?? 3e5);
5061
+ codePromise.catch(() => {});
5062
+ await (options.openUrl ?? defaultOpenUrl)(authorizeUrl);
5063
+ const tokens = await exchangeCode(meta, await codePromise, redirectUri, pkce);
5064
+ await credentials.modifyRecord(grantKey(meta), async () => ({
5065
+ kind: "grant",
5066
+ payload: toGrantPayload(tokens)
5067
+ }));
5068
+ return { ok: true };
5069
+ } catch (error) {
5070
+ return {
5071
+ ok: false,
5072
+ error: error instanceof Error ? error.message : String(error)
5073
+ };
5074
+ } finally {
5075
+ if (server.listening) server.close();
5076
+ }
5077
+ }
5078
+ /** Read the stored grant for a provider, or undefined when none is stored. */
5079
+ async function readOAuthGrant(meta, credentials) {
5080
+ const record = await credentials.readRecord(grantKey(meta));
5081
+ return record?.kind === "grant" ? record.payload : void 0;
5082
+ }
5083
+ /** Revoke (delete) a provider's stored grant. Removing an absent record is a no-op. */
5084
+ async function revokeOAuthGrant(meta, credentials) {
5085
+ await credentials.deleteRecord(grantKey(meta));
5086
+ }
5087
+ //#endregion
4894
5088
  //#region src/tui-app/session.ts
4895
5089
  /**
4896
5090
  * ACRYL terminal host adapter: brings up one normal local runtime, opens or
@@ -4948,6 +5142,12 @@ function deriveApiKeyRef(route) {
4948
5142
  const upper = route.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
4949
5143
  return `${/^[A-Z_]/.test(upper) ? upper : `P_${upper}`}_API_KEY`;
4950
5144
  }
5145
+ /** Nest a provider settings section at its path, e.g. `['providers','deepseek']` -> `{ providers: { deepseek: section } }`. */
5146
+ function nestAtPath(path, section) {
5147
+ let patch = section;
5148
+ for (let index = path.length - 1; index >= 0; index--) patch = { [path[index]]: patch };
5149
+ return patch;
5150
+ }
4951
5151
  /** English display names for the shipped preset ids (the metadata is authored in Chinese, and there is no server-side locale resolution). */
4952
5152
  const PRESET_LABELS = {
4953
5153
  standard: "Standard mode",
@@ -5015,6 +5215,8 @@ async function attachSession(host, resumeId) {
5015
5215
  const userValue = descriptor === void 0 ? void 0 : getAtPath(descriptor.user, entry.settingsPath);
5016
5216
  const apiKeyRef = value?.apiKeyEnv ?? deriveApiKeyRef(entry.provider);
5017
5217
  const info = await credentialsSvc.describe(apiKeyRef);
5218
+ const oauth = oauthProviderFor(entry.provider);
5219
+ const grant = oauth === void 0 ? void 0 : await readOAuthGrant(oauth, credentialsSvc);
5018
5220
  rows.push({
5019
5221
  route: entry.provider,
5020
5222
  displayName: value?.displayName ?? entry.displayName,
@@ -5026,6 +5228,8 @@ async function attachSession(host, resumeId) {
5026
5228
  baseURL: value?.baseURL,
5027
5229
  apiKeyRef,
5028
5230
  apiKeyConfigured: info.configured,
5231
+ oauth,
5232
+ grantConfigured: grant !== void 0,
5029
5233
  models: value?.models ?? [],
5030
5234
  revision: descriptor?.revision
5031
5235
  });
@@ -5184,6 +5388,56 @@ async function attachSession(host, resumeId) {
5184
5388
  store.openModelProfile();
5185
5389
  loadProviders();
5186
5390
  },
5391
+ login() {
5392
+ store.openModelProfile();
5393
+ loadProviders();
5394
+ },
5395
+ loginWithOAuth(route) {
5396
+ (async () => {
5397
+ const credentialsSvc = host.ctx.get("credentials");
5398
+ if (credentialsSvc === void 0) {
5399
+ store.setNotice("Credentials are not available in this profile.");
5400
+ return;
5401
+ }
5402
+ const meta = oauthProviderFor(route);
5403
+ if (meta === void 0) {
5404
+ store.setNotice("OAuth is not available for this provider.");
5405
+ return;
5406
+ }
5407
+ store.setNotice(`Opening ${meta.route} OAuth login…`);
5408
+ const result = await runOAuthLogin(meta, credentialsSvc);
5409
+ if (result.ok) {
5410
+ store.setNotice(`OAuth login complete for ${meta.route}.`);
5411
+ loadProviders();
5412
+ } else store.setNotice(`OAuth login failed: ${result.error}`);
5413
+ })();
5414
+ },
5415
+ logout() {
5416
+ (async () => {
5417
+ const credentialsSvc = host.ctx.get("credentials");
5418
+ if (credentialsSvc === void 0) {
5419
+ store.setNotice("Credentials are not available in this profile.");
5420
+ return;
5421
+ }
5422
+ const selection = host.ctx.get("agentDefaultModel")?.currentSelection?.();
5423
+ const overlay = store.getSnapshot().overlay;
5424
+ const rows = overlay.kind === "modelProfile" ? overlay.modelProfile.providers : void 0;
5425
+ const row = rows?.find((entry) => entry.route === selection?.provider) ?? (rows !== void 0 && rows.length === 1 ? rows[0] : void 0);
5426
+ if (row === void 0) {
5427
+ store.setNotice(logoutNoneMessage());
5428
+ return;
5429
+ }
5430
+ try {
5431
+ const oauth = oauthProviderFor(row.route);
5432
+ if (oauth !== void 0) await revokeOAuthGrant(oauth, credentialsSvc);
5433
+ await credentialsSvc.unset(row.apiKeyRef);
5434
+ store.setNotice(logoutSuccessMessage(row.displayName));
5435
+ loadProviders();
5436
+ } catch (error) {
5437
+ store.setNotice(`logout failed: ${error instanceof Error ? error.message : String(error)}`);
5438
+ }
5439
+ })();
5440
+ },
5187
5441
  openTrajectory() {
5188
5442
  store.openTrajectory();
5189
5443
  },
@@ -5220,9 +5474,76 @@ async function attachSession(host, resumeId) {
5220
5474
  draft: void 0
5221
5475
  });
5222
5476
  },
5223
- editProvider() {},
5224
- saveProvider() {},
5225
- deleteProvider() {},
5477
+ editProvider(route) {
5478
+ const overlay = store.getSnapshot().overlay;
5479
+ if (overlay.kind !== "modelProfile") return;
5480
+ const row = overlay.modelProfile.providers?.find((entry) => entry.route === route);
5481
+ if (row === void 0) return;
5482
+ const draft = {
5483
+ route: row.route,
5484
+ isNew: false,
5485
+ settingsNs: row.settingsNs,
5486
+ settingsPath: row.settingsPath,
5487
+ displayName: row.displayName,
5488
+ api: row.api ?? "",
5489
+ baseURL: row.baseURL ?? "",
5490
+ apiKeyRef: row.apiKeyRef,
5491
+ apiKeyConfigured: row.apiKeyConfigured,
5492
+ apiKeyDraft: "",
5493
+ models: row.models,
5494
+ revision: row.revision
5495
+ };
5496
+ store.updateModelProfile({
5497
+ view: "form",
5498
+ draft,
5499
+ formKey: overlay.modelProfile.formKey + 1
5500
+ });
5501
+ },
5502
+ saveProvider(draft) {
5503
+ (async () => {
5504
+ const settingsSvc = host.ctx.get("settings");
5505
+ const credentialsSvc = host.ctx.get("credentials");
5506
+ if (settingsSvc === void 0 || credentialsSvc === void 0) {
5507
+ store.setNotice("Provider settings are not available in this profile.");
5508
+ return;
5509
+ }
5510
+ try {
5511
+ const key = draft.apiKeyDraft.trim();
5512
+ if (key !== "") await credentialsSvc.set(draft.apiKeyRef, key);
5513
+ const section = {
5514
+ displayName: draft.displayName,
5515
+ api: draft.api,
5516
+ baseURL: draft.baseURL,
5517
+ apiKeyEnv: draft.apiKeyRef,
5518
+ models: draft.models
5519
+ };
5520
+ await settingsSvc.update(draft.settingsNs, nestAtPath(draft.settingsPath, section), draft.revision);
5521
+ store.setNotice(`Saved ${draft.displayName || draft.route}.`);
5522
+ store.updateModelProfile({ view: "list" });
5523
+ loadProviders();
5524
+ } catch (error) {
5525
+ store.setNotice(`save failed: ${error instanceof Error ? error.message : String(error)}`);
5526
+ }
5527
+ })();
5528
+ },
5529
+ deleteProvider(row) {
5530
+ (async () => {
5531
+ const settingsSvc = host.ctx.get("settings");
5532
+ const credentialsSvc = host.ctx.get("credentials");
5533
+ if (settingsSvc === void 0 || credentialsSvc === void 0) {
5534
+ store.setNotice("Provider settings are not available in this profile.");
5535
+ return;
5536
+ }
5537
+ try {
5538
+ await credentialsSvc.unset(row.apiKeyRef);
5539
+ await settingsSvc.update(row.settingsNs, nestAtPath(row.settingsPath, {}), row.revision);
5540
+ store.setNotice(`Removed ${row.displayName}.`);
5541
+ loadProviders();
5542
+ } catch (error) {
5543
+ store.setNotice(`delete failed: ${error instanceof Error ? error.message : String(error)}`);
5544
+ }
5545
+ })();
5546
+ },
5226
5547
  discoverModelsForDraft() {},
5227
5548
  setActiveModel() {},
5228
5549
  closeTrajectory() {