@dsh-agentic-roleplay/core 0.5.0 → 0.6.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 (37) hide show
  1. package/lib/access-EbNdZFbk.js +25 -0
  2. package/lib/{authoring-tools-Ch_3oIKC.js → authoring-tools-BGzzW6O5.js} +5 -5
  3. package/lib/authoring.js +5 -5
  4. package/lib/{access-tN5D3WI8.js → child-D5SVNk4O.js} +58 -78
  5. package/lib/client.js +819 -327
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -2
  8. package/lib/doctor.js +3 -3
  9. package/lib/helper.js +26 -0
  10. package/lib/{hooks-C7gt2c01.js → hooks-BLperIIB.js} +70 -7
  11. package/lib/images.js +1 -1
  12. package/lib/index.js +43 -11
  13. package/lib/{lorebook-author-tools-DII7Xt7Q.js → lorebook-author-tools-C-cFiE6E.js} +5 -5
  14. package/lib/lorebook-authoring.js +3 -3
  15. package/lib/{narration-DstnwrvX.js → narration-_dA9oIt2.js} +57 -2
  16. package/lib/orchestration.js +364 -46
  17. package/lib/{pack-jail-AzR6dCNm.js → pack-jail-BKFmbYP8.js} +8 -8
  18. package/lib/{packs-C7g534Mi.js → packs-ZTG7fWut.js} +2 -2
  19. package/lib/{presenter-agent-BsC6Vftz.js → presenter-agent-BHSbyWwZ.js} +3 -2
  20. package/lib/{preset-Drfu_K-H.js → preset-CJLW8Mp0.js} +3 -3
  21. package/lib/{preset-author-tools-CdIsFhQw.js → preset-author-tools-1RstgEZs.js} +5 -5
  22. package/lib/preset-authoring.js +4 -4
  23. package/lib/{presets-CADd77WB.js → presets-DcPCnn8O.js} +3 -3
  24. package/lib/{reflection-CUGuPAZR.js → reflection-6qfOC5OT.js} +235 -31
  25. package/package.json +4 -3
  26. package/prompts/en/roleplay/check-rule.md +3 -0
  27. package/prompts/en/roleplay/decide-reflection.md +3 -0
  28. package/prompts/en/roleplay/decide-trigger.md +3 -0
  29. package/prompts/en/roleplay/gate-agency.md +1 -0
  30. package/prompts/en/roleplay/gate-refusal.md +1 -0
  31. package/prompts/en/roleplay/gate-secret.md +3 -0
  32. package/prompts/zh/roleplay/check-rule.md +3 -0
  33. package/prompts/zh/roleplay/decide-reflection.md +3 -0
  34. package/prompts/zh/roleplay/decide-trigger.md +3 -0
  35. package/prompts/zh/roleplay/gate-agency.md +1 -0
  36. package/prompts/zh/roleplay/gate-refusal.md +1 -0
  37. package/prompts/zh/roleplay/gate-secret.md +3 -0
@@ -1,12 +1,13 @@
1
- import { _ as roleplaySessionOf, a as childTrace, g as chatSessionId, h as tokensOf, m as estimateAnswer, n as childModel, o as runChild, p as currentTurn, r as childSampling, t as promptFor } from "./access-tN5D3WI8.js";
2
- import { b as INTENT_STATUSES } from "./presets-CADd77WB.js";
3
- import { a as whereabouts, g as referent, h as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-CUGuPAZR.js";
4
- import { a as liveSettings, n as encodeOutput } from "./narration-DstnwrvX.js";
5
- import { D as zoneOf, E as describeWhen, L as wrongLanguage, O as RESULTS, _ as readVerdicts, at as ReflectionRefusedError, c as record, d as toolEnabled, f as MAX_OOC_ANSWER, l as AUTHORING_NEEDS, lt as languageOf, n as installHooks, o as PREVIEW_TOOL, p as storesOf, r as externalGiven, s as createTools$1, u as characterRunner, ut as translator, v as writeVerdicts, w as ClockError } from "./hooks-C7gt2c01.js";
1
+ import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { b as INTENT_STATUSES } from "./presets-DcPCnn8O.js";
3
+ import { a as whereabouts, b as sameWords, c as noAt, f as Timelines, l as routeVerdicts, n as memoryReflector, o as announceProblem, r as recordFailure, s as askYesNo, t as dueReflection, u as yesAt, x as referent } from "./reflection-6qfOC5OT.js";
4
+ import { a as liveSettings, g as GATE_SITES, n as encodeOutput } from "./narration-_dA9oIt2.js";
5
+ import { D as describeWhen, O as zoneOf, R as wrongLanguage, T as ClockError, c as record, d as toolEnabled, dt as translator, f as MAX_OOC_ANSWER, k as RESULTS, l as AUTHORING_NEEDS, n as installHooks, o as PREVIEW_TOOL, ot as ReflectionRefusedError, p as storesOf, r as externalGiven, s as createTools$1, u as characterRunner, ut as languageOf, v as readVerdicts, y as writeVerdicts } from "./hooks-BLperIIB.js";
6
+ import { h as tokensOf, i as childTrace, m as estimateAnswer, n as childSampling, o as runChild, p as currentTurn, t as childModel } from "./child-D5SVNk4O.js";
6
7
  import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-DsDc6fQa.js";
7
- import { _ as API_PREFIX } from "./packs-C7g534Mi.js";
8
+ import { _ as API_PREFIX } from "./packs-ZTG7fWut.js";
8
9
  import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-C7VOJ3xH.js";
9
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-BsC6Vftz.js";
10
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-BHSbyWwZ.js";
10
11
  import { join } from "node:path";
11
12
  import { existsSync } from "node:fs";
12
13
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -162,7 +163,7 @@ function describePrompt(job, memory) {
162
163
  ...records.open_threads.length === 0 ? ["- none"] : records.open_threads.map((thread) => `- id ${thread.id}: ${thread.text}`)
163
164
  ].join("\n");
164
165
  }
