@kweaver-ai/kweaver-sdk 0.4.1 → 0.4.4
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/dist/api/agent-list.d.ts +44 -0
- package/dist/api/agent-list.js +104 -14
- package/dist/api/bkn-backend.d.ts +16 -0
- package/dist/api/bkn-backend.js +46 -0
- package/dist/api/ontology-query.d.ts +1 -1
- package/dist/api/ontology-query.js +1 -0
- package/dist/api/vega.d.ts +110 -0
- package/dist/api/vega.js +254 -0
- package/dist/auth/oauth.d.ts +9 -73
- package/dist/auth/oauth.js +98 -342
- package/dist/cli.js +12 -0
- package/dist/client.d.ts +19 -0
- package/dist/client.js +65 -13
- package/dist/commands/agent-chat.js +4 -1
- package/dist/commands/agent.js +343 -29
- package/dist/commands/auth.d.ts +0 -8
- package/dist/commands/auth.js +59 -80
- package/dist/commands/bkn.d.ts +16 -0
- package/dist/commands/bkn.js +422 -70
- package/dist/commands/call.js +43 -7
- package/dist/commands/config.d.ts +1 -0
- package/dist/commands/config.js +52 -0
- package/dist/commands/context-loader.js +46 -40
- package/dist/commands/ds.js +29 -13
- package/dist/commands/vega.d.ts +1 -0
- package/dist/commands/vega.js +684 -0
- package/dist/config/store.d.ts +12 -25
- package/dist/config/store.js +43 -42
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/resources/agents.d.ts +83 -9
- package/dist/resources/agents.js +46 -10
- package/dist/resources/knowledge-networks.js +2 -3
- package/package.json +10 -1
package/dist/auth/oauth.d.ts
CHANGED
|
@@ -1,75 +1,11 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
interface RegisterClientOptions {
|
|
3
|
-
baseUrl: string;
|
|
4
|
-
clientName: string;
|
|
5
|
-
redirectUri: string;
|
|
6
|
-
logoutRedirectUri: string;
|
|
7
|
-
lang?: string;
|
|
8
|
-
product?: string;
|
|
9
|
-
xForwardedPrefix?: string;
|
|
10
|
-
}
|
|
1
|
+
import { type TokenConfig } from "../config/store.js";
|
|
11
2
|
export declare function normalizeBaseUrl(value: string): string;
|
|
12
|
-
export declare function
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
redirectUriOverride?: string;
|
|
21
|
-
lang?: string;
|
|
22
|
-
product?: string;
|
|
23
|
-
xForwardedPrefix?: string;
|
|
24
|
-
}
|
|
25
|
-
export interface EnsuredClientConfig {
|
|
26
|
-
client: ClientConfig;
|
|
27
|
-
created: boolean;
|
|
28
|
-
}
|
|
29
|
-
export interface AuthRedirectConfig {
|
|
30
|
-
redirectUri: string;
|
|
31
|
-
logoutRedirectUri: string;
|
|
32
|
-
listenHost: string;
|
|
33
|
-
listenPort: number;
|
|
34
|
-
callbackPath: string;
|
|
35
|
-
}
|
|
36
|
-
export declare function buildAuthRedirectConfig(options: {
|
|
37
|
-
port: number;
|
|
38
|
-
host?: string;
|
|
39
|
-
redirectUriOverride?: string;
|
|
40
|
-
}): AuthRedirectConfig;
|
|
41
|
-
export declare function ensureClientConfig(options: EnsureClientOptions): Promise<EnsuredClientConfig>;
|
|
42
|
-
export declare function buildAuthorizationUrl(client: ClientConfig, state?: string): string;
|
|
43
|
-
/**
|
|
44
|
-
* Call the platform's end-session endpoint so the server invalidates the session.
|
|
45
|
-
* Best-effort: failures are ignored so local logout still proceeds.
|
|
46
|
-
*/
|
|
47
|
-
export declare function callLogoutEndpoint(client: ClientConfig, token: TokenConfig | null): Promise<void>;
|
|
48
|
-
export declare function refreshAccessToken(client: ClientConfig, refreshToken: string): Promise<TokenConfig>;
|
|
49
|
-
export declare function ensureValidToken(): Promise<TokenConfig>;
|
|
50
|
-
export interface AuthLoginOptions {
|
|
51
|
-
baseUrl: string;
|
|
52
|
-
port: number;
|
|
53
|
-
clientName: string;
|
|
54
|
-
open: boolean;
|
|
55
|
-
forceRegister: boolean;
|
|
56
|
-
host?: string;
|
|
57
|
-
redirectUriOverride?: string;
|
|
58
|
-
lang?: string;
|
|
59
|
-
product?: string;
|
|
60
|
-
xForwardedPrefix?: string;
|
|
61
|
-
}
|
|
62
|
-
export declare function login(options: AuthLoginOptions): Promise<{
|
|
63
|
-
client: ClientConfig;
|
|
64
|
-
token: TokenConfig;
|
|
65
|
-
authorizationUrl: string;
|
|
66
|
-
callback: CallbackSession;
|
|
67
|
-
created: boolean;
|
|
68
|
-
}>;
|
|
69
|
-
export declare function getStoredAuthSummary(baseUrl?: string): {
|
|
70
|
-
client: ClientConfig | null;
|
|
71
|
-
token: TokenConfig | null;
|
|
72
|
-
callback: CallbackSession | null;
|
|
73
|
-
};
|
|
3
|
+
export declare function playwrightLogin(baseUrl: string, options?: {
|
|
4
|
+
username?: string;
|
|
5
|
+
password?: string;
|
|
6
|
+
}): Promise<TokenConfig>;
|
|
7
|
+
export declare function ensureValidToken(opts?: {
|
|
8
|
+
forceRefresh?: boolean;
|
|
9
|
+
}): Promise<TokenConfig>;
|
|
10
|
+
export declare function withTokenRetry<T>(fn: (token: TokenConfig) => Promise<T>): Promise<T>;
|
|
74
11
|
export declare function formatHttpError(error: unknown): string;
|
|
75
|
-
export {};
|
package/dist/auth/oauth.js
CHANGED
|
@@ -1,374 +1,130 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { openBrowser } from "../utils/browser.js";
|
|
5
|
-
import { fetchTextOrThrow, HttpError, NetworkRequestError } from "../utils/http.js";
|
|
6
|
-
import { getCurrentPlatform, loadCallbackSession, loadClientConfig, loadTokenConfig, saveCallbackSession, saveClientConfig, saveTokenConfig, setCurrentPlatform, } from "../config/store.js";
|
|
1
|
+
import { getCurrentPlatform, loadTokenConfig, saveTokenConfig, setCurrentPlatform, } from "../config/store.js";
|
|
2
|
+
import { HttpError, NetworkRequestError } from "../utils/http.js";
|
|
3
|
+
const TOKEN_TTL_SECONDS = 3600;
|
|
7
4
|
export function normalizeBaseUrl(value) {
|
|
8
5
|
return value.replace(/\/+$/, "");
|
|
9
6
|
}
|
|
10
|
-
function
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
function toBasicAuth(clientId, clientSecret) {
|
|
17
|
-
const user = encodeURIComponent(clientId);
|
|
18
|
-
const password = encodeURIComponent(clientSecret);
|
|
19
|
-
return `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`;
|
|
20
|
-
}
|
|
21
|
-
function buildTokenConfig(baseUrl, token) {
|
|
22
|
-
const obtainedAt = new Date().toISOString();
|
|
23
|
-
const expiresAt = token.expires_in === undefined
|
|
24
|
-
? undefined
|
|
25
|
-
: new Date(Date.now() + token.expires_in * 1000).toISOString();
|
|
26
|
-
return {
|
|
27
|
-
baseUrl,
|
|
28
|
-
accessToken: token.access_token,
|
|
29
|
-
tokenType: token.token_type,
|
|
30
|
-
scope: token.scope,
|
|
31
|
-
expiresIn: token.expires_in,
|
|
32
|
-
expiresAt,
|
|
33
|
-
refreshToken: token.refresh_token,
|
|
34
|
-
idToken: token.id_token,
|
|
35
|
-
obtainedAt,
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
export async function registerClient(options) {
|
|
39
|
-
const baseUrl = normalizeBaseUrl(options.baseUrl);
|
|
40
|
-
const payload = {
|
|
41
|
-
client_name: options.clientName,
|
|
42
|
-
grant_types: ["authorization_code", "implicit", "refresh_token"],
|
|
43
|
-
response_types: ["token id_token", "code", "token"],
|
|
44
|
-
scope: "openid offline all",
|
|
45
|
-
redirect_uris: [options.redirectUri],
|
|
46
|
-
post_logout_redirect_uris: [options.logoutRedirectUri],
|
|
47
|
-
metadata: {
|
|
48
|
-
device: {
|
|
49
|
-
name: options.clientName,
|
|
50
|
-
client_type: "web",
|
|
51
|
-
description: "kweaver CLI",
|
|
52
|
-
},
|
|
53
|
-
},
|
|
54
|
-
};
|
|
55
|
-
const { body } = await fetchTextOrThrow(`${baseUrl}/oauth2/clients`, {
|
|
56
|
-
method: "POST",
|
|
57
|
-
headers: {
|
|
58
|
-
"content-type": "application/json",
|
|
59
|
-
accept: "application/json",
|
|
60
|
-
},
|
|
61
|
-
body: JSON.stringify(payload),
|
|
62
|
-
});
|
|
63
|
-
const data = JSON.parse(body);
|
|
64
|
-
const clientConfig = {
|
|
65
|
-
baseUrl,
|
|
66
|
-
clientId: data.client_id,
|
|
67
|
-
clientSecret: data.client_secret,
|
|
68
|
-
redirectUri: options.redirectUri,
|
|
69
|
-
logoutRedirectUri: options.logoutRedirectUri,
|
|
70
|
-
scope: payload.scope,
|
|
71
|
-
lang: options.lang,
|
|
72
|
-
product: options.product,
|
|
73
|
-
xForwardedPrefix: options.xForwardedPrefix,
|
|
74
|
-
};
|
|
75
|
-
saveClientConfig(clientConfig);
|
|
76
|
-
return clientConfig;
|
|
77
|
-
}
|
|
78
|
-
function toSuccessfulLogoutPath(pathname) {
|
|
79
|
-
if (pathname.endsWith("/callback")) {
|
|
80
|
-
return `${pathname.slice(0, -"/callback".length)}/successful-logout`;
|
|
81
|
-
}
|
|
82
|
-
return `${pathname.replace(/\/$/, "")}/successful-logout`;
|
|
83
|
-
}
|
|
84
|
-
function normalizeListenHost(host) {
|
|
85
|
-
return host?.trim() || "127.0.0.1";
|
|
86
|
-
}
|
|
87
|
-
export function buildAuthRedirectConfig(options) {
|
|
88
|
-
const listenHost = normalizeListenHost(options.host);
|
|
89
|
-
const listenPort = options.port;
|
|
90
|
-
if (options.redirectUriOverride) {
|
|
91
|
-
const redirect = new URL(options.redirectUriOverride);
|
|
92
|
-
const logout = new URL(options.redirectUriOverride);
|
|
93
|
-
logout.pathname = toSuccessfulLogoutPath(redirect.pathname);
|
|
94
|
-
logout.search = "";
|
|
95
|
-
logout.hash = "";
|
|
96
|
-
return {
|
|
97
|
-
redirectUri: redirect.toString(),
|
|
98
|
-
logoutRedirectUri: logout.toString(),
|
|
99
|
-
listenHost,
|
|
100
|
-
listenPort,
|
|
101
|
-
callbackPath: redirect.pathname,
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
return {
|
|
105
|
-
redirectUri: `http://${listenHost}:${listenPort}/callback`,
|
|
106
|
-
logoutRedirectUri: `http://${listenHost}:${listenPort}/successful-logout`,
|
|
107
|
-
listenHost,
|
|
108
|
-
listenPort,
|
|
109
|
-
callbackPath: "/callback",
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
export async function ensureClientConfig(options) {
|
|
113
|
-
const baseUrl = normalizeBaseUrl(options.baseUrl);
|
|
114
|
-
const redirect = buildAuthRedirectConfig({
|
|
115
|
-
port: options.port,
|
|
116
|
-
host: options.host,
|
|
117
|
-
redirectUriOverride: options.redirectUriOverride,
|
|
118
|
-
});
|
|
119
|
-
const { redirectUri, logoutRedirectUri } = redirect;
|
|
120
|
-
const client = loadClientConfig(baseUrl);
|
|
121
|
-
if (client &&
|
|
122
|
-
!options.forceRegister &&
|
|
123
|
-
client.baseUrl === baseUrl &&
|
|
124
|
-
client.redirectUri === redirectUri &&
|
|
125
|
-
client.clientId &&
|
|
126
|
-
client.clientSecret) {
|
|
127
|
-
return { client, created: false };
|
|
7
|
+
export async function playwrightLogin(baseUrl, options) {
|
|
8
|
+
let chromium;
|
|
9
|
+
try {
|
|
10
|
+
const modName = "playwright";
|
|
11
|
+
const pw = await import(/* webpackIgnore: true */ modName);
|
|
12
|
+
chromium = pw.chromium;
|
|
128
13
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
clientName: options.clientName,
|
|
132
|
-
redirectUri,
|
|
133
|
-
logoutRedirectUri,
|
|
134
|
-
lang: options.lang,
|
|
135
|
-
product: options.product,
|
|
136
|
-
xForwardedPrefix: options.xForwardedPrefix,
|
|
137
|
-
});
|
|
138
|
-
return {
|
|
139
|
-
client: createdClient,
|
|
140
|
-
created: true,
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
export function buildAuthorizationUrl(client, state = randomValue(12)) {
|
|
144
|
-
const authorizationUrl = new URL(`${client.baseUrl}/oauth2/auth`);
|
|
145
|
-
authorizationUrl.searchParams.set("redirect_uri", client.redirectUri);
|
|
146
|
-
authorizationUrl.searchParams.set("x-forwarded-prefix", client.xForwardedPrefix ?? "");
|
|
147
|
-
authorizationUrl.searchParams.set("client_id", client.clientId);
|
|
148
|
-
authorizationUrl.searchParams.set("scope", client.scope);
|
|
149
|
-
authorizationUrl.searchParams.set("response_type", "code");
|
|
150
|
-
authorizationUrl.searchParams.set("state", state);
|
|
151
|
-
authorizationUrl.searchParams.set("lang", client.lang ?? "zh-cn");
|
|
152
|
-
if (client.product) {
|
|
153
|
-
authorizationUrl.searchParams.set("product", client.product);
|
|
14
|
+
catch {
|
|
15
|
+
throw new Error("Playwright is not installed. Run:\n npm install playwright && npx playwright install chromium");
|
|
154
16
|
}
|
|
155
|
-
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
response.statusCode = 400;
|
|
183
|
-
response.end("State mismatch");
|
|
184
|
-
server.close();
|
|
185
|
-
reject(new Error("State mismatch in OAuth callback"));
|
|
186
|
-
return;
|
|
17
|
+
const hasCredentials = options?.username && options?.password;
|
|
18
|
+
const browser = await chromium.launch({ headless: hasCredentials ? true : false });
|
|
19
|
+
try {
|
|
20
|
+
const context = await browser.newContext();
|
|
21
|
+
const page = await context.newPage();
|
|
22
|
+
await page.goto(`${baseUrl}/api/dip-hub/v1/login`, {
|
|
23
|
+
waitUntil: "networkidle",
|
|
24
|
+
timeout: 30_000,
|
|
25
|
+
});
|
|
26
|
+
if (hasCredentials) {
|
|
27
|
+
// Headless mode: auto-fill credentials
|
|
28
|
+
await page.waitForSelector('input[name="account"]', { timeout: 10_000 });
|
|
29
|
+
await page.fill('input[name="account"]', options.username);
|
|
30
|
+
await page.fill('input[name="password"]', options.password);
|
|
31
|
+
await page.click("button.ant-btn-primary");
|
|
32
|
+
}
|
|
33
|
+
// else: headed mode — user logs in manually in the browser window
|
|
34
|
+
const TIMEOUT_SECONDS = hasCredentials ? 30 : 120;
|
|
35
|
+
let accessToken = null;
|
|
36
|
+
for (let i = 0; i < TIMEOUT_SECONDS; i++) {
|
|
37
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
38
|
+
// Check cookies (works even after navigation)
|
|
39
|
+
for (const cookie of await context.cookies()) {
|
|
40
|
+
if (cookie.name === "dip.oauth2_token") {
|
|
41
|
+
accessToken = decodeURIComponent(cookie.value);
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
187
44
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
45
|
+
if (accessToken)
|
|
46
|
+
break;
|
|
47
|
+
// In headless mode, check for login error messages
|
|
48
|
+
if (hasCredentials) {
|
|
49
|
+
try {
|
|
50
|
+
const errorEl = await page.$(".ant-message-error, .ant-alert-error");
|
|
51
|
+
if (errorEl) {
|
|
52
|
+
const errorText = await errorEl.textContent();
|
|
53
|
+
throw new Error(`Login failed: ${errorText?.trim() || "unknown error"}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
if (e instanceof Error && e.message.startsWith("Login failed:"))
|
|
58
|
+
throw e;
|
|
59
|
+
}
|
|
195
60
|
}
|
|
196
|
-
response.statusCode = 200;
|
|
197
|
-
response.setHeader("content-type", "text/plain; charset=utf-8");
|
|
198
|
-
response.end(getAuthorizationSuccessMessage());
|
|
199
|
-
server.close();
|
|
200
|
-
resolve({
|
|
201
|
-
code,
|
|
202
|
-
state,
|
|
203
|
-
scope: callbackUrl.searchParams.get("scope") ?? undefined,
|
|
204
|
-
});
|
|
205
|
-
});
|
|
206
|
-
server.on("error", (error) => reject(error));
|
|
207
|
-
server.listen(listenPort, listenHost);
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
async function exchangeAuthorizationCode(client, code) {
|
|
211
|
-
const payload = new URLSearchParams({
|
|
212
|
-
grant_type: "authorization_code",
|
|
213
|
-
code,
|
|
214
|
-
redirect_uri: client.redirectUri,
|
|
215
|
-
});
|
|
216
|
-
const { body } = await fetchTextOrThrow(`${client.baseUrl}/oauth2/token`, {
|
|
217
|
-
method: "POST",
|
|
218
|
-
headers: {
|
|
219
|
-
"content-type": "application/x-www-form-urlencoded",
|
|
220
|
-
accept: "application/json",
|
|
221
|
-
authorization: toBasicAuth(client.clientId, client.clientSecret),
|
|
222
|
-
},
|
|
223
|
-
body: payload.toString(),
|
|
224
|
-
});
|
|
225
|
-
const tokenConfig = buildTokenConfig(client.baseUrl, JSON.parse(body));
|
|
226
|
-
saveTokenConfig(tokenConfig);
|
|
227
|
-
return tokenConfig;
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Call the platform's end-session endpoint so the server invalidates the session.
|
|
231
|
-
* Best-effort: failures are ignored so local logout still proceeds.
|
|
232
|
-
*/
|
|
233
|
-
export async function callLogoutEndpoint(client, token) {
|
|
234
|
-
const url = new URL(`${client.baseUrl}/oauth2/signout`);
|
|
235
|
-
if (token?.idToken) {
|
|
236
|
-
url.searchParams.set("id_token_hint", token.idToken);
|
|
237
|
-
}
|
|
238
|
-
url.searchParams.set("post_logout_redirect_uri", client.logoutRedirectUri);
|
|
239
|
-
url.searchParams.set("client_id", client.clientId);
|
|
240
|
-
try {
|
|
241
|
-
const response = await fetch(url.toString(), { method: "GET", redirect: "manual" });
|
|
242
|
-
if (!response.ok && response.status !== 302) {
|
|
243
|
-
const body = await response.text();
|
|
244
|
-
console.error(`Logout endpoint returned ${response.status}: ${body.slice(0, 200)}`);
|
|
245
61
|
}
|
|
62
|
+
if (!accessToken) {
|
|
63
|
+
throw new Error(`Login timed out: dip.oauth2_token cookie not received within ${TIMEOUT_SECONDS} seconds.`);
|
|
64
|
+
}
|
|
65
|
+
const now = new Date();
|
|
66
|
+
const tokenConfig = {
|
|
67
|
+
baseUrl,
|
|
68
|
+
accessToken,
|
|
69
|
+
tokenType: "bearer",
|
|
70
|
+
scope: "",
|
|
71
|
+
expiresIn: TOKEN_TTL_SECONDS,
|
|
72
|
+
expiresAt: new Date(now.getTime() + TOKEN_TTL_SECONDS * 1000).toISOString(),
|
|
73
|
+
obtainedAt: now.toISOString(),
|
|
74
|
+
};
|
|
75
|
+
saveTokenConfig(tokenConfig);
|
|
76
|
+
setCurrentPlatform(baseUrl);
|
|
77
|
+
return tokenConfig;
|
|
246
78
|
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
console.error(`Logout endpoint request failed: ${msg}`);
|
|
79
|
+
finally {
|
|
80
|
+
await browser.close();
|
|
250
81
|
}
|
|
251
82
|
}
|
|
252
|
-
export async function
|
|
253
|
-
const payload = new URLSearchParams({
|
|
254
|
-
grant_type: "refresh_token",
|
|
255
|
-
refresh_token: refreshToken,
|
|
256
|
-
});
|
|
257
|
-
const { body } = await fetchTextOrThrow(`${client.baseUrl}/oauth2/token`, {
|
|
258
|
-
method: "POST",
|
|
259
|
-
headers: {
|
|
260
|
-
"content-type": "application/x-www-form-urlencoded",
|
|
261
|
-
accept: "application/json",
|
|
262
|
-
authorization: toBasicAuth(client.clientId, client.clientSecret),
|
|
263
|
-
},
|
|
264
|
-
body: payload.toString(),
|
|
265
|
-
});
|
|
266
|
-
const parsed = JSON.parse(body);
|
|
267
|
-
const tokenConfig = buildTokenConfig(client.baseUrl, {
|
|
268
|
-
...parsed,
|
|
269
|
-
refresh_token: parsed.refresh_token ?? refreshToken,
|
|
270
|
-
});
|
|
271
|
-
saveTokenConfig(tokenConfig);
|
|
272
|
-
return tokenConfig;
|
|
273
|
-
}
|
|
274
|
-
export async function ensureValidToken() {
|
|
83
|
+
export async function ensureValidToken(opts) {
|
|
275
84
|
const envToken = process.env.KWEAVER_TOKEN;
|
|
276
85
|
const envBaseUrl = process.env.KWEAVER_BASE_URL;
|
|
277
|
-
if (envToken && envBaseUrl) {
|
|
86
|
+
if (!opts?.forceRefresh && envToken && envBaseUrl) {
|
|
87
|
+
const rawToken = envToken.replace(/^Bearer\s+/i, "");
|
|
278
88
|
return {
|
|
279
89
|
baseUrl: normalizeBaseUrl(envBaseUrl),
|
|
280
|
-
accessToken:
|
|
90
|
+
accessToken: rawToken,
|
|
281
91
|
tokenType: "bearer",
|
|
282
|
-
scope: "
|
|
92
|
+
scope: "",
|
|
283
93
|
obtainedAt: new Date().toISOString(),
|
|
284
94
|
};
|
|
285
95
|
}
|
|
286
96
|
const currentPlatform = getCurrentPlatform();
|
|
287
97
|
if (!currentPlatform) {
|
|
288
|
-
throw new Error("No active platform selected. Run `kweaver auth <platform-url>` first.");
|
|
98
|
+
throw new Error("No active platform selected. Run `kweaver auth login <platform-url>` first.");
|
|
289
99
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
if (!client || !token) {
|
|
293
|
-
throw new Error(`Missing saved credentials for ${currentPlatform}. Run \`kweaver auth ${currentPlatform}\` first.`);
|
|
100
|
+
if (opts?.forceRefresh) {
|
|
101
|
+
throw new Error(`Token refresh is not supported. Run \`kweaver auth login ${currentPlatform}\` again.`);
|
|
294
102
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
const expiresAtMs = Date.parse(token.expiresAt);
|
|
299
|
-
if (Number.isNaN(expiresAtMs) || expiresAtMs - 60_000 > Date.now()) {
|
|
300
|
-
return token;
|
|
103
|
+
const token = loadTokenConfig(currentPlatform);
|
|
104
|
+
if (!token) {
|
|
105
|
+
throw new Error(`No saved token for ${currentPlatform}. Run \`kweaver auth login ${currentPlatform}\` first.`);
|
|
301
106
|
}
|
|
302
|
-
if (
|
|
303
|
-
|
|
107
|
+
if (token.expiresAt) {
|
|
108
|
+
const expiresAtMs = Date.parse(token.expiresAt);
|
|
109
|
+
if (!Number.isNaN(expiresAtMs) && expiresAtMs - 60_000 <= Date.now()) {
|
|
110
|
+
throw new Error(`Access token expired. Run \`kweaver auth login ${currentPlatform}\` again.`);
|
|
111
|
+
}
|
|
304
112
|
}
|
|
305
|
-
return
|
|
113
|
+
return token;
|
|
306
114
|
}
|
|
307
|
-
export async function
|
|
308
|
-
const
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
redirectUriOverride: options.redirectUriOverride,
|
|
312
|
-
});
|
|
313
|
-
const { client, created } = await ensureClientConfig({
|
|
314
|
-
baseUrl: options.baseUrl,
|
|
315
|
-
port: options.port,
|
|
316
|
-
clientName: options.clientName,
|
|
317
|
-
forceRegister: options.forceRegister,
|
|
318
|
-
host: options.host,
|
|
319
|
-
redirectUriOverride: options.redirectUriOverride,
|
|
320
|
-
lang: options.lang,
|
|
321
|
-
product: options.product,
|
|
322
|
-
xForwardedPrefix: options.xForwardedPrefix,
|
|
323
|
-
});
|
|
324
|
-
const state = randomValue(12);
|
|
325
|
-
const authorizationUrl = buildAuthorizationUrl(client, state);
|
|
326
|
-
const waitForCode = waitForAuthorizationCode({
|
|
327
|
-
listenHost: redirect.listenHost,
|
|
328
|
-
listenPort: redirect.listenPort,
|
|
329
|
-
callbackPath: redirect.callbackPath,
|
|
330
|
-
}, state);
|
|
331
|
-
if (options.open) {
|
|
332
|
-
console.log(`Opening browser for authorization: ${authorizationUrl}`);
|
|
333
|
-
const opened = await openBrowser(authorizationUrl);
|
|
334
|
-
if (!opened) {
|
|
335
|
-
console.error("Failed to open a browser automatically. Open this URL manually:");
|
|
336
|
-
console.error(authorizationUrl);
|
|
337
|
-
}
|
|
115
|
+
export async function withTokenRetry(fn) {
|
|
116
|
+
const token = await ensureValidToken();
|
|
117
|
+
try {
|
|
118
|
+
return await fn(token);
|
|
338
119
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
console.log(`Waiting for OAuth callback on http://${redirect.listenHost}:${redirect.listenPort}${redirect.callbackPath}`);
|
|
345
|
-
if (redirect.listenHost === "127.0.0.1" || redirect.listenHost === "localhost") {
|
|
346
|
-
console.log("");
|
|
347
|
-
console.log("If your browser is on another machine, use SSH port forwarding first:");
|
|
348
|
-
console.log(`ssh -L ${redirect.listenPort}:127.0.0.1:${redirect.listenPort} user@server`);
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (error instanceof HttpError && error.status === 401) {
|
|
122
|
+
const platform = token.baseUrl;
|
|
123
|
+
throw new Error(`Authentication failed (401). Token may be expired or revoked.\n` +
|
|
124
|
+
`Run \`kweaver auth login ${platform}\` again.`);
|
|
349
125
|
}
|
|
126
|
+
throw error;
|
|
350
127
|
}
|
|
351
|
-
const callbackResult = await waitForCode;
|
|
352
|
-
const callback = {
|
|
353
|
-
baseUrl: client.baseUrl,
|
|
354
|
-
redirectUri: client.redirectUri,
|
|
355
|
-
code: callbackResult.code,
|
|
356
|
-
state: callbackResult.state,
|
|
357
|
-
scope: callbackResult.scope,
|
|
358
|
-
receivedAt: new Date().toISOString(),
|
|
359
|
-
};
|
|
360
|
-
saveCallbackSession(callback);
|
|
361
|
-
const token = await exchangeAuthorizationCode(client, callbackResult.code);
|
|
362
|
-
setCurrentPlatform(client.baseUrl);
|
|
363
|
-
return { client, token, authorizationUrl, callback, created };
|
|
364
|
-
}
|
|
365
|
-
export function getStoredAuthSummary(baseUrl) {
|
|
366
|
-
const targetBaseUrl = baseUrl ?? getCurrentPlatform() ?? undefined;
|
|
367
|
-
return {
|
|
368
|
-
client: loadClientConfig(targetBaseUrl),
|
|
369
|
-
token: loadTokenConfig(targetBaseUrl),
|
|
370
|
-
callback: loadCallbackSession(targetBaseUrl),
|
|
371
|
-
};
|
|
372
128
|
}
|
|
373
129
|
function formatOAuthErrorBody(body) {
|
|
374
130
|
let data;
|
package/dist/cli.js
CHANGED
|
@@ -2,9 +2,11 @@ import { runAgentCommand } from "./commands/agent.js";
|
|
|
2
2
|
import { runAuthCommand } from "./commands/auth.js";
|
|
3
3
|
import { runKnCommand } from "./commands/bkn.js";
|
|
4
4
|
import { runCallCommand } from "./commands/call.js";
|
|
5
|
+
import { runConfigCommand } from "./commands/config.js";
|
|
5
6
|
import { runContextLoaderCommand } from "./commands/context-loader.js";
|
|
6
7
|
import { runDsCommand } from "./commands/ds.js";
|
|
7
8
|
import { runTokenCommand } from "./commands/token.js";
|
|
9
|
+
import { runVegaCommand } from "./commands/vega.js";
|
|
8
10
|
function printHelp() {
|
|
9
11
|
console.log(`kweaver
|
|
10
12
|
|
|
@@ -31,6 +33,8 @@ Usage:
|
|
|
31
33
|
kweaver bkn create [options]
|
|
32
34
|
kweaver bkn update <kn-id> [options]
|
|
33
35
|
kweaver bkn delete <kn-id>
|
|
36
|
+
kweaver config [set-bd|show]
|
|
37
|
+
kweaver vega [health|stats|inspect|catalog|resource|connector-type]
|
|
34
38
|
kweaver context-loader [config|kn-search|...]
|
|
35
39
|
kweaver --help
|
|
36
40
|
|
|
@@ -41,6 +45,8 @@ Commands:
|
|
|
41
45
|
ds Manage datasources (list, get, delete, tables, connect)
|
|
42
46
|
agent Chat with a KWeaver agent (agent chat <id>), list published agents (agent list)
|
|
43
47
|
bkn Business knowledge network (list/get/create/update/delete/export/stats; object-type, subgraph, action-type, action-log)
|
|
48
|
+
config Per-platform configuration (business domain)
|
|
49
|
+
vega Vega observability platform (catalogs, resources, connector-types, health)
|
|
44
50
|
context-loader Call context-loader MCP (tools, resources, prompts; kn-search, query-*, etc.)
|
|
45
51
|
help Show this message`);
|
|
46
52
|
}
|
|
@@ -68,6 +74,12 @@ export async function run(argv) {
|
|
|
68
74
|
if (command === "bkn") {
|
|
69
75
|
return runKnCommand(rest);
|
|
70
76
|
}
|
|
77
|
+
if (command === "vega") {
|
|
78
|
+
return runVegaCommand(rest);
|
|
79
|
+
}
|
|
80
|
+
if (command === "config") {
|
|
81
|
+
return runConfigCommand(rest);
|
|
82
|
+
}
|
|
71
83
|
if (command === "context-loader" || command === "context") {
|
|
72
84
|
return runContextLoaderCommand(rest);
|
|
73
85
|
}
|
package/dist/client.d.ts
CHANGED
|
@@ -31,6 +31,12 @@ export interface KWeaverClientOptions {
|
|
|
31
31
|
* Override with KWEAVER_BUSINESS_DOMAIN env var or pass explicitly.
|
|
32
32
|
*/
|
|
33
33
|
businessDomain?: string;
|
|
34
|
+
/**
|
|
35
|
+
* When true, read credentials exclusively from ~/.kweaver/ (saved by
|
|
36
|
+
* `kweaver auth login`), ignoring KWEAVER_BASE_URL / KWEAVER_TOKEN env vars.
|
|
37
|
+
* Useful when env vars hold stale tokens or are intended for other tooling.
|
|
38
|
+
*/
|
|
39
|
+
config?: boolean;
|
|
34
40
|
}
|
|
35
41
|
/**
|
|
36
42
|
* Main entry point for the KWeaver TypeScript SDK.
|
|
@@ -73,6 +79,19 @@ export declare class KWeaverClient implements ClientContext {
|
|
|
73
79
|
/** Conversation and message history. */
|
|
74
80
|
readonly conversations: ConversationsResource;
|
|
75
81
|
constructor(opts?: KWeaverClientOptions);
|
|
82
|
+
/**
|
|
83
|
+
* Async factory that auto-refreshes expired or revoked tokens.
|
|
84
|
+
*
|
|
85
|
+
* Reads credentials from `~/.kweaver/` and refreshes the access token
|
|
86
|
+
* if it has expired or been revoked (using the saved refresh token).
|
|
87
|
+
* If the initial token fails with 401, forces a refresh and retries.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```typescript
|
|
91
|
+
* const client = await KWeaverClient.connect();
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
static connect(opts?: KWeaverClientOptions): Promise<KWeaverClient>;
|
|
76
95
|
/** @internal — used by resource classes to build API call options. */
|
|
77
96
|
base(): {
|
|
78
97
|
baseUrl: string;
|