@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
package/lib/compaction.js CHANGED
@@ -1,5 +1,5 @@
1
- import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { a as liveSettings, t as decodeOutput } from "./narration-BT9uvQry.js";
1
+ import { _ as roleplaySessionOf, h as tokensOf, n as childModel, o as runChild, r as childSampling, t as promptFor } from "./access-tN5D3WI8.js";
2
+ import { a as liveSettings, t as decodeOutput } from "./narration-DstnwrvX.js";
3
3
  import { join } from "node:path";
4
4
  import { sessionFolder } from "@dsh-agentic-roleplay/state";
5
5
  import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
@@ -137,30 +137,23 @@ const SUMMARY_SCHEMA = {
137
137
  required: ["summary"],
138
138
  additionalProperties: false
139
139
  };
140
- /** Writes each passage with a one-shot sub-agent of the game master that has the chronicler's persona and no tools. */
141
- function subagentChronicler(subagents, parent, language) {
140
+ /** Writes each passage with a one-shot child of the game master that has the chronicler's persona and no tools of its own. */
141
+ function childChronicler(parent, settings) {
142
+ const language = settings.prompts.language;
142
143
  return { async write({ task, material, words }, signal) {
143
- const run = await subagents.start("spawn", {
144
+ const estimate = tokensOf(words * (language.toLowerCase().startsWith("zh") ? 1 : 6), language) + 8;
145
+ return (await runChild({
144
146
  parent,
145
147
  signal,
146
- label: "Chronicler",
147
- prompt: [{
148
- type: "text",
149
- text: `${task}\n\nWrite at most ${words} words.\n\n${material}`
150
- }],
148
+ reasoningEffort: settings.reasoning.children,
149
+ sampling: childSampling(settings, "records", estimate),
150
+ ...childModel(settings, "records"),
151
151
  persona: promptFor(parent, "roleplay/chronicler", language),
152
- toolFilter: { allow: [] },
153
- outputSchema: SUMMARY_SCHEMA
154
- });
155
- try {
156
- const result = await run.result;
157
- if (result.stopReason !== "completed") throw new Error(`the chronicler did not finish (${result.stopReason})`);
158
- const text = result.structured?.summary;
159
- if (typeof text !== "string" || text.trim() === "") throw new Error("the chronicler wrote nothing");
160
- return text;
161
- } finally {
162
- await run.dispose();
163
- }
152
+ prompt: `${task}\n\nWrite at most ${words} words.\n\n${material}`,
153
+ result: SUMMARY_SCHEMA,
154
+ beforeSubmit: (value) => value.summary?.trim() === "" ? "the passage is empty: write it" : void 0,
155
+ maxCalls: 3
156
+ })).summary;
164
157
  } };
165
158
  }
166
159
  //#endregion
@@ -292,14 +285,16 @@ var RoleplayCompaction = class extends BasicCompactionEngine {
292
285
  if (config?.provider === void 0 || config.model === void 0) throw new Error("the conversation limit follows the model, but this chat has none selected: set the limit in the chat settings");
293
286
  const window = (await this.ctx.llm.resolveModelInfo(config.provider, config.model, signal)).context?.contextWindow;
294
287
  if (window === void 0) throw new Error(`the conversation limit follows the model, but the context window of ${config.provider}/${config.model} is not known: set the limit in the chat settings or the model's contextWindow in the provider`);
295
- return Math.max(MIN_LIMIT, Math.round(window * context.limitRatio));
288
+ const share = Math.round(window * context.limitRatio);
289
+ return Math.max(MIN_LIMIT, context.workingTokens > 0 ? Math.min(share, context.workingTokens) : share);
296
290
  }
297
291
  async summarize(input, agent, signal) {
298
292
  const fold = this.folds.get(agent.session.id);
299
293
  if (fold === void 0) return super.summarize(input, agent, signal);
300
294
  const story = this.ctx.roleplayState.openSession(this.sessionsDir(), fold.id);
301
- const { context, prompts } = liveSettings(fold.folder);
302
- const chronicler = subagentChronicler(this.ctx.subagents, agent, prompts.language);
295
+ const settings = liveSettings(fold.folder);
296
+ const { context, prompts } = settings;
297
+ const chronicler = childChronicler(agent, settings);
303
298
  const { playerInputs, transcript } = readFolded(input.messages);
304
299
  await foldSummaries({
305
300
  story,
package/lib/doctor.js CHANGED
@@ -1,6 +1,6 @@
1
- import { n as chatSessionId } from "./access-EbNdZFbk.js";
2
- import { a as liveSettings } from "./narration-BT9uvQry.js";
3
- import { i as externalTools, t as externalToolLimit } from "./hooks-B2EhBS_-.js";
1
+ import { g as chatSessionId } from "./access-tN5D3WI8.js";
2
+ import { a as liveSettings } from "./narration-DstnwrvX.js";
3
+ import { i as externalTools, t as externalToolLimit } from "./hooks-C7gt2c01.js";
4
4
  import { n as doctorSessionOf } from "./doctor-chat-ByDfCMeo.js";
5
5
  import { join } from "node:path";
6
6
  import { existsSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { f as mediaTypeOf, h as writeImageFileMetadata, m as sidecarOf, p as readImageFileMetadata, r as LIBRARY_FOLDER, v as mapLimit } from "./library-COIktKBa.js";
1
+ import { f as mediaTypeOf, h as writeImageFileMetadata, m as sidecarOf, p as readImageFileMetadata, r as LIBRARY_FOLDER, v as mapLimit } from "./library-DsDc6fQa.js";
2
2
  import { join, sep } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { lstat, mkdir, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
@@ -192,4 +192,4 @@ async function updateImage(sessionFolder, path, update) {
192
192
  //#endregion
193
193
  export { updateImage as i, galleryFile as n, listGallery as r, describeGalleryImage as t };
194
194
 
195
- //# sourceMappingURL=gallery-CDYKJf_O.js.map
195
+ //# sourceMappingURL=gallery-C7VOJ3xH.js.map
@@ -1,4 +1,4 @@
1
- import { c as referenceImagePath, l as sceneImagePath, u as writeImage } from "./library-COIktKBa.js";
1
+ import { c as referenceImagePath, l as sceneImagePath, u as writeImage } from "./library-DsDc6fQa.js";
2
2
  //#region src/host/images/generator.ts
3
3
  const unique = (values) => [...new Set(values.map((value) => value.trim()).filter((value) => value !== ""))];
4
4
  /** What a reference image shows: the subject and its stable look. */
@@ -142,4 +142,4 @@ async function generateTransientImage(service, request) {
142
142
  //#endregion
143
143
  export { uploadReferenceImage as a, transientPrompt as i, generateTransientImage as n, referencePrompt as r, generateReferenceImage as t };
144
144
 
145
- //# sourceMappingURL=generator-BR1ugzln.js.map
145
+ //# sourceMappingURL=generator-CO8usAjE.js.map
@@ -1,6 +1,6 @@
1
- import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { a as liveSettings, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-BT9uvQry.js";
3
- import { a as runChild, d as addTokens, h as trimCharacters, i as childTrace, l as tokensOf, n as childSampling, p as estimateAnswer, t as childModel, u as NO_TOKENS } from "./child-DsixtqTw.js";
1
+ import { _ as roleplaySessionOf, a as childTrace, d as NO_TOKENS, f as addTokens, m as estimateAnswer, n as childModel, o as runChild, r as childSampling, t as promptFor, u as tokensOf } from "./access-tN5D3WI8.js";
2
+ import { a as liveSettings, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-DstnwrvX.js";
3
+ import { t as trimCharacters } from "./text-CT1re6XT.js";
4
4
  import { dirname, join } from "node:path";
5
5
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
@@ -55,6 +55,13 @@ const ZH = {
55
55
  "Background": "背景",
56
56
  "Appearance": "外貌",
57
57
  "How you speak": "说话方式",
58
+ "Talk to {name}.": "和{name}聊聊。",
59
+ "Go to {place}.": "前往{place}。",
60
+ "Take a closer look at {thing}.": "仔细看看{thing}。",
61
+ "Look around carefully.": "仔细观察四周。",
62
+ "Wait and see what happens.": "先等等,看看会发生什么。",
63
+ "Ask what is going on.": "问问这是怎么回事。",
64
+ "Think about what to do next.": "想想接下来该怎么办。",
58
65
  "You are {name}.": "你是{name}。",
59
66
  "You are also called {names}.": "你也被称作{names}。",
60
67
  "age: {value}": "年龄:{value}",
@@ -1805,6 +1812,64 @@ function describeShown(shown) {
1805
1812
  }).join("; ");
1806
1813
  }
1807
1814
  //#endregion
1815
+ //#region src/host/orchestration/skeleton.ts
1816
+ const PLAIN_IMPORTANCE = 2;
1817
+ const CONSEQUENTIAL_IMPORTANCE = 3;
1818
+ /** Who took in what an entry did: the people in the same place, the actor included; off stage, only those named in the round. */
1819
+ function witnesses(round, entry) {
1820
+ const here = entry.at?.key;
1821
+ if (here === void 0) return round.entries.map((other) => other.character);
1822
+ const people = round.present ?? round.entries.flatMap((other) => other.at === void 0 ? [] : [{
1823
+ character: other.character,
1824
+ place: other.at.key
1825
+ }]);
1826
+ return [.../* @__PURE__ */ new Set([entry.character, ...people.filter((person) => person.place === here).map((person) => person.character)])];
1827
+ }
1828
+ /**
1829
+ * The records a round always leaves, written without a model: one event for what each character
1830
+ * did and one for what it said, word for word. What the game master said bystanders can see is
1831
+ * all they take in of the act; the keeper only enriches these (importance, tags, threads,
1832
+ * misperception), so a failed run leaves plainer records, never missing ones.
1833
+ */
1834
+ function skeletonEvents(round) {
1835
+ return round.entries.flatMap((entry) => {
1836
+ const seen = witnesses(round, entry);
1837
+ const base = {
1838
+ turn: round.turn,
1839
+ round: round.round,
1840
+ tags: [],
1841
+ ...entry.at === void 0 ? {} : { location: entry.at.key }
1842
+ };
1843
+ const act = seen.map((character) => character === entry.character || entry.publicState === void 0 ? {
1844
+ character,
1845
+ mode: "witnessed"
1846
+ } : {
1847
+ character,
1848
+ mode: "witnessed",
1849
+ content: entry.publicState,
1850
+ accuracy: "partial"
1851
+ });
1852
+ const events = [{
1853
+ ...base,
1854
+ text: entry.summary,
1855
+ importance: entry.moved !== void 0 || entry.items !== void 0 ? CONSEQUENTIAL_IMPORTANCE : PLAIN_IMPORTANCE,
1856
+ involves: [entry.character],
1857
+ perceivedBy: act
1858
+ }];
1859
+ if (entry.utterance !== void 0 && entry.spoken) events.push({
1860
+ ...base,
1861
+ text: `${entry.name}: "${entry.utterance}"`,
1862
+ importance: PLAIN_IMPORTANCE,
1863
+ involves: [entry.character],
1864
+ perceivedBy: seen.map((character) => ({
1865
+ character,
1866
+ mode: character === entry.character ? "witnessed" : "heard"
1867
+ }))
1868
+ });
1869
+ return events;
1870
+ });
1871
+ }
1872
+ //#endregion
1808
1873
  //#region src/host/orchestration/store.ts
1809
1874
  /** The rules the session copied from its world when it started. */
1810
1875
  function worldRules(session) {
@@ -2155,7 +2220,13 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
2155
2220
  session.metadata.recordTurn();
2156
2221
  },
2157
2222
  queueCommit: (record) => {
2158
- session.pendingCommits.enqueue(record.turn, record.round, JSON.parse(JSON.stringify(record)));
2223
+ session.transaction(() => {
2224
+ session.pendingCommits.enqueue(record.turn, record.round, JSON.parse(JSON.stringify(record)));
2225
+ session.edit({
2226
+ turn: record.turn,
2227
+ events: skeletonEvents(record)
2228
+ });
2229
+ });
2159
2230
  },
2160
2231
  pendingCommits: () => session.pendingCommits.list().map((entry) => entry.payload),
2161
2232
  completeCommits: (rounds) => {
@@ -2229,6 +2300,11 @@ const OPTIONAL_TOOLS = [
2229
2300
  agent: "gameMaster",
2230
2301
  default: true
2231
2302
  },
2303
+ {
2304
+ id: "roll_and_narrate",
2305
+ agent: "gameMaster",
2306
+ default: false
2307
+ },
2232
2308
  {
2233
2309
  id: "recall_my_memories",
2234
2310
  agent: "characters",
@@ -3480,7 +3556,9 @@ function installHooks(ctx, deps) {
3480
3556
  ctx.on("agent/created", ({ agent }) => {
3481
3557
  const owner = ownerOf(agent, 0);
3482
3558
  const store = owner === void 0 ? void 0 : stores(owner.chat);
3483
- if (store !== void 0) applyTools(agent, store);
3559
+ if (store === void 0) return;
3560
+ showPreviewTool(agent, store.settings().preview.enabled);
3561
+ applyTools(agent, store);
3484
3562
  });
3485
3563
  ctx.on("session/event", (session, event) => {
3486
3564
  if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
@@ -3501,7 +3579,7 @@ function installHooks(ctx, deps) {
3501
3579
  if (owner === void 0) return;
3502
3580
  const missing = engine.missing(owner);
3503
3581
  if (missing === void 0) return;
3504
- if (!engine.object(owner)) {
3582
+ if (!engine.object(owner, missing)) {
3505
3583
  ctx.logger.warn(`roleplay: ${owner.chat} ended turn ${turn} without finishing it (${missing})`);
3506
3584
  return;
3507
3585
  }
@@ -3518,6 +3596,7 @@ function installHooks(ctx, deps) {
3518
3596
  if (decision.kind !== "enter" || payload.step !== 1) return decision;
3519
3597
  if (owner === void 0 || store === void 0) return decision;
3520
3598
  const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
3599
+ if (!store.settings().background.concurrent) await engine.quiesce(owner.chat);
3521
3600
  await timelines.begin(owner.chat, payload.turn, text);
3522
3601
  const cast = store.cast();
3523
3602
  const ooc = parseOoc(text);
@@ -3610,6 +3689,6 @@ function installHooks(ctx, deps) {
3610
3689
  });
3611
3690
  }
3612
3691
  //#endregion
3613
- export { shippedPromptsDirectory as $, populatePlots as A, readDocument as B, describeTime as C, answerLimits as D, RESULTS as E, wrongLanguage as F, PROMPTS_FOLDER as G, formatIssue as H, PLOTS_FILE_NAME as I, inheritPrompts as J, PromptLibrary as K, loadPlots as L, STORY_LANGUAGES as M, isStoryLanguage as N, PLOTS_METADATA_KEY as O, textLanguage as P, shippedLanguages as Q, parsePlotsFile as R, ClockError as S, zoneOf as T, errorMessage as U, Reader as V, LANGUAGE_FOLDER as W, listFiles as X, languageOf as Y, promptProblem as Z, readWithdrawn as _, externalWithheld as a, SessionNotFoundError as at, readNotes as b, AUTHORING_NEEDS as c, translator as ct, storesOf as d, AgentUnavailableError as et, readUsage as f, writeVerdicts as g, readVerdicts as h, externalTools as i, SessionArchivedError as it, LANGUAGE_NAMES as j, plotProgressOf as k, toolEnabled as l, readRunDetail as m, installHooks as n, InvalidWorldError as nt, PREVIEW_TOOL as o, WorldNotFoundError as ot, readActivity as p, copyWorldPrompts as q, externalGiven as r, ReflectionRefusedError as rt, createTools$1 as s, languageOf$1 as st, externalToolLimit as t, InvalidStartError as tt, MAX_OOC_ANSWER as u, addToNote as v, describeWhen as w, observeAsPlayer as x, notesOfSession as y, plotReferenceProblems as z };
3692
+ export { promptProblem as $, PLOTS_METADATA_KEY as A, parsePlotsFile as B, observeAsPlayer as C, zoneOf as D, describeWhen as E, isStoryLanguage as F, errorMessage as G, readDocument as H, textLanguage as I, PromptLibrary as J, LANGUAGE_FOLDER as K, wrongLanguage as L, populatePlots as M, LANGUAGE_NAMES as N, RESULTS as O, STORY_LANGUAGES as P, listFiles as Q, PLOTS_FILE_NAME as R, readNotes as S, describeTime as T, Reader as U, plotReferenceProblems as V, formatIssue as W, inheritPrompts as X, copyWorldPrompts as Y, languageOf as Z, readVerdicts as _, externalWithheld as a, ReflectionRefusedError as at, addToNote as b, record as c, WorldNotFoundError as ct, toolEnabled as d, shippedLanguages as et, MAX_OOC_ANSWER as f, readRunDetail as g, readActivity as h, externalTools as i, InvalidWorldError as it, plotProgressOf as j, answerLimits as k, AUTHORING_NEEDS as l, languageOf$1 as lt, readUsage as m, installHooks as n, AgentUnavailableError as nt, PREVIEW_TOOL as o, SessionArchivedError as ot, storesOf as p, PROMPTS_FOLDER as q, externalGiven as r, InvalidStartError as rt, createTools$1 as s, SessionNotFoundError as st, externalToolLimit as t, shippedPromptsDirectory as tt, characterRunner as u, translator as ut, writeVerdicts as v, ClockError as w, notesOfSession as x, readWithdrawn as y, loadPlots as z };
3614
3693
 
3615
- //# sourceMappingURL=hooks-B2EhBS_-.js.map
3694
+ //# sourceMappingURL=hooks-C7gt2c01.js.map
package/lib/images.js CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as withPngMetadata, a as inheritImages, c as referenceImagePath, g as readPngMetadata, i as entityImageDirectory, l as sceneImagePath, o as nextSceneSerial, s as readImageMetadata, t as addToLibrary } from "./library-COIktKBa.js";
2
- import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-BR1ugzln.js";
3
- import { i as updateImage, r as listGallery } from "./gallery-CDYKJf_O.js";
4
- import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Gu34bZwd.js";
1
+ import { _ as withPngMetadata, a as inheritImages, c as referenceImagePath, g as readPngMetadata, i as entityImageDirectory, l as sceneImagePath, o as nextSceneSerial, s as readImageMetadata, t as addToLibrary } from "./library-DsDc6fQa.js";
2
+ import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-CO8usAjE.js";
3
+ import { i as updateImage, r as listGallery } from "./gallery-C7VOJ3xH.js";
4
+ import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-BsC6Vftz.js";
5
5
  export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };
package/lib/index.js CHANGED
@@ -1,19 +1,19 @@
1
- import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
- import { B as loadItems, Bt as ImportCardError, C as populateLocations, D as populateVariables, E as populateTriggers, Et as writeLorebookEntry, F as loadCalendar, Ft as parseLoreEdit, Gt as LORE_SCOPES, Ht as pictureOf, I as parseCalendarFile, It as parsePlaceEdit, J as withPlayer, Jt as DICE_RESULTS, Kt as DICE_COMPARISONS, Lt as parseRelationEdit, M as loadDice, Mt as InvalidEditProblems, N as parseDiceFile, Nt as parseCharacterEdit, O as routineProblems, P as CALENDAR_FILE_NAME, Pt as parseFactionEdit, Q as variableProblems, R as loadLocations, Rt as parseThingEdit, S as populateKnowledge, St as lorebookDirectory, T as populateRoutines, Tt as updateLorebookInfo, U as CHARACTERS_DIR, Ut as readCard, Vt as isPng, W as loadCharacters, Wt as LORE_KINDS, X as loadVariables, Y as VARIABLES_FILE_NAME, Z as parseVariablesFile, _ as populateCharacters, _t as deleteLorebookEntry, at as CHARACTER_FILE_NAME, b as populateFactions, bt as listLorebooks, ct as ImportNotFoundError, d as markReady, dt as WORLD_FILE_NAME, f as guardedLookup, ft as parseWorldFile, g as populateCalendar, gt as deleteLorebook, h as knowsCharacter, ht as createLorebook, j as DICE_FILE_NAME, jt as subfolders, k as TRIGGERS_FILE_NAME, l as authoringChatSessionId, lt as ImportStore, m as loadValidatedWorld, mt as addLorebookEntries, ot as parseCharacterFile, p as vetUrl, pt as parseWorldInfoEdit, q as partsOf, qt as DICE_READINGS, st as IMPORT_FOLDER, t as AuthoringTools, ut as parseChoices, v as populateClock, vt as entriesOf, w as populateLore, wt as reserveLorebook, x as populateItems, xt as loadLorebook, y as populateDice, yt as isLorebookName, zt as IMPORT_COMMAND } from "./authoring-tools-C_8ClUkP.js";
3
- import { _ as readWorldPrompt, a as isPresetName, c as presetDirectory, d as savePresetFromWorld, g as listWorldPrompts, h as deleteWorldPrompt, i as deletePreset, o as listPresets, p as updatePresetInfo, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE, u as reservePreset, v as writeWorldPrompt } from "./presets-C3mhqqfz.js";
4
- import { c as copyPreset, d as switchPreset, f as readTimeline, i as reflectionStatus, l as presetStatus, m as defaultBoundaries, o as TimelineError, p as pathTo, u as recordPreset } from "./reflection-Btsj0ZLh.js";
5
- import { _ as VARIABLE_VISIBILITIES, a as liveSettings, c as writeSettings, d as parseSettings, g as VARIABLE_SUBJECTS, h as VARIABLE_KINDS, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-BT9uvQry.js";
6
- import { A as populatePlots, B as readDocument, H as formatIssue, K as PromptLibrary, O as PLOTS_METADATA_KEY, Q as shippedLanguages, R as parsePlotsFile, T as zoneOf, U as errorMessage, Y as languageOf, _ as readWithdrawn, at as SessionNotFoundError, b as readNotes, et as AgentUnavailableError, f as readUsage, i as externalTools, it as SessionArchivedError, k as plotProgressOf, m as readRunDetail, nt as InvalidWorldError, ot as WorldNotFoundError, p as readActivity, q as copyWorldPrompts, rt as ReflectionRefusedError, tt as InvalidStartError, v as addToNote, x as observeAsPlayer, y as notesOfSession, z as plotReferenceProblems } from "./hooks-B2EhBS_-.js";
7
- import { c as sharedSamplingOf, h as trimCharacters, r as childSamplingOf, s as parseSampling } from "./child-DsixtqTw.js";
8
- import { a as inheritImages, b as slug, c as referenceImagePath, l as sceneImagePath, t as addToLibrary, x as uniqueKey } from "./library-COIktKBa.js";
9
- import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, I as PRESET_FILE$1, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-soI-In96.js";
10
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-3zn8xme7.js";
11
- import { a as lorebookImportMessage, d as selectEntries, l as previewLorebook, s as lorebookChatSessionId, t as LOREBOOK_UPLOAD, u as readLorebook } from "./lorebook-author-tools-C-o0t4dL.js";
12
- import { a as presetChatSessionId, n as narrationImportMessage } from "./preset-author-tools-C-X8G40s.js";
1
+ import { _ as roleplaySessionOf, c as parseSampling, g as chatSessionId, i as childSamplingOf, l as sharedSamplingOf } from "./access-tN5D3WI8.js";
2
+ import { B as loadItems, Bt as ImportCardError, C as populateLocations, D as populateVariables, E as populateTriggers, Et as writeLorebookEntry, F as loadCalendar, Ft as parseLoreEdit, Gt as LORE_SCOPES, Ht as pictureOf, I as parseCalendarFile, It as parsePlaceEdit, J as withPlayer, Jt as DICE_RESULTS, Kt as DICE_COMPARISONS, Lt as parseRelationEdit, M as loadDice, Mt as InvalidEditProblems, N as parseDiceFile, Nt as parseCharacterEdit, O as routineProblems, P as CALENDAR_FILE_NAME, Pt as parseFactionEdit, Q as variableProblems, R as loadLocations, Rt as parseThingEdit, S as populateKnowledge, St as lorebookDirectory, T as populateRoutines, Tt as updateLorebookInfo, U as CHARACTERS_DIR, Ut as readCard, Vt as isPng, W as loadCharacters, Wt as LORE_KINDS, X as loadVariables, Y as VARIABLES_FILE_NAME, Z as parseVariablesFile, _ as populateCharacters, _t as deleteLorebookEntry, at as CHARACTER_FILE_NAME, b as populateFactions, bt as listLorebooks, ct as ImportNotFoundError, d as markReady, dt as WORLD_FILE_NAME, f as guardedLookup, ft as parseWorldFile, g as populateCalendar, gt as deleteLorebook, h as knowsCharacter, ht as createLorebook, j as DICE_FILE_NAME, jt as subfolders, k as TRIGGERS_FILE_NAME, l as authoringChatSessionId, lt as ImportStore, m as loadValidatedWorld, mt as addLorebookEntries, ot as parseCharacterFile, p as vetUrl, pt as parseWorldInfoEdit, q as partsOf, qt as DICE_READINGS, st as IMPORT_FOLDER, t as AuthoringTools, ut as parseChoices, v as populateClock, vt as entriesOf, w as populateLore, wt as reserveLorebook, x as populateItems, xt as loadLorebook, y as populateDice, yt as isLorebookName, zt as IMPORT_COMMAND } from "./authoring-tools-Ch_3oIKC.js";
3
+ import { _ as readWorldPrompt, a as isPresetName, c as presetDirectory, d as savePresetFromWorld, g as listWorldPrompts, h as deleteWorldPrompt, i as deletePreset, o as listPresets, p as updatePresetInfo, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE, u as reservePreset, v as writeWorldPrompt } from "./presets-CADd77WB.js";
4
+ import { c as copyPreset, d as switchPreset, f as readTimeline, i as reflectionStatus, l as presetStatus, m as defaultBoundaries, o as TimelineError, p as pathTo, u as recordPreset } from "./reflection-CUGuPAZR.js";
5
+ import { _ as VARIABLE_VISIBILITIES, a as liveSettings, c as writeSettings, d as parseSettings, g as VARIABLE_SUBJECTS, h as VARIABLE_KINDS, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-DstnwrvX.js";
6
+ import { A as PLOTS_METADATA_KEY, B as parsePlotsFile, C as observeAsPlayer, D as zoneOf, G as errorMessage, H as readDocument, J as PromptLibrary, M as populatePlots, S as readNotes, V as plotReferenceProblems, W as formatIssue, Y as copyWorldPrompts, Z as languageOf, at as ReflectionRefusedError, b as addToNote, ct as WorldNotFoundError, et as shippedLanguages, g as readRunDetail, h as readActivity, i as externalTools, it as InvalidWorldError, j as plotProgressOf, m as readUsage, nt as AgentUnavailableError, ot as SessionArchivedError, rt as InvalidStartError, st as SessionNotFoundError, x as notesOfSession, y as readWithdrawn } from "./hooks-C7gt2c01.js";
7
+ import { t as trimCharacters } from "./text-CT1re6XT.js";
8
+ import { a as inheritImages, b as slug, c as referenceImagePath, l as sceneImagePath, t as addToLibrary, x as uniqueKey } from "./library-DsDc6fQa.js";
9
+ import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, I as PRESET_FILE$1, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-AzR6dCNm.js";
10
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-Drfu_K-H.js";
11
+ import { a as lorebookImportMessage, d as selectEntries, l as previewLorebook, s as lorebookChatSessionId, t as LOREBOOK_UPLOAD, u as readLorebook } from "./lorebook-author-tools-DII7Xt7Q.js";
12
+ import { a as presetChatSessionId, n as narrationImportMessage } from "./preset-author-tools-CdIsFhQw.js";
13
13
  import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
14
- import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-CJPSe5LI.js";
15
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BR1ugzln.js";
16
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CDYKJf_O.js";
14
+ import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-C7g534Mi.js";
15
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-CO8usAjE.js";
16
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-C7VOJ3xH.js";
17
17
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
18
18
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
19
19
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -215,20 +215,30 @@ const AGENT_PRESET = "roleplay";
215
215
  async function isStored(persistence, sessionId) {
216
216
  return persistence?.stat !== void 0 && await persistence.stat(SessionId(sessionId)) !== void 0;
217
217
  }
218
- /** Create or adopt one named preset chat and only name it on first creation. */
218
+ /**
219
+ * Make sure one named preset chat belongs to its project, and only name it on first creation. DSH's `create` reuses a stored chat only while
220
+ * it has no turn and mints another id otherwise, so a chat that exists is never created again: one that is stored (it holds an opening) is
221
+ * attached to the project, and only a chat that does not exist is created.
222
+ */
219
223
  async function ensureAgentChat(services, request, knownProject) {
220
224
  const project = knownProject ?? await services.registry.create(request.projectPath, request.projectTitle);
221
225
  const existed = project.sessionIds.includes(request.sessionId);
222
- const { sessionId } = await services.controller.create({
223
- workspaceId: project.id,
224
- sessionId: request.sessionId,
225
- agentPreset: request.agentPreset
226
- });
226
+ if (!existed) {
227
+ if (await isStored(services.persistence, request.sessionId)) await project.attachSession(request.sessionId);
228
+ else {
229
+ const { sessionId } = await services.controller.create({
230
+ workspaceId: project.id,
231
+ sessionId: request.sessionId,
232
+ agentPreset: request.agentPreset
233
+ });
234
+ if (sessionId !== request.sessionId) throw new Error(`DSH made the chat "${sessionId}" instead of "${request.sessionId}", so the chat cannot be found again`);
235
+ }
236
+ }
227
237
  if (!existed || request.renameExisting === true) await services.controller.rename({
228
- sessionId,
238
+ sessionId: request.sessionId,
229
239
  title: request.title
230
240
  });
231
- return sessionId;
241
+ return request.sessionId;
232
242
  }
233
243
  /** Looks the services up on first use: profiles without the web app do not have them. */
234
244
  function agentServicesOf(ctx) {
@@ -7427,6 +7437,7 @@ function apply(ctx, config) {
7427
7437
  return {
7428
7438
  temperature: sampling.master,
7429
7439
  ...sharedSamplingOf(sampling),
7440
+ maxTokens: sampling.masterMaxTokens,
7430
7441
  priority: "foreground"
7431
7442
  };
7432
7443
  }), "roleplay: request controls");
@@ -1,4 +1,4 @@
1
- import { g as withoutExtension, h as trimCharacters } from "./child-DsixtqTw.js";
1
+ import { n as withoutExtension, t as trimCharacters } from "./text-CT1re6XT.js";
2
2
  import { dirname, extname, join } from "node:path";
3
3
  import { existsSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
@@ -332,4 +332,4 @@ async function addToLibrary(sessionFolder, bytes, originalName) {
332
332
  //#endregion
333
333
  export { withPngMetadata as _, inheritImages as a, slug as b, referenceImagePath as c, MEDIA_TYPES as d, mediaTypeOf as f, readPngMetadata as g, writeImageFileMetadata as h, entityImageDirectory as i, sceneImagePath as l, sidecarOf as m, imageExtensionOf as n, nextSceneSerial as o, readImageFileMetadata as p, LIBRARY_FOLDER as r, readImageMetadata as s, addToLibrary as t, writeImage as u, mapLimit as v, uniqueKey as x, norm as y };
334
334
 
335
- //# sourceMappingURL=library-COIktKBa.js.map
335
+ //# sourceMappingURL=library-DsDc6fQa.js.map
@@ -1,8 +1,8 @@
1
- import { Bt as ImportCardError, Ct as readLorebook$1, Et as writeLorebookEntry, Gt as LORE_SCOPES, J as withPlayer, K as cleanText, St as lorebookDirectory, Tt as updateLorebookInfo, Wt as LORE_KINDS, _t as deleteLorebookEntry, i as contextOf, q as partsOf, r as MAX_PREVIEW_TEXT, st as IMPORT_FOLDER, vt as entriesOf, xt as loadLorebook } from "./authoring-tools-C_8ClUkP.js";
2
- import { n as createPresetFromGuidance } from "./presets-C3mhqqfz.js";
3
- import "./narration-BT9uvQry.js";
4
- import { $ as shippedPromptsDirectory } from "./hooks-B2EhBS_-.js";
5
- import { b as slug, v as mapLimit, x as uniqueKey } from "./library-COIktKBa.js";
1
+ import { Bt as ImportCardError, Ct as readLorebook$1, Et as writeLorebookEntry, Gt as LORE_SCOPES, J as withPlayer, K as cleanText, St as lorebookDirectory, Tt as updateLorebookInfo, Wt as LORE_KINDS, _t as deleteLorebookEntry, i as contextOf, q as partsOf, r as MAX_PREVIEW_TEXT, st as IMPORT_FOLDER, vt as entriesOf, xt as loadLorebook } from "./authoring-tools-Ch_3oIKC.js";
2
+ import { n as createPresetFromGuidance } from "./presets-CADd77WB.js";
3
+ import "./narration-DstnwrvX.js";
4
+ import { tt as shippedPromptsDirectory } from "./hooks-C7gt2c01.js";
5
+ import { b as slug, v as mapLimit, x as uniqueKey } from "./library-DsDc6fQa.js";
6
6
  import { join } from "node:path";
7
7
  import { existsSync, readFileSync } from "node:fs";
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -691,4 +691,4 @@ async function lorebookApproval(exec, next, state) {
691
691
  //#endregion
692
692
  export { lorebookImportMessage as a, lorebookOfChat as c, selectEntries as d, lorebookAuthorTools as i, previewLorebook as l, LorebookReader as n, pendingTargets as o, lorebookApproval as r, lorebookChatSessionId as s, LOREBOOK_UPLOAD as t, readLorebook as u };
693
693
 
694
- //# sourceMappingURL=lorebook-author-tools-C-o0t4dL.js.map
694
+ //# sourceMappingURL=lorebook-author-tools-DII7Xt7Q.js.map
@@ -1,6 +1,6 @@
1
- import { St as lorebookDirectory, n as limitAuthoringAgents } from "./authoring-tools-C_8ClUkP.js";
2
- import "./hooks-B2EhBS_-.js";
3
- import { c as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-C-o0t4dL.js";
1
+ import { St as lorebookDirectory, n as limitAuthoringAgents } from "./authoring-tools-Ch_3oIKC.js";
2
+ import "./hooks-C7gt2c01.js";
3
+ import { c as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-DII7Xt7Q.js";
4
4
  import { join } from "node:path";
5
5
  import { existsSync, readdirSync } from "node:fs";
6
6
  //#region src/lorebook-authoring.ts
@@ -190,6 +190,7 @@ const SETTINGS_SPEC = {
190
190
  context: {
191
191
  limitTokens: integer(0, 1e6, 0),
192
192
  limitRatio: ratio(.1, .9, .6),
193
+ workingTokens: integer(0, 1e6, 0),
193
194
  retainRatio: ratio(.1, .9, .5),
194
195
  shortTermTokens: integer(200, 2e4, 1500),
195
196
  longTermTokens: integer(200, 4e4, 2500)
@@ -207,6 +208,7 @@ const SETTINGS_SPEC = {
207
208
  maxSkipDays: integer(1, 3650, 30)
208
209
  },
209
210
  diagnostics: { keepRuns: flag(false) },
211
+ background: { concurrent: flag(false) },
210
212
  offstage: {
211
213
  perTurn: integer(0, 5, 2),
212
214
  perCharacter: integer(1, 3, 1),
@@ -226,6 +228,7 @@ const SETTINGS_SPEC = {
226
228
  authoring: ratio(0, 2, .4),
227
229
  records: ratio(0, 2, .1),
228
230
  tools: choice(["auto", "required"], "required"),
231
+ masterMaxTokens: integer(1024, 64e3, 12e3),
229
232
  maxTokens: integer(256, 64e3, 8e3),
230
233
  shortMaxTokens: integer(256, 64e3, 2e3),
231
234
  headroom: ratio(1, 10, 2)
@@ -523,4 +526,4 @@ function decodeOutput(text) {
523
526
  //#endregion
524
527
  export { VARIABLE_VISIBILITIES as _, liveSettings as a, writeSettings as c, parseSettings as d, parseSwitchboard as f, VARIABLE_SUBJECTS as g, VARIABLE_KINDS as h, InvalidSettingsError as i, DEFAULT_SETTINGS as l, rulesOf as m, encodeOutput as n, readSettings as o, WORLD_RULES_KEY as p, encodePreview as r, useChildReasoning as s, decodeOutput as t, SETTINGS_SPEC as u };
525
528
 
526
- //# sourceMappingURL=narration-BT9uvQry.js.map
529
+ //# sourceMappingURL=narration-DstnwrvX.js.map