@dsh-agentic-roleplay/core 0.3.6 → 0.4.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.
Files changed (49) hide show
  1. package/lib/{tools-Dy1fgP6B.js → authoring-tools-C2BHkEFP.js} +129 -25
  2. package/lib/authoring.js +7 -5
  3. package/lib/{child-CFjnaTZt.js → child-DsixtqTw.js} +94 -2
  4. package/lib/client.js +3758 -2276
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +3 -2
  7. package/lib/doctor.js +2 -4
  8. package/lib/{gallery-DIEgETzU.js → gallery-CDYKJf_O.js} +2 -2
  9. package/lib/{generator-DJ48HxPI.js → generator-BR1ugzln.js} +2 -2
  10. package/lib/{deliver-BBgciEEK.js → hooks-CHmUksFS.js} +1963 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +847 -254
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/{lorebook-author-tools-Bj31z1cu.js → lorebook-author-tools-CaT74Q7v.js} +118 -43
  15. package/lib/lorebook-authoring.js +5 -3
  16. package/lib/{settings-CA6icLL_.js → narration-DstnwrvX.js} +148 -2
  17. package/lib/orchestration.js +344 -37
  18. package/lib/{pack-jail-2XztyYAX.js → pack-jail-CEDDI4Xw.js} +170 -13
  19. package/lib/{packs-xHRCcGdb.js → packs-DB_9xiCp.js} +7 -4
  20. package/lib/{presenter-agent-DnNEG_Mn.js → presenter-agent-Gu34bZwd.js} +6 -6
  21. package/lib/preset-BL1d40oG.js +242 -0
  22. package/lib/{preset-author-tools-BxycmoAr.js → preset-author-tools-B2wZXKZo.js} +7 -7
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-gkBWAiVb.js → presets-Dc15L6OU.js} +9 -26
  25. package/lib/{reflection-q0UpwXlx.js → reflection-BWMVdHhR.js} +51 -17
  26. package/package.json +2 -2
  27. package/packs/scene/map.html +1 -0
  28. package/packs/scene/strip.html +1 -0
  29. package/prompts/en/import/lorebook.md +2 -1
  30. package/prompts/en/import/style.md +1 -0
  31. package/prompts/en/lorebook/procedure.md +1 -1
  32. package/prompts/en/preset/procedure.md +1 -1
  33. package/prompts/en/roleplay/character-lookup.md +1 -0
  34. package/prompts/en/roleplay/game-master.md +1 -1
  35. package/prompts/en/roleplay/record-keeper.md +3 -3
  36. package/prompts/en/world/procedure.md +1 -1
  37. package/prompts/zh/import/lorebook.md +2 -1
  38. package/prompts/zh/import/style.md +1 -0
  39. package/prompts/zh/lorebook/procedure.md +1 -1
  40. package/prompts/zh/preset/procedure.md +1 -1
  41. package/prompts/zh/roleplay/character-lookup.md +1 -0
  42. package/prompts/zh/roleplay/game-master.md +1 -1
  43. package/prompts/zh/roleplay/record-keeper.md +3 -3
  44. package/prompts/zh/world/procedure.md +1 -1
  45. package/lib/hooks-DkwFGtNH.js +0 -1060
  46. package/lib/language-BgyxtB2h.js +0 -38
  47. package/lib/load-CVwJjIJ5.js +0 -486
  48. package/lib/narration-DK2kiIjE.js +0 -141
  49. package/lib/preset-D0FMSeZ9.js +0 -59
