@dsh-agentic-roleplay/core 0.1.0 → 0.1.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 (55) hide show
  1. package/lib/{notes-CJzbN_-E.js → activity-BbqFG9-3.js} +35 -9
  2. package/lib/authoring.js +3 -3
  3. package/lib/client.js +880 -372
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +1 -1
  6. package/lib/{documents-BBq88wXP.js → documents-ZVoUTnD2.js} +54 -33
  7. package/lib/{gallery-CjG9_4Sz.js → gallery-KGCdeCnM.js} +2 -2
  8. package/lib/{generator-pxZS-pu-.js → generator-NYnNdpWb.js} +100 -9
  9. package/lib/images.js +3 -3
  10. package/lib/index.js +220 -15
  11. package/lib/{narration-tYy6Rkfr.js → narration-DcnCqA1l.js} +20 -3
  12. package/lib/orchestration.js +510 -82
  13. package/lib/{presenter-agent-DbZALurg.js → presenter-agent-7j1c7QEz.js} +3 -3
  14. package/lib/{worlds-Bj-EGS_i.js → worlds-DYgjdH8O.js} +28 -2
  15. package/package.json +3 -2
  16. package/prompts/en/roleplay/faction-strategist.md +5 -0
  17. package/prompts/en/roleplay/trigger-judge.md +3 -0
  18. package/prompts/zh/roleplay/faction-strategist.md +5 -0
  19. package/prompts/zh/roleplay/trigger-judge.md +3 -0
  20. package/starter-worlds/blackwater-observatory/characters/arthur-moore/character.json +65 -0
  21. package/starter-worlds/blackwater-observatory/characters/clara-whitlock/character.json +87 -0
  22. package/starter-worlds/blackwater-observatory/characters/eleanor-graves/character.json +80 -0
  23. package/starter-worlds/blackwater-observatory/characters/marcus-reed/character.json +73 -0
  24. package/starter-worlds/blackwater-observatory/items/anonymous-letter/item.json +9 -0
  25. package/starter-worlds/blackwater-observatory/items/brass-laboratory-key/item.json +10 -0
  26. package/starter-worlds/blackwater-observatory/items/claras-gossip-notebook/item.json +9 -0
  27. package/starter-worlds/blackwater-observatory/items/harlans-notebook/item.json +10 -0
  28. package/starter-worlds/blackwater-observatory/items/investigators-coat/item.json +10 -0
  29. package/starter-worlds/blackwater-observatory/items/investigators-notebook/item.json +9 -0
  30. package/starter-worlds/blackwater-observatory/items/locked-filing-cabinet/item.json +10 -0
  31. package/starter-worlds/blackwater-observatory/items/marcus-calibration-notes/item.json +9 -0
  32. package/starter-worlds/blackwater-observatory/items/mayors-administrative-seal/item.json +9 -0
  33. package/starter-worlds/blackwater-observatory/items/municipal-lockbox/item.json +10 -0
  34. package/starter-worlds/blackwater-observatory/items/pocket-revolver/item.json +10 -0
  35. package/starter-worlds/blackwater-observatory/items/room-7-cash-receipt/item.json +9 -0
  36. package/starter-worlds/blackwater-observatory/items/rusting-mine-cart/item.json +10 -0
  37. package/starter-worlds/blackwater-observatory/items/signal-recording-strip/item.json +9 -0
  38. package/starter-worlds/blackwater-observatory/items/silver-pocket-watch/item.json +9 -0
  39. package/starter-worlds/blackwater-observatory/items/survey-archive-cabinet/item.json +10 -0
  40. package/starter-worlds/blackwater-observatory/items/surveyors-map/item.json +10 -0
  41. package/starter-worlds/blackwater-observatory/items/unknown-visitors-note-fragment/item.json +10 -0
  42. package/starter-worlds/blackwater-observatory/locations/blackwater-ridge/location.json +5 -0
  43. package/starter-worlds/blackwater-observatory/locations/iron-stag-bar/location.json +30 -0
  44. package/starter-worlds/blackwater-observatory/locations/iron-stag-room-7/location.json +18 -0
  45. package/starter-worlds/blackwater-observatory/locations/north-forest-cabin/location.json +18 -0
  46. package/starter-worlds/blackwater-observatory/locations/observatory-directors-office/location.json +20 -0
  47. package/starter-worlds/blackwater-observatory/locations/observatory-telescope-chamber/location.json +25 -0
  48. package/starter-worlds/blackwater-observatory/locations/old-mine-entrance/location.json +27 -0
  49. package/starter-worlds/blackwater-observatory/locations/old-mine-main-tunnel/location.json +13 -0
  50. package/starter-worlds/blackwater-observatory/locations/town-hall-mayors-office/location.json +25 -0
  51. package/starter-worlds/blackwater-observatory/locations/town-hall-records-room/location.json +13 -0
  52. package/starter-worlds/blackwater-observatory/locations/town-square/location.json +30 -0
  53. package/starter-worlds/blackwater-observatory/triggers.json +20 -0
  54. package/starter-worlds/blackwater-observatory/variables.json +39 -0
  55. package/starter-worlds/blackwater-observatory/world.json +27 -0
package/lib/compaction.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as roleplaySessionOf } from "./chat-AKrVcWIC.js";
2
- import { a as liveSettings, t as decodeOutput } from "./narration-tYy6Rkfr.js";
2
+ import { a as liveSettings, t as decodeOutput } from "./narration-DcnCqA1l.js";
3
3
  import { t as promptFor } from "./access-C1nFQiyT.js";
4
4
  import { join } from "node:path";
5
5
  import { sessionFolder } from "@dsh-agentic-roleplay/state";
@@ -1,6 +1,6 @@
1
+ import { D as INTENT_STATUSES, E as INTENT_HORIZONS, O as INTENT_TYPES, S as InvalidWorldError, _ as shippedLanguages, a as plotReferenceProblems, c as Reader, g as promptProblem, h as listFiles, i as parsePlotsFile, l as formatIssue, m as languageOf, n as PLOTS_FILE_NAME, o as readDocument, r as loadPlots, s as errorMessage, t as API_PREFIX, u as PROMPTS_FOLDER, v as shippedPromptsDirectory } from "./worlds-DYgjdH8O.js";
1
2
  import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
2
- import { S as InvalidWorldError, _ as shippedLanguages, a as plotReferenceProblems, c as Reader, g as promptProblem, h as listFiles, i as parsePlotsFile, l as formatIssue, m as languageOf, n as PLOTS_FILE_NAME, o as readDocument, r as loadPlots, s as errorMessage, t as API_PREFIX, u as PROMPTS_FOLDER, v as shippedPromptsDirectory } from "./worlds-Bj-EGS_i.js";
3
- import { C as slug, S as norm, a as addToLibrary, f as referenceImagePath, m as MEDIA_TYPES, o as imageExtensionOf, t as generateReferenceImage, v as writeImageFileMetadata, w as uniqueKey, x as mapLimit } from "./generator-pxZS-pu-.js";
3
+ import { C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-NYnNdpWb.js";
4
4
  import { basename, dirname, join } from "node:path";
5
5
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
6
6
  import { createHash, randomUUID } from "node:crypto";
@@ -19,32 +19,6 @@ const CHARACTER_TIERS = [
19
19
  ];
20
20
  const CHARACTER_KINDS = ["person", "group"];
21
21
  //#endregion
22
- //#region ../dsh-roleplay-model/src/intent.ts
23
- const INTENT_TYPES = [
24
- "need",
25
- "obligation",
26
- "quest",
27
- "agenda",
28
- "aspiration",
29
- "relationship",
30
- "habit",
31
- "reaction"
32
- ];
33
- const INTENT_STATUSES = [
34
- "active",
35
- "paused",
36
- "completed",
37
- "failed",
38
- "abandoned"
39
- ];
40
- const INTENT_HORIZONS = [
41
- "immediate",
42
- "short",
43
- "day",
44
- "long",
45
- "open_ended"
46
- ];
47
- //#endregion
48
22
  //#region ../dsh-roleplay-model/src/item.ts
49
23
  /** Whether a container can be got into. */
50
24
  const CONTAINER_STATES = [
@@ -394,7 +368,8 @@ function parseEntityEdit(value, kind) {
394
368
  "name",
395
369
  "description",
396
370
  "features",
397
- "visualIdentity"
371
+ "visualIdentity",
372
+ "parent"
398
373
  ] : [
399
374
  "name",
400
375
  "description",
@@ -403,8 +378,16 @@ function parseEntityEdit(value, kind) {
403
378
  "notable",
404
379
  "hidden",
405
380
  "containerState",
406
- "visualIdentity"
381
+ "visualIdentity",
382
+ "owner"
407
383
  ];
384
+ const link = kind === "place" ? "parent" : "owner";
385
+ if (link in input) {
386
+ const target = input[link];
387
+ if (target === null) edit[link] = null;
388
+ else if (typeof target !== "string") problems.push(`${link} must be a key or null`);
389
+ else edit[link] = target.trim() === "" ? null : target.trim();
390
+ }
408
391
  for (const key of Object.keys(input)) if (!allowed.includes(key)) problems.push(`${key} is not something that can be edited`);
409
392
  for (const key of [
410
393
  "name",
@@ -724,7 +707,8 @@ const TEXT_FIELDS = [
724
707
  "authorName",
725
708
  "authorUrl",
726
709
  "timeZone",
727
- "startingTime"
710
+ "startingTime",
711
+ "version"
728
712
  ];
729
713
  const LIST_FIELDS = ["tags", "rules"];
730
714
  /** Reads a body that came from the browser; every field is checked and each problem is reported. */
@@ -758,6 +742,7 @@ function parseWorldInfoEdit(value) {
758
742
  edit["alternateOpenings"] = kept;
759
743
  }
760
744
  }
745
+ if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
761
746
  if (edit["name"] === "") problems.push("the world needs a name");
762
747
  if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
763
748
  if (problems.length > 0) throw new InvalidEditProblems(problems);
@@ -871,6 +856,10 @@ function parseWorldFile(text) {
871
856
  const description = reader.text("description");
872
857
  const tags = reader.object("metadata")?.strings("tags") ?? [];
873
858
  const author = readAuthor(reader.object("author"));
859
+ const rawVersion = reader.raw("version");
860
+ if (rawVersion !== void 0 && rawVersion !== null && typeof rawVersion !== "string" && typeof rawVersion !== "number") reader.fail("version", "must be text or a number");
861
+ const version = (typeof rawVersion === "string" || typeof rawVersion === "number" ? String(rawVersion).trim() : "") || void 0;
862
+ if (version !== void 0 && version.length > 40) reader.fail("version", `is longer than 40 characters`);
874
863
  const coverMediaId = reader.string("cover_media_id");
875
864
  const opening = readOpening(reader);
876
865
  const clock = readClock(reader);
@@ -890,6 +879,7 @@ function parseWorldFile(text) {
890
879
  description,
891
880
  tags,
892
881
  ...author === void 0 ? {} : { author },
882
+ ...version === void 0 ? {} : { version },
893
883
  ...coverMediaId === void 0 ? {} : { coverMediaId },
894
884
  ...opening === void 0 ? {} : { opening },
895
885
  ...clock === void 0 ? {} : { clock },
@@ -5512,6 +5502,12 @@ async function editEntityFile(world, directory, fileName, key, parse, mutate) {
5512
5502
  return await readWorldEditor(world);
5513
5503
  }
5514
5504
  async function editWorldPlace(world, key, edit) {
5505
+ if (edit.parent !== void 0 && edit.parent !== null) {
5506
+ const places = (await readWorldEditor(world)).places;
5507
+ if (!places.some((place) => place.key === edit.parent)) throw new InvalidEditProblems([`there is no place "${edit.parent}" to put it in`]);
5508
+ const parents = new Map(places.map((place) => [place.key, place.parent?.key]));
5509
+ for (let at = edit.parent; at !== void 0; at = parents.get(at)) if (at === key) throw new InvalidEditProblems(["a place cannot be inside itself or a place within it"]);
5510
+ }
5515
5511
  return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, key, parseLocationFile, (document) => {
5516
5512
  if (edit.name !== void 0) document["name"] = edit.name;
5517
5513
  if (edit.description !== void 0) document["description"] = edit.description;
@@ -5520,10 +5516,13 @@ async function editWorldPlace(world, key, edit) {
5520
5516
  name: feature.name,
5521
5517
  description: feature.description
5522
5518
  }));
5519
+ if (edit.parent === null) delete document["parent"];
5520
+ else if (edit.parent !== void 0) document["parent"] = edit.parent;
5523
5521
  setVisualIdentity(document, edit.visualIdentity);
5524
5522
  });
5525
5523
  }
5526
5524
  async function editWorldThing(world, key, edit) {
5525
+ if (edit.owner !== void 0 && edit.owner !== null && !(await readWorldEditor(world)).characters.some((character) => character.key === edit.owner)) throw new InvalidEditProblems([`there is no character "${edit.owner}" to own it`]);
5527
5526
  return await editEntityFile(world, ITEMS_DIR, ITEM_FILE_NAME, key, parseItemFile, (document) => {
5528
5527
  for (const field of [
5529
5528
  "name",
@@ -5534,6 +5533,8 @@ async function editWorldThing(world, key, edit) {
5534
5533
  "hidden"
5535
5534
  ]) if (edit[field] !== void 0) document[field] = edit[field];
5536
5535
  if (edit.containerState !== void 0) object(document, "container")["state"] = edit.containerState;
5536
+ if (edit.owner === null) delete document["owner"];
5537
+ else if (edit.owner !== void 0) document["owner"] = edit.owner;
5537
5538
  setVisualIdentity(document, edit.visualIdentity);
5538
5539
  });
5539
5540
  }
@@ -5770,6 +5771,26 @@ async function generateWorldCharacterPortrait(world, key, service) {
5770
5771
  });
5771
5772
  return await readWorldEditor(world);
5772
5773
  }
5774
+ /** The picture the author brought becomes the character's portrait. */
5775
+ async function uploadWorldCharacterPortrait(world, key, png, originalName) {
5776
+ const character = await characterOf(world, key);
5777
+ try {
5778
+ await uploadReferenceImage({
5779
+ root: world.directory,
5780
+ subject: {
5781
+ kind: "character",
5782
+ localId: character.id,
5783
+ name: character.name,
5784
+ ...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
5785
+ },
5786
+ png,
5787
+ ...originalName === void 0 ? {} : { originalName }
5788
+ });
5789
+ } catch (error) {
5790
+ throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
5791
+ }
5792
+ return await readWorldEditor(world);
5793
+ }
5773
5794
  /** Resolve a portrait through authored data so request parameters cannot select arbitrary files. */
5774
5795
  async function worldCharacterPortraitFile(world, key) {
5775
5796
  const character = await characterOf(world, key);
@@ -5902,6 +5923,6 @@ async function deleteAuthoredEntity(world, kind, key) {
5902
5923
  return destination;
5903
5924
  }
5904
5925
  //#endregion
5905
- export { CHARACTER_FILE_NAME as $, populateClock as A, loadLocations as B, finish as C, survey as D, markReady as E, populateLore as F, PROSE_PROMPTS as G, CHARACTERS_DIR as H, populateRoutines as I, readWorldPrompt as J, deleteWorldPrompt as K, populateTriggers as L, populateItems as M, populateKnowledge as N, loadValidatedWorld as O, populateLocations as P, variableProblems as Q, populateVariables as R, endReview as S, isReviewing as T, loadCharacters as U, loadItems as V, subfolders as W, VARIABLES_FILE_NAME as X, writeWorldPrompt as Y, parseVariablesFile as Z, replaceFile$1 as _, replaceAuthoredEntity as a, WORLD_FILE_NAME as at, authoringChatSessionId as b, editWorldLore as c, InvalidEditProblems as ct, editWorldPlots as d, parseLoreEdit as dt, parseCharacterFile as et, editWorldRelation as f, parsePlaceEdit as ft, readWorldEditor as g, parseImportCommand as gt, generateWorldCharacterPortrait as h, IMPORT_COMMAND as ht, readAuthoredEntityDocument as i, parseChoices as it, populateFactions as j, populateCharacters as k, editWorldNarrationVoice as l, parseCharacterEdit as lt, entityFolder as m, parseThingEdit as mt, createAuthoredEntity as n, ImportNotFoundError as nt, editWorldCharacter as o, parseWorldFile as ot, editWorldThing as p, parseRelationEdit as pt, listWorldPrompts as q, deleteAuthoredEntity as r, ImportStore as rt, editWorldFaction as s, parseWorldInfoEdit as st, AUTHORED_ENTITY_KINDS as t, IMPORT_FOLDER as tt, editWorldPlace as u, parseFactionEdit as ut, worldCharacterPortraitFile as v, importPhase as w, build as x, authoredWorldOf as y, routineProblems as z };
5926
+ export { variableProblems as $, populateCharacters as A, routineProblems as B, endReview as C, markReady as D, isReviewing as E, populateLocations as F, subfolders as G, loadItems as H, populateLore as I, listWorldPrompts as J, PROSE_PROMPTS as K, populateRoutines as L, populateFactions as M, populateItems as N, survey as O, populateKnowledge as P, parseVariablesFile as Q, populateTriggers as R, build as S, importPhase as T, CHARACTERS_DIR as U, loadLocations as V, loadCharacters as W, writeWorldPrompt as X, readWorldPrompt as Y, VARIABLES_FILE_NAME as Z, replaceFile$1 as _, parseImportCommand as _t, replaceAuthoredEntity as a, parseChoices as at, authoredWorldOf as b, editWorldLore as c, parseWorldInfoEdit as ct, editWorldPlots as d, parseFactionEdit as dt, CHARACTER_FILE_NAME as et, editWorldRelation as f, parseLoreEdit as ft, readWorldEditor as g, IMPORT_COMMAND as gt, generateWorldCharacterPortrait as h, parseThingEdit as ht, readAuthoredEntityDocument as i, ImportStore as it, populateClock as j, loadValidatedWorld as k, editWorldNarrationVoice as l, InvalidEditProblems as lt, entityFolder as m, parseRelationEdit as mt, createAuthoredEntity as n, IMPORT_FOLDER as nt, editWorldCharacter as o, WORLD_FILE_NAME as ot, editWorldThing as p, parsePlaceEdit as pt, deleteWorldPrompt as q, deleteAuthoredEntity as r, ImportNotFoundError as rt, editWorldFaction as s, parseWorldFile as st, AUTHORED_ENTITY_KINDS as t, parseCharacterFile as tt, editWorldPlace as u, parseCharacterEdit as ut, uploadWorldCharacterPortrait as v, finish as w, authoringChatSessionId as x, worldCharacterPortraitFile as y, populateVariables as z };
5906
5927
 
5907
- //# sourceMappingURL=documents-BBq88wXP.js.map
5928
+ //# sourceMappingURL=documents-ZVoUTnD2.js.map
@@ -1,4 +1,4 @@
1
- import { _ as sidecarOf, g as readImageFileMetadata, h as mediaTypeOf, s as LIBRARY_FOLDER, v as writeImageFileMetadata, x as mapLimit } from "./generator-pxZS-pu-.js";
1
+ import { S as mapLimit, _ as readImageFileMetadata, c as LIBRARY_FOLDER, g as mediaTypeOf, v as sidecarOf, y as writeImageFileMetadata } from "./generator-NYnNdpWb.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-CjG9_4Sz.js.map
195
+ //# sourceMappingURL=gallery-KGCdeCnM.js.map
@@ -27,10 +27,34 @@ function childSampling(settings, kind) {
27
27
  return {
28
28
  temperature: settings.sampling[kind],
29
29
  toolChoice: settings.sampling.tools,
30
- maxTokens: settings.sampling.maxTokens,
30
+ maxTokens: kind === "characters" || kind === "suggestions" ? settings.sampling.shortMaxTokens : settings.sampling.maxTokens,
31
31
  priority: kind === "characters" || kind === "authoring" ? "foreground" : "background"
32
32
  };
33
33
  }
34
+ /** What a caller passes as `trace`: files each run of a kind of helper under a label in the store's record of activity. */
35
+ function childTrace(store, kind, label) {
36
+ const model = store.settings().models[kind].trim();
37
+ return (run) => {
38
+ store.recordActivity({
39
+ at: Date.now(),
40
+ label,
41
+ model,
42
+ ms: run.ms,
43
+ calls: run.calls,
44
+ ...run.error === void 0 ? {} : { error: run.error.slice(0, 300) }
45
+ });
46
+ };
47
+ }
48
+ /** The `model` the settings give a kind of helper, to spread into its task; nothing when it runs on the chat's own model. */
49
+ function childModel(settings, kind) {
50
+ const named = settings.models[kind].trim();
51
+ if (named === "") return {};
52
+ const slash = named.indexOf("/");
53
+ return { model: {
54
+ provider: named.slice(0, slash),
55
+ model: named.slice(slash + 1)
56
+ } };
57
+ }
34
58
  const samplings = /* @__PURE__ */ new Map();
35
59
  /** The controls set for a running child, by its session id. */
36
60
  const childSamplingOf = (sessionId) => samplings.get(sessionId);
@@ -57,10 +81,46 @@ function childOptions(task) {
57
81
  };
58
82
  return Object.keys(options).length === 0 ? void 0 : options;
59
83
  }
84
+ /** A model that is cut off in the middle of its tool call leaves an unfinished argument no one can read; asking again usually gives a whole one. */
85
+ const isUnfinishedCall = (error) => error instanceof Error && /parse tool call arguments|unfinished tool call/i.test(error.message);
60
86
  async function runChild(task) {
87
+ for (let attempt = 1;; attempt += 1) {
88
+ const began = Date.now();
89
+ const stats = { calls: 0 };
90
+ try {
91
+ const result = await execute(task, stats);
92
+ task.trace?.({
93
+ ms: Date.now() - began,
94
+ calls: stats.calls
95
+ });
96
+ return result;
97
+ } catch (error) {
98
+ task.trace?.({
99
+ ms: Date.now() - began,
100
+ calls: stats.calls,
101
+ error: error instanceof Error ? error.message : String(error)
102
+ });
103
+ if (attempt >= 2 || task.signal.aborted || !isUnfinishedCall(error)) throw error;
104
+ }
105
+ }
106
+ }
107
+ /**
108
+ * The thinking level a child may be given on its model: the one asked for when the model offers it, none when it does not (a model chosen for a
109
+ * helper has its own levels, and one that lacks the level the chat asks for would refuse the request).
110
+ */
111
+ async function supportedEffort(task) {
112
+ const level = task.reasoningEffort;
113
+ if (level === void 0 || level === "" || task.model === void 0) return level;
114
+ try {
115
+ return (await task.parent.ctx.llm.resolveModelInfo(task.model.provider, task.model.model, task.signal)).reasoning?.efforts.some((effort) => effort.id === level) === true ? level : void 0;
116
+ } catch {
117
+ return level;
118
+ }
119
+ }
120
+ async function execute(task, stats) {
61
121
  const { parent, signal } = task;
122
+ const reasoningEffort = await supportedEffort(task);
62
123
  let submitted;
63
- let calls = 0;
64
124
  let reminders = 0;
65
125
  let stopped;
66
126
  let overran = false;
@@ -71,12 +131,12 @@ async function runChild(task) {
71
131
  const counted = (tool) => ({
72
132
  ...tool,
73
133
  execute: async (args, exec) => {
74
- calls += 1;
75
- if (calls > budget + OVERRUN) {
134
+ stats.calls += 1;
135
+ if (stats.calls > budget + OVERRUN) {
76
136
  overran = true;
77
137
  stopped?.();
78
138
  }
79
- if (calls > budget) throw new Error(`you have made ${budget} calls: submit your result now and say what is still missing`);
139
+ if (stats.calls > budget) throw new Error(`you have made ${budget} calls: submit your result now and say what is still missing`);
80
140
  const signature = JSON.stringify(args);
81
141
  const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
82
142
  if (repeats >= REPEATS_STOPPED) {
@@ -151,7 +211,10 @@ async function runChild(task) {
151
211
  sessionId,
152
212
  parentAgent: parent,
153
213
  meta: childSessionMeta(parent, depth, false),
154
- agentOptions: resolveChildAgentOptions(parent, childOptions(task), depth),
214
+ agentOptions: resolveChildAgentOptions(parent, childOptions({
215
+ ...task,
216
+ ...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
217
+ }), depth),
155
218
  signal,
156
219
  setup: (childCtx, child) => {
157
220
  appendDelegatedPolicyOverrides(child.session, inherited);
@@ -205,7 +268,7 @@ async function runChild(task) {
205
268
  const ended = handle.agent.session.snapshotEvents().findLast((event) => event.type === "turn/end");
206
269
  const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
207
270
  if (reason?.kind === "error") throw new Error(`the agent failed: ${reason.error.message}`);
208
- throw new Error(`the agent stopped without submitting a result (${calls} call(s))`);
271
+ throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
209
272
  }
210
273
  return submitted.value;
211
274
  }
@@ -614,6 +677,34 @@ async function generateReferenceImage(service, request) {
614
677
  await writeImage(path, image.data, metadata, { replace: true });
615
678
  return path;
616
679
  }
680
+ const PNG_SIGNATURE = [
681
+ 137,
682
+ 80,
683
+ 78,
684
+ 71,
685
+ 13,
686
+ 10,
687
+ 26,
688
+ 10
689
+ ];
690
+ /** 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. */
691
+ async function uploadReferenceImage(request) {
692
+ 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");
693
+ const path = referenceImagePath(request.root, request.subject);
694
+ const metadata = {
695
+ schema: "dsh-roleplay-image/v3",
696
+ purpose: "reference",
697
+ origin: "uploaded",
698
+ reusable: true,
699
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
700
+ description: `${request.subject.name}, a picture brought by the author.`,
701
+ tags: [request.subject.name],
702
+ ...request.originalName === void 0 ? {} : { originalName: request.originalName },
703
+ subjects: [request.subject]
704
+ };
705
+ await writeImage(path, request.png, metadata, { replace: true });
706
+ return path;
707
+ }
617
708
  /** Generates one immutable scene image for a timeline node. It is intentionally not registered in the live roleplay loop yet. */
618
709
  async function generateTransientImage(service, request) {
619
710
  if (request.subjects.length === 0) throw new Error("a transient image needs at least one subject");
@@ -650,6 +741,6 @@ async function generateTransientImage(service, request) {
650
741
  return path;
651
742
  }
652
743
  //#endregion
653
- export { slug as C, runChild as D, childSamplingOf as E, norm as S, childSampling as T, sidecarOf as _, addToLibrary as a, withPngMetadata as b, entityImageDirectory as c, readImageMetadata as d, referenceImagePath as f, readImageFileMetadata as g, mediaTypeOf as h, transientPrompt as i, inheritImages as l, MEDIA_TYPES as m, generateTransientImage as n, imageExtensionOf as o, sceneImagePath as p, referencePrompt as r, LIBRARY_FOLDER as s, generateReferenceImage as t, nextSceneSerial as u, writeImageFileMetadata as v, uniqueKey as w, mapLimit as x, readPngMetadata as y };
744
+ export { runChild as A, norm as C, childSampling as D, childModel as E, childSamplingOf as O, mapLimit as S, uniqueKey as T, readImageFileMetadata as _, uploadReferenceImage as a, readPngMetadata as b, LIBRARY_FOLDER as c, nextSceneSerial as d, readImageMetadata as f, mediaTypeOf as g, MEDIA_TYPES as h, transientPrompt as i, childTrace as k, entityImageDirectory as l, sceneImagePath as m, generateTransientImage as n, addToLibrary as o, referenceImagePath as p, referencePrompt as r, imageExtensionOf as s, generateReferenceImage as t, inheritImages as u, sidecarOf as v, slug as w, withPngMetadata as x, writeImageFileMetadata as y };
654
745
 
655
- //# sourceMappingURL=generator-pxZS-pu-.js.map
746
+ //# sourceMappingURL=generator-NYnNdpWb.js.map
package/lib/images.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as addToLibrary, b as withPngMetadata, c as entityImageDirectory, d as readImageMetadata, f as referenceImagePath, i as transientPrompt, l as inheritImages, n as generateTransientImage, p as sceneImagePath, r as referencePrompt, t as generateReferenceImage, u as nextSceneSerial, y as readPngMetadata } from "./generator-pxZS-pu-.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-CjG9_4Sz.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-DbZALurg.js";
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-NYnNdpWb.js";
2
+ import { i as updateImage, r as listGallery } from "./gallery-KGCdeCnM.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-7j1c7QEz.js";
4
4
  export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };