@dsh-agentic-roleplay/core 0.3.4 → 0.3.5

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.
@@ -0,0 +1,38 @@
1
+ //#region src/host/translate/language.ts
2
+ const STORY_LANGUAGES = ["en", "zh"];
3
+ /** Less than this many letters of either script is too little to tell a language. */
4
+ const MIN_LETTERS = 20;
5
+ /** A text is Chinese when this share of its Han and Latin letters is Han: names in the other script do not decide it. */
6
+ const HAN_SHARE = .3;
7
+ const count = (text, pattern) => text.match(pattern)?.length ?? 0;
8
+ /** The language a text is written in, by the script of its letters; nothing when there is too little text to tell. */
9
+ function textLanguage(text) {
10
+ const han = count(text, /\p{Script=Han}/gu);
11
+ const latin = count(text, /\p{Script=Latin}/gu);
12
+ if (han + latin < MIN_LETTERS) return void 0;
13
+ return han / (han + latin) >= HAN_SHARE ? "zh" : "en";
14
+ }
15
+ const isStoryLanguage = (value) => value === "en" || value === "zh";
16
+ const LANGUAGE_NAMES = {
17
+ en: {
18
+ en: "English",
19
+ zh: "英文"
20
+ },
21
+ zh: {
22
+ en: "Chinese",
23
+ zh: "中文"
24
+ }
25
+ };
26
+ /** What is wrong with texts that should be in the chat's language but are written in the other one; nothing when they are right, too short to tell, or the language is not one we can read. */
27
+ function wrongLanguage(wanted, texts) {
28
+ if (!isStoryLanguage(wanted)) return void 0;
29
+ const wrong = Object.entries(texts).flatMap(([name, text]) => {
30
+ const found = text === void 0 ? void 0 : textLanguage(text);
31
+ return found === void 0 || found === wanted ? [] : [`${name} is written in ${LANGUAGE_NAMES[found].en}`];
32
+ });
33
+ return wrong.length === 0 ? void 0 : `${wrong.join(" and ")}: write it in ${LANGUAGE_NAMES[wanted].en} (${LANGUAGE_NAMES[wanted][wanted]})`;
34
+ }
35
+ //#endregion
36
+ export { wrongLanguage as a, textLanguage as i, STORY_LANGUAGES as n, isStoryLanguage as r, LANGUAGE_NAMES as t };
37
+
38
+ //# sourceMappingURL=language-BgyxtB2h.js.map
@@ -329,147 +329,6 @@ async function addToLibrary(sessionFolder, bytes, originalName) {
329
329
  return `${LIBRARY_FOLDER}/${name}`;
330
330
  }
331
331
  //#endregion
