@sparkelf/dsh-bot-agent 0.0.0-stage → 0.2.9-alpha.127
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.i18n.yaml +34 -0
- package/README.md +68 -2
- package/README.zh.md +69 -0
- package/lib/client.js +3 -0
- package/lib/index.js +675 -0
- package/lib/types/api.d.ts +70 -0
- package/lib/types/builtin.d.ts +12 -0
- package/lib/types/client/BotAvatar.d.ts +26 -0
- package/lib/types/client/BotAvatarPicker.d.ts +20 -0
- package/lib/types/client/BotDetail.d.ts +28 -0
- package/lib/types/client/BotMarket.d.ts +37 -0
- package/lib/types/client/BotPanel.d.ts +34 -0
- package/lib/types/client/BotPanelIcon.d.ts +15 -0
- package/lib/types/client/HueTile.d.ts +27 -0
- package/lib/types/client/SessionRowAvatar.d.ts +21 -0
- package/lib/types/client/api.d.ts +23 -0
- package/lib/types/client/avatars.d.ts +24 -0
- package/lib/types/client/index.d.ts +38 -0
- package/lib/types/client/locales.d.ts +74 -0
- package/lib/types/client/mention.d.ts +31 -0
- package/lib/types/client/store.d.ts +37 -0
- package/lib/types/client/templates.d.ts +65 -0
- package/lib/types/index.d.ts +22 -0
- package/lib/types/policy.d.ts +53 -0
- package/lib/types/presets.d.ts +33 -0
- package/lib/types/routing.d.ts +38 -0
- package/lib/types/storage.d.ts +89 -0
- package/package.json +94 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
import { z as z$1 } from "zod";
|
|
4
|
+
import { brandString } from "@deepseek-ai/dsh-brand";
|
|
5
|
+
import { defineDomain, domainTable } from "@deepseek-ai/dsh-storage-domain";
|
|
6
|
+
import { setTimeout } from "node:timers/promises";
|
|
7
|
+
import { parseEntryYaml } from "@deepseek-ai/cordis-plugin-include";
|
|
8
|
+
//#region lib/types/api.js
|
|
9
|
+
/**
|
|
10
|
+
* The same-origin API surface shared by this package's two halves.
|
|
11
|
+
*
|
|
12
|
+
* The Host registers one prefix and dispatches on the trailing method name; the
|
|
13
|
+
* browser calls the same strings. Keeping them in one module stops the halves
|
|
14
|
+
* drifting apart. This module stays dependency-free so both bundles can import
|
|
15
|
+
* it: the Client bundle rejects Node builtins and non-platform packages.
|
|
16
|
+
*
|
|
17
|
+
* @module @sparkelf/dsh-bot-agent/api
|
|
18
|
+
*/
|
|
19
|
+
/** Prefix the Host registers and the browser calls. */
|
|
20
|
+
const BOT_API_PREFIX = "/bot-agent/api";
|
|
21
|
+
/** Method names the Host dispatches on. */
|
|
22
|
+
const BOT_API = {
|
|
23
|
+
/** Every bot, built-in first. */
|
|
24
|
+
list: "list",
|
|
25
|
+
/** One bot by id. */
|
|
26
|
+
get: "get",
|
|
27
|
+
/** Create a custom bot. */
|
|
28
|
+
create: "create",
|
|
29
|
+
/** Update a bot's editable fields. */
|
|
30
|
+
update: "update",
|
|
31
|
+
/** Delete a custom bot; the built-in is refused. */
|
|
32
|
+
delete: "delete"
|
|
33
|
+
};
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region lib/types/storage.js
|
|
36
|
+
/**
|
|
37
|
+
* Durable bot entities over the storage-domain `agents` domain.
|
|
38
|
+
*
|
|
39
|
+
* One `bots` table holds every agent configuration record. The schema is the
|
|
40
|
+
* single authority for a record's layout: the domain validates every stored row
|
|
41
|
+
* at the durable read boundary, and the same inference types the Host handle.
|
|
42
|
+
* @module @sparkelf/dsh-bot-agent/storage
|
|
43
|
+
*/
|
|
44
|
+
const botIdSchema = z$1.string().min(1).transform(brandString);
|
|
45
|
+
const presetSchema = z$1.object({
|
|
46
|
+
identity: z$1.string().default(""),
|
|
47
|
+
duties: z$1.string().default(""),
|
|
48
|
+
workStyle: z$1.string().default(""),
|
|
49
|
+
replyStyle: z$1.string().default("")
|
|
50
|
+
}).strict();
|
|
51
|
+
const policySchema = z$1.object({
|
|
52
|
+
mode: z$1.enum([
|
|
53
|
+
"all",
|
|
54
|
+
"allow",
|
|
55
|
+
"deny"
|
|
56
|
+
]).default("all"),
|
|
57
|
+
list: z$1.array(z$1.string()).default([])
|
|
58
|
+
}).strict();
|
|
59
|
+
const kbScopeSchema = z$1.object({
|
|
60
|
+
mode: z$1.enum([
|
|
61
|
+
"all",
|
|
62
|
+
"include",
|
|
63
|
+
"exclude"
|
|
64
|
+
]).default("all"),
|
|
65
|
+
paths: z$1.array(z$1.string()).default([])
|
|
66
|
+
}).strict();
|
|
67
|
+
/** One stored bot record. New optional fields default so older rows stay readable. */
|
|
68
|
+
const botSchema = z$1.object({
|
|
69
|
+
id: botIdSchema,
|
|
70
|
+
name: z$1.string().min(1),
|
|
71
|
+
avatar: z$1.string().min(1),
|
|
72
|
+
preset: presetSchema,
|
|
73
|
+
retrievalSummary: z$1.string().default(""),
|
|
74
|
+
kbScope: kbScopeSchema.default({
|
|
75
|
+
mode: "all",
|
|
76
|
+
paths: []
|
|
77
|
+
}),
|
|
78
|
+
skillPolicy: policySchema.default({
|
|
79
|
+
mode: "all",
|
|
80
|
+
list: []
|
|
81
|
+
}),
|
|
82
|
+
toolPolicy: policySchema.default({
|
|
83
|
+
mode: "all",
|
|
84
|
+
list: []
|
|
85
|
+
}),
|
|
86
|
+
createdAt: z$1.number().int().nonnegative(),
|
|
87
|
+
builtin: z$1.boolean().default(false),
|
|
88
|
+
templateId: z$1.string().optional()
|
|
89
|
+
}).strict();
|
|
90
|
+
/** The authoritative `agents` domain: one `bots` table, whole-unit layout. */
|
|
91
|
+
const agentsDomain = defineDomain({
|
|
92
|
+
name: "agents",
|
|
93
|
+
version: 1,
|
|
94
|
+
tables: { bots: domainTable(botSchema) }
|
|
95
|
+
});
|
|
96
|
+
//#endregion
|
|
97
|
+
//#region lib/types/builtin.js
|
|
98
|
+
/**
|
|
99
|
+
* The built-in super assistant: the one bot a deployment always carries.
|
|
100
|
+
*
|
|
101
|
+
* It is seeded once, cannot be deleted, and stays configurable. Its persona
|
|
102
|
+
* keeps the deployment's base coding-agent prompt so an unconfigured session
|
|
103
|
+
* behaves like the default; the general-assistant scope is full knowledge,
|
|
104
|
+
* skills, and tools. P0 marks it `builtin`; excluding it from subagent routing
|
|
105
|
+
* is later work.
|
|
106
|
+
* @module @sparkelf/dsh-bot-agent/builtin
|
|
107
|
+
*/
|
|
108
|
+
/** Stable id of the built-in bot; also its agent preset id. */
|
|
109
|
+
const BUILTIN_BOT_ID = "bot-super";
|
|
110
|
+
/** Avatar catalog key the built-in renders. */
|
|
111
|
+
const BUILTIN_AVATAR = "super";
|
|
112
|
+
/**
|
|
113
|
+
* The seed record for the built-in super assistant.
|
|
114
|
+
* @param now - creation instant, epoch milliseconds.
|
|
115
|
+
* @returns the built-in bot, marked `builtin`.
|
|
116
|
+
*/
|
|
117
|
+
function builtinBot(now) {
|
|
118
|
+
return {
|
|
119
|
+
id: brandString(BUILTIN_BOT_ID),
|
|
120
|
+
name: "超级助手",
|
|
121
|
+
avatar: BUILTIN_AVATAR,
|
|
122
|
+
preset: {
|
|
123
|
+
identity: "You are a coding agent powered by the {{model}} model.",
|
|
124
|
+
duties: "",
|
|
125
|
+
workStyle: "",
|
|
126
|
+
replyStyle: ""
|
|
127
|
+
},
|
|
128
|
+
retrievalSummary: "通用主助手",
|
|
129
|
+
kbScope: {
|
|
130
|
+
mode: "all",
|
|
131
|
+
paths: []
|
|
132
|
+
},
|
|
133
|
+
skillPolicy: {
|
|
134
|
+
mode: "all",
|
|
135
|
+
list: []
|
|
136
|
+
},
|
|
137
|
+
toolPolicy: {
|
|
138
|
+
mode: "all",
|
|
139
|
+
list: []
|
|
140
|
+
},
|
|
141
|
+
createdAt: now,
|
|
142
|
+
builtin: true
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region lib/types/presets.js
|
|
147
|
+
/**
|
|
148
|
+
* Per-bot agent presets: the deployment's base composition with the bot's
|
|
149
|
+
* persona swapped in.
|
|
150
|
+
*
|
|
151
|
+
* A bot composes a session through the official preset registry, so its tools,
|
|
152
|
+
* prompt, and durable `agentPreset` header are the harness's own. The composition
|
|
153
|
+
* is the base preset's declared child list — read through the registry's document
|
|
154
|
+
* surface and parsed in the Loader's own YAML dialect, so `!!js` rows and groups
|
|
155
|
+
* round-trip losslessly — with the persona row's prefix replaced by the bot's
|
|
156
|
+
* prose. This is the registry's "duplicate, then edit" authoring path.
|
|
157
|
+
* @module @sparkelf/dsh-bot-agent/presets
|
|
158
|
+
*/
|
|
159
|
+
/** The persona row every shipped composition carries. */
|
|
160
|
+
const PERSONA_MODULE = "@deepseek-ai/dsh-persona";
|
|
161
|
+
/** The skill catalog/loader row whose name filter enforces a bot's skill policy. */
|
|
162
|
+
const TOOL_SKILL_MODULE = "@deepseek-ai/dsh-tool-skill";
|
|
163
|
+
/**
|
|
164
|
+
* Compose the bot's persona prefix from its four prose fields.
|
|
165
|
+
*
|
|
166
|
+
* An empty identity keeps the base composition's own prefix, so a bot that only
|
|
167
|
+
* sets duties still runs the deployment's coding-agent prompt. The non-empty
|
|
168
|
+
* fields append as labelled sections.
|
|
169
|
+
* @param bot - the bot whose prose composes the prefix.
|
|
170
|
+
* @param basePrefix - the base composition's persona prefix, the identity fallback.
|
|
171
|
+
* @returns the persona prefix template.
|
|
172
|
+
*/
|
|
173
|
+
function botPersonaPrefix(bot, basePrefix) {
|
|
174
|
+
const sections = [bot.preset.identity.trim() || basePrefix];
|
|
175
|
+
const duties = bot.preset.duties.trim();
|
|
176
|
+
const workStyle = bot.preset.workStyle.trim();
|
|
177
|
+
const replyStyle = bot.preset.replyStyle.trim();
|
|
178
|
+
if (duties !== "") sections.push(`Duties:\n${duties}`);
|
|
179
|
+
if (workStyle !== "") sections.push(`Work style:\n${workStyle}`);
|
|
180
|
+
if (replyStyle !== "") sections.push(`Reply style:\n${replyStyle}`);
|
|
181
|
+
return sections.join("\n\n");
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Locate one module's row in a parsed composition, descending into groups.
|
|
185
|
+
* @param rows - parsed child rows.
|
|
186
|
+
* @param name - the module specifier to find.
|
|
187
|
+
* @returns the row, or undefined when the composition declares none.
|
|
188
|
+
*/
|
|
189
|
+
function findModule(rows, name) {
|
|
190
|
+
for (const value of rows) {
|
|
191
|
+
if (typeof value !== "object" || value === null) continue;
|
|
192
|
+
const row = value;
|
|
193
|
+
if (row.group === true && Array.isArray(row.config)) {
|
|
194
|
+
const nested = findModule(row.config, name);
|
|
195
|
+
if (nested !== void 0) return nested;
|
|
196
|
+
}
|
|
197
|
+
if (row.name === name) return row;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Locate the persona row in a parsed composition, descending into groups.
|
|
202
|
+
* @param rows - parsed child rows.
|
|
203
|
+
* @returns the persona row and its current prefix, or undefined when none is declared.
|
|
204
|
+
*/
|
|
205
|
+
function findPersona(rows) {
|
|
206
|
+
const row = findModule(rows, PERSONA_MODULE);
|
|
207
|
+
if (row === void 0) return void 0;
|
|
208
|
+
const config = typeof row.config === "object" && row.config !== null ? row.config : {};
|
|
209
|
+
return {
|
|
210
|
+
row,
|
|
211
|
+
basePrefix: typeof config.prefix === "string" ? config.prefix : ""
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Impose a bot's skill policy on the composition's `tool-skill` row.
|
|
216
|
+
*
|
|
217
|
+
* The skill catalog, named loads, and user invocations all read that row's name
|
|
218
|
+
* filter, so `deny` sets `excludedSkills` and `allow` sets `includedSkills`. A
|
|
219
|
+
* composition without a `tool-skill` row offers no skill surface to narrow.
|
|
220
|
+
* @param rows - parsed child rows, edited in place.
|
|
221
|
+
* @param policy - the bot's stored skill policy.
|
|
222
|
+
*/
|
|
223
|
+
function applySkillPolicy(rows, policy) {
|
|
224
|
+
if (policy.mode === "all") return;
|
|
225
|
+
const row = findModule(rows, TOOL_SKILL_MODULE);
|
|
226
|
+
if (row === void 0) return;
|
|
227
|
+
const config = typeof row.config === "object" && row.config !== null ? row.config : {};
|
|
228
|
+
row.config = policy.mode === "deny" ? {
|
|
229
|
+
...config,
|
|
230
|
+
excludedSkills: [...policy.list]
|
|
231
|
+
} : {
|
|
232
|
+
...config,
|
|
233
|
+
includedSkills: [...policy.list]
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Read the base preset's document, waiting out the boot ordering where the base
|
|
238
|
+
* declaration registers after this plugin activates.
|
|
239
|
+
* @param ctx - host context carrying the preset registry.
|
|
240
|
+
* @param baseId - the preset identity to copy.
|
|
241
|
+
* @param deadlineMs - how long to wait for the declaration to appear.
|
|
242
|
+
* @returns the base document.
|
|
243
|
+
* @throws the last read failure once the deadline passes.
|
|
244
|
+
*/
|
|
245
|
+
async function readBaseDocument(ctx, baseId, deadlineMs) {
|
|
246
|
+
const start = Date.now();
|
|
247
|
+
for (;;) try {
|
|
248
|
+
return await ctx.agentPresets.readDocument(baseId);
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (Date.now() - start >= deadlineMs) throw error;
|
|
251
|
+
await setTimeout(100);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Build the bot's preset definition from the base composition.
|
|
256
|
+
* @param document - the base preset's declared document.
|
|
257
|
+
* @param bot - the bot whose persona and metadata the preset carries.
|
|
258
|
+
* @returns a definition ready for `agentPresets.register`.
|
|
259
|
+
*/
|
|
260
|
+
function buildBotPreset(document, bot) {
|
|
261
|
+
const parsed = parseEntryYaml(document.content);
|
|
262
|
+
const rows = Array.isArray(parsed) ? parsed : [];
|
|
263
|
+
const persona = findPersona(rows);
|
|
264
|
+
const prefix = botPersonaPrefix(bot, persona?.basePrefix ?? "");
|
|
265
|
+
if (persona !== void 0) {
|
|
266
|
+
const config = typeof persona.row.config === "object" && persona.row.config !== null ? persona.row.config : {};
|
|
267
|
+
persona.row.config = {
|
|
268
|
+
...config,
|
|
269
|
+
prefix
|
|
270
|
+
};
|
|
271
|
+
} else rows.unshift({
|
|
272
|
+
id: "persona",
|
|
273
|
+
name: PERSONA_MODULE,
|
|
274
|
+
config: { prefix }
|
|
275
|
+
});
|
|
276
|
+
applySkillPolicy(rows, bot.skillPolicy);
|
|
277
|
+
const description = bot.retrievalSummary.trim() || bot.preset.duties.trim() || bot.name;
|
|
278
|
+
return {
|
|
279
|
+
id: bot.id,
|
|
280
|
+
name: bot.name,
|
|
281
|
+
description,
|
|
282
|
+
plugins: rows
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
//#endregion
|
|
286
|
+
//#region lib/types/routing.js
|
|
287
|
+
/**
|
|
288
|
+
* Task→bot routing: match a delegation's task text against each bot's
|
|
289
|
+
* retrievalSummary and pick the best-covering bot preset.
|
|
290
|
+
*
|
|
291
|
+
* The business rule lives here, not in the delegation tool: `dsh-tool-subagent`
|
|
292
|
+
* offers the task text through the `subagent/preset-proposal` waterfall, and this
|
|
293
|
+
* package's host half answers with a bot id. Matching is token coverage — the
|
|
294
|
+
* fraction of a summary's tokens that appear in the task — over ASCII words and
|
|
295
|
+
* CJK character bigrams, so Chinese summaries match without a segmenter.
|
|
296
|
+
* @module @sparkelf/dsh-bot-agent/routing
|
|
297
|
+
*/
|
|
298
|
+
/** CJK ideograph runs tokenized into sliding bigrams (main block, ext A, compatibility). */
|
|
299
|
+
const CJK_RUN = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+/g;
|
|
300
|
+
/**
|
|
301
|
+
* Tokenize text for coverage matching: lowercase ASCII words plus CJK character
|
|
302
|
+
* bigrams. Bigrams approximate Chinese word boundaries without a segmenter; a
|
|
303
|
+
* one-character CJK run yields no bigram and contributes nothing.
|
|
304
|
+
* @param text - the task or summary text.
|
|
305
|
+
* @returns the distinct match tokens.
|
|
306
|
+
*/
|
|
307
|
+
function matchTokens(text) {
|
|
308
|
+
const tokens = /* @__PURE__ */ new Set();
|
|
309
|
+
const lower = text.toLowerCase();
|
|
310
|
+
for (const word of lower.match(/[a-z0-9]+/g) ?? []) tokens.add(word);
|
|
311
|
+
for (const run of lower.match(CJK_RUN) ?? []) for (let i = 0; i + 1 < run.length; i += 1) tokens.add(run.slice(i, i + 2));
|
|
312
|
+
return tokens;
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Pick the bot whose retrievalSummary best covers the task text. Coverage is the
|
|
316
|
+
* fraction of the summary's tokens present in the task; a bot is eligible only
|
|
317
|
+
* when its coverage reaches `minCoverage`. The highest-coverage eligible bot wins;
|
|
318
|
+
* ties keep the caller's order. A bot with an empty summary is never eligible.
|
|
319
|
+
* @param bots - candidate bots, in the caller's preference order.
|
|
320
|
+
* @param taskText - the delegation's task text (description and prompt).
|
|
321
|
+
* @param minCoverage - the minimum coverage in [0,1] a bot must reach.
|
|
322
|
+
* @returns the selected bot id, or undefined when no bot reaches the threshold.
|
|
323
|
+
*/
|
|
324
|
+
function matchBotPreset(bots, taskText, minCoverage) {
|
|
325
|
+
const taskTokens = matchTokens(taskText);
|
|
326
|
+
let best;
|
|
327
|
+
for (const bot of bots) {
|
|
328
|
+
const summaryTokens = matchTokens(bot.retrievalSummary);
|
|
329
|
+
if (summaryTokens.size === 0) continue;
|
|
330
|
+
let hit = 0;
|
|
331
|
+
for (const token of summaryTokens) if (taskTokens.has(token)) hit += 1;
|
|
332
|
+
const coverage = hit / summaryTokens.size;
|
|
333
|
+
if (coverage >= minCoverage && (best === void 0 || coverage > best.coverage)) best = {
|
|
334
|
+
id: bot.id,
|
|
335
|
+
coverage
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
return best?.id;
|
|
339
|
+
}
|
|
340
|
+
//#endregion
|
|
341
|
+
//#region lib/types/policy.js
|
|
342
|
+
/**
|
|
343
|
+
* Compute the inherited-tool mask a bot's tool policy imposes.
|
|
344
|
+
*
|
|
345
|
+
* `deny` accepts any name (the registry removes a name even before anything offers
|
|
346
|
+
* it), so the list passes through unchanged. `allow` keeps only names an inherited
|
|
347
|
+
* registration can offer, intersected with the live tool universe; an empty result
|
|
348
|
+
* hides every inherited tool, the fail-closed reading of a whitelist. `all` and an
|
|
349
|
+
* empty deny list impose no mask.
|
|
350
|
+
* @param policy - the bot's stored tool policy.
|
|
351
|
+
* @param knownNames - tool names the agent's composition offers before the mask.
|
|
352
|
+
* @returns the restriction to apply, or undefined when the policy narrows nothing.
|
|
353
|
+
*/
|
|
354
|
+
function toolRestrictionFilter(policy, knownNames) {
|
|
355
|
+
if (policy.mode === "deny") return policy.list.length === 0 ? void 0 : { deny: [...policy.list] };
|
|
356
|
+
if (policy.mode === "allow") return { allow: policy.list.filter((name) => knownNames.has(name)) };
|
|
357
|
+
}
|
|
358
|
+
/** Knowledge-base file tools whose arguments carry view-relative paths. */
|
|
359
|
+
const KB_PATH_ARGS = Object.freeze({
|
|
360
|
+
kb_file_write: ["path"],
|
|
361
|
+
kb_file_move: ["from", "to"],
|
|
362
|
+
kb_file_delete: ["path"],
|
|
363
|
+
kb_file_mkdir: ["path"],
|
|
364
|
+
kb_file_extract: ["path"]
|
|
365
|
+
});
|
|
366
|
+
/** Normalize one view-relative path for prefix comparison: trim, drop `./` and trailing slashes. */
|
|
367
|
+
function normalizePath(path) {
|
|
368
|
+
return path.trim().replace(/^\.\//u, "").replace(/\/+$/u, "");
|
|
369
|
+
}
|
|
370
|
+
/** Whether a view-relative path is the prefix itself or sits beneath it. */
|
|
371
|
+
function underPrefix(path, prefix) {
|
|
372
|
+
const target = normalizePath(path);
|
|
373
|
+
const base = normalizePath(prefix);
|
|
374
|
+
if (base === "") return true;
|
|
375
|
+
return target === base || target.startsWith(`${base}/`);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Compute a guard denial for a knowledge-base file call outside the bot's scope.
|
|
379
|
+
*
|
|
380
|
+
* Only the explicit-path file tools are checked; a narrowed scope cannot admit a
|
|
381
|
+
* whole-tree extract (no path argument). Query-based reads (`kb_search` and the
|
|
382
|
+
* citation/outline tools) carry no path to scope here and stay with the
|
|
383
|
+
* knowledge-base plugin's own authorization.
|
|
384
|
+
* @param kbScope - the bot's stored knowledge scope.
|
|
385
|
+
* @param toolName - the executing tool's name.
|
|
386
|
+
* @param args - the call's parsed arguments.
|
|
387
|
+
* @returns a model-facing denial reason, or undefined when the call is in scope.
|
|
388
|
+
*/
|
|
389
|
+
function kbScopeDenial(kbScope, toolName, args) {
|
|
390
|
+
if (kbScope.mode === "all") return void 0;
|
|
391
|
+
const argNames = KB_PATH_ARGS[toolName];
|
|
392
|
+
if (argNames === void 0) return void 0;
|
|
393
|
+
const record = typeof args === "object" && args !== null ? args : {};
|
|
394
|
+
if (toolName === "kb_file_extract" && (typeof record.path !== "string" || record.path === "")) return "this agent's knowledge scope is narrowed; a whole-tree extract is not allowed";
|
|
395
|
+
for (const argName of argNames) {
|
|
396
|
+
const value = record[argName];
|
|
397
|
+
if (typeof value !== "string" || value === "") continue;
|
|
398
|
+
if (!(kbScope.mode === "include" ? kbScope.paths.some((prefix) => underPrefix(value, prefix)) : !kbScope.paths.some((prefix) => underPrefix(value, prefix)))) return `path "${value}" is outside this agent's knowledge scope`;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Apply each bot's tool and knowledge policies to agents as they are created.
|
|
403
|
+
*
|
|
404
|
+
* The listener reads the agent's composed preset, looks up that bot, and applies
|
|
405
|
+
* the mask and guard on the agent's own scope. Both registrations are owned by the
|
|
406
|
+
* agent's context, so they lift when the agent disposes; nothing is tracked here.
|
|
407
|
+
* @param ctx - host context carrying the agent registry, tool registry, and preset registry.
|
|
408
|
+
* @param lookupBot - resolves a preset id to its stored bot, or undefined.
|
|
409
|
+
*/
|
|
410
|
+
function installPolicyEnforcement(ctx, lookupBot) {
|
|
411
|
+
ctx.on("agent/created", ({ agent }) => {
|
|
412
|
+
const presetId = ctx.agentPresets.composedPreset(agent.ctx);
|
|
413
|
+
const bot = presetId === void 0 ? void 0 : lookupBot(presetId);
|
|
414
|
+
if (bot === void 0) return;
|
|
415
|
+
const knownNames = new Set(ctx.tools.getAll(agent).map((tool) => tool.name));
|
|
416
|
+
const restriction = toolRestrictionFilter(bot.toolPolicy, knownNames);
|
|
417
|
+
if (restriction !== void 0) agent.ctx.tools.restrict(restriction);
|
|
418
|
+
if (bot.kbScope.mode !== "all") {
|
|
419
|
+
const kbScope = bot.kbScope;
|
|
420
|
+
agent.ctx.tools.guard((execution) => kbScopeDenial(kbScope, execution.name, execution.arguments));
|
|
421
|
+
}
|
|
422
|
+
}, { global: true });
|
|
423
|
+
}
|
|
424
|
+
//#endregion
|
|
425
|
+
//#region lib/types/index.js
|
|
426
|
+
/**
|
|
427
|
+
* Bot agent management — host half.
|
|
428
|
+
*
|
|
429
|
+
* Owns the durable `agents` domain, seeds the built-in super assistant, registers
|
|
430
|
+
* one agent preset per bot (the base composition with the bot's persona), and
|
|
431
|
+
* serves the CRUD routes the browser half calls. A session binds a bot by running
|
|
432
|
+
* its preset: the durable `agentPreset` header records the bot id, so the binding
|
|
433
|
+
* survives resume without a session-format change.
|
|
434
|
+
*
|
|
435
|
+
* @module @sparkelf/dsh-bot-agent
|
|
436
|
+
*/
|
|
437
|
+
/** Stable cordis plugin name. */
|
|
438
|
+
const name = "bot-agent";
|
|
439
|
+
/** Services required before the domain, routes, presets, and policy enforcement can mount. */
|
|
440
|
+
const inject = [
|
|
441
|
+
"storageDomain",
|
|
442
|
+
"webServer",
|
|
443
|
+
"agentPresets",
|
|
444
|
+
"agents",
|
|
445
|
+
"tools"
|
|
446
|
+
];
|
|
447
|
+
/** Default coverage threshold a bot's retrievalSummary must reach to win a delegation. */
|
|
448
|
+
const DEFAULT_ROUTING_MIN_COVERAGE = .3;
|
|
449
|
+
/** Runtime schema for the plugin config. */
|
|
450
|
+
const Config = z.object({
|
|
451
|
+
basePreset: z.string(),
|
|
452
|
+
routingMinCoverage: z.number().min(0).max(1).default(DEFAULT_ROUTING_MIN_COVERAGE)
|
|
453
|
+
});
|
|
454
|
+
/** How long boot waits for the base preset declaration before giving up on a bot's preset. */
|
|
455
|
+
const BASE_PRESET_DEADLINE_MS = 1e4;
|
|
456
|
+
/** Write a JSON response. */
|
|
457
|
+
function writeJson(res, status, body) {
|
|
458
|
+
const text = JSON.stringify(body);
|
|
459
|
+
res.writeHead(status, {
|
|
460
|
+
"content-type": "application/json; charset=utf-8",
|
|
461
|
+
"content-length": String(Buffer.byteLength(text))
|
|
462
|
+
});
|
|
463
|
+
res.end(text);
|
|
464
|
+
}
|
|
465
|
+
/** Read a bounded JSON request body. */
|
|
466
|
+
async function readJson(req, maxBytes) {
|
|
467
|
+
const chunks = [];
|
|
468
|
+
let total = 0;
|
|
469
|
+
for await (const chunk of req) {
|
|
470
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
471
|
+
total += buf.length;
|
|
472
|
+
if (total > maxBytes) throw new Error("request body too large");
|
|
473
|
+
chunks.push(buf);
|
|
474
|
+
}
|
|
475
|
+
if (total === 0) return {};
|
|
476
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
477
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("request body must be a JSON object");
|
|
478
|
+
return parsed;
|
|
479
|
+
}
|
|
480
|
+
/** One required string field. */
|
|
481
|
+
function requireString(value, field) {
|
|
482
|
+
if (typeof value !== "string" || value === "") throw new Error(`missing ${field}`);
|
|
483
|
+
return value;
|
|
484
|
+
}
|
|
485
|
+
/** A fresh custom bot id: kebab-case, namespaced apart from the built-in. */
|
|
486
|
+
function newBotId() {
|
|
487
|
+
return brandString(`bot-${randomBytes(6).toString("hex")}`);
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Validate a draft into a stored record, applying schema defaults.
|
|
491
|
+
* @param draft - the caller's editable fields.
|
|
492
|
+
* @param id - the bot identity.
|
|
493
|
+
* @param createdAt - creation instant, epoch milliseconds.
|
|
494
|
+
* @param builtin - whether the record is the built-in.
|
|
495
|
+
* @returns the validated bot.
|
|
496
|
+
*/
|
|
497
|
+
function draftToBot(draft, id, createdAt, builtin) {
|
|
498
|
+
return botSchema.parse({
|
|
499
|
+
id,
|
|
500
|
+
name: draft.name,
|
|
501
|
+
avatar: draft.avatar,
|
|
502
|
+
preset: draft.preset ?? {
|
|
503
|
+
identity: "",
|
|
504
|
+
duties: "",
|
|
505
|
+
workStyle: "",
|
|
506
|
+
replyStyle: ""
|
|
507
|
+
},
|
|
508
|
+
retrievalSummary: draft.retrievalSummary ?? "",
|
|
509
|
+
kbScope: draft.kbScope,
|
|
510
|
+
skillPolicy: draft.skillPolicy,
|
|
511
|
+
toolPolicy: draft.toolPolicy,
|
|
512
|
+
createdAt,
|
|
513
|
+
builtin,
|
|
514
|
+
templateId: draft.templateId
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
/** Every bot, built-in first then by creation order. */
|
|
518
|
+
function listBots(domain) {
|
|
519
|
+
return [...domain.table("bots").entries()].map(([, bot]) => bot).sort((a, b) => Number(b.builtin) - Number(a.builtin) || a.createdAt - b.createdAt);
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Register or refresh one bot's agent preset.
|
|
523
|
+
*
|
|
524
|
+
* The previous registration is disposed first so the id is free; a live session
|
|
525
|
+
* keeps the revision it composed from until it releases. A failure leaves the bot
|
|
526
|
+
* stored and logs, so CRUD never depends on the preset plane being ready.
|
|
527
|
+
* @param ctx - host context carrying the preset registry.
|
|
528
|
+
* @param bot - the bot whose preset synchronizes.
|
|
529
|
+
* @param state - the live registrations and disposed flag.
|
|
530
|
+
* @param basePreset - the composition to copy, or the registry default.
|
|
531
|
+
*/
|
|
532
|
+
async function syncPreset(ctx, bot, state, basePreset) {
|
|
533
|
+
const previous = state.disposers.get(bot.id);
|
|
534
|
+
if (previous !== void 0) {
|
|
535
|
+
state.disposers.delete(bot.id);
|
|
536
|
+
await previous();
|
|
537
|
+
}
|
|
538
|
+
if (state.disposed) return;
|
|
539
|
+
try {
|
|
540
|
+
const baseId = basePreset ?? ctx.agentPresets.defaultId;
|
|
541
|
+
if (baseId === void 0) throw new Error("no base preset configured");
|
|
542
|
+
const document = await readBaseDocument(ctx, baseId, BASE_PRESET_DEADLINE_MS);
|
|
543
|
+
if (state.disposed) return;
|
|
544
|
+
const dispose = await ctx.agentPresets.register(buildBotPreset(document, bot));
|
|
545
|
+
if (state.disposed) {
|
|
546
|
+
await dispose();
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
state.disposers.set(bot.id, dispose);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
ctx.logger.warn(`bot-agent: preset for '${bot.id}' not registered: ${String(error)}`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Seed the built-in super assistant once.
|
|
556
|
+
* @param domain - the open agents domain.
|
|
557
|
+
* @returns the built-in record, existing or freshly seeded.
|
|
558
|
+
*/
|
|
559
|
+
async function ensureBuiltin(domain) {
|
|
560
|
+
const table = domain.table("bots");
|
|
561
|
+
const existing = table.get(brandString(BUILTIN_BOT_ID));
|
|
562
|
+
if (existing !== void 0) return existing;
|
|
563
|
+
const seeded = builtinBot(Date.now());
|
|
564
|
+
await table.put(seeded.id, seeded);
|
|
565
|
+
return seeded;
|
|
566
|
+
}
|
|
567
|
+
/** The CRUD routes over one open domain. */
|
|
568
|
+
function makeRoutes(ctx, domain, state, basePreset) {
|
|
569
|
+
const table = domain.table("bots");
|
|
570
|
+
const handler = async (req, res) => {
|
|
571
|
+
const method = new URL(req.url ?? "/", "http://dsh.internal").pathname.slice(15);
|
|
572
|
+
try {
|
|
573
|
+
switch (method) {
|
|
574
|
+
case BOT_API.list:
|
|
575
|
+
writeJson(res, 200, { bots: listBots(domain) });
|
|
576
|
+
return;
|
|
577
|
+
case BOT_API.get: {
|
|
578
|
+
const body = await readJson(req, 65536);
|
|
579
|
+
const bot = table.get(brandString(requireString(body.id, "id")));
|
|
580
|
+
if (bot === void 0) {
|
|
581
|
+
writeJson(res, 404, { error: "unknown bot" });
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
writeJson(res, 200, { bot });
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
case BOT_API.create: {
|
|
588
|
+
const bot = draftToBot(await readJson(req, 1 << 20), newBotId(), Date.now(), false);
|
|
589
|
+
await table.put(bot.id, bot);
|
|
590
|
+
await syncPreset(ctx, bot, state, basePreset);
|
|
591
|
+
writeJson(res, 200, { bot });
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
case BOT_API.update: {
|
|
595
|
+
const body = await readJson(req, 1 << 20);
|
|
596
|
+
const id = brandString(requireString(body.id, "id"));
|
|
597
|
+
const existing = table.get(id);
|
|
598
|
+
if (existing === void 0) {
|
|
599
|
+
writeJson(res, 404, { error: "unknown bot" });
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
const next = draftToBot(body, id, existing.createdAt, existing.builtin);
|
|
603
|
+
await table.put(id, next);
|
|
604
|
+
await syncPreset(ctx, next, state, basePreset);
|
|
605
|
+
writeJson(res, 200, { bot: next });
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
case BOT_API.delete: {
|
|
609
|
+
const id = brandString(requireString((await readJson(req, 65536)).id, "id"));
|
|
610
|
+
const existing = table.get(id);
|
|
611
|
+
if (existing === void 0) {
|
|
612
|
+
writeJson(res, 404, { error: "unknown bot" });
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
if (existing.builtin) {
|
|
616
|
+
writeJson(res, 403, { error: "the built-in assistant cannot be deleted" });
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
await table.delete(id);
|
|
620
|
+
const dispose = state.disposers.get(id);
|
|
621
|
+
if (dispose !== void 0) {
|
|
622
|
+
state.disposers.delete(id);
|
|
623
|
+
await dispose();
|
|
624
|
+
}
|
|
625
|
+
writeJson(res, 200, { ok: true });
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
default: writeJson(res, 404, { error: `unknown method ${method}` });
|
|
629
|
+
}
|
|
630
|
+
} catch (error) {
|
|
631
|
+
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
return [{
|
|
635
|
+
kind: "prefix",
|
|
636
|
+
path: BOT_API_PREFIX,
|
|
637
|
+
handler
|
|
638
|
+
}];
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Mount the bot domain, built-in seed, presets, and CRUD routes.
|
|
642
|
+
* @param ctx - host context carrying storage, the web server, and the preset registry.
|
|
643
|
+
* @param config - resolved plugin config.
|
|
644
|
+
*/
|
|
645
|
+
function apply(ctx, config = {}) {
|
|
646
|
+
const state = {
|
|
647
|
+
disposers: /* @__PURE__ */ new Map(),
|
|
648
|
+
disposed: false
|
|
649
|
+
};
|
|
650
|
+
ctx.effect(async () => {
|
|
651
|
+
const domain = await ctx.storageDomain.open(agentsDomain);
|
|
652
|
+
await ensureBuiltin(domain);
|
|
653
|
+
installPolicyEnforcement(ctx, (presetId) => domain.table("bots").get(brandString(presetId)));
|
|
654
|
+
const routeDisposers = makeRoutes(ctx, domain, state, config.basePreset).map((route) => ctx.webServer.register(route));
|
|
655
|
+
for (const bot of listBots(domain)) {
|
|
656
|
+
if (state.disposed) break;
|
|
657
|
+
await syncPreset(ctx, bot, state, config.basePreset);
|
|
658
|
+
}
|
|
659
|
+
const minCoverage = config.routingMinCoverage ?? DEFAULT_ROUTING_MIN_COVERAGE;
|
|
660
|
+
const proposalDisposer = ctx.on("subagent/preset-proposal", (request, next) => {
|
|
661
|
+
const match = matchBotPreset(listBots(domain).filter((bot) => !bot.builtin && state.disposers.has(bot.id)), `${request.description}\n${request.prompt}`, minCoverage);
|
|
662
|
+
return match === void 0 ? next() : Promise.resolve(match);
|
|
663
|
+
});
|
|
664
|
+
return async () => {
|
|
665
|
+
state.disposed = true;
|
|
666
|
+
proposalDisposer();
|
|
667
|
+
for (const dispose of routeDisposers) dispose();
|
|
668
|
+
for (const dispose of state.disposers.values()) await dispose();
|
|
669
|
+
state.disposers.clear();
|
|
670
|
+
await domain.close();
|
|
671
|
+
};
|
|
672
|
+
}, "bot-agent: domain, routes, presets, routing");
|
|
673
|
+
}
|
|
674
|
+
//#endregion
|
|
675
|
+
export { Config, apply, inject, name };
|