@kweaver-ai/kweaver-sdk 0.4.0
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/bin/kweaver.js +9 -0
- package/dist/api/agent-chat.d.ts +69 -0
- package/dist/api/agent-chat.js +379 -0
- package/dist/api/agent-list.d.ts +12 -0
- package/dist/api/agent-list.js +33 -0
- package/dist/api/context-loader.d.ts +115 -0
- package/dist/api/context-loader.js +259 -0
- package/dist/api/conversations.d.ts +24 -0
- package/dist/api/conversations.js +64 -0
- package/dist/api/knowledge-networks.d.ts +57 -0
- package/dist/api/knowledge-networks.js +158 -0
- package/dist/api/ontology-query.d.ts +75 -0
- package/dist/api/ontology-query.js +238 -0
- package/dist/api/semantic-search.d.ts +12 -0
- package/dist/api/semantic-search.js +34 -0
- package/dist/auth/oauth.d.ts +75 -0
- package/dist/auth/oauth.js +417 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +79 -0
- package/dist/client.d.ts +95 -0
- package/dist/client.js +104 -0
- package/dist/commands/agent-chat.d.ts +12 -0
- package/dist/commands/agent-chat.js +193 -0
- package/dist/commands/agent.d.ts +28 -0
- package/dist/commands/agent.js +431 -0
- package/dist/commands/auth.d.ts +9 -0
- package/dist/commands/auth.js +201 -0
- package/dist/commands/bkn.d.ts +70 -0
- package/dist/commands/bkn.js +1371 -0
- package/dist/commands/call.d.ts +14 -0
- package/dist/commands/call.js +151 -0
- package/dist/commands/context-loader.d.ts +1 -0
- package/dist/commands/context-loader.js +383 -0
- package/dist/commands/token.d.ts +2 -0
- package/dist/commands/token.js +24 -0
- package/dist/config/store.d.ts +77 -0
- package/dist/config/store.js +380 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.js +44 -0
- package/dist/kweaver.d.ts +146 -0
- package/dist/kweaver.js +184 -0
- package/dist/resources/agents.d.ts +37 -0
- package/dist/resources/agents.js +60 -0
- package/dist/resources/bkn.d.ts +45 -0
- package/dist/resources/bkn.js +86 -0
- package/dist/resources/context-loader.d.ts +15 -0
- package/dist/resources/context-loader.js +32 -0
- package/dist/resources/conversations.d.ts +11 -0
- package/dist/resources/conversations.js +17 -0
- package/dist/resources/knowledge-networks.d.ts +65 -0
- package/dist/resources/knowledge-networks.js +167 -0
- package/dist/ui/ChatApp.d.ts +16 -0
- package/dist/ui/ChatApp.js +248 -0
- package/dist/ui/MarkdownBlock.d.ts +5 -0
- package/dist/ui/MarkdownBlock.js +137 -0
- package/dist/ui/display-text.d.ts +1 -0
- package/dist/ui/display-text.js +1 -0
- package/dist/utils/browser.d.ts +1 -0
- package/dist/utils/browser.js +20 -0
- package/dist/utils/display-text.d.ts +3 -0
- package/dist/utils/display-text.js +46 -0
- package/dist/utils/http.d.ts +17 -0
- package/dist/utils/http.js +72 -0
- package/package.json +62 -0
package/bin/kweaver.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export interface SendChatRequestOptions {
|
|
2
|
+
baseUrl: string;
|
|
3
|
+
accessToken: string;
|
|
4
|
+
agentId: string;
|
|
5
|
+
agentKey: string;
|
|
6
|
+
agentVersion: string;
|
|
7
|
+
query: string;
|
|
8
|
+
conversationId?: string;
|
|
9
|
+
stream: boolean;
|
|
10
|
+
verbose?: boolean;
|
|
11
|
+
businessDomain?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface ChatResult {
|
|
14
|
+
text: string;
|
|
15
|
+
conversationId?: string;
|
|
16
|
+
/** From message.content.middle_answer.progress when stream is false. */
|
|
17
|
+
progress?: ProgressItem[];
|
|
18
|
+
}
|
|
19
|
+
/** One step from message.content.middle_answer.progress (tool/skill or LLM stage). */
|
|
20
|
+
export interface ProgressItem {
|
|
21
|
+
agent_name?: string;
|
|
22
|
+
skill_info?: {
|
|
23
|
+
name?: string;
|
|
24
|
+
type?: string;
|
|
25
|
+
checked?: boolean;
|
|
26
|
+
args?: Array<{
|
|
27
|
+
name?: string;
|
|
28
|
+
type?: string;
|
|
29
|
+
value?: unknown;
|
|
30
|
+
}>;
|
|
31
|
+
};
|
|
32
|
+
status?: string;
|
|
33
|
+
answer?: string | Record<string, unknown>;
|
|
34
|
+
description?: string;
|
|
35
|
+
result?: string;
|
|
36
|
+
stage?: string;
|
|
37
|
+
input_message?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface AgentInfo {
|
|
40
|
+
id: string;
|
|
41
|
+
key: string;
|
|
42
|
+
version: string;
|
|
43
|
+
}
|
|
44
|
+
export declare function buildChatUrl(baseUrl: string, agentId: string): string;
|
|
45
|
+
export declare function buildAgentInfoUrl(baseUrl: string, agentId: string, version: string): string;
|
|
46
|
+
export declare function fetchAgentInfo(options: {
|
|
47
|
+
baseUrl: string;
|
|
48
|
+
accessToken: string;
|
|
49
|
+
agentId: string;
|
|
50
|
+
version: string;
|
|
51
|
+
businessDomain?: string;
|
|
52
|
+
}): Promise<AgentInfo>;
|
|
53
|
+
export declare function extractText(data: unknown): string;
|
|
54
|
+
export declare function processIncrementalUpdate(data: {
|
|
55
|
+
key?: string[];
|
|
56
|
+
content?: unknown;
|
|
57
|
+
action?: string;
|
|
58
|
+
}, result: Record<string, unknown>): void;
|
|
59
|
+
export declare function sendChatRequest(options: SendChatRequestOptions): Promise<ChatResult>;
|
|
60
|
+
export interface SendChatRequestStreamCallbacks {
|
|
61
|
+
onTextDelta: (fullText: string) => void;
|
|
62
|
+
/** Optional: called when message.content.middle_answer.progress updates (tool/skill steps). */
|
|
63
|
+
onProgress?: (progress: ProgressItem[]) => void;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Stream-only entry point for TUI: same as sendChatRequest with stream=true,
|
|
67
|
+
* but invokes onTextDelta(fullText) for each incremental text update instead of writing to stdout.
|
|
68
|
+
*/
|
|
69
|
+
export declare function sendChatRequestStream(options: SendChatRequestOptions, callbacks: SendChatRequestStreamCallbacks): Promise<ChatResult>;
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { fetchTextOrThrow, HttpError } from "../utils/http.js";
|
|
2
|
+
import { normalizeDisplayText } from "../utils/display-text.js";
|
|
3
|
+
const CHAT_PATH = "/api/agent-factory/v1/app";
|
|
4
|
+
const AGENT_INFO_PATH = "/api/agent-factory/v3/agent-market/agent";
|
|
5
|
+
export function buildChatUrl(baseUrl, agentId) {
|
|
6
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
7
|
+
return `${base}${CHAT_PATH}/${agentId}/chat/completion`;
|
|
8
|
+
}
|
|
9
|
+
export function buildAgentInfoUrl(baseUrl, agentId, version) {
|
|
10
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
11
|
+
return `${base}${AGENT_INFO_PATH}/${agentId}/version/${version}?is_visit=true`;
|
|
12
|
+
}
|
|
13
|
+
export async function fetchAgentInfo(options) {
|
|
14
|
+
const { baseUrl, accessToken, agentId, version, businessDomain = "bd_public" } = options;
|
|
15
|
+
const url = buildAgentInfoUrl(baseUrl, agentId, version);
|
|
16
|
+
const { body } = await fetchTextOrThrow(url, {
|
|
17
|
+
method: "GET",
|
|
18
|
+
headers: {
|
|
19
|
+
accept: "application/json, text/plain, */*",
|
|
20
|
+
Authorization: `Bearer ${accessToken}`,
|
|
21
|
+
token: accessToken,
|
|
22
|
+
"x-business-domain": businessDomain,
|
|
23
|
+
"x-language": "zh-CN",
|
|
24
|
+
"x-requested-with": "XMLHttpRequest",
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
const data = JSON.parse(body);
|
|
28
|
+
if (!data.id || !data.key) {
|
|
29
|
+
throw new Error("Agent info response did not include id and key.");
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
id: data.id,
|
|
33
|
+
key: data.key,
|
|
34
|
+
version: typeof data.version === "string" ? data.version : version,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function getByPath(obj, path) {
|
|
38
|
+
let current = obj;
|
|
39
|
+
for (const key of path) {
|
|
40
|
+
if (current === null || typeof current !== "object")
|
|
41
|
+
return undefined;
|
|
42
|
+
current = current[key];
|
|
43
|
+
}
|
|
44
|
+
return current;
|
|
45
|
+
}
|
|
46
|
+
function setByPath(obj, path, value) {
|
|
47
|
+
let current = obj;
|
|
48
|
+
for (let i = 0; i < path.length - 1; i += 1) {
|
|
49
|
+
const key = path[i];
|
|
50
|
+
const next = path[i + 1];
|
|
51
|
+
if (!(key in current) || typeof current[key] !== "object") {
|
|
52
|
+
current[key] = typeof next === "number" ? [] : {};
|
|
53
|
+
}
|
|
54
|
+
current = current[key];
|
|
55
|
+
}
|
|
56
|
+
current[path[path.length - 1]] = value;
|
|
57
|
+
}
|
|
58
|
+
function stringFromAnswerObject(obj) {
|
|
59
|
+
const answer = obj.answer;
|
|
60
|
+
const block = obj.block_answer;
|
|
61
|
+
const src = answer ?? block;
|
|
62
|
+
if (!src || typeof src !== "object")
|
|
63
|
+
return "";
|
|
64
|
+
const d = typeof src.description === "string" ? src.description : "";
|
|
65
|
+
const c = typeof src.code === "string" ? src.code : "";
|
|
66
|
+
const s = typeof src.solution === "string" ? src.solution : "";
|
|
67
|
+
const parts = [d, c ? `code: ${c}` : "", s ? `solution: ${s}` : ""].filter(Boolean);
|
|
68
|
+
return parts.join("\n");
|
|
69
|
+
}
|
|
70
|
+
export function extractText(data) {
|
|
71
|
+
if (!data || typeof data !== "object")
|
|
72
|
+
return "";
|
|
73
|
+
const obj = data;
|
|
74
|
+
const fa = obj.final_answer;
|
|
75
|
+
if (fa?.answer && typeof fa.answer === "object") {
|
|
76
|
+
const ans = fa.answer;
|
|
77
|
+
if (typeof ans.text === "string")
|
|
78
|
+
return ans.text;
|
|
79
|
+
}
|
|
80
|
+
if (typeof fa?.text === "string") {
|
|
81
|
+
return fa.text;
|
|
82
|
+
}
|
|
83
|
+
const msg = obj.message;
|
|
84
|
+
if (typeof msg?.text === "string") {
|
|
85
|
+
return msg.text;
|
|
86
|
+
}
|
|
87
|
+
if (msg?.content && typeof msg.content === "object") {
|
|
88
|
+
const content = msg.content;
|
|
89
|
+
if (typeof content.text === "string")
|
|
90
|
+
return content.text;
|
|
91
|
+
const contentFinalAnswer = content.final_answer;
|
|
92
|
+
if (contentFinalAnswer?.answer && typeof contentFinalAnswer.answer === "object") {
|
|
93
|
+
const answer = contentFinalAnswer.answer;
|
|
94
|
+
if (typeof answer.text === "string")
|
|
95
|
+
return answer.text;
|
|
96
|
+
}
|
|
97
|
+
if (typeof contentFinalAnswer?.text === "string") {
|
|
98
|
+
return contentFinalAnswer.text;
|
|
99
|
+
}
|
|
100
|
+
const other = contentFinalAnswer?.answer_type_other;
|
|
101
|
+
if (other && typeof other === "object") {
|
|
102
|
+
const desc = stringFromAnswerObject(other);
|
|
103
|
+
if (desc)
|
|
104
|
+
return desc;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const topOther = fa?.answer_type_other;
|
|
108
|
+
if (topOther && typeof topOther === "object") {
|
|
109
|
+
const desc = stringFromAnswerObject(topOther);
|
|
110
|
+
if (desc)
|
|
111
|
+
return desc;
|
|
112
|
+
}
|
|
113
|
+
const answer = obj.answer;
|
|
114
|
+
if (typeof answer?.text === "string") {
|
|
115
|
+
return answer.text;
|
|
116
|
+
}
|
|
117
|
+
return "";
|
|
118
|
+
}
|
|
119
|
+
export function processIncrementalUpdate(data, result) {
|
|
120
|
+
const path = data.key;
|
|
121
|
+
const content = data.content;
|
|
122
|
+
const action = data.action;
|
|
123
|
+
if (!path || path.length === 0)
|
|
124
|
+
return;
|
|
125
|
+
if (action === "upsert" && content !== undefined) {
|
|
126
|
+
setByPath(result, path, content);
|
|
127
|
+
}
|
|
128
|
+
else if (action === "append") {
|
|
129
|
+
const existing = getByPath(result, path);
|
|
130
|
+
const newVal = typeof existing === "string"
|
|
131
|
+
? existing + (typeof content === "string" ? content : String(content ?? ""))
|
|
132
|
+
: String(content ?? "");
|
|
133
|
+
setByPath(result, path, newVal);
|
|
134
|
+
}
|
|
135
|
+
else if (action === "remove") {
|
|
136
|
+
if (path.length === 1) {
|
|
137
|
+
delete result[path[0]];
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function parseJsonResponse(text) {
|
|
142
|
+
try {
|
|
143
|
+
return JSON.parse(text);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
throw new Error("Agent chat returned invalid JSON.");
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function getProgressFromResult(result) {
|
|
150
|
+
const raw = getByPath(result, ["message", "content", "middle_answer", "progress"]);
|
|
151
|
+
if (!Array.isArray(raw) || raw.length === 0)
|
|
152
|
+
return [];
|
|
153
|
+
return raw.filter((item) => item != null && typeof item === "object").map((item) => {
|
|
154
|
+
if (!item || typeof item !== "object")
|
|
155
|
+
return {};
|
|
156
|
+
const o = item;
|
|
157
|
+
const answer = o.answer;
|
|
158
|
+
return {
|
|
159
|
+
agent_name: typeof o.agent_name === "string" ? o.agent_name : undefined,
|
|
160
|
+
skill_info: o.skill_info && typeof o.skill_info === "object"
|
|
161
|
+
? {
|
|
162
|
+
name: typeof o.skill_info.name === "string"
|
|
163
|
+
? normalizeDisplayText(o.skill_info.name)
|
|
164
|
+
: undefined,
|
|
165
|
+
type: typeof o.skill_info.type === "string"
|
|
166
|
+
? o.skill_info.type
|
|
167
|
+
: undefined,
|
|
168
|
+
checked: typeof o.skill_info.checked === "boolean"
|
|
169
|
+
? o.skill_info.checked
|
|
170
|
+
: undefined,
|
|
171
|
+
args: Array.isArray(o.skill_info.args)
|
|
172
|
+
? o.skill_info.args
|
|
173
|
+
.filter((arg) => arg && typeof arg === "object")
|
|
174
|
+
.map((arg) => ({
|
|
175
|
+
name: typeof arg.name === "string" ? normalizeDisplayText(arg.name) : undefined,
|
|
176
|
+
type: typeof arg.type === "string" ? arg.type : undefined,
|
|
177
|
+
value: typeof arg.value === "string"
|
|
178
|
+
? normalizeDisplayText(arg.value)
|
|
179
|
+
: arg.value,
|
|
180
|
+
}))
|
|
181
|
+
: undefined,
|
|
182
|
+
}
|
|
183
|
+
: undefined,
|
|
184
|
+
status: typeof o.status === "string" ? normalizeDisplayText(o.status) : undefined,
|
|
185
|
+
answer: typeof answer === "string"
|
|
186
|
+
? normalizeDisplayText(answer)
|
|
187
|
+
: answer && typeof answer === "object" && answer !== null
|
|
188
|
+
? answer
|
|
189
|
+
: undefined,
|
|
190
|
+
description: typeof o.description === "string" ? normalizeDisplayText(o.description) : undefined,
|
|
191
|
+
result: typeof o.result === "string" ? normalizeDisplayText(o.result) : undefined,
|
|
192
|
+
stage: typeof o.stage === "string" ? normalizeDisplayText(o.stage) : undefined,
|
|
193
|
+
input_message: typeof o.input_message === "string" ? normalizeDisplayText(o.input_message) : undefined,
|
|
194
|
+
};
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
function applySseDataLine(line, state, verbose, onTextDelta, onProgress) {
|
|
198
|
+
if (!line.startsWith("data: ")) {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const dataStr = line.slice(6).trim();
|
|
202
|
+
if (dataStr === "" || dataStr === "[DONE]") {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
try {
|
|
206
|
+
const data = JSON.parse(dataStr);
|
|
207
|
+
processIncrementalUpdate(data, state.result);
|
|
208
|
+
if (data.key?.length === 1 && data.key[0] === "conversation_id" && data.action === "upsert") {
|
|
209
|
+
state.conversationId =
|
|
210
|
+
typeof data.content === "string" ? data.content : String(data.content ?? "");
|
|
211
|
+
}
|
|
212
|
+
const progress = getProgressFromResult(state.result);
|
|
213
|
+
if (progress.length > 0 && onProgress) {
|
|
214
|
+
onProgress(progress);
|
|
215
|
+
}
|
|
216
|
+
const text = normalizeDisplayText(extractText(state.result));
|
|
217
|
+
if (text && text !== state.lastText) {
|
|
218
|
+
if (onTextDelta) {
|
|
219
|
+
onTextDelta(text);
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
const delta = text.slice(state.lastText.length);
|
|
223
|
+
process.stdout.write(delta);
|
|
224
|
+
}
|
|
225
|
+
state.lastText = text;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
if (verbose) {
|
|
230
|
+
console.error(`SSE parse skip: ${dataStr}`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
export async function sendChatRequest(options) {
|
|
235
|
+
const { baseUrl, accessToken, agentId, agentKey, agentVersion, query, conversationId, stream, verbose, businessDomain = "bd_public", } = options;
|
|
236
|
+
const url = buildChatUrl(baseUrl, agentId);
|
|
237
|
+
const body = {
|
|
238
|
+
agent_id: agentId,
|
|
239
|
+
agent_key: agentKey,
|
|
240
|
+
agent_version: agentVersion,
|
|
241
|
+
query,
|
|
242
|
+
stream,
|
|
243
|
+
};
|
|
244
|
+
if (conversationId) {
|
|
245
|
+
body.conversation_id = conversationId;
|
|
246
|
+
}
|
|
247
|
+
const headers = {
|
|
248
|
+
"Content-Type": "application/json",
|
|
249
|
+
accept: stream ? "text/event-stream" : "application/json",
|
|
250
|
+
Authorization: `Bearer ${accessToken}`,
|
|
251
|
+
"Accept-Language": "zh-CN",
|
|
252
|
+
"x-Language": "zh-CN",
|
|
253
|
+
"x-business-domain": businessDomain,
|
|
254
|
+
};
|
|
255
|
+
if (verbose) {
|
|
256
|
+
console.error(`POST ${url}`);
|
|
257
|
+
console.error(`Headers: ${JSON.stringify(headers)}`);
|
|
258
|
+
console.error(`Body: ${JSON.stringify(body)}`);
|
|
259
|
+
}
|
|
260
|
+
let response;
|
|
261
|
+
try {
|
|
262
|
+
response = await fetch(url, {
|
|
263
|
+
method: "POST",
|
|
264
|
+
headers,
|
|
265
|
+
body: JSON.stringify(body),
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
270
|
+
throw new Error(`Agent chat request failed: ${message}`);
|
|
271
|
+
}
|
|
272
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
273
|
+
if (!response.ok) {
|
|
274
|
+
const text = await response.text();
|
|
275
|
+
throw new HttpError(response.status, response.statusText, text);
|
|
276
|
+
}
|
|
277
|
+
if (stream && contentType.includes("text/event-stream")) {
|
|
278
|
+
return handleStreamResponse(response, verbose);
|
|
279
|
+
}
|
|
280
|
+
const text = await response.text();
|
|
281
|
+
const json = parseJsonResponse(text);
|
|
282
|
+
const resultText = normalizeDisplayText(extractText(json));
|
|
283
|
+
const convId = json.conversation_id;
|
|
284
|
+
const progress = getProgressFromResult(json);
|
|
285
|
+
return { text: resultText, conversationId: convId, progress };
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Stream-only entry point for TUI: same as sendChatRequest with stream=true,
|
|
289
|
+
* but invokes onTextDelta(fullText) for each incremental text update instead of writing to stdout.
|
|
290
|
+
*/
|
|
291
|
+
export async function sendChatRequestStream(options, callbacks) {
|
|
292
|
+
const opts = { ...options, stream: true };
|
|
293
|
+
const { baseUrl, accessToken, agentId, agentKey, agentVersion, query, conversationId, verbose, businessDomain = "bd_public", } = opts;
|
|
294
|
+
const url = buildChatUrl(baseUrl, agentId);
|
|
295
|
+
const body = {
|
|
296
|
+
agent_id: agentId,
|
|
297
|
+
agent_key: agentKey,
|
|
298
|
+
agent_version: agentVersion,
|
|
299
|
+
query,
|
|
300
|
+
stream: true,
|
|
301
|
+
};
|
|
302
|
+
if (conversationId) {
|
|
303
|
+
body.conversation_id = conversationId;
|
|
304
|
+
}
|
|
305
|
+
const headers = {
|
|
306
|
+
"Content-Type": "application/json",
|
|
307
|
+
accept: "text/event-stream",
|
|
308
|
+
Authorization: `Bearer ${accessToken}`,
|
|
309
|
+
"Accept-Language": "zh-CN",
|
|
310
|
+
"x-Language": "zh-CN",
|
|
311
|
+
"x-business-domain": businessDomain,
|
|
312
|
+
};
|
|
313
|
+
if (verbose) {
|
|
314
|
+
console.error(`POST ${url}`);
|
|
315
|
+
console.error(`Headers: ${JSON.stringify(headers)}`);
|
|
316
|
+
console.error(`Body: ${JSON.stringify(body)}`);
|
|
317
|
+
}
|
|
318
|
+
let response;
|
|
319
|
+
try {
|
|
320
|
+
response = await fetch(url, {
|
|
321
|
+
method: "POST",
|
|
322
|
+
headers,
|
|
323
|
+
body: JSON.stringify(body),
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
328
|
+
throw new Error(`Agent chat request failed: ${message}`);
|
|
329
|
+
}
|
|
330
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
331
|
+
if (!response.ok) {
|
|
332
|
+
const text = await response.text();
|
|
333
|
+
throw new HttpError(response.status, response.statusText, text);
|
|
334
|
+
}
|
|
335
|
+
if (contentType.includes("text/event-stream")) {
|
|
336
|
+
return handleStreamResponse(response, verbose, callbacks.onTextDelta, callbacks.onProgress);
|
|
337
|
+
}
|
|
338
|
+
const text = await response.text();
|
|
339
|
+
const json = parseJsonResponse(text);
|
|
340
|
+
const resultText = normalizeDisplayText(extractText(json));
|
|
341
|
+
const convId = json.conversation_id;
|
|
342
|
+
callbacks.onTextDelta(resultText);
|
|
343
|
+
return { text: resultText, conversationId: convId, progress: getProgressFromResult(json) };
|
|
344
|
+
}
|
|
345
|
+
async function handleStreamResponse(response, verbose, onTextDelta, onProgress) {
|
|
346
|
+
const reader = response.body?.getReader();
|
|
347
|
+
if (!reader) {
|
|
348
|
+
throw new Error("No response body for stream");
|
|
349
|
+
}
|
|
350
|
+
const decoder = new TextDecoder();
|
|
351
|
+
let buffer = "";
|
|
352
|
+
const state = {
|
|
353
|
+
result: {},
|
|
354
|
+
conversationId: undefined,
|
|
355
|
+
lastText: "",
|
|
356
|
+
};
|
|
357
|
+
const applyLine = (line) => {
|
|
358
|
+
applySseDataLine(line, state, verbose, onTextDelta, onProgress);
|
|
359
|
+
};
|
|
360
|
+
while (true) {
|
|
361
|
+
const { done, value } = await reader.read();
|
|
362
|
+
if (done)
|
|
363
|
+
break;
|
|
364
|
+
buffer += decoder.decode(value, { stream: true });
|
|
365
|
+
const lines = buffer.split("\n");
|
|
366
|
+
buffer = lines.pop() ?? "";
|
|
367
|
+
for (const line of lines) {
|
|
368
|
+
applyLine(line.trimEnd());
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (buffer.trim()) {
|
|
372
|
+
applyLine(buffer.trimEnd());
|
|
373
|
+
}
|
|
374
|
+
if (!onTextDelta && state.lastText && !state.lastText.endsWith("\n")) {
|
|
375
|
+
process.stdout.write("\n");
|
|
376
|
+
}
|
|
377
|
+
const finalText = normalizeDisplayText(extractText(state.result) || state.lastText);
|
|
378
|
+
return { text: finalText, conversationId: state.conversationId };
|
|
379
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface ListAgentsOptions {
|
|
2
|
+
baseUrl: string;
|
|
3
|
+
accessToken: string;
|
|
4
|
+
businessDomain?: string;
|
|
5
|
+
name?: string;
|
|
6
|
+
offset?: number;
|
|
7
|
+
limit?: number;
|
|
8
|
+
category_id?: string;
|
|
9
|
+
custom_space_id?: string;
|
|
10
|
+
is_to_square?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare function listAgents(options: ListAgentsOptions): Promise<string>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { HttpError } from "../utils/http.js";
|
|
2
|
+
export async function listAgents(options) {
|
|
3
|
+
const { baseUrl, accessToken, businessDomain = "bd_public", name = "", offset = 0, limit = 50, category_id = "", custom_space_id = "", is_to_square = 1, } = options;
|
|
4
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
5
|
+
const url = `${base}/api/agent-factory/v3/published/agent`;
|
|
6
|
+
const body = JSON.stringify({
|
|
7
|
+
offset,
|
|
8
|
+
limit,
|
|
9
|
+
category_id,
|
|
10
|
+
name,
|
|
11
|
+
custom_space_id,
|
|
12
|
+
is_to_square,
|
|
13
|
+
});
|
|
14
|
+
const response = await fetch(url, {
|
|
15
|
+
method: "POST",
|
|
16
|
+
headers: {
|
|
17
|
+
accept: "application/json, text/plain, */*",
|
|
18
|
+
"accept-language": "zh-CN",
|
|
19
|
+
authorization: `Bearer ${accessToken}`,
|
|
20
|
+
token: accessToken,
|
|
21
|
+
"x-business-domain": businessDomain,
|
|
22
|
+
"x-language": "zh-CN",
|
|
23
|
+
"x-requested-with": "XMLHttpRequest",
|
|
24
|
+
"content-type": "application/json",
|
|
25
|
+
},
|
|
26
|
+
body,
|
|
27
|
+
});
|
|
28
|
+
const responseBody = await response.text();
|
|
29
|
+
if (!response.ok) {
|
|
30
|
+
throw new HttpError(response.status, response.statusText, responseBody);
|
|
31
|
+
}
|
|
32
|
+
return responseBody;
|
|
33
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** Per-call options for context-loader MCP. */
|
|
2
|
+
export interface ContextLoaderCallOptions {
|
|
3
|
+
mcpUrl: string;
|
|
4
|
+
knId: string;
|
|
5
|
+
accessToken: string;
|
|
6
|
+
}
|
|
7
|
+
/** Layer 1: kn_search arguments. */
|
|
8
|
+
export interface KnSearchArgs {
|
|
9
|
+
query: string;
|
|
10
|
+
only_schema?: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** Layer 1: kn_schema_search arguments. */
|
|
13
|
+
export interface KnSchemaSearchArgs {
|
|
14
|
+
query: string;
|
|
15
|
+
max_concepts?: number;
|
|
16
|
+
}
|
|
17
|
+
/** Condition for query_object_instance and query_instance_subgraph. */
|
|
18
|
+
export interface ConditionSpec {
|
|
19
|
+
operation: "and" | "or";
|
|
20
|
+
sub_conditions: Array<{
|
|
21
|
+
field?: string;
|
|
22
|
+
operation?: string;
|
|
23
|
+
value_from?: "const";
|
|
24
|
+
value?: unknown;
|
|
25
|
+
}>;
|
|
26
|
+
}
|
|
27
|
+
/** Layer 2: query_object_instance arguments. */
|
|
28
|
+
export interface QueryObjectInstanceArgs {
|
|
29
|
+
ot_id: string;
|
|
30
|
+
limit?: number;
|
|
31
|
+
condition: ConditionSpec;
|
|
32
|
+
}
|
|
33
|
+
/** Layer 2: query_instance_subgraph relation type path. */
|
|
34
|
+
export interface RelationTypePath {
|
|
35
|
+
object_types: Array<{
|
|
36
|
+
id: string;
|
|
37
|
+
condition: ConditionSpec;
|
|
38
|
+
limit?: number;
|
|
39
|
+
}>;
|
|
40
|
+
relation_types: Array<{
|
|
41
|
+
relation_type_id: string;
|
|
42
|
+
source_object_type_id: string;
|
|
43
|
+
target_object_type_id: string;
|
|
44
|
+
}>;
|
|
45
|
+
}
|
|
46
|
+
/** Layer 2: query_instance_subgraph arguments. */
|
|
47
|
+
export interface QueryInstanceSubgraphArgs {
|
|
48
|
+
relation_type_paths: RelationTypePath[];
|
|
49
|
+
}
|
|
50
|
+
/** Layer 3: get_logic_properties_values arguments. */
|
|
51
|
+
export interface GetLogicPropertiesValuesArgs {
|
|
52
|
+
ot_id: string;
|
|
53
|
+
query: string;
|
|
54
|
+
_instance_identities: Record<string, string>[];
|
|
55
|
+
properties: string[];
|
|
56
|
+
additional_context?: string;
|
|
57
|
+
}
|
|
58
|
+
/** Layer 3: get_action_info arguments. */
|
|
59
|
+
export interface GetActionInfoArgs {
|
|
60
|
+
at_id: string;
|
|
61
|
+
_instance_identity: Record<string, string>;
|
|
62
|
+
}
|
|
63
|
+
/** Error when get_logic_properties_values returns MISSING_INPUT_PARAMS. */
|
|
64
|
+
export interface MissingInputParamsError {
|
|
65
|
+
error_code: "MISSING_INPUT_PARAMS";
|
|
66
|
+
message: string;
|
|
67
|
+
missing: Array<{
|
|
68
|
+
property: string;
|
|
69
|
+
params: Array<{
|
|
70
|
+
name: string;
|
|
71
|
+
type: string;
|
|
72
|
+
hint: string;
|
|
73
|
+
}>;
|
|
74
|
+
}>;
|
|
75
|
+
}
|
|
76
|
+
/** Build retry hint from MISSING_INPUT_PARAMS response. */
|
|
77
|
+
export declare function formatMissingInputParamsHint(err: MissingInputParamsError): string;
|
|
78
|
+
/** Guardrail: value_from only supports "const"; must appear with value. */
|
|
79
|
+
export declare function validateCondition(condition: unknown): void;
|
|
80
|
+
/** Guardrail: _instance_identity must be a plain object (from Layer 2 output, not fabricated). */
|
|
81
|
+
export declare function validateInstanceIdentity(v: unknown, label: string): void;
|
|
82
|
+
/** Guardrail: _instance_identities must be array of plain objects from Layer 2. */
|
|
83
|
+
export declare function validateInstanceIdentities(v: unknown): void;
|
|
84
|
+
/** Layer 1: kn_search. Returns object_types, relation_types, action_types. */
|
|
85
|
+
export declare function knSearch(options: ContextLoaderCallOptions, args: KnSearchArgs): Promise<unknown>;
|
|
86
|
+
/** Layer 1: kn_schema_search. Returns concepts (candidate discovery only). */
|
|
87
|
+
export declare function knSchemaSearch(options: ContextLoaderCallOptions, args: KnSchemaSearchArgs): Promise<unknown>;
|
|
88
|
+
/** Layer 2: query_object_instance. Returns datas with _instance_identity. */
|
|
89
|
+
export declare function queryObjectInstance(options: ContextLoaderCallOptions, args: QueryObjectInstanceArgs): Promise<unknown>;
|
|
90
|
+
/** Layer 2: query_instance_subgraph. Returns entries with nested _instance_identity. */
|
|
91
|
+
export declare function queryInstanceSubgraph(options: ContextLoaderCallOptions, args: QueryInstanceSubgraphArgs): Promise<unknown>;
|
|
92
|
+
/** Layer 3: get_logic_properties_values. Throws with retry hint on MISSING_INPUT_PARAMS. */
|
|
93
|
+
export declare function getLogicPropertiesValues(options: ContextLoaderCallOptions, args: GetLogicPropertiesValuesArgs): Promise<unknown>;
|
|
94
|
+
/** Layer 3: get_action_info. Returns _dynamic_tools. */
|
|
95
|
+
export declare function getActionInfo(options: ContextLoaderCallOptions, args: GetActionInfoArgs): Promise<unknown>;
|
|
96
|
+
/** MCP tools/list. Returns list of available tools. */
|
|
97
|
+
export declare function listTools(options: ContextLoaderCallOptions, params?: {
|
|
98
|
+
cursor?: string;
|
|
99
|
+
}): Promise<unknown>;
|
|
100
|
+
/** MCP resources/list. Returns list of available resources. */
|
|
101
|
+
export declare function listResources(options: ContextLoaderCallOptions, params?: {
|
|
102
|
+
cursor?: string;
|
|
103
|
+
}): Promise<unknown>;
|
|
104
|
+
/** MCP resources/read. Returns resource content by URI. */
|
|
105
|
+
export declare function readResource(options: ContextLoaderCallOptions, uri: string): Promise<unknown>;
|
|
106
|
+
/** MCP resources/templates/list. Returns list of resource templates. */
|
|
107
|
+
export declare function listResourceTemplates(options: ContextLoaderCallOptions, params?: {
|
|
108
|
+
cursor?: string;
|
|
109
|
+
}): Promise<unknown>;
|
|
110
|
+
/** MCP prompts/list. Returns list of available prompts. */
|
|
111
|
+
export declare function listPrompts(options: ContextLoaderCallOptions, params?: {
|
|
112
|
+
cursor?: string;
|
|
113
|
+
}): Promise<unknown>;
|
|
114
|
+
/** MCP prompts/get. Returns prompt by name with optional arguments. */
|
|
115
|
+
export declare function getPrompt(options: ContextLoaderCallOptions, name: string, args?: Record<string, unknown>): Promise<unknown>;
|