@dsh-agentic-roleplay/core 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/compaction.js CHANGED
@@ -1,6 +1,5 @@
1
- import { n as roleplaySessionOf } from "./chat-AKrVcWIC.js";
2
- import { a as liveSettings, t as decodeOutput } from "./narration-BRyHU0H2.js";
3
- import { t as promptFor } from "./access-C1nFQiyT.js";
1
+ import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { a as liveSettings, t as decodeOutput } from "./narration-CKZTk5UE.js";
4
3
  import { join } from "node:path";
5
4
  import { sessionFolder } from "@dsh-agentic-roleplay/state";
6
5
  import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
@@ -1,10 +1,18 @@
1
- import { n as roleplaySessionOf } from "./chat-AKrVcWIC.js";
2
- import { B as SessionNotFoundError, i as inheritPacks, k as inheritPrompts } from "./packs-ByP1J-zj.js";
3
- import { j as estimateAnswer, u as inheritImages } from "./generator-HPifO3Kk.js";
1
+ import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { V as SessionNotFoundError, i as inheritPacks, k as inheritPrompts } from "./packs-alJTiDM2.js";
3
+ import "./src-CWTNeL6Y.js";
4
+ import { A as runChild, D as childSampling, E as childModel, j as estimateAnswer, k as childTrace, u as inheritImages } from "./generator-HPifO3Kk.js";
4
5
  import { join } from "node:path";
