narrarium-engine 0.1.25 → 0.1.27

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 (68) hide show
  1. package/README.md +12 -2
  2. package/dist/ai/budget.d.ts +21 -1
  3. package/dist/ai/budget.d.ts.map +1 -1
  4. package/dist/ai/budget.js +17 -1
  5. package/dist/ai/budget.js.map +1 -1
  6. package/dist/ai/config.d.ts +27 -0
  7. package/dist/ai/config.d.ts.map +1 -1
  8. package/dist/ai/config.js +16 -1
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/ai/fetch-client.d.ts +2 -2
  11. package/dist/ai/fetch-client.d.ts.map +1 -1
  12. package/dist/ai/fetch-client.js +63 -10
  13. package/dist/ai/fetch-client.js.map +1 -1
  14. package/dist/ai/memory.d.ts +30 -6
  15. package/dist/ai/memory.d.ts.map +1 -1
  16. package/dist/ai/memory.js +15 -2
  17. package/dist/ai/memory.js.map +1 -1
  18. package/dist/ai/prompt-cache.d.ts +41 -0
  19. package/dist/ai/prompt-cache.d.ts.map +1 -0
  20. package/dist/ai/prompt-cache.js +76 -0
  21. package/dist/ai/prompt-cache.js.map +1 -0
  22. package/dist/ai/request.d.ts +6 -1
  23. package/dist/ai/request.d.ts.map +1 -1
  24. package/dist/ai/request.js +76 -1
  25. package/dist/ai/request.js.map +1 -1
  26. package/dist/ai/router.d.ts +5 -1
  27. package/dist/ai/router.d.ts.map +1 -1
  28. package/dist/ai/router.js +2 -1
  29. package/dist/ai/router.js.map +1 -1
  30. package/dist/ai/routing.d.ts +7 -3
  31. package/dist/ai/routing.d.ts.map +1 -1
  32. package/dist/ai/routing.js +48 -23
  33. package/dist/ai/routing.js.map +1 -1
  34. package/dist/ai/types.d.ts +43 -3
  35. package/dist/ai/types.d.ts.map +1 -1
  36. package/dist/ai/types.js +22 -2
  37. package/dist/ai/types.js.map +1 -1
  38. package/dist/autopilot/errors.d.ts.map +1 -1
  39. package/dist/autopilot/errors.js +7 -1
  40. package/dist/autopilot/errors.js.map +1 -1
  41. package/dist/autopilot/estimate-texts.d.ts +5 -0
  42. package/dist/autopilot/estimate-texts.d.ts.map +1 -1
  43. package/dist/autopilot/estimate-texts.js +9 -3
  44. package/dist/autopilot/estimate-texts.js.map +1 -1
  45. package/dist/autopilot/estimate.d.ts +19 -2
  46. package/dist/autopilot/estimate.d.ts.map +1 -1
  47. package/dist/autopilot/estimate.js +46 -10
  48. package/dist/autopilot/estimate.js.map +1 -1
  49. package/dist/autopilot/runner.d.ts +2 -0
  50. package/dist/autopilot/runner.d.ts.map +1 -1
  51. package/dist/autopilot/runner.js +22 -0
  52. package/dist/autopilot/runner.js.map +1 -1
  53. package/dist/autopilot/tasks.d.ts.map +1 -1
  54. package/dist/autopilot/tasks.js +76 -56
  55. package/dist/autopilot/tasks.js.map +1 -1
  56. package/dist/autopilot/types.d.ts +20 -4
  57. package/dist/autopilot/types.d.ts.map +1 -1
  58. package/dist/autopilot/types.js.map +1 -1
  59. package/dist/index.d.ts +1 -0
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +1 -0
  62. package/dist/index.js.map +1 -1
  63. package/dist/server/protocol.d.ts +2 -0
  64. package/dist/server/protocol.d.ts.map +1 -1
  65. package/dist/server/protocol.js.map +1 -1
  66. package/dist/version.d.ts +1 -1
  67. package/dist/version.js +1 -1
  68. package/package.json +1 -1
@@ -90,6 +90,20 @@ function data(sections) {
90
90
  function request(lines) {
91
91
  return currentRequest(lines.filter((line) => Boolean(line && line.trim())).join("\n\n"));
92
92
  }
93
+ /**
94
+ * The prompt of a call that is made again and again about the same material (the rounds of a review, the revisions of a plan, the scenes repaired of a chapter): what stays the same from one call to the next
95
+ * (`stable`) first, then what changes with each call (`changing`: the fixes of the last round, the findings of this one), and the request, which changes too, last. A provider that caches the start of a prompt serves
96
+ * everything before the first thing that changes from its cache, and one that has to be told where (`cache_control`) is told it ends there. The words are the same as with the request first: only their order is not.
97
+ */
98
+ function stableFirst(stable, changing, asked) {
99
+ const closing = "\n</repository_content>";
100
+ const text = data([...stable, ...changing]);
101
+ const first = data(stable);
102
+ // The stable sections end where the first one that changes begins: inside the one block of data, after their blank line (`data` joins the sections with one); when nothing changes, where the request begins.
103
+ const changes = changing.some((section) => Boolean(section && section.trim()));
104
+ const stableEnd = changes ? first.length - closing.length + 2 : text.length + 2;
105
+ return { user: `${text}\n\n${asked}`, cacheBreak: Math.min(stableEnd, text.length + 2) };
106
+ }
93
107
  /** A limit on the reply of a step, sized for a book in a Latin script and grown for the language of this one (unchanged for Italian and English). */
94
108
  function outputLimit(ctx, tokens) {
95
109
  return scaleOutputTokens(tokens, ctx.snapshot.book.language);
@@ -1119,27 +1133,28 @@ async function runPlanReview(ctx) {
1119
1133
  capability: AI_CAPABILITIES.director,
1120
1134
  label: "autopilot:plan-review",
1121
1135
  system: directorSystemPrompt(ctx.director, ctx.language),
1122
- user: `${request([
1123
- `Review the concept and the chapter plan before any prose is written (review ${plan.rounds + 1}).`,
1124
- "Approve when the plan delivers the brief and the vision with a satisfying shape; otherwise list precise changes chapter by chapter. Weigh the simulated readers by their weights: do not chase every opinion.",
1125
- view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) binds the plan: never ask to change its chapters, their order, their titles or their events; ask only for what enriches them." : "",
1126
- style.rule,
1127
- lastRound ? "This is the final plan review: approve it and turn anything still imperfect into standing guidance." : "",
1128
- ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical choice you cannot settle from the vision and the author's rules.",
1129
- authorRules(ctx, false),
1130
- ])}\n\n${data([
1136
+ ...stableFirst([
1131
1137
  bookHeader(ctx),
1132
1138
  briefBlock(ctx),
1133
1139
  outlineBookSection(view),
1134
- outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1135
1140
  style.block,
1136
1141
  design ? `STORY DESIGN:\n${design}` : "",
1137
1142
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
1143
+ ], [
1144
+ outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1138
1145
  listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
1139
1146
  plan.readerReactions.length
1140
1147
  ? `SIMULATED READERS:\n${plan.readerReactions.map((reaction) => `- ${reaction.name} (weight ${ctx.director.readerWeights[reaction.slug] ?? 1}): ${reaction.interest}/10 — ${reaction.reaction}${reaction.concerns.length ? ` Concerns: ${reaction.concerns.join("; ")}.` : ""}${reaction.wishes.length ? ` Wishes: ${reaction.wishes.join("; ")}.` : ""}`).join("\n")}`
1141
1148
  : "",
1142
- ])}`,
1149
+ ], request([
1150
+ `Review the concept and the chapter plan before any prose is written (review ${plan.rounds + 1}).`,
1151
+ "Approve when the plan delivers the brief and the vision with a satisfying shape; otherwise list precise changes chapter by chapter. Weigh the simulated readers by their weights: do not chase every opinion.",
1152
+ view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) binds the plan: never ask to change its chapters, their order, their titles or their events; ask only for what enriches them." : "",
1153
+ style.rule,
1154
+ lastRound ? "This is the final plan review: approve it and turn anything still imperfect into standing guidance." : "",
1155
+ ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical choice you cannot settle from the vision and the author's rules.",
1156
+ authorRules(ctx, false),
1157
+ ])),
1143
1158
  json: PLAN_REVIEW_TOOL,
1144
1159
  maxOutputTokens: outputLimit(ctx, 4000),
1145
1160
  });
