@dsh-agentic-roleplay/core 0.11.1 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/{access-Md1YTSX1.js → access-DifaiHrI.js} +3 -15
- package/lib/{authoring-tools-BFdw7ahj.js → authoring-tools-VOaXzr_R.js} +58 -766
- package/lib/authoring.js +136 -13
- package/lib/{child-C9nPIy9j.js → child-DzZ-aI6k.js} +130 -2
- package/lib/client.js +17093 -2269
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +3 -3
- package/lib/dev-context-Bdm-eVer.js +40 -0
- package/lib/doctor.js +5 -3
- package/lib/{gallery-BWHmjogd.js → gallery-Ctz-UoFk.js} +3 -3
- package/lib/{generator-QCdm8nUh.js → generator-Cv6WWmZT.js} +2 -2
- package/lib/helper.js +15 -1
- package/lib/{hooks-C2U1-8ur.js → hooks-BdR3mBeM.js} +751 -344
- package/lib/images.js +4 -4
- package/lib/index.js +342 -463
- package/lib/jail-Cp4zEfip.js +107 -0
- package/lib/{library-4zmCAshR.js → library-BU2A_Dx8.js} +3 -3
- package/lib/{lorebook-author-tools-Bjfjt3bg.js → lorebook-author-tools-DUKcQu8P.js} +20 -7
- package/lib/lorebook-authoring.js +12 -5
- package/lib/{narration-b_VBEUWn.js → narration-CDsJ5wxH.js} +29 -2
- package/lib/orchestration.js +615 -48
- package/lib/{pack-jail-Ci9bIeDI.js → pack-jail-CzHQu0n3.js} +559 -23
- package/lib/{packs-CYkozh8Q.js → packs-BZ-45J4-.js} +2 -2
- package/lib/{presenter-agent-CqkAL03Q.js → presenter-agent-C2ZkoxZu.js} +9 -9
- package/lib/{preset-B-35yUmt.js → preset-BPnRPW-1.js} +4 -4
- package/lib/{preset-author-tools-BUymqZM5.js → preset-author-tools-DBqPwn-o.js} +9 -8
- package/lib/preset-authoring.js +11 -6
- package/lib/{reflection-B9N0z3KY.js → reflection-Cuy0YLv0.js} +22 -16
- package/lib/{presets-_U-xroo0.js → serial-BZNeK57v.js} +1305 -331
- package/lib/service-mRKwpWjX.js +140 -0
- package/lib/{text-C2AGl7Je.js → text-Dfv8S8eq.js} +27 -2
- package/lib/{turn-guard-C0M3rXEN.js → turn-guard-xaFxYc1T.js} +3 -3
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +34 -34
- package/prompts/en/import/finish-ok.md +1 -1
- package/prompts/en/import/generator.md +1 -1
- package/prompts/en/import/style.md +2 -1
- package/prompts/en/import/variables.md +2 -1
- package/prompts/en/roleplay/character-lookup.md +1 -1
- package/prompts/en/roleplay/decide-errand.md +1 -0
- package/prompts/en/roleplay/decide-message.md +1 -0
- package/prompts/en/roleplay/dream.md +1 -0
- package/prompts/en/roleplay/gate-repeat.md +1 -0
- package/prompts/en/world/procedure.md +1 -1
- package/prompts/zh/import/finish-ok.md +1 -1
- package/prompts/zh/import/generator.md +1 -1
- package/prompts/zh/import/style.md +2 -1
- package/prompts/zh/import/variables.md +2 -1
- package/prompts/zh/roleplay/character-lookup.md +1 -1
- package/prompts/zh/roleplay/decide-errand.md +1 -0
- package/prompts/zh/roleplay/decide-message.md +1 -0
- package/prompts/zh/roleplay/dream.md +1 -0
- package/prompts/zh/roleplay/gate-repeat.md +1 -0
- package/prompts/zh/world/procedure.md +1 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
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-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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-DzZ-aI6k.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-CDsJ5wxH.js";
|
|
3
|
+
import { t as promptFor } from "./access-DifaiHrI.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";
|
|
@@ -248,9 +249,11 @@ function fill(id, text, given, tag) {
|
|
|
248
249
|
return String(value);
|
|
249
250
|
});
|
|
250
251
|
}
|
|
252
|
+
/** Prompt text as it was written: a checkout that writes CRLF must not change what the models are sent. */
|
|
253
|
+
const textOf$1 = (path) => readFileSync(path, "utf8").replaceAll("\r\n", "\n");
|
|
251
254
|
/** A prompt as the package ships it, without a roleplay root: for code that has none, such as tests. */
|
|
252
255
|
function shippedText(id, language = "en", variables = {}) {
|
|
253
|
-
return fill(id,
|
|
256
|
+
return fill(id, textOf$1(join(shippedPromptsDirectory(), language, `${id}.md`)), variables, language);
|
|
254
257
|
}
|
|
255
258
|
function listFiles(directory, prefix = "") {
|
|
256
259
|
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
@@ -292,7 +295,7 @@ var PromptLibrary = class extends Service {
|
|
|
292
295
|
if (!existsSync(this.directory)) return [];
|
|
293
296
|
return readdirSync(this.directory, { withFileTypes: true }).filter((entry) => entry.isDirectory() && LANGUAGE.test(entry.name)).flatMap((entry) => listFiles(join(this.directory, entry.name)).flatMap((id) => {
|
|
294
297
|
const path = join(this.directory, entry.name, `${id}.md`);
|
|
295
|
-
const text =
|
|
298
|
+
const text = textOf$1(path);
|
|
296
299
|
const message = !ID.test(id) || ![entry.name, "en"].some((name) => existsSync(join(this.shipped, name, `${id}.md`))) ? void 0 : text.includes("{{") ? "holds \"{{\", which DSH reads as a variable of its own" : promptProblem(entry.name, id, text, this.shipped);
|
|
297
300
|
return message === void 0 ? [] : [{
|
|
298
301
|
path,
|
|
@@ -308,7 +311,7 @@ var PromptLibrary = class extends Service {
|
|
|
308
311
|
if (!ID.test(id)) throw new Error(`"${id}" is not a prompt id`);
|
|
309
312
|
const tag = languageOf(language);
|
|
310
313
|
const own = session === void 0 ? void 0 : this.override(id, tag, session);
|
|
311
|
-
return fill(id,
|
|
314
|
+
return fill(id, textOf$1(own ?? this.file(id, tag)), variables, tag);
|
|
312
315
|
}
|
|
313
316
|
override(id, language, session) {
|
|
314
317
|
if (!SESSION_ID.test(session)) throw new Error(`"${session}" is not a session id`);
|
|
@@ -707,7 +710,7 @@ function plotReferenceProblems(plots, entities) {
|
|
|
707
710
|
return plots.flatMap((plot) => plot.participants.filter((participant) => !known.has(participant)).map((participant) => `plot "${plot.id}" names unknown participant "${participant}"`));
|
|
708
711
|
}
|
|
709
712
|
// src/host/sessions/usage.ts
|
|
710
|
-
const KEY$
|
|
713
|
+
const KEY$6 = "usage";
|
|
711
714
|
const isCount = (value) => typeof value === "object" && value !== null && [
|
|
712
715
|
"input",
|
|
713
716
|
"cached",
|
|
@@ -716,7 +719,7 @@ const isCount = (value) => typeof value === "object" && value !== null && [
|
|
|
716
719
|
const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
|
|
717
720
|
/** 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
721
|
function readUsage(session) {
|
|
719
|
-
const stored = session.metadata.getValue(KEY$
|
|
722
|
+
const stored = session.metadata.getValue(KEY$6);
|
|
720
723
|
return Array.isArray(stored) ? stored.filter(isUsage) : [];
|
|
721
724
|
}
|
|
722
725
|
/** Adds tokens to a turn's record: the game master's own, or a helper's run. */
|
|
@@ -741,7 +744,7 @@ function addUsage(session, turn, who, tokens, masterMs) {
|
|
|
741
744
|
if (at === -1) all.push(next);
|
|
742
745
|
else all[at] = next;
|
|
743
746
|
all.sort((a, b) => a.turn - b.turn);
|
|
744
|
-
session.metadata.setValue(KEY$
|
|
747
|
+
session.metadata.setValue(KEY$6, all);
|
|
745
748
|
}
|
|
746
749
|
// src/host/translate/language.ts
|
|
747
750
|
const STORY_LANGUAGES = ["en", "zh"];
|
|
@@ -1122,6 +1125,7 @@ function describeAgenda(agenda, now, tr = ENGLISH, language = "en") {
|
|
|
1122
1125
|
until: when(agenda.now.until),
|
|
1123
1126
|
note: agenda.now.interruptible ? "" : tr(" (not something you would drop lightly)")
|
|
1124
1127
|
}));
|
|
1128
|
+
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
1129
|
if (agenda.next !== void 0) lines.push(tr("Your day, next: {activity}{place}, from {from}.", {
|
|
1126
1130
|
activity: agenda.next.activity,
|
|
1127
1131
|
place: at(agenda.next.place),
|
|
@@ -1155,6 +1159,10 @@ function describeSceneAgenda(agenda, now, tr = ENGLISH, language = "en") {
|
|
|
1155
1159
|
activity: move.activity
|
|
1156
1160
|
}))) }));
|
|
1157
1161
|
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}`)) }));
|
|
1162
|
+
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})", {
|
|
1163
|
+
name: `${entry.name} [${entry.key}]`,
|
|
1164
|
+
until: describeWhen(entry.until, now, agenda.zone, language)
|
|
1165
|
+
}))) }));
|
|
1158
1166
|
if (agenda.engagements.length > 0) {
|
|
1159
1167
|
const entries = agenda.engagements.map((engagement) => {
|
|
1160
1168
|
const values = {
|
|
@@ -1282,6 +1290,7 @@ const sharedContext = { brief(request) {
|
|
|
1282
1290
|
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
1291
|
const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now, tr, language);
|
|
1284
1292
|
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")}`);
|
|
1293
|
+
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
1294
|
if (carrying !== void 0 && carrying.length > 0) sections.push(`${tr("What you have on you:")}\n${describeItems(carrying, { withKeys: false }, tr)}`);
|
|
1286
1295
|
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
1296
|
const attitude = describeAttitude(relation, tr);
|
|
@@ -1597,6 +1606,7 @@ const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
|
|
|
1597
1606
|
const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
|
|
1598
1607
|
/** Finds no fault: without a gate the output is delivered as the game master wrote it. */
|
|
1599
1608
|
const tracksNothing = { track: () => Promise.resolve(0) };
|
|
1609
|
+
const keepsNoErrands = { keep: () => Promise.resolve(0) };
|
|
1600
1610
|
const passesEverything = { check: () => Promise.resolve([]) };
|
|
1601
1611
|
/** Finds no broken rule: without a check the game master's judgement of an action stands as it is. */
|
|
1602
1612
|
const breaksNoRule = { check: () => Promise.resolve([]) };
|
|
@@ -1621,6 +1631,7 @@ function defaultBoundaries() {
|
|
|
1621
1631
|
outputGate: passesEverything,
|
|
1622
1632
|
ruleCheck: breaksNoRule,
|
|
1623
1633
|
variableTracker: tracksNothing,
|
|
1634
|
+
errandKeeper: keepsNoErrands,
|
|
1624
1635
|
suggester: offersNothing,
|
|
1625
1636
|
recaller: recordsRecall,
|
|
1626
1637
|
sceneContext: castSummary
|
|
@@ -1659,10 +1670,11 @@ function observeAsPlayer(session, turn) {
|
|
|
1659
1670
|
const NOTE_KINDS = [
|
|
1660
1671
|
"suggestions",
|
|
1661
1672
|
"away",
|
|
1662
|
-
"world"
|
|
1673
|
+
"world",
|
|
1674
|
+
"message"
|
|
1663
1675
|
];
|
|
1664
1676
|
// src/host/sessions/notes.ts
|
|
1665
|
-
const KEY$
|
|
1677
|
+
const KEY$5 = "notes";
|
|
1666
1678
|
const isNote = (value) => {
|
|
1667
1679
|
if (typeof value !== "object" || value === null) return false;
|
|
1668
1680
|
const note = value;
|
|
@@ -1670,12 +1682,12 @@ const isNote = (value) => {
|
|
|
1670
1682
|
};
|
|
1671
1683
|
/** The notes of a session, at most one per kind. */
|
|
1672
1684
|
function readNotes(session) {
|
|
1673
|
-
const stored = session.metadata.getValue(KEY$
|
|
1685
|
+
const stored = session.metadata.getValue(KEY$5);
|
|
1674
1686
|
return Array.isArray(stored) ? stored.filter(isNote) : [];
|
|
1675
1687
|
}
|
|
1676
1688
|
/** Replaces the note of the same kind. */
|
|
1677
1689
|
function putNote(session, note) {
|
|
1678
|
-
session.metadata.setValue(KEY$
|
|
1690
|
+
session.metadata.setValue(KEY$5, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
|
|
1679
1691
|
}
|
|
1680
1692
|
/** The most lines one note keeps: what is past it is not told. */
|
|
1681
1693
|
const MAX_NOTE_LINES = 8;
|
|
@@ -1690,7 +1702,7 @@ function addToNote(session, kind, turn, lines) {
|
|
|
1690
1702
|
}
|
|
1691
1703
|
/** Removes every note: they belong to the turn that made them. */
|
|
1692
1704
|
function clearNotes(session) {
|
|
1693
|
-
if (readNotes(session).length > 0) session.metadata.setValue(KEY$
|
|
1705
|
+
if (readNotes(session).length > 0) session.metadata.setValue(KEY$5, []);
|
|
1694
1706
|
}
|
|
1695
1707
|
/**
|
|
1696
1708
|
* The notes of a session, for the player's screen.
|
|
@@ -1751,10 +1763,10 @@ function masterTrace(events) {
|
|
|
1751
1763
|
};
|
|
1752
1764
|
}
|
|
1753
1765
|
// src/host/triggers/deliver.ts
|
|
1754
|
-
const KEY$
|
|
1766
|
+
const KEY$4 = "triggers.withdrawn";
|
|
1755
1767
|
/** Why a note was withdrawn instead of told, by the number of the note. */
|
|
1756
1768
|
function readWithdrawn(session) {
|
|
1757
|
-
const stored = session.metadata.getValue(KEY$
|
|
1769
|
+
const stored = session.metadata.getValue(KEY$4);
|
|
1758
1770
|
if (!Array.isArray(stored)) return {};
|
|
1759
1771
|
return Object.fromEntries(stored.flatMap((entry) => {
|
|
1760
1772
|
const { note, reason } = entry ?? {};
|
|
@@ -1773,7 +1785,7 @@ function deliverNow(session, notes, clock) {
|
|
|
1773
1785
|
note: Number(note),
|
|
1774
1786
|
reason
|
|
1775
1787
|
}));
|
|
1776
|
-
session.metadata.setValue(KEY$
|
|
1788
|
+
session.metadata.setValue(KEY$4, [...before, ...withdrawn.map(({ note, reason }) => ({
|
|
1777
1789
|
note: note.id,
|
|
1778
1790
|
reason
|
|
1779
1791
|
}))].slice(-100));
|
|
@@ -1784,9 +1796,9 @@ function deliverNow(session, notes, clock) {
|
|
|
1784
1796
|
}));
|
|
1785
1797
|
}
|
|
1786
1798
|
// src/host/triggers/judged.ts
|
|
1787
|
-
const KEY$
|
|
1799
|
+
const KEY$3 = "triggers.judged";
|
|
1788
1800
|
function readVerdicts(session) {
|
|
1789
|
-
const stored = session.metadata.getValue(KEY$
|
|
1801
|
+
const stored = session.metadata.getValue(KEY$3);
|
|
1790
1802
|
if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
|
|
1791
1803
|
const verdicts = {};
|
|
1792
1804
|
for (const [statement, value] of Object.entries(stored)) {
|
|
@@ -1800,7 +1812,7 @@ function readVerdicts(session) {
|
|
|
1800
1812
|
}
|
|
1801
1813
|
/** 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
1814
|
function writeVerdicts(session, verdicts, keep) {
|
|
1803
|
-
session.metadata.setValue(KEY$
|
|
1815
|
+
session.metadata.setValue(KEY$3, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
|
|
1804
1816
|
}
|
|
1805
1817
|
/** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
|
|
1806
1818
|
const verdictReader = (session) => {
|
|
@@ -1934,11 +1946,11 @@ function noteStore(session, settings, clock) {
|
|
|
1934
1946
|
};
|
|
1935
1947
|
}
|
|
1936
1948
|
// src/host/sessions/trace.ts
|
|
1937
|
-
const KEY$
|
|
1949
|
+
const KEY$2 = "trace";
|
|
1938
1950
|
const isTrace = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.startedAt === "number";
|
|
1939
1951
|
/** 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
1952
|
function readTraces(session) {
|
|
1941
|
-
const stored = session.metadata.getValue(KEY$
|
|
1953
|
+
const stored = session.metadata.getValue(KEY$2);
|
|
1942
1954
|
return Array.isArray(stored) ? stored.filter(isTrace) : [];
|
|
1943
1955
|
}
|
|
1944
1956
|
/** 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 +1969,10 @@ function updateTrace(session, turn, patch, merge) {
|
|
|
1957
1969
|
if (at === -1) all.push(next);
|
|
1958
1970
|
else all[at] = next;
|
|
1959
1971
|
all.sort((a, b) => a.turn - b.turn);
|
|
1960
|
-
session.metadata.setValue(KEY$
|
|
1972
|
+
session.metadata.setValue(KEY$2, all.slice(-30));
|
|
1961
1973
|
}
|
|
1962
1974
|
// src/host/sessions/activity.ts
|
|
1963
|
-
const KEY = "activity";
|
|
1975
|
+
const KEY$1 = "activity";
|
|
1964
1976
|
const isEntry = (value) => {
|
|
1965
1977
|
if (typeof value !== "object" || value === null) return false;
|
|
1966
1978
|
const entry = value;
|
|
@@ -1968,13 +1980,13 @@ const isEntry = (value) => {
|
|
|
1968
1980
|
};
|
|
1969
1981
|
/** The recorded runs, oldest first. */
|
|
1970
1982
|
function readActivity(session) {
|
|
1971
|
-
const stored = session.metadata.getValue(KEY);
|
|
1983
|
+
const stored = session.metadata.getValue(KEY$1);
|
|
1972
1984
|
return Array.isArray(stored) ? stored.filter(isEntry) : [];
|
|
1973
1985
|
}
|
|
1974
1986
|
/** Files the run and returns the runs that fell off the end of the record to make room. */
|
|
1975
1987
|
function recordActivity(session, entry) {
|
|
1976
1988
|
const all = [...readActivity(session), entry];
|
|
1977
|
-
session.metadata.setValue(KEY, all.slice(-60));
|
|
1989
|
+
session.metadata.setValue(KEY$1, all.slice(-60));
|
|
1978
1990
|
return all.slice(0, -60);
|
|
1979
1991
|
}
|
|
1980
1992
|
const RUN_FOLDER = "activity";
|
|
@@ -2056,11 +2068,76 @@ function recordDecisions(folder, site, report, now = () => /* @__PURE__ */ new D
|
|
|
2056
2068
|
writeFileSync(aside, JSON.stringify(stats, null, 2));
|
|
2057
2069
|
renameSync(aside, target);
|
|
2058
2070
|
}
|
|
2071
|
+
// src/host/sessions/autonomy.ts
|
|
2072
|
+
const KEY = "autonomy";
|
|
2073
|
+
const isMessage = (value) => {
|
|
2074
|
+
const entry = value;
|
|
2075
|
+
return typeof entry === "object" && entry !== null && typeof entry["at"] === "number" && typeof entry["character"] === "string" && typeof entry["name"] === "string" && typeof entry["text"] === "string";
|
|
2076
|
+
};
|
|
2077
|
+
function readAutonomy(session) {
|
|
2078
|
+
const stored = session.metadata.getValue(KEY);
|
|
2079
|
+
const sent = typeof stored?.sent === "object" && stored.sent !== null && !Array.isArray(stored.sent) ? Object.fromEntries(Object.entries(stored.sent).filter(([, value]) => typeof value === "number")) : {};
|
|
2080
|
+
return {
|
|
2081
|
+
unanswered: typeof stored?.unanswered === "number" ? stored.unanswered : 0,
|
|
2082
|
+
sent,
|
|
2083
|
+
inbox: Array.isArray(stored?.inbox) ? stored.inbox.filter(isMessage) : []
|
|
2084
|
+
};
|
|
2085
|
+
}
|
|
2086
|
+
/** A character wrote to the player: it counts as one more thing done without a reply, and waits to be told to the story. */
|
|
2087
|
+
function recordMessage(session, message) {
|
|
2088
|
+
const state = readAutonomy(session);
|
|
2089
|
+
const next = {
|
|
2090
|
+
unanswered: state.unanswered + 1,
|
|
2091
|
+
sent: {
|
|
2092
|
+
...state.sent,
|
|
2093
|
+
[message.character]: message.at
|
|
2094
|
+
},
|
|
2095
|
+
inbox: [...state.inbox, message].slice(-20)
|
|
2096
|
+
};
|
|
2097
|
+
session.metadata.setValue(KEY, next);
|
|
2098
|
+
return next;
|
|
2099
|
+
}
|
|
2100
|
+
/** A character was asked whether it wants to write and did not: it is not asked again until the gap has passed. */
|
|
2101
|
+
function recordAsk(session, character, at) {
|
|
2102
|
+
const state = readAutonomy(session);
|
|
2103
|
+
session.metadata.setValue(KEY, {
|
|
2104
|
+
...state,
|
|
2105
|
+
sent: {
|
|
2106
|
+
...state.sent,
|
|
2107
|
+
[character]: at
|
|
2108
|
+
}
|
|
2109
|
+
});
|
|
2110
|
+
}
|
|
2111
|
+
/** The player wrote: what the story was not told of yet, and the count of things done without a reply starts again. */
|
|
2112
|
+
function takeInbox(session) {
|
|
2113
|
+
const state = readAutonomy(session);
|
|
2114
|
+
if (state.inbox.length === 0 && state.unanswered === 0) return [];
|
|
2115
|
+
session.metadata.setValue(KEY, {
|
|
2116
|
+
...state,
|
|
2117
|
+
unanswered: 0,
|
|
2118
|
+
inbox: []
|
|
2119
|
+
});
|
|
2120
|
+
return state.inbox;
|
|
2121
|
+
}
|
|
2122
|
+
/** When the player last played: the last turn, or the start of a story not yet played. */
|
|
2123
|
+
function lastPlayerAt(session) {
|
|
2124
|
+
const { lastPlayedAt, createdAt } = session.metadata.get();
|
|
2125
|
+
const at = Date.parse(lastPlayedAt ?? createdAt);
|
|
2126
|
+
return Number.isNaN(at) ? void 0 : at;
|
|
2127
|
+
}
|
|
2059
2128
|
// src/host/clock/agenda.ts
|
|
2060
2129
|
const CURSOR = "agenda.cursor";
|
|
2061
2130
|
const ASKED = "agenda.asked";
|
|
2062
2131
|
/** 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
2132
|
const TRAVEL = "agenda.travel";
|
|
2133
|
+
/** 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). */
|
|
2134
|
+
const SHIFTED = "agenda.shifted";
|
|
2135
|
+
/** 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. */
|
|
2136
|
+
const HOLDS = "agenda.holds";
|
|
2137
|
+
/** The longest a character stays where the story left it waiting for the player. */
|
|
2138
|
+
const PLAYER_HOLD_CAP = 1440 * MINUTE;
|
|
2139
|
+
/** How long a character that no window bounds is held when nothing says. */
|
|
2140
|
+
const DEFAULT_HOLD = 60 * MINUTE;
|
|
2064
2141
|
/** At most this many characters are asked to be given a day at a time, so that it never floods the world author. */
|
|
2065
2142
|
const MAX_ASKED = 3;
|
|
2066
2143
|
/** How far ahead the characters are told about what comes next in their day. */
|
|
@@ -2068,6 +2145,65 @@ const NEXT_HORIZON = 240 * MINUTE;
|
|
|
2068
2145
|
/** What a character is shown of its own agenda at most. */
|
|
2069
2146
|
const SHOWN_ENGAGEMENTS = 4;
|
|
2070
2147
|
const SHOWN_GOALS = 3;
|
|
2148
|
+
const readHolds = (session) => {
|
|
2149
|
+
const stored = session.metadata.getValue(HOLDS);
|
|
2150
|
+
return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
|
|
2151
|
+
};
|
|
2152
|
+
/** Whether the story has taken a character off its day for now. */
|
|
2153
|
+
function isHeld(session, characterId, now) {
|
|
2154
|
+
const hold = readHolds(session)[characterId];
|
|
2155
|
+
return hold !== void 0 && now < hold.until;
|
|
2156
|
+
}
|
|
2157
|
+
/**
|
|
2158
|
+
* 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
|
|
2159
|
+
* `minutes` are over, or when that is not said before its day next changes, and it takes its day up again then.
|
|
2160
|
+
*/
|
|
2161
|
+
function holdCharacter(session, characterId, zone, now, minutes, untilPlayer = false) {
|
|
2162
|
+
const windows = session.routines.list(characterId);
|
|
2163
|
+
const current = occurrenceAt(windows, now, zone);
|
|
2164
|
+
const next = current === void 0 ? nextOccurrence(windows, now, zone, 1440 * MINUTE) : void 0;
|
|
2165
|
+
const until = untilPlayer ? now + PLAYER_HOLD_CAP : minutes !== void 0 ? now + minutes * MINUTE : current?.endsAt ?? next?.startsAt ?? now + DEFAULT_HOLD;
|
|
2166
|
+
const holds = readHolds(session);
|
|
2167
|
+
const kept = holds[characterId];
|
|
2168
|
+
const live = kept !== void 0 && now < kept.until;
|
|
2169
|
+
const end = Math.max(until, live ? kept.until : -Infinity, now + MINUTE);
|
|
2170
|
+
const waiting = untilPlayer || live && kept.untilPlayer !== void 0;
|
|
2171
|
+
holds[characterId] = {
|
|
2172
|
+
since: live ? kept.since : now,
|
|
2173
|
+
until: end,
|
|
2174
|
+
...waiting ? { untilPlayer: live && kept.untilPlayer !== void 0 ? kept.untilPlayer : { apart: false } } : {}
|
|
2175
|
+
};
|
|
2176
|
+
session.metadata.setValue(HOLDS, holds);
|
|
2177
|
+
const stored = session.metadata.getValue(TRAVEL);
|
|
2178
|
+
if (typeof stored === "object" && stored !== null && !Array.isArray(stored) && String(characterId) in stored) {
|
|
2179
|
+
const { [String(characterId)]: _gone, ...rest } = stored;
|
|
2180
|
+
session.metadata.setValue(TRAVEL, rest);
|
|
2181
|
+
}
|
|
2182
|
+
return end;
|
|
2183
|
+
}
|
|
2184
|
+
/** 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. */
|
|
2185
|
+
function sleepingNow(session, characterId, zone, now) {
|
|
2186
|
+
const character = session.characters.get(characterId);
|
|
2187
|
+
if (character === void 0 || character.control === "player" || isHeld(session, characterId, now)) return void 0;
|
|
2188
|
+
const current = occurrenceAt(session.routines.list(characterId), now, zone);
|
|
2189
|
+
if (current?.window.sleep !== true) return void 0;
|
|
2190
|
+
const here = session.placements.get("character", characterId);
|
|
2191
|
+
if (current.window.locationId !== void 0 && here?.locationId !== current.window.locationId) return void 0;
|
|
2192
|
+
return { until: current.endsAt };
|
|
2193
|
+
}
|
|
2194
|
+
/** Everyone asleep now. */
|
|
2195
|
+
function sleepersNow(session, zone, now) {
|
|
2196
|
+
return session.characters.list().flatMap((character) => {
|
|
2197
|
+
const asleep = sleepingNow(session, character.id, zone, now);
|
|
2198
|
+
return asleep === void 0 ? [] : [{
|
|
2199
|
+
character: character.id,
|
|
2200
|
+
key: keyOfCharacter$1(character),
|
|
2201
|
+
name: character.name,
|
|
2202
|
+
aliases: character.aliases,
|
|
2203
|
+
until: asleep.until
|
|
2204
|
+
}];
|
|
2205
|
+
});
|
|
2206
|
+
}
|
|
2071
2207
|
const keyOfCharacter$1 = (character) => character.sourceId ?? String(character.id);
|
|
2072
2208
|
/**
|
|
2073
2209
|
* 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 +2218,11 @@ function catchUpRoutines(session, zone, now, turn, ask) {
|
|
|
2082
2218
|
const player = session.characters.list().find((character) => character.control === "player");
|
|
2083
2219
|
const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
|
|
2084
2220
|
const moves = [];
|
|
2221
|
+
const shifted = /* @__PURE__ */ new Set();
|
|
2085
2222
|
const stored = session.metadata.getValue(TRAVEL);
|
|
2086
2223
|
const journeys = typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
|
|
2087
2224
|
const arrive = (character, target) => {
|
|
2225
|
+
if (cursor !== void 0) shifted.add(keyOfCharacter$1(character));
|
|
2088
2226
|
if (target.locationId !== void 0) {
|
|
2089
2227
|
session.move(character.id, {
|
|
2090
2228
|
to: target.locationId,
|
|
@@ -2101,6 +2239,7 @@ function catchUpRoutines(session, zone, now, turn, ask) {
|
|
|
2101
2239
|
}
|
|
2102
2240
|
if (session.characterStates.get(character.id)?.activity !== target.activity) session.characterStates.update(character.id, { activity: target.activity });
|
|
2103
2241
|
};
|
|
2242
|
+
const holds = readHolds(session);
|
|
2104
2243
|
const alreadyAsked = new Set(Array.isArray(session.metadata.getValue(ASKED)) ? session.metadata.getValue(ASKED) : []);
|
|
2105
2244
|
const asked = [];
|
|
2106
2245
|
for (const character of session.characters.list()) {
|
|
@@ -2121,6 +2260,18 @@ function catchUpRoutines(session, zone, now, turn, ask) {
|
|
|
2121
2260
|
}
|
|
2122
2261
|
continue;
|
|
2123
2262
|
}
|
|
2263
|
+
const held = holds[characterId];
|
|
2264
|
+
let rejoin = false;
|
|
2265
|
+
if (held !== void 0) {
|
|
2266
|
+
if (held.untilPlayer !== void 0 && now < held.until) {
|
|
2267
|
+
if (away) held.untilPlayer.apart = true;
|
|
2268
|
+
else if (held.untilPlayer.apart) delete holds[characterId];
|
|
2269
|
+
continue;
|
|
2270
|
+
}
|
|
2271
|
+
if (now < held.until) continue;
|
|
2272
|
+
delete holds[characterId];
|
|
2273
|
+
rejoin = true;
|
|
2274
|
+
}
|
|
2124
2275
|
if (!away) continue;
|
|
2125
2276
|
const current = occurrenceAt(window, now, zone);
|
|
2126
2277
|
const journey = journeys[characterId];
|
|
@@ -2135,7 +2286,7 @@ function catchUpRoutines(session, zone, now, turn, ask) {
|
|
|
2135
2286
|
}
|
|
2136
2287
|
if (current === void 0) continue;
|
|
2137
2288
|
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;
|
|
2289
|
+
if (!rejoin && before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
|
|
2139
2290
|
const target = current.window;
|
|
2140
2291
|
if (target.locationId !== void 0 && (here?.locationId !== target.locationId || target.position !== void 0 && here.position !== target.position)) {
|
|
2141
2292
|
const way = here?.locationId === target.locationId ? void 0 : session.planMove(characterId, { to: target.locationId });
|
|
@@ -2151,32 +2302,52 @@ function catchUpRoutines(session, zone, now, turn, ask) {
|
|
|
2151
2302
|
continue;
|
|
2152
2303
|
}
|
|
2153
2304
|
arrive(character, target);
|
|
2154
|
-
} else
|
|
2305
|
+
} else {
|
|
2306
|
+
if (cursor !== void 0) shifted.add(keyOfCharacter$1(character));
|
|
2307
|
+
if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
|
|
2308
|
+
}
|
|
2155
2309
|
}
|
|
2156
2310
|
session.metadata.setValue(CURSOR, now);
|
|
2157
2311
|
session.metadata.setValue(TRAVEL, journeys);
|
|
2312
|
+
session.metadata.setValue(HOLDS, holds);
|
|
2313
|
+
if (shifted.size > 0) {
|
|
2314
|
+
const before = session.metadata.getValue(SHIFTED);
|
|
2315
|
+
session.metadata.setValue(SHIFTED, [.../* @__PURE__ */ new Set([...Array.isArray(before) ? before.filter((entry) => typeof entry === "string") : [], ...shifted])]);
|
|
2316
|
+
}
|
|
2158
2317
|
if (asked.length > 0) session.metadata.setValue(ASKED, [...alreadyAsked, ...asked]);
|
|
2159
2318
|
return moves;
|
|
2160
2319
|
});
|
|
2161
2320
|
}
|
|
2321
|
+
/** The characters whose day changed since this was last asked, by key; asking forgets them. */
|
|
2322
|
+
function takeShifts(session) {
|
|
2323
|
+
const stored = session.metadata.getValue(SHIFTED);
|
|
2324
|
+
const keys = Array.isArray(stored) ? stored.filter((entry) => typeof entry === "string") : [];
|
|
2325
|
+
if (keys.length > 0) session.metadata.setValue(SHIFTED, []);
|
|
2326
|
+
return keys;
|
|
2327
|
+
}
|
|
2162
2328
|
/** A character's agenda at an instant, with places by name and others by name. */
|
|
2163
|
-
function agendaView(session, characterId, zone, now) {
|
|
2329
|
+
function agendaView(session, characterId, zone, now, scheduled = true) {
|
|
2164
2330
|
const agenda = agendaAt(session, characterId, now, zone, {
|
|
2165
2331
|
horizon: NEXT_HORIZON,
|
|
2166
2332
|
engagements: SHOWN_ENGAGEMENTS,
|
|
2167
2333
|
goals: SHOWN_GOALS
|
|
2168
2334
|
});
|
|
2335
|
+
const hold = scheduled ? readHolds(session)[characterId] : void 0;
|
|
2336
|
+
const held = hold !== void 0 && now < hold.until;
|
|
2337
|
+
const dayless = !scheduled || session.characters.get(characterId)?.control === "player";
|
|
2169
2338
|
const place = (id) => id === void 0 ? void 0 : session.locations.get(id)?.name;
|
|
2170
2339
|
const names = (ids) => ids.filter((id) => id !== characterId).map((id) => session.characters.get(id)?.name ?? String(id));
|
|
2171
2340
|
return {
|
|
2172
2341
|
zone,
|
|
2173
|
-
...agenda.now === void 0 ? {} : { now: {
|
|
2342
|
+
...agenda.now === void 0 || held || dayless ? {} : { now: {
|
|
2174
2343
|
activity: agenda.now.window.activity,
|
|
2175
2344
|
...place(agenda.now.window.locationId) === void 0 ? {} : { place: place(agenda.now.window.locationId) },
|
|
2176
2345
|
until: agenda.now.endsAt,
|
|
2177
|
-
interruptible: agenda.now.window.interruptible
|
|
2346
|
+
interruptible: agenda.now.window.interruptible,
|
|
2347
|
+
...agenda.now.window.sleep === true ? { sleep: true } : {}
|
|
2178
2348
|
} },
|
|
2179
|
-
...
|
|
2349
|
+
...held ? { offDay: { until: hold.until } } : {},
|
|
2350
|
+
...agenda.next === void 0 || dayless ? {} : { next: {
|
|
2180
2351
|
activity: agenda.next.window.activity,
|
|
2181
2352
|
...place(agenda.next.window.locationId) === void 0 ? {} : { place: place(agenda.next.window.locationId) },
|
|
2182
2353
|
at: agenda.next.startsAt
|
|
@@ -2203,12 +2374,13 @@ const SOON = 30 * MINUTE;
|
|
|
2203
2374
|
const MAX_NOTES = 6;
|
|
2204
2375
|
/** An engagement that has been overdue for longer than this is not worth the game master's attention every turn. */
|
|
2205
2376
|
const STALE = 1440 * MINUTE;
|
|
2206
|
-
function sceneAgenda(session, zone, now, moved) {
|
|
2377
|
+
function sceneAgenda(session, zone, now, moved, scheduled = true) {
|
|
2207
2378
|
const player = session.characters.list().find((character) => character.control === "player");
|
|
2208
2379
|
const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
|
|
2209
2380
|
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
2381
|
const here = [];
|
|
2211
|
-
for (const characterId of withPlayer) {
|
|
2382
|
+
for (const characterId of scheduled ? withPlayer : []) {
|
|
2383
|
+
if (isHeld(session, characterId, now)) continue;
|
|
2212
2384
|
const windows = session.routines.list(characterId);
|
|
2213
2385
|
const current = occurrenceAt(windows, now, zone);
|
|
2214
2386
|
const upcoming = nextOccurrence(windows, now, zone, SOON);
|
|
@@ -2237,43 +2409,49 @@ function sceneAgenda(session, zone, now, moved) {
|
|
|
2237
2409
|
with: engagement.participants.map((id) => session.characters.get(id)?.name ?? String(id)),
|
|
2238
2410
|
overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE)
|
|
2239
2411
|
}));
|
|
2412
|
+
const asleep = scheduled ? sleepersNow(session, zone, now).map(({ key, name, until }) => ({
|
|
2413
|
+
key,
|
|
2414
|
+
name,
|
|
2415
|
+
until
|
|
2416
|
+
})) : [];
|
|
2240
2417
|
return {
|
|
2241
2418
|
zone,
|
|
2242
2419
|
moved,
|
|
2243
2420
|
here: here.slice(0, MAX_NOTES),
|
|
2421
|
+
asleep,
|
|
2244
2422
|
engagements
|
|
2245
2423
|
};
|
|
2246
2424
|
}
|
|
2247
2425
|
// src/host/clock/passage.ts
|
|
2248
2426
|
/** 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) {
|
|
2427
|
+
function startTurn(session, config, turn, wall, scheduled = true) {
|
|
2250
2428
|
const started = beginTurn(session, config, turn, wall);
|
|
2251
|
-
const moved = catchUpRoutines(session, started.time.zone, started.time.now, turn, true);
|
|
2429
|
+
const moved = scheduled ? catchUpRoutines(session, started.time.zone, started.time.now, turn, true) : [];
|
|
2252
2430
|
return {
|
|
2253
2431
|
...started,
|
|
2254
|
-
agenda: sceneAgenda(session, started.time.zone, started.time.now, moved)
|
|
2432
|
+
agenda: sceneAgenda(session, started.time.zone, started.time.now, moved, scheduled)
|
|
2255
2433
|
};
|
|
2256
2434
|
}
|
|
2257
2435
|
/** 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) {
|
|
2436
|
+
function passRound(session, config, turn, round, wall, stated, minimum, scheduled = true) {
|
|
2259
2437
|
const span = endRound(session, config, turn, round, wall, stated, minimum);
|
|
2260
2438
|
return {
|
|
2261
2439
|
...span,
|
|
2262
|
-
moved: catchUpRoutines(session, span.zone, span.to, turn, false)
|
|
2440
|
+
moved: scheduled ? catchUpRoutines(session, span.zone, span.to, turn, false) : []
|
|
2263
2441
|
};
|
|
2264
2442
|
}
|
|
2265
2443
|
/** 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) {
|
|
2444
|
+
function skipAhead(session, config, turn, round, wall, request, scheduled = true) {
|
|
2267
2445
|
const span = skipTime(session, config, turn, round, wall, request);
|
|
2268
2446
|
return {
|
|
2269
2447
|
...span,
|
|
2270
|
-
moved: catchUpRoutines(session, span.zone, span.to, turn, true)
|
|
2448
|
+
moved: scheduled ? catchUpRoutines(session, span.zone, span.to, turn, true) : []
|
|
2271
2449
|
};
|
|
2272
2450
|
}
|
|
2273
2451
|
/** What a character is told of its own agenda. */
|
|
2274
|
-
function agendaFor(session, config, turn, wall, characterId) {
|
|
2452
|
+
function agendaFor(session, config, turn, wall, characterId, scheduled = true) {
|
|
2275
2453
|
const time = readTime(session, config, turn, wall());
|
|
2276
|
-
return agendaView(session, characterId, zoneOf(config), time.now);
|
|
2454
|
+
return agendaView(session, characterId, zoneOf(config), time.now, scheduled);
|
|
2277
2455
|
}
|
|
2278
2456
|
// src/host/clock/offscene.ts
|
|
2279
2457
|
const HANDLED = "offscene.handled";
|
|
@@ -2706,10 +2884,10 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
|
|
|
2706
2884
|
time: (turn) => readTime(session, settings().clock, turn, wall()),
|
|
2707
2885
|
beginTurn: (turn) => {
|
|
2708
2886
|
observeAsPlayer(session, turn);
|
|
2709
|
-
return startTurn(session, settings().clock, turn, wall());
|
|
2887
|
+
return startTurn(session, settings().clock, turn, wall(), settings().schedule.enabled);
|
|
2710
2888
|
},
|
|
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),
|
|
2889
|
+
endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum, settings().schedule.enabled),
|
|
2890
|
+
skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request, settings().schedule.enabled),
|
|
2713
2891
|
checkVariableChanges: (changes) => changes.flatMap((spec) => {
|
|
2714
2892
|
const planned = planVariableChange(session, spec);
|
|
2715
2893
|
return planned.ok ? [] : planned.problems;
|
|
@@ -2768,15 +2946,66 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
|
|
|
2768
2946
|
recordTrace: (turn, patch, merge) => {
|
|
2769
2947
|
updateTrace(session, turn, patch, merge);
|
|
2770
2948
|
},
|
|
2949
|
+
folders: async () => await storyRoots(dirname(dirname(folder)), folder),
|
|
2950
|
+
autonomy: {
|
|
2951
|
+
catchUp: (turn) => {
|
|
2952
|
+
if (!settings().schedule.enabled) return [];
|
|
2953
|
+
const { now, zone } = readTime(session, settings().clock, turn, wall());
|
|
2954
|
+
return catchUpRoutines(session, zone, now, turn, false);
|
|
2955
|
+
},
|
|
2956
|
+
shifts: () => takeShifts(session),
|
|
2957
|
+
state: () => readAutonomy(session),
|
|
2958
|
+
lastPlayerAt: () => lastPlayerAt(session),
|
|
2959
|
+
said: (turn, message) => {
|
|
2960
|
+
session.transaction(() => {
|
|
2961
|
+
recordMessage(session, message);
|
|
2962
|
+
addToNote(session, "message", turn, [`${message.name}: ${message.text}`]);
|
|
2963
|
+
});
|
|
2964
|
+
},
|
|
2965
|
+
asked: (character, at) => {
|
|
2966
|
+
recordAsk(session, character, at);
|
|
2967
|
+
},
|
|
2968
|
+
inbox: () => takeInbox(session),
|
|
2969
|
+
looked: (outcome, at) => {
|
|
2970
|
+
session.metadata.setValue("autonomy.look", {
|
|
2971
|
+
outcome,
|
|
2972
|
+
at
|
|
2973
|
+
});
|
|
2974
|
+
}
|
|
2975
|
+
},
|
|
2771
2976
|
notes: () => readNotes(session),
|
|
2772
2977
|
clearNotes: () => {
|
|
2773
2978
|
clearNotes(session);
|
|
2774
2979
|
},
|
|
2775
|
-
agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId),
|
|
2776
|
-
|
|
2980
|
+
agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId, settings().schedule.enabled),
|
|
2981
|
+
asleep: (turn, characterId) => {
|
|
2982
|
+
if (!settings().schedule.enabled) return void 0;
|
|
2983
|
+
const { now, zone } = readTime(session, settings().clock, turn, wall());
|
|
2984
|
+
return sleepingNow(session, characterId, zone, now);
|
|
2985
|
+
},
|
|
2986
|
+
sleepers: (turn) => {
|
|
2987
|
+
if (!settings().schedule.enabled) return [];
|
|
2988
|
+
const { now, zone } = readTime(session, settings().clock, turn, wall());
|
|
2989
|
+
return sleepersNow(session, zone, now).map(({ key, name, aliases, until }) => ({
|
|
2990
|
+
key,
|
|
2991
|
+
name,
|
|
2992
|
+
aliases,
|
|
2993
|
+
until
|
|
2994
|
+
}));
|
|
2995
|
+
},
|
|
2996
|
+
holdForPlayer: (characterId) => {
|
|
2997
|
+
if (!settings().schedule.enabled) return;
|
|
2998
|
+
const { now, zone } = readTime(session, settings().clock, session.metadata.get().turns + 1, wall());
|
|
2999
|
+
holdCharacter(session, characterId, zone, now, void 0, true);
|
|
3000
|
+
},
|
|
3001
|
+
commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items, hold }) => {
|
|
2777
3002
|
session.characterStates.update(character, patch);
|
|
2778
3003
|
const effects = (items ?? []).map((spec) => changeItem(session, character, spec));
|
|
2779
3004
|
if (move !== void 0) session.move(character, move);
|
|
3005
|
+
if (hold !== void 0 && settings().schedule.enabled) {
|
|
3006
|
+
const { now, zone } = readTime(session, settings().clock, session.metadata.get().turns + 1, wall());
|
|
3007
|
+
holdCharacter(session, character, zone, now, hold.minutes, hold.untilPlayer === true);
|
|
3008
|
+
}
|
|
2780
3009
|
return effects;
|
|
2781
3010
|
})),
|
|
2782
3011
|
checkItemChanges: (entries) => dryRunItems(session, entries),
|
|
@@ -2832,113 +3061,6 @@ function parseOoc(text) {
|
|
|
2832
3061
|
}
|
|
2833
3062
|
/** The longest answer to an out-of-character question. */
|
|
2834
3063
|
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
3064
|
// src/shared/tools.ts
|
|
2943
3065
|
/** What this version can offer. A name in a settings file or a world that is not here is kept and ignored. */
|
|
2944
3066
|
const OPTIONAL_TOOLS = [
|
|
@@ -3011,175 +3133,6 @@ function toolEnabled(board, agent, id) {
|
|
|
3011
3133
|
function externalEnabled(board, agent, name) {
|
|
3012
3134
|
return board[agent]?.[name] === true;
|
|
3013
3135
|
}
|
|
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
3136
|
// src/host/pacing/author.ts
|
|
3184
3137
|
const RESULT = {
|
|
3185
3138
|
type: "object",
|
|
@@ -3436,6 +3389,11 @@ function createTools$1(deps) {
|
|
|
3436
3389
|
type: "string",
|
|
3437
3390
|
required: true,
|
|
3438
3391
|
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."
|
|
3392
|
+
},
|
|
3393
|
+
wakes: {
|
|
3394
|
+
type: "array",
|
|
3395
|
+
items: { type: "string" },
|
|
3396
|
+
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
3397
|
}
|
|
3440
3398
|
},
|
|
3441
3399
|
output: {
|
|
@@ -3456,7 +3414,8 @@ function createTools$1(deps) {
|
|
|
3456
3414
|
});
|
|
3457
3415
|
return record(await deps.engine.activate(owner, {
|
|
3458
3416
|
situation: args.situation,
|
|
3459
|
-
characters: args.characters
|
|
3417
|
+
characters: args.characters,
|
|
3418
|
+
...args.wakes === void 0 ? {} : { wakes: args.wakes }
|
|
3460
3419
|
}, run, exec.signal));
|
|
3461
3420
|
}
|
|
3462
3421
|
});
|
|
@@ -3487,6 +3446,14 @@ function createTools$1(deps) {
|
|
|
3487
3446
|
required: true,
|
|
3488
3447
|
description: "What concretely happens to the character, in a sentence. It becomes what the character is doing."
|
|
3489
3448
|
},
|
|
3449
|
+
off_routine_minutes: {
|
|
3450
|
+
type: "integer",
|
|
3451
|
+
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."
|
|
3452
|
+
},
|
|
3453
|
+
waits_for_player: {
|
|
3454
|
+
type: "boolean",
|
|
3455
|
+
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."
|
|
3456
|
+
},
|
|
3490
3457
|
roll: {
|
|
3491
3458
|
type: "integer",
|
|
3492
3459
|
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 +3610,8 @@ function createTools$1(deps) {
|
|
|
3643
3610
|
...outcome.public_state === void 0 ? {} : { publicState: outcome.public_state },
|
|
3644
3611
|
...outcome.spoken === void 0 ? {} : { spoken: outcome.spoken },
|
|
3645
3612
|
...outcome.roll === void 0 ? {} : { roll: outcome.roll },
|
|
3613
|
+
...outcome.waits_for_player === true ? { waitsForPlayer: true } : {},
|
|
3614
|
+
...outcome.off_routine_minutes === void 0 ? {} : { offRoutineMinutes: outcome.off_routine_minutes },
|
|
3646
3615
|
...outcome.item_changes === void 0 || outcome.item_changes.length === 0 ? {} : { itemChanges: outcome.item_changes.map((change) => ({
|
|
3647
3616
|
item: change.item,
|
|
3648
3617
|
action: change.action,
|
|
@@ -4065,6 +4034,10 @@ function createTools$1(deps) {
|
|
|
4065
4034
|
required: true,
|
|
4066
4035
|
description: "Whether what the character tries can work: false when any listed rule is broken or it is not viable."
|
|
4067
4036
|
},
|
|
4037
|
+
goes_to: {
|
|
4038
|
+
type: "string",
|
|
4039
|
+
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."
|
|
4040
|
+
},
|
|
4068
4041
|
uncertain: {
|
|
4069
4042
|
type: "boolean",
|
|
4070
4043
|
required: true,
|
|
@@ -4087,7 +4060,7 @@ function createTools$1(deps) {
|
|
|
4087
4060
|
async execute(args, exec) {
|
|
4088
4061
|
const { owner } = ownerOf(exec.agent);
|
|
4089
4062
|
await deps.engine.checkRules(owner, args.allowed);
|
|
4090
|
-
const judged = deps.engine.judge(owner, args.allowed, args.reason, args.at, args.uncertain);
|
|
4063
|
+
const judged = deps.engine.judge(owner, args.allowed, args.reason, args.at, args.uncertain, args.goes_to);
|
|
4091
4064
|
const store = deps.stores(owner.chat);
|
|
4092
4065
|
return record(judged.roll === true && store !== void 0 && toolEnabled(store.settings().tools, "gameMaster", "roll_and_narrate") ? {
|
|
4093
4066
|
...judged,
|
|
@@ -4141,7 +4114,317 @@ function externalGiven(registry, board, agent) {
|
|
|
4141
4114
|
function externalWithheld(registry, board, agent) {
|
|
4142
4115
|
return externalTools(registry).map((tool) => tool.name).filter((name) => !externalEnabled(board, agent, name));
|
|
4143
4116
|
}
|
|
4117
|
+
/** 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. */
|
|
4118
|
+
function charactersGiven(registry, board, away) {
|
|
4119
|
+
return away ? [] : externalGiven(registry, board, "characters");
|
|
4120
|
+
}
|
|
4121
|
+
// src/host/workspace/describe.ts
|
|
4122
|
+
/** 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. */
|
|
4123
|
+
function foldersLine(roots, language) {
|
|
4124
|
+
const [workspace, ...rest] = roots;
|
|
4125
|
+
if (workspace === void 0) return void 0;
|
|
4126
|
+
const tr = translator(language);
|
|
4127
|
+
const given = rest.map((folder) => folder.write ? tr("{path} (read and write)", { path: folder.path }) : tr("{path} (read only)", { path: folder.path }));
|
|
4128
|
+
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}", {
|
|
4129
|
+
workspace: workspace.path,
|
|
4130
|
+
given: given.length === 0 ? "" : tr(" Given for this story: {folders}.", { folders: given.join(tr(", ")) })
|
|
4131
|
+
});
|
|
4132
|
+
}
|
|
4133
|
+
// src/host/orchestration/character-runner.ts
|
|
4134
|
+
/**
|
|
4135
|
+
* Runs each character as a one-shot child of the game master. It is the character and nothing
|
|
4136
|
+
* else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
|
|
4137
|
+
* the memory of that character alone, so characters acting at the same time cannot see each
|
|
4138
|
+
* other's memories.
|
|
4139
|
+
*/
|
|
4140
|
+
function characterRunner(deps) {
|
|
4141
|
+
return async (request, signal) => {
|
|
4142
|
+
const brief = deps.boundaries().characterContext.brief(request);
|
|
4143
|
+
const settings = deps.store.settings();
|
|
4144
|
+
const tools = settings.memory.lookup ? createCharacterTools(() => ({
|
|
4145
|
+
session: deps.store.story,
|
|
4146
|
+
turn: request.turn,
|
|
4147
|
+
policy: settings.memory,
|
|
4148
|
+
queryVector: deps.store.queryVector
|
|
4149
|
+
}), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)).map((tool) => notingEmpty(tool, deps.store, request.turn, request.member.character.name)) : [];
|
|
4150
|
+
const background = (request.knowledge?.lore.length ?? 0) > 0 && tools.some((tool) => tool.name === "recall_my_lore");
|
|
4151
|
+
const external = charactersGiven(deps.parent.ctx.tools, settings.tools, request.away === true);
|
|
4152
|
+
const folders = external.length === 0 ? void 0 : await deps.store.folders?.().then((roots) => foldersLine(roots, languageOf$1(settings.prompts.language)));
|
|
4153
|
+
const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
|
|
4154
|
+
return parseCharacterAction(await runChild({
|
|
4155
|
+
parent: deps.parent,
|
|
4156
|
+
signal,
|
|
4157
|
+
sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
|
|
4158
|
+
...childModel(settings, "characters", named),
|
|
4159
|
+
trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named, request.away === true ? "off stage" : void 0),
|
|
4160
|
+
reasoningEffort: deps.store.settings().reasoning.children,
|
|
4161
|
+
persona: brief.persona,
|
|
4162
|
+
prompt: folders === void 0 ? brief.prompt : `${brief.prompt}\n\n${folders}`,
|
|
4163
|
+
tools,
|
|
4164
|
+
external,
|
|
4165
|
+
maxCalls: deps.store.settings().memory.lookupCalls + (external.length === 0 ? 0 : EXTERNAL_CALLS),
|
|
4166
|
+
result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
|
|
4167
|
+
unenforced: ["thought"],
|
|
4168
|
+
beforeSubmit: submitGate(settings.prompts.language, background, request.away === true ? [] : ownLines(deps.store, request.member.character))
|
|
4169
|
+
}));
|
|
4170
|
+
};
|
|
4171
|
+
}
|
|
4172
|
+
/** A look-up that finds nothing is kept in the turn's trace: it is where the world lacks what a character reached for. */
|
|
4173
|
+
function notingEmpty(tool, store, turn, character) {
|
|
4174
|
+
return {
|
|
4175
|
+
...tool,
|
|
4176
|
+
async execute(args, exec) {
|
|
4177
|
+
const found = await tool.execute(args, exec);
|
|
4178
|
+
const about = args.about;
|
|
4179
|
+
if (Array.isArray(found) && found.length === 0 && typeof about === "string" && about.trim() !== "") try {
|
|
4180
|
+
store.recordTrace?.(turn, {}, (current) => ({ missing: [...current.missing ?? [], {
|
|
4181
|
+
character,
|
|
4182
|
+
tool: tool.name,
|
|
4183
|
+
about: about.trim().slice(0, 120)
|
|
4184
|
+
}].slice(-40) }));
|
|
4185
|
+
} catch {}
|
|
4186
|
+
return found;
|
|
4187
|
+
}
|
|
4188
|
+
};
|
|
4189
|
+
}
|
|
4190
|
+
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";
|
|
4191
|
+
/** The model decides whether the moment touches its background; asking once at the point of answering is what makes it decide. */
|
|
4192
|
+
function submitGate(language, background, said = []) {
|
|
4193
|
+
let asked = !background;
|
|
4194
|
+
let reminded = false;
|
|
4195
|
+
const tr = translator(languageOf$1(language));
|
|
4196
|
+
return (value) => {
|
|
4197
|
+
if (!asked) {
|
|
4198
|
+
asked = true;
|
|
4199
|
+
return BACKGROUND_CHECK;
|
|
4200
|
+
}
|
|
4201
|
+
const wrong = spokenIn(language, value);
|
|
4202
|
+
if (wrong !== void 0) return wrong;
|
|
4203
|
+
const line = value.utterance;
|
|
4204
|
+
if (!reminded && line !== void 0 && said.some((earlier) => sameWords(earlier, line))) {
|
|
4205
|
+
reminded = true;
|
|
4206
|
+
return tr("you already said exactly this earlier in the story: \"{line}\". Say something new that answers this moment, or give no utterance", { line });
|
|
4207
|
+
}
|
|
4208
|
+
};
|
|
4209
|
+
}
|
|
4210
|
+
/** What a character has said in the story so far, most recent last, as the records keep it. */
|
|
4211
|
+
function ownLines(store, character) {
|
|
4212
|
+
const opening = `${character.name}: "`;
|
|
4213
|
+
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);
|
|
4214
|
+
}
|
|
4215
|
+
/** What a character that was given tools of other plugins may call on top of its memory look-ups. */
|
|
4216
|
+
const EXTERNAL_CALLS = 5;
|
|
4217
|
+
/** 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. */
|
|
4218
|
+
function spokenIn(language, value) {
|
|
4219
|
+
const given = value;
|
|
4220
|
+
return wrongLanguage(language, {
|
|
4221
|
+
thought: given.thought,
|
|
4222
|
+
intent: given.intent,
|
|
4223
|
+
utterance: given.utterance,
|
|
4224
|
+
account: given.account
|
|
4225
|
+
}, { strays: true }) ?? narratedSpeech(given.utterance);
|
|
4226
|
+
}
|
|
4227
|
+
const CLOSING_QUOTE = {
|
|
4228
|
+
"\"": "\"",
|
|
4229
|
+
"“": "”",
|
|
4230
|
+
"「": "」",
|
|
4231
|
+
"『": "』"
|
|
4232
|
+
};
|
|
4233
|
+
function outsideQuotedSpeech(utterance) {
|
|
4234
|
+
const parts = [];
|
|
4235
|
+
let outside = 0;
|
|
4236
|
+
let cursor = 0;
|
|
4237
|
+
while (cursor < utterance.length) {
|
|
4238
|
+
const closing = CLOSING_QUOTE[utterance[cursor]];
|
|
4239
|
+
if (closing === void 0) {
|
|
4240
|
+
cursor += 1;
|
|
4241
|
+
continue;
|
|
4242
|
+
}
|
|
4243
|
+
const end = utterance.indexOf(closing, cursor + 1);
|
|
4244
|
+
if (end < 0) {
|
|
4245
|
+
cursor += 1;
|
|
4246
|
+
continue;
|
|
4247
|
+
}
|
|
4248
|
+
parts.push(utterance.slice(outside, cursor));
|
|
4249
|
+
outside = end + 1;
|
|
4250
|
+
cursor = outside;
|
|
4251
|
+
}
|
|
4252
|
+
parts.push(utterance.slice(outside));
|
|
4253
|
+
return parts;
|
|
4254
|
+
}
|
|
4255
|
+
/** 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. */
|
|
4256
|
+
function narratedSpeech(utterance) {
|
|
4257
|
+
if (utterance === void 0) return void 0;
|
|
4258
|
+
const parts = outsideQuotedSpeech(utterance);
|
|
4259
|
+
if (parts.length - 1 < 2) return void 0;
|
|
4260
|
+
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;
|
|
4261
|
+
}
|
|
4262
|
+
/** What the character was reminded of and why, for the run's record, when the recall said why. */
|
|
4263
|
+
function recalledOf(request) {
|
|
4264
|
+
const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
|
|
4265
|
+
return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
|
|
4266
|
+
clarity,
|
|
4267
|
+
turn,
|
|
4268
|
+
text,
|
|
4269
|
+
why
|
|
4270
|
+
})) };
|
|
4271
|
+
}
|
|
4272
|
+
const ANSWER_SCHEMA = {
|
|
4273
|
+
type: "object",
|
|
4274
|
+
properties: { answer: {
|
|
4275
|
+
type: "string",
|
|
4276
|
+
description: "The answer to the player, in plain words, in a few sentences."
|
|
4277
|
+
} },
|
|
4278
|
+
required: ["answer"],
|
|
4279
|
+
additionalProperties: false
|
|
4280
|
+
};
|
|
4281
|
+
/**
|
|
4282
|
+
* 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
|
|
4283
|
+
* game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
|
|
4284
|
+
*/
|
|
4285
|
+
function answerRunner(deps) {
|
|
4286
|
+
return async (request, signal) => {
|
|
4287
|
+
const brief = deps.boundaries().characterContext.brief(request);
|
|
4288
|
+
return (await runChild({
|
|
4289
|
+
parent: deps.parent,
|
|
4290
|
+
signal,
|
|
4291
|
+
sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
|
|
4292
|
+
...childModel(deps.store.settings(), "records"),
|
|
4293
|
+
trace: childTrace(deps.store, "records", "answer to the player"),
|
|
4294
|
+
reasoningEffort: deps.store.settings().reasoning.children,
|
|
4295
|
+
persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
|
|
4296
|
+
prompt: brief.prompt,
|
|
4297
|
+
tools: [],
|
|
4298
|
+
maxCalls: 3,
|
|
4299
|
+
result: ANSWER_SCHEMA
|
|
4300
|
+
})).answer;
|
|
4301
|
+
};
|
|
4302
|
+
}
|
|
4303
|
+
// src/shared/dream.ts
|
|
4304
|
+
/** 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. */
|
|
4305
|
+
function parseDream(text) {
|
|
4306
|
+
const value = text.trimStart();
|
|
4307
|
+
if (value.slice(0, 6).toLowerCase() !== "/dream" || value.length > 6 && !/\s/u.test(value[6])) return void 0;
|
|
4308
|
+
return { who: value.slice(6).trim() };
|
|
4309
|
+
}
|
|
4310
|
+
// src/shared/roll.ts
|
|
4311
|
+
/** 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. */
|
|
4312
|
+
function parseRoll(text) {
|
|
4313
|
+
const value = text.trimStart();
|
|
4314
|
+
if (value.slice(0, 5).toLowerCase() !== "/roll" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
|
|
4315
|
+
const body = value.slice(5).trimStart();
|
|
4316
|
+
const boundary = body.search(/\s/u);
|
|
4317
|
+
return boundary < 0 ? {
|
|
4318
|
+
expression: body,
|
|
4319
|
+
reason: ""
|
|
4320
|
+
} : {
|
|
4321
|
+
expression: body.slice(0, boundary),
|
|
4322
|
+
reason: body.slice(boundary).trim()
|
|
4323
|
+
};
|
|
4324
|
+
}
|
|
4325
|
+
// src/shared/wait.ts
|
|
4326
|
+
const UNITS = [
|
|
4327
|
+
[/^(?:m|min|mins|minute|minutes|分钟|分)$/iu, 1],
|
|
4328
|
+
[/^(?:h|hr|hrs|hour|hours|小时|時間|时)$/iu, 60],
|
|
4329
|
+
[/^(?:d|day|days|天|日)$/iu, 1440]
|
|
4330
|
+
];
|
|
4331
|
+
/**
|
|
4332
|
+
* 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
|
|
4333
|
+
* unreadable, and is then `undefined` in `minutes`.
|
|
4334
|
+
*/
|
|
4335
|
+
function parseWait(text) {
|
|
4336
|
+
const value = text.trimStart();
|
|
4337
|
+
if (value.slice(0, 5).toLowerCase() !== "/wait" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
|
|
4338
|
+
const body = value.slice(5).trim();
|
|
4339
|
+
const match = /^(\d+(?:\.\d+)?)\s*([\p{L}]+)\s*(.*)$/su.exec(body);
|
|
4340
|
+
if (match === null) return {
|
|
4341
|
+
minutes: void 0,
|
|
4342
|
+
reason: body
|
|
4343
|
+
};
|
|
4344
|
+
const unit = UNITS.find(([pattern]) => pattern.test(match[2]));
|
|
4345
|
+
if (unit === void 0) return {
|
|
4346
|
+
minutes: void 0,
|
|
4347
|
+
reason: body
|
|
4348
|
+
};
|
|
4349
|
+
const minutes = Math.round(Number(match[1]) * unit[1]);
|
|
4350
|
+
return {
|
|
4351
|
+
minutes: minutes >= 1 && minutes <= 525600 ? minutes : void 0,
|
|
4352
|
+
reason: match[3].trim()
|
|
4353
|
+
};
|
|
4354
|
+
}
|
|
4355
|
+
// src/host/agents/repeat-guard.ts
|
|
4356
|
+
/**
|
|
4357
|
+
* 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
|
|
4358
|
+
* 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.
|
|
4359
|
+
* @param languageOf the language of the chat the call belongs to, or nothing when the guard does not apply to it.
|
|
4360
|
+
*/
|
|
4361
|
+
function guardRepeatedCalls(ctx, languageOf, limit) {
|
|
4362
|
+
const calls = /* @__PURE__ */ new Map();
|
|
4363
|
+
ctx.on("agent/pre-step", async (payload, next) => {
|
|
4364
|
+
if (payload.step === 1) calls.delete(payload.agent.session.id);
|
|
4365
|
+
return await next();
|
|
4366
|
+
});
|
|
4367
|
+
ctx.on("tools/pre-execute", async (exec, next) => {
|
|
4368
|
+
const chat = exec.agent?.session.id;
|
|
4369
|
+
const language = chat === void 0 || exec.agent?.session.header.origin === "subagent" ? void 0 : languageOf(exec);
|
|
4370
|
+
if (chat === void 0 || language === void 0) return await next();
|
|
4371
|
+
const signature = `${exec.name}:${JSON.stringify(exec.arguments)}`;
|
|
4372
|
+
const seen = calls.get(chat) ?? /* @__PURE__ */ new Map();
|
|
4373
|
+
calls.set(chat, seen);
|
|
4374
|
+
const count = (seen.get(signature) ?? 0) + 1;
|
|
4375
|
+
seen.set(signature, count);
|
|
4376
|
+
if (count <= limit) return await next();
|
|
4377
|
+
if (count > limit + 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
|
|
4378
|
+
return {
|
|
4379
|
+
kind: "deny",
|
|
4380
|
+
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 })
|
|
4381
|
+
};
|
|
4382
|
+
}, { prepend: true });
|
|
4383
|
+
}
|
|
4384
|
+
// src/host/orchestration/runaway.ts
|
|
4385
|
+
/** The levels of thinking that mean none, as models name them. */
|
|
4386
|
+
const NONE = [
|
|
4387
|
+
"off",
|
|
4388
|
+
"none",
|
|
4389
|
+
"minimal"
|
|
4390
|
+
];
|
|
4391
|
+
/**
|
|
4392
|
+
* 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
|
|
4393
|
+
* 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.
|
|
4394
|
+
*/
|
|
4395
|
+
var RunawayThinking = class {
|
|
4396
|
+
before = /* @__PURE__ */ new Map();
|
|
4397
|
+
/** To be called before each step of a chat's game master. */
|
|
4398
|
+
async step(chat, agent, step) {
|
|
4399
|
+
const earlier = this.before.get(chat);
|
|
4400
|
+
if (earlier !== void 0 && step === 1) {
|
|
4401
|
+
agent.model.select(earlier);
|
|
4402
|
+
this.before.delete(chat);
|
|
4403
|
+
return;
|
|
4404
|
+
}
|
|
4405
|
+
if (step === 1 || earlier !== void 0 || !cutOff(agent)) return;
|
|
4406
|
+
const current = agent.model.current();
|
|
4407
|
+
if (current === void 0) return;
|
|
4408
|
+
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));
|
|
4409
|
+
if (level === void 0 || current.reasoningEffort === level.id) return;
|
|
4410
|
+
this.before.set(chat, current);
|
|
4411
|
+
agent.model.select({
|
|
4412
|
+
...current,
|
|
4413
|
+
reasoningEffort: ReasoningEffortId(level.id)
|
|
4414
|
+
});
|
|
4415
|
+
}
|
|
4416
|
+
};
|
|
4144
4417
|
// src/host/orchestration/hooks.ts
|
|
4418
|
+
/** DSH's file tools that a story may give its game master. */
|
|
4419
|
+
const FILE_TOOLS = [
|
|
4420
|
+
"read",
|
|
4421
|
+
"read_image",
|
|
4422
|
+
"write",
|
|
4423
|
+
"edit",
|
|
4424
|
+
"glob",
|
|
4425
|
+
"grep",
|
|
4426
|
+
"apply_patch"
|
|
4427
|
+
];
|
|
4145
4428
|
const notice = (text) => createUserMessage({
|
|
4146
4429
|
content: [{
|
|
4147
4430
|
type: "text",
|
|
@@ -4221,6 +4504,42 @@ function installHooks(ctx, deps) {
|
|
|
4221
4504
|
}))];
|
|
4222
4505
|
};
|
|
4223
4506
|
const runaway = new RunawayThinking();
|
|
4507
|
+
const turns = deps.traces ?? new TurnTraces(() => tracerOf(ctx));
|
|
4508
|
+
engine.observe = (chat, round) => {
|
|
4509
|
+
const span = turns.child(chat, {
|
|
4510
|
+
name: round.attempt === 1 ? "round" : "round (retry)",
|
|
4511
|
+
kind: "span",
|
|
4512
|
+
input: {
|
|
4513
|
+
characters: round.characters,
|
|
4514
|
+
...round.away ? { away: true } : {}
|
|
4515
|
+
},
|
|
4516
|
+
metadata: {
|
|
4517
|
+
turn: round.turn,
|
|
4518
|
+
attempt: round.attempt
|
|
4519
|
+
}
|
|
4520
|
+
});
|
|
4521
|
+
return (result) => {
|
|
4522
|
+
if (span === void 0) return;
|
|
4523
|
+
if (result instanceof Error) {
|
|
4524
|
+
span.end({
|
|
4525
|
+
level: "ERROR",
|
|
4526
|
+
statusMessage: result.message
|
|
4527
|
+
});
|
|
4528
|
+
return;
|
|
4529
|
+
}
|
|
4530
|
+
span.end({ output: {
|
|
4531
|
+
acted: result.reports.map((report) => ({
|
|
4532
|
+
character: report.name,
|
|
4533
|
+
intent: report.intent,
|
|
4534
|
+
commitment: report.commitment
|
|
4535
|
+
})),
|
|
4536
|
+
failed: result.failures.map((failure) => ({
|
|
4537
|
+
character: failure.name,
|
|
4538
|
+
reason: failure.reason
|
|
4539
|
+
}))
|
|
4540
|
+
} });
|
|
4541
|
+
};
|
|
4542
|
+
};
|
|
4224
4543
|
guardRepeatedCalls(ctx, (exec) => {
|
|
4225
4544
|
const owner = exec.agent === void 0 ? void 0 : ownerOf(exec.agent, 0);
|
|
4226
4545
|
return owner === void 0 ? void 0 : stores(owner.chat)?.settings().prompts.language;
|
|
@@ -4232,25 +4551,43 @@ function installHooks(ctx, deps) {
|
|
|
4232
4551
|
registerConditionalTools(agent, conditionsOf(agent.session.id));
|
|
4233
4552
|
applyLimit(agent, store);
|
|
4234
4553
|
});
|
|
4554
|
+
/** Where the open turn of each chat began, so its own events can be read back without walking the whole log. */
|
|
4555
|
+
const openTurns = /* @__PURE__ */ new Map();
|
|
4235
4556
|
ctx.on("session/event", (session, event) => {
|
|
4236
|
-
if (
|
|
4557
|
+
if (session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
|
|
4558
|
+
if (event.type === "turn/start") {
|
|
4559
|
+
openTurns.set(session.id, {
|
|
4560
|
+
seq: event.seq,
|
|
4561
|
+
time: event.time
|
|
4562
|
+
});
|
|
4563
|
+
return;
|
|
4564
|
+
}
|
|
4565
|
+
if (event.type !== "turn/end") return;
|
|
4237
4566
|
ctx.roleplayOrchestration.recovery.clear(session.id);
|
|
4238
|
-
|
|
4239
|
-
const
|
|
4240
|
-
|
|
4241
|
-
|
|
4567
|
+
turns.end(session.id);
|
|
4568
|
+
const began = openTurns.get(session.id);
|
|
4569
|
+
openTurns.delete(session.id);
|
|
4570
|
+
timelines.ended(session.id, session, event.seq, began === void 0 ? void 0 : began.seq);
|
|
4571
|
+
const events = session.snapshotEvents(began?.seq ?? 0);
|
|
4572
|
+
const from = began === void 0 ? events.findLastIndex((entry) => entry.type === "turn/start") : 0;
|
|
4573
|
+
if (from === -1) return;
|
|
4574
|
+
const turn = events.slice(from);
|
|
4575
|
+
const start = turn[0];
|
|
4242
4576
|
if (start?.type !== "turn/start") return;
|
|
4243
4577
|
const store = stores(session.id);
|
|
4244
|
-
store?.recordUsage?.(start.data.turn, tokensOf(
|
|
4578
|
+
store?.recordUsage?.(start.data.turn, tokensOf(turn), Math.max(0, event.time - start.time));
|
|
4245
4579
|
try {
|
|
4246
4580
|
store?.recordTrace?.(start.data.turn, {
|
|
4247
|
-
...masterTrace(
|
|
4581
|
+
...masterTrace(turn),
|
|
4248
4582
|
endedAt: event.time
|
|
4249
4583
|
});
|
|
4250
4584
|
} catch (error) {
|
|
4251
4585
|
ctx.logger.warn(`roleplay: the trace of turn ${start.data.turn} could not be kept: ${error instanceof Error ? error.message : String(error)}`);
|
|
4252
4586
|
}
|
|
4253
4587
|
});
|
|
4588
|
+
ctx.on("session/disposed", (session) => {
|
|
4589
|
+
openTurns.delete(session.id);
|
|
4590
|
+
});
|
|
4254
4591
|
ctx.on("agent/created", async ({ agent }) => {
|
|
4255
4592
|
const { header } = agent.session;
|
|
4256
4593
|
if (header.origin === "subagent" || !header.isSeeded || header.parentSession === void 0) return;
|
|
@@ -4293,11 +4630,13 @@ function installHooks(ctx, deps) {
|
|
|
4293
4630
|
if (!store.settings().background.concurrent) await engine.quiesce(owner.chat, { skipOptional: true });
|
|
4294
4631
|
await ctx.roleplayOrchestration.unitFree(owner.chat);
|
|
4295
4632
|
const began = await timelines.begin(owner.chat, payload.turn, text);
|
|
4633
|
+
turns.begin(owner.chat, payload.turn, text);
|
|
4296
4634
|
deps.rolls?.begin(owner.chat, store.story.metadata.get().id, began.parent);
|
|
4297
4635
|
const cast = store.cast();
|
|
4298
4636
|
const ooc = parseOoc(text);
|
|
4299
4637
|
const command = ooc === void 0 ? /^\/([\p{L}\p{N}_]+)/u.exec(text.trim())?.[1] : void 0;
|
|
4300
4638
|
const used = store.raiseCommand?.(command, payload.turn);
|
|
4639
|
+
const dream = ooc === void 0 ? parseDream(text) : void 0;
|
|
4301
4640
|
const verdict = ooc === void 0 ? boundaries().inputValidator.validate({
|
|
4302
4641
|
text,
|
|
4303
4642
|
turn: payload.turn,
|
|
@@ -4305,7 +4644,7 @@ function installHooks(ctx, deps) {
|
|
|
4305
4644
|
}) : { ok: true };
|
|
4306
4645
|
if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
|
|
4307
4646
|
else if (ooc === void 0) {
|
|
4308
|
-
engine.expectJudgement(owner);
|
|
4647
|
+
if (dream === void 0) engine.expectJudgement(owner);
|
|
4309
4648
|
engine.noteInput(owner, text);
|
|
4310
4649
|
}
|
|
4311
4650
|
const queryVector = await store.queryVector(ooc?.request ?? text);
|
|
@@ -4317,6 +4656,7 @@ function installHooks(ctx, deps) {
|
|
|
4317
4656
|
name: move.name,
|
|
4318
4657
|
place: move.to
|
|
4319
4658
|
})));
|
|
4659
|
+
const arrived = store.autonomy?.inbox() ?? [];
|
|
4320
4660
|
const world = {
|
|
4321
4661
|
happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
|
|
4322
4662
|
names: cue.names.join(tr(" and ")),
|
|
@@ -4372,9 +4712,13 @@ function installHooks(ctx, deps) {
|
|
|
4372
4712
|
}), ...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
4713
|
if (pacing !== void 0) addLine("pacing", describePacingAdvice(pacing));
|
|
4374
4714
|
else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) addLine("pacing", store.text("roleplay/plot-hint"));
|
|
4715
|
+
const filing = FILE_TOOLS.some((name) => externalEnabled(store.settings().tools, "gameMaster", name)) ? await deps.folders?.(owner.chat) : void 0;
|
|
4716
|
+
const folderLine = filing === void 0 ? void 0 : foldersLine(filing, languageOf$1(store.settings().prompts.language) === "zh" ? "zh" : "en");
|
|
4717
|
+
if (folderLine !== void 0) addLine("folders", folderLine);
|
|
4718
|
+
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
4719
|
const rules = store.rules();
|
|
4376
4720
|
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;
|
|
4721
|
+
const wanted = ooc === void 0 && dream === void 0 ? parseRoll(text) : void 0;
|
|
4378
4722
|
if (wanted !== void 0) try {
|
|
4379
4723
|
const made = rollPlain(wanted.expression, deps.rolls?.roller(owner.chat));
|
|
4380
4724
|
const roll = store.story.dice.record({
|
|
@@ -4398,18 +4742,81 @@ function installHooks(ctx, deps) {
|
|
|
4398
4742
|
engine.skip(owner);
|
|
4399
4743
|
lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
|
|
4400
4744
|
}
|
|
4401
|
-
|
|
4745
|
+
if (dream !== void 0) {
|
|
4746
|
+
const sleepers = store.sleepers(payload.turn);
|
|
4747
|
+
const wantedName = dream.who.toLowerCase();
|
|
4748
|
+
const found = wantedName === "" ? sleepers.length === 1 ? sleepers : [] : sleepers.filter((entry) => entry.key.toLowerCase() === wantedName || [entry.name, ...entry.aliases ?? []].some((name) => name.toLowerCase().includes(wantedName)));
|
|
4749
|
+
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;
|
|
4750
|
+
if (refusal !== void 0) {
|
|
4751
|
+
engine.skip(owner);
|
|
4752
|
+
lines.push(store.text("roleplay/input-refused", { reason: refusal }));
|
|
4753
|
+
} else {
|
|
4754
|
+
const sleeper = found[0];
|
|
4755
|
+
engine.beginDream(owner, sleeper.key, tr("You are asleep and the player's character has come into your dream. Say what the dream holds."));
|
|
4756
|
+
const report = await engine.dream(owner, characterRunner({
|
|
4757
|
+
parent: payload.agent,
|
|
4758
|
+
boundaries,
|
|
4759
|
+
store
|
|
4760
|
+
}));
|
|
4761
|
+
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.", {
|
|
4762
|
+
name: sleeper.name,
|
|
4763
|
+
key: sleeper.key
|
|
4764
|
+
}) : 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.", {
|
|
4765
|
+
name: sleeper.name,
|
|
4766
|
+
intent: report.intent,
|
|
4767
|
+
said: report.utterance === void 0 || report.utterance === "" ? "" : tr(", said \"{text}\"", { text: report.utterance })
|
|
4768
|
+
});
|
|
4769
|
+
addLine("dream", store.text("roleplay/dream", {
|
|
4770
|
+
name: sleeper.name,
|
|
4771
|
+
key: sleeper.key,
|
|
4772
|
+
asked
|
|
4773
|
+
}));
|
|
4774
|
+
}
|
|
4775
|
+
}
|
|
4776
|
+
const waiting = ooc === void 0 && wanted === void 0 && dream === void 0 ? parseWait(text) : void 0;
|
|
4402
4777
|
if (waiting !== void 0) {
|
|
4403
4778
|
const clock = store.settings().clock;
|
|
4404
4779
|
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
4780
|
if (refusal !== void 0) {
|
|
4406
4781
|
engine.skip(owner);
|
|
4407
4782
|
lines.push(store.text("roleplay/input-refused", { reason: refusal }));
|
|
4408
|
-
} else
|
|
4409
|
-
|
|
4410
|
-
|
|
4411
|
-
|
|
4412
|
-
|
|
4783
|
+
} else {
|
|
4784
|
+
const reason = waiting.reason === "" ? "" : ` (${waiting.reason})`;
|
|
4785
|
+
const language = languageOf$1(store.settings().prompts.language) === "zh" ? "zh" : "en";
|
|
4786
|
+
const skipped = (() => {
|
|
4787
|
+
try {
|
|
4788
|
+
return engine.advanceTime(owner, {
|
|
4789
|
+
byMinutes: waiting.minutes,
|
|
4790
|
+
reason: waiting.reason === "" ? tr("time passes") : waiting.reason
|
|
4791
|
+
});
|
|
4792
|
+
} catch {
|
|
4793
|
+
return;
|
|
4794
|
+
}
|
|
4795
|
+
})();
|
|
4796
|
+
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.", {
|
|
4797
|
+
minutes: waiting.minutes,
|
|
4798
|
+
reason,
|
|
4799
|
+
rounds: store.settings().maxRounds
|
|
4800
|
+
}));
|
|
4801
|
+
else {
|
|
4802
|
+
const moved = skipped.moved.map((move) => tr("{name} went to {place}.", {
|
|
4803
|
+
name: move.name,
|
|
4804
|
+
place: move.to
|
|
4805
|
+
})).join(" ");
|
|
4806
|
+
const happened = skipped.world.flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
|
|
4807
|
+
names: cue.names.join(tr(" and ")),
|
|
4808
|
+
text: cue.text
|
|
4809
|
+
}))]).join(" ");
|
|
4810
|
+
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.", {
|
|
4811
|
+
minutes: waiting.minutes,
|
|
4812
|
+
reason,
|
|
4813
|
+
now: describeInstant(skipped.to, skipped.zone, language),
|
|
4814
|
+
moved: moved === "" ? "" : `${moved} `,
|
|
4815
|
+
happened: happened === "" ? "" : `${happened} `,
|
|
4816
|
+
rounds: store.settings().maxRounds
|
|
4817
|
+
}));
|
|
4818
|
+
}
|
|
4819
|
+
}
|
|
4413
4820
|
}
|
|
4414
4821
|
if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
|
|
4415
4822
|
if (ooc !== void 0 && ooc.request === "") {
|
|
@@ -4430,6 +4837,6 @@ function installHooks(ctx, deps) {
|
|
|
4430
4837
|
};
|
|
4431
4838
|
});
|
|
4432
4839
|
}
|
|
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,
|
|
4840
|
+
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
4841
|
|
|
4435
|
-
//# sourceMappingURL=hooks-
|
|
4842
|
+
//# sourceMappingURL=hooks-BdR3mBeM.js.map
|