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,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-disk cache of the workspace's deployed retrieval services.
|
|
3
|
+
*
|
|
4
|
+
* Landing spot: `${DSH_HOME:-~/.dsh}/cache/bailian-kb/services-<workspaceId>.json`.
|
|
5
|
+
* Per-workspace files are required: an api key is scoped to one workspace, and
|
|
6
|
+
* the panel's "autofill" button exists to switch accounts, so one shared file
|
|
7
|
+
* would blend services from different accounts.
|
|
8
|
+
*
|
|
9
|
+
* Why not `ctx.storage`: the storage hub is absent from every shipped agent
|
|
10
|
+
* preset, so `inject(['storage'])` may never fire for a third-party plugin, and
|
|
11
|
+
* the JSON backend's on-disk location is decided by its own `root` config — the
|
|
12
|
+
* plugin could not tell anyone where the data went. Why not `settings.yaml`: that
|
|
13
|
+
* document is the user's, and it hot-reloads, so writing machine-refreshed data
|
|
14
|
+
* there both fights the user for the file and republishes configuration for no
|
|
15
|
+
* reason.
|
|
16
|
+
*
|
|
17
|
+
* Every read is best-effort and total: a missing, malformed, foreign, or
|
|
18
|
+
* stale-schema file reads as a miss. Callers run inside `agent/pre-step`, where a
|
|
19
|
+
* throw fails the user's step.
|
|
20
|
+
*/
|
|
21
|
+
import type { KbClient } from "./client.js";
|
|
22
|
+
import { type ServiceEntry } from "./services.js";
|
|
23
|
+
/** Refresh interval. Evaluated per `agent/pre-step`, so a short window genuinely takes effect. */
|
|
24
|
+
export declare const CACHE_TTL_MS: number;
|
|
25
|
+
/**
|
|
26
|
+
* Refresh interval applied when the cached list is EMPTY.
|
|
27
|
+
*
|
|
28
|
+
* An empty list is almost never a settled fact — it is the intermediate state of
|
|
29
|
+
* a workspace being set up. Caching that negative result for the full TTL breaks
|
|
30
|
+
* the standard first-run path: configure the plugin against a fresh workspace (0
|
|
31
|
+
* services) → create a knowledge base and a service → and then wait up to half an
|
|
32
|
+
* hour before the catalog appears. Re-asking every minute while the answer is
|
|
33
|
+
* "nothing yet" has a bounded cost and removes that trap.
|
|
34
|
+
*/
|
|
35
|
+
export declare const EMPTY_CACHE_TTL_MS: number;
|
|
36
|
+
/** The stored document. */
|
|
37
|
+
export interface ServiceCacheDocument {
|
|
38
|
+
version: number;
|
|
39
|
+
/** Epoch millis of the fetch that produced `entries`. */
|
|
40
|
+
fetchedAt: number;
|
|
41
|
+
/** Guards against reading a file written for another account or region. */
|
|
42
|
+
workspaceId: string;
|
|
43
|
+
endpointHost: string;
|
|
44
|
+
entries: ServiceEntry[];
|
|
45
|
+
total: number;
|
|
46
|
+
truncated: boolean;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Build the cache path for one workspace.
|
|
50
|
+
* @param workspaceId - the resolved Bailian workspace id.
|
|
51
|
+
* @param home - override for tests; defaults to `$DSH_HOME` or `~/.dsh`.
|
|
52
|
+
* @returns the absolute file path.
|
|
53
|
+
*/
|
|
54
|
+
export declare function serviceCachePath(workspaceId: string, home?: string): string;
|
|
55
|
+
/**
|
|
56
|
+
* Read a cache document, validating it belongs to this workspace and schema.
|
|
57
|
+
* @param path - the cache file path.
|
|
58
|
+
* @param workspaceId - the workspace the caller is serving.
|
|
59
|
+
* @param endpointHost - the host the caller is serving.
|
|
60
|
+
* @returns the document, or undefined for any miss (absent, malformed, foreign, or wrong version).
|
|
61
|
+
*/
|
|
62
|
+
export declare function readServiceCache(path: string, workspaceId: string, endpointHost: string): ServiceCacheDocument | undefined;
|
|
63
|
+
/**
|
|
64
|
+
* Publish a cache document atomically: a reader either sees the previous file or
|
|
65
|
+
* the complete new one, never a half-written mix.
|
|
66
|
+
* @param path - the cache file path.
|
|
67
|
+
* @param doc - the document to store.
|
|
68
|
+
*/
|
|
69
|
+
export declare function writeServiceCache(path: string, doc: ServiceCacheDocument): void;
|
|
70
|
+
/** What the settings panel shows about the cache; see {@link ServiceCache.status}. */
|
|
71
|
+
export interface ServiceCacheStatus {
|
|
72
|
+
workspaceId: string;
|
|
73
|
+
/** Epoch millis of the last successful fetch; absent when nothing is cached. */
|
|
74
|
+
fetchedAt?: number;
|
|
75
|
+
searchCount: number;
|
|
76
|
+
chatCount: number;
|
|
77
|
+
/** Server-reported total, which exceeds the counts above when the fetch was capped. */
|
|
78
|
+
total: number;
|
|
79
|
+
truncated: boolean;
|
|
80
|
+
stale: boolean;
|
|
81
|
+
}
|
|
82
|
+
export interface ServiceCacheOptions {
|
|
83
|
+
client: KbClient;
|
|
84
|
+
/** Resolves the current workspace id; a failure means "not configured yet". */
|
|
85
|
+
resolveWorkspaceId: () => Promise<string>;
|
|
86
|
+
endpointHost: string;
|
|
87
|
+
/** Reports refresh failures without escalating them. */
|
|
88
|
+
warn: (message: string) => void;
|
|
89
|
+
/** Test seams. */
|
|
90
|
+
home?: string;
|
|
91
|
+
now?: () => number;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The service cache: a synchronous in-memory view over the on-disk document,
|
|
95
|
+
* plus a deduplicated background refresh.
|
|
96
|
+
*/
|
|
97
|
+
export declare class ServiceCache {
|
|
98
|
+
private readonly opts;
|
|
99
|
+
/** Last document read or written; undefined until one is available. */
|
|
100
|
+
private document;
|
|
101
|
+
/** The in-flight refresh, if any. One per instance: `pre-step` asks on every model request. */
|
|
102
|
+
private inFlight;
|
|
103
|
+
/** Workspace of {@link document}, so a workspace switch invalidates in memory too. */
|
|
104
|
+
private loadedFor;
|
|
105
|
+
constructor(opts: ServiceCacheOptions);
|
|
106
|
+
private get now();
|
|
107
|
+
/**
|
|
108
|
+
* The cached entries for a workspace, loading the file on first use.
|
|
109
|
+
* Synchronous and total — safe to call from `agent/pre-step`.
|
|
110
|
+
* @param workspaceId - the workspace being served.
|
|
111
|
+
* @returns the document, or undefined when nothing usable is cached.
|
|
112
|
+
*/
|
|
113
|
+
peek(workspaceId: string): ServiceCacheDocument | undefined;
|
|
114
|
+
/**
|
|
115
|
+
* Whether the cached document is missing or older than its TTL.
|
|
116
|
+
* An empty list expires on the much shorter {@link EMPTY_CACHE_TTL_MS}.
|
|
117
|
+
* @param workspaceId - the workspace being served.
|
|
118
|
+
* @returns true when a refresh is due.
|
|
119
|
+
*/
|
|
120
|
+
isStale(workspaceId: string): boolean;
|
|
121
|
+
/** Drop the in-memory view and force the next `peek` to re-read from disk. */
|
|
122
|
+
invalidate(): void;
|
|
123
|
+
/**
|
|
124
|
+
* A diagnostic snapshot for the settings panel.
|
|
125
|
+
*
|
|
126
|
+
* The panel exists because this cache's staleness is otherwise invisible: a
|
|
127
|
+
* developer whose agent silently stops retrieving cannot tell an empty
|
|
128
|
+
* workspace from a stale list without reading the JSON file. `fetchedAt` plus
|
|
129
|
+
* the per-scene counts answer that in one glance.
|
|
130
|
+
* @param workspaceId - the workspace being served.
|
|
131
|
+
* @returns the snapshot; `fetchedAt` is undefined when nothing is cached.
|
|
132
|
+
*/
|
|
133
|
+
status(workspaceId: string): ServiceCacheStatus;
|
|
134
|
+
/**
|
|
135
|
+
* The cached entries of one scene, most recently modified first.
|
|
136
|
+
* Backs the panel's service picker, which exists so a default service can be
|
|
137
|
+
* chosen by name instead of by pasting a 36-character hex id.
|
|
138
|
+
* @param workspaceId - the workspace being served.
|
|
139
|
+
* @param scene - `search` or `chat`.
|
|
140
|
+
* @returns the entries, newest first.
|
|
141
|
+
*/
|
|
142
|
+
entriesFor(workspaceId: string, scene: ServiceEntry["scene"]): ServiceEntry[];
|
|
143
|
+
/**
|
|
144
|
+
* Fetch and store the current service list.
|
|
145
|
+
* Never rejects: failures are warned and leave the previous document in place.
|
|
146
|
+
* Concurrent calls share one request.
|
|
147
|
+
* @returns a promise resolving once the attempt finishes.
|
|
148
|
+
*/
|
|
149
|
+
refresh(): Promise<void>;
|
|
150
|
+
private runRefresh;
|
|
151
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-disk cache of the workspace's deployed retrieval services.
|
|
3
|
+
*
|
|
4
|
+
* Landing spot: `${DSH_HOME:-~/.dsh}/cache/bailian-kb/services-<workspaceId>.json`.
|
|
5
|
+
* Per-workspace files are required: an api key is scoped to one workspace, and
|
|
6
|
+
* the panel's "autofill" button exists to switch accounts, so one shared file
|
|
7
|
+
* would blend services from different accounts.
|
|
8
|
+
*
|
|
9
|
+
* Why not `ctx.storage`: the storage hub is absent from every shipped agent
|
|
10
|
+
* preset, so `inject(['storage'])` may never fire for a third-party plugin, and
|
|
11
|
+
* the JSON backend's on-disk location is decided by its own `root` config — the
|
|
12
|
+
* plugin could not tell anyone where the data went. Why not `settings.yaml`: that
|
|
13
|
+
* document is the user's, and it hot-reloads, so writing machine-refreshed data
|
|
14
|
+
* there both fights the user for the file and republishes configuration for no
|
|
15
|
+
* reason.
|
|
16
|
+
*
|
|
17
|
+
* Every read is best-effort and total: a missing, malformed, foreign, or
|
|
18
|
+
* stale-schema file reads as a miss. Callers run inside `agent/pre-step`, where a
|
|
19
|
+
* throw fails the user's step.
|
|
20
|
+
*/
|
|
21
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
22
|
+
import { homedir } from "node:os";
|
|
23
|
+
import { dirname, join } from "node:path";
|
|
24
|
+
import { listServices } from "./services.js";
|
|
25
|
+
/** Bumped whenever the stored shape changes; a mismatch reads as a miss (no migration). */
|
|
26
|
+
const CACHE_VERSION = 1;
|
|
27
|
+
/** Refresh interval. Evaluated per `agent/pre-step`, so a short window genuinely takes effect. */
|
|
28
|
+
export const CACHE_TTL_MS = 30 * 60 * 1000;
|
|
29
|
+
/**
|
|
30
|
+
* Refresh interval applied when the cached list is EMPTY.
|
|
31
|
+
*
|
|
32
|
+
* An empty list is almost never a settled fact — it is the intermediate state of
|
|
33
|
+
* a workspace being set up. Caching that negative result for the full TTL breaks
|
|
34
|
+
* the standard first-run path: configure the plugin against a fresh workspace (0
|
|
35
|
+
* services) → create a knowledge base and a service → and then wait up to half an
|
|
36
|
+
* hour before the catalog appears. Re-asking every minute while the answer is
|
|
37
|
+
* "nothing yet" has a bounded cost and removes that trap.
|
|
38
|
+
*/
|
|
39
|
+
export const EMPTY_CACHE_TTL_MS = 60 * 1000;
|
|
40
|
+
/** Resolve the harness home the same way `settings-file` does. */
|
|
41
|
+
function dshHome() {
|
|
42
|
+
const fromEnv = process.env.DSH_HOME;
|
|
43
|
+
return fromEnv !== undefined && fromEnv !== "" ? fromEnv : join(homedir(), ".dsh");
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Build the cache path for one workspace.
|
|
47
|
+
* @param workspaceId - the resolved Bailian workspace id.
|
|
48
|
+
* @param home - override for tests; defaults to `$DSH_HOME` or `~/.dsh`.
|
|
49
|
+
* @returns the absolute file path.
|
|
50
|
+
*/
|
|
51
|
+
export function serviceCachePath(workspaceId, home = dshHome()) {
|
|
52
|
+
return join(home, "cache", "bailian-kb", `services-${workspaceId}.json`);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Read a cache document, validating it belongs to this workspace and schema.
|
|
56
|
+
* @param path - the cache file path.
|
|
57
|
+
* @param workspaceId - the workspace the caller is serving.
|
|
58
|
+
* @param endpointHost - the host the caller is serving.
|
|
59
|
+
* @returns the document, or undefined for any miss (absent, malformed, foreign, or wrong version).
|
|
60
|
+
*/
|
|
61
|
+
export function readServiceCache(path, workspaceId, endpointHost) {
|
|
62
|
+
let parsed;
|
|
63
|
+
try {
|
|
64
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
65
|
+
}
|
|
66
|
+
catch (_unreadableOrMalformed) {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
|
70
|
+
return undefined;
|
|
71
|
+
const doc = parsed;
|
|
72
|
+
if (doc.version !== CACHE_VERSION)
|
|
73
|
+
return undefined;
|
|
74
|
+
if (doc.workspaceId !== workspaceId || doc.endpointHost !== endpointHost)
|
|
75
|
+
return undefined;
|
|
76
|
+
if (typeof doc.fetchedAt !== "number" || !Array.isArray(doc.entries))
|
|
77
|
+
return undefined;
|
|
78
|
+
return {
|
|
79
|
+
version: CACHE_VERSION,
|
|
80
|
+
fetchedAt: doc.fetchedAt,
|
|
81
|
+
workspaceId,
|
|
82
|
+
endpointHost,
|
|
83
|
+
entries: doc.entries,
|
|
84
|
+
total: typeof doc.total === "number" ? doc.total : doc.entries.length,
|
|
85
|
+
truncated: doc.truncated === true,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Publish a cache document atomically: a reader either sees the previous file or
|
|
90
|
+
* the complete new one, never a half-written mix.
|
|
91
|
+
* @param path - the cache file path.
|
|
92
|
+
* @param doc - the document to store.
|
|
93
|
+
*/
|
|
94
|
+
export function writeServiceCache(path, doc) {
|
|
95
|
+
const dir = dirname(path);
|
|
96
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
97
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
98
|
+
writeFileSync(temp, `${JSON.stringify(doc, undefined, 2)}\n`, { mode: 0o600 });
|
|
99
|
+
renameSync(temp, path);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The service cache: a synchronous in-memory view over the on-disk document,
|
|
103
|
+
* plus a deduplicated background refresh.
|
|
104
|
+
*/
|
|
105
|
+
export class ServiceCache {
|
|
106
|
+
opts;
|
|
107
|
+
/** Last document read or written; undefined until one is available. */
|
|
108
|
+
document;
|
|
109
|
+
/** The in-flight refresh, if any. One per instance: `pre-step` asks on every model request. */
|
|
110
|
+
inFlight;
|
|
111
|
+
/** Workspace of {@link document}, so a workspace switch invalidates in memory too. */
|
|
112
|
+
loadedFor;
|
|
113
|
+
constructor(opts) {
|
|
114
|
+
this.opts = opts;
|
|
115
|
+
}
|
|
116
|
+
get now() {
|
|
117
|
+
return (this.opts.now ?? Date.now)();
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The cached entries for a workspace, loading the file on first use.
|
|
121
|
+
* Synchronous and total — safe to call from `agent/pre-step`.
|
|
122
|
+
* @param workspaceId - the workspace being served.
|
|
123
|
+
* @returns the document, or undefined when nothing usable is cached.
|
|
124
|
+
*/
|
|
125
|
+
peek(workspaceId) {
|
|
126
|
+
if (this.loadedFor !== workspaceId) {
|
|
127
|
+
this.document = readServiceCache(serviceCachePath(workspaceId, this.opts.home ?? dshHome()), workspaceId, this.opts.endpointHost);
|
|
128
|
+
this.loadedFor = workspaceId;
|
|
129
|
+
}
|
|
130
|
+
return this.document;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Whether the cached document is missing or older than its TTL.
|
|
134
|
+
* An empty list expires on the much shorter {@link EMPTY_CACHE_TTL_MS}.
|
|
135
|
+
* @param workspaceId - the workspace being served.
|
|
136
|
+
* @returns true when a refresh is due.
|
|
137
|
+
*/
|
|
138
|
+
isStale(workspaceId) {
|
|
139
|
+
const doc = this.peek(workspaceId);
|
|
140
|
+
if (doc === undefined)
|
|
141
|
+
return true;
|
|
142
|
+
const ttl = doc.entries.length === 0 ? EMPTY_CACHE_TTL_MS : CACHE_TTL_MS;
|
|
143
|
+
return this.now - doc.fetchedAt >= ttl;
|
|
144
|
+
}
|
|
145
|
+
/** Drop the in-memory view and force the next `peek` to re-read from disk. */
|
|
146
|
+
invalidate() {
|
|
147
|
+
this.document = undefined;
|
|
148
|
+
this.loadedFor = undefined;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* A diagnostic snapshot for the settings panel.
|
|
152
|
+
*
|
|
153
|
+
* The panel exists because this cache's staleness is otherwise invisible: a
|
|
154
|
+
* developer whose agent silently stops retrieving cannot tell an empty
|
|
155
|
+
* workspace from a stale list without reading the JSON file. `fetchedAt` plus
|
|
156
|
+
* the per-scene counts answer that in one glance.
|
|
157
|
+
* @param workspaceId - the workspace being served.
|
|
158
|
+
* @returns the snapshot; `fetchedAt` is undefined when nothing is cached.
|
|
159
|
+
*/
|
|
160
|
+
status(workspaceId) {
|
|
161
|
+
const doc = this.peek(workspaceId);
|
|
162
|
+
if (doc === undefined) {
|
|
163
|
+
return { workspaceId, searchCount: 0, chatCount: 0, total: 0, truncated: false, stale: true };
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
workspaceId,
|
|
167
|
+
fetchedAt: doc.fetchedAt,
|
|
168
|
+
searchCount: doc.entries.filter((entry) => entry.scene === "search").length,
|
|
169
|
+
chatCount: doc.entries.filter((entry) => entry.scene === "chat").length,
|
|
170
|
+
total: doc.total,
|
|
171
|
+
truncated: doc.truncated,
|
|
172
|
+
stale: this.isStale(workspaceId),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The cached entries of one scene, most recently modified first.
|
|
177
|
+
* Backs the panel's service picker, which exists so a default service can be
|
|
178
|
+
* chosen by name instead of by pasting a 36-character hex id.
|
|
179
|
+
* @param workspaceId - the workspace being served.
|
|
180
|
+
* @param scene - `search` or `chat`.
|
|
181
|
+
* @returns the entries, newest first.
|
|
182
|
+
*/
|
|
183
|
+
entriesFor(workspaceId, scene) {
|
|
184
|
+
const doc = this.peek(workspaceId);
|
|
185
|
+
if (doc === undefined)
|
|
186
|
+
return [];
|
|
187
|
+
return doc.entries
|
|
188
|
+
.filter((entry) => entry.scene === scene)
|
|
189
|
+
.sort((left, right) => (right.modify_time ?? "").localeCompare(left.modify_time ?? ""));
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Fetch and store the current service list.
|
|
193
|
+
* Never rejects: failures are warned and leave the previous document in place.
|
|
194
|
+
* Concurrent calls share one request.
|
|
195
|
+
* @returns a promise resolving once the attempt finishes.
|
|
196
|
+
*/
|
|
197
|
+
async refresh() {
|
|
198
|
+
// Without this guard `pre-step` would start a fetch on every model request
|
|
199
|
+
// while the first is still outstanding.
|
|
200
|
+
this.inFlight ??= this.runRefresh().finally(() => {
|
|
201
|
+
this.inFlight = undefined;
|
|
202
|
+
});
|
|
203
|
+
return await this.inFlight;
|
|
204
|
+
}
|
|
205
|
+
async runRefresh() {
|
|
206
|
+
try {
|
|
207
|
+
const workspaceId = await this.opts.resolveWorkspaceId();
|
|
208
|
+
const list = await listServices(this.opts.client);
|
|
209
|
+
// Both scenes failing means the fetch produced nothing; keep the old file.
|
|
210
|
+
if (list.failedScenes.length === 2) {
|
|
211
|
+
this.opts.warn("bailian-kb service cache not refreshed: both scene queries failed");
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (list.failedScenes.length > 0) {
|
|
215
|
+
this.opts.warn(`bailian-kb service cache refreshed without scene(s): ${list.failedScenes.join(", ")}`);
|
|
216
|
+
}
|
|
217
|
+
const doc = {
|
|
218
|
+
version: CACHE_VERSION,
|
|
219
|
+
fetchedAt: this.now,
|
|
220
|
+
workspaceId,
|
|
221
|
+
endpointHost: this.opts.endpointHost,
|
|
222
|
+
entries: list.entries,
|
|
223
|
+
total: list.total,
|
|
224
|
+
truncated: list.truncated,
|
|
225
|
+
};
|
|
226
|
+
writeServiceCache(serviceCachePath(workspaceId, this.opts.home ?? dshHome()), doc);
|
|
227
|
+
this.document = doc;
|
|
228
|
+
this.loadedFor = workspaceId;
|
|
229
|
+
}
|
|
230
|
+
catch (failed) {
|
|
231
|
+
this.opts.warn(`bailian-kb service cache refresh failed: ${String(failed)}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders the deployed-service catalog the model reads before deciding whether
|
|
3
|
+
* to retrieve.
|
|
4
|
+
*
|
|
5
|
+
* This is a pure function on purpose: the four selection branches below are the
|
|
6
|
+
* whole routing policy, and they are far easier to pin down in tests than
|
|
7
|
+
* through a live pre-step.
|
|
8
|
+
*
|
|
9
|
+
* Rendering conventions (settled):
|
|
10
|
+
* - English frame, service names verbatim — same language as the tool
|
|
11
|
+
* descriptions, so the model is not switched between languages mid-prompt.
|
|
12
|
+
* - Truncation is always stated. Silently cutting the list makes the model treat
|
|
13
|
+
* it as complete and flatly answer "there is no such knowledge base".
|
|
14
|
+
* - An empty scene omits its whole section. `no chat services` is pure noise and
|
|
15
|
+
* invites the model to handle a case that does not exist.
|
|
16
|
+
*/
|
|
17
|
+
import type { ServiceEntry } from "./services.js";
|
|
18
|
+
/** Entries rendered per scene before switching to "most recently modified" mode. */
|
|
19
|
+
export declare const CATALOG_ENTRY_LIMIT = 10;
|
|
20
|
+
export interface CatalogInput {
|
|
21
|
+
entries: readonly ServiceEntry[];
|
|
22
|
+
/** Server-reported total, which may exceed `entries` when the fetch itself was capped. */
|
|
23
|
+
total: number;
|
|
24
|
+
/** True when the fetch stopped before the server ran out of rows. */
|
|
25
|
+
truncated: boolean;
|
|
26
|
+
defaultRetrieveAgentId?: string;
|
|
27
|
+
defaultChatAgentId?: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Build the catalog text for one cached service list.
|
|
31
|
+
* @param input - the cached entries plus the deployment's configured defaults.
|
|
32
|
+
* @returns the model-facing text, or undefined when there is nothing worth injecting.
|
|
33
|
+
*/
|
|
34
|
+
export declare function buildServiceCatalog(input: CatalogInput): string | undefined;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders the deployed-service catalog the model reads before deciding whether
|
|
3
|
+
* to retrieve.
|
|
4
|
+
*
|
|
5
|
+
* This is a pure function on purpose: the four selection branches below are the
|
|
6
|
+
* whole routing policy, and they are far easier to pin down in tests than
|
|
7
|
+
* through a live pre-step.
|
|
8
|
+
*
|
|
9
|
+
* Rendering conventions (settled):
|
|
10
|
+
* - English frame, service names verbatim — same language as the tool
|
|
11
|
+
* descriptions, so the model is not switched between languages mid-prompt.
|
|
12
|
+
* - Truncation is always stated. Silently cutting the list makes the model treat
|
|
13
|
+
* it as complete and flatly answer "there is no such knowledge base".
|
|
14
|
+
* - An empty scene omits its whole section. `no chat services` is pure noise and
|
|
15
|
+
* invites the model to handle a case that does not exist.
|
|
16
|
+
*/
|
|
17
|
+
/** Entries rendered per scene before switching to "most recently modified" mode. */
|
|
18
|
+
export const CATALOG_ENTRY_LIMIT = 10;
|
|
19
|
+
/** Truncation applied to a service description once the backend returns one. */
|
|
20
|
+
const DESCRIPTION_LIMIT = 200;
|
|
21
|
+
const SCENE_LABEL = {
|
|
22
|
+
search: "kb_search (retrieval)",
|
|
23
|
+
chat: "kb_chat (grounded Q&A)",
|
|
24
|
+
};
|
|
25
|
+
/** Render one entry as a single line. */
|
|
26
|
+
function renderEntry(entry) {
|
|
27
|
+
const name = entry.agent_name === "" ? "(unnamed)" : entry.agent_name;
|
|
28
|
+
const description = entry.description === undefined || entry.description.trim() === ""
|
|
29
|
+
? undefined
|
|
30
|
+
: entry.description.trim().length > DESCRIPTION_LIMIT
|
|
31
|
+
? `${entry.description.trim().slice(0, DESCRIPTION_LIMIT - 1)}…`
|
|
32
|
+
: entry.description.trim();
|
|
33
|
+
return `- ${entry.agent_id} — ${name}${description === undefined ? "" : `: ${description}`}`;
|
|
34
|
+
}
|
|
35
|
+
/** Most recently modified first; entries without a timestamp sort last. */
|
|
36
|
+
function byRecency(left, right) {
|
|
37
|
+
const l = left.modify_time ?? "";
|
|
38
|
+
const r = right.modify_time ?? "";
|
|
39
|
+
if (l === r)
|
|
40
|
+
return 0;
|
|
41
|
+
if (l === "")
|
|
42
|
+
return 1;
|
|
43
|
+
if (r === "")
|
|
44
|
+
return -1;
|
|
45
|
+
return l < r ? 1 : -1;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Render one scene's section, or undefined when the scene has no services.
|
|
49
|
+
* @param entries - all cached entries (any scene).
|
|
50
|
+
* @param scene - the scene to render.
|
|
51
|
+
* @param defaultAgentId - this scene's configured default service, when set.
|
|
52
|
+
* @param truncatedFetch - whether the fetch itself left rows unread.
|
|
53
|
+
* @returns the section lines, or undefined to omit the section entirely.
|
|
54
|
+
*/
|
|
55
|
+
function renderScene(entries, scene, defaultAgentId, truncatedFetch) {
|
|
56
|
+
const forScene = entries.filter((entry) => entry.scene === scene);
|
|
57
|
+
if (forScene.length === 0)
|
|
58
|
+
return undefined;
|
|
59
|
+
const lines = [`${SCENE_LABEL[scene]}:`];
|
|
60
|
+
const configured = defaultAgentId === undefined
|
|
61
|
+
? undefined
|
|
62
|
+
: forScene.find((entry) => entry.agent_id === defaultAgentId);
|
|
63
|
+
if (configured !== undefined) {
|
|
64
|
+
// A configured default is the user's own pick: the highest-quality signal
|
|
65
|
+
// available, so it is the only entry worth spending context on.
|
|
66
|
+
lines.push(renderEntry(configured));
|
|
67
|
+
const others = forScene.length - 1;
|
|
68
|
+
if (others > 0) {
|
|
69
|
+
lines.push(` (default service; ${others} other${others === 1 ? "" : "s"} exist — ` +
|
|
70
|
+
`run \`bl knowledge service list --scene ${scene}\` to see them)`);
|
|
71
|
+
}
|
|
72
|
+
return lines;
|
|
73
|
+
}
|
|
74
|
+
if (forScene.length <= CATALOG_ENTRY_LIMIT && !truncatedFetch) {
|
|
75
|
+
lines.push(...forScene.map(renderEntry));
|
|
76
|
+
return lines;
|
|
77
|
+
}
|
|
78
|
+
const shown = [...forScene].sort(byRecency).slice(0, CATALOG_ENTRY_LIMIT);
|
|
79
|
+
lines.push(...shown.map(renderEntry));
|
|
80
|
+
// State the shortfall: the model must know this list is partial before it
|
|
81
|
+
// concludes no service covers the question.
|
|
82
|
+
const knownTotal = Math.max(forScene.length, shown.length);
|
|
83
|
+
lines.push(` (showing ${shown.length} most recently modified of ${truncatedFetch ? "more than " : ""}` +
|
|
84
|
+
`${knownTotal} deployed ${scene} services — run \`bl knowledge service list --scene ${scene} ` +
|
|
85
|
+
"--name <keyword>` to look for others)");
|
|
86
|
+
return lines;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Build the catalog text for one cached service list.
|
|
90
|
+
* @param input - the cached entries plus the deployment's configured defaults.
|
|
91
|
+
* @returns the model-facing text, or undefined when there is nothing worth injecting.
|
|
92
|
+
*/
|
|
93
|
+
export function buildServiceCatalog(input) {
|
|
94
|
+
const search = renderScene(input.entries, "search", input.defaultRetrieveAgentId, input.truncated);
|
|
95
|
+
const chat = renderScene(input.entries, "chat", input.defaultChatAgentId, input.truncated);
|
|
96
|
+
if (search === undefined && chat === undefined)
|
|
97
|
+
return undefined;
|
|
98
|
+
return [
|
|
99
|
+
"<system-reminder>",
|
|
100
|
+
// The header must not name the tools: a scene with no services omits its
|
|
101
|
+
// section, and naming that tool anyway would invite passing an id from the
|
|
102
|
+
// other scene, which the service rejects. Section labels carry the mapping.
|
|
103
|
+
"Bailian knowledge services deployed in this workspace, grouped by the tool that accepts them. " +
|
|
104
|
+
"Pass an id from the matching section as that tool's `agent_id` argument — it is required and " +
|
|
105
|
+
"cannot be guessed.",
|
|
106
|
+
"",
|
|
107
|
+
...(search ?? []),
|
|
108
|
+
...(search !== undefined && chat !== undefined ? [""] : []),
|
|
109
|
+
...(chat ?? []),
|
|
110
|
+
"",
|
|
111
|
+
"If none of these services covers what the user is asking about, say so plainly rather than " +
|
|
112
|
+
"trying the closest-looking id — an unrelated retrieval result is worse than none.",
|
|
113
|
+
"</system-reminder>",
|
|
114
|
+
].join("\n");
|
|
115
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Publishes the cached service catalog into each request as a sourced context
|
|
3
|
+
* message, on the `agent/pre-step` waterfall.
|
|
4
|
+
*
|
|
5
|
+
* Why a context message rather than the tool descriptions: a tool description is
|
|
6
|
+
* fixed when the plugin loads, and a plugin loads once per PROCESS, not once per
|
|
7
|
+
* session. In a long-running host the TTL would be evaluated exactly once at
|
|
8
|
+
* `apply()` and a service created elsewhere would never be noticed until a
|
|
9
|
+
* restart. Re-registering tools to refresh a description instead invalidates the
|
|
10
|
+
* prompt prefix cache from the first changed schema token. Injecting context
|
|
11
|
+
* keeps the tool schemas byte-stable forever and still refreshes per step.
|
|
12
|
+
*
|
|
13
|
+
* Two hard constraints follow from `agent/pre-step` semantics:
|
|
14
|
+
*
|
|
15
|
+
* 1. `pre-step` fires once per STEP, and a step is one model request — a turn with
|
|
16
|
+
* five tool calls fires it six times. Re-injecting each time would insert six
|
|
17
|
+
* copies into one turn and void the KV cache from the first insertion onward,
|
|
18
|
+
* so change suppression is a correctness requirement, not an optimization.
|
|
19
|
+
* 2. A throwing listener fails the proposed step, i.e. the user's turn stalls.
|
|
20
|
+
* Everything here is therefore wrapped: any failure degrades to "inject
|
|
21
|
+
* nothing this step".
|
|
22
|
+
*/
|
|
23
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
24
|
+
import type { ServiceCache } from "./service-cache.js";
|
|
25
|
+
export interface ServiceContextOptions {
|
|
26
|
+
cache: ServiceCache;
|
|
27
|
+
/** Resolves the workspace being served; undefined means "not configured yet". */
|
|
28
|
+
resolveWorkspaceId: () => Promise<string | undefined>;
|
|
29
|
+
/** Resolves the configured default retrieval service (settings then credential). */
|
|
30
|
+
resolveDefaultRetrieveAgentId: () => Promise<string | undefined>;
|
|
31
|
+
/** Resolves the configured default chat service (settings then credential). */
|
|
32
|
+
resolveDefaultChatAgentId: () => Promise<string | undefined>;
|
|
33
|
+
warn: (message: string) => void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Install the pre-step listener that keeps the catalog present and current.
|
|
37
|
+
* @param ctx - a context with `agents` available.
|
|
38
|
+
* @param opts - the cache plus the deployment's resolved workspace and defaults.
|
|
39
|
+
*/
|
|
40
|
+
export declare function installServiceContext(ctx: Context, opts: ServiceContextOptions): void;
|