@sparkelf/dsh-bot-agent 0.0.0-stage → 0.2.9-alpha.125

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/lib/index.js ADDED
@@ -0,0 +1,554 @@
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
+ /**
162
+ * Compose the bot's persona prefix from its four prose fields.
163
+ *
164
+ * An empty identity keeps the base composition's own prefix, so a bot that only
165
+ * sets duties still runs the deployment's coding-agent prompt. The non-empty
166
+ * fields append as labelled sections.
167
+ * @param bot - the bot whose prose composes the prefix.
168
+ * @param basePrefix - the base composition's persona prefix, the identity fallback.
169
+ * @returns the persona prefix template.
170
+ */
171
+ function botPersonaPrefix(bot, basePrefix) {
172
+ const sections = [bot.preset.identity.trim() || basePrefix];
173
+ const duties = bot.preset.duties.trim();
174
+ const workStyle = bot.preset.workStyle.trim();
175
+ const replyStyle = bot.preset.replyStyle.trim();
176
+ if (duties !== "") sections.push(`Duties:\n${duties}`);
177
+ if (workStyle !== "") sections.push(`Work style:\n${workStyle}`);
178
+ if (replyStyle !== "") sections.push(`Reply style:\n${replyStyle}`);
179
+ return sections.join("\n\n");
180
+ }
181
+ /**
182
+ * Locate the persona row in a parsed composition, descending into groups.
183
+ * @param rows - parsed child rows.
184
+ * @returns the persona row and its current prefix, or undefined when none is declared.
185
+ */
186
+ function findPersona(rows) {
187
+ for (const value of rows) {
188
+ if (typeof value !== "object" || value === null) continue;
189
+ const row = value;
190
+ if (row.group === true && Array.isArray(row.config)) {
191
+ const nested = findPersona(row.config);
192
+ if (nested !== void 0) return nested;
193
+ }
194
+ if (row.name === PERSONA_MODULE) {
195
+ const config = typeof row.config === "object" && row.config !== null ? row.config : {};
196
+ return {
197
+ row,
198
+ basePrefix: typeof config.prefix === "string" ? config.prefix : ""
199
+ };
200
+ }
201
+ }
202
+ }
203
+ /**
204
+ * Read the base preset's document, waiting out the boot ordering where the base
205
+ * declaration registers after this plugin activates.
206
+ * @param ctx - host context carrying the preset registry.
207
+ * @param baseId - the preset identity to copy.
208
+ * @param deadlineMs - how long to wait for the declaration to appear.
209
+ * @returns the base document.
210
+ * @throws the last read failure once the deadline passes.
211
+ */
212
+ async function readBaseDocument(ctx, baseId, deadlineMs) {
213
+ const start = Date.now();
214
+ for (;;) try {
215
+ return await ctx.agentPresets.readDocument(baseId);
216
+ } catch (error) {
217
+ if (Date.now() - start >= deadlineMs) throw error;
218
+ await setTimeout(100);
219
+ }
220
+ }
221
+ /**
222
+ * Build the bot's preset definition from the base composition.
223
+ * @param document - the base preset's declared document.
224
+ * @param bot - the bot whose persona and metadata the preset carries.
225
+ * @returns a definition ready for `agentPresets.register`.
226
+ */
227
+ function buildBotPreset(document, bot) {
228
+ const parsed = parseEntryYaml(document.content);
229
+ const rows = Array.isArray(parsed) ? parsed : [];
230
+ const persona = findPersona(rows);
231
+ const prefix = botPersonaPrefix(bot, persona?.basePrefix ?? "");
232
+ if (persona !== void 0) {
233
+ const config = typeof persona.row.config === "object" && persona.row.config !== null ? persona.row.config : {};
234
+ persona.row.config = {
235
+ ...config,
236
+ prefix
237
+ };
238
+ } else rows.unshift({
239
+ id: "persona",
240
+ name: PERSONA_MODULE,
241
+ config: { prefix }
242
+ });
243
+ const description = bot.retrievalSummary.trim() || bot.preset.duties.trim() || bot.name;
244
+ return {
245
+ id: bot.id,
246
+ name: bot.name,
247
+ description,
248
+ plugins: rows
249
+ };
250
+ }
251
+ //#endregion
252
+ //#region lib/types/routing.js
253
+ /**
254
+ * Task→bot routing: match a delegation's task text against each bot's
255
+ * retrievalSummary and pick the best-covering bot preset.
256
+ *
257
+ * The business rule lives here, not in the delegation tool: `dsh-tool-subagent`
258
+ * offers the task text through the `subagent/preset-proposal` waterfall, and this
259
+ * package's host half answers with a bot id. Matching is token coverage — the
260
+ * fraction of a summary's tokens that appear in the task — over ASCII words and
261
+ * CJK character bigrams, so Chinese summaries match without a segmenter.
262
+ * @module @sparkelf/dsh-bot-agent/routing
263
+ */
264
+ /** CJK ideograph runs tokenized into sliding bigrams (main block, ext A, compatibility). */
265
+ const CJK_RUN = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+/g;
266
+ /**
267
+ * Tokenize text for coverage matching: lowercase ASCII words plus CJK character
268
+ * bigrams. Bigrams approximate Chinese word boundaries without a segmenter; a
269
+ * one-character CJK run yields no bigram and contributes nothing.
270
+ * @param text - the task or summary text.
271
+ * @returns the distinct match tokens.
272
+ */
273
+ function matchTokens(text) {
274
+ const tokens = /* @__PURE__ */ new Set();
275
+ const lower = text.toLowerCase();
276
+ for (const word of lower.match(/[a-z0-9]+/g) ?? []) tokens.add(word);
277
+ 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));
278
+ return tokens;
279
+ }
280
+ /**
281
+ * Pick the bot whose retrievalSummary best covers the task text. Coverage is the
282
+ * fraction of the summary's tokens present in the task; a bot is eligible only
283
+ * when its coverage reaches `minCoverage`. The highest-coverage eligible bot wins;
284
+ * ties keep the caller's order. A bot with an empty summary is never eligible.
285
+ * @param bots - candidate bots, in the caller's preference order.
286
+ * @param taskText - the delegation's task text (description and prompt).
287
+ * @param minCoverage - the minimum coverage in [0,1] a bot must reach.
288
+ * @returns the selected bot id, or undefined when no bot reaches the threshold.
289
+ */
290
+ function matchBotPreset(bots, taskText, minCoverage) {
291
+ const taskTokens = matchTokens(taskText);
292
+ let best;
293
+ for (const bot of bots) {
294
+ const summaryTokens = matchTokens(bot.retrievalSummary);
295
+ if (summaryTokens.size === 0) continue;
296
+ let hit = 0;
297
+ for (const token of summaryTokens) if (taskTokens.has(token)) hit += 1;
298
+ const coverage = hit / summaryTokens.size;
299
+ if (coverage >= minCoverage && (best === void 0 || coverage > best.coverage)) best = {
300
+ id: bot.id,
301
+ coverage
302
+ };
303
+ }
304
+ return best?.id;
305
+ }
306
+ //#endregion
307
+ //#region lib/types/index.js
308
+ /**
309
+ * Bot agent management — host half.
310
+ *
311
+ * Owns the durable `agents` domain, seeds the built-in super assistant, registers
312
+ * one agent preset per bot (the base composition with the bot's persona), and
313
+ * serves the CRUD routes the browser half calls. A session binds a bot by running
314
+ * its preset: the durable `agentPreset` header records the bot id, so the binding
315
+ * survives resume without a session-format change.
316
+ *
317
+ * @module @sparkelf/dsh-bot-agent
318
+ */
319
+ /** Stable cordis plugin name. */
320
+ const name = "bot-agent";
321
+ /** Services required before the domain, routes, and presets can mount. */
322
+ const inject = [
323
+ "storageDomain",
324
+ "webServer",
325
+ "agentPresets"
326
+ ];
327
+ /** Default coverage threshold a bot's retrievalSummary must reach to win a delegation. */
328
+ const DEFAULT_ROUTING_MIN_COVERAGE = .3;
329
+ /** Runtime schema for the plugin config. */
330
+ const Config = z.object({
331
+ basePreset: z.string(),
332
+ routingMinCoverage: z.number().min(0).max(1).default(DEFAULT_ROUTING_MIN_COVERAGE)
333
+ });
334
+ /** How long boot waits for the base preset declaration before giving up on a bot's preset. */
335
+ const BASE_PRESET_DEADLINE_MS = 1e4;
336
+ /** Write a JSON response. */
337
+ function writeJson(res, status, body) {
338
+ const text = JSON.stringify(body);
339
+ res.writeHead(status, {
340
+ "content-type": "application/json; charset=utf-8",
341
+ "content-length": String(Buffer.byteLength(text))
342
+ });
343
+ res.end(text);
344
+ }
345
+ /** Read a bounded JSON request body. */
346
+ async function readJson(req, maxBytes) {
347
+ const chunks = [];
348
+ let total = 0;
349
+ for await (const chunk of req) {
350
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
351
+ total += buf.length;
352
+ if (total > maxBytes) throw new Error("request body too large");
353
+ chunks.push(buf);
354
+ }
355
+ if (total === 0) return {};
356
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
357
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("request body must be a JSON object");
358
+ return parsed;
359
+ }
360
+ /** One required string field. */
361
+ function requireString(value, field) {
362
+ if (typeof value !== "string" || value === "") throw new Error(`missing ${field}`);
363
+ return value;
364
+ }
365
+ /** A fresh custom bot id: kebab-case, namespaced apart from the built-in. */
366
+ function newBotId() {
367
+ return brandString(`bot-${randomBytes(6).toString("hex")}`);
368
+ }
369
+ /**
370
+ * Validate a draft into a stored record, applying schema defaults.
371
+ * @param draft - the caller's editable fields.
372
+ * @param id - the bot identity.
373
+ * @param createdAt - creation instant, epoch milliseconds.
374
+ * @param builtin - whether the record is the built-in.
375
+ * @returns the validated bot.
376
+ */
377
+ function draftToBot(draft, id, createdAt, builtin) {
378
+ return botSchema.parse({
379
+ id,
380
+ name: draft.name,
381
+ avatar: draft.avatar,
382
+ preset: draft.preset ?? {
383
+ identity: "",
384
+ duties: "",
385
+ workStyle: "",
386
+ replyStyle: ""
387
+ },
388
+ retrievalSummary: draft.retrievalSummary ?? "",
389
+ kbScope: draft.kbScope,
390
+ skillPolicy: draft.skillPolicy,
391
+ toolPolicy: draft.toolPolicy,
392
+ createdAt,
393
+ builtin,
394
+ templateId: draft.templateId
395
+ });
396
+ }
397
+ /** Every bot, built-in first then by creation order. */
398
+ function listBots(domain) {
399
+ return [...domain.table("bots").entries()].map(([, bot]) => bot).sort((a, b) => Number(b.builtin) - Number(a.builtin) || a.createdAt - b.createdAt);
400
+ }
401
+ /**
402
+ * Register or refresh one bot's agent preset.
403
+ *
404
+ * The previous registration is disposed first so the id is free; a live session
405
+ * keeps the revision it composed from until it releases. A failure leaves the bot
406
+ * stored and logs, so CRUD never depends on the preset plane being ready.
407
+ * @param ctx - host context carrying the preset registry.
408
+ * @param bot - the bot whose preset synchronizes.
409
+ * @param state - the live registrations and disposed flag.
410
+ * @param basePreset - the composition to copy, or the registry default.
411
+ */
412
+ async function syncPreset(ctx, bot, state, basePreset) {
413
+ const previous = state.disposers.get(bot.id);
414
+ if (previous !== void 0) {
415
+ state.disposers.delete(bot.id);
416
+ await previous();
417
+ }
418
+ if (state.disposed) return;
419
+ try {
420
+ const baseId = basePreset ?? ctx.agentPresets.defaultId;
421
+ if (baseId === void 0) throw new Error("no base preset configured");
422
+ const document = await readBaseDocument(ctx, baseId, BASE_PRESET_DEADLINE_MS);
423
+ if (state.disposed) return;
424
+ const dispose = await ctx.agentPresets.register(buildBotPreset(document, bot));
425
+ if (state.disposed) {
426
+ await dispose();
427
+ return;
428
+ }
429
+ state.disposers.set(bot.id, dispose);
430
+ } catch (error) {
431
+ ctx.logger.warn(`bot-agent: preset for '${bot.id}' not registered: ${String(error)}`);
432
+ }
433
+ }
434
+ /**
435
+ * Seed the built-in super assistant once.
436
+ * @param domain - the open agents domain.
437
+ * @returns the built-in record, existing or freshly seeded.
438
+ */
439
+ async function ensureBuiltin(domain) {
440
+ const table = domain.table("bots");
441
+ const existing = table.get(brandString(BUILTIN_BOT_ID));
442
+ if (existing !== void 0) return existing;
443
+ const seeded = builtinBot(Date.now());
444
+ await table.put(seeded.id, seeded);
445
+ return seeded;
446
+ }
447
+ /** The CRUD routes over one open domain. */
448
+ function makeRoutes(ctx, domain, state, basePreset) {
449
+ const table = domain.table("bots");
450
+ const handler = async (req, res) => {
451
+ const method = new URL(req.url ?? "/", "http://dsh.internal").pathname.slice(15);
452
+ try {
453
+ switch (method) {
454
+ case BOT_API.list:
455
+ writeJson(res, 200, { bots: listBots(domain) });
456
+ return;
457
+ case BOT_API.get: {
458
+ const body = await readJson(req, 65536);
459
+ const bot = table.get(brandString(requireString(body.id, "id")));
460
+ if (bot === void 0) {
461
+ writeJson(res, 404, { error: "unknown bot" });
462
+ return;
463
+ }
464
+ writeJson(res, 200, { bot });
465
+ return;
466
+ }
467
+ case BOT_API.create: {
468
+ const bot = draftToBot(await readJson(req, 1 << 20), newBotId(), Date.now(), false);
469
+ await table.put(bot.id, bot);
470
+ await syncPreset(ctx, bot, state, basePreset);
471
+ writeJson(res, 200, { bot });
472
+ return;
473
+ }
474
+ case BOT_API.update: {
475
+ const body = await readJson(req, 1 << 20);
476
+ const id = brandString(requireString(body.id, "id"));
477
+ const existing = table.get(id);
478
+ if (existing === void 0) {
479
+ writeJson(res, 404, { error: "unknown bot" });
480
+ return;
481
+ }
482
+ const next = draftToBot(body, id, existing.createdAt, existing.builtin);
483
+ await table.put(id, next);
484
+ await syncPreset(ctx, next, state, basePreset);
485
+ writeJson(res, 200, { bot: next });
486
+ return;
487
+ }
488
+ case BOT_API.delete: {
489
+ const id = brandString(requireString((await readJson(req, 65536)).id, "id"));
490
+ const existing = table.get(id);
491
+ if (existing === void 0) {
492
+ writeJson(res, 404, { error: "unknown bot" });
493
+ return;
494
+ }
495
+ if (existing.builtin) {
496
+ writeJson(res, 403, { error: "the built-in assistant cannot be deleted" });
497
+ return;
498
+ }
499
+ await table.delete(id);
500
+ const dispose = state.disposers.get(id);
501
+ if (dispose !== void 0) {
502
+ state.disposers.delete(id);
503
+ await dispose();
504
+ }
505
+ writeJson(res, 200, { ok: true });
506
+ return;
507
+ }
508
+ default: writeJson(res, 404, { error: `unknown method ${method}` });
509
+ }
510
+ } catch (error) {
511
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
512
+ }
513
+ };
514
+ return [{
515
+ kind: "prefix",
516
+ path: BOT_API_PREFIX,
517
+ handler
518
+ }];
519
+ }
520
+ /**
521
+ * Mount the bot domain, built-in seed, presets, and CRUD routes.
522
+ * @param ctx - host context carrying storage, the web server, and the preset registry.
523
+ * @param config - resolved plugin config.
524
+ */
525
+ function apply(ctx, config = {}) {
526
+ const state = {
527
+ disposers: /* @__PURE__ */ new Map(),
528
+ disposed: false
529
+ };
530
+ ctx.effect(async () => {
531
+ const domain = await ctx.storageDomain.open(agentsDomain);
532
+ await ensureBuiltin(domain);
533
+ const routeDisposers = makeRoutes(ctx, domain, state, config.basePreset).map((route) => ctx.webServer.register(route));
534
+ for (const bot of listBots(domain)) {
535
+ if (state.disposed) break;
536
+ await syncPreset(ctx, bot, state, config.basePreset);
537
+ }
538
+ const minCoverage = config.routingMinCoverage ?? DEFAULT_ROUTING_MIN_COVERAGE;
539
+ const proposalDisposer = ctx.on("subagent/preset-proposal", (request, next) => {
540
+ const match = matchBotPreset(listBots(domain).filter((bot) => !bot.builtin && state.disposers.has(bot.id)), `${request.description}\n${request.prompt}`, minCoverage);
541
+ return match === void 0 ? next() : Promise.resolve(match);
542
+ });
543
+ return async () => {
544
+ state.disposed = true;
545
+ proposalDisposer();
546
+ for (const dispose of routeDisposers) dispose();
547
+ for (const dispose of state.disposers.values()) await dispose();
548
+ state.disposers.clear();
549
+ await domain.close();
550
+ };
551
+ }, "bot-agent: domain, routes, presets, routing");
552
+ }
553
+ //#endregion
554
+ export { Config, apply, inject, name };
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The same-origin API surface shared by this package's two halves.
3
+ *
4
+ * The Host registers one prefix and dispatches on the trailing method name; the
5
+ * browser calls the same strings. Keeping them in one module stops the halves
6
+ * drifting apart. This module stays dependency-free so both bundles can import
7
+ * it: the Client bundle rejects Node builtins and non-platform packages.
8
+ *
9
+ * @module @sparkelf/dsh-bot-agent/api
10
+ */
11
+ /** Prefix the Host registers and the browser calls. */
12
+ export declare const BOT_API_PREFIX = "/bot-agent/api";
13
+ /** Method names the Host dispatches on. */
14
+ export declare const BOT_API: {
15
+ /** Every bot, built-in first. */
16
+ readonly list: "list";
17
+ /** One bot by id. */
18
+ readonly get: "get";
19
+ /** Create a custom bot. */
20
+ readonly create: "create";
21
+ /** Update a bot's editable fields. */
22
+ readonly update: "update";
23
+ /** Delete a custom bot; the built-in is refused. */
24
+ readonly delete: "delete";
25
+ };
26
+ /** One bot's persona prose, composed into its agent preset's system prompt. */
27
+ export interface BotPresetWire {
28
+ identity: string;
29
+ duties: string;
30
+ workStyle: string;
31
+ replyStyle: string;
32
+ }
33
+ /** A skill or tool black/white list. `all` admits everything; the list is unused. */
34
+ export interface BotPolicyWire {
35
+ mode: 'all' | 'allow' | 'deny';
36
+ list: string[];
37
+ }
38
+ /** Knowledge-base scope. `all` admits the whole library; the paths narrow it. */
39
+ export interface BotKbScopeWire {
40
+ mode: 'all' | 'include' | 'exclude';
41
+ paths: string[];
42
+ }
43
+ /** One bot as the browser receives it. */
44
+ export interface BotWire {
45
+ id: string;
46
+ name: string;
47
+ avatar: string;
48
+ preset: BotPresetWire;
49
+ retrievalSummary: string;
50
+ kbScope: BotKbScopeWire;
51
+ skillPolicy: BotPolicyWire;
52
+ toolPolicy: BotPolicyWire;
53
+ createdAt: number;
54
+ builtin: boolean;
55
+ /** Marketplace template this bot was copied from; absent for hand-made bots. */
56
+ templateId?: string;
57
+ }
58
+ /** Fields a create or update accepts; the Host fills id, createdAt, and builtin. */
59
+ export interface BotDraftWire {
60
+ name: string;
61
+ avatar: string;
62
+ preset: BotPresetWire;
63
+ retrievalSummary: string;
64
+ kbScope?: BotKbScopeWire;
65
+ skillPolicy?: BotPolicyWire;
66
+ toolPolicy?: BotPolicyWire;
67
+ /** Marketplace template id when the draft copies a template. */
68
+ templateId?: string;
69
+ }
70
+ //# sourceMappingURL=api.d.ts.map
@@ -0,0 +1,12 @@
1
+ import type { Bot } from './storage.ts';
2
+ /** Stable id of the built-in bot; also its agent preset id. */
3
+ export declare const BUILTIN_BOT_ID = "bot-super";
4
+ /** Avatar catalog key the built-in renders. */
5
+ export declare const BUILTIN_AVATAR = "super";
6
+ /**
7
+ * The seed record for the built-in super assistant.
8
+ * @param now - creation instant, epoch milliseconds.
9
+ * @returns the built-in bot, marked `builtin`.
10
+ */
11
+ export declare function builtinBot(now: number): Bot;
12
+ //# sourceMappingURL=builtin.d.ts.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * One bot avatar: the catalog's hue and glyph drawn through the shared
3
+ * {@link HueTile} recipe (rounded tile, gradient, top highlight, hairline).
4
+ * Self-written and offline-safe; the same component serves the grid card, the
5
+ * detail header, the picker, and the session-row seat at the size each surface
6
+ * asks for.
7
+ *
8
+ * @module @sparkelf/dsh-bot-agent/client/BotAvatar
9
+ */
10
+ import type { ReactNode } from 'react';
11
+ /** Props of one avatar render. */
12
+ export interface BotAvatarProps {
13
+ /** Stored avatar key. */
14
+ avatar: string;
15
+ /** Edge length in pixels. */
16
+ size: number;
17
+ /** Accessible name; omitted renders a decorative glyph. */
18
+ label?: string;
19
+ }
20
+ /**
21
+ * Render the avatar tile.
22
+ * @param props - avatar key, edge size, and optional accessible name.
23
+ * @returns the avatar SVG.
24
+ */
25
+ export declare function BotAvatar({ avatar, size, label }: BotAvatarProps): ReactNode;
26
+ //# sourceMappingURL=BotAvatar.d.ts.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Avatar picker: the curated SVG catalog as a selectable grid.
3
+ *
4
+ * @module @sparkelf/dsh-bot-agent/client/BotAvatarPicker
5
+ */
6
+ import type { ReactNode } from 'react';
7
+ import type { BotLocaleKey } from './locales.ts';
8
+ /** Props of the avatar picker. */
9
+ export interface BotAvatarPickerProps {
10
+ value: string;
11
+ onChange: (key: string) => void;
12
+ t: (key: BotLocaleKey) => string;
13
+ }
14
+ /**
15
+ * Render the avatar catalog as a radio-like grid.
16
+ * @param props - selected key, change callback, and copy resolver.
17
+ * @returns the picker grid.
18
+ */
19
+ export declare function BotAvatarPicker({ value, onChange, t }: BotAvatarPickerProps): ReactNode;
20
+ //# sourceMappingURL=BotAvatarPicker.d.ts.map