@@ -1257,23 +1272,15 @@ async function runDesignReview(ctx) {
1257
1272
  capability: AI_CAPABILITIES.director,
1258
1273
  label: "autopilot:plan-review",
1259
1274
  system: directorSystemPrompt(ctx.director, ctx.language),
1260
- user: `${request([
1261
- `Review the design of the book before any prose is written (review ${roundNumber} of at most ${Math.max(maxRounds, roundNumber)}).`,
1262
- `Approve when the design delivers the brief and the vision with a satisfying shape and deserves ${target}/10 or more; otherwise list precise changes chapter by chapter. Weigh the simulated readers by their weights: do not chase every opinion.`,
1263
- ...DESIGN_DIRECTOR_RULES,
1264
- view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) binds the design: never ask to change its chapters, their order, their titles or their events; ask only for what enriches them." : "",
1265
- style.rule,
1266
- lastRound ? "This is the final review of the design: approve it unless a critical inconsistency is left, and turn anything still imperfect into standing guidance." : "",
1267
- ctx.director.autonomy === "full" ? "Never ask the author a question of taste: decide." : "Ask the author (questionForAuthor) only for a critical choice you cannot settle from the vision and the author's rules.",
1268
- authorRules(ctx, false),
1269
- ])}\n\n${data([
1275
+ ...stableFirst([
1270
1276
  bookHeader(ctx),
1271
1277
  briefBlock(ctx),
1272
1278
  outlineBookSection(view),
1273
- outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1274
1279
  style.block,
1275
1280
  storyDesign ? `STORY DESIGN:\n${storyDesign}` : "",
1276
1281
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
1282
+ ], [
1283
+ outlineListSection([...view.entries.values()], planFocus(plan), "AUTHOR'S OUTLINE (binding)"),
1277
1284
  ...designData.sections,
1278
1285
  listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
1279
1286
  entriesSection,
@@ -1281,7 +1288,16 @@ async function runDesignReview(ctx) {
1281
1288
  plan.readerReactions.length
1282
1289
  ? `SIMULATED READERS:\n${plan.readerReactions.map((reaction) => `- ${reaction.name} (weight ${ctx.director.readerWeights[reaction.slug] ?? 1}): ${reaction.interest}/10 — ${reaction.reaction}${reaction.concerns.length ? ` Concerns: ${reaction.concerns.join("; ")}.` : ""}${reaction.wishes.length ? ` Wishes: ${reaction.wishes.join("; ")}.` : ""}`).join("\n")}`
1283
1290
  : "",
1284
- ])}`,
1291
+ ], request([
1292
+ `Review the design of the book before any prose is written (review ${roundNumber} of at most ${Math.max(maxRounds, roundNumber)}).`,
1293
+ `Approve when the design delivers the brief and the vision with a satisfying shape and deserves ${target}/10 or more; otherwise list precise changes chapter by chapter. Weigh the simulated readers by their weights: do not chase every opinion.`,
1294
+ ...DESIGN_DIRECTOR_RULES,
1295
+ view.any ? "The author's outline (AUTHOR'S OUTLINE, in the data) binds the design: never ask to change its chapters, their order, their titles or their events; ask only for what enriches them." : "",
1296
+ style.rule,
1297
+ lastRound ? "This is the final review of the design: approve it unless a critical inconsistency is left, and turn anything still imperfect into standing guidance." : "",
1298
+ ctx.director.autonomy === "full" ? "Never ask the author a question of taste: decide." : "Ask the author (questionForAuthor) only for a critical choice you cannot settle from the vision and the author's rules.",
1299
+ authorRules(ctx, false),
1300
+ ])),
1285
1301
  json: DESIGN_REVIEW_TOOL,
1286
1302
  maxOutputTokens: outputLimit(ctx, 5000),
1287
1303
  });
