@dsh-agentic-roleplay/core 0.9.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +1 -1
  2. package/lib/{access-CfQWbNZP.js → access-CXtaZNbx.js} +50 -2
  3. package/lib/{authoring-tools-C_l07RYn.js → authoring-tools-C6Hzy8jU.js} +1571 -1301
  4. package/lib/authoring.js +19 -8
  5. package/lib/{child-lYYeOwl2.js → child-C8r8AFpm.js} +150 -14
  6. package/lib/client.js +6295 -3329
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +3 -3
  9. package/lib/doctor.js +3 -3
  10. package/lib/{gallery-q7niLtWn.js → gallery-CtG-bDzz.js} +5 -9
  11. package/lib/{generator-BpjPrvHe.js → generator-nLoPM5MF.js} +2 -2
  12. package/lib/helper.js +1 -1
  13. package/lib/{hooks-DNaDzMjW.js → hooks-BuQ61nvQ.js} +207 -56
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +1312 -125
  16. package/lib/{library-CIkxhf_R.js → library-CH-ahlm0.js} +7 -14
  17. package/lib/{lorebook-author-tools-BiMDmdFi.js → lorebook-author-tools-B6_Jj8oe.js} +7 -7
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-CjB_KwwY.js → narration-B0hConSw.js} +11 -53
  20. package/lib/orchestration.js +196 -14
  21. package/lib/{pack-jail-B35Vx3hT.js → pack-jail-OZSgU85i.js} +11 -11
  22. package/lib/{packs-BajKw7S9.js → packs-B88bxt8E.js} +2 -2
  23. package/lib/{presenter-agent-jgtuTwZr.js → presenter-agent-D-WNs626.js} +12 -17
  24. package/lib/{preset-DWgkcPau.js → preset-DNuqvMan.js} +4 -4
  25. package/lib/{preset-author-tools-BhuYIKms.js → preset-author-tools-CDwavcTb.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-9GzaSELc.js → presets-9_MNxwaw.js} +105 -10
  28. package/lib/{reflection-4L0Plvct.js → reflection-BvM0w1R4.js} +179 -112
  29. package/lib/{text-CbGQhK1-.js → text-CzqhC8sT.js} +11 -1
  30. package/lib/{turn-guard-sCUXmp-5.js → turn-guard-Ygdww1Wt.js} +3 -3
  31. package/package.json +2 -2
  32. package/prompts/en/checks/conflict.md +1 -1
  33. package/prompts/en/checks/decide-conflict.md +1 -1
  34. package/prompts/en/checks/decide-opening.md +1 -1
  35. package/prompts/en/checks/decide-same-value.md +1 -1
  36. package/prompts/en/checks/decide-sheet.md +1 -1
  37. package/prompts/en/checks/decide-stated.md +1 -0
  38. package/prompts/en/checks/fidelity.md +1 -0
  39. package/prompts/zh/checks/conflict.md +1 -1
  40. package/prompts/zh/checks/decide-conflict.md +1 -1
  41. package/prompts/zh/checks/decide-opening.md +1 -1
  42. package/prompts/zh/checks/decide-same-value.md +1 -1
  43. package/prompts/zh/checks/decide-sheet.md +1 -1
  44. package/prompts/zh/checks/decide-stated.md +1 -0
  45. package/prompts/zh/checks/fidelity.md +1 -0
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-B0hConSw.js";
2
+ import { l as roleplaySessionOf, t as promptFor } from "./access-CXtaZNbx.js";
3
+ import { C as tokensOf, c as runChild, n as childModel, r as childSampling } from "./child-C8r8AFpm.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-DNaDzMjW.js";
4
- import { a as liveSettings } from "./narration-CjB_KwwY.js";
3
+ import { i as externalTools, t as externalToolLimit } from "./hooks-BuQ61nvQ.js";
4
+ import { a as liveSettings } from "./narration-B0hConSw.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, g as sidecarOf, h as readImageFileMetadata, m as mediaTypeOf, x as mapLimit } from "./library-CIkxhf_R.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-CH-ahlm0.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-q7niLtWn.js.map
190
+ //# sourceMappingURL=gallery-CtG-bDzz.js.map
@@ -1,4 +1,4 @@
1
- import { d as sceneImagePath, f as writeImage, u as referenceImagePath } from "./library-CIkxhf_R.js";
1
+ import { d as sceneImagePath, f as writeImage, u as referenceImagePath } from "./library-CH-ahlm0.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-BpjPrvHe.js.map
144
+ //# sourceMappingURL=generator-nLoPM5MF.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-C8r8AFpm.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";
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";
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-B0hConSw.js";
3
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CzqhC8sT.js";
4
+ import { S as estimateAnswer, _ 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 } from "./child-C8r8AFpm.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";
@@ -559,6 +559,43 @@ function plotReferenceProblems(plots, entities) {
559
559
  const known = new Set(entities);
560
560
  return plots.flatMap((plot) => plot.participants.filter((participant) => !known.has(participant)).map((participant) => `plot "${plot.id}" names unknown participant "${participant}"`));
561
561
  }
