@dsh-agentic-roleplay/core 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  3. package/lib/authoring.js +469 -17
  4. package/lib/client.js +3013 -607
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +2 -3
  7. package/lib/{activity-BbqFG9-3.js → deliver--uMhC6oO.js} +741 -55
  8. package/lib/{documents-ZVoUTnD2.js → documents-7GMc5NnW.js} +108 -5
  9. package/lib/{gallery-KGCdeCnM.js → gallery-DUeBMHQX.js} +2 -2
  10. package/lib/{generator-NYnNdpWb.js → generator-HPifO3Kk.js} +125 -20
  11. package/lib/images.js +3 -3
  12. package/lib/index.js +865 -15
  13. package/lib/{narration-DcnCqA1l.js → narration-CKZTk5UE.js} +19 -4
  14. package/lib/orchestration.js +373 -207
  15. package/lib/packs-alJTiDM2.js +1336 -0
  16. package/lib/{presenter-agent-7j1c7QEz.js → presenter-agent-PX1WVaJB.js} +4 -4
  17. package/package.json +5 -3
  18. package/packs/scene/map.html +12 -0
  19. package/packs/scene/map.js +55 -0
  20. package/packs/scene/pack.json +11 -0
  21. package/packs/scene/strip.html +11 -0
  22. package/packs/scene/strip.js +26 -0
  23. package/packs/scene/style.css +16 -0
  24. package/prompts/en/roleplay/ask-answerer.md +3 -0
  25. package/prompts/en/roleplay/ask-question.md +2 -0
  26. package/prompts/en/roleplay/character-decide.md +1 -1
  27. package/prompts/en/roleplay/character-lookup.md +1 -1
  28. package/prompts/en/roleplay/game-master.md +5 -1
  29. package/prompts/en/roleplay/ooc-empty.md +1 -1
  30. package/prompts/en/roleplay/reflection.md +9 -0
  31. package/prompts/en/world/procedure.md +1 -1
  32. package/prompts/en/world/welcome.md +1 -1
  33. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  34. package/prompts/zh/roleplay/ask-question.md +2 -0
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-lookup.md +1 -1
  37. package/prompts/zh/roleplay/game-master.md +5 -1
  38. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/world/procedure.md +1 -1
  41. package/prompts/zh/world/welcome.md +1 -1
  42. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  43. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  44. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  45. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  46. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  47. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  48. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  49. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  50. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  51. package/lib/access-C1nFQiyT.js +0 -12
  52. package/lib/worlds-DYgjdH8O.js +0 -504
@@ -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
+ import { A as languageOf, C as errorMessage, E as PROMPTS_FOLDER, G as INTENT_TYPES, M as promptProblem, N as shippedLanguages, P as shippedPromptsDirectory, R as InvalidWorldError, S as readDocument, T as formatIssue, U as INTENT_HORIZONS, W as INTENT_STATUSES, _ 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-alJTiDM2.js";
2
2
  import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.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";
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";
@@ -5069,6 +5069,71 @@ function authoredWorldOf(chatSessionId) {
5069
5069
  }
5070
5070
  }
5071
5071
  //#endregion
