@dsh-agentic-roleplay/core 0.10.2 → 0.11.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 (43) hide show
  1. package/lib/{access-CXtaZNbx.js → access-Md1YTSX1.js} +4 -1
  2. package/lib/{authoring-tools-C9cmcUbD.js → authoring-tools-BFdw7ahj.js} +72 -9
  3. package/lib/authoring.js +38 -8
  4. package/lib/client.js +777 -427
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +2 -2
  7. package/lib/doctor.js +3 -3
  8. package/lib/{gallery-CtG-bDzz.js → gallery-BWHmjogd.js} +3 -3
  9. package/lib/{generator-nLoPM5MF.js → generator-QCdm8nUh.js} +9 -3
  10. package/lib/helper.js +9 -0
  11. package/lib/{hooks-BpLN_hhT.js → hooks-C2U1-8ur.js} +709 -67
  12. package/lib/images.js +4 -4
  13. package/lib/index.js +225 -19
  14. package/lib/{library-CH-ahlm0.js → library-4zmCAshR.js} +3 -3
  15. package/lib/{lorebook-author-tools-Cg7QQemi.js → lorebook-author-tools-Bjfjt3bg.js} +7 -7
  16. package/lib/lorebook-authoring.js +4 -4
  17. package/lib/{narration-B0hConSw.js → narration-b_VBEUWn.js} +7 -3
  18. package/lib/orchestration.js +338 -28
  19. package/lib/{pack-jail-D5j5mIq6.js → pack-jail-Ci9bIeDI.js} +25 -15
  20. package/lib/{packs-Cc05FrId.js → packs-CYkozh8Q.js} +2 -2
  21. package/lib/{presenter-agent-UKbKYXMO.js → presenter-agent-CqkAL03Q.js} +10 -7
  22. package/lib/{preset-Be4lz6vB.js → preset-B-35yUmt.js} +3 -3
  23. package/lib/{preset-author-tools-C3s0iSfv.js → preset-author-tools-BUymqZM5.js} +7 -7
  24. package/lib/preset-authoring.js +5 -5
  25. package/lib/{presets-Cl9sU3Qs.js → presets-_U-xroo0.js} +27 -8
  26. package/lib/{reflection-I9z-PvFK.js → reflection-B9N0z3KY.js} +9 -608
  27. package/lib/{text-CzqhC8sT.js → text-C2AGl7Je.js} +11 -2
  28. package/lib/{turn-guard-B9pGCeir.js → turn-guard-C0M3rXEN.js} +10 -10
  29. package/package.json +33 -32
  30. package/prompts/en/import/variables.md +1 -0
  31. package/prompts/en/roleplay/character-decide.md +1 -1
  32. package/prompts/en/roleplay/decide-reuse.md +3 -0
  33. package/prompts/en/roleplay/decide-variable.md +1 -0
  34. package/prompts/en/roleplay/image-presenter.md +1 -0
  35. package/prompts/en/roleplay/track-values.md +1 -0
  36. package/prompts/en/roleplay/track-variables.md +1 -0
  37. package/prompts/zh/import/variables.md +1 -0
  38. package/prompts/zh/roleplay/character-decide.md +1 -1
  39. package/prompts/zh/roleplay/decide-reuse.md +3 -0
  40. package/prompts/zh/roleplay/decide-variable.md +1 -0
  41. package/prompts/zh/roleplay/image-presenter.md +1 -0
  42. package/prompts/zh/roleplay/track-values.md +1 -0
  43. package/prompts/zh/roleplay/track-variables.md +1 -0
