@dsh-agentic-roleplay/core 0.7.2 → 0.8.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 (54) hide show
  1. package/README.md +1 -1
  2. package/lib/authoring-tools-DNnx0Nts.js +3574 -0
  3. package/lib/authoring.js +295 -333
  4. package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
  5. package/lib/client.js +931 -415
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +2 -2
  8. package/lib/doctor.js +2 -2
  9. package/lib/{gallery-BxZGOgMb.js → gallery-D9nG3C78.js} +2 -2
  10. package/lib/{generator-BFmSYvR8.js → generator-r1Czm7oi.js} +2 -2
  11. package/lib/helper.js +1 -1
  12. package/lib/{hooks-HnqXO8mM.js → hooks-BQCzgggH.js} +92 -8
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +1326 -1638
  15. package/lib/{library-BGxPKs9a.js → library-zI-2tG7h.js} +59 -9
  16. package/lib/{lorebook-author-tools-D9RrMK5g.js → lorebook-author-tools-ywaYicwd.js} +7 -7
  17. package/lib/lorebook-authoring.js +4 -4
  18. package/lib/{narration-DvFBqmqe.js → narration-CnBlVure.js} +52 -8
  19. package/lib/orchestration.js +95 -18
  20. package/lib/{pack-jail-MPekqSuQ.js → pack-jail-5EJ-WYyW.js} +1274 -69
  21. package/lib/{packs-jowC-MN_.js → packs-Cv8hanXJ.js} +2 -2
  22. package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-BSaMSd3G.js} +6 -6
  23. package/lib/{preset-VatN-845.js → preset-CWI3-0r1.js} +4 -3
  24. package/lib/{preset-author-tools-8kv1Glxe.js → preset-author-tools-BrJYa2cr.js} +7 -7
  25. package/lib/preset-authoring.js +5 -5
  26. package/lib/presets-MwOSMMyu.js +3998 -0
  27. package/lib/{reflection-CvOZGjmn.js → reflection-zSaMsjKj.js} +127 -127
  28. package/lib/{text-JbWfTHbr.js → text-BzudpQLS.js} +11 -1
  29. package/lib/{turn-guard-BvCs1VxB.js → turn-guard-Cv8pfHEA.js} +6 -2
  30. package/package.json +2 -2
  31. package/prompts/en/import/casting.md +14 -0
  32. package/prompts/en/import/classifier.md +9 -0
  33. package/prompts/en/import/finish-draft.md +1 -0
  34. package/prompts/en/import/generator.md +8 -0
  35. package/prompts/en/import/notice-repair.md +4 -0
  36. package/prompts/en/import/repair-again.md +3 -0
  37. package/prompts/en/import/roster.md +1 -0
  38. package/prompts/en/import/variables.md +1 -0
  39. package/prompts/en/roleplay/game-master.md +3 -0
  40. package/prompts/en/roleplay/standing.md +1 -0
  41. package/prompts/en/world/author.md +1 -1
  42. package/prompts/zh/import/casting.md +14 -0
  43. package/prompts/zh/import/classifier.md +9 -0
  44. package/prompts/zh/import/finish-draft.md +1 -0
  45. package/prompts/zh/import/generator.md +8 -0
  46. package/prompts/zh/import/notice-repair.md +4 -0
  47. package/prompts/zh/import/repair-again.md +3 -0
  48. package/prompts/zh/import/roster.md +1 -0
  49. package/prompts/zh/import/variables.md +1 -0
  50. package/prompts/zh/roleplay/game-master.md +3 -0
  51. package/prompts/zh/roleplay/standing.md +1 -0
  52. package/prompts/zh/world/author.md +1 -1
  53. package/lib/authoring-tools-q34iq3hW.js +0 -6140
  54. package/lib/route-DRTJ_vcA.js +0 -518
@@ -1,8 +1,8 @@
1
1
  import "./access-DtOxFKBK.js";
2
- import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-JbWfTHbr.js";
2
+ import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-BzudpQLS.js";
3
3
  import { dirname, extname, join } from "node:path";
4
4
  import { existsSync } from "node:fs";
