@dsh-agentic-roleplay/core 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/lib/authoring.js +7 -256
  2. package/lib/{child-lPncV1ps.js → child-CFjnaTZt.js} +62 -7
  3. package/lib/client.js +10950 -7439
  4. package/lib/client.js.map +1 -1
  5. package/lib/{deliver-De62a8i9.js → deliver-Cl6bjp7g.js} +49 -11
  6. package/lib/doctor.js +83 -7
  7. package/lib/{gallery-CtFDL22W.js → gallery-DIEgETzU.js} +2 -2
  8. package/lib/generator-DJ48HxPI.js +145 -0
  9. package/lib/{hooks-Ka22sFNy.js → hooks-DdO_tNhu.js} +58 -17
  10. package/lib/images.js +4 -3
  11. package/lib/index.js +1761 -71
  12. package/lib/language-BgyxtB2h.js +38 -0
  13. package/lib/{generator-B6FxlKOV.js → library-9JB9zw5a.js} +2 -143
  14. package/lib/{language-DWVwi1R7.js → load-Clkl0T7C.js} +6 -40
  15. package/lib/orchestration.js +23 -26
  16. package/lib/pack-jail-ClMpVc__.js +1979 -0
  17. package/lib/{packs-BYjrAen6.js → packs-BC2A3geF.js} +3 -29
  18. package/lib/{presenter-agent-Dt21K96b.js → presenter-agent-DnNEG_Mn.js} +5 -4
  19. package/lib/{documents-Do4lz4SB.js → preset-ClQm7KPQ.js} +67 -1656
  20. package/lib/preset-author-tools-Dibp-LY9.js +270 -0
  21. package/lib/preset-authoring.js +53 -0
  22. package/lib/presets-DNjNxQL5.js +335 -0
  23. package/lib/{reflection-md7BCYCl.js → reflection-Bju_LPFn.js} +131 -9
  24. package/package.json +3 -2
  25. package/prompts/en/doctor/procedure.md +1 -1
  26. package/prompts/en/import/character.md +1 -1
  27. package/prompts/en/preset/persona.md +1 -0
  28. package/prompts/en/preset/procedure.md +1 -0
  29. package/prompts/en/preset/welcome.md +1 -0
  30. package/prompts/en/roleplay/record-keeper.md +2 -2
  31. package/prompts/zh/doctor/procedure.md +1 -1
  32. package/prompts/zh/import/character.md +1 -1
  33. package/prompts/zh/preset/persona.md +1 -0
  34. package/prompts/zh/preset/procedure.md +1 -0
  35. package/prompts/zh/preset/welcome.md +1 -0
  36. package/prompts/zh/roleplay/record-keeper.md +2 -2
@@ -1,8 +1,9 @@
1
1
  import { t as promptFor } from "./access-EbNdZFbk.js";
2
2
  import "./settings-CA6icLL_.js";
3
- import { a as wrongLanguage, c as parsePlotsFile, k as SessionNotFoundError } from "./language-DWVwi1R7.js";
3
+ import { T as SessionNotFoundError, r as parsePlotsFile } from "./load-Clkl0T7C.js";
4
4
  import { n as encodeOutput, r as encodePreview } from "./narration-DK2kiIjE.js";
5
- import { a as runChild, i as childTrace, n as childSampling, o as estimateAnswer, t as childModel } from "./child-lPncV1ps.js";
5
+ import { a as runChild, c as addTokens, i as childTrace, n as childSampling, s as NO_TOKENS, t as childModel, u as estimateAnswer } from "./child-CFjnaTZt.js";
6
+ import { a as wrongLanguage } from "./language-BgyxtB2h.js";
6
7
  import { join } from "node:path";
7
8
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
9
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -562,7 +563,7 @@ const NOTE_KINDS = [
562
563
  ];
563
564
  //#endregion
564
565
  //#region src/host/sessions/notes.ts
