@dsh-agentic-roleplay/core 0.7.2 → 0.8.1

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.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/lib/authoring-tools-DNnx0Nts.js +3574 -0
  3. package/lib/authoring.js +295 -333
  4. package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
  5. package/lib/client.js +931 -415
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +2 -2
  8. package/lib/doctor.js +2 -2
  9. package/lib/{gallery-BxZGOgMb.js → gallery-D9nG3C78.js} +2 -2
  10. package/lib/{generator-BFmSYvR8.js → generator-r1Czm7oi.js} +2 -2
  11. package/lib/helper.js +1 -1
  12. package/lib/{hooks-HnqXO8mM.js → hooks-BQCzgggH.js} +92 -8
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +1326 -1638
  15. package/lib/{library-BGxPKs9a.js → library-zI-2tG7h.js} +59 -9
  16. package/lib/{lorebook-author-tools-D9RrMK5g.js → lorebook-author-tools-ywaYicwd.js} +7 -7
  17. package/lib/lorebook-authoring.js +4 -4
  18. package/lib/{narration-DvFBqmqe.js → narration-CnBlVure.js} +52 -8
  19. package/lib/orchestration.js +95 -18
  20. package/lib/{pack-jail-MPekqSuQ.js → pack-jail-5EJ-WYyW.js} +1274 -69
  21. package/lib/{packs-jowC-MN_.js → packs-Cv8hanXJ.js} +2 -2
  22. package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-BSaMSd3G.js} +6 -6
  23. package/lib/{preset-VatN-845.js → preset-CWI3-0r1.js} +4 -3
  24. package/lib/{preset-author-tools-8kv1Glxe.js → preset-author-tools-BrJYa2cr.js} +7 -7
  25. package/lib/preset-authoring.js +5 -5
  26. package/lib/presets-MwOSMMyu.js +3998 -0
  27. package/lib/{reflection-CvOZGjmn.js → reflection-zSaMsjKj.js} +127 -127
  28. package/lib/{text-JbWfTHbr.js → text-BzudpQLS.js} +11 -1
  29. package/lib/{turn-guard-BvCs1VxB.js → turn-guard-Cv8pfHEA.js} +6 -2
  30. package/package.json +2 -2
  31. package/prompts/en/import/casting.md +14 -0
  32. package/prompts/en/import/classifier.md +9 -0
  33. package/prompts/en/import/finish-draft.md +1 -0
  34. package/prompts/en/import/generator.md +8 -0
  35. package/prompts/en/import/notice-repair.md +4 -0
  36. package/prompts/en/import/repair-again.md +3 -0
  37. package/prompts/en/import/roster.md +1 -0
  38. package/prompts/en/import/variables.md +1 -0
  39. package/prompts/en/roleplay/game-master.md +3 -0
  40. package/prompts/en/roleplay/standing.md +1 -0
  41. package/prompts/en/world/author.md +1 -1
  42. package/prompts/zh/import/casting.md +14 -0
  43. package/prompts/zh/import/classifier.md +9 -0
  44. package/prompts/zh/import/finish-draft.md +1 -0
  45. package/prompts/zh/import/generator.md +8 -0
  46. package/prompts/zh/import/notice-repair.md +4 -0
  47. package/prompts/zh/import/repair-again.md +3 -0
  48. package/prompts/zh/import/roster.md +1 -0
  49. package/prompts/zh/import/variables.md +1 -0
  50. package/prompts/zh/roleplay/game-master.md +3 -0
  51. package/prompts/zh/roleplay/standing.md +1 -0
  52. package/prompts/zh/world/author.md +1 -1
  53. package/lib/authoring-tools-q34iq3hW.js +0 -6140
  54. package/lib/route-DRTJ_vcA.js +0 -518