332
- //#region src/host/images/generator.ts
333
- const unique = (values) => [...new Set(values.map((value) => value.trim()).filter((value) => value !== ""))];
334
- /** What a reference image shows: the subject and its stable look. */
335
- function referenceDescription(request) {
336
- return `${request.subject.name} (${request.subject.kind}): ${request.identity.description}`.trim();
337
- }
338
- /** What a scene image shows: the established moment, then how each subject looks in it. */
339
- function transientDescription(request) {
340
- return [request.scene.trim(), ...request.subjects.map((subject) => subject.transient.trim() === "" ? void 0 : `${subject.name}: ${subject.transient.trim()}`)].filter((part) => part !== void 0 && part !== "").join("\n");
341
- }
342
- function lines(parts) {
343
- return parts.filter((part) => part !== void 0 && part.trim() !== "").join("\n");
344
- }
345
- function referencePrompt(request) {
346
- const { subject, identity } = request;
347
- return lines([
348
- request.artDirection,
349
- `Create a canonical reference image of the ${subject.kind} ${subject.name}.`,
350
- identity.description,
351
- identity.tags.length === 0 ? void 0 : `Stable visual traits: ${identity.tags.join(", ")}.`,
352
- "Show the subject clearly and neutrally. Do not add story events or temporary changes.",
353
- identity.negativeTags.length === 0 ? void 0 : `Avoid: ${identity.negativeTags.join(", ")}.`
354
- ]);
355
- }
356
- function transientPrompt(request) {
357
- return lines([
358
- request.artDirection,
359
- `Illustrate this established story moment: ${request.scene}`,
360
- ...request.subjects.map((subject) => lines([
361
- `${subject.kind} ${subject.name}: ${subject.identity.description}`,
362
- subject.identity.tags.length === 0 ? void 0 : `Stable visual traits: ${subject.identity.tags.join(", ")}.`,
363
- subject.transient === "" ? void 0 : `Current visible state: ${subject.transient}`
364
- ])),
365
- "Preserve every canonical identity. Depict only the stated subjects, state and action; do not invent story facts.",
366
- request.subjects.flatMap((subject) => subject.identity.negativeTags).length === 0 ? void 0 : `Avoid: ${[...new Set(request.subjects.flatMap((subject) => subject.identity.negativeTags))].join(", ")}.`
367
- ]);
368
- }
369
- async function firstPng(service, prompt, options = {}) {
370
- const result = await service.generate(prompt, {
371
- count: 1,
372
- ...options
373
- });
374
- const image = result.images[0];
375
- if (image === void 0) throw new Error(`${service.provider} returned no image`);
376
- if (image.mediaType !== "image/png") throw new Error(`${service.provider} returned ${image.mediaType}; roleplay image storage currently requires PNG`);
377
- return {
378
- data: new Uint8Array(await image.data.arrayBuffer()),
379
- model: result.model,
380
- ...image.revisedPrompt === void 0 ? {} : { revisedPrompt: image.revisedPrompt }
381
- };
382
- }
383
- /** Generates the stable reference.png of one entity. It is intentionally not registered in the live roleplay loop yet. */
384
- async function generateReferenceImage(service, request) {
385
- const prompt = referencePrompt(request);
386
- const image = await firstPng(service, prompt, request.signal === void 0 ? {} : { signal: request.signal });
387
- request.signal?.throwIfAborted();
388
- const path = referenceImagePath(request.root, request.subject);
389
- const metadata = {
390
- schema: "dsh-roleplay-image/v3",
391
- purpose: "reference",
392
- origin: "generated",
393
- reusable: true,
394
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
395
- prompt,
396
- description: referenceDescription(request),
397
- tags: unique([request.subject.name, ...request.identity.tags]),
398
- ...image.revisedPrompt === void 0 ? {} : { revisedPrompt: image.revisedPrompt },
399
- provider: service.provider,
400
- model: image.model,
401
- subjects: [{
402
- ...request.subject,
403
- identityVersion: request.identity.version
404
- }]
405
- };
406
- await writeImage(path, image.data, metadata, { replace: true });
407
- return path;
408
- }
409
- const PNG_SIGNATURE = [
410
- 137,
411
- 80,
412
- 78,
413
- 71,
414
- 13,
415
- 10,
416
- 26,
417
- 10
418
- ];
419
- /** Takes a picture the person brought as the stable reference.png of one entity, replacing the one there. Only PNG is stored, so any other format is refused. */
420
- async function uploadReferenceImage(request) {
421
- if (request.png.length < PNG_SIGNATURE.length || PNG_SIGNATURE.some((byte, index) => request.png[index] !== byte)) throw new Error("the portrait must be a PNG picture: convert it first");
422
- const path = referenceImagePath(request.root, request.subject);
423
- const metadata = {
424
- schema: "dsh-roleplay-image/v3",
425
- purpose: "reference",
426
- origin: "uploaded",
427
- reusable: true,
428
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
429
- description: `${request.subject.name}, a picture brought by the author.`,
430
- tags: [request.subject.name],
431
- ...request.originalName === void 0 ? {} : { originalName: request.originalName },
432
- subjects: [request.subject]
433
- };
434
- await writeImage(path, request.png, metadata, { replace: true });
435
- return path;
436
- }
437
- /** Generates one immutable scene image for a timeline node. It is intentionally not registered in the live roleplay loop yet. */
438
- async function generateTransientImage(service, request) {
439
- if (request.subjects.length === 0) throw new Error("a transient image needs at least one subject");
440
- const prompt = transientPrompt(request);
441
- const image = await firstPng(service, prompt, {
442
- ...request.references === void 0 ? {} : { references: request.references },
443
- ...request.signal === void 0 ? {} : { signal: request.signal }
444
- });
445
- request.signal?.throwIfAborted();
446
- const path = sceneImagePath(request.root, request.timelineNode, request.serial);
447
- const metadata = {
448
- schema: "dsh-roleplay-image/v3",
449
- purpose: "transient",
450
- origin: "generated",
451
- reusable: request.reusable === true,
452
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
453
- prompt,
454
- description: transientDescription(request),
455
- tags: unique(request.subjects.flatMap((subject) => [subject.name, ...subject.identity.tags])),
456
- ...image.revisedPrompt === void 0 ? {} : { revisedPrompt: image.revisedPrompt },
457
- provider: service.provider,
458
- model: image.model,
459
- subjects: request.subjects.map(({ identity, transient: _transient, ...subject }) => ({
460
- ...subject,
461
- identityVersion: identity.version
462
- })),
463
- source: {
464
- turn: request.turn,
465
- timelineNode: request.timelineNode,
466
- ...request.segment === void 0 ? {} : { segment: request.segment }
467
- }
468
- };
469
- await writeImage(path, image.data, metadata);
470
- return path;
471
- }
472
- //#endregion
473
- export { norm as C, mapLimit as S, uniqueKey as T, readImageFileMetadata as _, uploadReferenceImage as a, readPngMetadata as b, LIBRARY_FOLDER as c, nextSceneSerial as d, readImageMetadata as f, mediaTypeOf as g, MEDIA_TYPES as h, transientPrompt as i, entityImageDirectory as l, sceneImagePath as m, generateTransientImage as n, addToLibrary as o, referenceImagePath as p, referencePrompt as r, imageExtensionOf as s, generateReferenceImage as t, inheritImages as u, sidecarOf as v, slug as w, withPngMetadata as x, writeImageFileMetadata as y };
332
+ 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 };
474
333
 