package/lib/images.js CHANGED
@@ -1,5 +1,5 @@
1
- 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-UKbKYXMO.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-CtG-bDzz.js";
3
- import { c as nextSceneSerial, d as sceneImagePath, l as readImageMetadata, o as entityImageDirectory, s as inheritImages, t as addToLibrary, u as referenceImagePath, v as readPngMetadata, y as withPngMetadata } from "./library-CH-ahlm0.js";
4
- import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-nLoPM5MF.js";
1
+ import { a as searchImages, c as presentedFor, n as interpretImage, o as tokensOf, r as imageTools, s as present, t as runImagePresenter } from "./presenter-agent-CqkAL03Q.js";
2
+ import { i as updateImage, r as listGallery } from "./gallery-BWHmjogd.js";
3
+ import { c as nextSceneSerial, d as sceneImagePath, l as readImageMetadata, o as entityImageDirectory, s as inheritImages, t as addToLibrary, u as referenceImagePath, v as readPngMetadata, y as withPngMetadata } from "./library-4zmCAshR.js";
4
+ import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-QCdm8nUh.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,20 +1,20 @@
1
- import { a as VARIABLE_KINDS, c as chatSessionId, i as atomicWriteSync, l as roleplaySessionOf, n as atomicWrite, o as VARIABLE_SUBJECTS, r as atomicWriteJson, s as VARIABLE_VISIBILITIES } from "./access-CXtaZNbx.js";
2
- import { $t as subfolders, At as populateLore, Bt as loadLocations, Ct as populateCharacters, Dt as populateItems, E as loadWorldParts, Et as populateFactions, F as localChanges, Ft as TRIGGERS_FILE_NAME, G as vetUrl, Gt as DICE_FILE_NAME, Ht as loadItems, I as readOrigin, Jt as CALENDAR_FILE_NAME, Kt as loadDice, L as writeOrigin, M as describeChanges, Mt as populateTriggers, N as hashWorld, Nt as populateVariables, Ot as populateKnowledge, P as isUnchanged, Pt as routineProblems, Qt as loadCharacters, R as CatalogueError, St as populateCalendar, T as readWorldInfo, Tt as populateDice, U as guardedLookup, Xt as parseCalendarFile, Yt as loadCalendar, Zt as CHARACTERS_DIR, _ as runChecks, _t as writeLorebookEntry, an as readCard, at as addLorebookEntries, c as importPhase, cn as DICE_RESULTS, ct as deleteLorebookEntry, d as markReady, dt as listLorebooks, en as knownOutputCeiling, et as WORLD_FILE_NAME, f as settleDraft, ft as loadLorebook, gt as updateLorebookInfo, ht as reserveLorebook, in as pictureOf, it as questionView, jt as populateRoutines, kt as populateLocations, ln as authoredWorldOf, lt as entriesOf, nn as cardFormat, nt as parseWorldInfoEdit, on as DICE_COMPARISONS, ot as createLorebook, p as structureImport, pt as lorebookDirectory, qt as parseDiceFile, rn as isPng, rt as combineAnswers, sn as DICE_READINGS, st as deleteLorebook, t as AuthoringTools, tn as ImportCardError, tt as parseWorldFile, u as keepDraft, ut as isLorebookName, vt as checkWorld, w as editWorldInfo, wt as populateClock, xt as knowsCharacter, yt as loadValidatedWorld } from "./authoring-tools-C9cmcUbD.js";
3
- import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-Cg7QQemi.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-C3s0iSfv.js";
5
- import { $ as listFiles, B as COMMANDS_KEY, C as readNotes, D as PLOTS_METADATA_KEY, F as readUsage, G as formatIssue, J as PROMPTS_FOLDER, K as errorMessage, O as plotProgressOf, Q as languageOf, R as parsePlotsFile, S as notesOfSession, U as readDocument, X as copyWorldPrompts, Y as PromptLibrary, _ as readTraces, at as InvalidStartError, b as readWithdrawn, ct as SessionArchivedError, et as promptProblem, g as readRunDetail, h as readActivity, i as externalTools, it as AgentUnavailableError, k as populatePlots, lt as SessionNotFoundError, m as readDecisionStats, mt as zoneOf, ot as InvalidWorldError, q as LANGUAGE_FOLDER, st as ReflectionRefusedError, tt as shippedLanguages, ut as WorldNotFoundError, w as observeAsPlayer, x as addToNote, z as plotReferenceProblems } from "./hooks-BpLN_hhT.js";
6
- import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-B0hConSw.js";
7
- import { $ as DOCTOR_OPENING_SOURCE, A as worldEntityImageFile, B as languageOfDocuments, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as PRESET_FILE, G as revertUpdate, H as findTargets, I as presetMessage, J as AuthoringSessions, K as startUpdate, O as uploadWorldEntityImage, Q as agentServicesOf, R as translateMessage, S as generateWorldEntityImage, T as removeWorldTrigger, V as readWorldDocuments, X as ensureAuthoringChat, Y as authoringTitle, Z as AgentSessions, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, et as appendEmptyTurn, 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, q as updateStatus, t as MAX_PACK_TEXT, tt as appendNarratedTurn, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1 } from "./pack-jail-D5j5mIq6.js";
1
+ import { a as VARIABLE_KINDS, c as chatSessionId, i as atomicWriteSync, l as roleplaySessionOf, n as atomicWrite, o as VARIABLE_SUBJECTS, r as atomicWriteJson, s as VARIABLE_VISIBILITIES } from "./access-Md1YTSX1.js";
2
+ import { $t as subfolders, At as populateLore, Bt as loadLocations, Ct as populateCharacters, Dt as populateItems, E as loadWorldParts, Et as populateFactions, F as localChanges, Ft as TRIGGERS_FILE_NAME, G as vetUrl, Gt as DICE_FILE_NAME, Ht as loadItems, I as readOrigin, Jt as CALENDAR_FILE_NAME, Kt as loadDice, L as writeOrigin, M as describeChanges, Mt as populateTriggers, N as hashWorld, Nt as populateVariables, Ot as populateKnowledge, P as isUnchanged, Pt as routineProblems, Qt as loadCharacters, R as CatalogueError, St as populateCalendar, T as readWorldInfo, Tt as populateDice, U as guardedLookup, Xt as parseCalendarFile, Yt as loadCalendar, Zt as CHARACTERS_DIR, _ as runChecks, _t as writeLorebookEntry, an as readCard, at as addLorebookEntries, c as importPhase, cn as DICE_RESULTS, ct as deleteLorebookEntry, d as markReady, dt as listLorebooks, en as knownOutputCeiling, et as WORLD_FILE_NAME, f as settleDraft, ft as loadLorebook, gt as updateLorebookInfo, ht as reserveLorebook, in as pictureOf, it as questionView, jt as populateRoutines, kt as populateLocations, ln as authoredWorldOf, lt as entriesOf, nn as cardFormat, nt as parseWorldInfoEdit, on as DICE_COMPARISONS, ot as createLorebook, p as structureImport, pt as lorebookDirectory, qt as parseDiceFile, rn as isPng, rt as combineAnswers, sn as DICE_READINGS, st as deleteLorebook, t as AuthoringTools, tn as ImportCardError, tt as parseWorldFile, u as keepDraft, ut as isLorebookName, vt as checkWorld, w as editWorldInfo, wt as populateClock, xt as knowsCharacter, yt as loadValidatedWorld } from "./authoring-tools-BFdw7ahj.js";
3
+ import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-Bjfjt3bg.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BUymqZM5.js";
5
+ import { A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as copyWorldPrompts, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, X as PROMPTS_FOLDER, Y as LANGUAGE_FOLDER, Z as PromptLibrary, _ as readTraces, b as readWithdrawn, ct as InvalidWorldError, dt as SessionNotFoundError, et as languageOf, ft as WorldNotFoundError, g as readRunDetail, h as readActivity, ht as zoneOf, i as externalTools, j as populatePlots, k as PLOTS_METADATA_KEY, lt as ReflectionRefusedError, m as readDecisionStats, nt as promptProblem, ot as AgentUnavailableError, q as formatIssue, rt as shippedLanguages, st as InvalidStartError, tt as listFiles, ut as SessionArchivedError, w as observeAsPlayer, x as addToNote } from "./hooks-C2U1-8ur.js";
6
+ import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-b_VBEUWn.js";
7
+ import { $ as IMPORT_FOLDER, At as InvalidEditProblems, Dt as parseCharacterFile, Et as CHARACTER_FILE_NAME, Ft as parseRelationEdit, G as deleteWorldPrompt, It as parseThingEdit, J as writeWorldPrompt, K as listWorldPrompts, Lt as guarded, Mt as parseFactionEdit, Nt as parseLoreEdit, Pt as parsePlaceEdit, Q as withPlayer, Rt as LORE_KINDS, Z as partsOf, a as isPresetName, at as readImportFolder, c as presetDirectory, ct as sourceSummary, d as savePresetFromWorld, et as ImportNotFoundError, ft as VARIABLES_FILE_NAME, ht as variableProblems, i as deletePreset, it as parseChoices, jt as parseCharacterEdit, lt as IMPORT_COMMAND, mt as parseVariablesFile, o as listPresets, p as updatePresetInfo, pt as loadVariables, q as readWorldPrompt, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE, tt as ImportStore, u as reservePreset, zt as LORE_SCOPES } from "./presets-_U-xroo0.js";
8
+ import { $ as DOCTOR_OPENING_SOURCE, A as worldEntityImageFile, B as languageOfDocuments, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as PRESET_FILE$1, G as revertUpdate, H as findTargets, I as presetMessage, J as AuthoringSessions, K as startUpdate, O as uploadWorldEntityImage, Q as agentServicesOf, R as translateMessage, S as generateWorldEntityImage, T as removeWorldTrigger, V as readWorldDocuments, X as ensureAuthoringChat, Y as authoringTitle, Z as AgentSessions, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, et as appendEmptyTurn, 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, q as updateStatus, t as MAX_PACK_TEXT, tt as appendNarratedTurn, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1 } from "./pack-jail-Ci9bIeDI.js";
8
9
  import { d as parseSampling, f as sharedSamplingOf, i as childSamplingOf, m as RECOVERY_SHRINK, p as RECOVERY_FLOOR, s as isUnfinishedCall, x as totalTokens } from "./child-C9nPIy9j.js";