@@ -1,518 +0,0 @@
1
- import "./narration-DvFBqmqe.js";
2
- import { $ as listFiles, J as PROMPTS_FOLDER, Q as languageOf, et as promptProblem, nt as shippedPromptsDirectory, q as LANGUAGE_FOLDER, tt as shippedLanguages } from "./hooks-HnqXO8mM.js";
3
- import { u as parseSampling } from "./child-CyCViUKa.js";
4
- import { dirname, join } from "node:path";
5
- import { existsSync, readFileSync, readdirSync } from "node:fs";
6
- import { createHash } from "node:crypto";
7
- import { mkdir, rename, rm, writeFile } from "node:fs/promises";
8
- //#region ../dsh-roleplay-model/src/intent.ts
9
- const INTENT_TYPES = [
10
- "need",
11
- "obligation",
12
- "quest",
13
- "agenda",
14
- "aspiration",
15
- "relationship",
16
- "habit",
17
- "reaction"
18
- ];
19
- const INTENT_STATUSES = [
20
- "active",
21
- "paused",
22
- "completed",
23
- "failed",
24
- "abandoned"
25
- ];
26
- const INTENT_HORIZONS = [
27
- "immediate",
28
- "short",
29
- "day",
30
- "long",
31
- "open_ended"
32
- ];
33
- //#endregion
34
- //#region src/host/prompts/world-prompts.ts
35
- /** The prompts that decide how the story is written and who the models are (prose and persona); every other prompt holds rules of the game. */
36
- const PROSE_PROMPTS = [
37
- "roleplay/persona",
38
- "roleplay/style",
39
- "roleplay/character-style"
40
- ];
41
- function shippedFile(shipped, language, id) {
42
- return [language, "en"].map((name) => join(shipped, name, `${id}.md`)).find((path) => existsSync(path));
43
- }
44
- function fileOf(directory, language, id, shipped) {
45
- const problem = promptProblem(language, id, "x", shipped);
46
- if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story; the ones that can be carried are listed by list_world_prompts`);
47
- if (problem !== void 0 && problem.startsWith("there is no prompt")) throw new Error(problem);
48
- return join(directory, PROMPTS_FOLDER, language, `${id}.md`);
49
- }
50
- /** Every prompt of the story, in a language, and whether the world carries its own version. */
51
- function listWorldPrompts(directory, language, shipped = shippedPromptsDirectory()) {
52
- const tag = languageOf(language);
53
- return readdirSync(join(shipped, "en"), { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name === "roleplay").flatMap((entry) => listFiles(join(shipped, "en", entry.name), `${entry.name}/`)).sort().map((id) => ({
54
- id,
55
- kind: PROSE_PROMPTS.includes(id) ? "prose" : "rules",
56
- carried: existsSync(join(directory, PROMPTS_FOLDER, tag, `${id}.md`))
57
- }));
58
- }
59
- /** A prompt as sessions of the world get it: the world's own version, else the shipped text. */
60
- function readWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
61
- const tag = languageOf(language);
62
- const own = fileOf(directory, tag, id, shipped);
63
- if (existsSync(own)) return {
64
- id,
65
- language: tag,
66
- carried: true,
67
- text: readFileSync(own, "utf8")
68
- };
69
- const original = shippedFile(shipped, tag, id);
70
- return {
71
- id,
72
- language: tag,
73
- carried: false,
74
- text: original === void 0 ? "" : readFileSync(original, "utf8")
75
- };
76
- }
77
- /** @throws {Error} when the text is not acceptable for the prompt: see `promptProblem`. */
78
- async function writeWorldPrompt(directory, language, id, text, shipped = shippedPromptsDirectory()) {
79
- const tag = languageOf(language);
80
- const file = fileOf(directory, tag, id, shipped);
81
- const problem = promptProblem(tag, id, text, shipped);
82
- if (problem !== void 0) throw new Error(problem);
83
- await mkdir(dirname(file), { recursive: true });
84
- const temporary = `${file}.tmp`;
85
- await writeFile(temporary, text.endsWith("\n") ? text : `${text}\n`);
86
- await rename(temporary, file);
87
- }
88
- /** Moves the world's own version into its `.trash`, so sessions use the shipped one again. @returns where it went. */
89
- async function deleteWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
90
- const tag = languageOf(language);
91
- const file = fileOf(directory, tag, id, shipped);
92
- if (!existsSync(file)) throw new Error(`the world carries no prompt "${id}" in ${tag}`);
93
- const aside = join(directory, ".trash", PROMPTS_FOLDER, tag, `${id}.${Date.now()}.md`);
94
- await mkdir(dirname(aside), { recursive: true });
95
- await rename(file, aside);
96
- await rm(dirname(file), { recursive: false }).catch(() => void 0);
97
- return aside;
98
- }
99
- //#endregion
100
- //#region src/host/presets/presets.ts
101
- const PRESETS_FOLDER = "presets";
102
- const PRESET_FILE = "preset.json";
103
- const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
104
- const MAX_TEXT = 300;
105
- const isPresetName = (name) => NAME.test(name);
106
- const presetsDirectory = (root) => join(root, PRESETS_FOLDER);
107
- function presetDirectory(root, name) {
108
- if (!isPresetName(name)) throw new Error(`"${name}" is not a usable preset name (letters, digits, "-" and "_", up to 64)`);
109
- return join(presetsDirectory(root), name);
110
- }
111
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
112
- function parseHeader(value, problems) {
113
- if (!isRecord(value)) {
114
- problems.push(`${PRESET_FILE} must be an object`);
115
- return { sampling: {} };
116
- }
117
- const text = (key) => {
118
- const field = value[key];
119
- if (field === void 0 || field === null) return void 0;
120
- if (typeof field !== "string" || field.length > MAX_TEXT) {
121
- problems.push(`${PRESET_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
122
- return;
123
- }
124
- return field.trim() || void 0;
125
- };
126
- const sampling = parseSampling(value["sampling"], `${PRESET_FILE}: sampling`, problems);
127
- const title = text("title");
128
- const description = text("description");
129
- return {
130
- ...title === void 0 ? {} : { title },
131
- ...description === void 0 ? {} : { description },
132
- sampling
133
- };
134
- }
135
- function readHeader(directory, problems) {
136
- const file = join(directory, PRESET_FILE);
137
- if (!existsSync(file)) return { sampling: {} };
138
- let value;
139
- try {
140
- value = JSON.parse(readFileSync(file, "utf8"));
141
- } catch {
142
- problems.push(`${PRESET_FILE} is not valid JSON`);
143
- return { sampling: {} };
144
- }
145
- return parseHeader(value, problems);
146
- }
147
- /** Reads one preset folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
148
- function readPreset(directory, name, shipped = shippedPromptsDirectory()) {
149
- if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
150
- const problems = [];
151
- const header = readHeader(directory, problems);
152
- const files = /* @__PURE__ */ new Map();
153
- const base = join(directory, PROMPTS_FOLDER);
154
- if (existsSync(base)) for (const entry of readdirSync(base, { withFileTypes: true })) {
155
- if (!entry.isDirectory() || !LANGUAGE_FOLDER.test(entry.name)) {
156
- problems.push(`prompts/${entry.name}: prompts are kept in a folder named by the language, such as en or zh`);
157
- continue;
158
- }
159
- for (const id of listFiles(join(base, entry.name))) {
160
- const path = `${entry.name}/${id}.md`;
161
- const text = readFileSync(join(base, path), "utf8");
162
- const problem = id.startsWith("roleplay/") ? promptProblem(entry.name, id, text, shipped) : `"${id}" is not a prompt of the story`;
163
- if (problem !== void 0) problems.push(`prompts/${path}: ${problem}`);
164
- else files.set(path, text);
165
- }
166
- }
167
- if (files.size === 0 && problems.length === 0) problems.push("the preset carries no prompts");
168
- const paths = [...files.keys()];
169
- const ids = [...new Set(paths.map((path) => path.slice(path.indexOf("/") + 1, -3)))].sort((a, b) => a.localeCompare(b));
170
- return {
171
- summary: {
172
- name,
173
- title: header.title ?? name,
174
- description: header.description ?? "",
175
- languages: [...new Set(paths.map((path) => path.split("/")[0]))].sort((a, b) => a.localeCompare(b)),
176
- prompts: ids,
177
- rules: ids.filter((id) => !PROSE_PROMPTS.includes(id)),
178
- sampling: header.sampling,
179
- problems
180
- },
181
- files
182
- };
183
- }
184
- /** Every preset in the library; one that cannot be read is listed with its problems. */
185
- function listPresets(root) {
186
- const folder = presetsDirectory(root);
187
- if (!existsSync(folder)) return [];
188
- return readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isPresetName(entry.name)).map((entry) => readPreset(join(folder, entry.name), entry.name)).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
189
- }
190
- function loadPreset(root, name) {
191
- return readPreset(presetDirectory(root, name), name);
192
- }
193
- const sha = (text) => createHash("sha256").update(text).digest("hex");
194
- /**
195
- * Makes a preset of the prose prompts a world carries. Nothing is overwritten.
196
- * @throws {Error} when the name is taken, the world carries no prose prompt, or what it carries is not acceptable.
197
- */
198
- async function savePresetFromWorld(root, worldDirectory, request) {
199
- const target = presetDirectory(root, request.name);
200
- if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
201
- const source = join(worldDirectory, PROMPTS_FOLDER);
202
- const found = [];
203
- if (existsSync(source)) {
204
- for (const entry of readdirSync(source, { withFileTypes: true })) if (entry.isDirectory() && LANGUAGE_FOLDER.test(entry.name)) {
205
- for (const id of listFiles(join(source, entry.name))) if (PROSE_PROMPTS.includes(id)) found.push({
206
- language: entry.name,
207
- id
208
- });
209
- }
210
- }
211
- if (found.length === 0) throw new Error("the world carries no prose prompts to make a preset of");
212
- const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
213
- try {
214
- for (const { language, id } of found) {
215
- const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
216
- await mkdir(dirname(to), { recursive: true });
217
- await writeFile(to, readFileSync(join(source, language, `${id}.md`), "utf8"));
218
- }
219
- const header = {
220
- ...request.title === void 0 || request.title.trim() === "" ? {} : { title: request.title.trim() },
221
- ...request.description === void 0 || request.description.trim() === "" ? {} : { description: request.description.trim() },
222
- ...request.sampling === void 0 || Object.keys(request.sampling).length === 0 ? {} : { sampling: request.sampling }
223
- };
224
- await writeFile(join(staging, PRESET_FILE), JSON.stringify(header, null, 2));
225
- const loaded = readPreset(staging, request.name);
226
- if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
227
- await mkdir(presetsDirectory(root), { recursive: true });
228
- await rename(staging, target);
229
- return readPreset(target, request.name);
230
- } finally {
231
- await rm(staging, {
232
- recursive: true,
233
- force: true
234
- });
235
- }
236
- }
237
- /** Moves a preset out of the library into `<root>/.trash/presets/`. @returns where it went. */
238
- async function deletePreset(root, name, now = Date.now) {
239
- const directory = presetDirectory(root, name);
240
- if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
241
- const aside = join(root, ".trash", PRESETS_FOLDER, `${name}-${now()}`);
242
- await mkdir(dirname(aside), { recursive: true });
243
- await rename(directory, aside);
244
- return aside;
245
- }
246
- function headerFile(title, description, sampling) {
247
- return `${JSON.stringify({
248
- ...title === void 0 ? {} : { title },
249
- ...description === void 0 ? {} : { description },
250
- ...Object.keys(sampling).length === 0 ? {} : { sampling }
251
- }, null, 2)}\n`;
252
- }
253
- async function writeHeader(directory, text) {
254
- const file = join(directory, PRESET_FILE);
255
- await writeFile(`${file}.tmp`, text);
256
- await rename(`${file}.tmp`, file);
257
- }
258
- /** Changes what a preset says about itself. @throws {Error} when the preset does not exist or the change is not acceptable; nothing is written then. */
259
- async function updatePresetInfo(root, name, change) {
260
- const directory = presetDirectory(root, name);
261
- if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
262
- const current = readHeader(directory, []);
263
- const problems = [];
264
- const next = parseHeader({
265
- title: change.title ?? current.title,
266
- description: change.description ?? current.description,
267
- sampling: change.sampling ?? current.sampling
268
- }, problems);
269
- if (problems.length > 0) throw new Error(problems.join("; "));
270
- await writeHeader(directory, headerFile(next.title, next.description, next.sampling));
271
- return readPreset(directory, name);
272
- }
273
- /**
274
- * Makes a preset holding the shipped prose prompts of every language, as a starting point to edit. Nothing is overwritten.
275
- * @throws {Error} when the name is taken or the information is not acceptable.
276
- */
277
- async function createPresetFromShipped(root, request, shipped = shippedPromptsDirectory()) {
278
- const target = presetDirectory(root, request.name);
279
- if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
280
- const problems = [];
281
- const header = parseHeader({
282
- title: request.title?.trim(),
283
- description: request.description?.trim(),
284
- sampling: request.sampling
285
- }, problems);
286
- if (problems.length > 0) throw new Error(problems.join("; "));
287
- const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
288
- try {
289
- for (const language of shippedLanguages(shipped)) for (const id of PROSE_PROMPTS) {
290
- const from = join(shipped, language, `${id}.md`);
291
- if (!existsSync(from)) continue;
292
- const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
293
- await mkdir(dirname(to), { recursive: true });
294
- await writeFile(to, readFileSync(from, "utf8"));
295
- }
296
- await mkdir(staging, { recursive: true });
297
- await writeHeader(staging, headerFile(header.title, header.description, header.sampling));
298
- const loaded = readPreset(staging, request.name);
299
- if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
300
- await mkdir(presetsDirectory(root), { recursive: true });
301
- await rename(staging, target);
302
- return readPreset(target, request.name);
303
- } finally {
304
- await rm(staging, {
305
- recursive: true,
306
- force: true
307
- });
308
- }
309
- }
310
- /** Makes an empty preset folder that the import is about to fill; it has no prompts yet, so it reads as having problems until it does. */
311
- async function reservePreset(root, name, title, sampling = {}) {
312
- const target = presetDirectory(root, name);
313
- if (existsSync(target)) throw new Error(`there is already a preset "${name}"`);
314
- await mkdir(target, { recursive: true });
315
- await writeHeader(target, headerFile(title.trim().slice(0, MAX_TEXT) || void 0, void 0, sampling));
316
- return target;
317
- }
318
- /**
319
- * Makes a preset that adds guidance to the shipped prompts, in every language the program ships: each prompt keeps its shipped text and the guidance follows it, so that
320
- * the prompt keeps naming the tools and values it needs. The guidance is the importer's, in the language it was written in.
321
- * @throws {Error} when the name is taken, there is no guidance, or a prompt would not be acceptable; nothing is made then.
322
- */
323
- async function createPresetFromGuidance(root, request, guidance, shipped = shippedPromptsDirectory()) {
324
- const target = presetDirectory(root, request.name);
325
- if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
326
- const ids = Object.keys(guidance).filter((id) => (guidance[id]?.length ?? 0) > 0);
327
- if (ids.length === 0) throw new Error("there is no guidance to make a preset of");
328
- const problems = [];
329
- const header = parseHeader({
330
- title: request.title?.trim(),
331
- description: request.description?.trim()
332
- }, problems);
333
- if (problems.length > 0) throw new Error(problems.join("; "));
334
- const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
335
- try {
336
- for (const language of shippedLanguages(shipped)) for (const id of ids) {
337
- const base = readWorldPrompt(join(staging, "none"), language, id, shipped).text.trimEnd();
338
- const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
339
- await mkdir(dirname(to), { recursive: true });
340
- await writeFile(to, `${base}\n\n${(guidance[id] ?? []).join("\n")}\n`);
341
- }
342
- await writeHeader(staging, headerFile(header.title, header.description, {}));
343
- const loaded = readPreset(staging, request.name);
344
- if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
345
- await mkdir(presetsDirectory(root), { recursive: true });
346
- await rename(staging, target);
347
- return readPreset(target, request.name);
348
- } finally {
349
- await rm(staging, {
350
- recursive: true,
351
- force: true
352
- });
353
- }
354
- }
355
- //#endregion
356
- //#region src/host/decisions/route.ts
357
- /** The probability from which a yes is taken as a yes, for the confidence a chat asks. */
358
- const yesAt = (confidence) => (1 + confidence) / 2;
359
- /** The probability up to which a no is taken as a no. */
360
- const noAt = (confidence) => (1 - confidence) / 2;
361
- const clip = (text) => text.length > 120 ? `${text.slice(0, 119)}…` : text;
362
- const reportOf = (mode, items) => ({
363
- mode,
364
- items,
365
- decided: 0,
366
- escalated: 0,
367
- fallbacks: 0,
368
- agreed: 0,
369
- disagreed: 0,
370
- decisionMs: 0,
371
- llmMs: 0,
372
- samples: []
373
- });
374
- async function timed(run) {
375
- const started = performance.now();
376
- return {
377
- value: await run(),
378
- ms: Math.round(performance.now() - started)
379
- };
380
- }
381
- /**
382
- * Gives each key a verdict the way its site is set to: from the language model, from the decision model, from the decision model where it
383
- * is confident and the language model elsewhere, or from the language model while comparing it with the decision model. A decision model
384
- * that cannot be used never stops a story: its keys go to the language model and the report says why.
385
- */
386
- async function routeVerdicts(route, signal) {
387
- const { mode, keys } = route;
388
- const report = reportOf(mode, keys.length);
389
- const verdicts = /* @__PURE__ */ new Map();
390
- if (keys.length === 0) return {
391
- verdicts,
392
- report
393
- };
394
- const viaLlm = async (subset) => {
395
- const { value, ms } = await timed(() => route.llm(subset));
396
- report.llmMs += ms;
397
- for (const [key, verdict] of value) verdicts.set(key, verdict);
398
- };
399
- const viaDecision = async () => {
400
- try {
401
- const { value, ms } = await timed(() => route.probabilities(keys));
402
- report.decisionMs += ms;
403
- return value;
404
- } catch (error) {
405
- if (signal.aborted) throw error;
406
- report.problem = error instanceof Error ? error.message : String(error);
407
- return;
408
- }
409
- };
410
- if (mode === "llm") {
411
- await viaLlm(keys);
412
- return {
413
- verdicts,
414
- report
415
- };
416
- }
417
- if (mode === "shadow") {
418
- const [decided] = await Promise.all([viaDecision(), viaLlm(keys)]);
419
- if (decided === void 0) return {
420
- verdicts,
421
- report
422
- };
423
- for (const key of keys) {
424
- const probability = decided.get(key);
425
- const llm = verdicts.get(key);
426
- if (probability === void 0 || llm === void 0) continue;
427
- const decision = probability >= route.yesAt;
428
- if (decision === llm) report.agreed += 1;
429
- else {
430
- report.disagreed += 1;
431
- if (report.samples.length < 20) report.samples.push({
432
- turn: route.turn,
433
- what: clip(route.what(key)),
434
- probability: Math.round(probability * 1e3) / 1e3,
435
- decision,
436
- llm
437
- });
438
- }
439
- }
440
- return {
441
- verdicts,
442
- report
443
- };
444
- }
445
- const decided = await viaDecision();
446
- if (decided === void 0) {
447
- report.fallbacks = keys.length;
448
- await viaLlm(keys);
449
- return {
450
- verdicts,
451
- report
452
- };
453
- }
454
- const unsure = [];
455
- for (const key of keys) {
456
- const probability = decided.get(key);
457
- if (probability === void 0) {
458
- unsure.push(key);
459
- continue;
460
- }
461
- if (mode === "hybrid" && probability > route.noAt && probability < route.yesAt) unsure.push(key);
462
- else verdicts.set(key, probability >= route.yesAt);
463
- }
464
- report.decided = keys.length - unsure.length;
465
- report.escalated = unsure.length;
466
- if (unsure.length > 0) await viaLlm(unsure);
467
- return {
468
- verdicts,
469
- report
470
- };
471
- }
472
- /** Asks the decision model one yes-or-no question for each key about one state, in a single request; the answers are probabilities of yes. */
473
- async function askYesNo(service, state, asks, signal) {
474
- const questions = Object.fromEntries(asks.map(({ key, instructions }) => [key, {
475
- type: "noul",
476
- instructions
477
- }]));
478
- const { answers } = await service.decide(state, questions, {
479
- priority: "background",
480
- signal
481
- });
482
- return new Map(asks.map(({ key }) => [key, answers[key].probability]));
483
- }
484
- /**
485
- * Says once, through `say`, why a site's decision model could not be used, and again only when the reason changes, so that a story
486
- * played on without the service does not fill the log.
487
- */
488
- function announceProblem(seen, key, report, say) {
489
- if (report.problem === void 0) {
490
- seen.delete(key);
491
- return;
492
- }
493
- if (seen.get(key) === report.problem) return;
494
- seen.set(key, report.problem);
495
- say?.(`the decision model could not be used for ${key}, the language model judged instead: ${report.problem}`);
496
- }
497
- /** The reports of several routed runs of one site as one: counts and times added, the disagreements kept up to the limit, the latest problem. */
498
- function mergeReports(mode, reports) {
499
- const merged = reportOf(mode, 0);
500
- for (const report of reports) {
501
- merged.items += report.items;
502
- merged.decided += report.decided;
503
- merged.escalated += report.escalated;
504
- merged.fallbacks += report.fallbacks;
505
- merged.agreed += report.agreed;
506
- merged.disagreed += report.disagreed;
507
- merged.decisionMs += report.decisionMs;
508
- merged.llmMs += report.llmMs;
509
- merged.samples.push(...report.samples);
510
- if (report.problem !== void 0) merged.problem = report.problem;
511
- }
512
- merged.samples = merged.samples.slice(-20);
513
- return merged;
514
- }
515
- //#endregion
516
- export { readWorldPrompt as C, INTENT_TYPES as D, INTENT_STATUSES as E, listWorldPrompts as S, INTENT_HORIZONS as T, savePresetFromWorld as _, routeVerdicts as a, PROSE_PROMPTS as b, createPresetFromGuidance as c, isPresetName as d, listPresets as f, reservePreset as g, readPreset as h, noAt as i, createPresetFromShipped as l, presetDirectory as m, askYesNo as n, yesAt as o, loadPreset as p, mergeReports as r, PRESET_FILE as s, announceProblem as t, deletePreset as u, sha as v, writeWorldPrompt as w, deleteWorldPrompt as x, updatePresetInfo as y };
517
-
518
- //# sourceMappingURL=route-DRTJ_vcA.js.map