@dsh-agentic-roleplay/core 0.4.1 → 0.6.0

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 (40) hide show
  1. package/lib/{authoring-tools-C2BHkEFP.js → authoring-tools-BGzzW6O5.js} +7 -6
  2. package/lib/authoring.js +5 -5
  3. package/lib/{child-DsixtqTw.js → child-D5SVNk4O.js} +58 -71
  4. package/lib/client.js +747 -316
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +18 -23
  7. package/lib/doctor.js +2 -2
  8. package/lib/{gallery-CDYKJf_O.js → gallery-C7VOJ3xH.js} +2 -2
  9. package/lib/{generator-BR1ugzln.js → generator-CO8usAjE.js} +2 -2
  10. package/lib/helper.js +26 -0
  11. package/lib/{hooks-CHmUksFS.js → hooks-BLperIIB.js} +70 -7
  12. package/lib/images.js +4 -4
  13. package/lib/index.js +64 -22
  14. package/lib/{library-COIktKBa.js → library-DsDc6fQa.js} +2 -2
  15. package/lib/{lorebook-author-tools-CaT74Q7v.js → lorebook-author-tools-C-cFiE6E.js} +6 -6
  16. package/lib/lorebook-authoring.js +3 -3
  17. package/lib/{narration-DstnwrvX.js → narration-_dA9oIt2.js} +57 -2
  18. package/lib/orchestration.js +372 -48
  19. package/lib/{pack-jail-CEDDI4Xw.js → pack-jail-BKFmbYP8.js} +10 -10
  20. package/lib/{packs-DB_9xiCp.js → packs-ZTG7fWut.js} +2 -2
  21. package/lib/{presenter-agent-Gu34bZwd.js → presenter-agent-BHSbyWwZ.js} +5 -5
  22. package/lib/{preset-BL1d40oG.js → preset-CJLW8Mp0.js} +3 -3
  23. package/lib/{preset-author-tools-B2wZXKZo.js → preset-author-tools-1RstgEZs.js} +5 -5
  24. package/lib/preset-authoring.js +4 -4
  25. package/lib/{presets-Dc15L6OU.js → presets-DcPCnn8O.js} +3 -3
  26. package/lib/{reflection-BWMVdHhR.js → reflection-6qfOC5OT.js} +236 -32
  27. package/lib/text-CT1re6XT.js +18 -0
  28. package/package.json +38 -41
  29. package/prompts/en/roleplay/check-rule.md +3 -0
  30. package/prompts/en/roleplay/decide-reflection.md +3 -0
  31. package/prompts/en/roleplay/decide-trigger.md +3 -0
  32. package/prompts/en/roleplay/gate-agency.md +1 -0
  33. package/prompts/en/roleplay/gate-refusal.md +1 -0
  34. package/prompts/en/roleplay/gate-secret.md +3 -0
  35. package/prompts/zh/roleplay/check-rule.md +3 -0
  36. package/prompts/zh/roleplay/decide-reflection.md +3 -0
  37. package/prompts/zh/roleplay/decide-trigger.md +3 -0
  38. package/prompts/zh/roleplay/gate-agency.md +1 -0
  39. package/prompts/zh/roleplay/gate-refusal.md +1 -0
  40. package/prompts/zh/roleplay/gate-secret.md +3 -0
@@ -1,13 +1,13 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { b as INTENT_STATUSES } from "./presets-Dc15L6OU.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-BWMVdHhR.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-CHmUksFS.js";
6
- import { a as runChild, f as currentTurn, i as childTrace, m as tokensOf, n as childSampling, p as estimateAnswer, t as childModel } from "./child-DsixtqTw.js";
7
- import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-COIktKBa.js";
8
- import { _ as API_PREFIX } from "./packs-DB_9xiCp.js";
9
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CDYKJf_O.js";
10
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Gu34bZwd.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";
7
+ import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-DsDc6fQa.js";
8
+ import { _ as API_PREFIX } from "./packs-ZTG7fWut.js";
9
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-C7VOJ3xH.js";
10
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-BHSbyWwZ.js";
11
11
  import { join } from "node:path";
12
12
  import { existsSync } from "node:fs";
13
13
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -163,7 +163,7 @@ function describePrompt(job, memory) {
163
163
  ...records.open_threads.length === 0 ? ["- none"] : records.open_threads.map((thread) => `- id ${thread.id}: ${thread.text}`)
164
164
  ].join("\n");
165
165
  }