@@ -1856,12 +1872,7 @@ async function runSpecialists(ctx) {
1856
1872
  capability: AI_CAPABILITIES.specialist,
1857
1873
  label: `autopilot:specialists:${chapter.number}`,
1858
1874
  system: specialistsSystemPrompt(ctx.language),
1859
- user: `${request([
1860
- `Review chapter ${chapter.number} «${chapter.title}» (review round ${review.round}). Return at most 12 findings, most important first, using the scene numbers of the markers.`,
1861
- review.previousFixes.length ? `These fixes were applied after the previous round: verify them and report only remaining or new real problems.\n${bulletList(review.previousFixes)}` : "",
1862
- style.rule,
1863
- authorRules(ctx, false),
1864
- ])}\n\n${data([
1875
+ ...stableFirst([
1865
1876
  bookHeader(ctx),
1866
1877
  `GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
1867
1878
  style.block,
@@ -1869,10 +1880,16 @@ async function runSpecialists(ctx) {
1869
1880
  chapterPlanBlock(chapter),
1870
1881
  `SCENE PLANS:\n${chapter.scenes.map((scene) => `- Scene ${scene.number} «${scene.title}»: ${scene.goal}`).join("\n")}`,
1871
1882
  `CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: false }) || "-"}`,
1872
- relevant.length ? `CANON DETAILS:\n${await canonDetails(ctx.store, relevant, 600)}` : "",
1873
1883
  secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
1874
1884
  `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, sceneLimit(ctx, 14000))}`,
1875
- ])}`,
1885
+ // What the chapter's text names is read from the text: it goes after it, so that everything before the text stays the same while the text is not touched.
1886
+ relevant.length ? `CANON DETAILS:\n${await canonDetails(ctx.store, relevant, 600)}` : "",
1887
+ ], [], request([
1888
+ `Review chapter ${chapter.number} «${chapter.title}» (review round ${review.round}). Return at most 12 findings, most important first, using the scene numbers of the markers.`,
1889
+ review.previousFixes.length ? `These fixes were applied after the previous round: verify them and report only remaining or new real problems.\n${bulletList(review.previousFixes)}` : "",
1890
+ style.rule,
1891
+ authorRules(ctx, false),
1892
+ ])),
1876
1893
  json: FINDINGS_TOOL,
1877
1894
  maxOutputTokens: outputLimit(ctx, 5000),
1878
1895
  });
@@ -1940,20 +1957,7 @@ async function runDirectorReview(ctx) {
1940
1957
  label: `autopilot:director-review:${chapter.number}`,
1941
1958
  // The profile as the policy makes it: its approval score is the target (the same profile, word for word, without a policy).
1942
1959
  system: directorSystemPrompt(target === ctx.director.approvalScore ? ctx.director : { ...ctx.director, approvalScore: target }, ctx.language),
1943
- user: `${request([
1944
- `Decide on chapter ${chapter.number} «${chapter.title}» (review round ${review.round} of ${maxRounds}).`,
1945
- "For EVERY finding decide exactly once: accept it with a precise, minimal remediation for the ghostwriter and its scene number, or reject it with the reason. Reject unfounded or unanchored findings, findings against the vision or the author's rules, and single-reader taste the intended audience would not share.",
1946
- `Score the chapter from 1 to 10. Verdict "approve" when it deserves at least ${target}/10 and nothing critical remains; otherwise "revise".`,
1947
- gate ? "The readers' targets in the data are rules too: the chapter is closed only when they are reached. Accept the concrete corrections of the readers under their target that serve the book's vision, each with a precise fix and its scene." : "",
1948
- style.rule,
1949
- review.authorEdit
1950
- ? "The author changed this chapter after it was approved: judge the chapter as it is now. The author's text stays as it is: no fix will be applied and there is no other round, so your accepted fixes are advice for the author."
1951
- : last ? "This is the LAST review round: accepted fixes will be applied and the chapter closed without another review, so accept only what really matters." : "",
1952
- authorNote ? `The author's note on the change: «${authorNote}»` : "",
1953
- "Add standing guidance for the next chapters when this chapter taught you something.",
1954
- ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical matter you must not settle alone.",
1955
- authorRules(ctx, false),
1956
- ])}\n\n${data([
1960
+ ...stableFirst([
1957
1961
  bookHeader(ctx),
1958
1962
  directorGuidance(ctx),
1959
1963
  style.block,
@@ -1966,10 +1970,25 @@ async function runDirectorReview(ctx) {
1966
1970
  : "",
1967
1971
  readersSummary ? `READERS PANEL SUMMARY:\n${readersSummary}` : "",
1968
1972
  gate ? readersTargetsBlock(ctx, review, gate) : "",
1973
+ `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, perScene)}`,
1974
+ // What changes with each round (the fixes of the last one, the findings of this one) goes after the text, which does not change until a fix is applied.
1975
+ ], [
1969
1976
  review.previousFixes.length ? `FIXES APPLIED AFTER THE PREVIOUS ROUND:\n${bulletList(review.previousFixes)}` : "",
1970
1977
  `FINDINGS TO DECIDE:\n${review.findings.length ? review.findings.map(findingLine).join("\n\n") : "None."}`,
1971
- `CHAPTER TEXT:\n${markedChapterText(source.paragraphs, perScene)}`,
1972
- ])}`,
1978
+ ], request([
1979
+ `Decide on chapter ${chapter.number} «${chapter.title}» (review round ${review.round} of ${maxRounds}).`,
1980
+ "For EVERY finding decide exactly once: accept it with a precise, minimal remediation for the ghostwriter and its scene number, or reject it with the reason. Reject unfounded or unanchored findings, findings against the vision or the author's rules, and single-reader taste the intended audience would not share.",
1981
+ `Score the chapter from 1 to 10. Verdict "approve" when it deserves at least ${target}/10 and nothing critical remains; otherwise "revise".`,
1982
+ gate ? "The readers' targets in the data are rules too: the chapter is closed only when they are reached. Accept the concrete corrections of the readers under their target that serve the book's vision, each with a precise fix and its scene." : "",
1983
+ style.rule,
1984
+ review.authorEdit
1985
+ ? "The author changed this chapter after it was approved: judge the chapter as it is now. The author's text stays as it is: no fix will be applied and there is no other round, so your accepted fixes are advice for the author."
1986
+ : last ? "This is the LAST review round: accepted fixes will be applied and the chapter closed without another review, so accept only what really matters." : "",
1987
+ authorNote ? `The author's note on the change: «${authorNote}»` : "",
1988
+ "Add standing guidance for the next chapters when this chapter taught you something.",
1989
+ ctx.director.autonomy === "full" ? "Never ask the author: decide." : "Ask the author (questionForAuthor) only for a critical matter you must not settle alone.",
1990
+ authorRules(ctx, false),
1991
+ ])),
1973
1992
  json: CHAPTER_REVIEW_TOOL,
