@dsh-agentic-roleplay/core 0.9.0 → 0.10.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.
Files changed (47) hide show
  1. package/lib/{access-CfQWbNZP.js → access-CXtaZNbx.js} +50 -2
  2. package/lib/{authoring-tools-CdHlvx32.js → authoring-tools-B4mEdKp_.js} +1349 -604
  3. package/lib/authoring.js +23 -19
  4. package/lib/{child-lYYeOwl2.js → child-Dtv76jNx.js} +116 -11
  5. package/lib/client.js +2810 -795
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-BKh7eu80.js → gallery-BZJleAeH.js} +5 -9
  10. package/lib/{generator-DdZ1-sgv.js → generator-Cg6CQc5S.js} +2 -2
  11. package/lib/helper.js +1 -1
  12. package/lib/{hooks-CcQj_dJo.js → hooks-DTjHWTfx.js} +168 -28
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +362 -33
  15. package/lib/{library-QFL6Z_Nr.js → library-GIlrkOim.js} +9 -14
  16. package/lib/{lorebook-author-tools-DWBnYo1E.js → lorebook-author-tools-BCFFJSle.js} +6 -6
  17. package/lib/lorebook-authoring.js +4 -4
  18. package/lib/{narration-CjB_KwwY.js → narration-BVzew4-K.js} +7 -52
  19. package/lib/orchestration.js +155 -10
  20. package/lib/{pack-jail-BMy6NcCY.js → pack-jail-hsNQNTOf.js} +25 -15
  21. package/lib/{packs-BREPSfHy.js → packs-UpK_cvI4.js} +2 -2
  22. package/lib/{presenter-agent-B49-_iUm.js → presenter-agent-DZOgBOR9.js} +12 -17
  23. package/lib/{preset-BqgY1Tz4.js → preset-Cyoj1ZWa.js} +4 -4
  24. package/lib/{preset-author-tools-BB_Dcv2o.js → preset-author-tools-RSta6pHK.js} +6 -6
  25. package/lib/preset-authoring.js +5 -5
  26. package/lib/{presets-Bwnrx7p0.js → presets-CvpsW_10.js} +17 -9
  27. package/lib/{reflection-CUWG-6Qg.js → reflection-0qTvw2It.js} +53 -26
  28. package/lib/{turn-guard-Bb8Ew-1z.js → turn-guard-BzNeGNnc.js} +3 -3
  29. package/package.json +2 -2
  30. package/prompts/en/checks/conflict.md +1 -0
  31. package/prompts/en/checks/decide-conflict.md +1 -0
  32. package/prompts/en/checks/decide-covered.md +1 -0
  33. package/prompts/en/checks/decide-opening.md +1 -0
  34. package/prompts/en/checks/decide-same-thing.md +1 -0
  35. package/prompts/en/checks/decide-same-value.md +1 -0
  36. package/prompts/en/checks/decide-sheet.md +1 -1
  37. package/prompts/en/checks/fidelity.md +1 -0
  38. package/prompts/en/checks/notice.md +2 -2
  39. package/prompts/zh/checks/conflict.md +1 -0
  40. package/prompts/zh/checks/decide-conflict.md +1 -0
  41. package/prompts/zh/checks/decide-covered.md +1 -0
  42. package/prompts/zh/checks/decide-opening.md +1 -0
  43. package/prompts/zh/checks/decide-same-thing.md +1 -0
  44. package/prompts/zh/checks/decide-same-value.md +1 -0
  45. package/prompts/zh/checks/decide-sheet.md +1 -1
  46. package/prompts/zh/checks/fidelity.md +1 -0
  47. package/prompts/zh/checks/notice.md +2 -2
package/lib/compaction.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as liveSettings, t as decodeOutput } from "./narration-CjB_KwwY.js";
2
- import { o as roleplaySessionOf, t as promptFor } from "./access-CfQWbNZP.js";
3
- import { c as runChild, n as childModel, r as childSampling, y as tokensOf } from "./child-lYYeOwl2.js";
1
+ import { a as liveSettings, t as decodeOutput } from "./narration-BVzew4-K.js";
2
+ import { l as roleplaySessionOf, t as promptFor } from "./access-CXtaZNbx.js";
3
+ import { S as tokensOf, c as runChild, n as childModel, r as childSampling } from "./child-Dtv76jNx.js";
4
4
  import { join } from "node:path";