565
- const KEY$2 = "notes";
566
+ const KEY$3 = "notes";
566
567
  const isNote = (value) => {
567
568
  if (typeof value !== "object" || value === null) return false;
568
569
  const note = value;
@@ -570,12 +571,12 @@ const isNote = (value) => {
570
571
  };
571
572
  /** The notes of a session, at most one per kind. */
572
573
  function readNotes(session) {
573
- const stored = session.metadata.getValue(KEY$2);
574
+ const stored = session.metadata.getValue(KEY$3);
574
575
  return Array.isArray(stored) ? stored.filter(isNote) : [];
575
576
  }
576
577
  /** Replaces the note of the same kind. */
577
578
  function putNote(session, note) {
578
- session.metadata.setValue(KEY$2, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
579
+ session.metadata.setValue(KEY$3, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
579
580
  }
580
581
  /** The most lines one note keeps: what is past it is not told. */
581
582
  const MAX_NOTE_LINES = 8;
@@ -590,7 +591,7 @@ function addToNote(session, kind, turn, lines) {
590
591
  }
591
592
  /** Removes every note: they belong to the turn that made them. */
592
593
  function clearNotes(session) {
593
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$2, []);
594
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$3, []);
594
595
  }
595
596
  /**
596
597
  * The notes of a session, for the player's screen.
@@ -1847,7 +1848,7 @@ function externalWithheld(registry, board, agent) {
1847
1848
  }
1848
1849
  //#endregion
1849
1850
  //#region src/host/sessions/activity.ts
1850
- const KEY$1 = "activity";
1851
+ const KEY$2 = "activity";
1851
1852
  const isEntry = (value) => {
1852
1853
  if (typeof value !== "object" || value === null) return false;
1853
1854
  const entry = value;
@@ -1855,13 +1856,13 @@ const isEntry = (value) => {
1855
1856
  };
1856
1857
  /** The recorded runs, oldest first. */
1857
1858
  function readActivity(session) {
1858
- const stored = session.metadata.getValue(KEY$1);
1859
+ const stored = session.metadata.getValue(KEY$2);
1859
1860
  return Array.isArray(stored) ? stored.filter(isEntry) : [];
1860
1861
  }
1861
1862
  /** Files the run and returns the runs that fell off the end of the record to make room. */
1862
1863
  function recordActivity(session, entry) {
1863
1864
  const all = [...readActivity(session), entry];
1864
- session.metadata.setValue(KEY$1, all.slice(-60));
1865
+ session.metadata.setValue(KEY$2, all.slice(-60));
1865
1866
  return all.slice(0, -60);
1866
1867
  }
1867
1868
  const RUN_FOLDER = "activity";
@@ -1890,6 +1891,43 @@ function forgetRunDetails(folder, dropped) {
1890
1891
  for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
1891
1892
  }
1892
1893
  //#endregion
1894
+ //#region src/host/sessions/usage.ts
1895
+ const KEY$1 = "usage";
1896
+ const isCount = (value) => typeof value === "object" && value !== null && [
1897
+ "input",
1898
+ "cached",
1899
+ "output"
1900
+ ].every((field) => typeof value[field] === "number");
1901
+ const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
1902
+ /** 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. */
1903
+ function readUsage(session) {
1904
+ const stored = session.metadata.getValue(KEY$1);
1905
+ return Array.isArray(stored) ? stored.filter(isUsage) : [];
1906
+ }
1907
+ /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
1908
+ function addUsage(session, turn, who, tokens) {
1909
+ const all = readUsage(session);
1910
+ const at = all.findIndex((entry) => entry.turn === turn);
1911
+ const entry = at === -1 ? {
1912
+ turn,
1913
+ master: NO_TOKENS,
1914
+ helpers: NO_TOKENS,
1915
+ runs: 0
1916
+ } : all[at];
1917
+ const next = who === "master" ? {
1918
+ ...entry,
1919
+ master: addTokens(entry.master, tokens)
1920
+ } : {
1921
+ ...entry,
1922
+ helpers: addTokens(entry.helpers, tokens),
1923
+ runs: entry.runs + 1
1924
+ };
1925
+ if (at === -1) all.push(next);
1926
+ else all[at] = next;
1927
+ all.sort((a, b) => a.turn - b.turn);
1928
+ session.metadata.setValue(KEY$1, all);
1929
+ }
1930
+ //#endregion
1893
1931
  //#region src/host/triggers/deliver.ts
1894
1932
  const KEY = "triggers.withdrawn";
1895
1933
  /** Why a note was withdrawn instead of told, by the number of the note. */
@@ -1924,6 +1962,6 @@ function deliverNow(session, notes, clock) {
1924
1962
  }));
1925
1963
  }
1926
1964
  //#endregion
1927
- export { ClockError as A, languageOf as B, addToNote as C, readNotes as D, putNote as E, readTime as F, skipTime as I, zoneOf as L, describeTime as M, describeWhen as N, observeAsPlayer as O, endRound as P, RESULTS as R, toolEnabled as S, notesOfSession as T, translator as V, plotProgressOf as _, readActivity as a, MAX_OOC_ANSWER as b, externalGiven as c, PREVIEW_TOOL as d, createTools$1 as f, plotAuthorNeeded as g, pacingAdvice as h, keepRunDetail as i, beginTurn as j, observeSurroundings as k, externalTools as l, describePacingAdvice as m, readWithdrawn as n, readRunDetail as o, PLOTS_METADATA_KEY as p, forgetRunDetails as r, recordActivity as s, deliverNow as t, externalWithheld as u, populatePlots as v, clearNotes as w, parseOoc as x, AUTHORING_NEEDS as y, answerLimits as z };
1965
+ export { observeAsPlayer as A, RESULTS as B, parseOoc as C, notesOfSession as D, clearNotes as E, describeWhen as F, languageOf as H, endRound as I, readTime as L, ClockError as M, beginTurn as N, putNote as O, describeTime as P, skipTime as R, MAX_OOC_ANSWER as S, addToNote as T, translator as U, answerLimits as V, pacingAdvice as _, forgetRunDetails as a, populatePlots as b, readRunDetail as c, externalTools as d, externalWithheld as f, describePacingAdvice as g, PLOTS_METADATA_KEY as h, readUsage as i, observeSurroundings as j, readNotes as k, recordActivity as l, createTools$1 as m, readWithdrawn as n, keepRunDetail as o, PREVIEW_TOOL as p, addUsage as r, readActivity as s, deliverNow as t, externalGiven as u, plotAuthorNeeded as v, toolEnabled as w, AUTHORING_NEEDS as x, plotProgressOf as y, zoneOf as z };
1928
1966
 
1929
- //# sourceMappingURL=deliver-De62a8i9.js.map
1967
+ //# sourceMappingURL=deliver-Cl6bjp7g.js.map
package/lib/doctor.js CHANGED
@@ -1,25 +1,68 @@
1
- import "./language-DWVwi1R7.js";
2
- import { l as externalTools } from "./deliver-De62a8i9.js";
1
+ import { n as chatSessionId } from "./access-EbNdZFbk.js";
2
+ import "./load-Clkl0T7C.js";
3
+ import { d as externalTools } from "./deliver-Cl6bjp7g.js";
3
4
  import { a as liveSettings } from "./narration-DK2kiIjE.js";
4
5
  import { n as doctorSessionOf } from "./doctor-chat-ByDfCMeo.js";
5
- import { t as externalToolLimit } from "./hooks-Ka22sFNy.js";
6
+ import { t as externalToolLimit } from "./hooks-DdO_tNhu.js";
6
7
  import { join } from "node:path";
7
8
  import { existsSync } from "node:fs";
9
+ import { SessionId } from "@deepseek-ai/dsh-session";
10
+ import { defineTool } from "@deepseek-ai/dsh-tools";
8
11
  import { createTools, isSessionId, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
12
+ //#region src/host/agent/doctor-undo.ts
13
+ const UNDO_SNAPSHOT = "doctor-undo";
14
+ const UNDO_KEY = "doctor.undo";
15
+ var UndoRefusedError = class extends Error {};
16
+ /** Keeps the story as it stands, to put back after the one approved edit that is about to be applied. */
17
+ function keepBeforeEdit(deps, id) {
18
+ const dir = deps.sessionsDir();
19
+ deps.state.snapshot(dir, id, UNDO_SNAPSHOT);
20
+ const { metadata } = deps.state.openSession(dir, id);
21
+ metadata.setValue(UNDO_KEY, { turns: metadata.get().turns });
22
+ }
23
+ /**
24
+ * Puts the story back as it was before the last edit the doctor applied. The story is not taken back across a turn: what a later turn recorded
25
+ * and the conversation it went with would no longer match.
26
+ * @throws {UndoRefusedError} when nothing was kept, a turn was played or is playing since, or the edit was undone already.
27
+ */
28
+ async function undoLastEdit(deps, id) {
29
+ const dir = deps.sessionsDir();
30
+ const session = deps.state.openSession(dir, id);
31
+ const kept = session.metadata.getValue(UNDO_KEY);
32
+ if (kept === void 0 || !deps.state.snapshots(dir, id).includes("doctor-undo")) throw new UndoRefusedError("there is no edit of mine to undo: nothing was kept, or it was undone already");
33
+ if (deps.busy(id)) throw new UndoRefusedError("a turn is being played: undo after it has been delivered, and only if no turn is played after it");
34
+ if (session.metadata.get().turns !== kept.turns) throw new UndoRefusedError("a turn was played after the edit, so the story cannot be put back without losing it: mend what is wrong with a new edit instead");
35
+ await deps.halt(id);
36
+ deps.state.restore(dir, id, UNDO_SNAPSHOT);
37
+ deps.state.removeSnapshot(dir, id, UNDO_SNAPSHOT);
38
+ }
39
+ //#endregion
9
40
  //#region src/doctor.ts
10
41
  const name = "@dsh-agentic-roleplay/core/doctor";
11
42
  const inject = [
12
43
  "roleplayState",
13
44
  "roleplayRoot",
14
45
  "roleplayPrompts",
46
+ "roleplayOrchestration",
15
47
  "tools",
16
- "systemPrompt"
48
+ "systemPrompt",
49
+ "agents"
17
50
  ];
18
51
  const DOCTOR_TOOL = "edit_records";
52
+ const UNDO_TOOL = "undo_last_edit";
19
53
  const SHOWN_EDIT = 700;
20
54
  /** What the person is asked to approve: the edit, as it will be applied. */
21
55
  function doctorApproval(exec) {
22
- if (exec.name !== DOCTOR_TOOL || exec.agent === void 0 || doctorSessionOf(exec.agent.session.id) === void 0) return void 0;
56
+ if (exec.agent === void 0 || doctorSessionOf(exec.agent.session.id) === void 0) return void 0;
57
+ if (exec.name === UNDO_TOOL) return {
58
+ kind: "ask",
59
+ reason: "put the story back as it was before my last edit",
60
+ displayReason: {
61
+ en: "Put the story back as it was before the last edit?",
62
+ zh: "把故事恢复到上一次修改之前?"
63
+ }
64
+ };
65
+ if (exec.name !== DOCTOR_TOOL) return void 0;
23
66
  const { turn: _turn, ...edit } = exec.arguments;
24
67
  if (Object.keys(edit).length === 0) return {
25
68
  kind: "deny",
@@ -51,7 +94,17 @@ function apply(ctx) {
51
94
  };
52
95
  };
53
96
  ctx.effect(() => ctx.roleplayState.bind(resolve), "roleplay: session doctor reads");
54
- for (const tool of createTools(resolve, { write: true }).filter((candidate) => candidate.name === DOCTOR_TOOL)) ctx.tools.register(inTurn(tool, resolve));
97
+ const undo = {
98
+ state: ctx.roleplayState,
99
+ sessionsDir,
100
+ busy: (id) => {
101
+ const agent = ctx.agents.get(SessionId(chatSessionId(id)));
102
+ return agent !== void 0 && agent.status !== "idle";
103
+ },
104
+ halt: (id) => ctx.roleplayOrchestration.halt(chatSessionId(id))
105
+ };
106
+ for (const tool of createTools(resolve, { write: true }).filter((candidate) => candidate.name === DOCTOR_TOOL)) ctx.tools.register(inTurn(tool, resolve, (id) => keepBeforeEdit(undo, id)));
107
+ ctx.tools.register(undoTool(undo));
55
108
  ctx.on("tools/pre-execute", async (exec, next) => doctorApproval(exec) ?? await next());
56
109
  ctx.on("agent/created", ({ agent }) => {
57
110
  if (doctorSessionOf(agent.session.id) !== void 0 && agent.session.header.origin !== "subagent") externalToolLimit(agent, externalTools(agent.ctx.tools).map((tool) => tool.name));
@@ -77,11 +130,13 @@ function apply(ctx) {
77
130
  });
78
131
  }
79
132
  /** The edit is written at the turn the story is at (the first, in a story with none played), whatever turn the model put in it. */
80
- function inTurn(tool, resolve) {
133
+ function inTurn(tool, resolve, keep) {
81
134
  return {
82
135
  ...tool,
83
136
  async execute(args, exec) {
84
137
  const link = exec.agent === void 0 ? void 0 : resolve(exec.agent.session.id);
138
+ const story = exec.agent === void 0 ? void 0 : doctorSessionOf(exec.agent.session.id);
139
+ if (story !== void 0) keep(story);
85
140
  return await tool.execute(link === void 0 ? args : {
86
141
  ...args,
87
142
  turn: Math.max(1, link.turn)
@@ -89,6 +144,27 @@ function inTurn(tool, resolve) {
89
144
  }
90
145
  };
91
146
  }
147
+ function undoTool(deps) {
148
+ return defineTool({
149
+ name: UNDO_TOOL,
150
+ description: "Put the story back as it was before the last edit you applied, when that edit turned out wrong. Only possible while no turn has been played since, and only once: the player is asked first.",
151
+ parameters: {},
152
+ output: {
153
+ schema: { type: "json" },
154
+ render: (_args, value) => [{
155
+ type: "text",
156
+ text: value.text
157
+ }]
158
+ },
159
+ isConcurrencySafe: () => false,
160
+ async execute(_args, exec) {
161
+ const story = exec.agent === void 0 ? void 0 : doctorSessionOf(exec.agent.session.id);
162
+ if (story === void 0) throw new Error("this tool is for a session doctor chat");
163
+ await undoLastEdit(deps, story);
164
+ return { text: "The story is as it was before the last edit. Read the records again before saying what stands." };
165
+ }
166
+ });
167
+ }
92
168
  //#endregion
93
169
  export { apply, doctorApproval, inject, name };
94
170
 
@@ -1,4 +1,4 @@
1
- import { S as mapLimit, _ as readImageFileMetadata, c as LIBRARY_FOLDER, g as mediaTypeOf, v as sidecarOf, y as writeImageFileMetadata } from "./generator-B6FxlKOV.js";
1
+ import { f as mediaTypeOf, h as writeImageFileMetadata, m as sidecarOf, p as readImageFileMetadata, r as LIBRARY_FOLDER, v as mapLimit } from "./library-9JB9zw5a.js";
2
2
  import { join, sep } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { lstat, mkdir, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
@@ -192,4 +192,4 @@ async function updateImage(sessionFolder, path, update) {
192
192
  //#endregion
193
193
  export { updateImage as i, galleryFile as n, listGallery as r, describeGalleryImage as t };
194
194
 
195
- //# sourceMappingURL=gallery-CtFDL22W.js.map
195
+ //# sourceMappingURL=gallery-DIEgETzU.js.map
@@ -0,0 +1,145 @@
1
+ import { c as referenceImagePath, l as sceneImagePath, u as writeImage } from "./library-9JB9zw5a.js";
2
+ //#region src/host/images/generator.ts
3
+ const unique = (values) => [...new Set(values.map((value) => value.trim()).filter((value) => value !== ""))];
4
+ /** What a reference image shows: the subject and its stable look. */
5
+ function referenceDescription(request) {
6
+ return `${request.subject.name} (${request.subject.kind}): ${request.identity.description}`.trim();
7
+ }
8
+ /** What a scene image shows: the established moment, then how each subject looks in it. */
9
+ function transientDescription(request) {
10
+ return [request.scene.trim(), ...request.subjects.map((subject) => subject.transient.trim() === "" ? void 0 : `${subject.name}: ${subject.transient.trim()}`)].filter((part) => part !== void 0 && part !== "").join("\n");
11
+ }
12
+ function lines(parts) {
13
+ return parts.filter((part) => part !== void 0 && part.trim() !== "").join("\n");
14
+ }
15
+ function referencePrompt(request) {
16
+ const { subject, identity } = request;
17
+ return lines([
18
+ request.artDirection,
19
+ `Create a canonical reference image of the ${subject.kind} ${subject.name}.`,
20
+ identity.description,
21
+ identity.tags.length === 0 ? void 0 : `Stable visual traits: ${identity.tags.join(", ")}.`,
22
+ "Show the subject clearly and neutrally. Do not add story events or temporary changes.",
23
+ identity.negativeTags.length === 0 ? void 0 : `Avoid: ${identity.negativeTags.join(", ")}.`
24
+ ]);
25
+ }
26
+ function transientPrompt(request) {
27
+ return lines([
28
+ request.artDirection,
29
+ `Illustrate this established story moment: ${request.scene}`,
30
+ ...request.subjects.map((subject) => lines([
31
+ `${subject.kind} ${subject.name}: ${subject.identity.description}`,
32
+ subject.identity.tags.length === 0 ? void 0 : `Stable visual traits: ${subject.identity.tags.join(", ")}.`,
33
+ subject.transient === "" ? void 0 : `Current visible state: ${subject.transient}`
34
+ ])),
35
+ "Preserve every canonical identity. Depict only the stated subjects, state and action; do not invent story facts.",
36
+ request.subjects.flatMap((subject) => subject.identity.negativeTags).length === 0 ? void 0 : `Avoid: ${[...new Set(request.subjects.flatMap((subject) => subject.identity.negativeTags))].join(", ")}.`
37
+ ]);
38
+ }
39
+ async function firstPng(service, prompt, options = {}) {
40
+ const result = await service.generate(prompt, {
41
+ count: 1,
42
+ ...options
43
+ });
44
+ const image = result.images[0];
45
+ if (image === void 0) throw new Error(`${service.provider} returned no image`);
46
+ if (image.mediaType !== "image/png") throw new Error(`${service.provider} returned ${image.mediaType}; roleplay image storage currently requires PNG`);
47
+ return {
48
+ data: new Uint8Array(await image.data.arrayBuffer()),
49
+ model: result.model,
50
+ ...image.revisedPrompt === void 0 ? {} : { revisedPrompt: image.revisedPrompt }
51
+ };
52
+ }
53
+ /** Generates the stable reference.png of one entity. It is intentionally not registered in the live roleplay loop yet. */
54
+ async function generateReferenceImage(service, request) {
55
+ const prompt = referencePrompt(request);
56
+ const image = await firstPng(service, prompt, request.signal === void 0 ? {} : { signal: request.signal });
57
+ request.signal?.throwIfAborted();
58
+ const path = referenceImagePath(request.root, request.subject);
59
+ const metadata = {
60
+ schema: "dsh-roleplay-image/v3",
61
+ purpose: "reference",
62
+ origin: "generated",
63
+ reusable: true,
64
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
65
+ prompt,
66
+ description: referenceDescription(request),
67
+ tags: unique([request.subject.name, ...request.identity.tags]),
68
+ ...image.revisedPrompt === void 0 ? {} : { revisedPrompt: image.revisedPrompt },
69
+ provider: service.provider,
70
+ model: image.model,
71
+ subjects: [{
72
+ ...request.subject,
73
+ identityVersion: request.identity.version
74
+ }]
75
+ };
76
+ await writeImage(path, image.data, metadata, { replace: true });
77
+ return path;
78
+ }
79
+ const PNG_SIGNATURE = [
80
+ 137,
81
+ 80,
82
+ 78,
83
+ 71,
84
+ 13,
85
+ 10,
86
+ 26,
87
+ 10
88
+ ];
89
+ /** Takes a picture the person brought as the stable reference.png of one entity, replacing the one there. Only PNG is stored, so any other format is refused. */
90
+ async function uploadReferenceImage(request) {
91
+ if (request.png.length < PNG_SIGNATURE.length || PNG_SIGNATURE.some((byte, index) => request.png[index] !== byte)) throw new Error("the portrait must be a PNG picture: convert it first");
92
+ const path = referenceImagePath(request.root, request.subject);
93
+ const metadata = {
94
+ schema: "dsh-roleplay-image/v3",
95
+ purpose: "reference",
96
+ origin: "uploaded",
97
+ reusable: true,
98
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
99
+ description: `${request.subject.name}, a picture brought by the author.`,
100
+ tags: [request.subject.name],
101
+ ...request.originalName === void 0 ? {} : { originalName: request.originalName },
102
+ subjects: [request.subject]
103
+ };
104
+ await writeImage(path, request.png, metadata, { replace: true });
105
+ return path;
106
+ }
107
+ /** Generates one immutable scene image for a timeline node. It is intentionally not registered in the live roleplay loop yet. */
108
+ async function generateTransientImage(service, request) {
109
+ if (request.subjects.length === 0) throw new Error("a transient image needs at least one subject");
110
+ const prompt = transientPrompt(request);
111
+ const image = await firstPng(service, prompt, {
112
+ ...request.references === void 0 ? {} : { references: request.references },
113
+ ...request.signal === void 0 ? {} : { signal: request.signal }
114
+ });
115
+ request.signal?.throwIfAborted();
116
+ const path = sceneImagePath(request.root, request.timelineNode, request.serial);
117
+ const metadata = {
118
+ schema: "dsh-roleplay-image/v3",
119
+ purpose: "transient",
120
+ origin: "generated",
121
+ reusable: request.reusable === true,
122
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
123
+ prompt,
124
+ description: transientDescription(request),
125
+ tags: unique(request.subjects.flatMap((subject) => [subject.name, ...subject.identity.tags])),
126
+ ...image.revisedPrompt === void 0 ? {} : { revisedPrompt: image.revisedPrompt },
127
+ provider: service.provider,
128
+ model: image.model,
129
+ subjects: request.subjects.map(({ identity, transient: _transient, ...subject }) => ({
130
+ ...subject,
131
+ identityVersion: identity.version
132
+ })),
133
+ source: {
134
+ turn: request.turn,
135
+ timelineNode: request.timelineNode,
136
+ ...request.segment === void 0 ? {} : { segment: request.segment }
137
+ }
138
+ };
139
+ await writeImage(path, image.data, metadata);
140
+ return path;
141
+ }
142
+ //#endregion
143
+ export { uploadReferenceImage as a, transientPrompt as i, generateTransientImage as n, referencePrompt as r, generateReferenceImage as t };
144
+
145
+ //# sourceMappingURL=generator-DJ48HxPI.js.map
@@ -1,8 +1,9 @@
1
1
  import { r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
2
  import { a as WORLD_RULES_KEY, o as rulesOf } from "./settings-CA6icLL_.js";
3
- import { C as shippedText } from "./language-DWVwi1R7.js";
4
- import { B as languageOf, C as addToNote, D as readNotes, E as putNote, F as readTime, I as skipTime, L as zoneOf, N as describeWhen, O as observeAsPlayer, P as endRound, S as toolEnabled, V as translator, g as plotAuthorNeeded, h as pacingAdvice, i as keepRunDetail, j as beginTurn, k as observeSurroundings, m as describePacingAdvice, r as forgetRunDetails, s as recordActivity, t as deliverNow, u as externalWithheld, w as clearNotes, x as parseOoc } from "./deliver-De62a8i9.js";
3
+ import { y as shippedText } from "./load-Clkl0T7C.js";
4
+ import { A as observeAsPlayer, C as parseOoc, E as clearNotes, F as describeWhen, H as languageOf, I as endRound, L as readTime, N as beginTurn, O as putNote, R as skipTime, T as addToNote, U as translator, _ as pacingAdvice, a as forgetRunDetails, f as externalWithheld, g as describePacingAdvice, j as observeSurroundings, k as readNotes, l as recordActivity, o as keepRunDetail, r as addUsage, t as deliverNow, v as plotAuthorNeeded, w as toolEnabled, z as zoneOf } from "./deliver-Cl6bjp7g.js";
5
5
  import { a as liveSettings } from "./narration-DK2kiIjE.js";
6
+ import { o as tokensOf } from "./child-CFjnaTZt.js";
6
7
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
7
8
  import { ENGAGEMENT_GRACE, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, describeDuration, describeInstant, describeValue, inAudience, itemKey, locationKey, nextOccurrence, occurrenceAt, parseInstant, planItemChange, planVariableChange, rollPlain, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
8
9
  //#region src/host/triggers/judged.ts
@@ -138,6 +139,8 @@ function noteStore(session, settings, clock) {
138
139
  //#region src/host/clock/agenda.ts
139
140
  const CURSOR = "agenda.cursor";
140
141
  const ASKED = "agenda.asked";
142
+ /** Characters on their way to the place their day has them at, by character id: they get there when the way has taken as long as it takes. */
143
+ const TRAVEL = "agenda.travel";
141
144
  /** At most this many characters are asked to be given a day at a time, so that it never floods the world author. */
142
145
  const MAX_ASKED = 3;
143
146
  /** How far ahead the characters are told about what comes next in their day. */
@@ -159,6 +162,25 @@ function catchUpRoutines(session, zone, now, turn, ask) {
159
162
  const player = session.characters.list().find((character) => character.control === "player");
160
163
  const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
161
164
  const moves = [];
165
+ const stored = session.metadata.getValue(TRAVEL);
166
+ const journeys = typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
167
+ const arrive = (character, target) => {
168
+ if (target.locationId !== void 0) {
169
+ session.move(character.id, {
170
+ to: target.locationId,
171
+ ignoreExits: true,
172
+ ...target.position === void 0 ? {} : { position: target.position },
173
+ ...target.featureKey === void 0 ? {} : { featureKey: target.featureKey }
174
+ });
175
+ moves.push({
176
+ character: keyOfCharacter$1(character),
177
+ name: character.name,
178
+ to: session.locations.get(target.locationId)?.name ?? String(target.locationId),
179
+ activity: target.activity
180
+ });
181
+ }
182
+ if (session.characterStates.get(character.id)?.activity !== target.activity) session.characterStates.update(character.id, { activity: target.activity });
183
+ };
162
184
  const alreadyAsked = new Set(Array.isArray(session.metadata.getValue(ASKED)) ? session.metadata.getValue(ASKED) : []);
163
185
  const asked = [];
164
186
  for (const character of session.characters.list()) {
@@ -181,27 +203,38 @@ function catchUpRoutines(session, zone, now, turn, ask) {
181
203
  }
182
204
  if (!away) continue;
183
205
  const current = occurrenceAt(window, now, zone);
206
+ const journey = journeys[characterId];
207
+ if (journey !== void 0) {
208
+ const same = current !== void 0 && current.window.id === journey.windowId && current.startsAt === journey.startsAt;
209
+ if (same && now < journey.arriveAt) continue;
210
+ delete journeys[characterId];
211
+ if (same) {
212
+ arrive(character, current.window);
213
+ continue;
214
+ }
215
+ }
184
216
  if (current === void 0) continue;
185
217
  const before = cursor === void 0 ? void 0 : occurrenceAt(window, cursor, zone);
186
218
  if (before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
187
219
  const target = current.window;
188
220
  if (target.locationId !== void 0 && (here?.locationId !== target.locationId || target.position !== void 0 && here.position !== target.position)) {
189
- session.move(characterId, {
190
- to: target.locationId,
191
- ignoreExits: true,
192
- ...target.position === void 0 ? {} : { position: target.position },
193
- ...target.featureKey === void 0 ? {} : { featureKey: target.featureKey }
194
- });
195
- moves.push({
196
- character: keyOfCharacter$1(character),
197
- name: character.name,
198
- to: session.locations.get(target.locationId)?.name ?? String(target.locationId),
199
- activity: target.activity
200
- });
201
- }
202
- if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
221
+ const way = here?.locationId === target.locationId ? void 0 : session.planMove(characterId, { to: target.locationId });
222
+ const seconds = way?.ok === true ? way.plan.travelSeconds : void 0;
223
+ if (seconds !== void 0 && current.startsAt + seconds * 1e3 > now) {
224
+ journeys[characterId] = {
225
+ windowId: target.id,
226
+ startsAt: current.startsAt,
227
+ arriveAt: current.startsAt + seconds * 1e3
228
+ };
229
+ const text = `on the way to ${session.locations.get(target.locationId)?.name ?? String(target.locationId)}, for "${target.activity}"`;
230
+ if (session.characterStates.get(characterId)?.activity !== text) session.characterStates.update(characterId, { activity: text });
231
+ continue;
232
+ }
233
+ arrive(character, target);
234
+ } else if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
203
235
  }
204
236
  session.metadata.setValue(CURSOR, now);
237
+ session.metadata.setValue(TRAVEL, journeys);
205
238
  if (asked.length > 0) session.metadata.setValue(ASKED, [...alreadyAsked, ...asked]);
206
239
  return moves;
207
240
  });
@@ -737,6 +770,10 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
737
770
  recordActivity: (entry, detail) => {
738
771
  if (detail !== void 0 && entry.run !== void 0) keepRunDetail(folder, entry.run, detail);
739
772
  forgetRunDetails(folder, recordActivity(session, entry));
773
+ if (entry.turn !== void 0 && entry.tokens !== void 0) addUsage(session, entry.turn, "helper", entry.tokens);
774
+ },
775
+ recordUsage: (turn, tokens) => {
776
+ addUsage(session, turn, "master", tokens);
740
777
  },
741
778
  notes: () => readNotes(session),
742
779
  clearNotes: () => {
@@ -893,6 +930,10 @@ function installHooks(ctx, deps) {
893
930
  ctx.on("session/event", (session, event) => {
894
931
  if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
895
932
  timelines.ended(session.id, session, event.seq);
933
+ const events = session.snapshotEvents();
934
+ const began = events.findLastIndex((entry) => entry.type === "turn/start");
935
+ const start = began === -1 ? void 0 : events[began];
936
+ if (start?.type === "turn/start") stores(session.id)?.recordUsage?.(start.data.turn, tokensOf(events.slice(began)));
896
937
  });
897
938
  ctx.on("agent/created", async ({ agent }) => {
898
939
  const { header } = agent.session;
@@ -1016,4 +1057,4 @@ function installHooks(ctx, deps) {
1016
1057
  //#endregion
1017
1058
  export { writeVerdicts as a, readVerdicts as i, installHooks as n, storesOf as r, externalToolLimit as t };
1018
1059
 
1019
- //# sourceMappingURL=hooks-Ka22sFNy.js.map
1060
+ //# sourceMappingURL=hooks-DdO_tNhu.js.map
package/lib/images.js CHANGED
@@ -1,4 +1,5 @@
1
- import { b as readPngMetadata, d as nextSceneSerial, f as readImageMetadata, i as transientPrompt, l as entityImageDirectory, m as sceneImagePath, n as generateTransientImage, o as addToLibrary, p as referenceImagePath, r as referencePrompt, t as generateReferenceImage, u as inheritImages, x as withPngMetadata } from "./generator-B6FxlKOV.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-CtFDL22W.js";
3
- 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-Dt21K96b.js";
1
+ import { _ as withPngMetadata, a as inheritImages, c as referenceImagePath, g as readPngMetadata, i as entityImageDirectory, l as sceneImagePath, o as nextSceneSerial, s as readImageMetadata, t as addToLibrary } from "./library-9JB9zw5a.js";
2
+ import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-DJ48HxPI.js";
3
+ import { i as updateImage, r as listGallery } from "./gallery-DIEgETzU.js";
4
+ 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-DnNEG_Mn.js";
4
5
  export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };