@dsh-agentic-roleplay/core 0.7.2 → 0.7.3

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The UI, orchestration, world authoring, media, and filesystem integration plugin behind DSH Agentic Roleplay.
4
4
 
5
- It provides the bounded game-master loop, point-of-view character agents, world and session interfaces, authoring agents and tools that ask before changing files by default, story compaction, speech integration, and image-generation workflows. It turns the structured state supplied by [`@dsh-agentic-roleplay/state`](https://www.npmjs.com/package/@dsh-agentic-roleplay/state) into a playable and editable experience.
5
+ It provides the bounded game-master loop, point-of-view character agents, world and session interfaces, authoring agents and tools that ask before changing files by default, character-card import and assisted card-version updates, story compaction, speech integration, and image-generation workflows. It turns the structured state supplied by [`@dsh-agentic-roleplay/state`](https://www.npmjs.com/package/@dsh-agentic-roleplay/state) into a playable and editable experience.
6
6
 
7
7
  ## Install
8
8
 
@@ -1,10 +1,10 @@
1
1
  import { i as VARIABLE_VISIBILITIES, n as VARIABLE_KINDS, r as VARIABLE_SUBJECTS } from "./access-DtOxFKBK.js";
2
- import { D as INTENT_TYPES, E as INTENT_STATUSES, T as INTENT_HORIZONS, b as PROSE_PROMPTS, d as isPresetName, n as askYesNo, o as yesAt } from "./route-DRTJ_vcA.js";
2
+ import { D as INTENT_TYPES, E as INTENT_STATUSES, T as INTENT_HORIZONS, b as PROSE_PROMPTS, d as isPresetName, n as askYesNo, o as yesAt } from "./route-C6SHz9j2.js";
3
3
  import { f as parseSwitchboard } from "./narration-DvFBqmqe.js";
4
- import { B as loadPlots, G as formatIssue, H as plotReferenceProblems, J as PROMPTS_FOLDER, K as errorMessage, U as readDocument, W as Reader, a as externalWithheld, at as InvalidWorldError, et as promptProblem, r as externalGiven, t as externalToolLimit, tt as shippedLanguages } from "./hooks-HnqXO8mM.js";
5
- import { t as trimCharacters } from "./text-JbWfTHbr.js";
4
+ import { B as loadPlots, G as formatIssue, H as plotReferenceProblems, J as PROMPTS_FOLDER, K as errorMessage, U as readDocument, W as Reader, a as externalWithheld, at as InvalidWorldError, et as promptProblem, r as externalGiven, t as externalToolLimit, tt as shippedLanguages } from "./hooks-C8eELrni.js";
5
+ import { t as trimCharacters } from "./text-Cwl5s0j0.js";
6
6
  import { c as runChild, h as currentTurn, s as namedModel, t as ChildTimeoutError, u as parseSampling } from "./child-CyCViUKa.js";
7
- import { S as uniqueKey, b as slug, c as referenceImagePath, d as MEDIA_TYPES, h as writeImageFileMetadata, n as imageExtensionOf, t as addToLibrary, v as mapLimit, x as trOf, y as norm } from "./library-BGxPKs9a.js";
7
+ import { C as trOf, S as slug, _ as writeImageFileMetadata, b as mapLimit, i as pictureHash, n as imageExtensionOf, p as MEDIA_TYPES, r as libraryHashes, t as addToLibrary, u as referenceImagePath, w as uniqueKey, x as norm } from "./library-lVNf9qG_.js";
8
8
  import { dirname, join } from "node:path";
9
9
  import { existsSync, readFileSync } from "node:fs";
10
10
  import { createHash, randomUUID } from "node:crypto";
@@ -1071,9 +1071,9 @@ function lorebookDirectory(root, name) {
1071
1071
  if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
1072
1072
  return join(lorebooksDirectory(root), name);
1073
1073
  }
1074
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1074
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1075
1075
  function parseHeader(value, problems) {
1076
- if (!isRecord(value)) {
1076
+ if (!isRecord$1(value)) {
1077
1077
  problems.push(`${LOREBOOK_FILE} must be an object`);
1078
1078
  return {};
1079
1079
  }
@@ -1663,10 +1663,11 @@ var ImportStore = class {
1663
1663
  force: true
1664
1664
  });
1665
1665
  }
1666
- /** Moves the folder into the world it became, as `.import/`. */
1667
- async adopt(id, worldDirectory) {
1666
+ /** Moves the folder into the world it became, as `.import/`, or into the given place of the world (a card that updates it waits there). */
1667
+ async adopt(id, worldDirectory, into = IMPORT_FOLDER) {
1668
1668
  const from = this.folder(id);
1669
- const to = join(worldDirectory, IMPORT_FOLDER);
1669
+ const to = join(worldDirectory, into);
1670
+ await mkdir(join(to, ".."), { recursive: true });
1670
1671
  try {
1671
1672
  await rename(from, to);
1672
1673
  } catch (error) {
@@ -5606,9 +5607,10 @@ function fileNameOf(url) {
5606
5607
  */
5607
5608
  async function fetchPictures(world, urls, deps = {}) {
5608
5609
  const fetcher = deps.fetcher ?? requestOnce;
5609
- const { candidates, skipped } = candidateUrls(urls);
5610
+ const { candidates, skipped: refused } = candidateUrls(urls);
5611
+ const skipped = [...refused];
5610
5612
  const added = [];
5611
- const hashes = /* @__PURE__ */ new Set();
5613
+ const hashes = await libraryHashes(world);
5612
5614
  await mapLimit(candidates, deps.concurrency ?? CONCURRENCY, async (address) => {
5613
5615
  const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS * 2), ...deps.signal === void 0 ? [] : [deps.signal]]);
5614
5616
  const url = new URL(address);
@@ -5643,18 +5645,21 @@ async function fetchPictures(world, urls, deps = {}) {
5643
5645
  });
5644
5646
  return;
5645
5647
  }
5646
- const hash = createHash("sha256").update(reply.body).digest("hex");
5647
- if (hashes.has(hash)) {
5648
+ const hash = pictureHash(reply.body);
5649
+ const copyOf = hashes.get(hash);
5650
+ if (copyOf !== void 0) {
5648
5651
  skipped.push({
5649
5652
  url: address,
5650
- reason: "a copy of another picture"
5653
+ reason: "a copy of another picture",
5654
+ of: copyOf
5651
5655
  });
5652
5656
  return;
5653
5657
  }
5654
- hashes.add(hash);
5658
+ const path = await addToLibrary(world, reply.body, fileNameOf(url));
5659
+ hashes.set(hash, path);
5655
5660
  added.push({
5656
5661
  url: address,
5657
- path: await addToLibrary(world, reply.body, fileNameOf(url))
5662
+ path
5658
5663
  });
5659
5664
  } catch (error) {
5660
5665
  skipped.push({
@@ -5669,6 +5674,176 @@ async function fetchPictures(world, urls, deps = {}) {
5669
5674
  skipped
5670
5675
  };
5671
5676
  }
5677
+ /** The key an address is known by: the way `candidateUrls` reads it, without a fragment. */
5678
+ function addressKey(raw) {
5679
+ try {
5680
+ const url = new URL(raw);
5681
+ url.hash = "";
5682
+ return url.href;
5683
+ } catch {
5684
+ return raw;
5685
+ }
5686
+ }
5687
+ const FINAL = [
5688
+ /^not an? /,
5689
+ /^format not supported/,
5690
+ /^gone$/,
5691
+ /^too small$/,
5692
+ /^too large$/,
5693
+ /^a copy of /,
5694
+ /^has credentials/,
5695
+ /^uses an unusual port/,
5696
+ /^is a private address/,
5697
+ /^a redirect /,
5698
+ /is not a public address$/,
5699
+ /^answered (4(?!08|29)\d\d)$/
5700
+ ];
5701
+ /** Whether asking again could give another answer: a picture that is not one, is gone or may not be fetched stays settled; a timeout, a server error or a refusal to wait does not. */
5702
+ const worthAskingAgain = (reason) => !FINAL.some((pattern) => pattern.test(reason));
5703
+ /**
5704
+ * The addresses of a newer card to ask for: those the earlier card did not have, and those it had that were not settled (the record says a request failed). With no record
5705
+ * of that fetch every address of the earlier card counts as settled, so what the person removed from the library is not brought back.
5706
+ */
5707
+ function addressesToFetch(earlier, later, record) {
5708
+ const settled = new Set(earlier.map(addressKey));
5709
+ if (record !== void 0) {
5710
+ const unsettled = new Set(record.skipped.filter((entry) => worthAskingAgain(entry.reason)).map((entry) => addressKey(entry.url)));
5711
+ const fetched = new Set(record.added.map((entry) => addressKey(entry.url)));
5712
+ for (const key of [...settled]) if (unsettled.has(key) && !fetched.has(key)) settled.delete(key);
5713
+ }
5714
+ return later.filter((url) => !settled.has(addressKey(url)));
5715
+ }
5716
+ /** The record after a second fetch: what was added stays, an address asked again takes its new answer. */
5717
+ function mergeReports(earlier, later, found) {
5718
+ const asked = new Set([...later.added.map((entry) => entry.url), ...later.skipped.map((entry) => entry.url)].map(addressKey));
5719
+ return {
5720
+ found,
5721
+ added: [...earlier?.added ?? [], ...later.added],
5722
+ skipped: [...(earlier?.skipped ?? []).filter((entry) => !asked.has(addressKey(entry.url))), ...later.skipped]
5723
+ };
5724
+ }
5725
+ //#endregion
5726
+ //#region src/host/catalogue/errors.ts
5727
+ var CatalogueError = class extends Error {
5728
+ failure;
5729
+ detail;
5730
+ constructor(message, failure, detail) {
5731
+ super(message);
5732
+ this.failure = failure;
5733
+ this.detail = detail;
5734
+ }
5735
+ };
5736
+ //#endregion
5737
+ //#region src/host/catalogue/origin.ts
5738
+ const ORIGIN_FILE = ".catalogue.json";
5739
+ const MAX_LISTED_CHANGES = 12;
5740
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5741
+ /** The origin recorded in a world's folder, or nothing when it has none. @throws {CatalogueError} when the record is damaged. */
5742
+ async function readOrigin(directory) {
5743
+ let text;
5744
+ try {
5745
+ text = await readFile(join(directory, ORIGIN_FILE), "utf8");
5746
+ } catch (error) {
5747
+ if (error.code === "ENOENT") return void 0;
5748
+ throw error;
5749
+ }
5750
+ const damaged = () => new CatalogueError(`${ORIGIN_FILE} in ${directory} is damaged`, "invalid");
5751
+ let value;
5752
+ try {
5753
+ value = JSON.parse(text);
5754
+ } catch {
5755
+ throw damaged();
5756
+ }
5757
+ if (!isRecord(value)) throw damaged();
5758
+ const { kind, root, resourceId, versionId, version, files } = value;
5759
+ if (kind !== "release" && kind !== "card" || typeof root !== "string" || typeof resourceId !== "string" || typeof versionId !== "string" || typeof version !== "string") throw damaged();
5760
+ if (kind === "card") return {
5761
+ kind,
5762
+ root,
5763
+ resourceId,
5764
+ versionId,
5765
+ version
5766
+ };
5767
+ if (!isRecord(files) || !Object.values(files).every((hash) => typeof hash === "string")) throw damaged();
5768
+ return {
5769
+ kind,
5770
+ root,
5771
+ resourceId,
5772
+ versionId,
5773
+ version,
5774
+ files
5775
+ };
5776
+ }
5777
+ async function writeOrigin(directory, origin) {
5778
+ const file = join(directory, ORIGIN_FILE);
5779
+ const temporary = `${file}.${randomUUID()}.tmp`;
5780
+ await writeFile(temporary, JSON.stringify(origin, null, 2));
5781
+ await rename(temporary, file);
5782
+ }
5783
+ /** SHA-256 of every file in a world folder; entries whose names start with a dot (this record, the trash, import state) are not the world's own. */
5784
+ async function hashWorld(directory, skip = () => false) {
5785
+ const hashes = {};
5786
+ const walk = async (relative) => {
5787
+ for (const entry of await readdir(join(directory, relative), { withFileTypes: true })) {
5788
+ if (relative === "" && entry.name.startsWith(".")) continue;
5789
+ const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
5790
+ if (entry.isDirectory()) await walk(path);
5791
+ else if (entry.isFile() && !skip(path)) hashes[path] = createHash("sha256").update(await readFile(join(directory, path))).digest("hex");
5792
+ }
5793
+ };
5794
+ await walk("");
5795
+ return hashes;
5796
+ }
5797
+ function compare(recorded, current) {
5798
+ return {
5799
+ changed: Object.keys(recorded).filter((path) => current[path] !== void 0 && current[path] !== recorded[path]),
5800
+ added: Object.keys(current).filter((path) => recorded[path] === void 0),
5801
+ removed: Object.keys(recorded).filter((path) => current[path] === void 0)
5802
+ };
5803
+ }
5804
+ const isUnchanged = (changes) => changes.changed.length + changes.added.length + changes.removed.length === 0;
5805
+ /** The differences as short lines for a person to read, capped. */
5806
+ function describeChanges(changes) {
5807
+ const lines = [
5808
+ ...changes.changed.map((path) => `changed: ${path}`),
5809
+ ...changes.added.map((path) => `added: ${path}`),
5810
+ ...changes.removed.map((path) => `removed: ${path}`)
5811
+ ];
5812
+ return lines.length <= MAX_LISTED_CHANGES ? lines : [...lines.slice(0, MAX_LISTED_CHANGES), `and ${lines.length - MAX_LISTED_CHANGES} more`];
5813
+ }
5814
+ /** How a world's files compare with the release it came from: the differences, or `unverified` when no record of the release exists. */
5815
+ async function localChanges(directory) {
5816
+ const origin = await readOrigin(directory);
5817
+ if (origin?.kind !== "release") return "unverified";
5818
+ return compare(origin.files, await hashWorld(directory));
5819
+ }
5820
+ //#endregion
5821
+ //#region src/host/import/snapshot.ts
5822
+ const SNAPSHOT = "files.json";
5823
+ /** The pictures of a world are fetched and generated in the background and are not what a card says. */
5824
+ const notTheCards = (path) => path.startsWith("images/");
5825
+ /** What a world's files were when its import was over; "changed since" is measured against it. */
5826
+ async function writeSnapshot(directory) {
5827
+ const file = join(directory, IMPORT_FOLDER, SNAPSHOT);
5828
+ const temporary = `${file}.${randomUUID()}.tmp`;
5829
+ await writeFile(temporary, JSON.stringify(await hashWorld(directory, notTheCards)));
5830
+ await rename(temporary, file);
5831
+ }
5832
+ /** How a world compares with its snapshot: `no` for no change, `yes` with the files, and `unknown` when the import left no snapshot (an older import). */
5833
+ async function editsSince(directory) {
5834
+ let recorded;
5835
+ try {
5836
+ recorded = JSON.parse(await readFile(join(directory, IMPORT_FOLDER, SNAPSHOT), "utf8"));
5837
+ } catch (error) {
5838
+ if (error.code === "ENOENT") return { edited: "unknown" };
5839
+ throw error;
5840
+ }
5841
+ const changes = compare(recorded, await hashWorld(directory, notTheCards));
5842
+ return isUnchanged(changes) ? { edited: "no" } : {
5843
+ edited: "yes",
5844
+ changes: describeChanges(changes)
5845
+ };
5846
+ }
5672
5847
  //#endregion
5673
5848
  //#region src/host/import/run-import.ts
5674
5849
  /** The import in a world is not in the state the step needs, or there is none. The message says what to do. */
@@ -5742,9 +5917,11 @@ async function isReviewing(world) {
5742
5917
  throw error;
5743
5918
  }
5744
5919
  }
5745
- /** The import turn is over: the world is edited like any other from now on. */
5920
+ /** The import turn is over: the world is edited like any other from now on, and what it holds now is what a later edit is measured against. */
5746
5921
  async function endReview(world) {
5747
- if (await isReviewing(world)) await writeJson(join(folder(world), STATE), { phase: "done" });
5922
+ if (!await isReviewing(world)) return;
5923
+ await writeJson(join(folder(world), STATE), { phase: "done" });
5924
+ await writeSnapshot(world);
5748
5925
  }
5749
5926
  /** Marks a folder that was just moved into a world as an import that is ready to run. */
5750
5927
  async function markReady(world) {
@@ -6135,6 +6312,6 @@ function limitAuthoringAgents(ctx, kindOf) {
6135
6312
  });
6136
6313
  }
6137
6314
  //#endregion
6138
- export { variableProblems as $, loadDice as A, loadLore as At, loadFactions as B, parseThingEdit as Bt, populateRoutines as C, loadLorebook as Ct, TRIGGERS_FILE_NAME as D, updateLorebookInfo as Dt, routineProblems as E, reserveLorebook as Et, LOCATIONS_DIR as F, parseCharacterEdit as Ft, findEntity as G, readCard as Gt, loadCharacters as H, ImportCardError as Ht, loadLocations as I, parseFactionEdit as It, partsOf as J, DICE_COMPARISONS as Jt, cleanText as K, LORE_KINDS as Kt, ITEMS_DIR as L, parseLoreEdit as Lt, CALENDAR_FILE_NAME as M, parseLoreFile as Mt, loadCalendar as N, subfolders as Nt, loadTriggers as O, writeLorebookEntry as Ot, parseCalendarFile as P, InvalidEditProblems as Pt, parseVariablesFile as Q, authoringChatSessionId as Qt, loadItems as R, parsePlaceEdit as Rt, populateLore as S, listLorebooks as St, populateVariables as T, readLorebook as Tt, extractStyleFrom as U, isPng as Ut, CHARACTERS_DIR as V, IMPORT_COMMAND as Vt, sourcesFor as W, pictureOf as Wt, VARIABLES_FILE_NAME as X, DICE_RESULTS as Xt, withPlayer as Y, DICE_READINGS as Yt, loadVariables as Z, authoredWorldOf as Zt, populateDice as _, createLorebook as _t, importHooks as a, parseFactionFile as at, populateKnowledge as b, entriesOf as bt, isReviewing as c, IMPORT_FOLDER as ct, vetUrl as d, parseChoices as dt, LOCATION_FILE_NAME as et, loadValidatedWorld as f, readImportFolder as ft, populateClock as g, addLorebookEntries as gt, populateCharacters as h, parseWorldInfoEdit as ht, contextOf as i, FACTION_FILE_NAME as it, parseDiceFile as j, LORE_FILE_NAME as jt, DICE_FILE_NAME as k, LORE_DIR as kt, markReady as l, ImportNotFoundError as lt, populateCalendar as m, parseWorldFile as mt, limitAuthoringAgents as n, ITEM_FILE_NAME as nt, importTools as o, CHARACTER_FILE_NAME as ot, knowsCharacter as p, WORLD_FILE_NAME as pt, itemise as q, LORE_SCOPES as qt, MAX_PREVIEW_TEXT as r, parseItemFile as rt, worldOf as s, parseCharacterFile as st, AuthoringTools as t, parseLocationFile as tt, guardedLookup as u, ImportStore as ut, populateFactions as v, deleteLorebook as vt, populateTriggers as w, lorebookDirectory as wt, populateLocations as x, isLorebookName as xt, populateItems as y, deleteLorebookEntry as yt, FACTIONS_DIR as z, parseRelationEdit as zt };
6315
+ export { parseCalendarFile as $, LORE_FILE_NAME as $t, writePortrait as A, PICTURE_FILE as At, populateLocations as B, deleteLorebook as Bt, fetchPictures as C, FACTION_FILE_NAME as Ct, alternateOpenings as D, IMPORT_FOLDER as Dt, vetUrl as E, parseCharacterFile as Et, populateClock as F, WORLD_FILE_NAME as Ft, routineProblems as G, loadLorebook as Gt, populateRoutines as H, entriesOf as Ht, populateDice as I, parseWorldFile as It, DICE_FILE_NAME as J, reserveLorebook as Jt, TRIGGERS_FILE_NAME as K, lorebookDirectory as Kt, populateFactions as L, parseWorldInfoEdit as Lt, knowsCharacter as M, parseChoices as Mt, populateCalendar as N, readImportFolder as Nt, cardCharacter as O, ImportNotFoundError as Ot, populateCharacters as P, writeChoices as Pt, loadCalendar as Q, loadLore as Qt, populateItems as R, addLorebookEntries as Rt, candidateUrls as S, parseItemFile as St, mergeReports as T, CHARACTER_FILE_NAME as Tt, populateTriggers as U, isLorebookName as Ut, populateLore as V, deleteLorebookEntry as Vt, populateVariables as W, listLorebooks as Wt, parseDiceFile as X, writeLorebookEntry as Xt, loadDice as Y, updateLorebookInfo as Yt, CALENDAR_FILE_NAME as Z, LORE_DIR as Zt, readOrigin as _, DICE_READINGS as _n, parseVariablesFile as _t, importHooks as a, parseLoreEdit as an, loadFactions as at, addressKey as b, authoringChatSessionId as bn, parseLocationFile as bt, importPhase as c, parseThingEdit as cn, extractStyleFrom as ct, editsSince as d, isPng as dn, cleanText as dt, parseLoreFile as en, LOCATIONS_DIR as et, writeSnapshot as f, pictureOf as fn, itemise as ft, localChanges as g, DICE_COMPARISONS as gn, loadVariables as gt, isUnchanged as h, LORE_SCOPES as hn, VARIABLES_FILE_NAME as ht, contextOf as i, parseFactionEdit as in, FACTIONS_DIR as it, loadValidatedWorld as j, openingText as jt, openingMessage as k, ImportStore as kt, isReviewing as l, IMPORT_COMMAND as ln, sourcesFor as lt, hashWorld as m, LORE_KINDS as mn, withPlayer as mt, limitAuthoringAgents as n, InvalidEditProblems as nn, ITEMS_DIR as nt, importTools as o, parsePlaceEdit as on, CHARACTERS_DIR as ot, describeChanges as p, readCard as pn, partsOf as pt, loadTriggers as q, readLorebook as qt, MAX_PREVIEW_TEXT as r, parseCharacterEdit as rn, loadItems as rt, worldOf as s, parseRelationEdit as sn, loadCharacters as st, AuthoringTools as t, subfolders as tn, loadLocations as tt, markReady as u, ImportCardError as un, findEntity as ut, writeOrigin as v, DICE_RESULTS as vn, variableProblems as vt, guardedLookup as w, parseFactionFile as wt, addressesToFetch as x, ITEM_FILE_NAME as xt, CatalogueError as y, authoredWorldOf as yn, LOCATION_FILE_NAME as yt, populateKnowledge as z, createLorebook as zt };
6139
6316
 
6140
- //# sourceMappingURL=authoring-tools-q34iq3hW.js.map
6317
+ //# sourceMappingURL=authoring-tools-CIsWbq0B.js.map