@dsh-agentic-roleplay/core 0.1.0 → 0.2.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 (80) hide show
  1. package/README.md +1 -1
  2. package/lib/{notes-CJzbN_-E.js → activity-t7OBgHlc.js} +267 -47
  3. package/lib/authoring.js +295 -14
  4. package/lib/client.js +2599 -648
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/{documents-BBq88wXP.js → documents-Bu5uYRZB.js} +54 -33
  8. package/lib/{gallery-CjG9_4Sz.js → gallery-DUeBMHQX.js} +2 -2
  9. package/lib/{generator-pxZS-pu-.js → generator-HPifO3Kk.js} +211 -15
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +849 -20
  12. package/lib/{narration-tYy6Rkfr.js → narration-BRyHU0H2.js} +28 -5
  13. package/lib/orchestration.js +803 -233
  14. package/lib/packs-ByP1J-zj.js +1334 -0
  15. package/lib/{presenter-agent-DbZALurg.js → presenter-agent-G43ODV8I.js} +3 -3
  16. package/package.json +5 -3
  17. package/prompts/en/roleplay/ask-answerer.md +3 -0
  18. package/prompts/en/roleplay/ask-question.md +2 -0
  19. package/prompts/en/roleplay/character-decide.md +1 -1
  20. package/prompts/en/roleplay/character-lookup.md +1 -1
  21. package/prompts/en/roleplay/faction-strategist.md +5 -0
  22. package/prompts/en/roleplay/game-master.md +5 -1
  23. package/prompts/en/roleplay/ooc-empty.md +1 -1
  24. package/prompts/en/roleplay/trigger-judge.md +3 -0
  25. package/prompts/en/world/procedure.md +1 -1
  26. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  27. package/prompts/zh/roleplay/ask-question.md +2 -0
  28. package/prompts/zh/roleplay/character-decide.md +1 -1
  29. package/prompts/zh/roleplay/character-lookup.md +1 -1
  30. package/prompts/zh/roleplay/faction-strategist.md +5 -0
  31. package/prompts/zh/roleplay/game-master.md +5 -1
  32. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  33. package/prompts/zh/roleplay/trigger-judge.md +3 -0
  34. package/prompts/zh/world/procedure.md +1 -1
  35. package/starter-worlds/blackwater-observatory/characters/arthur-moore/character.json +65 -0
  36. package/starter-worlds/blackwater-observatory/characters/clara-whitlock/character.json +87 -0
  37. package/starter-worlds/blackwater-observatory/characters/eleanor-graves/character.json +80 -0
  38. package/starter-worlds/blackwater-observatory/characters/marcus-reed/character.json +73 -0
  39. package/starter-worlds/blackwater-observatory/items/anonymous-letter/item.json +9 -0
  40. package/starter-worlds/blackwater-observatory/items/brass-laboratory-key/item.json +10 -0
  41. package/starter-worlds/blackwater-observatory/items/claras-gossip-notebook/item.json +9 -0
  42. package/starter-worlds/blackwater-observatory/items/harlans-notebook/item.json +10 -0
  43. package/starter-worlds/blackwater-observatory/items/investigators-coat/item.json +10 -0
  44. package/starter-worlds/blackwater-observatory/items/investigators-notebook/item.json +9 -0
  45. package/starter-worlds/blackwater-observatory/items/locked-filing-cabinet/item.json +10 -0
  46. package/starter-worlds/blackwater-observatory/items/marcus-calibration-notes/item.json +9 -0
  47. package/starter-worlds/blackwater-observatory/items/mayors-administrative-seal/item.json +9 -0
  48. package/starter-worlds/blackwater-observatory/items/municipal-lockbox/item.json +10 -0
  49. package/starter-worlds/blackwater-observatory/items/pocket-revolver/item.json +10 -0
  50. package/starter-worlds/blackwater-observatory/items/room-7-cash-receipt/item.json +9 -0
  51. package/starter-worlds/blackwater-observatory/items/rusting-mine-cart/item.json +10 -0
  52. package/starter-worlds/blackwater-observatory/items/signal-recording-strip/item.json +9 -0
  53. package/starter-worlds/blackwater-observatory/items/silver-pocket-watch/item.json +9 -0
  54. package/starter-worlds/blackwater-observatory/items/survey-archive-cabinet/item.json +10 -0
  55. package/starter-worlds/blackwater-observatory/items/surveyors-map/item.json +10 -0
  56. package/starter-worlds/blackwater-observatory/items/unknown-visitors-note-fragment/item.json +10 -0
  57. package/starter-worlds/blackwater-observatory/locations/blackwater-ridge/location.json +5 -0
  58. package/starter-worlds/blackwater-observatory/locations/iron-stag-bar/location.json +30 -0
  59. package/starter-worlds/blackwater-observatory/locations/iron-stag-room-7/location.json +18 -0
  60. package/starter-worlds/blackwater-observatory/locations/north-forest-cabin/location.json +18 -0
  61. package/starter-worlds/blackwater-observatory/locations/observatory-directors-office/location.json +20 -0
  62. package/starter-worlds/blackwater-observatory/locations/observatory-telescope-chamber/location.json +25 -0
  63. package/starter-worlds/blackwater-observatory/locations/old-mine-entrance/location.json +27 -0
  64. package/starter-worlds/blackwater-observatory/locations/old-mine-main-tunnel/location.json +13 -0
  65. package/starter-worlds/blackwater-observatory/locations/town-hall-mayors-office/location.json +25 -0
  66. package/starter-worlds/blackwater-observatory/locations/town-hall-records-room/location.json +13 -0
  67. package/starter-worlds/blackwater-observatory/locations/town-square/location.json +30 -0
  68. package/starter-worlds/blackwater-observatory/triggers.json +20 -0
  69. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  70. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  71. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  72. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  73. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  74. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  75. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  76. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  77. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  78. package/starter-worlds/blackwater-observatory/variables.json +39 -0
  79. package/starter-worlds/blackwater-observatory/world.json +27 -0
  80. package/lib/worlds-Bj-EGS_i.js +0 -478
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-BRyHU0H2.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 { A as languageOf, C as errorMessage, E as PROMPTS_FOLDER, H as INTENT_HORIZONS, M as promptProblem, N as shippedLanguages, P as shippedPromptsDirectory, R as InvalidWorldError, S as readDocument, T as formatIssue, U as INTENT_STATUSES, W as INTENT_TYPES, _ as API_PREFIX, b as parsePlotsFile, j as listFiles, v as PLOTS_FILE_NAME, w as Reader, x as plotReferenceProblems, y as loadPlots } from "./packs-ByP1J-zj.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-HPifO3Kk.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-Bu5uYRZB.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-HPifO3Kk.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-DUeBMHQX.js.map
@@ -6,6 +6,28 @@ import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
6
6
  import { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth } from "@deepseek-ai/dsh-subagent";
