@dsh-agentic-roleplay/core 0.3.2 → 0.3.4

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 (33) hide show
  1. package/lib/authoring.js +15 -255
  2. package/lib/child-CFjnaTZt.js +435 -0
  3. package/lib/client.js +2852 -586
  4. package/lib/client.js.map +1 -1
  5. package/lib/{deliver-BSsDtF6X.js → deliver-CpZOxBX5.js} +145 -1622
  6. package/lib/doctor-chat-ByDfCMeo.js +17 -0
  7. package/lib/doctor.js +171 -0
  8. package/lib/{gallery-DS5-qH9F.js → gallery-CtFDL22W.js} +2 -2
  9. package/lib/{generator-BzeepLd2.js → generator-B6FxlKOV.js} +2 -378
  10. package/lib/hooks-KTCR3fNJ.js +1060 -0
  11. package/lib/images.js +3 -3
  12. package/lib/index.js +1365 -201
  13. package/lib/language-DWVwi1R7.js +520 -0
  14. package/lib/orchestration.js +142 -1146
  15. package/lib/{documents-B5XAdfo2.js → pack-jail-CybSNzxr.js} +869 -80
  16. package/lib/{packs-BCGK9KZV.js → packs-BYjrAen6.js} +4 -518
  17. package/lib/{presenter-agent-Cp-J0onD.js → presenter-agent-CiEVKcjJ.js} +4 -3
  18. package/lib/reflection-waxFg1x-.js +1843 -0
  19. package/package.json +3 -2
  20. package/prompts/en/doctor/persona.md +1 -0
  21. package/prompts/en/doctor/procedure.md +5 -0
  22. package/prompts/en/doctor/welcome.md +1 -0
  23. package/prompts/en/import/character.md +1 -0
  24. package/prompts/en/roleplay/record-keeper.md +2 -2
  25. package/prompts/en/roleplay/reflection-check.md +5 -0
  26. package/prompts/en/roleplay/reflection.md +2 -0
  27. package/prompts/zh/doctor/persona.md +1 -0
  28. package/prompts/zh/doctor/procedure.md +5 -0
  29. package/prompts/zh/doctor/welcome.md +1 -0
  30. package/prompts/zh/import/character.md +1 -0
  31. package/prompts/zh/roleplay/record-keeper.md +2 -2
  32. package/prompts/zh/roleplay/reflection-check.md +5 -0
  33. package/prompts/zh/roleplay/reflection.md +2 -0
@@ -1,26 +1,12 @@
1
- import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { K as SessionNotFoundError, P as inheritPrompts, S as wrongLanguage, T as parsePlotsFile, i as inheritPacks } from "./packs-BCGK9KZV.js";
1
+ import { t as promptFor } from "./access-EbNdZFbk.js";
3
2
  import "./settings-CA6icLL_.js";
3
+ import { a as wrongLanguage, c as parsePlotsFile, k as SessionNotFoundError } from "./language-DWVwi1R7.js";
4
4
  import { n as encodeOutput, r as encodePreview } from "./narration-DK2kiIjE.js";
5
- import { A as runChild, D as childSampling, E as childModel, j as estimateAnswer, k as childTrace, u as inheritImages } from "./generator-BzeepLd2.js";
5
+ import { a as runChild, c as addTokens, i as childTrace, n as childSampling, s as NO_TOKENS, t as childModel, u as estimateAnswer } from "./child-CFjnaTZt.js";
6
6
  import { join } from "node:path";
7
7
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
9
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
10
- import { DAY, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, characterKey, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, holidaysOn, isSessionId, localTime, locationKey, mentioned, nextTimeOfDay, overlap, readCalendar, seasonOf, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
11
- //#region ../dsh-roleplay-model/src/memory.ts
12
- const MEMORY_KINDS = [
13
- "belief",
14
- "relationship",
15
- "knowledge"
16
- ];
17
- /** How sure a character is of what it believes, from least to most. */
18
- const MEMORY_CONFIDENCES = [
19
- "doubtful",
20
- "likely",
21
- "sure"
22
- ];
23
- //#endregion
9
+ import { DAY, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, holidaysOn, isSessionId, localTime, nextTimeOfDay, readCalendar, seasonOf, sessionDatabase } from "@dsh-agentic-roleplay/state";
24
10
  //#region ../dsh-roleplay-model/src/messages-zh.ts
25
11
  /** The Chinese of the texts built in code, by the English that stands in the code. A `{name}` is filled in and must stand in both. */
26
12
  const ZH = {
@@ -157,6 +143,16 @@ const ZH = {
157
143
  "{where}: one passing moment is not yet a belief; rest it on things from at least two different turns, or on one event that turned the story": "{where}:一个转瞬即逝的瞬间还不是看法;请以至少两个不同回合的经历为依据,或以一件扭转了故事的事件为依据",
158
144
  "{where}: to be sure of something it must rest on things from at least two different turns": "{where}:要对某事确信,必须以至少两个不同回合的经历为依据",
159
145
  "{where}: \"{name}\" is not a character; name them as they are named": "{where}:“{name}”不是角色;请使用他们的名字",
146
+ "say in a sentence what the belief claims and what the things say, before the verdict": "先用一句话说明这个看法主张什么、这些内容说了什么,再给出判断",
147
+ "the verdict is consistent or contradicted": "判断是 consistent 或 contradicted",
148
+ "a belief that can be true together with all of them names none of them": "与它们全都可以同时成立的看法,不应列出其中任何一条",
149
+ "name the things that cannot be true together with the belief": "写出与这个看法不可能同时成立的内容",
150
+ "there is no thing listed numbered {id}": "列出的内容里没有编号为 {id} 的",
151
+ "thing {id} came before the belief was formed": "内容 {id} 出现在这个看法形成之前",
152
+ "A belief held by {name}: {text}": "{name} 持有的一个看法:{text}",
153
+ "What they took in since that bears on it:": "此后他们接收到的、与之有关的内容:",
154
+ "Can the belief and each of these be true together? Name the ones that cannot be.": "这个看法与其中每一件事能否同时成立?指出不能同时成立的。",
155
+ "{names} could not be sorted this time and will be tried again: {reason}": "{names} 这一次没能整理,下次会再试:{reason}",
160
156
  "{where}: belief {id} is already changed in this pass": "{where}:看法 {id} 在这一轮中已经修改过",
161
157
  "{where}: say what it took in since that bears on it": "{where}:请写出此后与之相关的经历",
162
158
  "{where}: thing {id} came before the belief was formed; cite what came after": "{where}:经历 {id} 发生在看法形成之前;请引用之后发生的事",
@@ -218,7 +214,8 @@ const ZH = {
218
214
  "{names} noticed: {text}": "{names}注意到:{text}",
219
215
  "{name} went to {place}.": "{name}去了{place}。",
220
216
  "## MCP resource servers\n\nUse {tools} with the server argument naming an MCP server.": "## MCP 资源服务器\n\n使用 {tools},server 参数填 MCP 服务器的名称。",
221
- "## MCP resource servers\n\nUse {tools} with one of these names as the server argument: {servers}.": "## MCP 资源服务器\n\n使用 {tools},server 参数填下列名称之一:{servers}。"
217
+ "## MCP resource servers\n\nUse {tools} with one of these names as the server argument: {servers}.": "## MCP 资源服务器\n\n使用 {tools},server 参数填下列名称之一:{servers}。",
218
+ "{where}: the text is longer than {max} characters. A belief is not rewritten to hold what speaks against it: leave the text out and list the belief under doubt with the numbers of what speaks against it, and put what was learned as a new belief of its own": "{where}:文字超过 {max} 个字符。不要通过改写信念来容纳与之相悖的事:不要写文字,把这条信念列入 doubt 并给出与之相悖的编号;新了解到的内容另写成一条新信念"
222
219
  };
223
220
  //#endregion
224
221
  //#region ../dsh-roleplay-model/src/messages.ts
@@ -379,16 +376,6 @@ function parseCharacterAction(value) {
379
376
  };
380
377
  }
381
378
  //#endregion
382
- //#region src/host/orchestration/referent.ts
383
- /**
384
- * How a person is named wherever the text may go on to say what they do: the name with the pronouns the world gave them, or the gender when only that is given.
385
- * A model that is not told guesses, and a wrong guess written into a record or a narration is never corrected; nothing is made up when the world says neither.
386
- */
387
- function referent(character) {
388
- const mark = [character.pronouns, character.gender].find((text) => text !== void 0 && text.trim() !== "")?.trim();
389
- return mark === void 0 ? character.name : `${character.name} (${mark})`;
390
- }
391
- //#endregion
392
379
  //#region src/host/clock/story-clock.ts
393
380
  var ClockError = class extends Error {};
394
381
  /** A moment as it is told next to `now`: the clock when it is the same day, the date as well when it is not. */
@@ -537,974 +524,6 @@ function skipTime(session, config, turn, round, wall, request) {
537
524
  });
538
525
  }
539
526
  //#endregion
