@kweaver-ai/kweaver-sdk 0.7.1 → 0.7.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.
@@ -37,7 +37,10 @@ Subcommands:
37
37
  delete <id> [-y] Delete a datasource
38
38
  tables <id> [--keyword X] List tables with columns
39
39
  connect <db_type> <host> <port> <database> --account X --password Y [--schema Z] [--name N]
40
+ [--reuse-existing|--force-new]
40
41
  Test connectivity, register datasource, and discover tables.
42
+ By default reuses an existing ds with the same (type, host, port, database, account)
43
+ instead of creating a duplicate. --force-new always creates a new entry.
41
44
  import-csv <ds-id> --files <glob_or_list> [--table-prefix X] [--batch-size N]
42
45
  Import CSV files into datasource tables via dataflow API.`);
43
46
  return 0;
@@ -206,6 +209,52 @@ async function runDsTablesCommand(args) {
206
209
  console.log(formatCallOutput(body, pretty));
207
210
  return 0;
208
211
  }
212
+ export function findExistingDatasource(listBody, sig) {
213
+ const parsed = JSON.parse(listBody);
214
+ const entries = Array.isArray(parsed) ? parsed : (parsed.entries ?? []);
215
+ const tupleMatch = entries.find((e) => e.id &&
216
+ e.type === sig.type &&
217
+ e.bin_data?.host === sig.host &&
218
+ Number(e.bin_data?.port) === Number(sig.port) &&
219
+ e.bin_data?.database_name === sig.database &&
220
+ e.bin_data?.account === sig.account);
221
+ if (tupleMatch) {
222
+ return {
223
+ id: String(tupleMatch.id),
224
+ name: String(tupleMatch.name ?? ""),
225
+ matchedByName: tupleMatch.name === sig.name,
226
+ matchedByTuple: true,
227
+ };
228
+ }
229
+ if (sig.name) {
230
+ const nameMatch = entries.find((e) => e.id && e.name === sig.name);
231
+ if (nameMatch) {
232
+ return {
233
+ id: String(nameMatch.id),
234
+ name: String(nameMatch.name),
235
+ matchedByName: true,
236
+ matchedByTuple: false,
237
+ };
238
+ }
239
+ }
240
+ return undefined;
241
+ }
242
+ export function findDatasourceIdByName(listBody, name) {
243
+ const parsed = JSON.parse(listBody);
244
+ const entries = Array.isArray(parsed) ? parsed : (parsed.entries ?? []);
245
+ const hit = entries.find((e) => e.id && e.name === name);
246
+ return hit?.id ? String(hit.id) : undefined;
247
+ }
248
+ function isDuplicateNameError(err) {
249
+ if (!err || typeof err !== "object")
250
+ return false;
251
+ // HttpError.message is just "HTTP 400 ..."; the description lives in body.
252
+ const status = "status" in err ? Number(err.status) : NaN;
253
+ const body = "body" in err ? String(err.body) : "";
254
+ if (status !== 400)
255
+ return false;
256
+ return /数据源名称已存在|datasource name.*exist|already exists/i.test(body);
257
+ }
209
258
  async function runDsConnectCommand(args) {
210
259
  let dbType = "";
211
260
  let host = "";
@@ -215,6 +264,7 @@ async function runDsConnectCommand(args) {
215
264
  let password = "";
216
265
  let schema;
217
266
  let name;
267
+ let forceNew = false;
218
268
  for (let i = 0; i < args.length; i += 1) {
219
269
  const arg = args[i];
220
270
  if (arg === "--account" && args[i + 1]) {
@@ -233,6 +283,14 @@ async function runDsConnectCommand(args) {
233
283
  name = args[++i];
234
284
  continue;
235
285
  }
286
+ if (arg === "--force-new") {
287
+ forceNew = true;
288
+ continue;
289
+ }
290
+ if (arg === "--reuse-existing") {
291
+ forceNew = false;
292
+ continue;
293
+ }
236
294
  if (!arg.startsWith("-")) {
237
295
  if (!dbType)
238
296
  dbType = arg;
@@ -245,7 +303,7 @@ async function runDsConnectCommand(args) {
245
303
  }
246
304
  }
247
305
  if (!dbType || !host || !database || !account || !password) {
248
- console.error("Usage: kweaver ds connect <db_type> <host> <port> <database> --account X --password Y [--schema Z] [--name N]");
306
+ console.error("Usage: kweaver ds connect <db_type> <host> <port> <database> --account X --password Y [--schema Z] [--name N] [--reuse-existing|--force-new]");
249
307
  return 1;
250
308
  }
251
309
  if (Number.isNaN(port) || port < 1) {
@@ -254,6 +312,28 @@ async function runDsConnectCommand(args) {
254
312
  }
255
313
  const token = await ensureValidToken();
256
314
  const base = { baseUrl: token.baseUrl, accessToken: token.accessToken };
315
+ const dsName = name ?? database;
316
+ // Pre-flight dedup: connection-tuple match is the silent-orphan vector.
317
+ // Backend already rejects duplicate names with 400, but won't notice
318
+ // tuple collisions, so we own that check.
319
+ if (!forceNew) {
320
+ const listBody = await listDatasources({ ...base });
321
+ const hit = findExistingDatasource(listBody, {
322
+ type: dbType,
323
+ host,
324
+ port,
325
+ database,
326
+ account,
327
+ name: dsName,
328
+ });
329
+ if (hit) {
330
+ const why = hit.matchedByTuple
331
+ ? "matched by (type,host,port,database,account)"
332
+ : "matched by --name";
333
+ console.error(`Reusing existing datasource ${hit.id} (${hit.name}); ${why}. Use --force-new to override.`);
334
+ return printDsConnectOutput(base, hit.id);
335
+ }
336
+ }
257
337
  console.error("Testing connectivity ...");
258
338
  await testDatasource({
259
339
  ...base,
@@ -265,27 +345,45 @@ async function runDsConnectCommand(args) {
265
345
  password,
266
346
  schema,
267
347
  });
268
- const dsName = name ?? database;
269
- const createBody = await createDatasource({
270
- ...base,
271
- name: dsName,
272
- type: dbType,
273
- host,
274
- port,
275
- database,
276
- account,
277
- password,
278
- schema,
279
- });
280
- const dsId = extractDatasourceId(createBody);
348
+ let dsId = "";
349
+ try {
350
+ const createBody = await createDatasource({
351
+ ...base,
352
+ name: dsName,
353
+ type: dbType,
354
+ host,
355
+ port,
356
+ database,
357
+ account,
358
+ password,
359
+ schema,
360
+ });
361
+ dsId = extractDatasourceId(createBody);
362
+ }
363
+ catch (err) {
364
+ // Backend checks name uniqueness but not tuple. If we raced another caller
365
+ // (or tuple match got disabled by --force-new and the name still collides),
366
+ // turn the raw 400 into a useful pointer to the existing id.
367
+ if (isDuplicateNameError(err)) {
368
+ // Backend rejected the name; look it up specifically (not by tuple —
369
+ // sibling ds sharing the same connection would mislead the pointer).
370
+ const listBody = await listDatasources({ ...base });
371
+ const existingId = findDatasourceIdByName(listBody, dsName);
372
+ if (existingId) {
373
+ console.error(`Datasource name '${dsName}' already exists as ${existingId}. Re-run without --force-new to reuse it, or pick a different --name.`);
374
+ return 1;
375
+ }
376
+ }
377
+ throw err;
378
+ }
281
379
  if (!dsId) {
282
380
  console.error("Failed to get datasource ID from create response");
283
381
  return 1;
284
382
  }
285
- const tablesBody = await listTablesWithColumns({
286
- ...base,
287
- id: dsId,
288
- });
383
+ return printDsConnectOutput(base, dsId);
384
+ }
385
+ async function printDsConnectOutput(base, dsId) {
386
+ const tablesBody = await listTablesWithColumns({ ...base, id: dsId });
289
387
  const tables = JSON.parse(tablesBody);
290
388
  const output = {
291
389
  datasource_id: dsId,
@@ -1,8 +1,9 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, resolve } from "node:path";
3
3
  import { ensureValidToken, formatHttpError, with401RefreshRetry } from "../auth/oauth.js";
4
4
  import { resolveBusinessDomain } from "../config/store.js";
5
- import { deleteSkill, downloadSkill, fetchSkillContent, fetchSkillFile, getSkill, getSkillContentIndex, installSkillArchive, listSkillMarket, listSkills, readSkillFile, registerSkillContent, registerSkillZip, updateSkillStatus, } from "../api/skills.js";
5
+ import { deleteSkill, downloadSkill, fetchSkillContent, fetchSkillFile, getSkill, getSkillContentIndex, installSkillArchive, listSkillMarket, listSkills, readSkillFile, registerSkillZip, updateSkillStatus, } from "../api/skills.js";
6
+ import { bundleSkillDirectoryToZip, bundleSkillFileToZip } from "../utils/skill-bundle.js";
6
7
  function printSkillHelp(subcommand) {
7
8
  if (subcommand === "list") {
8
9
  console.log(`kweaver skill list [--name kw] [--source src] [--status status] [--create-user user]