165
- const RESULT$3 = {
166
+ const RESULT$4 = {
166
167
  type: "object",
167
168
  properties: {
168
169
  complete: {
@@ -297,7 +298,7 @@ function recordKeeper(deps) {
297
298
  prompt: describePrompt(job, memory),
298
299
  tools: keeperTools(job, memory, progress),
299
300
  external: externalGiven(parent.ctx.tools, job.store.settings().tools, "records"),
300
- result: RESULT$3,
301
+ result: RESULT$4,
301
302
  beforeSubmit: () => {
302
303
  if (progress.edits === 0 && !warned && job.store.story.records({ rounds: job.rounds.map(({ turn, round }) => ({
303
304
  turn,
@@ -329,7 +330,7 @@ function suggestionProblems(lines, wanted) {
329
330
  const tidySuggestions = (lines) => lines.map((line) => line.trim().replace(/\s+/g, " "));
330
331
  //#endregion
331
332
  //#region src/host/orchestration/suggester.ts
332
- const RESULT$2 = {
333
+ const RESULT$3 = {
333
334
  type: "object",
334
335
  properties: { options: {
335
336
  type: "array",
@@ -368,7 +369,7 @@ function suggestionWriter(deps) {
368
369
  trace: childTrace(job.store, "suggestions", "suggestions"),
369
370
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
370
371
  prompt: promptOf(job),
371
- result: RESULT$2,
372
+ result: RESULT$3,
372
373
  beforeSubmit: (value) => {
373
374
  const problems = suggestionProblems(tidySuggestions(value.options), job.count);
374
375
  return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
@@ -379,7 +380,7 @@ function suggestionWriter(deps) {
379
380
  }
380
381
  //#endregion
381
382
  //#region src/host/triggers/judge.ts
382
- const RESULT$1 = {
383
+ const RESULT$2 = {
383
384
  type: "object",
384
385
  properties: { verdicts: {
385
386
  type: "array",
@@ -408,25 +409,35 @@ const RESULT$1 = {
408
409
  required: ["verdicts"],
409
410
  additionalProperties: false
410
411
  };
412
+ /** The longest reason a verdict gives, in characters: what the answer is given room for besides its number and its yes or no. */
413
+ const REASON_CHARS$1 = 600;
411
414
  /** The statements of the triggers still waiting, each once. */
412
415
  function waitingStatements(job) {
413
416
  return [...new Set(job.store.story.triggers.list({ status: "dormant" }).flatMap((trigger) => judgedStatements(trigger.condition)))];
414
417
  }
415
- function brief$1(job, statements) {
416
- const events = job.store.story.events.list().slice(-15).map((event) => `- ${event.text}`);
417
- const cast = job.store.cast().map((member) => `- ${member.character.name}${member.place === void 0 ? "" : ` (at ${member.place.location.name})`}${member.state === void 0 ? "" : `: ${[member.state.publicState, member.state.activity].filter((text) => text !== "").join("; ")}`}`);
418
+ /** What the story has recorded lately and where each character is, for whoever judges the statements. */
419
+ function sceneOf(job) {
420
+ return {
421
+ events: job.store.story.events.list().slice(-15).map((event) => event.text),
422
+ cast: job.store.cast().map((member) => `${member.character.name}${member.place === void 0 ? "" : ` (at ${member.place.location.name})`}${member.state === void 0 ? "" : `: ${[member.state.publicState, member.state.activity].filter((text) => text !== "").join("; ")}`}`)
423
+ };
424
+ }
425
+ function brief$1(scene, statements) {
418
426
  return [
419
427
  "Statements to judge:",
420
428
  ...statements.map((statement, index) => `${index + 1}. ${statement}`),
421
- `Recorded events, the latest last:\n${events.join("\n") || "- none yet"}`,
422
- `Where everyone is and what they are doing:\n${cast.join("\n") || "- nobody"}`
429
+ `Recorded events, the latest last:\n${scene.events.map((event) => `- ${event}`).join("\n") || "- none yet"}`,
430
+ `Where everyone is and what they are doing:\n${scene.cast.map((line) => `- ${line}`).join("\n") || "- nobody"}`
423
431
  ].join("\n\n");
424
432
  }
425
433
  /**
426
- * After a turn, has a model say whether the statements that triggers wait on hold now, for no more than `triggers.judgedPerTurn` of them, the
427
- * longest unjudged first, in one request. The verdicts are stored; a trigger fires from them at the next look, like from any other condition.
434
+ * After a turn, says whether the statements that triggers wait on hold now, for no more than `triggers.judgedPerTurn` of them, the
435
+ * longest unjudged first. The language model judges them in one request; a decision model, when the chat is set to use one, answers a
436
+ * yes-or-no question for each in one request of its own (see `decisions.triggers`). The verdicts are stored; a trigger fires from
437
+ * them at the next look, like from any other condition.
428
438
  */
429
439
  function triggerJudge(deps) {
440
+ const seen = /* @__PURE__ */ new Map();
430
441
  return { async judge(job, signal) {
431
442
  const { judgedPerTurn } = job.store.settings().triggers;
432
443
  const waiting = waitingStatements(job);
@@ -437,35 +448,271 @@ function triggerJudge(deps) {
437
448
  const parent = deps.agentOf(job.chat);
438
449
  if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
439
450
  const store = job.store;
440
- const answer = await runChild({
441
- parent,
442
- signal,
443
- reasoningEffort: store.settings().reasoning.children,
444
- sampling: childSampling(store.settings(), "records", statements.length * 2 * 8 + 8),
445
- ...childModel(store.settings(), "records"),
446
- trace: childTrace(store, "records", "trigger judge"),
447
- persona: promptFor(parent, "roleplay/trigger-judge", store.settings().prompts.language),
448
- prompt: brief$1(job, statements),
449
- result: RESULT$1,
450
- beforeSubmit: (value) => {
451
- const numbers = value.verdicts.map((verdict) => verdict.number);
452
- const missing = statements.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
453
- return missing.length === 0 ? void 0 : `judge every statement: ${missing.join(", ")} ${missing.length === 1 ? "has" : "have"} no verdict`;
454
- },
455
- maxCalls: 3
456
- });
451
+ const settings = store.settings();
452
+ const scene = sceneOf(job);
453
+ const statementOf = (key) => statements[key - 1];
454
+ const askLanguageModel = async (keys) => {
455
+ const subset = keys.map(statementOf);
456
+ const answer = await runChild({
457
+ parent,
458
+ signal,
459
+ reasoningEffort: settings.reasoning.children,
460
+ sampling: childSampling(settings, "records", estimateAnswer(subset.flatMap(() => [
461
+ REASON_CHARS$1,
462
+ 0,
463
+ 0
464
+ ]), settings.prompts.language)),
465
+ ...childModel(settings, "records"),
466
+ trace: childTrace(store, "records", "trigger judge"),
467
+ persona: promptFor(parent, "roleplay/trigger-judge", settings.prompts.language),
468
+ prompt: brief$1(scene, subset),
469
+ result: RESULT$2,
470
+ beforeSubmit: (value) => {
471
+ const numbers = value.verdicts.map((verdict) => verdict.number);
472
+ const missing = subset.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
473
+ return missing.length === 0 ? void 0 : `judge every statement: ${missing.join(", ")} ${missing.length === 1 ? "has" : "have"} no verdict`;
474
+ },
475
+ maxCalls: 3
476
+ });
477
+ return new Map(answer.verdicts.flatMap((verdict) => keys[verdict.number - 1] === void 0 ? [] : [[keys[verdict.number - 1], verdict.holds]]));
478
+ };
479
+ const askDecisionModel = async (keys) => {
480
+ const service = deps.decisions?.();
481
+ if (service === void 0) throw new Error("no decision service is selected, or the selected one is not loaded");
482
+ const asked = await askYesNo(service, {
483
+ recorded_events: scene.events.length === 0 ? ["none yet"] : scene.events,
484
+ where_everyone_is: scene.cast.length === 0 ? ["nobody"] : scene.cast
485
+ }, keys.map((key) => ({
486
+ key: `s${key}`,
487
+ instructions: store.text("roleplay/decide-trigger", { statement: statementOf(key) })
488
+ })), signal);
489
+ return new Map(keys.map((key) => [key, asked.get(`s${key}`)]));
490
+ };
491
+ const routed = await routeVerdicts({
492
+ mode: settings.decisions.triggers,
493
+ yesAt: yesAt(settings.decisions.confidence),
494
+ noAt: noAt(settings.decisions.confidence),
495
+ turn: job.turn,
496
+ keys: statements.map((_, index) => index + 1),
497
+ what: statementOf,
498
+ probabilities: askDecisionModel,
499
+ llm: askLanguageModel
500
+ }, signal);
501
+ announceProblem(seen, `${job.chat}:triggers`, routed.report, deps.problem);
502
+ store.recordDecisions?.("triggers", routed.report);
457
503
  const next = readVerdicts(store.story);
458
- for (const verdict of answer.verdicts) {
459
- const statement = statements[verdict.number - 1];
460
- if (statement !== void 0) next[statement] = {
461
- holds: verdict.holds,
462
- turn: job.turn
463
- };
464
- }
504
+ for (const [key, holds] of routed.verdicts) next[statementOf(key)] = {
505
+ holds,
506
+ turn: job.turn
507
+ };
465
508
  writeVerdicts(store.story, next, new Set(waiting));
466
- return { judged: answer.verdicts.length };
509
+ return { judged: routed.verdicts.size };
510
+ } };
511
+ }
512
+ const SECRET_CHARS = 300;
513
+ /**
514
+ * The lore a character does not know: what is listed for others only and has no knowledge edge to them. A fact whose title the passage names is
515
+ * asked about first, so that a crowded world is cut where it matters least.
516
+ */
517
+ function hiddenFrom(story, character, passage) {
518
+ const text = passage.toLowerCase();
519
+ const hidden = story.lore.list().filter((entry) => entry.scope === "listed" && entry.summary.trim() !== "" && !story.knowledge.knows(character, "lore", entry.id));
520
+ const named = (title) => text.includes(title.toLowerCase());
521
+ return [...hidden.filter((entry) => named(entry.title)), ...hidden.filter((entry) => !named(entry.title))].slice(0, 16).map((entry) => ({
522
+ title: entry.title,
523
+ text: entry.summary.trim().slice(0, SECRET_CHARS)
524
+ }));
525
+ }
526
+ /** What a decision model that only adds a check has to report: one request, no language model to compare with. */
527
+ const reportOf = (items, ms, problem) => ({
528
+ mode: "decision",
529
+ items,
530
+ decided: problem === void 0 ? items : 0,
531
+ escalated: 0,
532
+ fallbacks: 0,
533
+ agreed: 0,
534
+ disagreed: 0,
535
+ decisionMs: ms,
536
+ llmMs: 0,
537
+ samples: [],
538
+ ...problem === void 0 ? {} : { problem }
539
+ });
540
+ /**
541
+ * Asks the decision model one yes-or-no question for each key in a request of its own and says which keys came back at or above the threshold.
542
+ * A check that cannot be made is not a verdict: the report says why, and nothing is found.
543
+ */
544
+ async function askExtra(service, state, asks, threshold, signal) {
545
+ const started = performance.now();
546
+ try {
547
+ if (service === void 0) throw new Error("no decision service is selected, or the selected one is not loaded");
548
+ const answers = await askYesNo(service, state, asks, signal);
549
+ return {
550
+ found: asks.filter((ask) => (answers.get(ask.key) ?? 0) >= threshold).map((ask) => ask.key),
551
+ report: reportOf(asks.length, Math.round(performance.now() - started))
552
+ };
553
+ } catch (error) {
554
+ if (signal.aborted) throw error;
555
+ return {
556
+ found: [],
557
+ report: reportOf(asks.length, Math.round(performance.now() - started), error instanceof Error ? error.message : String(error))
558
+ };
559
+ }
560
+ }
561
+ /** Says once that an extra site could not be checked, and keeps the run in the story's figures. */
562
+ function noteExtra(site, chat, store, report, seen, say) {
563
+ announceProblem(seen, `${chat}:${site}`, report, say === void 0 ? void 0 : (message) => {
564
+ say(message.replace("the language model judged instead", "nothing was checked"));
565
+ });
566
+ store.recordDecisions?.(site, report);
567
+ }
568
+ const RULE_PROMPT = "roleplay/check-rule";
569
+ /**
570
+ * Checks the player's action against every rule of the world and of the player in one request of the decision model, one question for each rule, when the chat
571
+ * has `decisions.rules` on. It is only ever asked after the game master has judged the action allowed: a rule that holds there is found for the game master to look at again.
572
+ */
573
+ function ruleChecks(deps) {
574
+ const seen = /* @__PURE__ */ new Map();
575
+ return { async check(job, signal) {
576
+ const settings = job.store.settings();
577
+ const rules = job.store.rules();
578
+ if (settings.decisions.rules === "off" || rules.length === 0 || job.input.trim() === "") return [];
579
+ const asks = rules.map((rule, index) => ({
580
+ key: `rule${index}`,
581
+ instructions: job.store.text(RULE_PROMPT, { rule })
582
+ }));
583
+ const { found, report } = await askExtra(deps.decisions?.(), {
584
+ player_character: job.player,
585
+ player_message: job.input
586
+ }, asks, settings.decisions.gateThreshold, signal);
587
+ noteExtra("rules", job.chat, job.store, report, seen, deps.problem);
588
+ return found.map((key) => rules[Number(key.slice(4))]);
589
+ } };
590
+ }
591
+ //#endregion
592
+ //#region src/host/decisions/gates.ts
593
+ /**
594
+ * How far below the threshold a probability may fall and still be not sure. A decision model gives a rare fault a low probability even when it
595
+ * sees it (measured: faults between 0.3 and 0.9, clean passages below 0.4), so a gate's cut is its own threshold, not the chat's confidence.
596
+ */
597
+ const GATE_BAND = .15;
598
+ /** What a verdict of the language model may say besides its yes or no, in characters: the room its answer is given. */
599
+ const REASON_CHARS = 400;
600
+ const RESULT$1 = {
601
+ type: "object",
602
+ properties: {
603
+ reason: {
604
+ type: "string",
605
+ description: "One short sentence, written first: what the passage does, and whether that is the fault."
606
+ },
607
+ fault: {
608
+ type: "boolean",
609
+ description: "Whether the passage has the fault."
610
+ }
611
+ },
612
+ required: ["reason", "fault"],
613
+ additionalProperties: false
614
+ };
615
+ const ANSWER = "Give your reason in one short sentence first, then say whether the passage has the fault.";
616
+ const GATES = {
617
+ agency: {
618
+ prompt: "roleplay/gate-agency",
619
+ state: (job) => ({
620
+ player_character: job.player,
621
+ player_message: job.input,
622
+ narration: job.narration
623
+ }),
624
+ brief: (job) => `The player's character: ${job.player}\n\nThe player's message:\n${job.input}\n\nThe narration to check:\n${job.narration}`,
625
+ applies: (job) => job.input.trim() !== "" && job.narration.trim() !== "",
626
+ what: (job) => job.narration,
627
+ message: (job) => `the narration speaks, acts or thinks for ${job.player} beyond what the player wrote: let ${job.player} do only what the player's message says, and describe the world and what the others do instead`
628
+ },
629
+ refusal: {
630
+ prompt: "roleplay/gate-refusal",
631
+ state: (job) => ({ passage: job.passage }),
632
+ brief: (job) => `The passage to check:\n${job.passage}`,
633
+ applies: (job) => job.passage.trim() !== "",
634
+ what: (job) => job.passage,
635
+ message: () => "the output steps out of the story (a refusal, a warning, a disclaimer or a remark to the player): write the scene as part of the story, in its own voice"
636
+ }
637
+ };
638
+ /**
639
+ * Checks the output of a turn for the faults the chat's settings switch on (`decisions.agency`, `decisions.refusal`), each by the language model, a
640
+ * decision model, or both, as the setting says. A check that cannot be made never stops the turn: it is reported once, and the output goes on as it is.
641
+ */
642
+ function outputGates(deps) {
643
+ const seen = /* @__PURE__ */ new Map();
644
+ return { async check(job, signal) {
645
+ const settings = job.store.settings();
646
+ const parent = deps.agentOf(job.chat);
647
+ return [...(await Promise.all(GATE_SITES.map(async (site) => {
648
+ const mode = settings.decisions[site];
649
+ const gate = GATES[site];
650
+ if (mode === "off" || !gate.applies(job)) return [];
651
+ try {
652
+ const routed = await routeVerdicts({
653
+ mode,
654
+ yesAt: settings.decisions.gateThreshold,
655
+ noAt: Math.max(0, settings.decisions.gateThreshold - GATE_BAND),
656
+ turn: job.turn,
657
+ keys: ["fault"],
658
+ what: () => gate.what(job),
659
+ probabilities: async () => {
660
+ const service = deps.decisions?.();
661
+ if (service === void 0) throw new Error("no decision service is selected, or the selected one is not loaded");
662
+ const asked = await askYesNo(service, gate.state(job), [{
663
+ key: "fault",
664
+ instructions: job.store.text(gate.prompt)
665
+ }], signal);
666
+ return /* @__PURE__ */ new Map([["fault", asked.get("fault")]]);
667
+ },
668
+ llm: async () => {
669
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
670
+ const answer = await runChild({
671
+ parent,
672
+ signal,
673
+ reasoningEffort: settings.reasoning.children,
674
+ sampling: childSampling(settings, "records", estimateAnswer([REASON_CHARS, 0], settings.prompts.language)),
675
+ ...childModel(settings, "records"),
676
+ trace: childTrace(job.store, "records", `${site} check`),
677
+ persona: `${promptFor(parent, gate.prompt, settings.prompts.language)}\n\n${ANSWER}`,
678
+ prompt: gate.brief(job),
679
+ result: RESULT$1,
680
+ maxCalls: 2
681
+ });
682
+ return /* @__PURE__ */ new Map([["fault", answer.fault]]);
683
+ }
684
+ }, signal);
685
+ announceProblem(seen, `${job.chat}:${site}`, routed.report, deps.problem);
686
+ job.store.recordDecisions?.(site, routed.report);
687
+ return routed.verdicts.get("fault") === true ? [{
688
+ gate: site,
689
+ message: gate.message(job)
690
+ }] : [];
691
+ } catch (error) {
692
+ if (signal.aborted) throw error;
693
+ deps.problem?.(`the ${site} check of turn ${job.turn} could not be made, the output goes on as it is: ${error instanceof Error ? error.message : String(error)}`);
694
+ return [];
695
+ }
696
+ }))).flat(), ...await secretFindings(job, settings.decisions, deps.decisions?.(), seen, signal, deps.problem)];
467
697
  } };
468
698
  }
699
+ const SECRET_PROMPT = "roleplay/gate-secret";
700
+ /** The hidden lore the output gives away, when the chat has `decisions.secrets` on: one question to the decision model for each fact, in one request. */
701
+ async function secretFindings(job, decisions, service, seen, signal, say) {
702
+ if (decisions.secrets === "off" || job.secrets.length === 0 || job.passage.trim() === "") return [];
703
+ const asks = job.secrets.map((secret, index) => ({
704
+ key: `secret${index}`,
705
+ instructions: job.store.text(SECRET_PROMPT, { secret: secret.text })
706
+ }));
707
+ const { found, report } = await askExtra(service, { passage: job.passage }, asks, decisions.gateThreshold, signal);
708
+ noteExtra("secrets", job.chat, job.store, report, seen, say);
709
+ if (found.length === 0) return [];
710
+ const titles = found.map((key) => job.secrets[Number(key.slice(6))].title);
711
+ return [{
712
+ gate: "secrets",
713
+ message: `the output may give away what ${job.player === "" ? "the player's character" : job.player} does not know yet (${titles.join("; ")}): show only what can be seen or heard, and let the rest be learned in the story; if this is meant to be revealed now, deliver it again unchanged`
714
+ }];
715
+ }
469
716
  //#endregion
470
717
  //#region src/host/factions/strategist.ts
471
718
  const LAST_KEY = "strategy.last";
@@ -2320,10 +2567,35 @@ var TurnEngine = class {
2320
2567
  }
2321
2568
  return state.judgement;
2322
2569
  }
2570
+ /**
2571
+ * When the chat has the rules checked, the action the game master judged allowed is put against every rule once more by the decision model; a rule it
2572
+ * finds likely broken is told to the game master, which judges again (the second judgement stands, whatever it says).
2573
+ * @throws {Error} with the rules found, once per turn.
2574
+ */
2575
+ async checkRules(owner, allowed) {
2576
+ const state = this.stateFor(owner);
2577
+ if (!allowed || state.rulesChecked === true || state.ooc !== void 0 || state.phase !== "idle" || state.judgement !== void 0) return;
2578
+ const store = this.storeOf(owner);
2579
+ if (store.settings().decisions.rules === "off") return;
2580
+ state.rulesChecked = true;
2581
+ const player = store.cast().find((member) => member.character.control === "player")?.character.name ?? "";
2582
+ const broken = await this.boundaries().ruleCheck.check({
2583
+ chat: owner.chat,
2584
+ turn: owner.turn,
2585
+ store,
2586
+ input: state.input ?? "",
2587
+ player
2588
+ }, state.cancel.signal);
2589
+ if (broken.length > 0) throw new Error(`a check of the rules found that this action may break: ${broken.map((rule) => `"${rule}"`).join("; ")}. Judge it again: if it breaks a rule it is not allowed; if you are sure it does not, call judge_action again with the same answer and give in the reason why the rule does not apply`);
2590
+ }
2323
2591
  /** The turn is an ordinary one: the game master judges the player's action before anything else. */
2324
2592
  expectJudgement(owner) {
2325
2593
  this.stateFor(owner).judgeWanted = true;
2326
2594
  }
2595
+ /** Keeps what the player wrote this turn, for the checks of the output. */
2596
+ noteInput(owner, text) {
2597
+ this.stateFor(owner).input = text;
2598
+ }
2327
2599
  /** Mark a turn as one that needs no round, for example because the player's input was refused. */
2328
2600
  skip(owner) {
2329
2601
  this.stateFor(owner).phase = "skipped";
@@ -2904,8 +3176,36 @@ var TurnEngine = class {
2904
3176
  const waiting = store?.pendingCommits().length ?? 0;
2905
3177
  if ((this.runs.get(owner.chat) ?? 0) === 0 && store !== void 0 && waiting > 0 && (state.requested || waiting >= store.settings().memory.backlogRounds)) this.write(owner, state);
2906
3178
  }
3179
+ /**
3180
+ * Has the output checked for the faults the chat switched on, and sends it back to the game master when it has one, as often as a
3181
+ * refusal may be made; past that, or for an output a narrator wrote or one that was corrected for the game master, it goes as it is.
3182
+ */
3183
+ async gate(owner, state, output, silent) {
3184
+ if (silent || output.repaired || state.ooc !== void 0 || state.refused >= 2) return;
3185
+ const store = this.storeOf(owner);
3186
+ const narration = output.segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join("\n");
3187
+ const passage = output.segments.map((segment) => segment.type === "narration" ? segment.text : `${segment.name}: ${segment.text}`).join("\n");
3188
+ const playing = state.cast.find((member) => member.character.control === "player")?.character;
3189
+ const player = playing?.name ?? "";
3190
+ const secrets = playing === void 0 || state.secretsFound === true || store.settings().decisions.secrets === "off" ? [] : hiddenFrom(store.story, playing.id, passage);
3191
+ const findings = await this.boundaries().outputGate.check({
3192
+ chat: owner.chat,
3193
+ turn: owner.turn,
3194
+ store,
3195
+ input: state.input ?? "",
3196
+ player,
3197
+ narration,
3198
+ passage,
3199
+ secrets
3200
+ }, state.cancel.signal);
3201
+ if (findings.length === 0) return;
3202
+ if (findings.some((finding) => finding.gate === "secrets")) state.secretsFound = true;
3203
+ state.refused += 1;
3204
+ throw new Error(`the output is not acceptable: ${findings.map((finding) => finding.message).join("; ")}. Deliver it again with this corrected; utterances may not be touched`);
3205
+ }
2907
3206
  async deliver(owner, state, segments, silent, run) {
2908
3207
  let output = checkedOutput(this.boundaries().narrationChecker, this.storeOf(owner).settings().prompts.language, state, segments, silent);
3208
+ await this.gate(owner, state, output, silent);
2909
3209
  if (state.ooc?.ruling !== void 0) output = {
2910
3210
  ...output,
2911
3211
  ooc: state.ooc.ruling
@@ -3171,6 +3471,7 @@ function apply(ctx) {
3171
3471
  ctx.logger.warn(`roleplay: ${message}`);
3172
3472
  };
3173
3473
  const sessionsDir = () => join(ctx.roleplayRoot.path, "sessions");
3474
+ const decisions = () => ctx.get("decisions");
3174
3475
  const index = new EmbeddingIndex({
3175
3476
  embedder: () => ctx.get("embeddings"),
3176
3477
  story: (chat) => {
@@ -3195,9 +3496,26 @@ function apply(ctx) {
3195
3496
  })), "roleplay: rerank memories");
3196
3497
  });
3197
3498
  ctx.effect(() => ctx.roleplayOrchestration.replace({ committer: recordKeeper({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: record keeper");
3198
- ctx.effect(() => ctx.roleplayOrchestration.replace({ judge: triggerJudge({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: trigger judge");
3499
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ judge: triggerJudge({
3500
+ agentOf: (chat) => ctx.agents.get(SessionId(chat)),
3501
+ decisions,
3502
+ problem
3503
+ }) }), "roleplay: trigger judge");
3504
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ outputGate: outputGates({
3505
+ agentOf: (chat) => ctx.agents.get(SessionId(chat)),
3506
+ decisions,
3507
+ problem
3508
+ }) }), "roleplay: output gates");
3509
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ ruleCheck: ruleChecks({
3510
+ decisions,
3511
+ problem
3512
+ }) }), "roleplay: rule check");
3199
3513
  ctx.effect(() => ctx.roleplayOrchestration.replace({ strategist: factionStrategist({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: faction strategist");
3200
- ctx.effect(() => ctx.roleplayOrchestration.replace({ reflector: memoryReflector({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: reflection");
3514
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ reflector: memoryReflector({
3515
+ agentOf: (chat) => ctx.agents.get(SessionId(chat)),
3516
+ decisions,
3517
+ problem
3518
+ }) }), "roleplay: reflection");
3201
3519
  ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({
3202
3520
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
3203
3521
  external: (parent) => ctx.get("roleplayAuthoringTools")?.given(parent.ctx.tools, "worldAuthor") ?? []
@@ -1,11 +1,11 @@
1
- import { c as parseSampling } from "./access-tN5D3WI8.js";
2
- import { $ as LOCATION_FILE_NAME, A as loadTriggers, At as parseLoreFile, B as loadItems, C as populateLocations, D as populateVariables, Dt as LORE_DIR, F as loadCalendar, G as extractStyleFrom, H as loadFactions, J as withPlayer, L as LOCATIONS_DIR, Mt as InvalidEditProblems, Ot as loadLore, R as loadLocations, U as CHARACTERS_DIR, V as FACTIONS_DIR, W as loadCharacters, X as loadVariables, _ as populateCharacters, at as CHARACTER_FILE_NAME, c as authoredWorldOf, dt as WORLD_FILE_NAME, et as parseLocationFile, ft as parseWorldFile, h as knowsCharacter, i as contextOf, it as parseFactionFile, jt as subfolders, k as TRIGGERS_FILE_NAME, kt as LORE_FILE_NAME, m as loadValidatedWorld, nt as parseItemFile, ot as parseCharacterFile, rt as FACTION_FILE_NAME, s as worldOf, st as IMPORT_FOLDER, tt as ITEM_FILE_NAME, x as populateItems, z as ITEMS_DIR } from "./authoring-tools-Ch_3oIKC.js";
3
- import { v as writeWorldPrompt } from "./presets-CADd77WB.js";
4
- import { f as parseSwitchboard } from "./narration-DstnwrvX.js";
5
- import { B as parsePlotsFile, F as isStoryLanguage, I as textLanguage, N as LANGUAGE_NAMES, P as STORY_LANGUAGES, R as PLOTS_FILE_NAME, V as plotReferenceProblems, W as formatIssue, et as shippedLanguages, it as InvalidWorldError, q as PROMPTS_FOLDER, z as loadPlots } from "./hooks-C7gt2c01.js";
1
+ import { $ as LOCATION_FILE_NAME, A as loadTriggers, At as parseLoreFile, B as loadItems, C as populateLocations, D as populateVariables, Dt as LORE_DIR, F as loadCalendar, G as extractStyleFrom, H as loadFactions, J as withPlayer, L as LOCATIONS_DIR, Mt as InvalidEditProblems, Ot as loadLore, R as loadLocations, U as CHARACTERS_DIR, V as FACTIONS_DIR, W as loadCharacters, X as loadVariables, _ as populateCharacters, at as CHARACTER_FILE_NAME, c as authoredWorldOf, dt as WORLD_FILE_NAME, et as parseLocationFile, ft as parseWorldFile, h as knowsCharacter, i as contextOf, it as parseFactionFile, jt as subfolders, k as TRIGGERS_FILE_NAME, kt as LORE_FILE_NAME, m as loadValidatedWorld, nt as parseItemFile, ot as parseCharacterFile, rt as FACTION_FILE_NAME, s as worldOf, st as IMPORT_FOLDER, tt as ITEM_FILE_NAME, x as populateItems, z as ITEMS_DIR } from "./authoring-tools-BGzzW6O5.js";
2
+ import { v as writeWorldPrompt } from "./presets-DcPCnn8O.js";
3
+ import { f as parseSwitchboard } from "./narration-_dA9oIt2.js";
4
+ import { B as loadPlots, F as STORY_LANGUAGES, G as formatIssue, H as plotReferenceProblems, I as isStoryLanguage, J as PROMPTS_FOLDER, L as textLanguage, P as LANGUAGE_NAMES, V as parsePlotsFile, at as InvalidWorldError, tt as shippedLanguages, z as PLOTS_FILE_NAME } from "./hooks-BLperIIB.js";
5
+ import { c as parseSampling } from "./child-D5SVNk4O.js";
6
6
  import { c as referenceImagePath, v as mapLimit } from "./library-DsDc6fQa.js";
7
- import { n as readPreset } from "./preset-Drfu_K-H.js";
8
- import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-C7g534Mi.js";
7
+ import { n as readPreset } from "./preset-CJLW8Mp0.js";
8
+ import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-ZTG7fWut.js";
9
9
  import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-CO8usAjE.js";
10
10
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
11
  import { existsSync, lstatSync, statSync } from "node:fs";
@@ -2134,4 +2134,4 @@ function registerPackJail(ctx, deps) {
2134
2134
  //#endregion
2135
2135
  export { worldEntityImageFile as A, readWorldInfo as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile$1 as E, loadWorldParts as F, translateTools as H, PRESET_FILE as I, presetMessage as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, presetTools as R, generateWorldEntityImage as S, removeWorldTrigger as T, languageOfDocuments as U, translateMessage as V, readWorldDocuments as W, editWorldPlots as _, deleteWorldPackFile as a, entityFolder as b, createAuthoredEntity as c, replaceAuthoredEntity as d, editWorldCharacter as f, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, editWorldLore as m, packFileProblem as n, listWorldPacks as o, editWorldFaction as p, registerPackJail as r, AUTHORED_ENTITY_KINDS as s, MAX_PACK_TEXT as t, readAuthoredEntityDocument as u, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, editWorldInfo as z };
2136
2136
 
2137
- //# sourceMappingURL=pack-jail-AzR6dCNm.js.map
2137
+ //# sourceMappingURL=pack-jail-BKFmbYP8.js.map
@@ -1,4 +1,4 @@
1
- import { U as Reader } from "./hooks-C7gt2c01.js";
1
+ import { W as Reader } from "./hooks-BLperIIB.js";
2
2
  import { dirname, extname, join, posix, sep } from "node:path";
3
3
  import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
4
4
  import { createHash } from "node:crypto";
@@ -840,4 +840,4 @@ function anyTab(bases) {
840
840
  //#endregion
841
841
  export { API_PREFIX as _, packIds as a, describePack as c, packPath as d, readPack as f, SURFACE_NAMES as g, PACK_MEDIA_TYPES as h, inheritPacks as i, isPackId as l, PACK_LIMITS as m, anyTab as n, syncWorldPacks as o, PACK_ACTIONS as p, copyWorldPacks as r, worldPackStates as s, activePack as t, packFile as u };
842
842
 
843
- //# sourceMappingURL=packs-C7g534Mi.js.map
843
+ //# sourceMappingURL=packs-ZTG7fWut.js.map
@@ -1,4 +1,5 @@
1
- import { o as runChild, t as promptFor } from "./access-tN5D3WI8.js";
1
+ import { t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { o as runChild } from "./child-D5SVNk4O.js";
2
3
  import { c as referenceImagePath, o as nextSceneSerial } from "./library-DsDc6fQa.js";
3
4
  import { n as generateTransientImage, t as generateReferenceImage } from "./generator-CO8usAjE.js";
4
5
  import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-C7VOJ3xH.js";
@@ -851,4 +852,4 @@ async function runImagePresenter(job) {
851
852
  //#endregion
852
853
  export { tokensOf as a, searchImages as i, interpretImage as n, present as o, imageTools as r, presentedFor as s, runImagePresenter as t };
853
854
 
854
- //# sourceMappingURL=presenter-agent-BsC6Vftz.js.map
855
+ //# sourceMappingURL=presenter-agent-BHSbyWwZ.js.map
@@ -1,5 +1,5 @@
1
- import { s as SAMPLING_RANGES } from "./access-tN5D3WI8.js";
2
- import { Bt as ImportCardError, K as cleanText, r as MAX_PREVIEW_TEXT } from "./authoring-tools-Ch_3oIKC.js";
1
+ import { Bt as ImportCardError, K as cleanText, r as MAX_PREVIEW_TEXT } from "./authoring-tools-BGzzW6O5.js";
2
+ import { s as SAMPLING_RANGES } from "./child-D5SVNk4O.js";
3
3
  //#region src/host/import/preset.ts
4
4
  /** The older preset layout keeps its texts under fixed keys. */
5
5
  const LEGACY_KEYS = [
@@ -239,4 +239,4 @@ function selectPrompts(file, enabled, keepSampling) {
239
239
  //#endregion
240
240
  export { readPreset as n, selectPrompts as r, previewPreset as t };
241
241
 
242
- //# sourceMappingURL=preset-Drfu_K-H.js.map
242
+ //# sourceMappingURL=preset-CJLW8Mp0.js.map
@@ -1,7 +1,7 @@
1
- import { G as extractStyleFrom, J as withPlayer, i as contextOf, st as IMPORT_FOLDER } from "./authoring-tools-Ch_3oIKC.js";
2
- import { _ as readWorldPrompt, c as presetDirectory, g as listWorldPrompts, h as deleteWorldPrompt, l as readPreset, m as PROSE_PROMPTS, p as updatePresetInfo, t as PRESET_FILE, v as writeWorldPrompt } from "./presets-CADd77WB.js";
3
- import { Z as languageOf, et as shippedLanguages, tt as shippedPromptsDirectory } from "./hooks-C7gt2c01.js";
4
- import { n as readPreset$1 } from "./preset-Drfu_K-H.js";
1
+ import { G as extractStyleFrom, J as withPlayer, i as contextOf, st as IMPORT_FOLDER } from "./authoring-tools-BGzzW6O5.js";
2
+ import { _ as readWorldPrompt, c as presetDirectory, g as listWorldPrompts, h as deleteWorldPrompt, l as readPreset, m as PROSE_PROMPTS, p as updatePresetInfo, t as PRESET_FILE, v as writeWorldPrompt } from "./presets-DcPCnn8O.js";
3
+ import { Q as languageOf, nt as shippedPromptsDirectory, tt as shippedLanguages } from "./hooks-BLperIIB.js";
4
+ import { n as readPreset$1 } from "./preset-CJLW8Mp0.js";
5
5
  import { join } from "node:path";
6
6
  import { existsSync } from "node:fs";
7
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -273,4 +273,4 @@ async function presetApproval(exec, next, carries) {
273
273
  //#endregion
274
274
  export { presetChatSessionId as a, presetAuthorTools as i, narrationImportMessage as n, presetOfChat as o, presetApproval as r, PresetReader as t };
275
275
 
276
- //# sourceMappingURL=preset-author-tools-CdIsFhQw.js.map
276
+ //# sourceMappingURL=preset-author-tools-1RstgEZs.js.map
@@ -1,7 +1,7 @@
1
- import { n as limitAuthoringAgents } from "./authoring-tools-Ch_3oIKC.js";
2
- import { c as presetDirectory } from "./presets-CADd77WB.js";
3
- import "./hooks-C7gt2c01.js";
4
- import { i as presetAuthorTools, o as presetOfChat, r as presetApproval, t as PresetReader } from "./preset-author-tools-CdIsFhQw.js";
1
+ import { n as limitAuthoringAgents } from "./authoring-tools-BGzzW6O5.js";
2
+ import { c as presetDirectory } from "./presets-DcPCnn8O.js";
3
+ import "./hooks-BLperIIB.js";
4
+ import { i as presetAuthorTools, o as presetOfChat, r as presetApproval, t as PresetReader } from "./preset-author-tools-1RstgEZs.js";
5
5
  import { join } from "node:path";
6
6
  import { existsSync } from "node:fs";
7
7
  //#region src/preset-authoring.ts
@@ -1,5 +1,5 @@
1
- import { c as parseSampling } from "./access-tN5D3WI8.js";
2
- import { $ as promptProblem, K as LANGUAGE_FOLDER, Q as listFiles, Z as languageOf, et as shippedLanguages, q as PROMPTS_FOLDER, tt as shippedPromptsDirectory } from "./hooks-C7gt2c01.js";
1
+ 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-BLperIIB.js";
2
+ import { c as parseSampling } from "./child-D5SVNk4O.js";
3
3
  import { dirname, join } from "node:path";
4
4
  import { existsSync, readFileSync, readdirSync } from "node:fs";
5
5
  import { createHash } from "node:crypto";
@@ -354,4 +354,4 @@ async function createPresetFromGuidance(root, request, guidance, shipped = shipp
354
354
  //#endregion
355
355
  export { readWorldPrompt as _, isPresetName as a, INTENT_STATUSES as b, presetDirectory as c, savePresetFromWorld as d, sha as f, listWorldPrompts as g, deleteWorldPrompt as h, deletePreset as i, readPreset as l, PROSE_PROMPTS as m, createPresetFromGuidance as n, listPresets as o, updatePresetInfo as p, createPresetFromShipped as r, loadPreset as s, PRESET_FILE as t, reservePreset as u, writeWorldPrompt as v, INTENT_TYPES as x, INTENT_HORIZONS as y };
356
356
 
357
- //# sourceMappingURL=presets-CADd77WB.js.map
357
+ //# sourceMappingURL=presets-DcPCnn8O.js.map