acryl 0.1.15 → 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/README.md +64 -3
- package/lib/bin.js +202 -4
- package/lib/bin.js.map +1 -1
- package/lib/index.js +202 -4
- package/lib/index.js.map +1 -1
- package/package.json +12 -5
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
|
|
@@ -3149,12 +3150,14 @@ var ModelProfileOverlay = class {
|
|
|
3149
3150
|
const marker = row.configured ? "● " : "○ ";
|
|
3150
3151
|
const active = row.live ? " (active)" : "";
|
|
3151
3152
|
const noKey = row.apiKeyConfigured ? "" : " [no api key]";
|
|
3153
|
+
const oauthStatus = row.oauth === void 0 ? "" : row.grantConfigured ? " [oauth ✓]" : " [oauth]";
|
|
3152
3154
|
const confirm = this.confirmDelete === index ? " — press d again to delete" : "";
|
|
3153
|
-
const text = `${index === selected ? "› " : " "}${marker}${row.displayName}${active}${noKey}${confirm}`;
|
|
3155
|
+
const text = `${index === selected ? "› " : " "}${marker}${row.displayName}${active}${noKey}${oauthStatus}${confirm}`;
|
|
3154
3156
|
lines.push(index === selected ? invert$4(text) : text);
|
|
3155
3157
|
});
|
|
3156
3158
|
if (providers?.length === 0) lines.push(muted$9("No providers configured yet — press a to add one."));
|
|
3157
|
-
|
|
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`));
|
|
3158
3161
|
return lines;
|
|
3159
3162
|
}
|
|
3160
3163
|
handleListInput(data, mp) {
|
|
@@ -3191,6 +3194,11 @@ var ModelProfileOverlay = class {
|
|
|
3191
3194
|
if (model !== void 0) this.actions.setActiveModel(row.route, model.id);
|
|
3192
3195
|
return;
|
|
3193
3196
|
}
|
|
3197
|
+
if (data === "o") {
|
|
3198
|
+
const row = providers[selected];
|
|
3199
|
+
if (row.oauth !== void 0) this.actions.loginWithOAuth(row.route);
|
|
3200
|
+
return;
|
|
3201
|
+
}
|
|
3194
3202
|
if (data === "d") {
|
|
3195
3203
|
if (this.confirmDelete === selected) {
|
|
3196
3204
|
this.confirmDelete = void 0;
|
|
@@ -4912,6 +4920,170 @@ function logoutSuccessMessage(provider) {
|
|
|
4912
4920
|
function logoutNoneMessage() {
|
|
4913
4921
|
return "No active provider is selected; nothing to log out.";
|
|
4914
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
|
+
}
|
|
4915
5087
|
//#endregion
|
|
4916
5088
|
//#region src/tui-app/session.ts
|
|
4917
5089
|
/**
|
|
@@ -5043,6 +5215,8 @@ async function attachSession(host, resumeId) {
|
|
|
5043
5215
|
const userValue = descriptor === void 0 ? void 0 : getAtPath(descriptor.user, entry.settingsPath);
|
|
5044
5216
|
const apiKeyRef = value?.apiKeyEnv ?? deriveApiKeyRef(entry.provider);
|
|
5045
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);
|
|
5046
5220
|
rows.push({
|
|
5047
5221
|
route: entry.provider,
|
|
5048
5222
|
displayName: value?.displayName ?? entry.displayName,
|
|
@@ -5054,6 +5228,8 @@ async function attachSession(host, resumeId) {
|
|
|
5054
5228
|
baseURL: value?.baseURL,
|
|
5055
5229
|
apiKeyRef,
|
|
5056
5230
|
apiKeyConfigured: info.configured,
|
|
5231
|
+
oauth,
|
|
5232
|
+
grantConfigured: grant !== void 0,
|
|
5057
5233
|
models: value?.models ?? [],
|
|
5058
5234
|
revision: descriptor?.revision
|
|
5059
5235
|
});
|
|
@@ -5216,6 +5392,26 @@ async function attachSession(host, resumeId) {
|
|
|
5216
5392
|
store.openModelProfile();
|
|
5217
5393
|
loadProviders();
|
|
5218
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
|
+
},
|
|
5219
5415
|
logout() {
|
|
5220
5416
|
(async () => {
|
|
5221
5417
|
const credentialsSvc = host.ctx.get("credentials");
|
|
@@ -5232,6 +5428,8 @@ async function attachSession(host, resumeId) {
|
|
|
5232
5428
|
return;
|
|
5233
5429
|
}
|
|
5234
5430
|
try {
|
|
5431
|
+
const oauth = oauthProviderFor(row.route);
|
|
5432
|
+
if (oauth !== void 0) await revokeOAuthGrant(oauth, credentialsSvc);
|
|
5235
5433
|
await credentialsSvc.unset(row.apiKeyRef);
|
|
5236
5434
|
store.setNotice(logoutSuccessMessage(row.displayName));
|
|
5237
5435
|
loadProviders();
|