5
5
  import { sessionFolder } from "@dsh-agentic-roleplay/state";
6
6
  import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
package/lib/doctor.js CHANGED
@@ -1,7 +1,7 @@
1
- import { a as chatSessionId } from "./access-CfQWbNZP.js";
1
+ import { c as chatSessionId } from "./access-CXtaZNbx.js";
2
2
  import { n as doctorSessionOf } from "./doctor-chat-hL1a61hp.js";
3
- import { i as externalTools, t as externalToolLimit } from "./hooks-CcQj_dJo.js";
4
- import { a as liveSettings } from "./narration-CjB_KwwY.js";
3
+ import { i as externalTools, t as externalToolLimit } from "./hooks-DTjHWTfx.js";
4
+ import { a as liveSettings } from "./narration-BVzew4-K.js";
5
5
  import { join } from "node:path";
6
6
  import { existsSync } from "node:fs";
7
7
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -1,7 +1,7 @@
1
- import { _ as writeImageFileMetadata, a as LIBRARY_FOLDER, b as mapLimit, g as sidecarOf, h as readImageFileMetadata, m as mediaTypeOf } from "./library-QFL6Z_Nr.js";
1
+ import { n as atomicWrite } from "./access-CXtaZNbx.js";
2
+ import { _ as writeImageFileMetadata, a as LIBRARY_FOLDER, g as sidecarOf, h as readImageFileMetadata, m as mediaTypeOf, x as mapLimit } from "./library-GIlrkOim.js";
2
3
  import { join, sep } from "node:path";
3
- import { randomUUID } from "node:crypto";
4
- import { lstat, mkdir, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
4
+ import { lstat, readFile, readdir, realpath, stat } from "node:fs/promises";
5
5
  // src/host/images/gallery.ts
6
6
  const READ_AT_ONCE = 8;
7
7
  const SEGMENT = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}._-]{0,199}$/u;
@@ -95,11 +95,7 @@ async function readCache(images) {
95
95
  };
96
96
  }
97
97
  async function writeCache(images, cache) {
98
- await mkdir(images, { recursive: true });
99
- const file = join(images, CACHE_FILE);
100
- const temporary = `${file}.${process.pid}.${randomUUID()}.writing`;
101
- await writeFile(temporary, JSON.stringify(cache));
102
- await rename(temporary, file);
98
+ await atomicWrite(join(images, CACHE_FILE), JSON.stringify(cache), { createDirectory: true });
103
99
  }
104
100
  /**
105
101
  * Every image of a session folder with what its file says, newest first. The files are the truth; `images/.index.json` only remembers what
@@ -191,4 +187,4 @@ async function updateImage(sessionFolder, path, update) {
191
187
  }
192
188
  export { updateImage as i, galleryFile as n, listGallery as r, describeGalleryImage as t };
193
189
 
194
- //# sourceMappingURL=gallery-BKh7eu80.js.map
190
+ //# sourceMappingURL=gallery-BZJleAeH.js.map
@@ -1,4 +1,4 @@
1
- import { d as sceneImagePath, f as writeImage, u as referenceImagePath } from "./library-QFL6Z_Nr.js";
1
+ import { d as sceneImagePath, f as writeImage, u as referenceImagePath } from "./library-GIlrkOim.js";
2
2
  // src/host/images/generator.ts
3
3
  const unique = (values) => [...new Set(values.map((value) => value.trim()).filter((value) => value !== ""))];
4
4
  /** What a reference image shows: the subject and its stable look. */
@@ -141,4 +141,4 @@ async function generateTransientImage(service, request) {
141
141
  }
142
142
  export { uploadReferenceImage as a, transientPrompt as i, generateTransientImage as n, referencePrompt as r, generateReferenceImage as t };
143
143
 
144
- //# sourceMappingURL=generator-DdZ1-sgv.js.map
144
+ //# sourceMappingURL=generator-Cg6CQc5S.js.map
package/lib/helper.js CHANGED
@@ -1,4 +1,4 @@
1
- import { o as helpers } from "./child-lYYeOwl2.js";
1
+ import { o as helpers } from "./child-Dtv76jNx.js";
2
2
  // src/helper.ts
3
3
  const name = "@dsh-agentic-roleplay/core/helper";
4
4
  const inject = ["tools", "systemPrompt"];
@@ -1,7 +1,7 @@
1
- import { o as roleplaySessionOf, t as promptFor } from "./access-CfQWbNZP.js";
2
- import { _ as DECISION_SITES, a as liveSettings, g as rulesOf, h as WORLD_RULES_KEY, n as encodeOutput, r as encodePreview, y as emptyStats } from "./narration-CjB_KwwY.js";
1
+ import { l as roleplaySessionOf, t as promptFor } from "./access-CXtaZNbx.js";
2
+ import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-BVzew4-K.js";
3
3
  import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CbGQhK1-.js";
4
- import { a as childTrace, c as runChild, f as tokensOf, m as addTokens, n as childModel, p as NO_TOKENS, r as childSampling, v as estimateAnswer } from "./child-lYYeOwl2.js";
4
+ import { _ as addTokens, a as childTrace, c as runChild, f as requestsOf, g as NO_TOKENS, h as tokensOf, m as estimateTokens, n as childModel, p as blockText, r as childSampling, x as estimateAnswer } from "./child-Dtv76jNx.js";
5
5
  import { dirname, join } from "node:path";
6
6
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
7
  import { readFile, stat } from "node:fs/promises";
@@ -268,6 +268,30 @@ var Reader = class Reader {
268
268
  data;
269
269
  path;
270
270
  issues;
271
+ static watched;
272
+ looked = /* @__PURE__ */ new Set();
273
+ inner = [];
274
+ /**
275
+ * Runs a parse and returns what it never looked at: the fields of the document (and of the objects inside it) that nothing reads, as paths, and the top-level fields it did look at. A parser that gave up
276
+ * early has not looked at the rest, so only a parse that succeeded says anything.
277
+ */
278
+ static unreadBy(parse) {
279
+ const outer = Reader.watched;
280
+ const roots = [];
281
+ Reader.watched = roots;
282
+ try {
283
+ parse();
284
+ } finally {
285
+ Reader.watched = outer;
286
+ }
287
+ return {
288
+ unread: roots.flatMap((root) => root.unread()),
289
+ read: roots.flatMap((root) => [...root.looked])
290
+ };
291
+ }
292
+ unread() {
293
+ return [...Object.keys(this.data).filter((key) => !this.looked.has(key)).map((key) => this.child(key)), ...this.inner.flatMap((reader) => reader.unread())];
294
+ }
271
295
  constructor(data, path, issues) {
272
296
  this.data = data;
273
297
  this.path = path;
@@ -292,7 +316,9 @@ var Reader = class Reader {
292
316
  });
293
317
  return;
294
318
  }
295
- return new Reader(data, "", issues);
319
+ const reader = new Reader(data, "", issues);
320
+ Reader.watched?.push(reader);
321
+ return reader;
296
322
  }