5072
+ //#region src/host/triggers/parts.ts
5073
+ /** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
5074
+ async function loadWorldParts(directory) {
5075
+ const { characters, problems: characterProblems } = await loadCharacters(directory);
5076
+ const { locations, problems: locationProblems } = await loadLocations(directory);
5077
+ const { items, slots, problems: itemProblems } = await loadItems(directory, {
5078
+ characters: characters.map((character) => character.id),
5079
+ locations
5080
+ });
5081
+ const { defs, problems: variableProblems } = await loadVariables(directory);
5082
+ const problems = [
5083
+ ...characterProblems,
5084
+ ...locationProblems,
5085
+ ...itemProblems,
5086
+ ...variableProblems
5087
+ ];
5088
+ if (problems.length > 0) throw new InvalidEditProblems([`the world's other files have problems that come first: ${problems.map((problem) => `${problem.path}: ${problem.message}`).join("; ")}`]);
5089
+ return {
5090
+ characters,
5091
+ locations,
5092
+ items,
5093
+ slots,
5094
+ variables: defs
5095
+ };
5096
+ }
5097
+ //#endregion
5098
+ //#region src/host/triggers/check.ts
5099
+ /**
5100
+ * What each trigger names that the world does not have (a character, place, item or variable in its condition, its cues or the words of a
5101
+ * cue), found as a session start finds it: against a scratch story made from the world's files. Triggers that wait for each other count
5102
+ * as there. @returns the problems by trigger key; a trigger with none is not in it.
5103
+ */
5104
+ function triggerProblemsOf(parts, definitions) {
5105
+ const found = /* @__PURE__ */ new Map();
5106
+ if (definitions.length === 0) return found;
5107
+ const scratch = createSessionStore(":memory:", {
5108
+ id: "scratch",
5109
+ name: "scratch",
5110
+ world: {
5111
+ id: "scratch",
5112
+ name: "scratch"
5113
+ }
5114
+ }, { vectors: false });
5115
+ try {
5116
+ const session = scratch;
5117
+ populateLocations(session, parts.locations);
5118
+ populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
5119
+ populateItems(session, parts.items, parts.slots, parts.locations);
5120
+ populateVariables(session, parts.variables, {
5121
+ characters: parts.characters,
5122
+ items: parts.items,
5123
+ locations: parts.locations,
5124
+ values: void 0
5125
+ });
5126
+ const keys = definitions.map((definition) => definition.key);
5127
+ for (const definition of definitions) {
5128
+ const problems = triggerReferenceProblems(scratch, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
5129
+ if (problems.length > 0) found.set(definition.key, problems);
5130
+ }
5131
+ } finally {
5132
+ scratch.close();
5133
+ }
5134
+ return found;
5135
+ }
5136
+ //#endregion
5072
5137
  //#region src/host/worlds/world-editor.ts
5073
5138
  function stateOf(world, definition, names) {
5074
5139
  const { start } = definition;
@@ -5115,6 +5180,34 @@ function stateOf(world, definition, names) {
5115
5180
  }))
5116
5181
  };
5117
5182
  }
5183
+ /** The triggers of the world's file as the editor shows them, with what each names that the world does not have; or why the file cannot be shown. */
5184
+ function triggersOf(parts, scripted) {
5185
+ if (scripted.problems.length > 0) return {
5186
+ triggers: [],
5187
+ triggersProblem: scripted.problems.map((problem) => problem.message).join("; ")
5188
+ };
5189
+ const view = (problems) => scripted.triggers.map((definition) => ({
5190
+ key: definition.key,
5191
+ name: definition.name,
5192
+ when: definition.condition,
5193
+ effects: definition.effects,
5194
+ repeat: definition.repeat,
5195
+ priority: definition.priority,
5196
+ ...definition.cooldownSeconds === void 0 ? {} : { cooldownSeconds: definition.cooldownSeconds },
5197
+ ...definition.chance === void 0 ? {} : { chance: definition.chance },
5198
+ ...definition.expires === void 0 ? {} : { expires: definition.expires },
5199
+ announced: definition.announce !== void 0,
5200
+ problems: problems.get(definition.key) ?? []
5201
+ }));
5202
+ try {
5203
+ return { triggers: view(triggerProblemsOf(parts, scripted.triggers)) };
5204
+ } catch (error) {
5205
+ return {
5206
+ triggers: view(/* @__PURE__ */ new Map()),
5207
+ triggersProblem: `what the triggers name could not be checked, because the rest of the world has a problem: ${error instanceof Error ? error.message : String(error)}`
5208
+ };
5209
+ }
5210
+ }
5118
5211
  /** The characters of a world as they start, and the places they can start in. */
5119
5212
  async function readWorldEditor(world) {
5120
5213
  const [{ characters }, { locations }, { factions }, { lore }, { plots }] = await Promise.all([
@@ -5124,10 +5217,18 @@ async function readWorldEditor(world) {
5124
5217
  loadLore(world.directory),
5125
5218
  loadPlots(world.directory)
5126
5219
  ]);
5127
- const { items } = await loadItems(world.directory, {
5220
+ const { items, slots } = await loadItems(world.directory, {
5128
5221
  characters: characters.map((character) => character.id),
5129
5222
  locations
5130
5223
  });
5224
+ const scripted = await loadTriggers(world.directory);
5225
+ const { triggers, triggersProblem } = triggersOf({
5226
+ characters,
5227
+ locations,
5228
+ items,
5229
+ slots,
5230
+ variables: (await loadVariables(world.directory)).defs
5231
+ }, scripted);
5131
5232
  const names = new Map(locations.map((location) => [location.id, location.name]));
5132
5233
  const characterNames = new Map(characters.map((character) => [character.id, character.name]));
5133
5234
  const itemNames = new Map(items.map((item) => [item.id, item.name]));
@@ -5296,6 +5397,8 @@ async function readWorldEditor(world) {
5296
5397
  })),
5297
5398
  sources: entry.sources
5298
5399
  })),
5400
+ triggers,
5401
+ ...triggersProblem === void 0 ? {} : { triggersProblem },
5299
5402
  plots: plots.map((definition) => ({ definition })),
5300
5403
  relations
5301
5404
  };
@@ -5923,6 +6026,6 @@ async function deleteAuthoredEntity(world, kind, key) {
5923
6026
  return destination;
5924
6027
  }
5925
6028
  //#endregion
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 };
6029
+ export { writeWorldPrompt as $, survey as A, populateTriggers as B, authoringChatSessionId as C, importPhase as D, finish as E, populateItems as F, loadItems as G, routineProblems as H, populateKnowledge as I, subfolders as J, CHARACTERS_DIR as K, populateLocations as L, populateCharacters as M, populateClock as N, isReviewing as O, populateFactions as P, readWorldPrompt as Q, populateLore as R, authoredWorldOf as S, endReview as T, TRIGGERS_FILE_NAME as U, populateVariables as V, loadLocations as W, deleteWorldPrompt as X, PROSE_PROMPTS as Y, listWorldPrompts as Z, replaceFile$1 as _, parseRelationEdit as _t, replaceAuthoredEntity as a, IMPORT_FOLDER as at, triggerProblemsOf as b, parseImportCommand as bt, editWorldLore as c, parseChoices as ct, editWorldPlots as d, parseWorldInfoEdit as dt, VARIABLES_FILE_NAME as et, editWorldRelation as f, InvalidEditProblems as ft, readWorldEditor as g, parsePlaceEdit as gt, generateWorldCharacterPortrait as h, parseLoreEdit as ht, readAuthoredEntityDocument as i, parseCharacterFile as it, loadValidatedWorld as j, markReady as k, editWorldNarrationVoice as l, WORLD_FILE_NAME as lt, entityFolder as m, parseFactionEdit as mt, createAuthoredEntity as n, variableProblems as nt, editWorldCharacter as o, ImportNotFoundError as ot, editWorldThing as p, parseCharacterEdit as pt, loadCharacters as q, deleteAuthoredEntity as r, CHARACTER_FILE_NAME as rt, editWorldFaction as s, ImportStore as st, AUTHORED_ENTITY_KINDS as t, parseVariablesFile as tt, editWorldPlace as u, parseWorldFile as ut, uploadWorldCharacterPortrait as v, parseThingEdit as vt, build as w, loadWorldParts as x, worldCharacterPortraitFile as y, IMPORT_COMMAND as yt, populateRoutines as z };
5927
6030
 
5928
- //# sourceMappingURL=documents-ZVoUTnD2.js.map
6031
+ //# sourceMappingURL=documents-7GMc5NnW.js.map
@@ -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-NYnNdpWb.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-KGCdeCnM.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,37 +39,49 @@ 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: kind === "characters" || kind === "suggestions" ? settings.sampling.shortMaxTokens : 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
  }
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();
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();
37
65
  return (run) => {
66
+ const keep = store.settings().diagnostics.keepRuns;
67
+ const id = keep ? randomUUID() : void 0;
38
68
  store.recordActivity({
39
69
  at: Date.now(),
40
70
  label,
41
71
  model,
42
72
  ms: run.ms,
43
73
  calls: run.calls,
44
- ...run.error === void 0 ? {} : { error: run.error.slice(0, 300) }
45
- });
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);
46
80
  };
47
81
  }