562
+ // src/host/sessions/usage.ts
563
+ const KEY$5 = "usage";
564
+ const isCount = (value) => typeof value === "object" && value !== null && [
565
+ "input",
566
+ "cached",
567
+ "output"
568
+ ].every((field) => typeof value[field] === "number");
569
+ const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
570
+ /** What each turn used, oldest first. The record belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
571
+ function readUsage(session) {
572
+ const stored = session.metadata.getValue(KEY$5);
573
+ return Array.isArray(stored) ? stored.filter(isUsage) : [];
574
+ }
575
+ /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
576
+ function addUsage(session, turn, who, tokens, masterMs) {
577
+ const all = readUsage(session);
578
+ const at = all.findIndex((entry) => entry.turn === turn);
579
+ const entry = at === -1 ? {
580
+ turn,
581
+ master: NO_TOKENS,
582
+ helpers: NO_TOKENS,
583
+ runs: 0
584
+ } : all[at];
585
+ const next = who === "master" ? {
586
+ ...entry,
587
+ master: addTokens(entry.master, tokens),
588
+ ...masterMs === void 0 ? {} : { masterMs: (entry.masterMs ?? 0) + masterMs }
589
+ } : {
590
+ ...entry,
591
+ helpers: addTokens(entry.helpers, tokens),
592
+ runs: entry.runs + 1
593
+ };
594
+ if (at === -1) all.push(next);
595
+ else all[at] = next;
596
+ all.sort((a, b) => a.turn - b.turn);
597
+ session.metadata.setValue(KEY$5, all);
598
+ }
562
599
  // src/host/translate/language.ts
563
600
  const STORY_LANGUAGES = ["en", "zh"];
564
601
  /** Less than this many letters of either script is too little to tell a language. */
@@ -1069,6 +1106,49 @@ function notesOfSession(deps, id) {
1069
1106
  count: waiting
1070
1107
  }];
1071
1108
  }
1109
+ // src/host/diagnostics/master-trace.ts
1110
+ const cut = (text) => text.length > 240 ? `${text.slice(0, 240)}…` : text;
1111
+ const textOf = (message) => Array.isArray(message?.content) ? message.content.map(blockText).join("") : typeof message?.content === "string" ? message.content : "";
1112
+ /**
1113
+ * 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
1114
+ * 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.
1115
+ */
1116
+ function masterTrace(events) {
1117
+ const start = events.find((event) => event.type === "turn/start");
1118
+ const end = events.findLast((event) => event.type === "turn/end");
1119
+ const first = events.find((event) => event.type === "step/start");
1120
+ const pending = /* @__PURE__ */ new Map();
1121
+ const calls = [];
1122
+ const steered = [];
1123
+ let answered = false;
1124
+ for (const event of events) {
1125
+ const data = event.data;
1126
+ if (event.type === "assistant/message") answered = true;
1127
+ else if (event.type === "tool/call" && data?.callId !== void 0 && data.name !== void 0) pending.set(data.callId, {
1128
+ tool: data.name,
1129
+ at: event.time ?? 0
1130
+ });
1131
+ else if (event.type === "tool/result") {
1132
+ const message = data?.message;
1133
+ const call = message?.toolCallId === void 0 ? void 0 : pending.get(message.toolCallId);
1134
+ if (call !== void 0 && calls.length < 60) calls.push({
1135
+ tool: call.tool,
1136
+ ...event.time === void 0 ? {} : { ms: Math.max(0, event.time - call.at) },
1137
+ failed: message?.isError === true,
1138
+ note: cut(textOf(message))
1139
+ });
1140
+ } else if (event.type === "user/message" && answered && data?.source?.kind === "roleplay" && steered.length < 20) steered.push(cut(textOf(data)));
1141
+ }
1142
+ const requests = requestsOf(events);
1143
+ return {
1144
+ startedAt: start?.time ?? 0,
1145
+ ...end?.time === void 0 ? {} : { endedAt: end.time },
1146
+ ...start?.time === void 0 || first?.time === void 0 ? {} : { beforeMs: Math.max(0, first.time - start.time) },
1147
+ ...requests.length === 0 ? {} : { requests },
1148
+ ...calls.length === 0 ? {} : { calls },
1149
+ ...steered.length === 0 ? {} : { steered }
1150
+ };
1151
+ }
1072
1152
  // src/host/triggers/deliver.ts
