narrarium-engine 0.1.8 → 0.1.10

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 (144) hide show
  1. package/README.md +409 -27
  2. package/dist/ai/budget.d.ts +18 -2
  3. package/dist/ai/budget.d.ts.map +1 -1
  4. package/dist/ai/budget.js +9 -2
  5. package/dist/ai/budget.js.map +1 -1
  6. package/dist/ai/catalog-fetch.d.ts.map +1 -1
  7. package/dist/ai/catalog-fetch.js +2 -1
  8. package/dist/ai/catalog-fetch.js.map +1 -1
  9. package/dist/ai/fetch-client.d.ts +13 -6
  10. package/dist/ai/fetch-client.d.ts.map +1 -1
  11. package/dist/ai/fetch-client.js +26 -3
  12. package/dist/ai/fetch-client.js.map +1 -1
  13. package/dist/ai/request.d.ts +1 -1
  14. package/dist/ai/request.d.ts.map +1 -1
  15. package/dist/ai/request.js +31 -5
  16. package/dist/ai/request.js.map +1 -1
  17. package/dist/ai/routing.d.ts.map +1 -1
  18. package/dist/ai/routing.js +1 -1
  19. package/dist/ai/routing.js.map +1 -1
  20. package/dist/ai/types.d.ts +29 -2
  21. package/dist/ai/types.d.ts.map +1 -1
  22. package/dist/ai/types.js +5 -2
  23. package/dist/ai/types.js.map +1 -1
  24. package/dist/autopilot/chapter-state.d.ts +19 -0
  25. package/dist/autopilot/chapter-state.d.ts.map +1 -0
  26. package/dist/autopilot/chapter-state.js +31 -0
  27. package/dist/autopilot/chapter-state.js.map +1 -0
  28. package/dist/autopilot/errors.d.ts +2 -1
  29. package/dist/autopilot/errors.d.ts.map +1 -1
  30. package/dist/autopilot/errors.js +17 -1
  31. package/dist/autopilot/errors.js.map +1 -1
  32. package/dist/autopilot/estimate-math.d.ts +19 -0
  33. package/dist/autopilot/estimate-math.d.ts.map +1 -0
  34. package/dist/autopilot/estimate-math.js +74 -0
  35. package/dist/autopilot/estimate-math.js.map +1 -0
  36. package/dist/autopilot/estimate-texts.d.ts +40 -0
  37. package/dist/autopilot/estimate-texts.d.ts.map +1 -0
  38. package/dist/autopilot/estimate-texts.js +130 -0
  39. package/dist/autopilot/estimate-texts.js.map +1 -0
  40. package/dist/autopilot/estimate.d.ts +303 -0
  41. package/dist/autopilot/estimate.d.ts.map +1 -0
  42. package/dist/autopilot/estimate.js +887 -0
  43. package/dist/autopilot/estimate.js.map +1 -0
  44. package/dist/autopilot/frozen.d.ts +166 -0
  45. package/dist/autopilot/frozen.d.ts.map +1 -0
  46. package/dist/autopilot/frozen.js +483 -0
  47. package/dist/autopilot/frozen.js.map +1 -0
  48. package/dist/autopilot/outline-change.d.ts +69 -0
  49. package/dist/autopilot/outline-change.d.ts.map +1 -0
  50. package/dist/autopilot/outline-change.js +42 -0
  51. package/dist/autopilot/outline-change.js.map +1 -0
  52. package/dist/autopilot/outline-check.d.ts +40 -0
  53. package/dist/autopilot/outline-check.d.ts.map +1 -0
  54. package/dist/autopilot/outline-check.js +84 -0
  55. package/dist/autopilot/outline-check.js.map +1 -0
  56. package/dist/autopilot/outline-compose.d.ts +203 -0
  57. package/dist/autopilot/outline-compose.d.ts.map +1 -0
  58. package/dist/autopilot/outline-compose.js +492 -0
  59. package/dist/autopilot/outline-compose.js.map +1 -0
  60. package/dist/autopilot/planner.d.ts +29 -1
  61. package/dist/autopilot/planner.d.ts.map +1 -1
  62. package/dist/autopilot/planner.js +78 -8
  63. package/dist/autopilot/planner.js.map +1 -1
  64. package/dist/autopilot/presets.d.ts +36 -0
  65. package/dist/autopilot/presets.d.ts.map +1 -0
  66. package/dist/autopilot/presets.js +54 -0
  67. package/dist/autopilot/presets.js.map +1 -0
  68. package/dist/autopilot/profile-check.d.ts +7 -4
  69. package/dist/autopilot/profile-check.d.ts.map +1 -1
  70. package/dist/autopilot/profile-check.js +9 -6
  71. package/dist/autopilot/profile-check.js.map +1 -1
  72. package/dist/autopilot/runner.d.ts +61 -7
  73. package/dist/autopilot/runner.d.ts.map +1 -1
  74. package/dist/autopilot/runner.js +313 -32
  75. package/dist/autopilot/runner.js.map +1 -1
  76. package/dist/autopilot/session.d.ts +50 -7
  77. package/dist/autopilot/session.d.ts.map +1 -1
  78. package/dist/autopilot/session.js +225 -10
  79. package/dist/autopilot/session.js.map +1 -1
  80. package/dist/autopilot/speed.d.ts +30 -0
  81. package/dist/autopilot/speed.d.ts.map +1 -0
  82. package/dist/autopilot/speed.js +71 -0
  83. package/dist/autopilot/speed.js.map +1 -0
  84. package/dist/autopilot/state.d.ts +21 -2
  85. package/dist/autopilot/state.d.ts.map +1 -1
  86. package/dist/autopilot/state.js +215 -3
  87. package/dist/autopilot/state.js.map +1 -1
  88. package/dist/autopilot/tasks.d.ts +14 -2
  89. package/dist/autopilot/tasks.d.ts.map +1 -1
  90. package/dist/autopilot/tasks.js +478 -34
  91. package/dist/autopilot/tasks.js.map +1 -1
  92. package/dist/autopilot/types.d.ts +238 -14
  93. package/dist/autopilot/types.d.ts.map +1 -1
  94. package/dist/autopilot/types.js +18 -2
  95. package/dist/autopilot/types.js.map +1 -1
  96. package/dist/book/context.d.ts +3 -0
  97. package/dist/book/context.d.ts.map +1 -1
  98. package/dist/book/context.js +7 -1
  99. package/dist/book/context.js.map +1 -1
  100. package/dist/book/freeze.d.ts +115 -0
  101. package/dist/book/freeze.d.ts.map +1 -0
  102. package/dist/book/freeze.js +286 -0
  103. package/dist/book/freeze.js.map +1 -0
  104. package/dist/book/outline.d.ts +245 -0
  105. package/dist/book/outline.d.ts.map +1 -0
  106. package/dist/book/outline.js +488 -0
  107. package/dist/book/outline.js.map +1 -0
  108. package/dist/book/paths.d.ts +18 -0
  109. package/dist/book/paths.d.ts.map +1 -1
  110. package/dist/book/paths.js +25 -0
  111. package/dist/book/paths.js.map +1 -1
  112. package/dist/book/snapshot.d.ts +25 -1
  113. package/dist/book/snapshot.d.ts.map +1 -1
  114. package/dist/book/snapshot.js +24 -4
  115. package/dist/book/snapshot.js.map +1 -1
  116. package/dist/director/opinion.d.ts +6 -0
  117. package/dist/director/opinion.d.ts.map +1 -1
  118. package/dist/director/opinion.js +4 -1
  119. package/dist/director/opinion.js.map +1 -1
  120. package/dist/index.d.ts +10 -0
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js +11 -0
  123. package/dist/index.js.map +1 -1
  124. package/dist/profiles/evaluation-style.d.ts +44 -0
  125. package/dist/profiles/evaluation-style.d.ts.map +1 -0
  126. package/dist/profiles/evaluation-style.js +152 -0
  127. package/dist/profiles/evaluation-style.js.map +1 -0
  128. package/dist/server/client.d.ts +92 -7
  129. package/dist/server/client.d.ts.map +1 -1
  130. package/dist/server/client.js +138 -11
  131. package/dist/server/client.js.map +1 -1
  132. package/dist/server/protocol.d.ts +226 -2
  133. package/dist/server/protocol.d.ts.map +1 -1
  134. package/dist/server/protocol.js +69 -0
  135. package/dist/server/protocol.js.map +1 -1
  136. package/dist/util/text.d.ts +6 -0
  137. package/dist/util/text.d.ts.map +1 -1
  138. package/dist/util/text.js +21 -0
  139. package/dist/util/text.js.map +1 -1
  140. package/dist/version.d.ts +1 -1
  141. package/dist/version.d.ts.map +1 -1
  142. package/dist/version.js +1 -1
  143. package/dist/version.js.map +1 -1
  144. package/package.json +1 -1