9
- import { $ as IMPORT_FOLDER, At as InvalidEditProblems, Dt as parseCharacterFile, Et as CHARACTER_FILE_NAME, Ft as parseRelationEdit, G as deleteWorldPrompt, It as parseThingEdit, J as writeWorldPrompt, K as listWorldPrompts, Lt as LORE_KINDS, Mt as parseFactionEdit, Nt as parseLoreEdit, Pt as parsePlaceEdit, Q as withPlayer, Rt as LORE_SCOPES, Z as partsOf, a as isPresetName, at as readImportFolder, c as presetDirectory, ct as sourceSummary, d as savePresetFromWorld, et as ImportNotFoundError, ft as VARIABLES_FILE_NAME, ht as variableProblems, i as deletePreset, it as parseChoices, jt as parseCharacterEdit, lt as IMPORT_COMMAND, mt as parseVariablesFile, o as listPresets, p as updatePresetInfo, pt as loadVariables, q as readWorldPrompt, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE$1, tt as ImportStore, u as reservePreset } from "./presets-Cl9sU3Qs.js";
10
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CzqhC8sT.js";
11
- import { _ as START_SNAPSHOT, b as snapshotOf, c as copyPreset, d as switchPreset, f as defaultBoundaries, g as writeTimeline, h as readTimeline, i as reflectionStatus, l as presetStatus, o as TimelineError, u as recordPreset, v as childrenOf, y as pathTo } from "./reflection-I9z-PvFK.js";
12
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-Be4lz6vB.js";
13
- import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-CH-ahlm0.js";
10
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-C2AGl7Je.js";
11
+ import { _ as snapshotOf, c as copyPreset, d as switchPreset, f as readTimeline, g as pathTo, h as childrenOf, i as reflectionStatus, l as presetStatus, m as START_SNAPSHOT, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-B9N0z3KY.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-B-35yUmt.js";
13
+ import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-4zmCAshR.js";
14
14
  import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
15
- 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-Cc05FrId.js";
16
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-nLoPM5MF.js";
17
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CtG-bDzz.js";
15
+ 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-CYkozh8Q.js";
16
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-QCdm8nUh.js";
17
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BWHmjogd.js";
18
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
19
19
  import { SESSION_DATABASE_FILE, addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, openSessionStore, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
20
20
  import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -30,6 +30,194 @@ import { homedir } from "node:os";
30
30
  import { pipeline } from "node:stream/promises";
31
31
  import { spawn } from "node:child_process";
32
32
  import z from "@deepseek-ai/schemastery";
33
+ // src/shared/offload.ts
34
+ /** The kinds of model a story uses that may have to share one machine's memory. `main` is whatever model the chat itself is set to. */
35
+ const OFFLOAD_ROLES = [
36
+ "main",
37
+ "embedding",
38
+ "reranker",
39
+ "decision",
40
+ "image",
41
+ "speech"
42
+ ];
43
+ const DEFAULT_OFFLOAD = {
44
+ models: {},
45
+ groups: []
46
+ };
47
+ const isRole = (value) => OFFLOAD_ROLES.includes(value);
48
+ const text$1 = (value) => typeof value === "string" ? value.trim() : "";
49
+ /** The configuration as written, brought to its shape: unknown roles and blank entries are dropped, a group lists each role once and has at least two. */
50
+ function offloadOf(value) {
51
+ const row = typeof value === "object" && value !== null ? value : {};
52
+ const models = {};
53
+ const given = typeof row["models"] === "object" && row["models"] !== null ? row["models"] : {};
54
+ for (const role of OFFLOAD_ROLES) {
55
+ if (role === "main") continue;
56
+ const entry = given[role];
57
+ if (typeof entry !== "object" || entry === null) continue;
58
+ const route = text$1(entry["route"]);
59
+ const model = text$1(entry["model"]);
60
+ if (route !== "" || model !== "") models[role] = {
61
+ route,
62
+ model
63
+ };
64
+ }
65
+ return {
66
+ models,
67
+ groups: (Array.isArray(row["groups"]) ? row["groups"] : []).map((group) => OFFLOAD_ROLES.filter((role) => Array.isArray(group) && group.some((member) => isRole(member) && member === role))).filter((group) => group.length >= 2)
68
+ };
69
+ }
70
+ /** The roles that may not be loaded together with `role`. */
71
+ function conflictsOf(config, role) {
72
+ const others = /* @__PURE__ */ new Set();
73
+ for (const group of config.groups) if (group.includes(role)) {
74
+ for (const member of group) if (member !== role) others.add(member);
75
+ }
76
+ return [...others];
77
+ }
78
+ // src/host/residency/residency.ts
79
+ /**
80
+ * Keeps the models that cannot share memory from being loaded together. Before a model of a role is used, the models of the roles that
81
+ * conflict with it are unloaded; the server loads what is asked of it on its own, so nothing is loaded here. Which models may still be
82
+ * resident is only what this process has used since it started or since it unloaded them (a server that was already running is asked
83
+ * once), so a role used again and again costs nothing.
84
+ */
85
+ var ModelResidency = class {
86
+ deps;
87
+ possible = /* @__PURE__ */ new Set([
88
+ "main",
89
+ "embedding",
90
+ "reranker",
91
+ "decision",
92
+ "image",
93
+ "speech"
94
+ ]);
95
+ turn = Promise.resolve();
96
+ reported = /* @__PURE__ */ new Set();
97
+ lastMain;
98
+ active = /* @__PURE__ */ new Map();
99
+ drained = /* @__PURE__ */ new Map();
100
+ constructor(deps) {
101
+ this.deps = deps;
102
+ }
103
+ /** Whether using `role` ever unloads `other`. */
104
+ conflicts(role, other) {
105
+ return conflictsOf(this.deps.config(), role).includes(other);
106
+ }
107
+ /**
108
+ * Makes room for `role`. @param main the chat's own model, which is what `main` stands for; the last one seen is used when a caller does not know it.
109
+ * Never fails: a model that cannot be unloaded is reported once and the work goes on, because the server may well manage on its own.
110
+ */
111
+ async ensure(role, main) {
112
+ if (role === "main" && main !== void 0) this.lastMain = main;
113
+ const config = this.deps.config();
114
+ if (conflictsOf(config, role).every((other) => !this.possible.has(other))) {
115
+ this.possible.add(role);
116
+ return;
117
+ }
118
+ for (let busy = this.busy(role); busy.length > 0; busy = this.busy(role)) await Promise.all(busy.map((other) => this.idle(other)));
119
+ const done = this.turn.then(async () => {
120
+ for (const victim of conflictsOf(this.deps.config(), role).filter((other) => this.possible.has(other) && !this.inUse(other))) await this.unload(victim, config, main ?? this.lastMain);
121
+ this.possible.add(role);
122
+ });
123
+ this.turn = done.catch(() => void 0);
124
+ await done;
125
+ }
126
+ /** Switches to `role`, reserves it before another switch can begin, and keeps that model resident for the call. */
127
+ async run(role, call, main) {
128
+ if (role === "main" && main !== void 0) this.lastMain = main;
129
+ const ready = this.turn.then(async () => {
130
+ for (let busy = this.busy(role); busy.length > 0; busy = this.busy(role)) await Promise.all(busy.map((other) => this.idle(other)));
131
+ const config = this.deps.config();
132
+ for (const victim of conflictsOf(config, role).filter((other) => this.possible.has(other) && !this.inUse(other))) await this.unload(victim, config, main ?? this.lastMain);
133
+ this.possible.add(role);
134
+ this.active.set(role, (this.active.get(role) ?? 0) + 1);
135
+ });
136
+ this.turn = ready.catch(() => void 0);
137
+ await ready;
138
+ try {
139
+ return await call();
140
+ } finally {
141
+ this.release(role);
142
+ }
143
+ }
144
+ /** Runs a call that uses a model of `role`, so that the model is not unloaded while the call is on. */
145
+ async using(role, call) {
146
+ this.active.set(role, (this.active.get(role) ?? 0) + 1);
147
+ try {
148
+ return await call();
149
+ } finally {
150
+ this.release(role);
151
+ }
152
+ }
153
+ release(role) {
154
+ const left = (this.active.get(role) ?? 1) - 1;
155
+ if (left > 0) this.active.set(role, left);
156
+ else {
157
+ this.active.delete(role);
158
+ for (const resume of this.drained.get(role) ?? []) resume();
159
+ this.drained.delete(role);
160
+ }
161
+ }
162
+ inUse(role) {
163
+ return (this.active.get(role) ?? 0) > 0;
164
+ }
165
+ /** The roles that conflict with `role`, may be resident and have calls on. */
166
+ busy(role) {
167
+ return conflictsOf(this.deps.config(), role).filter((other) => this.possible.has(other) && this.inUse(other));
168
+ }
169
+ idle(role) {
170
+ return new Promise((resolve) => {
171
+ this.drained.set(role, [...this.drained.get(role) ?? [], resolve]);
172
+ });
173
+ }
174
+ async unload(role, config, main) {
175
+ const target = role === "main" ? main === void 0 ? void 0 : {
176
+ route: main.provider,
177
+ model: main.model
178
+ } : config.models[role];
179
+ if (target === void 0 || target.route === "" || target.model === "") {
180
+ this.report(`offload: the ${role} model is not set, so it is not unloaded`);
181
+ this.possible.delete(role);
182
+ return;
183
+ }
184
+ const admin = this.deps.admin();
185
+ if (admin === void 0) {
186
+ this.report("offload: the AI providers plugin offers no model administration, so nothing is unloaded");
187
+ this.possible.delete(role);
188
+ return;
189
+ }
190
+ try {
191
+ const operations = admin.operations(target.route);
192
+ if (!operations.includes("unload")) {
193
+ this.report(`offload: the route "${target.route}" cannot unload models`);
194
+ this.possible.delete(role);
195
+ return;
196
+ }
197
+ if (operations.includes("status") && await this.loaded(admin, target) === false) {
198
+ this.possible.delete(role);
199
+ return;
200
+ }
201
+ await admin.unload(target.route, target.model);
202
+ this.possible.delete(role);
203
+ } catch (error) {
204
+ this.report(`offload: could not unload ${target.model} on ${target.route}: ${error instanceof Error ? error.message : String(error)}`);
205
+ }
206
+ }
207
+ /** Whether the server has the model in memory; a server that cannot say is taken to have it, since unloading what is not there is harmless. */
208
+ async loaded(admin, target) {
209
+ try {
210
+ return (await admin.status(target.route, target.model)).state !== "uninitialized";
211
+ } catch {
212
+ return true;
213
+ }
214
+ }
215
+ report(message) {
216
+ if (this.reported.has(message)) return;
217
+ this.reported.add(message);
218
+ this.deps.problem(message);
219
+ }
220
+ };
33
221
  // src/host/prompts/manage.ts
34
222
  /** A prompt the person asked for does not exist or cannot be written; the message says why. */
35
223
  var PromptEditError = class extends Error {};
@@ -810,7 +998,7 @@ async function uploadPreset(deps, worldId, file, name, language) {
810
998
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
811
999
  const preset = readPreset(file, name);
812
1000
  await mkdir(join(world.directory, IMPORT_FOLDER), { recursive: true });
813
- await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE), file);
1001
+ await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE$1), file);
814
1002
  const chatSessionId = await deps.authoring.ensure(world.summary.id, world.summary.name, authoringTitle(world.summary.name, language), language);
