@kweaver-ai/kweaver-sdk 0.6.9 → 0.7.1

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,18 +1,29 @@
1
- import { access } from "node:fs/promises";
1
+ import { access, readFile } from "node:fs/promises";
2
2
  import { ensureValidToken, formatHttpError, with401RefreshRetry } from "../auth/oauth.js";
3
- import { listTools, setToolStatuses, uploadTool } from "../api/toolboxes.js";
3
+ import { debugTool, executeTool, listTools, setToolStatuses, uploadTool } from "../api/toolboxes.js";
4
4
  import { formatCallOutput } from "./call.js";
5
5
  import { resolveBusinessDomain } from "../config/store.js";
6
6
  const HELP = `kweaver tool
7
7
 
8
8
  Subcommands:
9
9
  upload --toolbox <box-id> <openapi-spec-path> [--metadata-type openapi]
10
- Upload an OpenAPI spec file as a tool
11
- list --toolbox <box-id> List tools in a toolbox
12
- enable --toolbox <box-id> <tool-id>... Enable one or more tools
13
- disable --toolbox <box-id> <tool-id>... Disable one or more tools
10
+ Upload an OpenAPI spec file as a tool
11
+ list --toolbox <box-id> List tools in a toolbox
12
+ enable --toolbox <box-id> <tool-id>... Enable one or more tools
13
+ disable --toolbox <box-id> <tool-id>... Disable one or more tools
14
+ execute --toolbox <box-id> <tool-id> [--body '<json>'|--body-file <path>]
15
+ Invoke a published+enabled tool
16
+ debug --toolbox <box-id> <tool-id> [--body '<json>'|--body-file <path>]
17
+ Invoke a tool (works on draft/disabled too)
14
18
 
15
- Options:
19
+ Options for execute/debug:
20
+ --header '<json>' Headers map forwarded to the downstream tool
21
+ (Authorization is auto-injected from current session
22
+ when --header omits it; pass {} to send none)
23
+ --query '<json>' Query params map forwarded to the downstream tool
24
+ --timeout <seconds> Per-call timeout (backend default applies when omitted)
25
+
26
+ Common options:
16
27
  -bd, --biz-domain <s> Business domain (default: bd_public)
17
28
  --pretty Pretty-print JSON (default)
18
29
  --compact Single-line JSON (pipeline-friendly)`;
@@ -31,6 +42,10 @@ export async function runToolCommand(args) {
31
42
  return runToolStatus(rest, "enabled");
32
43
  if (subcommand === "disable")
33
44
  return runToolStatus(rest, "disabled");
45
+ if (subcommand === "execute")
46
+ return runToolInvoke(rest, "execute");
47
+ if (subcommand === "debug")
48
+ return runToolInvoke(rest, "debug");
34
49
  return Promise.resolve(-1);
35
50
  };
36
51
  try {
@@ -206,3 +221,158 @@ async function runToolStatus(args, status) {
206
221
  console.error(`${status === "enabled" ? "Enabled" : "Disabled"} ${opts.toolIds.length} tool(s) in toolbox ${opts.boxId}`);
207
222
  return 0;
208
223
  }
224
+ function parseJsonOption(name, raw) {
225
+ let value;
226
+ try {
227
+ value = JSON.parse(raw);
228
+ }
229
+ catch (e) {
230
+ throw new Error(`${name} must be valid JSON: ${e.message}`);
231
+ }
232
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
233
+ throw new Error(`${name} must be a JSON object`);
234
+ }
235
+ return value;
236
+ }
237
+ export function parseToolInvokeArgs(args) {
238
+ let boxId = "";
239
+ let toolId = "";
240
+ let businessDomain = "";
241
+ let pretty = true;
242
+ let header;
243
+ let query;
244
+ let body;
245
+ let bodyProvided = false;
246
+ let bodyFile;
247
+ let timeout;
248
+ for (let i = 0; i < args.length; i += 1) {
249
+ const a = args[i];
250
+ if (a === "--toolbox" && args[i + 1]) {
251
+ boxId = args[++i];
252
+ continue;
253
+ }
254
+ if (a === "--header" && args[i + 1]) {
255
+ header = parseJsonOption("--header", args[++i]);
256
+ continue;
257
+ }
258
+ if (a === "--query" && args[i + 1]) {
259
+ query = parseJsonOption("--query", args[++i]);
260
+ continue;
261
+ }
262
+ if (a === "--body" && args[i + 1]) {
263
+ const raw = args[++i];
264
+ try {
265
+ body = JSON.parse(raw);
266
+ }
267
+ catch (e) {
268
+ throw new Error(`--body must be valid JSON: ${e.message}`);
269
+ }
270
+ bodyProvided = true;
271
+ continue;
272
+ }
273
+ if (a === "--body-file" && args[i + 1]) {
274
+ bodyFile = args[++i];
275
+ bodyProvided = true;
276
+ continue;
277
+ }
278
+ if (a === "--timeout" && args[i + 1]) {
279
+ const t = Number(args[++i]);
280
+ if (!Number.isFinite(t) || t <= 0)
281
+ throw new Error("--timeout must be a positive number");
282
+ timeout = t;
283
+ continue;
284
+ }
285
+ if ((a === "-bd" || a === "--biz-domain") && args[i + 1]) {
286
+ businessDomain = args[++i];
287
+ continue;
288
+ }
289
+ if (a === "--pretty") {
290
+ pretty = true;
291
+ continue;
292
+ }
293
+ if (a === "--compact") {
294
+ pretty = false;
295
+ continue;
296
+ }
297
+ if (!a.startsWith("-") && !toolId) {
298
+ toolId = a;
299
+ continue;
300
+ }
301
+ }
302
+ if (!boxId)
303
+ throw new Error("Missing required flag: --toolbox");
304
+ if (!toolId)
305
+ throw new Error("Missing required positional argument: <tool-id>");
306
+ if (bodyFile && body !== undefined)
307
+ throw new Error("--body and --body-file are mutually exclusive");
308
+ if (!businessDomain)
309
+ businessDomain = resolveBusinessDomain();
310
+ return {
311
+ boxId,
312
+ toolId,
313
+ header,
314
+ query,
315
+ body: bodyProvided ? body : undefined,
316
+ bodyFile,
317
+ timeout,
318
+ businessDomain,
319
+ pretty,
320
+ };
321
+ }
322
+ async function loadBodyFile(path) {
323
+ let raw;
324
+ try {
325
+ raw = await readFile(path, "utf8");
326
+ }
327
+ catch (e) {
328
+ throw new Error(`Cannot read --body-file ${path}: ${e.message}`);
329
+ }
330
+ try {
331
+ return JSON.parse(raw);
332
+ }
333
+ catch (e) {
334
+ throw new Error(`--body-file ${path} is not valid JSON: ${e.message}`);
335
+ }
336
+ }
337
+ async function runToolInvoke(args, action) {
338
+ let opts;
339
+ try {
340
+ opts = parseToolInvokeArgs(args);
341
+ }
342
+ catch (e) {
343
+ console.error(e instanceof Error ? e.message : String(e));
344
+ return 1;
345
+ }
346
+ let body = opts.body;
347
+ if (opts.bodyFile !== undefined) {
348
+ try {
349
+ body = await loadBodyFile(opts.bodyFile);
350
+ }
351
+ catch (e) {
352
+ console.error(e instanceof Error ? e.message : String(e));
353
+ return 1;
354
+ }
355
+ }
356
+ const token = await ensureValidToken();
357
+ // Auto-inject Authorization unless caller already provided one — most tools
358
+ // declare an `Authorization` header parameter and would otherwise be called
359
+ // anonymously, which the downstream tool answers with 401 token expired.
360
+ const header = { ...(opts.header ?? {}) };
361
+ const hasAuth = Object.keys(header).some((k) => k.toLowerCase() === "authorization");
362
+ if (!hasAuth)
363
+ header.Authorization = `Bearer ${token.accessToken}`;
364
+ const fn = action === "execute" ? executeTool : debugTool;
365
+ const responseBody = await fn({
366
+ baseUrl: token.baseUrl,
367
+ accessToken: token.accessToken,
368
+ businessDomain: opts.businessDomain,
369
+ boxId: opts.boxId,
370
+ toolId: opts.toolId,
371
+ header,
372
+ query: opts.query,
373
+ body,
374
+ timeout: opts.timeout,
375
+ });
376
+ console.log(formatCallOutput(responseBody, opts.pretty));
377
+ return 0;
378
+ }
@@ -1,3 +1,4 @@
1
+ import { type ImpexType } from "../api/toolboxes.js";
1
2
  export declare function runToolboxCommand(args: string[]): Promise<number>;
2
3
  export interface ToolboxCreateOptions {
3
4
  name: string;
@@ -12,3 +13,17 @@ export interface ToolboxSetStatusOptions {
12
13
  businessDomain: string;
13
14
  }
14
15
  export declare function parseToolboxSetStatusArgs(args: string[]): ToolboxSetStatusOptions;
16
+ export interface ToolboxExportOptions {
17
+ boxId: string;
18
+ output: string;
19
+ type: ImpexType;
20
+ businessDomain: string;
21
+ }
22
+ export declare function parseToolboxExportArgs(args: string[]): ToolboxExportOptions;
23
+ export interface ToolboxImportOptions {
24
+ filePath: string;
25
+ type: ImpexType;
26
+ businessDomain: string;
27
+ pretty: boolean;
28
+ }
29
+ export declare function parseToolboxImportArgs(args: string[]): ToolboxImportOptions;
@@ -1,8 +1,10 @@
1
+ import { writeFile } from "node:fs/promises";
1
2
  import { createInterface } from "node:readline";
2
3
  import { ensureValidToken, formatHttpError, with401RefreshRetry } from "../auth/oauth.js";
3
- import { createToolbox, deleteToolbox, listToolboxes, setToolboxStatus } from "../api/toolboxes.js";
4
+ import { createToolbox, deleteToolbox, exportConfig, importConfig, listToolboxes, setToolboxStatus, } from "../api/toolboxes.js";
4
5
  import { formatCallOutput } from "./call.js";
5
6
  import { resolveBusinessDomain } from "../config/store.js";
7
+ const VALID_IMPEX_TYPES = new Set(["toolbox", "mcp", "operator"]);
6
8
  const HELP = `kweaver toolbox
7
9
 
8
10
  Subcommands:
@@ -11,6 +13,8 @@ Subcommands:
11
13
  publish <box-id> Publish a toolbox (status=published)
12
14
  unpublish <box-id> Unpublish (status=draft)
13
15
  delete <box-id> [-y|--yes] Delete a toolbox
16
+ export <box-id> [-o <file>|-] [--type toolbox|mcp|operator] Export toolbox config (.adp JSON)
17
+ import <file> [--type toolbox|mcp|operator] Import a previously exported config
14
18
 
15
19
  Options:
16
20
  -bd, --biz-domain <s> Business domain (default: bd_public)
@@ -33,6 +37,10 @@ export async function runToolboxCommand(args) {
33
37
  return runToolboxSetStatus(rest, "draft");
34
38
  if (subcommand === "delete")
35
39
  return runToolboxDelete(rest);
40
+ if (subcommand === "export")
41
+ return runToolboxExport(rest);
42
+ if (subcommand === "import")
43
+ return runToolboxImport(rest);
36
44
  return Promise.resolve(-1);
37
45
  };
38
46
  try {
@@ -254,3 +262,125 @@ async function runToolboxDelete(args) {
254
262
  console.error(`Deleted toolbox ${boxId}`);
255
263
  return 0;
256
264
  }
265
+ export function parseToolboxExportArgs(args) {
266
+ let boxId = "";
267
+ let output = "";
268
+ let type = "toolbox";
269
+ let businessDomain = "";
270
+ for (let i = 0; i < args.length; i += 1) {
271
+ const a = args[i];
272
+ if ((a === "-o" || a === "--output") && args[i + 1] !== undefined) {
273
+ output = args[++i];
274
+ continue;
275
+ }
276
+ if (a === "--type" && args[i + 1]) {
277
+ const v = args[++i];
278
+ if (!VALID_IMPEX_TYPES.has(v)) {
279
+ throw new Error(`--type must be one of: ${[...VALID_IMPEX_TYPES].join(", ")}`);
280
+ }
281
+ type = v;
282
+ continue;
283
+ }
284
+ if ((a === "-bd" || a === "--biz-domain") && args[i + 1]) {
285
+ businessDomain = args[++i];
286
+ continue;
287
+ }
288
+ if (!a.startsWith("-")) {
289
+ boxId = a;
290
+ continue;
291
+ }
292
+ }
293
+ if (!boxId)
294
+ throw new Error("Missing required argument: <box-id>");
295
+ if (!businessDomain)
296
+ businessDomain = resolveBusinessDomain();
297
+ return { boxId, output, type, businessDomain };
298
+ }
299
+ async function runToolboxExport(args) {
300
+ let opts;
301
+ try {
302
+ opts = parseToolboxExportArgs(args);
303
+ }
304
+ catch (e) {
305
+ console.error(e instanceof Error ? e.message : String(e));
306
+ console.error("Usage: kweaver toolbox export <box-id> [-o <file>|-] [--type toolbox|mcp|operator]");
307
+ return 1;
308
+ }
309
+ const token = await ensureValidToken();
310
+ const buf = await exportConfig({
311
+ baseUrl: token.baseUrl,
312
+ accessToken: token.accessToken,
313
+ businessDomain: opts.businessDomain,
314
+ id: opts.boxId,
315
+ type: opts.type,
316
+ });
317
+ if (opts.output === "-") {
318
+ process.stdout.write(buf);
319
+ if (buf.length === 0 || buf[buf.length - 1] !== 0x0a)
320
+ process.stdout.write("\n");
321
+ return 0;
322
+ }
323
+ const target = opts.output || `${opts.type}_${opts.boxId}.adp`;
324
+ await writeFile(target, buf);
325
+ console.error(`Exported ${opts.type} ${opts.boxId} → ${target} (${buf.byteLength} bytes)`);
326
+ return 0;
327
+ }
328
+ export function parseToolboxImportArgs(args) {
329
+ let filePath = "";
330
+ let type = "toolbox";
331
+ let businessDomain = "";
332
+ let pretty = true;
333
+ for (let i = 0; i < args.length; i += 1) {
334
+ const a = args[i];
335
+ if (a === "--type" && args[i + 1]) {
336
+ const v = args[++i];
337
+ if (!VALID_IMPEX_TYPES.has(v)) {
338
+ throw new Error(`--type must be one of: ${[...VALID_IMPEX_TYPES].join(", ")}`);
339
+ }
340
+ type = v;
341
+ continue;
342
+ }
343
+ if ((a === "-bd" || a === "--biz-domain") && args[i + 1]) {
344
+ businessDomain = args[++i];
345
+ continue;
346
+ }
347
+ if (a === "--pretty") {
348
+ pretty = true;
349
+ continue;
350
+ }
351
+ if (a === "--compact") {
352
+ pretty = false;
353
+ continue;
354
+ }
355
+ if (!a.startsWith("-")) {
356
+ filePath = a;
357
+ continue;
358
+ }
359
+ }
360
+ if (!filePath)
361
+ throw new Error("Missing required argument: <file>");
362
+ if (!businessDomain)
363
+ businessDomain = resolveBusinessDomain();
364
+ return { filePath, type, businessDomain, pretty };
365
+ }
366
+ async function runToolboxImport(args) {
367
+ let opts;
368
+ try {
369
+ opts = parseToolboxImportArgs(args);
370
+ }
371
+ catch (e) {
372
+ console.error(e instanceof Error ? e.message : String(e));
373
+ console.error("Usage: kweaver toolbox import <file> [--type toolbox|mcp|operator]");
374
+ return 1;
375
+ }
376
+ const token = await ensureValidToken();
377
+ const body = await importConfig({
378
+ baseUrl: token.baseUrl,
379
+ accessToken: token.accessToken,
380
+ businessDomain: opts.businessDomain,
381
+ filePath: opts.filePath,
382
+ type: opts.type,
383
+ });
384
+ console.log(formatCallOutput(body, opts.pretty));
385
+ return 0;
386
+ }
@@ -783,8 +783,13 @@ export async function autoSelectBusinessDomain(baseUrl, accessToken, options) {
783
783
  return selected;
784
784
  }
785
785
  catch (error) {
786
- const message = error instanceof Error ? error.message : String(error);
787
- console.warn(`Could not fetch business domains: ${message}. Using bd_public.`);
786
+ // Endpoint may be unavailable on this deployment or for this account
787
+ // type fall back silently. Set KWEAVER_DEBUG=1 to surface the
788
+ // underlying error during diagnostics.
789
+ if (process.env.KWEAVER_DEBUG) {
790
+ const message = error instanceof Error ? error.message : String(error);
791
+ console.warn(`Business domain list unavailable (${message}); defaulting to bd_public.`);
792
+ }
788
793
  return "bd_public";
789
794
  }
790
795
  }
package/dist/index.d.ts CHANGED
@@ -35,10 +35,10 @@ export type { ListAgentsOptions, GetAgentOptions, GetAgentByKeyOptions, CreateAg
35
35
  export { listAgents, getAgent, getAgentByKey, createAgent, updateAgent, deleteAgent, publishAgent, unpublishAgent, } from "./api/agent-list.js";
36
36
  export type { ListConversationsOptions, ListMessagesOptions } from "./api/conversations.js";
37
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";
38
+ export type { SemanticSearchOptions, KnSearchHttpOptions } from "./api/semantic-search.js";
39
+ export { semanticSearch, knSearchHttp } from "./api/semantic-search.js";
40
+ export type { ContextLoaderCallOptions, SearchSchemaArgs, SearchSchemaScope, SearchSchemaResult, ConditionSpec, QueryObjectInstanceArgs, RelationTypePath, QueryInstanceSubgraphArgs, GetLogicPropertiesValuesArgs, GetActionInfoArgs, FindSkillsArgs, FindSkillsResult, MissingInputParamsError, } from "./api/context-loader.js";
41
+ export { callTool, searchSchema, queryObjectInstance, queryInstanceSubgraph, getLogicPropertiesValues, getActionInfo, findSkills, formatMissingInputParamsHint, validateCondition, validateInstanceIdentity, validateInstanceIdentities, } from "./api/context-loader.js";
42
42
  export type { ConfigureOptions } from "./kweaver.js";
43
43
  export { configure, search, agents, chat, bkns, weaver, getClient } from "./kweaver.js";
44
44
  export type { KWeaverClientOptions, ClientContext } from "./client.js";
@@ -50,6 +50,8 @@ export { BknResource } from "./resources/bkn.js";
50
50
  export { ConversationsResource } from "./resources/conversations.js";
51
51
  export { ContextLoaderResource } from "./resources/context-loader.js";
52
52
  export { SkillsResource } from "./resources/skills.js";
53
+ export { ToolboxesResource } from "./resources/toolboxes.js";
54
+ export type { InvokeToolArgs } from "./resources/toolboxes.js";
53
55
  export type { SkillStatus, SkillSummary, SkillInfo, SkillFileSummary, SkillContentIndex, SkillFileReadResult, RegisterSkillResult, DeleteSkillResult, UpdateSkillStatusResult, SkillListResult, ListSkillsOptions, ListSkillMarketOptions, GetSkillOptions, RegisterSkillContentOptions, RegisterSkillZipOptions, UpdateSkillStatusOptions, ReadSkillFileOptions, DownloadSkillOptions, DownloadedSkillArchive, } from "./api/skills.js";
54
56
  export { listSkills, listSkillMarket, getSkill, deleteSkill, updateSkillStatus, registerSkillContent, registerSkillZip, getSkillContentIndex, fetchSkillContent, readSkillFile, fetchSkillFile, downloadSkill, installSkillArchive, } from "./api/skills.js";
55
57
  export type { ViewField, DataView, CreateDataViewOptions, GetDataViewOptions, ListDataViewsOptions, DeleteDataViewOptions, FindDataViewOptions, QueryDataViewOptions, DataViewQueryResult, } from "./api/dataviews.js";
@@ -57,6 +59,8 @@ export { parseDataView, createDataView, getDataView, listDataViews, deleteDataVi
57
59
  export { DataViewsResource } from "./resources/dataviews.js";
58
60
  export type { BusinessDomain, ListBusinessDomainsOptions } from "./api/business-domains.js";
59
61
  export { listBusinessDomains } from "./api/business-domains.js";
62
+ export type { CreateToolboxOptions, DeleteToolboxOptions, SetToolboxStatusOptions, UploadToolOptions, SetToolStatusesOptions, ListToolboxesOptions, ListToolsOptions, InvokeToolOptions, } from "./api/toolboxes.js";
63
+ export { createToolbox, deleteToolbox, setToolboxStatus, uploadTool, setToolStatuses, listToolboxes, listTools, executeTool, debugTool, } from "./api/toolboxes.js";
60
64
  export { HttpError, NetworkRequestError, fetchTextOrThrow } from "./utils/http.js";
61
65
  export type { TokenConfig, ContextLoaderEntry, ContextLoaderConfig, } from "./config/store.js";
62
66
  export type { UserProfile } from "./config/store.js";
package/dist/index.js CHANGED
@@ -30,8 +30,8 @@ export { objectTypeQuery, objectTypeProperties, subgraph, actionTypeQuery, actio
30
30
  export { sendChatRequest, sendChatRequestStream, fetchAgentInfo, buildChatUrl, buildAgentInfoUrl, extractText, } from "./api/agent-chat.js";
31
31
  export { listAgents, getAgent, getAgentByKey, createAgent, updateAgent, deleteAgent, publishAgent, unpublishAgent, } from "./api/agent-list.js";
32
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";
33
+ export { semanticSearch, knSearchHttp } from "./api/semantic-search.js";
34
+ export { callTool, searchSchema, queryObjectInstance, queryInstanceSubgraph, getLogicPropertiesValues, getActionInfo, findSkills, formatMissingInputParamsHint, validateCondition, validateInstanceIdentity, validateInstanceIdentities, } from "./api/context-loader.js";
35
35
  export { configure, search, agents, chat, bkns, weaver, getClient } from "./kweaver.js";
36
36
  export { KWeaverClient } from "./client.js";
37
37
  export { KnowledgeNetworksResource } from "./resources/knowledge-networks.js";
@@ -40,10 +40,12 @@ export { BknResource } from "./resources/bkn.js";
40
40
  export { ConversationsResource } from "./resources/conversations.js";
41
41
  export { ContextLoaderResource } from "./resources/context-loader.js";
42
42
  export { SkillsResource } from "./resources/skills.js";
43
+ export { ToolboxesResource } from "./resources/toolboxes.js";
43
44
  export { listSkills, listSkillMarket, getSkill, deleteSkill, updateSkillStatus, registerSkillContent, registerSkillZip, getSkillContentIndex, fetchSkillContent, readSkillFile, fetchSkillFile, downloadSkill, installSkillArchive, } from "./api/skills.js";
44
45
  export { parseDataView, createDataView, getDataView, listDataViews, deleteDataView, findDataView, queryDataView, } from "./api/dataviews.js";
45
46
  export { DataViewsResource } from "./resources/dataviews.js";
46
47
  export { listBusinessDomains } from "./api/business-domains.js";
48
+ export { createToolbox, deleteToolbox, setToolboxStatus, uploadTool, setToolStatuses, listToolboxes, listTools, executeTool, debugTool, } from "./api/toolboxes.js";
47
49
  // ── HTTP utilities ────────────────────────────────────────────────────────────
48
50
  export { HttpError, NetworkRequestError, fetchTextOrThrow } from "./utils/http.js";
49
51
  export { NO_AUTH_TOKEN, isNoAuth, saveNoAuthPlatform, autoSelectBusinessDomain, getConfigDir, getCurrentPlatform, getActiveUser, setActiveUser, listUsers, listUserProfiles, resolveUserId, extractUserId, } from "./config/store.js";
@@ -11,11 +11,25 @@ export class AgentsResource {
11
11
  const { keyword, ...rest } = opts;
12
12
  const raw = await listAgents({ ...this.ctx.base(), name: keyword, ...rest });
13
13
  const parsed = JSON.parse(raw);
14
- const items = parsed && typeof parsed === "object" && "data" in parsed
15
- ? parsed.data?.records ?? []
16
- : Array.isArray(parsed)
17
- ? parsed
18
- : [];
14
+ const items = (() => {
15
+ if (Array.isArray(parsed))
16
+ return parsed;
17
+ if (!parsed || typeof parsed !== "object")
18
+ return [];
19
+ const obj = parsed;
20
+ if (Array.isArray(obj.entries))
21
+ return obj.entries;
22
+ if (Array.isArray(obj.data))
23
+ return obj.data;
24
+ if (obj.data && typeof obj.data === "object") {
25
+ const dataObj = obj.data;
26
+ if (Array.isArray(dataObj.records))
27
+ return dataObj.records;
28
+ if (Array.isArray(dataObj.entries))
29
+ return dataObj.entries;
30
+ }
31
+ return [];
32
+ })();
19
33
  return items;
20
34
  }
21
35
  // ── Get by ID ────────────────────────────────────────────────────────────
@@ -48,7 +48,7 @@ export declare class BknResource {
48
48
  cancelActionLog(knId: string, logId: string): Promise<unknown>;
49
49
  /**
50
50
  * Search KN schema — finds matching object types, relation types, and action types.
51
- * Uses MCP protocol via the context-loader (public endpoint).
51
+ * Uses the public agent-retrieval HTTP compatibility endpoint.
52
52
  */
53
53
  knSearch(knId: string, query: string, opts?: {
54
54
  onlySchema?: boolean;
@@ -56,6 +56,7 @@ export declare class BknResource {
56
56
  object_types?: unknown[];
57
57
  relation_types?: unknown[];
58
58
  action_types?: unknown[];
59
+ metric_types?: unknown[];
59
60
  nodes?: unknown[];
60
61
  }>;
61
62
  }
@@ -1,4 +1,5 @@
1
1
  import { buildHeaders } from "../api/headers.js";
2
+ import { knSearchHttp } from "../api/semantic-search.js";
2
3
  import { objectTypeQuery, objectTypeProperties, subgraph, actionTypeQuery, actionTypeExecute, actionExecutionGet, actionLogsList, actionLogGet, actionLogCancel, } from "../api/ontology-query.js";
3
4
  import { fetchTextOrThrow } from "../utils/http.js";
4
5
  /** BKN engine resource — instance queries, subgraph, action execution and logs. */
@@ -88,14 +89,25 @@ export class BknResource {
88
89
  }
89
90
  /**
90
91
  * Search KN schema — finds matching object types, relation types, and action types.
91
- * Uses MCP protocol via the context-loader (public endpoint).
92
+ * Uses the public agent-retrieval HTTP compatibility endpoint.
92
93
  */
93
94
  async knSearch(knId, query, opts = {}) {
94
- const { ContextLoaderResource } = await import("./context-loader.js");
95
- const { baseUrl } = this.ctx.base();
96
- const mcpUrl = `${baseUrl}/api/agent-retrieval/v1/mcp`;
97
- const cl = new ContextLoaderResource(this.ctx, mcpUrl, knId);
98
- const result = await cl.search({ query, only_schema: opts.onlySchema ?? false });
99
- return result;
95
+ const raw = await knSearchHttp({
96
+ ...this.ctx.base(),
97
+ knId,
98
+ query,
99
+ onlySchema: opts.onlySchema ?? false,
100
+ });
101
+ let parsed;
102
+ try {
103
+ parsed = JSON.parse(raw);
104
+ }
105
+ catch {
106
+ throw new Error(`kn_search returned non-JSON body (first 200 chars): ${raw.slice(0, 200)}`);
107
+ }
108
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
109
+ throw new Error(`kn_search returned unexpected JSON shape (first 200 chars): ${raw.slice(0, 200)}`);
110
+ }
111
+ return parsed;
100
112
  }
101
113
  }
@@ -1,4 +1,4 @@
1
- import type { KnSearchArgs, KnSchemaSearchArgs, QueryObjectInstanceArgs, QueryInstanceSubgraphArgs, GetLogicPropertiesValuesArgs, GetActionInfoArgs } from "../api/context-loader.js";
1
+ import type { SearchSchemaArgs, QueryObjectInstanceArgs, QueryInstanceSubgraphArgs, GetLogicPropertiesValuesArgs, GetActionInfoArgs, FindSkillsArgs, FindSkillsResult } from "../api/context-loader.js";
2
2
  import type { ClientContext } from "../client.js";
3
3
  export declare class ContextLoaderResource {
4
4
  private readonly ctx;
@@ -6,10 +6,11 @@ export declare class ContextLoaderResource {
6
6
  private readonly knId;
7
7
  constructor(ctx: ClientContext, mcpUrl: string, knId: string);
8
8
  private opts;
9
- search(args: KnSearchArgs): Promise<unknown>;
10
- schemaSearch(args: KnSchemaSearchArgs): Promise<unknown>;
9
+ callTool(toolName: string, args: Record<string, unknown>): Promise<unknown>;
10
+ searchSchema(args: SearchSchemaArgs): Promise<unknown>;
11
11
  queryInstances(args: QueryObjectInstanceArgs): Promise<unknown>;
12
12
  querySubgraph(args: QueryInstanceSubgraphArgs): Promise<unknown>;
13
13
  getLogicProperties(args: GetLogicPropertiesValuesArgs): Promise<unknown>;
14
14
  getActionInfo(args: GetActionInfoArgs): Promise<unknown>;
15
+ findSkills(args: FindSkillsArgs): Promise<FindSkillsResult>;
15
16
  }
@@ -1,4 +1,4 @@
1
- import { knSearch, knSchemaSearch, queryObjectInstance, queryInstanceSubgraph, getLogicPropertiesValues, getActionInfo, } from "../api/context-loader.js";
1
+ import { callTool, searchSchema, queryObjectInstance, queryInstanceSubgraph, getLogicPropertiesValues, getActionInfo, findSkills, } from "../api/context-loader.js";
2
2
  export class ContextLoaderResource {
3
3
  ctx;
4
4
  mcpUrl;
@@ -11,11 +11,11 @@ export class ContextLoaderResource {
11
11
  opts() {
12
12
  return { mcpUrl: this.mcpUrl, knId: this.knId, accessToken: this.ctx.base().accessToken };
13
13
  }
14
- async search(args) {
15
- return knSearch(this.opts(), args);
14
+ async callTool(toolName, args) {
15
+ return callTool(this.opts(), toolName, args);
16
16
  }
17
- async schemaSearch(args) {
18
- return knSchemaSearch(this.opts(), args);
17
+ async searchSchema(args) {
18
+ return searchSchema(this.opts(), args);
19
19
  }
20
20
  async queryInstances(args) {
21
21
  return queryObjectInstance(this.opts(), args);
@@ -29,4 +29,7 @@ export class ContextLoaderResource {
29
29
  async getActionInfo(args) {
30
30
  return getActionInfo(this.opts(), args);
31
31
  }
32
+ async findSkills(args) {
33
+ return findSkills(this.opts(), args);
34
+ }
32
35
  }
@@ -0,0 +1,54 @@
1
+ import type { ClientContext } from "../client.js";
2
+ import { type ImpexType } from "../api/toolboxes.js";
3
+ export interface InvokeToolArgs {
4
+ /** Optional headers to forward to the downstream tool. Authorization is
5
+ * auto-injected from the client's access token when omitted; pass `{}` to
6
+ * send no headers. */
7
+ header?: Record<string, unknown>;
8
+ query?: Record<string, unknown>;
9
+ body?: unknown;
10
+ /** Per-call timeout in seconds (backend default applies when omitted). */
11
+ timeout?: number;
12
+ }
13
+ /** Toolbox / tool management on the agent-operator-integration service. */
14
+ export declare class ToolboxesResource {
15
+ private readonly ctx;
16
+ constructor(ctx: ClientContext);
17
+ list(opts?: {
18
+ keyword?: string;
19
+ limit?: number;
20
+ offset?: number;
21
+ }): Promise<string>;
22
+ listToolsIn(boxId: string): Promise<string>;
23
+ uploadTool(opts: {
24
+ boxId: string;
25
+ filePath: string;
26
+ metadataType?: "openapi";
27
+ }): Promise<string>;
28
+ setToolStatuses(opts: {
29
+ boxId: string;
30
+ updates: Array<{
31
+ toolId: string;
32
+ status: "enabled" | "disabled";
33
+ }>;
34
+ }): Promise<void>;
35
+ /** Execute a published+enabled tool through the toolbox proxy. */
36
+ execute(boxId: string, toolId: string, args?: InvokeToolArgs): Promise<string>;
37
+ /** Debug a tool through the toolbox proxy (works on draft/disabled tools too). */
38
+ debug(boxId: string, toolId: string, args?: InvokeToolArgs): Promise<string>;
39
+ /**
40
+ * Export a toolbox/mcp/operator config (.adp JSON) as raw bytes.
41
+ *
42
+ * Returned bytes are usually UTF-8 JSON; mirrors the Python SDK's
43
+ * `export_config -> bytes`. Use `new TextDecoder().decode(buf)` if you
44
+ * need a string.
45
+ */
46
+ exportConfig(id: string, opts?: {
47
+ type?: ImpexType;
48
+ }): Promise<Uint8Array>;
49
+ /** Import a previously exported config from disk. */
50
+ importConfig(filePath: string, opts?: {
51
+ type?: ImpexType;
52
+ }): Promise<string>;
53
+ private injectAuth;
54
+ }