@kweaver-ai/kweaver-sdk 0.5.2 → 0.6.0

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.
Files changed (56) hide show
  1. package/README.md +19 -1
  2. package/README.zh.md +19 -1
  3. package/dist/api/agent-chat.d.ts +7 -1
  4. package/dist/api/agent-chat.js +146 -40
  5. package/dist/api/agent-list.js +13 -13
  6. package/dist/api/business-domains.js +9 -5
  7. package/dist/api/context-loader.js +4 -1
  8. package/dist/api/conversations.js +4 -9
  9. package/dist/api/dataflow2.d.ts +95 -0
  10. package/dist/api/dataflow2.js +80 -0
  11. package/dist/api/headers.d.ts +2 -0
  12. package/dist/api/headers.js +7 -2
  13. package/dist/api/skills.js +2 -10
  14. package/dist/api/vega.d.ts +0 -16
  15. package/dist/api/vega.js +0 -33
  16. package/dist/auth/oauth.d.ts +1 -1
  17. package/dist/auth/oauth.js +64 -7
  18. package/dist/cli.js +21 -1
  19. package/dist/client.d.ts +9 -0
  20. package/dist/client.js +48 -8
  21. package/dist/commands/auth.js +80 -32
  22. package/dist/commands/bkn-schema.js +22 -0
  23. package/dist/commands/call.js +8 -5
  24. package/dist/commands/dataflow.d.ts +1 -0
  25. package/dist/commands/dataflow.js +251 -0
  26. package/dist/commands/explore-bkn.d.ts +79 -0
  27. package/dist/commands/explore-bkn.js +273 -0
  28. package/dist/commands/explore-chat.d.ts +3 -0
  29. package/dist/commands/explore-chat.js +193 -0
  30. package/dist/commands/explore-vega.d.ts +3 -0
  31. package/dist/commands/explore-vega.js +71 -0
  32. package/dist/commands/explore.d.ts +9 -0
  33. package/dist/commands/explore.js +258 -0
  34. package/dist/commands/vega.js +2 -104
  35. package/dist/config/no-auth.d.ts +3 -0
  36. package/dist/config/no-auth.js +5 -0
  37. package/dist/config/store.d.ts +8 -0
  38. package/dist/config/store.js +22 -0
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/kweaver.d.ts +5 -0
  42. package/dist/kweaver.js +32 -2
  43. package/dist/resources/bkn.js +2 -3
  44. package/dist/resources/knowledge-networks.js +3 -8
  45. package/dist/resources/vega.d.ts +0 -6
  46. package/dist/resources/vega.js +1 -10
  47. package/dist/templates/explorer/app.js +136 -0
  48. package/dist/templates/explorer/bkn.js +747 -0
  49. package/dist/templates/explorer/chat.js +980 -0
  50. package/dist/templates/explorer/dashboard.js +82 -0
  51. package/dist/templates/explorer/index.html +35 -0
  52. package/dist/templates/explorer/style.css +2440 -0
  53. package/dist/templates/explorer/vega.js +291 -0
  54. package/dist/utils/http.d.ts +3 -0
  55. package/dist/utils/http.js +37 -1
  56. package/package.json +9 -5
@@ -0,0 +1,258 @@
1
+ import { createServer } from "node:http";
2
+ import { readFileSync, existsSync } from "node:fs";
3
+ import { join, extname } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { execSync } from "node:child_process";
6
+ import { ensureValidToken } from "../auth/oauth.js";
7
+ import { resolveBusinessDomain } from "../config/store.js";
8
+ import { registerBknRoutes, loadExploreMetaWithRetry, readBody } from "./explore-bkn.js";
9
+ import { registerChatRoutes } from "./explore-chat.js";
10
+ import { registerVegaRoutes } from "./explore-vega.js";
11
+ import { listKnowledgeNetworks } from "../api/knowledge-networks.js";
12
+ import { listAgents } from "../api/agent-list.js";
13
+ import { listVegaCatalogs } from "../api/vega.js";
14
+ export function parseExploreArgs(args) {
15
+ const opts = {
16
+ knId: "",
17
+ agentId: "",
18
+ port: 3721,
19
+ open: true,
20
+ businessDomain: "",
21
+ };
22
+ for (let i = 0; i < args.length; i++) {
23
+ const a = args[i];
24
+ if (a === "--help" || a === "-h")
25
+ throw new Error("help");
26
+ if (a === "--port" && args[i + 1]) {
27
+ opts.port = Number(args[++i]);
28
+ continue;
29
+ }
30
+ if (a === "--no-open") {
31
+ opts.open = false;
32
+ continue;
33
+ }
34
+ if (a === "--kn" && args[i + 1]) {
35
+ opts.knId = args[++i];
36
+ continue;
37
+ }
38
+ if (a === "--agent" && args[i + 1]) {
39
+ opts.agentId = args[++i];
40
+ continue;
41
+ }
42
+ if ((a === "-bd" || a === "--biz-domain") && args[i + 1]) {
43
+ opts.businessDomain = args[++i];
44
+ continue;
45
+ }
46
+ }
47
+ return opts;
48
+ }
49
+ function printExploreHelp() {
50
+ console.log(`kweaver explore
51
+
52
+ Launch an interactive web UI for exploring KWeaver resources.
53
+
54
+ Usage:
55
+ kweaver explore [options]
56
+
57
+ Options:
58
+ --kn <id> Open directly to BKN tab with specified KN
59
+ --agent <id> Open directly to Chat tab with specified Agent
60
+ --port <n> HTTP server port (default: 3721)
61
+ --no-open Don't auto-open browser
62
+ -bd <value> Business domain override
63
+ -h, --help Show this help
64
+ `);
65
+ }
66
+ // MIME map for static files
67
+ const MIME = {
68
+ ".html": "text/html; charset=utf-8",
69
+ ".css": "text/css; charset=utf-8",
70
+ ".js": "application/javascript; charset=utf-8",
71
+ ".json": "application/json; charset=utf-8",
72
+ ".png": "image/png",
73
+ ".svg": "image/svg+xml",
74
+ };
75
+ /**
76
+ * Returns a fresh token, re-reading from disk each time.
77
+ * This ensures long-running server processes always use the latest
78
+ * access token after a refresh, rather than a stale snapshot.
79
+ */
80
+ async function freshToken() {
81
+ return ensureValidToken();
82
+ }
83
+ async function startServer(opts, token, businessDomain) {
84
+ // 1. Load BKN meta if --kn provided
85
+ let bknMeta = null;
86
+ if (opts.knId) {
87
+ console.error(`Loading schema for KN ${opts.knId}...`);
88
+ bknMeta = await loadExploreMetaWithRetry(token, opts.knId, businessDomain);
89
+ console.error(`Loaded: ${bknMeta.objectTypes.length} OTs, ${bknMeta.relationTypes.length} RTs`);
90
+ }
91
+ // 2. Collect route handlers
92
+ const routes = new Map();
93
+ // Dashboard route: aggregate KN, Agents, Vega Catalogs in parallel
94
+ routes.set("GET /api/dashboard", async (_req, res) => {
95
+ try {
96
+ const t = await freshToken();
97
+ const bd = businessDomain;
98
+ const [knRaw, agentsRaw, catalogsRaw] = await Promise.allSettled([
99
+ listKnowledgeNetworks({ baseUrl: t.baseUrl, accessToken: t.accessToken, businessDomain: bd }),
100
+ listAgents({ baseUrl: t.baseUrl, accessToken: t.accessToken, businessDomain: bd }),
101
+ listVegaCatalogs({ baseUrl: t.baseUrl, accessToken: t.accessToken, businessDomain: bd }),
102
+ ]);
103
+ const parseSettled = (r) => r.status === "fulfilled" ? JSON.parse(r.value) : { error: String(r.reason) };
104
+ const payload = {
105
+ kn: parseSettled(knRaw),
106
+ agents: parseSettled(agentsRaw),
107
+ catalogs: parseSettled(catalogsRaw),
108
+ };
109
+ res.writeHead(200, { "Content-Type": "application/json" });
110
+ res.end(JSON.stringify(payload));
111
+ }
112
+ catch (err) {
113
+ res.writeHead(500, { "Content-Type": "application/json" });
114
+ res.end(JSON.stringify({ error: String(err) }));
115
+ }
116
+ });
117
+ // BKN routes
118
+ if (bknMeta) {
119
+ const bknRoutes = registerBknRoutes(bknMeta, freshToken, businessDomain);
120
+ for (const [key, handler] of bknRoutes)
121
+ routes.set(key, handler);
122
+ }
123
+ // Dynamic KN loading: POST /api/bkn/load { knId }
124
+ routes.set("POST /api/bkn/load", async (req, res) => {
125
+ try {
126
+ const bodyStr = await readBody(req);
127
+ const { knId } = JSON.parse(bodyStr);
128
+ if (!knId) {
129
+ res.writeHead(400, { "Content-Type": "application/json" });
130
+ res.end(JSON.stringify({ error: "knId required" }));
131
+ return;
132
+ }
133
+ console.error(`Loading schema for KN ${knId}...`);
134
+ const t = await freshToken();
135
+ const meta = await loadExploreMetaWithRetry(t, knId, businessDomain);
136
+ console.error(`Loaded: ${meta.objectTypes.length} OTs, ${meta.relationTypes.length} RTs`);
137
+ // Replace BKN routes with new KN's routes
138
+ for (const key of [...routes.keys()]) {
139
+ if (key.startsWith("GET /api/bkn/") || key.startsWith("POST /api/bkn/")) {
140
+ if (key !== "POST /api/bkn/load")
141
+ routes.delete(key);
142
+ }
143
+ }
144
+ const newRoutes = registerBknRoutes(meta, freshToken, businessDomain);
145
+ for (const [key, handler] of newRoutes)
146
+ routes.set(key, handler);
147
+ bknMeta = meta;
148
+ res.writeHead(200, { "Content-Type": "application/json" });
149
+ res.end(JSON.stringify({ ok: true }));
150
+ }
151
+ catch (err) {
152
+ console.error("Failed to load KN:", err.message || err);
153
+ res.writeHead(500, { "Content-Type": "application/json" });
154
+ res.end(JSON.stringify({ error: String(err.message || err) }));
155
+ }
156
+ });
157
+ // Chat routes
158
+ const chatRoutes = registerChatRoutes(freshToken, businessDomain);
159
+ for (const [key, handler] of chatRoutes)
160
+ routes.set(key, handler);
161
+ // Vega routes
162
+ const vegaRoutes = registerVegaRoutes(freshToken, businessDomain);
163
+ for (const [key, handler] of vegaRoutes)
164
+ routes.set(key, handler);
165
+ // 3. Resolve template directory
166
+ const __filename = fileURLToPath(import.meta.url);
167
+ const __dirname = join(__filename, "..");
168
+ const templateDir = join(__dirname, "..", "templates", "explorer");
169
+ // 4. Create HTTP server
170
+ const server = createServer((req, res) => {
171
+ const url = new URL(req.url || "/", `http://localhost:${opts.port}`);
172
+ const method = req.method || "GET";
173
+ const pathname = url.pathname;
174
+ // API route matching
175
+ const routeKey = `${method} ${pathname}`;
176
+ const handler = routes.get(routeKey);
177
+ if (handler) {
178
+ handler(req, res);
179
+ return;
180
+ }
181
+ // Static file serving
182
+ let filePath = pathname === "/" ? "/index.html" : pathname;
183
+ const fullPath = join(templateDir, filePath);
184
+ // Security: prevent directory traversal
185
+ if (!fullPath.startsWith(templateDir)) {
186
+ res.writeHead(403);
187
+ res.end("Forbidden");
188
+ return;
189
+ }
190
+ if (existsSync(fullPath)) {
191
+ const ext = extname(fullPath);
192
+ const contentType = MIME[ext] || "application/octet-stream";
193
+ const content = readFileSync(fullPath);
194
+ res.writeHead(200, { "Content-Type": contentType });
195
+ res.end(content);
196
+ }
197
+ else {
198
+ // SPA fallback: serve index.html for unknown routes
199
+ const indexPath = join(templateDir, "index.html");
200
+ if (existsSync(indexPath)) {
201
+ const content = readFileSync(indexPath);
202
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
203
+ res.end(content);
204
+ }
205
+ else {
206
+ res.writeHead(404);
207
+ res.end("Not Found");
208
+ }
209
+ }
210
+ });
211
+ // 5. Start listening
212
+ server.listen(opts.port, () => {
213
+ const initialHash = opts.knId ? `#/bkn/${opts.knId}` :
214
+ opts.agentId ? `#/chat/${opts.agentId}` : "";
215
+ const url = `http://localhost:${opts.port}/${initialHash}`;
216
+ console.error(`\nKWeaver Explorer running at ${url}\n`);
217
+ console.error("Press Ctrl+C to stop.\n");
218
+ // 6. Open browser
219
+ if (opts.open) {
220
+ try {
221
+ const platform = process.platform;
222
+ if (platform === "darwin")
223
+ execSync(`open "${url}"`);
224
+ else if (platform === "win32")
225
+ execSync(`start "" "${url}"`);
226
+ else
227
+ execSync(`xdg-open "${url}"`);
228
+ }
229
+ catch { /* ignore browser open failures */ }
230
+ }
231
+ });
232
+ // 7. Ctrl+C handling
233
+ await new Promise((resolve) => {
234
+ process.on("SIGINT", () => {
235
+ console.error("\nShutting down...");
236
+ server.close(() => resolve());
237
+ });
238
+ });
239
+ }
240
+ export async function runExploreCommand(args) {
241
+ let opts;
242
+ try {
243
+ opts = parseExploreArgs(args);
244
+ }
245
+ catch (err) {
246
+ if (err?.message === "help") {
247
+ printExploreHelp();
248
+ return 0;
249
+ }
250
+ throw err;
251
+ }
252
+ // Acquire token
253
+ const token = await ensureValidToken();
254
+ const businessDomain = opts.businessDomain || resolveBusinessDomain();
255
+ // Start the server
256
+ await startServer(opts, token, businessDomain);
257
+ return 0;
258
+ }
@@ -1,6 +1,6 @@
1
1
  import { createInterface } from "node:readline";
