@kweaver-ai/kweaver-sdk 0.4.2 → 0.4.5

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.
@@ -1,5 +1,6 @@
1
1
  import { ensureValidToken, formatHttpError } from "../auth/oauth.js";
2
2
  import { fetchAgentInfo, sendChatRequest } from "../api/agent-chat.js";
3
+ import { resolveBusinessDomain } from "../config/store.js";
3
4
  function formatCliArg(value) {
4
5
  if (/^[A-Za-z0-9_./:=+-]+$/.test(value)) {
5
6
  return value;
@@ -42,7 +43,7 @@ export function parseChatArgs(args) {
42
43
  let conversationId;
43
44
  let stream;
44
45
  let verbose = false;
45
- let businessDomain = "bd_public";
46
+ let businessDomain = "";
46
47
  for (let i = 0; i < args.length; i += 1) {
47
48
  const arg = args[i];
48
49
  if (arg === "-m" || arg === "--message") {
@@ -104,6 +105,8 @@ export function parseChatArgs(args) {
104
105
  if (!agentId) {
105
106
  throw new Error("Missing agent_id. Usage: kweaver agent chat <agent_id> [-m \"message\"]");
106
107
  }
108
+ if (!businessDomain)
109
+ businessDomain = resolveBusinessDomain();
107
110
  return { agentId, version, message, conversationId, stream, verbose, businessDomain };
108
111
  }
109
112
  export async function runAgentChatCommand(args) {
@@ -1,8 +1,9 @@
1
- import { ensureValidToken, formatHttpError } from "../auth/oauth.js";
1
+ import { ensureValidToken, formatHttpError, with401RefreshRetry } from "../auth/oauth.js";
2
2
  import { runAgentChatCommand } from "./agent-chat.js";
3
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
+ import { resolveBusinessDomain } from "../config/store.js";
6
7
  function readStringField(value, ...keys) {
7
8
  for (const key of keys) {
8
9
  const candidate = value[key];
@@ -48,7 +49,7 @@ export function parseAgentListArgs(args) {
48
49
  let category_id = "";
49
50
  let custom_space_id = "";
50
51
  let is_to_square = 1;
51
- let businessDomain = "bd_public";
52
+ let businessDomain = "";
52
53
  let pretty = true;
53
54
  let verbose = false;
54
55
  for (let i = 0; i < args.length; i += 1) {
@@ -113,6 +114,8 @@ export function parseAgentListArgs(args) {
113
114
  }
114
115
  throw new Error(`Unsupported agent list argument: ${arg}`);
115
116
  }
117
+ if (!businessDomain)
118
+ businessDomain = resolveBusinessDomain();
116
119
  return {
117
120
  name,
118
121
  offset,
@@ -130,7 +133,7 @@ export function parseAgentSessionsArgs(args) {
130
133
  if (!agentId || agentId.startsWith("-")) {
131
134
  throw new Error("Missing agent_id");
132
135
  }
133
- let businessDomain = "bd_public";
136
+ let businessDomain = "";
134
137
  let limit;
135
138
  let pretty = true;
136
139
  for (let i = 1; i < args.length; i += 1) {
@@ -163,6 +166,8 @@ export function parseAgentSessionsArgs(args) {
163
166
  }
164
167
  throw new Error(`Unsupported agent sessions argument: ${arg}`);
165
168
  }
169
+ if (!businessDomain)
170
+ businessDomain = resolveBusinessDomain();
166
171
  return { agentId, businessDomain, limit, pretty };
167
172
  }
168
173
  export function parseAgentHistoryArgs(args) {
@@ -170,7 +175,7 @@ export function parseAgentHistoryArgs(args) {
170
175
  if (!conversationId || conversationId.startsWith("-")) {
171
176
  throw new Error("Missing conversation_id");
172
177
  }
173
- let businessDomain = "bd_public";
178
+ let businessDomain = "";
174
179
  let limit;
175
180
  let pretty = true;
176
181
  for (let i = 1; i < args.length; i += 1) {
@@ -203,9 +208,11 @@ export function parseAgentHistoryArgs(args) {
203
208
  }
204
209
  throw new Error(`Unsupported agent history argument: ${arg}`);
205
210
  }
211
+ if (!businessDomain)
212
+ businessDomain = resolveBusinessDomain();
206
213
  return { conversationId, businessDomain, limit, pretty };
207
214
  }
208
- export function runAgentCommand(args) {
215
+ export async function runAgentCommand(args) {
209
216
  const [subcommand, ...rest] = args;
210
217
  if (!subcommand || subcommand === "--help" || subcommand === "-h") {
211
218
  console.log(`kweaver agent
@@ -227,6 +234,32 @@ Subcommands:
227
234
  history <conversation_id> Show message history for a conversation`);
228
235
  return Promise.resolve(0);
229
236
  }
237
+ const dispatch = async () => {
238
+ if (subcommand === "chat")
239
+ return runAgentChatCommand(rest);
240
+ if (subcommand === "get")
241
+ return runAgentGetCommand(rest);
242
+ if (subcommand === "list")
243
+ return runAgentListCommand(rest);
244
+ if (subcommand === "sessions")
245
+ return runAgentSessionsCommand(rest);
246
+ if (subcommand === "history")
247
+ return runAgentHistoryCommand(rest);
248
+ if (subcommand === "get-by-key")
249
+ return runAgentGetByKeyCommand(rest);
250
+ if (subcommand === "create")
251
+ return runAgentCreateCommand(rest);
252
+ if (subcommand === "update")
253
+ return runAgentUpdateCommand(rest);
254
+ if (subcommand === "delete")
255
+ return runAgentDeleteCommand(rest);
256
+ if (subcommand === "publish")
257
+ return runAgentPublishCommand(rest);
258
+ if (subcommand === "unpublish")
259
+ return runAgentUnpublishCommand(rest);
260
+ return -1;
261
+ };
262
+ // Show subcommand-specific help inline (no retry needed)
230
263
  if (subcommand === "chat") {
231
264
  if (rest.length === 1 && (rest[0] === "--help" || rest[0] === "-h")) {
232
265
  console.log(`kweaver agent chat <agent_id> [-m "message"] [options]
@@ -264,9 +297,8 @@ Options:
264
297
  --verbose, -v Show full JSON response
265
298
  -bd, --biz-domain <value> Business domain (default: bd_public)
266
299
  --pretty Pretty-print JSON output (default)`);
267
- return Promise.resolve(0);
300
+ return 0;
268
301
  }
269
- return runAgentGetCommand(rest);
270
302
  }
271
303
  if (subcommand === "list") {
272
304
  if (rest.length === 1 && (rest[0] === "--help" || rest[0] === "-h")) {
@@ -284,9 +316,8 @@ Options:
284
316
  --verbose, -v Show full JSON response
285
317
  -bd, --biz-domain <value> Business domain (default: bd_public)
286
318
  --pretty Pretty-print JSON output (applies to both modes)`);
287
- return Promise.resolve(0);
319
+ return 0;
288
320
  }
289
- return runAgentListCommand(rest);
290
321
  }
291
322
  if (subcommand === "sessions") {
292
323
  if (rest.length === 1 && (rest[0] === "--help" || rest[0] === "-h")) {
@@ -298,9 +329,8 @@ Options:
298
329
  --limit <n> Max conversations to return
299
330
  -bd, --biz-domain <value> Business domain (default: bd_public)
300
331
  --pretty Pretty-print JSON output (default)`);
301
- return Promise.resolve(0);
332
+ return 0;
302
333
  }
303
- return runAgentSessionsCommand(rest);
304
334
  }
305
335
  if (subcommand === "history") {
306
336
  if (rest.length === 1 && (rest[0] === "--help" || rest[0] === "-h")) {
@@ -312,37 +342,30 @@ Options:
312
342
  --limit <n> Max messages to return
313
343
  -bd, --biz-domain <value> Business domain (default: bd_public)
314
344
  --pretty Pretty-print JSON output (default)`);
315
- return Promise.resolve(0);
345
+ return 0;
316
346
  }
317
- return runAgentHistoryCommand(rest);
318
- }
319
- if (subcommand === "get-by-key") {
320
- return runAgentGetByKeyCommand(rest);
321
347
  }
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);
348
+ try {
349
+ return await with401RefreshRetry(async () => {
350
+ const code = await dispatch();
351
+ if (code === -1) {
352
+ console.error(`Unknown agent subcommand: ${subcommand}`);
353
+ return 1;
354
+ }
355
+ return code;
356
+ });
333
357
  }
334
- if (subcommand === "unpublish") {
335
- return runAgentUnpublishCommand(rest);
358
+ catch (error) {
359
+ console.error(formatHttpError(error));
360
+ return 1;
336
361
  }
337
- console.error(`Unknown agent subcommand: ${subcommand}`);
338
- return Promise.resolve(1);
339
362
  }
340
363
  export function parseAgentGetArgs(args) {
341
364
  const agentId = args[0];
342
365
  if (!agentId || agentId.startsWith("-")) {
343
366
  throw new Error("Missing agent_id. Usage: kweaver agent get <agent_id> [options]");
344
367
  }
345
- let businessDomain = "bd_public";
368
+ let businessDomain = "";
346
369
  let pretty = true;
347
370
  let verbose = false;
348
371
  for (let i = 1; i < args.length; i += 1) {
@@ -368,6 +391,8 @@ export function parseAgentGetArgs(args) {
368
391
  }
369
392
  throw new Error(`Unsupported agent get argument: ${arg}`);
370
393
  }
394
+ if (!businessDomain)
395
+ businessDomain = resolveBusinessDomain();
371
396
  return { agentId, businessDomain, pretty, verbose };
372
397
  }
373
398
  function formatSimpleAgentGet(text, pretty) {
@@ -577,7 +602,7 @@ async function runAgentCreateCommand(args) {
577
602
  let systemPrompt = "";
578
603
  let llmId = "";
579
604
  let llmMaxTokens = 4096;
580
- let businessDomain = "bd_public";
605
+ let businessDomain = "";
581
606
  for (let i = 0; i < args.length; i += 1) {
582
607
  const arg = args[i];
583
608
  if (arg === "--help" || arg === "-h") {
@@ -631,6 +656,8 @@ Optional:
631
656
  continue;
632
657
  }
633
658
  }
659
+ if (!businessDomain)
660
+ businessDomain = resolveBusinessDomain();
634
661
  if (!name) {
635
662
  console.error("--name is required");
636
663
  return 1;
@@ -1,9 +1 @@
1
- import type { CallbackSession, ClientConfig, TokenConfig } from "../config/store.js";
2
- export declare function getClientProvisioningMessage(created: boolean): string;
3
- export declare function formatAuthStatusSummary(input: {
4
- client: ClientConfig;
5
- token: TokenConfig | null;
6
- callback: CallbackSession | null;
7
- isCurrent?: boolean;
8
- }): string[];
9
1
  export declare function runAuthCommand(args: string[]): Promise<number>;
@@ -1,38 +1,18 @@
1
- import { clearPlatformSession, deletePlatform, getConfigDir, getCurrentPlatform, getPlatformAlias, hasPlatform, listPlatforms, resolvePlatformIdentifier, setCurrentPlatform, setPlatformAlias, } from "../config/store.js";
2
- import { callLogoutEndpoint, formatHttpError, getStoredAuthSummary, login, normalizeBaseUrl, } from "../auth/oauth.js";
3
- export function getClientProvisioningMessage(created) {
4
- return created ? "Registered a new OAuth client." : "Reusing existing OAuth client.";
5
- }
6
- export function formatAuthStatusSummary(input) {
7
- const lines = [
8
- `Config directory: ${getConfigDir()}`,
9
- `Platform: ${input.client.baseUrl}`,
10
- `Current platform: ${input.isCurrent ? "yes" : "no"}`,
11
- `Client ID: ${input.client.clientId}`,
12
- `Redirect URI: ${input.client.redirectUri}`,
13
- `Token present: ${input.token ? "yes" : "no"}`,
14
- `Callback recorded: ${input.callback ? "yes" : "no"}`,
15
- ];
16
- if (input.client.product) {
17
- lines.push(`Product: ${input.client.product}`);
18
- }
19
- if (input.client.lang) {
20
- lines.push(`Lang: ${input.client.lang}`);
21
- }
22
- if (input.token?.expiresAt) {
23
- lines.push(`Token expires at: ${input.token.expiresAt}`);
24
- }
25
- if (input.callback?.receivedAt) {
26
- lines.push(`Last callback at: ${input.callback.receivedAt}`);
27
- }
28
- if (input.callback?.scope) {
29
- lines.push(`Last callback scope: ${input.callback.scope}`);
30
- }
31
- return lines;
32
- }
1
+ import { clearPlatformSession, deletePlatform, getConfigDir, getCurrentPlatform, getPlatformAlias, hasPlatform, listPlatforms, loadTokenConfig, resolvePlatformIdentifier, setCurrentPlatform, setPlatformAlias, } from "../config/store.js";
2
+ import { formatHttpError, normalizeBaseUrl, playwrightLogin, } from "../auth/oauth.js";
33
3
  export async function runAuthCommand(args) {
34
4
  const target = args[0];
35
5
  const rest = args.slice(1);
6
+ if (!target || target === "--help" || target === "-h") {
7
+ console.log(`kweaver auth login <url> Login to a platform (browser login)
8
+ kweaver auth <url> Login (shorthand)
9
+ kweaver auth status [url] Show current auth status
10
+ kweaver auth list List saved platforms
11
+ kweaver auth use <url> Switch active platform
12
+ kweaver auth logout [url] Logout (clear local token)
13
+ kweaver auth delete <url> Delete saved credentials`);
14
+ return 0;
15
+ }
36
16
  if (target === "login") {
37
17
  const url = rest[0];
38
18
  if (!url) {
@@ -44,47 +24,34 @@ export async function runAuthCommand(args) {
44
24
  if (target && target !== "status" && target !== "list" && target !== "use" && target !== "delete" && target !== "logout") {
45
25
  try {
46
26
  const normalizedTarget = normalizeBaseUrl(target);
47
- const port = Number(readOption(args, "--port") ?? "9010");
48
- const clientName = readOption(args, "--client-name") ?? "kweaver";
49
27
  const alias = readOption(args, "--alias");
50
- const host = readOption(args, "--host");
51
- const redirectUriOverride = readOption(args, "--redirect-uri");
52
- const forceRegister = args.includes("--force-register");
53
- const open = !args.includes("--no-open");
54
- const lang = readOption(args, "--lang") ?? "zh-cn";
55
- const product = readOption(args, "--product") ?? "adp";
56
- const xForwardedPrefix = readOption(args, "--x-forwarded-prefix") ?? "";
57
- const result = await login({
58
- baseUrl: normalizedTarget,
59
- port,
60
- clientName,
61
- open,
62
- forceRegister,
63
- host,
64
- redirectUriOverride,
65
- lang,
66
- product,
67
- xForwardedPrefix,
68
- });
28
+ const username = readOption(args, "--username") ?? readOption(args, "-u");
29
+ const password = readOption(args, "--password") ?? readOption(args, "-p");
30
+ if (username && password) {
31
+ console.log("Logging in (headless)...");
32
+ }
33
+ else {
34
+ console.log("Opening browser for login...");
35
+ }
36
+ const token = await playwrightLogin(normalizedTarget, username && password ? { username, password } : undefined);
69
37
  if (alias) {
70
38
  setPlatformAlias(normalizedTarget, alias);
71
39
  }
72
40
  console.log(`Config directory: ${getConfigDir()}`);
73
- console.log(getClientProvisioningMessage(result.created));
74
- console.log(`Client ID: ${result.client.clientId}`);
75
41
  if (alias) {
76
42
  console.log(`Alias: ${alias.toLowerCase()}`);
77
43
  }
78
44
  else {
79
- const savedAlias = getPlatformAlias(result.client.baseUrl);
45
+ const savedAlias = getPlatformAlias(normalizedTarget);
80
46
  if (savedAlias) {
81
47
  console.log(`Alias: ${savedAlias}`);
82
48
  }
83
49
  }
84
- console.log(`Authorization URL: ${result.authorizationUrl}`);
85
- console.log(`Callback received at: ${result.callback.receivedAt}`);
86
- console.log(`Current platform: ${result.client.baseUrl}`);
50
+ console.log(`Current platform: ${normalizedTarget}`);
87
51
  console.log(`Access token saved: yes`);
52
+ if (token.expiresAt) {
53
+ console.log(`Token expires at: ${token.expiresAt}`);
54
+ }
88
55
  return 0;
89
56
  }
90
57
  catch (error) {
@@ -95,18 +62,35 @@ export async function runAuthCommand(args) {
95
62
  if (target === "status") {
96
63
  const resolvedTarget = args[1] ? resolvePlatformIdentifier(args[1]) : undefined;
97
64
  const statusTarget = resolvedTarget && /^https?:\/\//.test(resolvedTarget) ? normalizeBaseUrl(resolvedTarget) : resolvedTarget ?? undefined;
98
- const { client, token, callback } = getStoredAuthSummary(statusTarget);
99
- if (!client) {
100
- console.error(statusTarget ? `No saved client config found for ${statusTarget}.` : "No saved client config found.");
65
+ const platform = statusTarget ?? getCurrentPlatform();
66
+ if (!platform) {
67
+ console.error("No active platform. Run `kweaver auth login <platform-url>` first.");
68
+ return 1;
69
+ }
70
+ const token = loadTokenConfig(platform);
71
+ if (!token) {
72
+ console.error(statusTarget ? `No saved token for ${statusTarget}.` : "No saved token found.");
101
73
  return 1;
102
74
  }
103
75
  const currentPlatform = getCurrentPlatform();
104
- for (const line of formatAuthStatusSummary({
105
- client,
106
- token,
107
- callback,
108
- isCurrent: currentPlatform === client.baseUrl,
109
- })) {
76
+ const lines = [
77
+ `Config directory: ${getConfigDir()}`,
78
+ `Platform: ${token.baseUrl}`,
79
+ `Current platform: ${token.baseUrl === currentPlatform ? "yes" : "no"}`,
80
+ `Token present: yes`,
81
+ ];
82
+ if (token.expiresAt) {
83
+ const expiry = new Date(token.expiresAt);
84
+ const remainingMs = expiry.getTime() - Date.now();
85
+ if (remainingMs > 0) {
86
+ const remainingMin = Math.ceil(remainingMs / 60_000);
87
+ lines.push(`Token status: active (expires in ${remainingMin} min)`);
88
+ }
89
+ else {
90
+ lines.push(`Token status: expired (run \`kweaver auth login ${token.baseUrl}\` again)`);
91
+ }
92
+ }
93
+ for (const line of lines) {
110
94
  console.log(line);
111
95
  }
112
96
  return 0;
@@ -134,7 +118,7 @@ export async function runAuthCommand(args) {
134
118
  return 1;
135
119
  }
136
120
  if (!hasPlatform(useTarget)) {
137
- console.error(`No saved client config found for ${useTarget}. Run \`kweaver auth ${useTarget}\` first.`);
121
+ console.error(`No saved token for ${useTarget}. Run \`kweaver auth login ${useTarget}\` first.`);
138
122
  return 1;
139
123
  }
140
124
  setCurrentPlatform(useTarget);
@@ -149,7 +133,7 @@ export async function runAuthCommand(args) {
149
133
  return 1;
150
134
  }
151
135
  if (!hasPlatform(deleteTarget)) {
152
- console.error(`No saved client config found for ${deleteTarget}.`);
136
+ console.error(`No saved token for ${deleteTarget}.`);
153
137
  return 1;
154
138
  }
155
139
  const wasCurrent = getCurrentPlatform() === deleteTarget;
@@ -166,25 +150,20 @@ export async function runAuthCommand(args) {
166
150
  const logoutTarget = resolvedTarget && /^https?:\/\//.test(resolvedTarget) ? normalizeBaseUrl(resolvedTarget) : resolvedTarget;
167
151
  if (!logoutTarget) {
168
152
  console.error("Usage: kweaver auth logout [platform-url|alias]");
169
- console.error("No current platform. Specify a platform to logout, e.g. kweaver auth logout <platform-url|alias>");
153
+ console.error("No current platform. Specify a platform to logout.");
170
154
  return 1;
171
155
  }
172
156
  if (!hasPlatform(logoutTarget)) {
173
- console.error(`No saved client config found for ${logoutTarget}.`);
157
+ console.error(`No saved token for ${logoutTarget}.`);
174
158
  return 1;
175
159
  }
176
- const { client, token } = getStoredAuthSummary(logoutTarget);
177
- if (client) {
178
- await callLogoutEndpoint(client, token);
179
- }
180
160
  clearPlatformSession(logoutTarget);
181
161
  console.log(`Logged out: ${logoutTarget}`);
182
- console.log(`Run \`kweaver auth ${logoutTarget}\` to sign in again (e.g. as a different user).`);
162
+ console.log(`Run \`kweaver auth login ${logoutTarget}\` to sign in again.`);
183
163
  return 0;
184
164
  }
185
- console.error("Usage: kweaver auth <platform-url>");
186
- console.error(" kweaver auth login <platform-url>");
187
- console.error(" kweaver auth <platform-url> [--alias <name>] [--no-open] [--host <host>] [--redirect-uri <uri>]");
165
+ console.error("Usage: kweaver auth login <platform-url>");
166
+ console.error(" kweaver auth <platform-url> [--alias <name>]");
188
167
  console.error(" kweaver auth status [platform-url|alias]");
189
168
  console.error(" kweaver auth list");
190
169
  console.error(" kweaver auth use <platform-url|alias>");