@@ -1,22 +1,19 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { b as INTENT_STATUSES } from "./presets-gkBWAiVb.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-q0UpwXlx.js";
4
- import "./settings-CA6icLL_.js";
5
- import { C as ReflectionRefusedError } from "./load-CVwJjIJ5.js";
6
- import { B as RESULTS, F as describeWhen, H as languageOf, M as ClockError, S as MAX_OOC_ANSWER, U as translator, m as createTools$1, p as PREVIEW_TOOL, u as externalGiven, w as toolEnabled, x as AUTHORING_NEEDS, z as zoneOf } from "./deliver-BBgciEEK.js";
7
- import { a as liveSettings } from "./narration-DK2kiIjE.js";
8
- import { a as runChild, d as tokensOf, i as childTrace, l as currentTurn, n as childSampling, t as childModel, u as estimateAnswer } from "./child-CFjnaTZt.js";
9
- import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-9JB9zw5a.js";
10
- import { a as wrongLanguage } from "./language-BgyxtB2h.js";
11
- import { _ as API_PREFIX } from "./packs-xHRCcGdb.js";
12
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DIEgETzU.js";
13
- import { a as writeVerdicts, i as readVerdicts, n as installHooks, r as storesOf } from "./hooks-DkwFGtNH.js";
14
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-DnNEG_Mn.js";
2
+ import { b as INTENT_STATUSES } from "./presets-Dc15L6OU.js";
3
+ import { a as whereabouts, g as referent, h as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-BWMVdHhR.js";
4
+ import { a as liveSettings, n as encodeOutput } from "./narration-DstnwrvX.js";
5
+ import { D as zoneOf, E as describeWhen, L as wrongLanguage, O as RESULTS, _ as readVerdicts, at as ReflectionRefusedError, c as record, d as toolEnabled, f as MAX_OOC_ANSWER, l as AUTHORING_NEEDS, lt as languageOf, n as installHooks, o as PREVIEW_TOOL, p as storesOf, r as externalGiven, s as createTools$1, u as characterRunner, ut as translator, v as writeVerdicts, w as ClockError } from "./hooks-CHmUksFS.js";
6
+ import { a as runChild, f as currentTurn, i as childTrace, m as tokensOf, n as childSampling, p as estimateAnswer, t as childModel } from "./child-DsixtqTw.js";
7
+ import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-COIktKBa.js";
8
+ import { _ as API_PREFIX } from "./packs-DB_9xiCp.js";
9
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CDYKJf_O.js";
10
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Gu34bZwd.js";
15
11
  import { join } from "node:path";
16
12
  import { existsSync } from "node:fs";
17
13
  import { SessionId } from "@deepseek-ai/dsh-session";
14
+ import { defineTool } from "@deepseek-ai/dsh-tools";
18
15
  import { readdir } from "node:fs/promises";
19
- import { InvalidEditError, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, parseRecordsEdit, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
16
+ 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";
20
17
  //#region src/host/tools/resource-hint.ts
21
18
  /** 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. */
22
19
  const RESOURCE_HINT_SECTION = "mcp-resource-servers";
@@ -25,7 +22,11 @@ const RESOURCE_TOOLS = [
25
22
  "list_mcp_resource_templates",
26
23
  "read_mcp_resource"
27
24
  ];
28
- const NAMESPACED = /^mcp__(.+?)__.+$/;
25
+ function serverOf(name) {
26
+ if (!name.startsWith("mcp__")) return [];
27
+ const end = name.indexOf("__", 5);
28
+ return end <= 5 || end + 2 >= name.length ? [] : [name.slice(5, end)];
29
+ }
29
30
  /**
30
31
  * What an agent is told about MCP resources: nothing unless it can see a resource tool, since the plugin's own paragraph names the tools
31
32
  * and servers to every agent whether or not it was given them, and an agent that is told of a tool it lacks goes looking for it. The servers are
@@ -34,14 +35,55 @@ const NAMESPACED = /^mcp__(.+?)__.+$/;
34
35
  function resourceHint(visible, registered, tr) {
35
36
  const tools = RESOURCE_TOOLS.filter((name) => visible.includes(name));
36
37
  if (tools.length === 0) return "";
37
- const servers = [...new Set(registered.flatMap((name) => NAMESPACED.exec(name)?.[1] ?? []))].sort();
38
+ const servers = [...new Set(registered.flatMap(serverOf))].sort((a, b) => a.localeCompare(b));
38
39
  return servers.length === 0 ? tr("## MCP resource servers\n\nUse {tools} with the server argument naming an MCP server.", { tools: tools.join(", ") }) : tr("## MCP resource servers\n\nUse {tools} with one of these names as the server argument: {servers}.", {
39
40
  tools: tools.join(", "),
40
41
  servers: JSON.stringify(servers)
41
42
  });
42
43
  }
43
44
  //#endregion
45
+ //#region src/host/memory/tags.ts
46
+ const MIN_FUZZY_LENGTH = 5;
47
+ const plain = (tag) => tag.normalize("NFKC").trim().toLowerCase().replace(/[\s_]+/g, "-");
48
+ /** What two spellings of one word share: separators and a plural ending do not make a different tag. */
49
+ const stem = (tag) => {
50
+ const joined = plain(tag).replace(/-/g, "");
51
+ return /^[a-z]{4,}s$/.test(joined) && !joined.endsWith("ss") ? joined.slice(0, -1) : joined;
52
+ };
53
+ /** Whether two words differ by one letter (a substitution, an insertion or a deletion). */
54
+ function nearby(a, b) {
55
+ if (Math.abs(a.length - b.length) > 1 || a === b) return a === b;
56
+ const [short, long] = a.length <= b.length ? [a, b] : [b, a];
57
+ let index = 0;
58
+ while (index < short.length && short[index] === long[index]) index += 1;
59
+ return short.length === long.length ? short.slice(index + 1) === long.slice(index + 1) : short.slice(index) === long.slice(index + 1);
60
+ }
61
+ /** How often each tag is used by the story's events, most used first: the vocabulary a new tag is chosen from. */
62
+ function tagUsage(events) {
63
+ const counts = /* @__PURE__ */ new Map();
64
+ 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);
65
+ return new Map([...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])));
66
+ }
67
+ /**
68
+ * Brings new tags onto the tags already in use: the same word spelled differently (case,
69
+ * separators, a plural, one letter off in a long word) becomes the existing tag, so recall, which
70
+ * matches tags exactly, finds both. A tag that matches nothing stays: "none fits" is allowed.
71
+ */
72
+ function canonicalTags(known, tags) {
73
+ const vocabulary = [...known.keys()];
74
+ const canonical = tags.map(plain).filter((tag) => tag !== "").map((tag) => {
75
+ if (known.has(tag)) return tag;
76
+ const same = vocabulary.find((existing) => stem(existing) === stem(tag));
77
+ if (same !== void 0) return same;
78
+ if (!/^[a-z]+$/.test(tag) || tag.length < MIN_FUZZY_LENGTH) return tag;
79
+ return vocabulary.find((existing) => /^[a-z]+$/.test(existing) && existing.length >= MIN_FUZZY_LENGTH && nearby(existing, tag)) ?? tag;
80
+ });
81
+ return [...new Set(canonical)];
82
+ }
83
+ //#endregion
44
84
  //#region src/host/orchestration/committer.ts
85
+ /** How many of the tags in use a brief lists. */
86
+ const TAGS_LISTED = 60;
45
87
  /** What the keeper reads back by default: the parts of the records its edits write. */
46
88
  const VERIFY_SECTIONS = [
47
89
  "characters",
@@ -86,6 +128,7 @@ function describePrompt(job, memory) {
86
128
  const records = job.store.story.records({ timeZone: zoneOf(job.store.settings().clock) });
87
129
  const own = job.store.story.records({ rounds }).events;
88
130
  const known = new Map(job.store.cast().map((member) => [member.key, referent(member.character)]));
131
+ const tags = [...tagUsage(job.store.story.events.list())].slice(0, TAGS_LISTED);
89
132
  const before = records.events.filter((event) => event.turn < first.turn || event.turn === first.turn && event.round < first.round).slice(-6);
90
133
  return [
91
134
  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 +144,12 @@ function describePrompt(job, memory) {
101
144
  "## Recorded before these rounds (do not repeat)",
102
145
  ...before.length === 0 ? ["- nothing"] : before.map((event) => `- [turn ${event.turn}] ${event.text}`),
103
146
  "",
104
- "## Already recorded for these rounds (an earlier attempt wrote them: continue from them, do not repeat them)",
147
+ "## 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
148
  ...own.length === 0 ? ["- nothing"] : own.map((event) => `- id ${event.id}, ${label(event)}: ${event.text}`),
106
149
  "",
150
+ "## Tags already in use (choose from these; a new tag only when none fits)",
151
+ ...tags.length === 0 ? ["- none yet"] : [tags.map(([tag, count]) => `${tag} (${count})`).join(", ")],
152
+ "",
107
153
  "## Goals of the characters (ids for intent_edits)",
108
154
  ...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
155
  "",
@@ -179,7 +225,7 @@ function keeperTools(job, memory, progress) {
179
225
  ].join(" ")
180
226
  });
181
227
  if (wording !== void 0) throw new InvalidEditError([wording]);
182
- const result = await tool.execute(args, exec);
228
+ const result = await tool.execute(withKnownTags(args, tagUsage(job.store.story.events.list())), exec);
183
229
  progress.edits += 1;
184
230
  progress.unchecked = true;
185
231
  return result;
@@ -203,6 +249,19 @@ function keeperTools(job, memory, progress) {
203
249
  return tool;
204
250
  });
205
251
  }
252
+ /** The edit with the tags of its new and edited events brought onto the tags already in use. */
253
+ function withKnownTags(args, known) {
254
+ const edit = args;
255
+ const mapped = (entries) => entries?.map((entry) => Array.isArray(entry.tags) ? {
256
+ ...entry,
257
+ tags: canonicalTags(known, entry.tags)
258
+ } : entry);
259
+ return {
260
+ ...edit,
261
+ ...edit.events === void 0 ? {} : { events: mapped(edit.events) },
262
+ ...edit.event_edits === void 0 ? {} : { event_edits: mapped(edit.event_edits) }
263
+ };
264
+ }
206
265
  /** 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
266
  const KEEPER_CHARACTERS_PER_ROUND = 4e3;
208
267
  const keeperEstimate = (rounds, language) => tokensOf(rounds * KEEPER_CHARACTERS_PER_ROUND, language) + 192;
@@ -241,7 +300,10 @@ function recordKeeper(deps) {
241
300
  external: externalGiven(parent.ctx.tools, job.store.settings().tools, "records"),
242
301
  result: RESULT$3,
243
302
  beforeSubmit: () => {
244
- if (progress.edits === 0 && !warned) {
303
+ if (progress.edits === 0 && !warned && job.store.story.records({ rounds: job.rounds.map(({ turn, round }) => ({
304
+ turn,
305
+ round
306
+ })) }).events.length === 0) {
245
307
  warned = true;
246
308
  return "you have written nothing: record the rounds with edit_records. If truly nothing happened, say so in notes and submit again.";
247
309
  }
@@ -614,6 +676,8 @@ function factionStrategist(deps) {
614
676
  }
615
677
  //#endregion
616
678
  //#region src/host/authoring/author-agent.ts
679
+ /** How many calls of the tools of other plugins the author may make on top of its own budget. */
680
+ const EXTERNAL_CALLS = 10;
617
681
  /** A made-up thing in one edit: its name, description and the handful of fields a character, place or item carries. */
618
682
  const THING_TEXTS = 14;
619
683
  const THING_TEXT_CHARS = 300;
@@ -857,6 +921,7 @@ function worldAuthor(deps) {
857
921
  if (parent === void 0) throw new Error(`no agent for chat ${chat}`);
858
922
  return parent;
859
923
  };
924
+ const given = (parent) => deps.external?.(parent) ?? [];
860
925
  return {
861
926
  async create(job, signal) {
862
927
  const parent = parentOf(job.chat);
@@ -872,6 +937,7 @@ function worldAuthor(deps) {
872
937
  persona: promptFor(parent, "world/author", job.store.settings().prompts.language),
873
938
  prompt: createPrompt(job, authoring.perTurn),
874
939
  tools: authorTools(job, work, "create", authoring),
940
+ external: given(parent),
875
941
  result: CREATE_RESULT,
876
942
  beforeSubmit: (value) => {
877
943
  const { outcome } = value;
@@ -880,7 +946,7 @@ function worldAuthor(deps) {
880
946
  const errors = errorsAbout(job.store, work);
881
947
  return errors.length === 0 ? void 0 : `what you made is not usable yet; fix it with edit_world:\n${describeFindings(errors).join("\n")}`;
882
948
  },
883
- maxCalls: 30
949
+ maxCalls: 30 + (given(parent).length > 0 ? EXTERNAL_CALLS : 0)
884
950
  });
885
951
  const label = names(job.store);
886
952
  const created = work.created.map((entry) => ({
@@ -915,6 +981,7 @@ function worldAuthor(deps) {
915
981
  persona: promptFor(parent, "world/consolidate", job.store.settings().prompts.language),
916
982
  prompt: consolidationPrompt(job),
917
983
  tools: authorTools(job, work, "consolidate", authoring),
984
+ external: given(parent),
918
985
  result: CONSOLIDATE_RESULT,
919
986
  beforeSubmit: (value) => {
920
987
  if (!value.complete) return void 0;
@@ -923,7 +990,7 @@ function worldAuthor(deps) {
923
990
  const errors = lintWorld(job.store.story).filter((finding) => finding.severity === "error");
924
991
  return errors.length === 0 ? void 0 : `the world still shows errors:\n${describeFindings(errors).join("\n")}`;
925
992
  },
926
- maxCalls: 60
993
+ maxCalls: 60 + (given(parent).length > 0 ? EXTERNAL_CALLS : 0)
927
994
  });
928
995
  if (!result.complete) throw new Error(`not everything could be fitted in: ${result.notes}`);
929
996
  return {
@@ -939,6 +1006,11 @@ const PROTOCOL_SECTION = "roleplay:protocol";
939
1006
  const PERSONA_SECTION = "roleplay:persona";
940
1007
  //#endregion
941
1008
  //#region src/host/dice/describe.ts
1009
+ const sentenceBody = (value) => {
1010
+ let end = value.length;
1011
+ while (end > 0 && (value[end - 1] === "." || /\s/u.test(value[end - 1]))) end -= 1;
1012
+ return value.slice(0, end);
1013
+ };
942
1014
  /** The checks of a story as the game master is told of them: when each is used, what it rolls and what it needs. The result's bands are told by the roll itself. */
943
1015
  function describeChecks(checks, tr) {
944
1016
  if (checks.length === 0) return tr("No checks are defined: use roll_dice only.");
@@ -952,12 +1024,179 @@ function describeChecks(checks, tr) {
952
1024
  return `${tr("- {key} ({name}): {use}", {
953
1025
  key: check.key,
954
1026
  name: check.name,
955
- use: check.use.replace(/[.\s]+$/, "")
1027
+ use: sentenceBody(check.use)
956
1028
  })}. ${needs.join(" ")}`;
957
1029
  });
958
1030
  return [tr("The checks of this story:"), ...lines].join("\n");
959
1031
  }
960
1032
  //#endregion
1033
+ //#region src/host/orchestration/check-tool.ts
1034
+ const CHECK_NARRATE_TOOL = "roll_and_narrate";
1035
+ const BRANCHES = [
1036
+ ["succeeded", "on_success"],
1037
+ ["partial", "on_partial"],
1038
+ ["failed", "on_failure"]
1039
+ ];
1040
+ const SUMMARY = "What concretely happens to the character, in a sentence. It becomes what the character is doing.";
1041
+ const NARRATION = "What the player reads: narration only, no one else speaks.";
1042
+ /**
1043
+ * 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
1044
+ * delivers the branch they chose. A fast path only: anything that asks characters, moves someone or handles things goes through the ordinary round.
1045
+ */
1046
+ function createCheckNarrateTool(deps) {
1047
+ return defineTool({
1048
+ name: CHECK_NARRATE_TOOL,
1049
+ 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.",
1050
+ parameters: {
1051
+ check: {
1052
+ type: "string",
1053
+ required: true,
1054
+ description: "The key of the check, as list_checks gives it."
1055
+ },
1056
+ character: {
1057
+ type: "string",
1058
+ required: true,
1059
+ description: "The key of the player's character."
1060
+ },
1061
+ reason: {
1062
+ type: "string",
1063
+ required: true,
1064
+ description: "What is attempted, in a sentence."
1065
+ },
1066
+ target: {
1067
+ type: "integer",
1068
+ description: "When the check is read against a target: the difficulty, set by how hard the attempt is. Never 0 to make it easy."
1069
+ },
1070
+ bonus: {
1071
+ type: "integer",
1072
+ description: "What the circumstances add to or take from the roll, from -10 to 10; leave out for none."
1073
+ },
1074
+ on_success: {
1075
+ type: "object",
1076
+ additionalProperties: false,
1077
+ description: "What happens when the attempt succeeds.",
1078
+ properties: {
1079
+ summary: {
1080
+ type: "string",
1081
+ required: true,
1082
+ description: SUMMARY
1083
+ },
1084
+ narration: {
1085
+ type: "string",
1086
+ required: true,
1087
+ description: NARRATION
1088
+ }
1089
+ }
1090
+ },
1091
+ on_partial: {
1092
+ type: "object",
1093
+ additionalProperties: false,
1094
+ description: "What happens when the check gives a partial result; only for a check with a partial band.",
1095
+ properties: {
1096
+ summary: {
1097
+ type: "string",
1098
+ required: true,
1099
+ description: SUMMARY
1100
+ },
1101
+ narration: {
1102
+ type: "string",
1103
+ required: true,
1104
+ description: NARRATION
1105
+ }
1106
+ }
1107
+ },
1108
+ on_failure: {
1109
+ type: "object",
1110
+ additionalProperties: false,
1111
+ description: "What happens when the attempt fails.",
1112
+ properties: {
1113
+ summary: {
1114
+ type: "string",
1115
+ required: true,
1116
+ description: SUMMARY
1117
+ },
1118
+ narration: {
1119
+ type: "string",
1120
+ required: true,
1121
+ description: NARRATION
1122
+ }
1123
+ }
1124
+ }
1125
+ },
1126
+ output: {
1127
+ schema: { type: "json" },
1128
+ render: (_args, value) => {
1129
+ const done = value;
1130
+ return [{
1131
+ type: "text",
1132
+ text: `${done.roll}\nThe output has been delivered to the player. The turn ends here.\n${encodeOutput(done.output)}`
1133
+ }];
1134
+ }
1135
+ },
1136
+ isConcurrencySafe: () => false,
1137
+ async execute(args, exec) {
1138
+ const agent = exec.agent;
1139
+ if (agent === void 0) throw new Error("the roleplay tools can only be called by an agent");
1140
+ const owner = {
1141
+ chat: agent.session.id,
1142
+ turn: deps.turnOf(agent)
1143
+ };
1144
+ await deps.engine.settle(owner.chat, owner.turn);
1145
+ const store = deps.stores(owner.chat);
1146
+ if (store === void 0) throw new Error("this chat is not a roleplay session");
1147
+ const check = store.story.dice.check(args.check);
1148
+ if (check === void 0) throw new Error(`there is no check "${args.check}"; list_checks shows the story's checks`);
1149
+ const problem = deps.engine.soloCheckProblem(owner, args.character);
1150
+ if (problem !== void 0) throw new Error(problem);
1151
+ const given = {
1152
+ succeeded: args.on_success,
1153
+ partial: args.on_partial,
1154
+ failed: args.on_failure
1155
+ };
1156
+ const missing = BRANCHES.filter(([result]) => check.bands.some((band) => band.result === result) && given[result] === void 0).map(([, name]) => name);
1157
+ 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`);
1158
+ const rolled = rollForCheck({
1159
+ session: store.story,
1160
+ turn: owner.turn
1161
+ }, {
1162
+ check: check.key,
1163
+ reason: args.reason,
1164
+ character: args.character,
1165
+ ...args.target === void 0 ? {} : { target: args.target },
1166
+ ...args.bonus === void 0 ? {} : { bonus: args.bonus }
1167
+ });
1168
+ const branch = given[rolled.result];
1169
+ if (branch === void 0) throw new Error(`the roll gave ${rolled.result}, for which no branch was written`);
1170
+ const run = characterRunner({
1171
+ parent: agent,
1172
+ boundaries: deps.boundaries,
1173
+ store
1174
+ });
1175
+ await deps.engine.resolve(owner, [{
1176
+ character: args.character,
1177
+ result: rolled.result,
1178
+ summary: branch.summary,
1179
+ roll: rolled.roll
1180
+ }], run, exec.signal);
1181
+ const output = await deps.engine.narrate(owner, [{
1182
+ type: "narration",
1183
+ text: branch.narration
1184
+ }], run, []).catch((error) => {
1185
+ 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`);
1186
+ });
1187
+ const timelineNode = deps.delivered?.(owner.chat, output);
1188
+ exec.concludeTurn();
1189
+ return record({
1190
+ roll: rolled.text,
1191
+ output: timelineNode === void 0 ? output : {
1192
+ ...output,
1193
+ timelineNode
1194
+ }
1195
+ });
1196
+ }
1197
+ });
1198
+ }
1199
+ //#endregion
961
1200
  //#region src/host/memory/embedding-index.ts
962
1201
  const BATCH = 32;
963
1202
  /**
@@ -1080,6 +1319,36 @@ function rerankMemories(deps) {
1080
1319
  };
1081
1320
  }
1082
1321
  //#endregion
1322
+ //#region src/host/orchestration/suggestion-fallback.ts
1323
+ /**
1324
+ * 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:
1325
+ * someone to talk to, a way out, a thing to look at, then plain standbys. No model is asked.
1326
+ */
1327
+ function fallbackSuggestions(store, count) {
1328
+ const tr = translator(languageOf(store.settings().prompts.language));
1329
+ const player = store.cast().find((member) => member.character.control === "player");
1330
+ const view = player?.place === void 0 ? void 0 : store.place(player.place.location.id);
1331
+ const people = (view?.here ?? []).filter((member) => member.character.id !== player?.character.id).map((member) => tr("Talk to {name}.", { name: member.character.name }));
1332
+ const ways = (view?.exits ?? []).filter(({ exit }) => exit.state === "open").map(({ name }) => tr("Go to {place}.", { place: name }));
1333
+ const things = (view?.items ?? []).filter((item) => !item.hidden).map((item) => tr("Take a closer look at {thing}.", { thing: item.name }));
1334
+ const standbys = [
1335
+ tr("Look around carefully."),
1336
+ tr("Wait and see what happens."),
1337
+ tr("Ask what is going on."),
1338
+ tr("Think about what to do next.")
1339
+ ];
1340
+ const lanes = [
1341
+ people,
1342
+ ways,
1343
+ things
1344
+ ];
1345
+ const picked = [];
1346
+ 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]);
1347
+ for (const line of standbys) if (picked.length < count) picked.push(line);
1348
+ const lines = tidySuggestions(picked).map((line) => line.length > 200 ? `${line.slice(0, 199)}…` : line);
1349
+ return suggestionProblems(lines, count).length === 0 ? lines : [];
1350
+ }
1351
+ //#endregion
1083
1352
  //#region src/host/orchestration/after-turn.ts
1084
1353
  /** Something made up that has waited this many turns is fitted into the world even if few are waiting. */
1085
1354
  const STALE_AFTER_TURNS = 4;
@@ -1534,6 +1803,10 @@ function recordRound(store, owner, state, fire) {
1534
1803
  key: locationKey(playerPlace),
1535
1804
  name: playerPlace.name
1536
1805
  } },
1806
+ present: state.cast.flatMap((member) => member.place === void 0 ? [] : [{
1807
+ character: member.key,
1808
+ place: locationKey(member.place.location)
1809
+ }]),
1537
1810
  time: {
1538
1811
  from: time.from,
1539
1812
  to: time.to,
@@ -1781,7 +2054,7 @@ function asSpoken(segments, spoken) {
1781
2054
  */
1782
2055
  function checkedOutput(narrationChecker, language, state, segments, silent) {
1783
2056
  const problems = [...segments.flatMap((segment, index) => segment.type === "utterance" && segment.character === "" ? [`segment ${index + 1}: an utterance needs the character who says it`] : []), ...narrationChecker.check(segments, state.utterances)];
1784
- const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") });
2057
+ const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") }, { strays: true });
1785
2058
  if (problems.length === 0 && wording !== void 0 && !silent && state.refused < 2) {
1786
2059
  state.refused += 1;
1787
2060
  throw new Error(`the output is not acceptable: ${wording}. Deliver it again with the narration corrected; utterances may not be touched`);
@@ -2081,7 +2354,7 @@ var TurnEngine = class {
2081
2354
  });
2082
2355
  if (keys.length === 0) throw new Error("there is no character to activate");
2083
2356
  if (keys.length > most) throw new Error(`${keys.length} characters were asked, which is more than one round allows (${most}): ask only those the moment actually reaches, and the others in a later round if the story comes to them`);
2084
- const signature = `${[...keys].sort().join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
2357
+ const signature = `${[...keys].sort((a, b) => a.localeCompare(b)).join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
2085
2358
  if (repeatsEarlier(signature, state.asked)) throw new Error("the same characters were already asked about the same situation in this message, so nothing new would come of it: say what changed, ask others, or deliver the output with narrate");
2086
2359
  state.situation = situation;
2087
2360
  state.cast = cast;
@@ -2183,6 +2456,17 @@ var TurnEngine = class {
2183
2456
  };
2184
2457
  return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
2185
2458
  }
2459
+ /** 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. */
2460
+ soloCheckProblem(owner, character) {
2461
+ const state = this.stateFor(owner);
2462
+ const store = this.storeOf(owner);
2463
+ if (state.ooc !== void 0) return "this turn is an out-of-character one: use ooc_ruling or ooc_answer";
2464
+ 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";
2465
+ if (judgeDue(state) || previewDue(state)) return explainPhase(state, "resolve_round");
2466
+ if (state.judgement?.allowed === false) return `the action cannot work (${state.judgement.reason}): play it as a failed attempt with resolve_round, then narrate`;
2467
+ const player = store.cast().find((member) => member.character.control === "player");
2468
+ 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`;
2469
+ }
2186
2470
  /** The key of the player's character. */
2187
2471
  playerKey(state) {
2188
2472
  return state.cast.find((member) => member.character.control === "player")?.key;
@@ -2430,11 +2714,18 @@ var TurnEngine = class {
2430
2714
  spoken(owner) {
2431
2715
  return this.stateFor(owner).utterances;
2432
2716
  }
2433
- /** Whether the game master may still be turned back, counting this objection. */
2434
- object(owner) {
2717
+ /**
2718
+ * 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
2719
+ * 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.
2720
+ */
2721
+ object(owner, missing) {
2435
2722
  const key = `${owner.chat}#${owner.turn}`;
2436
- const count = (this.objections.get(key) ?? 0) + 1;
2437
- this.objections.set(key, count);
2723
+ const last = this.objections.get(key);
2724
+ const count = last?.missing === missing ? last.count + 1 : 1;
2725
+ this.objections.set(key, {
2726
+ missing,
2727
+ count
2728
+ });
2438
2729
  return count <= MAX_OBJECTIONS;
2439
2730
  }
2440
2731
  track(chat, job) {
@@ -2450,7 +2741,7 @@ var TurnEngine = class {
2450
2741
  this.states.get(chat)?.cancel.abort();
2451
2742
  this.reflectionCancels.get(chat)?.abort();
2452
2743
  }
2453
- /** Resolves when nothing of the chat writes to its story any more: the records, what was made up being fitted in, the characters away. */
2744
+ /** 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. */
2454
2745
  async quiesce(chat) {
2455
2746
  for (;;) {
2456
2747
  const jobs = [...this.working.get(chat) ?? [], ...this.chains.has(chat) ? [this.chains.get(chat)] : []];
@@ -2526,7 +2817,7 @@ var TurnEngine = class {
2526
2817
  if (waiting === 0) throw new Error("nothing is waiting to be recorded: the rounds so far are already in the story's records");
2527
2818
  if (focus !== void 0 && focus.trim() !== "") state.focus.push(focus.trim());
2528
2819
  state.requested = true;
2529
- this.write(owner, state);
2820
+ if (this.storeOf(owner).settings().background.concurrent) this.write(owner, state);
2530
2821
  return waiting;
2531
2822
  }
2532
2823
  /** How many recorded rounds wait for their memory to be written. */
@@ -2576,7 +2867,7 @@ var TurnEngine = class {
2576
2867
  const store = this.stores(owner.chat);
2577
2868
  const count = store?.settings().suggestions.count ?? 0;
2578
2869
  if (store === void 0 || count === 0) return;
2579
- this.boundaries().suggester.suggest({
2870
+ this.track(owner.chat, this.boundaries().suggester.suggest({
2580
2871
  chat: owner.chat,
2581
2872
  turn: owner.turn,
2582
2873
  store,
@@ -2593,8 +2884,20 @@ var TurnEngine = class {
2593
2884
  lines
2594
2885
  });
2595
2886
  }).catch((error) => {
2596
- if (!state.cancel.signal.aborted) this.problem(`suggestions for turn ${owner.turn} were not made: ${error instanceof Error ? error.message : String(error)}`);
2597
- });
2887
+ if (state.cancel.signal.aborted) return;
2888
+ this.problem(`suggestions for turn ${owner.turn} were not made: ${error instanceof Error ? error.message : String(error)}`);
2889
+ if (this.states.get(owner.chat) !== state) return;
2890
+ try {
2891
+ const lines = fallbackSuggestions(store, count);
2892
+ if (lines.length > 0) store.putNote({
2893
+ kind: "suggestions",
2894
+ turn: owner.turn,
2895
+ lines
2896
+ });
2897
+ } catch (failed) {
2898
+ this.problem(`suggestions for turn ${owner.turn} could not be made from the story either: ${failed instanceof Error ? failed.message : String(failed)}`);
2899
+ }
2900
+ }));
2598
2901
  }
2599
2902
  /** After the output is delivered: start writing what is due, without waiting for it. */
2600
2903
  startDueWrite(owner, state) {
@@ -2895,7 +3198,10 @@ function apply(ctx) {
2895
3198
  ctx.effect(() => ctx.roleplayOrchestration.replace({ judge: triggerJudge({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: trigger judge");
2896
3199
  ctx.effect(() => ctx.roleplayOrchestration.replace({ strategist: factionStrategist({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: faction strategist");
2897
3200
  ctx.effect(() => ctx.roleplayOrchestration.replace({ reflector: memoryReflector({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: reflection");
2898
- ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: world author");
3201
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({
3202
+ agentOf: (chat) => ctx.agents.get(SessionId(chat)),
3203
+ external: (parent) => ctx.get("roleplayAuthoringTools")?.given(parent.ctx.tools, "worldAuthor") ?? []
3204
+ }) }), "roleplay: world author");
2899
3205
  ctx.effect(() => ctx.roleplayOrchestration.replace({ suggester: suggestionWriter({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: suggestions");
2900
3206
  ctx.effect(() => ctx.roleplayState.bind((agentSessionId) => {
2901
3207
  const id = roleplaySessionOf(agentSessionId);
@@ -2965,7 +3271,7 @@ function apply(ctx) {
2965
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")));
2966
3272
  }
2967
3273
  });
2968
- const [previewTool, ...tools] = [...createTools$1({
3274
+ const toolDeps = {
2969
3275
  engine,
2970
3276
  boundaries,
2971
3277
  stores,
@@ -2975,7 +3281,8 @@ function apply(ctx) {
2975
3281
  if (node !== void 0) images.afterDelivery(chat, node, output);
2976
3282
  return node;
2977
3283
  }
2978
- })].sort((a, b) => Number(b.name === PREVIEW_TOOL) - Number(a.name === PREVIEW_TOOL));
3284
+ };
3285
+ const [previewTool, ...tools] = [...createTools$1(toolDeps)].sort((a, b) => Number(b.name === PREVIEW_TOOL) - Number(a.name === PREVIEW_TOOL));
2979
3286
  for (const tool of tools) ctx.tools.register(tool);
2980
3287
  ctx.effect(() => {
2981
3288
  ctx.roleplayOrchestration.reflect = (chat) => engine.reflect(chat);
@@ -3051,7 +3358,7 @@ function apply(ctx) {
3051
3358
  stores,
3052
3359
  timelines,
3053
3360
  previewTool,
3054
- optionalTools: createDiceTools(diceLink)
3361
+ optionalTools: [...createDiceTools(diceLink), createCheckNarrateTool(toolDeps)]
3055
3362
  });
3056
3363
  }
3057
3364
  //#endregion