1073
1153
  const KEY$3 = "triggers.withdrawn";
1074
1154
  /** Why a note was withdrawn instead of told, by the number of the note. */
@@ -1252,8 +1332,34 @@ function noteStore(session, settings, clock) {
1252
1332
  }
1253
1333
  };
1254
1334
  }
1335
+ // src/host/sessions/trace.ts
1336
+ const KEY$1 = "trace";
1337
+ const isTrace = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.startedAt === "number";
1338
+ /** 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. */
1339
+ function readTraces(session) {
1340
+ const stored = session.metadata.getValue(KEY$1);
1341
+ return Array.isArray(stored) ? stored.filter(isTrace) : [];
1342
+ }
1343
+ /** 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. */
1344
+ function updateTrace(session, turn, patch, merge) {
1345
+ const all = readTraces(session);
1346
+ const at = all.findIndex((entry) => entry.turn === turn);
1347
+ const current = at === -1 ? {
1348
+ turn,
1349
+ startedAt: 0
1350
+ } : all[at];
1351
+ const next = {
1352
+ ...current,
1353
+ ...patch,
1354
+ ...merge?.(current)
1355
+ };
1356
+ if (at === -1) all.push(next);
1357
+ else all[at] = next;
1358
+ all.sort((a, b) => a.turn - b.turn);
1359
+ session.metadata.setValue(KEY$1, all.slice(-30));
1360
+ }
1255
1361
  // src/host/sessions/activity.ts
1256
- const KEY$1 = "activity";
1362
+ const KEY = "activity";
1257
1363
  const isEntry = (value) => {
1258
1364
  if (typeof value !== "object" || value === null) return false;
1259
1365
  const entry = value;
@@ -1261,13 +1367,13 @@ const isEntry = (value) => {
1261
1367
  };
1262
1368
  /** The recorded runs, oldest first. */
1263
1369
  function readActivity(session) {
1264
- const stored = session.metadata.getValue(KEY$1);
1370
+ const stored = session.metadata.getValue(KEY);
1265
1371
  return Array.isArray(stored) ? stored.filter(isEntry) : [];
1266
1372
  }
1267
1373
  /** Files the run and returns the runs that fell off the end of the record to make room. */
1268
1374
  function recordActivity(session, entry) {
1269
1375
  const all = [...readActivity(session), entry];
1270
- session.metadata.setValue(KEY$1, all.slice(-60));
1376
+ session.metadata.setValue(KEY, all.slice(-60));
1271
1377
  return all.slice(0, -60);
1272
1378
  }
1273
1379
  const RUN_FOLDER = "activity";
@@ -1349,42 +1455,6 @@ function recordDecisions(folder, site, report, now = () => /* @__PURE__ */ new D
1349
1455
  writeFileSync(aside, JSON.stringify(stats, null, 2));
1350
1456
  renameSync(aside, target);
1351
1457
  }
1352
- // src/host/sessions/usage.ts
1353
- const KEY = "usage";
1354
- const isCount = (value) => typeof value === "object" && value !== null && [
1355
- "input",
1356
- "cached",
1357
- "output"
1358
- ].every((field) => typeof value[field] === "number");
1359
- const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
1360
- /** What each turn used, oldest first. The record belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1361
- function readUsage(session) {
1362
- const stored = session.metadata.getValue(KEY);
1363
- return Array.isArray(stored) ? stored.filter(isUsage) : [];
1364
- }
1365
- /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
1366
- function addUsage(session, turn, who, tokens) {
1367
- const all = readUsage(session);
1368
- const at = all.findIndex((entry) => entry.turn === turn);
1369
- const entry = at === -1 ? {
1370
- turn,
1371
- master: NO_TOKENS,
1372
- helpers: NO_TOKENS,
1373
- runs: 0
1374
- } : all[at];
1375
- const next = who === "master" ? {
1376
- ...entry,
1377
- master: addTokens(entry.master, tokens)
1378
- } : {
1379
- ...entry,
1380
- helpers: addTokens(entry.helpers, tokens),
1381
- runs: entry.runs + 1
1382
- };
1383
- if (at === -1) all.push(next);
1384
- else all[at] = next;
1385
- all.sort((a, b) => a.turn - b.turn);
1386
- session.metadata.setValue(KEY, all);
1387
- }
1388
1458
  // src/host/clock/agenda.ts
1389
1459
  const CURSOR = "agenda.cursor";
1390
1460
  const ASKED = "agenda.asked";
@@ -2089,8 +2159,11 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
2089
2159
  });
2090
2160
  return used;
2091
2161
  },
2092
- recordUsage: (turn, tokens) => {
2093
- 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);
2094
2167
  },
2095
2168
  notes: () => readNotes(session),
2096
2169
  clearNotes: () => {
@@ -2171,6 +2244,36 @@ function parseRoll(text) {
2171
2244
  reason: body.slice(boundary).trim()
2172
2245
  };
2173
2246
  }
2247
+ // src/shared/wait.ts
2248
+ const UNITS = [
2249
+ [/^(?:m|min|mins|minute|minutes|分钟|分)$/iu, 1],
2250
+ [/^(?:h|hr|hrs|hour|hours|小时|時間|时)$/iu, 60],
2251
+ [/^(?:d|day|days|天|日)$/iu, 1440]
2252
+ ];
2253
+ /**
2254
+ * The wait in a player's message (`/wait 2 hours`, `/wait 30m until the ferry`, `/wait 3天`), or nothing when the message does not start with `/wait`. The time may be missing or
2255
+ * unreadable, and is then `undefined` in `minutes`.
2256
+ */
2257
+ function parseWait(text) {
2258
+ const value = text.trimStart();
2259
+ if (value.slice(0, 5).toLowerCase() !== "/wait" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
2260
+ const body = value.slice(5).trim();
2261
+ const match = /^(\d+(?:\.\d+)?)\s*([\p{L}]+)\s*(.*)$/su.exec(body);
2262
+ if (match === null) return {
2263
+ minutes: void 0,
2264
+ reason: body
2265
+ };
2266
+ const unit = UNITS.find(([pattern]) => pattern.test(match[2]));
2267
+ if (unit === void 0) return {
2268
+ minutes: void 0,
2269
+ reason: body
2270
+ };
2271
+ const minutes = Math.round(Number(match[1]) * unit[1]);
2272
+ return {
2273
+ minutes: minutes >= 1 && minutes <= 525600 ? minutes : void 0,
2274
+ reason: match[3].trim()
2275
+ };
2276
+ }
2174
2277
  // src/host/agents/repeat-guard.ts
2175
2278
  /**
2176
2279
  * Keeps an agent that is stuck from making the same call again and again (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one
@@ -2297,7 +2400,7 @@ function characterRunner(deps) {
2297
2400
  signal,
2298
2401
  sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
2299
2402
  ...childModel(settings, "characters", named),
2300
- trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named),
2403
+ trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named, request.away === true ? "off stage" : void 0),
2301
2404
  reasoningEffort: deps.store.settings().reasoning.children,
2302
2405
  persona: brief.persona,
2303
2406
  prompt: brief.prompt,
@@ -3478,7 +3581,17 @@ function installHooks(ctx, deps) {
3478
3581
  const events = session.snapshotEvents();
3479
3582
  const began = events.findLastIndex((entry) => entry.type === "turn/start");
3480
3583
  const start = began === -1 ? void 0 : events[began];
3481
- if (start?.type === "turn/start") stores(session.id)?.recordUsage?.(start.data.turn, tokensOf(events.slice(began)));
3584
+ if (start?.type !== "turn/start") return;
3585
+ const store = stores(session.id);
3586
+ store?.recordUsage?.(start.data.turn, tokensOf(events.slice(began)), Math.max(0, event.time - start.time));
3587
+ try {
3588
+ store?.recordTrace?.(start.data.turn, {
3589
+ ...masterTrace(events.slice(began)),
3590
+ endedAt: event.time
3591
+ });
3592
+ } catch (error) {
3593
+ ctx.logger.warn(`roleplay: the trace of turn ${start.data.turn} could not be kept: ${error instanceof Error ? error.message : String(error)}`);
3594
+ }
3482
3595
  });
3483
3596
  ctx.on("agent/created", async ({ agent }) => {
3484
3597
  const { header } = agent.session;
@@ -3510,7 +3623,8 @@ function installHooks(ctx, deps) {
3510
3623
  const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
3511
3624
  if (!store.settings().background.concurrent) await engine.quiesce(owner.chat);
3512
3625
  await ctx.roleplayOrchestration.unitFree(owner.chat);
3513
- await timelines.begin(owner.chat, payload.turn, text);
3626
+ const began = await timelines.begin(owner.chat, payload.turn, text);
3627
+ deps.rolls?.begin(owner.chat, store.story.metadata.get().id, began.parent);
3514
3628
  const cast = store.cast();
3515
3629
  const ooc = parseOoc(text);
3516
3630
  const command = ooc === void 0 ? /^\/([\p{L}\p{N}_]+)/u.exec(text.trim())?.[1] : void 0;
@@ -3543,7 +3657,20 @@ function installHooks(ctx, deps) {
3543
3657
  upcoming: store.upcoming(payload.turn)
3544
3658
  };
3545
3659
  const tracked = store.tracked();
3660
+ const sections = [];
3661
+ let selection;
3546
3662
  const lines = [boundaries().sceneContext.scene({
3663
+ report: {
3664
+ section: (id, text) => {
3665
+ sections.push({
3666
+ id,
3667
+ tokens: estimateTokens(text)
3668
+ });
3669
+ },
3670
+ selected: (found) => {
3671
+ selection = found;
3672
+ }
3673
+ },
3547
3674
  ...tracked.length === 0 ? {} : { tracked },
3548
3675
  time: {
3549
3676
  now: time,
@@ -3563,17 +3690,24 @@ function installHooks(ctx, deps) {
3563
3690
  ...queryVector === void 0 ? {} : { queryVector }
3564
3691
  })];
3565
3692
  const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
3566
- 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.", {
3693
+ const addLine = (id, text) => {
3694
+ lines.push(text);
3695
+ sections.push({
3696
+ id,
3697
+ tokens: estimateTokens(text)
3698
+ });
3699
+ };
3700
+ 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.", {
3567
3701
  word: used.word,
3568
3702
  description: used.description
3569
3703
  }), ...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(" "));
3570
- if (pacing !== void 0) lines.push(describePacingAdvice(pacing));
3571
- else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
3704
+ if (pacing !== void 0) addLine("pacing", describePacingAdvice(pacing));
3705
+ else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) addLine("pacing", store.text("roleplay/plot-hint"));
3572
3706
  const rules = store.rules();
3573
- if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
3707
+ if (rules.length > 0) addLine("rules", store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
3574
3708
  const wanted = ooc === void 0 ? parseRoll(text) : void 0;
3575
3709
  if (wanted !== void 0) try {
3576
- const made = rollPlain(wanted.expression);
3710
+ const made = rollPlain(wanted.expression, deps.rolls?.roller(owner.chat));
3577
3711
  const roll = store.story.dice.record({
3578
3712
  turn: payload.turn,
3579
3713
  expression: made.expression,
@@ -3585,7 +3719,7 @@ function installHooks(ctx, deps) {
3585
3719
  reason: wanted.reason === "" ? tr("the player's roll") : wanted.reason,
3586
3720
  by: "player"
3587
3721
  });
3588
- 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.", {
3722
+ 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.", {
3589
3723
  dice: roll.expression,
3590
3724
  reason: roll.reason,
3591
3725
  total: roll.total,
@@ -3595,6 +3729,19 @@ function installHooks(ctx, deps) {
3595
3729
  engine.skip(owner);
3596
3730
  lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
3597
3731
  }
3732
+ const waiting = ooc === void 0 && wanted === void 0 ? parseWait(text) : void 0;
3733
+ if (waiting !== void 0) {
3734
+ const clock = store.settings().clock;
3735
+ const refusal = clock.mode === "real" ? tr("this chat follows the clock on the wall, so time cannot be skipped") : waiting.minutes === void 0 ? tr("say how long, for example /wait 2 hours or /wait 30 minutes until the ferry") : waiting.minutes > clock.maxSkipDays * 1440 ? tr("that is more than the {days} days this chat allows in one skip", { days: clock.maxSkipDays }) : void 0;
3736
+ if (refusal !== void 0) {
3737
+ engine.skip(owner);
3738
+ lines.push(store.text("roleplay/input-refused", { reason: refusal }));
3739
+ } else addLine("wait", tr("The player lets {minutes} minutes pass{reason}. Move the story's time on by that much with advance_time, and let the world move meanwhile as it would: characters keep to their days, and you ask only those the time reaches. Stop sooner, at the moment it happens, if something comes up that the player must decide or could not sleep through, say what, and let the player act. Then narrate what the player perceived in the time that passed. You may play at most {rounds} rounds for this.", {
3740
+ minutes: waiting.minutes,
3741
+ reason: waiting.reason === "" ? "" : ` (${waiting.reason})`,
3742
+ rounds: store.settings().maxRounds
3743
+ }));
3744
+ }
3598
3745
  if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
3599
3746
  if (ooc !== void 0 && ooc.request === "") {
3600
3747
  engine.skip(owner);
@@ -3604,12 +3751,16 @@ function installHooks(ctx, deps) {
3604
3751
  engine.skip(owner);
3605
3752
  lines.push(store.text("roleplay/input-refused", { reason: verdict.reason }));
3606
3753
  }
3754
+ store.recordTrace?.(payload.turn, {
3755
+ scene: sections,
3756
+ ...selection === void 0 ? {} : { selected: selection }
3757
+ });
3607
3758
  return {
3608
3759
  ...decision,
3609
3760
  messages: [...decision.messages, notice(lines.join("\n\n"))]
3610
3761
  };
3611
3762
  });
3612
3763
  }
3613
- 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 };
3764
+ export { PromptLibrary as $, answerLimits as A, PLOTS_FILE_NAME as B, readNotes as C, describeWhen as D, describeTime as E, STORY_LANGUAGES as F, commandFlagKey as G, parsePlotsFile as H, isStoryLanguage as I, Reader as J, commandsOf as K, textLanguage as L, plotProgressOf as M, populatePlots as N, zoneOf as O, LANGUAGE_NAMES as P, PROMPTS_FOLDER as Q, wrongLanguage as R, notesOfSession as S, ClockError as T, plotReferenceProblems as U, loadPlots as V, COMMANDS_KEY as W, errorMessage as X, formatIssue as Y, LANGUAGE_FOLDER as Z, readTraces as _, externalWithheld as a, shippedLanguages as at, readWithdrawn 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, readRunDetail as g, COMPARISONS as gt, readActivity as h, AUTHORING_NEEDS as ht, externalTools as i, promptProblem as it, PLOTS_METADATA_KEY as j, RESULTS as k, characterRunner as l, InvalidStartError as lt, readDecisionStats 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, readVerdicts as v, observeAsPlayer as w, addToNote as x, writeVerdicts as y, readUsage as z };
3614
3765
 
3615
- //# sourceMappingURL=hooks-DNaDzMjW.js.map
3766
+ //# sourceMappingURL=hooks-BuQ61nvQ.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-jgtuTwZr.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-q7niLtWn.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-CIkxhf_R.js";
4
- import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-BpjPrvHe.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-D-WNs626.js";
2
+ import { i as updateImage, r as listGallery } from "./gallery-CtG-bDzz.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-CH-ahlm0.js";
4
+ import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-nLoPM5MF.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 };