@kweaver-ai/kweaver-sdk 0.4.0 → 0.4.2

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 (41) hide show
  1. package/README.md +139 -0
  2. package/README.zh.md +139 -0
  3. package/dist/api/agent-list.d.ts +51 -0
  4. package/dist/api/agent-list.js +116 -7
  5. package/dist/api/bkn-backend.d.ts +16 -0
  6. package/dist/api/bkn-backend.js +46 -0
  7. package/dist/api/datasources.d.ts +73 -0
  8. package/dist/api/datasources.js +218 -0
  9. package/dist/api/dataviews.d.ts +20 -0
  10. package/dist/api/dataviews.js +72 -0
  11. package/dist/api/knowledge-networks.d.ts +84 -0
  12. package/dist/api/knowledge-networks.js +167 -0
  13. package/dist/api/ontology-query.d.ts +1 -1
  14. package/dist/api/ontology-query.js +1 -0
  15. package/dist/api/vega.d.ts +110 -0
  16. package/dist/api/vega.js +251 -0
  17. package/dist/auth/oauth.d.ts +3 -1
  18. package/dist/auth/oauth.js +12 -9
  19. package/dist/cli.js +15 -0
  20. package/dist/client.d.ts +19 -0
  21. package/dist/client.js +76 -13
  22. package/dist/commands/agent.d.ts +7 -0
  23. package/dist/commands/agent.js +392 -13
  24. package/dist/commands/bkn.d.ts +22 -0
  25. package/dist/commands/bkn.js +1057 -41
  26. package/dist/commands/call.js +20 -1
  27. package/dist/commands/context-loader.js +4 -4
  28. package/dist/commands/ds.d.ts +7 -0
  29. package/dist/commands/ds.js +283 -0
  30. package/dist/commands/vega.d.ts +1 -0
  31. package/dist/commands/vega.js +663 -0
  32. package/dist/index.d.ts +3 -2
  33. package/dist/index.js +1 -1
  34. package/dist/resources/agents.d.ts +83 -9
  35. package/dist/resources/agents.js +46 -10
  36. package/dist/resources/bkn.d.ts +12 -0
  37. package/dist/resources/bkn.js +12 -0
  38. package/dist/resources/knowledge-networks.js +19 -58
  39. package/dist/utils/crypto.d.ts +10 -0
  40. package/dist/utils/crypto.js +31 -0
  41. package/package.json +4 -2
@@ -1,5 +1,76 @@
1
1
  import type { ChatResult, SendChatRequestStreamCallbacks } from "../api/agent-chat.js";
2
2
  import type { ClientContext } from "../client.js";
3
+ export interface AgentLlmConfig {
4
+ id?: string;
5
+ name: string;
6
+ model_type?: string;
7
+ temperature?: number;
8
+ top_p?: number;
9
+ top_k?: number;
10
+ frequency_penalty?: number;
11
+ presence_penalty?: number;
12
+ max_tokens: number;
13
+ }
14
+ export interface AgentLlmItem {
15
+ is_default: boolean;
16
+ llm_config: AgentLlmConfig;
17
+ }
18
+ export interface AgentInputField {
19
+ name: string;
20
+ type?: string;
21
+ desc?: string;
22
+ }
23
+ export interface AgentInput {
24
+ fields: AgentInputField[];
25
+ rewrite?: Record<string, unknown>;
26
+ augment?: Record<string, unknown>;
27
+ }
28
+ export interface AgentOutput {
29
+ variables?: Record<string, unknown>;
30
+ default_format?: string;
31
+ }
32
+ export interface AgentConfig {
33
+ input: AgentInput;
34
+ output: AgentOutput;
35
+ system_prompt?: string;
36
+ dolphin?: string;
37
+ is_dolphin_mode?: number;
38
+ data_source?: Record<string, unknown>;
39
+ skills?: Record<string, unknown>;
40
+ llms?: AgentLlmItem[];
41
+ opening_remark_config?: Record<string, unknown>;
42
+ preset_questions?: Array<{
43
+ question: string;
44
+ }>;
45
+ memory?: {
46
+ is_enabled: boolean;
47
+ };
48
+ related_question?: {
49
+ is_enabled: boolean;
50
+ };
51
+ plan_mode?: {
52
+ is_enabled: boolean;
53
+ };
54
+ conversation_history_config?: Record<string, unknown>;
55
+ [key: string]: unknown;
56
+ }
57
+ export interface CreateAgentBody {
58
+ name: string;
59
+ profile: string;
60
+ avatar_type?: number;
61
+ avatar?: string;
62
+ product_key?: string;
63
+ key?: string;
64
+ config: AgentConfig;
65
+ }
66
+ export interface UpdateAgentBody {
67
+ name: string;
68
+ profile: string;
69
+ avatar_type: number;
70
+ avatar: string;
71
+ product_key: string;
72
+ config: AgentConfig;
73
+ }
3
74
  export declare class AgentsResource {
4
75
  private readonly ctx;
5
76
  constructor(ctx: ClientContext);
@@ -9,26 +80,29 @@ export declare class AgentsResource {
9
80
  offset?: number;
10
81
  limit?: number;
11
82
  }): Promise<unknown[]>;
12
- /** Resolve agent key and version for a given agent id. */
83
+ get(agentId: string): Promise<unknown>;
84
+ getByKey(key: string): Promise<unknown>;
85
+ create(body: CreateAgentBody): Promise<{
86
+ id: string;
87
+ version: string;
88
+ }>;
89
+ update(agentId: string, body: UpdateAgentBody): Promise<void>;
90
+ delete(agentId: string): Promise<void>;
91
+ publish(agentId: string, opts?: {
92
+ business_domain_id?: string;
93
+ }): Promise<unknown>;
94
+ unpublish(agentId: string): Promise<void>;
13
95
  info(agentId: string, version?: string): Promise<{
14
96
  id: string;
15
97
  key: string;
16
98
  version: string;
17
99
  }>;
18
- /**
19
- * Send a single message and return the full response.
20
- * Automatically resolves the agent key/version before sending.
21
- */
22
100
  chat(agentId: string, message: string, opts?: {
23
101
  conversationId?: string;
24
102
  version?: string;
25
103
  stream?: boolean;
26
104
  verbose?: boolean;
27
105
  }): Promise<ChatResult>;
28
- /**
29
- * Send a message with streaming callbacks.
30
- * Automatically resolves the agent key/version before sending.
31
- */
32
106
  stream(agentId: string, message: string, callbacks: SendChatRequestStreamCallbacks, opts?: {
33
107
  conversationId?: string;
34
108
  version?: string;
@@ -1,10 +1,12 @@
1
- import { listAgents } from "../api/agent-list.js";
1
+ import { listAgents, getAgent, getAgentByKey, createAgent, updateAgent, deleteAgent, publishAgent, unpublishAgent, } from "../api/agent-list.js";
2
2
  import { fetchAgentInfo, sendChatRequest, sendChatRequestStream, } from "../api/agent-chat.js";
3
+ // ── AgentsResource ───────────────────────────────────────────────────────────
3
4
  export class AgentsResource {
4
5
  ctx;
5
6
  constructor(ctx) {
6
7
  this.ctx = ctx;
7
8
  }
9
+ // ── List (published agents) ──────────────────────────────────────────────
8
10
  async list(opts = {}) {
9
11
  const { keyword, ...rest } = opts;
10
12
  const raw = await listAgents({ ...this.ctx.base(), name: keyword, ...rest });
@@ -16,15 +18,52 @@ export class AgentsResource {
16
18
  : [];
17
19
  return items;
18
20
  }
19
- /** Resolve agent key and version for a given agent id. */
21
+ // ── Get by ID ────────────────────────────────────────────────────────────
22
+ async get(agentId) {
23
+ const raw = await getAgent({ ...this.ctx.base(), agentId });
24
+ return JSON.parse(raw);
25
+ }
26
+ // ── Get by key ───────────────────────────────────────────────────────────
27
+ async getByKey(key) {
28
+ const raw = await getAgentByKey({ ...this.ctx.base(), key });
29
+ return JSON.parse(raw);
30
+ }
31
+ // ── Create ───────────────────────────────────────────────────────────────
32
+ async create(body) {
33
+ // Apply defaults for required fields the user may omit
34
+ const payload = {
35
+ avatar_type: body.avatar_type ?? 1,
36
+ avatar: body.avatar ?? "icon-dip-agent-default",
37
+ product_key: body.product_key ?? "DIP",
38
+ ...body,
39
+ };
40
+ const raw = await createAgent({ ...this.ctx.base(), body: JSON.stringify(payload) });
41
+ return JSON.parse(raw);
42
+ }
43
+ // ── Update ───────────────────────────────────────────────────────────────
44
+ async update(agentId, body) {
45
+ await updateAgent({ ...this.ctx.base(), agentId, body: JSON.stringify(body) });
46
+ }
47
+ // ── Delete ───────────────────────────────────────────────────────────────
48
+ async delete(agentId) {
49
+ await deleteAgent({ ...this.ctx.base(), agentId });
50
+ }
51
+ // ── Publish ──────────────────────────────────────────────────────────────
52
+ async publish(agentId, opts = {}) {
53
+ const body = JSON.stringify({ agent_id: agentId, ...opts });
54
+ const raw = await publishAgent({ ...this.ctx.base(), agentId, body });
55
+ return JSON.parse(raw);
56
+ }
57
+ // ── Unpublish ────────────────────────────────────────────────────────────
58
+ async unpublish(agentId) {
59
+ await unpublishAgent({ ...this.ctx.base(), agentId });
60
+ }
61
+ // ── Agent info (resolve key/version) ─────────────────────────────────────
20
62
  async info(agentId, version = "v0") {
21
63
  const info = await fetchAgentInfo({ ...this.ctx.base(), agentId, version });
22
64
  return info;
23
65
  }
24
- /**
25
- * Send a single message and return the full response.
26
- * Automatically resolves the agent key/version before sending.
27
- */
66
+ // ── Chat (single-shot) ──────────────────────────────────────────────────
28
67
  async chat(agentId, message, opts = {}) {
29
68
  const { version = "v0", stream = false, conversationId, verbose } = opts;
30
69
  const info = await fetchAgentInfo({ ...this.ctx.base(), agentId, version });
@@ -39,10 +78,7 @@ export class AgentsResource {
39
78
  verbose,
40
79
  });
41
80
  }
42
- /**
43
- * Send a message with streaming callbacks.
44
- * Automatically resolves the agent key/version before sending.
45
- */
81
+ // ── Stream ──────────────────────────────────────────────────────────────
46
82
  async stream(agentId, message, callbacks, opts = {}) {
47
83
  const { version = "v0", conversationId, verbose } = opts;
48
84
  const info = await fetchAgentInfo({ ...this.ctx.base(), agentId, version });
@@ -42,4 +42,16 @@ export declare class BknResource {
42
42
  }): Promise<unknown[]>;
43
43
  getActionLog(knId: string, logId: string): Promise<unknown>;
44
44
  cancelActionLog(knId: string, logId: string): Promise<unknown>;
45
+ /**
46
+ * Search KN schema — finds matching object types, relation types, and action types.
47
+ * Uses MCP protocol via the context-loader (public endpoint).
48
+ */
49
+ knSearch(knId: string, query: string, opts?: {
50
+ onlySchema?: boolean;
51
+ }): Promise<{
52
+ object_types?: unknown[];
53
+ relation_types?: unknown[];
54
+ action_types?: unknown[];
55
+ nodes?: unknown[];
56
+ }>;
45
57
  }
@@ -83,4 +83,16 @@ export class BknResource {
83
83
  const raw = await actionLogCancel({ ...this.ctx.base(), knId, logId });
84
84
  return JSON.parse(raw);
85
85
  }
86
+ /**
87
+ * Search KN schema — finds matching object types, relation types, and action types.
88
+ * Uses MCP protocol via the context-loader (public endpoint).
89
+ */
90
+ async knSearch(knId, query, opts = {}) {
91
+ const { ContextLoaderResource } = await import("./context-loader.js");
92
+ const { baseUrl } = this.ctx.base();
93
+ const mcpUrl = `${baseUrl}/api/agent-retrieval/v1/mcp`;
94
+ const cl = new ContextLoaderResource(this.ctx, mcpUrl, knId);
95
+ const result = await cl.search({ query, only_schema: opts.onlySchema ?? false });
96
+ return result;
97
+ }
86
98
  }
@@ -1,8 +1,5 @@
1
1
  import { listKnowledgeNetworks, getKnowledgeNetwork, createKnowledgeNetwork, updateKnowledgeNetwork, deleteKnowledgeNetwork, listObjectTypes, listRelationTypes, listActionTypes, } from "../api/knowledge-networks.js";
2
2
  import { fetchTextOrThrow } from "../utils/http.js";
3
- function is404(err) {
4
- return !!(err && typeof err === "object" && "status" in err && err.status === 404);
5
- }
6
3
  export class KnowledgeNetworksResource {
7
4
  ctx;
8
5
  constructor(ctx) {
@@ -11,9 +8,8 @@ export class KnowledgeNetworksResource {
11
8
  async list(opts = {}) {
12
9
  const raw = await listKnowledgeNetworks({ ...this.ctx.base(), ...opts });
13
10
  const parsed = JSON.parse(raw);
14
- const data = parsed && typeof parsed === "object" && "data" in parsed
15
- ? parsed.data
16
- : parsed;
11
+ // API returns { entries: [...] }
12
+ const data = parsed?.entries ?? parsed?.data ?? parsed;
17
13
  return Array.isArray(data) ? data : [];
18
14
  }
19
15
  async get(knId, opts = {}) {
@@ -77,29 +73,11 @@ export class KnowledgeNetworksResource {
77
73
  token: accessToken,
78
74
  "x-business-domain": businessDomain,
79
75
  };
80
- try {
81
- await fetchTextOrThrow(`${baseUrl}/api/agent-retrieval/in/v1/kn/full_build_ontology`, { method: "POST", headers, body: JSON.stringify({ kn_id: bknId }) });
82
- }
83
- catch (err) {
84
- if (!is404(err))
85
- throw err;
86
- // Fallback: call ontology-manager jobs endpoint directly
87
- try {
88
- await fetchTextOrThrow(`${baseUrl}/api/ontology-manager/in/v1/knowledge-networks/${encodeURIComponent(bknId)}/jobs`, {
89
- method: "POST",
90
- headers,
91
- body: JSON.stringify({ name: `sdk_build_${bknId.slice(0, 8)}`, job_type: "full" }),
92
- });
93
- }
94
- catch (err2) {
95
- if (is404(err2)) {
96
- throw new Error(`No build endpoint available for BKN ${bknId}. ` +
97
- `Both agent-retrieval and ontology-manager returned 404. ` +
98
- `This deployment may not support index rebuilds.`);
99
- }
100
- throw err2;
101
- }
102
- }
76
+ await fetchTextOrThrow(`${baseUrl}/api/ontology-manager/v1/knowledge-networks/${encodeURIComponent(bknId)}/jobs`, {
77
+ method: "POST",
78
+ headers,
79
+ body: JSON.stringify({ name: `sdk_build_${bknId.slice(0, 8)}`, job_type: "full" }),
80
+ });
103
81
  }
104
82
  /** Poll build status for a BKN. */
105
83
  async buildStatus(bknId) {
@@ -109,36 +87,19 @@ export class KnowledgeNetworksResource {
109
87
  token: accessToken,
110
88
  "x-business-domain": businessDomain,
111
89
  };
112
- try {
113
- const { body } = await fetchTextOrThrow(`${baseUrl}/api/agent-retrieval/in/v1/kn/full_ontology_building_status?kn_id=${encodeURIComponent(bknId)}`, { headers });
114
- const data = JSON.parse(body);
115
- return { state: data.state ?? "running", state_detail: data.state_detail };
116
- }
117
- catch (err) {
118
- if (!is404(err))
119
- throw err;
120
- // Fallback: check ontology-manager jobs for latest status
121
- try {
122
- const { body } = await fetchTextOrThrow(`${baseUrl}/api/ontology-manager/in/v1/knowledge-networks/${encodeURIComponent(bknId)}/jobs?limit=1&direction=desc`, { headers });
123
- const data = JSON.parse(body);
124
- const jobs = Array.isArray(data)
125
- ? data
126
- : data && typeof data === "object" && "entries" in data
127
- ? (data.entries ?? [])
128
- : data && typeof data === "object" && "data" in data
129
- ? (data.data ?? [])
130
- : [];
131
- if (jobs.length > 0) {
132
- return { state: jobs[0].state ?? "running" };
133
- }
134
- return { state: "completed" };
135
- }
136
- catch (err2) {
137
- if (is404(err2))
138
- return { state: "completed" };
139
- throw err2;
140
- }
90
+ const { body } = await fetchTextOrThrow(`${baseUrl}/api/ontology-manager/v1/knowledge-networks/${encodeURIComponent(bknId)}/jobs?limit=1&direction=desc`, { headers });
91
+ const data = JSON.parse(body);
92
+ const jobs = Array.isArray(data)
93
+ ? data
94
+ : data && typeof data === "object" && "entries" in data
95
+ ? (data.entries ?? [])
96
+ : data && typeof data === "object" && "data" in data
97
+ ? (data.data ?? [])
98
+ : [];
99
+ if (jobs.length > 0) {
100
+ return { state: jobs[0].state ?? "running", state_detail: jobs[0].state_detail };
141
101
  }
102
+ return { state: "completed" };
142
103
  }
143
104
  /**
144
105
  * Trigger a full BKN build and wait for it to complete.
@@ -0,0 +1,10 @@
1
+ /**
2
+ * RSA password encryption for the KWeaver data-connection API.
3
+ * The KWeaver backend requires datasource passwords to be RSA-encrypted
4
+ * (PKCS1v15) using a platform-wide public key before transmission.
5
+ */
6
+ /**
7
+ * Encrypt a password with the KWeaver platform RSA public key.
8
+ * Returns a base64-encoded ciphertext string.
9
+ */
10
+ export declare function encryptPassword(plaintext: string): string;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * RSA password encryption for the KWeaver data-connection API.
3
+ * The KWeaver backend requires datasource passwords to be RSA-encrypted
4
+ * (PKCS1v15) using a platform-wide public key before transmission.
5
+ */
6
+ import { publicEncrypt, createPublicKey, constants } from "node:crypto";
7
+ const KWEAVER_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
8
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA22GOSQ1jeDhpdzxhJddS
9
+ f+U10F4Ivut7giYhchFAIJgRonMamDT86MSqQUc8DdTFdPGLm7M3GUKcsG1qbC3S
10
+ qk4XJ9NjmQXbs7IMWyWEWQrN7Iv7S2QjDYJI+ppvIN03I0Km3WKsmnrle2bLzT/V
11
+ G8e72YX69dfXAeiX6uDhht1va/JxZVFMIV3pHa6AQQ9gn5SAUTX2akEhRfe1bPJj
12
+ fVyoM+dfNtvgdfaraqV1rOhVDEqd0NlOWt2RHwETQwU8gIJib2baj2MtyIAY+fQw
13
+ KlKWxUs1GcFbECnhVPiVN6BEhXD7OhRt9QE/cuYl5v4a6ypugGaMBK6VKOqFHDvf
14
+ mwIDAQAB
15
+ -----END PUBLIC KEY-----`;
16
+ let cachedKey = null;
17
+ function getPublicKey() {
18
+ if (!cachedKey) {
19
+ cachedKey = createPublicKey(KWEAVER_PUBLIC_KEY_PEM);
20
+ }
21
+ return cachedKey;
22
+ }
23
+ /**
24
+ * Encrypt a password with the KWeaver platform RSA public key.
25
+ * Returns a base64-encoded ciphertext string.
26
+ */
27
+ export function encryptPassword(plaintext) {
28
+ const key = getPublicKey();
29
+ const ciphertext = publicEncrypt({ key, padding: constants.RSA_PKCS1_PADDING }, Buffer.from(plaintext, "utf8"));
30
+ return ciphertext.toString("base64");
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kweaver-ai/kweaver-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
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",
@@ -27,7 +27,8 @@
27
27
  "build": "tsc -p tsconfig.json",
28
28
  "start": "node ./dist/cli.js",
29
29
  "lint": "tsc --noEmit -p tsconfig.json",
30
- "test": "node --import tsx --test test/**/*.test.ts",
30
+ "test": "node --import tsx --test test/*.test.ts",
31
+ "test:e2e": "node --import tsx --test test/e2e/**/*.test.ts",
31
32
  "prepublishOnly": "npm run build"
32
33
  },
33
34
  "keywords": [
@@ -53,6 +54,7 @@
53
54
  "typescript": "^5.9.3"
54
55
  },
55
56
  "dependencies": {
57
+ "@kweaver-ai/bkn": "^0.1.0",
56
58
  "ink": "^6.8.0",
57
59
  "ink-spinner": "^5.0.0",
58
60
  "ink-text-input": "^6.0.0",