297
323
  fail(key, message) {
298
324
  this.issues.push({
@@ -302,6 +328,7 @@ var Reader = class Reader {
302
328
  }
303
329
  /** The value as written, with `null` read as absent. */
304
330
  raw(key) {
331
+ this.looked.add(key);
305
332
  const value = this.data[key];
306
333
  return value === null ? void 0 : value;
307
334
  }
@@ -367,7 +394,9 @@ var Reader = class Reader {
367
394
  this.fail(key, "must be an object");
368
395
  return;
369
396
  }
370
- return new Reader(value, this.child(key), this.issues);
397
+ const reader = new Reader(value, this.child(key), this.issues);
398
+ this.inner.push(reader);
399
+ return reader;
371
400
  }
372
401
  objects(key) {
373
402
  const value = this.raw(key);
@@ -377,7 +406,11 @@ var Reader = class Reader {
377
406
  return [];
378
407
  }
379
408
  return value.flatMap((entry, index) => {
380
- if (isRecord(entry)) return [new Reader(entry, this.child(`${key}[${index}]`), this.issues)];
409
+ if (isRecord(entry)) {
410
+ const reader = new Reader(entry, this.child(`${key}[${index}]`), this.issues);
411
+ this.inner.push(reader);
412
+ return [reader];
413
+ }
381
414
  this.fail(`${key}[${index}]`, "must be an object");
382
415
  return [];
383
416
  });
@@ -991,7 +1024,7 @@ const NOTE_KINDS = [
991
1024
  "world"
992
1025
  ];
993
1026
  // src/host/sessions/notes.ts
994
- const KEY$4 = "notes";
1027
+ const KEY$5 = "notes";
995
1028
  const isNote = (value) => {
996
1029
  if (typeof value !== "object" || value === null) return false;
997
1030
  const note = value;
@@ -999,12 +1032,12 @@ const isNote = (value) => {
999
1032
  };
1000
1033
  /** The notes of a session, at most one per kind. */
1001
1034
  function readNotes(session) {
1002
- const stored = session.metadata.getValue(KEY$4);
1035
+ const stored = session.metadata.getValue(KEY$5);
1003
1036
  return Array.isArray(stored) ? stored.filter(isNote) : [];
1004
1037
  }
1005
1038
  /** Replaces the note of the same kind. */
1006
1039
  function putNote(session, note) {
1007
- session.metadata.setValue(KEY$4, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1040
+ session.metadata.setValue(KEY$5, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1008
1041
  }
1009
1042
  /** The most lines one note keeps: what is past it is not told. */
1010
1043
  const MAX_NOTE_LINES = 8;
@@ -1019,7 +1052,7 @@ function addToNote(session, kind, turn, lines) {
1019
1052
  }
1020
1053
  /** Removes every note: they belong to the turn that made them. */
1021
1054
  function clearNotes(session) {
1022
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$4, []);
1055
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$5, []);
1023
1056
  }
1024
1057
  /**
1025
1058
  * The notes of a session, for the player's screen.
@@ -1036,11 +1069,54 @@ function notesOfSession(deps, id) {
1036
1069
  count: waiting
1037
1070
  }];
1038
1071
  }
1072
+ // src/host/diagnostics/master-trace.ts
1073
+ const cut = (text) => text.length > 240 ? `${text.slice(0, 240)}…` : text;
1074
+ const textOf = (message) => Array.isArray(message?.content) ? message.content.map(blockText).join("") : typeof message?.content === "string" ? message.content : "";
1075
+ /**
1076
+ * What the chat's log says of one turn of the game master: how long it waited before its first request, each request with the parts of its prompt, each tool call with its time and the
1077
+ * reason when it was refused, and what the harness said to it to keep the turn going. `events` are those from the turn's start to its end.
1078
+ */
1079
+ function masterTrace(events) {
1080
+ const start = events.find((event) => event.type === "turn/start");
1081
+ const end = events.findLast((event) => event.type === "turn/end");
1082
+ const first = events.find((event) => event.type === "step/start");
1083
+ const pending = /* @__PURE__ */ new Map();
1084
+ const calls = [];
1085
+ const steered = [];
1086
+ let answered = false;
1087
+ for (const event of events) {
1088
+ const data = event.data;
1089
+ if (event.type === "assistant/message") answered = true;
1090
+ else if (event.type === "tool/call" && data?.callId !== void 0 && data.name !== void 0) pending.set(data.callId, {
1091
+ tool: data.name,
1092
+ at: event.time ?? 0
1093
+ });
1094
+ else if (event.type === "tool/result") {
1095
+ const message = data?.message;
1096
+ const call = message?.toolCallId === void 0 ? void 0 : pending.get(message.toolCallId);
1097
+ if (call !== void 0 && calls.length < 60) calls.push({
1098
+ tool: call.tool,
1099
+ ...event.time === void 0 ? {} : { ms: Math.max(0, event.time - call.at) },
1100
+ failed: message?.isError === true,
1101
+ note: cut(textOf(message))
1102
+ });
1103
+ } else if (event.type === "user/message" && answered && data?.source?.kind === "roleplay" && steered.length < 20) steered.push(cut(textOf(data)));
1104
+ }
1105
+ const requests = requestsOf(events);
1106
+ return {
1107
+ startedAt: start?.time ?? 0,
1108
+ ...end?.time === void 0 ? {} : { endedAt: end.time },
1109
+ ...start?.time === void 0 || first?.time === void 0 ? {} : { beforeMs: Math.max(0, first.time - start.time) },
1110
+ ...requests.length === 0 ? {} : { requests },
1111
+ ...calls.length === 0 ? {} : { calls },
1112
+ ...steered.length === 0 ? {} : { steered }
1113
+ };
1114
+ }
1039
1115
  // src/host/triggers/deliver.ts
1040
- const KEY$3 = "triggers.withdrawn";
1116
+ const KEY$4 = "triggers.withdrawn";
1041
1117
  /** Why a note was withdrawn instead of told, by the number of the note. */
1042
1118
  function readWithdrawn(session) {
1043
- const stored = session.metadata.getValue(KEY$3);
1119
+ const stored = session.metadata.getValue(KEY$4);
1044
1120
  if (!Array.isArray(stored)) return {};
1045
1121
  return Object.fromEntries(stored.flatMap((entry) => {
1046
1122
  const { note, reason } = entry ?? {};
@@ -1059,7 +1135,7 @@ function deliverNow(session, notes, clock) {
1059
1135
  note: Number(note),
1060
1136
  reason
1061
1137
  }));
1062
- session.metadata.setValue(KEY$3, [...before, ...withdrawn.map(({ note, reason }) => ({
1138
+ session.metadata.setValue(KEY$4, [...before, ...withdrawn.map(({ note, reason }) => ({
1063
1139
  note: note.id,
1064
1140
  reason
1065
1141
  }))].slice(-100));
@@ -1070,9 +1146,9 @@ function deliverNow(session, notes, clock) {
1070
1146
  }));
1071
1147
  }
1072
1148
  // src/host/triggers/judged.ts
1073
- const KEY$2 = "triggers.judged";
1149
+ const KEY$3 = "triggers.judged";
1074
1150
  function readVerdicts(session) {
1075
- const stored = session.metadata.getValue(KEY$2);
1151
+ const stored = session.metadata.getValue(KEY$3);
1076
1152
  if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
1077
1153
  const verdicts = {};
1078
1154
  for (const [statement, value] of Object.entries(stored)) {
@@ -1086,7 +1162,7 @@ function readVerdicts(session) {
1086
1162
  }
1087
1163
  /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
1088
1164
  function writeVerdicts(session, verdicts, keep) {
1089
- session.metadata.setValue(KEY$2, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1165
+ session.metadata.setValue(KEY$3, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1090
1166
  }
1091
1167
  /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
1092
1168
  const verdictReader = (session) => {
@@ -1219,6 +1295,32 @@ function noteStore(session, settings, clock) {
1219
1295
  }
1220
1296
  };
1221
1297
  }
1298
+ // src/host/sessions/trace.ts
1299
+ const KEY$2 = "trace";
1300
+ const isTrace = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.startedAt === "number";
1301
+ /** What the story kept of each turn's work, oldest first. It belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1302
+ function readTraces(session) {
1303
+ const stored = session.metadata.getValue(KEY$2);
1304
+ return Array.isArray(stored) ? stored.filter(isTrace) : [];
1305
+ }
1306
+ /** Adds to a turn's trace what one source of it knows; the sources (the characters' briefs, the scene, the log at the end of the turn) arrive at different times. */
1307
+ function updateTrace(session, turn, patch, merge) {
1308
+ const all = readTraces(session);
1309
+ const at = all.findIndex((entry) => entry.turn === turn);
1310
+ const current = at === -1 ? {
1311
+ turn,
1312
+ startedAt: 0
1313
+ } : all[at];
1314
+ const next = {
1315
+ ...current,
1316
+ ...patch,
1317
+ ...merge?.(current)
1318
+ };
1319
+ if (at === -1) all.push(next);
1320
+ else all[at] = next;
1321
+ all.sort((a, b) => a.turn - b.turn);
1322
+ session.metadata.setValue(KEY$2, all.slice(-30));
1323
+ }
1222
1324
  // src/host/sessions/activity.ts
1223
1325
  const KEY$1 = "activity";
1224
1326
  const isEntry = (value) => {
@@ -1330,7 +1432,7 @@ function readUsage(session) {
1330
1432
  return Array.isArray(stored) ? stored.filter(isUsage) : [];
1331
1433
  }
1332
1434
  /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
1333
- function addUsage(session, turn, who, tokens) {
1435
+ function addUsage(session, turn, who, tokens, masterMs) {
1334
1436
  const all = readUsage(session);
1335
1437
  const at = all.findIndex((entry) => entry.turn === turn);
1336
1438
  const entry = at === -1 ? {
@@ -1341,7 +1443,8 @@ function addUsage(session, turn, who, tokens) {
1341
1443
  } : all[at];
1342
1444
  const next = who === "master" ? {
1343
1445
  ...entry,
1344
- master: addTokens(entry.master, tokens)
1446
+ master: addTokens(entry.master, tokens),
1447
+ ...masterMs === void 0 ? {} : { masterMs: (entry.masterMs ?? 0) + masterMs }
1345
1448
  } : {
1346
1449
  ...entry,
1347
1450
  helpers: addTokens(entry.helpers, tokens),
@@ -2056,8 +2159,11 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
2056
2159
  });
2057
2160
  return used;
2058
2161
  },
2059
- recordUsage: (turn, tokens) => {
2060
- addUsage(session, turn, "master", tokens);
2162
+ recordUsage: (turn, tokens, ms) => {
2163
+ addUsage(session, turn, "master", tokens, ms);
2164
+ },
2165
+ recordTrace: (turn, patch, merge) => {
2166
+ updateTrace(session, turn, patch, merge);
2061
2167
  },
2062
2168
  notes: () => readNotes(session),
2063
2169
  clearNotes: () => {
@@ -3445,7 +3551,17 @@ function installHooks(ctx, deps) {
3445
3551
  const events = session.snapshotEvents();
3446
3552
  const began = events.findLastIndex((entry) => entry.type === "turn/start");
3447
3553
  const start = began === -1 ? void 0 : events[began];
3448
- if (start?.type === "turn/start") stores(session.id)?.recordUsage?.(start.data.turn, tokensOf(events.slice(began)));
3554
+ if (start?.type !== "turn/start") return;
3555
+ const store = stores(session.id);
3556
+ store?.recordUsage?.(start.data.turn, tokensOf(events.slice(began)), Math.max(0, event.time - start.time));
3557
+ try {
3558
+ store?.recordTrace?.(start.data.turn, {
3559
+ ...masterTrace(events.slice(began)),
3560
+ endedAt: event.time
3561
+ });
3562
+ } catch (error) {
3563
+ ctx.logger.warn(`roleplay: the trace of turn ${start.data.turn} could not be kept: ${error instanceof Error ? error.message : String(error)}`);
3564
+ }
3449
3565
  });
3450
3566
  ctx.on("agent/created", async ({ agent }) => {
3451
3567
  const { header } = agent.session;
@@ -3510,7 +3626,20 @@ function installHooks(ctx, deps) {
3510
3626
  upcoming: store.upcoming(payload.turn)
3511
3627
  };
3512
3628
  const tracked = store.tracked();
3629
+ const sections = [];
3630
+ let selection;
3513
3631
  const lines = [boundaries().sceneContext.scene({
3632
+ report: {
3633
+ section: (id, text) => {
3634
+ sections.push({
3635
+ id,
3636
+ tokens: estimateTokens(text)
3637
+ });
3638
+ },
3639
+ selected: (found) => {
3640
+ selection = found;
3641
+ }
3642
+ },
3514
3643
  ...tracked.length === 0 ? {} : { tracked },
3515
3644
  time: {
3516
3645
  now: time,
@@ -3530,14 +3659,21 @@ function installHooks(ctx, deps) {
3530
3659
  ...queryVector === void 0 ? {} : { queryVector }
3531
3660
  })];
3532
3661
  const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
3533
- if (used !== void 0) lines.push([tr("The player used the world's command /{word}: {description} It is part of the story, not an out-of-character command: play it in the story. The world raises and lowers the command's own flag itself: never change it.", {
3662
+ const addLine = (id, text) => {
3663
+ lines.push(text);
3664
+ sections.push({
3665
+ id,
3666
+ tokens: estimateTokens(text)
3667
+ });
3668
+ };
3669
+ if (used !== void 0) addLine("command", [tr("The player used the world's command /{word}: {description} It is part of the story, not an out-of-character command: play it in the story. The world raises and lowers the command's own flag itself: never change it.", {
3534
3670
  word: used.word,
3535
3671
  description: used.description
3536
3672
  }), ...commandBringsPeopleIn(store, used) ? [tr("The world itself brings in anyone this command calls for, after this turn: do not make them up yourself with expand_world.")] : []].join(" "));
3537
- if (pacing !== void 0) lines.push(describePacingAdvice(pacing));
3538
- else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
3673
+ if (pacing !== void 0) addLine("pacing", describePacingAdvice(pacing));
3674
+ else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) addLine("pacing", store.text("roleplay/plot-hint"));
3539
3675
  const rules = store.rules();
3540
- if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
3676
+ if (rules.length > 0) addLine("rules", store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
3541
3677
  const wanted = ooc === void 0 ? parseRoll(text) : void 0;
3542
3678
  if (wanted !== void 0) try {
3543
3679
  const made = rollPlain(wanted.expression);
@@ -3552,7 +3688,7 @@ function installHooks(ctx, deps) {
3552
3688
  reason: wanted.reason === "" ? tr("the player's roll") : wanted.reason,
3553
3689
  by: "player"
3554
3690
  });
3555
- lines.push(tr("The player rolled {dice} ({reason}) and got {total}: dice {faces}. This is a fact, decided by the dice: take it into account when you judge the attempt and decide what happens.", {
3691
+ addLine("roll", tr("The player rolled {dice} ({reason}) and got {total}: dice {faces}. This is a fact, decided by the dice: take it into account when you judge the attempt and decide what happens.", {
3556
3692
  dice: roll.expression,
3557
3693
  reason: roll.reason,
3558
3694
  total: roll.total,
@@ -3571,12 +3707,16 @@ function installHooks(ctx, deps) {
3571
3707
  engine.skip(owner);
3572
3708
  lines.push(store.text("roleplay/input-refused", { reason: verdict.reason }));
3573
3709
  }
3710
+ store.recordTrace?.(payload.turn, {
3711
+ scene: sections,
3712
+ ...selection === void 0 ? {} : { selected: selection }
3713
+ });
3574
3714
  return {
3575
3715
  ...decision,
3576
3716
  messages: [...decision.messages, notice(lines.join("\n\n"))]
3577
3717
  };
3578
3718
  });
3579
3719
  }
3580
- export { copyWorldPrompts as $, answerLimits as A, loadPlots as B, readNotes as C, describeWhen as D, describeTime as E, STORY_LANGUAGES as F, commandsOf as G, plotReferenceProblems as H, isStoryLanguage as I, formatIssue as J, readDocument as K, textLanguage as L, plotProgressOf as M, populatePlots as N, zoneOf as O, LANGUAGE_NAMES as P, PromptLibrary as Q, wrongLanguage as R, notesOfSession as S, ClockError as T, COMMANDS_KEY as U, parsePlotsFile as V, commandFlagKey as W, LANGUAGE_FOLDER as X, errorMessage as Y, PROMPTS_FOLDER as Z, readRunDetail as _, externalWithheld as a, shippedPromptsDirectory as at, readWithdrawn as b, record as c, InvalidStartError as ct, guardRepeatedCalls as d, SessionArchivedError as dt, inheritPrompts as et, MAX_OOC_ANSWER as f, SessionNotFoundError as ft, readActivity as g, readDecisionStats as h, COMPARISONS as ht, externalTools as i, shippedLanguages as it, PLOTS_METADATA_KEY as j, RESULTS as k, characterRunner as l, InvalidWorldError as lt, readUsage as m, AUTHORING_NEEDS as mt, installHooks as n, listFiles as nt, PREVIEW_TOOL as o, shippedText as ot, storesOf as p, WorldNotFoundError as pt, Reader as q, externalGiven as r, promptProblem as rt, createTools$1 as s, AgentUnavailableError as st, externalToolLimit as t, languageOf as tt, toolEnabled as u, ReflectionRefusedError as ut, readVerdicts as v, observeAsPlayer as w, addToNote as x, writeVerdicts as y, PLOTS_FILE_NAME as z };
3720
+ export { PromptLibrary as $, RESULTS as A, PLOTS_FILE_NAME as B, notesOfSession as C, describeTime as D, ClockError as E, LANGUAGE_NAMES as F, commandFlagKey as G, parsePlotsFile as H, STORY_LANGUAGES as I, Reader as J, commandsOf as K, isStoryLanguage as L, PLOTS_METADATA_KEY as M, plotProgressOf as N, describeWhen as O, populatePlots as P, PROMPTS_FOLDER as Q, textLanguage as R, addToNote as S, observeAsPlayer as T, plotReferenceProblems as U, loadPlots as V, COMMANDS_KEY as W, errorMessage as X, formatIssue as Y, LANGUAGE_FOLDER as Z, readRunDetail as _, externalWithheld as a, shippedLanguages as at, writeVerdicts as b, record as c, AgentUnavailableError as ct, guardRepeatedCalls as d, ReflectionRefusedError as dt, copyWorldPrompts as et, MAX_OOC_ANSWER as f, SessionArchivedError as ft, readActivity as g, COMPARISONS as gt, readDecisionStats as h, AUTHORING_NEEDS as ht, externalTools as i, promptProblem as it, answerLimits as j, zoneOf as k, characterRunner as l, InvalidStartError as lt, readUsage as m, WorldNotFoundError as mt, installHooks as n, languageOf as nt, PREVIEW_TOOL as o, shippedPromptsDirectory as ot, storesOf as p, SessionNotFoundError as pt, readDocument as q, externalGiven as r, listFiles as rt, createTools$1 as s, shippedText as st, externalToolLimit as t, inheritPrompts as tt, toolEnabled as u, InvalidWorldError as ut, readTraces as v, readNotes as w, readWithdrawn as x, readVerdicts as y, wrongLanguage as z };
3581
3721
 
3582
- //# sourceMappingURL=hooks-CcQj_dJo.js.map
3722
+ //# sourceMappingURL=hooks-DTjHWTfx.js.map
package/lib/images.js CHANGED
@@ -1,5 +1,5 @@
1
- import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-B49-_iUm.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-BKh7eu80.js";
3
- import { c as nextSceneSerial, d as sceneImagePath, l as readImageMetadata, o as entityImageDirectory, s as inheritImages, t as addToLibrary, u as referenceImagePath, v as readPngMetadata, y as withPngMetadata } from "./library-QFL6Z_Nr.js";
4
- import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-DdZ1-sgv.js";
1
+ import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-DZOgBOR9.js";
2
+ import { i as updateImage, r as listGallery } from "./gallery-BZJleAeH.js";
3
+ import { c as nextSceneSerial, d as sceneImagePath, l as readImageMetadata, o as entityImageDirectory, s as inheritImages, t as addToLibrary, u as referenceImagePath, v as readPngMetadata, y as withPngMetadata } from "./library-GIlrkOim.js";
4
+ import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-Cg6CQc5S.js";
5
5
  export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };