@kweaver-ai/kweaver-sdk 0.4.13 → 0.4.14

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 CHANGED
@@ -31,6 +31,18 @@ export KWEAVER_BASE_URL=https://your-kweaver-instance.com
31
31
  export KWEAVER_TOKEN=your-token
32
32
  ```
33
33
 
34
+ ### Business domain (platform)
35
+
36
+ Set or verify **before** calling list/query APIs that scope by tenant. DIP deployments often need a UUID, not only `bd_public`.
37
+
38
+ ```bash
39
+ kweaver config show
40
+ kweaver config list-bd
41
+ kweaver config set-bd <uuid>
42
+ ```
43
+
44
+ After `kweaver auth login`, the CLI may auto-select a domain when none is saved yet. Override with `KWEAVER_BUSINESS_DOMAIN` or `-bd` / `--biz-domain` on commands. See [`../../skills/kweaver-core/references/config.md`](../../skills/kweaver-core/references/config.md).
45
+
34
46
  ### Simple API (recommended)
35
47
 
36
48
  ```typescript
@@ -130,8 +142,8 @@ kweaver auth login <url> [--alias name] [-u user] [-p pass] [--playwright] [--in
130
142
  kweaver auth login <url> --client-id ID --client-secret S --refresh-token T (headless login)
131
143
  kweaver auth export [url|alias] [--json] (export command to run on a headless host)
132
144
  kweaver auth status/list/use/delete/logout
145
+ kweaver config show / list-bd / set-bd <value> # platform business domain — after login
133
146
  kweaver token
134
- kweaver config show / set-bd <value>
135
147
  kweaver ds list/get/delete/tables/connect
136
148
  kweaver ds import-csv <ds_id> --files <glob> [--table-prefix <p>] [--batch-size 500]
137
149
  kweaver dataview list/find/get/query/delete
package/README.zh.md CHANGED
@@ -31,6 +31,18 @@ export KWEAVER_BASE_URL=https://your-kweaver-instance.com
31
31
  export KWEAVER_TOKEN=your-token
32
32
  ```
33
33
 
34
+ ### 业务域(平台配置)
35
+
36
+ 在调用依赖租户范围的接口前,应先确认业务域;DIP 环境通常使用 **UUID**,不能长期只依赖默认 `bd_public`。
37
+
38
+ ```bash
39
+ kweaver config show
40
+ kweaver config list-bd
41
+ kweaver config set-bd <uuid>
42
+ ```
43
+
44
+ `kweaver auth login` 成功后,若尚未配置,CLI 可能自动选择业务域。也可用环境变量 `KWEAVER_BUSINESS_DOMAIN` 或各命令的 `-bd` / `--biz-domain` 覆盖。详见 [`../../skills/kweaver-core/references/config.md`](../../skills/kweaver-core/references/config.md)。
45
+
34
46
  ### 简洁 API(推荐)
35
47
 
36
48
  ```typescript
@@ -119,6 +131,7 @@ kweaver auth login <url> [--alias name] [-u user] [-p pass] [--playwright] [--in
119
131
  kweaver auth login <url> --client-id ID --client-secret S --refresh-token T (无浏览器登录)
120
132
  kweaver auth export [url|alias] [--json] (导出在无浏览器机器上运行的命令)
121
133
  kweaver auth status/list/use/delete/logout
134
+ kweaver config show / list-bd / set-bd <value> # 平台业务域,登录后优先
122
135
  kweaver token
123
136
  kweaver ds list/get/delete/tables/connect
124
137
  kweaver dataview list/find/get/query/delete
@@ -0,0 +1,20 @@
1
+ /** One business domain entry from GET /api/business-system/v1/business-domain */
2
+ export interface BusinessDomain {
3
+ id: string;
4
+ name?: string;
5
+ description?: string;
6
+ creator?: string;
7
+ products?: string[];
8
+ create_time?: string;
9
+ }
10
+ export interface ListBusinessDomainsOptions {
11
+ baseUrl: string;
12
+ accessToken: string;
13
+ /** When true, skip TLS verification (matches `--insecure` login). */
14
+ tlsInsecure?: boolean;
15
+ }
16
+ /**
17
+ * List business domains for the authenticated user. Does not send x-business-domain
18
+ * (the endpoint returns all domains the user can access).
19
+ */
20
+ export declare function listBusinessDomains(options: ListBusinessDomainsOptions): Promise<BusinessDomain[]>;
@@ -0,0 +1,54 @@
1
+ import { HttpError } from "../utils/http.js";
2
+ async function withTlsInsecure(tlsInsecure, fn) {
3
+ if (!tlsInsecure) {
4
+ return fn();
5
+ }
6
+ const prev = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
7
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
8
+ try {
9
+ return await fn();
10
+ }
11
+ finally {
12
+ if (prev === undefined) {
13
+ delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
14
+ }
15
+ else {
16
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = prev;
17
+ }
18
+ }
19
+ }
20
+ /**
21
+ * List business domains for the authenticated user. Does not send x-business-domain
22
+ * (the endpoint returns all domains the user can access).
23
+ */
24
+ export async function listBusinessDomains(options) {
25
+ const { baseUrl, accessToken, tlsInsecure } = options;
26
+ const base = baseUrl.replace(/\/+$/, "");
27
+ const url = `${base}/api/business-system/v1/business-domain`;
28
+ return withTlsInsecure(tlsInsecure, async () => {
29
+ const response = await fetch(url, {
30
+ method: "GET",
31
+ headers: {
32
+ accept: "application/json, text/plain, */*",
33
+ authorization: `Bearer ${accessToken}`,
34
+ token: accessToken,
35
+ },
36
+ });
37
+ const body = await response.text();
38
+ if (!response.ok) {
39
+ throw new HttpError(response.status, response.statusText, body);
40
+ }
41
+ const data = JSON.parse(body);
42
+ if (!Array.isArray(data)) {
43
+ throw new Error("Business domain list response was not a JSON array.");
44
+ }
45
+ return data.map((item) => {
46
+ const row = item;
47
+ const id = row.id;
48
+ if (typeof id !== "string" || id.length === 0) {
49
+ throw new Error("Business domain entry missing string id.");
50
+ }
51
+ return item;
52
+ });
53
+ });
54
+ }
@@ -60,6 +60,15 @@ export declare function refreshTokenLogin(baseUrl: string, options: {
60
60
  * Persists the new token to ~/.kweaver/ and returns it.
61
61
  */
62
62
  export declare function refreshAccessToken(token: TokenConfig): Promise<TokenConfig>;
63
+ /**
64
+ * Resolve a usable access token for the current platform.
65
+ *
66
+ * **Default behavior** (saved `~/.kweaver/` session from OAuth2 code login): when the access
67
+ * token is expired or near expiry, automatically exchanges the saved **refresh_token** for a new
68
+ * access token (OAuth2 `refresh_token` grant) and persists it. No extra flags are required.
69
+ *
70
+ * Static env `KWEAVER_TOKEN` bypasses refresh (see implementation).
71
+ */
63
72
  export declare function ensureValidToken(opts?: {
64
73
  forceRefresh?: boolean;
65
74
  }): Promise<TokenConfig>;
@@ -592,6 +592,15 @@ export async function refreshAccessToken(token) {
592
592
  saveTokenConfig(newToken);
593
593
  return newToken;
594
594
  }
595
+ /**
596
+ * Resolve a usable access token for the current platform.
597
+ *
598
+ * **Default behavior** (saved `~/.kweaver/` session from OAuth2 code login): when the access
599
+ * token is expired or near expiry, automatically exchanges the saved **refresh_token** for a new
600
+ * access token (OAuth2 `refresh_token` grant) and persists it. No extra flags are required.
601
+ *
602
+ * Static env `KWEAVER_TOKEN` bypasses refresh (see implementation).
603
+ */
595
604
  export async function ensureValidToken(opts) {
596
605
  const envToken = process.env.KWEAVER_TOKEN;
597
606
  const envBaseUrl = process.env.KWEAVER_BASE_URL;
package/dist/cli.js CHANGED
@@ -77,6 +77,7 @@ Usage:
77
77
  kweaver bkn action-log list|get|cancel <kn-id> ...
78
78
 
79
79
  kweaver config set-bd <value>
80
+ kweaver config list-bd
80
81
  kweaver config show
81
82
 
82
83
  kweaver vega health|stats|inspect
@@ -1,4 +1,4 @@
1
- import { clearPlatformSession, deletePlatform, getConfigDir, getCurrentPlatform, getPlatformAlias, hasPlatform, listPlatforms, loadClientConfig, loadTokenConfig, resolvePlatformIdentifier, setCurrentPlatform, setPlatformAlias, } from "../config/store.js";
1
+ import { autoSelectBusinessDomain, clearPlatformSession, deletePlatform, getConfigDir, getCurrentPlatform, getPlatformAlias, hasPlatform, listPlatforms, loadClientConfig, loadTokenConfig, resolvePlatformIdentifier, setCurrentPlatform, setPlatformAlias, } from "../config/store.js";
2
2
  import { buildCopyCommand, formatHttpError, normalizeBaseUrl, oauth2Login, playwrightLogin, refreshTokenLogin, } from "../auth/oauth.js";
3
3
  export async function runAuthCommand(args) {
4
4
  const target = args[0];
@@ -115,6 +115,10 @@ Login options:
115
115
  if (token.expiresAt) {
116
116
  console.log(`Token expires at: ${token.expiresAt}`);
117
117
  }
118
+ const selectedBd = await autoSelectBusinessDomain(normalizedTarget, token.accessToken, {
119
+ tlsInsecure: token.tlsInsecure,
120
+ });
121
+ console.log(`Business domain: ${selectedBd}`);
118
122
  return 0;
119
123
  }
120
124
  catch (error) {
@@ -1,13 +1,17 @@
1
- import { getCurrentPlatform, resolveBusinessDomain, savePlatformBusinessDomain, loadPlatformBusinessDomain, } from "../config/store.js";
1
+ import { listBusinessDomains } from "../api/business-domains.js";
2
+ import { withTokenRetry } from "../auth/oauth.js";
3
+ import { getCurrentPlatform, loadPlatformBusinessDomain, resolveBusinessDomain, savePlatformBusinessDomain, } from "../config/store.js";
2
4
  const HELP = `kweaver config
3
5
 
4
6
  Subcommands:
5
7
  set-bd <value> Set the default business domain for the current platform
8
+ list-bd List business domains as JSON (requires login)
6
9
  show Show current config (platform, business domain)
7
10
  --help Show this message
8
11
 
9
12
  Examples:
10
13
  kweaver config set-bd 54308785-4438-43df-9490-a7fd11df5765
14
+ kweaver config list-bd
11
15
  kweaver config show`;
12
16
  export async function runConfigCommand(args) {
13
17
  const [sub, ...rest] = args;
@@ -46,6 +50,35 @@ export async function runConfigCommand(args) {
46
50
  console.log(`Business domain set to: ${value}`);
47
51
  return 0;
48
52
  }
53
+ if (sub === "list-bd") {
54
+ const platform = getCurrentPlatform();
55
+ if (!platform) {
56
+ console.error("No active platform. Run `kweaver auth login <url>` first.");
57
+ return 1;
58
+ }
59
+ try {
60
+ const rows = await withTokenRetry((token) => listBusinessDomains({
61
+ baseUrl: platform,
62
+ accessToken: token.accessToken,
63
+ tlsInsecure: token.tlsInsecure,
64
+ }));
65
+ const currentId = resolveBusinessDomain(platform);
66
+ const payload = {
67
+ currentId,
68
+ domains: rows.map((r) => ({
69
+ ...r,
70
+ current: r.id === currentId,
71
+ })),
72
+ };
73
+ console.log(JSON.stringify(payload, null, 2));
74
+ return 0;
75
+ }
76
+ catch (error) {
77
+ const message = error instanceof Error ? error.message : String(error);
78
+ console.error(`Failed to list business domains: ${message}`);
79
+ return 1;
80
+ }
81
+ }
49
82
  console.error(`Unknown config subcommand: ${sub}`);
50
83
  console.log(HELP);
51
84
  return 1;
@@ -78,3 +78,11 @@ export declare function savePlatformBusinessDomain(baseUrl: string, businessDoma
78
78
  * If baseUrl is omitted, uses the current platform.
79
79
  */
80
80
  export declare function resolveBusinessDomain(baseUrl?: string): string;
81
+ /**
82
+ * Pick and persist a default business domain after login when none is configured.
83
+ * Skips API calls when KWEAVER_BUSINESS_DOMAIN is set or config already has businessDomain.
84
+ * Preference: bd_public if present in the list, else first item; empty list or failure → bd_public (not saved).
85
+ */
86
+ export declare function autoSelectBusinessDomain(baseUrl: string, accessToken: string, options?: {
87
+ tlsInsecure?: boolean;
88
+ }): Promise<string>;
@@ -1,6 +1,7 @@
1
1
  import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
+ import { listBusinessDomains } from "../api/business-domains.js";
4
5
  const MCP_PATH = "/api/agent-retrieval/v1/mcp";
5
6
  function buildMcpUrl(baseUrl) {
6
7
  return baseUrl.replace(/\/+$/, "") + MCP_PATH;
@@ -394,3 +395,41 @@ export function resolveBusinessDomain(baseUrl) {
394
395
  }
395
396
  return "bd_public";
396
397
  }
398
+ /**
399
+ * Pick and persist a default business domain after login when none is configured.
400
+ * Skips API calls when KWEAVER_BUSINESS_DOMAIN is set or config already has businessDomain.
401
+ * Preference: bd_public if present in the list, else first item; empty list or failure → bd_public (not saved).
402
+ */
403
+ export async function autoSelectBusinessDomain(baseUrl, accessToken, options) {
404
+ if (process.env.KWEAVER_BUSINESS_DOMAIN) {
405
+ return process.env.KWEAVER_BUSINESS_DOMAIN;
406
+ }
407
+ const configured = loadPlatformBusinessDomain(baseUrl);
408
+ if (configured) {
409
+ return configured;
410
+ }
411
+ try {
412
+ const list = await listBusinessDomains({
413
+ baseUrl,
414
+ accessToken,
415
+ tlsInsecure: options?.tlsInsecure,
416
+ });
417
+ let selected;
418
+ if (list.some((d) => d.id === "bd_public")) {
419
+ selected = "bd_public";
420
+ }
421
+ else if (list.length > 0 && list[0].id) {
422
+ selected = list[0].id;
423
+ }
424
+ else {
425
+ return "bd_public";
426
+ }
427
+ savePlatformBusinessDomain(baseUrl, selected);
428
+ return selected;
429
+ }
430
+ catch (error) {
431
+ const message = error instanceof Error ? error.message : String(error);
432
+ console.warn(`Could not fetch business domains: ${message}. Using bd_public.`);
433
+ return "bd_public";
434
+ }
435
+ }
package/dist/index.d.ts CHANGED
@@ -52,6 +52,8 @@ export { ContextLoaderResource } from "./resources/context-loader.js";
52
52
  export type { ViewField, DataView, CreateDataViewOptions, GetDataViewOptions, ListDataViewsOptions, DeleteDataViewOptions, FindDataViewOptions, QueryDataViewOptions, DataViewQueryResult, } from "./api/dataviews.js";
53
53
  export { parseDataView, createDataView, getDataView, listDataViews, deleteDataView, findDataView, queryDataView, } from "./api/dataviews.js";
54
54
  export { DataViewsResource } from "./resources/dataviews.js";
55
+ export type { BusinessDomain, ListBusinessDomainsOptions } from "./api/business-domains.js";
56
+ export { listBusinessDomains } from "./api/business-domains.js";
55
57
  export { HttpError, NetworkRequestError, fetchTextOrThrow } from "./utils/http.js";
56
58
  export type { TokenConfig, ContextLoaderEntry, ContextLoaderConfig, } from "./config/store.js";
57
- export { getConfigDir, getCurrentPlatform } from "./config/store.js";
59
+ export { autoSelectBusinessDomain, getConfigDir, getCurrentPlatform } from "./config/store.js";
package/dist/index.js CHANGED
@@ -41,6 +41,7 @@ export { ConversationsResource } from "./resources/conversations.js";
41
41
  export { ContextLoaderResource } from "./resources/context-loader.js";
42
42
  export { parseDataView, createDataView, getDataView, listDataViews, deleteDataView, findDataView, queryDataView, } from "./api/dataviews.js";
43
43
  export { DataViewsResource } from "./resources/dataviews.js";
44
+ export { listBusinessDomains } from "./api/business-domains.js";
44
45
  // ── HTTP utilities ────────────────────────────────────────────────────────────
45
46
  export { HttpError, NetworkRequestError, fetchTextOrThrow } from "./utils/http.js";
46
- export { getConfigDir, getCurrentPlatform } from "./config/store.js";
47
+ export { autoSelectBusinessDomain, getConfigDir, getCurrentPlatform } from "./config/store.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kweaver-ai/kweaver-sdk",
3
- "version": "0.4.13",
3
+ "version": "0.4.14",
4
4
  "description": "KWeaver TypeScript SDK — CLI tool and programmatic API for knowledge networks and Decision Agents.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",