5
- import { randomUUID } from "node:crypto";
5
+ import { createHash, randomUUID } from "node:crypto";
6
6
  import { copyFile, link, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
7
7
  //#region src/host/import/run.ts
8
8
  /** The labels of a job's prompt, in the language of the import. */
@@ -94,6 +94,18 @@ function chunks(png) {
94
94
  function isOurText(entry) {
95
95
  return entry.type === "iTXt" && entry.data.subarray(0, 12).toString("latin1") === KEYWORD && entry.data[12] === 0;
96
96
  }
97
+ /** Chunks that describe a picture instead of being it: text, time and EXIF. */
98
+ const DESCRIPTIVE_CHUNKS = /* @__PURE__ */ new Set([
99
+ "iTXt",
100
+ "tEXt",
101
+ "zTXt",
102
+ "tIME",
103
+ "eXIf"
104
+ ]);
105
+ /** The PNG without what only describes it, so the same picture gives the same bytes before and after metadata is written into it. */
106
+ function pngPictureBytes(png) {
107
+ return Buffer.concat([SIGNATURE, ...chunks(Buffer.from(png)).filter((entry) => !DESCRIPTIVE_CHUNKS.has(entry.type)).map((entry) => entry.bytes)]);
108
+ }
97
109
  /** Put self-describing UTF-8 JSON in a PNG iTXt chunk, replacing older roleplay metadata. */
98
110
  function withPngMetadata(png, metadata) {
99
111
  const entries = chunks(Buffer.from(png)).filter((entry) => !isOurText(entry));
@@ -296,6 +308,27 @@ const MAGIC = [
296
308
  function imageExtensionOf(bytes) {
297
309
  return MAGIC.find((format) => format.test(bytes))?.type;
298
310
  }
311
+ /** A hash of the picture itself: a PNG's metadata (ours is written into it after the file is saved) is left out, so the same picture hashes the same wherever it came from. */
312
+ function pictureHash(bytes) {
313
+ let picture = bytes;
314
+ if (imageExtensionOf(bytes) === ".png") try {
315
+ picture = pngPictureBytes(bytes);
316
+ } catch {
317
+ picture = bytes;
318
+ }
319
+ return createHash("sha256").update(picture).digest("hex");
320
+ }
321
+ /** The pictures already in the library, by the hash of the picture: its path under `images/`. */
322
+ async function libraryHashes(sessionFolder) {
323
+ const directory = join(sessionFolder, "images", LIBRARY_FOLDER);
324
+ const found = /* @__PURE__ */ new Map();
325
+ for (const name of await readdir(directory).catch(() => [])) {
326
+ if (MEDIA_TYPES[extname(name).toLowerCase()] === void 0) continue;
327
+ const bytes = await readFile(join(directory, name)).catch(() => void 0);
328
+ if (bytes !== void 0 && imageExtensionOf(bytes) !== void 0) found.set(pictureHash(bytes), `${LIBRARY_FOLDER}/${name}`);
329
+ }
330
+ return found;
331
+ }
299
332
  /** A file name made of the letters and digits of the name it came with, in any script. */
300
333
  function libraryName(original, extension, taken) {
301
334
  const stem = trimCharacters(withoutExtension(original).normalize("NFKC").replace(/[^\p{L}\p{N}]+/gu, "-"), "-").slice(0, 60) || "image";
@@ -305,14 +338,22 @@ function libraryName(original, extension, taken) {
305
338
  }
306
339
  }
307
340
  /**
308
- * Puts an image the person brought into the session's library, with metadata that says where it came from and that it is reusable. What it
309
- * shows is not known yet: the interpreter fills that in.
341
+ * Puts a picture into the library unless the library already holds that picture (the same image, whatever metadata the file carries), whatever it came from: an upload, an address, a generation.
342
+ * Metadata says where it came from and that it is reusable; what it shows is not known yet, and the interpreter fills that in.
343
+ * @param known the hashes of the library when the caller has read them (kept up to date here), to avoid reading the library again for each picture.
310
344
  * @throws {Error} when the bytes are not a PNG, JPEG, WebP or GIF image.
311
- * @returns its path under `images/`.
345
+ * @returns its path under `images/`, and whether it was added or an equal picture was there.
312
346
  */
313
- async function addToLibrary(sessionFolder, bytes, originalName) {
347
+ async function addToLibraryOnce(sessionFolder, bytes, originalName, known) {
314
348
  const extension = imageExtensionOf(bytes);
315
349
  if (extension === void 0 || MEDIA_TYPES[extension] === void 0) throw new Error("only PNG, JPEG, WebP and GIF images can be added");
350
+ const hashes = known ?? await libraryHashes(sessionFolder);
351
+ const hash = pictureHash(bytes);
352
+ const present = hashes.get(hash);
353
+ if (present !== void 0) return {
354
+ path: present,
355
+ added: false
356
+ };
316
357
  const directory = join(sessionFolder, "images", LIBRARY_FOLDER);
317
358
  await mkdir(directory, { recursive: true });
318
359
  const name = libraryName(originalName, extension, (candidate) => existsSync(join(directory, candidate)));
@@ -330,9 +371,18 @@ async function addToLibrary(sessionFolder, bytes, originalName) {
330
371
  subjects: [],
331
372
  tags: []
332
373
  });
333
- return `${LIBRARY_FOLDER}/${name}`;
374
+ const path = `${LIBRARY_FOLDER}/${name}`;
375
+ hashes.set(hash, path);
376
+ return {
377
+ path,
378
+ added: true
379
+ };
380
+ }
381
+ /** {@link addToLibraryOnce} for a caller that only wants the path: a picture the library holds already is not added again. */
382
+ async function addToLibrary(sessionFolder, bytes, originalName) {
383
+ return (await addToLibraryOnce(sessionFolder, bytes, originalName)).path;
334
384
  }
335
385
  //#endregion
336
- export { uniqueKey as S, 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, trOf as x, norm as y };
386
+ export { trOf as C, slug as S, writeImageFileMetadata as _, LIBRARY_FOLDER as a, mapLimit 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, uniqueKey as w, norm as x, withPngMetadata as y };
337
387
 
338
- //# sourceMappingURL=library-BGxPKs9a.js.map
388
+ //# sourceMappingURL=library-zI-2tG7h.js.map
@@ -1,13 +1,13 @@
1
1
  import "./access-DtOxFKBK.js";
2
- import { Ct as loadLorebook, Dt as updateLorebookInfo, Ht as ImportCardError, J as partsOf, K as cleanText, Kt as LORE_KINDS, Ot as writeLorebookEntry, Tt as readLorebook$1, Y as withPlayer, bt as entriesOf, ct as IMPORT_FOLDER, i as contextOf, qt as LORE_SCOPES, r as MAX_PREVIEW_TEXT, wt as lorebookDirectory, yt as deleteLorebookEntry } from "./authoring-tools-q34iq3hW.js";
3
- import { c as createPresetFromGuidance } from "./route-DRTJ_vcA.js";
4
- import { nt as shippedPromptsDirectory } from "./hooks-HnqXO8mM.js";
5
- import { i as translator, r as languageOf } from "./text-JbWfTHbr.js";
6
- import { S as uniqueKey, b as slug, v as mapLimit, x as trOf } from "./library-BGxPKs9a.js";
2
+ import { G as loadLorebook, H as entriesOf, K as lorebookDirectory, Nt as ImportCardError, V as deleteLorebookEntry, X as writeLorebookEntry, Y as updateLorebookInfo, i as contextOf, q as readLorebook$1, r as MAX_PREVIEW_TEXT } from "./authoring-tools-DNnx0Nts.js";
3
+ import { Dt as LORE_KINDS, G as withPlayer, H as cleanText, K as IMPORT_FOLDER, Ot as LORE_SCOPES, W as partsOf, n as createPresetFromGuidance } from "./presets-MwOSMMyu.js";
4
+ import { at as shippedPromptsDirectory } from "./hooks-BQCzgggH.js";
5
+ import { i as translator, r as languageOf } from "./text-BzudpQLS.js";
6
+ import { C as trOf, S as slug, b as mapLimit, w as uniqueKey } from "./library-zI-2tG7h.js";
7
7
  import { join } from "node:path";
8
8
  import { existsSync, readFileSync } from "node:fs";
9
- import { defineTool } from "@deepseek-ai/dsh-tools";
10
9
  import { readFile, rm, writeFile } from "node:fs/promises";
10
+ import { defineTool } from "@deepseek-ai/dsh-tools";
11
11
  //#region src/shared/lorebook-chat.ts
12
12
  const PREFIX = "lorebook-author-";
13
13
  /** Stable DSH chat identity for the authoring conversation of one library lorebook. */
@@ -699,4 +699,4 @@ async function lorebookApproval(exec, next, state) {
699
699
  //#endregion
700
700
  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 };
701
701
 
702
- //# sourceMappingURL=lorebook-author-tools-D9RrMK5g.js.map
702
+ //# sourceMappingURL=lorebook-author-tools-ywaYicwd.js.map
@@ -1,7 +1,7 @@
1
- import { n as limitAuthoringAgents, wt as lorebookDirectory } from "./authoring-tools-q34iq3hW.js";
2
- import { d as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-D9RrMK5g.js";
3
- import "./hooks-HnqXO8mM.js";
4
- import { t as guardAuthoringTurns } from "./turn-guard-BvCs1VxB.js";
1
+ import { K as lorebookDirectory, n as limitAuthoringAgents } from "./authoring-tools-DNnx0Nts.js";
2
+ import { d as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-ywaYicwd.js";
3
+ import "./hooks-BQCzgggH.js";
4
+ import { t as guardAuthoringTurns } from "./turn-guard-Cv8pfHEA.js";
5
5
  import { join } from "node:path";
6
6
  import { existsSync, readdirSync } from "node:fs";
7
7
  //#region src/lorebook-authoring.ts
@@ -1,6 +1,8 @@
1
1
  import "./access-DtOxFKBK.js";
2
- import { join } from "node:path";
3
- import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { chmodSync, existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
4
6
  //#region ../dsh-roleplay-model/src/clock.ts
5
7
  /**
6
8
  * How the story's time passes: `simulated` moves only when the story does (the game master says how
@@ -320,6 +322,51 @@ function parseSettings(value) {
320
322
  };
321
323
  }
322
324
  //#endregion
325
+ //#region src/host/atomic-write.ts
326
+ /**
327
+ * Replaces a file in one step: the data goes to a temporary file in the same folder and is renamed over the file, so an interruption leaves the old file or the new one,
328
+ * never half of either. Every writer of a file someone else may read at the same time goes through here.
329
+ */
330
+ async function atomicWrite(file, data, options = {}) {
331
+ if (options.createDirectory === true) await mkdir(dirname(file), { recursive: true });
332
+ const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
333
+ try {
334
+ const mode = options.mode ?? await stat(file).then((value) => value.mode & 511, (error) => {
335
+ if (error.code === "ENOENT") return 420;
336
+ throw error;
337
+ });
338
+ await writeFile(temporary, data, { mode });
339
+ await chmod(temporary, mode);
340
+ await rename(temporary, file);
341
+ } catch (error) {
342
+ await rm(temporary, { force: true });
343
+ throw error;
344
+ }
345
+ }
346
+ /** A JSON file written the same way, with the indentation given (none by default) and a final newline when it is indented. */
347
+ async function atomicWriteJson(file, value, options = {}) {
348
+ const { indent, ...rest } = options;
349
+ await atomicWrite(file, indent === void 0 ? JSON.stringify(value) : `${JSON.stringify(value, null, indent)}\n`, rest);
350
+ }
351
+ /** The synchronous form, for the few writers that cannot wait (the chat settings, read at every step). */
352
+ function atomicWriteSync(file, data) {
353
+ const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
354
+ try {
355
+ let mode = 420;
356
+ try {
357
+ mode = statSync(file).mode & 511;
358
+ } catch (error) {
359
+ if (error.code !== "ENOENT") throw error;
360
+ }
361
+ writeFileSync(temporary, data, { mode });
362
+ chmodSync(temporary, mode);
363
+ renameSync(temporary, file);
364
+ } catch (error) {
365
+ rmSync(temporary, { force: true });
366
+ throw error;
367
+ }
368
+ }
369
+ //#endregion
323
370
  //#region src/host/sessions/settings.ts
324
371
  const SETTINGS_FILE = "settings.json";
325
372
  const known = /* @__PURE__ */ new Map();
@@ -363,10 +410,7 @@ function readSettings(folder) {
363
410
  function writeSettings(folder, value) {
364
411
  const parsed = parseSettings(value);
365
412
  if (!parsed.ok) throw new InvalidSettingsError(parsed.problems);
366
- const file = join(folder, SETTINGS_FILE);
367
- const temporary = `${file}.${process.pid}.tmp`;
368
- writeFileSync(temporary, `${JSON.stringify(parsed.value, null, 2)}\n`);
369
- renameSync(temporary, file);
413
+ atomicWriteSync(join(folder, SETTINGS_FILE), `${JSON.stringify(parsed.value, null, 2)}\n`);
370
414
  known.delete(folder);
371
415
  return parsed.value;
372
416
  }
@@ -456,6 +500,6 @@ function decodeOutput(text) {
456
500
  }
457
501
  }
458
502
  //#endregion
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 };
503
+ export { DECISION_SITES as _, liveSettings as a, writeSettings as c, DEFAULT_SETTINGS as d, SETTINGS_SPEC as f, rulesOf as g, WORLD_RULES_KEY as h, InvalidSettingsError as i, atomicWrite as l, parseSwitchboard as m, encodeOutput as n, readSettings as o, parseSettings as p, encodePreview as r, useChildReasoning as s, decodeOutput as t, atomicWriteJson as u, GATE_SITES as v, emptyStats as y };
460
504
 
461
- //# sourceMappingURL=narration-DvFBqmqe.js.map
505
+ //# sourceMappingURL=narration-CnBlVure.js.map
@@ -1,19 +1,19 @@
1
1
  import { a as chatSessionId, o as roleplaySessionOf, t as promptFor } from "./access-DtOxFKBK.js";
2
- import { E as INTENT_STATUSES, a as routeVerdicts, i as noAt, n as askYesNo, o as yesAt, t as announceProblem } from "./route-DRTJ_vcA.js";
3
- import { _ as referent, a as whereabouts, g as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-CvOZGjmn.js";
4
- import { a as liveSettings, g as GATE_SITES, n as encodeOutput } from "./narration-DvFBqmqe.js";
5
- import { D as describeWhen, O as zoneOf, R as wrongLanguage, T as ClockError, c as record, d as toolEnabled, f as MAX_OOC_ANSWER, k as RESULTS, l as AUTHORING_NEEDS, n as installHooks, o as PREVIEW_TOOL, ot as ReflectionRefusedError, p as storesOf, r as externalGiven, s as createTools$1, u as characterRunner, v as readVerdicts, y as writeVerdicts } from "./hooks-HnqXO8mM.js";
6
- import { i as translator, r as languageOf } from "./text-JbWfTHbr.js";
7
- import { a as childTrace, c as runChild, h as currentTurn, n as childModel, r as childSampling, v as estimateAnswer, y as tokensOf } from "./child-CyCViUKa.js";
8
- import { S as uniqueKey, b as slug, t as addToLibrary } from "./library-BGxPKs9a.js";
9
- import { _ as API_PREFIX } from "./packs-jowC-MN_.js";
10
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-BxZGOgMb.js";
11
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-DvZtnf0Q.js";
2
+ import { F as routeVerdicts, I as yesAt, M as askYesNo, P as noAt, j as announceProblem, jt as INTENT_STATUSES, m as STANDING_PROMPT } from "./presets-MwOSMMyu.js";
3
+ import { _ as referent, a as whereabouts, g as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-zSaMsjKj.js";
4
+ import { a as liveSettings, n as encodeOutput, v as GATE_SITES } from "./narration-CnBlVure.js";
5
+ import { A as RESULTS, E as ClockError, O as describeWhen, b as writeVerdicts, c as record, d as toolEnabled, k as zoneOf, l as AUTHORING_NEEDS, m as storesOf, n as installHooks, o as PREVIEW_TOOL, ot as shippedText, p as MAX_OOC_ANSWER, r as externalGiven, s as createTools$1, u as characterRunner, ut as ReflectionRefusedError, y as readVerdicts, z as wrongLanguage } from "./hooks-BQCzgggH.js";
6
+ import { i as translator, r as languageOf } from "./text-BzudpQLS.js";
7
+ import { a as childTrace, c as runChild, h as currentTurn, n as childModel, r as childSampling, v as estimateAnswer, y as tokensOf } from "./child-D6mpkkCE.js";
8
+ import { S as slug, t as addToLibrary, w as uniqueKey } from "./library-zI-2tG7h.js";
9
+ import { _ as API_PREFIX } from "./packs-Cv8hanXJ.js";
10
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-D9nG3C78.js";
11
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-BSaMSd3G.js";
12
12
  import { join } from "node:path";
13
13
  import { existsSync } from "node:fs";
14
+ import { readdir } from "node:fs/promises";
14
15
  import { SessionId } from "@deepseek-ai/dsh-session";
15
16
  import { defineTool } from "@deepseek-ai/dsh-tools";
16
- import { readdir } from "node:fs/promises";
17
17
  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";
18
18
  //#region src/host/tools/resource-hint.ts
19
19
  /** 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. */
@@ -932,6 +932,20 @@ const THING_TEXT_CHARS = 300;
932
932
  const FIT_TEXTS = 6;
933
933
  const FIT_TEXT_CHARS = 200;
934
934
  const editEstimate = (things, texts, chars, language) => estimateAnswer(Array.from({ length: Math.max(1, things) * texts }, () => chars), language);
935
+ /** A person made up without a place joins the scene: the place of the player's character, which is where the author is told to put them. */
936
+ function placedWhereThePlayerIs(args, store) {
937
+ if (!Array.isArray(args["characters"])) return args;
938
+ const here = store.cast().find((member) => member.character.control === "player")?.place?.location;
939
+ if (here === void 0) return args;
940
+ const characters = args["characters"].map((entry) => typeof entry === "object" && entry !== null && entry["place"] === void 0 ? {
941
+ ...entry,
942
+ place: { location: locationKey(here) }
943
+ } : entry);
944
+ return {
945
+ ...args,
946
+ characters
947
+ };
948
+ }
935
949
  function authorTools(job, work, mode, limits) {
936
950
  const link = {
937
951
  session: job.store.story,
@@ -971,9 +985,26 @@ function authorTools(job, work, mode, limits) {
971
985
  const edit = parseRecordsEdit(args);
972
986
  const makes = (edit.characters?.length ?? 0) + (edit.places?.length ?? 0) + (edit.items?.length ?? 0) + (edit.variables?.length ?? 0) + (edit.triggers?.length ?? 0);
973
987
  if (mode === "consolidate" && makes > 0) throw new Error("fitting things in does not make up anything new: connect what exists");
974
- const already = job.store.story.consolidation.createdIn(job.turn).length;
975
- if (makes > 0 && already + makes > limits.perTurn) throw new Error(`this edit makes ${makes} new thing${makes === 1 ? "" : "s"} and ${already} ${already === 1 ? "was" : "were"} already made this turn, which would pass the ${limits.perTurn} this chat allows per turn: make fewer, or none`);
976
- const result = await tool.execute(args, exec);
988
+ const madeBefore = job.store.story.consolidation.createdIn(job.turn);
989
+ const allowed = [
990
+ [
991
+ "character",
992
+ edit.characters?.length ?? 0,
993
+ madeBefore.filter((entry) => entry.kind === "character").length
994
+ ],
995
+ [
996
+ "place",
997
+ edit.places?.length ?? 0,
998
+ madeBefore.filter((entry) => entry.kind === "location").length
999
+ ],
1000
+ [
1001
+ "other thing",
1002
+ (edit.items?.length ?? 0) + (edit.variables?.length ?? 0) + (edit.triggers?.length ?? 0),
1003
+ 0
1004
+ ]
1005
+ ];
1006
+ for (const [noun, now, already] of allowed) if (now > 0 && already + now > limits.perTurn) throw new Error(`this edit makes ${now} new ${noun}${now === 1 ? "" : "s"} and ${already} ${already === 1 ? "was" : "were"} already made this turn, which would pass the ${limits.perTurn} this chat allows per turn for each kind: make fewer, or none`);
1007
+ const result = await tool.execute(placedWhereThePlayerIs(args, job.store), exec);
977
1008
  for (const key of result.character_keys ?? []) work.created.push({
978
1009
  kind: "character",
979
1010
  key
@@ -1049,7 +1080,7 @@ function createPrompt(job, perTurn) {
1049
1080
  `The game master asks for something to be made up. Reason given: ${job.need}.`,
1050
1081
  `What it says is needed: ${job.what}`,
1051
1082
  "",
1052
- `It is turn ${job.turn}. At most ${perTurn} new thing${perTurn === 1 ? "" : "s"} may be made in a turn, and ${store.story.consolidation.createdIn(job.turn).length} already ${store.story.consolidation.createdIn(job.turn).length === 1 ? "was" : "were"} this turn.`,
1083
+ `It is turn ${job.turn}. At most ${perTurn} new character${perTurn === 1 ? "" : "s"} and ${perTurn} new place${perTurn === 1 ? "" : "s"} may be made in a turn (each kind has its own allowance); already made this turn: ${store.story.consolidation.createdIn(job.turn).filter((entry) => entry.kind === "character").length} character(s), ${store.story.consolidation.createdIn(job.turn).filter((entry) => entry.kind === "location").length} place(s).`,
1053
1084
  here === void 0 ? "The story is not in any place yet." : `The story is in ${here.name} (${locationKey(here)}). With the player's character: ${present.filter((member) => member.character.control !== "player").map((member) => `${member.character.name} (${member.key})`).join(", ") || "no one else"}.`,
1054
1085
  "",
1055
1086
  "## What happened lately",
@@ -1194,6 +1225,12 @@ function worldAuthor(deps) {
1194
1225
  return errors.length === 0 ? void 0 : `what you made is not usable yet; fix it with edit_world:\n${describeFindings(errors).join("\n")}`;
1195
1226
  },
1196
1227
  maxCalls: 30 + (given(parent).length > 0 ? EXTERNAL_CALLS : 0)
1228
+ }).catch((error) => {
1229
+ if (work.created.length === 0 || signal.aborted) throw error;
1230
+ return {
1231
+ outcome: "created",
1232
+ summary: `the author made it but did not finish its report (${error instanceof Error ? error.message : String(error)})`
1233
+ };
1197
1234
  });
1198
1235
  const label = names(job.store);
1199
1236
  const created = work.created.map((entry) => ({
@@ -1611,6 +1648,7 @@ var AfterTurnJobs = class {
1611
1648
  strategizing = /* @__PURE__ */ new Set();
1612
1649
  judging = /* @__PURE__ */ new Set();
1613
1650
  reflecting = /* @__PURE__ */ new Set();
1651
+ casting = /* @__PURE__ */ new Set();
1614
1652
  constructor(deps) {
1615
1653
  this.deps = deps;
1616
1654
  }
@@ -1618,6 +1656,7 @@ var AfterTurnJobs = class {
1618
1656
  this.consolidate(owner, cancel);
1619
1657
  this.strategize(owner, cancel);
1620
1658
  this.judge(owner, cancel);
1659
+ this.cast(owner, cancel);
1621
1660
  const reason = this.reflectionDue(owner);
1622
1661
  if (reason !== void 0) this.reflect(owner, reason, cancel);
1623
1662
  }
@@ -1693,6 +1732,37 @@ var AfterTurnJobs = class {
1693
1732
  this.strategizing.delete(owner.chat);
1694
1733
  }));
1695
1734
  }
1735
+ /** What a trigger asked the world author to make (a beat with `dispatch: author`) is made now, one request after the other: the game master is never asked, so it cannot ignore it. */
1736
+ cast(owner, cancel) {
1737
+ const store = this.deps.stores(owner.chat);
1738
+ if (store === void 0 || this.casting.has(owner.chat) || store.claimAuthorBeats === void 0 || !store.settings().authoring.enabled) return;
1739
+ const requests = store.claimAuthorBeats();
1740
+ if (requests.length === 0) return;
1741
+ this.casting.add(owner.chat);
1742
+ this.deps.track(owner.chat, (async () => {
1743
+ for (const request of requests) {
1744
+ const need = AUTHORING_NEEDS.find((candidate) => candidate === request.need);
1745
+ if (need === void 0) {
1746
+ this.deps.problem(`a trigger asked the world author for "${request.need}", which is not a reason to make something up`);
1747
+ continue;
1748
+ }
1749
+ try {
1750
+ await this.deps.boundaries().author.create({
1751
+ chat: owner.chat,
1752
+ turn: owner.turn,
1753
+ need,
1754
+ what: request.text,
1755
+ store
1756
+ }, cancel);
1757
+ this.deps.written(owner.chat);
1758
+ } catch (error) {
1759
+ if (!cancel.aborted) this.deps.problem(`the world author could not make what a trigger asked for: ${messageOf(error)}`);
1760
+ }
1761
+ }
1762
+ })().finally(() => {
1763
+ this.casting.delete(owner.chat);
1764
+ }));
1765
+ }
1696
1766
  /** The statements that triggers wait on are judged; a trigger fires from the verdict at the next look. */
1697
1767
  judge(owner, cancel) {
1698
1768
  const store = this.deps.stores(owner.chat);
@@ -2179,8 +2249,9 @@ async function expandWorld(boundaries, store, state, owner, input, signal) {
2179
2249
  if (what === "") throw new Error("say what is needed, from what the story has established: who or where, and why now");
2180
2250
  const { authoring } = store.settings();
2181
2251
  if (!authoring.enabled) throw new Error("this world is closed: nothing can be made up in it");
2182
- const made = store.story.consolidation.createdIn(owner.turn).length;
2183
- if (made >= authoring.perTurn) throw new Error(`${made} new thing${made === 1 ? " was" : "s were"} already made up this turn, which is the most this chat allows: work with what exists`);
2252
+ const kind = need === "scene_change" ? "location" : need === "arrival" || need === "introduction" ? "character" : void 0;
2253
+ const made = store.story.consolidation.createdIn(owner.turn).filter((entry) => kind === void 0 || entry.kind === kind).length;
2254
+ if (made >= authoring.perTurn) throw new Error(`${made} new ${kind === "location" ? made === 1 ? "place was" : "places were" : kind === "character" ? made === 1 ? "character was" : "characters were" : made === 1 ? "thing was" : "things were"} already made up this turn, which is the most this chat allows: work with what exists, and do not ask again this turn`);
2184
2255
  return await boundaries.author.create({
2185
2256
  chat: owner.chat,
2186
2257
  turn: owner.turn,
@@ -3558,6 +3629,11 @@ function apply(ctx) {
3558
3629
  checks
3559
3630
  }, chat.session);
3560
3631
  };
3632
+ /** What the world carries as standing rules (the card's always-on rules), with a line that says what they are; nothing for a world that has none. */
3633
+ const standingSection = (text, language) => {
3634
+ if (text.trim() === shippedText("roleplay/standing", language).trim()) return "";
3635
+ return `${translator(languageOf(language))("The standing rules of this world. Apply them on every turn:")}\n\n${text}`;
3636
+ };
3561
3637
  for (const [name, order, id] of [[
3562
3638
  PERSONA_SECTION,
3563
3639
  ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),
@@ -3576,7 +3652,8 @@ function apply(ctx) {
3576
3652
  const part = (name) => ctx.roleplayPrompts.text(name, language, {}, chat?.session);
3577
3653
  const variables = id === "roleplay/game-master" ? {
3578
3654
  preview: chat?.settings.preview.enabled === false ? "" : part("roleplay/preview"),
3579
- dice: diceSection(context, chat, language)
3655
+ dice: diceSection(context, chat, language),
3656
+ standing: standingSection(part(STANDING_PROMPT), language)
3580
3657
  } : id === "roleplay/persona" ? { style: part("roleplay/style") } : {};
3581
3658
  return ctx.roleplayPrompts.text(id, language, variables, chat?.session);
3582
3659
  }