2
2
  import { ensureValidToken, formatHttpError, with401RefreshRetry } from "../auth/oauth.js";
3
- import { vegaHealth, listVegaCatalogs, getVegaCatalog, createVegaCatalog, updateVegaCatalog, deleteVegaCatalogs, vegaCatalogHealthStatus, testVegaCatalogConnection, discoverVegaCatalog, listVegaCatalogResources, listVegaResources, getVegaResource, queryVegaResourceData, createVegaResource, updateVegaResource, deleteVegaResources, listVegaConnectorTypes, getVegaConnectorType, registerVegaConnectorType, updateVegaConnectorType, deleteVegaConnectorType, setVegaConnectorTypeEnabled, listVegaDiscoverTasks, getVegaDiscoverTask, createVegaDatasetDocs, updateVegaDatasetDocs, deleteVegaDatasetDocs, deleteVegaDatasetDocsQuery, buildVegaDataset, getVegaDatasetBuildStatus, executeVegaQuery, listAllVegaResources, } from "../api/vega.js";
3
+ import { vegaHealth, listVegaCatalogs, getVegaCatalog, createVegaCatalog, updateVegaCatalog, deleteVegaCatalogs, vegaCatalogHealthStatus, testVegaCatalogConnection, discoverVegaCatalog, listVegaCatalogResources, listVegaResources, getVegaResource, queryVegaResourceData, createVegaResource, updateVegaResource, deleteVegaResources, listVegaConnectorTypes, getVegaConnectorType, registerVegaConnectorType, updateVegaConnectorType, deleteVegaConnectorType, setVegaConnectorTypeEnabled, createVegaDatasetDocs, updateVegaDatasetDocs, deleteVegaDatasetDocs, deleteVegaDatasetDocsQuery, buildVegaDataset, getVegaDatasetBuildStatus, executeVegaQuery, listAllVegaResources, } from "../api/vega.js";
4
4
  import { formatCallOutput } from "./call.js";