@@ -20,7 +21,15 @@ function printSkillHelp(subcommand) {
20
21
  }
21
22
  if (subcommand === "register") {
22
23
  console.log(`kweaver skill register (--content-file <path> | --zip-file <path>)
23
- [--source src] [--extend-info json] [-bd value] [--pretty|--compact]`);
24
+ [--source src] [--extend-info json] [-bd value] [--pretty|--compact]
25
+
26
+ --content-file accepts either:
27
+ - a single file named SKILL.md (auto-bundled into a 1-file zip)
28
+ - a skill directory containing SKILL.md (bundled into a zip)
29
+ Both paths upload as multipart zip; the backend's file_type=content
30
+ registration is unreliable (publish-then-read returns 404) so the CLI
31
+ always goes through zip.
32
+ --zip-file accepts a pre-built .zip with SKILL.md at the archive root.`);
24
33
  return;
25
34
  }
26
35
  if (subcommand === "set-status" || subcommand === "status") {
@@ -54,6 +63,7 @@ Subcommands:
54
63
  market [--name kw] [--source src] [--page N] [--page-size N] [-bd value]
55
64
  get <skill-id> [-bd value]
56
65
  register --content-file <path> | --zip-file <path> [--source src] [--extend-info json]
66
+ (--content-file accepts a file named SKILL.md or a directory; both auto-zip)
57
67
  set-status <skill-id> <unpublish|published|offline> [-bd value]
58
68
  delete <skill-id> [-y] [-bd value]
59
69
  content <skill-id> [--raw] [--output file] [-bd value]
@@ -394,13 +404,23 @@ export async function runSkillCommand(args) {
394
404
  if (subcommand === "register") {
395
405
  const opts = parseSkillRegisterArgs(rest);
396
406
  if (opts.contentFile) {
397
- const content = readFileSync(resolve(opts.contentFile), "utf8");
398
- const result = await registerSkillContent({
407
+ // Always bundle into zip — the backend's file_type=content path
408
+ // doesn't write skill_file_index, so SKILL.md is unreachable
409
+ // after publish via /skills/:id/content. Going through zip
410
+ // (single SKILL.md or full directory) is the only path that
411
+ // produces a readable skill end-to-end.
412
+ const abs = resolve(opts.contentFile);
413
+ const stat = statSync(abs);
414
+ const bytes = stat.isDirectory()
415
+ ? await bundleSkillDirectoryToZip(abs)
416
+ : await bundleSkillFileToZip(abs);
417
+ const result = await registerSkillZip({
399
418
  ...token,
400
419
  businessDomain: opts.businessDomain,
401
- content,
402
420
  source: opts.source,
403
421
  extendInfo: opts.extendInfo,
422
+ filename: `${basename(abs).replace(/\.zip$/i, "")}.zip`,
423
+ bytes,
404
424
  });
405
425
  console.log(format(result, opts.pretty));
406
426
  return 0;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Stateless token mode: user passed --token on the CLI for this invocation.
3
+ *
4
+ * In stateless mode the CLI must not mutate ~/.kweaver/ — we error out from
5
+ * any command that would write tokens, sessions, or per-platform config.
6
+ *
7
+ * KWEAVER_TOKEN env (without --token flag) is NOT considered stateless: the
8
+ * env-var path predates this feature and keeps its existing semantics for
9
+ * backward compatibility. The cli.ts argv parser sets KWEAVER_TOKEN_SOURCE=flag
10
+ * only when --token was passed explicitly.
11
+ */
12
+ export declare function isStatelessTokenMode(): boolean;
13
+ export declare function assertNotStatelessForWrite(commandName: string): void;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Stateless token mode: user passed --token on the CLI for this invocation.
3
+ *
4
+ * In stateless mode the CLI must not mutate ~/.kweaver/ — we error out from
5
+ * any command that would write tokens, sessions, or per-platform config.
6
+ *
7
+ * KWEAVER_TOKEN env (without --token flag) is NOT considered stateless: the
8
+ * env-var path predates this feature and keeps its existing semantics for
9
+ * backward compatibility. The cli.ts argv parser sets KWEAVER_TOKEN_SOURCE=flag
10
+ * only when --token was passed explicitly.
11
+ */
12
+ export function isStatelessTokenMode() {
13
+ return process.env.KWEAVER_TOKEN_SOURCE === "flag";
14
+ }
15
+ export function assertNotStatelessForWrite(commandName) {
16
+ if (isStatelessTokenMode()) {
17
+ throw new Error(`Cannot run \`${commandName}\` with --token. The --token flag is for stateless invocations and ` +
18
+ `must not mutate ~/.kweaver/. Drop --token, or use \`kweaver auth login\` to obtain a saved session.`);
19
+ }
20
+ }
@@ -0,0 +1,5 @@
1
+ export declare class SkillBundleError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ export declare function bundleSkillDirectoryToZip(rootDir: string): Promise<Uint8Array>;
5
+ export declare function bundleSkillFileToZip(filePath: string): Promise<Uint8Array>;
@@ -0,0 +1,74 @@
1
+ import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { basename, join, posix, relative, sep } from "node:path";
3
+ import JSZip from "jszip";
4
+ const SKILL_MD = "SKILL.md";
5
+ export class SkillBundleError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "SkillBundleError";
9
+ }
10
+ }
11
+ function walk(rootDir) {
12
+ const out = [];
13
+ const stack = [rootDir];
14
+ while (stack.length > 0) {
15
+ const dir = stack.pop();
16
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
17
+ const abs = join(dir, entry.name);
18
+ if (entry.isDirectory()) {
19
+ stack.push(abs);
20
+ }
21
+ else if (entry.isFile()) {
22
+ out.push(abs);
23
+ }
24
+ }
25
+ }
26
+ return out;
27
+ }
28
+ function toPosixRelPath(rootDir, abs) {
29
+ const rel = relative(rootDir, abs);
30
+ return sep === posix.sep ? rel : rel.split(sep).join(posix.sep);
31
+ }
32
+ export async function bundleSkillDirectoryToZip(rootDir) {
33
+ const stat = statSync(rootDir);
34
+ if (!stat.isDirectory()) {
35
+ throw new SkillBundleError(`not a directory: ${rootDir}`);
36
+ }
37
+ const files = walk(rootDir);
38
+ if (files.length === 0) {
39
+ throw new SkillBundleError(`empty skill directory: ${rootDir}`);
40
+ }
41
+ const hasSkillMd = files.some((f) => toPosixRelPath(rootDir, f).toLowerCase() === SKILL_MD.toLowerCase());
42
+ if (!hasSkillMd) {
43
+ throw new SkillBundleError(`${SKILL_MD} not found at the root of ${rootDir} (server requires it)`);
44
+ }
45
+ const zip = new JSZip();
46
+ for (const abs of files) {
47
+ const relPath = toPosixRelPath(rootDir, abs);
48
+ zip.file(relPath, readFileSync(abs));
49
+ }
50
+ const buf = await zip.generateAsync({
51
+ type: "uint8array",
52
+ compression: "DEFLATE",
53
+ compressionOptions: { level: 6 },
54
+ });
55
+ return buf;
56
+ }
57
+ export async function bundleSkillFileToZip(filePath) {
58
+ const stat = statSync(filePath);
59
+ if (!stat.isFile()) {
60
+ throw new SkillBundleError(`not a file: ${filePath}`);
61
+ }
62
+ const fileName = basename(filePath);
63
+ if (fileName.toLowerCase() !== SKILL_MD.toLowerCase()) {
64
+ throw new SkillBundleError(`--content-file expects a file named ${SKILL_MD} (got ${fileName}). ` +
65
+ `Pass a directory containing ${SKILL_MD} for skills with assets.`);
66
+ }
67
+ const zip = new JSZip();
68
+ zip.file(SKILL_MD, readFileSync(filePath));
69
+ return zip.generateAsync({
70
+ type: "uint8array",
71
+ compression: "DEFLATE",
72
+ compressionOptions: { level: 6 },
73
+ });
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kweaver-ai/kweaver-sdk",
3
- "version": "0.7.1",
3
+ "version": "0.7.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",
@@ -63,6 +63,7 @@
63
63
  "ink": "^6.8.0",
64
64
  "ink-spinner": "^5.0.0",
65
65
  "ink-text-input": "^6.0.0",
66
+ "jszip": "^3.10.1",
66
67
  "marked": "^11.2.0",
67
68
  "react": "^19.2.4",
68
69
  "string-width": "^8.2.0",