@dsh-agentic-roleplay/core 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/lib/{child-DsixtqTw.js → access-tN5D3WI8.js} +21 -14
  2. package/lib/{authoring-tools-C_8ClUkP.js → authoring-tools-Ch_3oIKC.js} +7 -6
  3. package/lib/authoring.js +5 -5
  4. package/lib/client.js +346 -314
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +20 -25
  7. package/lib/doctor.js +3 -3
  8. package/lib/{gallery-CDYKJf_O.js → gallery-C7VOJ3xH.js} +2 -2
  9. package/lib/{generator-BR1ugzln.js → generator-CO8usAjE.js} +2 -2
  10. package/lib/{hooks-B2EhBS_-.js → hooks-C7gt2c01.js} +87 -8
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +34 -23
  13. package/lib/{library-COIktKBa.js → library-DsDc6fQa.js} +2 -2
  14. package/lib/{lorebook-author-tools-C-o0t4dL.js → lorebook-author-tools-DII7Xt7Q.js} +6 -6
  15. package/lib/lorebook-authoring.js +3 -3
  16. package/lib/{narration-BT9uvQry.js → narration-DstnwrvX.js} +4 -1
  17. package/lib/orchestration.js +326 -26
  18. package/lib/{pack-jail-soI-In96.js → pack-jail-AzR6dCNm.js} +10 -10
  19. package/lib/{packs-CJPSe5LI.js → packs-C7g534Mi.js} +2 -2
  20. package/lib/{presenter-agent-Gu34bZwd.js → presenter-agent-BsC6Vftz.js} +5 -6
  21. package/lib/{preset-3zn8xme7.js → preset-Drfu_K-H.js} +3 -3
  22. package/lib/{preset-author-tools-C-X8G40s.js → preset-author-tools-CdIsFhQw.js} +5 -5
  23. package/lib/preset-authoring.js +4 -4
  24. package/lib/{presets-C3mhqqfz.js → presets-CADd77WB.js} +3 -3
  25. package/lib/{reflection-Btsj0ZLh.js → reflection-CUGuPAZR.js} +8 -8
  26. package/lib/text-CT1re6XT.js +18 -0
  27. package/package.json +37 -41
  28. package/prompts/en/roleplay/record-keeper.md +3 -3
  29. package/prompts/zh/roleplay/record-keeper.md +3 -3
  30. package/lib/access-EbNdZFbk.js +0 -25
@@ -1,18 +1,18 @@
1
- import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { b as INTENT_STATUSES } from "./presets-C3mhqqfz.js";
3
- import { a as whereabouts, g as referent, h as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-Btsj0ZLh.js";
4
- import { a as liveSettings } from "./narration-BT9uvQry.js";
5
- import { E as RESULTS, F as wrongLanguage, S as ClockError, T as zoneOf, c as AUTHORING_NEEDS, ct as translator, d as storesOf, g as writeVerdicts, h as readVerdicts, l as toolEnabled, n as installHooks, o as PREVIEW_TOOL, r as externalGiven, rt as ReflectionRefusedError, s as createTools$1, st as languageOf, u as MAX_OOC_ANSWER, w as describeWhen } from "./hooks-B2EhBS_-.js";
6
- import { a as runChild, f as currentTurn, i as childTrace, m as tokensOf, n as childSampling, p as estimateAnswer, t as childModel } from "./child-DsixtqTw.js";
7
- import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-COIktKBa.js";
8
- import { _ as API_PREFIX } from "./packs-CJPSe5LI.js";
9
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CDYKJf_O.js";
10
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Gu34bZwd.js";
1
+ import { _ as roleplaySessionOf, a as childTrace, g as chatSessionId, h as tokensOf, m as estimateAnswer, n as childModel, o as runChild, p as currentTurn, r as childSampling, t as promptFor } from "./access-tN5D3WI8.js";
2
+ import { b as INTENT_STATUSES } from "./presets-CADd77WB.js";
3
+ import { a as whereabouts, g as referent, h as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-CUGuPAZR.js";
4
+ import { a as liveSettings, n as encodeOutput } from "./narration-DstnwrvX.js";
5
+ import { D as zoneOf, E as describeWhen, L as wrongLanguage, O as RESULTS, _ as readVerdicts, at as ReflectionRefusedError, c as record, d as toolEnabled, f as MAX_OOC_ANSWER, l as AUTHORING_NEEDS, lt as languageOf, n as installHooks, o as PREVIEW_TOOL, p as storesOf, r as externalGiven, s as createTools$1, u as characterRunner, ut as translator, v as writeVerdicts, w as ClockError } from "./hooks-C7gt2c01.js";
6
+ import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-DsDc6fQa.js";
7
+ import { _ as API_PREFIX } from "./packs-C7g534Mi.js";
8
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-C7VOJ3xH.js";
9
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-BsC6Vftz.js";
11
10
  import { join } from "node:path";
12
11
  import { existsSync } from "node:fs";
13
12
  import { SessionId } from "@deepseek-ai/dsh-session";
13
+ import { defineTool } from "@deepseek-ai/dsh-tools";
14
14
  import { readdir } from "node:fs/promises";
15
- import { InvalidEditError, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, parseRecordsEdit, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
15
+ import { InvalidEditError, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, parseRecordsEdit, rollForCheck, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
16
16
  //#region src/host/tools/resource-hint.ts
17
17
  /** The name DSH's MCP resource plugin gives the prompt paragraph it adds for every agent; a section of the same name in an agent's scope replaces it. */
18
18
  const RESOURCE_HINT_SECTION = "mcp-resource-servers";
@@ -41,7 +41,48 @@ function resourceHint(visible, registered, tr) {
41
41
  });
42
42
  }
43
43
  //#endregion
44
+ //#region src/host/memory/tags.ts
45
+ const MIN_FUZZY_LENGTH = 5;
46
+ const plain = (tag) => tag.normalize("NFKC").trim().toLowerCase().replace(/[\s_]+/g, "-");
47
+ /** What two spellings of one word share: separators and a plural ending do not make a different tag. */
48
+ const stem = (tag) => {
49
+ const joined = plain(tag).replace(/-/g, "");
50
+ return /^[a-z]{4,}s$/.test(joined) && !joined.endsWith("ss") ? joined.slice(0, -1) : joined;
51
+ };
52
+ /** Whether two words differ by one letter (a substitution, an insertion or a deletion). */
53
+ function nearby(a, b) {
54
+ if (Math.abs(a.length - b.length) > 1 || a === b) return a === b;
55
+ const [short, long] = a.length <= b.length ? [a, b] : [b, a];
56
+ let index = 0;
57
+ while (index < short.length && short[index] === long[index]) index += 1;
58
+ return short.length === long.length ? short.slice(index + 1) === long.slice(index + 1) : short.slice(index) === long.slice(index + 1);
59
+ }
60
+ /** How often each tag is used by the story's events, most used first: the vocabulary a new tag is chosen from. */
61
+ function tagUsage(events) {
62
+ const counts = /* @__PURE__ */ new Map();
63
+ for (const event of events) for (const tag of new Set(event.tags.map(plain))) if (tag !== "") counts.set(tag, (counts.get(tag) ?? 0) + 1);
64
+ return new Map([...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])));
65
+ }
66
+ /**
67
+ * Brings new tags onto the tags already in use: the same word spelled differently (case,
68
+ * separators, a plural, one letter off in a long word) becomes the existing tag, so recall, which
69
+ * matches tags exactly, finds both. A tag that matches nothing stays: "none fits" is allowed.
70
+ */
71
+ function canonicalTags(known, tags) {
72
+ const vocabulary = [...known.keys()];
73
+ const canonical = tags.map(plain).filter((tag) => tag !== "").map((tag) => {
74
+ if (known.has(tag)) return tag;
75
+ const same = vocabulary.find((existing) => stem(existing) === stem(tag));
76
+ if (same !== void 0) return same;
77
+ if (!/^[a-z]+$/.test(tag) || tag.length < MIN_FUZZY_LENGTH) return tag;
78
+ return vocabulary.find((existing) => /^[a-z]+$/.test(existing) && existing.length >= MIN_FUZZY_LENGTH && nearby(existing, tag)) ?? tag;
79
+ });
80
+ return [...new Set(canonical)];
81
+ }
82
+ //#endregion
44
83
  //#region src/host/orchestration/committer.ts