48
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. */
49
- function childModel(settings, kind) {
50
- const named = settings.models[kind].trim();
83
+ function childModel(settings, kind, override) {
84
+ const named = (override ?? settings.models[kind]).trim();
51
85
  if (named === "") return {};
52
86
  const slash = named.indexOf("/");
53
87
  return { model: {
@@ -81,24 +115,43 @@ function childOptions(task) {
81
115
  };
82
116
  return Object.keys(options).length === 0 ? void 0 : options;
83
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
+ }
84
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. */
85
127
  const isUnfinishedCall = (error) => error instanceof Error && /parse tool call arguments|unfinished tool call/i.test(error.message);
86
128
  async function runChild(task) {
87
129
  for (let attempt = 1;; attempt += 1) {
88
130
  const began = Date.now();
89
- const stats = { calls: 0 };
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
+ });
90
141
  try {
91
142
  const result = await execute(task, stats);
92
143
  task.trace?.({
93
144
  ms: Date.now() - began,
94
- calls: stats.calls
145
+ calls: stats.calls,
146
+ detail: detail()
95
147
  });
96
148
  return result;
97
149
  } catch (error) {
98
150
  task.trace?.({
99
151
  ms: Date.now() - began,
100
152
  calls: stats.calls,
101
- error: error instanceof Error ? error.message : String(error)
153
+ error: error instanceof Error ? error.message : String(error),
154
+ detail: detail()
102
155
  });
103
156
  if (attempt >= 2 || task.signal.aborted || !isUnfinishedCall(error)) throw error;
104
157
  }
@@ -117,12 +170,18 @@ async function supportedEffort(task) {
117
170
  return level;
118
171
  }
119
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
+ };
120
177
  async function execute(task, stats) {
121
178
  const { parent, signal } = task;
122
179
  const reasoningEffort = await supportedEffort(task);
123
180
  let submitted;
124
181
  let reminders = 0;
125
182
  let stopped;
183
+ let retire;
184
+ let stepsAfterRetire = -1;
126
185
  let overran = false;
127
186
  let refusals = 0;
128
187
  let lastRefusal = "";
@@ -132,11 +191,23 @@ async function execute(task, stats) {
132
191
  ...tool,
133
192
  execute: async (args, exec) => {
134
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
+ };
135
202
  if (stats.calls > budget + OVERRUN) {
136
203
  overran = true;
137
204
  stopped?.();
138
205
  }
139
- if (stats.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
+ }
140
211
  const signature = JSON.stringify(args);
141
212
  const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
142
213
  if (repeats >= REPEATS_STOPPED) {
@@ -150,7 +221,9 @@ async function execute(task, stats) {
150
221
  failed: true,
151
222
  repeats
152
223
  };
153
- 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);
154
227
  }
155
228
  previous = {
156
229
  name: tool.name,
@@ -159,10 +232,15 @@ async function execute(task, stats) {
159
232
  repeats
160
233
  };
161
234
  try {
162
- return await tool.execute(args, exec);
235
+ const outcome = await tool.execute(args, exec);
236
+ note(outcome, false);
237
+ return outcome;
163
238
  } catch (error) {
164
239
  if (previous !== void 0) previous.failed = true;
240
+ note(error instanceof Error ? error.message : String(error), true);
165
241
  throw error;
242
+ } finally {
243
+ if (stats.calls >= budget) retire?.();
166
244
  }
167
245
  }
168
246
  });
@@ -186,10 +264,16 @@ async function execute(task, stats) {
186
264
  }]
187
265
  },
188
266
  execute(args, exec) {
189
- const violations = validateJsonSchemaValue(task.result, args);
267
+ const violations = validateJsonSchemaValue(enforcedSchema(task), args);
190
268
  if (violations.length > 0) throw new ToolArgsError(violations);
191
269
  const refusal = task.beforeSubmit?.(args);
192
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
+ });
193
277
  refusals += 1;
194
278
  lastRefusal = refusal;
195
279
  if (refusals >= MAX_REFUSALS) {
@@ -199,6 +283,13 @@ async function execute(task, stats) {
199
283
  throw new Error(refusal);
200
284
  }
201
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
+ });
202
293
  exec.concludeTurn();
203
294
  return Promise.resolve({ recorded: true });
204
295
  }
@@ -222,7 +313,21 @@ async function execute(task, stats) {
222
313
  persona: `${task.persona}\n\n${SUBMIT_RULE}`,
223
314
  toolFilter: { allow: [] }
224
315
  });
225
- 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
+ });
226
331
  childCtx.tools.register(submit);
227
332
  childCtx.on("agent/turn-stopping", () => {
228
333
  if (submitted !== void 0 || reminders >= MAX_REMINDERS) return;
@@ -741,6 +846,6 @@ async function generateTransientImage(service, request) {
741
846
  return path;
742
847
  }
743
848
  //#endregion
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 };
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 };
745
850
 
746
- //# sourceMappingURL=generator-NYnNdpWb.js.map
851
+ //# sourceMappingURL=generator-HPifO3Kk.js.map
package/lib/images.js CHANGED
@@ -1,4 +1,4 @@
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";
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-PX1WVaJB.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 };