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 ADDED
@@ -0,0 +1,169 @@
1
+ # bailian-kb-dsh
2
+
3
+ 百炼知识库的 dsh 插件包(同时是 dsh bundle):在 `ctx.tools` 注册两个检索模型工具(kb_search、kb_chat),并在 skills 服务可用时注册管理面 skill。服务发现通过 bl CLI(bailian-cli)完成。
4
+
5
+ ## 安装(dsh 用户)
6
+
7
+ ```sh
8
+ dsh plugin --profile web add bailian-kb-dsh # 本地开发用绝对/相对路径
9
+ ```
10
+
11
+ 安装后 CLI 自动把 bundle 加入 profile 的层栈,无需手改 YAML。配置写入 `~/.dsh/.env`:
12
+
13
+ ```sh
14
+ BAILIAN_WORKSPACE_ID=ws-xxx # 必填:百炼工作空间 id
15
+ DASHSCOPE_API_KEY=sk-xxx # 必填:也可放 ~/.dsh/.credentials.yaml,或用设置页的“自动获取”
16
+ ```
17
+
18
+ 验证:`dsh --profile web --dump-config` 应能看到 `tool-bailian-kb` row。缺 `BAILIAN_WORKSPACE_ID` 时加载期直接报错(fail loud),不会静默跳过。卸载:`dsh plugin --profile web remove bailian-kb-dsh`。
19
+
20
+ ## 开发
21
+
22
+ 依赖 dsh 的运行时包(`@deepseek-ai/dsh-tools` 等)以 peerDependencies 声明、由 dsh 安装闭包在运行时提供。
23
+
24
+ ```sh
25
+ pnpm --filter bailian-kb-dsh run build # tsc 出 dist/ + tsdown 出 dist/web/client.js
26
+ pnpm --filter bailian-kb-dsh run typecheck # node 半 + web 半两套 tsconfig
27
+ pnpm --filter bailian-kb-dsh run test
28
+ ```
29
+
30
+ 本地联调(patch 文件受 HMR 监听):
31
+
32
+ ```sh
33
+ dsh plugin --profile dev add <本仓库>/packages/bailian-kb-dsh
34
+ ```
35
+
36
+ ## Bundle 声明
37
+
38
+ `package.json` 的 `dsh.bundle.patch` 指向 [`cordis.patch.yml`](cordis.patch.yml),向 profile 插入插件行:
39
+
40
+ ```yaml
41
+ - insert:
42
+ - id: tool-bailian-kb
43
+ name: "bailian-kb-dsh"
44
+ config:
45
+ workspaceId: !!js process.env.BAILIAN_WORKSPACE_ID
46
+ ```
47
+
48
+ `workspaceId` 只是解析链的一层,不是唯一来源:Config 同时注册为 `bailian-kb` settings namespace,patch entry 作 base 层,设置页/设置文档的用户层叠在其上;都未设置时 per-call 回退到 `BAILIAN_WORKSPACE_ID` credential。同样回退覆盖 `defaultRetrieveAgentId`(`BAILIAN_DEFAULT_RETRIEVE_AGENT_ID`)、`defaultChatAgentId`(`BAILIAN_DEFAULT_CHAT_AGENT_ID`)与 API key(`DASHSCOPE_API_KEY`,无 settings 面)。
49
+
50
+ ### 四个值的解析链
51
+
52
+ | 值 | 1️⃣ settings 用户层(设置页可编辑、回显) | 2️⃣ entry config(本 patch 或用户覆盖,作 base 层) | 3️⃣ credential(`~/.dsh/.credentials.yaml` / env) | 4️⃣ 都缺失时 |
53
+ | ----------------------------------- | ---------------------------------------- | -------------------------------------------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------- |
54
+ | `DASHSCOPE_API_KEY` | —(无 settings 面) | —(无 config 面) | ✅ | 工具调用报错并引导配置 |
55
+ | `BAILIAN_WORKSPACE_ID` | ✅ `workspaceId` | ✅ `workspaceId` | ✅ | 工具调用报错并引导配置 |
56
+ | `BAILIAN_DEFAULT_RETRIEVE_AGENT_ID` | ✅ `defaultRetrieveAgentId` | ✅ `defaultRetrieveAgentId` | ✅ | `kb_search` 无 `agent_id` 的**程序化**调用报错并附配置指引(模型侧 schema 恒必填) |
57
+ | `BAILIAN_DEFAULT_CHAT_AGENT_ID` | ✅ `defaultChatAgentId` | ✅ `defaultChatAgentId` | ✅ | `kb_chat` 无 `agent_id` 的**程序化**调用报错并附配置指引(模型侧 schema 恒必填) |
58
+
59
+ 行为参数(`endpointHost`/`agentVersion`/`chatTimeoutMs`)在 config/settings 层(设置文档可改,实时生效)。
60
+
61
+ ### Web UI 配置页
62
+
63
+ 装进 profile 后,Settings 左侧导航出现“百炼知识库”页(`settings.section` 槽位):
64
+
65
+ - **DashScope API Key** — write-only,`type=password` 遮罩输入草稿,仅显示 configured/来自环境变量 徽标;写 `~/.dsh/.credentials.yaml`
66
+ - **Bailian Workspace ID / 默认检索服务 ID / 默认对话服务 ID** — 回显:读写 `bailian-kb` settings 用户层,预填当前解析值;清空保存 = 移除用户层,回退 entry config → credential
67
+ - **自动获取** — 按钮调 Host 桥接路由 `/bailian-kb/autofill`:Host 在宿主机拉起浏览器登录百炼控制台(不经 `bl` 命令),回调落到本机 loopback 端口后直接把 API 密钥写入凭据存储、工作空间 ID 写入 settings,明文 key 不过浏览器;面板轮询到完成后自动刷新(无需再次点击)。登录 URL 始终请求签发新 key,因此每次都与当前账号配对,切换账号直接点一次即可。
68
+
69
+ 首次接入 seed:启动时若 API key / workspaceId 从未被设置过(settings、credential、env 均无值),自动从 `~/.bailian/config.json` 采纳一次;`seededFields` 字段(settings 文档内,面板不可编辑)记账已消费/已由用户管理的字段,用户主动清空的值永不会被重新填回。
70
+
71
+ 降级:远程浏览器(非 loopback,settings RPC 不可达)或未组合 settings 服务时,ID 字段退回旧的 write-only credential 控件,页面顶部显示提示。
72
+
73
+ ### 用户覆盖
74
+
75
+ 用户 patch 层在本 bundle 之上,按 id 覆盖时**替换整个 config(无 deep-merge)**:
76
+
77
+ ```yaml
78
+ # ~/.dsh/cordis.patch.yml 或 profile 的 cordis.patch.yml
79
+ - id: tool-bailian-kb
80
+ config:
81
+ defaultRetrieveAgentId: aid-search-service
82
+ defaultChatAgentId: aid-chat-service
83
+ chatTimeoutMs: 600000
84
+ ```
85
+
86
+ 禁用:`- id: tool-bailian-kb` + `disabled: true`。
87
+
88
+ ## Config
89
+
90
+ Config 同时注册为 `bailian-kb` settings namespace(`installSettingsSection`):profile patch 的 entry config 作为 base 层,用户在设置页/设置文档的修改叠在其上且实时生效(所有值每次调用经 source thunk 读取,无需重启或重注册工具)。
91
+
92
+ | 字段 | 类型 | 默认 | 语义 |
93
+ | ------------------------ | ------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
94
+ | `workspaceId` | string? | — | 百炼工作空间 id;API host 为 workspace 子域名 `https://<workspaceId>.<endpointHost>`。未设置时每次调用回退 `BAILIAN_WORKSPACE_ID` credential |
95
+ | `endpointHost` | string | `cn-beijing.maas.aliyuncs.com` | host 后缀,其他 region/私有化时替换 |
96
+ | `defaultRetrieveAgentId` | string? | — | 默认检索服务;`kb_search` 的 `agent_id` 参数 schema **恒必填**(模型永远显式传),此默认仅作用于省略 `agent_id` 的程序化调用,每次调用运行时解析(settings/config → credential) |
97
+ | `defaultChatAgentId` | string? | — | 默认对话服务;`kb_chat` 的 `agent_id` 参数 schema **恒必填**(模型永远显式传),此默认仅作用于省略 `agent_id` 的程序化调用,每次调用运行时解析(settings/config → credential) |
98
+ | `agentVersion` | string? | — | `beta`(草稿调试)或已发布版本号;不暴露给模型 |
99
+ | `chatTimeoutMs` | number | 300000 | kb_chat 超时;服务端是分钟级 agentic loop |
100
+
101
+ 凭证与回退链:`DASHSCOPE_API_KEY` 只走 `ctx.credentials` 引用(write-only,每次调用重新解析,热更换生效);`workspaceId`/`defaultRetrieveAgentId`/`defaultChatAgentId` 先取 settings 解析值(用户层 > entry config),缺失时回退同名 credential(`BAILIAN_WORKSPACE_ID`/`BAILIAN_DEFAULT_RETRIEVE_AGENT_ID`/`BAILIAN_DEFAULT_CHAT_AGENT_ID`),都没有时报错并附配置指引。注意:`agent_id` 在两个工具的 schema 中恒必填,模型路径不会触发默认服务回退;回退保留是为程序化调用与 credential 热切换。
102
+
103
+ ## 工具
104
+
105
+ | 工具 | 参数 | 返回 |
106
+ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
107
+ | `kb_search` | `query`、`agent_id`(**必填**;程序化省略时回退 defaultRetrieveAgentId)、`top_k?`(默认 5,**客户端截断**——服务端无此参数)、`images?` | chunks(text/score/来源)+ total |
108
+ | `kb_chat` | `message`、`agent_id`(**必填**;程序化省略时回退 defaultChatAgentId) | 完整答案(内部消费 SSE 流缓冲返回)+ request_id |
109
+
110
+ 两个工具的 **description 保持静态**(不含任何服务 id);可用服务清单由下述服务缓存经 `agent/pre-step` 注入为上下文消息。
111
+
112
+ ## 检索服务缓存与上下文注入
113
+
114
+ 模型要判断"该不该检索",靠的是看到本 workspace 部署了哪些检索服务。插件内部经 `/api/v1/indices/rag/app/list` 拉取该清单并缓存,**不对模型暴露服务发现工具**(`kb_service_list` 不会回归:它会把"先 list 再 search"的额外一轮重新引入);管理面仍用 bl。
115
+
116
+ ### 载体:上下文消息,不是工具描述
117
+
118
+ 清单经 `agent/pre-step` 注入为一条带 source 的 `UserMessage`(`{ kind: 'plugin', plugin: 'tool-bailian-kb/services', form: 'catalog' }`),而不是烘进 tool description。两个原因:
119
+
120
+ 1. **插件加载是每进程一次,不是每会话一次。** 描述在 `apply()` 时定型,长驻宿主里 TTL 只会被评估一次,用户在控制台新建的服务要等重启才能被感知;
121
+ 2. **重注册工具会废掉 prompt 前缀缓存**(从第一个变化的 schema token 起)。走上下文消息则让 schema 永久稳定。
122
+
123
+ **变化抑制是正确性要求,不是优化**:`pre-step` 每个“步”(= 一次模型请求)触发一次,一轮里调 5 次工具就触发 6 次。只有清单内容变化时才重发,且判定叠加**可见性**(`session.surface.nodes`)——压缩把清单消息裁掉后会自动重新注入,否则模型会静默失去清单。
124
+
125
+ ### 清单内容策略
126
+
127
+ | 情形 | 注入内容 |
128
+ | ------------------------ | ----------------------------------------------------- |
129
+ | 配了默认服务 | 只列该服务 + "另有 N 个" 提示 |
130
+ | 未配默认,deployed ≤ 10 | 全量 `agent_id` + 名称 |
131
+ | 未配默认,deployed > 10 | 按 `modify_time` 倒序取 10 条,**显式标明截断**与总数 |
132
+ | 0 个 / 拉取失败 / 无缓存 | 不注入(工具仍可用) |
133
+
134
+ 英文框架 + 服务名原样保留;空 scene 整节省略;截断必须告知(静默截断会让模型把清单当全集,进而断言"没有对应知识库")。
135
+
136
+ ### 缓存与刷新
137
+
138
+ 落点:`${DSH_HOME:-~/.dsh}/cache/bailian-kb/services-<workspaceId>.json`(临时文件 + `rename()` 原子发布,目录 `0o700`)。按 workspace 分文件是必需的:api key 只能访问自己的 workspace,而"自动获取"按钮就是为了切账号。
139
+
140
+ 存:`agent_id` / `agent_name` / `scene` / `status` / `modify_time`,预留 `description`(待列表接口返回)。**不存 `pipeline_list`**——它不稳定携带 `pipeline_name`,做不了知识库标签。
141
+
142
+ | 刷新触发点 | 模型何时看见 |
143
+ | --------------------------------------------------------- | ------------------------------------ |
144
+ | pre-step 间隔调度(超 TTL 30 分钟,后台异步,**不阻塞**) | 下一步 |
145
+ | 控制台登录成功(`/bailian-kb/autofill` 回调) | 下一步 |
146
+ | 调用撞 4xx(agent_id 已失效) | **本步**,刷新后的列表追加进错误消息 |
147
+ | workspaceId / apiKey 变更 | 下一步 |
148
+
149
+ 刷新失败只 warn,保留旧文档;并发刷新共享一个请求(pre-step 每步都会检查)。pre-step 监听器**永不抛异常**——抛出会使用户当前这一步失败。未组合 `agents` 的 headless 装配只是没有清单,工具照常可用。
150
+
151
+ ## 错误语义
152
+
153
+ - HTTP 错误:4xx 时刷新服务缓存并把当前可用服务追加进错误消息(这两个接口上 `agent_id` 是唯一的调用方标识符,所以 4xx 大多是 id 已失效);5xx 与刷新本身失败则原错误透传;
154
+ - 凭证缺失:指向 `~/.dsh/.env` / `.credentials.yaml` 配置方式与控制台取 key 页面;
155
+ - chat 超时:说明服务端多轮检索特性,建议重试或改用 `kb_search`;
156
+ - 服务端错误体截断至 500 字符进入错误信息(优先 `code: message`)。
157
+
158
+ ## 管理面 skill
159
+
160
+ `skills/bailian-kb/SKILL.md` 随包分发,插件通过 `ctx.inject(['skills'])` 在 skills 服务可用时以 `source: 'bundled'` 运行时注册;无 skills 服务的组合(headless 最小装配)不受影响。文件的 YAML frontmatter 是 name / description 的**单一事实源**,注册时会被剥离(`SkillDefinition.content` 契约上是已去元数据的正文,而 runtime 注册路径不做任何解析)。
161
+
162
+ 内容:bl CLI 安装/鉴权/workspace 解析、建库→上传→部署工作流、服务清单的行为语义。**skill 不承担"该不该检索"的引导**(那是工具描述与上下文清单的事:skill 正文要模型先决定加载才能读到,是二阶决策);它反过来承担一件工具做不到的事:**引导 agent 在 `service create` 时把服务名写清楚**。无 desc 时服务名是唯一语义来源,管理面的动作直接决定检索面的效果。
163
+
164
+ ## Known Limitations
165
+
166
+ - kb_chat 执行期无进展显示(缓冲式)。
167
+ - `top_k` 是客户端截断:请求体不含该参数,服务端返回条数由检索服务配置决定,截断只影响进入模型上下文的量。
168
+ - **服务画像的质量上限取决于服务名**:`service list` 接口当前不返回描述字段,所以模型只能靠 `agent_name` 判断一个服务能查什么。名字模糊的部署引导能力接近于零。列表接口补齐描述字段后只需改三处(`api-types` 补字段名 → `services.ts` 解析 → `buildServiceCatalog` 追加并截断到 200 字符),缓存已预留 `description` 键,无需迁移。
169
+ - 拉取每个 scene 最多 2 页,超出时标 `truncated` 并在清单里告知。
@@ -0,0 +1,13 @@
1
+ # bailian-kb-dsh: inserts the Bailian knowledge-base consumer over dsh-base.
2
+ # workspaceId here is one resolution layer, not the only one: a config value
3
+ # (this env read included) wins per call; when it is unset the plugin resolves
4
+ # the BAILIAN_WORKSPACE_ID credential instead (web UI card or
5
+ # ~/.dsh/.credentials.yaml). The same fallback covers defaultRetrieveAgentId
6
+ # via BAILIAN_DEFAULT_RETRIEVE_AGENT_ID, defaultChatAgentId via
7
+ # BAILIAN_DEFAULT_CHAT_AGENT_ID, and the API key via DASHSCOPE_API_KEY.
8
+
9
+ - insert:
10
+ - id: tool-bailian-kb
11
+ name: "bailian-kb-dsh"
12
+ config:
13
+ workspaceId: !!js process.env.BAILIAN_WORKSPACE_ID
@@ -0,0 +1,89 @@
1
+ /** Request/response fields of the DashScope search and chat endpoints. */
2
+ /** Retrieval-service scenes; the server requires one per list query. */
3
+ export type ServiceScene = "chat" | "search";
4
+ export interface ServiceListRequest {
5
+ agent_scene: ServiceScene;
6
+ /** Filter to deployed services (spelling required by the server). */
7
+ agent_status?: "deployed";
8
+ agent_name?: string;
9
+ page_number: number;
10
+ page_size: number;
11
+ }
12
+ /**
13
+ * One row of the service list.
14
+ *
15
+ * `description` is not included: the listing endpoint does not currently return
16
+ * it, even for services created with a description. Add it here once it starts
17
+ * appearing on the wire.
18
+ *
19
+ * `pipeline_list` is typed but deliberately never consumed: it can omit
20
+ * `pipeline_name` or come back empty, so it cannot serve as a knowledge-base
21
+ * label.
22
+ */
23
+ export interface ServiceListRow {
24
+ agent_id?: string;
25
+ agent_name?: string;
26
+ agent_scene?: string;
27
+ agent_status?: string;
28
+ agent_version?: string;
29
+ create_time?: string;
30
+ modify_time?: string;
31
+ pipeline_list?: {
32
+ pipeline_id?: string;
33
+ pipeline_name?: string;
34
+ }[];
35
+ }
36
+ export interface ServiceListResponse {
37
+ code?: string;
38
+ message?: string;
39
+ data?: {
40
+ total_count?: number;
41
+ rows?: ServiceListRow[];
42
+ };
43
+ }
44
+ export interface SearchRequest {
45
+ query: string;
46
+ agent_id: string;
47
+ agent_version?: string;
48
+ images?: string[];
49
+ }
50
+ export interface SearchResponse {
51
+ request_id?: string;
52
+ data?: {
53
+ total?: number;
54
+ nodes?: {
55
+ score: number;
56
+ text: string;
57
+ metadata?: Record<string, unknown>;
58
+ }[];
59
+ };
60
+ }
61
+ export interface ChatRequest {
62
+ input: {
63
+ messages: {
64
+ role: "user" | "assistant";
65
+ content: string;
66
+ }[];
67
+ };
68
+ parameters: {
69
+ agent_options: {
70
+ agent_id: string;
71
+ agent_version?: string;
72
+ };
73
+ };
74
+ stream: true;
75
+ }
76
+ export interface ChatStreamChunk {
77
+ output?: {
78
+ choices?: {
79
+ message?: {
80
+ content?: string;
81
+ extra?: {
82
+ step_change?: string;
83
+ };
84
+ };
85
+ finish_reason?: string;
86
+ }[];
87
+ };
88
+ request_id?: string;
89
+ }
@@ -0,0 +1,2 @@
1
+ /** Request/response fields of the DashScope search and chat endpoints. */
2
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Host-side bridge to the locally installed `bl` CLI (bailian-cli): reads the
3
+ * credentials an earlier `bl auth login` already stored, so a user who has
4
+ * already set the CLI up does not have to configure this plugin a second time.
5
+ *
6
+ * Reading the CLI's credential file (`~/.bailian/config.json`) is the only way
7
+ * to obtain the value programmatically — CLI commands mask stored keys on
8
+ * output, so there is nothing to parse from stdout.
9
+ *
10
+ * Starting a login is NOT done through the CLI; see `console-login.ts`.
11
+ */
12
+ /** The two values this plugin can adopt from the bl CLI credential file. */
13
+ export interface BlCliConfig {
14
+ /** DashScope api key (`api_key`, top-level default profile). */
15
+ apiKey?: string;
16
+ /** Bailian workspace id (`workspace_id`), present when the console login callback carried one. */
17
+ workspaceId?: string;
18
+ }
19
+ /** Default location of the bl CLI credential file (default profile at top level). */
20
+ export declare function blCliConfigPath(): string;
21
+ /**
22
+ * Read the api key and workspace id from the bl CLI credential file.
23
+ * Best-effort: a missing, unreadable, or malformed file reads as empty —
24
+ * callers treat that the same as "the CLI has not logged in yet".
25
+ * @param configPath - override for tests; defaults to `~/.bailian/config.json`.
26
+ * @returns the values found; fields are absent rather than blank.
27
+ */
28
+ export declare function readBlCliConfig(configPath?: string): BlCliConfig;
package/dist/bl-cli.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Host-side bridge to the locally installed `bl` CLI (bailian-cli): reads the
3
+ * credentials an earlier `bl auth login` already stored, so a user who has
4
+ * already set the CLI up does not have to configure this plugin a second time.
5
+ *
6
+ * Reading the CLI's credential file (`~/.bailian/config.json`) is the only way
7
+ * to obtain the value programmatically — CLI commands mask stored keys on
8
+ * output, so there is nothing to parse from stdout.
9
+ *
10
+ * Starting a login is NOT done through the CLI; see `console-login.ts`.
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { join } from "node:path";
15
+ /** Default location of the bl CLI credential file (default profile at top level). */
16
+ export function blCliConfigPath() {
17
+ return join(homedir(), ".bailian", "config.json");
18
+ }
19
+ /**
20
+ * Read the api key and workspace id from the bl CLI credential file.
21
+ * Best-effort: a missing, unreadable, or malformed file reads as empty —
22
+ * callers treat that the same as "the CLI has not logged in yet".
23
+ * @param configPath - override for tests; defaults to `~/.bailian/config.json`.
24
+ * @returns the values found; fields are absent rather than blank.
25
+ */
26
+ export function readBlCliConfig(configPath = blCliConfigPath()) {
27
+ try {
28
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
29
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
30
+ return {};
31
+ const record = parsed;
32
+ const apiKey = typeof record.api_key === "string" && record.api_key.trim() !== ""
33
+ ? record.api_key.trim()
34
+ : undefined;
35
+ const workspaceId = typeof record.workspace_id === "string" && record.workspace_id.trim() !== ""
36
+ ? record.workspace_id.trim()
37
+ : undefined;
38
+ return {
39
+ ...(apiKey !== undefined ? { apiKey } : {}),
40
+ ...(workspaceId !== undefined ? { workspaceId } : {}),
41
+ };
42
+ }
43
+ catch (_unreadable) {
44
+ return {};
45
+ }
46
+ }
package/dist/chat.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /** Buffered consumption of the knowledge chat SSE stream: deltas concatenate into one complete answer. */
2
+ export interface ChatResult {
3
+ answer: string;
4
+ requestId?: string;
5
+ }
6
+ /**
7
+ * Consume one chat SSE response to completion.
8
+ * @param res - the SSE response from KbClient.postSse.
9
+ * @returns the concatenated answer and the last seen request id.
10
+ */
11
+ export declare function consumeChatStream(res: Response): Promise<ChatResult>;
package/dist/chat.js ADDED
@@ -0,0 +1,44 @@
1
+ /** Buffered consumption of the knowledge chat SSE stream: deltas concatenate into one complete answer. */
2
+ import { KbApiError } from "./client.js";
3
+ import { parseSseStream } from "./sse.js";
4
+ /**
5
+ * Consume one chat SSE response to completion.
6
+ * @param res - the SSE response from KbClient.postSse.
7
+ * @returns the concatenated answer and the last seen request id.
8
+ */
9
+ export async function consumeChatStream(res) {
10
+ if (!res.body)
11
+ throw new KbApiError("knowledge chat returned no response body");
12
+ let answer = "";
13
+ let requestId;
14
+ for await (const event of parseSseStream(res.body)) {
15
+ if (event.data === "[DONE]")
16
+ break;
17
+ if (event.event === "error") {
18
+ let message = `knowledge chat stream error: ${event.data}`;
19
+ try {
20
+ const err = JSON.parse(event.data);
21
+ if (err.message)
22
+ message = `knowledge chat stream error${err.code ? ` (${err.code})` : ""}: ${err.message}`;
23
+ }
24
+ catch {
25
+ /* non-JSON error payload: keep the raw data in the message */
26
+ }
27
+ throw new KbApiError(message);
28
+ }
29
+ let parsed;
30
+ try {
31
+ parsed = JSON.parse(event.data);
32
+ }
33
+ catch {
34
+ continue;
35
+ } // unparseable keep-alive/comment payloads carry no answer content
36
+ if (parsed.request_id)
37
+ requestId = parsed.request_id;
38
+ for (const choice of parsed.output?.choices ?? []) {
39
+ if (choice.message?.content)
40
+ answer += choice.message.content;
41
+ }
42
+ }
43
+ return { answer, requestId };
44
+ }
@@ -0,0 +1,40 @@
1
+ /** Shared HTTP client for the knowledge endpoints: per-call Bearer auth, JSON/SSE POST, and error translation. */
2
+ /** One knowledge API failure: HTTP status plus a bounded server-body summary. */
3
+ export declare class KbApiError extends Error {
4
+ readonly status?: number | undefined;
5
+ constructor(message: string, status?: number | undefined);
6
+ }
7
+ export interface KbClientOptions {
8
+ /** Resolves the current workspace id per call (patch config or credential); throws with guidance when unconfigured. */
9
+ resolveWorkspaceId: () => Promise<string>;
10
+ endpointHost: string;
11
+ /** Service version forwarded on search/chat when set (deployment debug choice). */
12
+ agentVersion?: string;
13
+ /** Resolves the current DASHSCOPE_API_KEY per call; throws with guidance when unconfigured. */
14
+ resolveApiKey: () => Promise<string>;
15
+ /** Test seam; defaults to global fetch. */
16
+ fetchImpl?: typeof fetch;
17
+ }
18
+ export declare class KbClient {
19
+ private readonly opts;
20
+ constructor(opts: KbClientOptions);
21
+ /** The deployment's configured service version, exposed for request builders. */
22
+ get agentVersion(): string | undefined;
23
+ private post;
24
+ /**
25
+ * POST one JSON request and parse the JSON response.
26
+ * @param path - one KB_PATHS value.
27
+ * @param body - JSON-serializable request body.
28
+ * @param signal - optional abort/timeout signal.
29
+ * @returns the parsed response.
30
+ */
31
+ postJson<T>(path: string, body: unknown, signal?: AbortSignal): Promise<T>;
32
+ /**
33
+ * POST one JSON request expecting an SSE response stream.
34
+ * @param path - one KB_PATHS value.
35
+ * @param body - JSON-serializable request body.
36
+ * @param signal - abort/timeout signal (kb_chat passes its configured timeout).
37
+ * @returns the raw Response whose body is the SSE stream.
38
+ */
39
+ postSse(path: string, body: unknown, signal?: AbortSignal): Promise<Response>;
40
+ }
package/dist/client.js ADDED
@@ -0,0 +1,76 @@
1
+ /** Shared HTTP client for the knowledge endpoints: per-call Bearer auth, JSON/SSE POST, and error translation. */
2
+ import { kbEndpoint } from "./endpoints.js";
3
+ /** Maximum error-body characters kept in a translated message. */
4
+ const ERROR_BODY_LIMIT = 500;
5
+ /** One knowledge API failure: HTTP status plus a bounded server-body summary. */
6
+ export class KbApiError extends Error {
7
+ status;
8
+ constructor(message, status) {
9
+ super(message);
10
+ this.status = status;
11
+ this.name = "KbApiError";
12
+ }
13
+ }
14
+ export class KbClient {
15
+ opts;
16
+ constructor(opts) {
17
+ this.opts = opts;
18
+ }
19
+ /** The deployment's configured service version, exposed for request builders. */
20
+ get agentVersion() {
21
+ return this.opts.agentVersion;
22
+ }
23
+ async post(path, body, accept, signal) {
24
+ const [apiKey, workspaceId] = await Promise.all([
25
+ this.opts.resolveApiKey(),
26
+ this.opts.resolveWorkspaceId(),
27
+ ]);
28
+ const fetchImpl = this.opts.fetchImpl ?? fetch;
29
+ const url = kbEndpoint(this.opts.endpointHost, workspaceId, path);
30
+ const res = await fetchImpl(url, {
31
+ method: "POST",
32
+ headers: {
33
+ Authorization: `Bearer ${apiKey}`,
34
+ "Content-Type": "application/json",
35
+ Accept: accept,
36
+ },
37
+ body: JSON.stringify(body),
38
+ signal,
39
+ });
40
+ if (!res.ok) {
41
+ const raw = (await res.text().catch(() => "")).slice(0, ERROR_BODY_LIMIT);
42
+ let detail = raw;
43
+ try {
44
+ const parsed = JSON.parse(raw);
45
+ if (parsed.message)
46
+ detail = parsed.code ? `${parsed.code}: ${parsed.message}` : parsed.message;
47
+ }
48
+ catch {
49
+ /* non-JSON error body: keep the bounded raw text */
50
+ }
51
+ throw new KbApiError(`knowledge API ${path} failed (HTTP ${res.status}): ${detail}`, res.status);
52
+ }
53
+ return res;
54
+ }
55
+ /**
56
+ * POST one JSON request and parse the JSON response.
57
+ * @param path - one KB_PATHS value.
58
+ * @param body - JSON-serializable request body.
59
+ * @param signal - optional abort/timeout signal.
60
+ * @returns the parsed response.
61
+ */
62
+ async postJson(path, body, signal) {
63
+ const res = await this.post(path, body, "application/json", signal);
64
+ return (await res.json());
65
+ }
66
+ /**
67
+ * POST one JSON request expecting an SSE response stream.
68
+ * @param path - one KB_PATHS value.
69
+ * @param body - JSON-serializable request body.
70
+ * @param signal - abort/timeout signal (kb_chat passes its configured timeout).
71
+ * @returns the raw Response whose body is the SSE stream.
72
+ */
73
+ async postSse(path, body, signal) {
74
+ return await this.post(path, body, "text/event-stream", signal);
75
+ }
76
+ }
@@ -0,0 +1,83 @@
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
+ /** Credentials the console callback can carry. */
15
+ export interface ConsoleLoginCredentials {
16
+ /** Freshly issued DashScope api key. */
17
+ apiKey?: string;
18
+ /** Workspace id of the account that signed in. */
19
+ workspaceId?: string;
20
+ }
21
+ /**
22
+ * Where the login flow stands. Deliberately carries no secret: the plain key
23
+ * is handed to the completion callback and never retained here, so polling
24
+ * this state from the browser cannot leak it.
25
+ */
26
+ export type ConsoleLoginState = {
27
+ phase: "idle";
28
+ } | {
29
+ phase: "waiting";
30
+ loginUrl: string;
31
+ } | {
32
+ phase: "done";
33
+ fields: string[];
34
+ } | {
35
+ phase: "failed";
36
+ reason: string;
37
+ };
38
+ /** Read the current flow state (safe to expose to the panel). */
39
+ export declare function consoleLoginState(): ConsoleLoginState;
40
+ /**
41
+ * Parse a callback body as JSON (optionally wrapped in `data`) or as form
42
+ * encoding. Content-type is a hint only: both shapes occur in practice, so both
43
+ * are attempted.
44
+ * @param raw - the raw request body.
45
+ * @returns the flattened fields; an unparseable body yields no fields.
46
+ */
47
+ export declare function parseCallbackBody(raw: string): Record<string, unknown>;
48
+ /**
49
+ * Pick the api key and workspace id out of a callback's fields, query
50
+ * parameters taking priority over the body.
51
+ * @param query - the callback URL's query parameters.
52
+ * @param body - the parsed callback body.
53
+ * @returns the credentials found; fields are absent rather than blank.
54
+ */
55
+ export declare function pickCallbackCredentials(query: Record<string, unknown>, body: Record<string, unknown>): ConsoleLoginCredentials;
56
+ /** Outcome of asking the host to start a console login. */
57
+ export type ConsoleLoginStart = {
58
+ status: "started";
59
+ loginUrl: string;
60
+ } | {
61
+ status: "already-running";
62
+ loginUrl: string;
63
+ } | {
64
+ status: "failed";
65
+ reason: string;
66
+ };
67
+ /**
68
+ * Start a console login on the host: binds a loopback listener, opens the
69
+ * console login page in the host's default browser, and hands the credentials
70
+ * from the callback to `onComplete` (which persists them). Fire-and-forget —
71
+ * this resolves once the browser has been opened; poll {@link consoleLoginState}
72
+ * for the outcome.
73
+ * @param opts.site - console site, `domestic` (default) or `international`.
74
+ * @param opts.onComplete - persists the received credentials; its resolved
75
+ * field names become the `done` state's `fields`.
76
+ * @returns whether the flow started, plus the URL to open manually if needed.
77
+ */
78
+ export declare function startConsoleLogin(opts: {
79
+ site?: string;
80
+ onComplete: (credentials: ConsoleLoginCredentials) => Promise<string[]>;
81
+ }): Promise<ConsoleLoginStart>;
82
+ /** Abandon an in-flight login (closes the listener). */
83
+ export declare function cancelConsoleLogin(): void;