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
package/dist/index.js
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
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 z from "@deepseek-ai/schemastery";
|
|
7
|
+
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
8
|
+
import { settingsNamespace, SettingsProvider, } from "@deepseek-ai/dsh-settings";
|
|
9
|
+
import { readBlCliConfig } from "./bl-cli.js";
|
|
10
|
+
import { consoleLoginState, startConsoleLogin } from "./console-login.js";
|
|
11
|
+
import { KbClient } from "./client.js";
|
|
12
|
+
import { registerSkill } from "./skill.js";
|
|
13
|
+
import { ServiceCache } from "./service-cache.js";
|
|
14
|
+
import { CATALOG_ENTRY_LIMIT } from "./service-catalog.js";
|
|
15
|
+
import { installServiceContext } from "./service-context.js";
|
|
16
|
+
import { createKbTools } from "./tools.js";
|
|
17
|
+
export const name = "tool-bailian-kb";
|
|
18
|
+
export const inject = ["tools", "credentials"];
|
|
19
|
+
/** Settings namespace this plugin registers when a settings service is composed. */
|
|
20
|
+
const SETTINGS_NS = settingsNamespace("bailian-kb");
|
|
21
|
+
/** Settings fields seeded once from their credential references ({@link seedFromCredentials}). */
|
|
22
|
+
const CREDENTIAL_SEEDS = [
|
|
23
|
+
["workspaceId", "BAILIAN_WORKSPACE_ID"],
|
|
24
|
+
["defaultRetrieveAgentId", "BAILIAN_DEFAULT_RETRIEVE_AGENT_ID"],
|
|
25
|
+
["defaultChatAgentId", "BAILIAN_DEFAULT_CHAT_AGENT_ID"],
|
|
26
|
+
];
|
|
27
|
+
/**
|
|
28
|
+
* Every {@link Config} field the bridge route accepts. A static allowlist,
|
|
29
|
+
* NOT `key in current()`: optional fields with no default and no base
|
|
30
|
+
* (the default service ids) vanish from the resolved config once cleared,
|
|
31
|
+
* and a membership test against it would silently drop their next write.
|
|
32
|
+
*/
|
|
33
|
+
const CONFIG_FIELDS = new Set([
|
|
34
|
+
"workspaceId",
|
|
35
|
+
"endpointHost",
|
|
36
|
+
"defaultRetrieveAgentId",
|
|
37
|
+
"defaultChatAgentId",
|
|
38
|
+
"agentVersion",
|
|
39
|
+
"chatTimeoutMs",
|
|
40
|
+
]);
|
|
41
|
+
/**
|
|
42
|
+
* One-time migration: before this section existed, the workspace and
|
|
43
|
+
* default-service ids lived only as credentials, which the wire never echoes.
|
|
44
|
+
* Seed each field the resolved section does not answer from the WRITABLE
|
|
45
|
+
* credential layer (`file`), so the page shows the value the deployment
|
|
46
|
+
* already runs with; env-sourced values stay where they are — freezing one
|
|
47
|
+
* into the document would shadow later environment changes.
|
|
48
|
+
* @param ctx - registrant context carrying credentials.
|
|
49
|
+
* @param scope - the registered `bailian-kb` scope the seed writes through.
|
|
50
|
+
*/
|
|
51
|
+
async function seedFromCredentials(ctx, scope) {
|
|
52
|
+
try {
|
|
53
|
+
const seeds = {};
|
|
54
|
+
for (const [field, ref] of CREDENTIAL_SEEDS) {
|
|
55
|
+
if (scope.get()[field])
|
|
56
|
+
continue;
|
|
57
|
+
const resolved = await ctx.credentials.resolve(credentialRef(ref));
|
|
58
|
+
if (resolved?.source !== "file")
|
|
59
|
+
continue;
|
|
60
|
+
seeds[field] = resolved.value;
|
|
61
|
+
}
|
|
62
|
+
if (Object.keys(seeds).length > 0)
|
|
63
|
+
await scope.update(seeds);
|
|
64
|
+
}
|
|
65
|
+
catch (_migrationFailure) {
|
|
66
|
+
// Best-effort: a failed seed leaves the credential fallback in place, so
|
|
67
|
+
// resolution still answers — the page merely starts blank.
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* One-time adoption of the bl CLI's stored login (`~/.bailian/config.json`):
|
|
72
|
+
* fields never set anywhere are filled from the CLI's credential file, so a
|
|
73
|
+
* `bl auth login --console` done before installing the plugin "just works".
|
|
74
|
+
* `seededFields` is the consumed-once ledger — a field is marked when it was
|
|
75
|
+
* seeded here, or when it already had a value (user-managed elsewhere) — so
|
|
76
|
+
* a value the user later clears deliberately is never resurrected.
|
|
77
|
+
* @param ctx - registrant context carrying credentials.
|
|
78
|
+
* @param scope - the registered `bailian-kb` scope the seed writes through.
|
|
79
|
+
*/
|
|
80
|
+
async function seedFromBlCli(ctx, scope) {
|
|
81
|
+
try {
|
|
82
|
+
const done = new Set(scope.get().seededFields ?? []);
|
|
83
|
+
if (done.has("apiKey") && done.has("workspaceId"))
|
|
84
|
+
return;
|
|
85
|
+
const bl = readBlCliConfig();
|
|
86
|
+
const marks = [];
|
|
87
|
+
if (!done.has("apiKey")) {
|
|
88
|
+
const existing = await ctx.credentials.resolve(credentialRef("DASHSCOPE_API_KEY"));
|
|
89
|
+
if (existing) {
|
|
90
|
+
// Already configured (env or file): user-managed, never seed later.
|
|
91
|
+
marks.push("apiKey");
|
|
92
|
+
}
|
|
93
|
+
else if (bl.apiKey !== undefined) {
|
|
94
|
+
try {
|
|
95
|
+
await ctx.credentials.set(credentialRef("DASHSCOPE_API_KEY"), bl.apiKey);
|
|
96
|
+
marks.push("apiKey");
|
|
97
|
+
}
|
|
98
|
+
catch (_readOnlyShadow) {
|
|
99
|
+
// A read-only source refuses the write; leave unmarked so a later
|
|
100
|
+
// startup (once the shadow is gone) can still seed.
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// Neither configured nor available from the CLI: leave unmarked so a
|
|
104
|
+
// later startup (after `bl auth login --console`) can seed.
|
|
105
|
+
}
|
|
106
|
+
if (!done.has("workspaceId")) {
|
|
107
|
+
const configured = scope.get().workspaceId ||
|
|
108
|
+
(await ctx.credentials.resolve(credentialRef("BAILIAN_WORKSPACE_ID"))) !== undefined;
|
|
109
|
+
if (configured) {
|
|
110
|
+
marks.push("workspaceId");
|
|
111
|
+
}
|
|
112
|
+
else if (bl.workspaceId !== undefined) {
|
|
113
|
+
await scope.update({ workspaceId: bl.workspaceId });
|
|
114
|
+
marks.push("workspaceId");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (marks.length > 0) {
|
|
118
|
+
await scope.update({
|
|
119
|
+
seededFields: [...new Set([...(scope.get().seededFields ?? []), ...marks])],
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch (_seedFailure) {
|
|
124
|
+
// Best-effort: an unseeded field still resolves through the normal
|
|
125
|
+
// credential fallback chain, and the panel's autofill button remains.
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Schemastery validation for {@link Config}; workspaceId and default agent ids are optional — both resolve per call with a credentials fallback. */
|
|
129
|
+
export const Config = z.object({
|
|
130
|
+
workspaceId: z.string(),
|
|
131
|
+
endpointHost: z.string().default("cn-beijing.maas.aliyuncs.com"),
|
|
132
|
+
defaultRetrieveAgentId: z.string(),
|
|
133
|
+
defaultChatAgentId: z.string(),
|
|
134
|
+
agentVersion: z.string(),
|
|
135
|
+
chatTimeoutMs: z.number().default(300_000),
|
|
136
|
+
seededFields: z.array(z.string()),
|
|
137
|
+
});
|
|
138
|
+
/**
|
|
139
|
+
* Register the three knowledge tools over one shared client, plus the
|
|
140
|
+
* management skill when a skills registry is composed. The Config doubles as
|
|
141
|
+
* the `bailian-kb` settings section (entry config as the base layer), so
|
|
142
|
+
* every value is read through the live source thunk per call — tool schemas
|
|
143
|
+
* are static (agent_id stays optional regardless), so a settings edit needs
|
|
144
|
+
* no re-registration.
|
|
145
|
+
* @param ctx - registrant context carrying tools and credentials.
|
|
146
|
+
* @param config - deployment's workspace, host, pinning, and timeout choices.
|
|
147
|
+
*/
|
|
148
|
+
export function apply(ctx, config) {
|
|
149
|
+
// The active configuration source: the composition entry until a settings
|
|
150
|
+
// service attaches, then the resolved section (schema defaults → entry
|
|
151
|
+
// base → user layer). Detach falls back to the entry automatically.
|
|
152
|
+
// Hand-rolled instead of `installSettingsSection` for two extras it does
|
|
153
|
+
// not carry: the `expose` opt-in (this page edits the section from the
|
|
154
|
+
// browser) and the scope handle the credential migration writes through.
|
|
155
|
+
let current = () => config;
|
|
156
|
+
let scope;
|
|
157
|
+
/** The settings provider, captured for `mutate` (path-level unset) access. */
|
|
158
|
+
let settings;
|
|
159
|
+
/**
|
|
160
|
+
* Mark fields as consumed in the {@link seedFromBlCli} ledger — called on
|
|
161
|
+
* every user-driven write or clear, so a managed field is never re-seeded.
|
|
162
|
+
* Best-effort: a failed mark only risks one extra seed attempt.
|
|
163
|
+
*/
|
|
164
|
+
const markSeeded = async (fields) => {
|
|
165
|
+
if (!scope)
|
|
166
|
+
return;
|
|
167
|
+
try {
|
|
168
|
+
const done = new Set(scope.get().seededFields ?? []);
|
|
169
|
+
const added = fields.filter((field) => !done.has(field));
|
|
170
|
+
if (added.length === 0)
|
|
171
|
+
return;
|
|
172
|
+
await scope.update({ seededFields: [...done, ...added] });
|
|
173
|
+
}
|
|
174
|
+
catch (_markFailure) {
|
|
175
|
+
/* best-effort */
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
ctx.inject(["settings"], (sctx) => {
|
|
179
|
+
settings = sctx.settings;
|
|
180
|
+
// `expose` is the wire opt-in the harness documents as deferred work; the
|
|
181
|
+
// assertion keeps this compiling against pristine upstream types, which do
|
|
182
|
+
// not declare it yet. Until upstream lands it the option is ignored and
|
|
183
|
+
// the browser page degrades to its credentials-only fallback.
|
|
184
|
+
const options = { base: config, expose: true };
|
|
185
|
+
scope = sctx.settings.register(SETTINGS_NS, Config, options);
|
|
186
|
+
current = () => scope.get();
|
|
187
|
+
sctx.effect(() => () => {
|
|
188
|
+
current = () => config;
|
|
189
|
+
}, "tool-bailian-kb: settings source fallback");
|
|
190
|
+
void seedFromCredentials(ctx, scope).then(() => seedFromBlCli(ctx, scope));
|
|
191
|
+
// Any api-key write or clear — this panel, the Models page, an external
|
|
192
|
+
// file edit — means the user manages the credential: consume the seed so
|
|
193
|
+
// a deliberately cleared key is never resurrected at the next startup.
|
|
194
|
+
sctx.on("credentials/updated", (ref) => {
|
|
195
|
+
if (ref === "DASHSCOPE_API_KEY")
|
|
196
|
+
void markSeeded(["apiKey"]);
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
const client = new KbClient({
|
|
200
|
+
resolveWorkspaceId: async () => {
|
|
201
|
+
const pinned = current().workspaceId;
|
|
202
|
+
if (pinned)
|
|
203
|
+
return pinned;
|
|
204
|
+
const resolved = await ctx.credentials.resolve(credentialRef("BAILIAN_WORKSPACE_ID"));
|
|
205
|
+
if (!resolved) {
|
|
206
|
+
throw new Error("BAILIAN_WORKSPACE_ID is not configured. Set the workspace id in the web UI (Settings → 百炼知识库) " +
|
|
207
|
+
"or in ~/.dsh/.credentials.yaml; it appears as the subdomain of your Bailian endpoints.");
|
|
208
|
+
}
|
|
209
|
+
return resolved.value;
|
|
210
|
+
},
|
|
211
|
+
// Live settings reads: the client keeps no copy, so a committed edit to
|
|
212
|
+
// the section applies on the next call.
|
|
213
|
+
get endpointHost() {
|
|
214
|
+
return current().endpointHost;
|
|
215
|
+
},
|
|
216
|
+
get agentVersion() {
|
|
217
|
+
return current().agentVersion;
|
|
218
|
+
},
|
|
219
|
+
resolveApiKey: async () => {
|
|
220
|
+
const resolved = await ctx.credentials.resolve(credentialRef("DASHSCOPE_API_KEY"));
|
|
221
|
+
if (!resolved) {
|
|
222
|
+
throw new Error("DASHSCOPE_API_KEY is not configured. Set it in the web UI (Settings → 百炼知识库) " +
|
|
223
|
+
"or in ~/.dsh/.credentials.yaml (create a key at https://bailian.console.aliyun.com/?tab=app#/api-key).");
|
|
224
|
+
}
|
|
225
|
+
return resolved.value;
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
/** The workspace id if configured, without the client's guidance throw. */
|
|
229
|
+
const resolveWorkspaceIdOrUndefined = async () => {
|
|
230
|
+
const pinned = current().workspaceId;
|
|
231
|
+
if (pinned)
|
|
232
|
+
return pinned;
|
|
233
|
+
const resolved = await ctx.credentials.resolve(credentialRef("BAILIAN_WORKSPACE_ID"));
|
|
234
|
+
return resolved?.value;
|
|
235
|
+
};
|
|
236
|
+
const serviceCache = new ServiceCache({
|
|
237
|
+
client,
|
|
238
|
+
resolveWorkspaceId: async () => {
|
|
239
|
+
const workspaceId = await resolveWorkspaceIdOrUndefined();
|
|
240
|
+
if (workspaceId === undefined)
|
|
241
|
+
throw new Error("workspace id is not configured");
|
|
242
|
+
return workspaceId;
|
|
243
|
+
},
|
|
244
|
+
get endpointHost() {
|
|
245
|
+
return current().endpointHost;
|
|
246
|
+
},
|
|
247
|
+
warn: (message) => {
|
|
248
|
+
ctx.logger.warn(message);
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
/** The user's explicitly configured default for one scene: settings layer, then credential. */
|
|
252
|
+
const configuredDefaultAgentId = async (scene) => {
|
|
253
|
+
const pinned = scene === "search" ? current().defaultRetrieveAgentId : current().defaultChatAgentId;
|
|
254
|
+
if (pinned)
|
|
255
|
+
return pinned;
|
|
256
|
+
const ref = scene === "search" ? "BAILIAN_DEFAULT_RETRIEVE_AGENT_ID" : "BAILIAN_DEFAULT_CHAT_AGENT_ID";
|
|
257
|
+
const resolved = await ctx.credentials.resolve(credentialRef(ref));
|
|
258
|
+
return resolved?.value;
|
|
259
|
+
};
|
|
260
|
+
/**
|
|
261
|
+
* The default service for one scene, falling back to the sole deployed service
|
|
262
|
+
* when the workspace has exactly one. That last layer is the zero-configuration
|
|
263
|
+
* path for the common 2C deployment: with one service there is nothing to
|
|
264
|
+
* choose, so making the user name it in settings buys nothing.
|
|
265
|
+
*/
|
|
266
|
+
const resolveDefaultAgentId = async (scene) => {
|
|
267
|
+
const configured = await configuredDefaultAgentId(scene);
|
|
268
|
+
if (configured !== undefined)
|
|
269
|
+
return configured;
|
|
270
|
+
const workspaceId = await resolveWorkspaceIdOrUndefined();
|
|
271
|
+
if (workspaceId === undefined)
|
|
272
|
+
return undefined;
|
|
273
|
+
const forScene = serviceCache.peek(workspaceId)?.entries.filter((entry) => entry.scene === scene) ?? [];
|
|
274
|
+
return forScene.length === 1 ? forScene[0]?.agent_id : undefined;
|
|
275
|
+
};
|
|
276
|
+
for (const tool of createKbTools({
|
|
277
|
+
client,
|
|
278
|
+
resolveDefaultRetrieveAgentId: async () => await resolveDefaultAgentId("search"),
|
|
279
|
+
resolveDefaultChatAgentId: async () => await resolveDefaultAgentId("chat"),
|
|
280
|
+
// Self-heal for a cached id the server has since rejected: refresh once and
|
|
281
|
+
// put the current list in the error, which reaches the model this step.
|
|
282
|
+
describeServicesAfterRefresh: async (scene) => {
|
|
283
|
+
await serviceCache.refresh();
|
|
284
|
+
const workspaceId = await resolveWorkspaceIdOrUndefined();
|
|
285
|
+
if (workspaceId === undefined)
|
|
286
|
+
return undefined;
|
|
287
|
+
const forScene = serviceCache.peek(workspaceId)?.entries.filter((entry) => entry.scene === scene) ?? [];
|
|
288
|
+
if (forScene.length === 0)
|
|
289
|
+
return undefined;
|
|
290
|
+
const lines = forScene
|
|
291
|
+
.slice(0, CATALOG_ENTRY_LIMIT)
|
|
292
|
+
.map((entry) => `- ${entry.agent_id} — ${entry.agent_name === "" ? "(unnamed)" : entry.agent_name}`);
|
|
293
|
+
const more = forScene.length - lines.length;
|
|
294
|
+
return [
|
|
295
|
+
`Deployed ${scene} services in this workspace, re-read just now:`,
|
|
296
|
+
...lines,
|
|
297
|
+
...(more > 0
|
|
298
|
+
? [`(and ${more} more — \`bl knowledge service list --scene ${scene}\`)`]
|
|
299
|
+
: []),
|
|
300
|
+
].join("\n");
|
|
301
|
+
},
|
|
302
|
+
get chatTimeoutMs() {
|
|
303
|
+
return current().chatTimeoutMs;
|
|
304
|
+
},
|
|
305
|
+
})) {
|
|
306
|
+
ctx.tools.register(tool);
|
|
307
|
+
}
|
|
308
|
+
registerSkill(ctx);
|
|
309
|
+
// A management command that changes the service inventory invalidates the
|
|
310
|
+
// cache immediately, so the next session sees the new service instead of
|
|
311
|
+
// waiting out the TTL. `tools/result` is observe-only (it returns undefined and
|
|
312
|
+
// sits after the pipeline), so listening here cannot affect tool execution.
|
|
313
|
+
//
|
|
314
|
+
// The command string is matched inside the serialized arguments rather than
|
|
315
|
+
// against a specific tool name: the agent may run `bl` through bash, a
|
|
316
|
+
// terminal tool, or a run_code program. A loose match is deliberate — a false
|
|
317
|
+
// positive costs one list request, while a miss falls back to the TTL.
|
|
318
|
+
ctx.on("tools/result", (_exec, result) => {
|
|
319
|
+
if (result.isError)
|
|
320
|
+
return;
|
|
321
|
+
const args = JSON.stringify(_exec.arguments ?? "");
|
|
322
|
+
if (!/bl\s+knowledge\s+service\s+(create|deploy|delete|copy)/.test(args))
|
|
323
|
+
return;
|
|
324
|
+
serviceCache.invalidate();
|
|
325
|
+
void serviceCache.refresh();
|
|
326
|
+
});
|
|
327
|
+
// The service catalog rides an `agent/pre-step` context message rather than the
|
|
328
|
+
// tool descriptions: descriptions freeze at plugin load, and a plugin loads
|
|
329
|
+
// once per process, so in a long-running host a service created elsewhere
|
|
330
|
+
// would never be seen. Optional inject — a headless assembly without `agents`
|
|
331
|
+
// simply gets no catalog, and both tools keep working.
|
|
332
|
+
ctx.inject(["agents"], (actx) => {
|
|
333
|
+
installServiceContext(actx, {
|
|
334
|
+
cache: serviceCache,
|
|
335
|
+
resolveWorkspaceId: resolveWorkspaceIdOrUndefined,
|
|
336
|
+
resolveDefaultRetrieveAgentId: async () => await configuredDefaultAgentId("search"),
|
|
337
|
+
resolveDefaultChatAgentId: async () => await configuredDefaultAgentId("chat"),
|
|
338
|
+
warn: (message) => {
|
|
339
|
+
actx.logger.warn(message);
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
});
|
|
343
|
+
// Export the resolved workspace id as a shell environment variable so
|
|
344
|
+
// management CLI commands (`bl knowledge list`, `bl knowledge service list`, etc.)
|
|
345
|
+
// running in bash can see the value the settings service resolved.
|
|
346
|
+
// Without this, the settings.yaml value is invisible to child processes.
|
|
347
|
+
ctx.inject(["shellEnv"], (envCtx) => {
|
|
348
|
+
envCtx.shellEnv.register({
|
|
349
|
+
name: "bailian-kb",
|
|
350
|
+
variables: {
|
|
351
|
+
BAILIAN_WORKSPACE_ID: {
|
|
352
|
+
description: "Bailian workspace id resolved from settings (Settings → 百炼知识库) or credentials.",
|
|
353
|
+
},
|
|
354
|
+
},
|
|
355
|
+
resolve: () => {
|
|
356
|
+
const wsId = current().workspaceId;
|
|
357
|
+
return wsId ? { BAILIAN_WORKSPACE_ID: wsId } : {};
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
});
|
|
361
|
+
// Bridge routes let the browser settings page read and write the resolved
|
|
362
|
+
// section without riding the settings wire (which requires an apiproxy
|
|
363
|
+
// allowlist entry the composition does not grant out-of-tree namespaces).
|
|
364
|
+
// GET and POST share one exact-route registration: the webServer map keys
|
|
365
|
+
// on (kind, path), so two registrations for the same path throw
|
|
366
|
+
// "duplicate route" and the second handler silently replaces the first.
|
|
367
|
+
ctx.inject(["webServer"], (wctx) => {
|
|
368
|
+
wctx.effect(() => wctx.webServer.register({
|
|
369
|
+
kind: "exact",
|
|
370
|
+
path: "/bailian-kb/settings",
|
|
371
|
+
handler: async (req, res) => {
|
|
372
|
+
if (req.method === "GET" || req.method === "HEAD") {
|
|
373
|
+
sendJson(res, 200, current());
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (req.method !== "POST") {
|
|
377
|
+
sendJson(res, 405, { error: "use GET or POST" });
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
if (!scope) {
|
|
381
|
+
sendJson(res, 503, { error: "settings service unavailable" });
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
let body;
|
|
385
|
+
try {
|
|
386
|
+
body = await readJsonBody(req);
|
|
387
|
+
}
|
|
388
|
+
catch (err) {
|
|
389
|
+
sendJson(res, 400, { error: err instanceof Error ? err.message : "bad request" });
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (typeof body !== "object" || body === null) {
|
|
393
|
+
sendJson(res, 400, { error: "expected JSON object" });
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
// Build a settings update patch. null-valued keys are removals (the
|
|
397
|
+
// field falls back to the entry config and then the credential store).
|
|
398
|
+
const patch = {};
|
|
399
|
+
const removals = new Set();
|
|
400
|
+
for (const [key, value] of Object.entries(body)) {
|
|
401
|
+
if (!CONFIG_FIELDS.has(key))
|
|
402
|
+
continue;
|
|
403
|
+
if (value === null) {
|
|
404
|
+
removals.add(key);
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
patch[key] = value;
|
|
408
|
+
}
|
|
409
|
+
try {
|
|
410
|
+
// Apply non-removal patches first (scope.update merges into the user
|
|
411
|
+
// layer without disturbing other fields).
|
|
412
|
+
if (Object.keys(patch).length > 0)
|
|
413
|
+
await scope.update(patch);
|
|
414
|
+
// Remove fields via path-level unset ops: this deletes the key from
|
|
415
|
+
// the user layer so it re-inherits the entry base and schema defaults.
|
|
416
|
+
// Using scope.replace() with the resolved config would bake defaults
|
|
417
|
+
// (endpointHost, chatTimeoutMs) and entry values into the user layer,
|
|
418
|
+
// shadowing future entry changes and polluting the stored document.
|
|
419
|
+
if (removals.size > 0 && settings) {
|
|
420
|
+
for (const key of removals) {
|
|
421
|
+
await settings.mutate(SETTINGS_NS, [{ op: "unset", path: [key] }]);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
// A user-driven workspace write or clear consumes its bl-CLI seed:
|
|
425
|
+
// a deliberately cleared value must never be resurrected at startup.
|
|
426
|
+
if ("workspaceId" in patch || removals.has("workspaceId"))
|
|
427
|
+
await markSeeded(["workspaceId"]);
|
|
428
|
+
sendJson(res, 200, scope.get());
|
|
429
|
+
}
|
|
430
|
+
catch (err) {
|
|
431
|
+
sendJson(res, 500, {
|
|
432
|
+
error: err instanceof Error ? err.message : "settings write failed",
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
},
|
|
436
|
+
}), "tool-bailian-kb: settings bridge route");
|
|
437
|
+
// Service cache bridge: the panel's only window into cache freshness.
|
|
438
|
+
// GET returns the diagnostic snapshot plus the pickable services; POST
|
|
439
|
+
// forces a refresh and returns the same shape, so the numbers the developer
|
|
440
|
+
// sees update in place.
|
|
441
|
+
wctx.effect(() => wctx.webServer.register({
|
|
442
|
+
kind: "exact",
|
|
443
|
+
path: "/bailian-kb/services",
|
|
444
|
+
handler: async (req, res) => {
|
|
445
|
+
if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "POST") {
|
|
446
|
+
sendJson(res, 405, { error: "use GET or POST" });
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
const workspaceId = await resolveWorkspaceIdOrUndefined();
|
|
450
|
+
if (workspaceId === undefined) {
|
|
451
|
+
sendJson(res, 200, { configured: false });
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
if (req.method === "POST") {
|
|
455
|
+
// Force a fetch regardless of TTL: the button exists precisely for the
|
|
456
|
+
// case where the developer believes the cache is wrong.
|
|
457
|
+
serviceCache.invalidate();
|
|
458
|
+
await serviceCache.refresh();
|
|
459
|
+
}
|
|
460
|
+
sendJson(res, 200, {
|
|
461
|
+
configured: true,
|
|
462
|
+
status: serviceCache.status(workspaceId),
|
|
463
|
+
search: serviceCache.entriesFor(workspaceId, "search"),
|
|
464
|
+
chat: serviceCache.entriesFor(workspaceId, "chat"),
|
|
465
|
+
});
|
|
466
|
+
},
|
|
467
|
+
}), "tool-bailian-kb: service cache bridge route");
|
|
468
|
+
// Autofill bridge: fetch credentials by signing in to the Bailian console
|
|
469
|
+
// (panel button). `login` drives the console's callback protocol on the
|
|
470
|
+
// host and persists what comes back — the plain key never rides the wire
|
|
471
|
+
// to the browser; `loginStatus` lets the panel poll for the outcome.
|
|
472
|
+
wctx.effect(() => wctx.webServer.register({
|
|
473
|
+
kind: "exact",
|
|
474
|
+
path: "/bailian-kb/autofill",
|
|
475
|
+
handler: async (req, res) => {
|
|
476
|
+
if (req.method !== "POST") {
|
|
477
|
+
sendJson(res, 405, { error: "use POST" });
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
let action = "login";
|
|
481
|
+
try {
|
|
482
|
+
const body = await readJsonBody(req);
|
|
483
|
+
if (typeof body === "object" &&
|
|
484
|
+
body !== null &&
|
|
485
|
+
body.action === "loginStatus")
|
|
486
|
+
action = "loginStatus";
|
|
487
|
+
}
|
|
488
|
+
catch (_emptyOrMalformedBody) {
|
|
489
|
+
/* default to login */
|
|
490
|
+
}
|
|
491
|
+
if (action === "loginStatus") {
|
|
492
|
+
sendJson(res, 200, consoleLoginState());
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
// Drive the console flow ourselves, requesting a freshly issued key,
|
|
496
|
+
// so the key and the workspace id both belong to the account signing
|
|
497
|
+
// in now. Persisting here keeps the plain key on the host.
|
|
498
|
+
const started = await startConsoleLogin({
|
|
499
|
+
onComplete: async (credentials) => {
|
|
500
|
+
const written = [];
|
|
501
|
+
if (credentials.apiKey !== undefined) {
|
|
502
|
+
await ctx.credentials.set(credentialRef("DASHSCOPE_API_KEY"), credentials.apiKey);
|
|
503
|
+
written.push("apiKey");
|
|
504
|
+
}
|
|
505
|
+
if (credentials.workspaceId !== undefined && scope) {
|
|
506
|
+
await scope.update({ workspaceId: credentials.workspaceId });
|
|
507
|
+
written.push("workspaceId");
|
|
508
|
+
}
|
|
509
|
+
if (written.length > 0)
|
|
510
|
+
await markSeeded(written);
|
|
511
|
+
// A completed console login is the one unambiguous signal that the
|
|
512
|
+
// account may have changed. Without this the next session would
|
|
513
|
+
// build its catalog from the previous account's services, which is
|
|
514
|
+
// worse than having no cache at all.
|
|
515
|
+
if (written.length > 0) {
|
|
516
|
+
serviceCache.invalidate();
|
|
517
|
+
void serviceCache.refresh();
|
|
518
|
+
}
|
|
519
|
+
return written;
|
|
520
|
+
},
|
|
521
|
+
});
|
|
522
|
+
sendJson(res, 200, started);
|
|
523
|
+
},
|
|
524
|
+
}), "tool-bailian-kb: autofill bridge route");
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
/** Write a JSON response. */
|
|
528
|
+
function sendJson(res, status, data) {
|
|
529
|
+
res.statusCode = status;
|
|
530
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
531
|
+
res.end(JSON.stringify(data));
|
|
532
|
+
}
|
|
533
|
+
/** Read a UTF-8 JSON body up to a size limit. */
|
|
534
|
+
function readJsonBody(req, maxBytes = 16384) {
|
|
535
|
+
return new Promise((resolve, reject) => {
|
|
536
|
+
const chunks = [];
|
|
537
|
+
let total = 0;
|
|
538
|
+
req.on("data", (chunk) => {
|
|
539
|
+
total += chunk.length;
|
|
540
|
+
if (total > maxBytes) {
|
|
541
|
+
req.destroy();
|
|
542
|
+
reject(new Error("body too large"));
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
chunks.push(chunk);
|
|
546
|
+
});
|
|
547
|
+
req.on("end", () => {
|
|
548
|
+
try {
|
|
549
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
550
|
+
}
|
|
551
|
+
catch (err) {
|
|
552
|
+
reject(err);
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
req.on("error", reject);
|
|
556
|
+
});
|
|
557
|
+
}
|