5
6
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
7
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
7
- import { DAY, MINUTE, SECOND, clockTime, dayPart, describeDuration, describeInstant, isSessionId, localTime, locationKey, mentioned, nextTimeOfDay, overlap, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
8
+ import { DAY, MINUTE, SECOND, characterKey, clockTime, dayPart, describeDuration, describeInstant, isSessionId, localTime, locationKey, mentioned, nextTimeOfDay, overlap, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
9
+ //#region ../dsh-roleplay-model/src/memory.ts
10
+ const MEMORY_KINDS = [
11
+ "belief",
12
+ "relationship",
13
+ "knowledge"
14
+ ];
15
+ //#endregion
8
16
  //#region src/host/orchestration/protocol.ts
9
17
  const COMMITMENTS = [
10
18
  "low",
@@ -761,6 +769,8 @@ const declinesToAuthor = {
761
769
  };
762
770
  /** Lets no organisation act: without a strategist factions change only through what the story records. */
763
771
  const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
772
+ /** Reflects on nothing: without a reflector what characters believe changes only through what the story records. */
773
+ const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
764
774
  /** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
765
775
  const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
766
776
  /** Offers nothing: without a suggester the player writes their own move. */
@@ -777,6 +787,7 @@ function defaultBoundaries() {
777
787
  committer: writesNothing,
778
788
  author: declinesToAuthor,
779
789
  strategist: factionsStayPut,
790
+ reflector: reflectsOnNothing,
780
791
  judge: judgesNothing,
781
792
  suggester: offersNothing,
782
793
  recaller: recordsRecall,
@@ -1194,6 +1205,35 @@ var Timelines = class {
1194
1205
  }
1195
1206
  };
1196
1207
  //#endregion
1208
+ //#region src/host/orchestration/observation.ts
1209
+ /** What a character takes in where it stands and of what it carries: the place, the ways out and what they lead to, what lies in the open, what it holds. */
1210
+ function observeSurroundings(session, characterId, turn) {
1211
+ const placement = session.placements.get("character", characterId);
1212
+ if (placement !== void 0) {
1213
+ session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1214
+ for (const exit of session.locations.exitsFrom(placement.locationId)) {
1215
+ session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1216
+ session.knowledge.learn(characterId, "location", exit.toId, turn);
1217
+ }
1218
+ for (const { item } of session.items.contents({
1219
+ kind: "location",
1220
+ id: placement.locationId
1221
+ })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1222
+ }
1223
+ for (const { item } of session.items.contents({
1224
+ kind: "character",
1225
+ id: characterId
1226
+ })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1227
+ }
1228
+ /**
1229
+ * The player's character is never asked to act, so nothing else shows it its surroundings: it takes them in when a turn begins, which is
1230
+ * how it comes to know the way back from where it went.
1231
+ */
1232
+ function observeAsPlayer(session, turn) {
1233
+ const player = session.characters.list().find((character) => character.control === "player");
1234
+ if (player !== void 0) observeSurroundings(session, player.id, turn);
1235
+ }
1236
+ //#endregion
1197
1237
  //#region src/shared/notes.ts
1198
1238
  const NOTE_KINDS = [
1199
1239
  "suggestions",
@@ -1202,7 +1242,7 @@ const NOTE_KINDS = [
1202
1242
  ];
1203
1243
  //#endregion
1204
1244
  //#region src/host/sessions/notes.ts
1205
- const KEY$1 = "notes";
1245
+ const KEY$2 = "notes";
1206
1246
  const isNote = (value) => {
1207
1247
  if (typeof value !== "object" || value === null) return false;
1208
1248
  const note = value;
@@ -1210,12 +1250,12 @@ const isNote = (value) => {
1210
1250
  };
1211
1251
  /** The notes of a session, at most one per kind. */
1212
1252
  function readNotes(session) {
1213
- const stored = session.metadata.getValue(KEY$1);
1253
+ const stored = session.metadata.getValue(KEY$2);
1214
1254
  return Array.isArray(stored) ? stored.filter(isNote) : [];
1215
1255
  }
1216
1256
  /** Replaces the note of the same kind. */
1217
1257
  function putNote(session, note) {
1218
- session.metadata.setValue(KEY$1, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1258
+ session.metadata.setValue(KEY$2, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1219
1259
  }
1220
1260
  /** The most lines one note keeps: what is past it is not told. */
1221
1261
  const MAX_NOTE_LINES = 8;
@@ -1230,7 +1270,7 @@ function addToNote(session, kind, turn, lines) {
1230
1270
  }
1231
1271
  /** Removes every note: they belong to the turn that made them. */
1232
1272
  function clearNotes(session) {
1233
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$1, []);
1273
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$2, []);
1234
1274
  }
1235
1275
  /**
1236
1276
  * The notes of a session, for the player's screen.
@@ -1337,8 +1377,426 @@ function updatePlotProgress(store, plotId, developmentId, action) {
1337
1377
  return progress;
1338
1378
  }
1339
1379
  //#endregion
1380
+ //#region src/host/orchestration/whereabouts.ts
1381
+ const within = (inner, outer, places) => {
1382
+ const byId = new Map(places.map((place) => [place.id, place]));
1383
+ const seen = /* @__PURE__ */ new Set();
1384
+ for (let at = inner; at !== void 0 && !seen.has(at.id); at = at.parentId === void 0 ? void 0 : byId.get(at.parentId)) {
1385
+ if (at.id === outer.id) return true;
1386
+ seen.add(at.id);
1387
+ }
1388
+ return false;
1389
+ };
1390
+ /** Whether two places are one scene: the same place, or one inside the other (a room and its building). */
1391
+ const sameScene = (a, b, places) => within(a, b, places) || within(b, a, places);
1392
+ /**
1393
+ * Compares the place an action is said to happen at (by key) with where the character is. Only a proven mismatch counts: a character that is
1394
+ * nowhere, or a world without places, is no evidence, and a place that contains the other (a room and its building) is the same for this.
1395
+ */
1396
+ function whereabouts(places, here, at) {
1397
+ const target = places.find((place) => locationKey(place) === at);
1398
+ if (target === void 0) return { kind: "unknown" };
1399
+ if (here === void 0) return { kind: "unplaced" };
1400
+ return within(here, target, places) || within(target, here, places) ? { kind: "here" } : {
1401
+ kind: "elsewhere",
1402
+ target,
1403
+ here
1404
+ };
1405
+ }
1406
+ //#endregion
1407
+ //#region src/host/memory/reflection.ts
1408
+ const LAST_KEY = "reflection.last";
1409
+ const CURSOR_KEY = "reflection.cursor";
1410
+ const ANCHOR_KEY = "reflection.anchor";
1411
+ const ERROR_KEY = "reflection.error";
1412
+ const DAY_MS = 864e5;
1413
+ const MAX_MATERIAL = 40;
1414
+ const MAX_BELIEFS_SHOWN = 40;
1415
+ const MAX_ADDED = 4;
1416
+ const MAX_CHANGES = 10;
1417
+ const MAX_TEXT = 300;
1418
+ /** An event this important is reason enough for a belief on its own. */
1419
+ const DECISIVE_IMPORTANCE = 4;
1420
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1421
+ function readLast(session) {
1422
+ const stored = session.metadata.getValue(LAST_KEY);
1423
+ return isRecord(stored) && typeof stored["turn"] === "number" ? stored : void 0;
1424
+ }
1425
+ function readCursor(session) {
1426
+ const stored = session.metadata.getValue(CURSOR_KEY);
1427
+ return isRecord(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
1428
+ }
1429
+ function readAnchor(session) {
1430
+ const stored = session.metadata.getValue(ANCHOR_KEY);
1431
+ return isRecord(stored) && typeof stored["now"] === "number" ? {
1432
+ now: stored["now"],
1433
+ ...typeof stored["place"] === "number" ? { place: stored["place"] } : {}
1434
+ } : void 0;
1435
+ }
1436
+ function writeAnchor(session, place, now) {
1437
+ session.metadata.setValue(ANCHOR_KEY, {
1438
+ now,
1439
+ ...place === void 0 ? {} : { place: place.id }
1440
+ });
1441
+ }
1442
+ const playerPlace = (store) => store.cast().find((member) => member.character.control === "player")?.place?.location;
1443
+ /** What is known of the story's reflection: whether a pass runs, the latest that finished, and why the latest failed. */
1444
+ function reflectionStatus(session, running) {
1445
+ const last = readLast(session);
1446
+ const failure = session.metadata.getValue(ERROR_KEY);
1447
+ return {
1448
+ running,
1449
+ ...last === void 0 ? {} : { last },
1450
+ ...isRecord(failure) && typeof failure["message"] === "string" && typeof failure["at"] === "string" ? { error: {
1451
+ at: failure["at"],
1452
+ message: failure["message"]
1453
+ } } : {}
1454
+ };
1455
+ }
1456
+ function recordFailure(session, message) {
1457
+ session.metadata.setValue(ERROR_KEY, {
1458
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1459
+ message: message.slice(0, 500)
1460
+ });
1461
+ }
1462
+ /**
1463
+ * Whether the story should reflect after this turn, and why. A pass waits until `minTurns` turns have passed since the last one; then it
1464
+ * comes after `everyTurns` turns, or when the scene has changed since the last pass (the player's character is somewhere that is neither
1465
+ * where it was nor inside or around it, or `sceneDays` of story time have passed). The first look only notes where the story stands.
1466
+ */
1467
+ function dueReflection(store, turn) {
1468
+ const { reflection } = store.settings();
1469
+ if (!reflection.auto) return void 0;
1470
+ const session = store.story;
1471
+ const { now } = store.time(turn);
1472
+ const here = playerPlace(store);
1473
+ const anchor = readAnchor(session);
1474
+ if (anchor === void 0) {
1475
+ writeAnchor(session, here, now);
1476
+ return;
1477
+ }
1478
+ const since = turn - (readLast(session)?.turn ?? 0);
1479
+ if (since < reflection.minTurns) return void 0;
1480
+ if (reflection.everyTurns > 0 && since >= reflection.everyTurns) return "turns";
1481
+ if (!reflection.onSceneChange) return void 0;
1482
+ const places = session.locations.list();
1483
+ const before = places.find((place) => place.id === anchor.place);
1484
+ if (here !== void 0 && before !== void 0 && !sameScene(here, before, places)) return "scene";
1485
+ if (reflection.sceneDays > 0 && now - anchor.now >= reflection.sceneDays * DAY_MS) return "scene";
1486
+ }
1487
+ /**
1488
+ * The characters that have enough new to sort, the most first. Only what the story has made final counts, and only up to the first thing
1489
+ * still a draft, so that nothing is passed over that is sealed later.
1490
+ */
1491
+ function materialOf(session, minNew) {
1492
+ const cursor = readCursor(session);
1493
+ const found = [];
1494
+ for (const character of session.characters.list()) {
1495
+ if (character.control !== "agent" || character.kind !== "person" || character.tier === "background") continue;
1496
+ const taken = session.events.perceivedBy(character.id);
1497
+ const draft = taken.filter((entry) => !entry.event.sealed).map((entry) => entry.perception.id);
1498
+ const ceiling = draft.length === 0 ? Infinity : Math.min(...draft) - 1;
1499
+ const fresh = taken.filter((entry) => entry.event.sealed && entry.perception.id > (cursor[characterKey(character)] ?? 0) && entry.perception.id <= ceiling).sort((a, b) => a.perception.id - b.perception.id).slice(0, MAX_MATERIAL);
1500
+ if (fresh.length < minNew) continue;
1501
+ const beliefs = session.memories.list(character.id).sort((a, b) => b.importance - a.importance || a.id - b.id).slice(0, MAX_BELIEFS_SHOWN);
1502
+ found.push({
1503
+ character,
1504
+ fresh,
1505
+ beliefs
1506
+ });
1507
+ }
1508
+ return found.sort((a, b) => b.fresh.length - a.fresh.length);
1509
+ }
1510
+ const idList = {
1511
+ type: "array",
1512
+ items: { type: "integer" }
1513
+ };
1514
+ const RESULT = {
1515
+ type: "object",
1516
+ properties: {
1517
+ add: {
1518
+ type: "array",
1519
+ description: "New beliefs, at most four. Leave empty when nothing new can be firmly said.",
1520
+ items: {
1521
+ type: "object",
1522
+ properties: {
1523
+ kind: {
1524
+ type: "string",
1525
+ enum: [...MEMORY_KINDS],
1526
+ description: "belief: what it holds true or suspects; relationship: how it stands with someone; knowledge: something it knows."
1527
+ },
1528
+ text: {
1529
+ type: "string",
1530
+ description: "What the character believes, in one or two sentences, in its own terms. Say plainly when it is a suspicion, a rumour or a guess."
1531
+ },
1532
+ about: {
1533
+ type: "array",
1534
+ items: { type: "string" },
1535
+ description: "The names of the characters it is about."
1536
+ },
1537
+ importance: {
1538
+ type: "integer",
1539
+ description: `From 1 (passing) to 5 (it shapes how they act).`
1540
+ },
1541
+ perceptions: {
1542
+ ...idList,
1543
+ description: "The numbers of the things it took in that this rests on."
1544
+ },
1545
+ beliefs: {
1546
+ ...idList,
1547
+ description: "The numbers of the beliefs it generalises or builds on, if any."
1548
+ }
1549
+ },
1550
+ required: [
1551
+ "kind",
1552
+ "text",
1553
+ "importance",
1554
+ "perceptions"
1555
+ ],
1556
+ additionalProperties: false
1557
+ }
1558
+ },
1559
+ revise: {
1560
+ type: "array",
1561
+ description: "Beliefs to firm up, doubt or correct in the light of what came after them.",
1562
+ items: {
1563
+ type: "object",
1564
+ properties: {
1565
+ id: {
1566
+ type: "integer",
1567
+ description: "The number of the belief, as listed."
1568
+ },
1569
+ text: {
1570
+ type: "string",
1571
+ description: "The belief as it should read now."
1572
+ },
1573
+ importance: {
1574
+ type: "integer",
1575
+ description: `From 1 to 5.`
1576
+ },
1577
+ perceptions: {
1578
+ ...idList,
1579
+ description: "The numbers of the things it took in since that bear on it."
1580
+ }
1581
+ },
1582
+ required: ["id", "perceptions"],
1583
+ additionalProperties: false
1584
+ }
1585
+ },
1586
+ drop: {
1587
+ type: "array",
1588
+ description: "Beliefs to let go: settled or overturned by what came after, or merged into another.",
1589
+ items: {
1590
+ type: "object",
1591
+ properties: {
1592
+ id: { type: "integer" },
1593
+ perceptions: {
1594
+ ...idList,
1595
+ description: "What it took in since that settles or overturns it."
1596
+ },
1597
+ merged_into: {
1598
+ type: "integer",
1599
+ description: "The number of the belief that now says the same, instead of a reason from what it took in."
1600
+ }
1601
+ },
1602
+ required: ["id"],
1603
+ additionalProperties: false
1604
+ }
1605
+ }
1606
+ },
1607
+ required: [
1608
+ "add",
1609
+ "revise",
1610
+ "drop"
1611
+ ],
1612
+ additionalProperties: false
1613
+ };
1614
+ const shownOf = (material) => ({
1615
+ perceptions: new Map(material.fresh.map((entry) => [entry.perception.id, entry])),
1616
+ beliefs: new Map(material.beliefs.map((belief) => [belief.id, belief]))
1617
+ });
1618
+ /**
1619
+ * Why a proposal cannot be written, or nothing when it can. A belief must rest on what the character took in: on things from at least two
1620
+ * different turns, or on one event that turned the story; a belief is changed or let go only for what came after it, or for being merged
1621
+ * into another. Nothing is judged about whether the belief is wise; only whether it is grounded in what the character was given.
1622
+ */
1623
+ function proposalProblems(proposal, shown, resolveName) {
1624
+ const problems = [];
1625
+ const add = proposal.add ?? [];
1626
+ const revise = proposal.revise ?? [];
1627
+ const drop = proposal.drop ?? [];
1628
+ if (add.length > MAX_ADDED) problems.push(`add: at most ${MAX_ADDED} new beliefs in one pass; merge or choose`);
1629
+ if (add.length + revise.length + drop.length > MAX_CHANGES) problems.push(`at most ${MAX_CHANGES} changes in one pass`);
1630
+ const cited = (ids, where) => (ids ?? []).flatMap((id) => {
1631
+ const entry = shown.perceptions.get(id);
1632
+ if (entry === void 0) problems.push(`${where}: there is no thing it took in numbered ${id}`);
1633
+ return entry === void 0 ? [] : [entry];
1634
+ });
1635
+ add.forEach((belief, index) => {
1636
+ const where = `add[${index}]`;
1637
+ if (!MEMORY_KINDS.includes(belief.kind)) problems.push(`${where}: unknown kind "${belief.kind}"`);
1638
+ if (belief.text.trim() === "") problems.push(`${where}: say what it believes`);
1639
+ else if (belief.text.trim().length > MAX_TEXT) problems.push(`${where}: at most ${MAX_TEXT} characters; say it shorter`);
1640
+ if (!Number.isInteger(belief.importance) || belief.importance < 1 || belief.importance > 5) problems.push(`${where}: importance runs from 1 to 5`);
1641
+ const events = cited(belief.perceptions, where);
1642
+ const built = (belief.beliefs ?? []).flatMap((id) => {
1643
+ const known = shown.beliefs.get(id);
1644
+ if (known === void 0) problems.push(`${where}: there is no belief numbered ${id}`);
1645
+ return known === void 0 ? [] : [known];
1646
+ });
1647
+ if ((/* @__PURE__ */ new Set([...events.map((entry) => entry.event.turn), ...built.map((known) => known.turn)])).size < 2 && !events.some((entry) => entry.event.importance >= DECISIVE_IMPORTANCE)) problems.push(`${where}: one passing moment is not yet a belief; rest it on things from at least two different turns, or on one event that turned the story`);
1648
+ for (const name of belief.about ?? []) if (resolveName(name) === void 0) problems.push(`${where}: "${name}" is not a character; name them as they are named`);
1649
+ });
1650
+ const touched = /* @__PURE__ */ new Set();
1651
+ const touch = (id, where) => {
1652
+ if (touched.has(id)) problems.push(`${where}: belief ${id} is already changed in this pass`);
1653
+ touched.add(id);
1654
+ };
1655
+ const fresh = (events, belief, where) => {
1656
+ if (events.length === 0) problems.push(`${where}: say what it took in since that bears on it`);
1657
+ for (const entry of events) if (entry.event.turn < belief.turn) problems.push(`${where}: thing ${entry.perception.id} came before the belief was formed; cite what came after`);
1658
+ };
1659
+ revise.forEach((change, index) => {
1660
+ const where = `revise[${index}]`;
1661
+ const belief = shown.beliefs.get(change.id);
1662
+ if (belief === void 0) {
1663
+ problems.push(`${where}: there is no belief numbered ${change.id}`);
1664
+ return;
1665
+ }
1666
+ touch(change.id, where);
1667
+ if (change.text === void 0 && change.importance === void 0) problems.push(`${where}: say what changes`);
1668
+ if (change.text !== void 0 && (change.text.trim() === "" || change.text.trim().length > MAX_TEXT)) problems.push(`${where}: the text must be there and at most ${MAX_TEXT} characters`);
1669
+ if (change.importance !== void 0 && (!Number.isInteger(change.importance) || change.importance < 1 || change.importance > 5)) problems.push(`${where}: importance runs from 1 to 5`);
1670
+ fresh(cited(change.perceptions, where), belief, where);
1671
+ });
1672
+ const dropped = new Set(drop.map((entry) => entry.id));
1673
+ drop.forEach((change, index) => {
1674
+ const where = `drop[${index}]`;
1675
+ const belief = shown.beliefs.get(change.id);
1676
+ if (belief === void 0) {
1677
+ problems.push(`${where}: there is no belief numbered ${change.id}`);
1678
+ return;
1679
+ }
1680
+ touch(change.id, where);
1681
+ if (change.merged_into !== void 0) {
1682
+ if (change.merged_into === change.id || !shown.beliefs.has(change.merged_into) || dropped.has(change.merged_into)) problems.push(`${where}: merge into a belief that stays`);
1683
+ return;
1684
+ }
1685
+ fresh(cited(change.perceptions, where), belief, where);
1686
+ });
1687
+ return problems;
1688
+ }
1689
+ const keysOf = (names, resolveName) => (names ?? []).flatMap((name) => {
1690
+ const key = resolveName(name);
1691
+ return key === void 0 ? [] : [key];
1692
+ });
1693
+ /** The edit that writes a proposal that passed. */
1694
+ function editOf(turn, character, proposal, resolveName) {
1695
+ const who = characterKey(character);
1696
+ return {
1697
+ turn,
1698
+ beliefs: (proposal.add ?? []).map((belief) => ({
1699
+ character: who,
1700
+ kind: belief.kind,
1701
+ text: belief.text.trim(),
1702
+ about: keysOf(belief.about, resolveName),
1703
+ importance: belief.importance
1704
+ })),
1705
+ beliefEdits: (proposal.revise ?? []).map((change) => ({
1706
+ id: change.id,
1707
+ ...change.text === void 0 ? {} : { text: change.text.trim() },
1708
+ ...change.importance === void 0 ? {} : { importance: change.importance }
1709
+ })),
1710
+ beliefRetractions: (proposal.drop ?? []).map((change) => change.id)
1711
+ };
1712
+ }
1713
+ function brief(session, material, now, zone, time) {
1714
+ const { character, fresh, beliefs } = material;
1715
+ const named = (id) => session.characters.get(id)?.name ?? String(id);
1716
+ const believed = beliefs.map((belief) => {
1717
+ const about = belief.about.length === 0 ? "" : `, about ${belief.about.map(named).join(" and ")}`;
1718
+ return `- b${belief.id} (${belief.kind}, importance ${belief.importance}${about}): ${belief.text}`;
1719
+ });
1720
+ const taken = fresh.map((entry) => {
1721
+ const at = time(entry.event.turn, entry.event.round);
1722
+ return `- p${entry.perception.id}${at === void 0 ? "" : ` (${describeWhen(at, now, zone)})`}: ${entry.perception.content}`;
1723
+ });
1724
+ return [
1725
+ `Character: ${referent(character)}${character.summary === "" ? "" : ` - ${character.summary}`}`,
1726
+ "What they believe now:",
1727
+ ...believed.length === 0 ? ["(nothing yet)"] : believed,
1728
+ "What they have taken in since:",
1729
+ ...taken,
1730
+ "Sort their memory."
1731
+ ].join("\n");
1732
+ }
1733
+ /**
1734
+ * Has the characters with the most new to sort sort it into what they believe, one request each, one after another. Each answer is checked
1735
+ * against what the character was shown before it is written, and the writing of one character is all or nothing; a failure stops the pass
1736
+ * and leaves the characters not yet done as they were.
1737
+ */
1738
+ function memoryReflector(deps) {
1739
+ return { async reflect(job, signal) {
1740
+ const parent = deps.agentOf(job.chat);
1741
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
1742
+ const { store } = job;
1743
+ const session = store.story;
1744
+ const settings = store.settings();
1745
+ const { now, zone } = store.time(job.turn);
1746
+ const due = materialOf(session, job.reason === "manual" ? 1 : settings.reflection.minNew);
1747
+ const taken = job.reason === "manual" ? due : due.slice(0, settings.reflection.perRun);
1748
+ const resolveName = (name) => {
1749
+ const found = session.characters.findByName(name.trim());
1750
+ return found.length === 1 ? characterKey(found[0]) : void 0;
1751
+ };
1752
+ const characters = [];
1753
+ for (const material of taken) {
1754
+ const shown = shownOf(material);
1755
+ const proposal = await runChild({
1756
+ parent,
1757
+ signal,
1758
+ reasoningEffort: settings.reasoning.children,
1759
+ sampling: childSampling(settings, "records"),
1760
+ ...childModel(settings, "records"),
1761
+ trace: childTrace(store, "records", `reflection ${material.character.name}`),
1762
+ persona: promptFor(parent, "roleplay/reflection", settings.prompts.language),
1763
+ prompt: brief(session, material, now, zone, (turn, round) => session.clock.at(turn, round)),
1764
+ result: RESULT,
1765
+ beforeSubmit: (value) => {
1766
+ const problems = proposalProblems(value, shown, resolveName);
1767
+ return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
1768
+ },
1769
+ maxCalls: 3
1770
+ });
1771
+ const reached = Math.max(...material.fresh.map((entry) => entry.perception.id));
1772
+ session.transaction(() => {
1773
+ session.edit(editOf(job.turn, material.character, proposal, resolveName));
1774
+ session.metadata.setValue(CURSOR_KEY, {
1775
+ ...readCursor(session),
1776
+ [characterKey(material.character)]: reached
1777
+ });
1778
+ });
1779
+ characters.push({
1780
+ name: material.character.name,
1781
+ added: proposal.add?.length ?? 0,
1782
+ revised: proposal.revise?.length ?? 0,
1783
+ dropped: proposal.drop?.length ?? 0
1784
+ });
1785
+ }
1786
+ session.metadata.setValue(LAST_KEY, {
1787
+ turn: job.turn,
1788
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1789
+ reason: job.reason,
1790
+ characters
1791
+ });
1792
+ writeAnchor(session, playerPlace(store), now);
1793
+ session.metadata.deleteValue(ERROR_KEY);
1794
+ return { characters };
1795
+ } };
1796
+ }
1797
+ //#endregion
1340
1798
  //#region src/host/sessions/activity.ts
1341
- const KEY = "activity";
1799
+ const KEY$1 = "activity";
1342
1800
  const isEntry = (value) => {
1343
1801
  if (typeof value !== "object" || value === null) return false;
1344
1802
  const entry = value;
@@ -1346,13 +1804,13 @@ const isEntry = (value) => {
1346
1804
  };
1347
1805
  /** The recorded runs, oldest first. */
1348
1806
  function readActivity(session) {
1349
- const stored = session.metadata.getValue(KEY);
1807
+ const stored = session.metadata.getValue(KEY$1);
1350
1808
  return Array.isArray(stored) ? stored.filter(isEntry) : [];
1351
1809
  }
1352
1810
  /** Files the run and returns the runs that fell off the end of the record to make room. */
1353
1811
  function recordActivity(session, entry) {
1354
1812
  const all = [...readActivity(session), entry];
1355
- session.metadata.setValue(KEY, all.slice(-60));
1813
+ session.metadata.setValue(KEY$1, all.slice(-60));
1356
1814
  return all.slice(0, -60);
1357
1815
  }
1358
1816
  const RUN_FOLDER = "activity";
@@ -1381,6 +1839,40 @@ function forgetRunDetails(folder, dropped) {
1381
1839
  for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
1382
1840
  }
1383
1841
  //#endregion
1384
- export { readTime as A, defaultBoundaries as C, describeTime as D, beginTurn as E, CHARACTER_ACTION_SCHEMA as F, RESULTS as I, answerEstimate as L, zoneOf as M, referent as N, describeWhen as O, AWAY_ACTION_SCHEMA as P, parseCharacterAction as R, pathTo as S, ClockError as T, putNote as _, recordActivity as a, Timelines as b, describePacingAdvice as c, plotProgressOf as d, populatePlots as f, notesOfSession as g, clearNotes as h, readRunDetail as i, skipTime as j, endRound as k, pacingAdvice as l, addToNote as m, keepRunDetail as n, PLOTS_METADATA_KEY as o, updatePlotProgress as p, readActivity as r, addSessionPlot as s, forgetRunDetails as t, plotAuthorNeeded as u, readNotes as v, sameWords as w, readTimeline as x, TimelineError as y };
1842
+ //#region src/host/triggers/deliver.ts
1843
+ const KEY = "triggers.withdrawn";
1844
+ /** Why a note was withdrawn instead of told, by the number of the note. */
1845
+ function readWithdrawn(session) {
1846
+ const stored = session.metadata.getValue(KEY);
1847
+ if (!Array.isArray(stored)) return {};
1848
+ return Object.fromEntries(stored.flatMap((entry) => {
1849
+ const { note, reason } = entry ?? {};
1850
+ return typeof note === "number" && typeof reason === "string" ? [[note, reason]] : [];
1851
+ }));
1852
+ }
1853
+ /**
1854
+ * Tells these notes as the story stands now: each is written from the story at this moment, and one that no longer applies is let go and the
1855
+ * reason kept (`readWithdrawn`). @returns what is to be told, with the number of its note.
1856
+ */
1857
+ function deliverNow(session, notes, clock) {
1858
+ const { shown, withdrawn } = session.deliverNotes(notes, clock);
1859
+ if (withdrawn.length > 0) session.transaction(() => {
1860
+ for (const { note } of withdrawn) session.triggers.resolveNote(note.id, "lapsed");
1861
+ const before = Object.entries(readWithdrawn(session)).map(([note, reason]) => ({
1862
+ note: Number(note),
1863
+ reason
1864
+ }));
1865
+ session.metadata.setValue(KEY, [...before, ...withdrawn.map(({ note, reason }) => ({
1866
+ note: note.id,
1867
+ reason
1868
+ }))].slice(-100));
1869
+ });
1870
+ return shown.map(({ note, text }) => ({
1871
+ id: note.id,
1872
+ text
1873
+ }));
1874
+ }
1875
+ //#endregion
1876
+ export { readTimeline as A, skipTime as B, notesOfSession as C, observeSurroundings as D, observeAsPlayer as E, beginTurn as F, RESULTS as G, referent as H, describeTime as I, answerEstimate as K, describeWhen as L, defaultBoundaries as M, sameWords as N, TimelineError as O, ClockError as P, endRound as R, clearNotes as S, readNotes as T, AWAY_ACTION_SCHEMA as U, zoneOf as V, CHARACTER_ACTION_SCHEMA as W, plotAuthorNeeded as _, readActivity as a, updatePlotProgress as b, dueReflection as c, reflectionStatus as d, whereabouts as f, pacingAdvice as g, describePacingAdvice as h, keepRunDetail as i, pathTo as j, Timelines as k, memoryReflector as l, addSessionPlot as m, readWithdrawn as n, readRunDetail as o, PLOTS_METADATA_KEY as p, parseCharacterAction as q, forgetRunDetails as r, recordActivity as s, deliverNow as t, recordFailure as u, plotProgressOf as v, putNote as w, addToNote as x, populatePlots as y, readTime as z };
1385
1877
 
1386
- //# sourceMappingURL=activity-t7OBgHlc.js.map
1878
+ //# sourceMappingURL=deliver--uMhC6oO.js.map