166
- const RESULT$3 = {
166
+ const RESULT$4 = {
167
167
  type: "object",
168
168
  properties: {
169
169
  complete: {
@@ -298,7 +298,7 @@ function recordKeeper(deps) {
298
298
  prompt: describePrompt(job, memory),
299
299
  tools: keeperTools(job, memory, progress),
300
300
  external: externalGiven(parent.ctx.tools, job.store.settings().tools, "records"),
301
- result: RESULT$3,
301
+ result: RESULT$4,
302
302
  beforeSubmit: () => {
303
303
  if (progress.edits === 0 && !warned && job.store.story.records({ rounds: job.rounds.map(({ turn, round }) => ({
304
304
  turn,
@@ -330,7 +330,7 @@ function suggestionProblems(lines, wanted) {
330
330
  const tidySuggestions = (lines) => lines.map((line) => line.trim().replace(/\s+/g, " "));
331
331
  //#endregion
332
332
  //#region src/host/orchestration/suggester.ts
333
- const RESULT$2 = {
333
+ const RESULT$3 = {
334
334
  type: "object",
335
335
  properties: { options: {
336
336
  type: "array",
@@ -369,7 +369,7 @@ function suggestionWriter(deps) {
369
369
  trace: childTrace(job.store, "suggestions", "suggestions"),
370
370
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
371
371
  prompt: promptOf(job),
372
- result: RESULT$2,
372
+ result: RESULT$3,
373
373
  beforeSubmit: (value) => {
374
374
  const problems = suggestionProblems(tidySuggestions(value.options), job.count);
375
375
  return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
@@ -380,7 +380,7 @@ function suggestionWriter(deps) {
380
380
  }
381
381
  //#endregion
382
382
  //#region src/host/triggers/judge.ts
383
- const RESULT$1 = {
383
+ const RESULT$2 = {
384
384
  type: "object",
385
385
  properties: { verdicts: {
386
386
  type: "array",
@@ -409,25 +409,35 @@ const RESULT$1 = {
409
409
  required: ["verdicts"],
410
410
  additionalProperties: false
411
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;
412
414
  /** The statements of the triggers still waiting, each once. */
413
415
  function waitingStatements(job) {
414
416
  return [...new Set(job.store.story.triggers.list({ status: "dormant" }).flatMap((trigger) => judgedStatements(trigger.condition)))];
415
417
  }
416
- function brief$1(job, statements) {
417
- const events = job.store.story.events.list().slice(-15).map((event) => `- ${event.text}`);
418
- 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) {
419
426
  return [
420
427
  "Statements to judge:",
421
428
  ...statements.map((statement, index) => `${index + 1}. ${statement}`),
422
- `Recorded events, the latest last:\n${events.join("\n") || "- none yet"}`,
423
- `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"}`
424
431
  ].join("\n\n");
425
432
  }
426
433
  /**
427
- * 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
428
- * 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.
429
438
  */
430
439
  function triggerJudge(deps) {
440
+ const seen = /* @__PURE__ */ new Map();
431
441
  return { async judge(job, signal) {
432
442
  const { judgedPerTurn } = job.store.settings().triggers;
433
443
  const waiting = waitingStatements(job);
@@ -438,35 +448,271 @@ function triggerJudge(deps) {
438
448
  const parent = deps.agentOf(job.chat);
439
449
  if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
440
450
  const store = job.store;
441
- const answer = await runChild({
442
- parent,
443
- signal,
444
- reasoningEffort: store.settings().reasoning.children,
445
- sampling: childSampling(store.settings(), "records", statements.length * 2 * 8 + 8),
446
- ...childModel(store.settings(), "records"),
447
- trace: childTrace(store, "records", "trigger judge"),
448
- persona: promptFor(parent, "roleplay/trigger-judge", store.settings().prompts.language),
449
- prompt: brief$1(job, statements),
450
- result: RESULT$1,
451
- beforeSubmit: (value) => {
452
- const numbers = value.verdicts.map((verdict) => verdict.number);
453
- const missing = statements.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
454
- return missing.length === 0 ? void 0 : `judge every statement: ${missing.join(", ")} ${missing.length === 1 ? "has" : "have"} no verdict`;
455
- },
456
- maxCalls: 3
457
- });
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);
458
503
  const next = readVerdicts(store.story);
459
- for (const verdict of answer.verdicts) {
460
- const statement = statements[verdict.number - 1];
461
- if (statement !== void 0) next[statement] = {
462
- holds: verdict.holds,
463
- turn: job.turn
464
- };
465
- }
504
+ for (const [key, holds] of routed.verdicts) next[statementOf(key)] = {
505
+ holds,
506
+ turn: job.turn
507
+ };
466
508
  writeVerdicts(store.story, next, new Set(waiting));
467
- 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)];
468
697
  } };
469
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
+ }
470
716
  //#endregion
471
717
  //#region src/host/factions/strategist.ts
472
718
  const LAST_KEY = "strategy.last";
@@ -2321,10 +2567,35 @@ var TurnEngine = class {
2321
2567
  }
2322
2568
  return state.judgement;
2323
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
+ }
2324
2591
  /** The turn is an ordinary one: the game master judges the player's action before anything else. */
2325
2592
  expectJudgement(owner) {
2326
2593
  this.stateFor(owner).judgeWanted = true;
2327
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
+ }
2328
2599
  /** Mark a turn as one that needs no round, for example because the player's input was refused. */
2329
2600
  skip(owner) {
2330
2601
  this.stateFor(owner).phase = "skipped";
@@ -2905,8 +3176,36 @@ var TurnEngine = class {
2905
3176
  const waiting = store?.pendingCommits().length ?? 0;
2906
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);
2907
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
+ }
2908
3206
  async deliver(owner, state, segments, silent, run) {
2909
3207
  let output = checkedOutput(this.boundaries().narrationChecker, this.storeOf(owner).settings().prompts.language, state, segments, silent);
3208
+ await this.gate(owner, state, output, silent);
2910
3209
  if (state.ooc?.ruling !== void 0) output = {
2911
3210
  ...output,
2912
3211
  ooc: state.ooc.ruling
@@ -3150,6 +3449,7 @@ var ImageJobs = class {
3150
3449
  };
3151
3450
  //#endregion
3152
3451
  //#region src/orchestration.ts
3452
+ const WORKING_DIRECTORY_CONTEXT = "working-directory:current";
3153
3453
  const name = "@dsh-agentic-roleplay/core/orchestration";
3154
3454
  /**
3155
3455
  * Mounted by the `roleplay` agent preset, so it applies to roleplay chats only.
@@ -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") ?? []
@@ -3271,6 +3589,12 @@ function apply(ctx) {
3271
3589
  return resourceHint(ctx.tools.schemas(context.scope).map((tool) => tool.name), ctx.tools.schemas().map((tool) => tool.name), translator(languageOf(chat?.settings.prompts.language ?? "en")));
3272
3590
  }
3273
3591
  });
3592
+ ctx.systemPrompt.context({
3593
+ name: WORKING_DIRECTORY_CONTEXT,
3594
+ order: ctx.systemPrompt.getContextOrder("WORKING_DIRECTORY"),
3595
+ interpolate: false,
3596
+ text: ""
3597
+ });
3274
3598
  const toolDeps = {
3275
3599
  engine,
3276
3600
  boundaries,
@@ -1,12 +1,12 @@
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-C2BHkEFP.js";
2
- import { v as writeWorldPrompt } from "./presets-Dc15L6OU.js";
3
- import { f as parseSwitchboard } from "./narration-DstnwrvX.js";
4
- 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-CHmUksFS.js";
5
- import { s as parseSampling } from "./child-DsixtqTw.js";
6
- import { c as referenceImagePath, v as mapLimit } from "./library-COIktKBa.js";
7
- import { n as readPreset } from "./preset-BL1d40oG.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-DB_9xiCp.js";
9
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BR1ugzln.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
+ import { c as referenceImagePath, v as mapLimit } from "./library-DsDc6fQa.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
+ 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";
12
12
  import { randomUUID } from "node:crypto";
@@ -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-CEDDI4Xw.js.map
2137
+ //# sourceMappingURL=pack-jail-BKFmbYP8.js.map
@@ -1,4 +1,4 @@
1
- import { U as Reader } from "./hooks-CHmUksFS.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-DB_9xiCp.js.map
843
+ //# sourceMappingURL=packs-ZTG7fWut.js.map
@@ -1,8 +1,8 @@
1
1
  import { t as promptFor } from "./access-EbNdZFbk.js";
2
- import { a as runChild } from "./child-DsixtqTw.js";
3
- import { c as referenceImagePath, o as nextSceneSerial } from "./library-COIktKBa.js";
4
- import { n as generateTransientImage, t as generateReferenceImage } from "./generator-BR1ugzln.js";
5
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CDYKJf_O.js";
2
+ import { o as runChild } from "./child-D5SVNk4O.js";
3
+ import { c as referenceImagePath, o as nextSceneSerial } from "./library-DsDc6fQa.js";
4
+ import { n as generateTransientImage, t as generateReferenceImage } from "./generator-CO8usAjE.js";
5
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-C7VOJ3xH.js";
6
6
  import { dirname, join, relative } from "node:path";
7
7
  import { existsSync } from "node:fs";
8
8
  import { createHash, randomUUID } from "node:crypto";
@@ -852,4 +852,4 @@ async function runImagePresenter(job) {
852
852
  //#endregion
853
853
  export { tokensOf as a, searchImages as i, interpretImage as n, present as o, imageTools as r, presentedFor as s, runImagePresenter as t };
854
854
 
855
- //# sourceMappingURL=presenter-agent-Gu34bZwd.js.map
855
+ //# sourceMappingURL=presenter-agent-BHSbyWwZ.js.map
@@ -1,5 +1,5 @@
1
- import { Bt as ImportCardError, K as cleanText, r as MAX_PREVIEW_TEXT } from "./authoring-tools-C2BHkEFP.js";
2
- import { o as SAMPLING_RANGES } from "./child-DsixtqTw.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-BL1d40oG.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-C2BHkEFP.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-Dc15L6OU.js";
3
- import { Z as languageOf, et as shippedLanguages, tt as shippedPromptsDirectory } from "./hooks-CHmUksFS.js";
4
- import { n as readPreset$1 } from "./preset-BL1d40oG.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-B2wZXKZo.js.map
276
+ //# sourceMappingURL=preset-author-tools-1RstgEZs.js.map