84
+ /** How many of the tags in use a brief lists. */
85
+ const TAGS_LISTED = 60;
45
86
  /** What the keeper reads back by default: the parts of the records its edits write. */
46
87
  const VERIFY_SECTIONS = [
47
88
  "characters",
@@ -86,6 +127,7 @@ function describePrompt(job, memory) {
86
127
  const records = job.store.story.records({ timeZone: zoneOf(job.store.settings().clock) });
87
128
  const own = job.store.story.records({ rounds }).events;
88
129
  const known = new Map(job.store.cast().map((member) => [member.key, referent(member.character)]));
130
+ const tags = [...tagUsage(job.store.story.events.list())].slice(0, TAGS_LISTED);
89
131
  const before = records.events.filter((event) => event.turn < first.turn || event.turn === first.turn && event.round < first.round).slice(-6);
90
132
  return [
91
133
  memory.flaky ? "Perception in this chat: characters do not perceive perfectly. Mark a perception partial only when the character could take in just part of it (overheard, glimpsed), and mistaken only when the material shows it taking in something false; in both cases put the character's own version in content. Otherwise it is accurate and content is left out." : "Perception in this chat: every character perceives exactly what happened. Leave accuracy and content out.",
@@ -101,9 +143,12 @@ function describePrompt(job, memory) {
101
143
  "## Recorded before these rounds (do not repeat)",
102
144
  ...before.length === 0 ? ["- nothing"] : before.map((event) => `- [turn ${event.turn}] ${event.text}`),
103
145
  "",
104
- "## Already recorded for these rounds (an earlier attempt wrote them: continue from them, do not repeat them)",
146
+ "## Already recorded for these rounds (the actions and words of the round, written when it was decided, and anything an earlier attempt added: improve them with event_edits, do not repeat them)",
105
147
  ...own.length === 0 ? ["- nothing"] : own.map((event) => `- id ${event.id}, ${label(event)}: ${event.text}`),
106
148
  "",
149
+ "## Tags already in use (choose from these; a new tag only when none fits)",
150
+ ...tags.length === 0 ? ["- none yet"] : [tags.map(([tag, count]) => `${tag} (${count})`).join(", ")],
151
+ "",
107
152
  "## Goals of the characters (ids for intent_edits)",
108
153
  ...records.characters.flatMap((entry) => entry.goals.map((goal) => `- id ${goal.id}, ${entry.character}: ${goal.name} (${goal.type}, ${goal.status}${goal.deadline === null ? "" : `, deadline ${goal.deadline}`})${goal.plan.length === 0 ? "" : ` plan: ${goal.plan.join("; ")}`}`)).concat(records.characters.every((entry) => entry.goals.length === 0) ? ["- none"] : []),
109
154
  "",
@@ -179,7 +224,7 @@ function keeperTools(job, memory, progress) {
179
224
  ].join(" ")
180
225
  });
181
226
  if (wording !== void 0) throw new InvalidEditError([wording]);
182
- const result = await tool.execute(args, exec);
227
+ const result = await tool.execute(withKnownTags(args, tagUsage(job.store.story.events.list())), exec);
183
228
  progress.edits += 1;
184
229
  progress.unchecked = true;
185
230
  return result;
@@ -203,6 +248,19 @@ function keeperTools(job, memory, progress) {
203
248
  return tool;
204
249
  });
205
250
  }
