@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.
@@ -1,75 +1,11 @@
1
- import { type CallbackSession, type ClientConfig, type TokenConfig } from "../config/store.js";
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 getAuthorizationSuccessMessage(): string;
13
- export declare function registerClient(options: RegisterClientOptions): Promise<ClientConfig>;
14
- export interface EnsureClientOptions {
15
- baseUrl: string;
16
- port: number;
17
- clientName: string;
18
- forceRegister: boolean;
19
- host?: string;
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 {};
@@ -1,374 +1,130 @@
1
- import { createServer } from "node:http";
2
- import { randomBytes } from "node:crypto";
3
- import { URL } from "node:url";
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 randomValue(size = 24) {
11
- return randomBytes(size).toString("hex");
12
- }
13
- export function getAuthorizationSuccessMessage() {
14
- return "Authorization succeeded. You can close this page and return to the terminal.";
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
- const createdClient = await registerClient({
130
- baseUrl,
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
- return authorizationUrl.toString();
156
- }
157
- function waitForAuthorizationCode(options, expectedState) {
158
- const { listenHost, listenPort, callbackPath } = options;
159
- return new Promise((resolve, reject) => {
160
- const server = createServer((request, response) => {
161
- if (!request.url) {
162
- response.statusCode = 400;
163
- response.end("Missing request URL");
164
- return;
165
- }
166
- const callbackUrl = new URL(request.url, `http://${request.headers.host ?? `${listenHost}:${listenPort}`}`);
167
- if (callbackUrl.pathname !== callbackPath) {
168
- response.statusCode = 404;
169
- response.end("Not Found");
170
- return;
171
- }
172
- const error = callbackUrl.searchParams.get("error");
173
- if (error) {
174
- response.statusCode = 400;
175
- response.end(`Authorization failed: ${error}`);
176
- server.close();
177
- reject(new Error(`Authorization failed: ${error}`));
178
- return;
179
- }
180
- const state = callbackUrl.searchParams.get("state");
181
- if (state !== expectedState) {
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
- const code = callbackUrl.searchParams.get("code");
189
- if (!code) {
190
- response.statusCode = 400;
191
- response.end("Missing authorization code");
192
- server.close();
193
- reject(new Error("Missing authorization code"));
194
- return;
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
- catch (err) {
248
- const msg = err instanceof Error ? err.message : String(err);
249
- console.error(`Logout endpoint request failed: ${msg}`);
79
+ finally {
80
+ await browser.close();
250
81
  }
251
82
  }
252
- export async function refreshAccessToken(client, refreshToken) {
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: envToken,
90
+ accessToken: rawToken,
281
91
  tokenType: "bearer",
282
- scope: "openid",
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
- const client = loadClientConfig(currentPlatform);
291
- const token = loadTokenConfig(currentPlatform);
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
- if (!token.expiresAt) {
296
- return token;
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 (!token.refreshToken) {
303
- throw new Error("Access token expired and no refresh token is available. Run auth login again.");
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 refreshAccessToken(client, token.refreshToken);
113
+ return token;
306
114
  }
307
- export async function login(options) {
308
- const redirect = buildAuthRedirectConfig({
309
- port: options.port,
310
- host: options.host,
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
- else {
340
- console.log("Authorization URL:");
341
- console.log(authorizationUrl);
342
- console.log("");
343
- console.log(`Redirect URI: ${client.redirectUri}`);
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;