540
- //#region src/host/orchestration/defaults.ts
541
- const ENGLISH = translator("en");
542
- /** What the instructions say about how long each part of a character's answer may run. */
543
- const limitVariables = (language) => {
544
- const limits = answerLimits(language);
545
- return {
546
- thoughtLimit: limits.thought,
547
- intentLimit: limits.intent,
548
- utteranceLimit: limits.utterance
549
- };
550
- };
551
- function describe(character, tr) {
552
- const lines = [tr("You are {name}.", { name: character.name })];
553
- if (character.aliases.length > 0) lines.push(tr("You are also called {names}.", { names: character.aliases.join(tr(", ")) }));
554
- const facts = [
555
- character.age === void 0 ? void 0 : tr("age: {value}", { value: character.age }),
556
- character.gender === void 0 ? void 0 : tr("gender: {value}", { value: character.gender }),
557
- character.pronouns === void 0 ? void 0 : tr("pronouns: {value}", { value: character.pronouns })
558
- ].filter((fact) => fact !== void 0);
559
- if (facts.length > 0) lines.push(facts.join(tr("; ")) + tr("."));
560
- for (const [label, text] of [
561
- ["Summary", character.summary],
562
- ["Personality", character.personality],
563
- ["Background", character.background],
564
- ["Appearance", character.appearance],
565
- ["How you speak", character.speech.style]
566
- ]) if (text.trim() !== "") lines.push(`${tr(label)}${tr(": ")}${text.trim()}`);
567
- return lines.join("\n");
568
- }
569
- /** At most this many features and ways out of a place are told at once. */
570
- const SHOWN_FEATURES = 12;
571
- const SHOWN_EXITS = 12;
572
- const sentence = (text) => {
573
- return (/^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())?.[0] ?? text).trim();
574
- };
575
- /** At most this many things are listed at once: the rest are said to be there and left for a closer look. */
576
- const SHOWN_ITEMS = 12;
577
- /** One thing in a sentence: how many, what state it is in, where it is. */
578
- function describeItem(item, { withKeys }, tr = ENGLISH) {
579
- const name = `${item.quantity > 1 ? `${item.quantity} ` : ""}${item.name}${item.quality === "" ? "" : ` (${item.quality})`}`;
580
- const extra = [
581
- item.hidden ? tr("hidden") : "",
582
- item.state === void 0 ? "" : item.state,
583
- item.where ?? ""
584
- ].filter((part) => part !== "").join(tr(", "));
585
- const inside = item.contents === void 0 ? "" : tr(" holding {things}", { things: item.contents.join(tr(", ")) });
586
- return `${withKeys ? `${item.key}: ` : ""}${name}${extra === "" ? "" : ` [${extra}]`}${inside}`;
587
- }
588
- /** A list of things, capped. */
589
- function describeItems(items, options, tr = ENGLISH) {
590
- return `${items.slice(0, SHOWN_ITEMS).map((item) => describeItem(item, options, tr)).join(tr("; "))}${items.length > SHOWN_ITEMS ? tr("; and {count} more", { count: items.length - SHOWN_ITEMS }) : ""}`;
591
- }
592
- /** What someone in a place is told about it: what it is like, what can be pointed at, and the ways out. */
593
- function describePlace(view, { withKeys }, tr = ENGLISH) {
594
- const { location, exits } = view;
595
- const lines = [`${location.name}${withKeys ? ` (${view.key})` : ""}${location.description === "" ? "" : `: ${location.description}`}`];
596
- if (location.features.length > 0) {
597
- const shown = location.features.slice(0, SHOWN_FEATURES).map((feature) => `${withKeys ? `${feature.key}: ` : ""}${feature.name}${feature.description === "" ? "" : ` - ${sentence(feature.description)}`}`);
598
- lines.push(`${tr("Things here: ")}${shown.join(tr("; "))}${location.features.length > SHOWN_FEATURES ? tr("; and {count} more", { count: location.features.length - SHOWN_FEATURES }) : ""}`);
599
- }
600
- if (exits.length > 0) {
601
- const shown = exits.slice(0, SHOWN_EXITS).map(({ key, name, exit }) => `${withKeys ? `${key}: ` : ""}${name}${exit.description === "" ? "" : ` (${sentence(exit.description)})`}${exit.state === "open" ? "" : ` [${tr(exit.state)}${exit.note === "" ? "" : `: ${exit.note}`}]`}`);
602
- lines.push(`${tr("Ways out: ")}${shown.join(tr("; "))}${exits.length > SHOWN_EXITS ? tr("; and {count} more", { count: exits.length - SHOWN_EXITS }) : ""}`);
603
- }
604
- if (view.items !== void 0 && view.items.length > 0) lines.push(`${tr("Lying about: ")}${describeItems(view.items, { withKeys }, tr)}`);
605
- return lines;
606
- }
607
- /** How long the player has to have been away for it to be worth telling the game master. */
608
- const NOTICEABLE_ABSENCE = 5 * MINUTE;
609
- /** What the game master is told about time at the start of a turn, and how it passes. */
610
- function timeNotice(time, language, tr) {
611
- const now = tr("Time: {time}.", { time: describeTime(time.now, language) });
612
- if (time.now.mode === "simulated") return `${now} ${tr("The story's time moves only as you say: each round takes what you give it (elapsed_seconds in resolve_round, or the default), and advance_time skips ahead.")}`;
613
- const away = time.away !== void 0 && time.away >= NOTICEABLE_ABSENCE ? ` ${tr("The player was away for {duration} of real time and the story went on meanwhile: characters have been about their own business, so do not assume anyone is where or as the player left them unless the records say so.", { duration: describeDuration(time.away, language) })}` : "";
614
- return `${now} ${tr("The story's time follows the real clock: it cannot be skipped, and each round takes as long as it really took.")}${away}`;
615
- }
616
- /** What a character is told of its day, its commitments and what it is after. */
617
- function describeAgenda(agenda, now, tr = ENGLISH, language = "en") {
618
- const { zone } = agenda;
619
- const when = (instant) => describeWhen(instant, now, zone, language);
620
- const at = (place) => place === void 0 ? "" : tr(" at {place}", { place });
621
- const lines = [];
622
- if (agenda.now !== void 0) lines.push(tr("Your day, now: {activity}{place}, until {until}{note}.", {
623
- activity: agenda.now.activity,
624
- place: at(agenda.now.place),
625
- until: when(agenda.now.until),
626
- note: agenda.now.interruptible ? "" : tr(" (not something you would drop lightly)")
627
- }));
628
- if (agenda.next !== void 0) lines.push(tr("Your day, next: {activity}{place}, from {from}.", {
629
- activity: agenda.next.activity,
630
- place: at(agenda.next.place),
631
- from: when(agenda.next.at)
632
- }));
633
- for (const engagement of agenda.engagements) {
634
- const values = {
635
- title: engagement.title,
636
- place: at(engagement.place),
637
- with: engagement.with.length === 0 ? "" : tr(", with {names}", { names: engagement.with.join(tr(", ")) }),
638
- at: when(engagement.at)
639
- };
640
- lines.push(engagement.overdue ? tr("You were to: {title}{place}{with}, at {at}, which has passed and is still open.", values) : tr("You are due to: {title}{place}{with}, at {at}.", values));
641
- }
642
- if (agenda.goals.length > 0) {
643
- lines.push(tr("What you are after:"));
644
- for (const goal of agenda.goals) {
645
- const by = goal.deadline === void 0 ? "" : goal.overdue ? tr(", by {deadline}, which has passed", { deadline: when(goal.deadline) }) : tr(", by {deadline}", { deadline: when(goal.deadline) });
646
- lines.push(`- ${goal.name} (${goal.type})${by}${goal.description === "" ? "" : `${tr(": ")}${sentence(goal.description)}`}${goal.plan.length === 0 ? "" : tr(" Next: {plan}.", { plan: goal.plan.join(tr("; ")) })}`);
647
- }
648
- }
649
- return lines;
650
- }
651
- /** What the game master is told of the characters' days at the start of a turn; nothing when there is nothing to tell. */
652
- function describeSceneAgenda(agenda, now, tr = ENGLISH, language = "en") {
653
- const lines = [];
654
- const join = (entries) => entries.join(tr("; "));
655
- if (agenda.moved.length > 0) lines.push(tr("By their routines since you last looked: {moves}.", { moves: join(agenda.moved.map((move) => tr("{name} went to {place} ({activity})", {
656
- name: move.name,
657
- place: move.to,
658
- activity: move.activity
659
- }))) }));
660
- if (agenda.here.length > 0) lines.push(tr("With the player's character, and their days: {days}. The characters decide for themselves whether to keep to their day; the moment may keep them.", { days: join(agenda.here.map((entry) => `${entry.name}${tr(": ")}${entry.note}`)) }));
661
- if (agenda.engagements.length > 0) {
662
- const entries = agenda.engagements.map((engagement) => {
663
- const values = {
664
- title: engagement.title,
665
- with: engagement.with.join(tr(", ")),
666
- place: engagement.place === void 0 ? "" : tr(", at {place}", { place: engagement.place }),
667
- when: describeWhen(engagement.at, now, agenda.zone, language)
668
- };
669
- return engagement.overdue ? tr("\"{title}\" ({with}{place}) was due {when} and is still open", values) : tr("\"{title}\" ({with}{place}) is due {when}", values);
670
- });
671
- lines.push(tr("Commitments due soon or overdue: {entries}.", { entries: join(entries) }));
672
- }
673
- return lines.join("\n");
674
- }
675
- /** In words, how a character stands with another, from the numbers of its profile; nothing for what is unremarkable. */
676
- function describeAttitude(relation, tr = ENGLISH) {
677
- return [
678
- relation.familiarity >= .7 ? tr("knows them well") : relation.familiarity <= .15 ? tr("barely knows them") : "",
679
- relation.trust >= .4 ? tr("trusts them") : relation.trust <= -.4 ? tr("distrusts them") : "",
680
- relation.affinity >= .4 ? tr("is fond of them") : relation.affinity <= -.4 ? tr("dislikes them") : "",
681
- relation.tension >= .5 ? tr("things are strained between them") : ""
682
- ].filter((part) => part !== "").join(tr(", "));
683
- }
684
- function whereIs(member, tr = ENGLISH) {
685
- const place = member.place;
686
- if (place === void 0) return "";
687
- return [place.position, place.feature === void 0 ? "" : tr("at {feature}", { feature: place.feature.name })].filter((part) => part !== "").join(tr(", "));
688
- }
689
- function present(cast, self, tr) {
690
- return cast.map((member) => {
691
- const { key, character, state } = member;
692
- const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
693
- const where = whereIs(member);
694
- return `- ${key === self ? character.name : referent(character)}${key === self ? tr(" (you)") : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `${tr(": ")}${seen.join(tr("; "))}` : ""}`;
695
- }).join("\n");
696
- }
697
- /** A bounded, advisory order for who is most likely to need a turn; reachability still governs activation. */
698
- function describeActivationCandidates(cast, input, story, tr = ENGLISH) {
699
- const player = cast.find((member) => member.character.control === "player");
700
- if (player === void 0) return "";
701
- const named = mentioned(input, cast.map((member) => member.character));
702
- const cues = tokens(input);
703
- const candidates = cast.filter((member) => member.character.control === "agent").map((member) => {
704
- const relation = story.relationships.get(member.character.id, player.character.id);
705
- const here = member.place === void 0 || player.place === void 0 || member.place.location.id === player.place.location.id;
706
- const goal = story.intents.list(member.character.id, { status: "active" }).map((intent) => ({
707
- intent,
708
- match: overlap(cues, `${intent.name} ${intent.description}`, [])
709
- })).sort((a, b) => b.match - a.match)[0];
710
- const factionGoal = story.factionMemberships.ofCharacter(member.character.id, "active").flatMap((membership) => story.factionIntents.list(membership.factionId, { status: "active" }).map((intent) => ({
711
- intent,
712
- match: overlap(cues, `${intent.name} ${intent.description}`, []) * membership.commitment
713
- }))).sort((a, b) => b.match - a.match)[0];
714
- return {
715
- member,
716
- reasons: [
717
- named.has(member.character.id) ? tr("named in the move") : "",
718
- here ? tr("in the scene") : "",
719
- (goal?.match ?? 0) >= 2 ? tr("own goal: {goal}", { goal: goal.intent.name }) : "",
720
- (factionGoal?.match ?? 0) >= 2 ? tr("faction pressure: {goal}", { goal: factionGoal.intent.name }) : "",
721
- relation !== void 0 && relation.tension >= .5 ? tr("high tension toward the player") : "",
722
- relation !== void 0 && relation.trust <= -.4 ? tr("distrusts the player") : "",
723
- relation !== void 0 && Math.abs(relation.affinity) >= .4 ? relation.affinity > 0 ? tr("cares about the player") : tr("dislikes the player") : ""
724
- ].filter((reason) => reason !== ""),
725
- score: (named.has(member.character.id) ? 4 : 0) + (here ? 2 : 0) + Math.min(2, (goal?.match ?? 0) / 2) + Math.min(2, (factionGoal?.match ?? 0) / 2) + (relation?.tension ?? 0) + Math.max(0, -(relation?.trust ?? 0)) * .5 + Math.abs(relation?.affinity ?? 0) * .5
726
- };
727
- }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.member.key.localeCompare(b.member.key)).slice(0, 5);
728
- if (candidates.length === 0) return "";
729
- return `${tr("Likely characters to activate, in priority order (advice only; activate only whoever the moment actually reaches):")}\n${candidates.map(({ member, reasons }) => `- ${member.character.name} (${member.key}): ${reasons.join(tr(", ")) || tr("socially implicated")}`).join("\n")}`;
730
- }
731
- function said(entry, tr) {
732
- return entry.utterance === void 0 ? tr("- {name} intended: {intent} ({result}) {summary}", {
733
- name: entry.name,
734
- intent: entry.intent,
735
- result: entry.result,
736
- summary: entry.summary
737
- }) : tr("- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}", {
738
- name: entry.name,
739
- utterance: entry.utterance,
740
- intent: entry.intent,
741
- result: entry.result,
742
- summary: entry.summary
743
- });
744
- }
745
- function age(at, now, tr) {
746
- if (at === void 0 || now === void 0) return tr("some time ago");
747
- const seconds = Math.max(0, Math.floor((now - at) / 1e3));
748
- if (seconds < 60) return tr("just now");
749
- const amount = Math.floor(seconds / (seconds >= 86400 ? 86400 : seconds >= 3600 ? 3600 : 60));
750
- if (seconds >= 86400) return amount === 1 ? tr("1 day ago") : tr("{amount} days ago", { amount });
751
- if (seconds >= 3600) return amount === 1 ? tr("1 hour ago") : tr("{amount} hours ago", { amount });
752
- return amount === 1 ? tr("1 minute ago") : tr("{amount} minutes ago", { amount });
753
- }
754
- /** What a character remembers, in the way it remembers it: what is faded or vague is told as such, and what it is sure or doubtful of. */
755
- function remembered(memories, tr, now) {
756
- return memories.map((memory) => {
757
- const clarity = memory.clarity === "clear" ? [] : [memory.clarity === "faded" ? tr("the details are fuzzy") : tr("you barely remember")];
758
- const sure = memory.confidence === "sure" ? [tr("you are sure of it")] : memory.confidence === "doubtful" ? [tr("you doubt it")] : [];
759
- const against = memory.disputed === true ? [tr("something you have seen since speaks against it")] : [];
760
- return `- (${[
761
- age(memory.at, now, tr),
762
- ...clarity,
763
- ...sure,
764
- ...against,
765
- ...memory.linked === true ? [tr("it comes to mind with the rest")] : []
766
- ].join(tr(", "))}) ${memory.text}`;
767
- }).join("\n");
768
- }
769
- /** Every character is told the same thing about the scene, plus who it is and what it remembers. */
770
- const sharedContext = { brief(request) {
771
- const { member, cast, situation, attempt, earlier, reaction, previous, memories, place, relationships, knowledge, affiliations, carrying, time, agenda } = request;
772
- const language = languageOf(request.language);
773
- const tr = translator(language);
774
- const list = (entries) => entries.join(tr("; "));
775
- const company = place === void 0 ? cast : place.here;
776
- const sections = [
777
- `${tr("Situation:")}\n${situation}`,
778
- ...time === void 0 ? [] : [tr("Now: {time}.", { time: describeTime(time, language) })],
779
- ...place === void 0 ? [] : [`${tr("Where you are:")}\n${describePlace(place, { withKeys: false }, tr).join("\n")}`],
780
- `${tr("Present:")}\n${present(company, member.key, tr)}`
781
- ];
782
- if (request.upcoming !== void 0 && request.upcoming.length > 0) sections.push(`${tr("What you know is coming:")}\n${request.upcoming.map((entry) => `- ${entry.text}${entry.when === void 0 ? "" : ` (${entry.when})`}`).join("\n")}`);
783
- if (request.cues !== void 0 && request.cues.length > 0) sections.push(`${tr("Just now you notice:")}\n${request.cues.map((cue) => `- ${cue}`).join("\n")}`);
784
- if (request.tracked !== void 0 && request.tracked.self !== "") sections.push(`${tr("How you are (what you can tell of yourself):")}\n${request.tracked.self}`);
785
- if (request.tracked !== void 0 && request.tracked.others.length > 0) sections.push(`${tr("What you can tell of the others here:")}\n${request.tracked.others.map((other) => `- ${other.name}: ${other.text}`).join("\n")}`);
786
- const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now, tr, language);
787
- if (day.length > 0) sections.push(`${tr("Your day and what you are after (plans, not orders: keep them, put them off or drop them as the moment and your character suggest):")}\n${day.join("\n")}`);
788
- if (carrying !== void 0 && carrying.length > 0) sections.push(`${tr("What you have on you:")}\n${describeItems(carrying, { withKeys: false }, tr)}`);
789
- if (relationships !== void 0 && relationships.length > 0) sections.push(`${tr("How you stand with people who bear on this moment (your own view, not objective fact):")}\n${relationships.map((relation) => {
790
- const attitude = describeAttitude(relation, tr);
791
- return `- ${relation.name}${relation.present ? tr(" (here)") : tr(" (not here)")} — ${relation.label}${relation.summary === "" ? "" : `${tr(": ")}${relation.summary}`}${attitude === "" ? "" : ` [${attitude}]`}`;
792
- }).join("\n")}`);
793
- if (affiliations !== void 0 && affiliations.length > 0) sections.push(`${tr("Your affiliations (their goals are pressures and commitments, not commands):")}\n${affiliations.map((entry) => {
794
- const position = [entry.role, entry.rank].filter(Boolean).join(tr(", ")) || tr("member");
795
- const goals = entry.goals.length === 0 ? "" : tr(" Goals: {goals}.", { goals: list(entry.goals) });
796
- const state = entry.publicState === "" ? "" : ` ${entry.publicState}`;
797
- const attitude = entry.relationship === void 0 ? "" : describeAttitude(entry.relationship, tr);
798
- return tr("- {name}: {position}; {status}; commitment {commitment}.", {
799
- name: entry.name,
800
- position,
801
- status: entry.status,
802
- commitment: entry.commitment.toFixed(2)
803
- }) + `${state}${goals}${attitude === "" ? "" : tr(" Your view: {attitude}.", { attitude })}`;
804
- }).join("\n")}`);
805
- if (knowledge !== void 0) {
806
- const shown = (entries) => list(entries.slice(0, 30)) + (entries.length > 30 ? tr("; and {count} more you can recall if needed", { count: entries.length - 30 }) : "");
807
- const lines = [
808
- knowledge.characters.length === 0 ? void 0 : `${tr("People: ")}${shown(knowledge.characters)}`,
809
- knowledge.factions.length === 0 ? void 0 : `${tr("Factions: ")}${shown(knowledge.factions)}`,
810
- knowledge.locations.length === 0 ? void 0 : `${tr("Places: ")}${shown(knowledge.locations)}`,
811
- knowledge.routes.length === 0 ? void 0 : `${tr("Routes: ")}${shown(knowledge.routes)}`,
812
- knowledge.items.length === 0 ? void 0 : `${tr("Things: ")}${shown(knowledge.items)}`
813
- ].filter((line) => line !== void 0);
814
- if (lines.length > 0) sections.push(`${tr("What you know exists (this does not tell you where it is now or what state it is in):")}\n${lines.join("\n")}`);
815
- }
816
- if (memories !== void 0 && memories.length > 0) sections.splice(1, 0, `${tr("What you remember that bears on this (only what you took in yourself; do not claim to remember more, and be unsure of what is fuzzy):")}\n${remembered(memories, tr, time?.now)}`);
817
- else if (memories !== void 0) sections.splice(1, 0, tr("What you remember that bears on this: nothing comes to mind."));
818
- if (earlier !== void 0 && earlier.length > 0) sections.push(`${tr("Earlier in this scene, before this moment:")}\n${earlier.map((entry) => said(entry, tr)).join("\n")}`);
819
- if (attempt === 2 && reaction !== void 0) {
820
- sections.push(`${tr("What just happened, and what you are reacting to:")}\n${reaction.map((entry) => said(entry, tr)).join("\n")}`);
821
- if (previous !== void 0) sections.push(tr("Your earlier intent did not work out: {intent}\nYou are trying again, knowing the above. Decide again what you do now.", { intent: previous.intent }));
822
- }
823
- return {
824
- persona: [
825
- describe(member.character, tr),
826
- request.text("roleplay/character-rules", { name: member.character.name }),
827
- request.text("roleplay/character-style", { name: member.character.name }),
828
- ...request.lookup ? [request.text("roleplay/character-lookup")] : [],
829
- request.text("roleplay/character-decide", {
830
- name: member.character.name,
831
- ...limitVariables(request.language ?? "en")
832
- })
833
- ].join("\n\n"),
834
- prompt: sections.join("\n\n")
835
- };
836
- } };
837
- /**
838
- * Whoever is with the player's character acts, unless the game master names who (it always does in play). While the world has places, a character that is in none
839
- * is not part of the scene: asking it to act is refused, so that someone the story never placed cannot answer from nowhere. (A character in
840
- * another place can be asked when the moment reaches it.)
841
- */
842
- const everyoneActs = { plan({ cast, requested }) {
843
- const placed = cast.some((member) => member.place !== void 0);
844
- const available = cast.filter((member) => member.character.control === "agent");
845
- const here = cast.find((member) => member.character.control === "player")?.place?.location.id;
846
- const inScene = (member) => !placed || member.place !== void 0;
847
- if (requested === void 0 || requested.length === 0) return available.filter((member) => placed && here !== void 0 ? member.place?.location.id === here : inScene(member)).map((member) => member.key);
848
- const unknown = requested.filter((key) => !available.some((member) => member.key === key));
849
- if (unknown.length > 0) throw new Error(`cannot activate ${unknown.join(", ")}: not a character that acts on its own (available: ${available.map((member) => member.key).join(", ")})`);
850
- const nowhere = [...new Set(requested)].map((key) => available.find((member) => member.key === key)).filter((member) => !inScene(member));
851
- if (nowhere.length > 0) throw new Error(`cannot activate ${nowhere.map((member) => member.key).join(", ")}: in no place, so not part of this scene. Only characters that have a place act (${available.filter(inScene).map((member) => member.key).join(", ") || "nobody"}); leave the others out`);
852
- return [...new Set(requested)];
853
- } };
854
- const acceptsAnyIntent = { validate: ({ intent }) => intent.trim() === "" ? {
855
- ok: false,
856
- reason: "the intent is empty"
857
- } : { ok: true } };
858
- /** A character whose intent failed and who is highly committed tries once more. */
859
- const persistentRetry = { select({ reports, outcomes }) {
860
- return reports.filter((report) => report.commitment === "high" && outcomes.some((outcome) => outcome.character === report.character && outcome.result === "failed")).map((report) => report.character);
861
- } };
862
- const acceptsAnyInput = { validate: () => ({ ok: true }) };
863
- /** The game master narrates. */
864
- const gameMasterNarrates = { narrate: () => Promise.resolve(void 0) };
865
- /** Compares what was said, ignoring the quotes around it and the way whitespace is laid out. */
866
- const WRAPPING_QUOTES = /^["“”„«»'‘’]+|["“”„«»'‘’]+$/g;
867
- function sameWords(a, b) {
868
- const plain = (text) => text.trim().replace(WRAPPING_QUOTES, "").replace(/\s+/g, " ").trim();
869
- return plain(a) === plain(b);
870
- }
871
- /** How many earlier events the game master is reminded of at most. */
872
- const REMINDED_EVENTS = 5;
873
- /**
874
- * The state of the scene, what is still open in the story, and the earlier events that the
875
- * player's move brings to mind (by the session's search of words and meaning, and by who is named):
876
- * those already folded out of the conversation into the summaries, whose detail the summaries may have lost.
877
- */
878
- /** Where the player is and what is there, who is with them, and who is elsewhere. */
879
- function placedScene(cast, player, story, describeMember, tr, things) {
880
- const here = player?.place?.location;
881
- const sections = [];
882
- if (here !== void 0) {
883
- const view = {
884
- key: locationKey(here),
885
- location: here,
886
- here: cast.filter((member) => member.place?.location.id === here.id),
887
- ...things === void 0 ? {} : { items: things.at(here.id) },
888
- exits: story.locations.exitsFrom(here.id).flatMap((exit) => {
889
- const to = story.locations.get(exit.toId);
890
- return to === void 0 ? [] : [{
891
- key: locationKey(to),
892
- name: to.name,
893
- exit
894
- }];
895
- })
896
- };
897
- sections.push(tr("The player's character is in {place}", { place: describePlace(view, { withKeys: true }, tr).join("\n") }));
898
- sections.push(`${tr("Characters here:")}\n${view.here.map(describeMember).join("\n")}`);
899
- }
900
- const elsewhere = cast.filter((member) => member.place !== void 0 && member.place.location.id !== here?.id);
901
- if (elsewhere.length > 0) sections.push(`${tr("Characters elsewhere (they perceive nothing here unless the moment reaches them):")}\n${elsewhere.map((member) => tr("{member} - in {place} ({key})", {
902
- member: describeMember(member),
903
- place: member.place.location.name,
904
- key: locationKey(member.place.location)
905
- })).join("\n")}`);
906
- const nowhere = cast.filter((member) => member.place === void 0);
907
- if (nowhere.length > 0) sections.push(`${tr("Characters with no place (not part of this scene; they cannot be asked to act):")}\n${nowhere.map(describeMember).join("\n")}`);
908
- return sections.join("\n\n");
909
- }
910
- const castSummary = { scene({ tracked, time, world, cast, turn, input, queryVector, story, items, language: code }) {
911
- const language = languageOf(code);
912
- const tr = translator(language);
913
- const join = (entries) => entries.join(tr("; "));
914
- const describeMember = (member) => {
915
- const { key, character, state } = member;
916
- const role = character.control === "player" ? tr("the player's character, \"{key}\"", { key }) : tr("acts through \"{key}\"", { key });
917
- const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
918
- const where = whereIs(member, tr);
919
- return `- ${referent(character)} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `${tr(": ")}${character.summary}`}${seen.length > 0 ? ` ${tr("Currently: {state}", { state: join(seen) })}` : ""}`;
920
- };
921
- const player = cast.find((member) => member.character.control === "player");
922
- const days = time?.agenda === void 0 ? "" : describeSceneAgenda(time.agenda, time.now.now, tr, language);
923
- const scene = cast.some((member) => member.place !== void 0) ? placedScene(cast, player, story, describeMember, tr, items) : cast.map(describeMember).join("\n");
924
- const parts = [
925
- ...time === void 0 ? [] : [timeNotice(time, language, tr)],
926
- ...days === "" ? [] : [days],
927
- `${tr("Scene before turn {turn}:", { turn })}\n${scene}`
928
- ];
929
- const activation = describeActivationCandidates(cast, input, story, tr);
930
- if (activation !== "") parts.push(activation);
931
- if (items !== void 0) {
932
- const carried = cast.flatMap((member) => {
933
- const mine = items.carried(member.character.id);
934
- return mine.length === 0 ? [] : [`- ${member.character.name} (${member.key}): ${describeItems(mine, { withKeys: true }, tr)}`];
935
- });
936
- if (carried.length > 0) parts.push(`${tr("What characters have on them:")}\n${carried.join("\n")}`);
937
- }
938
- if (world !== void 0 && world.happened.length > 0) parts.push(`${tr("The world acted since the last turn, by itself:")}\n${world.happened.map((line) => `- ${line}`).join("\n")}`);
939
- if (world?.upcoming !== void 0 && world.upcoming.length > 0) parts.push(`${tr("Known beforehand, still to come (who knows of it; it will happen by itself when its time comes):")}\n${world.upcoming.map((entry) => `- ${entry.text}${entry.when === void 0 ? "" : ` (${entry.when})`} ${tr("[known to {who}]", { who: entry.who })}`).join("\n")}`);
940
- if (world !== void 0 && world.beats.length > 0) parts.push(`${tr("Weave these into the story when it fits, then say you did with addressed in narrate (each stays for a few turns and is then let go):")}\n${world.beats.map((beat) => `- [${beat.id}] ${beat.text}`).join("\n")}`);
941
- if (tracked !== void 0 && tracked.length > 0) parts.push(`${tr("What the story keeps track of (change it with variable_changes in an outcome when what happened calls for it):")}\n${tracked.map((line) => `- ${line}`).join("\n")}`);
942
- const threads = story.threads.list("open");
943
- if (threads.length > 0) parts.push(`${tr("Still open in the story:")}\n${threads.map((thread) => `- ${thread.text}`).join("\n")}`);
944
- const folded = story.summaries.list().reduce((latest, summary) => Math.max(latest, summary.toTurn), 0);
945
- if (folded > 0) {
946
- const mentionedIds = mentioned(input, cast.map(({ character }) => character));
947
- const cues = tokens(input);
948
- const names = new Map(cast.map(({ character }) => [character.id, character.name]));
949
- const byMeaning = story.searchEvents({
950
- text: input,
951
- ...queryVector === void 0 ? {} : { vector: queryVector },
952
- toTurn: folded,
953
- limit: REMINDED_EVENTS
954
- });
955
- const byCues = story.events.list({ toTurn: folded }).filter((event) => !byMeaning.some((found) => found.id === event.id)).map((event) => ({
956
- event,
957
- score: 3 * event.involves.filter((id) => mentionedIds.has(id)).length + overlap(cues, event.text, event.tags)
958
- })).filter(({ score }) => score >= 2).sort((a, b) => b.score + .5 * b.event.importance - a.score - .5 * a.event.importance || b.event.turn - a.event.turn).map(({ event }) => event);
959
- const relevant = [...byMeaning, ...byCues].slice(0, REMINDED_EVENTS).sort((a, b) => a.turn - b.turn).map((event) => ({ event }));
960
- if (relevant.length > 0) parts.push(`${tr("Earlier events that bear on what the player just did (from the records of the story):")}\n${relevant.map(({ event }) => {
961
- const who = event.involves.map((id) => names.get(id)).filter((name) => name !== void 0).join(tr(", "));
962
- return `- (${tr("turn {turn}", { turn: event.turn })}) ${event.text}${who === "" ? "" : ` [${who}]`}`;
963
- }).join("\n")}`);
964
- }
965
- return parts.join("\n\n");
966
- } };
967
- const sameCharacter = (utterance, character) => utterance.character === character || utterance.name === character;
968
- /** Every utterance appears once, exactly as given and in the order spoken, and no one speaks who did not. */
969
- const exactUtterances = {
970
- check(segments, required) {
971
- const problems = [];
972
- const used = /* @__PURE__ */ new Set();
973
- let latest = 0;
974
- segments.forEach((segment, index) => {
975
- const at = `segment ${index + 1}`;
976
- if (segment.type === "narration") {
977
- if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
978
- return;
979
- }
980
- const own = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) ? [position] : []);
981
- const free = own.filter((position) => !used.has(position));
982
- const exact = free.find((position) => sameWords(segment.text, required[position].text));
983
- if (exact !== void 0) {
984
- used.add(exact);
985
- const spoken = required[exact];
986
- if (spoken.round < latest) problems.push(`${at}: the utterance of ${spoken.name} from round ${spoken.round} comes after one from a later round; utterances keep the order they were spoken in`);
987
- latest = Math.max(latest, spoken.round);
988
- } else if (free.length > 0) {
989
- used.add(free[0]);
990
- problems.push(`${at}: the utterance of ${required[free[0]].name} was changed; it must be exactly "${required[free[0]].text}"`);
991
- } else if (own.length > 0) problems.push(`${at}: ${required[own[0]].name} has no more utterances to say; this one is repeated or invented, remove it`);
992
- else problems.push(`${at}: ${segment.character} has nothing to say this turn, so this utterance is invented; remove it`);
993
- });
994
- required.forEach((utterance, position) => {
995
- if (!used.has(position)) problems.push(`the utterance of ${utterance.name}${utterance.round > 1 ? ` (round ${utterance.round})` : ""} is missing; it must appear exactly as "${utterance.text}"`);
996
- });
997
- return problems;
998
- },
999
- repair(segments, required) {
1000
- const used = /* @__PURE__ */ new Set();
1001
- const kept = [];
1002
- for (const segment of segments) {
1003
- if (segment.type === "narration") {
1004
- if (segment.text.trim() !== "") kept.push({
1005
- segment,
1006
- round: void 0
1007
- });
1008
- continue;
1009
- }
1010
- const free = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) && !used.has(position) ? [position] : []);
1011
- const position = free.find((candidate) => sameWords(segment.text, required[candidate].text)) ?? free[0];
1012
- if (position === void 0) continue;
1013
- used.add(position);
1014
- const spoken = required[position];
1015
- kept.push({
1016
- segment: {
1017
- type: "utterance",
1018
- character: spoken.character,
1019
- name: spoken.name,
1020
- text: spoken.text
1021
- },
1022
- round: spoken.round
1023
- });
1024
- }
1025
- required.forEach((utterance, position) => {
1026
- if (used.has(position)) return;
1027
- const restored = {
1028
- type: "utterance",
1029
- character: utterance.character,
1030
- name: utterance.name,
1031
- text: utterance.text
1032
- };
1033
- const later = kept.findIndex((entry) => entry.round !== void 0 && entry.round > utterance.round);
1034
- kept.splice(later < 0 ? kept.length : later, 0, {
1035
- segment: restored,
1036
- round: utterance.round
1037
- });
1038
- });
1039
- return kept.map((entry) => entry.segment);
1040
- }
1041
- };
1042
- /** What a character is reminded of is what the story's records bring back for it: by the cues of the moment, by its words, and by its meaning when vectors exist. */
1043
- const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector, explain }, story, signal) => story.recallRanked({
1044
- characterId: member.character.id,
1045
- situation,
1046
- turn,
1047
- policy,
1048
- ...explain === true ? { explain } : {},
1049
- ...member.place === void 0 ? {} : { locationId: member.place.location.id }
1050
- }, signal, queryVector === void 0 ? {} : { queryVector }) };
1051
- /**
1052
- * Writes no memory. What the game master decided about each character is applied when the round is
1053
- * recorded, so without a memory keeper the story keeps its states and no events.
1054
- */
1055
- const writesNothing = { commit: () => Promise.resolve({
1056
- writes: 0,
1057
- notes: ""
1058
- }) };
1059
- /** Makes up nothing, and has nothing to fit in: without a world author the world stays as it was written. */
1060
- const declinesToAuthor = {
1061
- create: () => Promise.resolve({
1062
- created: [],
1063
- declined: "no world author is installed, so the world cannot grow"
1064
- }),
1065
- consolidate: () => Promise.resolve({
1066
- resolved: 0,
1067
- notes: ""
1068
- })
1069
- };
1070
- /** Lets no organisation act: without a strategist factions change only through what the story records. */
1071
- const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
1072
- /** Reflects on nothing: without a reflector what characters believe changes only through what the story records. */
1073
- const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
1074
- /** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
1075
- const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
1076
- /** Offers nothing: without a suggester the player writes their own move. */
1077
- const offersNothing = { suggest: () => Promise.resolve([]) };
1078
- function defaultBoundaries() {
1079
- return {
1080
- planner: everyoneActs,
1081
- characterContext: sharedContext,
1082
- outputValidator: acceptsAnyIntent,
1083
- retryPolicy: persistentRetry,
1084
- inputValidator: acceptsAnyInput,
1085
- narrator: gameMasterNarrates,
1086
- narrationChecker: exactUtterances,
1087
- committer: writesNothing,
1088
- author: declinesToAuthor,
1089
- strategist: factionsStayPut,
1090
- reflector: reflectsOnNothing,
1091
- judge: judgesNothing,
1092
- suggester: offersNothing,
1093
- recaller: recordsRecall,
1094
- sceneContext: castSummary
1095
- };
1096
- }
1097
- //#endregion
1098
- //#region src/shared/timeline.ts
1099
- const emptyTimeline = () => ({
1100
- version: 1,
1101
- head: null,
1102
- next: 1,
1103
- nodes: []
1104
- });
1105
- /** The turns from the first to `id`, in order; none for the start. */
1106
- function pathTo(timeline, id) {
1107
- const byId = new Map(timeline.nodes.map((node) => [node.id, node]));
1108
- const path = [];
1109
- for (let at = id === null ? void 0 : byId.get(id); at !== void 0; at = at.parent === null ? void 0 : byId.get(at.parent)) path.unshift(at);
1110
- return path;
1111
- }
1112
- /** The turns that follow `parent`, in the order they were played. */
1113
- const childrenOf = (timeline, parent) => timeline.nodes.filter((node) => node.parent === parent);
1114
- /** The snapshot that holds the state before any turn. */
1115
- const START_SNAPSHOT = "start";
1116
- /** The snapshot that holds the state after a turn. */
1117
- const snapshotOf = (id) => `after-${id}`;
1118
- /** Builds what the client shows from the timeline. */
1119
- function viewOf(timeline) {
1120
- const turn = (node) => ({
1121
- id: node.id,
1122
- turn: node.turn,
1123
- player: node.player,
1124
- ...node.endSeq === void 0 ? {} : { endSeq: node.endSeq },
1125
- ...node.output === void 0 ? {} : { output: node.output },
1126
- restorable: node.snapshot !== void 0,
1127
- alternatives: childrenOf(timeline, node.parent).map((sibling) => sibling.id)
1128
- });
1129
- const on = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
1130
- const withdrawn = timeline.nodes.filter((node) => !on.has(node.id) && node.userSeq >= 0).map((node) => ({
1131
- from: Math.min(node.startSeq ?? node.userSeq, node.userSeq),
1132
- to: node.endSeq ?? Number.MAX_SAFE_INTEGER
1133
- }));
1134
- return {
1135
- head: timeline.head,
1136
- path: pathTo(timeline, timeline.head).map(turn),
1137
- forward: childrenOf(timeline, timeline.head).map(turn),
1138
- canStart: true,
1139
- withdrawn
1140
- };
1141
- }
1142
- /** Where a notice stands for a turn that is not told by its own events: the player's words and what was delivered, as plain text. */
1143
- function noticeText(node) {
1144
- const told = node.output === void 0 ? "(nothing was delivered)" : node.output.segments.map((segment) => segment.type === "utterance" ? `${segment.name}: "${segment.text}"` : segment.text).join("\n");
1145
- const ooc = node.output?.ooc;
1146
- const ruling = ooc === void 0 ? "" : ooc.question === true ? `\nThe question was answered out of character: ${ooc.note}` : `\nThe command was ruled ${ooc.legal ? "legal" : "illegal and refused"}: ${ooc.note}`;
1147
- return `The story, as it went earlier (restored):\nThe player said: ${node.player}${ruling}\nIt was told to the player:\n${told}`;
1148
- }
1149
- //#endregion
1150
- //#region src/host/timeline/file.ts
1151
- const TIMELINE_FILE = "timeline.json";
1152
- function isNode(value) {
1153
- if (typeof value !== "object" || value === null) return false;
1154
- const node = value;
1155
- return typeof node["id"] === "string" && (node["parent"] === null || typeof node["parent"] === "string") && typeof node["turn"] === "number" && typeof node["userSeq"] === "number" && typeof node["player"] === "string" && typeof node["createdAt"] === "string";
1156
- }
1157
- /**
1158
- * The timeline of a session, or an empty one when it has none yet.
1159
- * @throws {Error} when the file is there and is not a timeline: it holds what lets the story be taken back, so it is not replaced silently.
1160
- */
1161
- function readTimeline(folder) {
1162
- let text;
1163
- try {
1164
- text = readFileSync(join(folder, TIMELINE_FILE), "utf8");
1165
- } catch (error) {
1166
- if (error.code === "ENOENT") return emptyTimeline();
1167
- throw error;
1168
- }
1169
- const value = JSON.parse(text);
1170
- if (value.version !== 1 || !Array.isArray(value.nodes) || !value.nodes.every(isNode) || typeof value.next !== "number" || value.head !== null && typeof value.head !== "string") throw new Error(`${join(folder, TIMELINE_FILE)} is not a timeline`);
1171
- return value;
1172
- }
1173
- /** Writes it aside and renames it, so a crash leaves the timeline as it was. */
1174
- function writeTimeline(folder, timeline) {
1175
- const target = join(folder, TIMELINE_FILE);
1176
- const aside = `${target}.writing`;
1177
- writeFileSync(aside, JSON.stringify(timeline, null, 2));
1178
- renameSync(aside, target);
1179
- }
1180
- //#endregion
1181
- //#region src/host/timeline/branch.ts
1182
- var BranchError = class extends Error {};
1183
- /**
1184
- * What a branch of a story cut at a log event keeps of the timeline: the turns that ended at or before it, standing at the one
1185
- * that ended last, and the state of the story after that turn.
1186
- * @param boundary - the seq of the last event the branch inherits.
1187
- * @param snapshots - the names of the snapshots the story has.
1188
- * @throws {BranchError} when the state at that point was not kept.
1189
- */
1190
- function branchTimeline(timeline, boundary, snapshots) {
1191
- const nodes = timeline.nodes.filter((node) => node.endSeq !== void 0 && node.endSeq <= boundary).map((node) => ({ ...node }));
1192
- for (const node of nodes) if (node.noticeSeq !== void 0 && node.noticeSeq > boundary) delete node.noticeSeq;
1193
- const last = nodes.reduce((found, node) => found === void 0 || node.endSeq > found.endSeq ? node : found, void 0);
1194
- const available = new Set(snapshots);
1195
- for (const node of nodes) if (node.snapshot !== void 0 && !available.has(node.snapshot)) delete node.snapshot;
1196
- const keep = [...nodes.flatMap((node) => node.snapshot === void 0 ? [] : [node.snapshot]), ...available.has("start") ? [START_SNAPSHOT] : []];
1197
- const branch = {
1198
- version: 1,
1199
- head: last?.id ?? null,
1200
- next: timeline.next,
1201
- nodes
1202
- };
1203
- if (last === void 0) {
1204
- if (!available.has("start")) throw new BranchError("the state at the start of the story was not kept, so it cannot be branched");
1205
- return {
1206
- timeline: branch,
1207
- from: { snapshot: START_SNAPSHOT },
1208
- keep
1209
- };
1210
- }
1211
- if (last.snapshot !== void 0) return {
1212
- timeline: branch,
1213
- from: { snapshot: last.snapshot },
1214
- keep
1215
- };
1216
- if (timeline.head === last.id) return {
1217
- timeline: branch,
1218
- from: { live: true },
1219
- keep
1220
- };
1221
- throw new BranchError(`the state of the story after its turn ${last.turn} was not kept, so it cannot be branched there`);
1222
- }
1223
- /** The name of a branch: the story's name with its trailing number counted up, or a 2 added. */
1224
- function branchName(name) {
1225
- const numbered = /^(.*?)(\d+)\s*$/.exec(name);
1226
- const next = numbered === null ? `${name} 2` : `${numbered[1]}${Number(numbered[2]) + 1}`;
1227
- return next.length > 200 ? `${[...name].slice(0, 190).join("").trimEnd()} 2` : next;
1228
- }
1229
- //#endregion
1230
- //#region src/host/timeline/plan.ts
1231
- /**
1232
- * Where the model's conversation has to be changed so that it carries the turns from the first to `target`, and no others.
1233
- * A turn is on the conversation when its own message is, or the notice that stands for it. The turns that stay are the longest
1234
- * run from the first that is on it; whatever else of the timeline is on it is shadowed, and the rest of the way is told by notices.
1235
- * @param surface - the seqs of the model's conversation, in order.
1236
- */
1237
- function planMove(timeline, target, surface) {
1238
- const onSurface = new Set(surface);
1239
- const path = pathTo(timeline, target);
1240
- let keptCount = 0;
1241
- let last = -1;
1242
- for (const node of path) {
1243
- const at = surface.indexOf(node.userSeq);
1244
- if (at <= last) break;
1245
- last = at;
1246
- keptCount += 1;
1247
- }
1248
- const kept = path.slice(0, keptCount);
1249
- const keptIds = new Set(kept.map((node) => node.id));
1250
- const byStart = [...timeline.nodes].sort((a, b) => a.userSeq - b.userSeq);
1251
- const seqs = /* @__PURE__ */ new Set();
1252
- byStart.forEach((node, index) => {
1253
- if (keptIds.has(node.id)) return;
1254
- if (node.noticeSeq !== void 0 && onSurface.has(node.noticeSeq)) seqs.add(node.noticeSeq);
1255
- if (!onSurface.has(node.userSeq)) return;
1256
- const end = node.endSeq ?? (byStart[index + 1]?.userSeq === void 0 ? Infinity : byStart[index + 1].userSeq - 1);
1257
- for (const seq of surface) if (seq >= node.userSeq && seq <= end) seqs.add(seq);
1258
- });
1259
- const shadow = [];
1260
- let run = [];
1261
- let previous = -2;
1262
- surface.forEach((seq, index) => {
1263
- if (!seqs.has(seq)) return;
1264
- if (index !== previous + 1 && run.length > 0) {
1265
- shadow.push({
1266
- startSeq: run[0],
1267
- endSeq: run.at(-1),
1268
- seqs: run
1269
- });
1270
- run = [];
1271
- }
1272
- run.push(seq);
1273
- previous = index;
1274
- });
1275
- if (run.length > 0) shadow.push({
1276
- startSeq: run[0],
1277
- endSeq: run.at(-1),
1278
- seqs: run
1279
- });
1280
- return {
1281
- shadow,
1282
- kept: kept.map((node) => node.id),
1283
- inject: path.slice(keptCount)
1284
- };
1285
- }
1286
- //#endregion
1287
- //#region src/host/timeline/service.ts
1288
- /** The text of the marker that stands for the turns it replaces: never empty, as a model service may refuse an empty message. */
1289
- const MARKER_TEXT = "(empty message)";
1290
- /** A turn that has not ended does not know yet where its own message is in the log. */
1291
- const UNKNOWN_SEQ = -1;
1292
- var TimelineError = class extends Error {};
1293
- /**
1294
- * What the story's turns are, and taking the story back to one of them (or forward again). The conversation with the model is
1295
- * only ever added to: the turns that no longer belong are replaced by a marker, which DSH keeps out of the next request, and
1296
- * a turn that comes back is told once as a notice. The state of the story is put back from the snapshot taken when the turn settled.
1297
- * Everything here is one at a time per chat.
1298
- */
1299
- var Timelines = class {
1300
- deps;
1301
- queues = /* @__PURE__ */ new Map();
1302
- constructor(deps) {
1303
- this.deps = deps;
1304
- }
1305
- serial(chat, job) {
1306
- const run = (this.queues.get(chat) ?? Promise.resolve()).then(job, job);
1307
- this.queues.set(chat, run.catch(() => void 0));
1308
- return run;
1309
- }
1310
- idOf(chat) {
1311
- const id = roleplaySessionOf(chat);
1312
- if (id === void 0) throw new TimelineError(`${chat} is not a roleplay chat`);
1313
- return id;
1314
- }
1315
- folder(id) {
1316
- return sessionFolder(this.deps.sessionsDir(), id);
1317
- }
1318
- read(id) {
1319
- return readTimeline(this.folder(id));
1320
- }
1321
- view(id) {
1322
- return viewOf(this.read(id));
1323
- }
1324
- /**
1325
- * The player has said something and a turn begins: the turn is added to the timeline after the head, and the state the earlier one left is kept at once,
1326
- * with the records still waiting for the keeper in it (they are in the database, so a restored state carries them).
1327
- */
1328
- begin(chat, turn, player) {
1329
- return this.serial(chat, async () => {
1330
- this.deps.cancel?.(chat);
1331
- const id = this.idOf(chat);
1332
- const timeline = this.read(id);
1333
- this.keep(id, timeline, timeline.head);
1334
- const node = {
1335
- id: `n${timeline.next}`,
1336
- parent: timeline.head,
1337
- turn,
1338
- userSeq: UNKNOWN_SEQ,
1339
- player,
1340
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1341
- };
1342
- timeline.nodes.push(node);
1343
- timeline.next += 1;
1344
- timeline.head = node.id;
1345
- writeTimeline(this.folder(id), timeline);
1346
- this.prune(id, timeline);
1347
- return node;
1348
- });
1349
- }
1350
- /** What the turn delivered; and, once nothing writes to the story any more, its state is kept. */
1351
- delivered(chat, output) {
1352
- const id = this.idOf(chat);
1353
- const timeline = this.read(id);
1354
- const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
1355
- if (node === void 0) return void 0;
1356
- node.output = output;
1357
- writeTimeline(this.folder(id), timeline);
1358
- this.deps.engine.quiesce(chat).then(() => this.serial(chat, () => {
1359
- const current = this.read(id);
1360
- if (current.head === node.id) this.keep(id, current, node.id);
1361
- return Promise.resolve();
1362
- })).catch(() => void 0);
1363
- return node.id;
1364
- }
1365
- /**
1366
- * The turn ended in the log. Its own message is found now: it is the first message of the player after the last turn that ended
1367
- * (it is not in the log yet when the turn begins).
1368
- */
1369
- ended(chat, session, seq) {
1370
- const id = this.idOf(chat);
1371
- const timeline = this.read(id);
1372
- const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
1373
- if (node === void 0 || node.endSeq !== void 0) return;
1374
- const after = Math.max(-1, ...timeline.nodes.filter((other) => other.id !== node.id).map((other) => other.endSeq ?? other.userSeq));
1375
- const human = session.snapshotEvents().find((event) => event.seq > after && event.type === "user/message" && event.data.source.kind === "user");
1376
- if (human === void 0) throw new TimelineError(`turn ${node.turn} has no message of the player in the log`);
1377
- node.userSeq = human.seq;
1378
- node.endSeq = seq;
1379
- const began = session.snapshotEvents().find((event) => event.type === "turn/start" && event.data.turn === node.turn);
1380
- node.startSeq = Math.min(began?.seq ?? human.seq, human.seq);
1381
- writeTimeline(this.folder(id), timeline);
1382
- }
1383
- /** Keeps the state as it is under the name of the turn it follows from, when that is not done yet. */
1384
- keep(id, timeline, at) {
1385
- if (this.deps.keepSnapshots(id) === 0) return;
1386
- const node = at === null ? void 0 : timeline.nodes.find((candidate) => candidate.id === at);
1387
- const name = node === void 0 ? START_SNAPSHOT : snapshotOf(node.id);
1388
- if (node !== void 0 && node.snapshot !== void 0) return;
1389
- if (node === void 0 && this.deps.state.snapshots(this.deps.sessionsDir(), id).includes("start")) return;
1390
- this.deps.state.snapshot(this.deps.sessionsDir(), id, name);
1391
- if (node !== void 0) {
1392
- node.snapshot = name;
1393
- writeTimeline(this.folder(id), timeline);
1394
- }
1395
- }
1396
- /** Lets the oldest snapshots go: only the turns most recently played keep theirs, and the one that holds the start stays. */
1397
- prune(id, timeline) {
1398
- const keep = this.deps.keepSnapshots(id);
1399
- const kept = timeline.nodes.filter((node) => node.snapshot !== void 0);
1400
- const dropped = kept.slice(0, Math.max(0, kept.length - keep));
1401
- if (dropped.length === 0) return;
1402
- for (const node of dropped) {
1403
- this.deps.state.removeSnapshot(this.deps.sessionsDir(), id, node.snapshot);
1404
- delete node.snapshot;
1405
- }
1406
- writeTimeline(this.folder(id), timeline);
1407
- }
1408
- /**
1409
- * Takes the story to the state after a turn (`null` for the start): what is in flight stops, the state is put back from the snapshot,
1410
- * the turns that no longer belong are replaced by a marker on the model's conversation, and the turns that come back are told as notices.
1411
- * @returns what the player said in the first turn that was left, to put back in the input; nothing when the story went forward.
1412
- * @throws {TimelineError} when there is no such turn, its state was not kept, or the chat is not loaded.
1413
- */
1414
- move(chat, target) {
1415
- return this.serial(chat, async () => {
1416
- const id = this.idOf(chat);
1417
- const timeline = this.read(id);
1418
- const to = target === null ? void 0 : timeline.nodes.find((node) => node.id === target);
1419
- if (target !== null && to === void 0) throw new TimelineError(`there is no turn "${target}"`);
1420
- const snapshot = target === null ? START_SNAPSHOT : to.snapshot;
1421
- if (snapshot === void 0 || !this.deps.state.snapshots(this.deps.sessionsDir(), id).includes(snapshot)) throw new TimelineError("the state of the story at that turn was not kept");
1422
- const agent = await this.deps.agentOf(chat);
1423
- if (agent === void 0) throw new TimelineError(`the chat ${chat} is not loaded`);
1424
- if (agent.status !== "idle") {
1425
- agent.cancel({ kind: "user" }, { keepInbox: true });
1426
- await agent.whenIdle();
1427
- }
1428
- this.deps.cancel?.(chat);
1429
- this.deps.engine.stop(chat);
1430
- await this.deps.engine.quiesce(chat);
1431
- this.deps.engine.forget(chat);
1432
- const was = pathTo(timeline, timeline.head);
1433
- const plan = planMove(timeline, target, [...agent.session.surface.nodes]);
1434
- this.deps.state.restore(this.deps.sessionsDir(), id, snapshot);
1435
- this.reconcile(agent, plan);
1436
- timeline.head = target;
1437
- writeTimeline(this.folder(id), timeline);
1438
- const left = was.find((node) => !pathTo(timeline, target).some((kept) => kept.id === node.id));
1439
- return left === void 0 ? {} : { draft: left.player };
1440
- });
1441
- }
1442
- /** Makes the model's conversation carry the turns of a plan and no others: what does not belong is replaced by a marker, and the turns that come back are told as notices. */
1443
- reconcile(agent, plan) {
1444
- for (const run of plan.shadow) agent.session.append("user/message", createUserMessage({
1445
- content: [{
1446
- type: "text",
1447
- text: MARKER_TEXT
1448
- }],
1449
- source: { kind: "roleplay" }
1450
- }), {
1451
- surfaceOp: {
1452
- op: "replace",
1453
- startSeq: run.startSeq,
1454
- endSeq: run.endSeq
1455
- },
1456
- sourceEventSeqs: run.seqs
1457
- });
1458
- for (const node of plan.inject) node.noticeSeq = agent.session.append("user/message", createUserMessage({
1459
- content: [{
1460
- type: "text",
1461
- text: noticeText(node)
1462
- }],
1463
- source: { kind: "roleplay" }
1464
- }), { surfaceOp: "append" }).seq;
1465
- }
1466
- /**
1467
- * A chat DSH made as a branch of a roleplay chat gets a session of its own: the state of the story where the branch was cut (its snapshot, or
1468
- * the live state when the story stands there and has not kept one yet), the turns it inherits, the settings, and a name. The branch's own chat is
1469
- * made to carry the turns it inherits and no others. A chat that already has its session (it is only loaded again) is left as it is.
1470
- * @param cut - the seq of the last event of the log the branch inherits.
1471
- * @returns whether a session was made.
1472
- * @throws {BranchError} when the state at the cut was not kept; the branch is then not made.
1473
- */
1474
- adopt(chat, parent, cut, agent) {
1475
- return this.serial(parent, async () => {
1476
- const id = this.idOf(chat);
1477
- const from = this.idOf(parent);
1478
- const directory = this.deps.sessionsDir();
1479
- if (existsSync(sessionDatabase(directory, id)) || !existsSync(sessionDatabase(directory, from))) return false;
1480
- const branch = branchTimeline(this.read(from), cut, this.deps.state.snapshots(directory, from));
1481
- if ("live" in branch.from) await this.deps.engine.quiesce(parent);
1482
- const name = branchName(this.deps.state.openSession(directory, from).metadata.get().name);
1483
- this.deps.state.fork(directory, from, id, branch.from, {
1484
- name,
1485
- keep: branch.keep
1486
- });
1487
- try {
1488
- await inheritImages(this.folder(from), this.folder(id), branch.timeline.nodes.map((node) => node.id));
1489
- inheritPrompts(this.folder(from), this.folder(id));
1490
- inheritPacks(this.folder(from), this.folder(id));
1491
- const plan = planMove(branch.timeline, branch.timeline.head, [...agent.session.surface.nodes]);
1492
- this.reconcile(agent, plan);
1493
- writeTimeline(this.folder(id), branch.timeline);
1494
- } catch (error) {
1495
- this.deps.state.deleteSession(directory, id);
1496
- throw error;
1497
- }
1498
- return true;
1499
- });
1500
- }
1501
- /** The turns that follow a turn, for the choices the story can be taken to. */
1502
- forward(id) {
1503
- const timeline = this.read(id);
1504
- return childrenOf(timeline, timeline.head);
1505
- }
1506
- };
1507
- //#endregion
1508
527
  //#region src/host/orchestration/observation.ts