475
- //# sourceMappingURL=generator-B6FxlKOV.js.map
334
+ //# sourceMappingURL=library-9JB9zw5a.js.map
@@ -46,7 +46,8 @@ var ReflectionRefusedError = class extends Error {};
46
46
  const PROMPTS_FOLDER = "prompts";
47
47
  const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
48
48
  const ID = /^[a-z0-9-]+(\/[a-z0-9-]+)*$/;
49
- const LANGUAGE = /^[a-z]{2,8}$/;
49
+ const LANGUAGE_FOLDER = /^[a-z]{2,8}$/;
50
+ const LANGUAGE = LANGUAGE_FOLDER;
50
51
  const VARIABLE = /\$\{([A-Za-z]+)\}/g;
51
52
  /** The folder of the prompts that ship with the package, found from this module so that it works from source and from the build. */
52
53
  function shippedPromptsDirectory(from = dirname(fileURLToPath(import.meta.url))) {
@@ -63,13 +64,13 @@ function languageOf(tag) {
63
64
  return primary;
64
65
  }
65
66
  /** How a language is named inside a prompt, for the instruction to write in it. */
66
- const LANGUAGE_NAMES$1 = {
67
+ const LANGUAGE_NAMES = {
67
68
  en: "English",
68
69
  zh: "中文"
69
70
  };
70
71
  function fill(id, text, given, tag) {
71
72
  const variables = {
72
- language: LANGUAGE_NAMES$1[tag] ?? tag,
73
+ language: LANGUAGE_NAMES[tag] ?? tag,
73
74
  ...given
74
75
  };
75
76
  return text.trim().replace(/^\$\{([A-Za-z]+)\}[ \t]*(\r?\n|$)/gm, (match, name) => variables[name] === "" ? "" : match).replace(VARIABLE, (_match, name) => {
@@ -480,41 +481,6 @@ function plotReferenceProblems(plots, entities) {
480
481
  return plots.flatMap((plot) => plot.participants.filter((participant) => !known.has(participant)).map((participant) => `plot "${plot.id}" names unknown participant "${participant}"`));
481
482
  }
482
483
  //#endregion
483
- //#region src/host/translate/language.ts
484
- const STORY_LANGUAGES = ["en", "zh"];
485
- /** Less than this many letters of either script is too little to tell a language. */
486
- const MIN_LETTERS = 20;
487
- /** A text is Chinese when this share of its Han and Latin letters is Han: names in the other script do not decide it. */
488
- const HAN_SHARE = .3;
489
- const count = (text, pattern) => text.match(pattern)?.length ?? 0;
490
- /** The language a text is written in, by the script of its letters; nothing when there is too little text to tell. */
491
- function textLanguage(text) {
492
- const han = count(text, /\p{Script=Han}/gu);
493
- const latin = count(text, /\p{Script=Latin}/gu);
494
- if (han + latin < MIN_LETTERS) return void 0;
495
- return han / (han + latin) >= HAN_SHARE ? "zh" : "en";
496
- }
497
- const isStoryLanguage = (value) => value === "en" || value === "zh";
498
- const LANGUAGE_NAMES = {
499
- en: {
500
- en: "English",
501
- zh: "英文"
502
- },
503
- zh: {
504
- en: "Chinese",
505
- zh: "中文"
506
- }
507
- };
508
- /** What is wrong with texts that should be in the chat's language but are written in the other one; nothing when they are right, too short to tell, or the language is not one we can read. */
509
- function wrongLanguage(wanted, texts) {
510
- if (!isStoryLanguage(wanted)) return void 0;
511
- const wrong = Object.entries(texts).flatMap(([name, text]) => {
512
- const found = text === void 0 ? void 0 : textLanguage(text);
513
- return found === void 0 || found === wanted ? [] : [`${name} is written in ${LANGUAGE_NAMES[found].en}`];
514
- });
515
- return wrong.length === 0 ? void 0 : `${wrong.join(" and ")}: write it in ${LANGUAGE_NAMES[wanted].en} (${LANGUAGE_NAMES[wanted][wanted]})`;
516
- }
517
- //#endregion
518
- export { WorldNotFoundError as A, shippedText as C, ReflectionRefusedError as D, InvalidWorldError as E, SessionArchivedError as O, shippedPromptsDirectory as S, InvalidStartError as T, inheritPrompts as _, wrongLanguage as a, promptProblem as b, parsePlotsFile as c, errorMessage as d, Reader as f, copyWorldPrompts as g, PromptLibrary as h, textLanguage as i, SessionNotFoundError as k, plotReferenceProblems as l, PROMPTS_FOLDER as m, STORY_LANGUAGES as n, PLOTS_FILE_NAME as o, formatIssue as p, isStoryLanguage as r, loadPlots as s, LANGUAGE_NAMES as t, readDocument as u, languageOf as v, AgentUnavailableError as w, shippedLanguages as x, listFiles as y };
484
+ export { ReflectionRefusedError as C, WorldNotFoundError as E, InvalidWorldError as S, SessionNotFoundError as T, shippedLanguages as _, readDocument as a, AgentUnavailableError as b, formatIssue as c, PromptLibrary as d, copyWorldPrompts as f, promptProblem as g, listFiles as h, plotReferenceProblems as i, LANGUAGE_FOLDER as l, languageOf as m, loadPlots as n, errorMessage as o, inheritPrompts as p, parsePlotsFile as r, Reader as s, PLOTS_FILE_NAME as t, PROMPTS_FOLDER as u, shippedPromptsDirectory as v, SessionArchivedError as w, InvalidStartError as x, shippedText as y };
519
485
 
520
- //# sourceMappingURL=language-DWVwi1R7.js.map
486
+ //# sourceMappingURL=load-Clkl0T7C.js.map
@@ -1,15 +1,17 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { _ as API_PREFIX, y as INTENT_STATUSES } from "./packs-BYjrAen6.js";
3
- import { a as whereabouts, d as sameWords, f as referent, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-waxFg1x-.js";
2
+ import { y as INTENT_STATUSES } from "./presets-DNjNxQL5.js";
3
+ import { a as whereabouts, g as referent, h as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-Bju_LPFn.js";
4
4
  import "./settings-CA6icLL_.js";
5
- import { D as ReflectionRefusedError, a as wrongLanguage } from "./language-DWVwi1R7.js";
6
- import { B as RESULTS, F as describeWhen, H as languageOf, M as ClockError, S as MAX_OOC_ANSWER, U as translator, m as createTools$1, p as PREVIEW_TOOL, u as externalGiven, w as toolEnabled, x as AUTHORING_NEEDS, z as zoneOf } from "./deliver-CpZOxBX5.js";
5
+ import { C as ReflectionRefusedError } from "./load-Clkl0T7C.js";
6
+ import { B as RESULTS, F as describeWhen, H as languageOf, M as ClockError, S as MAX_OOC_ANSWER, U as translator, m as createTools$1, p as PREVIEW_TOOL, u as externalGiven, w as toolEnabled, x as AUTHORING_NEEDS, z as zoneOf } from "./deliver-Cl6bjp7g.js";
7
7
  import { a as liveSettings } from "./narration-DK2kiIjE.js";
8
8
  import { a as runChild, d as tokensOf, i as childTrace, l as currentTurn, n as childSampling, t as childModel, u as estimateAnswer } from "./child-CFjnaTZt.js";
9
- import { T as uniqueKey, o as addToLibrary, w as slug } from "./generator-B6FxlKOV.js";
10
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CtFDL22W.js";
11
- import { a as writeVerdicts, i as readVerdicts, n as installHooks, r as storesOf } from "./hooks-KTCR3fNJ.js";
12
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-CiEVKcjJ.js";
9
+ import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-9JB9zw5a.js";
10
+ import { a as wrongLanguage } from "./language-BgyxtB2h.js";
11
+ import { _ as API_PREFIX } from "./packs-BC2A3geF.js";
12
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DIEgETzU.js";
13
+ import { a as writeVerdicts, i as readVerdicts, n as installHooks, r as storesOf } from "./hooks-DdO_tNhu.js";
14
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-DnNEG_Mn.js";
13
15
  import { join } from "node:path";
14
16
  import { existsSync } from "node:fs";
15
17
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -2393,12 +2395,7 @@ var TurnEngine = class {
2393
2395
  async reflect(chat) {
2394
2396
  const store = this.stores(chat);
2395
2397
  if (store === void 0) throw new Error(`no story for chat ${chat}`);
2396
- const turning = this.states.get(chat);
2397
- if (turning !== void 0 && [
2398
- "resolving",
2399
- "retrying",
2400
- "between"
2401
- ].includes(turning.phase)) throw new ReflectionRefusedError("a turn is being played; reflect when it is over");
2398
+ if (this.playing(chat)) throw new ReflectionRefusedError("a turn is being played; reflect when it is over");
2402
2399
  const delivered = this.delivered.get(chat);
2403
2400
  if (delivered !== void 0 && store.pendingCommits().length > 0) this.write({
2404
2401
  chat,
@@ -2412,6 +2409,15 @@ var TurnEngine = class {
2412
2409
  turn: store.story.metadata.get().turns
2413
2410
  }, cancel.signal);
2414
2411
  }
2412
+ /** Whether a turn is being played: characters are being asked or the game master is between rounds. */
2413
+ playing(chat) {
2414
+ const turning = this.states.get(chat);
2415
+ return turning !== void 0 && [
2416
+ "resolving",
2417
+ "retrying",
2418
+ "between"
2419
+ ].includes(turning.phase);
2420
+ }
2415
2421
  /** Whether a reflection is running for the chat. */
2416
2422
  reflecting(chat) {
2417
2423
  return this.afterTurn.isReflecting(chat);
@@ -2974,9 +2980,11 @@ function apply(ctx) {
2974
2980
  ctx.effect(() => {
2975
2981
  ctx.roleplayOrchestration.reflect = (chat) => engine.reflect(chat);
2976
2982
  ctx.roleplayOrchestration.reflecting = (chat) => engine.reflecting(chat);
2983
+ ctx.roleplayOrchestration.playing = (chat) => engine.playing(chat);
2977
2984
  return () => {
2978
2985
  ctx.roleplayOrchestration.reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
2979
2986
  ctx.roleplayOrchestration.reflecting = () => false;
2987
+ ctx.roleplayOrchestration.playing = () => false;
2980
2988
  };
2981
2989
  }, "roleplay: reflection control");
2982
2990
  ctx.effect(() => {