@dsh-agentic-roleplay/core 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/lib/{access-Md1YTSX1.js → access-DAw54-NI.js} +3 -15
  2. package/lib/{authoring-tools-BFdw7ahj.js → authoring-tools-4NgDhIJV.js} +51 -11
  3. package/lib/authoring.js +8 -8
  4. package/lib/{child-C9nPIy9j.js → child-D3QUNb3m.js} +121 -2
  5. package/lib/client.js +1013 -449
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-BWHmjogd.js → gallery-Ct6nm4UQ.js} +3 -3
  10. package/lib/{generator-QCdm8nUh.js → generator-CI8fOnXy.js} +2 -2
  11. package/lib/helper.js +13 -1
  12. package/lib/{hooks-C2U1-8ur.js → hooks-BNeoGMHZ.js} +722 -334
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +234 -20
  15. package/lib/jail-BIF79PJO.js +107 -0
  16. package/lib/{library-4zmCAshR.js → library-BF9ZMSFz.js} +3 -3
  17. package/lib/{lorebook-author-tools-Bjfjt3bg.js → lorebook-author-tools-DBk-V0hp.js} +7 -7
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-b_VBEUWn.js → narration-xvErE2yp.js} +29 -2
  20. package/lib/orchestration.js +593 -47
  21. package/lib/{pack-jail-Ci9bIeDI.js → pack-jail-C8EyX9Ix.js} +12 -11
  22. package/lib/{packs-CYkozh8Q.js → packs-S0SzrVv-.js} +2 -2
  23. package/lib/{presenter-agent-CqkAL03Q.js → presenter-agent-Bc478nTA.js} +6 -6
  24. package/lib/{preset-B-35yUmt.js → preset-SJZyw0kt.js} +4 -4
  25. package/lib/{preset-author-tools-BUymqZM5.js → preset-author-tools-CzogjK42.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-_U-xroo0.js → presets-DQ5rioMh.js} +231 -48
  28. package/lib/{reflection-B9N0z3KY.js → reflection-buQiSdvq.js} +15 -8
  29. package/lib/service-mRKwpWjX.js +140 -0
  30. package/lib/{text-C2AGl7Je.js → text-Dfv8S8eq.js} +27 -2
  31. package/lib/{turn-guard-C0M3rXEN.js → turn-guard-BSAba8sp.js} +3 -3
  32. package/package.json +3 -3
  33. package/prompts/en/import/finish-ok.md +1 -1
  34. package/prompts/en/import/generator.md +1 -1
  35. package/prompts/en/import/style.md +1 -1
  36. package/prompts/en/import/variables.md +2 -1
  37. package/prompts/en/roleplay/character-lookup.md +1 -1
  38. package/prompts/en/roleplay/decide-errand.md +1 -0
  39. package/prompts/en/roleplay/decide-message.md +1 -0
  40. package/prompts/en/roleplay/dream.md +1 -0
  41. package/prompts/en/roleplay/gate-repeat.md +1 -0
  42. package/prompts/zh/import/finish-ok.md +1 -1
  43. package/prompts/zh/import/generator.md +1 -1
  44. package/prompts/zh/import/style.md +1 -1
  45. package/prompts/zh/import/variables.md +2 -1
  46. package/prompts/zh/roleplay/character-lookup.md +1 -1
  47. package/prompts/zh/roleplay/decide-errand.md +1 -0
  48. package/prompts/zh/roleplay/decide-message.md +1 -0
  49. package/prompts/zh/roleplay/dream.md +1 -0
  50. package/prompts/zh/roleplay/gate-repeat.md +1 -0
@@ -1,7 +1,8 @@
1
- import { l as roleplaySessionOf, t as promptFor } from "./access-Md1YTSX1.js";
2
- import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-b_VBEUWn.js";
3
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-C2AGl7Je.js";
4
- import { C as cutOff, T as estimateAnswer, _ as estimateTokens, a as childTrace, b as addTokens, g as blockText, h as requestsOf, l as runChild, n as childModel, r as childSampling, v as tokensOf, w as finishOf, y as NO_TOKENS } from "./child-C9nPIy9j.js";
1
+ import { C as addTokens, D as finishOf, E as cutOff, O as estimateAnswer, S as NO_TOKENS, a as childTrace, b as estimateTokens, f as tracerOf, j as roleplaySessionOf, l as runChild, n as childModel, r as childSampling, u as TurnTraces, v as requestsOf, x as tokensOf, y as blockText } from "./child-D3QUNb3m.js";
2
+ import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-xvErE2yp.js";
3
+ import { t as promptFor } from "./access-DAw54-NI.js";
4
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-Dfv8S8eq.js";
5
+ import { n as storyRoots } from "./service-mRKwpWjX.js";
5
6
  import { dirname, join } from "node:path";
6
7
  import { DAY, ENGAGEMENT_GRACE, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, describeValue, holidaysOn, inAudience, isSessionId, itemKey, localTime, locationKey, mentioned, nextOccurrence, nextTimeOfDay, occurrenceAt, overlap, parseInstant, planItemChange, planVariableChange, readCalendar, rollPlain, seasonOf, sessionDatabase, sessionFolder, shownVariables, tokens } from "@dsh-agentic-roleplay/state";
7
8
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -707,7 +708,7 @@ function plotReferenceProblems(plots, entities) {
707
708
  return plots.flatMap((plot) => plot.participants.filter((participant) => !known.has(participant)).map((participant) => `plot "${plot.id}" names unknown participant "${participant}"`));
708
709
  }
709
710
  // src/host/sessions/usage.ts
710
- const KEY$5 = "usage";
711
+ const KEY$6 = "usage";
711
712
  const isCount = (value) => typeof value === "object" && value !== null && [
712
713
  "input",
713
714
  "cached",
@@ -716,7 +717,7 @@ const isCount = (value) => typeof value === "object" && value !== null && [
716
717
  const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
717
718
  /** 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. */
718
719
  function readUsage(session) {
719
- const stored = session.metadata.getValue(KEY$5);
720
+ const stored = session.metadata.getValue(KEY$6);
720
721
  return Array.isArray(stored) ? stored.filter(isUsage) : [];
721
722
  }
722
723
  /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
@@ -741,7 +742,7 @@ function addUsage(session, turn, who, tokens, masterMs) {
741
742
  if (at === -1) all.push(next);
742
743
  else all[at] = next;
743
744
  all.sort((a, b) => a.turn - b.turn);
744
- session.metadata.setValue(KEY$5, all);
745
+ session.metadata.setValue(KEY$6, all);
745
746
  }
746
747
  // src/host/translate/language.ts
747
748
  const STORY_LANGUAGES = ["en", "zh"];
@@ -1122,6 +1123,7 @@ function describeAgenda(agenda, now, tr = ENGLISH, language = "en") {
1122
1123
  until: when(agenda.now.until),
1123
1124
  note: agenda.now.interruptible ? "" : tr(" (not something you would drop lightly)")
1124
1125
  }));
1126
+ if (agenda.now === void 0 && agenda.offDay !== void 0) lines.push(tr("What is happening to you has taken you from your day for now; you take it up again {until}.", { until: when(agenda.offDay.until) }));
1125
1127
  if (agenda.next !== void 0) lines.push(tr("Your day, next: {activity}{place}, from {from}.", {
1126
1128
  activity: agenda.next.activity,
1127
1129
  place: at(agenda.next.place),
@@ -1155,6 +1157,10 @@ function describeSceneAgenda(agenda, now, tr = ENGLISH, language = "en") {
1155
1157
  activity: move.activity
1156
1158
  }))) }));
1157
1159
  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}`)) }));
1160
+ if (agenda.asleep.length > 0) lines.push(tr("Asleep now: {names}. An asleep character takes part only if what the player does wakes them: name them in wakes when you ask them, and show them waking.", { names: join(agenda.asleep.map((entry) => tr("{name} (until {until})", {
1161
+ name: `${entry.name} [${entry.key}]`,
1162
+ until: describeWhen(entry.until, now, agenda.zone, language)
1163
+ }))) }));
1158
1164
  if (agenda.engagements.length > 0) {
1159
1165
  const entries = agenda.engagements.map((engagement) => {
1160
1166
  const values = {
@@ -1282,6 +1288,7 @@ const sharedContext = { brief(request) {
1282
1288
  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")}`);
1283
1289
  const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now, tr, language);
1284
1290
  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")}`);
1291
+ if (request.dreaming === true) sections.push(tr("You are asleep and dreaming, and the player's character is in your dream. What you intend and say is the dream's: it may shift, blur and be odd, and it is not something you do awake. Answer from what the dream would make of the moment, out of your own fears, wants and what you have not said."));
1285
1292
  if (carrying !== void 0 && carrying.length > 0) sections.push(`${tr("What you have on you:")}\n${describeItems(carrying, { withKeys: false }, tr)}`);
