@kweaver-ai/kweaver-sdk 0.4.1 → 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.
package/dist/cli.js CHANGED
@@ -5,6 +5,7 @@ import { runCallCommand } from "./commands/call.js";
5
5
  import { runContextLoaderCommand } from "./commands/context-loader.js";
6
6
  import { runDsCommand } from "./commands/ds.js";
7
7
  import { runTokenCommand } from "./commands/token.js";
8
+ import { runVegaCommand } from "./commands/vega.js";
8
9
  function printHelp() {
9
10
  console.log(`kweaver
10
11
 
@@ -31,6 +32,7 @@ Usage:
31
32
  kweaver bkn create [options]
32
33
  kweaver bkn update <kn-id> [options]
33
34
  kweaver bkn delete <kn-id>
35
+ kweaver vega [health|stats|inspect|catalog|resource|connector-type]
34
36
  kweaver context-loader [config|kn-search|...]
35
37
  kweaver --help
36
38
 
@@ -41,6 +43,7 @@ Commands:
41
43
  ds Manage datasources (list, get, delete, tables, connect)
42
44
  agent Chat with a KWeaver agent (agent chat <id>), list published agents (agent list)
43
45
  bkn Business knowledge network (list/get/create/update/delete/export/stats; object-type, subgraph, action-type, action-log)
46
+ vega Vega observability platform (catalogs, resources, connector-types, health)
44
47
  context-loader Call context-loader MCP (tools, resources, prompts; kn-search, query-*, etc.)
45
48
  help Show this message`);
46
49
  }