7
7
  import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
8
8
  import { copyFile, link, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
9
+ //#region src/host/agents/budget.ts
10
+ /** Tokens a text of a number of characters comes to: a character of a script written without spaces takes about one and a half, of the others about a third. */
11
+ function tokensOf(characters, language) {
12
+ return Math.ceil(language.toLowerCase().startsWith("zh") ? characters * 1.5 : characters / 3);
13
+ }
14
+ /**
15
+ * The most tokens to let a request produce, for an answer estimated at some tokens: the estimate with room to spare (`headroom` times it, rounded up to ten). The room is
16
+ * for a model that thinks or says a little before it answers; what is far more than that is a model that does not stop, and is cut off instead of waited for.
17
+ */
18
+ function outputBudget(estimate, headroom) {
19
+ return Math.ceil(estimate * headroom / 10) * 10;
20
+ }
21
+ /** The estimate of an answer made of texts that each have a declared limit in characters. */
22
+ function estimateAnswer(limits, language) {
23
+ return limits.reduce((sum, limit) => sum + tokensOf(limit, language) + 8, 0);
24
+ }
25
+ //#endregion
26
+ //#region src/shared/activity.ts
27
+ /** Longest text kept for one call's arguments or outcome, and for the persona, the prompt and the result. */
28
+ const MAX_RUN_TEXT = 4e3;
29
+ const MAX_RUN_PROMPT = 24e3;
30
+ //#endregion
9
31
  //#region src/host/agents/child.ts
10
32
  /** The tool every child ends with: its arguments are the child's result. */
11
33
  const SUBMIT_TOOL = "submit_result";
@@ -17,20 +39,56 @@ const DEFAULT_MAX_CALLS = 40;
17
39
  const MAX_REMINDERS = 2;
18
40
  /** A child that goes on calling tools this many times past its budget, in spite of being told to submit, is stopped: it would otherwise loop for as long as the model keeps at it. */
19
41
  const OVERRUN = 5;
42
+ /** Steps a child gets to submit once its other tools are withdrawn: a model that keeps calling tools that are gone is stopped. */
43
+ const STEPS_AFTER_RETIRE = 3;
20
44
  /** The same call, with the same arguments, that failed before is refused after this many repeats, and the child is stopped at twice that: the model is not reading the reasons it was given. */
21
45
  const REPEATS_TOLD = 1;
22
46
  const REPEATS_STOPPED = 4;
23
47
  /** A result that is refused this many times is not going to be fixed by asking again: the child is stopped and the caller decides what to do without it. */
24
48
  const MAX_REFUSALS = 5;
25
- /** What the settings of a chat say about how a kind of helper is asked: prose is free, the keepers of records exact. */
26
- function childSampling(settings, kind) {
49
+ /**
50
+ * What the settings of a chat say about how a kind of helper is asked: prose is free, the keepers of records exact. A helper whose answer has a declared size (its `estimate`, in tokens)
51
+ * is let produce that with room to spare, no more than the chat's ceiling for its kind.
52
+ */
53
+ function childSampling(settings, kind, estimate) {
54
+ const ceiling = kind === "characters" || kind === "suggestions" ? settings.sampling.shortMaxTokens : settings.sampling.maxTokens;
27
55
  return {
28
56
  temperature: settings.sampling[kind],
29
57
  toolChoice: settings.sampling.tools,
30
- maxTokens: settings.sampling.maxTokens,
58
+ maxTokens: estimate === void 0 ? ceiling : Math.min(ceiling, outputBudget(estimate, settings.sampling.headroom)),
31
59
  priority: kind === "characters" || kind === "authoring" ? "foreground" : "background"
32
60
  };
33
61
  }
62
+ /** What a caller passes as `trace`: files each run of a kind of helper under a label in the store's record of activity, with its detail when the chat keeps it. */
63
+ function childTrace(store, kind, label, extra = {}, named) {
64
+ const model = (named ?? store.settings().models[kind]).trim();
65
+ return (run) => {
66
+ const keep = store.settings().diagnostics.keepRuns;
67
+ const id = keep ? randomUUID() : void 0;
68
+ store.recordActivity({
69
+ at: Date.now(),
70
+ label,
71
+ model,
72
+ ms: run.ms,
73
+ calls: run.calls,
74
+ ...run.error === void 0 ? {} : { error: run.error.slice(0, 300) },
75
+ ...id === void 0 ? {} : { run: id }
76
+ }, keep ? {
77
+ ...run.detail,
78
+ ...extra
79
+ } : void 0);
80
+ };
81
+ }
82
+ /** The `model` the settings give a kind of helper, to spread into its task; nothing when it runs on the chat's own model. */
83
+ function childModel(settings, kind, override) {
84
+ const named = (override ?? settings.models[kind]).trim();
85
+ if (named === "") return {};
86
+ const slash = named.indexOf("/");
87
+ return { model: {
88
+ provider: named.slice(0, slash),
89
+ model: named.slice(slash + 1)
90
+ } };
91
+ }
34
92
  const samplings = /* @__PURE__ */ new Map();
35
93
  /** The controls set for a running child, by its session id. */
36
94
  const childSamplingOf = (sessionId) => samplings.get(sessionId);
@@ -57,12 +115,73 @@ function childOptions(task) {
57
115
  };
58
116
  return Object.keys(options).length === 0 ? void 0 : options;
59
117
  }
118
+ /** The schema an answer is checked against: the one the model was given, without requiring what it was only asked for ({@link ChildTask.unenforced}). */
119
+ function enforcedSchema(task) {
120
+ const skipped = task.unenforced ?? [];
121
+ return skipped.length === 0 || task.result.required === void 0 ? task.result : {
122
+ ...task.result,
123
+ required: task.result.required.filter((name) => !skipped.includes(name))
124
+ };
125
+ }
126
+ /** 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. */
127
+ const isUnfinishedCall = (error) => error instanceof Error && /parse tool call arguments|unfinished tool call/i.test(error.message);
60
128
  async function runChild(task) {
129
+ for (let attempt = 1;; attempt += 1) {
130
+ const began = Date.now();
131
+ const stats = {
132
+ calls: 0,
133
+ record: []
134
+ };
135
+ const detail = () => ({
136
+ persona: task.persona.slice(0, MAX_RUN_PROMPT),
137
+ prompt: task.prompt.slice(0, MAX_RUN_PROMPT),
138
+ calls: stats.record,
139
+ ...stats.result === void 0 ? {} : { result: stats.result }
140
+ });
141
+ try {
142
+ const result = await execute(task, stats);
143
+ task.trace?.({
144
+ ms: Date.now() - began,
145
+ calls: stats.calls,
146
+ detail: detail()
147
+ });
148
+ return result;
149
+ } catch (error) {
150
+ task.trace?.({
151
+ ms: Date.now() - began,
152
+ calls: stats.calls,
153
+ error: error instanceof Error ? error.message : String(error),
154
+ detail: detail()
155
+ });
156
+ if (attempt >= 2 || task.signal.aborted || !isUnfinishedCall(error)) throw error;
157
+ }
158
+ }
159
+ }
160
+ /**
161
+ * 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
162
+ * helper has its own levels, and one that lacks the level the chat asks for would refuse the request).
163
+ */
164
+ async function supportedEffort(task) {
165
+ const level = task.reasoningEffort;
166
+ if (level === void 0 || level === "" || task.model === void 0) return level;
167
+ try {
168
+ 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;
169
+ } catch {
170
+ return level;
171
+ }
172
+ }
173
+ const cut = (value, limit = MAX_RUN_TEXT) => {
174
+ const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
175
+ return text.length > limit ? `${text.slice(0, limit)} ... (${text.length - limit} more characters)` : text;
176
+ };
177
+ async function execute(task, stats) {
61
178
  const { parent, signal } = task;
179
+ const reasoningEffort = await supportedEffort(task);
62
180
  let submitted;
63
- let calls = 0;
64
181
  let reminders = 0;
65
182
  let stopped;
183
+ let retire;
184
+ let stepsAfterRetire = -1;
66
185
  let overran = false;
67
186
  let refusals = 0;
68
187
  let lastRefusal = "";
@@ -71,12 +190,24 @@ async function runChild(task) {
71
190
  const counted = (tool) => ({
72
191
  ...tool,
73
192
  execute: async (args, exec) => {
74
- calls += 1;
75
- if (calls > budget + OVERRUN) {
193
+ stats.calls += 1;
194
+ const note = (outcome, failed) => {
195
+ if (stats.record.length < 60) stats.record.push({
196
+ tool: tool.name,
197
+ args: cut(args),
198
+ outcome: cut(outcome),
199
+ failed
200
+ });
201
+ };
202
+ if (stats.calls > budget + OVERRUN) {
76
203
  overran = true;
77
204
  stopped?.();
78
205
  }
79
- if (calls > budget) throw new Error(`you have made ${budget} calls: submit your result now and say what is still missing`);
206
+ if (stats.calls > budget) {
207
+ const message = `you have made ${budget} calls: submit your result now and say what is still missing`;
208
+ note(message, true);
209
+ throw new Error(message);
210
+ }
80
211
  const signature = JSON.stringify(args);
81
212
  const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
82
213
  if (repeats >= REPEATS_STOPPED) {
@@ -90,7 +221,9 @@ async function runChild(task) {
90
221
  failed: true,
91
222
  repeats
92
223
  };
93
- throw new Error("this is exactly the call that just failed, with the same arguments, so it fails for the same reasons: read the reasons the last result gave and change the arguments to fix every one of them");
224
+ const message = "this is exactly the call that just failed, with the same arguments, so it fails for the same reasons: read the reasons the last result gave and change the arguments to fix every one of them";
225
+ note(message, true);
226
+ throw new Error(message);
94
227
  }
95
228
  previous = {
96
229
  name: tool.name,
@@ -99,10 +232,15 @@ async function runChild(task) {
99
232
  repeats
100
233
  };
101
234
  try {
102
- return await tool.execute(args, exec);
235
+ const outcome = await tool.execute(args, exec);
236
+ note(outcome, false);
237
+ return outcome;
103
238
  } catch (error) {
104
239
  if (previous !== void 0) previous.failed = true;
240
+ note(error instanceof Error ? error.message : String(error), true);
105
241
  throw error;
242
+ } finally {
243
+ if (stats.calls >= budget) retire?.();
106
244
  }
107
245
  }
108
246
  });
@@ -126,10 +264,16 @@ async function runChild(task) {
126
264
  }]
127
265
  },
128
266
  execute(args, exec) {
129
- const violations = validateJsonSchemaValue(task.result, args);
267
+ const violations = validateJsonSchemaValue(enforcedSchema(task), args);
130
268
  if (violations.length > 0) throw new ToolArgsError(violations);
131
269
  const refusal = task.beforeSubmit?.(args);
132
270
  if (refusal !== void 0) {
271
+ if (stats.record.length < 60) stats.record.push({
272
+ tool: SUBMIT_TOOL,
273
+ args: cut(args),
274
+ outcome: cut(refusal),
275
+ failed: true
276
+ });
133
277
  refusals += 1;
134
278
  lastRefusal = refusal;
135
279
  if (refusals >= MAX_REFUSALS) {
@@ -139,6 +283,13 @@ async function runChild(task) {
139
283
  throw new Error(refusal);
140
284
  }
141
285
  submitted = { value: args };
286
+ stats.result = cut(args, MAX_RUN_PROMPT);
287
+ if (stats.record.length < 60) stats.record.push({
288
+ tool: SUBMIT_TOOL,
289
+ args: cut(args),
290
+ outcome: "Result recorded.",
291
+ failed: false
292
+ });
142
293
  exec.concludeTurn();
143
294
  return Promise.resolve({ recorded: true });
144
295
  }
@@ -151,7 +302,10 @@ async function runChild(task) {
151
302
  sessionId,
152
303
  parentAgent: parent,
153
304
  meta: childSessionMeta(parent, depth, false),
154
- agentOptions: resolveChildAgentOptions(parent, childOptions(task), depth),
305
+ agentOptions: resolveChildAgentOptions(parent, childOptions({
306
+ ...task,
307
+ ...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
308
+ }), depth),
155
309
  signal,
156
310
  setup: (childCtx, child) => {
157
311
  appendDelegatedPolicyOverrides(child.session, inherited);
@@ -159,7 +313,21 @@ async function runChild(task) {
159
313
  persona: `${task.persona}\n\n${SUBMIT_RULE}`,
160
314
  toolFilter: { allow: [] }
161
315
  });
162
- for (const tool of task.tools ?? []) childCtx.tools.register(counted(tool));
316
+ const registered = (task.tools ?? []).map((tool) => childCtx.tools.register(counted(tool)));
317
+ retire = () => {
318
+ for (const dispose of registered) dispose();
319
+ if (stepsAfterRetire < 0) stepsAfterRetire = 0;
320
+ };
321
+ childCtx.on("agent/pre-step", async (_payload, next) => {
322
+ const decision = await next();
323
+ if (stepsAfterRetire < 0) return decision;
324
+ stepsAfterRetire += 1;
325
+ if (stepsAfterRetire > STEPS_AFTER_RETIRE && submitted === void 0) {
326
+ overran = true;
327
+ stopped?.();
328
+ }
329
+ return decision;
330
+ });
163
331
  childCtx.tools.register(submit);
164
332
  childCtx.on("agent/turn-stopping", () => {
165
333
  if (submitted !== void 0 || reminders >= MAX_REMINDERS) return;
@@ -205,7 +373,7 @@ async function runChild(task) {
205
373
  const ended = handle.agent.session.snapshotEvents().findLast((event) => event.type === "turn/end");
206
374
  const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
207
375
  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))`);
376
+ throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
209
377
  }
210
378
  return submitted.value;
211
379
  }
@@ -614,6 +782,34 @@ async function generateReferenceImage(service, request) {
614
782
  await writeImage(path, image.data, metadata, { replace: true });
615
783
  return path;
616
784
  }
785
+ const PNG_SIGNATURE = [
786
+ 137,
787
+ 80,
788
+ 78,
789
+ 71,
790
+ 13,
791
+ 10,
792
+ 26,
793
+ 10
794
+ ];
795
+ /** 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. */
796
+ async function uploadReferenceImage(request) {
797
+ 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");
798
+ const path = referenceImagePath(request.root, request.subject);
799
+ const metadata = {
800
+ schema: "dsh-roleplay-image/v3",
801
+ purpose: "reference",
802
+ origin: "uploaded",
803
+ reusable: true,
804
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
805
+ description: `${request.subject.name}, a picture brought by the author.`,
806
+ tags: [request.subject.name],
807
+ ...request.originalName === void 0 ? {} : { originalName: request.originalName },
808
+ subjects: [request.subject]
809
+ };
810
+ await writeImage(path, request.png, metadata, { replace: true });
811
+ return path;
812
+ }
617
813
  /** Generates one immutable scene image for a timeline node. It is intentionally not registered in the live roleplay loop yet. */
618
814
  async function generateTransientImage(service, request) {
619
815
  if (request.subjects.length === 0) throw new Error("a transient image needs at least one subject");
@@ -650,6 +846,6 @@ async function generateTransientImage(service, request) {
650
846
  return path;
651
847
  }
652
848
  //#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 };
849
+ 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, estimateAnswer as j, 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
850
 
655
- //# sourceMappingURL=generator-pxZS-pu-.js.map
851
+ //# sourceMappingURL=generator-HPifO3Kk.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-HPifO3Kk.js";
2
+ import { i as updateImage, r as listGallery } from "./gallery-DUeBMHQX.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-G43ODV8I.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 };