@kweaver-ai/kweaver-sdk 0.4.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 (64) hide show
  1. package/bin/kweaver.js +9 -0
  2. package/dist/api/agent-chat.d.ts +69 -0
  3. package/dist/api/agent-chat.js +379 -0
  4. package/dist/api/agent-list.d.ts +12 -0
  5. package/dist/api/agent-list.js +33 -0
  6. package/dist/api/context-loader.d.ts +115 -0
  7. package/dist/api/context-loader.js +259 -0
  8. package/dist/api/conversations.d.ts +24 -0
  9. package/dist/api/conversations.js +64 -0
  10. package/dist/api/knowledge-networks.d.ts +57 -0
  11. package/dist/api/knowledge-networks.js +158 -0
  12. package/dist/api/ontology-query.d.ts +75 -0
  13. package/dist/api/ontology-query.js +238 -0
  14. package/dist/api/semantic-search.d.ts +12 -0
  15. package/dist/api/semantic-search.js +34 -0
  16. package/dist/auth/oauth.d.ts +75 -0
  17. package/dist/auth/oauth.js +417 -0
  18. package/dist/cli.d.ts +1 -0
  19. package/dist/cli.js +79 -0
  20. package/dist/client.d.ts +95 -0
  21. package/dist/client.js +104 -0
  22. package/dist/commands/agent-chat.d.ts +12 -0
  23. package/dist/commands/agent-chat.js +193 -0
  24. package/dist/commands/agent.d.ts +28 -0
  25. package/dist/commands/agent.js +431 -0
  26. package/dist/commands/auth.d.ts +9 -0
  27. package/dist/commands/auth.js +201 -0
  28. package/dist/commands/bkn.d.ts +70 -0
  29. package/dist/commands/bkn.js +1371 -0
  30. package/dist/commands/call.d.ts +14 -0
  31. package/dist/commands/call.js +151 -0
  32. package/dist/commands/context-loader.d.ts +1 -0
  33. package/dist/commands/context-loader.js +383 -0
  34. package/dist/commands/token.d.ts +2 -0
  35. package/dist/commands/token.js +24 -0
  36. package/dist/config/store.d.ts +77 -0
  37. package/dist/config/store.js +380 -0
  38. package/dist/index.d.ts +53 -0
  39. package/dist/index.js +44 -0
  40. package/dist/kweaver.d.ts +146 -0
  41. package/dist/kweaver.js +184 -0
  42. package/dist/resources/agents.d.ts +37 -0
  43. package/dist/resources/agents.js +60 -0
  44. package/dist/resources/bkn.d.ts +45 -0
  45. package/dist/resources/bkn.js +86 -0
  46. package/dist/resources/context-loader.d.ts +15 -0
  47. package/dist/resources/context-loader.js +32 -0
  48. package/dist/resources/conversations.d.ts +11 -0
  49. package/dist/resources/conversations.js +17 -0
  50. package/dist/resources/knowledge-networks.d.ts +65 -0
  51. package/dist/resources/knowledge-networks.js +167 -0
  52. package/dist/ui/ChatApp.d.ts +16 -0
  53. package/dist/ui/ChatApp.js +248 -0
  54. package/dist/ui/MarkdownBlock.d.ts +5 -0
  55. package/dist/ui/MarkdownBlock.js +137 -0
  56. package/dist/ui/display-text.d.ts +1 -0
  57. package/dist/ui/display-text.js +1 -0
  58. package/dist/utils/browser.d.ts +1 -0
  59. package/dist/utils/browser.js +20 -0
  60. package/dist/utils/display-text.d.ts +3 -0
  61. package/dist/utils/display-text.js +46 -0
  62. package/dist/utils/http.d.ts +17 -0
  63. package/dist/utils/http.js +72 -0
  64. package/package.json +62 -0
@@ -0,0 +1,380 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ const MCP_PATH = "/api/agent-retrieval/v1/mcp";
5
+ function buildMcpUrl(baseUrl) {
6
+ return baseUrl.replace(/\/+$/, "") + MCP_PATH;
7
+ }
8
+ const CONFIG_DIR = process.env.KWEAVERC_CONFIG_DIR || join(homedir(), ".kweaver");
9
+ function getConfigDirPath() {
10
+ return process.env.KWEAVERC_CONFIG_DIR || join(homedir(), ".kweaver");
11
+ }
12
+ function getPlatformsDirPath() {
13
+ return join(getConfigDirPath(), "platforms");
14
+ }
15
+ function getStateFilePath() {
16
+ return join(getConfigDirPath(), "state.json");
17
+ }
18
+ function getLegacyClientFilePath() {
19
+ return join(getConfigDirPath(), "client.json");
20
+ }
21
+ function getLegacyTokenFilePath() {
22
+ return join(getConfigDirPath(), "token.json");
23
+ }
24
+ function getLegacyCallbackFilePath() {
25
+ return join(getConfigDirPath(), "callback.json");
26
+ }
27
+ function ensureDir(path) {
28
+ if (!existsSync(path)) {
29
+ mkdirSync(path, { recursive: true, mode: 0o700 });
30
+ }
31
+ }
32
+ function ensureConfigDir() {
33
+ ensureDir(getConfigDirPath());
34
+ ensureDir(getPlatformsDirPath());
35
+ }
36
+ function readJsonFile(filePath) {
37
+ if (!existsSync(filePath)) {
38
+ return null;
39
+ }
40
+ return JSON.parse(readFileSync(filePath, "utf8"));
41
+ }
42
+ function writeJsonFile(filePath, value) {
43
+ ensureConfigDir();
44
+ writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
45
+ chmodSync(filePath, 0o600);
46
+ }
47
+ function encodePlatformKey(baseUrl) {
48
+ return Buffer.from(baseUrl, "utf8")
49
+ .toString("base64")
50
+ .replace(/\+/g, "-")
51
+ .replace(/\//g, "_")
52
+ .replace(/=+$/g, "");
53
+ }
54
+ function getPlatformDir(baseUrl) {
55
+ return join(getPlatformsDirPath(), encodePlatformKey(baseUrl));
56
+ }
57
+ function getPlatformFile(baseUrl, filename) {
58
+ return join(getPlatformDir(baseUrl), filename);
59
+ }
60
+ function ensurePlatformDir(baseUrl) {
61
+ ensureDir(getPlatformDir(baseUrl));
62
+ }
63
+ function readState() {
64
+ return readJsonFile(getStateFilePath()) ?? {};
65
+ }
66
+ function writeState(state) {
67
+ writeJsonFile(getStateFilePath(), state);
68
+ }
69
+ function normalizeAlias(value) {
70
+ return value.trim().toLowerCase();
71
+ }
72
+ function migrateLegacyFilesIfNeeded() {
73
+ const legacyClientFile = getLegacyClientFilePath();
74
+ const legacyTokenFile = getLegacyTokenFilePath();
75
+ const legacyCallbackFile = getLegacyCallbackFilePath();
76
+ const hasLegacy = existsSync(legacyClientFile) || existsSync(legacyTokenFile) || existsSync(legacyCallbackFile);
77
+ if (!hasLegacy) {
78
+ return;
79
+ }
80
+ const legacyClient = readJsonFile(legacyClientFile);
81
+ const legacyToken = readJsonFile(legacyTokenFile);
82
+ const legacyCallback = readJsonFile(legacyCallbackFile);
83
+ const baseUrl = legacyClient?.baseUrl ?? legacyToken?.baseUrl ?? legacyCallback?.baseUrl;
84
+ if (!baseUrl) {
85
+ return;
86
+ }
87
+ const platformClientFile = getPlatformFile(baseUrl, "client.json");
88
+ const platformTokenFile = getPlatformFile(baseUrl, "token.json");
89
+ const platformCallbackFile = getPlatformFile(baseUrl, "callback.json");
90
+ ensurePlatformDir(baseUrl);
91
+ if (legacyClient && !existsSync(platformClientFile)) {
92
+ writeJsonFile(platformClientFile, legacyClient);
93
+ }
94
+ if (legacyToken && !existsSync(platformTokenFile)) {
95
+ writeJsonFile(platformTokenFile, legacyToken);
96
+ }
97
+ if (legacyCallback && !existsSync(platformCallbackFile)) {
98
+ writeJsonFile(platformCallbackFile, legacyCallback);
99
+ }
100
+ const state = readState();
101
+ if (!state.currentPlatform) {
102
+ writeState({ ...state, currentPlatform: baseUrl });
103
+ }
104
+ }
105
+ function ensureStoreReady() {
106
+ ensureConfigDir();
107
+ migrateLegacyFilesIfNeeded();
108
+ }
109
+ export function getConfigDir() {
110
+ return getConfigDirPath();
111
+ }
112
+ export function getCurrentPlatform() {
113
+ ensureStoreReady();
114
+ return readState().currentPlatform ?? null;
115
+ }
116
+ export function setCurrentPlatform(baseUrl) {
117
+ ensureStoreReady();
118
+ const state = readState();
119
+ writeState({ ...state, currentPlatform: baseUrl });
120
+ }
121
+ export function setPlatformAlias(baseUrl, alias) {
122
+ ensureStoreReady();
123
+ const normalizedAlias = normalizeAlias(alias);
124
+ if (!normalizedAlias) {
125
+ throw new Error("Alias cannot be empty.");
126
+ }
127
+ const state = readState();
128
+ const aliases = { ...(state.aliases ?? {}) };
129
+ const existing = aliases[normalizedAlias];
130
+ if (existing && existing !== baseUrl) {
131
+ throw new Error(`Alias '${normalizedAlias}' is already assigned to ${existing}.`);
132
+ }
133
+ aliases[normalizedAlias] = baseUrl;
134
+ writeState({ ...state, aliases });
135
+ }
136
+ export function deletePlatformAlias(baseUrl) {
137
+ ensureStoreReady();
138
+ const state = readState();
139
+ const aliases = { ...(state.aliases ?? {}) };
140
+ let changed = false;
141
+ for (const [alias, targetBaseUrl] of Object.entries(aliases)) {
142
+ if (targetBaseUrl === baseUrl) {
143
+ delete aliases[alias];
144
+ changed = true;
145
+ }
146
+ }
147
+ if (!changed) {
148
+ return;
149
+ }
150
+ writeState({
151
+ ...state,
152
+ aliases: Object.keys(aliases).length > 0 ? aliases : undefined,
153
+ });
154
+ }
155
+ export function getPlatformAlias(baseUrl) {
156
+ ensureStoreReady();
157
+ const aliases = readState().aliases ?? {};
158
+ for (const [alias, targetBaseUrl] of Object.entries(aliases)) {
159
+ if (targetBaseUrl === baseUrl) {
160
+ return alias;
161
+ }
162
+ }
163
+ return null;
164
+ }
165
+ export function resolvePlatformIdentifier(value) {
166
+ ensureStoreReady();
167
+ const normalized = value.trim();
168
+ if (!normalized) {
169
+ return null;
170
+ }
171
+ const aliases = readState().aliases ?? {};
172
+ const aliasTarget = aliases[normalizeAlias(normalized)];
173
+ if (aliasTarget) {
174
+ return aliasTarget;
175
+ }
176
+ return normalized;
177
+ }
178
+ export function loadClientConfig(baseUrl) {
179
+ ensureStoreReady();
180
+ const targetBaseUrl = baseUrl ?? getCurrentPlatform();
181
+ if (!targetBaseUrl) {
182
+ return null;
183
+ }
184
+ return readJsonFile(getPlatformFile(targetBaseUrl, "client.json"));
185
+ }
186
+ export function saveClientConfig(config) {
187
+ ensureStoreReady();
188
+ ensurePlatformDir(config.baseUrl);
189
+ writeJsonFile(getPlatformFile(config.baseUrl, "client.json"), config);
190
+ }
191
+ export function loadTokenConfig(baseUrl) {
192
+ ensureStoreReady();
193
+ const targetBaseUrl = baseUrl ?? getCurrentPlatform();
194
+ if (!targetBaseUrl) {
195
+ return null;
196
+ }
197
+ return readJsonFile(getPlatformFile(targetBaseUrl, "token.json"));
198
+ }
199
+ export function saveTokenConfig(config) {
200
+ ensureStoreReady();
201
+ ensurePlatformDir(config.baseUrl);
202
+ writeJsonFile(getPlatformFile(config.baseUrl, "token.json"), config);
203
+ }
204
+ export function loadCallbackSession(baseUrl) {
205
+ ensureStoreReady();
206
+ const targetBaseUrl = baseUrl ?? getCurrentPlatform();
207
+ if (!targetBaseUrl) {
208
+ return null;
209
+ }
210
+ return readJsonFile(getPlatformFile(targetBaseUrl, "callback.json"));
211
+ }
212
+ export function saveCallbackSession(session) {
213
+ ensureStoreReady();
214
+ ensurePlatformDir(session.baseUrl);
215
+ writeJsonFile(getPlatformFile(session.baseUrl, "callback.json"), session);
216
+ }
217
+ function migrateLegacyContextLoader(raw) {
218
+ const leg = raw;
219
+ if (leg?.knId && !Array.isArray(raw.configs)) {
220
+ return {
221
+ configs: [{ name: "default", knId: leg.knId }],
222
+ current: "default",
223
+ };
224
+ }
225
+ return raw;
226
+ }
227
+ export function loadContextLoaderConfig(baseUrl) {
228
+ ensureStoreReady();
229
+ const targetBaseUrl = baseUrl ?? getCurrentPlatform();
230
+ if (!targetBaseUrl) {
231
+ return null;
232
+ }
233
+ const raw = readJsonFile(getPlatformFile(targetBaseUrl, "context-loader.json"));
234
+ if (!raw)
235
+ return null;
236
+ const migrated = migrateLegacyContextLoader(raw);
237
+ if (!Array.isArray(migrated.configs) ||
238
+ migrated.configs.length === 0 ||
239
+ !migrated.current) {
240
+ return null;
241
+ }
242
+ const hasCurrent = migrated.configs.some((c) => c.name === migrated.current);
243
+ if (!hasCurrent)
244
+ return null;
245
+ const isLegacy = raw?.knId && !raw.configs;
246
+ if (isLegacy) {
247
+ saveContextLoaderConfig(targetBaseUrl, migrated);
248
+ }
249
+ return migrated;
250
+ }
251
+ export function saveContextLoaderConfig(baseUrl, config) {
252
+ ensureStoreReady();
253
+ ensurePlatformDir(baseUrl);
254
+ writeJsonFile(getPlatformFile(baseUrl, "context-loader.json"), config);
255
+ }
256
+ export function getCurrentContextLoaderKn(baseUrl) {
257
+ ensureStoreReady();
258
+ const targetBaseUrl = baseUrl ?? getCurrentPlatform();
259
+ if (!targetBaseUrl)
260
+ return null;
261
+ const client = loadClientConfig(targetBaseUrl);
262
+ if (!client?.baseUrl)
263
+ return null;
264
+ const config = loadContextLoaderConfig(targetBaseUrl);
265
+ if (!config)
266
+ return null;
267
+ const entry = config.configs.find((c) => c.name === config.current);
268
+ if (!entry)
269
+ return null;
270
+ return {
271
+ mcpUrl: buildMcpUrl(client.baseUrl),
272
+ knId: entry.knId,
273
+ };
274
+ }
275
+ export function addContextLoaderEntry(baseUrl, name, knId) {
276
+ ensureStoreReady();
277
+ const existing = loadContextLoaderConfig(baseUrl);
278
+ const configs = existing?.configs ?? [];
279
+ const idx = configs.findIndex((c) => c.name === name);
280
+ const entry = { name, knId };
281
+ const newConfigs = idx >= 0
282
+ ? configs.map((c, i) => (i === idx ? entry : c))
283
+ : [...configs, entry];
284
+ const current = existing?.current ?? name;
285
+ const hasCurrent = newConfigs.some((c) => c.name === current);
286
+ saveContextLoaderConfig(baseUrl, {
287
+ configs: newConfigs,
288
+ current: hasCurrent ? current : name,
289
+ });
290
+ }
291
+ export function setCurrentContextLoader(baseUrl, name) {
292
+ ensureStoreReady();
293
+ const config = loadContextLoaderConfig(baseUrl);
294
+ if (!config) {
295
+ throw new Error("Context-loader is not configured. Run: kweaver context-loader config set --kn-id <id>");
296
+ }
297
+ const hasName = config.configs.some((c) => c.name === name);
298
+ if (!hasName) {
299
+ throw new Error(`No context-loader config named '${name}'. Use config list to see available configs.`);
300
+ }
301
+ saveContextLoaderConfig(baseUrl, { ...config, current: name });
302
+ }
303
+ export function removeContextLoaderEntry(baseUrl, name) {
304
+ ensureStoreReady();
305
+ const config = loadContextLoaderConfig(baseUrl);
306
+ if (!config)
307
+ return;
308
+ const newConfigs = config.configs.filter((c) => c.name !== name);
309
+ if (newConfigs.length === 0) {
310
+ const file = getPlatformFile(baseUrl, "context-loader.json");
311
+ if (existsSync(file))
312
+ rmSync(file, { force: true });
313
+ return;
314
+ }
315
+ let newCurrent = config.current;
316
+ if (config.current === name) {
317
+ newCurrent = newConfigs[0].name;
318
+ }
319
+ saveContextLoaderConfig(baseUrl, { configs: newConfigs, current: newCurrent });
320
+ }
321
+ export function hasPlatform(baseUrl) {
322
+ ensureStoreReady();
323
+ return existsSync(getPlatformFile(baseUrl, "client.json"));
324
+ }
325
+ /**
326
+ * Remove token and callback for a platform so the next auth will do a full login.
327
+ * Keeps client config so the same app registration can be reused.
328
+ */
329
+ export function clearPlatformSession(baseUrl) {
330
+ ensureStoreReady();
331
+ const tokenFile = getPlatformFile(baseUrl, "token.json");
332
+ const callbackFile = getPlatformFile(baseUrl, "callback.json");
333
+ if (existsSync(tokenFile)) {
334
+ rmSync(tokenFile, { force: true });
335
+ }
336
+ if (existsSync(callbackFile)) {
337
+ rmSync(callbackFile, { force: true });
338
+ }
339
+ }
340
+ export function deletePlatform(baseUrl) {
341
+ ensureStoreReady();
342
+ const platformDir = getPlatformDir(baseUrl);
343
+ if (!existsSync(platformDir)) {
344
+ return;
345
+ }
346
+ deletePlatformAlias(baseUrl);
347
+ rmSync(platformDir, { recursive: true, force: true });
348
+ const state = readState();
349
+ if (state.currentPlatform !== baseUrl) {
350
+ return;
351
+ }
352
+ const remainingPlatforms = listPlatforms();
353
+ writeState({
354
+ ...readState(),
355
+ currentPlatform: remainingPlatforms[0]?.baseUrl,
356
+ });
357
+ }
358
+ export function listPlatforms() {
359
+ ensureStoreReady();
360
+ const currentPlatform = getCurrentPlatform();
361
+ const items = [];
362
+ for (const entry of readdirSync(getPlatformsDirPath())) {
363
+ const dirPath = join(getPlatformsDirPath(), entry);
364
+ if (!statSync(dirPath).isDirectory()) {
365
+ continue;
366
+ }
367
+ const client = readJsonFile(join(dirPath, "client.json"));
368
+ if (!client?.baseUrl) {
369
+ continue;
370
+ }
371
+ items.push({
372
+ baseUrl: client.baseUrl,
373
+ hasToken: existsSync(join(dirPath, "token.json")),
374
+ isCurrent: client.baseUrl === currentPlatform,
375
+ alias: getPlatformAlias(client.baseUrl) ?? undefined,
376
+ });
377
+ }
378
+ items.sort((a, b) => a.baseUrl.localeCompare(b.baseUrl));
379
+ return items;
380
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * KWeaver TypeScript SDK — public API entry point.
3
+ *
4
+ * ## Recommended: KWeaverClient (high-level)
5
+ *
6
+ * ```typescript
7
+ * import { KWeaverClient } from "kweaver-sdk";
8
+ *
9
+ * const client = new KWeaverClient({ baseUrl, accessToken });
10
+ * const kns = await client.knowledgeNetworks.list();
11
+ * const reply = await client.agents.chat("agent-id", "你好");
12
+ * ```
13
+ *
14
+ * ## Advanced: raw API functions (low-level)
15
+ *
16
+ * All API functions take explicit `baseUrl` and `accessToken` parameters.
17
+ * Use `getCurrentPlatform` / `getConfigDir` to read credentials saved by the CLI.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import { listKnowledgeNetworks, sendChatRequest } from "kweaver-sdk";
22
+ *
23
+ * const kns = await listKnowledgeNetworks({ baseUrl, accessToken });
24
+ * const reply = await sendChatRequest({ baseUrl, accessToken, agentId, agentKey, agentVersion, query, stream: false });
25
+ * console.log(reply.text);
26
+ * ```
27
+ */
28
+ export type { ListKnowledgeNetworksOptions, GetKnowledgeNetworkOptions, CreateKnowledgeNetworkOptions, UpdateKnowledgeNetworkOptions, DeleteKnowledgeNetworkOptions, ListSchemaTypesOptions, } from "./api/knowledge-networks.js";
29
+ export { listKnowledgeNetworks, getKnowledgeNetwork, createKnowledgeNetwork, updateKnowledgeNetwork, deleteKnowledgeNetwork, listObjectTypes, listRelationTypes, listActionTypes, } from "./api/knowledge-networks.js";
30
+ export type { OntologyQueryBaseOptions, ObjectTypeQueryOptions, ObjectTypePropertiesOptions, SubgraphOptions, ActionTypeQueryOptions, ActionTypeExecuteOptions, ActionExecutionGetOptions, ActionLogsListOptions, ActionLogGetOptions, ActionLogCancelOptions, } from "./api/ontology-query.js";
31
+ export { objectTypeQuery, objectTypeProperties, subgraph, actionTypeQuery, actionTypeExecute, actionExecutionGet, actionLogsList, actionLogGet, actionLogCancel, } from "./api/ontology-query.js";
32
+ export type { SendChatRequestOptions, SendChatRequestStreamCallbacks, ChatResult, ProgressItem, AgentInfo, } from "./api/agent-chat.js";
33
+ export { sendChatRequest, sendChatRequestStream, fetchAgentInfo, buildChatUrl, buildAgentInfoUrl, extractText, } from "./api/agent-chat.js";
34
+ export type { ListAgentsOptions } from "./api/agent-list.js";
35
+ export { listAgents } from "./api/agent-list.js";
36
+ export type { ListConversationsOptions, ListMessagesOptions } from "./api/conversations.js";
37
+ export { listConversations, listMessages } from "./api/conversations.js";
38
+ export type { SemanticSearchOptions } from "./api/semantic-search.js";
39
+ export { semanticSearch } from "./api/semantic-search.js";
40
+ export type { ContextLoaderCallOptions, KnSearchArgs, KnSchemaSearchArgs, ConditionSpec, QueryObjectInstanceArgs, RelationTypePath, QueryInstanceSubgraphArgs, GetLogicPropertiesValuesArgs, GetActionInfoArgs, MissingInputParamsError, } from "./api/context-loader.js";
41
+ export { knSearch, knSchemaSearch, queryObjectInstance, queryInstanceSubgraph, getLogicPropertiesValues, getActionInfo, formatMissingInputParamsHint, validateCondition, validateInstanceIdentity, validateInstanceIdentities, } from "./api/context-loader.js";
42
+ export type { ConfigureOptions } from "./kweaver.js";
43
+ export { configure, search, agents, chat, bkns, weaver, getClient } from "./kweaver.js";
44
+ export type { KWeaverClientOptions, ClientContext } from "./client.js";
45
+ export { KWeaverClient } from "./client.js";
46
+ export { KnowledgeNetworksResource } from "./resources/knowledge-networks.js";
47
+ export { AgentsResource } from "./resources/agents.js";
48
+ export { BknResource } from "./resources/bkn.js";
49
+ export { ConversationsResource } from "./resources/conversations.js";
50
+ export { ContextLoaderResource } from "./resources/context-loader.js";
51
+ export { HttpError, NetworkRequestError, fetchTextOrThrow } from "./utils/http.js";
52
+ export type { ClientConfig, TokenConfig, ContextLoaderEntry, ContextLoaderConfig, PlatformSummary, } from "./config/store.js";
53
+ export { getConfigDir, getCurrentPlatform } from "./config/store.js";
package/dist/index.js ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * KWeaver TypeScript SDK — public API entry point.
3
+ *
4
+ * ## Recommended: KWeaverClient (high-level)
5
+ *
6
+ * ```typescript
7
+ * import { KWeaverClient } from "kweaver-sdk";
8
+ *
9
+ * const client = new KWeaverClient({ baseUrl, accessToken });
10
+ * const kns = await client.knowledgeNetworks.list();
11
+ * const reply = await client.agents.chat("agent-id", "你好");
12
+ * ```
13
+ *
14
+ * ## Advanced: raw API functions (low-level)
15
+ *
16
+ * All API functions take explicit `baseUrl` and `accessToken` parameters.
17
+ * Use `getCurrentPlatform` / `getConfigDir` to read credentials saved by the CLI.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import { listKnowledgeNetworks, sendChatRequest } from "kweaver-sdk";
22
+ *
23
+ * const kns = await listKnowledgeNetworks({ baseUrl, accessToken });
24
+ * const reply = await sendChatRequest({ baseUrl, accessToken, agentId, agentKey, agentVersion, query, stream: false });
25
+ * console.log(reply.text);
26
+ * ```
27
+ */
28
+ export { listKnowledgeNetworks, getKnowledgeNetwork, createKnowledgeNetwork, updateKnowledgeNetwork, deleteKnowledgeNetwork, listObjectTypes, listRelationTypes, listActionTypes, } from "./api/knowledge-networks.js";
29
+ export { objectTypeQuery, objectTypeProperties, subgraph, actionTypeQuery, actionTypeExecute, actionExecutionGet, actionLogsList, actionLogGet, actionLogCancel, } from "./api/ontology-query.js";
30
+ export { sendChatRequest, sendChatRequestStream, fetchAgentInfo, buildChatUrl, buildAgentInfoUrl, extractText, } from "./api/agent-chat.js";
31
+ export { listAgents } from "./api/agent-list.js";
32
+ export { listConversations, listMessages } from "./api/conversations.js";
33
+ export { semanticSearch } from "./api/semantic-search.js";
34
+ export { knSearch, knSchemaSearch, queryObjectInstance, queryInstanceSubgraph, getLogicPropertiesValues, getActionInfo, formatMissingInputParamsHint, validateCondition, validateInstanceIdentity, validateInstanceIdentities, } from "./api/context-loader.js";
35
+ export { configure, search, agents, chat, bkns, weaver, getClient } from "./kweaver.js";
36
+ export { KWeaverClient } from "./client.js";
37
+ export { KnowledgeNetworksResource } from "./resources/knowledge-networks.js";
38
+ export { AgentsResource } from "./resources/agents.js";
39
+ export { BknResource } from "./resources/bkn.js";
40
+ export { ConversationsResource } from "./resources/conversations.js";
41
+ export { ContextLoaderResource } from "./resources/context-loader.js";
42
+ // ── HTTP utilities ────────────────────────────────────────────────────────────
43
+ export { HttpError, NetworkRequestError, fetchTextOrThrow } from "./utils/http.js";
44
+ export { getConfigDir, getCurrentPlatform } from "./config/store.js";
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Module-level simple API — cognee-style usage without instantiating KWeaverClient.
3
+ *
4
+ * @example Read-only (search + chat, no weaver needed)
5
+ * ```typescript
6
+ * import kweaver from "kweaver-sdk/kweaver";
7
+ *
8
+ * kweaver.configure({ config: true, bknId: "your-bkn-id", agentId: "your-agent-id" });
9
+ *
10
+ * const results = await kweaver.search("供应链有哪些风险?");
11
+ * const reply = await kweaver.chat("总结前三大风险");
12
+ * console.log(reply.text);
13
+ * ```
14
+ *
15
+ * @example Write then build
16
+ * ```typescript
17
+ * kweaver.configure({ baseUrl: "https://...", accessToken: "token", bknId: "abc" });
18
+ * // ... add datasource, object types via kweaver.client ...
19
+ * await kweaver.weaver({ wait: true });
20
+ * const results = await kweaver.search("新接入的数据");
21
+ * ```
22
+ */
23
+ import { KWeaverClient } from "./client.js";
24
+ import type { ChatResult } from "./api/agent-chat.js";
25
+ import type { SemanticSearchResult } from "./resources/bkn.js";
26
+ import type { BuildStatus } from "./resources/knowledge-networks.js";
27
+ export interface ConfigureOptions {
28
+ /**
29
+ * KWeaver base URL. Required unless config=true or KWEAVER_BASE_URL is set.
30
+ */
31
+ baseUrl?: string;
32
+ /** Bearer access token. Required unless config=true or KWEAVER_TOKEN is set. */
33
+ accessToken?: string;
34
+ /**
35
+ * If true, read credentials from ~/.kweaver/ (saved by `kweaver auth login`).
36
+ * When config=true, baseUrl is ignored — the URL comes from the saved platform
37
+ * config, preventing accidental cross-environment credential leaks.
38
+ */
39
+ config?: boolean;
40
+ /** Default BKN ID used by search() and weaver(). */
41
+ bknId?: string;
42
+ /** Default agent ID used by chat(). */
43
+ agentId?: string;
44
+ /** x-business-domain header. Defaults to "bd_public". */
45
+ businessDomain?: string;
46
+ }
47
+ /**
48
+ * Initialize the default KWeaver client.
49
+ * Must be called before any other kweaver.* function.
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * kweaver.configure({ config: true, bknId: "abc", agentId: "ag1" });
54
+ * kweaver.configure({ baseUrl: "https://...", accessToken: "token", bknId: "abc" });
55
+ * ```
56
+ */
57
+ export declare function configure(opts: ConfigureOptions): void;
58
+ /**
59
+ * Semantic search over a BKN.
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const results = await kweaver.search("供应链风险");
64
+ * for (const c of results.concepts) console.log(c.concept_name);
65
+ * ```
66
+ */
67
+ export declare function search(query: string, opts?: {
68
+ bknId?: string;
69
+ mode?: string;
70
+ maxConcepts?: number;
71
+ }): Promise<SemanticSearchResult>;
72
+ /**
73
+ * List published agents.
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const list = await kweaver.agents({ keyword: "supply" });
78
+ * list.forEach(a => console.log(a));
79
+ * ```
80
+ */
81
+ export declare function agents(opts?: {
82
+ keyword?: string;
83
+ limit?: number;
84
+ }): Promise<unknown[]>;
85
+ /**
86
+ * Send a message to an agent.
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * const reply = await kweaver.chat("分析供应链风险");
91
+ * console.log(reply.text);
92
+ * ```
93
+ */
94
+ export declare function chat(message: string, opts?: {
95
+ agentId?: string;
96
+ conversationId?: string;
97
+ }): Promise<ChatResult>;
98
+ /**
99
+ * List BKNs (Business Knowledge Networks).
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * const list = await kweaver.bkns();
104
+ * list.forEach(b => console.log(b));
105
+ * ```
106
+ */
107
+ export declare function bkns(opts?: {
108
+ limit?: number;
109
+ name_pattern?: string;
110
+ }): Promise<unknown[]>;
111
+ /**
112
+ * Trigger a full build (index rebuild) of a BKN.
113
+ *
114
+ * Only needed after write-side changes (added datasource, modified object/relation
115
+ * types). Pure read-only usage (search, chat) does not require weaver().
116
+ *
117
+ * @param opts.wait If true, poll until completed and return the final BuildStatus.
118
+ * @param opts.timeout Max wait time in **milliseconds** (default 300_000 = 5 min).
119
+ * Note: Python SDK uses seconds; multiply by 1000 when porting.
120
+ * @param opts.interval Poll interval in **milliseconds** (default 2_000).
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * await kweaver.weaver({ wait: true }); // block until done
125
+ * await kweaver.weaver({ wait: true, timeout: 60_000 }); // 60-second timeout
126
+ * await kweaver.weaver(); // fire-and-forget (returns void)
127
+ * ```
128
+ */
129
+ export declare function weaver(opts?: {
130
+ bknId?: string;
131
+ wait?: boolean;
132
+ timeout?: number;
133
+ interval?: number;
134
+ }): Promise<BuildStatus | void>;
135
+ /** Access the underlying KWeaverClient for advanced operations. */
136
+ export declare function getClient(): KWeaverClient;
137
+ declare const _default: {
138
+ configure: typeof configure;
139
+ search: typeof search;
140
+ agents: typeof agents;
141
+ chat: typeof chat;
142
+ bkns: typeof bkns;
143
+ weaver: typeof weaver;
144
+ getClient: typeof getClient;
145
+ };
146
+ export default _default;