5
5
  import { resolveBusinessDomain } from "../config/store.js";
6
6
  // ---------------------------------------------------------------------------
@@ -42,9 +42,6 @@ Subcommands:
42
42
  connector-type update <type> -d <json> Update connector type
43
43
  connector-type delete <type> [-y] Delete connector type
44
44
  connector-type enable <type> --enabled <bool> Enable/disable connector type
45
- discovery-task list [--status X] [--limit N]
46
- discovery-task get <id>
47
-
48
45
  Common flags:
49
46
  -bd, --biz-domain <s> Business domain (default: bd_public)
50
47
  --pretty Pretty-print JSON (default)`);
@@ -108,8 +105,6 @@ export async function runVegaCommand(args) {
108
105
  return runVegaQueryCommand(rest);
109
106
  if (subcommand === "connector-type")
110
107
  return runVegaConnectorTypeCommand(rest);
111
- if (subcommand === "discovery-task")
112
- return runVegaDiscoveryTaskCommand(rest);
113
108
  return Promise.resolve(-1);
114
109
  };
115
110
  try {
@@ -179,7 +174,7 @@ async function runVegaStatsCommand(args) {
179
174
  // ---------------------------------------------------------------------------
180
175
  async function runVegaInspectCommand(args) {
181
176
  if (args.includes("--help") || args.includes("-h")) {
182
- console.log("kweaver vega inspect\n\nHealth + catalog summary + running discover tasks.");
177
+ console.log("kweaver vega inspect\n\nHealth + catalog summary.");
183
178
  return 0;
184
179
  }
185
180
  const { businessDomain, pretty } = parseCommonFlags(args);
@@ -206,17 +201,6 @@ async function runVegaInspectCommand(args) {
206
201
  console.error(`warn: catalog list failed: ${err instanceof Error ? err.message : String(err)}`);
207
202
  result.catalog_count = null;
208
203
  }
209
- // Running discover tasks — best-effort
210
- try {
211
- const tasksBody = await listVegaDiscoverTasks({ ...base, status: "running" });
212
- const parsed = JSON.parse(tasksBody);
213
- const entries = Array.isArray(parsed) ? parsed : (parsed.entries ?? parsed.data ?? parsed.items ?? parsed.tasks ?? []);
214
- result.running_discover_tasks = Array.isArray(entries) ? entries.length : 0;
215
- }
216
- catch (err) {
217
- console.error(`warn: discover tasks query failed: ${err instanceof Error ? err.message : String(err)}`);
218
- result.running_discover_tasks = null;
219
- }
220
204
  console.log(pretty ? JSON.stringify(result, null, 2) : JSON.stringify(result));
221
205
  return 0;
222
206
  }
@@ -1563,89 +1547,3 @@ async function runConnectorTypeEnable(args) {
1563
1547
  console.log(formatCallOutput(body || "{}", pretty));
1564
1548
  return 0;
1565
1549
  }
1566
- // ---------------------------------------------------------------------------
1567
- // Discovery-task router
1568
- // ---------------------------------------------------------------------------
1569
- async function runVegaDiscoveryTaskCommand(args) {
1570
- const [sub, ...rest] = args;
1571
- if (!sub || sub === "--help" || sub === "-h") {
1572
- console.log(`kweaver vega discovery-task
1573
-
1574
- Subcommands:
1575
- list [--status X] [--limit N]
1576
- get <id>`);
1577
- return 0;
1578
- }
1579
- if (sub === "list")
1580
- return await runDiscoveryTaskList(rest);
1581
- if (sub === "get")
1582
- return await runDiscoveryTaskGet(rest);
1583
- console.error(`Unknown discovery-task subcommand: ${sub}`);
1584
- return 1;
1585
- }
1586
- // ---------------------------------------------------------------------------
1587
- // discovery-task list
1588
- // ---------------------------------------------------------------------------
1589
- async function runDiscoveryTaskList(args) {
1590
- if (args.includes("--help") || args.includes("-h")) {
1591
- console.log(`kweaver vega discovery-task list [options]
1592
-
1593
- Options:
1594
- --catalog-id <cid> Filter by catalog (reserved)
1595
- --status <s> Filter by status
1596
- --limit <n> Max results`);
1597
- return 0;
1598
- }
1599
- let status;
1600
- let limit;
1601
- const { remaining, businessDomain, pretty } = parseCommonFlags(args);
1602
- for (let i = 0; i < remaining.length; i += 1) {
1603
- const arg = remaining[i];
1604
- if (arg === "--status" && remaining[i + 1]) {
1605
- status = remaining[++i];
1606
- continue;
1607
- }
1608
- if (arg === "--limit" && remaining[i + 1]) {
1609
- limit = parseInt(remaining[++i], 10);
1610
- continue;
1611
- }
1612
- if (arg === "--catalog-id" && remaining[i + 1]) {
1613
- remaining[++i];
1614
- continue;
1615
- }
1616
- }
1617
- const token = await ensureValidToken();
1618
- const body = await listVegaDiscoverTasks({
1619
- baseUrl: token.baseUrl,
1620
- accessToken: token.accessToken,
1621
- status,
1622
- limit,
1623
- businessDomain,
1624
- });
1625
- console.log(formatCallOutput(body, pretty));
1626
- return 0;
1627
- }
1628
- // ---------------------------------------------------------------------------
1629
- // discovery-task get
1630
- // ---------------------------------------------------------------------------
1631
- async function runDiscoveryTaskGet(args) {
1632
- if (args.includes("--help") || args.includes("-h")) {
1633
- console.log("kweaver vega discovery-task get <id>");
1634
- return 0;
1635
- }
1636
- const { remaining, businessDomain, pretty } = parseCommonFlags(args);
1637
- const id = remaining.find((a) => !a.startsWith("-"));
1638
- if (!id) {
1639
- console.error("Usage: kweaver vega discovery-task get <id>");
1640
- return 1;
1641
- }
1642
- const token = await ensureValidToken();
1643
- const body = await getVegaDiscoverTask({
1644
- baseUrl: token.baseUrl,
1645
- accessToken: token.accessToken,
1646
- id,
1647
- businessDomain,
1648
- });
1649
- console.log(formatCallOutput(body, pretty));
1650
- return 0;
1651
- }
@@ -0,0 +1,3 @@
1
+ /** Sentinel access token for platforms with no OAuth / no API authentication. */
2
+ export declare const NO_AUTH_TOKEN = "__NO_AUTH__";
3
+ export declare function isNoAuth(accessToken: string): boolean;
@@ -0,0 +1,5 @@
1
+ /** Sentinel access token for platforms with no OAuth / no API authentication. */
2
+ export const NO_AUTH_TOKEN = "__NO_AUTH__";
3
+ export function isNoAuth(accessToken) {
4
+ return accessToken === NO_AUTH_TOKEN;
5
+ }
@@ -1,3 +1,11 @@
1
+ export { NO_AUTH_TOKEN, isNoAuth } from "./no-auth.js";
2
+ /**
3
+ * Persist a no-auth session for a platform (users/default/token.json) and set it as current.
4
+ * Used by `kweaver auth <url> --no-auth` and when OAuth registration returns 404.
5
+ */
6
+ export declare function saveNoAuthPlatform(baseUrl: string, opts?: {
7
+ tlsInsecure?: boolean;
8
+ }): TokenConfig;
1
9
  export interface TokenConfig {
2
10
  baseUrl: string;
3
11
  accessToken: string;
@@ -2,7 +2,29 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { listBusinessDomains } from "../api/business-domains.js";
5
+ import { NO_AUTH_TOKEN } from "./no-auth.js";
5
6
  import { decodeJwtPayload, extractUserIdFromJwt } from "./jwt.js";
7
+ export { NO_AUTH_TOKEN, isNoAuth } from "./no-auth.js";
8
+ /**
9
+ * Persist a no-auth session for a platform (users/default/token.json) and set it as current.
10
+ * Used by `kweaver auth <url> --no-auth` and when OAuth registration returns 404.
11
+ */
12
+ export function saveNoAuthPlatform(baseUrl, opts) {
13
+ const base = baseUrl.replace(/\/+$/, "");
14
+ const token = {
15
+ baseUrl: base,
16
+ accessToken: NO_AUTH_TOKEN,
17
+ tokenType: "none",
18
+ scope: "",
19
+ obtainedAt: new Date().toISOString(),
20
+ };
21
+ if (opts?.tlsInsecure) {
22
+ token.tlsInsecure = true;
23
+ }
24
+ saveTokenConfig(token);
25
+ setCurrentPlatform(base);
26
+ return token;
27
+ }
6
28
  const MCP_PATH = "/api/agent-retrieval/v1/mcp";
7
29
  function buildMcpUrl(baseUrl) {
8
30
  return baseUrl.replace(/\/+$/, "") + MCP_PATH;
package/dist/index.d.ts CHANGED
@@ -60,5 +60,5 @@ export { listBusinessDomains } from "./api/business-domains.js";
60
60
  export { HttpError, NetworkRequestError, fetchTextOrThrow } from "./utils/http.js";
61
61
  export type { TokenConfig, ContextLoaderEntry, ContextLoaderConfig, } from "./config/store.js";
62
62
  export type { UserProfile } from "./config/store.js";
63
- export { autoSelectBusinessDomain, getConfigDir, getCurrentPlatform, getActiveUser, setActiveUser, listUsers, listUserProfiles, resolveUserId, extractUserId, } from "./config/store.js";
63
+ export { NO_AUTH_TOKEN, isNoAuth, saveNoAuthPlatform, autoSelectBusinessDomain, getConfigDir, getCurrentPlatform, getActiveUser, setActiveUser, listUsers, listUserProfiles, resolveUserId, extractUserId, } from "./config/store.js";
64
64
  export { decodeJwtPayload, extractUserIdFromJwt } from "./config/jwt.js";
package/dist/index.js CHANGED
@@ -46,6 +46,6 @@ export { DataViewsResource } from "./resources/dataviews.js";
46
46
  export { listBusinessDomains } from "./api/business-domains.js";
47
47
  // ── HTTP utilities ────────────────────────────────────────────────────────────
48
48
  export { HttpError, NetworkRequestError, fetchTextOrThrow } from "./utils/http.js";
49
- export { autoSelectBusinessDomain, getConfigDir, getCurrentPlatform, getActiveUser, setActiveUser, listUsers, listUserProfiles, resolveUserId, extractUserId, } from "./config/store.js";
49
+ export { NO_AUTH_TOKEN, isNoAuth, saveNoAuthPlatform, autoSelectBusinessDomain, getConfigDir, getCurrentPlatform, getActiveUser, setActiveUser, listUsers, listUserProfiles, resolveUserId, extractUserId, } from "./config/store.js";
50
50
  // ── JWT utilities ─────────────────────────────────────────────────────────────
51
51
  export { decodeJwtPayload, extractUserIdFromJwt } from "./config/jwt.js";
package/dist/kweaver.d.ts CHANGED
@@ -37,6 +37,11 @@ export interface ConfigureOptions {
37
37
  * config, preventing accidental cross-environment credential leaks.
38
38
  */
39
39
  config?: boolean;
40
+ /**
41
+ * If false, use no-auth mode (no Authorization headers). Requires baseUrl or KWEAVER_BASE_URL.
42
+ * Incompatible with config=true.
43
+ */
44
+ auth?: boolean;
40
45
  /** Default BKN ID used by search() and weaver(). */
41
46
  bknId?: string;
42
47
  /** Default agent ID used by chat(). */
package/dist/kweaver.js CHANGED
@@ -41,8 +41,25 @@ export function configure(opts) {
41
41
  _client = null;
42
42
  _defaultBknId = null;
43
43
  _defaultAgentId = null;
44
- const { bknId, agentId, businessDomain, config, baseUrl, accessToken } = opts;
45
- if (config) {
44
+ const { bknId, agentId, businessDomain, config, baseUrl, accessToken, auth } = opts;
45
+ if (auth === false && config) {
46
+ throw new Error("Cannot use auth: false with config: true.");
47
+ }
48
+ if (auth === false && accessToken) {
49
+ throw new Error("Cannot use auth: false with accessToken.");
50
+ }
51
+ if (auth === false) {
52
+ const resolvedBase = baseUrl ?? process.env.KWEAVER_BASE_URL;
53
+ if (!resolvedBase) {
54
+ throw new Error("Provide baseUrl= or set KWEAVER_BASE_URL when auth is false.");
55
+ }
56
+ _client = new KWeaverClient({
57
+ baseUrl: resolvedBase,
58
+ auth: false,
59
+ businessDomain,
60
+ });
61
+ }
62
+ else if (config) {
46
63
  // Use saved credentials — do NOT pass baseUrl to avoid cross-env leaks
47
64
  const platform = getCurrentPlatform();
48
65
  if (!platform) {
@@ -58,6 +75,19 @@ export function configure(opts) {
58
75
  businessDomain,
59
76
  });
60
77
  }
78
+ else if (!accessToken &&
79
+ !process.env.KWEAVER_TOKEN &&
80
+ ["1", "true", "yes"].includes((process.env.KWEAVER_NO_AUTH ?? "").toLowerCase())) {
81
+ const resolvedBase = baseUrl ?? process.env.KWEAVER_BASE_URL;
82
+ if (!resolvedBase) {
83
+ throw new Error("Provide baseUrl= or set KWEAVER_BASE_URL when KWEAVER_NO_AUTH is set.");
84
+ }
85
+ _client = new KWeaverClient({
86
+ baseUrl: resolvedBase,
87
+ auth: false,
88
+ businessDomain,
89
+ });
90
+ }
61
91
  else {
62
92
  if (!baseUrl && !process.env.KWEAVER_BASE_URL) {
63
93
  throw new Error("Provide baseUrl=, config=true, or set KWEAVER_BASE_URL.");
@@ -1,3 +1,4 @@
1
+ import { buildHeaders } from "../api/headers.js";
1
2
  import { objectTypeQuery, objectTypeProperties, subgraph, actionTypeQuery, actionTypeExecute, actionExecutionGet, actionLogsList, actionLogGet, actionLogCancel, } from "../api/ontology-query.js";
2
3
  import { fetchTextOrThrow } from "../utils/http.js";
3
4
  /** BKN engine resource — instance queries, subgraph, action execution and logs. */
@@ -21,9 +22,7 @@ export class BknResource {
21
22
  method: "POST",
22
23
  headers: {
23
24
  "content-type": "application/json",
24
- authorization: `Bearer ${accessToken}`,
25
- token: accessToken,
26
- "x-business-domain": businessDomain,
25
+ ...buildHeaders(accessToken, businessDomain),
27
26
  },
28
27
  body: JSON.stringify({
29
28
  kn_id: bknId,
@@ -1,3 +1,4 @@
1
+ import { buildHeaders } from "../api/headers.js";
1
2
  import { listKnowledgeNetworks, getKnowledgeNetwork, createKnowledgeNetwork, updateKnowledgeNetwork, deleteKnowledgeNetwork, listObjectTypes, listRelationTypes, listActionTypes, } from "../api/knowledge-networks.js";
2
3
  import { fetchTextOrThrow } from "../utils/http.js";
3
4
  export class KnowledgeNetworksResource {
@@ -69,9 +70,7 @@ export class KnowledgeNetworksResource {
69
70
  const { baseUrl, accessToken, businessDomain } = this.ctx.base();
70
71
  const headers = {
71
72
  "content-type": "application/json",
72
- authorization: `Bearer ${accessToken}`,
73
- token: accessToken,
74
- "x-business-domain": businessDomain,
73
+ ...buildHeaders(accessToken, businessDomain),
75
74
  };
76
75
  await fetchTextOrThrow(`${baseUrl}/api/ontology-manager/v1/knowledge-networks/${encodeURIComponent(bknId)}/jobs`, {
77
76
  method: "POST",
@@ -82,11 +81,7 @@ export class KnowledgeNetworksResource {
82
81
  /** Poll build status for a BKN. */
83
82
  async buildStatus(bknId) {
84
83
  const { baseUrl, accessToken, businessDomain } = this.ctx.base();
85
- const headers = {
86
- authorization: `Bearer ${accessToken}`,
87
- token: accessToken,
88
- "x-business-domain": businessDomain,
89
- };
84
+ const headers = buildHeaders(accessToken, businessDomain);
90
85
  const { body } = await fetchTextOrThrow(`${baseUrl}/api/ontology-manager/v1/knowledge-networks/${encodeURIComponent(bknId)}/jobs?limit=1&direction=desc`, { headers });
91
86
  const data = JSON.parse(body);
92
87
  const jobs = Array.isArray(data)
@@ -57,10 +57,4 @@ export declare class VegaResource {
57
57
  updateConnectorType(type: string, body: string): Promise<unknown>;
58
58
  deleteConnectorType(type: string): Promise<unknown>;
59
59
  setConnectorTypeEnabled(type: string, enabled: boolean): Promise<unknown>;
60
- listDiscoverTasks(opts?: {
61
- status?: string;
62
- limit?: number;
63
- offset?: number;
64
- }): Promise<unknown[]>;
65
- getDiscoverTask(id: string): Promise<unknown>;
66
60
  }
@@ -1,4 +1,4 @@
1
- import { vegaHealth, listVegaCatalogs, getVegaCatalog, createVegaCatalog, updateVegaCatalog, deleteVegaCatalogs, vegaCatalogHealthStatus, testVegaCatalogConnection, discoverVegaCatalog, listVegaCatalogResources, listVegaResources, getVegaResource, queryVegaResourceData, createVegaResource, updateVegaResource, deleteVegaResources, createVegaDatasetDocs, updateVegaDatasetDocs, deleteVegaDatasetDocs, deleteVegaDatasetDocsQuery, buildVegaDataset, getVegaDatasetBuildStatus, executeVegaQuery, listAllVegaResources, listVegaConnectorTypes, getVegaConnectorType, registerVegaConnectorType, updateVegaConnectorType, deleteVegaConnectorType, setVegaConnectorTypeEnabled, listVegaDiscoverTasks, getVegaDiscoverTask, } from "../api/vega.js";
1
+ import { vegaHealth, listVegaCatalogs, getVegaCatalog, createVegaCatalog, updateVegaCatalog, deleteVegaCatalogs, vegaCatalogHealthStatus, testVegaCatalogConnection, discoverVegaCatalog, listVegaCatalogResources, listVegaResources, getVegaResource, queryVegaResourceData, createVegaResource, updateVegaResource, deleteVegaResources, createVegaDatasetDocs, updateVegaDatasetDocs, deleteVegaDatasetDocs, deleteVegaDatasetDocsQuery, buildVegaDataset, getVegaDatasetBuildStatus, executeVegaQuery, listAllVegaResources, listVegaConnectorTypes, getVegaConnectorType, registerVegaConnectorType, updateVegaConnectorType, deleteVegaConnectorType, setVegaConnectorTypeEnabled, } from "../api/vega.js";
2
2
  function unwrapArray(raw) {
3
3
  const parsed = JSON.parse(raw);
4
4
  if (Array.isArray(parsed))
@@ -144,13 +144,4 @@ export class VegaResource {
144
144
  const raw = await setVegaConnectorTypeEnabled({ ...this.ctx.base(), type, enabled });
145
145
  return raw ? JSON.parse(raw) : {};
146
146
  }
147
- // ── Discover Tasks ──────────────────────────────────────────────────────────
148
- async listDiscoverTasks(opts = {}) {
149
- const raw = await listVegaDiscoverTasks({ ...this.ctx.base(), ...opts });
150
- return unwrapArray(raw);
151
- }
152
- async getDiscoverTask(id) {
153
- const raw = await getVegaDiscoverTask({ ...this.ctx.base(), id });
154
- return JSON.parse(raw);
155
- }
156
147
  }