@@ -68,6 +71,9 @@ export async function run(argv) {
68
71
  if (command === "bkn") {
69
72
  return runKnCommand(rest);
70
73
  }
74
+ if (command === "vega") {
75
+ return runVegaCommand(rest);
76
+ }
71
77
  if (command === "context-loader" || command === "context") {
72
78
  return runContextLoaderCommand(rest);
73
79
  }
package/dist/client.d.ts CHANGED
@@ -31,6 +31,12 @@ export interface KWeaverClientOptions {
31
31
  * Override with KWEAVER_BUSINESS_DOMAIN env var or pass explicitly.
32
32
  */
33
33
  businessDomain?: string;
34
+ /**
35
+ * When true, read credentials exclusively from ~/.kweaver/ (saved by
36
+ * `kweaver auth login`), ignoring KWEAVER_BASE_URL / KWEAVER_TOKEN env vars.
37
+ * Useful when env vars hold stale tokens or are intended for other tooling.
38
+ */
39
+ config?: boolean;
34
40
  }
35
41
  /**
36
42
  * Main entry point for the KWeaver TypeScript SDK.
@@ -73,6 +79,19 @@ export declare class KWeaverClient implements ClientContext {
73
79
  /** Conversation and message history. */
74
80
  readonly conversations: ConversationsResource;
75
81
  constructor(opts?: KWeaverClientOptions);
82
+ /**
83
+ * Async factory that auto-refreshes expired or revoked tokens.
84
+ *
85
+ * Reads credentials from `~/.kweaver/` and refreshes the access token
86
+ * if it has expired or been revoked (using the saved refresh token).
87
+ * If the initial token fails with 401, forces a refresh and retries.
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * const client = await KWeaverClient.connect();
92
+ * ```
93
+ */
94
+ static connect(opts?: KWeaverClientOptions): Promise<KWeaverClient>;
76
95
  /** @internal — used by resource classes to build API call options. */
77
96
  base(): {
78
97
  baseUrl: string;
package/dist/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getCurrentPlatform, loadTokenConfig, } from "./config/store.js";
2
+ import { ensureValidToken } from "./auth/oauth.js";
2
3
  import { AgentsResource } from "./resources/agents.js";
3
4
  import { ConversationsResource } from "./resources/conversations.js";
4
5
  import { ContextLoaderResource } from "./resources/context-loader.js";
@@ -46,20 +47,37 @@ export class KWeaverClient {
46
47
  /** Conversation and message history. */
47
48
  conversations;
48
49
  constructor(opts = {}) {
49
- const envUrl = process.env.KWEAVER_BASE_URL;
50
- const envToken = process.env.KWEAVER_TOKEN;
51
50
  const envDomain = process.env.KWEAVER_BUSINESS_DOMAIN;
52
- // Resolve baseUrl: explicit > env > saved config
53
- let baseUrl = opts.baseUrl ?? envUrl;
54
- let accessToken = opts.accessToken ?? envToken;
55
- if (!baseUrl || !accessToken) {
51
+ let baseUrl;
52
+ let accessToken;
53
+ if (opts.config) {
54
+ // config: true read exclusively from ~/.kweaver/, ignore env vars
56
55
  const platform = getCurrentPlatform();
57
- if (platform) {
58
- const stored = loadTokenConfig(platform);
59
- if (!baseUrl)
60
- baseUrl = platform;
61
- if (!accessToken && stored)
62
- accessToken = stored.accessToken;
56
+ if (!platform) {
57
+ throw new Error("No active platform. Run `kweaver auth login` first.");
58
+ }
59
+ const stored = loadTokenConfig(platform);
60
+ if (!stored?.accessToken) {
61
+ throw new Error(`No token for ${platform}. Run \`kweaver auth login\` first.`);
62
+ }
63
+ baseUrl = opts.baseUrl ?? platform;
64
+ accessToken = opts.accessToken ?? stored.accessToken;
65
+ }
66
+ else {
67
+ // Default: explicit > env > saved config
68
+ const envUrl = process.env.KWEAVER_BASE_URL;
69
+ const envToken = process.env.KWEAVER_TOKEN;
70
+ baseUrl = opts.baseUrl ?? envUrl;
71
+ accessToken = opts.accessToken ?? envToken;
72
+ if (!baseUrl || !accessToken) {
73
+ const platform = getCurrentPlatform();
74
+ if (platform) {
75
+ const stored = loadTokenConfig(platform);
76
+ if (!baseUrl)
77
+ baseUrl = platform;
78
+ if (!accessToken && stored)
79
+ accessToken = stored.accessToken;
80
+ }
63
81
  }
64
82
  }
65
83
  if (!baseUrl) {
@@ -71,13 +89,58 @@ export class KWeaverClient {
71
89
  "Pass it explicitly, set KWEAVER_TOKEN, or run `kweaver auth login`.");
72
90
  }
73
91
  this._baseUrl = baseUrl.replace(/\/+$/, "");
74
- this._accessToken = accessToken;
92
+ // Strip "Bearer " prefix if present — callers (env vars, config files) may
93
+ // include it, but API helpers always add their own "Bearer " prefix.
94
+ this._accessToken = accessToken.replace(/^Bearer\s+/i, "");
75
95
  this._businessDomain = opts.businessDomain ?? envDomain ?? "bd_public";
76
96
  this.knowledgeNetworks = new KnowledgeNetworksResource(this);
77
97
  this.agents = new AgentsResource(this);
78
98
  this.bkn = new BknResource(this);
79
99
  this.conversations = new ConversationsResource(this);
80
100
  }
101
+ /**
102
+ * Async factory that auto-refreshes expired or revoked tokens.
103
+ *
104
+ * Reads credentials from `~/.kweaver/` and refreshes the access token
105
+ * if it has expired or been revoked (using the saved refresh token).
106
+ * If the initial token fails with 401, forces a refresh and retries.
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * const client = await KWeaverClient.connect();
111
+ * ```
112
+ */
113
+ static async connect(opts = {}) {
114
+ // Try with current token first
115
+ let token = await ensureValidToken();
116
+ const client = new KWeaverClient({
117
+ baseUrl: token.baseUrl,
118
+ accessToken: token.accessToken,
119
+ ...opts,
120
+ });
121
+ // Quick probe — if the token was revoked server-side, force refresh
122
+ try {
123
+ const probe = await fetch(`${token.baseUrl.replace(/\/+$/, "")}/api/ontology-manager/v1/knowledge-networks?limit=1`, { headers: { authorization: `Bearer ${token.accessToken}`, token: token.accessToken } });
124
+ if (probe.status === 401) {
125
+ try {
126
+ token = await ensureValidToken({ forceRefresh: true });
127
+ }
128
+ catch {
129
+ throw new Error("Access token revoked and refresh token also expired. " +
130
+ "Run `kweaver auth login` to re-authenticate.");
131
+ }
132
+ return new KWeaverClient({
133
+ baseUrl: token.baseUrl,
134
+ accessToken: token.accessToken,
135
+ ...opts,
136
+ });
137
+ }
138
+ }
139
+ catch {
140
+ // Network error — return client as-is, let the caller deal with it
141
+ }
142
+ return client;
143
+ }
81
144
  /** @internal — used by resource classes to build API call options. */
82
145
  base() {
83
146
  return {
@@ -1,6 +1,6 @@
1
1
  import { ensureValidToken, formatHttpError } from "../auth/oauth.js";
2
2
  import { runAgentChatCommand } from "./agent-chat.js";
3
- import { listAgents, getAgent } from "../api/agent-list.js";
3
+ import { listAgents, getAgent, getAgentByKey, createAgent, updateAgent, deleteAgent, publishAgent, unpublishAgent, } from "../api/agent-list.js";
4
4
  import { listConversations, listMessages } from "../api/conversations.js";
5
5
  import { formatCallOutput } from "./call.js";
6
6
  function readStringField(value, ...keys) {
@@ -211,22 +211,20 @@ export function runAgentCommand(args) {
211
211
  console.log(`kweaver agent
212
212
 
213
213
  Subcommands:
214
+ list [options] List published agents
215
+ get <agent_id> [--verbose] Get agent details
216
+ get-by-key <key> Get agent by key
217
+ create --name <n> --profile <p> Create a new agent
218
+ [--key <key>] [--product-key <pk>] [--system-prompt <sp>]
219
+ [--llm-id <id>] [--llm-max-tokens <n>]
220
+ update <agent_id> --name <n> ... Update an existing agent
221
+ delete <agent_id> [-y] Delete an agent
222
+ publish <agent_id> Publish an agent
223
+ unpublish <agent_id> Unpublish an agent
214
224
  chat <agent_id> Start interactive chat with an agent
215
225
  chat <agent_id> -m "message" Send a single message (non-interactive)
216
- [--conversation-id id] Continue an existing conversation
217
- [-cid id] Short alias for --conversation-id
218
- [--session-id id] Alias for --conversation-id
219
- [-conversation_id id] Compatibility alias for reference examples
220
- [--version value] Resolve agent key from a specific version (default: v0)
221
- [--stream] [--no-stream] Enable or disable streaming (default: stream in interactive, no-stream in -m mode)
222
- [--verbose] Print request details to stderr
223
- [-bd|--biz-domain value] Override x-business-domain (default: bd_public)
224
- list [options] List published agents
225
- get <agent_id> [--verbose] Get agent details
226
226
  sessions <agent_id> List all conversations for an agent
227
- [--limit n] [-bd domain] [--pretty]
228
- history <conversation_id> Show message history for a conversation
229
- [--limit n] [-bd domain] [--pretty]`);
227
+ history <conversation_id> Show message history for a conversation`);
230
228
  return Promise.resolve(0);
231
229
  }
232
230
  if (subcommand === "chat") {
@@ -318,6 +316,24 @@ Options:
318
316
  }
319
317
  return runAgentHistoryCommand(rest);
320
318
  }
319
+ if (subcommand === "get-by-key") {
320
+ return runAgentGetByKeyCommand(rest);
321
+ }
322
+ if (subcommand === "create") {
323
+ return runAgentCreateCommand(rest);
324
+ }
325
+ if (subcommand === "update") {
326
+ return runAgentUpdateCommand(rest);
327
+ }
328
+ if (subcommand === "delete") {
329
+ return runAgentDeleteCommand(rest);
330
+ }
331
+ if (subcommand === "publish") {
332
+ return runAgentPublishCommand(rest);
333
+ }
334
+ if (subcommand === "unpublish") {
335
+ return runAgentUnpublishCommand(rest);
336
+ }
321
337
  console.error(`Unknown agent subcommand: ${subcommand}`);
322
338
  return Promise.resolve(1);
323
339
  }
@@ -530,3 +546,265 @@ Options:
530
546
  return 1;
531
547
  }
532
548
  }
549
+ // ── Get by key ───────────────────────────────────────────────────────────────
550
+ async function runAgentGetByKeyCommand(args) {
551
+ const key = args[0];
552
+ if (!key || key.startsWith("-")) {
553
+ console.error("Usage: kweaver agent get-by-key <key>");
554
+ return 1;
555
+ }
556
+ try {
557
+ const token = await ensureValidToken();
558
+ const body = await getAgentByKey({
559
+ baseUrl: token.baseUrl,
560
+ accessToken: token.accessToken,
561
+ key,
562
+ });
563
+ console.log(formatCallOutput(body, true));
564
+ return 0;
565
+ }
566
+ catch (error) {
567
+ console.error(formatHttpError(error));
568
+ return 1;
569
+ }
570
+ }
571
+ // ── Create ───────────────────────────────────────────────────────────────────
572
+ async function runAgentCreateCommand(args) {
573
+ let name = "";
574
+ let profile = "";
575
+ let key = "";
576
+ let productKey = "DIP";
577
+ let systemPrompt = "";
578
+ let llmId = "";
579
+ let llmMaxTokens = 4096;
580
+ let businessDomain = "bd_public";
581
+ for (let i = 0; i < args.length; i += 1) {
582
+ const arg = args[i];
583
+ if (arg === "--help" || arg === "-h") {
584
+ console.log(`kweaver agent create --name <name> --profile <profile> [options]
585
+
586
+ Create a new agent.
587
+
588
+ Required:
589
+ --name <text> Agent name (max 50)
590
+ --profile <text> Agent description (max 500)
591
+
592
+ Optional:
593
+ --key <text> Agent unique key (auto-generated if omitted)
594
+ --product-key <text> Product key: DIP, AnyShare, ChatBI (default: DIP)
595
+ --system-prompt <text> System prompt
596
+ --llm-id <id> LLM model ID (required for public API)
597
+ --llm-max-tokens <n> LLM max tokens (default: 4096)
598
+ -bd, --biz-domain <val> Business domain (default: bd_public)`);
599
+ return 0;
600
+ }
601
+ if (arg === "--name") {
602
+ name = args[++i] ?? "";
603
+ continue;
604
+ }
605
+ if (arg === "--profile") {
606
+ profile = args[++i] ?? "";
607
+ continue;
608
+ }
609
+ if (arg === "--key") {
610
+ key = args[++i] ?? "";
611
+ continue;
612
+ }
613
+ if (arg === "--product-key") {
614
+ productKey = args[++i] ?? "DIP";
615
+ continue;
616
+ }
617
+ if (arg === "--system-prompt") {
618
+ systemPrompt = args[++i] ?? "";
619
+ continue;
620
+ }
621
+ if (arg === "--llm-id") {
622
+ llmId = args[++i] ?? "";
623
+ continue;
624
+ }
625
+ if (arg === "--llm-max-tokens") {
626
+ llmMaxTokens = parseInt(args[++i] ?? "4096", 10);
627
+ continue;
628
+ }
629
+ if (arg === "-bd" || arg === "--biz-domain") {
630
+ businessDomain = args[++i] ?? "bd_public";
631
+ continue;
632
+ }
633
+ }
634
+ if (!name) {
635
+ console.error("--name is required");
636
+ return 1;
637
+ }
638
+ if (!profile) {
639
+ console.error("--profile is required");
640
+ return 1;
641
+ }
642
+ const config = {
643
+ input: { fields: [{ name: "user_input", type: "string", desc: "" }] },
644
+ output: { default_format: "markdown" },
645
+ system_prompt: systemPrompt,
646
+ };
647
+ if (llmId) {
648
+ config.llms = [{ is_default: true, llm_config: { id: llmId, name: llmId, max_tokens: llmMaxTokens } }];
649
+ }
650
+ const payload = {
651
+ name,
652
+ profile,
653
+ avatar_type: 1,
654
+ avatar: "icon-dip-agent-default",
655
+ product_key: productKey,
656
+ config,
657
+ };
658
+ if (key)
659
+ payload.key = key;
660
+ try {
661
+ const token = await ensureValidToken();
662
+ const body = await createAgent({
663
+ baseUrl: token.baseUrl,
664
+ accessToken: token.accessToken,
665
+ businessDomain,
666
+ body: JSON.stringify(payload),
667
+ });
668
+ console.log(body);
669
+ return 0;
670
+ }
671
+ catch (error) {
672
+ console.error(formatHttpError(error));
673
+ return 1;
674
+ }
675
+ }
676
+ // ── Update ───────────────────────────────────────────────────────────────────
677
+ async function runAgentUpdateCommand(args) {
678
+ const agentId = args[0];
679
+ if (!agentId || agentId.startsWith("-")) {
680
+ console.error("Usage: kweaver agent update <agent_id> [--name <n>] [--profile <p>] [--system-prompt <sp>]");
681
+ return 1;
682
+ }
683
+ try {
684
+ const token = await ensureValidToken();
685
+ const currentRaw = await getAgent({
686
+ baseUrl: token.baseUrl,
687
+ accessToken: token.accessToken,
688
+ agentId,
689
+ });
690
+ const current = JSON.parse(currentRaw);
691
+ for (let i = 1; i < args.length; i += 1) {
692
+ const arg = args[i];
693
+ if (arg === "--name") {
694
+ current.name = args[++i] ?? current.name;
695
+ continue;
696
+ }
697
+ if (arg === "--profile") {
698
+ current.profile = args[++i] ?? current.profile;
699
+ continue;
700
+ }
701
+ if (arg === "--system-prompt") {
702
+ const config = (current.config ?? {});
703
+ config.system_prompt = args[++i] ?? "";
704
+ current.config = config;
705
+ continue;
706
+ }
707
+ }
708
+ const body = await updateAgent({
709
+ baseUrl: token.baseUrl,
710
+ accessToken: token.accessToken,
711
+ agentId,
712
+ body: JSON.stringify({
713
+ name: current.name,
714
+ profile: current.profile,
715
+ avatar_type: current.avatar_type,
716
+ avatar: current.avatar,
717
+ product_key: current.product_key,
718
+ config: current.config,
719
+ }),
720
+ });
721
+ if (body)
722
+ console.log(body);
723
+ else
724
+ console.log("Updated.");
725
+ return 0;
726
+ }
727
+ catch (error) {
728
+ console.error(formatHttpError(error));
729
+ return 1;
730
+ }
731
+ }
732
+ // ── Delete ───────────────────────────────────────────────────────────────────
733
+ async function runAgentDeleteCommand(args) {
734
+ const agentId = args[0];
735
+ if (!agentId || agentId.startsWith("-")) {
736
+ console.error("Usage: kweaver agent delete <agent_id> [-y]");
737
+ return 1;
738
+ }
739
+ const autoConfirm = args.includes("-y") || args.includes("--yes");
740
+ if (!autoConfirm) {
741
+ process.stdout.write(`Delete agent ${agentId}? [y/N] `);
742
+ const answer = await new Promise((resolve) => {
743
+ process.stdin.setEncoding("utf8");
744
+ process.stdin.once("data", (data) => resolve(String(data).trim().toLowerCase()));
745
+ });
746
+ if (answer !== "y" && answer !== "yes") {
747
+ console.log("Cancelled.");
748
+ return 0;
749
+ }
750
+ }
751
+ try {
752
+ const token = await ensureValidToken();
753
+ await deleteAgent({
754
+ baseUrl: token.baseUrl,
755
+ accessToken: token.accessToken,
756
+ agentId,
757
+ });
758
+ console.log(`Deleted agent ${agentId}.`);
759
+ return 0;
760
+ }
761
+ catch (error) {
762
+ console.error(formatHttpError(error));
763
+ return 1;
764
+ }
765
+ }
766
+ // ── Publish ──────────────────────────────────────────────────────────────────
767
+ async function runAgentPublishCommand(args) {
768
+ const agentId = args[0];
769
+ if (!agentId || agentId.startsWith("-")) {
770
+ console.error("Usage: kweaver agent publish <agent_id>");
771
+ return 1;
772
+ }
773
+ try {
774
+ const token = await ensureValidToken();
775
+ const body = await publishAgent({
776
+ baseUrl: token.baseUrl,
777
+ accessToken: token.accessToken,
778
+ agentId,
779
+ body: JSON.stringify({ agent_id: agentId }),
780
+ });
781
+ console.log(body);
782
+ return 0;
783
+ }
784
+ catch (error) {
785
+ console.error(formatHttpError(error));
786
+ return 1;
787
+ }
788
+ }
789
+ // ── Unpublish ────────────────────────────────────────────────────────────────
790
+ async function runAgentUnpublishCommand(args) {
791
+ const agentId = args[0];
792
+ if (!agentId || agentId.startsWith("-")) {
793
+ console.error("Usage: kweaver agent unpublish <agent_id>");
794
+ return 1;
795
+ }
796
+ try {
797
+ const token = await ensureValidToken();
798
+ await unpublishAgent({
799
+ baseUrl: token.baseUrl,
800
+ accessToken: token.accessToken,
801
+ agentId,
802
+ });
803
+ console.log(`Unpublished agent ${agentId}.`);
804
+ return 0;
805
+ }
806
+ catch (error) {
807
+ console.error(formatHttpError(error));
808
+ return 1;
809
+ }
810
+ }
@@ -41,6 +41,20 @@ export interface KnDeleteOptions {
41
41
  yes: boolean;
42
42
  }
43
43
  export declare function parseKnDeleteArgs(args: string[]): KnDeleteOptions;
44
+ export interface KnPushOptions {
45
+ directory: string;
46
+ branch: string;
47
+ businessDomain: string;
48
+ pretty: boolean;
49
+ }
50
+ export declare function parseKnPushArgs(args: string[]): KnPushOptions;
51
+ export interface KnPullOptions {
52
+ knId: string;
53
+ directory: string;
54
+ branch: string;
55
+ businessDomain: string;
56
+ }
57
+ export declare function parseKnPullArgs(args: string[]): KnPullOptions;
44
58
  export interface KnObjectTypeQueryOptions {
45
59
  knId: string;
46
60
  otId: string;
@@ -66,6 +80,8 @@ export declare function parseKnBuildArgs(args: string[]): {
66
80
  timeout: number;
67
81
  businessDomain: string;
68
82
  };
83
+ export declare function packDirectoryToTar(dirPath: string): Buffer;
84
+ export declare function extractTarToDirectory(tarBuffer: Buffer, dirPath: string): void;
69
85
  export declare function parseKnSearchArgs(args: string[]): {
70
86
  knId: string;
71
87
  query: string;