251
+ /** The edit with the tags of its new and edited events brought onto the tags already in use. */
252
+ function withKnownTags(args, known) {
253
+ const edit = args;
254
+ const mapped = (entries) => entries?.map((entry) => Array.isArray(entry.tags) ? {
255
+ ...entry,
256
+ tags: canonicalTags(known, entry.tags)
257
+ } : entry);
258
+ return {
259
+ ...edit,
260
+ ...edit.events === void 0 ? {} : { events: mapped(edit.events) },
261
+ ...edit.event_edits === void 0 ? {} : { event_edits: mapped(edit.event_edits) }
262
+ };
263
+ }
206
264
  /** What one request of the keeper may carry: the events and what each witness took in, for every round it was given, and the shape of the call. */
207
265
  const KEEPER_CHARACTERS_PER_ROUND = 4e3;
208
266
  const keeperEstimate = (rounds, language) => tokensOf(rounds * KEEPER_CHARACTERS_PER_ROUND, language) + 192;
@@ -241,7 +299,10 @@ function recordKeeper(deps) {
241
299
  external: externalGiven(parent.ctx.tools, job.store.settings().tools, "records"),
242
300
  result: RESULT$3,
243
301
  beforeSubmit: () => {
244
- if (progress.edits === 0 && !warned) {
302
+ if (progress.edits === 0 && !warned && job.store.story.records({ rounds: job.rounds.map(({ turn, round }) => ({
303
+ turn,
304
+ round
305
+ })) }).events.length === 0) {
245
306
  warned = true;
246
307
  return "you have written nothing: record the rounds with edit_records. If truly nothing happened, say so in notes and submit again.";
247
308
  }
@@ -968,6 +1029,173 @@ function describeChecks(checks, tr) {
968
1029
  return [tr("The checks of this story:"), ...lines].join("\n");
969
1030
  }
970
1031
  //#endregion
1032
+ //#region src/host/orchestration/check-tool.ts
1033
+ const CHECK_NARRATE_TOOL = "roll_and_narrate";
1034
+ const BRANCHES = [
1035
+ ["succeeded", "on_success"],
1036
+ ["partial", "on_partial"],
1037
+ ["failed", "on_failure"]
1038
+ ];
1039
+ const SUMMARY = "What concretely happens to the character, in a sentence. It becomes what the character is doing.";
1040
+ const NARRATION = "What the player reads: narration only, no one else speaks.";
1041
+ /**
1042
+ * The game master settles a lone attempt of the player's character in one call: it writes what comes of each way the dice may fall and the code rolls and
1043
+ * delivers the branch they chose. A fast path only: anything that asks characters, moves someone or handles things goes through the ordinary round.
1044
+ */
1045
+ function createCheckNarrateTool(deps) {
1046
+ return defineTool({
1047
+ name: CHECK_NARRATE_TOOL,
1048
+ description: "Settle the player's own uncertain attempt in one step when nobody else needs to react and nothing moves or changes hands: write what comes of each way the check can fall, the dice are rolled for you, and the branch they choose is recorded as the round and delivered as the output, ending the turn. Give a branch for every result the check can give (list_checks shows its bands). The branches you do not get are discarded, so keep each short. When others must react, anything moves or things change hands, use roll_check, resolve_round and narrate instead.",
1049
+ parameters: {
1050
+ check: {
1051
+ type: "string",
1052
+ required: true,
1053
+ description: "The key of the check, as list_checks gives it."
1054
+ },
1055
+ character: {
1056
+ type: "string",
1057
+ required: true,
1058
+ description: "The key of the player's character."
1059
+ },
1060
+ reason: {
1061
+ type: "string",
1062
+ required: true,
1063
+ description: "What is attempted, in a sentence."
1064
+ },
1065
+ target: {
1066
+ type: "integer",
1067
+ description: "When the check is read against a target: the difficulty, set by how hard the attempt is. Never 0 to make it easy."
1068
+ },
1069
+ bonus: {
1070
+ type: "integer",
1071
+ description: "What the circumstances add to or take from the roll, from -10 to 10; leave out for none."
1072
+ },
1073
+ on_success: {
1074
+ type: "object",
1075
+ additionalProperties: false,
1076
+ description: "What happens when the attempt succeeds.",
1077
+ properties: {
1078
+ summary: {
1079
+ type: "string",
1080
+ required: true,
1081
+ description: SUMMARY
1082
+ },
1083
+ narration: {
1084
+ type: "string",
1085
+ required: true,
1086
+ description: NARRATION
1087
+ }
1088
+ }
1089
+ },
1090
+ on_partial: {
1091
+ type: "object",
1092
+ additionalProperties: false,
1093
+ description: "What happens when the check gives a partial result; only for a check with a partial band.",
1094
+ properties: {
1095
+ summary: {
1096
+ type: "string",
1097
+ required: true,
1098
+ description: SUMMARY
1099
+ },
1100
+ narration: {
1101
+ type: "string",
1102
+ required: true,
1103
+ description: NARRATION
1104
+ }
1105
+ }
1106
+ },
1107
+ on_failure: {
1108
+ type: "object",
1109
+ additionalProperties: false,
1110
+ description: "What happens when the attempt fails.",
1111
+ properties: {
1112
+ summary: {
1113
+ type: "string",
1114
+ required: true,
1115
+ description: SUMMARY
1116
+ },
1117
+ narration: {
1118
+ type: "string",
1119
+ required: true,
1120
+ description: NARRATION
1121
+ }
1122
+ }
1123
+ }
1124
+ },
1125
+ output: {
1126
+ schema: { type: "json" },
1127
+ render: (_args, value) => {
1128
+ const done = value;
1129
+ return [{
1130
+ type: "text",
1131
+ text: `${done.roll}\nThe output has been delivered to the player. The turn ends here.\n${encodeOutput(done.output)}`
1132
+ }];
1133
+ }
1134
+ },
1135
+ isConcurrencySafe: () => false,
1136
+ async execute(args, exec) {
1137
+ const agent = exec.agent;
1138
+ if (agent === void 0) throw new Error("the roleplay tools can only be called by an agent");
1139
+ const owner = {
1140
+ chat: agent.session.id,
1141
+ turn: deps.turnOf(agent)
1142
+ };
1143
+ await deps.engine.settle(owner.chat, owner.turn);
1144
+ const store = deps.stores(owner.chat);
1145
+ if (store === void 0) throw new Error("this chat is not a roleplay session");
1146
+ const check = store.story.dice.check(args.check);
1147
+ if (check === void 0) throw new Error(`there is no check "${args.check}"; list_checks shows the story's checks`);
1148
+ const problem = deps.engine.soloCheckProblem(owner, args.character);
1149
+ if (problem !== void 0) throw new Error(problem);
1150
+ const given = {
1151
+ succeeded: args.on_success,
1152
+ partial: args.on_partial,
1153
+ failed: args.on_failure
1154
+ };
1155
+ const missing = BRANCHES.filter(([result]) => check.bands.some((band) => band.result === result) && given[result] === void 0).map(([, name]) => name);
1156
+ if (missing.length > 0) throw new Error(`the check "${check.key}" can give ${[...new Set(check.bands.map((band) => band.result))].join(", ")}: give ${missing.join(" and ")} too; nothing was rolled`);
1157
+ const rolled = rollForCheck({
1158
+ session: store.story,
1159
+ turn: owner.turn
1160
+ }, {
1161
+ check: check.key,
1162
+ reason: args.reason,
1163
+ character: args.character,
1164
+ ...args.target === void 0 ? {} : { target: args.target },
1165
+ ...args.bonus === void 0 ? {} : { bonus: args.bonus }
1166
+ });
1167
+ const branch = given[rolled.result];
1168
+ if (branch === void 0) throw new Error(`the roll gave ${rolled.result}, for which no branch was written`);
1169
+ const run = characterRunner({
1170
+ parent: agent,
1171
+ boundaries: deps.boundaries,
1172
+ store
1173
+ });
1174
+ await deps.engine.resolve(owner, [{
1175
+ character: args.character,
1176
+ result: rolled.result,
1177
+ summary: branch.summary,
1178
+ roll: rolled.roll
1179
+ }], run, exec.signal);
1180
+ const output = await deps.engine.narrate(owner, [{
1181
+ type: "narration",
1182
+ text: branch.narration
1183
+ }], run, []).catch((error) => {
1184
+ throw new Error(`${error instanceof Error ? error.message : String(error)}. The roll (${rolled.roll}: ${rolled.result}) and the round are already recorded: do not roll again, call narrate with the output`);
1185
+ });
1186
+ const timelineNode = deps.delivered?.(owner.chat, output);
1187
+ exec.concludeTurn();
1188
+ return record({
1189
+ roll: rolled.text,
1190
+ output: timelineNode === void 0 ? output : {
1191
+ ...output,
1192
+ timelineNode
1193
+ }
1194
+ });
1195
+ }
1196
+ });
1197
+ }
1198
+ //#endregion
971
1199
  //#region src/host/memory/embedding-index.ts
972
1200
  const BATCH = 32;
973
1201
  /**
@@ -1090,6 +1318,36 @@ function rerankMemories(deps) {
1090
1318
  };
1091
1319
  }
1092
1320
  //#endregion
1321
+ //#region src/host/orchestration/suggestion-fallback.ts
1322
+ /**
1323
+ * Lines made from the story's own data when the suggester could not make any, so the player is never left with an empty tray:
1324
+ * someone to talk to, a way out, a thing to look at, then plain standbys. No model is asked.
1325
+ */
1326
+ function fallbackSuggestions(store, count) {
1327
+ const tr = translator(languageOf(store.settings().prompts.language));
1328
+ const player = store.cast().find((member) => member.character.control === "player");
1329
+ const view = player?.place === void 0 ? void 0 : store.place(player.place.location.id);
1330
+ const people = (view?.here ?? []).filter((member) => member.character.id !== player?.character.id).map((member) => tr("Talk to {name}.", { name: member.character.name }));
1331
+ const ways = (view?.exits ?? []).filter(({ exit }) => exit.state === "open").map(({ name }) => tr("Go to {place}.", { place: name }));
1332
+ const things = (view?.items ?? []).filter((item) => !item.hidden).map((item) => tr("Take a closer look at {thing}.", { thing: item.name }));
1333
+ const standbys = [
1334
+ tr("Look around carefully."),
1335
+ tr("Wait and see what happens."),
1336
+ tr("Ask what is going on."),
1337
+ tr("Think about what to do next.")
1338
+ ];
1339
+ const lanes = [
1340
+ people,
1341
+ ways,
1342
+ things
1343
+ ];
1344
+ const picked = [];
1345
+ for (let round = 0; picked.length < count && lanes.some((lane) => lane.length > round); round++) for (const lane of lanes) if (picked.length < count && lane[round] !== void 0) picked.push(lane[round]);
1346
+ for (const line of standbys) if (picked.length < count) picked.push(line);
1347
+ const lines = tidySuggestions(picked).map((line) => line.length > 200 ? `${line.slice(0, 199)}…` : line);
1348
+ return suggestionProblems(lines, count).length === 0 ? lines : [];
1349
+ }
1350
+ //#endregion
1093
1351
  //#region src/host/orchestration/after-turn.ts
1094
1352
  /** Something made up that has waited this many turns is fitted into the world even if few are waiting. */
1095
1353
  const STALE_AFTER_TURNS = 4;
@@ -1544,6 +1802,10 @@ function recordRound(store, owner, state, fire) {
1544
1802
  key: locationKey(playerPlace),
1545
1803
  name: playerPlace.name
1546
1804
  } },
1805
+ present: state.cast.flatMap((member) => member.place === void 0 ? [] : [{
1806
+ character: member.key,
1807
+ place: locationKey(member.place.location)
1808
+ }]),
1547
1809
  time: {
1548
1810
  from: time.from,
1549
1811
  to: time.to,
@@ -2193,6 +2455,17 @@ var TurnEngine = class {
2193
2455
  };
2194
2456
  return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
2195
2457
  }
2458
+ /** Why a lone check of the player's character cannot be rolled, recorded and narrated in one call, if it cannot: nothing is rolled until this is clear. */
2459
+ soloCheckProblem(owner, character) {
2460
+ const state = this.stateFor(owner);
2461
+ const store = this.storeOf(owner);
2462
+ if (state.ooc !== void 0) return "this turn is an out-of-character one: use ooc_ruling or ooc_answer";
2463
+ if (state.phase !== "idle" || state.rounds > 0) return "characters were already played in this turn: roll with roll_check, decide with resolve_round and deliver with narrate";
2464
+ if (judgeDue(state) || previewDue(state)) return explainPhase(state, "resolve_round");
2465
+ if (state.judgement?.allowed === false) return `the action cannot work (${state.judgement.reason}): play it as a failed attempt with resolve_round, then narrate`;
2466
+ const player = store.cast().find((member) => member.character.control === "player");
2467
+ return player?.key === character ? void 0 : `this is only for the player's character${player === void 0 ? "" : ` (${player.key})`}: anyone else's attempt goes through activate_characters`;
2468
+ }
2196
2469
  /** The key of the player's character. */
2197
2470
  playerKey(state) {
2198
2471
  return state.cast.find((member) => member.character.control === "player")?.key;
@@ -2440,11 +2713,18 @@ var TurnEngine = class {
2440
2713
  spoken(owner) {
2441
2714
  return this.stateFor(owner).utterances;
2442
2715
  }
2443
- /** Whether the game master may still be turned back, counting this objection. */
2444
- object(owner) {
2716
+ /**
2717
+ * Whether the game master may still be turned back, counting this objection. Only objections that get nowhere count: a turn that has moved on since the
2718
+ * last one (what is missing changed) starts the count again, because a turn cut short by a model's output limit has to be steered through every step.
2719
+ */
2720
+ object(owner, missing) {
2445
2721
  const key = `${owner.chat}#${owner.turn}`;
2446
- const count = (this.objections.get(key) ?? 0) + 1;
2447
- this.objections.set(key, count);
2722
+ const last = this.objections.get(key);
2723
+ const count = last?.missing === missing ? last.count + 1 : 1;
2724
+ this.objections.set(key, {
2725
+ missing,
2726
+ count
2727
+ });
2448
2728
  return count <= MAX_OBJECTIONS;
2449
2729
  }
2450
2730
  track(chat, job) {
@@ -2460,7 +2740,7 @@ var TurnEngine = class {
2460
2740
  this.states.get(chat)?.cancel.abort();
2461
2741
  this.reflectionCancels.get(chat)?.abort();
2462
2742
  }
2463
- /** Resolves when nothing of the chat writes to its story any more: the records, what was made up being fitted in, the characters away. */
2743
+ /** Resolves when nothing of the chat writes to its story any more: the records, what was made up being fitted in, the characters away, the suggestions. */
2464
2744
  async quiesce(chat) {
2465
2745
  for (;;) {
2466
2746
  const jobs = [...this.working.get(chat) ?? [], ...this.chains.has(chat) ? [this.chains.get(chat)] : []];
@@ -2536,7 +2816,7 @@ var TurnEngine = class {
2536
2816
  if (waiting === 0) throw new Error("nothing is waiting to be recorded: the rounds so far are already in the story's records");
2537
2817
  if (focus !== void 0 && focus.trim() !== "") state.focus.push(focus.trim());
2538
2818
  state.requested = true;
2539
- this.write(owner, state);
2819
+ if (this.storeOf(owner).settings().background.concurrent) this.write(owner, state);
2540
2820
  return waiting;
2541
2821
  }
2542
2822
  /** How many recorded rounds wait for their memory to be written. */
@@ -2586,7 +2866,7 @@ var TurnEngine = class {
2586
2866
  const store = this.stores(owner.chat);
2587
2867
  const count = store?.settings().suggestions.count ?? 0;
2588
2868
  if (store === void 0 || count === 0) return;
2589
- this.boundaries().suggester.suggest({
2869
+ this.track(owner.chat, this.boundaries().suggester.suggest({
2590
2870
  chat: owner.chat,
2591
2871
  turn: owner.turn,
2592
2872
  store,
@@ -2603,8 +2883,20 @@ var TurnEngine = class {
2603
2883
  lines
2604
2884
  });
2605
2885
  }).catch((error) => {
2606
- if (!state.cancel.signal.aborted) this.problem(`suggestions for turn ${owner.turn} were not made: ${error instanceof Error ? error.message : String(error)}`);
2607
- });
2886
+ if (state.cancel.signal.aborted) return;
2887
+ this.problem(`suggestions for turn ${owner.turn} were not made: ${error instanceof Error ? error.message : String(error)}`);
2888
+ if (this.states.get(owner.chat) !== state) return;
2889
+ try {
2890
+ const lines = fallbackSuggestions(store, count);
2891
+ if (lines.length > 0) store.putNote({
2892
+ kind: "suggestions",
2893
+ turn: owner.turn,
2894
+ lines
2895
+ });
2896
+ } catch (failed) {
2897
+ this.problem(`suggestions for turn ${owner.turn} could not be made from the story either: ${failed instanceof Error ? failed.message : String(failed)}`);
2898
+ }
2899
+ }));
2608
2900
  }
2609
2901
  /** After the output is delivered: start writing what is due, without waiting for it. */
2610
2902
  startDueWrite(owner, state) {
@@ -2857,6 +3149,7 @@ var ImageJobs = class {
2857
3149
  };
2858
3150
  //#endregion
2859
3151
  //#region src/orchestration.ts
3152
+ const WORKING_DIRECTORY_CONTEXT = "working-directory:current";
2860
3153
  const name = "@dsh-agentic-roleplay/core/orchestration";
2861
3154
  /**
2862
3155
  * Mounted by the `roleplay` agent preset, so it applies to roleplay chats only.
@@ -2978,7 +3271,13 @@ function apply(ctx) {
2978
3271
  return resourceHint(ctx.tools.schemas(context.scope).map((tool) => tool.name), ctx.tools.schemas().map((tool) => tool.name), translator(languageOf(chat?.settings.prompts.language ?? "en")));
2979
3272
  }
2980
3273
  });
2981
- const [previewTool, ...tools] = [...createTools$1({
3274
+ ctx.systemPrompt.context({
3275
+ name: WORKING_DIRECTORY_CONTEXT,
3276
+ order: ctx.systemPrompt.getContextOrder("WORKING_DIRECTORY"),
3277
+ interpolate: false,
3278
+ text: ""
3279
+ });
3280
+ const toolDeps = {
2982
3281
  engine,
2983
3282
  boundaries,
2984
3283
  stores,
@@ -2988,7 +3287,8 @@ function apply(ctx) {
2988
3287
  if (node !== void 0) images.afterDelivery(chat, node, output);
2989
3288
  return node;
2990
3289
  }
2991
- })].sort((a, b) => Number(b.name === PREVIEW_TOOL) - Number(a.name === PREVIEW_TOOL));
3290
+ };
3291
+ const [previewTool, ...tools] = [...createTools$1(toolDeps)].sort((a, b) => Number(b.name === PREVIEW_TOOL) - Number(a.name === PREVIEW_TOOL));
2992
3292
  for (const tool of tools) ctx.tools.register(tool);
2993
3293
  ctx.effect(() => {
2994
3294
  ctx.roleplayOrchestration.reflect = (chat) => engine.reflect(chat);
@@ -3064,7 +3364,7 @@ function apply(ctx) {
3064
3364
  stores,
3065
3365
  timelines,
3066
3366
  previewTool,
3067
- optionalTools: createDiceTools(diceLink)
3367
+ optionalTools: [...createDiceTools(diceLink), createCheckNarrateTool(toolDeps)]
3068
3368
  });
3069
3369
  }
3070
3370
  //#endregion
@@ -1,12 +1,12 @@
1
- import { $ as LOCATION_FILE_NAME, A as loadTriggers, At as parseLoreFile, B as loadItems, C as populateLocations, D as populateVariables, Dt as LORE_DIR, F as loadCalendar, G as extractStyleFrom, H as loadFactions, J as withPlayer, L as LOCATIONS_DIR, Mt as InvalidEditProblems, Ot as loadLore, R as loadLocations, U as CHARACTERS_DIR, V as FACTIONS_DIR, W as loadCharacters, X as loadVariables, _ as populateCharacters, at as CHARACTER_FILE_NAME, c as authoredWorldOf, dt as WORLD_FILE_NAME, et as parseLocationFile, ft as parseWorldFile, h as knowsCharacter, i as contextOf, it as parseFactionFile, jt as subfolders, k as TRIGGERS_FILE_NAME, kt as LORE_FILE_NAME, m as loadValidatedWorld, nt as parseItemFile, ot as parseCharacterFile, rt as FACTION_FILE_NAME, s as worldOf, st as IMPORT_FOLDER, tt as ITEM_FILE_NAME, x as populateItems, z as ITEMS_DIR } from "./authoring-tools-C_8ClUkP.js";
2
- import { v as writeWorldPrompt } from "./presets-C3mhqqfz.js";
3
- import { f as parseSwitchboard } from "./narration-BT9uvQry.js";
4
- import { G as PROMPTS_FOLDER, H as formatIssue, I as PLOTS_FILE_NAME, L as loadPlots, M as STORY_LANGUAGES, N as isStoryLanguage, P as textLanguage, Q as shippedLanguages, R as parsePlotsFile, j as LANGUAGE_NAMES, nt as InvalidWorldError, z as plotReferenceProblems } from "./hooks-B2EhBS_-.js";
5
- import { s as parseSampling } from "./child-DsixtqTw.js";
6
- import { c as referenceImagePath, v as mapLimit } from "./library-COIktKBa.js";
7
- import { n as readPreset } from "./preset-3zn8xme7.js";
8
- import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-CJPSe5LI.js";
9
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BR1ugzln.js";
1
+ import { c as parseSampling } from "./access-tN5D3WI8.js";
2
+ import { $ as LOCATION_FILE_NAME, A as loadTriggers, At as parseLoreFile, B as loadItems, C as populateLocations, D as populateVariables, Dt as LORE_DIR, F as loadCalendar, G as extractStyleFrom, H as loadFactions, J as withPlayer, L as LOCATIONS_DIR, Mt as InvalidEditProblems, Ot as loadLore, R as loadLocations, U as CHARACTERS_DIR, V as FACTIONS_DIR, W as loadCharacters, X as loadVariables, _ as populateCharacters, at as CHARACTER_FILE_NAME, c as authoredWorldOf, dt as WORLD_FILE_NAME, et as parseLocationFile, ft as parseWorldFile, h as knowsCharacter, i as contextOf, it as parseFactionFile, jt as subfolders, k as TRIGGERS_FILE_NAME, kt as LORE_FILE_NAME, m as loadValidatedWorld, nt as parseItemFile, ot as parseCharacterFile, rt as FACTION_FILE_NAME, s as worldOf, st as IMPORT_FOLDER, tt as ITEM_FILE_NAME, x as populateItems, z as ITEMS_DIR } from "./authoring-tools-Ch_3oIKC.js";
3
+ import { v as writeWorldPrompt } from "./presets-CADd77WB.js";
4
+ import { f as parseSwitchboard } from "./narration-DstnwrvX.js";
5
+ import { B as parsePlotsFile, F as isStoryLanguage, I as textLanguage, N as LANGUAGE_NAMES, P as STORY_LANGUAGES, R as PLOTS_FILE_NAME, V as plotReferenceProblems, W as formatIssue, et as shippedLanguages, it as InvalidWorldError, q as PROMPTS_FOLDER, z as loadPlots } from "./hooks-C7gt2c01.js";
6
+ import { c as referenceImagePath, v as mapLimit } from "./library-DsDc6fQa.js";
7
+ import { n as readPreset } from "./preset-Drfu_K-H.js";
8
+ import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-C7g534Mi.js";
9
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-CO8usAjE.js";
10
10
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
11
  import { existsSync, lstatSync, statSync } from "node:fs";
12
12
  import { randomUUID } from "node:crypto";
@@ -2134,4 +2134,4 @@ function registerPackJail(ctx, deps) {
2134
2134
  //#endregion
2135
2135
  export { worldEntityImageFile as A, readWorldInfo as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile$1 as E, loadWorldParts as F, translateTools as H, PRESET_FILE as I, presetMessage as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, presetTools as R, generateWorldEntityImage as S, removeWorldTrigger as T, languageOfDocuments as U, translateMessage as V, readWorldDocuments as W, editWorldPlots as _, deleteWorldPackFile as a, entityFolder as b, createAuthoredEntity as c, replaceAuthoredEntity as d, editWorldCharacter as f, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, editWorldLore as m, packFileProblem as n, listWorldPacks as o, editWorldFaction as p, registerPackJail as r, AUTHORED_ENTITY_KINDS as s, MAX_PACK_TEXT as t, readAuthoredEntityDocument as u, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, editWorldInfo as z };
2136
2136
 
2137
- //# sourceMappingURL=pack-jail-soI-In96.js.map
2137
+ //# sourceMappingURL=pack-jail-AzR6dCNm.js.map
@@ -1,4 +1,4 @@
1
- import { V as Reader } from "./hooks-B2EhBS_-.js";
1
+ import { U as Reader } from "./hooks-C7gt2c01.js";
2
2
  import { dirname, extname, join, posix, sep } from "node:path";
3
3
  import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
4
4
  import { createHash } from "node:crypto";
@@ -840,4 +840,4 @@ function anyTab(bases) {
840
840
  //#endregion
841
841
  export { API_PREFIX as _, packIds as a, describePack as c, packPath as d, readPack as f, SURFACE_NAMES as g, PACK_MEDIA_TYPES as h, inheritPacks as i, isPackId as l, PACK_LIMITS as m, anyTab as n, syncWorldPacks as o, PACK_ACTIONS as p, copyWorldPacks as r, worldPackStates as s, activePack as t, packFile as u };
842
842
 
843
- //# sourceMappingURL=packs-CJPSe5LI.js.map
843
+ //# sourceMappingURL=packs-C7g534Mi.js.map
@@ -1,8 +1,7 @@
1
- import { t as promptFor } from "./access-EbNdZFbk.js";
2
- import { a as runChild } from "./child-DsixtqTw.js";
3
- import { c as referenceImagePath, o as nextSceneSerial } from "./library-COIktKBa.js";
4
- import { n as generateTransientImage, t as generateReferenceImage } from "./generator-BR1ugzln.js";
5
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CDYKJf_O.js";
1
+ import { o as runChild, t as promptFor } from "./access-tN5D3WI8.js";
2
+ import { c as referenceImagePath, o as nextSceneSerial } from "./library-DsDc6fQa.js";
3
+ import { n as generateTransientImage, t as generateReferenceImage } from "./generator-CO8usAjE.js";
4
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-C7VOJ3xH.js";
6
5
  import { dirname, join, relative } from "node:path";
7
6
  import { existsSync } from "node:fs";
8
7
  import { createHash, randomUUID } from "node:crypto";
@@ -852,4 +851,4 @@ async function runImagePresenter(job) {
852
851
  //#endregion
853
852
  export { tokensOf as a, searchImages as i, interpretImage as n, present as o, imageTools as r, presentedFor as s, runImagePresenter as t };
854
853
 
855
- //# sourceMappingURL=presenter-agent-Gu34bZwd.js.map
854
+ //# sourceMappingURL=presenter-agent-BsC6Vftz.js.map
@@ -1,5 +1,5 @@
1
- import { Bt as ImportCardError, K as cleanText, r as MAX_PREVIEW_TEXT } from "./authoring-tools-C_8ClUkP.js";
2
- import { o as SAMPLING_RANGES } from "./child-DsixtqTw.js";
1
+ import { s as SAMPLING_RANGES } from "./access-tN5D3WI8.js";
2
+ import { Bt as ImportCardError, K as cleanText, r as MAX_PREVIEW_TEXT } from "./authoring-tools-Ch_3oIKC.js";
3
3
  //#region src/host/import/preset.ts
4
4
  /** The older preset layout keeps its texts under fixed keys. */
5
5
  const LEGACY_KEYS = [
@@ -239,4 +239,4 @@ function selectPrompts(file, enabled, keepSampling) {
239
239
  //#endregion
240
240
  export { readPreset as n, selectPrompts as r, previewPreset as t };
241
241
 
242
- //# sourceMappingURL=preset-3zn8xme7.js.map
242
+ //# sourceMappingURL=preset-Drfu_K-H.js.map
@@ -1,7 +1,7 @@
1
- import { G as extractStyleFrom, J as withPlayer, i as contextOf, st as IMPORT_FOLDER } from "./authoring-tools-C_8ClUkP.js";
2
- import { _ as readWorldPrompt, c as presetDirectory, g as listWorldPrompts, h as deleteWorldPrompt, l as readPreset, m as PROSE_PROMPTS, p as updatePresetInfo, t as PRESET_FILE, v as writeWorldPrompt } from "./presets-C3mhqqfz.js";
3
- import { $ as shippedPromptsDirectory, Q as shippedLanguages, Y as languageOf } from "./hooks-B2EhBS_-.js";
4
- import { n as readPreset$1 } from "./preset-3zn8xme7.js";
1
+ import { G as extractStyleFrom, J as withPlayer, i as contextOf, st as IMPORT_FOLDER } from "./authoring-tools-Ch_3oIKC.js";
2
+ import { _ as readWorldPrompt, c as presetDirectory, g as listWorldPrompts, h as deleteWorldPrompt, l as readPreset, m as PROSE_PROMPTS, p as updatePresetInfo, t as PRESET_FILE, v as writeWorldPrompt } from "./presets-CADd77WB.js";
3
+ import { Z as languageOf, et as shippedLanguages, tt as shippedPromptsDirectory } from "./hooks-C7gt2c01.js";
4
+ import { n as readPreset$1 } from "./preset-Drfu_K-H.js";
5
5
  import { join } from "node:path";
6
6
  import { existsSync } from "node:fs";
7
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -273,4 +273,4 @@ async function presetApproval(exec, next, carries) {
273
273
  //#endregion
274
274
  export { presetChatSessionId as a, presetAuthorTools as i, narrationImportMessage as n, presetOfChat as o, presetApproval as r, PresetReader as t };
275
275
 
276
- //# sourceMappingURL=preset-author-tools-C-X8G40s.js.map
276
+ //# sourceMappingURL=preset-author-tools-CdIsFhQw.js.map
@@ -1,7 +1,7 @@
1
- import { n as limitAuthoringAgents } from "./authoring-tools-C_8ClUkP.js";
2
- import { c as presetDirectory } from "./presets-C3mhqqfz.js";
3
- import "./hooks-B2EhBS_-.js";
4
- import { i as presetAuthorTools, o as presetOfChat, r as presetApproval, t as PresetReader } from "./preset-author-tools-C-X8G40s.js";
1
+ import { n as limitAuthoringAgents } from "./authoring-tools-Ch_3oIKC.js";
2
+ import { c as presetDirectory } from "./presets-CADd77WB.js";
3
+ import "./hooks-C7gt2c01.js";
4
+ import { i as presetAuthorTools, o as presetOfChat, r as presetApproval, t as PresetReader } from "./preset-author-tools-CdIsFhQw.js";
5
5
  import { join } from "node:path";
6
6
  import { existsSync } from "node:fs";
7
7
  //#region src/preset-authoring.ts
@@ -1,5 +1,5 @@
1
- import { $ as shippedPromptsDirectory, G as PROMPTS_FOLDER, Q as shippedLanguages, W as LANGUAGE_FOLDER, X as listFiles, Y as languageOf, Z as promptProblem } from "./hooks-B2EhBS_-.js";
2
- import { s as parseSampling } from "./child-DsixtqTw.js";
1
+ import { c as parseSampling } from "./access-tN5D3WI8.js";
2
+ import { $ as promptProblem, K as LANGUAGE_FOLDER, Q as listFiles, Z as languageOf, et as shippedLanguages, q as PROMPTS_FOLDER, tt as shippedPromptsDirectory } from "./hooks-C7gt2c01.js";
3
3
  import { dirname, join } from "node:path";
4
4
  import { existsSync, readFileSync, readdirSync } from "node:fs";
5
5
  import { createHash } from "node:crypto";
@@ -354,4 +354,4 @@ async function createPresetFromGuidance(root, request, guidance, shipped = shipp
354
354
  //#endregion
355
355
  export { readWorldPrompt as _, isPresetName as a, INTENT_STATUSES as b, presetDirectory as c, savePresetFromWorld as d, sha as f, listWorldPrompts as g, deleteWorldPrompt as h, deletePreset as i, readPreset as l, PROSE_PROMPTS as m, createPresetFromGuidance as n, listPresets as o, updatePresetInfo as p, createPresetFromShipped as r, loadPreset as s, PRESET_FILE as t, reservePreset as u, writeWorldPrompt as v, INTENT_TYPES as x, INTENT_HORIZONS as y };
356
356
 
357
- //# sourceMappingURL=presets-C3mhqqfz.js.map
357
+ //# sourceMappingURL=presets-CADd77WB.js.map