@@ -0,0 +1,887 @@
1
+ import { likelyTextTokens, resolveModelTokenBudgets } from "../ai/budget.js";
2
+ import { resolveAiCandidates } from "../ai/router.js";
3
+ import { REASONING_OUTPUT_MARGIN, STRUCTURED_OUTPUT_FLOOR, isReasoningModel } from "../ai/token-limit.js";
4
+ import { AI_CAPABILITIES } from "../ai/types.js";
5
+ import { DIRECTOR_OPINION_TOOL, directorSystemPrompt } from "../director/opinion.js";
6
+ import { currentRequest, untrustedData } from "../prompt/trust.js";
7
+ import { defaultDirector, directorPrompt } from "../profiles/director.js";
8
+ import { builtinReaderPersonas, readerPersonaSystemPrompt } from "../profiles/readers.js";
9
+ import { READER_EVALUATION_TOOL, READER_SUMMARY_TOOL } from "../readers/evaluation.js";
10
+ import { asInteger, asNumber, asRecord } from "../util/json.js";
11
+ import { OUTPUT_TOKENS_CEILING, countWords, isItalian, languageCode, scaleOutputTokens, tokensPerWord } from "../util/text.js";
12
+ import { sumCappedRamp, sumWindowedList, windowedList } from "./estimate-math.js";
13
+ import { estimateTexts } from "./estimate-texts.js";
14
+ import { PLAN_BATCH_CHAPTERS } from "./planner.js";
15
+ import { CHAPTER_REVIEW_TOOL, CHAPTER_SUMMARY_TOOL, CONCEPT_TOOL, CONSOLIDATION_TOOL, FINDINGS_TOOL, PLAN_REACTION_TOOL, PLAN_REVIEW_TOOL, PLAN_TOOL, SCENES_TOOL, SCENE_SUMMARY_TOOL, architectSystemPrompt, continuitySystemPrompt, specialistsSystemPrompt, writerSystemPrompt, } from "./prompts.js";
16
+ import { MAX_BOOK_CHAPTERS, MAX_DIRECTOR_NOTES, normalizeBrief, normalizeOptions } from "./state.js";
17
+ // What a run will cost before it starts. The estimate is arithmetic over the pipeline: it counts the calls the steps of the autopilot make (the formulas
18
+ // are written next to the step of `tasks.ts` and `planner.ts` they come from), weighs each call as the engine's router would weigh its prompt and as
19
+ // the replies of the schemas weigh, and prices the result with the models the author configured. Everything is closed-form: a book of five thousand
20
+ // chapters takes as long as one of five. It reads nothing and keeps nothing: no file, no clock, no network, no random number.
21
+ /** The capabilities of the router that the autopilot uses (`AI_CAPABILITIES`). */
22
+ export const ESTIMATE_CAPABILITIES = Object.freeze([
23
+ AI_CAPABILITIES.writer,
24
+ AI_CAPABILITIES.director,
25
+ AI_CAPABILITIES.reader,
26
+ AI_CAPABILITIES.readerSummary,
27
+ AI_CAPABILITIES.specialist,
28
+ AI_CAPABILITIES.summary,
29
+ ]);
30
+ /**
31
+ * The kinds of call a run makes, in the order of the pipeline; the names are the ones the labels of the requests start with
32
+ * (`autopilot:concept`, `autopilot:scenes:3`, `reader-evaluation:…`, `director:book`). Two of them are made inside a step of another kind:
33
+ * `scene-summary` is asked by `write` and `repair`, after the scene.
34
+ */
35
+ export const ESTIMATE_CALL_KINDS = Object.freeze([
36
+ "concept",
37
+ "summarize-imported",
38
+ "plan",
39
+ "plan-reader",
40
+ "plan-review",
41
+ "scenes",
42
+ "write",
43
+ "scene-summary",
44
+ "reader",
45
+ "readers-summary",
46
+ "specialists",
47
+ "director-review",
48
+ "repair",
49
+ "consolidate",
50
+ "final",
51
+ ]);
52
+ const CAPABILITY_OF = {
53
+ concept: AI_CAPABILITIES.writer,
54
+ "summarize-imported": AI_CAPABILITIES.summary,
55
+ plan: AI_CAPABILITIES.writer,
56
+ "plan-reader": AI_CAPABILITIES.reader,
57
+ "plan-review": AI_CAPABILITIES.director,
58
+ scenes: AI_CAPABILITIES.writer,
59
+ write: AI_CAPABILITIES.writer,
60
+ "scene-summary": AI_CAPABILITIES.summary,
61
+ reader: AI_CAPABILITIES.reader,
62
+ "readers-summary": AI_CAPABILITIES.readerSummary,
63
+ specialists: AI_CAPABILITIES.specialist,
64
+ "director-review": AI_CAPABILITIES.director,
65
+ repair: AI_CAPABILITIES.writer,
66
+ consolidate: AI_CAPABILITIES.writer,
67
+ final: AI_CAPABILITIES.director,
68
+ };
69
+ /**
70
+ * The sizes the estimate assumes where it cannot know them, in words (a word is six characters, the space included). They are the estimate's own
71
+ * assumptions, not measures of your book: pass what you have measured in `context`, and what a run has really spent will show where they are wrong.
72
+ * A real model may be longer or shorter than the replies it assumes; the tests that check the estimate against the pipeline answer with replies of these sizes.
73
+ */
74
+ export const ESTIMATE_TYPICAL = Object.freeze({
75
+ /** The idea of the brief, when the author wrote none. */
76
+ ideaWords: 60,
77
+ /** What a book that is just begun holds in the files the concept reads: its description, the story design and the world context, all to be filled. */
78
+ freshBookWords: 34,
79
+ designWords: 700,
80
+ worldWords: 250,
81
+ /** The default ghostwriter profile (`defaultGhostwriter`): 906 characters, at six a word. What a book that did not write its own has. */
82
+ ghostwriterWords: 150,
83
+ /** The canon manifest: a line (kind, name, summary) for each entry, and a summary for the characters: about six characters and four other entries. */
84
+ canonWords: 270,
85
+ /** The rules of what may be revealed, which the writer and the reviewers read, and the lines of the secrets in the manifest and in the plan of the reveals. */
86
+ secretsWords: 105,
87
+ secretLineWords: 20,
88
+ revealsWords: 45,
89
+ /** The binding rules of the author and the evaluation style of the book (the whole block of a chapter's review; the review of the plan carries about half: the method and the severity). */
90
+ rulesWords: 0,
91
+ styleWords: 0,
92
+ /** The standing guidance of the director when the plan is approved, and what each chapter adds to it, up to `MAX_DIRECTOR_NOTES` notes. */
93
+ notesWords: 30,
94
+ noteWords: 25,
95
+ /** An entry of the author's outline. */
96
+ outlineEntryWords: 60,
97
+ /** One entry of the canon as the prompts that quote it give it (a heading and its body), and how many a scene, a repair and the specialists quote. */
98
+ canonEntryWords: 45,
99
+ canonEntriesScene: 4,
100
+ canonEntriesSpecialists: 6,
101
+ /**
102
+ * A chapter of the plan as a block (title, summary, purpose, point of view, key events) and as a line of a list (number, title, summary); and the line of a chapter that is
103
+ * closed, whose summary is the one the closing wrote (`consolidate`), a little longer than the plan's.
104
+ */
105
+ chapterWords: 130,
106
+ chapterLineWords: 55,
107
+ closedLineWords: 64,
108
+ /** A scene of the plan as a block, and as a line. */
109
+ sceneWords: 110,
110
+ sceneLineWords: 25,
111
+ /** The story so far: what a chapter adds to it, and the length it is asked to stay under (`STORY_SO_FAR_TARGET_WORDS`). */
112
+ storyWordsPerChapter: 75,
113
+ storyWordsTarget: 900,
114
+ /**
115
+ * The longest a list of chapters is in a prompt: 24 000 characters (`OUTLINE_MAX_CHARS`). A list that does not fit keeps the `listFullLines` lines around the chapter it is
116
+ * about whole, and gives every other chapter a line of `titleLineWords`.
117
+ */
118
+ listCapWords: 4000,
119
+ listFullLines: 30,
120
+ titleLineWords: 5,
121
+ /** The specialists' findings in a round, the proposals of the readers' summary, and the lines they make in the director's prompt. */
122
+ findings: 5,
123
+ findingWords: 55,
124
+ readerProposals: 4,
125
+ proposalWords: 35,
126
+ /** A reader as one line of the director's prompt, and a fix the director accepts as the repair is told it. */
127
+ readerLineWords: 55,
128
+ fixWords: 25,
129
+ /** A scene's summary. */
130
+ summaryWords: 35,
131
+ // The replies, in words.
132
+ conceptWords: 1550,
133
+ chapterReplyWords: 125,
134
+ sceneReplyWords: 105,
135
+ planReactionWords: 100,
136
+ planReviewWords: 100,
137
+ readerWords: 150,
138
+ readersSummaryWords: 190,
139
+ findingReplyWords: 48,
140
+ directorBaseWords: 75,
141
+ decisionWords: 20,
142
+ consolidateBaseWords: 100,
143
+ recapSceneWords: 25,
144
+ importedSummaryWords: 60,
145
+ finalWords: 330,
146
+ });
147
+ // ─── What the pipeline asks of the models ───────────────────────────────────
148
+ /** The most rounds of review of a chapter, and the most times the plan is sent back (the third review of the plan is an approval). */
149
+ const MAX_ROUNDS = 3;
150
+ const MAX_PLAN_REVISIONS = 2;
151
+ /** A word of the book is six characters, the space included: what a limit in characters of a prompt is in words. */
152
+ const CHARS_PER_WORD = 6;
153
+ /** Tokens in a message besides its text, in the envelope of a function, and in a marker that opens a scene in a chapter's text. */
154
+ const MESSAGE_TOKENS = 4;
155
+ const FUNCTION_TOKENS = 8;
156
+ const SCENE_MARKER_TOKENS = 12;
157
+ /** Characters of the labels of a section of a prompt (its title, the lines that say what the next lines are), on average. */
158
+ const SECTION_LABEL_CHARS = 28;
159
+ /** Tokens a word of the book costs as the router counts a prompt: six characters (the space included) at four a token. */
160
+ const INPUT_TOKENS_PER_WORD = CHARS_PER_WORD / 4;
161
+ /** The tokens a word costs in the languages the engine's factor is built on (`TOKENS_PER_WORD`): the factor of another language is taken in proportion. */
162
+ const LATIN_TOKENS_PER_WORD = 2.4;
163
+ /** The most words of the director's taste a prompt carries: the lists of its profile and a vision cut at 2 500 characters (`directorTaste` in the steps of the writer). */
164
+ const MAX_TASTE_WORDS = 520;
165
+ const DEFAULT_PANEL_SIZE_FALLBACK = 8;
166
+ /**
167
+ * The request lines of each kind, in characters, and how many labelled sections its data has, measured on the prompts the pipeline builds (`autopilot/tasks.ts`) in their
168
+ * usual shape: no synopsis, no outline, no author's rules, one batch of the plan, a round that is not the last. What is in a section is counted in words; this is the English
169
+ * text around it (the lines of the request and the titles of the sections, `SECTION_LABEL_CHARS` each).
170
+ */
171
+ const REQUEST = {
172
+ concept: { chars: 341, sections: 11 },
173
+ "summarize-imported": { chars: 230, sections: 2 },
174
+ plan: { chars: 191, sections: 12 },
175
+ "plan-reader": { chars: 108, sections: 4 },
176
+ "plan-review": { chars: 407, sections: 7 },
177
+ scenes: { chars: 221, sections: 7 },
178
+ write: { chars: 189, sections: 14 },
179
+ "scene-summary": { chars: 76, sections: 0 },
180
+ reader: { chars: 55, sections: 2 },
181
+ "readers-summary": { chars: 47, sections: 3 },
182
+ specialists: { chars: 142, sections: 8 },
183
+ "director-review": { chars: 680, sections: 9 },
184
+ repair: { chars: 302, sections: 9 },
185
+ consolidate: { chars: 305, sections: 4 },
186
+ final: { chars: 408, sections: 6 },
187
+ };
188
+ /** The limit the pipeline puts on the reply of a call, in tokens (for the language of a Latin script; `scaleOutputTokens` grows it for the others). The prose is limited by its words. */
189
+ const REPLY_LIMIT = {
190
+ concept: 9000,
191
+ "summarize-imported": 600,
192
+ plan: 9000,
193
+ "plan-reader": 1500,
194
+ "plan-review": 4000,
195
+ scenes: 5000,
196
+ "scene-summary": 400,
197
+ reader: 2500,
198
+ "readers-summary": 2500,
199
+ specialists: 5000,
200
+ "director-review": 6000,
201
+ consolidate: 5000,
202
+ final: 4000,
203
+ };
204
+ /** The calls that are answered with prose, not with a function. */
205
+ const PROSE_KINDS = new Set(["write", "repair"]);
206
+ const TOOL_OF = {
207
+ concept: CONCEPT_TOOL,
208
+ "summarize-imported": CHAPTER_SUMMARY_TOOL,
209
+ plan: PLAN_TOOL,
210
+ "plan-reader": PLAN_REACTION_TOOL,
211
+ "plan-review": PLAN_REVIEW_TOOL,
212
+ scenes: SCENES_TOOL,
213
+ "scene-summary": SCENE_SUMMARY_TOOL,
214
+ reader: READER_EVALUATION_TOOL,
215
+ "readers-summary": READER_SUMMARY_TOOL,
216
+ specialists: FINDINGS_TOOL,
217
+ "director-review": CHAPTER_REVIEW_TOOL,
218
+ consolidate: CONSOLIDATION_TOOL,
219
+ final: DIRECTOR_OPINION_TOOL,
220
+ };
221
+ function prompt(base, ramps = [], once = 0, lists = []) {
222
+ return { base, ramps, lists, once };
223
+ }
224
+ function promptTotal(call, from, to) {
225
+ const chapters = Math.max(0, to - from + 1);
226
+ if (!chapters)
227
+ return 0;
228
+ return call.base * chapters + call.once
229
+ + call.ramps.reduce((total, ramp) => total + sumCappedRamp(ramp.slope, ramp.cap, from - (ramp.start ?? 1) + 1, to - (ramp.start ?? 1) + 1), 0)
230
+ + call.lists.reduce((total, list) => total + sumWindowedList(from - 1, to - 1, list.line, list.title, list.full, list.cap), 0);
231
+ }
232
+ function promptPeak(call, chapter) {
233
+ return call.base
234
+ + call.ramps.reduce((total, ramp) => total + Math.min(ramp.cap, ramp.slope * Math.max(0, chapter - (ramp.start ?? 1))), 0)
235
+ + call.lists.reduce((total, list) => total + windowedList(chapter - 1, list.line, list.title, list.full, list.cap), 0);
236
+ }
237
+ const messageTokens = (text) => Math.ceil(text.length / 4) + MESSAGE_TOKENS;
238
+ const functionTokens = (tool) => (tool ? likelyTextTokens(JSON.stringify([{ type: "function", function: tool }])) + FUNCTION_TOKENS : 0);
239
+ const staticCache = new Map();
240
+ function staticsFor(language) {
241
+ const key = language === "it" ? "it" : "en";
242
+ const cached = staticCache.get(key);
243
+ if (cached)
244
+ return cached;
245
+ const director = defaultDirector(key);
246
+ const system = (key === "it" ? "Italian" : "English");
247
+ const bullets = (entries) => entries.map((entry) => `- ${entry}`).join("\n");
248
+ const taste = [
249
+ director.priorities.length ? `Priorities:\n${bullets(director.priorities)}` : "",
250
+ director.taste.length ? `Taste:\n${bullets(director.taste)}` : "",
251
+ director.redLines.length ? `Red lines (never allowed):\n${bullets(director.redLines)}` : "",
252
+ director.body.trim() ? `Vision:\n${director.body.trim().slice(0, 2500)}` : "",
253
+ ].filter(Boolean).join("\n\n");
254
+ const profile = directorPrompt(director);
255
+ const directorSystem = directorSystemPrompt(director, key);
256
+ const personas = builtinReaderPersonas(key).filter((persona) => persona.enabled);
257
+ const personaSystem = (depth, extra = "") => {
258
+ if (!personas.length)
259
+ return MESSAGE_TOKENS;
260
+ const total = personas.reduce((sum, persona) => sum + readerPersonaSystemPrompt(persona, system, depth).length + extra.length, 0);
261
+ return Math.ceil(total / personas.length / 4) + MESSAGE_TOKENS;
262
+ };
263
+ const planReaderLine = "\n\nYou are reading the pitch and the chapter plan of a novel that is not written yet. React honestly as this reader would.";
264
+ const systems = {
265
+ concept: messageTokens(architectSystemPrompt(key)),
266
+ "summarize-imported": messageTokens(continuitySystemPrompt(key)),
267
+ plan: messageTokens(architectSystemPrompt(key)),
268
+ "plan-reader": personaSystem("brief", planReaderLine),
269
+ "plan-review": messageTokens(directorSystem),
270
+ scenes: messageTokens(architectSystemPrompt(key)),
271
+ write: messageTokens(writerSystemPrompt(key)),
272
+ "scene-summary": messageTokens(continuitySystemPrompt(key)),
273
+ reader: personaSystem("normal"),
274
+ "readers-summary": messageTokens(`Compare the separate simulated-reader evaluations. Preserve disagreements rather than flattening them. Return the summary in ${system}.`),
275
+ specialists: messageTokens(specialistsSystemPrompt(key)),
276
+ "director-review": messageTokens(directorSystem),
277
+ repair: messageTokens(writerSystemPrompt(key)),
278
+ consolidate: messageTokens(continuitySystemPrompt(key)),
279
+ final: messageTokens(directorSystem),
280
+ };
281
+ const tools = Object.fromEntries(ESTIMATE_CALL_KINDS.map((kind) => [kind, functionTokens(TOOL_OF[kind])]));
282
+ const statics = {
283
+ frame: untrustedData("repository_content", "").length + currentRequest("").length + 2,
284
+ system: systems,
285
+ tool: tools,
286
+ directorWords: countWords(profile),
287
+ directorProfileTokens: Math.ceil(profile.length / 4),
288
+ tasteTokens: Math.ceil(taste.length / 4),
289
+ tasteShare: profile.length ? taste.length / profile.length : 0,
290
+ readersEnabled: builtinReaderPersonas(key).filter((persona) => persona.enabled).length || DEFAULT_PANEL_SIZE_FALLBACK,
291
+ };
292
+ staticCache.set(key, statics);
293
+ return statics;
294
+ }
295
+ // ─── The input, as the estimate reads it ────────────────────────────────────
296
+ function whole(value, fallback, min, max) {
297
+ return asInteger(value, fallback, min, max);
298
+ }
299
+ /** A size in words that the host measured: anything that is not a number of words (no text, not a number, below nothing) is the typical size. */
300
+ function knob(value, fallback) {
301
+ return asNumber(value, fallback, 0, 10_000_000);
302
+ }
303
+ function pin(value, fallback, min, max) {
304
+ let low = fallback[0];
305
+ let high = fallback[1];
306
+ if (typeof value === "number" || typeof value === "string") {
307
+ const single = asNumber(value, Number.NaN);
308
+ if (!Number.isNaN(single))
309
+ low = high = single;
310
+ }
311
+ else if (value && typeof value === "object" && !Array.isArray(value)) {
312
+ const range = value;
313
+ const first = asNumber(range.min, Number.NaN);
314
+ const last = asNumber(range.max, Number.NaN);
315
+ if (!Number.isNaN(first))
316
+ low = first;
317
+ if (!Number.isNaN(last))
318
+ high = last;
319
+ }
320
+ const clamp = (number) => Math.min(max, Math.max(min, Math.round(number)));
321
+ low = clamp(low);
322
+ high = clamp(high);
323
+ return low <= high ? [low, high] : [high, low];
324
+ }
325
+ function priceOf(value) {
326
+ const pricing = asRecord(value);
327
+ const known = (price) => typeof price === "number" && Number.isFinite(price) && price >= 0;
328
+ if (!known(pricing.inputPerMTok) || !known(pricing.outputPerMTok))
329
+ return undefined;
330
+ // A cache that costs more than the input it saves is no saving: the cached price is never above the input's.
331
+ return { input: pricing.inputPerMTok, output: pricing.outputPerMTok, ...(known(pricing.cachedPerMTok) ? { cached: Math.min(pricing.cachedPerMTok, pricing.inputPerMTok) } : {}) };
332
+ }
333
+ function resolveModel(value) {
334
+ const source = asRecord(value);
335
+ const name = typeof source.model === "string" ? source.model.trim() : "";
336
+ if (!name)
337
+ return null;
338
+ const positive = (number) => (typeof number === "number" && Number.isFinite(number) && number > 0 ? number : undefined);
339
+ const provider = typeof source.provider === "string" ? source.provider : "";
340
+ const underlying = typeof source.underlyingModel === "string" ? source.underlyingModel : undefined;
341
+ const price = priceOf(source.pricing);
342
+ const window = positive(source.maxInputTokens);
343
+ const maxOutput = positive(source.maxOutputTokens);
344
+ const speed = positive(source.tokensPerSecond);
345
+ return {
346
+ name,
347
+ ...(window ? { window } : {}),
348
+ ...(maxOutput ? { maxOutput } : {}),
349
+ ...(price ? { price } : {}),
350
+ ...(speed ? { speed } : {}),
351
+ reasoning: source.supportsReasoning === true || isReasoningModel(provider, name, underlying),
352
+ };
353
+ }
354
+ /** The number of the last chapter an outline asks for, from what the host says of it. */
355
+ function outlineChaptersOf(outline) {
356
+ const last = whole(outline.lastChapter, 0, 0, MAX_BOOK_CHAPTERS);
357
+ const entries = whole(outline.entries, 0, 0, MAX_BOOK_CHAPTERS);
358
+ return Math.max(last, entries);
359
+ }
360
+ const rangeOf = (min, max) => ({ min, max });
361
+ const roundRange = (min, max) => ({ min: Math.round(min), max: Math.round(max) });
362
+ export function estimateAutopilotRun(input) {
363
+ const source = asRecord(input);
364
+ const languageText = typeof source.language === "string" && source.language.trim() ? source.language : "en";
365
+ const language = languageCode(languageText);
366
+ const italian = isItalian(language);
367
+ const statics = staticsFor(language);
368
+ const brief = normalizeBrief(source.brief);
369
+ const options = normalizeOptions(source.options);
370
+ const briefSource = asRecord(source.brief);
371
+ const context = asRecord(source.context);
372
+ const progress = asRecord(source.progress);
373
+ const outline = asRecord(source.outline);
374
+ const scenario = asRecord(source.scenario);
375
+ const T = ESTIMATE_TYPICAL;
376
+ // The tokens a word costs, in the book's language: the engine's factor, or the host's own.
377
+ const override = asNumber(source.tokensPerWord, Number.NaN);
378
+ const tpw = Number.isFinite(override) && override > 0 ? override : tokensPerWord(languageText);
379
+ const ratio = tpw / LATIN_TOKENS_PER_WORD;
380
+ /** Tokens of `count` words of the book in a prompt. */
381
+ const w = (count) => count * INPUT_TOKENS_PER_WORD * ratio;
382
+ const scenes = brief.scenesPerChapter;
383
+ const sceneWords = brief.wordsPerScene;
384
+ const chapterWords = scenes * sceneWords;
385
+ const maxRounds = whole(source.maxReviewRounds, 2, 1, MAX_ROUNDS);
386
+ // The book: the chapters the brief asks for, or the outline's if it asks for more.
387
+ const outlineChapters = outlineChaptersOf(outline);
388
+ const chapters = Math.min(MAX_BOOK_CHAPTERS, Math.max(brief.targetChapters, outlineChapters));
389
+ const outlineEntries = whole(outline.entries, 0, 0, MAX_BOOK_CHAPTERS) || (outlineChapters > 0 ? outlineChapters : 0);
390
+ const outlineWords = outlineEntries > 0 ? knob(outline.words, outlineEntries * T.outlineEntryWords) : 0;
391
+ // Where it is.
392
+ const withoutSummary = whole(progress.withoutSummary, 0, 0, MAX_BOOK_CHAPTERS);
393
+ const written = Math.max(whole(progress.chaptersDone, 0, 0, MAX_BOOK_CHAPTERS), withoutSummary);
394
+ const planned = whole(progress.planned, 0, 0, MAX_BOOK_CHAPTERS);
395
+ const conceptDone = typeof progress.conceptDone === "boolean" ? progress.conceptDone : written > 0 || planned > 0;
396
+ const finalDone = progress.finalDone === true;
397
+ const toWrite = Math.max(0, chapters - written);
398
+ const from = written + 1;
399
+ const importedChapterWords = withoutSummary > 0 ? Math.max(1, knob(progress.withoutSummaryWords, withoutSummary * chapterWords) / withoutSummary) : chapterWords;
400
+ // What is planned: a fresh plan for the chapters that are left, or the extension of a plan that is approved. Chapters the plan holds are not planned again.
401
+ const extension = planned > 0 && chapters > planned;
402
+ const planCount = planned > 0 ? (extension ? chapters - planned : 0) : toWrite;
403
+ const planBatches = planCount > 0 ? Math.ceil(planCount / PLAN_BATCH_CHAPTERS) : 0;
404
+ const freshPlan = planned === 0 && planCount > 0;
405
+ // The readers: those of the panel that are enabled, as many as the author asks. The readers of the plan do not depend on the readers of the chapters.
406
+ const panel = whole(source.readerPanelSize, statics.readersEnabled, 0, 1000);
407
+ const chapterReaders = options.readers ? Math.min(options.maxReaders, panel) : 0;
408
+ const planReaders = options.readersOnPlan ? Math.min(options.maxReaders, panel) : 0;
409
+ const specialists = options.specialists ? 1 : 0;
410
+ // The reviews.
411
+ const rounds = pin(scenario.rounds, [1, maxRounds], 1, maxRounds);
412
+ const repairs = pin(scenario.repairs, [Math.max(0, rounds[0] - 1), rounds[1] * scenes], 0, rounds[1] * scenes);
413
+ const revisions = pin(scenario.planRevisions, [0, MAX_PLAN_REVISIONS], 0, MAX_PLAN_REVISIONS);
414
+ const pinned = rounds[0] === rounds[1] && repairs[0] === repairs[1] && revisions[0] === revisions[1];
415
+ // What the files of the book weigh, in words.
416
+ const design = knob(context.designWords, T.designWords);
417
+ const world = knob(context.worldWords, T.worldWords);
418
+ const ghostwriter = knob(context.ghostwriterWords, T.ghostwriterWords);
419
+ const canon = knob(context.canonWords, T.canonWords);
420
+ const secrets = knob(context.secretsWords, T.secretsWords);
421
+ const rules = knob(context.rulesWords, T.rulesWords);
422
+ const notes = knob(context.notesWords, T.notesWords);
423
+ // The standing guidance grows with the book, a note for a chapter, up to the twelve the state keeps.
424
+ const notesRamp = { slope: w(T.noteWords), cap: w(Math.max(0, MAX_DIRECTOR_NOTES * T.noteWords - notes)), start: from };
425
+ const style = knob(context.styleWords, T.styleWords);
426
+ const ideaWords = typeof briefSource.idea === "string" && briefSource.idea.trim() ? countWords(briefSource.idea) : T.ideaWords;
427
+ const synopsisWords = typeof briefSource.synopsis === "string" && briefSource.synopsis.trim() ? countWords(briefSource.synopsis) : 0;
428
+ const customDirector = context.directorWords !== undefined && Number.isFinite(asNumber(context.directorWords, Number.NaN));
429
+ const directorWords = customDirector ? knob(context.directorWords, statics.directorWords) : statics.directorWords;
430
+ /** The system message of a kind, with the director's profile as the author wrote it when it is not the default one. */
431
+ const system = (kind) => {
432
+ const base = statics.system[kind];
433
+ if (!customDirector || (kind !== "plan-review" && kind !== "director-review" && kind !== "final"))
434
+ return base;
435
+ return base - statics.directorProfileTokens + w(directorWords);
436
+ };
437
+ /** The block of the director's taste that the writer's prompts carry. */
438
+ const taste = customDirector ? w(Math.min(directorWords * statics.tasteShare, MAX_TASTE_WORDS)) : statics.tasteTokens;
439
+ const tool = (kind) => statics.tool[kind];
440
+ /** The fixed part of the tokens of a call of this kind: the system message, the function, the envelope of the request and its text, the labels of the sections. */
441
+ const scaffold = (kind) => {
442
+ const request = REQUEST[kind];
443
+ return system(kind) + tool(kind) + Math.ceil((statics.frame + request.chars + request.sections * SECTION_LABEL_CHARS) / 4) + MESSAGE_TOKENS;
444
+ };
445
+ const prefix = (kind) => system(kind) + tool(kind);
446
+ // What a prompt carries of the story so far, in tokens a chapter adds and up to where it stops (the caller's limit in characters).
447
+ const story = (capChars) => ({ slope: w(T.storyWordsPerChapter), cap: w(Math.min(T.storyWordsTarget, capChars / CHARS_PER_WORD)) });
448
+ const line = w(T.chapterLineWords);
449
+ const closedLine = w(T.closedLineWords);
450
+ const titleLine = w(T.titleLineWords);
451
+ const listCap = w(T.listCapWords);
452
+ /** A list of `lines` chapters, one line each (`each` tokens), laid out within the budget of a list. */
453
+ const list = (lines, each = line) => windowedList(lines, each, titleLine, T.listFullLines, listCap);
454
+ const earlierChapters = { line: closedLine, title: titleLine, full: T.listFullLines, cap: listCap };
455
+ const chapterText = w(chapterWords) + scenes * SCENE_MARKER_TOKENS;
456
+ // The entries of the canon that a prompt quotes in full (a heading and the body): the ones a scene names, the ones a chapter's text names. A book with no canon quotes none.
457
+ const entriesOfScene = canon > 0 ? w(T.canonEntriesScene * (T.canonEntryWords + 4)) : 0;
458
+ const entriesOfChapter = canon > 0 ? w(T.canonEntriesSpecialists * (T.canonEntryWords + 4)) : 0;
459
+ const proposals = chapterReaders > 0 ? T.readerProposals : 0;
460
+ const findingsLines = specialists ? T.findings : 0;
461
+ // The outline, in the prompts that carry it: the description and the entries (12 000 characters at most), and the entries of a batch (24 000).
462
+ const outlineWordsCapped = (cap) => (outlineEntries > 0 ? w(Math.min(outlineWords, cap / CHARS_PER_WORD)) : 0);
463
+ // ─── The prompts of each kind, in tokens ──────────────────────────────────
464
+ const promptOf = (kind) => {
465
+ switch (kind) {
466
+ case "concept":
467
+ return prompt(scaffold(kind) + w(ideaWords + synopsisWords + T.freshBookWords + rules) + taste + outlineWordsCapped(12_000));
468
+ case "summarize-imported":
469
+ return prompt(scaffold(kind) + w(Math.min(importedChapterWords, 60_000 / CHARS_PER_WORD)) + scenes * SCENE_MARKER_TOKENS);
470
+ case "plan-reader":
471
+ return prompt(scaffold(kind) + w(ideaWords + Math.min(design, 2500 / CHARS_PER_WORD)) + list(chapters));
472
+ case "plan-review":
473
+ return prompt(scaffold(kind) + w(ideaWords + synopsisWords + Math.min(design, 5000 / CHARS_PER_WORD) + canon + T.secretLineWords + style / 2 + rules + planReaders * (T.planReactionWords + 14)) + list(chapters) + outlineWordsCapped(12_000));
474
+ case "scenes":
475
+ // The chapter before and the chapter after, one line each; the last chapter of the book has no next one.
476
+ return prompt(scaffold(kind) + w(notes + T.chapterWords + canon + secrets + rules + Math.min(design, 2500 / CHARS_PER_WORD)) + line, [story(5000), { slope: closedLine, cap: closedLine }, notesRamp], -line);
477
+ case "scene-summary":
478
+ return prompt(scaffold(kind) + w(sceneWords));
479
+ case "reader":
480
+ return prompt(scaffold(kind) + chapterText, [story(3000)]);
481
+ case "readers-summary":
482
+ return prompt(scaffold(kind) + w(chapterReaders * (T.readerWords + 27)));
483
+ case "specialists":
484
+ return prompt(scaffold(kind) + w(ghostwriter + style + T.chapterWords + scenes * T.sceneLineWords + canon + secrets + rules) + entriesOfChapter + chapterText, [], 0, [earlierChapters]);
485
+ case "director-review": {
486
+ const readerLines = chapterReaders * T.readerLineWords + (chapterReaders > 0 ? T.readersSummaryWords + 25 : 0);
487
+ return prompt(scaffold(kind) + w(notes + style + T.chapterWords + scenes * T.sceneLineWords + secrets + rules + readerLines + findingsLines * T.findingWords + proposals * T.proposalWords) + chapterText, [story(4000), notesRamp]);
488
+ }
489
+ case "repair":
490
+ return prompt(scaffold(kind) + w(T.fixWords + ghostwriter + notes + T.sceneWords + secrets + rules + Math.min(400, sceneWords) + Math.min(150, sceneWords) + sceneWords) + entriesOfScene, [notesRamp]);
491
+ case "consolidate":
492
+ return prompt(scaffold(kind) + w(T.chapterWords) + chapterText, [story(7000)]);
493
+ default:
494
+ return prompt(scaffold(kind));
495
+ }
496
+ };
497
+ /** The prompt of the scene `k` of a chapter: what the writer reads before it writes. */
498
+ const writePrompt = (k) => {
499
+ const previousEnding = k > 1 ? Math.min(400, sceneWords) : 0;
500
+ const base = scaffold("write")
501
+ + w(ghostwriter + notes + Math.min(world, 2000 / CHARS_PER_WORD) + T.chapterWords + (k - 1) * (T.summaryWords + 6) + previousEnding + T.sceneWords + (k < scenes ? T.sceneWords : 0) + secrets + rules)
502
+ + entriesOfScene + taste;
503
+ // The first scene of a chapter that is not the first begins after the last scene of the chapter before.
504
+ const ramps = [story(5000), notesRamp];
505
+ if (k === 1)
506
+ ramps.push({ slope: w(250), cap: w(250) });
507
+ return prompt(base, ramps);
508
+ };
509
+ // ─── The replies, in words ────────────────────────────────────────────────
510
+ const replyCap = (kind) => {
511
+ if (PROSE_KINDS.has(kind))
512
+ return OUTPUT_TOKENS_CEILING;
513
+ return scaleOutputTokens(REPLY_LIMIT[kind] ?? OUTPUT_TOKENS_CEILING, languageText);
514
+ };
515
+ /** The tokens of a reply of `words` words, no more than the pipeline lets it be. */
516
+ const reply = (kind, words) => Math.min(replyCap(kind), words * tpw);
517
+ const storyOut = (first, last) => sumCappedRamp(T.storyWordsPerChapter, T.storyWordsTarget, first + 1, last + 1) * tpw;
518
+ // The plan: a call for each batch of twenty chapters, asked again for every batch after each revision the director asks for. A revision of a plan in one batch
519
+ // carries the plan as it is; one of a plan in several carries the batch as it is and the lines of the others.
520
+ const planCalls = (() => {
521
+ const base = scaffold("plan") + w(ideaWords + synopsisWords + Math.min(design, 6000 / CHARS_PER_WORD) + Math.min(world, 2500 / CHARS_PER_WORD) + canon + T.secretLineWords + T.revealsWords + rules) + taste + outlineWordsCapped(36_000);
522
+ const alreadyWritten = written > 0 ? list(written, closedLine) + w(Math.min(T.storyWordsTarget, 4000 / CHARS_PER_WORD, T.storyWordsPerChapter * written)) : 0;
523
+ const notesOfChanges = w(3 * 25);
524
+ const result = { fresh: 0, revised: 0, output: 0, peakFresh: 0, peakRevised: 0 };
525
+ for (let batch = 1; batch <= planBatches; batch += 1) {
526
+ const inBatch = Math.min(PLAN_BATCH_CHAPTERS, planCount - PLAN_BATCH_CHAPTERS * (batch - 1));
527
+ const before = planBatches > 1 ? planned + PLAN_BATCH_CHAPTERS * (batch - 1) : 0;
528
+ const first = base + alreadyWritten + list(before) + (extension ? list(planned) + notesOfChanges : 0);
529
+ const again = planBatches > 1
530
+ ? base + alreadyWritten + w(inBatch * T.chapterWords) + list(chapters - inBatch) + notesOfChanges
531
+ : base + alreadyWritten + list(chapters) + notesOfChanges;
532
+ result.fresh += first;
533
+ result.revised += again;
534
+ result.output += reply("plan", inBatch * T.chapterReplyWords + 10);
535
+ result.peakFresh = Math.max(result.peakFresh, first);
536
+ result.peakRevised = Math.max(result.peakRevised, again, first);
537
+ }
538
+ return result;
539
+ })();
540
+ // The director's last look at the whole book: its design, its plot map (a summary and the scenes of each chapter), the story so far, a line for each chapter and the notes.
541
+ const plotMapWords = Math.min(4000 / CHARS_PER_WORD, 40 + chapters * (T.chapterLineWords + scenes * T.summaryWords + 20));
542
+ const notesAtTheEnd = Math.min(MAX_DIRECTOR_NOTES * T.noteWords, notes + T.noteWords * toWrite);
543
+ const finalPrompt = scaffold("final")
544
+ + w(Math.min(design, 5000 / CHARS_PER_WORD) + plotMapWords + Math.min(T.storyWordsTarget, 7000 / CHARS_PER_WORD, T.storyWordsPerChapter * chapters) + notesAtTheEnd + rules + style)
545
+ + list(chapters, w(T.closedLineWords + 4));
546
+ /** The largest prompt a call of this kind has in the run, in tokens: in the last chapter, the last scene of a chapter, the largest batch of the plan. */
547
+ const peakOf = (kind) => {
548
+ if (kind === "write")
549
+ return promptPeak(writePrompt(scenes), chapters);
550
+ if (kind === "plan")
551
+ return revisions[1] > 0 ? planCalls.peakRevised : planCalls.peakFresh;
552
+ if (kind === "final")
553
+ return finalPrompt;
554
+ return promptPeak(promptOf(kind), chapters);
555
+ };
556
+ // ─── One way the reviews turn out ─────────────────────────────────────────
557
+ const compute = ({ rounds: r, repairs: p, revisions: v }) => {
558
+ const points = Object.fromEntries(ESTIMATE_CALL_KINDS.map((kind) => [kind, { calls: 0, input: 0, output: 0, prefix: 0 }]));
559
+ const add = (kind, calls, input, output) => {
560
+ const point = points[kind];
561
+ point.calls += calls;
562
+ point.input += input;
563
+ point.output += output;
564
+ point.prefix += prefix(kind) * calls;
565
+ };
566
+ if (!conceptDone)
567
+ add("concept", 1, promptOf("concept").base, reply("concept", T.conceptWords));
568
+ if (withoutSummary > 0)
569
+ add("summarize-imported", withoutSummary, withoutSummary * promptOf("summarize-imported").base, withoutSummary * reply("summarize-imported", T.importedSummaryWords));
570
+ if (planBatches > 0) {
571
+ add("plan", planBatches * (1 + v), planCalls.fresh + v * planCalls.revised, planCalls.output * (1 + v));
572
+ add("plan-review", 1 + v, (1 + v) * promptOf("plan-review").base, (1 + v) * reply("plan-review", T.planReviewWords));
573
+ }
574
+ if (freshPlan && planReaders > 0)
575
+ add("plan-reader", planReaders, planReaders * promptOf("plan-reader").base, planReaders * reply("plan-reader", T.planReactionWords));
576
+ const count = toWrite;
577
+ if (count > 0) {
578
+ const to = chapters;
579
+ const perChapter = (kind, calls, replyWords, call = promptOf(kind)) => {
580
+ if (calls <= 0)
581
+ return;
582
+ add(kind, calls * count, calls * promptTotal(call, from, to), calls * count * reply(kind, replyWords));
583
+ };
584
+ perChapter("scenes", 1, scenes * T.sceneReplyWords + 5);
585
+ // The scenes: each is written with what the scenes before it did, and summarized after; a repair is summarized too.
586
+ let writeInput = 0;
587
+ for (let k = 1; k <= scenes; k += 1)
588
+ writeInput += promptTotal(writePrompt(k), from, to);
589
+ add("write", scenes * count, writeInput, scenes * count * reply("write", sceneWords));
590
+ perChapter("scene-summary", scenes + p, T.summaryWords);
591
+ perChapter("reader", chapterReaders, T.readerWords);
592
+ perChapter("readers-summary", chapterReaders > 0 ? 1 : 0, T.readersSummaryWords);
593
+ // The rounds after the first: the proposals of the readers are gone (they are made once, in the first round) and the fixes of the round before are told to the
594
+ // specialists and to the director.
595
+ const carried = r > 1 ? Math.min(scenes, p / (r - 1)) : 0;
596
+ const fixes = w(carried * (T.fixWords + 3));
597
+ const later = (call, dropped = 0) => ({ ...call, base: call.base - dropped + fixes });
598
+ const findingsReply = T.findings * T.findingReplyWords + 10;
599
+ perChapter("specialists", specialists, findingsReply);
600
+ perChapter("specialists", specialists * (r - 1), findingsReply, later(promptOf("specialists")));
601
+ perChapter("director-review", 1, T.directorBaseWords + (findingsLines + proposals) * T.decisionWords);
602
+ // The standing guidance (a note for a chapter) is asked for once, in the first round.
603
+ perChapter("director-review", r - 1, T.directorBaseWords - T.noteWords + findingsLines * T.decisionWords, later(promptOf("director-review"), w(proposals * T.proposalWords)));
604
+ // Each fix the director accepts is a remediation it writes out, for the repair to follow.
605
+ if (p > 0)
606
+ add("director-review", 0, 0, count * p * reply("director-review", T.fixWords));
607
+ perChapter("repair", p, sceneWords);
608
+ const closing = promptTotal(promptOf("consolidate"), from, to);
609
+ add("consolidate", count, closing, count * reply("consolidate", T.consolidateBaseWords + scenes * T.recapSceneWords) + storyOut(from, to));
610
+ }
611
+ if (count > 0 || !finalDone)
612
+ add("final", 1, finalPrompt, reply("final", T.finalWords));
613
+ return points;
614
+ };
615
+ const lowest = compute({ rounds: rounds[0], repairs: repairs[0], revisions: revisions[0] });
616
+ const highest = compute({ rounds: rounds[1], repairs: repairs[1], revisions: revisions[1] });
617
+ // ─── The models ───────────────────────────────────────────────────────────
618
+ const modelsInput = asRecord(source.models);
619
+ const models = Object.fromEntries(ESTIMATE_CAPABILITIES.map((capability) => [capability, resolveModel(modelsInput[capability])]));
620
+ /** The largest answer a call of this kind may ask for, as the router sends it: the structured floor, the room for the reasoning, and the model's own maximum. */
621
+ const requestLimit = (kind, model) => {
622
+ const requested = PROSE_KINDS.has(kind) ? Math.min(OUTPUT_TOKENS_CEILING, Math.ceil(Math.max(sceneWords, kind === "repair" ? 300 : 0) * tpw) + 800) : scaleOutputTokens(REPLY_LIMIT[kind] ?? OUTPUT_TOKENS_CEILING, languageText);
623
+ let limit = PROSE_KINDS.has(kind) ? requested : Math.max(requested, STRUCTURED_OUTPUT_FLOOR);
624
+ if (model.reasoning)
625
+ limit += REASONING_OUTPUT_MARGIN;
626
+ return model.maxOutput ? Math.min(limit, model.maxOutput) : limit;
627
+ };
628
+ const steps = {};
629
+ const capabilityTotals = Object.fromEntries(ESTIMATE_CAPABILITIES.map((capability) => [capability, {
630
+ calls: rangeOf(0, 0), inputTokens: rangeOf(0, 0), cachedInputTokens: rangeOf(0, 0), outputTokens: rangeOf(0, 0),
631
+ }]));
632
+ const cachedRate = (capability) => models[capability]?.price?.cached;
633
+ for (const kind of ESTIMATE_CALL_KINDS) {
634
+ const capability = CAPABILITY_OF[kind];
635
+ const low = lowest[kind];
636
+ const high = highest[kind];
637
+ // A reply is never more than the largest the model can give.
638
+ const modelMax = models[capability]?.maxOutput;
639
+ const outputLow = modelMax ? Math.min(low.output, low.calls * modelMax) : low.output;
640
+ const outputHigh = modelMax ? Math.min(high.output, high.calls * modelMax) : high.output;
641
+ steps[kind] = {
642
+ capability,
643
+ calls: rangeOf(low.calls, high.calls),
644
+ inputTokens: roundRange(low.input, high.input),
645
+ outputTokens: roundRange(outputLow, outputHigh),
646
+ };
647
+ const totals = capabilityTotals[capability];
648
+ const cached = cachedRate(capability) === undefined ? [0, 0] : [Math.min(low.prefix, low.input), Math.min(high.prefix, high.input)];
649
+ const sumInto = (target, range) => {
650
+ target.min += range.min;
651
+ target.max += range.max;
652
+ };
653
+ sumInto(totals.calls, steps[kind].calls);
654
+ sumInto(totals.inputTokens, steps[kind].inputTokens);
655
+ sumInto(totals.outputTokens, steps[kind].outputTokens);
656
+ sumInto(totals.cachedInputTokens, roundRange(cached[0], cached[1]));
657
+ }
658
+ // ─── Money and time, by capability ────────────────────────────────────────
659
+ const unpriced = [];
660
+ const unmeasured = [];
661
+ const capabilities = {};
662
+ let costMin = 0;
663
+ let costMax = 0;
664
+ let minutesMin = 0;
665
+ let minutesMax = 0;
666
+ for (const capability of ESTIMATE_CAPABILITIES) {
667
+ const totals = capabilityTotals[capability];
668
+ const model = models[capability];
669
+ const idle = totals.calls.max === 0;
670
+ let cost = rangeOf(0, 0);
671
+ let minutes = rangeOf(0, 0);
672
+ if (!idle) {
673
+ if (!model?.price) {
674
+ cost = null;
675
+ unpriced.push(capability);
676
+ }
677
+ else {
678
+ const { input, output, cached } = model.price;
679
+ const cachedLow = cached === undefined ? 0 : totals.cachedInputTokens.min;
680
+ cost = rangeOf(((totals.inputTokens.min - cachedLow) * input + cachedLow * (cached ?? input) + totals.outputTokens.min * output) / 1e6, (totals.inputTokens.max * input + totals.outputTokens.max * output) / 1e6);
681
+ }
682
+ if (!model?.speed) {
683
+ minutes = null;
684
+ unmeasured.push(capability);
685
+ }
686
+ else {
687
+ minutes = rangeOf(totals.outputTokens.min / model.speed / 60, totals.outputTokens.max / model.speed / 60);
688
+ }
689
+ }
690
+ if (cost) {
691
+ costMin += cost.min;
692
+ costMax += cost.max;
693
+ }
694
+ if (minutes) {
695
+ minutesMin += minutes.min;
696
+ minutesMax += minutes.max;
697
+ }
698
+ capabilities[capability] = { model: model?.name ?? null, ...totals, cost, minutes };
699
+ }
700
+ // ─── What the author should know before it starts ────────────────────────
701
+ const text = estimateTexts(italian);
702
+ const warnings = [];
703
+ for (const capability of ESTIMATE_CAPABILITIES) {
704
+ const totals = capabilityTotals[capability];
705
+ if (totals.calls.max === 0)
706
+ continue;
707
+ const model = models[capability];
708
+ if (!model) {
709
+ warnings.push({ code: "noModel", severity: "error", capability, text: text.noModel(capability) });
710
+ continue;
711
+ }
712
+ const kinds = ESTIMATE_CALL_KINDS.filter((kind) => CAPABILITY_OF[kind] === capability && highest[kind].calls > 0);
713
+ if (model.window) {
714
+ // The window is judged by the most demanding step: the largest prompt against what the engine leaves for a prompt once the step's own reply is reserved.
715
+ let worst = null;
716
+ for (const kind of kinds) {
717
+ const peak = Math.round(peakOf(kind));
718
+ const budget = resolveModelTokenBudgets(model.window, requestLimit(kind, model)).inputTokens;
719
+ if (!worst || peak / Math.max(1, budget) > worst.peak / Math.max(1, worst.budget))
720
+ worst = { kind, peak, budget };
721
+ }
722
+ if (worst && worst.peak * 1.25 > worst.budget) {
723
+ const fits = worst.peak <= worst.budget;
724
+ warnings.push({ code: "smallWindow", severity: fits ? "warning" : "error", capability, model: model.name, step: worst.kind, window: model.window, inputBudget: worst.budget, typicalPrompt: worst.peak, text: text.smallWindow(capability, model.name, model.window, worst.budget, worst.peak, worst.kind, fits) });
725
+ }
726
+ }
727
+ if (model.maxOutput) {
728
+ let longest = null;
729
+ for (const kind of kinds) {
730
+ const perCall = highest[kind].output / highest[kind].calls;
731
+ if (!longest || perCall > longest.reply)
732
+ longest = { kind, reply: perCall };
733
+ }
734
+ if (longest && Math.round(longest.reply) > model.maxOutput) {
735
+ warnings.push({ code: "smallOutput", severity: "warning", capability, model: model.name, step: longest.kind, maxOutputTokens: model.maxOutput, typicalReply: Math.round(longest.reply), text: text.smallOutput(capability, model.name, model.maxOutput, Math.round(longest.reply), longest.kind) });
736
+ }
737
+ }
738
+ if (!model.price)
739
+ warnings.push({ code: "noPrice", severity: "warning", capability, model: model.name, text: text.noPrice(capability, model.name) });
740
+ if (!model.speed)
741
+ warnings.push({ code: "noSpeed", severity: "info", capability, model: model.name, text: text.noSpeed(capability, model.name) });
742
+ if (model.reasoning)
743
+ warnings.push({ code: "reasoningModel", severity: "info", capability, model: model.name, text: text.reasoningModel(capability, model.name) });
744
+ }
745
+ if (outlineChapters > brief.targetChapters) {
746
+ warnings.push({ code: "outlineLongerThanBrief", severity: "info", briefChapters: brief.targetChapters, outlineChapters, text: text.outlineLonger(brief.targetChapters, outlineChapters) });
747
+ }
748
+ const gravity = { error: 0, warning: 1, info: 2 };
749
+ warnings.sort((left, right) => gravity[left.severity] - gravity[right.severity]);
750
+ const sumKinds = (select) => ESTIMATE_CALL_KINDS.reduce((total, kind) => ({ min: total.min + select(steps[kind]).min, max: total.max + select(steps[kind]).max }), rangeOf(0, 0));
751
+ const cachedTotal = ESTIMATE_CAPABILITIES.reduce((total, capability) => ({ min: total.min + capabilities[capability].cachedInputTokens.min, max: total.max + capabilities[capability].cachedInputTokens.max }), rangeOf(0, 0));
752
+ const currency = typeof source.currency === "string" && source.currency.trim() ? source.currency.trim() : undefined;
753
+ const label = (range) => `${range.min}-${range.max}`;
754
+ const assumptions = text.assumptions({
755
+ chapters,
756
+ written: Math.min(written, chapters),
757
+ toWrite,
758
+ scenes,
759
+ wordsPerScene: sceneWords,
760
+ words: toWrite * chapterWords,
761
+ pinned,
762
+ rounds: label(roundRange(rounds[0], rounds[1])),
763
+ repairs: label(roundRange(repairs[0], repairs[1])),
764
+ revisions: label(roundRange(revisions[0], revisions[1])),
765
+ maxRounds,
766
+ readers: chapterReaders,
767
+ planReaders: planBatches > 0 && freshPlan ? planReaders : 0,
768
+ panel,
769
+ specialists: Boolean(specialists),
770
+ tokensPerWord: tpw,
771
+ inputPerWord: INPUT_TOKENS_PER_WORD * ratio,
772
+ cached: ESTIMATE_CAPABILITIES.some((capability) => cachedRate(capability) !== undefined && capabilityTotals[capability].calls.max > 0),
773
+ outlineWords: Math.round(outlineWords),
774
+ });
775
+ return {
776
+ language,
777
+ chapters,
778
+ chaptersToWrite: toWrite,
779
+ words: toWrite * chapterWords,
780
+ calls: sumKinds((step) => step.calls),
781
+ inputTokens: sumKinds((step) => step.inputTokens),
782
+ cachedInputTokens: cachedTotal,
783
+ outputTokens: sumKinds((step) => step.outputTokens),
784
+ cost: unpriced.length ? null : { min: costMin, max: costMax, ...(currency ? { currency } : {}) },
785
+ unpriced,
786
+ minutes: unmeasured.length ? null : rangeOf(minutesMin, minutesMax),
787
+ unmeasured,
788
+ capabilities,
789
+ steps,
790
+ warnings,
791
+ assumptions,
792
+ };
793
+ }
794
+ function speedOfModel(speeds, model) {
795
+ if (!speeds)
796
+ return undefined;
797
+ const entry = speeds instanceof Map ? speeds.get(model) : Object.prototype.hasOwnProperty.call(speeds, model) ? speeds[model] : undefined;
798
+ const speed = entry?.tokensPerSecond;
799
+ return typeof speed === "number" && Number.isFinite(speed) && speed > 0 ? speed : undefined;
800
+ }
801
+ /**
802
+ * The model of each capability as the router would choose it (the first of `resolveAiCandidates`): its name, its window, its largest answer, its prices, whether it
803
+ * reasons, and the speed `speeds` has for it. No key, no address: only what the estimate reads. A capability the configuration has no model for is not in the answer.
804
+ */
805
+ export function estimateModelsFromConfig(config, speeds) {
806
+ const models = {};
807
+ const configuration = asRecord(config);
808
+ if (!Array.isArray(configuration.aiIntegrations))
809
+ return models;
810
+ const usable = { ...configuration, aiIntegrations: configuration.aiIntegrations.filter((integration) => integration && typeof integration === "object") };
811
+ for (const capability of ESTIMATE_CAPABILITIES) {
812
+ let candidate;
813
+ try {
814
+ candidate = resolveAiCandidates(usable, capability)[0];
815
+ }
816
+ catch {
817
+ // A configuration the router cannot read has no model for this capability.
818
+ }
819
+ if (!candidate)
820
+ continue;
821
+ const model = { model: candidate.model };
822
+ if (candidate.integration.provider === "azure_openai")
823
+ model.provider = "azure_openai";
824
+ if (candidate.underlyingModel)
825
+ model.underlyingModel = candidate.underlyingModel;
826
+ if (candidate.maxInputTokens)
827
+ model.maxInputTokens = candidate.maxInputTokens;
828
+ if (candidate.maxOutputTokens)
829
+ model.maxOutputTokens = candidate.maxOutputTokens;
830
+ const pricing = {};
831
+ for (const key of ["inputPerMTok", "cachedPerMTok", "outputPerMTok"]) {
832
+ const price = candidate.pricing?.[key];
833
+ if (typeof price === "number" && Number.isFinite(price))
834
+ pricing[key] = price;
835
+ }
836
+ if (Object.keys(pricing).length)
837
+ model.pricing = pricing;
838
+ if (candidate.supportsReasoning !== undefined)
839
+ model.supportsReasoning = candidate.supportsReasoning;
840
+ const speed = speedOfModel(speeds, candidate.model);
841
+ if (speed)
842
+ model.tokensPerSecond = speed;
843
+ models[capability] = model;
844
+ }
845
+ return models;
846
+ }
847
+ /**
848
+ * Where a book is, read from the state of the autopilot: the chapters done, the chapters of the plan when it is approved, whether the concept and the judgement of
849
+ * the whole book are done, and the chapters the author wrote that have no summary yet. What `EstimateInput.progress` takes for a book that is already started.
850
+ */
851
+ export function estimateProgressFromState(state) {
852
+ const source = asRecord(state);
853
+ const plan = asRecord(source.plan);
854
+ const chapters = Array.isArray(plan.chapters) ? plan.chapters.map(asRecord) : [];
855
+ const done = chapters.filter((chapter) => chapter.status === "done");
856
+ return {
857
+ chaptersDone: done.length,
858
+ planned: plan.approved === true ? chapters.length : 0,
859
+ conceptDone: asRecord(source.concept).done === true,
860
+ finalDone: source.finalDone === true,
861
+ withoutSummary: done.filter((chapter) => chapter.imported === true && !(typeof chapter.summary === "string" && chapter.summary.trim())).length,
862
+ };
863
+ }
864
+ /**
865
+ * Where a book is by its chapters alone, for a book the autopilot has not started (it has no state): every chapter with prose is the author's, so it is done, and the ones
866
+ * with no summary each cost a call before the plan. `snapshot.chapters` is what it takes. For a book with a state, `estimateProgressFromState` is the one to use.
867
+ */
868
+ export function estimateProgressFromChapters(chapters) {
869
+ const written = (Array.isArray(chapters) ? chapters : []).filter((chapter) => chapter && typeof chapter === "object" && Array.isArray(chapter.paragraphs) && chapter.paragraphs.length > 0);
870
+ return {
871
+ chaptersDone: written.length,
872
+ withoutSummary: written.filter((chapter) => !(typeof chapter.summary === "string" && chapter.summary.trim())).length,
873
+ };
874
+ }
875
+ /**
876
+ * What the state knows of the words the prompts carry: the author's rules (`constraints`), and the standing guidance of the director (`directorNotes`) once the plan is
877
+ * approved. What `EstimateInput.context` takes for a book that is already started, so that the estimate does not start from the typical notes of a book that has none.
878
+ */
879
+ export function estimateContextFromState(state) {
880
+ const source = asRecord(state);
881
+ const words = (list) => (Array.isArray(list) ? list.reduce((total, entry) => total + (typeof entry === "string" ? countWords(entry) : 0), 0) : 0);
882
+ return {
883
+ rulesWords: words(source.constraints),
884
+ ...(asRecord(source.plan).approved === true ? { notesWords: words(source.directorNotes) } : {}),
885
+ };
886
+ }
887
+ //# sourceMappingURL=estimate.js.map