1974
1993
  maxOutputTokens: outputLimit(ctx, 6000),
1975
1994
  });
@@ -2141,24 +2160,25 @@ async function rewriteScene(ctx, chapter, scene, instructions, mode) {
2141
2160
  capability: AI_CAPABILITIES.writer,
2142
2161
  label: `autopilot:${mode}:${chapter.number}.${scene.number}`,
2143
2162
  system: writerSystemPrompt(ctx.language),
2144
- user: `${request([
2145
- mode === "repair"
2146
- ? `Revise scene ${scene.number} of chapter ${chapter.number} «${scene.title}» applying ONLY these fixes approved by the director:`
2147
- : `Rewrite scene ${scene.number} of chapter ${chapter.number} «${scene.title}» to honor the author's revision:`,
2148
- instructions.map((instruction, index) => `${index + 1}. ${instruction}`).join("\n"),
2149
- "Keep everything else as it is: events, facts, voice, rhythm, secrets and approximate length, unless an instruction requires otherwise. Return the complete revised scene.",
2150
- authorRules(ctx),
2151
- ])}\n\n${data([
2163
+ ...stableFirst([
2152
2164
  bookHeader(ctx),
2153
2165
  `GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
2154
2166
  directorGuidance(ctx),
2167
+ ], [
2155
2168
  scenePlanBlock(scene),
2156
2169
  relevant.length ? `RELEVANT CANON:\n${await canonDetails(ctx.store, relevant)}` : "",
2157
2170
  secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
2158
2171
  neighbors.previousEnding ? `PREVIOUS SCENE ENDING:\n${neighbors.previousEnding}` : "",
2159
2172
  neighbors.nextOpening ? `NEXT SCENE OPENING (keep it consistent):\n${neighbors.nextOpening}` : "",
2160
2173
  `CURRENT SCENE:\n${loaded.document.body}`,
2161
- ])}`,
2174
+ ], request([
2175
+ mode === "repair"
2176
+ ? `Revise scene ${scene.number} of chapter ${chapter.number} «${scene.title}» applying ONLY these fixes approved by the director:`
2177
+ : `Rewrite scene ${scene.number} of chapter ${chapter.number} «${scene.title}» to honor the author's revision:`,
2178
+ instructions.map((instruction, index) => `${index + 1}. ${instruction}`).join("\n"),
2179
+ "Keep everything else as it is: events, facts, voice, rhythm, secrets and approximate length, unless an instruction requires otherwise. Return the complete revised scene.",
2180
+ authorRules(ctx),
2181
+ ])),
2162
2182
  maxOutputTokens: sceneOutputLimit(ctx, Math.max(originalWords, 300)),
2163
2183
  temperature: Math.min(0.7, ghostwriter?.temperature ?? 0.7),
2164
2184
  });