815
1003
  let failure;
816
1004
  try {
@@ -1359,6 +1547,8 @@ var RoleplayOrchestration = class extends Service {
1359
1547
  reflecting = () => false;
1360
1548
  /** What the story's turns are and taking the story back to one; there while the orchestration is. */
1361
1549
  timelines;
1550
+ /** Unloads the models that cannot share memory with the one about to be used; there while the plugin is. */
1551
+ residency;
1362
1552
  /** Background scene illustration jobs; there while the orchestration is mounted. */
1363
1553
  images;
1364
1554
  constructor(ctx) {
@@ -1501,7 +1691,7 @@ var Presets = class {
1501
1691
  const directory = await reservePreset(root, name, title ?? uploaded.name, uploaded.sampling);
1502
1692
  try {
1503
1693
  await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
1504
- await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE$1), file);
1694
+ await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
1505
1695
  } catch (error) {
1506
1696
  await deletePreset(root, name);
1507
1697
  throw error;
@@ -3673,6 +3863,7 @@ const VARIABLE_FIELDS = [
3673
3863
  "subject",
3674
3864
  "visibility",
3675
3865
  "description",
3866
+ "update",
3676
3867
  "min",
3677
3868
  "max",
3678
3869
  "integer",
@@ -3749,6 +3940,7 @@ function parseVariablesEdit(value) {
3749
3940
  subject: text("subject"),
3750
3941
  visibility: text("visibility"),
3751
3942
  ...text("description") === "" ? {} : { description: text("description") },
3943
+ ...text("update") === "" ? {} : { update: text("update") },
3752
3944
  ...min === void 0 ? {} : { min },
3753
3945
  ...max === void 0 ? {} : { max },
3754
3946
  ...integer === true ? { integer } : {},
@@ -9713,6 +9905,13 @@ const Config = z.object({
9713
9905
  passwordRef: z.string().default(""),
9714
9906
  intervalMinutes: z.number().min(0).default(0)
9715
9907
  }).default({ ...DEFAULT_SYNC }).volatile(),
9908
+ offload: z.object({
9909
+ models: z.dict(z.object({
9910
+ route: z.string().default(""),
9911
+ model: z.string().default("")
9912
+ })).default({}),
9913
+ groups: z.array(z.array(z.string())).default([])
9914
+ }).default({ ...DEFAULT_OFFLOAD }).volatile(),
9716
9915
  catalogueMaxBytes: z.number().min(1024).default(268435456).volatile(),
9717
9916
  catalogueTrashDays: z.number().min(0).default(30).volatile(),
9718
9917
  importMaxUploadBytes: z.number().min(1024).default(104857600).volatile(),
@@ -9763,6 +9962,13 @@ function apply(ctx, config) {
9763
9962
  const root = new RoleplayRoot(ctx, config.rootPath);
9764
9963
  root.start();
9765
9964
  const orchestration = new RoleplayOrchestration(ctx);
9965
+ orchestration.residency = new ModelResidency({
9966
+ config: () => offloadOf(config.offload.get()),
9967
+ admin: () => ctx.get("aiModels"),
9968
+ problem: (message) => {
9969
+ ctx.logger.warn(`roleplay: ${message}`);
9970
+ }
9971
+ });
9766
9972
  const worlds = new WorldCatalog(ctx, root);
9767
9973
  const prompts = new PromptLibrary(ctx, root);
9768
9974
  prompts.bootstrap();
@@ -10338,12 +10544,12 @@ async function editableWorld(worlds, worldId, rootPath) {
10338
10544
  };
10339
10545
  }
10340
10546
  function imageGenerationOf(ctx) {
10341
- const service = ctx.get("imageGeneration");
10547
+ const service = guarded(ctx.roleplayOrchestration.residency, "image", ctx.get("imageGeneration"), ["generate"]);
10342
10548
  if (service === void 0) throw new AgentUnavailableError("no image generation provider is selected");
10343
10549
  return service;
10344
10550
  }
10345
10551
  function textToSpeechOf(ctx) {
10346
- const service = ctx.get("textToSpeech");
10552
+ const service = guarded(ctx.roleplayOrchestration.residency, "speech", ctx.get("textToSpeech"), ["synthesize"]);
10347
10553
  if (service === void 0) throw new AgentUnavailableError("no text-to-speech provider is selected");
10348
10554
  return service;
10349
10555
  }
@@ -1,5 +1,5 @@
1
- import { n as atomicWrite } from "./access-CXtaZNbx.js";
2
- import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-CzqhC8sT.js";
1
+ import { n as atomicWrite } from "./access-Md1YTSX1.js";
2
+ import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-C2AGl7Je.js";
3
3
  import { dirname, extname, join } from "node:path";
4
4
  import { existsSync } from "node:fs";
5
5
  import { createHash } from "node:crypto";
@@ -374,4 +374,4 @@ async function addToLibrary(sessionFolder, bytes, originalName) {
374
374
  }
375
375
  export { slug as C, norm as S, uniqueKey as T, writeImageFileMetadata as _, LIBRARY_FOLDER as a, NoEmbeddingService as b, nextSceneSerial as c, sceneImagePath as d, writeImage as f, sidecarOf as g, readImageFileMetadata as h, libraryHashes as i, readImageMetadata as l, mediaTypeOf as m, addToLibraryOnce as n, entityImageDirectory as o, MEDIA_TYPES as p, imageExtensionOf as r, inheritImages as s, addToLibrary as t, referenceImagePath as u, readPngMetadata as v, trOf as w, mapLimit as x, withPngMetadata as y };
376
376
 
377
- //# sourceMappingURL=library-CH-ahlm0.js.map
377
+ //# sourceMappingURL=library-4zmCAshR.js.map
@@ -1,9 +1,9 @@
1
- import "./access-CXtaZNbx.js";
2
- import { _t as writeLorebookEntry, ct as deleteLorebookEntry, ft as loadLorebook, gt as updateLorebookInfo, i as contextOf, lt as entriesOf, mt as readLorebook$1, pt as lorebookDirectory, r as MAX_PREVIEW_TEXT, tn as ImportCardError } from "./authoring-tools-C9cmcUbD.js";
3
- import { $ as IMPORT_FOLDER, Lt as LORE_KINDS, Q as withPlayer, Rt as LORE_SCOPES, Y as cleanText, Z as partsOf, n as createPresetFromGuidance } from "./presets-Cl9sU3Qs.js";
4
- import { C as slug, T as uniqueKey, w as trOf, x as mapLimit } from "./library-CH-ahlm0.js";
5
- import { i as translator, r as languageOf } from "./text-CzqhC8sT.js";
6
- import { nt as shippedPromptsDirectory } from "./hooks-BpLN_hhT.js";
1
+ import "./access-Md1YTSX1.js";
2
+ import { _t as writeLorebookEntry, ct as deleteLorebookEntry, ft as loadLorebook, gt as updateLorebookInfo, i as contextOf, lt as entriesOf, mt as readLorebook$1, pt as lorebookDirectory, r as MAX_PREVIEW_TEXT, tn as ImportCardError } from "./authoring-tools-BFdw7ahj.js";
3
+ import { $ as IMPORT_FOLDER, Q as withPlayer, Rt as LORE_KINDS, Y as cleanText, Z as partsOf, n as createPresetFromGuidance, zt as LORE_SCOPES } from "./presets-_U-xroo0.js";
4
+ import { C as slug, T as uniqueKey, w as trOf, x as mapLimit } from "./library-4zmCAshR.js";
5
+ import { i as translator, r as languageOf } from "./text-C2AGl7Je.js";
6
+ import { it as shippedPromptsDirectory } from "./hooks-C2U1-8ur.js";
7
7
  import { join } from "node:path";
8
8
  import { existsSync, readFileSync } from "node:fs";
9
9
  import { readFile, rm, writeFile } from "node:fs/promises";
@@ -696,4 +696,4 @@ async function lorebookApproval(exec, next, state) {
696
696
  }
697
697
  export { lorebookImportMessage as a, readLorebook as c, lorebookOfChat as d, lorebookAuthorTools as i, selectEntries as l, LorebookReader as n, pendingTargets as o, lorebookApproval as r, previewLorebook as s, LOREBOOK_UPLOAD as t, lorebookChatSessionId as u };
698
698
 
699
- //# sourceMappingURL=lorebook-author-tools-Cg7QQemi.js.map
699
+ //# sourceMappingURL=lorebook-author-tools-Bjfjt3bg.js.map
@@ -1,7 +1,7 @@
1
- import { n as limitAuthoringAgents, pt as lorebookDirectory } from "./authoring-tools-C9cmcUbD.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-B9pGCeir.js";
3
- import { d as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-Cg7QQemi.js";
4
- import "./hooks-BpLN_hhT.js";
1
+ import { n as limitAuthoringAgents, pt as lorebookDirectory } from "./authoring-tools-BFdw7ahj.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-C0M3rXEN.js";
3
+ import { d as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-Bjfjt3bg.js";
4
+ import "./hooks-C2U1-8ur.js";
5
5
  import { join } from "node:path";
6
6
  import { existsSync, readdirSync } from "node:fs";
7
7
  // src/lorebook-authoring.ts
@@ -1,4 +1,4 @@
1
- import { i as atomicWriteSync } from "./access-CXtaZNbx.js";
1
+ import { i as atomicWriteSync } from "./access-Md1YTSX1.js";
2
2
  import { join } from "node:path";
3
3
  import { existsSync, readFileSync, statSync } from "node:fs";
4
4
  // ../dsh-roleplay-model/src/clock.ts
@@ -15,7 +15,9 @@ const DECISION_SITES = [
15
15
  "agency",
16
16
  "refusal",
17
17
  "rules",
18
- "secrets"
18
+ "secrets",
19
+ "variables",
20
+ "reuse"
19
21
  ];
20
22
  /** The sites that check what the game master delivers to the player. They are off unless a chat turns one on: a check costs a request, or at least a call, in every turn. */
21
23
  const GATE_SITES = ["agency", "refusal"];
@@ -188,6 +190,8 @@ const SETTINGS_SPEC = {
188
190
  refusal: choice(GATE_MODES, "off"),
189
191
  rules: choice(EXTRA_MODES, "off"),
190
192
  secrets: choice(EXTRA_MODES, "off"),
193
+ variables: choice(GATE_MODES, "llm"),
194
+ reuse: choice(EXTRA_MODES, "off"),
191
195
  gateThreshold: ratio(.1, .95, .5),
192
196
  confidence: ratio(0, 1, .7)
193
197
  },
@@ -454,4 +458,4 @@ function decodeOutput(text) {
454
458
  }
455
459
  export { emptyStats as _, liveSettings as a, writeSettings as c, parseSettings as d, parseSwitchboard as f, GATE_SITES as g, DECISION_SITES 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 };
456
460
 
457
- //# sourceMappingURL=narration-B0hConSw.js.map
461
+ //# sourceMappingURL=narration-b_VBEUWn.js.map