bailian-kb-dsh 0.1.18
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/README.md +169 -0
- package/cordis.patch.yml +13 -0
- package/dist/api-types.d.ts +89 -0
- package/dist/api-types.js +2 -0
- package/dist/bl-cli.d.ts +28 -0
- package/dist/bl-cli.js +46 -0
- package/dist/chat.d.ts +11 -0
- package/dist/chat.js +44 -0
- package/dist/client.d.ts +40 -0
- package/dist/client.js +76 -0
- package/dist/console-login.d.ts +83 -0
- package/dist/console-login.js +263 -0
- package/dist/endpoints.d.ts +20 -0
- package/dist/endpoints.js +22 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +557 -0
- package/dist/service-cache.d.ts +151 -0
- package/dist/service-cache.js +234 -0
- package/dist/service-catalog.d.ts +34 -0
- package/dist/service-catalog.js +115 -0
- package/dist/service-context.d.ts +40 -0
- package/dist/service-context.js +125 -0
- package/dist/services.d.ts +41 -0
- package/dist/services.js +78 -0
- package/dist/skill.d.ts +39 -0
- package/dist/skill.js +119 -0
- package/dist/sse.d.ts +11 -0
- package/dist/sse.js +48 -0
- package/dist/tools.d.ts +38 -0
- package/dist/tools.js +244 -0
- package/dist/web/client.js +1052 -0
- package/dist/web/client.js.map +1 -0
- package/package.json +118 -0
- package/skills/bailian-kb/SKILL.md +96 -0
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-contained Bailian console login: the plugin drives the console's browser
|
|
3
|
+
* login itself and persists what comes back, rather than shelling out to the
|
|
4
|
+
* `bl` CLI.
|
|
5
|
+
*
|
|
6
|
+
* Driving the flow here lets it always request a freshly issued api key, so the
|
|
7
|
+
* key and the workspace id both come from the account that just signed in, and
|
|
8
|
+
* the values land straight in the dsh stores.
|
|
9
|
+
*
|
|
10
|
+
* Shape of the flow: bind a loopback-only port, open the console login page
|
|
11
|
+
* pointed at that port, then accept one callback carrying the credentials as
|
|
12
|
+
* query parameters or a JSON / form-encoded body.
|
|
13
|
+
*/
|
|
14
|
+
import { execFile } from "node:child_process";
|
|
15
|
+
import { randomBytes } from "node:crypto";
|
|
16
|
+
import http from "node:http";
|
|
17
|
+
/** Console web origins by site, keyed as the CLI's `--console-site` values. */
|
|
18
|
+
const CONSOLE_ORIGINS = {
|
|
19
|
+
domestic: "https://bailian.console.aliyun.com",
|
|
20
|
+
international: "https://modelstudio.console.alibabacloud.com",
|
|
21
|
+
};
|
|
22
|
+
/** How long the loopback listener waits for the browser callback. */
|
|
23
|
+
const LOGIN_TIMEOUT_MS = 15 * 60 * 1000;
|
|
24
|
+
/** Upper bound on a callback body. */
|
|
25
|
+
const MAX_CALLBACK_BODY = 65536;
|
|
26
|
+
/** The single in-flight flow: one browser login at a time. */
|
|
27
|
+
let active;
|
|
28
|
+
let state = { phase: "idle" };
|
|
29
|
+
/** Read the current flow state (safe to expose to the panel). */
|
|
30
|
+
export function consoleLoginState() {
|
|
31
|
+
return state;
|
|
32
|
+
}
|
|
33
|
+
/** Pick the first non-blank string among the given keys. */
|
|
34
|
+
function stringField(source, ...keys) {
|
|
35
|
+
for (const key of keys) {
|
|
36
|
+
const value = source[key];
|
|
37
|
+
if (typeof value === "string" && value.trim() !== "")
|
|
38
|
+
return value.trim();
|
|
39
|
+
}
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
/** Read a bounded UTF-8 request body; an oversized body reads as empty. */
|
|
43
|
+
function readBody(req) {
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
const chunks = [];
|
|
46
|
+
let size = 0;
|
|
47
|
+
req.on("data", (chunk) => {
|
|
48
|
+
size += chunk.length;
|
|
49
|
+
if (size > MAX_CALLBACK_BODY) {
|
|
50
|
+
req.destroy();
|
|
51
|
+
resolve("");
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
chunks.push(chunk);
|
|
55
|
+
});
|
|
56
|
+
req.on("end", () => {
|
|
57
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
58
|
+
});
|
|
59
|
+
req.on("error", () => {
|
|
60
|
+
resolve("");
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Parse a callback body as JSON (optionally wrapped in `data`) or as form
|
|
66
|
+
* encoding. Content-type is a hint only: both shapes occur in practice, so both
|
|
67
|
+
* are attempted.
|
|
68
|
+
* @param raw - the raw request body.
|
|
69
|
+
* @returns the flattened fields; an unparseable body yields no fields.
|
|
70
|
+
*/
|
|
71
|
+
export function parseCallbackBody(raw) {
|
|
72
|
+
const text = raw.replace(/^\uFEFF/, "").trim();
|
|
73
|
+
if (text === "")
|
|
74
|
+
return {};
|
|
75
|
+
let json;
|
|
76
|
+
let parsedAsJson = false;
|
|
77
|
+
try {
|
|
78
|
+
json = JSON.parse(text);
|
|
79
|
+
parsedAsJson = true;
|
|
80
|
+
}
|
|
81
|
+
catch (_notJson) {
|
|
82
|
+
/* fall through to form parsing */
|
|
83
|
+
}
|
|
84
|
+
if (parsedAsJson) {
|
|
85
|
+
// Valid JSON that is not an object carries no fields. Returning here rather
|
|
86
|
+
// than falling through matters: form parsing would turn the whole payload
|
|
87
|
+
// into one junk key.
|
|
88
|
+
if (json === null || typeof json !== "object" || Array.isArray(json))
|
|
89
|
+
return {};
|
|
90
|
+
const record = json;
|
|
91
|
+
const inner = record.data;
|
|
92
|
+
if (inner !== null && typeof inner === "object" && !Array.isArray(inner)) {
|
|
93
|
+
// Merge the envelope's `data` under the top level, top level winning.
|
|
94
|
+
return { ...inner, ...record };
|
|
95
|
+
}
|
|
96
|
+
return record;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
100
|
+
}
|
|
101
|
+
catch (_notForm) {
|
|
102
|
+
return {};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Pick the api key and workspace id out of a callback's fields, query
|
|
107
|
+
* parameters taking priority over the body.
|
|
108
|
+
* @param query - the callback URL's query parameters.
|
|
109
|
+
* @param body - the parsed callback body.
|
|
110
|
+
* @returns the credentials found; fields are absent rather than blank.
|
|
111
|
+
*/
|
|
112
|
+
export function pickCallbackCredentials(query, body) {
|
|
113
|
+
const apiKey = stringField(query, "api_key", "apiKey") ?? stringField(body, "api_key", "apiKey");
|
|
114
|
+
const workspaceId = stringField(query, "workspace_id", "workspaceId") ??
|
|
115
|
+
stringField(body, "workspace_id", "workspaceId");
|
|
116
|
+
return {
|
|
117
|
+
...(apiKey !== undefined ? { apiKey } : {}),
|
|
118
|
+
...(workspaceId !== undefined ? { workspaceId } : {}),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** Extract the credentials from a callback, query parameters taking priority. */
|
|
122
|
+
async function extractCredentials(req, url) {
|
|
123
|
+
const method = req.method ?? "GET";
|
|
124
|
+
const body = method === "POST" || method === "PUT" || method === "PATCH"
|
|
125
|
+
? parseCallbackBody(await readBody(req))
|
|
126
|
+
: {};
|
|
127
|
+
return pickCallbackCredentials(Object.fromEntries(url.searchParams), body);
|
|
128
|
+
}
|
|
129
|
+
/** Open a URL with the OS default handler; never routed through a shell. */
|
|
130
|
+
function openInBrowser(url) {
|
|
131
|
+
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
132
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
133
|
+
return new Promise((resolve, reject) => {
|
|
134
|
+
execFile(cmd, args, { windowsHide: true }, (err) => {
|
|
135
|
+
if (err)
|
|
136
|
+
reject(err);
|
|
137
|
+
else
|
|
138
|
+
resolve();
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
/** Bind an http server to a loopback-only port chosen by the OS. */
|
|
143
|
+
function listenLoopback(server) {
|
|
144
|
+
return new Promise((resolve, reject) => {
|
|
145
|
+
const onError = (err) => {
|
|
146
|
+
reject(err);
|
|
147
|
+
};
|
|
148
|
+
server.once("error", onError);
|
|
149
|
+
server.listen({ port: 0, host: "127.0.0.1", exclusive: true }, () => {
|
|
150
|
+
server.off("error", onError);
|
|
151
|
+
const address = server.address();
|
|
152
|
+
if (address === null || typeof address === "string") {
|
|
153
|
+
reject(new Error("expected a TCP address"));
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
resolve(address.port);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Start a console login on the host: binds a loopback listener, opens the
|
|
162
|
+
* console login page in the host's default browser, and hands the credentials
|
|
163
|
+
* from the callback to `onComplete` (which persists them). Fire-and-forget —
|
|
164
|
+
* this resolves once the browser has been opened; poll {@link consoleLoginState}
|
|
165
|
+
* for the outcome.
|
|
166
|
+
* @param opts.site - console site, `domestic` (default) or `international`.
|
|
167
|
+
* @param opts.onComplete - persists the received credentials; its resolved
|
|
168
|
+
* field names become the `done` state's `fields`.
|
|
169
|
+
* @returns whether the flow started, plus the URL to open manually if needed.
|
|
170
|
+
*/
|
|
171
|
+
export async function startConsoleLogin(opts) {
|
|
172
|
+
if (active !== undefined) {
|
|
173
|
+
return {
|
|
174
|
+
status: "already-running",
|
|
175
|
+
loginUrl: state.phase === "waiting" ? state.loginUrl : "",
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
const expectedState = randomBytes(16).toString("hex");
|
|
179
|
+
let settled = false;
|
|
180
|
+
const server = http.createServer((req, res) => {
|
|
181
|
+
void (async () => {
|
|
182
|
+
if (req.method === "OPTIONS") {
|
|
183
|
+
// The console page posts cross-origin; answer its preflight.
|
|
184
|
+
res.writeHead(204, {
|
|
185
|
+
"Access-Control-Allow-Origin": "*",
|
|
186
|
+
"Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, OPTIONS",
|
|
187
|
+
"Access-Control-Allow-Headers": "Content-Type",
|
|
188
|
+
});
|
|
189
|
+
res.end();
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
193
|
+
if (url.searchParams.get("state") !== expectedState) {
|
|
194
|
+
// Not our callback (or a forged one): refuse without ending the flow.
|
|
195
|
+
res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
|
|
196
|
+
res.end("bad state\n");
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const credentials = await extractCredentials(req, url);
|
|
200
|
+
res.writeHead(200, {
|
|
201
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
202
|
+
"Access-Control-Allow-Origin": "*",
|
|
203
|
+
});
|
|
204
|
+
res.end("OK\n");
|
|
205
|
+
if (credentials.apiKey === undefined && credentials.workspaceId === undefined) {
|
|
206
|
+
// A callback with neither value (e.g. a bare probe): keep waiting.
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
settled = true;
|
|
210
|
+
try {
|
|
211
|
+
const fields = await opts.onComplete(credentials);
|
|
212
|
+
state = { phase: "done", fields };
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
state = { phase: "failed", reason: err instanceof Error ? err.message : "persist failed" };
|
|
216
|
+
}
|
|
217
|
+
server.close();
|
|
218
|
+
})().catch(() => {
|
|
219
|
+
res.statusCode = 500;
|
|
220
|
+
res.end();
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
let port;
|
|
224
|
+
try {
|
|
225
|
+
port = await listenLoopback(server);
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
const reason = err instanceof Error ? err.message : "could not bind a local port";
|
|
229
|
+
state = { phase: "failed", reason };
|
|
230
|
+
return { status: "failed", reason };
|
|
231
|
+
}
|
|
232
|
+
// Ask for a freshly issued key, so the key and the workspace id cannot end up
|
|
233
|
+
// belonging to two different accounts.
|
|
234
|
+
const origin = (opts.site !== undefined ? CONSOLE_ORIGINS[opts.site] : undefined) ?? CONSOLE_ORIGINS.domestic;
|
|
235
|
+
const loginUrl = `${origin}/console-login?notice=127.0.0.1:${port}` +
|
|
236
|
+
`?state=${encodeURIComponent(expectedState)}&needapikey=true`;
|
|
237
|
+
active = { server };
|
|
238
|
+
state = { phase: "waiting", loginUrl };
|
|
239
|
+
const timer = setTimeout(() => {
|
|
240
|
+
server.close();
|
|
241
|
+
}, LOGIN_TIMEOUT_MS);
|
|
242
|
+
timer.unref?.();
|
|
243
|
+
server.once("close", () => {
|
|
244
|
+
clearTimeout(timer);
|
|
245
|
+
active = undefined;
|
|
246
|
+
if (!settled && state.phase === "waiting") {
|
|
247
|
+
state = { phase: "failed", reason: "the login timed out before the console called back" };
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
try {
|
|
251
|
+
await openInBrowser(loginUrl);
|
|
252
|
+
}
|
|
253
|
+
catch (_browserRefused) {
|
|
254
|
+
// Headless or locked-down host: the panel shows `loginUrl` to open by hand.
|
|
255
|
+
}
|
|
256
|
+
return { status: "started", loginUrl };
|
|
257
|
+
}
|
|
258
|
+
/** Abandon an in-flight login (closes the listener). */
|
|
259
|
+
export function cancelConsoleLogin() {
|
|
260
|
+
active?.server.close();
|
|
261
|
+
active = undefined;
|
|
262
|
+
state = { phase: "idle" };
|
|
263
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Protocol path constants and the workspace-subdomain URL builder (external API spec; not configurable). */
|
|
2
|
+
/**
|
|
3
|
+
* DashScope knowledge API paths. `serviceList` backs the plugin's internal
|
|
4
|
+
* service cache only — it is deliberately NOT exposed as a model tool (a
|
|
5
|
+
* discovery tool reintroduces the "list before you search" round trip this
|
|
6
|
+
* design exists to remove); the management surface uses the bl CLI instead.
|
|
7
|
+
*/
|
|
8
|
+
export declare const KB_PATHS: {
|
|
9
|
+
readonly serviceList: "/api/v1/indices/rag/app/list";
|
|
10
|
+
readonly search: "/api/v1/indices/knowledge/search";
|
|
11
|
+
readonly chat: "/api/v2/apps/knowledge/chat";
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Build one knowledge API endpoint.
|
|
15
|
+
* @param endpointHost - host suffix, e.g. `cn-beijing.maas.aliyuncs.com`.
|
|
16
|
+
* @param workspaceId - Bailian workspace id used as the subdomain.
|
|
17
|
+
* @param path - one {@link KB_PATHS} value.
|
|
18
|
+
* @returns the absolute endpoint URL.
|
|
19
|
+
*/
|
|
20
|
+
export declare function kbEndpoint(endpointHost: string, workspaceId: string, path: string): string;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Protocol path constants and the workspace-subdomain URL builder (external API spec; not configurable). */
|
|
2
|
+
/**
|
|
3
|
+
* DashScope knowledge API paths. `serviceList` backs the plugin's internal
|
|
4
|
+
* service cache only — it is deliberately NOT exposed as a model tool (a
|
|
5
|
+
* discovery tool reintroduces the "list before you search" round trip this
|
|
6
|
+
* design exists to remove); the management surface uses the bl CLI instead.
|
|
7
|
+
*/
|
|
8
|
+
export const KB_PATHS = {
|
|
9
|
+
serviceList: "/api/v1/indices/rag/app/list",
|
|
10
|
+
search: "/api/v1/indices/knowledge/search",
|
|
11
|
+
chat: "/api/v2/apps/knowledge/chat",
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Build one knowledge API endpoint.
|
|
15
|
+
* @param endpointHost - host suffix, e.g. `cn-beijing.maas.aliyuncs.com`.
|
|
16
|
+
* @param workspaceId - Bailian workspace id used as the subdomain.
|
|
17
|
+
* @param path - one {@link KB_PATHS} value.
|
|
18
|
+
* @returns the absolute endpoint URL.
|
|
19
|
+
*/
|
|
20
|
+
export function kbEndpoint(endpointHost, workspaceId, path) {
|
|
21
|
+
return `https://${workspaceId}.${endpointHost}${path}`;
|
|
22
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bailian knowledge-base consumer plugin: registers kb_search and kb_chat over the DashScope RAG API,
|
|
3
|
+
* plus the bl management skill.
|
|
4
|
+
* @module dsh-tool-bailian-kb
|
|
5
|
+
*/
|
|
6
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
7
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
8
|
+
import z from "@deepseek-ai/schemastery";
|
|
9
|
+
/** Minimal webServer route shape (declared inline to avoid a host-package dependency). */
|
|
10
|
+
interface WebRoute {
|
|
11
|
+
kind: "exact" | "prefix";
|
|
12
|
+
path: string;
|
|
13
|
+
handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/** Shell-environment registration shape (declared inline to avoid a host-package dependency). */
|
|
16
|
+
interface ShellEnvRegistration {
|
|
17
|
+
name: string;
|
|
18
|
+
variables: Record<string, {
|
|
19
|
+
description: string;
|
|
20
|
+
}>;
|
|
21
|
+
resolve: () => Record<string, string | undefined>;
|
|
22
|
+
}
|
|
23
|
+
declare module "@deepseek-ai/cordis" {
|
|
24
|
+
interface Context {
|
|
25
|
+
webServer: {
|
|
26
|
+
register(route: WebRoute): () => void;
|
|
27
|
+
};
|
|
28
|
+
shellEnv: {
|
|
29
|
+
register(registration: ShellEnvRegistration): void;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export declare const name = "tool-bailian-kb";
|
|
34
|
+
export declare const inject: string[];
|
|
35
|
+
/** Bailian knowledge-base plugin configuration. */
|
|
36
|
+
export interface Config {
|
|
37
|
+
/** Bailian workspace id; the API host is the workspace subdomain `https://<workspaceId>.<endpointHost>`. Optional here: an unset value falls back per call to the BAILIAN_WORKSPACE_ID credential (env/.env or ~/.dsh/.credentials.yaml). Editable with echo on the Settings → 百炼知识库 page (settings layer). */
|
|
38
|
+
workspaceId?: string;
|
|
39
|
+
/** API host suffix; replace for other regions or private deployments. */
|
|
40
|
+
endpointHost: string;
|
|
41
|
+
/** Retrieval-service id pinned by this deployment; when unset, the per-call fallback reads the BAILIAN_DEFAULT_RETRIEVE_AGENT_ID credential. */
|
|
42
|
+
defaultRetrieveAgentId?: string;
|
|
43
|
+
/** Q&A-service id pinned by this deployment; when unset, the per-call fallback reads the BAILIAN_DEFAULT_CHAT_AGENT_ID credential. */
|
|
44
|
+
defaultChatAgentId?: string;
|
|
45
|
+
/** Service version to call: `beta` (draft) or a published number; defaults to the latest published version. Never model-visible. */
|
|
46
|
+
agentVersion?: string;
|
|
47
|
+
/** kb_chat timeout in milliseconds; the server side is a minutes-scale agentic loop. */
|
|
48
|
+
chatTimeoutMs: number;
|
|
49
|
+
/** Consumed-once ledger of {@link seedFromBlCli}: fields listed here are never auto-seeded again, so a deliberately cleared value stays cleared. Maintained by the host; not editable from the panel. */
|
|
50
|
+
seededFields?: string[];
|
|
51
|
+
}
|
|
52
|
+
/** Schemastery validation for {@link Config}; workspaceId and default agent ids are optional — both resolve per call with a credentials fallback. */
|
|
53
|
+
export declare const Config: z<Config>;
|
|
54
|
+
/**
|
|
55
|
+
* Register the three knowledge tools over one shared client, plus the
|
|
56
|
+
* management skill when a skills registry is composed. The Config doubles as
|
|
57
|
+
* the `bailian-kb` settings section (entry config as the base layer), so
|
|
58
|
+
* every value is read through the live source thunk per call — tool schemas
|
|
59
|
+
* are static (agent_id stays optional regardless), so a settings edit needs
|
|
60
|
+
* no re-registration.
|
|
61
|
+
* @param ctx - registrant context carrying tools and credentials.
|
|
62
|
+
* @param config - deployment's workspace, host, pinning, and timeout choices.
|
|
63
|
+
*/
|
|
64
|
+
export declare function apply(ctx: Context, config: Config): void;
|
|
65
|
+
export {};
|