1286
1293
  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) => {
1287
1294
  const attitude = describeAttitude(relation, tr);
@@ -1597,6 +1604,7 @@ const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
1597
1604
  const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
1598
1605
  /** Finds no fault: without a gate the output is delivered as the game master wrote it. */
1599
1606
  const tracksNothing = { track: () => Promise.resolve(0) };
1607
+ const keepsNoErrands = { keep: () => Promise.resolve(0) };
1600
1608
  const passesEverything = { check: () => Promise.resolve([]) };
1601
1609
  /** Finds no broken rule: without a check the game master's judgement of an action stands as it is. */
1602
1610
  const breaksNoRule = { check: () => Promise.resolve([]) };
@@ -1621,6 +1629,7 @@ function defaultBoundaries() {
1621
1629
  outputGate: passesEverything,
1622
1630
  ruleCheck: breaksNoRule,
1623
1631
  variableTracker: tracksNothing,
1632
+ errandKeeper: keepsNoErrands,
1624
1633
  suggester: offersNothing,
1625
1634
  recaller: recordsRecall,
1626
1635
  sceneContext: castSummary
@@ -1659,10 +1668,11 @@ function observeAsPlayer(session, turn) {
1659
1668
  const NOTE_KINDS = [
1660
1669
  "suggestions",
1661
1670
  "away",
1662
- "world"
1671
+ "world",
1672
+ "message"
1663
1673
  ];
1664
1674
  // src/host/sessions/notes.ts
1665
- const KEY$4 = "notes";
1675
+ const KEY$5 = "notes";
1666
1676
  const isNote = (value) => {
1667
1677
  if (typeof value !== "object" || value === null) return false;
1668
1678
  const note = value;
@@ -1670,12 +1680,12 @@ const isNote = (value) => {
1670
1680
  };
1671
1681
  /** The notes of a session, at most one per kind. */
1672
1682
  function readNotes(session) {
1673
- const stored = session.metadata.getValue(KEY$4);
1683
+ const stored = session.metadata.getValue(KEY$5);
1674
1684
  return Array.isArray(stored) ? stored.filter(isNote) : [];
1675
1685
  }
1676
1686
  /** Replaces the note of the same kind. */
1677
1687
  function putNote(session, note) {
1678
- session.metadata.setValue(KEY$4, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1688
+ session.metadata.setValue(KEY$5, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1679
1689
  }
1680
1690
  /** The most lines one note keeps: what is past it is not told. */
1681
1691
  const MAX_NOTE_LINES = 8;
@@ -1690,7 +1700,7 @@ function addToNote(session, kind, turn, lines) {
1690
1700
  }
1691
1701
  /** Removes every note: they belong to the turn that made them. */
1692
1702
  function clearNotes(session) {
1693
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$4, []);
1703
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$5, []);
1694
1704
  }
1695
1705
  /**
1696
1706
  * The notes of a session, for the player's screen.
@@ -1751,10 +1761,10 @@ function masterTrace(events) {
1751
1761
  };
1752
1762
  }
1753
1763
  // src/host/triggers/deliver.ts
1754
- const KEY$3 = "triggers.withdrawn";
1764
+ const KEY$4 = "triggers.withdrawn";
1755
1765
  /** Why a note was withdrawn instead of told, by the number of the note. */
1756
1766
  function readWithdrawn(session) {
1757
- const stored = session.metadata.getValue(KEY$3);
1767
+ const stored = session.metadata.getValue(KEY$4);
1758
1768
  if (!Array.isArray(stored)) return {};
1759
1769
  return Object.fromEntries(stored.flatMap((entry) => {
1760
1770
  const { note, reason } = entry ?? {};
@@ -1773,7 +1783,7 @@ function deliverNow(session, notes, clock) {
1773
1783
  note: Number(note),
1774
1784
  reason
1775
1785
  }));
1776
- session.metadata.setValue(KEY$3, [...before, ...withdrawn.map(({ note, reason }) => ({
1786
+ session.metadata.setValue(KEY$4, [...before, ...withdrawn.map(({ note, reason }) => ({
1777
1787
  note: note.id,
1778
1788
  reason
1779
1789
  }))].slice(-100));
@@ -1784,9 +1794,9 @@ function deliverNow(session, notes, clock) {
1784
1794
  }));
1785
1795
  }
1786
1796
  // src/host/triggers/judged.ts
1787
- const KEY$2 = "triggers.judged";
1797
+ const KEY$3 = "triggers.judged";
1788
1798
  function readVerdicts(session) {
1789
- const stored = session.metadata.getValue(KEY$2);
1799
+ const stored = session.metadata.getValue(KEY$3);
1790
1800
  if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
1791
1801
  const verdicts = {};
1792
1802
  for (const [statement, value] of Object.entries(stored)) {
@@ -1800,7 +1810,7 @@ function readVerdicts(session) {
1800
1810
  }
1801
1811
  /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
1802
1812
  function writeVerdicts(session, verdicts, keep) {
1803
- session.metadata.setValue(KEY$2, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1813
+ session.metadata.setValue(KEY$3, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1804
1814
  }
1805
1815
  /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
1806
1816
  const verdictReader = (session) => {
@@ -1934,11 +1944,11 @@ function noteStore(session, settings, clock) {
1934
1944
  };
1935
1945
  }
1936
1946
  // src/host/sessions/trace.ts
1937
- const KEY$1 = "trace";
1947
+ const KEY$2 = "trace";
1938
1948
  const isTrace = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.startedAt === "number";
1939
1949
  /** What the story kept of each turn's work, oldest first. It belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1940
1950
  function readTraces(session) {
1941
- const stored = session.metadata.getValue(KEY$1);
1951
+ const stored = session.metadata.getValue(KEY$2);
1942
1952
  return Array.isArray(stored) ? stored.filter(isTrace) : [];
1943
1953
  }
1944
1954
  /** Adds to a turn's trace what one source of it knows; the sources (the characters' briefs, the scene, the log at the end of the turn) arrive at different times. */
@@ -1957,10 +1967,10 @@ function updateTrace(session, turn, patch, merge) {
1957
1967
  if (at === -1) all.push(next);
1958
1968
  else all[at] = next;
1959
1969
  all.sort((a, b) => a.turn - b.turn);
1960
- session.metadata.setValue(KEY$1, all.slice(-30));
1970
+ session.metadata.setValue(KEY$2, all.slice(-30));
1961
1971
  }
1962
1972
  // src/host/sessions/activity.ts
1963
- const KEY = "activity";
1973
+ const KEY$1 = "activity";
1964
1974
  const isEntry = (value) => {
1965
1975
  if (typeof value !== "object" || value === null) return false;
1966
1976
  const entry = value;
@@ -1968,13 +1978,13 @@ const isEntry = (value) => {
1968
1978
  };
1969
1979
  /** The recorded runs, oldest first. */
1970
1980
  function readActivity(session) {
1971
- const stored = session.metadata.getValue(KEY);
1981
+ const stored = session.metadata.getValue(KEY$1);
1972
1982
  return Array.isArray(stored) ? stored.filter(isEntry) : [];
1973
1983
  }
1974
1984
  /** Files the run and returns the runs that fell off the end of the record to make room. */
1975
1985
  function recordActivity(session, entry) {
1976
1986
  const all = [...readActivity(session), entry];
1977
- session.metadata.setValue(KEY, all.slice(-60));
1987
+ session.metadata.setValue(KEY$1, all.slice(-60));
1978
1988
  return all.slice(0, -60);
1979
1989
  }
1980
1990
  const RUN_FOLDER = "activity";
@@ -2056,11 +2066,76 @@ function recordDecisions(folder, site, report, now = () => /* @__PURE__ */ new D
2056
2066
  writeFileSync(aside, JSON.stringify(stats, null, 2));
2057
2067
  renameSync(aside, target);
2058
2068
  }
2069
+ // src/host/sessions/autonomy.ts
2070
+ const KEY = "autonomy";
2071
+ const isMessage = (value) => {
2072
+ const entry = value;
2073
+ return typeof entry === "object" && entry !== null && typeof entry["at"] === "number" && typeof entry["character"] === "string" && typeof entry["name"] === "string" && typeof entry["text"] === "string";
2074
+ };
2075
+ function readAutonomy(session) {
2076
+ const stored = session.metadata.getValue(KEY);
2077
+ const sent = typeof stored?.sent === "object" && stored.sent !== null && !Array.isArray(stored.sent) ? Object.fromEntries(Object.entries(stored.sent).filter(([, value]) => typeof value === "number")) : {};
2078
+ return {
2079
+ unanswered: typeof stored?.unanswered === "number" ? stored.unanswered : 0,
2080
+ sent,
2081
+ inbox: Array.isArray(stored?.inbox) ? stored.inbox.filter(isMessage) : []
2082
+ };
2083
+ }
2084
+ /** A character wrote to the player: it counts as one more thing done without a reply, and waits to be told to the story. */
2085
+ function recordMessage(session, message) {
2086
+ const state = readAutonomy(session);
2087
+ const next = {
2088
+ unanswered: state.unanswered + 1,
2089
+ sent: {
2090
+ ...state.sent,
2091
+ [message.character]: message.at
2092
+ },
2093
+ inbox: [...state.inbox, message].slice(-20)
2094
+ };
2095
+ session.metadata.setValue(KEY, next);
2096
+ return next;
2097
+ }
2098
+ /** A character was asked whether it wants to write and did not: it is not asked again until the gap has passed. */
2099
+ function recordAsk(session, character, at) {
2100
+ const state = readAutonomy(session);
2101
+ session.metadata.setValue(KEY, {
2102
+ ...state,
2103
+ sent: {
2104
+ ...state.sent,
2105
+ [character]: at
2106
+ }
2107
+ });
2108
+ }
2109
+ /** The player wrote: what the story was not told of yet, and the count of things done without a reply starts again. */
2110
+ function takeInbox(session) {
2111
+ const state = readAutonomy(session);
2112
+ if (state.inbox.length === 0 && state.unanswered === 0) return [];
2113
+ session.metadata.setValue(KEY, {
2114
+ ...state,
2115
+ unanswered: 0,
2116
+ inbox: []
2117
+ });
2118
+ return state.inbox;
2119
+ }
2120
+ /** When the player last played: the last turn, or the start of a story not yet played. */
2121
+ function lastPlayerAt(session) {
2122
+ const { lastPlayedAt, createdAt } = session.metadata.get();
2123
+ const at = Date.parse(lastPlayedAt ?? createdAt);
2124
+ return Number.isNaN(at) ? void 0 : at;
2125
+ }
2059
2126
  // src/host/clock/agenda.ts
2060
2127
  const CURSOR = "agenda.cursor";
2061
2128
  const ASKED = "agenda.asked";
2062
2129
  /** Characters on their way to the place their day has them at, by character id: they get there when the way has taken as long as it takes. */
2063
2130
  const TRAVEL = "agenda.travel";
2131
+ /** The characters whose day changed since the autonomy last looked, by key: what makes a character likelier to write to the player (work is over, it woke up). */
2132
+ const SHIFTED = "agenda.shifted";
2133
+ /** Characters whose day has given way to what the story made of them, by character id: the routine does not pull them until `until`, when they rejoin it. */
2134
+ const HOLDS = "agenda.holds";
2135
+ /** The longest a character stays where the story left it waiting for the player. */
2136
+ const PLAYER_HOLD_CAP = 1440 * MINUTE;
2137
+ /** How long a character that no window bounds is held when nothing says. */
2138
+ const DEFAULT_HOLD = 60 * MINUTE;
2064
2139
  /** At most this many characters are asked to be given a day at a time, so that it never floods the world author. */
2065
2140
  const MAX_ASKED = 3;
2066
2141
  /** How far ahead the characters are told about what comes next in their day. */
@@ -2068,6 +2143,65 @@ const NEXT_HORIZON = 240 * MINUTE;
2068
2143
  /** What a character is shown of its own agenda at most. */
2069
2144
  const SHOWN_ENGAGEMENTS = 4;
2070
2145
  const SHOWN_GOALS = 3;
2146
+ const readHolds = (session) => {
2147
+ const stored = session.metadata.getValue(HOLDS);
2148
+ return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
2149
+ };
2150
+ /** Whether the story has taken a character off its day for now. */
2151
+ function isHeld(session, characterId, now) {
2152
+ const hold = readHolds(session)[characterId];
2153
+ return hold !== void 0 && now < hold.until;
2154
+ }
2155
+ /**
2156
+ * Take a character off its day: what the story made of it (it was led elsewhere, woken, sent on an errand) outranks the routine. The routine does not pull it back before
2157
+ * `minutes` are over, or when that is not said before its day next changes, and it takes its day up again then.
2158
+ */
2159
+ function holdCharacter(session, characterId, zone, now, minutes, untilPlayer = false) {
2160
+ const windows = session.routines.list(characterId);
2161
+ const current = occurrenceAt(windows, now, zone);
2162
+ const next = current === void 0 ? nextOccurrence(windows, now, zone, 1440 * MINUTE) : void 0;
2163
+ const until = untilPlayer ? now + PLAYER_HOLD_CAP : minutes !== void 0 ? now + minutes * MINUTE : current?.endsAt ?? next?.startsAt ?? now + DEFAULT_HOLD;
2164
+ const holds = readHolds(session);
2165
+ const kept = holds[characterId];
2166
+ const live = kept !== void 0 && now < kept.until;
2167
+ const end = Math.max(until, live ? kept.until : -Infinity, now + MINUTE);
2168
+ const waiting = untilPlayer || live && kept.untilPlayer !== void 0;
2169
+ holds[characterId] = {
2170
+ since: live ? kept.since : now,
2171
+ until: end,
2172
+ ...waiting ? { untilPlayer: live && kept.untilPlayer !== void 0 ? kept.untilPlayer : { apart: false } } : {}
2173
+ };
2174
+ session.metadata.setValue(HOLDS, holds);
2175
+ const stored = session.metadata.getValue(TRAVEL);
2176
+ if (typeof stored === "object" && stored !== null && !Array.isArray(stored) && String(characterId) in stored) {
2177
+ const { [String(characterId)]: _gone, ...rest } = stored;
2178
+ session.metadata.setValue(TRAVEL, rest);
2179
+ }
2180
+ return end;
2181
+ }
2182
+ /** Whether a character is asleep now: its day has it asleep, in the place it sleeps in, and nothing has woken it. The player's character is never asleep: it is the player's. */
2183
+ function sleepingNow(session, characterId, zone, now) {
2184
+ const character = session.characters.get(characterId);
2185
+ if (character === void 0 || character.control === "player" || isHeld(session, characterId, now)) return void 0;
2186
+ const current = occurrenceAt(session.routines.list(characterId), now, zone);
2187
+ if (current?.window.sleep !== true) return void 0;
2188
+ const here = session.placements.get("character", characterId);
2189
+ if (current.window.locationId !== void 0 && here?.locationId !== current.window.locationId) return void 0;
2190
+ return { until: current.endsAt };
2191
+ }
2192
+ /** Everyone asleep now. */
2193
+ function sleepersNow(session, zone, now) {
2194
+ return session.characters.list().flatMap((character) => {
2195
+ const asleep = sleepingNow(session, character.id, zone, now);
2196
+ return asleep === void 0 ? [] : [{
2197
+ character: character.id,
2198
+ key: keyOfCharacter$1(character),
2199
+ name: character.name,
2200
+ aliases: character.aliases,
2201
+ until: asleep.until
2202
+ }];
2203
+ });
2204
+ }
2071
2205
  const keyOfCharacter$1 = (character) => character.sourceId ?? String(character.id);
2072
2206
  /**
2073
2207
  * Bring the days of the characters up to the story's time: those who are not in the player's scene go where their
@@ -2082,9 +2216,11 @@ function catchUpRoutines(session, zone, now, turn, ask) {
2082
2216
  const player = session.characters.list().find((character) => character.control === "player");
2083
2217
  const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
2084
2218
  const moves = [];
2219
+ const shifted = /* @__PURE__ */ new Set();
2085
2220
  const stored = session.metadata.getValue(TRAVEL);
2086
2221
  const journeys = typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
2087
2222
  const arrive = (character, target) => {
2223
+ if (cursor !== void 0) shifted.add(keyOfCharacter$1(character));
2088
2224
  if (target.locationId !== void 0) {
2089
2225
  session.move(character.id, {
2090
2226
  to: target.locationId,
@@ -2101,6 +2237,7 @@ function catchUpRoutines(session, zone, now, turn, ask) {
2101
2237
  }
2102
2238
  if (session.characterStates.get(character.id)?.activity !== target.activity) session.characterStates.update(character.id, { activity: target.activity });
2103
2239
  };
2240
+ const holds = readHolds(session);
2104
2241
  const alreadyAsked = new Set(Array.isArray(session.metadata.getValue(ASKED)) ? session.metadata.getValue(ASKED) : []);
2105
2242
  const asked = [];
2106
2243
  for (const character of session.characters.list()) {
@@ -2121,6 +2258,18 @@ function catchUpRoutines(session, zone, now, turn, ask) {
2121
2258
  }
2122
2259
  continue;
2123
2260
  }
2261
+ const held = holds[characterId];
2262
+ let rejoin = false;
2263
+ if (held !== void 0) {
2264
+ if (held.untilPlayer !== void 0 && now < held.until) {
2265
+ if (away) held.untilPlayer.apart = true;
2266
+ else if (held.untilPlayer.apart) delete holds[characterId];
2267
+ continue;
2268
+ }
2269
+ if (now < held.until) continue;
2270
+ delete holds[characterId];
2271
+ rejoin = true;
2272
+ }
2124
2273
  if (!away) continue;
2125
2274
  const current = occurrenceAt(window, now, zone);
2126
2275
  const journey = journeys[characterId];
@@ -2135,7 +2284,7 @@ function catchUpRoutines(session, zone, now, turn, ask) {
2135
2284
  }
2136
2285
  if (current === void 0) continue;
2137
2286
  const before = cursor === void 0 ? void 0 : occurrenceAt(window, cursor, zone);
2138
- if (before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
2287
+ if (!rejoin && before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
2139
2288
  const target = current.window;
2140
2289
  if (target.locationId !== void 0 && (here?.locationId !== target.locationId || target.position !== void 0 && here.position !== target.position)) {
2141
2290
  const way = here?.locationId === target.locationId ? void 0 : session.planMove(characterId, { to: target.locationId });
@@ -2151,32 +2300,52 @@ function catchUpRoutines(session, zone, now, turn, ask) {
2151
2300
  continue;
2152
2301
  }
2153
2302
  arrive(character, target);
2154
- } else if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
2303
+ } else {
2304
+ if (cursor !== void 0) shifted.add(keyOfCharacter$1(character));
2305
+ if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
2306
+ }
2155
2307
  }
2156
2308
  session.metadata.setValue(CURSOR, now);
2157
2309
  session.metadata.setValue(TRAVEL, journeys);
2310
+ session.metadata.setValue(HOLDS, holds);
2311
+ if (shifted.size > 0) {
2312
+ const before = session.metadata.getValue(SHIFTED);
2313
+ session.metadata.setValue(SHIFTED, [.../* @__PURE__ */ new Set([...Array.isArray(before) ? before.filter((entry) => typeof entry === "string") : [], ...shifted])]);
2314
+ }
2158
2315
  if (asked.length > 0) session.metadata.setValue(ASKED, [...alreadyAsked, ...asked]);
2159
2316
  return moves;
2160
2317
  });
2161
2318
  }
2319
+ /** The characters whose day changed since this was last asked, by key; asking forgets them. */
2320
+ function takeShifts(session) {
2321
+ const stored = session.metadata.getValue(SHIFTED);
2322
+ const keys = Array.isArray(stored) ? stored.filter((entry) => typeof entry === "string") : [];
2323
+ if (keys.length > 0) session.metadata.setValue(SHIFTED, []);
2324
+ return keys;
2325
+ }
2162
2326
  /** A character's agenda at an instant, with places by name and others by name. */
2163
- function agendaView(session, characterId, zone, now) {
2327
+ function agendaView(session, characterId, zone, now, scheduled = true) {
2164
2328
  const agenda = agendaAt(session, characterId, now, zone, {
2165
2329
  horizon: NEXT_HORIZON,
2166
2330
  engagements: SHOWN_ENGAGEMENTS,
2167
2331
  goals: SHOWN_GOALS
2168
2332
  });
2333
+ const hold = scheduled ? readHolds(session)[characterId] : void 0;
2334
+ const held = hold !== void 0 && now < hold.until;
2335
+ const dayless = !scheduled || session.characters.get(characterId)?.control === "player";
2169
2336
  const place = (id) => id === void 0 ? void 0 : session.locations.get(id)?.name;
2170
2337
  const names = (ids) => ids.filter((id) => id !== characterId).map((id) => session.characters.get(id)?.name ?? String(id));
2171
2338
  return {
2172
2339
  zone,
2173
- ...agenda.now === void 0 ? {} : { now: {
2340
+ ...agenda.now === void 0 || held || dayless ? {} : { now: {
2174
2341
  activity: agenda.now.window.activity,
2175
2342
  ...place(agenda.now.window.locationId) === void 0 ? {} : { place: place(agenda.now.window.locationId) },
2176
2343
  until: agenda.now.endsAt,
2177
- interruptible: agenda.now.window.interruptible
2344
+ interruptible: agenda.now.window.interruptible,
2345
+ ...agenda.now.window.sleep === true ? { sleep: true } : {}
2178
2346
  } },
2179
- ...agenda.next === void 0 ? {} : { next: {
2347
+ ...held ? { offDay: { until: hold.until } } : {},
2348
+ ...agenda.next === void 0 || dayless ? {} : { next: {
2180
2349
  activity: agenda.next.window.activity,
2181
2350
  ...place(agenda.next.window.locationId) === void 0 ? {} : { place: place(agenda.next.window.locationId) },
2182
2351
  at: agenda.next.startsAt
@@ -2203,12 +2372,13 @@ const SOON = 30 * MINUTE;
2203
2372
  const MAX_NOTES = 6;
2204
2373
  /** An engagement that has been overdue for longer than this is not worth the game master's attention every turn. */
2205
2374
  const STALE = 1440 * MINUTE;
2206
- function sceneAgenda(session, zone, now, moved) {
2375
+ function sceneAgenda(session, zone, now, moved, scheduled = true) {
2207
2376
  const player = session.characters.list().find((character) => character.control === "player");
2208
2377
  const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
2209
2378
  const withPlayer = new Set(session.characters.list().filter((character) => playerPlace !== void 0 && session.placements.get("character", character.id)?.locationId === playerPlace && character.control !== "player").map((character) => character.id));
2210
2379
  const here = [];
2211
- for (const characterId of withPlayer) {
2380
+ for (const characterId of scheduled ? withPlayer : []) {
2381
+ if (isHeld(session, characterId, now)) continue;
2212
2382
  const windows = session.routines.list(characterId);
2213
2383
  const current = occurrenceAt(windows, now, zone);
2214
2384
  const upcoming = nextOccurrence(windows, now, zone, SOON);
@@ -2237,43 +2407,49 @@ function sceneAgenda(session, zone, now, moved) {
2237
2407
  with: engagement.participants.map((id) => session.characters.get(id)?.name ?? String(id)),
2238
2408
  overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE)
2239
2409
  }));
2410
+ const asleep = scheduled ? sleepersNow(session, zone, now).map(({ key, name, until }) => ({
2411
+ key,
2412
+ name,
2413
+ until
2414
+ })) : [];
2240
2415
  return {
2241
2416
  zone,
2242
2417
  moved,
2243
2418
  here: here.slice(0, MAX_NOTES),
2419
+ asleep,
2244
2420
  engagements
2245
2421
  };
2246
2422
  }
2247
2423
  // src/host/clock/passage.ts
2248
2424
  /** The start of a turn: the time, how long the player was away, and what the days of the characters make of it. */
2249
- function startTurn(session, config, turn, wall) {
2425
+ function startTurn(session, config, turn, wall, scheduled = true) {
2250
2426
  const started = beginTurn(session, config, turn, wall);
2251
- const moved = catchUpRoutines(session, started.time.zone, started.time.now, turn, true);
2427
+ const moved = scheduled ? catchUpRoutines(session, started.time.zone, started.time.now, turn, true) : [];
2252
2428
  return {
2253
2429
  ...started,
2254
- agenda: sceneAgenda(session, started.time.zone, started.time.now, moved)
2430
+ agenda: sceneAgenda(session, started.time.zone, started.time.now, moved, scheduled)
2255
2431
  };
2256
2432
  }
2257
2433
  /** A round passes, and the characters outside the scene take up what their days have for the new time. */
2258
- function passRound(session, config, turn, round, wall, stated, minimum) {
2434
+ function passRound(session, config, turn, round, wall, stated, minimum, scheduled = true) {
2259
2435
  const span = endRound(session, config, turn, round, wall, stated, minimum);
2260
2436
  return {
2261
2437
  ...span,
2262
- moved: catchUpRoutines(session, span.zone, span.to, turn, false)
2438
+ moved: scheduled ? catchUpRoutines(session, span.zone, span.to, turn, false) : []
2263
2439
  };
2264
2440
  }
2265
2441
  /** Time is skipped, and the characters outside the scene take up what their days have for the new time. */
2266
- function skipAhead(session, config, turn, round, wall, request) {
2442
+ function skipAhead(session, config, turn, round, wall, request, scheduled = true) {
2267
2443
  const span = skipTime(session, config, turn, round, wall, request);
2268
2444
  return {
2269
2445
  ...span,
2270
- moved: catchUpRoutines(session, span.zone, span.to, turn, true)
2446
+ moved: scheduled ? catchUpRoutines(session, span.zone, span.to, turn, true) : []
2271
2447
  };
2272
2448
  }
2273
2449
  /** What a character is told of its own agenda. */
2274
- function agendaFor(session, config, turn, wall, characterId) {
2450
+ function agendaFor(session, config, turn, wall, characterId, scheduled = true) {
2275
2451
  const time = readTime(session, config, turn, wall());
2276
- return agendaView(session, characterId, zoneOf(config), time.now);
2452
+ return agendaView(session, characterId, zoneOf(config), time.now, scheduled);
2277
2453
  }
2278
2454
  // src/host/clock/offscene.ts
2279
2455
  const HANDLED = "offscene.handled";
@@ -2706,10 +2882,10 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
2706
2882
  time: (turn) => readTime(session, settings().clock, turn, wall()),
2707
2883
  beginTurn: (turn) => {
2708
2884
  observeAsPlayer(session, turn);
2709
- return startTurn(session, settings().clock, turn, wall());
2885
+ return startTurn(session, settings().clock, turn, wall(), settings().schedule.enabled);
2710
2886
  },
2711
- endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum),
2712
- skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request),
2887
+ endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum, settings().schedule.enabled),
2888
+ skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request, settings().schedule.enabled),
2713
2889
  checkVariableChanges: (changes) => changes.flatMap((spec) => {
2714
2890
  const planned = planVariableChange(session, spec);
2715
2891
  return planned.ok ? [] : planned.problems;
@@ -2768,15 +2944,66 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
2768
2944
  recordTrace: (turn, patch, merge) => {
2769
2945
  updateTrace(session, turn, patch, merge);
2770
2946
  },
2947
+ folders: async () => await storyRoots(dirname(dirname(folder)), folder),
2948
+ autonomy: {
2949
+ catchUp: (turn) => {
2950
+ if (!settings().schedule.enabled) return [];
2951
+ const { now, zone } = readTime(session, settings().clock, turn, wall());
2952
+ return catchUpRoutines(session, zone, now, turn, false);
2953
+ },
2954
+ shifts: () => takeShifts(session),
2955
+ state: () => readAutonomy(session),
2956
+ lastPlayerAt: () => lastPlayerAt(session),
2957
+ said: (turn, message) => {
2958
+ session.transaction(() => {
2959
+ recordMessage(session, message);
2960
+ addToNote(session, "message", turn, [`${message.name}: ${message.text}`]);
2961
+ });
2962
+ },
2963
+ asked: (character, at) => {
2964
+ recordAsk(session, character, at);
2965
+ },
2966
+ inbox: () => takeInbox(session),
2967
+ looked: (outcome, at) => {
2968
+ session.metadata.setValue("autonomy.look", {
2969
+ outcome,
2970
+ at
2971
+ });
2972
+ }
2973
+ },
2771
2974
  notes: () => readNotes(session),
2772
2975
  clearNotes: () => {
2773
2976
  clearNotes(session);
2774
2977
  },
2775
- agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId),
2776
- commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items }) => {
2978
+ agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId, settings().schedule.enabled),
2979
+ asleep: (turn, characterId) => {
2980
+ if (!settings().schedule.enabled) return void 0;
2981
+ const { now, zone } = readTime(session, settings().clock, turn, wall());
2982
+ return sleepingNow(session, characterId, zone, now);
2983
+ },
2984
+ sleepers: (turn) => {
2985
+ if (!settings().schedule.enabled) return [];
2986
+ const { now, zone } = readTime(session, settings().clock, turn, wall());
2987
+ return sleepersNow(session, zone, now).map(({ key, name, aliases, until }) => ({
2988
+ key,
2989
+ name,
2990
+ aliases,
2991
+ until
2992
+ }));
2993
+ },
2994
+ holdForPlayer: (characterId) => {
2995
+ if (!settings().schedule.enabled) return;
2996
+ const { now, zone } = readTime(session, settings().clock, session.metadata.get().turns + 1, wall());
2997
+ holdCharacter(session, characterId, zone, now, void 0, true);
2998
+ },
2999
+ commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items, hold }) => {
2777
3000
  session.characterStates.update(character, patch);
2778
3001
  const effects = (items ?? []).map((spec) => changeItem(session, character, spec));
2779
3002
  if (move !== void 0) session.move(character, move);
3003
+ if (hold !== void 0 && settings().schedule.enabled) {
3004
+ const { now, zone } = readTime(session, settings().clock, session.metadata.get().turns + 1, wall());
3005
+ holdCharacter(session, character, zone, now, hold.minutes, hold.untilPlayer === true);
3006
+ }
2780
3007
  return effects;
2781
3008
  })),
2782
3009
  checkItemChanges: (entries) => dryRunItems(session, entries),
@@ -2832,113 +3059,6 @@ function parseOoc(text) {
2832
3059
  }
2833
3060
  /** The longest answer to an out-of-character question. */
2834
3061
  const MAX_OOC_ANSWER = 1200;
2835
- // src/shared/roll.ts
2836
- /** The roll in a player's message, or nothing when the message does not start with `/roll`. The notation may be empty, and is then refused. */
2837
- function parseRoll(text) {
2838
- const value = text.trimStart();
2839
- if (value.slice(0, 5).toLowerCase() !== "/roll" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
2840
- const body = value.slice(5).trimStart();
2841
- const boundary = body.search(/\s/u);
2842
- return boundary < 0 ? {
2843
- expression: body,
2844
- reason: ""
2845
- } : {
2846
- expression: body.slice(0, boundary),
2847
- reason: body.slice(boundary).trim()
2848
- };
2849
- }
2850
- // src/shared/wait.ts
2851
- const UNITS = [
2852
- [/^(?:m|min|mins|minute|minutes|分钟|分)$/iu, 1],
2853
- [/^(?:h|hr|hrs|hour|hours|小时|時間|时)$/iu, 60],
2854
- [/^(?:d|day|days|天|日)$/iu, 1440]
2855
- ];
2856
- /**
2857
- * The wait in a player's message (`/wait 2 hours`, `/wait 30m until the ferry`, `/wait 3天`), or nothing when the message does not start with `/wait`. The time may be missing or
2858
- * unreadable, and is then `undefined` in `minutes`.
2859
- */
2860
- function parseWait(text) {
2861
- const value = text.trimStart();
2862
- if (value.slice(0, 5).toLowerCase() !== "/wait" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
2863
- const body = value.slice(5).trim();
2864
- const match = /^(\d+(?:\.\d+)?)\s*([\p{L}]+)\s*(.*)$/su.exec(body);
2865
- if (match === null) return {
2866
- minutes: void 0,
2867
- reason: body
2868
- };
2869
- const unit = UNITS.find(([pattern]) => pattern.test(match[2]));
2870
- if (unit === void 0) return {
2871
- minutes: void 0,
2872
- reason: body
2873
- };
2874
- const minutes = Math.round(Number(match[1]) * unit[1]);
2875
- return {
2876
- minutes: minutes >= 1 && minutes <= 525600 ? minutes : void 0,
2877
- reason: match[3].trim()
2878
- };
2879
- }
2880
- // src/host/agents/repeat-guard.ts
2881
- /**
2882
- * Keeps an agent that is stuck from making the same call again and again (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one
2883
- * refused round resolution): past `limit` identical calls in one turn the call is refused with a word that sends it on, and when it goes on regardless the turn is ended. The count starts over at the first step of every turn.
2884
- * @param languageOf the language of the chat the call belongs to, or nothing when the guard does not apply to it.
2885
- */
2886
- function guardRepeatedCalls(ctx, languageOf, limit) {
2887
- const calls = /* @__PURE__ */ new Map();
2888
- ctx.on("agent/pre-step", async (payload, next) => {
2889
- if (payload.step === 1) calls.delete(payload.agent.session.id);
2890
- return await next();
2891
- });
2892
- ctx.on("tools/pre-execute", async (exec, next) => {
2893
- const chat = exec.agent?.session.id;
2894
- const language = chat === void 0 || exec.agent?.session.header.origin === "subagent" ? void 0 : languageOf(exec);
2895
- if (chat === void 0 || language === void 0) return await next();
2896
- const signature = `${exec.name}:${JSON.stringify(exec.arguments)}`;
2897
- const seen = calls.get(chat) ?? /* @__PURE__ */ new Map();
2898
- calls.set(chat, seen);
2899
- const count = (seen.get(signature) ?? 0) + 1;
2900
- seen.set(signature, count);
2901
- if (count <= limit) return await next();
2902
- if (count > limit + 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
2903
- return {
2904
- kind: "deny",
2905
- reason: translator(languageOf$1(language))("This exact call was already made {count} times in this turn with the same result. Do not repeat it: go on with the next step, or finish and say what is left.", { count: count - 1 })
2906
- };
2907
- }, { prepend: true });
2908
- }
2909
- // src/host/orchestration/runaway.ts
2910
- /** The levels of thinking that mean none, as models name them. */
2911
- const NONE = [
2912
- "off",
2913
- "none",
2914
- "minimal"
2915
- ];
2916
- /**
2917
- * A game master whose thinking ran on to the end of its output limit (found live: 12000 tokens, two and a half minutes, and a turn that ended without output) is asked to answer
2918
- * without thinking for the rest of the turn, when its model offers that. The level it was on is put back at the first step of the next turn.
2919
- */
2920
- var RunawayThinking = class {
2921
- before = /* @__PURE__ */ new Map();
2922
- /** To be called before each step of a chat's game master. */
2923
- async step(chat, agent, step) {
2924
- const earlier = this.before.get(chat);
2925
- if (earlier !== void 0 && step === 1) {
2926
- agent.model.select(earlier);
2927
- this.before.delete(chat);
2928
- return;
2929
- }
2930
- if (step === 1 || earlier !== void 0 || !cutOff(agent)) return;
2931
- const current = agent.model.current();
2932
- if (current === void 0) return;
2933
- const level = (await agent.ctx.llm.resolveModelInfo(current.provider, current.model, new AbortController().signal).catch(() => void 0))?.reasoning?.efforts.find((effort) => NONE.includes(effort.id));
2934
- if (level === void 0 || current.reasoningEffort === level.id) return;
2935
- this.before.set(chat, current);
2936
- agent.model.select({
2937
- ...current,
2938
- reasoningEffort: ReasoningEffortId(level.id)
2939
- });
2940
- }
2941
- };
2942
3062
  // src/shared/tools.ts
2943
3063
  /** What this version can offer. A name in a settings file or a world that is not here is kept and ignored. */
2944
3064
  const OPTIONAL_TOOLS = [
@@ -3011,175 +3131,6 @@ function toolEnabled(board, agent, id) {
3011
3131
  function externalEnabled(board, agent, name) {
3012
3132
  return board[agent]?.[name] === true;
3013
3133
  }
3014
- // src/host/orchestration/character-runner.ts
3015
- /**
3016
- * Runs each character as a one-shot child of the game master. It is the character and nothing
3017
- * else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
3018
- * the memory of that character alone, so characters acting at the same time cannot see each
3019
- * other's memories.
3020
- */
3021
- function characterRunner(deps) {
3022
- return async (request, signal) => {
3023
- const brief = deps.boundaries().characterContext.brief(request);
3024
- const settings = deps.store.settings();
3025
- const tools = settings.memory.lookup ? createCharacterTools(() => ({
3026
- session: deps.store.story,
3027
- turn: request.turn,
3028
- policy: settings.memory,
3029
- queryVector: deps.store.queryVector
3030
- }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)).map((tool) => notingEmpty(tool, deps.store, request.turn, request.member.character.name)) : [];
3031
- const background = (request.knowledge?.lore.length ?? 0) > 0 && tools.some((tool) => tool.name === "recall_my_lore");
3032
- const external = externalGiven(deps.parent.ctx.tools, settings.tools, "characters");
3033
- const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
3034
- return parseCharacterAction(await runChild({
3035
- parent: deps.parent,
3036
- signal,
3037
- sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
3038
- ...childModel(settings, "characters", named),
3039
- trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named, request.away === true ? "off stage" : void 0),
3040
- reasoningEffort: deps.store.settings().reasoning.children,
3041
- persona: brief.persona,
3042
- prompt: brief.prompt,
3043
- tools,
3044
- external,
3045
- maxCalls: deps.store.settings().memory.lookupCalls + (external.length === 0 ? 0 : EXTERNAL_CALLS),
3046
- result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
3047
- unenforced: ["thought"],
3048
- beforeSubmit: submitGate(settings.prompts.language, background, request.away === true ? [] : ownLines(deps.store, request.member.character))
3049
- }));
3050
- };
3051
- }
3052
- /** A look-up that finds nothing is kept in the turn's trace: it is where the world lacks what a character reached for. */
3053
- function notingEmpty(tool, store, turn, character) {
3054
- return {
3055
- ...tool,
3056
- async execute(args, exec) {
3057
- const found = await tool.execute(args, exec);
3058
- const about = args.about;
3059
- if (Array.isArray(found) && found.length === 0 && typeof about === "string" && about.trim() !== "") try {
3060
- store.recordTrace?.(turn, {}, (current) => ({ missing: [...current.missing ?? [], {
3061
- character,
3062
- tool: tool.name,
3063
- about: about.trim().slice(0, 120)
3064
- }].slice(-40) }));
3065
- } catch {}
3066
- return found;
3067
- }
3068
- };
3069
- }
3070
- const BACKGROUND_CHECK = "before you answer: does this moment touch your own past, skills, training, secrets or what you know of a person or place? If it does, read that background first with recall_my_lore (about: the subject) and answer from it; if it does not, submit the same answer again unchanged";
3071
- /** The model decides whether the moment touches its background; asking once at the point of answering is what makes it decide. */
3072
- function submitGate(language, background, said = []) {
3073
- let asked = !background;
3074
- let reminded = false;
3075
- const tr = translator(languageOf$1(language));
3076
- return (value) => {
3077
- if (!asked) {
3078
- asked = true;
3079
- return BACKGROUND_CHECK;
3080
- }
3081
- const wrong = spokenIn(language, value);
3082
- if (wrong !== void 0) return wrong;
3083
- const line = value.utterance;
3084
- if (!reminded && line !== void 0 && said.some((earlier) => sameWords(earlier, line))) {
3085
- reminded = true;
3086
- return tr("you already said exactly this earlier in the story: \"{line}\". Say something new that answers this moment, or give no utterance", { line });
3087
- }
3088
- };
3089
- }
3090
- /** What a character has said in the story so far, most recent last, as the records keep it. */
3091
- function ownLines(store, character) {
3092
- const opening = `${character.name}: "`;
3093
- return store.story.events.list({ involving: character.id }).flatMap((event) => event.text.startsWith(opening) && event.text.endsWith("\"") ? [event.text.slice(opening.length, -1)] : []).slice(-12);
3094
- }
3095
- /** What a character that was given tools of other plugins may call on top of its memory look-ups. */
3096
- const EXTERNAL_CALLS = 5;
3097
- /** A character whose sheet is in another language than the chat's writes in the sheet's: the answer is refused until it is in the chat's. */
3098
- function spokenIn(language, value) {
3099
- const given = value;
3100
- return wrongLanguage(language, {
3101
- thought: given.thought,
3102
- intent: given.intent,
3103
- utterance: given.utterance,
3104
- account: given.account
3105
- }, { strays: true }) ?? narratedSpeech(given.utterance);
3106
- }
3107
- const CLOSING_QUOTE = {
3108
- "\"": "\"",
3109
- "“": "”",
3110
- "「": "」",
3111
- "『": "』"
3112
- };
3113
- function outsideQuotedSpeech(utterance) {
3114
- const parts = [];
3115
- let outside = 0;
3116
- let cursor = 0;
3117
- while (cursor < utterance.length) {
3118
- const closing = CLOSING_QUOTE[utterance[cursor]];
3119
- if (closing === void 0) {
3120
- cursor += 1;
3121
- continue;
3122
- }
3123
- const end = utterance.indexOf(closing, cursor + 1);
3124
- if (end < 0) {
3125
- cursor += 1;
3126
- continue;
3127
- }
3128
- parts.push(utterance.slice(outside, cursor));
3129
- outside = end + 1;
3130
- cursor = outside;
3131
- }
3132
- parts.push(utterance.slice(outside));
3133
- return parts;
3134
- }
3135
- /** Writing instructions that ask for prose from the character's own point of view lead it to put its actions between its lines; the utterance is only what is said aloud. */
3136
- function narratedSpeech(utterance) {
3137
- if (utterance === void 0) return void 0;
3138
- const parts = outsideQuotedSpeech(utterance);
3139
- if (parts.length - 1 < 2) return void 0;
3140
- return parts.slice(1, -1).some((part) => part.replace(/[\s\p{P}]/gu, "").length >= 6) ? "the utterance holds more than the words said aloud: put what you do in intent and write in the utterance only what you say, with nothing between your lines" : void 0;
3141
- }
3142
- /** What the character was reminded of and why, for the run's record, when the recall said why. */
3143
- function recalledOf(request) {
3144
- const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
3145
- return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
3146
- clarity,
3147
- turn,
3148
- text,
3149
- why
3150
- })) };
3151
- }
3152
- const ANSWER_SCHEMA = {
3153
- type: "object",
3154
- properties: { answer: {
3155
- type: "string",
3156
- description: "The answer to the player, in plain words, in a few sentences."
3157
- } },
3158
- required: ["answer"],
3159
- additionalProperties: false
3160
- };
3161
- /**
3162
- * Answers a player's question as an agent that has only what the player's character is given when it acts: the character sheet is left out and nothing the
3163
- * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
3164
- */
3165
- function answerRunner(deps) {
3166
- return async (request, signal) => {
3167
- const brief = deps.boundaries().characterContext.brief(request);
3168
- return (await runChild({
3169
- parent: deps.parent,
3170
- signal,
3171
- sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
3172
- ...childModel(deps.store.settings(), "records"),
3173
- trace: childTrace(deps.store, "records", "answer to the player"),
3174
- reasoningEffort: deps.store.settings().reasoning.children,
3175
- persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
3176
- prompt: brief.prompt,
3177
- tools: [],
3178
- maxCalls: 3,
3179
- result: ANSWER_SCHEMA
3180
- })).answer;
3181
- };
3182
- }
3183
3134
  // src/host/pacing/author.ts
3184
3135
  const RESULT = {
3185
3136
  type: "object",
@@ -3436,6 +3387,11 @@ function createTools$1(deps) {
3436
3387
  type: "string",
3437
3388
  required: true,
3438
3389
  description: "An objective description of the moment: in the first round what the player's character just did or said; in a later round what is happening now, following from the rounds before (they are told those too). Every character is told this and nothing more, so leave out anyone's private thoughts."
3390
+ },
3391
+ wakes: {
3392
+ type: "array",
3393
+ items: { type: "string" },
3394
+ description: "Keys of the characters asleep (the scene says who) that what the player did wakes: only those you list take part, and your narration must show them waking. A sleeper you do not list cannot be asked. Leave out when nobody is woken."
3439
3395
  }
3440
3396
  },
3441
3397
  output: {
@@ -3456,7 +3412,8 @@ function createTools$1(deps) {
3456
3412
  });
3457
3413
  return record(await deps.engine.activate(owner, {
3458
3414
  situation: args.situation,
3459
- characters: args.characters
3415
+ characters: args.characters,
3416
+ ...args.wakes === void 0 ? {} : { wakes: args.wakes }
3460
3417
  }, run, exec.signal));
3461
3418
  }
3462
3419
  });
@@ -3487,6 +3444,14 @@ function createTools$1(deps) {
3487
3444
  required: true,
3488
3445
  description: "What concretely happens to the character, in a sentence. It becomes what the character is doing."
3489
3446
  },
3447
+ off_routine_minutes: {
3448
+ type: "integer",
3449
+ description: "For a character that has a daily routine: how long, in minutes, from now until it is free to go back to its routine, counting the whole time away and not only the way there (an errand, a vigil, a long talk). Never for the player's character, who has no routine. Always give it when the character is told or chooses to stay, wait, watch or keep going until something happens or someone returns (\"wait however long it takes\"): then count generously, past the longest the wait could last, such as 600 for a whole night. Leave it out only for a short detour: it then keeps to what it does until its day next changes, and its routine takes it back after that. A character who is led or sent elsewhere, or woken, is taken off its routine either way."
3450
+ },
3451
+ waits_for_player: {
3452
+ type: "boolean",
3453
+ description: "True when the character is told or chooses to stay, wait or watch until the player's character is with it again, or goes on an errand that ends only when it is back with the player. It then keeps to that until the player comes to it, whatever its routine says, for at most a day. Never for the player's character."
3454
+ },
3490
3455
  roll: {
3491
3456
  type: "integer",
3492
3457
  description: "The id of the dice roll that decided this outcome (the id roll_check gave), when you rolled for it: the result you give must be the roll's."
@@ -3643,6 +3608,8 @@ function createTools$1(deps) {
3643
3608
  ...outcome.public_state === void 0 ? {} : { publicState: outcome.public_state },
3644
3609
  ...outcome.spoken === void 0 ? {} : { spoken: outcome.spoken },
3645
3610
  ...outcome.roll === void 0 ? {} : { roll: outcome.roll },
3611
+ ...outcome.waits_for_player === true ? { waitsForPlayer: true } : {},
3612
+ ...outcome.off_routine_minutes === void 0 ? {} : { offRoutineMinutes: outcome.off_routine_minutes },
3646
3613
  ...outcome.item_changes === void 0 || outcome.item_changes.length === 0 ? {} : { itemChanges: outcome.item_changes.map((change) => ({
3647
3614
  item: change.item,
3648
3615
  action: change.action,
@@ -4065,6 +4032,10 @@ function createTools$1(deps) {
4065
4032
  required: true,
4066
4033
  description: "Whether what the character tries can work: false when any listed rule is broken or it is not viable."
4067
4034
  },
4035
+ goes_to: {
4036
+ type: "string",
4037
+ description: "The key of the place the player's character is going to, only when what it tries is to go, walk or travel to another place, or to enter one (the market, the cellar, home). Leave it out for anything else. If you do not then record the move with resolve_round, you are asked to before the output is delivered."
4038
+ },
4068
4039
  uncertain: {
4069
4040
  type: "boolean",
4070
4041
  required: true,
@@ -4087,7 +4058,7 @@ function createTools$1(deps) {
4087
4058
  async execute(args, exec) {
4088
4059
  const { owner } = ownerOf(exec.agent);
4089
4060
  await deps.engine.checkRules(owner, args.allowed);
4090
- const judged = deps.engine.judge(owner, args.allowed, args.reason, args.at, args.uncertain);
4061
+ const judged = deps.engine.judge(owner, args.allowed, args.reason, args.at, args.uncertain, args.goes_to);
4091
4062
  const store = deps.stores(owner.chat);
4092
4063
  return record(judged.roll === true && store !== void 0 && toolEnabled(store.settings().tools, "gameMaster", "roll_and_narrate") ? {
4093
4064
  ...judged,
@@ -4141,7 +4112,317 @@ function externalGiven(registry, board, agent) {
4141
4112
  function externalWithheld(registry, board, agent) {
4142
4113
  return externalTools(registry).map((tool) => tool.name).filter((name) => !externalEnabled(board, agent, name));
4143
4114
  }
4115
+ /** What a character may use besides its own look-ups: nothing while it is away, because nobody is playing to see what it does with a tool. */
4116
+ function charactersGiven(registry, board, away) {
4117
+ return away ? [] : externalGiven(registry, board, "characters");
4118
+ }
4119
+ // src/host/workspace/describe.ts
4120
+ /** What an agent with file tools is told of where they reach: the shared workspace first, then the folders given to this story. Nothing for a story with no workspace. */
4121
+ function foldersLine(roots, language) {
4122
+ const [workspace, ...rest] = roots;
4123
+ if (workspace === void 0) return void 0;
4124
+ const tr = translator(language);
4125
+ const given = rest.map((folder) => folder.write ? tr("{path} (read and write)", { path: folder.path }) : tr("{path} (read only)", { path: folder.path }));
4126
+ return tr("Your file tools reach only these folders, and every path must be a whole path. The shared workspace, which you may read and write: {workspace}.{given}", {
4127
+ workspace: workspace.path,
4128
+ given: given.length === 0 ? "" : tr(" Given for this story: {folders}.", { folders: given.join(tr(", ")) })
4129
+ });
4130
+ }
4131
+ // src/host/orchestration/character-runner.ts
4132
+ /**
4133
+ * Runs each character as a one-shot child of the game master. It is the character and nothing
4134
+ * else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
4135
+ * the memory of that character alone, so characters acting at the same time cannot see each
4136
+ * other's memories.
4137
+ */
4138
+ function characterRunner(deps) {
4139
+ return async (request, signal) => {
4140
+ const brief = deps.boundaries().characterContext.brief(request);
4141
+ const settings = deps.store.settings();
4142
+ const tools = settings.memory.lookup ? createCharacterTools(() => ({
4143
+ session: deps.store.story,
4144
+ turn: request.turn,
4145
+ policy: settings.memory,
4146
+ queryVector: deps.store.queryVector
4147
+ }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)).map((tool) => notingEmpty(tool, deps.store, request.turn, request.member.character.name)) : [];
4148
+ const background = (request.knowledge?.lore.length ?? 0) > 0 && tools.some((tool) => tool.name === "recall_my_lore");
4149
+ const external = charactersGiven(deps.parent.ctx.tools, settings.tools, request.away === true);
4150
+ const folders = external.length === 0 ? void 0 : await deps.store.folders?.().then((roots) => foldersLine(roots, languageOf$1(settings.prompts.language)));
4151
+ const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
4152
+ return parseCharacterAction(await runChild({
4153
+ parent: deps.parent,
4154
+ signal,
4155
+ sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
4156
+ ...childModel(settings, "characters", named),
4157
+ trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named, request.away === true ? "off stage" : void 0),
4158
+ reasoningEffort: deps.store.settings().reasoning.children,
4159
+ persona: brief.persona,
4160
+ prompt: folders === void 0 ? brief.prompt : `${brief.prompt}\n\n${folders}`,
4161
+ tools,
4162
+ external,
4163
+ maxCalls: deps.store.settings().memory.lookupCalls + (external.length === 0 ? 0 : EXTERNAL_CALLS),
4164
+ result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
4165
+ unenforced: ["thought"],
4166
+ beforeSubmit: submitGate(settings.prompts.language, background, request.away === true ? [] : ownLines(deps.store, request.member.character))
4167
+ }));
4168
+ };
4169
+ }
4170
+ /** A look-up that finds nothing is kept in the turn's trace: it is where the world lacks what a character reached for. */
4171
+ function notingEmpty(tool, store, turn, character) {
4172
+ return {
4173
+ ...tool,
4174
+ async execute(args, exec) {
4175
+ const found = await tool.execute(args, exec);
4176
+ const about = args.about;
4177
+ if (Array.isArray(found) && found.length === 0 && typeof about === "string" && about.trim() !== "") try {
4178
+ store.recordTrace?.(turn, {}, (current) => ({ missing: [...current.missing ?? [], {
4179
+ character,
4180
+ tool: tool.name,
4181
+ about: about.trim().slice(0, 120)
4182
+ }].slice(-40) }));
4183
+ } catch {}
4184
+ return found;
4185
+ }
4186
+ };
4187
+ }
4188
+ const BACKGROUND_CHECK = "before you answer: does this moment touch your own past, skills, training, secrets or what you know of a person or place? If it does, read that background first with recall_my_lore (about: the subject) and answer from it; if it does not, submit the same answer again unchanged";
4189
+ /** The model decides whether the moment touches its background; asking once at the point of answering is what makes it decide. */
4190
+ function submitGate(language, background, said = []) {
4191
+ let asked = !background;
4192
+ let reminded = false;
4193
+ const tr = translator(languageOf$1(language));
4194
+ return (value) => {
4195
+ if (!asked) {
4196
+ asked = true;
4197
+ return BACKGROUND_CHECK;
4198
+ }
4199
+ const wrong = spokenIn(language, value);
4200
+ if (wrong !== void 0) return wrong;
4201
+ const line = value.utterance;
4202
+ if (!reminded && line !== void 0 && said.some((earlier) => sameWords(earlier, line))) {
4203
+ reminded = true;
4204
+ return tr("you already said exactly this earlier in the story: \"{line}\". Say something new that answers this moment, or give no utterance", { line });
4205
+ }
4206
+ };
4207
+ }
4208
+ /** What a character has said in the story so far, most recent last, as the records keep it. */
4209
+ function ownLines(store, character) {
4210
+ const opening = `${character.name}: "`;
4211
+ return store.story.events.list({ involving: character.id }).flatMap((event) => event.text.startsWith(opening) && event.text.endsWith("\"") ? [event.text.slice(opening.length, -1)] : []).slice(-12);
4212
+ }
4213
+ /** What a character that was given tools of other plugins may call on top of its memory look-ups. */
4214
+ const EXTERNAL_CALLS = 5;
4215
+ /** A character whose sheet is in another language than the chat's writes in the sheet's: the answer is refused until it is in the chat's. */
4216
+ function spokenIn(language, value) {
4217
+ const given = value;
4218
+ return wrongLanguage(language, {
4219
+ thought: given.thought,
4220
+ intent: given.intent,
4221
+ utterance: given.utterance,
4222
+ account: given.account
4223
+ }, { strays: true }) ?? narratedSpeech(given.utterance);
4224
+ }
4225
+ const CLOSING_QUOTE = {
4226
+ "\"": "\"",
4227
+ "“": "”",
4228
+ "「": "」",
4229
+ "『": "』"
4230
+ };
4231
+ function outsideQuotedSpeech(utterance) {
4232
+ const parts = [];
4233
+ let outside = 0;
4234
+ let cursor = 0;
4235
+ while (cursor < utterance.length) {
4236
+ const closing = CLOSING_QUOTE[utterance[cursor]];
4237
+ if (closing === void 0) {
4238
+ cursor += 1;
4239
+ continue;
4240
+ }
4241
+ const end = utterance.indexOf(closing, cursor + 1);
4242
+ if (end < 0) {
4243
+ cursor += 1;
4244
+ continue;
4245
+ }
4246
+ parts.push(utterance.slice(outside, cursor));
4247
+ outside = end + 1;
4248
+ cursor = outside;
4249
+ }
4250
+ parts.push(utterance.slice(outside));
4251
+ return parts;
4252
+ }
4253
+ /** Writing instructions that ask for prose from the character's own point of view lead it to put its actions between its lines; the utterance is only what is said aloud. */
4254
+ function narratedSpeech(utterance) {
4255
+ if (utterance === void 0) return void 0;
4256
+ const parts = outsideQuotedSpeech(utterance);
4257
+ if (parts.length - 1 < 2) return void 0;
4258
+ return parts.slice(1, -1).some((part) => part.replace(/[\s\p{P}]/gu, "").length >= 6) ? "the utterance holds more than the words said aloud: put what you do in intent and write in the utterance only what you say, with nothing between your lines" : void 0;
4259
+ }
4260
+ /** What the character was reminded of and why, for the run's record, when the recall said why. */
4261
+ function recalledOf(request) {
4262
+ const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
4263
+ return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
4264
+ clarity,
4265
+ turn,
4266
+ text,
4267
+ why
4268
+ })) };
4269
+ }
4270
+ const ANSWER_SCHEMA = {
4271
+ type: "object",
4272
+ properties: { answer: {
4273
+ type: "string",
4274
+ description: "The answer to the player, in plain words, in a few sentences."
4275
+ } },
4276
+ required: ["answer"],
4277
+ additionalProperties: false
4278
+ };
4279
+ /**
4280
+ * Answers a player's question as an agent that has only what the player's character is given when it acts: the character sheet is left out and nothing the
4281
+ * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
4282
+ */
4283
+ function answerRunner(deps) {
4284
+ return async (request, signal) => {
4285
+ const brief = deps.boundaries().characterContext.brief(request);
4286
+ return (await runChild({
4287
+ parent: deps.parent,
4288
+ signal,
4289
+ sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
4290
+ ...childModel(deps.store.settings(), "records"),
4291
+ trace: childTrace(deps.store, "records", "answer to the player"),
4292
+ reasoningEffort: deps.store.settings().reasoning.children,
4293
+ persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
4294
+ prompt: brief.prompt,
4295
+ tools: [],
4296
+ maxCalls: 3,
4297
+ result: ANSWER_SCHEMA
4298
+ })).answer;
4299
+ };
4300
+ }
4301
+ // src/shared/dream.ts
4302
+ /** The dream a player asks to enter (`/dream`, `/dream Clara`, `/dream 做梦的人`), or nothing when the message does not start with `/dream`. `who` is empty when no one is named. */
4303
+ function parseDream(text) {
4304
+ const value = text.trimStart();
4305
+ if (value.slice(0, 6).toLowerCase() !== "/dream" || value.length > 6 && !/\s/u.test(value[6])) return void 0;
4306
+ return { who: value.slice(6).trim() };
4307
+ }
4308
+ // src/shared/roll.ts
4309
+ /** The roll in a player's message, or nothing when the message does not start with `/roll`. The notation may be empty, and is then refused. */
4310
+ function parseRoll(text) {
4311
+ const value = text.trimStart();
4312
+ if (value.slice(0, 5).toLowerCase() !== "/roll" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
4313
+ const body = value.slice(5).trimStart();
4314
+ const boundary = body.search(/\s/u);
4315
+ return boundary < 0 ? {
4316
+ expression: body,
4317
+ reason: ""
4318
+ } : {
4319
+ expression: body.slice(0, boundary),
4320
+ reason: body.slice(boundary).trim()
4321
+ };
4322
+ }
4323
+ // src/shared/wait.ts
4324
+ const UNITS = [
4325
+ [/^(?:m|min|mins|minute|minutes|分钟|分)$/iu, 1],
4326
+ [/^(?:h|hr|hrs|hour|hours|小时|時間|时)$/iu, 60],
4327
+ [/^(?:d|day|days|天|日)$/iu, 1440]
4328
+ ];
4329
+ /**
4330
+ * The wait in a player's message (`/wait 2 hours`, `/wait 30m until the ferry`, `/wait 3天`), or nothing when the message does not start with `/wait`. The time may be missing or
4331
+ * unreadable, and is then `undefined` in `minutes`.
4332
+ */
4333
+ function parseWait(text) {
4334
+ const value = text.trimStart();
4335
+ if (value.slice(0, 5).toLowerCase() !== "/wait" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
4336
+ const body = value.slice(5).trim();
4337
+ const match = /^(\d+(?:\.\d+)?)\s*([\p{L}]+)\s*(.*)$/su.exec(body);
4338
+ if (match === null) return {
4339
+ minutes: void 0,
4340
+ reason: body
4341
+ };
4342
+ const unit = UNITS.find(([pattern]) => pattern.test(match[2]));
4343
+ if (unit === void 0) return {
4344
+ minutes: void 0,
4345
+ reason: body
4346
+ };
4347
+ const minutes = Math.round(Number(match[1]) * unit[1]);
4348
+ return {
4349
+ minutes: minutes >= 1 && minutes <= 525600 ? minutes : void 0,
4350
+ reason: match[3].trim()
4351
+ };
4352
+ }
4353
+ // src/host/agents/repeat-guard.ts
4354
+ /**
4355
+ * Keeps an agent that is stuck from making the same call again and again (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one
4356
+ * refused round resolution): past `limit` identical calls in one turn the call is refused with a word that sends it on, and when it goes on regardless the turn is ended. The count starts over at the first step of every turn.
4357
+ * @param languageOf the language of the chat the call belongs to, or nothing when the guard does not apply to it.
4358
+ */
4359
+ function guardRepeatedCalls(ctx, languageOf, limit) {
4360
+ const calls = /* @__PURE__ */ new Map();
4361
+ ctx.on("agent/pre-step", async (payload, next) => {
4362
+ if (payload.step === 1) calls.delete(payload.agent.session.id);
4363
+ return await next();
4364
+ });
4365
+ ctx.on("tools/pre-execute", async (exec, next) => {
4366
+ const chat = exec.agent?.session.id;
4367
+ const language = chat === void 0 || exec.agent?.session.header.origin === "subagent" ? void 0 : languageOf(exec);
4368
+ if (chat === void 0 || language === void 0) return await next();
4369
+ const signature = `${exec.name}:${JSON.stringify(exec.arguments)}`;
4370
+ const seen = calls.get(chat) ?? /* @__PURE__ */ new Map();
4371
+ calls.set(chat, seen);
4372
+ const count = (seen.get(signature) ?? 0) + 1;
4373
+ seen.set(signature, count);
4374
+ if (count <= limit) return await next();
4375
+ if (count > limit + 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
4376
+ return {
4377
+ kind: "deny",
4378
+ reason: translator(languageOf$1(language))("This exact call was already made {count} times in this turn with the same result. Do not repeat it: go on with the next step, or finish and say what is left.", { count: count - 1 })
4379
+ };
4380
+ }, { prepend: true });
4381
+ }
4382
+ // src/host/orchestration/runaway.ts
4383
+ /** The levels of thinking that mean none, as models name them. */
4384
+ const NONE = [
4385
+ "off",
4386
+ "none",
4387
+ "minimal"
4388
+ ];
4389
+ /**
4390
+ * A game master whose thinking ran on to the end of its output limit (found live: 12000 tokens, two and a half minutes, and a turn that ended without output) is asked to answer
4391
+ * without thinking for the rest of the turn, when its model offers that. The level it was on is put back at the first step of the next turn.
4392
+ */
4393
+ var RunawayThinking = class {
4394
+ before = /* @__PURE__ */ new Map();
4395
+ /** To be called before each step of a chat's game master. */
4396
+ async step(chat, agent, step) {
4397
+ const earlier = this.before.get(chat);
4398
+ if (earlier !== void 0 && step === 1) {
4399
+ agent.model.select(earlier);
4400
+ this.before.delete(chat);
4401
+ return;
4402
+ }
4403
+ if (step === 1 || earlier !== void 0 || !cutOff(agent)) return;
4404
+ const current = agent.model.current();
4405
+ if (current === void 0) return;
4406
+ const level = (await agent.ctx.llm.resolveModelInfo(current.provider, current.model, new AbortController().signal).catch(() => void 0))?.reasoning?.efforts.find((effort) => NONE.includes(effort.id));
4407
+ if (level === void 0 || current.reasoningEffort === level.id) return;
4408
+ this.before.set(chat, current);
4409
+ agent.model.select({
4410
+ ...current,
4411
+ reasoningEffort: ReasoningEffortId(level.id)
4412
+ });
4413
+ }
4414
+ };
4144
4415
  // src/host/orchestration/hooks.ts
4416
+ /** DSH's file tools that a story may give its game master. */
4417
+ const FILE_TOOLS = [
4418
+ "read",
4419
+ "read_image",
4420
+ "write",
4421
+ "edit",
4422
+ "glob",
4423
+ "grep",
4424
+ "apply_patch"
4425
+ ];
4145
4426
  const notice = (text) => createUserMessage({
4146
4427
  content: [{
4147
4428
  type: "text",
@@ -4221,6 +4502,42 @@ function installHooks(ctx, deps) {
4221
4502
  }))];
4222
4503
  };
4223
4504
  const runaway = new RunawayThinking();
4505
+ const turns = deps.traces ?? new TurnTraces(() => tracerOf(ctx));
4506
+ engine.observe = (chat, round) => {
4507
+ const span = turns.child(chat, {
4508
+ name: round.attempt === 1 ? "round" : "round (retry)",
4509
+ kind: "span",
4510
+ input: {
4511
+ characters: round.characters,
4512
+ ...round.away ? { away: true } : {}
4513
+ },
4514
+ metadata: {
4515
+ turn: round.turn,
4516
+ attempt: round.attempt
4517
+ }
4518
+ });
4519
+ return (result) => {
4520
+ if (span === void 0) return;
4521
+ if (result instanceof Error) {
4522
+ span.end({
4523
+ level: "ERROR",
4524
+ statusMessage: result.message
4525
+ });
4526
+ return;
4527
+ }
4528
+ span.end({ output: {
4529
+ acted: result.reports.map((report) => ({
4530
+ character: report.name,
4531
+ intent: report.intent,
4532
+ commitment: report.commitment
4533
+ })),
4534
+ failed: result.failures.map((failure) => ({
4535
+ character: failure.name,
4536
+ reason: failure.reason
4537
+ }))
4538
+ } });
4539
+ };
4540
+ };
4224
4541
  guardRepeatedCalls(ctx, (exec) => {
4225
4542
  const owner = exec.agent === void 0 ? void 0 : ownerOf(exec.agent, 0);
4226
4543
  return owner === void 0 ? void 0 : stores(owner.chat)?.settings().prompts.language;
@@ -4235,6 +4552,7 @@ function installHooks(ctx, deps) {
4235
4552
  ctx.on("session/event", (session, event) => {
4236
4553
  if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
4237
4554
  ctx.roleplayOrchestration.recovery.clear(session.id);
4555
+ turns.end(session.id);
4238
4556
  timelines.ended(session.id, session, event.seq);
4239
4557
  const events = session.snapshotEvents();
4240
4558
  const began = events.findLastIndex((entry) => entry.type === "turn/start");
@@ -4293,11 +4611,13 @@ function installHooks(ctx, deps) {
4293
4611
  if (!store.settings().background.concurrent) await engine.quiesce(owner.chat, { skipOptional: true });
4294
4612
  await ctx.roleplayOrchestration.unitFree(owner.chat);
4295
4613
  const began = await timelines.begin(owner.chat, payload.turn, text);
4614
+ turns.begin(owner.chat, payload.turn, text);
4296
4615
  deps.rolls?.begin(owner.chat, store.story.metadata.get().id, began.parent);
4297
4616
  const cast = store.cast();
4298
4617
  const ooc = parseOoc(text);
4299
4618
  const command = ooc === void 0 ? /^\/([\p{L}\p{N}_]+)/u.exec(text.trim())?.[1] : void 0;
4300
4619
  const used = store.raiseCommand?.(command, payload.turn);
4620
+ const dream = ooc === void 0 ? parseDream(text) : void 0;
4301
4621
  const verdict = ooc === void 0 ? boundaries().inputValidator.validate({
4302
4622
  text,
4303
4623
  turn: payload.turn,
@@ -4305,7 +4625,7 @@ function installHooks(ctx, deps) {
4305
4625
  }) : { ok: true };
4306
4626
  if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
4307
4627
  else if (ooc === void 0) {
4308
- engine.expectJudgement(owner);
4628
+ if (dream === void 0) engine.expectJudgement(owner);
4309
4629
  engine.noteInput(owner, text);
4310
4630
  }
4311
4631
  const queryVector = await store.queryVector(ooc?.request ?? text);
@@ -4317,6 +4637,7 @@ function installHooks(ctx, deps) {
4317
4637
  name: move.name,
4318
4638
  place: move.to
4319
4639
  })));
4640
+ const arrived = store.autonomy?.inbox() ?? [];
4320
4641
  const world = {
4321
4642
  happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
4322
4643
  names: cue.names.join(tr(" and ")),
@@ -4372,9 +4693,13 @@ function installHooks(ctx, deps) {
4372
4693
  }), ...commandBringsPeopleIn(store, used) ? [tr("The world itself brings in anyone this command calls for, after this turn: do not make them up yourself with expand_world.")] : []].join(" "));
4373
4694
  if (pacing !== void 0) addLine("pacing", describePacingAdvice(pacing));
4374
4695
  else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) addLine("pacing", store.text("roleplay/plot-hint"));
4696
+ const filing = FILE_TOOLS.some((name) => externalEnabled(store.settings().tools, "gameMaster", name)) ? await deps.folders?.(owner.chat) : void 0;
4697
+ const folderLine = filing === void 0 ? void 0 : foldersLine(filing, languageOf$1(store.settings().prompts.language) === "zh" ? "zh" : "en");
4698
+ if (folderLine !== void 0) addLine("folders", folderLine);
4699
+ if (arrived.length > 0) addLine("messages", tr("While the player was away, these messages reached their character, who has read them: {messages}. Refer to them only if the player does.", { messages: arrived.map((message) => `${message.name}: "${message.text}"`).join(" ") }));
4375
4700
  const rules = store.rules();
4376
4701
  if (rules.length > 0) addLine("rules", store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
4377
- const wanted = ooc === void 0 ? parseRoll(text) : void 0;
4702
+ const wanted = ooc === void 0 && dream === void 0 ? parseRoll(text) : void 0;
4378
4703
  if (wanted !== void 0) try {
4379
4704
  const made = rollPlain(wanted.expression, deps.rolls?.roller(owner.chat));
4380
4705
  const roll = store.story.dice.record({
@@ -4398,18 +4723,81 @@ function installHooks(ctx, deps) {
4398
4723
  engine.skip(owner);
4399
4724
  lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
4400
4725
  }
4401
- const waiting = ooc === void 0 && wanted === void 0 ? parseWait(text) : void 0;
4726
+ if (dream !== void 0) {
4727
+ const sleepers = store.sleepers(payload.turn);
4728
+ const wantedName = dream.who.toLowerCase();
4729
+ const found = wantedName === "" ? sleepers.length === 1 ? sleepers : [] : sleepers.filter((entry) => entry.key.toLowerCase() === wantedName || [entry.name, ...entry.aliases ?? []].some((name) => name.toLowerCase().includes(wantedName)));
4730
+ const refusal = !store.settings().schedule.enabled ? tr("this chat keeps no days for its characters, so nobody sleeps and there is no dream to enter") : sleepers.length === 0 ? tr("nobody is asleep, so there is no dream to enter") : found.length === 0 ? tr("say whose dream: {names}", { names: sleepers.map((entry) => entry.name).join(tr(", ")) }) : found.length > 1 ? tr("more than one is asleep ({names}): say whose dream", { names: found.map((entry) => entry.name).join(tr(", ")) }) : void 0;
4731
+ if (refusal !== void 0) {
4732
+ engine.skip(owner);
4733
+ lines.push(store.text("roleplay/input-refused", { reason: refusal }));
4734
+ } else {
4735
+ const sleeper = found[0];
4736
+ engine.beginDream(owner, sleeper.key, tr("You are asleep and the player's character has come into your dream. Say what the dream holds."));
4737
+ const report = await engine.dream(owner, characterRunner({
4738
+ parent: payload.agent,
4739
+ boundaries,
4740
+ store
4741
+ }));
4742
+ const asked = report === void 0 ? tr("Ask {name} (activate_characters with only {key}; the sleeper stays asleep and needs no wakes) what the dream holds, then narrate it.", {
4743
+ name: sleeper.name,
4744
+ key: sleeper.key
4745
+ }) : tr("{name} has already been asked and answered from the dream: intent \"{intent}\"{said}. Ask nobody and call no tool but narrate, with narration segments only, and put what {name} says in the narration.", {
4746
+ name: sleeper.name,
4747
+ intent: report.intent,
4748
+ said: report.utterance === void 0 || report.utterance === "" ? "" : tr(", said \"{text}\"", { text: report.utterance })
4749
+ });
4750
+ addLine("dream", store.text("roleplay/dream", {
4751
+ name: sleeper.name,
4752
+ key: sleeper.key,
4753
+ asked
4754
+ }));
4755
+ }
4756
+ }
4757
+ const waiting = ooc === void 0 && wanted === void 0 && dream === void 0 ? parseWait(text) : void 0;
4402
4758
  if (waiting !== void 0) {
4403
4759
  const clock = store.settings().clock;
4404
4760
  const refusal = clock.mode === "real" ? tr("this chat follows the clock on the wall, so time cannot be skipped") : waiting.minutes === void 0 ? tr("say how long, for example /wait 2 hours or /wait 30 minutes until the ferry") : waiting.minutes > clock.maxSkipDays * 1440 ? tr("that is more than the {days} days this chat allows in one skip", { days: clock.maxSkipDays }) : void 0;
4405
4761
  if (refusal !== void 0) {
4406
4762
  engine.skip(owner);
4407
4763
  lines.push(store.text("roleplay/input-refused", { reason: refusal }));
4408
- } else addLine("wait", tr("The player lets {minutes} minutes pass{reason}. Move the story's time on by that much with advance_time, and let the world move meanwhile as it would: characters keep to their days, and you ask only those the time reaches. Stop sooner, at the moment it happens, if something comes up that the player must decide or could not sleep through, say what, and let the player act. Then narrate what the player perceived in the time that passed. You may play at most {rounds} rounds for this.", {
4409
- minutes: waiting.minutes,
4410
- reason: waiting.reason === "" ? "" : ` (${waiting.reason})`,
4411
- rounds: store.settings().maxRounds
4412
- }));
4764
+ } else {
4765
+ const reason = waiting.reason === "" ? "" : ` (${waiting.reason})`;
4766
+ const language = languageOf$1(store.settings().prompts.language) === "zh" ? "zh" : "en";
4767
+ const skipped = (() => {
4768
+ try {
4769
+ return engine.advanceTime(owner, {
4770
+ byMinutes: waiting.minutes,
4771
+ reason: waiting.reason === "" ? tr("time passes") : waiting.reason
4772
+ });
4773
+ } catch {
4774
+ return;
4775
+ }
4776
+ })();
4777
+ if (skipped === void 0) addLine("wait", tr("The player lets {minutes} minutes pass{reason}. Move the story's time on by that much with advance_time, and let the world move meanwhile as it would: characters keep to their days, and you ask only those the time reaches. Stop sooner, at the moment it happens, if something comes up that the player must decide or could not sleep through, say what, and let the player act. Then narrate what the player perceived in the time that passed. You may play at most {rounds} rounds for this.", {
4778
+ minutes: waiting.minutes,
4779
+ reason,
4780
+ rounds: store.settings().maxRounds
4781
+ }));
4782
+ else {
4783
+ const moved = skipped.moved.map((move) => tr("{name} went to {place}.", {
4784
+ name: move.name,
4785
+ place: move.to
4786
+ })).join(" ");
4787
+ const happened = skipped.world.flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
4788
+ names: cue.names.join(tr(" and ")),
4789
+ text: cue.text
4790
+ }))]).join(" ");
4791
+ addLine("wait", tr("The player let {minutes} minutes pass{reason}, and the story's time has already been moved on to {now}: do not call advance_time for it. {moved}{happened}Narrate what the player perceived in that time, in the story's own terms. If something in it would have made the player act or woken them, let it come at the end and stop there. You may play at most {rounds} rounds for this.", {
4792
+ minutes: waiting.minutes,
4793
+ reason,
4794
+ now: describeInstant(skipped.to, skipped.zone, language),
4795
+ moved: moved === "" ? "" : `${moved} `,
4796
+ happened: happened === "" ? "" : `${happened} `,
4797
+ rounds: store.settings().maxRounds
4798
+ }));
4799
+ }
4800
+ }
4413
4801
  }
4414
4802
  if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
4415
4803
  if (ooc !== void 0 && ooc.request === "") {
@@ -4430,6 +4818,6 @@ function installHooks(ctx, deps) {
4430
4818
  };
4431
4819
  });
4432
4820
  }
4433
- export { inheritPrompts as $, plotProgressOf as A, parsePlotsFile as B, readNotes as C, referent as D, sameWords as E, textLanguage as F, readDocument as G, COMMANDS_KEY as H, wrongLanguage as I, errorMessage as J, Reader as K, readUsage as L, LANGUAGE_NAMES as M, STORY_LANGUAGES as N, RESULTS as O, isStoryLanguage as P, copyWorldPrompts as Q, PLOTS_FILE_NAME as R, notesOfSession as S, defaultBoundaries as T, commandFlagKey as U, plotReferenceProblems as V, commandsOf as W, PROMPTS_FOLDER as X, LANGUAGE_FOLDER as Y, PromptLibrary as Z, readTraces as _, COMPARISONS as _t, externalWithheld as a, shippedText as at, readWithdrawn as b, record as c, InvalidWorldError as ct, guardRepeatedCalls as d, SessionNotFoundError as dt, languageOf as et, MAX_OOC_ANSWER as f, WorldNotFoundError as ft, readRunDetail as g, AUTHORING_NEEDS as gt, readActivity as h, zoneOf as ht, externalTools as i, shippedPromptsDirectory as it, populatePlots as j, PLOTS_METADATA_KEY as k, characterRunner as l, ReflectionRefusedError as lt, readDecisionStats as m, describeWhen as mt, installHooks as n, promptProblem as nt, PREVIEW_TOOL as o, AgentUnavailableError as ot, storesOf as p, ClockError as pt, formatIssue as q, externalGiven as r, shippedLanguages as rt, createTools$1 as s, InvalidStartError as st, externalToolLimit as t, listFiles as tt, toolEnabled as u, SessionArchivedError as ut, readVerdicts as v, observeAsPlayer as w, addToNote as x, writeVerdicts as y, loadPlots as z };
4821
+ export { inheritPrompts as $, plotProgressOf as A, parsePlotsFile as B, readNotes as C, referent as D, sameWords as E, textLanguage as F, readDocument as G, COMMANDS_KEY as H, wrongLanguage as I, errorMessage as J, Reader as K, readUsage as L, LANGUAGE_NAMES as M, STORY_LANGUAGES as N, RESULTS as O, isStoryLanguage as P, copyWorldPrompts as Q, PLOTS_FILE_NAME as R, notesOfSession as S, defaultBoundaries as T, commandFlagKey as U, plotReferenceProblems as V, commandsOf as W, PROMPTS_FOLDER as X, LANGUAGE_FOLDER as Y, PromptLibrary as Z, readTraces as _, COMPARISONS as _t, externalGiven as a, shippedText as at, readWithdrawn as b, PREVIEW_TOOL as c, InvalidWorldError as ct, toolEnabled as d, SessionNotFoundError as dt, languageOf as et, MAX_OOC_ANSWER as f, WorldNotFoundError as ft, readRunDetail as g, AUTHORING_NEEDS as gt, readActivity as h, zoneOf as ht, characterRunner as i, shippedPromptsDirectory as it, populatePlots as j, PLOTS_METADATA_KEY as k, createTools$1 as l, ReflectionRefusedError as lt, readDecisionStats as m, describeWhen as mt, installHooks as n, promptProblem as nt, externalTools as o, AgentUnavailableError as ot, storesOf as p, ClockError as pt, formatIssue as q, guardRepeatedCalls as r, shippedLanguages as rt, externalWithheld as s, InvalidStartError as st, externalToolLimit as t, listFiles as tt, record as u, SessionArchivedError as ut, readVerdicts as v, observeAsPlayer as w, addToNote as x, writeVerdicts as y, loadPlots as z };
4434
4822
 
4435
- //# sourceMappingURL=hooks-C2U1-8ur.js.map
4823
+ //# sourceMappingURL=hooks-BNeoGMHZ.js.map