1509
528
  /** What a character takes in where it stands and of what it carries: the place, the ways out and what they lead to, what lies in the open, what it holds. */
1510
529
  function observeSurroundings(session, characterId, turn) {
@@ -1535,6 +554,7 @@ function observeAsPlayer(session, turn) {
1535
554
  }
1536
555
  //#endregion
1537
556
  //#region src/shared/notes.ts
557
+ /** The kinds the host stores; `unwritten` is made when the notes are read, from the rounds still waiting for the record keeper. */
1538
558
  const NOTE_KINDS = [
1539
559
  "suggestions",
1540
560
  "away",
@@ -1542,7 +562,7 @@ const NOTE_KINDS = [
1542
562
  ];
1543
563
  //#endregion
1544
564
  //#region src/host/sessions/notes.ts
1545
- const KEY$2 = "notes";
565
+ const KEY$3 = "notes";
1546
566
  const isNote = (value) => {
1547
567
  if (typeof value !== "object" || value === null) return false;
1548
568
  const note = value;
@@ -1550,12 +570,12 @@ const isNote = (value) => {
1550
570
  };
1551
571
  /** The notes of a session, at most one per kind. */
1552
572
  function readNotes(session) {
1553
- const stored = session.metadata.getValue(KEY$2);
573
+ const stored = session.metadata.getValue(KEY$3);
1554
574
  return Array.isArray(stored) ? stored.filter(isNote) : [];
1555
575
  }
1556
576
  /** Replaces the note of the same kind. */
1557
577
  function putNote(session, note) {
1558
- session.metadata.setValue(KEY$2, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
578
+ session.metadata.setValue(KEY$3, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1559
579
  }
1560
580
  /** The most lines one note keeps: what is past it is not told. */
1561
581
  const MAX_NOTE_LINES = 8;
@@ -1570,7 +590,7 @@ function addToNote(session, kind, turn, lines) {
1570
590
  }
1571
591
  /** Removes every note: they belong to the turn that made them. */
1572
592
  function clearNotes(session) {
1573
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$2, []);
593
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$3, []);
1574
594
  }
1575
595
  /**
1576
596
  * The notes of a session, for the player's screen.
@@ -1578,7 +598,82 @@ function clearNotes(session) {
1578
598
  */
1579
599
  function notesOfSession(deps, id) {
1580
600
  if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1581
- return readNotes(deps.open(id));
601
+ const session = deps.open(id);
602
+ const waiting = session.pendingCommits?.list().length ?? 0;
603
+ return waiting === 0 ? readNotes(session) : [...readNotes(session), {
604
+ kind: "unwritten",
605
+ turn: 0,
606
+ lines: [],
607
+ count: waiting
608
+ }];
609
+ }
610
+ //#endregion
611
+ //#region src/shared/tools.ts
612
+ /** What this version can offer. A name in a settings file or a world that is not here is kept and ignored. */
613
+ const OPTIONAL_TOOLS = [
614
+ {
615
+ id: "roll_check",
616
+ agent: "gameMaster",
617
+ default: true
618
+ },
619
+ {
620
+ id: "roll_dice",
621
+ agent: "gameMaster",
622
+ default: true
623
+ },
624
+ {
625
+ id: "list_checks",
626
+ agent: "gameMaster",
627
+ default: true
628
+ },
629
+ {
630
+ id: "recall_my_memories",
631
+ agent: "characters",
632
+ default: true
633
+ },
634
+ {
635
+ id: "recall_my_known_entities",
636
+ agent: "characters",
637
+ default: true
638
+ },
639
+ {
640
+ id: "recall_my_lore",
641
+ agent: "characters",
642
+ default: true
643
+ },
644
+ {
645
+ id: "search_events",
646
+ agent: "records",
647
+ default: true
648
+ },
649
+ {
650
+ id: "list_threads",
651
+ agent: "records",
652
+ default: true
653
+ },
654
+ {
655
+ id: "list_relationships",
656
+ agent: "records",
657
+ default: true
658
+ },
659
+ {
660
+ id: "list_items",
661
+ agent: "records",
662
+ default: true
663
+ }
664
+ ];
665
+ /** Whether an agent of this kind has a tool, by what the switches say and, failing that, by default. A tool this version does not offer is never on. */
666
+ function toolEnabled(board, agent, id) {
667
+ const offered = OPTIONAL_TOOLS.find((tool) => tool.agent === agent && tool.id === id);
668
+ if (offered === void 0) return false;
669
+ return board[agent]?.[id] ?? offered.default;
670
+ }
671
+ /**
672
+ * Whether an agent of this kind has a tool that is not one of this plugin's own: only when it was switched on. Such tools are off by default, because
673
+ * they reach beyond the story (files, a shell, the web), and a name that no plugin registers now has no effect.
674
+ */
675
+ function externalEnabled(board, agent, name) {
676
+ return board[agent]?.[name] === true;
1582
677
  }
1583
678
  //#endregion
1584
679
  //#region src/shared/ooc.ts
@@ -1605,13 +700,13 @@ const MAX_OOC_ANSWER = 1200;
1605
700
  function characterRunner(deps) {
1606
701
  return async (request, signal) => {
1607
702
  const brief = deps.boundaries().characterContext.brief(request);
1608
- const tools = request.lookup ? createCharacterTools(() => ({
703
+ const settings = deps.store.settings();
704
+ const tools = settings.memory.lookup ? createCharacterTools(() => ({
1609
705
  session: deps.store.story,
1610
706
  turn: request.turn,
1611
- policy: deps.store.settings().memory,
707
+ policy: settings.memory,
1612
708
  queryVector: deps.store.queryVector
1613
- }), request.member.character.id) : [];
1614
- const settings = deps.store.settings();
709
+ }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)) : [];
1615
710
  const external = externalGiven(deps.parent.ctx.tools, settings.tools, "characters");
1616
711
  const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
1617
712
  return parseCharacterAction(await runChild({
@@ -1794,7 +889,7 @@ function updatePlotProgress(store, plotId, developmentId, action) {
1794
889
  }
1795
890
  //#endregion
1796
891
  //#region src/host/pacing/author.ts
1797
- const RESULT$1 = {
892
+ const RESULT = {
1798
893
  type: "object",
1799
894
  required: [
1800
895
  "id",
@@ -1905,7 +1000,7 @@ async function authorPlot(parent, store, turn, signal) {
1905
1000
  trace: childTrace(store, "authoring", "plot author"),
1906
1001
  persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
1907
1002
  reasoningEffort: store.settings().reasoning.children,
1908
- result: RESULT$1,
1003
+ result: RESULT,
1909
1004
  maxCalls: 3,
1910
1005
  prompt: `The story has gone quiet by turn ${turn}. Propose one optional plot scaffold that grows from this state.\n\nCharacters:\n${cast || "- none"}\n\nFactions:\n${factions || "- none"}\n\nPlaces: ${places || "none"}\n\nRecent recorded events:\n${events || "- none"}`,
1911
1006
  beforeSubmit(value) {
@@ -2718,39 +1813,6 @@ function createTools$1(deps) {
2718
1813
  ];
2719
1814
  }
2720
1815
  //#endregion
2721
- //#region src/shared/tools.ts
2722
- /** What this version can offer. A name in a settings file or a world that is not here is kept and ignored. */
2723
- const OPTIONAL_TOOLS = [
2724
- {
2725
- id: "roll_check",
2726
- agent: "gameMaster",
2727
- default: true
2728
- },
2729
- {
2730
- id: "roll_dice",
2731
- agent: "gameMaster",
2732
- default: true
2733
- },
2734
- {
2735
- id: "list_checks",
2736
- agent: "gameMaster",
2737
- default: true
2738
- }
2739
- ];
2740
- /** Whether an agent of this kind has a tool, by what the switches say and, failing that, by default. A tool this version does not offer is never on. */
2741
- function toolEnabled(board, agent, id) {
2742
- const offered = OPTIONAL_TOOLS.find((tool) => tool.agent === agent && tool.id === id);
2743
- if (offered === void 0) return false;
2744
- return board[agent]?.[id] ?? offered.default;
2745
- }
2746
- /**
2747
- * Whether an agent of this kind has a tool that is not one of this plugin's own: only when it was switched on. Such tools are off by default, because
2748
- * they reach beyond the story (files, a shell, the web), and a name that no plugin registers now has no effect.
2749
- */
2750
- function externalEnabled(board, agent, name) {
2751
- return board[agent]?.[name] === true;
2752
- }
2753
- //#endregion
2754
1816
  //#region src/host/tools/external.ts
2755
1817
  /** The reserved transport DSH presents tools through; it is never a tool of its own to switch. */
2756
1818
  const RESERVED = /* @__PURE__ */ new Set(["run_code"]);
@@ -2784,584 +1846,8 @@ function externalWithheld(registry, board, agent) {
2784
1846
  return externalTools(registry).map((tool) => tool.name).filter((name) => !externalEnabled(board, agent, name));
2785
1847
  }
2786
1848
  //#endregion
2787
- //#region src/host/orchestration/whereabouts.ts
2788
- const within = (inner, outer, places) => {
2789
- const byId = new Map(places.map((place) => [place.id, place]));
2790
- const seen = /* @__PURE__ */ new Set();
2791
- for (let at = inner; at !== void 0 && !seen.has(at.id); at = at.parentId === void 0 ? void 0 : byId.get(at.parentId)) {
2792
- if (at.id === outer.id) return true;
2793
- seen.add(at.id);
2794
- }
2795
- return false;
2796
- };
2797
- /** Whether two places are one scene: the same place, or one inside the other (a room and its building). */
2798
- const sameScene = (a, b, places) => within(a, b, places) || within(b, a, places);
2799
- /**
2800
- * Compares the place an action is said to happen at (by key) with where the character is. Only a proven mismatch counts: a character that is
2801
- * nowhere, or a world without places, is no evidence, and a place that contains the other (a room and its building) is the same for this.
2802
- */
2803
- function whereabouts(places, here, at) {
2804
- const target = places.find((place) => locationKey(place) === at);
2805
- if (target === void 0) return { kind: "unknown" };
2806
- if (here === void 0) return { kind: "unplaced" };
2807
- return within(here, target, places) || within(target, here, places) ? { kind: "here" } : {
2808
- kind: "elsewhere",
2809
- target,
2810
- here
2811
- };
2812
- }
2813
- //#endregion
2814
- //#region src/host/memory/reflection.ts
2815
- const LAST_KEY = "reflection.last";
2816
- const CURSOR_KEY = "reflection.cursor";
2817
- const ANCHOR_KEY = "reflection.anchor";
2818
- const ERROR_KEY = "reflection.error";
2819
- const DAY_MS = 864e5;
2820
- const MAX_MATERIAL = 40;
2821
- const MAX_BELIEFS_SHOWN = 40;
2822
- const MAX_ADDED = 4;
2823
- const MAX_CHANGES = 10;
2824
- const MAX_TEXT = 300;
2825
- /** An event this important is reason enough for a belief on its own. */
2826
- const DECISIVE_IMPORTANCE = 4;
2827
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2828
- function readLast(session) {
2829
- const stored = session.metadata.getValue(LAST_KEY);
2830
- return isRecord(stored) && typeof stored["turn"] === "number" ? stored : void 0;
2831
- }
2832
- function readCursor(session) {
2833
- const stored = session.metadata.getValue(CURSOR_KEY);
2834
- return isRecord(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
2835
- }
2836
- function readAnchor(session) {
2837
- const stored = session.metadata.getValue(ANCHOR_KEY);
2838
- return isRecord(stored) && typeof stored["now"] === "number" ? {
2839
- now: stored["now"],
2840
- ...typeof stored["place"] === "number" ? { place: stored["place"] } : {}
2841
- } : void 0;
2842
- }
2843
- function writeAnchor(session, place, now) {
2844
- session.metadata.setValue(ANCHOR_KEY, {
2845
- now,
2846
- ...place === void 0 ? {} : { place: place.id }
2847
- });
2848
- }
2849
- const playerPlace = (store) => store.cast().find((member) => member.character.control === "player")?.place?.location;
2850
- /** What is known of the story's reflection: whether a pass runs, the latest that finished, and why the latest failed. */
2851
- function reflectionStatus(session, running) {
2852
- const last = readLast(session);
2853
- const failure = session.metadata.getValue(ERROR_KEY);
2854
- return {
2855
- running,
2856
- ...last === void 0 ? {} : { last },
2857
- ...isRecord(failure) && typeof failure["message"] === "string" && typeof failure["at"] === "string" ? { error: {
2858
- at: failure["at"],
2859
- message: failure["message"]
2860
- } } : {}
2861
- };
2862
- }
2863
- function recordFailure(session, message) {
2864
- session.metadata.setValue(ERROR_KEY, {
2865
- at: (/* @__PURE__ */ new Date()).toISOString(),
2866
- message: message.slice(0, 500)
2867
- });
2868
- }
2869
- /**
2870
- * Whether the story should reflect after this turn, and why. A pass waits until `minTurns` turns have passed since the last one; then it
2871
- * comes after `everyTurns` turns, or when the scene has changed since the last pass (the player's character is somewhere that is neither
2872
- * where it was nor inside or around it, or `sceneDays` of story time have passed). The first look only notes where the story stands.
2873
- */
2874
- function dueReflection(store, turn) {
2875
- const { reflection } = store.settings();
2876
- if (!reflection.auto) return void 0;
2877
- const session = store.story;
2878
- const { now } = store.time(turn);
2879
- const here = playerPlace(store);
2880
- const anchor = readAnchor(session);
2881
- if (anchor === void 0) {
2882
- writeAnchor(session, here, now);
2883
- return;
2884
- }
2885
- const since = turn - (readLast(session)?.turn ?? 0);
2886
- if (since < reflection.minTurns) return void 0;
2887
- if (reflection.everyTurns > 0 && since >= reflection.everyTurns) return "turns";
2888
- if (!reflection.onSceneChange) return void 0;
2889
- const places = session.locations.list();
2890
- const before = places.find((place) => place.id === anchor.place);
2891
- if (here !== void 0 && before !== void 0 && !sameScene(here, before, places)) return "scene";
2892
- if (reflection.sceneDays > 0 && now - anchor.now >= reflection.sceneDays * DAY_MS) return "scene";
2893
- }
2894
- /**
2895
- * The characters that have enough new to sort, the most first. Only what the story has made final counts, and only up to the first thing
2896
- * still a draft, so that nothing is passed over that is sealed later.
2897
- */
2898
- function materialOf(session, minNew) {
2899
- const cursor = readCursor(session);
2900
- const found = [];
2901
- for (const character of session.characters.list()) {
2902
- if (character.control !== "agent" || character.kind !== "person" || character.tier === "background") continue;
2903
- const taken = session.events.perceivedBy(character.id);
2904
- const draft = taken.filter((entry) => !entry.event.sealed).map((entry) => entry.perception.id);
2905
- const ceiling = draft.length === 0 ? Infinity : Math.min(...draft) - 1;
2906
- const fresh = taken.filter((entry) => entry.event.sealed && entry.perception.id > (cursor[characterKey(character)] ?? 0) && entry.perception.id <= ceiling).sort((a, b) => a.perception.id - b.perception.id).slice(0, MAX_MATERIAL);
2907
- if (fresh.length < minNew) continue;
2908
- const beliefs = session.memories.list(character.id).sort((a, b) => b.importance - a.importance || a.id - b.id).slice(0, MAX_BELIEFS_SHOWN);
2909
- found.push({
2910
- character,
2911
- fresh,
2912
- beliefs
2913
- });
2914
- }
2915
- return found.sort((a, b) => b.fresh.length - a.fresh.length);
2916
- }
2917
- const idList = {
2918
- type: "array",
2919
- items: { type: "integer" }
2920
- };
2921
- const RESULT = {
2922
- type: "object",
2923
- properties: {
2924
- add: {
2925
- type: "array",
2926
- description: "New beliefs, at most four. Leave empty when nothing new can be firmly said.",
2927
- items: {
2928
- type: "object",
2929
- properties: {
2930
- kind: {
2931
- type: "string",
2932
- enum: [...MEMORY_KINDS],
2933
- description: "belief: what it holds true or suspects; relationship: how it stands with someone; knowledge: something it knows."
2934
- },
2935
- text: {
2936
- type: "string",
2937
- description: "What the character believes, in one or two sentences, in its own terms. Say plainly when it is a suspicion, a rumour or a guess."
2938
- },
2939
- about: {
2940
- type: "array",
2941
- items: { type: "string" },
2942
- description: "The names of the characters it is about."
2943
- },
2944
- importance: {
2945
- type: "integer",
2946
- description: `From 1 (passing) to 5 (it shapes how they act).`
2947
- },
2948
- confidence: {
2949
- type: "string",
2950
- enum: [...MEMORY_CONFIDENCES],
2951
- description: "How sure they are: doubtful, likely (when you leave it out) or sure, which needs things from at least two different turns."
2952
- },
2953
- perceptions: {
2954
- ...idList,
2955
- description: "The numbers of the things it took in that this rests on."
2956
- },
2957
- beliefs: {
2958
- ...idList,
2959
- description: "The numbers of the beliefs it generalises or builds on, if any."
2960
- }
2961
- },
2962
- required: [
2963
- "kind",
2964
- "text",
2965
- "importance",
2966
- "perceptions"
2967
- ],
2968
- additionalProperties: false
2969
- }
2970
- },
2971
- revise: {
2972
- type: "array",
2973
- description: "Beliefs to firm up, doubt or correct in the light of what came after them.",
2974
- items: {
2975
- type: "object",
2976
- properties: {
2977
- id: {
2978
- type: "integer",
2979
- description: "The number of the belief, as listed."
2980
- },
2981
- text: {
2982
- type: "string",
2983
- description: "The belief as it should read now."
2984
- },
2985
- importance: {
2986
- type: "integer",
2987
- description: `From 1 to 5.`
2988
- },
2989
- confidence: {
2990
- type: "string",
2991
- enum: [...MEMORY_CONFIDENCES],
2992
- description: "How sure they are now. Raise it only for what supports the belief; lower it only together with contradicted_by."
2993
- },
2994
- perceptions: {
2995
- ...idList,
2996
- description: "The numbers of the things it took in since that support the belief or bear on it."
2997
- },
2998
- contradicted_by: {
2999
- ...idList,
3000
- description: "The numbers of the things it took in since that speak against the belief; the belief is then doubted, and its confidence must be lowered."
3001
- }
3002
- },
3003
- required: ["id"],
3004
- additionalProperties: false
3005
- }
3006
- },
3007
- doubt: {
3008
- type: "array",
3009
- description: "Beliefs that something the character took in since speaks against, which it still holds but with more doubt: name the belief and the numbers of what speaks against it, and its confidence is lowered for you. This is the way to answer a belief that a later event contradicts, instead of revising or dropping it.",
3010
- items: {
3011
- type: "object",
3012
- properties: {
3013
- id: {
3014
- type: "integer",
3015
- description: "The number of the belief, as listed."
3016
- },
3017
- contradicted_by: {
3018
- ...idList,
3019
- description: "The numbers of the things it took in since that speak against the belief."
3020
- },
3021
- text: {
3022
- type: "string",
3023
- description: "The belief reworded to say what is now in doubt, when its words need it; one or two sentences, and nothing but the belief: its confidence and the numbers are not part of the text."
3024
- }
3025
- },
3026
- required: ["id", "contradicted_by"],
3027
- additionalProperties: false
3028
- }
3029
- },
3030
- drop: {
3031
- type: "array",
3032
- description: "Beliefs to let go: settled or overturned by what came after, or merged into another.",
3033
- items: {
3034
- type: "object",
3035
- properties: {
3036
- id: { type: "integer" },
3037
- perceptions: {
3038
- ...idList,
3039
- description: "What it took in since that settles or overturns it."
3040
- },
3041
- merged_into: {
3042
- type: "integer",
3043
- description: "The number of the belief that now says the same, instead of a reason from what it took in."
3044
- }
3045
- },
3046
- required: ["id"],
3047
- additionalProperties: false
3048
- }
3049
- }
3050
- },
3051
- required: [
3052
- "add",
3053
- "revise",
3054
- "drop"
3055
- ],
3056
- additionalProperties: false
3057
- };
3058
- function shownOf(session, material) {
3059
- const turnOf = (perceptionId) => {
3060
- const seen = session.events.getPerception(perceptionId);
3061
- return seen === void 0 ? void 0 : session.events.get(seen.eventId)?.turn;
3062
- };
3063
- return {
3064
- perceptions: new Map(material.fresh.map((entry) => [entry.perception.id, entry])),
3065
- beliefs: new Map(material.beliefs.map((belief) => [belief.id, belief])),
3066
- supportTurns: new Map(material.beliefs.map((belief) => [belief.id, new Set(session.memories.evidenceOf(belief.id).filter((entry) => entry.relation === "supports").flatMap((entry) => turnOf(entry.perceptionId) ?? []))]))
3067
- };
3068
- }
3069
- const rankOf = (confidence) => MEMORY_CONFIDENCES.indexOf(confidence);
3070
- /** What a model writes into a belief's text when it has not put it in the fields: its confidence, importance or the numbers it rests on. */
3071
- const MIXED_IN = /\((?:[^)]*\b(?:doubtful|likely|sure|importance)\b[^)]*|[^)]*\bperceptions?\s*\[?\d[^)]*)\)|\bperceptions?\s*\[\d/i;
3072
- /** One step less sure, and no less than doubtful. */
3073
- const lowered = (confidence) => MEMORY_CONFIDENCES[Math.max(0, rankOf(confidence) - 1)];
3074
- /**
3075
- * Why a proposal cannot be written, or nothing when it can. A belief must rest on what the character took in: on things from at least two
3076
- * different turns, or on one event that turned the story; a belief is changed or let go only for what came after it, or for being merged
3077
- * into another. Nothing is judged about whether the belief is wise; only whether it is grounded in what the character was given.
3078
- */
3079
- function proposalProblems(proposal, shown, resolveName, tr = translator("en")) {
3080
- const problems = [];
3081
- const add = proposal.add ?? [];
3082
- const revise = proposal.revise ?? [];
3083
- const drop = proposal.drop ?? [];
3084
- const doubt = proposal.doubt ?? [];
3085
- if (add.length > MAX_ADDED) problems.push(tr("add: at most {max} new beliefs in one pass; merge or choose", { max: MAX_ADDED }));
3086
- if (add.length + revise.length + drop.length + doubt.length > MAX_CHANGES) problems.push(tr("at most {max} changes in one pass", { max: MAX_CHANGES }));
3087
- const cited = (ids, where) => (ids ?? []).flatMap((id) => {
3088
- const entry = shown.perceptions.get(id);
3089
- if (entry === void 0) problems.push(tr("{where}: there is no thing it took in numbered {id}", {
3090
- where,
3091
- id
3092
- }));
3093
- return entry === void 0 ? [] : [entry];
3094
- });
3095
- const known = (value, where) => {
3096
- const fine = value === void 0 || MEMORY_CONFIDENCES.includes(value);
3097
- if (!fine) problems.push(tr("{where}: confidence is one of {options}", {
3098
- where,
3099
- options: MEMORY_CONFIDENCES.join(", ")
3100
- }));
3101
- return fine;
3102
- };
3103
- add.forEach((belief, index) => {
3104
- const where = `add[${index}]`;
3105
- if (!MEMORY_KINDS.includes(belief.kind)) problems.push(tr("{where}: unknown kind \"{kind}\"", {
3106
- where,
3107
- kind: belief.kind
3108
- }));
3109
- if (belief.text.trim() === "") problems.push(tr("{where}: say what it believes", { where }));
3110
- else if (belief.text.trim().length > MAX_TEXT) problems.push(tr("{where}: at most {max} characters; say it shorter", {
3111
- where,
3112
- max: MAX_TEXT
3113
- }));
3114
- if (!Number.isInteger(belief.importance) || belief.importance < 1 || belief.importance > 5) problems.push(tr("{where}: importance runs from {min} to {max}", {
3115
- where,
3116
- min: 1,
3117
- max: 5
3118
- }));
3119
- const sure = known(belief.confidence, where) && belief.confidence === "sure";
3120
- const events = cited(belief.perceptions, where);
3121
- const built = (belief.beliefs ?? []).flatMap((id) => {
3122
- const found = shown.beliefs.get(id);
3123
- if (found === void 0) problems.push(tr("{where}: there is no belief numbered {id}", {
3124
- where,
3125
- id
3126
- }));
3127
- return found === void 0 ? [] : [found];
3128
- });
3129
- const turns = /* @__PURE__ */ new Set([...events.map((entry) => entry.event.turn), ...built.map((found) => found.turn)]);
3130
- if (turns.size < 2 && !events.some((entry) => entry.event.importance >= DECISIVE_IMPORTANCE)) problems.push(tr("{where}: one passing moment is not yet a belief; rest it on things from at least two different turns, or on one event that turned the story", { where }));
3131
- if (sure && turns.size < 2) problems.push(tr("{where}: to be sure of something it must rest on things from at least two different turns", { where }));
3132
- for (const name of belief.about ?? []) if (resolveName(name) === void 0) problems.push(tr("{where}: \"{name}\" is not a character; name them as they are named", {
3133
- where,
3134
- name
3135
- }));
3136
- });
3137
- const touched = /* @__PURE__ */ new Set();
3138
- const touch = (id, where) => {
3139
- if (touched.has(id)) problems.push(tr("{where}: belief {id} is already changed in this pass", {
3140
- where,
3141
- id
3142
- }));
3143
- touched.add(id);
3144
- };
3145
- const fresh = (events, belief, where) => {
3146
- if (events.length === 0) problems.push(tr("{where}: say what it took in since that bears on it", { where }));
3147
- for (const entry of events) if (entry.event.turn < belief.turn) problems.push(tr("{where}: thing {id} came before the belief was formed; cite what came after", {
3148
- where,
3149
- id: entry.perception.id
3150
- }));
3151
- };
3152
- revise.forEach((change, index) => {
3153
- const where = `revise[${index}]`;
3154
- const belief = shown.beliefs.get(change.id);
3155
- if (belief === void 0) {
3156
- problems.push(tr("{where}: there is no belief numbered {id}", {
3157
- where,
3158
- id: change.id
3159
- }));
3160
- return;
3161
- }
3162
- touch(change.id, where);
3163
- const supports = cited(change.perceptions, where);
3164
- const against = cited(change.contradicted_by, where);
3165
- if (change.text === void 0 && change.importance === void 0 && change.confidence === void 0 && against.length === 0) problems.push(tr("{where}: say what changes", { where }));
3166
- if (change.text !== void 0 && (change.text.trim() === "" || change.text.trim().length > MAX_TEXT)) problems.push(tr("{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is", {
3167
- where,
3168
- max: MAX_TEXT
3169
- }));
3170
- if (change.text !== void 0 && MIXED_IN.test(change.text)) problems.push(tr("{where}: the confidence, the importance and the numbers are fields of their own, not part of the text", { where }));
3171
- if (change.importance !== void 0 && (!Number.isInteger(change.importance) || change.importance < 1 || change.importance > 5)) problems.push(tr("{where}: importance runs from {min} to {max}", {
3172
- where,
3173
- min: 1,
3174
- max: 5
3175
- }));
3176
- fresh([...supports, ...against], belief, where);
3177
- if (!known(change.confidence, where) || change.confidence === void 0) {
3178
- if (against.length > 0) problems.push(tr("{where}: a belief that something contradicts must be doubted: lower its confidence", { where }));
3179
- return;
3180
- }
3181
- if (against.length > 0 && rankOf(change.confidence) >= rankOf(belief.confidence)) problems.push(tr("{where}: a belief that something contradicts must be doubted: lower its confidence", { where }));
3182
- if (against.length === 0 && rankOf(change.confidence) < rankOf(belief.confidence)) problems.push(tr("{where}: to doubt a belief, name what contradicts it in contradicted_by", { where }));
3183
- if (change.confidence === "sure" && belief.confidence !== "sure") {
3184
- if ((/* @__PURE__ */ new Set([...shown.supportTurns?.get(belief.id) ?? [], ...supports.map((entry) => entry.event.turn)])).size < 2) problems.push(tr("{where}: to be sure of something it must rest on things from at least two different turns", { where }));
3185
- }
3186
- });
3187
- doubt.forEach((change, index) => {
3188
- const where = `doubt[${index}]`;
3189
- const belief = shown.beliefs.get(change.id);
3190
- if (belief === void 0) {
3191
- problems.push(tr("{where}: there is no belief numbered {id}", {
3192
- where,
3193
- id: change.id
3194
- }));
3195
- return;
3196
- }
3197
- touch(change.id, where);
3198
- const against = cited(change.contradicted_by, where);
3199
- if (against.length === 0) problems.push(tr("{where}: name what speaks against the belief in contradicted_by", { where }));
3200
- fresh(against, belief, where);
3201
- if (change.text !== void 0 && (change.text.trim() === "" || change.text.trim().length > MAX_TEXT)) problems.push(tr("{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is", {
3202
- where,
3203
- max: MAX_TEXT
3204
- }));
3205
- if (change.text !== void 0 && MIXED_IN.test(change.text)) problems.push(tr("{where}: the confidence, the importance and the numbers are fields of their own, not part of the text", { where }));
3206
- });
3207
- const dropped = new Set(drop.map((entry) => entry.id));
3208
- drop.forEach((change, index) => {
3209
- const where = `drop[${index}]`;
3210
- const belief = shown.beliefs.get(change.id);
3211
- if (belief === void 0) {
3212
- problems.push(tr("{where}: there is no belief numbered {id}", {
3213
- where,
3214
- id: change.id
3215
- }));
3216
- return;
3217
- }
3218
- touch(change.id, where);
3219
- if (change.merged_into !== void 0) {
3220
- if (change.merged_into === change.id || !shown.beliefs.has(change.merged_into) || dropped.has(change.merged_into)) problems.push(tr("{where}: merge into a belief that stays", { where }));
3221
- return;
3222
- }
3223
- fresh(cited(change.perceptions, where), belief, where);
3224
- });
3225
- return problems;
3226
- }
3227
- const keysOf = (names, resolveName) => (names ?? []).flatMap((name) => {
3228
- const key = resolveName(name);
3229
- return key === void 0 ? [] : [key];
3230
- });
3231
- /** The edit that writes a proposal that passed. */
3232
- function editOf(turn, character, proposal, resolveName, confidenceOf = () => void 0) {
3233
- const who = characterKey(character);
3234
- return {
3235
- turn,
3236
- beliefs: (proposal.add ?? []).map((belief) => ({
3237
- character: who,
3238
- kind: belief.kind,
3239
- text: belief.text.trim(),
3240
- about: keysOf(belief.about, resolveName),
3241
- importance: belief.importance,
3242
- ...belief.confidence === void 0 ? {} : { confidence: belief.confidence },
3243
- evidenceFor: belief.perceptions ?? []
3244
- })),
3245
- beliefEdits: [...proposal.revise ?? [], ...(proposal.doubt ?? []).map((change) => ({
3246
- id: change.id,
3247
- ...change.text === void 0 ? {} : { text: change.text },
3248
- confidence: lowered(confidenceOf(change.id) ?? "likely"),
3249
- contradicted_by: change.contradicted_by
3250
- }))].map((change) => ({
3251
- id: change.id,
3252
- ...change.text === void 0 ? {} : { text: change.text.trim() },
3253
- ..."importance" in change && change.importance !== void 0 ? { importance: change.importance } : {},
3254
- ...change.confidence === void 0 ? {} : { confidence: change.confidence },
3255
- evidenceFor: "perceptions" in change ? change.perceptions ?? [] : [],
3256
- evidenceAgainst: change.contradicted_by ?? []
3257
- })),
3258
- beliefRetractions: (proposal.drop ?? []).map((change) => change.id)
3259
- };
3260
- }
3261
- function brief(session, material, now, zone, time, tr) {
3262
- const { character, fresh, beliefs } = material;
3263
- const named = (id) => session.characters.get(id)?.name ?? String(id);
3264
- const { disputed } = session.memories.evidenceIndex(character.id);
3265
- const believed = beliefs.map((belief) => {
3266
- const about = belief.about.length === 0 ? "" : tr(", about {names}", { names: belief.about.map(named).join(tr(" and ")) });
3267
- const dispute = disputed.has(belief.id) ? tr(", something taken in since speaks against it") : "";
3268
- return `- b${belief.id} (${tr("{kind}, importance {importance}, {confidence}{about}{dispute}", {
3269
- kind: belief.kind,
3270
- importance: belief.importance,
3271
- confidence: tr(belief.confidence),
3272
- about,
3273
- dispute
3274
- })}): ${belief.text}`;
3275
- });
3276
- const taken = fresh.map((entry) => {
3277
- const at = time(entry.event.turn, entry.event.round);
3278
- return `- p${entry.perception.id}${at === void 0 ? "" : ` (${describeWhen(at, now, zone)})`}: ${entry.perception.content}`;
3279
- });
3280
- return [
3281
- tr("Character: {name}{summary}", {
3282
- name: referent(character),
3283
- summary: character.summary === "" ? "" : ` - ${character.summary}`
3284
- }),
3285
- tr("What they believe now:"),
3286
- ...believed.length === 0 ? [tr("(nothing yet)")] : believed,
3287
- tr("What they have taken in since:"),
3288
- ...taken,
3289
- tr("Sort their memory.")
3290
- ].join("\n");
3291
- }
3292
- /**
3293
- * Has the characters with the most new to sort sort it into what they believe, one request each, one after another. Each answer is checked
3294
- * against what the character was shown before it is written, and the writing of one character is all or nothing; a failure stops the pass
3295
- * and leaves the characters not yet done as they were.
3296
- */
3297
- function memoryReflector(deps) {
3298
- return { async reflect(job, signal) {
3299
- const parent = deps.agentOf(job.chat);
3300
- if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
3301
- const { store } = job;
3302
- const session = store.story;
3303
- const settings = store.settings();
3304
- const { now, zone } = store.time(job.turn);
3305
- const due = materialOf(session, job.reason === "manual" ? 1 : settings.reflection.minNew);
3306
- const taken = job.reason === "manual" ? due : due.slice(0, settings.reflection.perRun);
3307
- const resolveName = (name) => {
3308
- const found = session.characters.findByName(name.trim());
3309
- return found.length === 1 ? characterKey(found[0]) : void 0;
3310
- };
3311
- const tr = translator(languageOf(settings.prompts.language));
3312
- const characters = [];
3313
- for (const material of taken) {
3314
- const shown = shownOf(session, material);
3315
- const proposal = await runChild({
3316
- parent,
3317
- signal,
3318
- reasoningEffort: settings.reasoning.children,
3319
- sampling: childSampling(settings, "records"),
3320
- ...childModel(settings, "records"),
3321
- trace: childTrace(store, "records", `reflection ${material.character.name}`),
3322
- persona: promptFor(parent, "roleplay/reflection", settings.prompts.language),
3323
- prompt: brief(session, material, now, zone, (turn, round) => session.clock.at(turn, round), tr),
3324
- result: RESULT,
3325
- beforeSubmit: (value) => {
3326
- const given = value;
3327
- const problems = [...proposalProblems(given, shown, resolveName, tr), ...[wrongLanguage(settings.prompts.language, { beliefs: [
3328
- ...given.add ?? [],
3329
- ...given.revise ?? [],
3330
- ...given.doubt ?? []
3331
- ].map((belief) => belief.text ?? "").join(" ") })].flatMap((problem) => problem === void 0 ? [] : [problem])];
3332
- return problems.length === 0 ? void 0 : tr("not acceptable: {problems}", { problems: problems.join("; ") });
3333
- },
3334
- maxCalls: 3
3335
- });
3336
- const reached = Math.max(...material.fresh.map((entry) => entry.perception.id));
3337
- session.transaction(() => {
3338
- session.edit(editOf(job.turn, material.character, proposal, resolveName, (belief) => shown.beliefs.get(belief)?.confidence));
3339
- session.metadata.setValue(CURSOR_KEY, {
3340
- ...readCursor(session),
3341
- [characterKey(material.character)]: reached
3342
- });
3343
- });
3344
- characters.push({
3345
- name: material.character.name,
3346
- added: proposal.add?.length ?? 0,
3347
- revised: (proposal.revise?.length ?? 0) + (proposal.doubt?.length ?? 0),
3348
- dropped: proposal.drop?.length ?? 0
3349
- });
3350
- }
3351
- session.metadata.setValue(LAST_KEY, {
3352
- turn: job.turn,
3353
- at: (/* @__PURE__ */ new Date()).toISOString(),
3354
- reason: job.reason,
3355
- characters
3356
- });
3357
- writeAnchor(session, playerPlace(store), now);
3358
- session.metadata.deleteValue(ERROR_KEY);
3359
- return { characters };
3360
- } };
3361
- }
3362
- //#endregion
3363
1849
  //#region src/host/sessions/activity.ts
3364
- const KEY$1 = "activity";
1850
+ const KEY$2 = "activity";
3365
1851
  const isEntry = (value) => {
3366
1852
  if (typeof value !== "object" || value === null) return false;
3367
1853
  const entry = value;
@@ -3369,13 +1855,13 @@ const isEntry = (value) => {
3369
1855
  };
3370
1856
  /** The recorded runs, oldest first. */
3371
1857
  function readActivity(session) {
3372
- const stored = session.metadata.getValue(KEY$1);
1858
+ const stored = session.metadata.getValue(KEY$2);
3373
1859
  return Array.isArray(stored) ? stored.filter(isEntry) : [];
3374
1860
  }
3375
1861
  /** Files the run and returns the runs that fell off the end of the record to make room. */
3376
1862
  function recordActivity(session, entry) {
3377
1863
  const all = [...readActivity(session), entry];
3378
- session.metadata.setValue(KEY$1, all.slice(-60));
1864
+ session.metadata.setValue(KEY$2, all.slice(-60));
3379
1865
  return all.slice(0, -60);
3380
1866
  }
3381
1867
  const RUN_FOLDER = "activity";
@@ -3404,6 +1890,43 @@ function forgetRunDetails(folder, dropped) {
3404
1890
  for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
3405
1891
  }
3406
1892
  //#endregion
1893
+ //#region src/host/sessions/usage.ts
1894
+ const KEY$1 = "usage";
1895
+ const isCount = (value) => typeof value === "object" && value !== null && [
1896
+ "input",
1897
+ "cached",
1898
+ "output"
1899
+ ].every((field) => typeof value[field] === "number");
1900
+ const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
1901
+ /** What each turn used, oldest first. The record belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1902
+ function readUsage(session) {
1903
+ const stored = session.metadata.getValue(KEY$1);
1904
+ return Array.isArray(stored) ? stored.filter(isUsage) : [];
1905
+ }
1906
+ /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
1907
+ function addUsage(session, turn, who, tokens) {
1908
+ const all = readUsage(session);
1909
+ const at = all.findIndex((entry) => entry.turn === turn);
1910
+ const entry = at === -1 ? {
1911
+ turn,
1912
+ master: NO_TOKENS,
1913
+ helpers: NO_TOKENS,
1914
+ runs: 0
1915
+ } : all[at];
1916
+ const next = who === "master" ? {
1917
+ ...entry,
1918
+ master: addTokens(entry.master, tokens)
1919
+ } : {
1920
+ ...entry,
1921
+ helpers: addTokens(entry.helpers, tokens),
1922
+ runs: entry.runs + 1
1923
+ };
1924
+ if (at === -1) all.push(next);
1925
+ else all[at] = next;
1926
+ all.sort((a, b) => a.turn - b.turn);
1927
+ session.metadata.setValue(KEY$1, all);
1928
+ }
1929
+ //#endregion
3407
1930
  //#region src/host/triggers/deliver.ts
3408
1931
  const KEY = "triggers.withdrawn";
3409
1932
  /** Why a note was withdrawn instead of told, by the number of the note. */
@@ -3438,6 +1961,6 @@ function deliverNow(session, notes, clock) {
3438
1961
  }));
3439
1962
  }
3440
1963
  //#endregion
3441
- export { notesOfSession as A, sameWords as B, plotProgressOf as C, parseOoc as D, MAX_OOC_ANSWER as E, TimelineError as F, readTime as G, beginTurn as H, Timelines as I, referent as J, skipTime as K, readTimeline as L, readNotes as M, observeAsPlayer as N, addToNote as O, observeSurroundings as P, pathTo as R, plotAuthorNeeded as S, AUTHORING_NEEDS as T, describeWhen as U, ClockError as V, endRound as W, languageOf as X, RESULTS as Y, translator as Z, PREVIEW_TOOL as _, readActivity as a, describePacingAdvice as b, dueReflection as c, reflectionStatus as d, whereabouts as f, toolEnabled as g, externalWithheld as h, keepRunDetail as i, putNote as j, clearNotes as k, memoryReflector as l, externalTools as m, readWithdrawn as n, readRunDetail as o, externalGiven as p, zoneOf as q, forgetRunDetails as r, recordActivity as s, deliverNow as t, recordFailure as u, createTools$1 as v, populatePlots as w, pacingAdvice as x, PLOTS_METADATA_KEY as y, defaultBoundaries as z };
1964
+ export { observeAsPlayer as A, RESULTS as B, parseOoc as C, notesOfSession as D, clearNotes as E, describeWhen as F, languageOf as H, endRound as I, readTime as L, ClockError as M, beginTurn as N, putNote as O, describeTime as P, skipTime as R, MAX_OOC_ANSWER as S, addToNote as T, translator as U, answerLimits as V, pacingAdvice as _, forgetRunDetails as a, populatePlots as b, readRunDetail as c, externalTools as d, externalWithheld as f, describePacingAdvice as g, PLOTS_METADATA_KEY as h, readUsage as i, observeSurroundings as j, readNotes as k, recordActivity as l, createTools$1 as m, readWithdrawn as n, keepRunDetail as o, PREVIEW_TOOL as p, addUsage as r, readActivity as s, deliverNow as t, externalGiven as u, plotAuthorNeeded as v, toolEnabled as w, AUTHORING_NEEDS as x, plotProgressOf as y, zoneOf as z };
3442
1965
 
3443
- //# sourceMappingURL=deliver-BSsDtF6X.js.map
1966
+ //# sourceMappingURL=deliver-CpZOxBX5.js.map